diff --git "a/417.jsonl" "b/417.jsonl"
new file mode 100644--- /dev/null
+++ "b/417.jsonl"
@@ -0,0 +1,734 @@
+{"seq_id":"248253835","text":"import os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport json\r\nimport re\r\nimport nltk\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import SnowballStemmer\r\nfrom nltk.tokenize import WordPunctTokenizer\r\nfrom gensim import models\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import confusion_matrix, precision_recall_fscore_support \r\nimport dill\r\nimport pickle\r\nfrom sklearn.model_selection import cross_val_score\r\n\r\nclass classifier_logisticRegression:\r\n\tdef __init__(self, word2vec, json_file):\r\n\t\t# model = models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)\r\n\t\tself.word2vec=models.KeyedVectors.load_word2vec_format(word2vec,binary=True)\r\n\t\tself.data=pd.read_json(json_file, lines=True)\r\n\t# def preprocessing_data(self, data):\r\n\tdef get_w2v_word(self, word):\r\n\t\treturn (self.word2vec[word])\r\n\tdef get_data_column(self, columns):\r\n\t\treturn (self.data[columns])\r\n\tdef preprocessing(self):\r\n\t\tself.data['text']=[\"title \"+ str(i)+\" \" for i in range(0,len(self.data['short_description']))]+self.data.short_description\r\n\tdef clean_text(self):\r\n\t\tstemmer = SnowballStemmer('english')\r\n\t\twords = stopwords.words('english')\r\n\t\tself.data['cleaned_text'] = self.data['text'].apply(lambda x:\" \".join([stemmer.stem(i) for i in re.sub(\"[^a-zA-Z]\",\" \",x).split() if i not in words]))\r\n\t\treturn self.data['cleaned_text']\r\n\tdef compute_doc_vec_single(self, clean_text):\r\n\t\tvec = np.zeros((self.word2vec.vector_size,), dtype=np.float32)\r\n\t\tn = 0\r\n\t\ttokenized_clean_text=nltk.word_tokenize(clean_text)\r\n\t\tfor word in tokenized_clean_text:\r\n\t\t\tif word in self.word2vec:\r\n\t\t\t\tvec += self.word2vec[word]\r\n\t\t\t\tn += 1\r\n\t\tif(n==0):\r\n\t\t\treturn (self.word2vec[\"Hello\"]*0)\r\n\t\telse:\r\n\t\t\treturn (vec/n)\r\n\tdef compute_doc_vec(self, clean_text):\r\n\t\treturn np.row_stack([self.compute_doc_vec_single(x) for x in clean_text])\r\n\r\n\tdef get_target_y(self):\r\n\t\ty_encoder=LabelEncoder()\r\n\t\ty=y_encoder.fit_transform(self.data['category'])\r\n\t\treturn y,y_encoder\r\n\tdef get_train_test(self, x, y):\r\n\t\ttrain_idx, test_idx = train_test_split(range(len(y)), test_size=0.1, stratify=y)\r\n\t\ttrain_x=x[train_idx, :]\r\n\t\ttrain_y=y[train_idx]\r\n\t\ttest_x=x[test_idx, :]\r\n\t\ttest_y=y[test_idx]\r\n\t\treturn train_x, train_y, test_x, test_y,test_idx\r\n\tdef get_LR_model(self, train_x, train_y):\r\n\t\tmodel=LogisticRegression(multi_class='multinomial',solver='lbfgs',max_iter=3000, n_jobs=-1)\r\n\t\tmodel.fit(train_x, train_y)\r\n\t\treturn (model)\r\n\tdef save_model(self, model, y_encoder):\r\n\t\toutput_dir=u'LR_output'\r\n\t\tif not os.path.exists(output_dir):\r\n\t\t\tos.mkdir(output_dir)\r\n\t\tmodel_file=os.path.join(output_dir, u'model.pkl')\r\n\t\twith open(model_file, 'wb') as outfile:\r\n\t\t\tpickle.dump({'y_encoder': y_encoder, 'lr': model}, outfile)\r\n\t\treturn model_file\r\n\t\r\n\tdef CV_predict(self,x,y):\r\n\t\tprint(\"10-fold cross validation...\")\r\n\t\tscore=cross_val_score(LogisticRegression(multi_class='multinomial', solver='lbfgs',max_iter=3000,verbose=2, n_jobs=-1), x,y, cv=10)\r\n\t\tprint(np.mean(score))\r\n\t\r\n\r\n\r\n\tdef tradition_predict(self, lr_model_file,test_idx, truth):\r\n\t\tprint(\"Traditional predict method...\")\r\n\t\tclf=Predictor(self.word2vec,lr_model_file)\r\n\t\tnew_y_pred = clf.predict(self.data['cleaned_text'][test_idx])\r\n\t\tdf=pd.DataFrame({u'test': new_y_pred, u'truth': truth[test_idx]})\r\n\t\ttest=list(map(str,df['test']))\r\n\t\ttruth=list(map(str,df['truth']))\r\n\t\tcount=0\r\n\t\tfor i in range(0, len(test)):\r\n\t\t\tif test[i]==truth[i]:\r\n\t\t\t\tcount+=1\r\n\t\tprint(count/len(test))\r\n\t\r\n\tdef process(self):\r\n\t\tprint(\"Preprocessing...\")\r\n\t\tself.preprocessing()\r\n\t\tprint(\"Cleaning text...\")\r\n\t\ttemp_clean_text=self.clean_text()\r\n\t\tprint(\"Getting the article vector...\")\r\n\t\tx=self.compute_doc_vec(temp_clean_text)\r\n\t\tprint(\"Getting train data and test data...\")\r\n\t\ty, y_encoder=self.get_target_y()\r\n\t\ttrain_x, train_y, test_x, test_y, test_idx=self.get_train_test(x,y)\r\n\t\tprint(\"Getting model...\")\r\n\t\tmodel=self.get_LR_model(train_x, train_y)\r\n\t\tprint(\"Saving model...\")\r\n\t\tmodel_file=self.save_model(model, y_encoder)\r\n\t\treturn model_file, test_idx, x,y\r\n\r\n\r\nclass Predictor(object):\r\n\tdef __init__(self, loaded_w2v, lr_model_file):\r\n\t\tself.w2v = loaded_w2v\r\n\t\twith open(lr_model_file, 'rb') as infile:\r\n\t\t\tself.model = pickle.load(infile)\r\n \r\n\tdef predict(self, articles):\r\n\t\tx = self._compute_doc_vec(articles)\r\n\t\ty = self.model['lr'].predict(x)\r\n# y_label = self.model1['y_encoder'].inverse_transform(y)\r\n\t\treturn y\r\n \r\n\tdef _compute_doc_vec(self, clean_text):\r\n\t\treturn np.row_stack([self._compute_doc_vec_single(x) for x in clean_text])\r\n\r\n\tdef _compute_doc_vec_single(self, clean_text):\r\n\t\tvec = np.zeros((self.w2v.vector_size,), dtype=np.float32)\r\n\t\tn = 0\r\n\t\ttokenized_clean_text=nltk.word_tokenize(clean_text)\r\n\t\tfor word in tokenized_clean_text:\r\n\t\t\tif word in self.w2v:\r\n\t\t\t\tvec += self.w2v[word]\r\n\t\t\t\tn += 1\r\n\t\tif(n==0):\r\n\t\t\treturn (self.w2v[\"Hello\"]*0)\r\n\t\telse:\r\n\t\t\treturn (vec/n)\r\n\r\n\r\nif __name__==\"__main__\":\r\n\tprint(\"Loading the pre-trained word2vec file and the json file...\")\r\n\tLR_classifier=classifier_logisticRegression(\"GoogleNews-vectors-negative300.bin\", \"News_Category_Dataset_v2.json\")\r\n\tclf, test_idx, x,y=LR_classifier.process()\r\n\r\n\r\n\t#Two methods to get precision\r\n\t#Method1 tradition, the same as online test\r\n\t#**********************************************************\r\n\tLR_classifier.tradition_predict(clf, test_idx,y)\r\n\t#**********************************************************\r\n\t\r\n\t#Method2 10-fold cross validation\r\n\t#**********************************************************\r\n\t# LR_classifier.CV_predict(x,y)\r\n\t#**********************************************************\r\n\r\n\r\n","sub_path":"news_classifier/classifier_logisticRegression.py","file_name":"classifier_logisticRegression.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"254607490","text":"#!/usr/bin/env python\n\nfrom itertools import permutations\n\nwith open(\"inputs/day2.txt\", \"r\") as f:\n nums = [list(map(int, l.split(\"\\t\"))) for l in f if l.strip() != \"\"]\n\nprint(sum(map(lambda r: max(r) - min(r), nums)))\nprint(sum([a // b for a, b in permutations(row, 2) if a % b == 0][0] for row in nums))\n\n","sub_path":"day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"105343063","text":"# Some utility classes to represent a PDB structure\nimport numpy as np\nfrom itertools import combinations as combo\nimport pickle\n\nclass Atom:\n \"\"\"\n A simple class for an amino acid residue\n \"\"\"\n\n def __init__(self, type):\n self.type = type\n self.coords = (0.0, 0.0, 0.0)\n\n # Overload the __repr__ operator to make printing simpler.\n def __repr__(self):\n return self.type\n\nclass Residue:\n \"\"\"\n A simple class for an amino acid residue\n \"\"\"\n\n def __init__(self, type, number):\n self.type = type\n self.number = number\n self.atoms = []\n\n # Overload the __repr__ operator to make printing simpler.\n def __repr__(self):\n return \"{0} {1}\".format(self.type, self.number)\n\nclass ActiveSite:\n \"\"\"\n A simple class for an active site\n \"\"\"\n\n def __init__(self, name):\n self.name = name\n self.residues = []\n self.metrics = [None,None,None]\n\n # Overload the __repr__ operator to make printing simpler.\n def __repr__(self):\n return self.name\n \n def get_raw_metrics(self):\n if self.metrics[0] is None:\n self._individual_metrics()\n return self.metrics[0] \n \n def get_norm_metrics(self,redo_mean_dev=False):\n if self.metrics[2] is None or redo_mean_dev:\n self._individual_metrics()\n self.metrics[1] = flatten_metrics(self.metrics[0])\n self._normalize_metrics(redo_mean_dev)\n return self.metrics[2]\n \n def _individual_metrics(self,printMe=None):\n \"\"\"\n Compute metrics of chemistry, morphology and homogeneity for an ActiveSite instance.\n\n Input: ActiveSite instance\n Output: a dictionary of metrics\n \n Metrics:\n - Mean and Variance of total charge/polarity of residues\n - Fraction of carbon / nitrogen / oxygen\n - Total number of atoms / residues\n - Mean distance between residue centers of mass\n \"\"\"\n\n chem_properties = {\n \"GLY\": \"nonpolar\",\n \"ALA\": \"nonpolar\",\n \"VAL\": \"nonpolar\",\n \"ILE\": \"nonpolar\",\n \"LEU\": \"nonpolar\",\n \"MET\": \"nonpolar\",\n \"PHE\": \"nonpolar\",\n \"TYR\": \"nonpolar\",\n \"TRP\": \"nonpolar\",\n \"PRO\": \"nonpolar\",\n \"CYS\": \"nonpolar\",\n \"SER\": \"polar\",\n \"THR\": \"polar\",\n \"ASN\": \"polar\",\n \"GLN\": \"polar\",\n \"ARG\": \"basic\",\n \"HIS\": \"basic\",\n \"LYS\": \"basic\",\n \"ASP\": \"acidic\",\n \"GLU\": \"acidic\",\n }\n \n charge = {\"nonpolar\": 0, \"polar\": 0, \"basic\": 1, \"acidic\": -1}\n polarity = {\"nonpolar\":0, \"polar\": 0.5, \"basic\": 1, \"acidic\": 1}\n res_type = {\"nonpolar\":0, \"polar\": 0, \"basic\": 0, \"acidic\": 0}\n \n atom_type = {\"C\":0,\"N\":0,\"O\":0}\n \n metric_names = ['meanChar','meanPol','elemFracC',\n 'numAtoms','numRes','meanResDist',\n 'nonpolarFrac','acidicFrac','basicFrac']\n \n metrics = dict.fromkeys(metric_names)\n \n #first calculate mean of total charges/polarity of residues\n residue_charge = np.ndarray(0)\n residue_polarity = np.ndarray(0)\n numRes = len(self.residues)\n \n for residue in self.residues:\n res_type[chem_properties[residue.type.strip()]] += 1\n residue_charge = np.append(residue_charge, charge[chem_properties[residue.type.strip()]])\n residue_polarity = np.append(residue_polarity, polarity[chem_properties[residue.type.strip()]])\n \n for key in res_type.keys():\n res_type[key] /= numRes\n \n self._update_dict(metrics,\n ('meanChar','meanPol','nonpolarFrac','acidicFrac','basicFrac'),\n (np.mean(residue_charge), np.mean(residue_polarity),res_type['nonpolar'],\n res_type['acidic'],res_type['basic'])\n )\n \n #now calculate the fraction of atoms of carbon in the active zone\n numAtoms = 0\n \n for residue in self.residues:\n for atom in residue.atoms:\n numAtoms += 1\n type = atom.type[0]\n if type.lower()=='c':\n atom_type['C'] += 1\n \n for key in atom_type.keys():\n atom_type[key] /= numAtoms\n \n self._update_dict(metrics,\n ('elemFracC','numAtoms','numRes'),\n (atom_type['C'],numAtoms,numRes)\n )\n \n #now calculate the \"center of mass\" for each residue.\n #then calculate the mean of the pairwise Euclidean distance between residue COMs. \n\n for residue in self.residues:\n numAtoms = 0\n centerOfMass = np.zeros(3)\n \n for atom in residue.atoms:\n numAtoms += 1\n centerOfMass += np.asarray(atom.coords)\n \n if not numAtoms==0:\n centerOfMass /= numAtoms\n \n residue.com = tuple(centerOfMass)\n \n residue_dist = []\n \n for pair in combo(self.residues,2):\n distance = np.linalg.norm(np.asarray(pair[0].com)-np.asarray(pair[1].com))\n residue_dist.append(distance) \n \n metrics['meanResDist'] = np.mean(residue_dist)\n \n if printMe: \n for metric in metrics.keys():\n print('{0}\\n\\t\\t{1}\\n'.format(metric,metrics[metric]))\n \n #store\n self.metrics[0] = metrics\n \n return self.metrics[0]\n \n \n def _normalize_metrics(self,redo_mean_dev=False):\n \"\"\"\n Normalizes metric arrays to saved (or custom) dataset\n \"\"\"\n \n #if you want to recalculate mean/devs\n if redo_mean_dev:\n io.gen_mean_dev_normalizations()\n \n means = load_pickle('means_arr')\n devs = load_pickle('devs_arr')\n \n #normalize\n \n self.metrics[2] = (self.metrics[1] - means)/devs\n\n return self.metrics[2]\n \n def _update_dict(self,dictionary,keys,values):\n \"\"\"\n Update dictionary given lists of keys and values\n \n Input: dictionary, keys, values\n Output: None (dictionary updated automatically)\n \"\"\"\n\n dictionary.update(dict(zip(keys,values)))\n \ndef save_pickle(obj, name):\n with open('obj/'+ name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n\ndef load_pickle(name):\n with open('obj/' + name + '.pkl', 'rb') as f:\n return pickle.load(f)\n\ndef flatten_metrics(metrics_dict):\n \"\"\"\n Flattens metric dictionary into a numpy array\n \"\"\"\n\n #NOTE: When converting into array, follows the metric_names list\n #so that you can consistently compare numpy arrays element-wise\n\n metric_names = ['meanChar','meanPol','elemFracC',\n 'numAtoms','numRes','meanResDist',\n 'nonpolarFrac','acidicFrac','basicFrac']\n\n metric_arr = np.ndarray(0)\n\n for metric in metric_names:\n metric_arr = np.append(metric_arr,metrics_dict[metric])\n \n return metric_arr\n","sub_path":"clustering/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"378451947","text":"import os\nfrom code.general import folder_management\nfrom code.general import request_file\nfrom code.general import run_multiprocessing\n\ndef download_files(list_of_enzyme_commission_numbers, list_of_databases, cpus):\n \"\"\" Downloads a url into an HTML file\n Creates data/raw path if does not exist\n Creates a list of files to download, running multiprocessing for speed purposes\n Multiprocessing function runs using a list of tupples, number of cpus and a function\n \"\"\"\n data_path = \"data/raw\"\n folder_management.create_folder(data_path)\n list_of_downloads = []\n for enzyme in list_of_enzyme_commission_numbers:\n for database in list_of_databases:\n download_data = ((enzyme, database, data_path))\n list_of_downloads.append(download_data)\n run_multiprocessing.run_mp(list_of_downloads, cpus, download_manager)\n\ndef download_manager(enzyme, database, data_path):\n \"\"\" Function that is being multiprocessed\n Runs request_file script, who downloads the url into HTML file\n download_path: in our case, it is conserved always with the same scheme\n if the file that we are going to save does not exists, it makes the request\n \"\"\"\n download_path = \"https://www.genome.jp/dbget-bin/get_linkdb?-t+{}+ec:{}\".format(database, enzyme)\n name_of_the_file_path = \"{}/{}_{}_raw.txt\".format(data_path, enzyme, database)\n if not os.path.exists(name_of_the_file_path):\n print(\"Downloading {} enzyme information from {} database. Path: {}\".format(enzyme, database, download_path))\n request_file.download_file(download_path, name_of_the_file_path)\n","sub_path":"code/downloader/download_information.py","file_name":"download_information.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"527586701","text":"import random\n\nclass Fruit():\n\n def __init__(self,tile_x,tile_y):\n self._tile_x = tile_x\n self._tile_y = tile_y\n self._object = []\n \n def GetBody(self):\n return self._object()\n\n def SpawnFruit(self):\n x = random.randint(1,self._tile_x-1)\n y = random.randint(1,self._tile_y-1)\n if (x,y) in self._player_1.GetBody() or (x,y) in self._player_2.GetBody():\n self.SpawnFruit()\n else:\n self._fruit = [(x,y)]","sub_path":"fruit.py","file_name":"fruit.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"411918235","text":"import vk,json,time,random\n\nclass PostToGroupOperation:\n \"\"\"This class execute requests from users\n to spam group via static methods implemented below\"\"\"\n\n @staticmethod\n def get_vk_api(token):\n if None is not token:\n session = vk.Session(access_token=token)\n return vk.API(session=session)\n return None\n\n @staticmethod\n def send_message(vk_api):\n try:\n print(vk_api.messages.send(domain = \"krupenin_pavel\", message = \"Hello\"))\n except Exception as err:\n print(err)\n\n\n @staticmethod\n def getFriends(vk_api):\n print(vk_api.friends.get(fields = 'nickname'))\n\n @staticmethod\n def send_posts_to_groups(vk_api,list_of_posts,list_of_groups):\n try:\n for i in list_of_groups:\n print(vk_api.wall.post(owner_id = '-' + i,message = random.choice(list_of_posts)))\n time.sleep(5)\n except Exception as err:\n print(err)\n\n\n","sub_path":"Model/Logic/VkOperations/PostToGroup/PostToGroupOperation.py","file_name":"PostToGroupOperation.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"120111283","text":"# -*- coding: utf-8 -*-\n\"\"\"\nMétodo simple de infiltración de Green-Ampt\nde una capa. \n\nBasado en ecuaciones presentadas en \n\nChow, V.T., Maidment, D.R., Mays, L.W., 1988. Applied Hydrology, \n\tMcGraw-Hill series in water resources and environmental \n\tengineering. Tata McGraw-Hill Education.\n\nAutor: Alejandro Jaramillo\n\"\"\"\nimport numpy as np\nfrom scipy.optimize import fsolve\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\n\n### PARAMETROS INGRESADOS POR EL USUARIO ###\n\n#Porosidad(n=\\eta)\nn = 0.501\n#Porosidad efectiva (Qe=\\theta_e)\nQe = 0.486\n#Cabesa de succión del suelo en el frente mojado\n#(Psi=\\psi) en cm.\nPsi = 16.68 # cm\n#Conductividad hidráulica (K) en cm/hora \nK = 0.65 # cm/h\n#Saturación efectiva (Se)\nSe = 0.3 # cm\n# Horas de simulación\nSimT = 3 # Horas de similación\n### PARAMETROS INGRESADOS POR EL USUARIO ###\n\nDQ = (1.0-Se)*Qe\nt = np.linspace(0,SimT*60,SimT*60)\nt = t/60\nF = np.zeros(len(t))\n\n\n\ndef func(F,t):\n\tfun = F-(K*t)-(Psi*DQ*np.log(1.0+(F/(Psi*DQ))))\n\treturn fun\n\ni = 0\nfor tt in t:\n\tF[i] = fsolve(func,K*tt,args=tt)\n\ti += 1\n\nf = K*(((Psi*DQ)/F[1:])+1.0)\ntf = t[1:]\n\nFmax = F.max()\nfmax = f.max()\n\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))\nfig.suptitle('Modelo de Green-Ampt de 1 Capa \\n'+r'$\\eta=$'+str(n)+r'; $\\theta_e=$'+str(Qe)+r'; $\\psi=$'+str(Psi)+r'; $K=$'+str(K)+r'; $S_e=$'+str(Se))\nax1 = axes[0]\nax1.set_xlim([0, SimT])\nax1.set_ylim([0, Fmax])\nax1.set_xlabel('Tiempo [Horas]')\nax1.set_ylabel('F [cm]')\nax1.plot(t, F, lw=2,ls='-.',color='b')\nax2 = axes[1]\nax2.set_xlim([0, SimT])\nax2.set_ylim([0, fmax])\nax2.set_xlabel('Tiempo [Horas]')\nax2.set_ylabel('f [cm/Hora]')\nax2.plot(tf, f, lw=2,ls='-.',color='r')\nplt.savefig('Modelo_GreenAmpt.png',format='png')\n#plt.show()\nplt.close(1)\n\n\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))\nfig.suptitle('Modelo de Green-Ampt de 1 Capa \\n'+r'$\\eta=$'+str(n)+r'; $\\theta_e=$'+str(Qe)+r'; $\\psi=$'+str(Psi)+r'; $K=$'+str(K)+r'; $S_e=$'+str(Se))\nax1 = axes[0]\nax1.set_xlim([0, SimT])\nax1.set_ylim([0, Fmax])\nax1.set_xlabel('Tiempo [Horas]')\nax1.set_ylabel('F [cm]')\nlineF, = ax1.plot([], [], lw=2,ls='-.',color='b')\nax2 = axes[1]\nax2.set_xlim([0, SimT])\nax2.set_ylim([0, fmax])\nax2.set_xlabel('Tiempo [Horas]')\nax2.set_ylabel('f [cm/Hora]')\nlinef, = ax2.plot([], [], lw=2,ls='-.',color='r')\n\ndef init():\n\tlineF.set_data([], [])\n\tlinef.set_data([], [])\n\treturn lineF,linef,\n\ndef animate(i):\n\t#print \"Frame = \" + str(i) \n\tlineF.set_data(t[0:i], F[0:i])\n\tlinef.set_data(tf[0:i], f[0:i])\n\treturn lineF,linef,\n\nanim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=len(t)-2, interval=100, blit=True)\n\n# save the animation as an mp4. This requires ffmpeg or mencoder to be\n# installed. The extra_args ensure that the x264 codec is used, so that\n# the video can be embedded in html5. You may need to adjust this for\n# your system: for more information, see\n# http://matplotlib.sourceforge.net/api/animation_api.html\nanim.save('GreenAmpt.mp4', fps=100, extra_args=['-vcodec', 'libx264'])\n\nplt.show()\n","sub_path":"Hidrologia/GreenAmpt_1LModel/GreenAmpt_1LModelV2.0.py","file_name":"GreenAmpt_1LModelV2.0.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"618019871","text":"import unittest\n\nfrom pyalink.alink import *\n\n\nclass TestPinjiu(unittest.TestCase):\n\n def test_doc_hash_count_vectorizer_op(self):\n import numpy as np\n import pandas as pd\n data = np.array([\n [0, u'二手旧书:医学电磁成像'],\n [1, u'二手美国文学选读( 下册 )李宜燮南开大学出版社 9787310003969'],\n [2, u'二手正版图解象棋入门/谢恩思主编/华龄出版社'],\n [3, u'二手中国糖尿病文献索引'],\n [4, u'二手郁达夫文集( 国内版 )全十二册馆藏书']])\n df = pd.DataFrame({\"id\": data[:, 0], \"text\": data[:, 1]})\n inOp1 = BatchOperator.fromDataframe(df, schemaStr='id int, text string')\n inOp2 = StreamOperator.fromDataframe(df, schemaStr='id int, text string')\n\n segment = SegmentBatchOp().setSelectedCol(\"text\").linkFrom(inOp1)\n train = DocHashCountVectorizerTrainBatchOp().setSelectedCol(\"text\").linkFrom(segment)\n predictBatch = DocHashCountVectorizerPredictBatchOp().setSelectedCol(\"text\").linkFrom(train, segment)\n [model, predict] = collectToDataframes(train, predictBatch)\n print(model)\n print(predict)\n","sub_path":"python/src/main/python/pyalink/alink/tests/examples/operator/batch/test_doc_hash_count_vectorizer.py","file_name":"test_doc_hash_count_vectorizer.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"282351668","text":"from keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TerminateOnNaN, CSVLogger\nfrom keras import backend as K\nfrom keras.models import load_model\n\nfrom models.keras_ssd7 import build_model\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\n\nfrom ssd_encoder_decoder.ssd_input_encoder import SSDInputEncoder\nfrom ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast\n\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\nfrom data_generator.object_detection_2d_misc_utils import apply_inverse_transforms\nfrom data_generator.data_augmentation_chain_variable_input_size import DataAugmentationVariableInputSize\nfrom data_generator.data_augmentation_chain_constant_input_size import DataAugmentationConstantInputSize\nfrom data_generator.data_augmentation_chain_original_ssd import SSDDataAugmentation\n\nimport os\nimport csv\nimport cv2\nfrom math import ceil\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg_height = 300 # Height of the input images\nimg_width = 480 # Width of the input images\nimg_channels = 3 # Number of color channels of the input images\nintensity_mean = 127.5 # Set this to your preference (maybe `None`). The current settings transform the input pixel values to the interval `[-1,1]`.\nintensity_range = 127.5 # Set this to your preference (maybe `None`). The current settings transform the input pixel values to the interval `[-1,1]`.\nn_classes = 3 # Number of positive classes\nscales = [0.08, 0.16, 0.32, 0.64, 0.96] # An explicit list of anchor box scaling factors. If this is passed, it will override `min_scale` and `max_scale`.\naspect_ratios = [0.5, 1.0, 2.0] # The list of aspect ratios for the anchor boxes\ntwo_boxes_for_ar1 = True # Whether or not you want to generate two anchor boxes for aspect ratio 1\nsteps = None # In case you'd like to set the step sizes for the anchor box grids manually; not recommended\noffsets = None # In case you'd like to set the offsets for the anchor box grids manually; not recommended\nclip_boxes = False # Whether or not to clip the anchor boxes to lie entirely within the image boundaries\nvariances = [1.0, 1.0, 1.0, 1.0] # The list of variances by which the encoded target coordinates are scaled\nnormalize_coords = True # Whether or not the model is supposed to use coordinates relative to the image size\n\nbatch_size = 64\n\ndef loadModel(path_model):\n\tssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\n\tmodel = load_model(path_model, custom_objects={'AnchorBoxes':AnchorBoxes,\n\t\t\t\t\t\t\t\t\t'compute_loss':ssd_loss.compute_loss})\n\treturn model\n\ndef buildModel(path_weights=None):\n\n\tmodel = build_model(image_size=(img_height, img_width, img_channels),\n\t\t\t\t\t\t\tn_classes=n_classes,\n\t\t\t\t\t\t\tmode='training',\n\t\t\t\t\t\t\tl2_regularization=0.0005,\n\t\t\t\t\t\t\tscales=scales,\n\t\t\t\t\t\t\taspect_ratios_global=aspect_ratios,\n\t\t\t\t\t\t\taspect_ratios_per_layer=None,\n\t\t\t\t\t\t\ttwo_boxes_for_ar1=two_boxes_for_ar1,\n\t\t\t\t\t\t\tsteps=steps,\n\t\t\t\t\t\t\toffsets=offsets,\n\t\t\t\t\t\t\tclip_boxes=clip_boxes,\n\t\t\t\t\t\t\tvariances=variances,\n\t\t\t\t\t\t\tnormalize_coords=normalize_coords,\n\t\t\t\t\t\t\tsubtract_mean=intensity_mean,\n\t\t\t\t\t\t\tdivide_by_stddev=intensity_range)\n\n\tif path_weights:\n\t\tmodel.load_weights(path_weights, by_name=True)\n\n\tadam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n\tssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\n\tmodel.compile(optimizer=adam, loss=ssd_loss.compute_loss)\n\n\treturn model\n\ndef createModel(path_model=None, path_weights=None):\n\tif path_model:\n\t\tmodel = loadModel(path_model)\n\telse:\n\t\tmodel = buildModel(path_weights)\n\ndef createGenerator(dir_img, file_labels, file_h5=None, batch_size=64):\n\n\tdata_augmentation_chain = DataAugmentationConstantInputSize(\n\t\t\t\t\t\t\t\trandom_brightness=(-48, 48, 0.5),\n\t\t\t\t\t\t\t\trandom_contrast=(0.5, 1.8, 0.5),\n\t\t\t\t\t\t\t\trandom_saturation=(0.5, 1.8, 0.5),\n\t\t\t\t\t\t\t\trandom_hue=(18, 0.5),\n\t\t\t\t\t\t\t\trandom_flip=0.5,\n\t\t\t\t\t\t\t\trandom_translate=((0.03,0.5), (0.03,0.5), 0.5),\n\t\t\t\t\t\t\t\trandom_scale=(0.5, 2.0, 0.5),\n\t\t\t\t\t\t\t\tn_trials_max=3,\n\t\t\t\t\t\t\t\tclip_boxes=True,\n\t\t\t\t\t\t\t\toverlap_criterion='area',\n\t\t\t\t\t\t\t\tbounds_box_filter=(0.3, 1.0),\n\t\t\t\t\t\t\t\tbounds_validator=(0.5, 1.0),\n\t\t\t\t\t\t\t\tn_boxes_min=1,\n\t\t\t\t\t\t\t\tbackground=(0,0,0))\n\n\tpredictor_sizes = [model.get_layer('classes4').output_shape[1:3],\n\t\t\t\t\t\tmodel.get_layer('classes5').output_shape[1:3],\n\t\t\t\t\t\tmodel.get_layer('classes6').output_shape[1:3],\n\t\t\t\t\t\tmodel.get_layer('classes7').output_shape[1:3]]\n\n\tssd_input_encoder = SSDInputEncoder(img_height=img_height,\n\t\t\t\t\t\t\t\t\timg_width=img_width,\n\t\t\t\t\t\t\t\t\tn_classes=n_classes,\n\t\t\t\t\t\t\t\t\tpredictor_sizes=predictor_sizes,\n\t\t\t\t\t\t\t\t\tscales=scales,\n\t\t\t\t\t\t\t\t\taspect_ratios_global=aspect_ratios,\n\t\t\t\t\t\t\t\t\ttwo_boxes_for_ar1=two_boxes_for_ar1,\n\t\t\t\t\t\t\t\t\tsteps=steps,\n\t\t\t\t\t\t\t\t\toffsets=offsets,\n\t\t\t\t\t\t\t\t\tclip_boxes=clip_boxes,\n\t\t\t\t\t\t\t\t\tvariances=variances,\n\t\t\t\t\t\t\t\t\tmatching_type='multi',\n\t\t\t\t\t\t\t\t\tpos_iou_threshold=0.5,\n\t\t\t\t\t\t\t\t\tneg_iou_limit=0.3,\n\t\t\t\t\t\t\t\t\tnormalize_coords=normalize_coords)\n\n\n\n\tdatagen = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=file_h5)\n\tdatagen.parse_csv(images_dir=dir_img,\n\t\t\t\t\t\t\tlabels_filename=file_labels,\n\t\t\t\t\t\t\tinput_format=['xmin', 'ymin', 'xmax', 'ymax', 'image_name','class_id'],\n\t\t\t\t\t\t\tinclude_classes='all')\n\n\tif not file_h5:\n\t\tdatagen.create_hdf5_dataset(file_path=file_h5,\n\t\t\t\t\t\t\t\t\tresize=False,\n\t\t\t\t\t\t\t\t\tvariable_image_size=False,\n\t\t\t\t\t\t\t\t\tverbose=True)\n\n\tprint('number of images: %d' %datagen.get_dataset_size())\n\n\tgenerator = datagen.generate(batch_size=batch_size,\n\t\t\t\t\t\t\t\t\tshuffle=True,\n\t\t\t\t\t\t\t\t\ttransformations=[data_augmentation_chain],\n\t\t\t\t\t\t\t\t\tlabel_encoder=ssd_input_encoder,\n\t\t\t\t\t\t\t\t\treturns={'processed_images',\n\t\t\t\t\t\t\t\t\t\t\t'encoded_labels'},\n\t\t\t\t\t\t\t\t\tkeep_images_without_gt=False)\n\n\treturn generator, datagen.get_dataset_size()\n\ndef createCallBacks(path_history):\n\tif not os.path.isdir(path_history):\n\t\tos.mkdir(path_history)\n\n\tfile_checkpoint = '{epoch:03d}_{loss:.4f}_{val_loss:.4f}.h5'\n\tfile_log = 'ssd7_training_log.csv'\n\n\tcheckpoint = ModelCheckpoint(filepath=os.path.join(path_history,file_checkpoint),\n\t\t\t\t\t\t\t\tmonitor='val_loss',\n\t\t\t\t\t\t\t\tverbose=1,\n\t\t\t\t\t\t\t\tsave_best_only=True,\n\t\t\t\t\t\t\t\tsave_weights_only=False,\n\t\t\t\t\t\t\t\tmode='auto',\n\t\t\t\t\t\t\t\tperiod=1)\n\n\tlogger = CSVLogger(filename=os.path.join(pathHistory,file_log),\n\t\t\t\t\t\t\tseparator=',',\n\t\t\t\t\t\t\tappend=True)\n\n\tearly_stopping = EarlyStopping(monitor='val_loss',\n\t\t\t\t\t\t\t\tmin_delta=0.0,\n\t\t\t\t\t\t\t\tpatience=10,\n\t\t\t\t\t\t\t\tverbose=1)\n\n\treduce_lr = ReduceLROnPlateau(monitor='val_loss',\n\t\t\t\t\t\t\t\t\t\tfactor=0.1,\n\t\t\t\t\t\t\t\t\t\tpatience=5,\n\t\t\t\t\t\t\t\t\t\tverbose=1,\n\t\t\t\t\t\t\t\t\t\tmin_delta=0.001,\n\t\t\t\t\t\t\t\t\t\tcooldown=0,\n\t\t\t\t\t\t\t\t\t\tmin_lr=0.00001)\n\n\tcallbacks = [checkpoint, logger, early_stopping, reduce_lr]\n\n\treturn callbacks\n\nif __name__ == \"__main__\":\n\tdir_img = '/DataSet/Crowdai300/' # image dir\n\tfile_labels_train = '/DataSet/train.csv' # file labels train\n\tfile_labels_val = '/DataSet/val.csv'\t# file labels val\n\tpath_history = '/DataSet/History'\t\t# dir contain results\n\t\n\tmodel = createModel()\n\n\tgenerator_train, nb_samples_train = createGenerator(dir_img, file_labels_train, batch_size=batch_size)\n\tgenerator_val, nb_samples_val = createGenerator(dir_img, file_labels_val, batch_size=batch_size)\n\n\tcallbacks = createCallBacks(path_history)\n\n\tini_epoch = 0\n\tnb_epochs = 200\n\tsteps = ceil(nb_samples_train/batch_size) \n\tsteps_val = ceil(nb_samples_val/batch_size) \n\n\tmodel.fit_generator(generator=generator_train,\n\t\t\t\t\t\tsteps_per_epoch=steps_per_epoch,\n\t\t\t\t\t\tepochs=nb_epochs,\n\t\t\t\t\t\tcallbacks=callbacks,\n\t\t\t\t\t\tvalidation_data=generator_val,\n\t\t\t\t\t\tvalidation_steps=steps_val,\n\t\t\t\t\t\tinitial_epoch=ini_epoch)\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"131058160","text":"from DibujoSvg import Dibujo\nfrom Punto import Punto\nfrom FibonacciHeap import FH\nfrom random import randint\nfrom time import sleep, time\nimport matplotlib.pyplot as plt\n\n\n# iniciadores\ndef CrearPuntos(ancho, alto, numPuntos=50): # Cambias el valor para decidir cuantos puntos habrá\n # Crea un número N de puntos aleatorios y su matriz de adyacencia\n dibujo = Dibujo(ancho, alto)\n l = [] # lista de puntos\n g = [] # matriz de adyacencia\n\n for i in range(0, numPuntos):\n l.append(Punto(randint(0, alto), randint(0, ancho), aleatorio=False)) # Se crea un punto aleatorio\n dibujo.EscribirLinea(l[-1].GetSvg()) # Se dibuja en SVG el punto creado\n # sleep(0.25)#Se espera\n for j in range(len(l)):\n g.append([0] * len(l)) # Se inicializan a 0 las distancias\n for i in range(0, len(l)):\n for j in range(0, len(l)):\n if i == j:\n g[i][j] = float(\n \"inf\") # La distancia de un punto a él mismo se pone infinita para que no sea factible nunca\n else:\n g[i][j] = l[i].CalcularDistancia(l[j]) # Se rellena la matriz con las distancias a todos los puntos\n g[j][i] = g[i][j]\n return l, g, dibujo\n\n\ndef CrearCuadrícula(ancho, alto, numPuntos, dibujo):\n l = [] # lista de puntos\n g = [] # matriz de adyacencia\n separación = 50\n for i in range(0, numPuntos):\n for j in range(0, numPuntos):\n l.append(Punto(10 + i * separación, 10 + j * separación)) # Se crea un punto aleatorio\n dibujo.EscribirLinea(l[-1].GetSvg()) # Se dibuja en SVG el punto creado\n # sleep(0.25)#Se espera\n for j in range(len(l)):\n g.append([0] * len(l))\n for i in range(0, len(l)):\n print(i)\n for j in range(0, len(l)):\n if i == j:\n g[i][j] = float(\"inf\")\n else:\n g[i][j] = l[i].CalcularDistancia(l[j]) # Se rellena la matriz con las distancias a todos los puntos\n g[j][i] = g[i][j]\n return l, g\n\n\n\ndef SacarAristas(g, elem, visitados, aristas=FH()): # Devuelve en una lista todas las aristas del elemento indicado\n for i in range(0, len(g[elem])):\n if not visitados[i] and g[elem][i]!=float(\"inf\"):\n aristas.añadir((elem, i, g[elem][i])) # Se devuelve i,j,distancia\n return aristas\n\ndef CrearLinea(p1, p2):\n # Crea una línea entre dos puntos, además, deja un espacio vacío para que quede bonito\n i1, j1 = p1.GetPuntos()\n r1 = p1.GetRadio()\n r2 = p2.GetRadio()\n i2, j2 = p2.GetPuntos()\n IncrementoJ1 = (j2 - j1)\n IncrementoJ2 = -IncrementoJ1\n IncrementoI1 = (i2 - i1)\n IncrementoI2 = -IncrementoI1\n\n h = (IncrementoI1 ** 2 + IncrementoJ1 ** 2) ** 0.5 # hipotenusa\n return ''\n\n\ndef Prim(g, l, dibujo):\n visitados = [False] * len(g)\n visitados[0] = True\n aristas = SacarAristas(g, 0, visitados)\n while not all(visitados) and not aristas.IsEmpty():\n linea = aristas.extractmin()\n if not visitados[linea[1]]:\n dibujo.EscribirLinea(CrearLinea(l[linea[0]], l[linea[1]]), True) # Se dibuja la linea que une los puntos\n #sleep(5)\n dibujo.Mostrar()\n visitados[linea[1]] = True\n SacarAristas(g, linea[1], visitados, aristas) # Se añaden las aristas del nuevo punto\n dibujo.Terminar()\n\n\n\ndef UnirTodo(g, l, dibujo):\n for i in range(0, len(g)):\n for j in range(0, len(g)):\n if not i == j:\n dibujo.EscribirLinea(CrearLinea(l[i], l[j]), True)\n else:\n break\n dibujo.Mostrar()\n\n\nancho = 1920\nalto = 1080\npuntos = 50\n\nsleep(1)\nl, g, d = CrearPuntos(ancho, alto, puntos)\n\"\"\"\np1=Punto(200,300)\np2=Punto(100,200)\nEscribirLinea(p1.GetSvg())\nEscribirLinea(p2.GetSvg())\nEscribirLinea(CrearLinea(p2,p1))\n\"\"\"\nd.Mostrar()\nPrim(g, l, d)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"353659998","text":"array=[5,7,9,0,3,1,6,2,4,8]\n\ndef quick_sort(array,start,end):\n if start>=end: # 원소가 1개인 경우 종료\n return\n pivot=start #피벗은 첫번째 원소\n left=start+1\n right =end\n while left<=right:\n while left <= end and array[left] <= array[pivot]:\n left +=1\n while right >start and array[right] >=array[pivot]:\n right -=1\n\n if left >right:\n array[right],array[pivot]=array[pivot],array[right]\n else:\n array[left],array[right]=array[right],array[left]\n quick_sort(array,start,right-1)\n quick_sort(array,right+1,end)\n\nquick_sort(array,0,len(array)-1)\nprint(array)\n","sub_path":"정렬/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"600072868","text":"from inhere import myproject\nimport re\n\n\ninfo = {'Cid': '2019171064',\n 'Cname': '天津华电南疆热电环保信息化平台项目',\n 'Ccompany': '天津华电南疆热电有限公司',\n 'Caddress': '天津市塘沽区港塘路2657号 天津华电南疆热电有限公司 物资部',\n 'Cperson': '曾春',\n 'Cphone': '18874053395',\n }\n\n\n\npath = r\"C:\\Users\\gao\\Desktop\\环保\\projects\"\nname = \"2019173067广东华电韶关热电有限公司环保信息化平台合同\"\nfilename = \"深圳坪山\"\n\na1 = myproject(path)\na1.makepro('天津南疆')\na1.makefy(info)\n\n\n\n\nid = re.match(r\"\\d*\",name)\norg = re.match(r\"[^0-9]*\",name)\n\n\n\n\n","sub_path":"Xiangmu/ProjectXG.py","file_name":"ProjectXG.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"104707952","text":"#!/usr/bin/python\n\"\"\"\nTime series analysis of data\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pylab as ppl\n\nppl.close('all')\n\n# Load paramters\nimport ConfigDetailSingle\nreload(ConfigDetailSingle)\nfrom ConfigDetailSingle import *\n\nnT = 2 #Thermistor number\n\n# Chunks working best for 380-450 \nChunk1 = np.array([388, 404.5])\nChunk2 = np.array([408.5, 422.2])\n\n# For 290-350\n#Chunk1 = np.array([291.4, 306.5])\n#Chunk2 = np.array([312.1, 335.3])\n#Chunk2 = np.array([311.9, 315.2])\n#Chunk2 = np.array([307.4, 315.2])\n#Chunk2 = np.array([331.1, 341.5])\n\n#function to perform block averaging\nfrom BlockAverage import BlockAverage\n\nprint ('Load data...')\n\nfrom netCDF4 import Dataset as ncdf\nfile = ncdf(DetailDir+'Output_data.nc', mode='r', format='NETCDF4')\ntime = file.variables['Time'][:]\nT = file.variables['Temp'][nT-1,np.nonzero((time>=Start)&(time<=End))[0]]\nZ = file.variables['Depth'][nT-1]\nddt = file.SkipData\nfile.close()\ntime = time[np.nonzero((time>=Start)&(time<=End))]\n\nprint ('Data loaded')\n\n# Make block average of data if subsampling is requested\nT = BlockAverage(T, ddt, SubSamp)\ntime = BlockAverage(time, ddt, SubSamp)\n\n# Interpolate to regular time step\nintTime = np.arange(time[0], time[-1], SubSamp/86400.)\nData = np.interp(intTime, time, T, left=np.nan, right=np.nan)\ntime = intTime\n\n# For the FFT analysis\nfrom scipy.signal import detrend\nT1 = T[np.nonzero((time>Chunk1[0])&(time<=Chunk1[1]))]\nT1 = detrend(T1)\nT2 = T[np.nonzero((time>Chunk2[0])&(time<=Chunk2[1]))]\nT2 = detrend(T2)\ntime1 = time[np.nonzero((time>Chunk1[0])&(time<=Chunk1[1]))]\ntime2 = time[np.nonzero((time>Chunk2[0])&(time<=Chunk2[1]))]\n\nprint ('Fourier analysis')\n\n# Use Hanning window (see pag.445 Data Analysis Methods in Phys. Oc)\nfrom scipy.signal import hann\nT1w = T1*hann(T1.size)\nT2w = T2*hann(T2.size)\n# Use Kaiser window\n#from scipy.signal import kaiser\n#T1 *= kaiser(T1.size, 2)\n#T2 *= kaiser(T1.size, 2)\n\nprint ('Compute FFT')\n# Use matplotlib psd\n\nN1 = 2**int(np.log2(T1w.size)+1); N2 = 2**int(np.log2(T2w.size)+1)\n#N1 = 2**22; N2=2**22\n\n# 8/3 for hanning\n# N1/T1.size for compensate zero padding\nfft_pw1 = (N1/np.float(T1.size))*np.abs(((8./3.)**0.5)*np.fft.fft(T1w,N1)) ** 2 # FFT power spectrum\nfft_pw2 = (N2/np.float(T2.size))*np.abs(((8./3.)**0.5)*np.fft.fft(T2w,N2)) ** 2\nfreqs1 = np.fft.fftfreq(len(fft_pw1), SubSamp) # frequencies of FFT\nfreqs2 = np.fft.fftfreq(len(fft_pw2), SubSamp)\n\n# Normalization: Dt*abs(FFT)**2/N\n# this way Df*sum(power)/N = variance\nfft_power1 = SubSamp*fft_pw1[:fft_pw1.size/2]/N1\nfft_power1[1:] += SubSamp*fft_pw1[fft_pw1.size/2+1:]/N1\nfft_power2 = SubSamp*fft_pw2[:fft_pw2.size/2]/N2\nfft_power2[1:] += SubSamp*fft_pw2[fft_pw2.size/2+1:]/N2\nfreqs1 = freqs1[:freqs1.size/2]\nfreqs2 = freqs2[:freqs2.size/2]\n\nwin = 19 #width of smoothing window\nsm_fft_power1 = np.convolve(fft_power1,np.ones(win))\nsm_fft_power1 = sm_fft_power1[(win/2):-(win/2)]/np.float(win)\nsm_fft_power2 = np.convolve(fft_power2,np.ones(win))\nsm_fft_power2 = sm_fft_power2[(win/2):-(win/2)]/np.float(win)\n\n# significance levels for smoothed spectra (pag.454 Data Analysis Methods in Phys. Oc.)\nfrom scipy.stats import chi2\nslev = 0.05 # significance level\nnu1 = 2*win#T1.size/np.float(win) *8./3. # for a Hanning window!\nnu2 = 2*win#T2.size/np.float(win) *8./3.\nsig1 = np.diff([np.log10(nu1/chi2.ppf(1-slev/2,nu1)), np.log10(nu1/chi2.ppf(slev/2,nu1))])\nsig2 = np.diff([np.log10(nu2/chi2.ppf(1-slev/2,nu2)), np.log10(nu2/chi2.ppf(slev/2,nu2))])\n\nprint ('Wavelet analysis')\n\nfrom sys import path\n#Path to toolbox\npath.append('/home/cimatori/installed')\n\nimport wavelet\n\nstd = Data.std() # Standard deviation\nstd2 = std ** 2 # Variance\nvar = (Data - Data.mean()) / std # Calculating anomaly and normalizing\n#p = np.polyfit(time, Data, 1) # Linear fit of the data\n#var = (Data - p[0]*time - p[1]) / std # Calculating anomaly, normalizing and removing linear trend\n\nN = var.size # Number of measurements\n\nmother = wavelet.Morlet(6.) # Morlet mother wavelet with wavenumber=6\n#mother = wavelet.Mexican_hat() # Mexican hat wavelet, or DOG with m=2\n#mother = wavelet.Paul(4) # Paul wavelet with order m=4\n#mother = wavelet.DOG(6) # Derivative of the Gaussian, with m=6\n\n# perform the wavelet transform\nwave, scales, freqs, coi, fft, fftfreqs = wavelet.cwt(var, dt, dj, s0, J,\n mother)\n\npower = (np.abs(wave)) ** 2 # Normalized wavelet power spectrum\nfft_power = std2 * np.abs(fft) ** 2 # FFT power spectrum\nperiod = 1. / freqs\n\n# Calculates the global wavelet spectrum\nglbl_power = std2 * power.mean(axis=1)\n\n# Scale average between avg1 and avg2 periods and significance level\nsel = ppl.find((period >= avg1) & (period < avg2))\n#sel = np.ones(period.shape, dtype=int)\nCdelta = mother.cdelta\nscale_avg = (scales * np.ones((N, 1))).transpose()\n# As in Torrence and Compo (1998) equation 24\nscale_avg = power / scale_avg\nscale_avg = std2 * dj * dt / Cdelta * scale_avg[sel, :].sum(axis=0)\n\n# Compute time average of scale average in the chunks\nw_power1 = SubSamp*std2*\\\n np.mean(power[:,np.nonzero((time>Chunk1[0])&(time<=Chunk1[1]))[0]],\n axis=1)\nw_power2 = SubSamp*std2*\\\n np.mean(power[:,np.nonzero((time>Chunk2[0])&(time<=Chunk2[1]))[0]],\n axis=1)\n\nprint ('Done.\\n Plot data...')\n\n# The following routines plot the results in four different subplots containing\n# the original series anomaly, the wavelet power spectrum, the global wavelet\n# and Fourier spectra and finally the range averaged wavelet spectrum. In all\n# sub-plots the significance levels are either included as dotted lines or as\n# filled contour lines.\n#ppl.ion()\nfontsize = 'medium'\nparams = {'text.fontsize': fontsize,\n 'xtick.labelsize': fontsize,\n 'ytick.labelsize': fontsize,\n 'axes.titlesize': fontsize\n }\nppl.rcParams.update(params) # Plot parameters\n\n#\n# First plot, wavelet analysis\n#\n\nfigprops = dict(figsize=(11, 8))\nfig = ppl.figure(**figprops)\n\nunits='^{\\circ}C'\ntitle='Time series at depth {:.1f}m'.format(Z)\nlabel='Temp.'\n# First sub-plot, the original time series anomaly.\n\nax = fig.add_axes([0.1, 0.75, 0.65, 0.2])\nax.plot(time, Data, 'k', linewidth=1.5)\ntmin = Data.min()-Data.std(); tmax=Data.max()+Data.std()\nax.set_title('a) %s' % (title, ))\nif units != '':\n ax.set_ylabel(r'%s [$%s$]' % (label, units,))\nelse:\n ax.set_ylabel(r'%s' % (label, ))\nax.set_ylim(tmin,tmax)\n\n# Second sub-plot, the normalized wavelet power spectrum and significance level\n# contour lines and cone of influece hatched area.\nbx = fig.add_axes([0.1, 0.37, 0.65, 0.28], sharex=ax)\npmean = np.log2(power).mean(); pstd = np.log2(power).std()\nlevels = np.arange(int(pmean-2*pstd),int(pmean+2*pstd),1)\nbx.contourf(time, np.log2(period), np.log2(power), levels,\n extend='both')\n#bx.contour(time, np.log2(period), sig95, [-99, 1], colors='k',\n# linewidths=2.)\nbx.fill(np.concatenate([time[:1]-dt, time, time[-1:]+dt, time[-1:]+dt,\n time[:1]-dt, time[:1]-dt]), np.log2(np.concatenate([[1e-9], np.fmax(coi,1e-9),\n [1e-9], period[-1:], period[-1:], [1e-9]])), 'k', alpha='0.3',\n hatch='x')\nbx.plot([time[0],time[-1]], [np.log2(Tf/24.),np.log2(Tf/24.)], '--',\n color=[0.5,0.5,0.5], lw=2) # Inertial period\nbx.plot([time[0],time[-1]], [np.log2(avg1),np.log2(avg1)], 'w-') # Power averaging limits\nbx.plot([time[0],time[-1]], [np.log2(avg2),np.log2(avg2)], 'w-')\nbx.set_title('b) %s Wavelet Power Spectrum (%s)' % (label, mother.name))\nbx.set_ylabel('Period (hours)')\nYticks = 2 ** np.arange(np.ceil(np.log2(period.min())),\n np.ceil(np.log2(period.max())))\nbx.set_yticks(np.log2(Yticks))\nbx.set_yticklabels([\"%.3f\" % tick for tick in Yticks*24])\nbx.set_ylim(np.log2([period.min(), period.max()]))\nbx.invert_yaxis()\n\n# Third sub-plot, the global wavelet and Fourier power spectra and theoretical\n# noise spectra.\ncx = fig.add_axes([0.77, 0.37, 0.2, 0.28], sharey=bx)\n#cx.plot(np.log10(glbl_signif), np.log2(period), 'k--')\ncx.plot(np.log10(fft_power), np.log2(1./fftfreqs), '-', color=[0.7, 0.7, 0.7],\n linewidth=1.)\ncx.plot(np.log10(glbl_power), np.log2(period), 'k-', linewidth=1.5)\ncx.plot([-100,100], [np.log2(Tf/24.),np.log2(Tf/24.)], '--',\n color=[0.5,0.5,0.5], lw=2)\ncx.set_title('c) Global Wavelet Spectrum')\nif units != '':\n cx.set_xlabel(r'log(Power) [$%s^2$]' % (units, ))\nelse:\n cx.set_xlabel(r'log(Power)')\ncx.set_xlim([-9, np.log10(glbl_power.max())+0.9])\ncx.set_ylim(np.log2([period.min(), period.max()]))\ncx.set_yticks(np.log2(Yticks))\n#cx.set_yticklabels(Yticks)\nppl.setp(cx.get_yticklabels(), visible=False)\ncx.invert_yaxis()\n\n# Fourth sub-plot, the scale averaged wavelet spectrum as determined by the\n# avg1 and avg2 parameters\ndx = fig.add_axes([0.1, 0.07, 0.65, 0.2], sharex=ax)\n#dx.axhline(scale_avg_signif, color='k', linestyle='--', linewidth=1.)\ndx.plot(time, scale_avg, 'k-', linewidth=1.5)\ndx.set_title('d) ${}$-${}$ hour scale-averaged power' .format(24*avg1, 24*avg2))\ndx.set_xlabel('Time (yeardays)')\nif units != '':\n dx.set_ylabel(r'Average variance [$%s$]' % (units, ))\nelse:\n dx.set_ylabel(r'Average variance')\n#\nax.set_xlim([time.min(), time.max()])\n#\nppl.draw()\nppl.show()\nfig.savefig(OutDir+'WaveletAnalysis/'+\\\n 'Wavelet_analysis_nT_{}_day_{}_{}_SubSample_{}.png'.format(nT,Start,End,SubSamp))\n\n#\n# Second plot: comparison between fourier transform and wavelet power\n#\n\nfigprops = dict(figsize=(11, 6))\nfig = ppl.figure(**figprops)\nfig.subplots_adjust(wspace=0.5, hspace=0.5)\n\n#First subplot, time series\nax = ppl.subplot2grid((3,2), (0,0), colspan=3, rowspan=1)\nax.plot(time, Data, 'k', linewidth=1.5)\ntmin = Data.min()-Data.std(); tmax=Data.max()+Data.std()\nax.fill(np.hstack((Chunk1,Chunk1[::-1])), [tmin,tmin,tmax,tmax], 'b', alpha=0.5)\nax.fill(np.hstack((Chunk2,Chunk2[::-1])), [tmin,tmin,tmax,tmax], 'r', alpha=0.5)\nax.set_title('a) %s' % (title, ))\nif units != '':\n ax.set_ylabel(r'%s [$%s$]' % (label, units,))\nelse:\n ax.set_ylabel(r'%s' % (label, ))\nax.set_ylim(tmin,tmax)\n\n# First sub-plot, spectra of first chunk\nbx = ppl.subplot2grid((3,2), (1,0), colspan=1, rowspan=2)\n\n#Handy pointers for plotting spectra\nper1 = np.log10(1./freqs1)\nper2 = np.log10(1./freqs2)\ndata1 = np.log10(fft_power1) # data to be plotted\ndata2 = np.log10(fft_power2)\nsdata1 = np.log10(sm_fft_power1)\nsdata2 = np.log10(sm_fft_power2)\n\n#plot spectrum\nbx.plot(per1, data1, 'b-', linewidth=0.5, alpha=0.3)\nbx.plot(per1, sdata1, 'b-', linewidth=1.5, alpha=0.7)\nbx.plot(np.log10(period*86400), np.log10(w_power1), 'b-', linewidth=2)\nxsig = np.log10(60); ysig=1 #where to centre significance bar\nbx.errorbar(xsig,ysig, yerr=sig1, color='k', lw=2)\n\nbx.set_title('b) PS time interval: {}-{} days'.format(Chunk1[0],Chunk1[1]))\nbx.set_ylabel('$\\log_{10}$(Power) [$'+units+'^2 \\cdot Hz^{-1}$]')\n\n# Fifth sub-plot, spectra of second chunk\ncx = ppl.subplot2grid((3,2), (1,1), colspan=1, rowspan=2)\n\n#plot spectrum\ncx.plot(per2, data2, 'r-', linewidth=0.5, alpha=0.3)\ncx.plot(per2, sdata2, 'r-', linewidth=1.5, alpha=0.7)\ncx.plot(np.log10(period*86400), np.log10(w_power2), 'r-', linewidth=2)\ncx.errorbar(xsig,ysig, yerr=sig2, color='k', lw=2)\n\ncx.set_title('c) Time interval: {}-{} days'.format(Chunk2[0],Chunk2[1]))\n\n# Common settings for the spectra of the two chunks\n# plot reference lines\nxi = np.log10(np.array([86400, 3600])); xh = np.log10(np.array([2400, 180]))\nslopes = [3, 2, 5./3] # slopes to be plotted\nticks = np.array([60, 600, 3600, 86400]) #ticks to be used\nbx.plot(xi, xi-xi[0]+2, 'k-', lw=2)\nbx.text(xi[0], 2, '-1', fontsize='x-large')\n#cx.plot(xi, 2*(xi-xi[0])+3, 'k-', lw=2) # -2 slope\ncx.plot(xi, xi-xi[0]+2, 'k-', lw=2) # -1 slope\ncx.text(xi[0], 2, '-1', fontsize='x-large')\nfor axis in [bx,cx]:\n for slope in slopes:\n axis.plot(xh, slope*xh-slope*xh[1]-3, color='k', lw=2)\n # plot inertial frequency\n axis.plot(2*[np.log10(Tf*3600)], [-100, 100],\\\n '--', color=[0.5,0.5,0.5], lw=2)\n # settings common to spectra subplots\n axis.set_xlabel('Period [hours]')\n axis.set_xticks(np.log10(ticks))\n axis.set_xticklabels([\"%.3f\" % member for member in ticks/3600.])\n axis.set_xlim(np.log10(2.5*86400), np.log10(61))\nbx.set_ylim(sdata1.min(), sdata1.max()+1)\ncx.set_ylim(sdata2.min(), sdata2.max()+1)\n\nppl.draw()\nppl.show()\nfig.savefig(OutDir+'WaveletAnalysis/'+\\\n 'Wavelet_FFT_analysis_nT_{}_day_{}_{}_SubSample_{}.png'.format(nT,Start,End,SubSamp))\n\nprint ('Done.')\n","sub_path":"CanaryBasin/Wavelet_FFT_analysis.py","file_name":"Wavelet_FFT_analysis.py","file_ext":"py","file_size_in_byte":12627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"246681021","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom urllib.parse import unquote, unquote_plus\n\n\ndef main():\n url1 = \"http://localhost:8080/~hellmann/\"\n url2 = \"http%3A%2F%2Flocalhost%3A8080%2F%7Ehellmann%2F\"\n\n print(\"unquote() :\", unquote(url1))\n print(\"unquote_plus():\", unquote_plus(url2))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"standard/057.urllib.parse/encode_query_arguments/urllib_parse_unquote.py","file_name":"urllib_parse_unquote.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"211262621","text":"dnaResult = []\nfileContent = \"\"\nfileContent1 = \"\"\nfileContent2 = \"\"\nmutateFile = \"\"\nnormalFile = \"\"\n\n#this function takes the users DNA sequence input and slpits it on every third character in the sequence (the code in line 2) and then runs a for loop for each set of 3 characters to test which Amino Acid the 3 characters form and adds the Acids accronym to the empty list which is returned at the end of the function\ndef translate(fileContent):\n sequence = [fileContent[i:i+3] for i in range(0, len(fileContent), 3)]\n for item in sequence:\n if item == \"ATT\" or item == \"ATC\" or item == \"ATA\" : \n dnaResult.append(\" I \")\n elif item == \"CTT\" or item == \"CTC\" or item == \"CTA\" or item == \"CTG\" or item == \"TTA\" or item == \"TTG\" : \n dnaResult.append(\" L \")\n elif item == \"GTT\" or item == \"GTC\" or item == \"GTA\" or item == \"GTG\" :\n dnaResult.append(\" V \")\n elif item == \"TTT\" or item == \"TTC\" : \n dnaResult.append(\" F \")\n elif item == \"ATG\" : \n dnaResult.append(\" M \")\n else:\n dnaResult.append(\" X \")\n return dnaResult\n\n#i open the file and then read each line \nfile = open(\"DNA.txt\",\"r\" )\nfileContent = file.read()\nfile.close()\n\n#then i make a for loop to go over each letter which was read from the file, if the latter is ‘a’ it mutates it ‘T’ and fix’s it ‘A’ and adds it to variables mutateFile and normalFile, if the letter is not ‘a’ it just adds the letter exactly as is to the same variables\nfor letter in fileContent:\n if letter == \"a\":\n mutateFile = (mutateFile + \"T\")\n normalFile = (normalFile + \"A\")\n else :\n mutateFile = (mutateFile + letter)\n normalFile = (normalFile + letter)\n\n#next 2 functions open 2 new files and writes to each file one of the different variabls mutateFile and normalFile\nfile = open(\"mutatedDNA.txt\",\"w\")\nfile.write(mutateFile)\nfile.close()\n\nfile = open(\"normalDNA.txt\",\"w\")\nfile.write(normalFile)\nfile.close()\n\n#the next 2 functions read from each file that was created above and runs them through the function “translate” to find the amino acids in each DNA sequence, i think this is where my error comes in, its when you call these to functions\nfile = open(\"mutatedDNA.txt\",\"r\")\nfileContent1 = file.read()\nprint(\"These are the folowing Amino Acids found in the DNA sequence's found in the mutated DNA text file : '\" + str(translate(fileContent1)))\nfile.close()\n\ndnaResult.clear()\n\nfile = open(\"normalDNA.txt\",\"r\")\nfileContent2 = file.read()\nprint(\"These are the folowing Amino Acids found in the DNA sequence's found in the normal DNA text file : '\" + str(translate(fileContent2)))\nfile.close()\n\ndnaResult.clear()\n","sub_path":"DNA_readfile.py","file_name":"DNA_readfile.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"126576279","text":"# Copyright 2020 The Forte Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nTrain preprocessor helps doing data pre-processing during training.\n\"\"\"\nimport logging\nfrom typing import Optional, Dict, Type, Any, Union, Iterator, List\nfrom texar.torch.data import DataIterator, Batch\nimport torch\nfrom torch import device\n\nfrom forte.common.configuration import Config\nfrom forte.data.converter import Converter\nfrom forte.data.data_pack import DataPack\nfrom forte.data.data_pack_dataset import DataPackDataset, DataPackIterator\nfrom forte.data.base_extractor import BaseExtractor\nfrom forte.data.ontology.core import Entry\nfrom forte.data.ontology.core import EntryType\nfrom forte.utils import get_class\n\nlogger = logging.getLogger(__name__)\n\n__all__ = [\"TrainPreprocessor\"]\n\n\nclass TrainPreprocessor:\n r\"\"\"\n `TrainPreprocessor` provides the functionality of doing pre-processing work\n including building vocabulary, extracting the features, batching and\n padding (optional). The main functionality is provided by its method\n :meth:`get_train_batch_iterator` which will return an `iterator` over the\n batch of pre-processed data. Please refer to the documentation of\n that method for how the pre-processing is done.\n\n `TrainPreprocessor` will maintain a Config that stores all the configurable\n parameters for various components.\n\n `TrainPreprocessor` will also accept a user request. Internally it will\n parse this user request and store the parsed result.\n\n Args:\n pack_iterator (Iterator[DataPack]): An iterator of\n :class:`~forte.data.data_pack.DataPack`.\n request (Dict): A request that specifies how to do train pre-processing.\n Please refer to :meth:`request` for details.\n config: A `Dict` or :class:`~forte.common.configuration.Config` that\n configs this preprocessor. See :meth:`default_configs` for\n the defaults.\n\n\n .. note::\n For parameters `request`, user does not necessarily need to provide\n `converter`. If no `converter` is specified, a default converter of\n type :class:`~forte.data.converter.Converter` will be picked.\n \"\"\"\n\n DATA_INPUT = 0\n DATA_OUTPUT = 1\n\n def __init__(self, pack_iterator: Iterator[DataPack]):\n self._pack_iterator: Iterator[DataPack] = pack_iterator\n self._cached_packs: List[DataPack] = []\n\n self._user_request: Dict = {}\n self._request: Dict = {}\n self._request_ready: bool = False\n self._vocab_ready: bool = False\n\n def initialize(self, config: Optional[Union[Config, Dict]] = None):\n # pylint: disable=attribute-defined-outside-init,unused-argument\n self._config = Config(config, default_hparams=self.default_configs())\n self._user_request = self._config.request\n self._validate_config()\n self._parse_request(self._user_request)\n self._build_vocab()\n\n @staticmethod\n def default_configs():\n r\"\"\"Returns a dictionary of default hyper-parameters.\n\n .. code-block:: python\n\n {\n \"preprocess\": {\n \"device\": \"cpu\",\n },\n \"dataset\": DataPackDataset.default_hparams()\n }\n\n Here:\n\n `\"preprocessor.device\"`:\n The device of the produced batches. For GPU training,\n set to current CUDA device.\n\n `\"dataset\"`:\n This contains all the configurable options same as\n :class:`~forte.data.data_pack_dataset.DataPackDataset`.\n \"\"\"\n\n # Configs should be serializable\n return {\n \"preprocess\": {\n \"device\": \"cpu\",\n },\n \"dataset\": DataPackDataset.default_hparams(),\n \"request\": {\"scope\": None, \"feature_scheme\": None},\n }\n\n def _validate_config(self):\n # Placeholder\n pass\n\n def _parse_request(self, request: Dict):\n \"\"\"\n This method has two responsibilities:\n 1. parse the given data request and stored it internally\n 2. validate if the given data request is valid\n \"\"\"\n parsed_request: Dict[str, Any] = {}\n\n assert \"scope\" in request, \"Field not found for data request: `scope`\"\n assert (\n \"feature_scheme\" in request\n ), \"Field not found for data request: `schemes`\"\n\n parsed_request[\"scope\"] = get_class(request[\"scope\"])\n parsed_request[\"schemes\"] = {}\n\n # Used for check dependency between different extractors\n scheme_group: Dict[str, Dict] = {\"dependent\": {}, \"dependee\": {}}\n\n for tag, scheme in request[\"feature_scheme\"].items():\n assert (\n \"extractor\" in scheme\n ), \"Field not found for data request scheme: `extractor`\"\n parsed_request[\"schemes\"][tag] = {}\n\n assert (\n \"type\" in scheme\n ), \"Field not found for data request scheme: `type`\"\n assert scheme[\"type\"] in [\n \"data_input\",\n \"data_output\",\n ], \"Type field must be either data_input or data_output.\"\n if scheme[\"type\"] == \"data_input\":\n parsed_request[\"schemes\"][tag][\n \"type\"\n ] = TrainPreprocessor.DATA_INPUT\n if scheme[\"type\"] == \"data_output\":\n parsed_request[\"schemes\"][tag][\n \"type\"\n ] = TrainPreprocessor.DATA_OUTPUT\n\n extractor_class = scheme[\"extractor\"][\"class_name\"]\n if not isinstance(get_class(extractor_class)(), BaseExtractor):\n raise RuntimeError(\"Invalid extractor: \", scheme[\"extractor\"])\n\n extractor: BaseExtractor = get_class(extractor_class)()\n extractor.initialize(config=scheme[\"extractor\"][\"config\"])\n parsed_request[\"schemes\"][tag][\"extractor\"] = extractor\n\n # Track dependency\n if hasattr(extractor, \"based_on\"):\n if extractor.entry_type not in scheme_group[\"dependent\"]:\n scheme_group[\"dependent\"][extractor.entry_type] = set()\n scheme_group[\"dependent\"][extractor.entry_type].add(extractor)\n else:\n if extractor.entry_type not in scheme_group[\"dependee\"]:\n scheme_group[\"dependee\"][extractor.entry_type] = set()\n scheme_group[\"dependee\"][extractor.entry_type].add(extractor)\n\n # Create default converter if there is no given converter\n if \"converter\" not in scheme:\n converter: Converter = Converter({})\n parsed_request[\"schemes\"][tag][\"converter\"] = converter\n\n # Check dependency\n for _, dependent_extractors in scheme_group[\"dependent\"].items():\n for dependent_extractor in dependent_extractors:\n based_on: Entry = dependent_extractor.based_on\n if based_on not in scheme_group[\"dependee\"]:\n raise ValueError(\n \"Extractor {} needs the entry {} to do extraction \"\n \"processing but it is not extracted by any other \"\n \"extractors given in request\".format(\n based_on, dependent_extractor.tag\n )\n )\n\n self._request = parsed_request\n self._request_ready = True\n\n def _build_vocab(self):\n scope: EntryType = self._request[\"scope\"]\n schemes: Dict = self._request[\"schemes\"]\n\n # TODO: clear vocab?\n\n # Cached all data packs\n for data_pack in self._pack_iterator:\n self._cached_packs.append(data_pack)\n\n for _, scheme in schemes.items():\n extractor: BaseExtractor = scheme[\"extractor\"]\n if extractor.vocab_method != \"raw\":\n for data_pack in self._cached_packs:\n for instance in data_pack.get(scope):\n extractor.update_vocab(data_pack, instance)\n\n self._vocab_ready = True\n\n def _build_dataset_iterator(self) -> DataIterator:\n scope: Type[EntryType] = self._request[\"scope\"] # type: ignore\n schemes: Dict[str, Dict[str, Any]] = self._request[\"schemes\"]\n\n data_source = DataPackIterator(\n pack_iterator=iter(self._cached_packs),\n context_type=scope,\n request={scope: []},\n )\n\n dataset = DataPackDataset(\n data_source, schemes, self._config.dataset, self.device\n )\n iterator = DataIterator(dataset)\n\n return iterator\n\n @property\n def request(self) -> Dict:\n # pylint: disable=line-too-long\n r\"\"\"A `Dict` containing all the information needed for doing the\n pre-processing. This is obtained via parsing the input `request`\n\n An example `request` is:\n\n .. code-block:: python\n\n request = {\n \"scope\": ft.onto.Sentence\n \"schemes\": {\n \"text_tag\": {\n \"extractor\": forte.data.extractor.AttributeExtractor,\n \"converter\": forte.data.converter.Converter,\n \"type\": TrainPreprocessor.DATA_INPUT,\n },\n \"char_tag\" {\n \"extractor\": forte.data.extractor.CharExtractor,\n \"converter\": forte.data.converter.Converter,\n \"type\": TrainPreprocessor.DATA_INPUT,\n }\n \"ner_tag\": {\n \"extractor\":\n forte.data.extractor.BioSeqTaggingExtractor,\n \"converter\": forte.data.converter.Converter,\n \"type\": TrainPreprocessor.DATA_OUTPUT,\n }\n }\n }\n\n Here:\n\n `\"scope\"`: Entry\n A class of type :class:`~forte.data.ontology.core.Entry` The\n granularity to separate data into different examples. For example,\n if `scope` is :class:`~ft.onto.base_ontology.Sentence`, then each\n training example will represent the information of a sentence.\n\n `\"schemes\"`: `Dict`\n A `Dict` containing the information about doing the pre-processing.\n The `key` is the tags provided by input `request`. The `value` is a\n `Dict` containing the information for doing pre-processing for that\n feature.\n\n `\"schemes.tag.extractor\"`: Extractor\n An instance of type :class:`~forte.data.extractor.BaseExtractor`.\n\n `\"schemes.tag.converter\"`: Converter\n An instance of type :class:`~forte.data.converter.Converter`.\n\n `\"schemes.tag.type\"`: TrainPreprocessor.DATA_INPUT/DATA_OUTPUT\n Denoting whether this feature is the input or output feature.\n \"\"\"\n if not self._request:\n self._parse_request(self._request)\n return self._request\n\n @property\n def device(self) -> device:\n r\"\"\"The device of the produced batches. For GPU training,\n set to current CUDA device.\n \"\"\"\n return torch.device(self._config.preprocess.device)\n\n @property\n def config(self) -> Config:\n r\"\"\"A :class:`~forte.common.configuration.Config` maintaining all the\n configurable options for this `TrainPreprocessor`.\n \"\"\"\n return self._config\n\n def get_train_batch_iterator(self) -> Iterator[Batch]:\n r\"\"\"\n This method mainly has four steps:\n\n 1. Iterate over :class:`~forte.data.data_pack.DataPack`\n via pack iterator\n 2. Extract :class:`~forte.data.converter.feature.Feature` from\n :class:`~forte.data.data_pack.DataPack`\n 3. Batch :class:`~forte.data.converter.feature.Feature`\n 4. (optional) Pad a batch of\n :class:`~forte.data.converter.feature.Feature`\n\n It will return an `iterator` of a batch of pre-processed data.\n\n Returns:\n An `Iterator` of type :class:`~texar.torch.data.Batch`\n\n Please refer to :meth:`collate` in\n :class:`~forte.data.data_pack_dataset.DataPackDataset` for details\n about its structure.\n \"\"\"\n if not self._request:\n raise ValueError(\"Feature resource is not parsed\")\n\n if not self._vocab_ready:\n raise ValueError(\"Vocab is not built\")\n\n dataset_iter = self._build_dataset_iterator()\n\n return iter(dataset_iter)\n","sub_path":"forte/train_preprocessor.py","file_name":"train_preprocessor.py","file_ext":"py","file_size_in_byte":13243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"417672064","text":"import ModelCreators.GANs\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass GAN:\n def __init__(self, images, discriminator, generator, network_optimizer, trainer, noise_dim=100):\n _, size = images.data.shape\n if (images.image_width * images.image_height != size):\n raise ValueError('Invalid image dimensions.')\n self.images = images\n \n self.discriminator = discriminator\n self.discriminator.trainable = False\n self.discriminator_loss = []\n \n self.generator = generator\n self.generator_loss = []\n \n self.network = ModelCreators.GANs.create_gan(generator, discriminator, network_optimizer, noise_dim)\n \n self.trainer = trainer\n \n self.noise_dim = noise_dim\n \n def train(self, epochs=1, batch_size=100):\n self.trainer(self, epochs, batch_size)\n\n def generateImages(self, number_images=100, dim=(10, 10), figsize=(10,10), filename=None):\n noise_vector = np.random.normal(0, 1, size=[number_images, self.noise_dim])\n \n generated_images = self.generator.predict(noise_vector)\n generated_images = generated_images.reshape(number_images,\n self.images.image_width, self.images.image_height)\n \n plt.figure(figsize=figsize)\n \n for image in range(number_images):\n plt.subplot(dim[0], dim[1], image + 1)\n plt.imshow(generated_images[image], interpolation='nearest', cmap='gray_r')\n plt.axis('off')\n \n plt.tight_layout()\n \n if filename is not None:\n plt.savefig(filename)\n else:\n plt.show()","sub_path":"YAGAN/GAN.py","file_name":"GAN.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"645937047","text":"# coding=utf-8\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport calendar\nimport sys\n\n\ndef add_months(dt,months):\n month = dt.month - 1 + months\n year = dt.year + int(month / 12)\n month = month % 12 + 1\n day = min(dt.day, calendar.monthrange(year, month)[1])\n return dt.replace(year=year, month=month, day=day)\n\ntoday = datetime.now().date()\ntoday=today.replace(year=2012,month=1,day=1)\n\nprint(today)\n\ntodaytime = datetime.now()\n# todaytime=todaytime.date(2014,1,1)\n# print (today.)\nprint(today.replace(2014).strftime('%Y%m'))\n\n# print(isinstance(demo, unicode))\n# with open('a.txt', 'w+', encoding=\"gb2312\") as f:\n# f.write(wpage)\n\n\n# print(ss.find_all('tr'))\n# pd.dataframe\n\n# https://www.aqistudy.cn/historydata/daydata.php?city=%E6%9D%AD%E5%B7%9E&month=2014-12\nwith open('ZhouShan.csv', 'w+', encoding='utf-8') as f:\n detail=today.strftime('%Y%m')\n while detail<='201902':\n \n response = requests.get(\n 'http://qq.ip138.com/weather/zhejiang/ZhouShan/'+detail+'.htm')\n wpage = response.text\n wpage = wpage.encode('iso-8859-1').decode('gb2312')\n soup = BeautifulSoup(wpage, 'html.parser')\n if (soup.find_all('table', id='weatherHistory')!=[]):\n ss = soup.find_all('table', id='weatherHistory')[0]\n else :\n ss = soup.find_all('table',class_='t12')[0]\n month_sum=[]\n for n, i in enumerate(ss):\n if n != 0:\n ii = i.find_all('td')\n s = []\n for item in ii:\n s.append(re.sub('[\\t\\n\\r]','',item.string))\n month_sum.append(s)\n month_sum=month_sum[::-1]\n for m in month_sum:\n f.writelines(','.join(m)+'\\n')\n \n today=add_months(today,1)\n detail=today.strftime('%Y%m')\n print(detail)\n\n","sub_path":"scrach.py","file_name":"scrach.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"546651406","text":"\"\"\"For parsing input/output files\"\"\"\nimport re\nimport os\nfrom copy import deepcopy\nfrom io import StringIO, IOBase\nfrom warnings import warn\n\nimport numpy as np\n\nfrom AaronTools.atoms import Atom\nfrom AaronTools.const import ELEMENTS, PHYSICAL, UNIT\n\nread_types = [\"xyz\", \"log\", \"com\", \"sd\"]\nwrite_types = [\"xyz\", \"com\"]\nfile_type_err = \"File type not yet implemented: {}\"\nfloat_num = re.compile(\"[-+]?\\d+\\.?\\d*\")\nNORM_FINISH = \"Normal termination\"\nERRORS = {\n \"Convergence failure -- run terminated.\": \"CONV\",\n \"Inaccurate quadrature in CalDSu\": \"CONV_CDS\",\n \"Error termination request processed by link 9999\": \"CONV_LINK\",\n \"FormBX had a problem\": \"FBX\",\n \"NtrErr Called from FileIO\": \"CHK\",\n \"Wrong number of Negative eigenvalues\": \"EIGEN\",\n \"Erroneous write\": \"QUOTA\",\n \"Atoms too close\": \"CLASH\",\n \"The combination of multiplicity\": \"CHARGEMULT\",\n \"Bend failed for angle\": \"REDUND\",\n \"Unknown message\": \"UNKNOWN\",\n}\n\n\ndef is_alpha(test):\n rv = re.search(\"^[a-zA-Z]+$\", test)\n return bool(rv)\n\n\ndef is_int(test):\n rv = re.search(\"^[+-]?\\d+$\", test)\n return bool(rv)\n\n\ndef is_num(test):\n rv = re.search(\"^[+-]?\\d+\\.?\\d*\", test)\n return bool(rv)\n\n\ndef step2str(step):\n if int(step) == step:\n return str(int(step))\n else:\n return str(step).replace(\".\", \"-\")\n\n\ndef str2step(step_str):\n if \"-\" in step_str:\n return float(step_str.replace(\"-\", \".\"))\n else:\n return float(step_str)\n\n\nclass FileWriter:\n @classmethod\n def write_file(cls, geom, style=\"xyz\", append=False, outfile=None, *args, **kwargs):\n \"\"\"\n Writes file from geometry in the specified style\n\n :geom: the Geometry to use\n :style: the file type style to generate\n Currently supported options: xyz, com\n :append: for *.xyz, append geometry to the same file\n :options: for *.com files, the computational options\n \"\"\"\n if style.lower() not in write_types:\n raise NotImplementedError(file_type_err.format(style))\n\n if style.lower() == \"xyz\":\n cls.write_xyz(geom, append, outfile)\n elif style.lower() == \"com\":\n if \"theory\" in kwargs and \"step\" in kwargs:\n step = kwargs[\"step\"]\n theory = kwargs[\"theory\"]\n del kwargs[\"step\"]\n del kwargs[\"theory\"]\n cls.write_com(geom, step, theory, outfile, **kwargs)\n else:\n raise TypeError(\n \"when writing com files, **kwargs must include: theory=Aaron.Theory(), step=int/float()\"\n )\n\n @classmethod\n def write_xyz(cls, geom, append, outfile=None):\n mode = \"a\" if append else \"w\"\n fmt = \"{:3s} {: 10.5f} {: 10.5f} {: 10.5f}\\n\"\n s = \"%i\\n\" % len(geom.atoms)\n s += \"%s\\n\" % geom.comment\n for atom in geom.atoms:\n s += fmt.format(atom.element, *atom.coords)\n\n if outfile is None:\n #if no output file is specified, use the name of the geometry\n with open(geom.name + \".xyz\", mode) as f:\n f.write(s)\n elif outfile is False:\n #if no output file is desired, just return the file contents\n return s.strip()\n else:\n #write output to the requested destination\n with open(outfile, mode) as f:\n f.write(s)\n\n return\n\n @classmethod\n def write_com(cls, geom, step, theory, outfile=None, **kwargs):\n has_frozen = False\n fmt = \"{:<3s}\" + \" {:> 12.6f}\" * 3 + \"\\n\"\n for atom in geom.atoms:\n if atom.flag:\n fmt = \"{:<3s} {:> 2d}\" + \" {:> 12.6f}\" * 3 + \"\\n\"\n has_frozen = True\n break\n\n s = theory.make_header(geom, step, **kwargs)\n for atom in geom.atoms:\n if has_frozen:\n s += fmt.format(a.element, -a.flag, *a.coords)\n else:\n s += fmt.format(a.element, *a.coords)\n\n s += theory.make_footer(geom, step)\n\n if outfile is None:\n #if outfile is not specified, name file in Aaron format\n fname = \"{}.{}.com\".format(geom.name, step2str(step))\n with open(fname, \"w\") as f:\n f.write(s)\n elif outfile is False:\n return s\n else:\n with open(outfile, 'w') as f:\n f.write(s)\n\n return\n\n\nclass FileReader:\n \"\"\"\n Attributes:\n name ''\n file_type ''\n comment ''\n atoms [Atom]\n other {}\n \"\"\"\n\n def __init__(self, fname, get_all=False, just_geom=True):\n \"\"\"\n :fname: either a string specifying the file name of the file to read\n or a tuple of (str(name), str(file_type), str(content))\n :get_all: if true, optimization steps are also saved in\n self.other['all_geom']; otherwise only saves last geometry\n :just_geom: if true, does not store other information, such as\n frequencies, only what is needed to construct a Geometry() obj\n \"\"\"\n # Initialization\n self.name = \"\"\n self.file_type = \"\"\n self.comment = \"\"\n self.atoms = []\n self.other = {}\n self.content = None\n self.all_geom = None\n\n # get file name and extention\n if isinstance(fname, str):\n fname = fname.rsplit(\".\", 1)\n self.name = fname[0]\n self.file_type = fname[1].lower()\n elif isinstance(fname, (tuple, list)):\n self.name = fname[0]\n self.file_type = fname[1]\n self.content = fname[2]\n if self.file_type not in read_types:\n raise NotImplementedError(file_type_err.format(self.file_type))\n\n # Fill in attributes with geometry information\n if self.content is None:\n self.read_file(get_all, just_geom)\n elif isinstance(self.content, str):\n f = StringIO(self.content)\n elif isinstance(self.content, IOBase):\n f = self.content\n\n if self.content is not None:\n if self.file_type == \"log\":\n self.read_log(f, get_all, just_geom)\n elif self.file_type == \"sd\":\n self.read_sd(f)\n elif self.file_type == \"xyz\":\n self.read_xyz(f)\n elif self.file_type == \"com\":\n self.read_com(f)\n\n def read_file(self, get_all=False, just_geom=True):\n \"\"\"\n Reads geometry information from fname.\n Parameters:\n get_all If false (default), only keep the last geom\n If true, self is last geom, but return list\n of all others encountered\n \"\"\"\n if os.path.isfile(self.name):\n f = open(self.name)\n else:\n fname = '.'.join([self.name, self.file_type])\n if os.path.isfile(fname):\n f = open(fname)\n else:\n raise FileNotFoundError(\"Error while looking for %s: could not find %s or %s in %s\" % \\\n (self.name, fname, self.name, os.getcwd()))\n\n if self.file_type == \"xyz\":\n self.read_xyz(f, get_all)\n elif self.file_type == \"log\":\n self.read_log(f, get_all, just_geom)\n elif self.file_type == \"com\":\n self.read_com(f)\n elif self.file_type == \"sd\":\n self.read_sd(f)\n\n f.close()\n\n return\n\n def skip_lines(self, f, n):\n for i in range(n):\n f.readline()\n return\n\n def read_xyz(self, f, get_all=False):\n self.all_geom = []\n # number of atoms\n f.readline()\n # comment\n self.comment = f.readline().strip()\n # atom info\n for line in f:\n line = line.strip()\n if line == \"\":\n continue\n try:\n int(line)\n if get_all:\n self.all_geom += [\n (deepcopy(self.comment), deepcopy(self.atoms))\n ]\n self.comment = f.readline().strip()\n self.atoms = []\n except ValueError:\n line = line.split()\n self.atoms += [Atom(element=line[0], coords=line[1:4])]\n for i, a in enumerate(self.atoms):\n a.name = str(i + 1)\n if get_all:\n self.all_geom += [(deepcopy(self.comment), deepcopy(self.atoms))]\n\n def read_sd(self, f, get_all=False):\n self.all_geom = []\n lines = f.readlines()\n self.comment = lines[0]\n counts = lines[3].split()\n natoms = int(counts[0])\n nbonds = int(counts[1])\n self.atoms = []\n for line in lines[4:4+natoms]:\n atom_info = line.split()\n self.atoms += [Atom(element=atom_info[3], coords = atom_info[0:3])]\n\n for i, a in enumerate(self.atoms):\n a.name = str(i + 1)\n\n def read_log(self, f, get_all=False, just_geom=True):\n def get_atoms(f, n):\n rv = []\n self.skip_lines(f, 4)\n line = f.readline()\n n += 5\n while \"--\" not in line:\n line = line.strip()\n line = line.split()\n for l in line:\n try:\n float(l)\n except ValueError:\n msg = \"Error detected with log file on line {}\"\n raise IOError(msg.format(n))\n elem = ELEMENTS[int(line[1])]\n flag = not bool(line[2])\n rv += [Atom(element=elem, flag=flag, coords=line[3:])]\n line = f.readline()\n n += 1\n return rv, n\n\n self.all_geom = []\n line = f.readline()\n self.other[\"archive\"] = \"\"\n found_archive = False\n n = 1\n while line != \"\":\n # archive entry\n if line.strip().startswith(\"1\\\\1\\\\\"):\n found_archive = True\n line = \"@\" + line.strip()[4:]\n if found_archive and line.strip().endswith(\"@\"):\n self.other[\"archive\"] = self.other[\"archive\"][:-2] + \"\\\\\\\\\"\n found_archive = False\n elif found_archive:\n self.other[\"archive\"] += line.strip()\n\n # geometry\n if re.search(\"(Standard|Input) orientation:\", line):\n if get_all and len(self.atoms) > 0:\n self.all_geom += [deepcopy(self.atoms)]\n self.atoms, n = get_atoms(f, n)\n if just_geom:\n line = f.readline()\n n += 1\n continue\n if \"Symbolic Z-matrix:\" in line:\n line = f.readline()\n n += 1\n match = re.search(\n \"Charge\\s*=\\s*(\\d+)\\s*Multiplicity\\s*=\\s*(\\d+)\", line\n )\n if match is not None:\n self.other[\"charge\"] = int(match.group(1))\n self.other[\"multiplicity\"] = int(match.group(2))\n\n # status\n if NORM_FINISH in line:\n self.other[\"finished\"] = True\n if \"SCF Done\" in line:\n self.other[\"energy\"] = float(line.split()[4])\n if \"Molecular mass:\" in line:\n self.other[\"mass\"] = float(float_num.search(line).group(0))\n self.other[\"mass\"] *= UNIT.AMU_TO_KG\n\n # Frequencies\n if \"hpmodes\" in line:\n self.other[\"hpmodes\"] = True\n if \"Harmonic frequencies\" in line:\n freq_str = line\n while line != \"\\n\":\n line = f.readline()\n n += 1\n freq_str += line\n if \"hpmodes\" not in self.other:\n self.other[\"hpmodes\"] = False\n self.other[\"frequency\"] = Frequency(\n freq_str, self.other[\"hpmodes\"]\n )\n\n # Thermo\n if \"Temperature\" in line:\n self.other[\"temperature\"] = float(\n float_num.search(line).group(0)\n )\n if \"Rotational constants (GHZ):\" in line:\n rot = float_num.findall(line)\n rot = [\n float(r) * PHYSICAL.PLANK * (10 ** 9) / PHYSICAL.KB\n for r in rot\n ]\n self.other[\"rotational_temperature\"] = rot\n if \"Sum of electronic and zero-point Energies=\" in line:\n self.other[\"E_ZPVE\"] = float(float_num.search(line).group(0))\n if \"Sum of electronic and thermal Enthalpies=\" in line:\n self.other[\"enthalpy\"] = float(float_num.search(line).group(0))\n if \"Sum of electronic and thermal Free Energies=\" in line:\n self.other[\"free_energy\"] = float(\n float_num.search(line).group(0)\n )\n if \"Zero-point correction=\" in line:\n self.other[\"ZPVE\"] = float(float_num.search(line).group(0))\n if \"Rotational symmetry number\" in line:\n self.other[\"rotational_symmetry_number\"] = int(\n re.search(\"\\d+\", line).group(0)\n )\n\n # Gradient\n if re.search(\"Threshold\\s+Converged\", line) is not None:\n line = f.readline()\n n += 1\n grad = {}\n\n def add_grad(line, name, grad):\n line = line.split()\n grad[name] = {\n \"value\": line[2],\n \"threshold\": line[3],\n \"converged\": True if line[4] == \"YES\" else False,\n }\n return grad\n\n while line != \"\":\n if \"Predicted change in Energy\" in line:\n break\n if re.search(\"Maximum\\s+Force\", line) is not None:\n grad = add_grad(line, \"Max Force\", grad)\n if re.search(\"RMS\\s+Force\", line) is not None:\n grad = add_grad(line, \"RMS Force\", grad)\n if re.search(\"Maximum\\s+Displacement\", line) is not None:\n grad = add_grad(line, \"Max Disp\", grad)\n if re.search(\"RMS\\s+Displacement\", line) is not None:\n grad = add_grad(line, \"RMS Disp\", grad)\n line = f.readline()\n n += 1\n self.other[\"gradient\"] = grad\n\n # capture errors\n for err in ERRORS:\n if err in line:\n self.other[\"error\"] = ERRORS[err]\n self.other[\"error_msg\"] = line.strip()\n break\n else:\n self.other[\"error\"] = None\n\n line = f.readline()\n n += 1\n\n for i, a in enumerate(self.atoms):\n a.name = str(i + 1)\n\n if \"finished\" not in self.other:\n self.other[\"finished\"] = False\n if \"error\" not in self.other:\n self.other[\"error\"] = None\n if not self.other[\"finished\"] and not self.other[\"error\"]:\n self.other[\"error\"] = ERRORS[\"Unknown message\"]\n self.other[\"error_msg\"] = \"Unknown message\"\n return\n\n def read_com(self, f):\n found_atoms = False\n found_constraint = False\n atoms = []\n other = {}\n for line in f:\n # header\n if line.startswith(\"%\"):\n continue\n if line.startswith(\"#\"):\n method = re.search(\"^#([NnPpTt]\\s+?)(\\S+)|^#\\s*?(\\S+)\", line)\n #route can be #n functional/basis ...\n #or #functional/basis ...\n #or # functional/basis ...\n if method.group(3):\n other['method'] = method.group(3)\n else:\n other['method'] = method.group(2)\n if \"temperature=\" in line:\n other[\"temperature\"] = re.search(\n \"temperature=(\\d+\\.?\\d*)\", line\n ).group(1)\n if \"solvent=\" in line:\n other[\"solvent\"] = re.search(\n \"solvent=(\\S+)\\)\", line\n ).group(1)\n if \"scrf=\" in line:\n other[\"solvent_model\"] = re.search(\n \"scrf=\\((\\S+),\", line\n ).group(1)\n if \"EmpiricalDispersion=\" in line:\n other[\"emp_dispersion\"] = re.search(\n \"EmpiricalDispersion=(\\S+)\", line\n ).group(1)\n if \"int=(grid(\" in line:\n other[\"grid\"] = re.search(\"int=\\(grid(\\S+)\", line).group(1)\n for _ in range(4):\n line = f.readline()\n line = line.split()\n other[\"charge\"] = line[0]\n other[\"mult\"] = line[1]\n found_atoms = True\n continue\n # constraints\n if found_atoms and line.startswith(\"B\") and line.endswith(\"F\"):\n found_constraint = True\n if \"constraint\" not in other:\n other[\"constraint\"] = []\n other[\"constraint\"] += [float_num.findall(line)]\n continue\n # footer\n if found_constraint:\n if \"footer\" not in other:\n other[\"footer\"] = \"\"\n other[\"footer\"] += line\n continue\n # atom coords\n nums = float_num.findall(line)\n line = line.split()\n if len(line) == 5 and is_alpha(line[0]) and len(nums) == 4:\n if not is_int(line[1]):\n continue\n a = Atom(element=line[0], coords=nums[1:], flag=nums[0])\n atoms += [a]\n elif len(line) == 4 and is_alpha(line[0]) and len(nums) == 3:\n a = Atom(element=line[0], coords=nums)\n atoms += [a]\n else:\n continue\n self.atoms = atoms\n self.other = other\n return\n\n\nclass Frequency:\n \"\"\"\n ATTRIBUTES\n :data: Data - contains frequencies, intensities, and normal mode vectors\n :imaginary_frequencies: list(float)\n :real_frequencies: list(float)\n :lowest_frequency: float\n :by_frequency: dict keyed by frequency containing intensities and vectors\n {freq: {intensity: float, vector: np.array}}\n :is_TS: bool - true if len(imaginary_frequencies) == 1, else False\n \"\"\"\n\n class Data:\n \"\"\"\n ATTRIBUTES\n :frequency: float\n :intensity: float\n :vector: (2D array) normal mode vectors\n \"\"\"\n\n def __init__(self, frequency, intensity=None, vector=[], forcek=[]):\n self.frequency = frequency\n self.intensity = intensity\n self.vector = np.array(vector)\n self.forcek = np.array(forcek)\n\n def __init__(self, data, hpmodes=None):\n \"\"\"\n :data: should either be a str containing the lines of the output file\n with frequency information, or a list of Data objects\n :hpmodes: required when data is a string\n \"\"\"\n self.data = []\n self.imaginary_frequencies = None\n self.real_frequencies = None\n self.lowest_frequency = None\n self.by_frequency = {}\n self.is_TS = None\n\n if isinstance(data[0], Frequency.Data):\n self.data = data\n self.sort_frequencies()\n return\n else:\n if hpmodes is None:\n raise TypeError(\n \"hpmode argument required when data is a string\"\n )\n\n lines = data.split(\"\\n\")\n num_head = 0\n for line in lines:\n if \"Harmonic frequencies\" in line:\n num_head += 1\n if hpmodes and num_head != 2:\n warn(\"Log file damaged, cannot get frequencies\")\n return\n self.parse_lines(lines, hpmodes)\n self.sort_frequencies()\n return\n\n def parse_lines(self, lines, hpmodes):\n num_head = 0\n idx = -1\n modes = []\n for line in lines:\n if \"Harmonic frequencies\" in line:\n num_head += 1\n if hpmodes and num_head == 2:\n # if hpmodes, want just the first set of freqs\n break\n continue\n if \"Frequencies\" in line and ((hpmodes and \"---\" in line) or \\\n (\"--\" in line and not hpmodes)):\n for i in float_num.findall(line):\n self.data += [Frequency.Data(float(i))]\n modes += [[]]\n idx += 1\n continue\n\n if (\"Force constants\" in line and \"---\" in line and hpmodes) or \\\n (\"Frc consts\" in line and \"--\" in line and not hpmodes):\n force_constants = float_num.findall(line)\n for i in range(-len(force_constants), 0, 1):\n self.data[i].forcek = float(force_constants[i])\n continue\n\n if \"IR Inten\" in line and ((hpmodes and \"---\" in line) or \\\n (not hpmodes and \"--\" in line)):\n for i in float_num.findall(line):\n self.data[idx].intensity = float(i)\n continue\n\n if hpmodes:\n match = re.search(\n \"^\\s+\\d+\\s+\\d+\\s+\\d+(\\s+[+-]?\\d+\\.\\d+)+$\", line\n )\n if match is None:\n continue\n values = float_num.findall(line)\n coord = int(values[0]) - 1\n atom = int(values[1]) - 1\n moves = values[3:]\n for i, m in enumerate(moves):\n tmp = len(moves) - i\n mode = modes[-tmp]\n try:\n vector = mode[atom]\n except IndexError:\n vector = [0, 0, 0]\n modes[-tmp] += [[]]\n vector[coord] = m\n modes[-tmp][atom] = vector\n else:\n match = re.search(\"^\\s+\\d+\\s+\\d+(\\s+[+-]?\\d+\\.\\d+)+$\", line)\n if match is None:\n continue\n values = float_num.findall(line)\n atom = int(values[0]) - 1\n moves = np.array(values[2:], dtype=np.float)\n n_moves = len(moves) // 3\n for i in range(-n_moves, 0):\n modes[i].append(moves[3*n_moves+3*i:4*n_moves+3*i])\n\n for mode, data in zip(modes, self.data):\n data.vector = np.array(mode, dtype=np.float)\n return\n\n def sort_frequencies(self):\n self.imaginary_frequencies = []\n self.real_frequencies = []\n for i, data in enumerate(self.data):\n freq = data.frequency\n if freq < 0:\n self.imaginary_frequencies += [freq]\n elif freq > 0:\n self.real_frequencies += [freq]\n self.by_frequency[freq] = {\n \"intensity\": data.intensity,\n \"vector\": data.vector,\n }\n self.lowest_frequency = self.data[0].frequency\n self.is_TS = True if len(self.imaginary_frequencies) == 1 else False\n","sub_path":"fileIO.py","file_name":"fileIO.py","file_ext":"py","file_size_in_byte":23585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"375921798","text":"import os # isort:skip\nfrom decouple import config\nimport django_heroku\nimport dj_database_url\ngettext = lambda s: s\nDATA_DIR = os.path.dirname(os.path.dirname(__file__))\n\"\"\"\nDjango settings for mylaptop project.\n\nGenerated by 'django-admin startproject' using Django 1.11.25.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.11/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.11/ref/settings/\n\"\"\"\n\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/\n\n\nSECRET_KEY = config('SECRET_KEY')\nDEBUG = config('DEBUG', default=False, cast=bool)\n\nALLOWED_HOSTS = ['coollaptop.herokuapp.com', '127.0.0.1']\n\n\n# Application definition\n\n\nROOT_URLCONF = 'mylaptop.urls'\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.11/topics/i18n/\n\nLANGUAGE_CODE = 'en'\n\nTIME_ZONE = 'Europe/Kiev'\n\nUSE_I18N = False\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.11/howto/static-files/\n\nSTATIC_URL = '/static/'\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(DATA_DIR, 'media')\nSTATIC_ROOT = os.path.join(DATA_DIR, 'mylaptop', 'static')\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\nSITE_ID = 8\n\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'mylaptop', 'templates'),],\n 'OPTIONS': {\n 'context_processors': [\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.template.context_processors.media',\n 'django.template.context_processors.csrf',\n 'django.template.context_processors.tz',\n 'sekizai.context_processors.sekizai',\n 'django.template.context_processors.static',\n 'cms.context_processors.cms_settings'\n ],\n 'loaders': [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n ],\n },\n },\n]\n\n\nMIDDLEWARE = [\n 'cms.middleware.utils.ApphookReloadMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'cms.middleware.user.CurrentUserMiddleware',\n 'cms.middleware.page.CurrentPageMiddleware',\n 'cms.middleware.toolbar.ToolbarMiddleware',\n 'cms.middleware.language.LanguageCookieMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django_otp.middleware.OTPMiddleware',\n\n]\n\nINSTALLED_APPS = [\n 'djangocms_admin_style',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.admin',\n 'django.contrib.sites',\n 'django.contrib.sitemaps',\n 'django.contrib.staticfiles',\n 'django.contrib.messages',\n 'cms',\n 'menus',\n 'sekizai',\n 'treebeard',\n 'djangocms_text_ckeditor',\n 'filer',\n 'easy_thumbnails',\n 'djangocms_column',\n 'djangocms_file',\n 'djangocms_link',\n 'djangocms_picture',\n 'djangocms_style',\n 'djangocms_snippet',\n 'djangocms_googlemap',\n 'djangocms_video',\n\n 'mylaptop',\n 'accounts',\n 'egs',\n 'questions',\n 'django_otp',\n 'django_otp.plugins.otp_static',\n 'django_otp.plugins.otp_totp',\n 'two_factor',\n\n]\n\n\nLANGUAGES = (\n # Customize this\n ('en', gettext('en')),\n)\nCMS_LANGUAGES = {\n # Customize this\n 1: [\n {\n 'code': 'en',\n 'name': gettext('en'),\n 'redirect_on_fallback': True,\n 'public': True,\n 'hide_untranslated': False,\n },\n ],\n 'default': {\n 'redirect_on_fallback': True,\n 'public': True,\n 'hide_untranslated': False,\n },\n}\n\nCMS_TEMPLATES = (\n # Customize this\n ('fullwidth.html', 'Fullwidth'),\n ('sidebar_left.html', 'Sidebar Left'),\n ('sidebar_right.html', 'Sidebar Right'),\n ('homepage.html', 'home'),\n\n)\n\nCMS_PERMISSION = True\n\nCMS_PLACEHOLDER_CONF = {}\n\nCMS_TOOLBAR_ANONYMOUS_ON = False\n\nDATABASES = {\n 'default': {\n 'CONN_MAX_AGE': 0,\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'HOST': 'localhost',\n 'NAME': 'Laptop',\n 'PASSWORD': 'mortal99',\n 'PORT': '5432',\n 'USER': 'postgres'\n }\n}\n\ndb_from_env = dj_database_url.config()\nDATABASES['default'].update(db_from_env)\n\nMIGRATION_MODULES = {\n \n}\n\nTHUMBNAIL_PROCESSORS = (\n 'easy_thumbnails.processors.colorspace',\n 'easy_thumbnails.processors.autocrop',\n 'filer.thumbnail_processors.scale_and_crop_with_subject_location',\n 'easy_thumbnails.processors.filters'\n)\n\nEMAIL_USE_TLS = True\nEMAIL_USE_SSL = False\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'nineball.hustler.nine@gmail.com'\nDEFAULT_FROM_EMAIL = EMAIL_HOST_USER\nEMAIL_HOST_PASSWORD = 'mortal99kombat'\nEMAIL_PORT = 587\n\n\nLOGIN_URL = 'two_factor:login'\n\n\nSECURE_SSL_REDIRECT = True\nSESSION_COOKIE_SECURE = True\nCSRF_COOKIE_SECURE = True\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n","sub_path":"mylaptop/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"277183242","text":"\nimport time\nimport sys\n\nsys.path.append(\"..\")\nimport database.db_operator as db_operator\nimport log.custom_logger as custom_logger\n\nclass CommonDBOperation:\n # 通用,常用的数据库操作\n\n def __init__(self):\n pass\n\n def get_the_last_trading_date(self,day):\n # 获取传入日期参数最近的交易日期, 即上一个交易日\n # day: 交易日期,如 2021-06-09\n # return: 如果存在最近的交易日期,则返回日期\n # 如果不存在,则返回 0000-00-00\n\n # 查询SQL\n selecting_sql = \"SELECT trading_date FROM trading_days WHERE trading_date < '%s' ORDER BY \" \\\n \"ABS(DATEDIFF(trading_date, '%s')) ASC LIMIT 1\" % (day,day)\n\n # 查询\n selecting_result = db_operator.DBOperator().select_one(\"financial_data\", selecting_sql)\n\n if selecting_result is not None:\n return selecting_result[\"trading_date\"]\n else:\n # 日志记录\n log_msg = \"无法获取 \"+day+\" 最近的交易日期\"\n custom_logger.CustomLogger().log_writter(log_msg, 'error')\n return \"0000-00-00\"\n\n\n\n\n\n\n\nif __name__ == '__main__':\n go = CommonDBOperation()\n last_trade_day = go.get_the_last_trading_date(\"2001-05-06\")\n print(last_trade_day)","sub_path":"data_miner/common_db_operation.py","file_name":"common_db_operation.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"557199454","text":"import discord\nfrom discord.ext import commands\nimport random\nclass BAfun():\n\n def __init__(ctx, bot):\n ctx.bot = bot\n ctx.toggle = False\n ctx.nsword = ctx.nlove = ctx.nsquat = ctx.npizza = ctx.nbribe = ctx.ndad = ctx.ncalc \\\n = ctx.nbutt = ctx.ncom = ctx.nflirt = ctx.nup = 0\n \n@commands.command(name=\"8ball\")\nasync def _ball(self, ctx, *, question):\n ': Ask me a question'\n question = question\n answers = random.randint(1, 20)\n\n if question == \"\":\n return\n\n elif answers == 1:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` It is certain```\"\"\")\n\n elif answers == 2:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` It is decidedly so```\"\"\")\n\n elif answers == 3:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Without a doubt```\"\"\")\n\n elif answers == 4:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Yes definitely```\"\"\")\n\n elif answers == 5:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` You may rely on it```\"\"\")\n\n elif answers == 6:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` As i see it, yes```\"\"\")\n\n elif answers == 7:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Most likely```\"\"\")\n\n elif answers == 8:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Outlook good```\"\"\")\n\n elif answers == 9:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Yes```\"\"\")\n\n elif answers == 10:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Signs point to yes```\"\"\")\n\n elif answers == 11:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Reply hazy try again```\"\"\")\n\n elif answers == 12:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Ask again later```\"\"\")\n\n elif answers == 13:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Better not to tell you now```\"\"\")\n\n elif answers == 14:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Cannot predict now```\"\"\")\n\n elif answers == 15:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Concentrate and ask again```\"\"\")\n\n elif answers == 16:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Don't count on it```\"\"\")\n\n elif answers == 17:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` My reply is no```\"\"\")\n\n elif answers == 18:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` My sources say no```\"\"\")\n\n elif answers == 19:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Outlook not so good```\"\"\")\n\n elif answers == 20:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Very doubtful```\"\"\")\n \n@commands.command()\nasync def sword(ctx, *, user: discord.Member):\n \"\"\"Sword Duel!\"\"\"\n author = ctx.message.author\n if user.id == ctx.bot.user.id:\n await ctx.send(\"I'm not the fighting kind\")\n else:\n await ctx.send(author.mention + \" and \" + user.mention + \" dueled for \" + str(randint(2, 120)) +\n \" gruesome hours! It was a long, heated battle, but \" +\n choice([author.mention, user.mention]) + \" came out victorious!\")\n ctx.counter(n)\n\n@commands.command()\nasync def love(ctx, user: discord.Member):\n \"\"\"Found your one true love?\"\"\"\n author = ctx.message.author\n if user.id == ctx.bot.user.id:\n await ctx.send(\"I am not capable of loving like you can. I'm sorry.\" )\n else:\n await ctx.send(author.mention + \" is capable of loving \" + user.mention + \" a whopping \" +\n str(randint(0, 100)) + \"%!\")\n ctx.counter(n)\n\n@commands.command()\nasync def squat(ctx):\n \"\"\"How is your workout going?\"\"\"\n author = ctx.message.author\n await ctx.send(author.mention + \" puts on their game face and does \" + str(randint(2, 1000)) +\n \" squats in \" + str(randint(4, 90)) + \" minutes. Wurk it!\")\n ctx.counter(n)\n\n@commands.command()\nasync def pizza(ctx):\n \"\"\"How many slices of pizza have you eaten today?\"\"\"\n author = ctx.message.author\n await ctx.send(author.mention + \" has eaten \" + str(randint(2, 120)) + \" slices of pizza today.\")\n ctx.counter(n)\n\n@commands.command()\nasync def bribe(ctx):\n \"\"\"Find out who is paying under the table\"\"\"\n author = ctx.message.author\n await ctx.send(author.mention + \" has bribed \" + ctx.bot.user.mention + \" with \" +\n str(randint(10, 10000)) + \" dollars!\")\n ctx.counter(n)\n\n@commands.command()\nasync def daddy(ctx):\n \"\"\"Pass the salt\"\"\"\n author = ctx.message.author\n await ctx.send(\"I'm kink shaming you, \" + author.mention)\n ctx.counter(n)\n\n@commands.command()\nasync def calculated(ctx):\n \"\"\"That was 100% calculated!\"\"\"\n await ctx.send(\"That was \" + str(randint(0, 100)) + \"% calculated!\")\n ctx.counter(n)\n\n@commands.command()\nasync def butts(ctx):\n \"\"\"butts\"\"\"\n await ctx.send(\"ლ(́◉◞౪◟◉‵ლ)\")\n ctx.counter(n)\n\n@commands.command()\nasync def _commands(ctx):\n \"\"\"Command the bot\"\"\"\n await ctx.send(\"Don't tell me what to do.\")\n ctx.counter(n)\n\n@commands.command()\nasync def flirt(ctx):\n \"\"\"Slide into DMs\"\"\"\n await ctx.send(\" ;)) ))) hey b a b e ; ; ;))) ) ;)\")\n ctx.counter(n)\n\n@commands.command()\nasync def updog(ctx):\n \"\"\"This is updog\"\"\"\n await ctx.send(\"What's updog?\")\n ctx.counter(n)\n@commands.command(pass_context=True)\nasync def poke(ctx, member: discord.Member):\n \"\"\"poke someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n poke = \"**{0} poked {1}!**\"\n\n choices = ['https://pa1.narvii.com/6021/b50b8078fa1d8e8f6d2ebfb085f106c642141723_hq.gif',\n 'https://media1.tenor.com/images/8fe23ec8e2c5e44964e5c11983ff6f41/tenor.gif',\n 'https://media.giphy.com/media/WvVzZ9mCyMjsc/giphy.gif',\n 'https://media.giphy.com/media/pWd3gD577gOqs/giphy.gif',\n 'http://gifimage.net/wp-content/uploads/2017/09/anime-poke-gif-12.gif', 'https://i.gifer.com/S00v.gif',\n 'https://i.imgur.com/1NMqz0i.gif']\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=poke.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n@commands.command(pass_context=True)\nasync def hug(ctx, member: discord.Member):\n \"\"\"hug someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n hug = \"**{0}Aww, I see you are lonely, take a hug <3{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/447337220895145998/466226631778893824/hug-rk_6GyncG.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466227315110576129/hug-ry6o__7D-.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466227511165190175/hug-Bk5haAocG.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466228974326906891/hug-BkBs2uk_b.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466229286966394881/hug-HkfgF_QvW.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466230001872666635/hug-BkZngAYtb.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466230123209687040/hug-Bk5T2_1Ob.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466230234795212802/hug-Hy4hxRKtW.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=hug.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n@commands.command(pass_context=True)\nasync def slap(ctx, member: discord.Member):\n \"\"\"Slap someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n slap = \"**{0}Hmm, why do you want this?Slaps.{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/447337220895145998/466229677300908042/slap-rJYqQyKv-.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466229535059345408/slap-r1PXzRYtZ.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466229453236731904/slap-SkSCyl5yz.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466231429337055242/slap-B1-nQyFDb.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466231614352130048/slap-HkskD56OG.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466231875120267284/slap-By2iXyFw-.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466232154112917504/slap-SkKn-xc1f.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466232493889290241/slap-rJrnXJYPb.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=slap.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n\n@commands.command()\nasync def dog(ctx):\n ''''sends cute dog pics'''\n r = requests.get(\"https://dog.ceo/api/breeds/image/random\").json()\n embed=discord.Embed()\n embed.set_image(url=r[\"message\"])\n await ctx.send(embed=embed)\n\n\n\n@commands.command(pass_context=True, no_pm=True)\nasync def insult(ctx, user : discord.Member=None):\n \"\"\"Insult the user\"\"\"\n\n msg =\" How original. No one else had thought of trying to get the bot to insult itself. I applaud your creativity. Yawn. Perhaps this is why you don't have friends. You don't add anything new to any conversation. You are more of a bot than me, predictable answers, and absolutely dull to have an actual conversation with.\"\n if user != None:\n if user.id == ctx.bot.user.id:\n user = ctx.message.author\n await ctx.send(user.mention + msg)\n else:\n await ctx.send(user.mention + msg + random.choice(msg))\n else:\n await ctx.send(ctx.message.author.mention + msg + random.choice(msg))\n\n@commands.command(pass_context=True)\nasync def bite(ctx, member: discord.Member):\n \"\"\"bites someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n bite = \"**{0}bites you.{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/456701536912015361/466571069973856256/bite-HkutgeXob.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466571762339938304/bite-ry00lxmob.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572007258193920/bite-H1_Jbemjb.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572188372434964/bite-H1hige7sZ.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572377233293322/bite-Hk1sxlQjZ.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572552739880961/bite-rkakblmiZ.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572804385669120/bite-BJXRmfr6-.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466573024078987284/bite-ry3pQGraW.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=bite.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n@commands.command(pass_context=True)\nasync def cuddle(ctx, member: discord.Member):\n \"\"\"cuddle someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n cuddle = \"**cuddles you.{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/456701536912015361/466573538841591809/cuddle-SJn18IXP-.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466573996201082900/cuddle-r1s9RqB7G.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574139805794306/cuddle-SJceIU7wZ.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574279127859200/cuddle-r1XEOymib.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574467070427156/cuddle-S1T91Att-.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574644577697792/cuddle-BkZCSI7Pb.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574850375548939/cuddle-Byd1IUmP-.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466575399862665216/cuddle-BkN0rIQDZ.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=cuddle.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n\n@commands.command(pass_context=True)\nasync def pat(ctx, member: discord.Member):\n \"\"\"pat someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n pat = \"**you have been patted .{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/456701536912015361/466577618771378176/pat-rktsca40-.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466577986209185812/pat-rkZbJAYKW.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466578464619626496/pat-SJva1kFv-.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466578677090484224/pat-BkJBQlckz.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466578825468182538/pat-H1s5hx0Bf.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466579159435706380/pat-rJMskkFvb.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466579338490544128/pat-rkBZkRttW.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466579500117917727/pat-Sk2FyQHpZ.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=pat.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n@commands.command(pass_context=True)\nasync def kiss(ctx, member: discord.Member):\n \"\"\"kiss someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n kiss = \"** kissed you.{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/456701536912015361/466579840070582284/kiss-B1MJ2aODb.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466580423116324874/kiss-Hkt-nTOwW.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466581686591946763/kiss-r1VWnTuPW.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466582897755947017/kiss-BkUJNec1M.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466583102047780914/kiss-Sk1k3TdPW.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466583257341755392/kiss-BJv0o6uDZ.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466583404222087168/kiss-S1PCJWASf.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466583780736499712/kiss-SJ3dXCKtW.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=kiss.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n@commands.command(pass_context=True)\nasync def pepe(ctx, user: discord.Member = None):\n \"\"\"kiss someone!\"\"\"\n user = user or ctx.message.author\n\n pepe = \"** kissed you.{1}!**\"\n\n choices = [\"http://i.imgur.com/vpIyEue.png\",\n \"http://i.imgur.com/0koMC0v.jpg\",\n \"http://i.imgur.com/9Q6KMZa.png\",\n \"http://i.imgur.com/54xy6jr.png\",\n \"http://i.imgur.com/QvCngiJ.jpg\",\n \"http://i.imgur.com/ftWgrOE.jpg\",\n \"http://i.imgur.com/rhDSqRv.jpg\",\n \"http://i.imgur.com/89NZ3zM.jpg\",\n \"http://i.imgur.com/I4cIH5b.png\",\n \"http://i.imgur.com/GIFc4uX.png\",\n \"http://i.imgur.com/bgShJpZ.png\",\n \"http://i.imgur.com/jpfPLyn.png\",\n \"http://i.imgur.com/pZeYoej.png\",\n \"http://i.imgur.com/M8V9WKB.jpg\",\n \"http://i.imgur.com/ZBzHxNk.jpg\",\n \"http://i.imgur.com/xTyJ6xa.png\",\n \"http://i.imgur.com/TOozxRQ.png\",\n \"http://i.imgur.com/Eli5HdZ.png\",\n \"http://i.imgur.com/pkikqcA.jpg\",\n \"http://i.imgur.com/gMF8eo5.png\",\n \"http://i.imgur.com/HYh8BUm.jpg\",\n \"http://i.imgur.com/ZGVrRye.jpg\",\n \"http://i.imgur.com/Au4F1px.jpg\",\n \"http://i.imgur.com/gh36k9y.jpg\",\n \"http://i.imgur.com/MHDoRuN.png\",\n \"http://i.imgur.com/V3MJfyK.png\",\n \"http://i.imgur.com/QGGTipc.jpg\",\n \"http://i.imgur.com/PRFrTgz.png\",\n \"http://i.imgur.com/9UBJrwM.jpg\",\n \"http://i.imgur.com/WQY9Vhb.jpg\",\n \"http://i.imgur.com/sIbQdou.jpg\",\n \"http://i.imgur.com/LlUMg00.jpg\",\n \"http://i.imgur.com/MmijlWa.png\",\n \"http://i.imgur.com/i0CrtrX.png\",\n \"http://i.imgur.com/Dfpudwp.jpg\",\n \"http://i.imgur.com/hhg0wVF.gif\",\n \"http://i.imgur.com/7VDiIHN.jpg\",\n \"http://i.imgur.com/nxvXpNV.jpg\",\n \"http://i.imgur.com/DZYEjrW.gif\",\n \"http://i.imgur.com/mnyQ0Rh.jpg\",\n \"http://i.imgur.com/aHawbbs.jpg\",\n \"http://i.imgur.com/g8cCHV7.jpg\",\n \"http://i.imgur.com/E2cMU7Y.jpg\",\n \"http://i.imgur.com/PkmcgGF.jpg\",\n \"http://i.imgur.com/7qLQ1xl.jpg\",\n \"http://i.imgur.com/7qLQ1xl.jpg\",\n \"http://i.imgur.com/arSsPwf.png\",\n \"http://i.imgur.com/xcYh4iC.png\",\n \"http://i.imgur.com/9692WND.jpg\",\n \"http://i.imgur.com/diAK5Nu.jpg\",\n \"http://i.imgur.com/zDs0tRW.jpg\",\n \"http://i.imgur.com/PEM87nV.jpg\",\n \"http://i.imgur.com/zlCzlND.jpg\",\n \"http://i.imgur.com/n0OHxDl.jpg\",\n \"http://i.imgur.com/TQRf1WH.png\",\n \"http://i.imgur.com/zi9ad15.jpg\",\n \"http://i.imgur.com/b8A6Qke.jpg\",\n \"http://i.imgur.com/YuLapEu.png\",\n \"http://i.imgur.com/fWFXkY1.jpg\",\n \"http://i.imgur.com/i5vNvWU.png\",\n \"http://i.imgur.com/oXwUwtJ.jpg\",\n \"http://i.imgur.com/hadm4jV.jpg\",\n \"http://i.imgur.com/gbCvkqo.png\",\n \"http://i.imgur.com/wDiiWBG.jpg\",\n \"http://i.imgur.com/Mvghx4V.jpg\",\n \"http://i.imgur.com/SnTAjiJ.jpg\",\n \"http://i.imgur.com/QvMYBnu.png\",\n \"http://i.imgur.com/WkzPvfB.jpg\",\n \"http://i.imgur.com/PfAm4ot.png\",\n \"http://i.imgur.com/SIk4a45.png\",\n \"http://i.imgur.com/aISFmQq.jpg\",\n \"http://i.imgur.com/sMQkToE.png\",\n \"http://i.imgur.com/7i3cBrP.png\",\n \"http://i.imgur.com/1oMSz6e.png\",\n \"http://i.imgur.com/nVCRnRv.png\",\n \"http://i.imgur.com/FzWmxmi.jpg\",\n \"http://i.imgur.com/rpUI20F.jpg\",\n \"http://i.imgur.com/FDmnFDZ.jpg\",\n \"http://i.imgur.com/40Z1Yyg.jpg\",\n \"http://i.imgur.com/osy5Nu4.png\",\n \"http://i.imgur.com/4w81MSS.jpg\",\n \"http://i.imgur.com/qRXQFYa.png\",\n \"http://i.imgur.com/A1af62j.jpg\",\n \"http://i.imgur.com/wOc6fUe.jpg\",\n \"http://i.imgur.com/Z6ILiJ4.jpg\",\n \"http://i.imgur.com/537UpEJ.jpg\",\n \"http://i.imgur.com/HDc6kko.png\",\n \"http://i.imgur.com/oyLpuXq.jpg\",\n \"http://i.imgur.com/iCmGtJS.jpg\",\n \"http://i.imgur.com/MjpnlQm.png\",\n \"http://i.imgur.com/c6MWRQ9.jpg\"]\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=f\"\"\"{user.name}\"\"\", colour=discord.Colour(0xba4b5b))\n embed.add_field(name=' Random', value=f''' ~~pepe~~''', inline=False)\n embed.set_image(url=image)\n\n\n await ctx.send(embed=embed)\n\n\n\n@commands.cooldown(1,120 , commands.BucketType.user)\n@commands.command(aliases= [\"s\"])\nasync def spawn(ctx, user: discord.Member = None): \n user = user or ctx.message.author\n \n\n\n spawn = \"** A wild .{1}!**\"\n\n \n choices = [\"http://www.pokestadium.com/sprites/xy/shiny/xerneas.gif\",\n \"http://www.pokestadium.com/sprites/xy/xerneas-active.gif\",\n \"http://www.pokestadium.com/sprites/xy/zekrom.gif\",\n \"http://www.pokestadium.com/sprites/xy/charizard.gif\",\n \"http://www.pokestadium.com/sprites/xy/shiny/charizard.gif\",\n \"http://www.pokestadium.com/sprites/xy/yveltal.gif\",\n \"http://www.pokestadium.com/sprites/xy/shiny/yveltal.gif\",\n \"http://www.pokestadium.com/sprites/xy/raikou.gif\",\n \"http://www.pokestadium.com/sprites/xy/shiny/raikou.gif\",\n \"https://cdn.discordapp.com/attachments/386324037552308224/503050326627319809/PokecordSpawn.jpg\",\n \"https://cdn.discordapp.com/attachments/386324037552308224/503050526603214848/PokecordSpawn.jpg\",\n \"https://cdn.discordapp.com/attachments/386324037552308224/503050157286227968/PokecordSpawn.jpg\",\n \"https://cdn.discordapp.com/attachments/482056981931098112/502861665180581908/PokecordSpawn.jpg\",\n \"https://img.nijimen.net/uploads/topic/wide_image/18879/78ea52a0-5e3c-48ee-bbe4-8ff6fe38764b.jpg\"\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRE1NX0EsJ0SUcP1LEdglNTN12UIatAoXfA1rxuz1fkL8Q8vWL9zQ\",\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTOENKjnLEl2H8OdMbOaVqJT0QWr0toBNsWfKa3wQWh_mj827UsLg\",\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQo8_G9cOLmqWNGNFh1BxSx_bkpNOxIW7sv2bqlClQgI_u9TiVx\"]\n \n image = random.choice(choices)\n\n embed = discord.Embed(description=f\"\"\"{user.name}\"\"\", colour=discord.Colour(0xba4b5b))\n embed.add_field(name=' A wild pokémon has appeared!', value=f''' ~~Guess the pokemon~~''', inline=False)\n embed.set_image(url=image)\n\n\n\n await ctx.send(embed=embed)\n\n\n@commands.command()\nasync def cat(ctx):\n \"\"\"Get a random cat image!\n\n **Usage:** `g_dog`\n\n **Permission:** User\"\"\"\n isVideo = True\n while isVideo:\n r = requests.get('https://random.dog/woof.json')\n js = r.json()\n if js['url'].endswith('.mp4'):\n pass\n else:\n isVideo = False\n colours = [0x1abc9c, 0x11806a, 0x2ecc71, 0x1f8b4c, 0x3498db, 0x206694, 0x9b59b6, 0x71368a, 0xe91e63, 0xad1457, 0xf1c40f, 0xc27c0e, 0xa84300, 0xe74c3c, 0x992d22, 0x95a5a6, 0x607d8b, 0x979c9f, 0x546e7a]\n col = int(random.random() * len(colours))\n content = [\":dog: Don't be sad! This doggy wants to play with you!\", \"You seem lonely, {0.mention}. Here, have a dog. They're not as nice as cats, but enjoy!\".format(ctx.message.author), \"Weuf, woof, woooooooooof. Woof you.\", \"Pupper!\", \"Meow... wait wrong animal.\"]\n con = int(random.random() * len(content))\n em = discord.Embed(color=colours[col])\n em.set_image(url=js['url'])\n await ctx.send(content=content[con], embed=em)\n\n@commands.command()\nasync def neko(ctx):\n ''''sends cute dog pics'''\n r = requests.get(\"https://nekos.life/api/neko\").json()\n\n colours = [0x1abc9c, 0x11806a, 0x2ecc71, 0x1f8b4c, 0x3498db, 0x206694, 0x9b59b6, 0x71368a, 0xe91e63, 0xad1457, 0xf1c40f, 0xc27c0e, 0xa84300, 0xe74c3c, 0x992d22, 0x95a5a6, 0x607d8b, 0x979c9f, 0x546e7a]\n col = int(random.random() * len(colours))\n content = [\":neko: Don't be sad! This neko wants to play with you!\", \"You seem lonely, {0.mention}. Here, have a neko. They're not as nice , but enjoy!\".format(ctx.message.author), \"Weuf, woof, woooooooooof. Woof you.\", \"Pupper!\", \"Meow... wait its neko.\"]\n con = int(random.random() * len(content))\n embed=discord.Embed()\n embed.set_image(url=r[\"neko\"])\n await ctx.send(content=content[con],embed=embed)\n\n\n@commands.command(pass_context=True)\nasync def rps(ctx, choice):\n \"\"\"\"\"\"\n choices = [\"rock\", \"paper\", \"scissors\"]\n await ctx.send(\"You chose {} | CPU chose {}\".format(choice, random.choice(choices)))\n\ndef setup(bot):\n bot.add_cog(BAfun(bot))","sub_path":"fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":25221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"10581818","text":"\"\"\"\nWCH5Dataset update to apply normalization on the fly to the test dataset\n\"\"\"\n\n# PyTorch imports\nfrom torch.utils.data import Dataset\nimport h5py\n\nimport numpy as np\n\n# WatChMaL imports\nimport preprocessing.normalize_funcs as norm_funcs\n\nclass WCH5DatasetTest(Dataset):\n \"\"\"\n Dataset storing image-like data from Water Cherenkov detector\n memory-maps the detector data from the hdf5 file\n The detector data must be uncompresses and unchunked\n labels are loaded into memory outright\n No other data is currently loaded\n \"\"\"\n\n def __init__(self, test_dset_path, norm_params_path, chrg_norm=\"identity\", time_norm=\"identity\", shuffle=1, test_subset=None, seed=42):\n \n f = h5py.File(test_dset_path, \"r\")\n \n hdf5_event_data = f[\"event_data\"]\n hdf5_labels = f[\"labels\"]\n hdf5_energies = f[\"energies\"]\n hdf5_positions = f[\"positions\"]\n hdf5_angles = f[\"angles\"]\n \n assert hdf5_event_data.shape[0] == hdf5_labels.shape[0]\n \n assert hasattr(norm_funcs, chrg_norm) and hasattr(norm_funcs, time_norm), \"Functions \"+ chrg_norm + \" and/or \" + time_norm + \" are not implemented in normalize_funcs.py, aborting.\"\n \n # Create a memory map for event_data - loads event data into memory only on __getitem__()\n self.event_data = np.memmap(test_dset_path, mode=\"r\", shape=hdf5_event_data.shape,\n offset=hdf5_event_data.id.get_offset(), dtype=hdf5_event_data.dtype)\n \n # Load the contents which could fit easily into memory\n self.labels = np.array(hdf5_labels)\n self.energies = np.array(hdf5_energies)\n self.positions = np.array(hdf5_positions)\n self.angles = np.array(hdf5_angles)\n \n # Load the normalization parameters used by normalize_hdf5 methods\n norm_params = np.load(norm_params_path, allow_pickle=True)\n self.chrg_acc = norm_params[\"c_acc\"]\n self.time_acc = norm_params[\"t_acc\"]\n \n self.chrg_func = getattr(norm_funcs, chrg_norm)\n self.time_func = getattr(norm_funcs, time_norm)\n \n # Set the total size of the trainval dataset to use\n self.reduced_size = test_subset\n \n self.test_indices = np.arange(len(self))\n if self.reduced_size is not None:\n assert len(self.test_indices)>=self.reduced_size\n self.test_indices = np.random.choice(self.labels.shape[0], self.reduced_size)\n \n # Seed the pseudo random number generator\n if seed is not None:\n np.random.seed(seed)\n \n # Shuffle the indices\n if shuffle:\n np.random.shuffle(self.test_indices)\n \n def __getitem__(self, index):\n return np.array(self.event_data[index,:]), np.concatenate([np.squeeze(self.chrg_func(np.expand_dims(self.event_data[index, :, :, :19], axis=0), self.chrg_acc, apply=True)), np.squeeze(self.time_func(np.expand_dims(self.event_data[index, :, :, 19:], axis=0), self.time_acc, apply=True))], axis=2), self.labels[index], self.energies[index], self.angles[index], index, self.positions[index]\n \n def __len__(self):\n if self.reduced_size is None:\n return self.labels.shape[0]\n else:\n return self.reduced_size","sub_path":"io_utils/data_handling_test.py","file_name":"data_handling_test.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"417744585","text":"from pymongo import MongoClient\nfrom modules.appleId_check import AppleId\nfrom config import Config\n\n\nclass ProfileExistence:\n\n def __init__(self):\n\n self.client = MongoClient(Config.MONGO_URI)\n db = self.client.Apple_db\n self.collection = db.account\n self.dict = {}\n\n def db_check(self, id):\n\n # if database consists the profile\n if self.collection.find_one({'profile_id': id}):\n\n for doc in self.collection.find({'profile_id': id}):\n # print(doc)\n self.dict['profileExists'] = doc['profileExists']\n self.dict['profile_id'] = doc['profile_id']\n\n return self.dict\n\n # when profile isn't in database\n else:\n obj = AppleId()\n data_from_apple = obj.id_check(id)\n # print(data_from_fb)\n self.db_loader(data_from_apple)\n return data_from_apple\n\n def db_loader(self, data):\n\n # print(data)\n if data['profileExists'] is False:\n pass\n else:\n\n d = {\"profileExists\": data['profileExists'],\n \"profile_id\": data['profile_id']\n }\n self.collection.insert_one(d)\n\n # close db connection\n self.client.close()\n\n\nif __name__ == '__main__':\n obj = ProfileExistence()\n print(obj.db_check(\"jaqsoms43@gmail.com\"))\n\n","sub_path":"apple-api/modules/appleId_check_db.py","file_name":"appleId_check_db.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"100845173","text":"#!/usr/bin/python\n#\n# Derived from download_and_preprocess_flowers.sh\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ==============================================================================\n\"\"\"\n Script to download and preprocess the flowers data set. This data set\n provides a demonstration for how to perform fine-tuning (i.e. tranfer\n learning) from one model to a new data set.\n\n This script provides a demonstration for how to prepare an arbitrary\n data set for training an Inception v3 model.\n\n We demonstrate this with the flowers data set which consists of images\n of labeled flower images from 5 classes:\n\n daisy, dandelion, roses, sunflowers, tulips\n\n The final output of this script are sharded TFRecord files containing\n serialized Example protocol buffers. See build_image_data.py for\n details of how the Example protocol buffer contains image data.\n\n usage:\n ./download_and_preprocess_flowers.py [data-dir]\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom subprocess import call\nimport os\nimport os.path\nimport shutil\nimport sys\nimport random\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('Usage: download_and_preprocess_flowers.sh [data dir]\\n')\n sys.exit(-1)\ndata_dir = os.path.realpath(sys.argv[1])\n\n# Create the output and temporary directories.\nwork_dir = __file__ + \".runfiles/inception/inception\"\nscratch_dir = data_dir + '/raw-data/'\ntry:\n os.makedirs(scratch_dir);\nexcept OSError as e:\n print('Mkdir error: \"%s\" %s' % (scratch_dir,os.strerror(e.errno)))\n\n# Download the flowers data.\ndata_url = 'http://download.tensorflow.org/example_images/flower_photos.tgz'\nbase_dir = os.path.dirname(os.path.realpath(__file__))\ncurrent_dir = os.getcwd();\ntry:\n os.chdir(data_dir)\nexcept OSError as e:\n print(os.strerror(e.errno))\n sys.exit(-1)\n\ntarball = \"flower_photos.tgz\"\nif not os.path.isfile(tarball):\n print('Downloading flower data set.\\n')\n call(['curl', '-o', tarball, data_url])\nelse:\n print('Skipping download of flower data.')\n\n# Note the locations of the train and validation data.\ntrain_directory = scratch_dir + 'train/'\nvalidation_directory = scratch_dir + 'validation/'\n\n# process\nprint(\"Organizing the validation data into sub-directories.\")\nlabels_file = scratch_dir + 'labels.txt'\n\n# Expands the data into the flower_photos/ directory and rename it as the\n# train directory.\ncall(['tar', 'xf', 'flower_photos.tgz'])\n\nshutil.rmtree(train_directory, True)\nshutil.rmtree(validation_directory, True)\n\nos.rename('flower_photos', train_directory)\n\n# Generate a list of 5 labels: daisy, dandelion, roses, sunflowers, tulips\nlabels_file = scratch_dir + 'labels.txt'\n\nlabels = [d for d in os.listdir(train_directory) if os.path.isdir(os.path.join(train_directory, d))]\nlabels.sort()\nwith open(labels_file, 'w') as f:\n [f.write(label+'\\n') for label in labels]\n\n\n# Generate the validation data set.\nos.makedirs(validation_directory)\nfor label in labels:\n validation_dir_for_label = validation_directory + label\n train_dir_for_label = train_directory + label\n os.makedirs(validation_dir_for_label)\n\n # Move the first randomly selected 100 images to the validation set.\n images = [f for f in os.listdir(train_dir_for_label)]\n random.shuffle(images)\n validation_images = images[0:99]\n\n for image in validation_images:\n os.rename(train_dir_for_label + '/' + image, validation_dir_for_label + '/' + image)\n\n\n# Build the TFRecords version of the image data.\nos.chdir(current_dir)\nbuild_script = work_dir + \"/build_image_data\"\noutput_directory = data_dir\nos.system(build_script +\n ' --train_directory=\"%s\"'\n ' --validation_directory=\"%s\"'\n ' --output_directory=\"%s\"'\n ' --labels_file=\"%s\"' %\n (train_directory, validation_directory, output_directory, labels_file));\n\n","sub_path":"inception/inception/data/download_and_preprocess_flowers.py","file_name":"download_and_preprocess_flowers.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"207873333","text":"def tic_tac_toe_check(board):\n \n col = []\n cols = []\n game_board = []\n topL_to_bottomR = []\n topR_to_bottomL = []\n winner = []\n with_empty = {'x','o',''}\n without_empty = {'x','o'}\n \n #check that what is being passed in is not just a string or different data type\n #Will catch things such as:\n #test_board = 'x', 'x', '', 'x', 'x', 'x', 'x', 'x', 'x' (tuple)\n if isinstance(board, list) is False:\n #change to type error\n raise TypeError('Element is of type \\'' + str(type(board)) + '\\'. A list must be passed in.')\n #list is empty -> []\n if not board:\n return None\n \n #check that there are 9 spots\n if len(board) != 9:\n raise ValueError('Board does not have 9 spots. It has ' + str(len(board)) + ' spots.')\n\n #check that each element is a string. \n #Will catch things such as:\n #test_board = [['', '', '', '', '', '', '', '', '']] (list of lists)\n for s in board:\n if s:\n if not isinstance(s, str):\n raise ValueError('Element is not a string: ' + str(s))\n if not s:\n if not isinstance(s, str):\n raise ValueError('Element is not a string: ' + str(s))\n\n #All game pieces are the same. Either all 'x', 'o', or '' (empty string)\n if len(set(board)) == 1:\n if 'x' in board:\n raise ValueError('Player \\'x\\' cannot win in more than one way.')\n elif 'o' in board:\n raise ValueError('Player \\'o\\' cannot win in more than one way.')\n elif '' in board:\n return None\n\n #check if any elements are uppercase\n for s in board:\n if s.isupper():\n raise ValueError('Uppercase is not allowed.')\n \n #check if a string in the list is more than one letter, must only be 'x' not 'xx'\n for s in board:\n if s != '':\n if len(s) != 1:\n raise ValueError('Element must be of length 1')\n \n #checking for invalid characters\n if '' in board: #empty in board\n if (set(board) != set(with_empty)):\n if 'x' in board: #will allow only 'x' and ''\n if((set(board) != set({'x',''}))):\n raise ValueError('Elements must be \\'x\\', \\'o\\', or \\'\\'')\n elif 'o' in board: #will allow only 'o' and ''\n if (set(board) != set({'o',''})):\n raise ValueError('Elements must be \\'x\\', \\'o\\', or \\'\\'')\n else:\n if set({''}) != set(board):\n raise ValueError('Elements must be \\'x\\', \\'o\\', or \\'\\'')\n elif '' not in board: #no empty in board\n if (set(board) != set(without_empty)):\n #checks for board of either all 'x' or all 'o'\n if(set(board) != set({'x'})) or (set(board) != set({'o'})):\n raise ValueError('Elements must be \\'x\\', \\'o\\', or \\'\\'')\n \n #passed in as: board -> ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n #append as a list of lists -> [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] \n game_board.append(board[0:3]) #first row ie: ['1', '2', '3']\n game_board.append(board[3:6]) #second row ie: ['4', '5', '6']\n game_board.append(board[6:9]) #third row ie: ['7', '8', '9']\n \n i = 0\n while i < 3:\n \n #get diagonal (top left -> bottom right)\n topL_to_bottomR.append(game_board[i][i])\n \n j = 0 \n while j < 3:\n #get columns\n col.append(game_board[j][i])\n j += 1\n i += 1\n\n #diagonal (top right -> bottom left)\n i = 0\n j = 2\n while i < 3:\n topR_to_bottomL.append(game_board[i][j])\n i += 1\n j -= 1\n \n #append as a list of lists -> [['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9']]\n cols.append(col[0:3]) #first col ie: ['1', '4', '7']\n cols.append(col[3:6]) #second col ie: ['2', '5', '8']\n cols.append(col[6:9]) #third col ie: ['3', '6', '9']\n \n #Check for winners\n #If string isn't empty, if set length is 1 add winner for row\n for row in game_board:\n if '' not in row:\n if len(set(row)) == 1:\n winner.append(row[0])\n \n #If string isn't empty, if set length is 1 add winner for col \n for col in cols:\n if '' not in col:\n if len(set(col)) == 1:\n winner.append(col[0])\n \n #If string isn't empty, if set length is 1 add winner for Top L to Bottom R Diagonal\n if len(set(topL_to_bottomR)) == 1:\n if '' not in topL_to_bottomR:\n winner.append(topL_to_bottomR[0])\n \n #If string isn't empty, if set length is 1 add winner for Top R to Bottom L Diagonal\n if len(set(topR_to_bottomL)) == 1:\n if '' not in topR_to_bottomL:\n winner.append(topR_to_bottomL[0])\n \n winner_set = set(winner)\n set_length = len(winner_set)\n\n if len(winner) == 1 and '' not in winner_set:\n return next(iter(winner_set)) #return tuple(winner_set)[0] #next(iter(winner_set))\n else:\n if set_length > 1:\n raise ValueError('Two players are not allowed to win.')\n elif len(winner) > 1:\n raise ValueError('Player \\'' + next(iter(winner_set)) + '\\' cannot win in more than one way.')\n else:\n return None","sub_path":"640/impl-2.py","file_name":"impl-2.py","file_ext":"py","file_size_in_byte":5356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"319866929","text":"# -*- coding: utf-8 -*-\n# @Time : 2021-04-23 10:58\n# @Author : zxl\n# @FileName: Offer015.py\n\n\nclass Solution:\n def hammingWeight(self, n: int) -> int:\n\n count = 0\n while n:\n count += n%2\n n//=2\n return count\n\n\n","sub_path":"Offer015.py","file_name":"Offer015.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"335484083","text":"import itertools\nperms = itertools.permutations([1, 2, 3], 2)\nnext(perms) \n# (1, 2) , (1, 3), (2, 1) ...\n# 找排列组合的自带method, 太tm强了,这都有!!\n\n\nlist(itertools.product('ABC', '123'))\n#[('A', '1'), ('A', '2'), ('A', '3'), \n#('B', '1'), ('B', '2'), ('B', '3'), \n#('C', '1'), ('C', '2'), ('C', '3')]\n# itertools.product() function returns an iterator containing the Cartesian product of two sequences\n\nlist(itertools.combinations('ABC', 2))\n# [('A', 'B'), ('A', 'C'), ('B', 'C')]\n# itertools.combinations() function returns an iterator containing all the possible combinations of the given sequence of the given length","sub_path":"PythonWorkSpace/LearnPython/Advanced Iterators/itertools_showcase.py","file_name":"itertools_showcase.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"323690747","text":"\"\"\"Bodega Custmize CLI class.\"\"\"\nfrom enum import Enum\nfrom bodega_utils import Utils\n\n\nclass Types(Enum):\n \"\"\"Values TYPE can take in CUSTOMIZE command.\"\"\"\n\n DEV_MACHINE = 'dev_machine'\n\n\nclass PositionalArguments(Enum):\n \"\"\"POSITIONAL_ARGUMENTs for CUSTOMIZE command.\"\"\"\n\n HOST_INFO = 'host_info'\n\n\nclass NamedArguments(Enum):\n \"\"\"NAMED_ARGUMENTs for CUSTOMIZE command.\"\"\"\n\n SD_DEV_MOUNTRC_FILE = 'sd_dev_mountrc_file'\n PEM_FILE = \"pem_file\"\n GIT_REPO_FILE = \"git_repo_file\"\n\n\nclass BodegaCustomize(object):\n \"\"\"Sub-parser for the CUSTOMIZE command.\"\"\"\n\n def __init__(self, sub_parser, bodega_commands):\n \"\"\"Initialize BodegaCustomize class.\"\"\"\n self.commands = bodega_commands\n\n self.parser = sub_parser\n self.subparsers = self.parser.add_subparsers()\n\n self._init_subparsers()\n\n def _init_subparsers(self):\n self._init_dev_machine()\n\n def _init_dev_machine(self):\n description = \"\"\"Configure a existing dev machine\"\"\"\n sub_parser = self.subparsers.add_parser(Types.DEV_MACHINE.value,\n description=description,\n epilog=Utils.epilog)\n sub_parser.add_argument(PositionalArguments.HOST_INFO.value,\n type=Utils.parse_userhost,\n help='Host information @, ' +\n 'username is optional')\n sub_parser.add_argument(\n Utils.get_short_arg_from_name(\n NamedArguments.SD_DEV_MOUNTRC_FILE.value),\n Utils.get_long_arg_from_name(\n NamedArguments.SD_DEV_MOUNTRC_FILE.value),\n default=Utils.get_default_sd_dev_file(),\n help='sd_dev_mountrc file to use [default:%(default)s]',\n metavar='FILE')\n sub_parser.add_argument(\n Utils.get_short_arg_from_name(\n NamedArguments.PEM_FILE.value),\n Utils.get_long_arg_from_name(\n NamedArguments.PEM_FILE.value),\n default=Utils.get_default_ubuntu_pem_key(),\n help='pem file to use [default:%(default)s]',\n metavar='FILE')\n sub_parser.add_argument(\n Utils.get_short_arg_from_name(\n NamedArguments.GIT_REPO_FILE.value),\n Utils.get_long_arg_from_name(\n NamedArguments.GIT_REPO_FILE.value),\n default=None,\n help='git repo file to use, \" + \\\n \"refer to conf/sd_dev_git_repos.defaults',\n metavar='YML FILE')\n\n sub_parser.set_defaults(func=self._exec_configure_dev_machine)\n\n def _exec_configure_dev_machine(self, args_dict):\n username, host = args_dict[PositionalArguments.HOST_INFO.value]\n sync_file = args_dict[NamedArguments.SD_DEV_MOUNTRC_FILE.value]\n pem_file = args_dict[NamedArguments.PEM_FILE.value]\n git_repo_file = args_dict[NamedArguments.GIT_REPO_FILE.value]\n self.commands.configure_dev_machine(username, host,\n sync_file=sync_file,\n git_repo_file=git_repo_file,\n pem_file=pem_file)\n","sub_path":"lab/bodega/cli/bodega_customize.py","file_name":"bodega_customize.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"193815873","text":"#!/usr/bin/env python\n\"\"\"\n================================================================================\n:mod:`config` -- Configuration parser\n================================================================================\n\n.. module:: config\n :synopsis: Read configuration file\n\n.. inheritance-diagram:: pymontecarlo.util.config\n\nConfiguration parser to read INI type files.\nThis parser differs slightly from those available in the :mod:`ConfigParser`\nmodule as the sections, options and values can be accessed using attributes\ninstead of getters and setters.\nWhile the access of the data is different, this class uses the\n:class:`SafeConfigParser` of the :mod:`ConfigParser` module to read and\nwrite configuration file.\n\n.. warning::\n\n This parser does *not* support section or option starting with a number.\n\nLet's take the configuration file::\n\n [section1]\n option1=value1\n option2=value2\n\n [section2]\n option3 = value3\n\nTo load the configuration file, use the :meth:`read` method::\n\n >>> config = ConfigParser()\n >>> with open(filepath, 'r') as fp:\n ... config.read(fp)\n\nTo get the value of ``option1`` in ``section1``::\n\n >>> config.section1.option1\n 'value1'\n\nor of ``option3`` in ``section2``::\n\n >>> config.section2.option3\n 'value3'\n\nTo check if a section is present, use the ``in`` statement::\n\n >>> 'section3' in config\n False\n >>> 'option2' in config.section1\n True\n\nTo iterate over all sections and options::\n\n >>> for section, option, value in config:\n ... print section, option, value\n 'section1' 'option1' 'value1'\n 'section1' 'option2' 'value2'\n 'section2' 'option3' 'value3'\n\nNote that the order may changed.\n\nTo add a section or option::\n\n >>> config.add_section('section3')\n >>> 'section3' in config\n True\n >>> config.section3.option4 = 'value4'\n\nThe following syntax can be shorten as :meth:`add_section` method returns the\nadded section::\n\n >>> config.add_section('section3').option4 = 'value4'\n\nIf the added section already exists, no section is added and the current one\nis returned::\n\n >>> config.add_section('section1').option1\n 'value1'\n\nFinally, the configuration can be saved back to a file::\n\n >>> with open(filepath, 'w') as fp:\n ... config.write(fp)\n\n\"\"\"\n\n# Script information for the file.\n__author__ = \"Philippe T. Pinard\"\n__email__ = \"philippe.pinard@gmail.com\"\n__version__ = \"0.1\"\n__copyright__ = \"Copyright (c) 2011 Philippe T. Pinard\"\n__license__ = \"GPL v3\"\n\n# Standard library modules.\nfrom configparser import ConfigParser as _ConfigParser\n\n# Third party modules.\n\n# Local modules.\n\n# Globals and constants variables.\n\nclass _Section(object):\n def __init__(self, options={}):\n self.__dict__.update(options)\n\n def __iter__(self):\n for option_name, value in self.__dict__.items():\n yield option_name, value\n\n def __contains__(self, option_name):\n return option_name in self.__dict__\n\nclass ConfigParser(object):\n \"\"\"\n Configuration parser.\n \"\"\"\n\n def __contains__(self, section_name):\n return section_name in self.__dict__\n\n def __iter__(self):\n for section_name, section in self.__dict__.items():\n for option_name, value in section:\n yield section_name, option_name, value\n\n def add_section(self, section_name):\n \"\"\"\n Adds a new section if the specified section name doesn't exist.\n Does nothing if the section already exists.\n\n :return: section\n \"\"\"\n if section_name not in self.__dict__:\n self.__dict__[section_name] = _Section()\n return self.__dict__[section_name]\n\n def read(self, fileobj, ignore_errors=False):\n \"\"\"\n Reads the configuration from the file object.\n\n If ``ignore_errors`` is ``True`` and a section or option starts with\n a number, a :exc:`IOError` exception is raised.\n If not, these sections or options are skipped.\n\n :arg fileobj: file object\n :arg ignore_errors: whether to raise exception or skip invalid\n section(s) and option(s)\n \"\"\"\n parser = _ConfigParser()\n parser.read_file(fileobj)\n\n for section in parser.sections():\n if section[0].isdigit():\n if ignore_errors:\n continue\n raise IOError(\"Section name (%s) cannot start with a digit\" % section)\n\n options = {}\n\n for option in parser.options(section):\n if option[0].isdigit():\n if ignore_errors:\n continue\n raise IOError(\"Option name (%s) cannot start with a digit\" % option)\n\n options[option] = parser.get(section, option)\n\n self.__dict__[section] = _Section(options)\n\n def write(self, fileobj):\n \"\"\"\n Writes the configuration inside the file object.\n\n :arg fileobj: file object\n \"\"\"\n parser = _ConfigParser()\n\n # Add sections\n for section_name in self.__dict__:\n parser.add_section(section_name)\n\n # Add options\n for section_name, option_name, value in self:\n parser.set(section_name, option_name, str(value))\n\n parser.write(fileobj)\n","sub_path":"pymontecarlo/util/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"429806656","text":"# 2675번: 문자열 반복\n# https://www.acmicpc.net/problem/2675\n# Version: Python 3.9.7\n\n\nfrom sys import stdin\n\nread = stdin.readline\n\nif __name__ == \"__main__\":\n for _ in range(int(read())):\n count, string = read().rstrip().split()\n for char in string:\n print(char * int(count), end=\"\")\n print()\n\n","sub_path":"boj/bronze2/2675.py","file_name":"2675.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"651403410","text":"class Graph:\n def __init__(self, vertices=[], edges=[]):\n self._vertices = vertices\n self._edges = edges\n\n def add_node(self, *vertices):\n for vertex in vertices:\n self._vertices.append(vertex)\n\n def create_adj(self, *edges):\n for edge in edges:\n self._edges.append(edge)\n\n def vertices(self): return self._vertices\n def edges(self): return self._edges\n\n def __str__(self):\n traversal = \"\"\n for i in self._edges:\n vertex_from = self._vertices[i[0]]\n vertex_to = self._vertices[i[1]]\n traversal += str(vertex_from) + \" <-> \" + str(vertex_to) + \"\\n\"\n return traversal\n\n\ndef read_int(prompt):\n return int(input(prompt))\n\n\nif __name__ == '__main__':\n g = Graph()\n\n print(\"1. Add node to graph\")\n print(\"2. Create adjacency\")\n print(\"3. Print adjacencies\")\n\n while True:\n print(\"Vertices:\", g.vertices())\n print(\"Edges\", g.edges())\n inp = read_int(\"Your choice: \")\n if inp == 1:\n g.add_node(input(\" Enter node: \"))\n elif inp == 2:\n g.create_adj([read_int(\" Enter edge from: \"),\n read_int(\" Enter edge to: \")])\n else:\n print(g)\n","sub_path":"MCA/Data Structures/Graph_adj.py","file_name":"Graph_adj.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"133511127","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.core.validators\nimport uuidfield.fields\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='ManagrUser',\n fields=[\n ('password', models.CharField(max_length=128, verbose_name='password')),\n ('last_login', models.DateTimeField(verbose_name='last login', default=django.utils.timezone.now)),\n ('id', uuidfield.fields.UUIDField(editable=False, unique=True, primary_key=True, blank=True, serialize=False, max_length=32)),\n ('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),\n ('phone_number', models.CharField(unique=True, verbose_name='mobile phone number', default=None, null=True, validators=[django.core.validators.RegexValidator(regex='^\\\\+?1?\\\\d{9,15}$', message=\"Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.\")], blank=True, max_length=20)),\n ('is_active', models.BooleanField(default=True)),\n ('is_admin', models.BooleanField(default=False)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"account/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"265298686","text":"#!/usr/bin/python3\nimport numpy as np\nimport networkx as nx\nimport itertools\nimport scipy.stats as stats\nimport essentials as es\nimport random\nimport time\n#Scripted by David Vargas\n#---------------------------------------------\n#Convention if directed networks are introduced,\n#Aij=1 if there is an edge from j to i. This\n#means one would sum over row i to get the total\n#number of incoming edges to node i.\n#Here I am summing over rows.\n#Unfinished function - quantum assortativity\n#Next implement hierarchical clustering algorithm\n#described on page 388 of Newman's book on networks\n#Next implement fractal dimension calculation proposed\n#by Simona.\n\ndef strengths(mutualinformation):\n #Return the strength of all nodes in the network in order.\n return np.sum(mutualinformation, axis = 1)\n\ndef density(matrix):\n #Calculates density, also termed connectance in some\n #literature. Defined on page 134 of Mark Newman's book\n #on networks.\n l = len(matrix)\n lsq = l*(l-1)\n return np.sum(matrix)/lsq \n\n# def clustering(matrix):\n# #Calculates the clustering coefficient\n# #as it is defined in equation 7.39 of\n# #Mark Newman's book on networks. Page 199.\n# matrixcube = np.linalg.matrix_power(matrix, 3)\n# matrixsq = np.linalg.matrix_power(matrix, 2)\n# #Zero out diagonal entries. So we do not count edges as\n# #connected triples.\n# for i in range(len(matrixsq)):\n# matrixsq[i][i] = 0\n# denominator = np.sum(matrixsq)\n# numerator = np.trace(matrixcube)\n# #if there are no closed paths of length\n# #three the clustering is automatically\n# #set to zero.\n# if numerator == 0.:\n# return 0.\n# else:\n# return numerator/denominator\n\ndef clustering(matrix):\n #Calculates the clustering coefficient\n #as it is defined in equation 7.39 of\n #Mark Newman's book on networks. Page 199.\n matrixcube = np.linalg.matrix_power(matrix, 3)\n numerator = np.trace(matrixcube)\n #if there are no closed paths of length\n #three the clustering is automatically\n #set to zero.\n if numerator == 0.:\n return 0.\n else:\n matrixsq = np.linalg.matrix_power(matrix, 2)\n denominator = np.sum(matrixsq) - np.trace(matrixsq)\n return numerator/denominator\n\ndef localclustering(matrix):\n l = len(matrix)\n localclustering = []\n matrixcube = np.linalg.matrix_power(matrix, 3)\n for i in range(l):\n matrix2 = np.outer(matrix[i,:], matrix[i,:])\n numerator = matrixcube[i][i]\n denominator = (np.sum(matrix2)-np.trace(matrix2))\n if denominator != 0:\n localclustering.append(numerator/denominator)\n else:\n localclustering.append(0)\n # squaretmp = 0\n # for i in range(l):\n # for j in range(l):\n # for k in range(j):\n # squaretmp += matrix[i][j]*matrix[i][k]\n # if squaretmp != 0:\n # localclustering.append(0.5*matrixcube[i][i]/squaretmp)\n # else:\n # localclustering.append(0)\n # squaretmp = 0\n return np.array(localclustering)\n\ndef rhotype(rho):\n localtmp = 0\n localtmp2 = 0\n d = len(rho)\n basisstate = np.zeros(d)\n brastate = np.zeros(d)\n #By construction I do not have to conjugate the elements to get the bra.\n #This is because basis state is a vector with a single one in a list of zeros.\n for i in range(d):\n basisstate[i] = 1\n brastate = basisstate\n #Map basis state to basis state.\n basisstate = np.dot(rho, basisstate)\n# print 'basis',basisstate\n# print 'bra',brastate,'basis',basisstate\n# print 'rho',rho\n expectation=np.dot(brastate, basisstate)\n basisstate[i] = 0\n# print tuple([expectation,i])\n if expectation >= localtmp:\n localtmp = expectation\n localtmp2 = i\n rhotype = localtmp2\n return int(rhotype)\n\ndef rhotypes(rhos):\n L = len(rhos)\n rhoTypes = np.zeros(L, dtype = int)\n for i in range(L):\n rhoTypes[i] = rhotype(rhos[i])\n return rhoTypes\n\ndef quantumassortativity(rhos,mutualinformation,typefunction):\n L = len(rhos)\n sites = np.array(range(L))\n rhoTypes = typefunction(rhos)\n types = np.unique(rhoTypes)\n longtype = {}\n for atype in types:\n longtype[atype] = atype*np.ones(L, dtype = int)\n ed = len(types)\n eab = np.zeros((ed,ed))\n sitesbytype = {}\n sitesbytype2 = []\n for atype in types:\n abool = np.equal(rhoTypes,longtype[atype])\n sitesbytype[atype] = list(sites[abool])\n for atype in types:\n for btype in types:\n for i in sitesbytype[atype]:\n for j in sitesbytype[btype]:\n eab[atype][btype] += mutualinformation[i][j]\n eab = eab/np.sum(eab)\n trace = np.trace(eab)\n prodsum = np.sum(np.dot(eab,eab))\n if 1. - prodsum != 0:\n assortativity = (trace-prodsum)/(1.-prodsum)\n return assortativity\n else:\n return nan\n \n# def disparity(matrix):\n# #Disparity defined on page 199 of doi:10.1016/j.physrep.2005.10.009 \n# #Equation 2.39, Here I take the average of this quantity over the\n# #entire network\n# l = len(matrix)\n# numerator = np.sum(matrix**2, axis = 1)/l\n# denominator = np.sum(matrix, axis = 1)\n# #Logical Check\n# logos = denominator > 0\n# numerator = numerator[logos]\n# denominator = denominator[logos]\n# denominator = denominator**2\n# #Check for zero denominator.\n\n# if sum(denominator) == 0.:\n# return np.nan\n# else: \n# return sum(numerator/denominator)\n\ndef disparity(matrix):\n #Disparity defined on page 199 of doi:10.1016/j.physrep.2005.10.009 \n #Equation 2.39, Here I take the average of this quantity over the\n #entire network\n l = len(matrix)\n numerator = np.sum(matrix**2, axis = 1)/l\n denominator = np.sum(matrix, axis = 1)**2 + 1.E-16j\n return np.sum(numerator/denominator).real# .real\n # #Check for zero denominator.\n # if sum(denominator) == 0.:\n # return np.nan\n # else: \n # return sum(numerator/denominator)\n\ndef disparitylattice(matrix):\n #Local disparity across the entire lattice.\n numerator = np.sum(matrix**2, axis = 1)\n denominator = np.sum(matrix, axis = 1)**2 + 1.E-16j\n disparity = (numerator/denominator).real\n return disparity\n\ndef strengthdist(mutualinformation, bins = np.linspace(0, 1, 11)):\n #Compute the weighted analog of a degree distribution.\n strens = strengths(mutualinformation)\n # maxinfo=np.max(strens)\n # mininfo=np.min(strens)\n return np.histogram(strens,bins)\n\ndef pearson(mutualinformation):\n L = len(mutualinformation)\n pearsonR = np.zeros((L,L))\n pvalues = np.zeros((L,L))\n for i in range(L):\n for j in range(L):\n if i != j:\n r,p = stats.pearsonr(mutualinformation[i], mutualinformation[j])\n pearsonR[i][j] = r\n pvalues[i][j] = p\n else:\n pearsonR[i][j] = 0.\n pvalues[i][j] = 0.\n return [pearsonR, pvalues]\n\ndef edgeweightdist(mutualinformation, bins):\n L = len(mutualinformation)\n edges = es.flatten(list(mutualinformation))\n return np.histogram(edges,bins)[0]\n\ndef coarsegrainnetwork(mutualinformation, bins):\n #Default behavior of histograms is to have the intervals\n #Closed on the left and open on the right.\n #The bin with the largest values is closed on both ends.\n L = len(mutualinformation)\n coarsematrix = np.zeros((L,L))\n ll = len(bins)\n for i in range(L):\n for j in range(L):\n for k in range(ll-2):\n if bins[k] <= mutualinformation[i][j] < bins[k+1]:\n coarsematrix[i][j] = k\n if bins[ll-2] <= mutualinformation[i][j] <= bins[ll-1]:\n coarsematrix[i][j] = ll-2\n return coarsematrix\n\n#NetworkX additions\n#---------------------------------------------\n\ndef distance(mutualinformation):\n #Initialize array\n length = len(mutualinformation)\n thisdistance = np.zeros((length,length))\n #If an element has value less than (10^-14) in absolute value,\n #then treat it as of value (10^-16), set its distance\n #to 10^16. Otherwise set it mij^(-1).\n #The value (10^-14) must be adjusted in coordination with\n #the cutoff applied to the weighted network of interest.\n #The purpose of setting this value equal to 10^16 is\n #so that the geodesic path length algorithm will ignore\n #any edges less than the cutoff treating.\n for i in range(length):\n for j in range(length):\n if np.abs(mutualinformation[i, j]) <= 1E-14:\n thisdistance[i, j] = np.power(10.,16)\n else:\n thisdistance[i, j] = np.power(mutualinformation[i, j],-1)\n return thisdistance\n\ndef geodesic(distance, i, j):\n #Initialize networkx graph object\n #NetworkX indexing starts at zero.\n #Ends at N-1 where N is the number of nodes.\n latticelength = len(distance)\n G = nx.Graph(distance)\n #Use networkx algorithm to compute the shortest path from\n #the first lattice site to the last lattice site.\n pathlength = nx.shortest_path_length(G, source = i-1, target = j-1, weight = 'weight')\n #The pathlength is tested for an unreasonable value.\n #An unreasonable value for the path length is a function of the cutoff\n #applied to the weighted network under analysis and the value set in\n #the distance function thisdistance[i,j]=np.power(10.,16)\n if pathlength > np.power(10., 15):\n return np.nan\n return pathlength\n\ndef harmoniclength(distance):\n #page 11, equation 2 The Structure and Function of Complex Networks\n #If the geodesic distance between two nodes is a number then \n #append it to alist to include it in the sum.\n l = len(distance)\n# print 'Node count: ', l\n factor = 1./(0.5*l*(l-1))\n# print 'Factor: ', factor\n alist = []\n for i in range(1, len(distance) + 1):\n for j in range(i+1, len(distance) + 1):\n geo = geodesic(distance, i, j)\n if not np.isnan(geo):\n# print '(i,j)',tuple([i,j])\n alist.append(1./geo)\n# print 'alist',alist\n# print 'Harmonic Mean of Distances: ', 1./(factor*sum(alist))\n return 1./(factor*sum(alist))\n\ndef eigenvectorcentralitynx0(mutualinformation):\n #Uses the power method to find eigenvector of \n #a weighted adjacency matrix.\n G = nx.Graph(mutualinformation)\n eigvcent = nx.eigenvector_centrality(G, weight='weight', max_iter=2000)\n return eigvcent\n\ndef eigenvectorcentralitynx(mutualinformation, startingvector):\n #Identical to eigenvectorcentralitynx0, but requires an additional argument startingvector.\n #starting vector provides an initial guess for the eigen vector centrality of all nodes.\n #startingvector must be a python dictionary. key = node, value = eigenvector centrality estimate.\n G = nx.Graph(mutualinformation)\n eigvcent = nx.eigenvector_centrality(G, weight = 'weight', max_iter = 2000, nstart = startingvector)\n return eigvcent\n\n#Here I provide some test cases. These test cases assume the weighted\n#networks being provided are quantum mutual information networks.\ntest=True\ndef main():\n if test==True:\n testrho = np.array([[0.1, 0], [0, 0.9]])\n testrho2 = np.array([[0.7, 0], [0, 0.3]])\n testrho3 = np.array([[0.5, 0.], [0.0, 0.5]])\n testrhos = [testrho, testrho2, testrho3]\n singlet = np.array([[0., 0., 1.], [0., 0., 0.], [1., 0., 0.]])\n ghz = np.array([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]])\n w = np.array([[0, 0.636514, 0.636514],\n [0.636514, 0, 0.636514],\n [0.636514, 0.636514, 0]])\n fourqubits = np.array([[0, 1, 0, 0], [1, 0, 1, 1],\n [0, 1, 0, 1], [0, 1, 1, 0]])\n states = [singlet, ghz, w, fourqubits]\n names = ['singlet', 'ghz', 'w', 'Four Qubits']\n functions = [strengths, density, clustering, localclustering, disparity,\n disparitylattice, distance]#, eigenvectorcentralitynx0]\n measurenames = ['Strengths', 'Density', 'Clustering', \n 'Local Clustering', 'Average Disparity', \n 'Nodal Disparity', 'Distances']#,\n# 'Eigenvector Centrality']\n for i in range(len(states)):\n print(names[i])\n for function in functions:\n print(function, function(states[i]))\n print('Rhos: ', testrho, '\\n', testrho2, '\\n', testrho3, '\\n')\n print('Rho Types: ', rhotypes(testrhos))\n print(quantumassortativity(testrhos, ghz, rhotypes))\n #Counterintuitive result for pearson correlation of ghz state.\n #It is negative. This is because we are arbitarily setting the \n #diagonal of the mutual information matrix to zero. \n print(pearson(ghz))\n \n print(\"Edge Weight Distribution: \", edgeweightdist(ghz, [0, 0.5, 1]))\n print(\"Full Matrix: \", ghz)\n print(\"Coarse Matrix:\", coarsegrainnetwork(ghz, [0, 0.5, 1]))\n \n \n # print(\"Local Clustering: \", localclustering(matrix))\n \n # total = 0\n # total2 = 0\n # for i in range(10000):\n # matrix = np.zeros((26, 26))\n # for i in range(26):\n # for j in range(26):\n # matrix[i][j] = random.random()\n # t0 = time.time()\n # clustering(matrix)\n # t1 = time.time()\n # clustering2(matrix)\n # t2 = time.time()\n # total += (t1-t0)/(t2-t1)\n # total2 += clustering2(matrix) - clustering(matrix)\n # print(total/10000)\n # print(total2/10000)\n #This effect should go away in the thermodynamic limit. \n #I can check this. Next I should check how robust the\n #result is against the size of the numerical noise.\n # def GHZ(L):\n # mutualinformation=np.zeros((L,L))\n # for i in range(L):\n # for j in range(L):\n # if i!=j:\n # mutualinformation[i][j]=0.5#+0.01*(np.random.rand()-0.5)\n # else:\n # mutualinformation[i][j]=0.\n # return mutualinformation\n # for l in [4,10,20,50]:\n # print l,'\\n',pearson(GHZ(l))[0][l/2][l/2+1]\n # a=1.E-14*np.ones((20,20))\n # for i in range(len(a)):\n # a[i][i]=0.\n # print 'disparity', disparity(a)\n # print 'clustering', clustering(GHZ(3))\n # print 0.2*GHZ(3)\n # a=0.01*np.ones(100)*range(100)\n # for i in a:\n # print clustering(i*GHZ(3))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"networkmeasures.py","file_name":"networkmeasures.py","file_ext":"py","file_size_in_byte":14824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"223273380","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('rb15.jpg')\n\n\"\"\"\nAffine transforms\n- scaling\n- rotation\n- translation\n- skewing\n- preserve collinearity and parallelism\n\nNon-affine transforms\n- also known as projective transformation, homography\n- does not preserve parallelism, length, and angle\n- does preserve collinearity and incidence\n\nTranslation Matrix = |1 0 Tx|\n |0 1 Ty|\nTx = shift along x-axis\nTy = shift along y-axis\nuse cv2.warpAffine to implement translations\n\nRotation Matrix:\nM = |cos(theta) -sin(theta)|\n |sin(theta) cos(theta) |\n\ncv2.getRotationMatrix2D(rotation_center_x, rotation_center_y, angle of rotation, scale)\n\"\"\"\n\nheight, width = img.shape[:2]\nquarter_height, quarter_width = height/4, width/4\n\nT = np.float32([[1, 0, -quarter_width], [0, 1, -quarter_height]])\n\nimg_translation = cv2.warpAffine(img, T, (width, height))\ncv2.imshow('Translation', img_translation)\n\nrotation_matrix = cv2.getRotationMatrix2D((width/2, height/2), 90, 1)\nrotated_image = cv2.warpAffine(img, rotation_matrix, (width, height))\n\ncv2.imshow('Rotation', rotated_image)\n\nt_img = cv2.transpose(img)\ncv2.imshow(\"Transpose\", t_img)\n\nh_flipped = cv2.flip(image, 1)\nv_flipped = cv2.flip(image, -1)\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"translations, rotations, and transformations.py","file_name":"translations, rotations, and transformations.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"348595680","text":"# indexing a local csv file test.csv\nINDEX_NAME = 'titanic' # 数据库名字\nTYPE_NAME = 'passenger' # 表名字\nID_FIELD = 'passengerid' # 文档ID\n\nimport csv\nimport sys\n\nresponse = open(sys.argv[1], 'rt', encoding=\"utf-8\") # put this the same directory as test.csv\nfile_object = csv.reader(response)\nheader = file_object.__next__() # header得第一行 file_object去第一行\nheader = [item.lower() for item in header] # 第一行内容小写\n\nbulk_data = [] \n\nfor row in file_object:\n data_dict = {}\n for i in range(len(row)):\n data_dict[header[i]] = row[i]\n op_dict = {\n \"index\": {\n \"_index\": INDEX_NAME, \n \"_type\": TYPE_NAME, \n \"_id\": data_dict[ID_FIELD]\n }\n }\n bulk_data.append(op_dict)\n bulk_data.append(data_dict)\n\n# step1 : create ES client\nfrom elasticsearch import Elasticsearch\nesHost1 = {\"host\" : \"localhost\", \"port\" : 9200}\nes = Elasticsearch(hosts=[esHost1])\n\n# step2 : check\n# if the index already exist, delete it and create it again\nif es.indices.exists(INDEX_NAME):\n print(\"deleting '%s' index...\" % (INDEX_NAME))\n res = es.indices.delete(index = INDEX_NAME)\n print(\" response: '%s'\" % (res))\n\n# step3 : settings\n# since we are running locally, use one shard and no replicas\n# Each index created can have specific settings associated with it.\nrequest_body = {\n \"settings\" : {\n \"index\" : {\n \"number_of_shards\": 1,\n \"number_of_replicas\": 0\n }\n }\n}\n# Default for number_of_shards is 5\n# Default for number_of_replicas is 1 (ie one replica for each primary shard)\n# The index settings can also be defined with JSON:\n'''\n\n$ curl -XPUT 'http://localhost:9200/twitter/' -d '{\n \"settings\" : {\n \"index\" : {\n \"number_of_shards\" : 3,\n \"number_of_replicas\" : 2\n }\n }\n}'\n\n'''\n# or more simplified\n'''\n\n$ curl -XPUT 'http://localhost:9200/twitter/' -d '{\n \"settings\" : {\n \"number_of_shards\" : 3,\n \"number_of_replicas\" : 2\n }\n}'\n\n'''\n# You do not have to explicitly specify index section inside the settings section.\n\n# step4 : create index\nprint(\"creating '%s' index...\" % (INDEX_NAME))\nres = es.indices.create(index = INDEX_NAME, body = request_body)\nprint(\" response: '%s'\" % (res))\n\n# bulk index the data\nprint(\"bulk indexing...\")\nres = es.bulk(index = INDEX_NAME, body = bulk_data, refresh = True)\n\n# sanity check\nres = es.search(index = INDEX_NAME, size=30, body={\"query\": {\"match_all\": {}}})\n# display the result immediately:\n# print(\" response: '%s'\" % (res)) \n\n# To display the results more clearly, we can loop through them:\nprint(\"results:\")\nfor hit in res['hits']['hits']:\n print(\"\\n\") # str\n print(hit[\"_source\"]) # dict\n\nresponse.close # close the file\n","sub_path":"es4.py","file_name":"es4.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"577984340","text":"#!/usr/bin/python\n\n\"\"\"\nUnit test for MetaData.\n\"\"\"\n\n# Get object to test \nimport sys\nsys.path.append('../')\nfrom MetaData import MetaData\n\n# Get base class to run tests off of\nimport unittest\n\n# Create derived class that has the tests.\nclass TestMetaData(unittest.TestCase):\n def setUp(self):\n self.metaData = MetaData({})\n\n def test_meta_data_is_processed(self):\n testStr = '\\n'\n\n self.metaData.process(testStr)\n metaData = self.metaData.get()\n self.assertEqual('myblog', metaData['blogId'])\n\n def test_blank_meta_data_returns_none(self):\n testStr = ''\n self.metaData.process(testStr)\n metaData = self.metaData.get()\n self.assertEqual({}, metaData);\n\n\n\n\n# Main function will run all tests in classes derived from TestCase\nif __name__ == \"__main__\":\n unittest.main()\n\n\n","sub_path":"unit_tests/MetaData.t.py","file_name":"MetaData.t.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"478601341","text":"#Create a function named exponents() that takes two lists as parameters named bases and powers. \n#Return a new list containing every number in bases raised to every number in powers.\n\n\ndef exponents(bases, powers):\n new_ar = []\n for a in bases:\n for b in powers:\n new_ar.append(a**b)\n\n return new_ar\n\nprint(exponents([2, 3, 4], [1, 2, 3]))\n","sub_path":"6_1_Looping_Exponents.py","file_name":"6_1_Looping_Exponents.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"506611961","text":"import snowboydecoder\nimport sys\nimport signal\n\ninterrupted = False\n\ndef signal_handler(signal, frame):\n global interrupted\n interrupted = True\n\ndef interrupt_callback():\n global interrupted\n return interrupted\n\nmodel = r'resources/snowboy.umdl' # 修改model,指定其文件名\n\n# capture SIGINT signal, e.g., Ctrl+C\nsignal.signal(signal.SIGINT, signal_handler)\n\n# 唤醒词检测函数,调整sensitivity参数可修改唤醒词检测的准确性\ndetector = snowboydecoder.HotwordDetector(model, sensitivity=0.5)\nprint('Listening... Press Ctrl+C to exit')\n\n# main loop\n# 回调函数 detected_callback=snowboydecoder.play_audio_file \n# 修改回调函数可实现我们想要的功能\ndetector.start(detected_callback=snowboydecoder.play_audio_file,\n interrupt_check=interrupt_callback,\n sleep_time=0.03)\n\n# 释放资源\ndetector.terminate()\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"203364033","text":"import os \r\nfrom PIL import Image\r\n\r\nif not os.path.exists('../data/'):\r\n\tos.mkdir('../data')\r\nimgs = os.listdir()\r\nimgs = [i for i in imgs if '.jpg' in i]\r\nfor i in imgs:\r\n\timg = Image.open(i)\r\n\timg = img.resize((120,120))\r\n\timg.save(f'../data/{i}')\r\n\tprint(f'已完成第{i}张图片')\r\n","sub_path":"rawdata/datamake.py","file_name":"datamake.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"577738248","text":"import Transactions\r\nimport Payments\r\nimport Customers\r\nimport Database as db\r\nimport Constants\r\n\r\n#name,prv_out_standing, payments_recvd, outstd_bal, old_points, points_added, new_points\r\nCustomers_test_data = [[\"Jhon\",30000,0,30000,100,0,100],\r\n [\"Ram\",50000,0,50000,200,0,200],\r\n [\"Raj\",450000,0,450000,600,0,600],\r\n [\"Ian\",26000,0,26000,400,0,400],\r\n [\"Sachin\",110000,0,110000,500,0,500]]\r\n\r\n#name, date, amount\r\nPayments_data = [[\"Jhon\",\"10-06-2016\",1000],\r\n [\"Jhon\",\"10-07-2016\",2000],\r\n [\"Jhon\",\"10-09-2016\",10000],\r\n [\"Ram\",\"10-11-2016\",11200],\r\n [\"Ram\",\"10-12-2016\",5000]]\r\n#name, trans_id, date, amount,trans_type\r\nTransactions_data = [[\"Jhon\",112,\"1-06-2016\",5000,Constants.TRANS_SCHD],\r\n [\"Jhon\",113,\"2-06-2016\",3000,Constants.TRANS_SWIPE],\r\n [\"Jhon\",114,\"3-06-2016\",4000,Constants.TRANS_ONLINE],\r\n [\"Ram\",1,\"1-06-2016\",5000,Constants.TRANS_ONLINE],\r\n [\"Ram\",2,\"2-06-2016\",7000,Constants.TRANS_SWIPE]]\r\n\r\n\r\n\r\ndef main():\r\n print(\"Hello World!\")\r\n for row in Customers_test_data:\r\n # print(row)\r\n Customers.AddCustomer(row)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n\r\n for row in Transactions_data:\r\n print(\"Transaction:\", row)\r\n Transactions.ProcessTrans(row)\r\n #db.printTable(Constants.TRANS_TBL)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n\r\n for row in Payments_data:\r\n print(\"Payment : \", row)\r\n Payments.ProcessPayments(row)\r\n #db.printTable(Constants.TRANS_TBL)\r\n #db.printTable(Constants.PAYMENTS_TBL)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n Customers.generateStatment();\r\n\r\n for row in Transactions_data:\r\n print(\"Transaction:\",row)\r\n Transactions.ProcessTrans(row)\r\n #db.printTable(Constants.TRANS_TBL)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n\r\n for row in Payments_data:\r\n print(\"Payment : \", row)\r\n Payments.ProcessPayments(row)\r\n #db.printTable(Constants.TRANS_TBL)\r\n #db.printTable(Constants.PAYMENTS_TBL)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n Customers.generateStatment();\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"589676043","text":"\"\"\"\nCreated on Aug 28, 2018\n\n@author: mjasnik\n\"\"\"\n\n# imports\nimport os\nimport getpass\nfrom os import geteuid\n\n# timekpr imports\nfrom timekpr.common.constants import constants as cons\nfrom timekpr.common.log import log\nfrom timekpr.client.interface.dbus.administration import timekprAdminConnector\nfrom timekpr.common.utils.config import timekprConfig\nfrom timekpr.common.constants import messages as msg\n\n\nclass timekprAdminClient(object):\n \"\"\"Main class for holding all client logic (including dbus)\"\"\"\n\n # --------------- initialization / control methods --------------- #\n\n def __init__(self, pIsDevActive=False):\n \"\"\"Initialize admin client\"\"\"\n # dev\n self._isDevActive = pIsDevActive\n\n # get our connector\n self._timekprAdminConnector = timekprAdminConnector(self._isDevActive)\n\n # main object for GUI\n self._adminGUI = None\n\n def startTimekprAdminClient(self, *args):\n \"\"\"Start up timekpr admin (choose gui or cli and start this up)\"\"\"\n # check whether we need CLI or GUI\n lastParam = args[len(args)-1]\n timekprForceCLI = False\n\n # check for script\n if (\"/timekpra\" in lastParam or \"timekpra.py\" in lastParam):\n # whether we have X running or wayland?\n timekprX11Available = os.getenv(\"DISPLAY\") is not None\n timekprWaylandAvailable = os.getenv(\"WAYLAND_DISPLAY\") is not None\n timekprMirAvailable = os.getenv(\"MIR_SOCKET\") is not None\n\n # if we are required to run graphical thing\n if (timekprX11Available or timekprWaylandAvailable or timekprMirAvailable):\n # save logging for later use in classes down tree\n self._logging = {cons.TK_LOG_L: cons.TK_LOG_LEVEL_DEBUG, cons.TK_LOG_D: cons.TK_LOG_TEMP_DIR, cons.TK_LOG_W: (cons.TK_LOG_OWNER_ADMIN_SU if geteuid() == 0 else cons.TK_LOG_OWNER_ADMIN), cons.TK_LOG_U: getpass.getuser()}\n # logging init\n log.setLogging(self._logging)\n\n # configuration init\n _timekprConfigManager = timekprConfig(pIsDevActive=self._isDevActive, pLog=self._logging)\n # load config\n _timekprConfigManager.loadMainConfiguration()\n # resource dir\n _resourcePathGUI = os.path.join(_timekprConfigManager.getTimekprSharedDir(), \"client/forms\")\n\n # use GUI\n from timekpr.client.gui.admingui import timekprAdminGUI\n # load GUI and process from there\n self._adminGUI = timekprAdminGUI(cons.TK_VERSION, _resourcePathGUI, getpass.getuser(), self._isDevActive)\n # nor X nor wayland are available\n else:\n # print to console\n log.consoleOut(msg.getTranslation(\"TK_MSG_CONSOLE_GUI_NOT_AVAILABLE\") + \"\\n\")\n # forced CLI\"\n timekprForceCLI = True\n else:\n # CLI\n timekprForceCLI = True\n\n # for CLI connections\n if timekprForceCLI:\n # connect\n self._timekprAdminConnector.initTimekprConnection(True)\n # connected?\n if self._timekprAdminConnector.isConnected()[1]:\n # use CLI\n # validate possible parameters and their values, when fine - execute them as well\n self.checkAndExecuteAdminCommands(*args)\n\n # --------------- parameter validation methods --------------- #\n\n def checkAndExecuteAdminCommands(self, *args):\n \"\"\"Init connection to timekpr dbus server\"\"\"\n # initial param len\n paramIdx = 0\n paramLen = len(args)\n adminCmdIncorrect = False\n tmpIdx = 0\n\n # determine parameter offset\n for rArg in args:\n # count offset\n tmpIdx += 1\n # check for script\n if \"/timekpra\" in rArg or \"timekpra.py\" in rArg:\n paramIdx = tmpIdx\n\n # this gets the command itself (args[0] is the script name)\n adminCmd = args[paramIdx] if paramLen > paramIdx else \"timekpra\"\n\n # now based on params check them out\n # this gets saved user list from the server\n if adminCmd == \"--help\":\n # fine\n pass\n # this gets saved user list from the server\n elif adminCmd == \"--userlist\":\n # check param len\n if paramLen != paramIdx + 1:\n # fail\n adminCmdIncorrect = True\n else:\n # get list\n result, message, userList = self._timekprAdminConnector.getUserList()\n\n # process\n if result == 0:\n # process\n self.printUserList(userList)\n else:\n # log error\n log.consoleOut(message)\n\n # this gets user configuration from the server\n elif adminCmd == \"--userconfig\":\n # check param len\n if paramLen != paramIdx + 2:\n # fail\n adminCmdIncorrect = True\n else:\n # get user config\n result, message, userConfig = self._timekprAdminConnector.getUserConfig(args[paramIdx+1])\n\n # process\n if result == 0:\n # process\n self.printUserConfig(args[paramIdx+1], userConfig)\n else:\n # log error\n log.consoleOut(message)\n\n # this sets allowed days for the user\n elif adminCmd == \"--setalloweddays\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetAllowedDays(args[paramIdx+1], args[paramIdx+2])\n\n # this sets allowed hours per specified day or ALL for every day\n elif adminCmd == \"--setallowedhours\":\n # check param len\n if paramLen != paramIdx + 4:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetAllowedHours(args[paramIdx+1], args[paramIdx+2], args[paramIdx+3])\n\n # this sets time limits per allowed days\n elif adminCmd == \"--settimelimits\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTimeLimits(args[paramIdx+1], args[paramIdx+2])\n\n # this sets time limits per week\n elif adminCmd == \"--settimelimitweek\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTimeLimitWeek(args[paramIdx+1], args[paramIdx+2])\n\n # this sets time limits per month\n elif adminCmd == \"--settimelimitmonth\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTimeLimitMonth(args[paramIdx+1], args[paramIdx+2])\n\n # this sets whether to track inactive user sessions\n elif adminCmd == \"--settrackinactive\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTrackInactive(args[paramIdx+1], args[paramIdx+2])\n\n # this sets time left for the user at current moment\n elif adminCmd == \"--settimeleft\":\n # check param len\n if paramLen != paramIdx + 4:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTimeLeft(args[paramIdx+1], args[paramIdx+2], args[paramIdx+3])\n\n else:\n # out\n adminCmdIncorrect = True\n\n # check whether command is supported\n if (adminCmd not in cons.TK_USER_ADMIN_COMMANDS and adminCmd not in cons.TK_ADMIN_COMMANDS) or adminCmd == \"--help\" or adminCmdIncorrect:\n # fail\n if adminCmdIncorrect:\n log.consoleOut(msg.getTranslation(\"TK_MSG_CONSOLE_COMMAND_INCORRECT\"), *args)\n\n log.consoleOut(\"\\n\" + msg.getTranslation(\"TK_MSG_CONSOLE_USAGE_NOTES\"))\n # initial order\n cmds = [\"--help\", \"--userlist\", \"--userconfig\"]\n # print initial commands as first\n for rCmd in cmds:\n log.consoleOut(\" \", rCmd, cons.TK_USER_ADMIN_COMMANDS[rCmd])\n\n # put a little space in between\n log.consoleOut(\"\")\n\n # print help\n for rCmd, rCmdDesc in cons.TK_USER_ADMIN_COMMANDS.items():\n # do not print already known commands\n if rCmd not in cmds:\n log.consoleOut(\" \", rCmd, rCmdDesc)\n\n # --------------- parameter execution methods --------------- #\n\n def printUserList(self, pUserList):\n \"\"\"Format and print userlist\"\"\"\n # print to console\n log.consoleOut(msg.getTranslation(\"TK_MSG_CONSOLE_USERS_TOTAL\", len(pUserList)))\n # loop and print\n for rUser in pUserList:\n log.consoleOut(rUser)\n\n def printUserConfig(self, pUserName, pPrintUserConfig):\n \"\"\"Format and print user config\"\"\"\n # print to console\n log.consoleOut(msg.getTranslation(\"TK_MSG_CONSOLE_CONFIG_FOR\") % (pUserName))\n # loop and print the same format as ppl will use to set that\n for rUserKey, rUserConfig in pPrintUserConfig.items():\n # join the lists\n if \"ALLOWED_W\" in rUserKey or \"LIMITS_P\" in rUserKey:\n # print join\n log.consoleOut(\"%s: %s\" % (rUserKey, \";\".join(list(map(str, rUserConfig)))))\n # join the lists\n elif \"ALLOWED_H\" in rUserKey:\n # hrs\n hrs = \"\"\n # print join\n if len(rUserConfig) > 0:\n for rUserHour in sorted(list(map(int, rUserConfig))):\n # get config per hr\n hr = \"%s\" % (rUserHour) if rUserConfig[str(rUserHour)][cons.TK_CTRL_SMIN] <= 0 and rUserConfig[str(rUserHour)][cons.TK_CTRL_EMIN] >= 60 else \"%s[%s-%s]\" % (rUserHour, rUserConfig[str(rUserHour)][cons.TK_CTRL_SMIN], rUserConfig[str(rUserHour)][cons.TK_CTRL_EMIN])\n # empty\n if hrs == \"\":\n hrs = \"%s\" % (hr)\n else:\n hrs = \"%s;%s\" % (hrs, hr)\n\n log.consoleOut(\"%s: %s\" % (rUserKey, hrs))\n elif \"TRACK_IN\" in rUserKey:\n log.consoleOut(\"%s: %s\" % (rUserKey, bool(rUserConfig)))\n else:\n log.consoleOut(\"%s: %s\" % (rUserKey, str(rUserConfig)))\n\n def processSetAllowedDays(self, pUserName, pDayList):\n \"\"\"Process allowed days\"\"\"\n # defaults\n dayMap = ()\n result = 0\n\n # day map\n try:\n # try to parse parameters\n dayMap = list(map(int, pDayList.split(\";\")))\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setAllowedDays(pUserName, dayMap)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetAllowedHours(self, pUserName, pDayNumber, pHourList):\n \"\"\"Process allowed hours\"\"\"\n # this is the dict for hour config\n allowedHours = {}\n result = 0\n\n # allowed hours\n try:\n # check hours\n for rHour in str(pHourList).split(\";\"):\n # verify hour\n hour = int(rHour.split(\"[\", 1)[0])\n # if we have advanced config (minutes)\n if \"[\" in rHour and \"]\" in rHour and \"-\" in rHour:\n # get minutes\n minutes = rHour.split(\"[\", 1)[1].split(\"]\")[0].split(\"-\")\n # verify minutes\n tmp = int(minutes[0])\n tmp = int(minutes[1])\n # get our dict done\n allowedHours[str(hour)] = {cons.TK_CTRL_SMIN: min(max(int(minutes[0]), 0), 60), cons.TK_CTRL_EMIN: min(max(int(minutes[1]), 0), 60)}\n else:\n # get our dict done\n allowedHours[str(hour)] = {cons.TK_CTRL_SMIN: 0, cons.TK_CTRL_EMIN: 60}\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setAllowedHours(pUserName, pDayNumber, allowedHours)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTimeLimits(self, pUserName, pDayLimits):\n \"\"\"Process time limits for days\"\"\"\n # defaults\n dayLimits = ()\n result = 0\n\n # day limists\n try:\n # try to parse parameters\n dayLimits = list(map(int, pDayLimits.split(\";\")))\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTimeLimitForDays(pUserName, dayLimits)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTimeLimitWeek(self, pUserName, pTimeLimitWeek):\n \"\"\"Process time limits for week\"\"\"\n # defaults\n weekLimit = 0\n result = 0\n\n # week limit\n try:\n # try to parse parameters\n weekLimit = int(pTimeLimitWeek)\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTimeLimitForWeek(pUserName, weekLimit)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTimeLimitMonth(self, pUserName, pTimeLimitMonth):\n \"\"\"Process time limits for month\"\"\"\n # defaults\n monthLimit = 0\n result = 0\n\n # week limit\n try:\n # try to parse parameters\n monthLimit = int(pTimeLimitMonth)\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTimeLimitForMonth(pUserName, monthLimit)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTrackInactive(self, pUserName, pTrackInactive):\n \"\"\"Process track inactive\"\"\"\n # defaults\n trackInactive = None\n result = 0\n\n # check\n if pTrackInactive not in [\"true\", \"True\", \"TRUE\", \"false\", \"False\", \"FALSE\"]:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (\"please specify true or false\")\n else:\n trackInactive = True if pTrackInactive in [\"true\", \"True\", \"TRUE\"] else False\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTrackInactive(pUserName, trackInactive)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTimeLeft(self, pUserName, pOperation, pLimit):\n \"\"\"Process time left\"\"\"\n # defaults\n limit = 0\n result = 0\n\n # limit\n try:\n # try to parse parameters\n limit = int(pLimit)\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTimeLeft(pUserName, pOperation, limit)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n","sub_path":"client/admin/adminprocessor.py","file_name":"adminprocessor.py","file_ext":"py","file_size_in_byte":16989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"109722134","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 7 12:55:30 2018\n\n@author: Henry Tessier\n\"\"\"\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport numpy as np\nimport re\nimport random\nfrom collections import Counter\nimport seaborn as sns\n\n\n# Base url, and a lambda func to return url for a given year\nbase_url = 'http://kenpom.com/index.php'\nurl_year = lambda x: '%s?y=%s' % (base_url, str(x) if x != 2018 else base_url)\n\n# Create a method that parses a given year and spits out a raw dataframe\ndef import_raw_year(year):\n \n #Imports raw data from a ken pom year into a dataframe\n \n f = requests.get(url_year(year))\n soup = BeautifulSoup(f.text, \"lxml\")\n table_html = soup.find_all('table', {'id': 'ratings-table'})\n\n # Weird issue w/ in the html\n # Prevents us from just using pd.read_html\n # Let's find all the thead contents and just replace/remove them\n # This allows us to easily put the table row data into a dataframe using panda\n thead = table_html[0].find_all('thead')\n\n table = table_html[0]\n for x in thead:\n table = str(table).replace(str(x), '')\n\n df = pd.read_html(table)[0]\n df['year'] = year\n return df\n \n\n# Import all the years into a singular dataframe\ndf = None\npickyear = input(\"Enter Year (2002 - 2018): \")\nprint(\"\")\nprint(\"Gathering most recent statistics...\")\ndf = pd.concat( (df, import_raw_year(pickyear)), axis=0) \n\n# Column rename based off of original website\ndf.columns = ['Rank', 'Team', 'Conference', 'W-L', 'AdjEM', \n 'AdjustO', 'AdjustO Rank', 'AdjustD', 'AdjustD Rank',\n 'AdjustT', 'AdjustT Rank', 'Luck', 'Luck Rank', \n 'SOS_Pyth', 'SOS Pyth Rank', 'SOS OppO', 'SOS OppO Rank',\n 'SOS OppD', 'SOS OppD Rank', 'NCSOS Pyth', 'NCSOS Pyth Rank', 'Year']\n \n# Lambda that returns true if given string is a number and a valid seed number (1-16)\nvalid_seed = lambda x: True if str(x).replace(' ', '').isdigit() \\\n and int(x) > 0 and int(x) <= 16 else False\n\n# Use lambda to parse out seed/team\ndf['Seed'] = df['Team'].apply(lambda x: x[-2:].replace(' ', '') \\\n if valid_seed(x[-2:]) else np.nan )\n\ndf['Team'] = df['Team'].apply(lambda x: x[:-2] if valid_seed(x[-2:]) else x)\n\n# Split W-L column into wins and losses\ndf['Wins'] = df['W-L'].apply(lambda x: int(re.sub('-.*', '', x)) )\ndf['Losses'] = df['W-L'].apply(lambda x: int(re.sub('.*-', '', x)) )\ndf.drop('W-L', inplace=True, axis=1)\n\n\ndf=df[[ 'Year', 'Rank', 'Team', 'Conference', 'Wins', 'Losses', 'Seed','AdjEM', \n 'AdjustO', 'AdjustO Rank', 'AdjustD', 'AdjustD Rank',\n 'AdjustT', 'AdjustT Rank', 'Luck', 'Luck Rank', \n 'SOS_Pyth', 'SOS Pyth Rank', 'SOS OppO', 'SOS OppO Rank',\n 'SOS OppD', 'SOS OppD Rank', 'NCSOS Pyth', 'NCSOS Pyth Rank']]\n \ndf = df[['Team','Wins','Losses','AdjEM','SOS_Pyth']]\ndf.Team = df.Team.str.rstrip()\ndf.Team = df.Team.str.replace('\\s+', '_')\ndf.Team = df.Team.str.replace('.', '')\ndf.Team = df.Team.str.replace('&', '')\ndf.Team = df.Team.str.replace('\\'', '')\ndf['WLPercentage'] = df.Wins / (df.Losses + df.Wins)\ndf['Name'] = df.Team\ndf = df.set_index('Name')\n\n\n# ______________________Data Import Completed_________________________________\n\nprint(\"\")\nregion = {}\nx = 1\nwhile x < 17: \n region[\"Seed{0}\".format(x)] = input(\"Enter \"+str(x)+\" Seed Team: \")\n if (region[\"Seed{0}\".format(x)]) not in df.Team:\n print(x, \"seed team not found\")\n else:\n x += 1\n \n\ndef sim_game(Team1, Team2):\n #results = []\n #for x in range(reps): \n ELO1 = ((df.loc[Team1].AdjEM + 40) + ((df.loc[Team1].SOS_Pyth + 15) * df.loc[Team1].WLPercentage)) \n ELO2 = ((df.loc[Team2].AdjEM + 40) + ((df.loc[Team2].SOS_Pyth + 15) * df.loc[Team2].WLPercentage))\n m = ELO1 - ELO2\n A = (1/(1+10**(abs(m)/23)))\n odds = (1-A)\n if m < 0:\n odds = (1-odds)\n result = random.random() <= odds\n \n if result == True:\n return(Team1)\n else:\n return(Team2)\n \n\"\"\" \n#For running multiple simulations of 1 game rather than multiple simulations of 1 region\n\n results += [result]\n if results.count(True) > results.count(False):\n return(Team1)\n elif results.count(False) > results.count(True):\n return(Team2)\n else:\n if ELO1 > ELO2:\n return(Team1)\n else:\n return(Team2)\n\"\"\"\n\nreps = int(input('Enter number of tournaments to simulate: '))\n\n\n###################################\n###NCAA Tourney Region Simulator###\n###################################\n\nWinners = []\nRound1W = []\nRound2W = []\nRound3W = []\n\nfor x in range(reps):\n#Round 1\n Win1 = sim_game(region['Seed1'],region['Seed16'])\n Win2 = sim_game(region['Seed8'],region['Seed9'])\n Win3 = sim_game(region['Seed5'],region['Seed12'])\n Win4 = sim_game(region['Seed4'],region['Seed13'])\n Win5 = sim_game(region['Seed6'],region['Seed11'])\n Win6 = sim_game(region['Seed3'],region['Seed14'])\n Win7 = sim_game(region['Seed7'],region['Seed10'])\n Win8 = sim_game(region['Seed2'],region['Seed15'])\n Round1W += [Win1,Win2,Win3,Win4,Win5,Win6,Win7,Win8]\n\n#Round 2\n Win2_1 = sim_game(Win1,Win2)\n Win2_2 = sim_game(Win3,Win4)\n Win2_3 = sim_game(Win5,Win6)\n Win2_4 = sim_game(Win7,Win8)\n Round2W += [Win2_1,Win2_2,Win2_3,Win2_4]\n\n#Round 3\n Win3_1 = sim_game(Win2_1,Win2_2)\n Win3_2 = sim_game(Win2_3,Win2_4)\n Round3W += [Win3_1,Win3_2]\n\n#Round 4\n WinFF = sim_game(Win3_1,Win3_2)\n Winners += [WinFF]\n\n#Graph for final round winner\n\ntotwins = Counter(Winners)\nfor x in totwins:\n totwins[x] = totwins[x]/reps\n\nresults = pd.DataFrame(list(totwins.items()), columns=['Team', 'Win Share %'])\nresults['Team'] = results['Team'].str.replace('_', ' ')\nresults[\"Win Share %\"] = (results[\"Win Share %\"] * 100)\nresults = results.sort_values([\"Win Share %\"], ascending = False)\nOutput = sns.barplot(x = results[\"Win Share %\"], y = results[\"Team\"])\nOutput.set(xlabel = \"Projected Win Shares (%)\")\n#print(results)\n\n######### Data for all previous rounds ##########\n\nround1wins = Counter(Round1W)\nround2wins = Counter(Round2W)\nround3wins = Counter(Round3W)\n\nfor x in round3wins:\n round3wins[x] = round3wins[x]/reps\nfor x in round2wins:\n round2wins[x] = round2wins[x]/reps\nfor x in round1wins:\n round1wins[x] = round1wins[x]/reps\n\nresults3 = pd.DataFrame(list(round3wins.items()), columns=['Team', 'Win Share %'])\nresults3['Team'] = results3['Team'].str.replace('_', ' ')\nresults3[\"Win Share %\"] = (results3[\"Win Share %\"] * 100)\nresults3 = results3.sort_values([\"Win Share %\"], ascending = False)\n\nresults2 = pd.DataFrame(list(round2wins.items()), columns=['Team', 'Win Share %'])\nresults2['Team'] = results2['Team'].str.replace('_', ' ')\nresults2[\"Win Share %\"] = (results2[\"Win Share %\"] * 100)\nresults2 = results2.sort_values([\"Win Share %\"], ascending = False)\n\nresults1 = pd.DataFrame(list(round1wins.items()), columns=['Team', 'Win Share %'])\nresults1['Team'] = results1['Team'].str.replace('_', ' ')\nresults1[\"Win Share %\"] = (results1[\"Win Share %\"] * 100)\nresults1 = results1.sort_values([\"Win Share %\"], ascending = False)\n\nprint(\"\")\nprint(\"Make Final Four Probability:\")\nprint(results)\nprint(\"\")\nprint(\"Make Elite Eight Probability:\")\nprint(results3)\nprint(\"\")\nprint(\"Make Sweet 16 Probability:\")\nprint(results2)\nprint(\"\")\nprint(\"Make Second Round Probability:\")\nprint(results1)\n","sub_path":"BracketModel.py","file_name":"BracketModel.py","file_ext":"py","file_size_in_byte":7456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"359603367","text":"import re\n\nimport pandas as pd\n\nfrom config.common import log\nfrom egovResearch.egovScDoc.spiders.docSpider.base_spider import *\nfrom pyQwSciLib import app\nfrom wSpider.egovernment.egov_spider_lite.extra.common_utils import *\n\n\n# app = create_app()\n\ndef filter_special_words():\n \"\"\"\n 过滤特殊字符\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query.all()\n for item in item_list:\n title = item.title\n title = title.replace(\"\\n\",\"\")\n title = title.replace(\"\",\"\")\n title = title.strip()\n item.title = title\n item.update()\n\n pass\n\n\"\"\"读取和更新政策的年份信息\"\"\"\ndef get_year():\n \"\"\"\n 读取年份\n :return:\n \"\"\"\n item_list = db.session.query(\n EGOVSCPolicyPaper.id,\n EGOVSCPolicyPaper.release_time,\n EGOVSCPolicyPaper.material_date,\n EGOVSCPolicyPaper.year\n ).filter(\n EGOVSCPolicyPaper.year == None\n ).all()\n print(len(list(item_list)))\n for elem in item_list:\n item_id = elem[0]\n release_time = elem[1]\n material_date = elem[2]\n year = elem[3]\n if year is None:\n item = EGOVSCPolicyPaper.query.filter(EGOVSCPolicyPaper.id==item_id).first()\n if item.year is None:\n print(item.release_time,\" \",item.material_date,\" \",item.year)\n # if item.release_time is not None and item.material_date == \"\":\n # item.material_date = item.release_time\n # item.year = item.release_time.split(\"-\")[0]\n # item.update()\n if item.release_time is not None:\n item.material_date = item.release_time\n item.year = item.material_date.split(\"-\")[0]\n item.update()\n\nwith open(\"key_words.txt\",\"r\",encoding=\"UTF-8\") as f:\n key_words = f.read().split(\"\\n\")\ndef batch_judge_if_title_have_key_words(title):\n for key_word in key_words:\n if key_word in title:\n return True\n return False\n\n\"\"\"默认过滤是否和电子政务相关\"\"\"\ndef get_egov_related_title():\n \"\"\"\n 过滤是否和电子政务相关\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query_by_city_year_and_flag(None,None,0)\n for item in item_list:\n elem = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.id == item.id\n ).first()\n if batch_judge_if_title_have_key_words(item.title):\n elem.flag = EGOVSCPolicyPaper.__FILE_FLAG_BATCH_VALIDATED__\n log.info(\"---------{}---------\".format(elem.title))\n else:\n if judge_if_title_have_key_words(item.title):\n elem.flag = EGOVSCPolicyPaper.__FILE_FLAG_VALIDATED__\n log.info(\"--{}--\".format(elem.title))\n else:\n elem.flag = EGOVSCPolicyPaper.__FILE_FLAG_DELETED__\n elem.update()\n pass\n\n\"\"\"二次过滤\"\"\"\ndef filter_egov_related_title():\n \"\"\"\n 二次过滤是否和电子政务相关\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query_by_city_year_and_flag(\n None,None,EGOVSCPolicyPaper.__FILE_FLAG_VALIDATED__)\n print(len(item_list))\n for item in item_list:\n elem = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.id == item.id\n ).first()\n if batch_judge_if_title_have_key_words(item.title):\n elem.flag = EGOVSCPolicyPaper.__FILE_FLAG_BATCH_VALIDATED__\n log.info(\"---------{}---------\".format(elem.title))\n elem.update()\n pass\n\n\"\"\"查看模糊月份\"\"\"\ndef get_indefinite_month():\n \"\"\"\n 查找月份模糊的File\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.flag == EGOVSCPolicyPaper.__FILE_FLAG_ARCHIVED__\n ).all()\n for elem in item_list:\n print(elem.material_date)\n pass\n\n\"\"\"读取城市列表\"\"\"\ndef read_cities():\n \"\"\"\n 初始化城市列表\n :return:\n \"\"\"\n with open(\"cities.txt\",\"r\",encoding=\"utf-8\") as f:\n city_list = f.read().split(\"\\n\")\n for city in city_list:\n item = EGOVSCPolicyPapersCompare()\n city_item = EGOVProvinceCityInfo.query.filter(\n EGOVProvinceCityInfo.city == city\n ).first()\n if city_item is None:\n city_name = \"{}市\".format(city)\n city_item = EGOVProvinceCityInfo.query.filter(\n EGOVProvinceCityInfo.city == city_name\n ).first()\n item.city_id = city_item.id\n item.city = city\n item.city_name = city_item.city\n item.save()\n\nsheets_name = [\n \"省会城市政府网站服务能力.xlsx\", # 0\n \"省会城市政府微博服务能力.xlsx\",\n \"省会城市政府微信服务能力.xlsx\", # 2\n \"省会城市政府APP服务能力.xlsx\",\n \"省会城市政府双微服务能力.xlsx\", # 4\n \"省会城市政府新媒体服务能力.xlsx\",\n \"省会城市电子政务综合服务能力.xlsx\", # 6\n]\nsheet_name = sheets_name[5]\n\"\"\"读取测评报告数据\"\"\"\ndef read_egovsc_data():\n \"\"\"\n 读取Excel中的测评数据结果\n :return:\n \"\"\"\n base_dir = \"D:\\Documents\\QingwuDOC\\eGovernment\\省会城市政策文件分词\\Manuscript\\数据\\{}\"\n data_sheet = pd.read_excel(base_dir.format(sheet_name))\n for elem in data_sheet.iterrows():\n elem = elem[1]\n if not pd.isna(elem[\"省会城市\"]):\n item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city == elem[\"省会城市\"]\n ).first()\n if item is None:\n item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city_name == elem[\"省会城市\"]\n ).first()\n print(item.city_name)\n item.egovsc_new_media_2016 = elem[\"2016年\"] if not pd.isna(elem[\"2016年\"]) else 0\n item.egovsc_new_media_2017 = elem[\"2017年\"] if not pd.isna(elem[\"2017年\"]) else 0\n if float(\"%.2f\" % (item.egovsc_new_media_2017-item.egovsc_new_media_2016)) == float(\n \"%.2f\" % elem[\"变化情况\"]):\n print(elem[\"变化情况\"])\n item.egovsc_new_media_variation = elem[\"变化情况\"]\n else:\n raise Exception\n item.update()\n\n\"\"\"政府网站元数据灰色关联排序\"\"\"\ndef update_website_metadata_gray_index():\n \"\"\"\n 政府网站元数据灰色关联排序\n :return:\n \"\"\"\n data_sheet = pd.read_excel(\"D:\\Desktop\\元数据data.xlsx\")\n print(data_sheet)\n for elem in data_sheet.iterrows():\n elem = elem[1]\n if not pd.isna(elem[\"省会城市\"]):\n item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city_name == elem[\"省会城市\"]\n ).first()\n if item is not None:\n print(item.city_name)\n item.website_metadata_gray_index = elem[\"gray_index\"]\n item.update()\n\n\"\"\"国家行政学院电子政务发展指数\"\"\"\ndef update_chinese_academy_of_governance_egdi():\n \"\"\"\n 国家行政学院电子政务发展指数\n :return:\n \"\"\"\n data_sheet = pd.read_excel(\n \"D:\\Documents\\QingwuDOC\\eGovernment\\省会城市政策文件分词\\Manuscript\\数据\\中国行政学院报告\\中国城市电子政务报告.xlsx\",\n sheet_name=\"2016\"\n )\n for elem in data_sheet.iterrows():\n elem = elem[1]\n if not pd.isna(elem[\"city_name\"]):\n item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city_name == elem[\"city_name\"]\n ).first()\n if item is not None:\n print(item.city_name)\n item.ccps_egdi_online_service_2016 = elem[\"在线服务指数\"]\n item.update()\n\n\"\"\"转移省会城市数据库文件\"\"\"\ndef transfer_city_egov_files():\n \"\"\"\n 转移文件\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.flag == EGOVSCPolicyPaper.__FILE_FLAG_ARCHIVED__\n ).all()\n for elem in item_list:\n item = EGOVSCPolicyPaperAnalysis()\n same_item = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.file_title.like(\n elem.title\n )\n ).first()\n if same_item is not None:\n print(same_item.file_title)\n continue\n item.paper_id = elem.id\n item.file_title = elem.title\n item.file_content = elem.file_content\n item.city_id = elem.city_id\n item.city_name = elem.city_name\n\n time_strs = elem.material_date.split(\"-\")\n item.year_interval_str = \"{}.{}\".format(time_strs[0], int(time_strs[1]))\n item.source_flag = 0\n item.save()\n pass\n\"\"\"转移中央数据库文件\"\"\"\ndef transfer_council_egov_files():\n \"\"\"\n 转移中央文件\n :return:\n \"\"\"\n from pyQwSciLib.models import EGOVPolicyPaper\n from time import strftime,strptime\n item_list = EGOVPolicyPaper.query.filter(\n EGOVPolicyPaper.id >= 8560\n ).all()\n print(len(item_list))\n for elem in item_list:\n item = EGOVSCPolicyPaperAnalysis()\n same_item = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.file_title.like(\n elem.title\n )\n ).first()\n if same_item is not None:\n print(same_item.file_title)\n continue\n item.paper_id = elem.id\n item.file_title = elem.title\n file_content = str(elem.file_content, encoding='utf-8')\n\n item.file_content = file_content\n item.city_id = elem.city_id\n item.city_name = elem.city_name\n\n struct_time = strptime(elem.time,u\"%Y年%m月%d日\")\n str_time = strftime(u\"%Y-%m-%d\",struct_time)\n time_strs = str_time.split(\"-\")\n item.year_interval_str = \"{}.{}\".format(time_strs[0], int(time_strs[1]))\n print(item.year_interval_str)\n item.source_flag = 0\n item.org_flag = 1\n item.save()\n pass\n\"\"\"读取本地搜集省会城市文件\"\"\"\ndef read_city_files_from_local():\n \"\"\"\n 读取本地文件存入数据库\n :return:\n \"\"\"\n base_dir = \"D:\\Desktop\\修改政策\\\\2011.7-2016.6\\省会城市\"\n city_list = os.listdir(base_dir)\n for city in city_list:\n city_item = EGOVProvinceCityInfo.query.filter(\n EGOVProvinceCityInfo.city == \"{}市\".format(city)\n ).first()\n city_dir = \"{}\\{}\".format(base_dir,city)\n paper_list = os.listdir(city_dir)\n for paper in paper_list:\n item = EGOVSCPolicyPaperAnalysis()\n paper_file_name = paper.replace(\".txt\", \"\")\n title_info = re.findall(\"(\\d+).(\\d+)\", paper_file_name)\n year_interval_str = \"{}.{}\".format(title_info[0][0],title_info[0][1])\n title = paper_file_name.replace(year_interval_str,\"\").strip()\n # print(title_info)\n # print(title)\n # print(year_interval_str)\n item.city_id = city_item.id\n item.city_name = city_item.city\n item.paper_id = 0\n\n item.file_title = title\n item.year_interval_str = year_interval_str\n item.source_flag = 1\n item.save()\n with open(\"{}\\{}\".format(\n city_dir, paper\n ), \"r\", encoding=\"GBK\",errors=\"ignore\") as fc:\n # print(fc.read())\n item.file_content = fc.read()\n res = item.update()\n if res is False:\n print(paper)\n pass\n\"\"\"读取本地搜集中央文件\"\"\"\ndef read_council_files_from_local():\n \"\"\"\n 读取本地中央文件存入数据库\n :return:\n \"\"\"\n # base_dir = \"D:\\Desktop\\修改政策\\\\2011.7-2016.6\\国务院\"\n base_dir = \"D:\\Desktop\\修改政策\\\\2016.7-2017.6\\国务院\"\n paper_list = os.listdir(base_dir)\n for paper in paper_list:\n item = EGOVSCPolicyPaperAnalysis()\n paper_file_name = paper.replace(\".txt\", \"\")\n title_info = re.findall(\"(\\d+).(\\d+)\", paper_file_name)\n year_interval_str = \"{}.{}\".format(title_info[0][0],title_info[0][1])\n title = paper_file_name.replace(year_interval_str,\"\").strip()\n\n same_item = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.file_title.like(\n title\n )\n ).first()\n if same_item is not None:\n print(same_item.file_title)\n continue\n\n item.city_id = 1\n item.city_name = \"国务院\"\n item.paper_id = 0\n\n item.file_title = title\n item.year_interval_str = year_interval_str\n item.source_flag = 1\n item.save()\n with open(\"{}\\{}\".format(\n base_dir, paper\n ), \"r\", encoding=\"GBK\",errors=\"ignore\") as fc:\n # print(fc.read())\n item.file_content = fc.read()\n\n res = item.update()\n if res is False:\n print(paper)\n pass\n\nyear_intervals = [\n \"2017.7之后\", # 0\n \"2016.7-2017.6\", # 1\n \"2015.7-2016.6\", # 2\n \"2014.7-2015.6\", # 3\n \"2013.7-2014.6\", # 4\n \"2012.7-2013.6\", # 5\n \"2011.7-2012.6\", # 6 # \"2011.6之前\" # 7\n \"2010.7-2011.6\", # 7\n \"2009.7-2010.6\", # 8\n \"2009.6之前\", # 9\n]\n\"\"\"更新年份区间\"\"\"\ndef update_year_interval():\n \"\"\"\n 更新年份区间\n :return:\n \"\"\"\n\n # id_list = db.session.query(EGOVSCPolicyPaper.id).all()\n # print(len(id_list))\n # for item_id in id_list:\n # item = EGOVSCPolicyPaper.query.filter(EGOVSCPolicyPaper.id == item_id).first()\n # print(item.id)\n # year_interval = item.material_date.split(\"-\")\n\n item_list = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.org_flag == 1\n ).all()\n print(len(item_list))\n for item in item_list:\n year_interval = item.year_interval_str.split(\".\")\n year = int(year_interval[0])\n month = int(year_interval[1])\n if year >= 2018:\n item.year_interval = 0\n elif year < 2009:\n item.year_interval = 9\n else:\n if month <= 6:\n item.year_interval = 2018 - year\n else:\n item.year_interval = 2018 - year - 1\n item.update()\n\nconfigs = [\n {\n \"year\": 2014,\n \"year_interval_start\": 3,\n \"loop_minuend\": 10\n },\n {\n \"year\": 2015,\n \"year_interval_start\": 2,\n \"loop_minuend\": 9\n },\n {\n \"year\": 2016,\n \"year_interval_start\": 1,\n \"loop_minuend\": 8\n },\n {\n \"year\": 2017,\n \"year_interval_start\": 0,\n \"loop_minuend\": 7\n }\n]\ncount_configs = [\n # {\n # \"count_str\":\"counts\"\n # },\n {\n \"count_str\":\"total_counts\"\n }\n]\n\n\"\"\"更新文件数量\"\"\"\ndef update_file_counts():\n \"\"\"\n 更新文件数量(此处文件是指跟电子政务有关的文件)\n 更新文件总数,此处文件是指省会城市的所有文件\n :return:\n \"\"\"\n for count_config in count_configs:\n for config in configs:\n if count_config[\"count_str\"] == \"counts\":\n city_list = EGOVSCPolicyPaperAnalysis.query.all()\n item_list = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.year_interval > config[\"year_interval_start\"]\n ).all()\n else:\n city_list = EGOVSCPolicyPaper.query.all()\n print(len(city_list))\n item_list = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.year_interval > config[\"year_interval_start\"]\n ).all()\n print(len(item_list))\n\n file_year_city_list = []\n city_dicts = {}\n for city in city_list:\n city_dicts[city.city_id] = city.city_name\n for i in range(1, 7): # 一共5+1个回溯期\n file_year_city_list.append({})\n for city in city_list:\n file_year_city_list[i-1][city.city_id] = []\n\n for item in item_list:\n file_content = item.file_content\n for i in range(config[\"loop_minuend\"]-item.year_interval):\n file_year_city_list[5-i][item.city_id].append(file_content)\n if item.year_interval - config[\"year_interval_start\"] > 6: # 1 2 3 4 5 6\n file_year_city_list[5][item.city_id].append(file_content)\n\n for index, year_list in enumerate(file_year_city_list):\n for city_id, file_list in year_list.items():\n egovsc_compare_item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city_id == city_id\n ).first()\n if egovsc_compare_item is not None:\n if egovsc_compare_item.city_name == city_dicts[city_id]:\n print(city_dicts[city_id],\"recall:\",index,len(file_list))\n setattr(egovsc_compare_item,\n \"policy_{}_{}_recall_{}\".format(\n count_config[\"count_str\"],\n config[\"year\"],\n index+1\n ),\n len(file_list)\n )\n egovsc_compare_item.update()\n else:\n raise Exception\n\n\"\"\"读取并输出文件数量\"\"\"\ndef output_file_counts():\n \"\"\"\n 文件数量(此处文件是指跟电子政务有关的文件)\n 文件总数,此处文件是指省会城市的所有文件\n :return:\n \"\"\"\n writer = pd.ExcelWriter(\"D:\\\\Desktop\\\\data.xlsx\")\n city_list = EGOVSCPolicyPaperAnalysis.query.all()\n\n city_dicts = {}\n for city in city_list:\n city_dicts[city.city_id] = city.city_name\n\n def sum_file_counts(df,item_list):\n for index, city in enumerate(city_dicts.items()):\n df.loc[index, \"城市\"] = city[1]\n for i in range(0,8): # 一共8个年份\n df.loc[index, \"{}\".format(i+2)] = 0\n for item in item_list:\n city_index = df[(df[\"城市\"] == item.city_name)].index[0]\n df.loc[city_index,\"{}\".format(item.year_interval)] += 1\n df.columns = [\"省会城市\"] + year_intervals[2:]\n\n egov_item_list = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.year_interval > 1\n ).all()\n total_item_list = []\n total_item_list_res = db.session.query(\n EGOVSCPolicyPaper.id,\n EGOVSCPolicyPaper.year_interval,\n EGOVSCPolicyPaper.city_name\n ).filter(\n EGOVSCPolicyPaper.year_interval > 1\n ).all()\n print(len(total_item_list_res))\n for elem in total_item_list_res:\n item = EGOVSCPolicyPaper()\n item.year_interval = elem[1]\n item.city_name = elem[2]\n total_item_list.append(item)\n df_egov = pd.DataFrame()\n df_total = pd.DataFrame()\n sum_file_counts(df_egov,egov_item_list)\n sum_file_counts(df_total,total_item_list)\n df_egov.to_excel(writer,\"EGOV\",index=None)\n df_total.to_excel(writer,\"TOTAL\",index=None)\n writer.save()\n\nogd_key_words = [\n # \"数据开放\",\n \"政务公开\",\n \"信息公开\",\n # \"大数据行动\",\n # \"大数据发展\",\n \"申请公开\"\n]\ndef filter_ogd_papers():\n item_list = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.flag == 6 ,EGOVSCPolicyPaper.year_interval > 0).all()\n print(len(item_list))\n item_list = EGOVSCPolicyPaper.query.filter(EGOVSCPolicyPaper.flag == 6).all()\n counter = 0\n for item in item_list:\n for word in ogd_key_words:\n if word in item.title:\n print(item.title)\n counter += 1\n # item.flag = EGOVSCPolicyPaper.__FILE_FLAG_OGD__\n # item.update()\n break\n print(len(item_list))\n print(counter)\n pass\n\nfield_list = [\n\n]\nif __name__ == '__main__':\n with app.app_context():\n # output_file_counts()\n\n # query = db.session.query(EGOVSCPolicyPapersCompare)\n # df = pd.read_sql(query.statement, query.session.bind)\n # df.to_excel(\"D:\\\\Desktop\\\\xlsxdata.xlsx\")\n\n filter_ogd_papers()\n pass\n","sub_path":"egovResearch/egovScDoc/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":20574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"49212279","text":"import json\nimport pickle\nimport shutil\n\nimport pandas as pd\nimport sklearn.datasets\nimport random\nimport os\nimport uuid\nimport uuid as myuuid\nfrom river import compose\nfrom river import linear_model\nfrom river import metrics\nfrom river import preprocessing\n\nimport time\nfrom confluent_kafka import Producer, Consumer, KafkaException, KafkaError, TopicPartition\nimport certifi\n\ndef predict():\n current_model_path = os.path.join(app_config['root_folder'], app_config['models_sub_folder'], app_config['latest_version'],\n app_config['model_f_name'])\n\n md=pd.read_pickle(current_model_path)\n model =md['model']\n\n consumer = get_kafka_consumer()\n producer = get_kafka_producer()\n while (True):\n msg = consumer.poll(timeout=1.0)\n if msg is None: continue\n\n\n message = json.loads(msg.value().decode(\"utf-8\"))\n message['y_hat']=model.predict_one(message['x'])\n producer.produce(y_cap_topic,message)\n producer.flush()\n\n uuid = message['uuid']\n with open(os.path.join(app_config['root_folder'],app_config['raw_data_folder'],app_config['data_sub_folder'],uuid),'w') as f:\n f.write(json.dumps(message))\n\n\ndef get_kafka_consumer():\n curdir = os.getcwd()\n config_dir = curdir + '/../config/config.json'\n kafka_config = json.load(open(config_dir))\n kafka_consumer_config = kafka_config\n kafka_consumer_config['group.id'] = 'prediction-x-1'\n kafka_consumer_config['auto.offset.reset'] = 'earliest'\n consumer = Consumer(kafka_consumer_config)\n\n tls = [TopicPartition(x_topic, 0),TopicPartition(x_topic, 1),TopicPartition(x_topic, 2),TopicPartition(x_topic, 3)]\n consumer.assign(tls)\n return consumer\n\ndef get_kafka_producer():\n curdir = os.getcwd()\n config_dir = curdir + '/../config/config.json'\n kafka_config = json.load(open(config_dir))\n kafka_config['ssl.ca.location'] = certifi.where()\n kafka_config['client.id'] = 'test-sw-1'\n producer = Producer(kafka_config)\n return producer\n\n\n\napp_config = json.load(open(\"../config/app_config.json\"))\nx_topic='X'\ny_cap_topic='X_Y_CAP'\n\nif __name__ == '__main__':\n print('Start consuming x-data')\n predict()\n '''\n data_folder = root_folder + data_sub_folder\n truth_folder = root_folder + truth_sub_folder\n datasets_folder = root_folder + datasets_sub_folder\n dataset_metadata_config = root_folder + dataset_metadata_config_file\n model_metadata_config = root_folder + model_metadata_config_file\n print('Initializing')\n initialize()\n '''\n #create_initial_data()\n #gen_data(data_folder,truth_folder)\n #create_versioned_data(dataset_metadata_config,truth_folder,data_folder,datasets_folder)\n #create_versioned_model()","sub_path":"src/model_inference_api.py","file_name":"model_inference_api.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"380427632","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/5/21 14:03\n# @Author : Gavin\n\nimport redis\nimport logging\nlogger = logging.getLogger('InsertRequest')\n\n\ndef InsertRequest(url, type):\n try:\n r = redis.Redis(host='127.0.0.1', port=6379, db=0)\n if type == 0:\n r.lpush('ZhiLianCrawl:requests', url)\n if type == 1:\n r.lpush('ZhuoPinCrawl:requests', url)\n if type == 2:\n r.lpush('BossCrawl:requests', url)\n if type == 3:\n r.lpush('ChinaHRCrawl:requests', url)\n except:\n logger.info(\"Redis open failed!!!\")\n\n","sub_path":"code/RecruitmentMaster/RecruitmentMaster/src/InsertRedis.py","file_name":"InsertRedis.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"123726437","text":"def _pie(self, kwargs):\n\n\tkwargs['colors'] = kwargs.get('colors', self.colors)\n\tkwargs['colors'] = kwargs['colors'] + (len(kwargs['values'])-len(kwargs['colors']))*['#000000']\n\n\tdata = dict(\n\t\ttype = 'pie',\n\t\tvalues = kwargs['values'],\n\t\tlabels = kwargs.get('labels', ['']*len(kwargs['values'])),\n\t\ttextinfo = kwargs.get('textinfo', 'none'),\n\t\tmarker = dict(colors=kwargs['colors']),\n\t\thole = kwargs.get('hole', 0),\n\t\tdirection =kwargs.get('direction', 'clockwise'),\n\t\tsort = kwargs.get('sort', False),\n\t)\n\tself.data.append(data)\n\n\tkwargs['width'] = kwargs.get('width', 600)\n\t#self.layout.update(dict())\n\n\treturn kwargs","sub_path":"plotlywrapper/_pie.py","file_name":"_pie.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"114832787","text":"# coding=utf-8\n\"\"\"\nInternal tools for NimLime development & testing.\n\"\"\"\nfrom pprint import pformat\n\nimport sublime\nfrom nimlime_core import configuration\n\ntry:\n from cProfile import Profile\nexcept ImportError:\n from profile import Profile\nfrom functools import wraps\nfrom pstats import Stats\n\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\ndebug_on = False\nif debug_on:\n sublime.message_dialog('NimLime running in debug mode.')\n\n\n# Debug printer\ndef debug_print(*args):\n \"\"\"\n Print when debugging.\n :type args: Any\n \"\"\"\n if configuration.in_debug_mode:\n res = []\n for o in args:\n if isinstance(o, str):\n res.append(o)\n else:\n res.append(pformat(o))\n print(''.join(res))\n\n\n# Profiling functions\nprofiler = Profile()\nprofiler_running = False\n\n\ndef profile_func(func):\n \"\"\"\n Decorator which profiles a single function.\n Call print_profile_data to print the collected data.\n :type func: Callable\n :rtype: Callable\n \"\"\"\n\n @wraps(func)\n def _profile_wrapper(*args, **kwargs):\n global profiler_running\n if not profiler_running:\n profiler_running = True\n try:\n profiler.enable()\n return func(*args, **kwargs)\n finally:\n profiler.disable()\n profiler_running = False\n\n return _profile_wrapper\n\n\ndef print_profile_data():\n \"\"\"\n Print the collected profile data.\n \"\"\"\n stream = StringIO()\n statistics = Stats(profiler, stream=stream)\n statistics.sort_stats('cumulative')\n statistics.print_stats()\n print(stream.getvalue())\n","sub_path":"nimlime_core/utils/internal_tools.py","file_name":"internal_tools.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"394830621","text":"import os\nimport nibabel as nib\nimport numpy as np\nimport pickle\n\n#folders = [\"..\\\\Calgary_PS_DTI_Dataset\\\\\", \"..\\\\b2000\\\\\"]\nfolders = [\"../Calgary_PS_DTI_Dataset/\"]\nniiFiles = list()\nsNames = dict()\nfor folder in folders:\n for dirpaths, dirs, files in os.walk(folder):\n for file in files:\n if file.endswith('.nii'):\n filePath = os.path.join(dirpaths, file)\n niiFiles.append(filePath)\n sEnd = file.rfind('_')\n if sEnd == -1:\n sEnd = len(file)-4\n sName = file[0:sEnd]\n sNames[filePath] = sName\n \nmaxVals = dict()\ncount = 0\nfor file in niiFiles:\n count+=1\n sName = sNames[file]\n print(file, sName, count)\n nii = nib.load(file)\n data = nii.get_fdata()\n for vol in range(35):\n maxVal = np.max(data[:,:,:,vol])\n maxVals[sName, vol] = maxVal\n#%%\nwith open('maxVals.pickle', 'wb+') as f:\n pickle.dump(maxVals, f)","sub_path":"CNN/MaxGenerator.py","file_name":"MaxGenerator.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"111663054","text":"# DistRDF version of the RDataFrame benchmark df104\n# - Used DistRDF RDataFrame constructor for Spark\n# - Added npartitions parameter for Spark RDataFrame constructor\n# - Replaced generator by list in RDataFrame construction (the former is not supported by DistRDF yet)\n# - Removed RunGraphs execution option\n# - Replaced use of TH1DModel by a tuple (CppWorkflow does not support the former yet)\n\nimport os\nimport ROOT\n\ndistributed = ROOT.RDF.Experimental.Distributed\nRDataFrame = distributed.Spark.RDataFrame\n\ndef initialize():\n # Compile a function to compute the invariant mass of the diphoton system\n ROOT.gInterpreter.Declare(\n \"\"\"\n #ifndef df104_HiggsToTwoPhotons\n #define df104_HiggsToTwoPhotons\n using Vec_t = const ROOT::VecOps::RVec;\n float ComputeInvariantMass(Vec_t& pt, Vec_t& eta, Vec_t& phi, Vec_t& e) {\n ROOT::Math::PtEtaPhiEVector p1(pt[0], eta[0], phi[0], e[0]);\n ROOT::Math::PtEtaPhiEVector p2(pt[1], eta[1], phi[1], e[1]);\n return (p1 + p2).mass() / 1000.0;\n }\n #endif\n \"\"\")\n\ndef run(path, npartitions):\n # Register initialization function\n distributed.initialize(initialize)\n\n # Create a ROOT dataframe for each dataset\n df = {}\n df[\"data\"] = RDataFrame(\"mini\", [os.path.join(path, \"data_{}.GamGam.root\".format(x)) for x in (\"A\", \"B\", \"C\", \"D\")]*10, npartitions=npartitions)\n df[\"ggH\"] = RDataFrame(\"mini\", [os.path.join(path, \"mc_343981.ggH125_gamgam.GamGam.root\")]*10, npartitions=npartitions)\n df[\"VBF\"] = RDataFrame(\"mini\", [os.path.join(path, \"mc_345041.VBFH125_gamgam.GamGam.root\")]*10, npartitions=npartitions)\n processes = list(df.keys())\n\n # Apply scale factors and MC weight for simulated events and a weight of 1 for the data\n for p in [\"ggH\", \"VBF\"]:\n df[p] = df[p].Define(\"weight\",\n \"scaleFactor_PHOTON * scaleFactor_PhotonTRIGGER * scaleFactor_PILEUP * mcWeight\");\n df[\"data\"] = df[\"data\"].Define(\"weight\", \"1.0\")\n\n # Select the events for the analysis\n for p in processes:\n # Apply preselection cut on photon trigger\n df[p] = df[p].Filter(\"trigP\")\n\n # Find two good muons with tight ID, pt > 25 GeV and not in the transition region between barrel and encap\n df[p] = df[p].Define(\"goodphotons\", \"photon_isTightID && (photon_pt > 25000) && (abs(photon_eta) < 2.37) && ((abs(photon_eta) < 1.37) || (abs(photon_eta) > 1.52))\")\\\n .Filter(\"Sum(goodphotons) == 2\")\n\n # Take only isolated photons\n df[p] = df[p].Filter(\"Sum(photon_ptcone30[goodphotons] / photon_pt[goodphotons] < 0.065) == 2\")\\\n .Filter(\"Sum(photon_etcone20[goodphotons] / photon_pt[goodphotons] < 0.065) == 2\")\n\n # Define a new column with the invariant mass and perform final event selection\n hists = {}\n for p in processes:\n # Make four vectors and compute invariant mass\n df[p] = df[p].Define(\"m_yy\", \"ComputeInvariantMass(photon_pt[goodphotons], photon_eta[goodphotons], photon_phi[goodphotons], photon_E[goodphotons])\")\n\n # Make additional kinematic cuts and select mass window\n df[p] = df[p].Filter(\"photon_pt[goodphotons][0] / 1000.0 / m_yy > 0.35\")\\\n .Filter(\"photon_pt[goodphotons][1] / 1000.0 / m_yy > 0.25\")\\\n .Filter(\"m_yy > 105 && m_yy < 160\")\n\n # Book histogram of the invariant mass with this selection\n hists[p] = df[p].Histo1D(\n (p, \"Diphoton invariant mass; m_{#gamma#gamma} [GeV];Events\", 30, 105, 160),\n \"m_yy\", \"weight\")\n\n # Run the event loop\n # Time also event loops at this stage\n watch = ROOT.TStopwatch()\n ggh = hists[\"ggH\"].GetValue()\n elapsed_ggh = watch.RealTime()\n print(\"\\tEvent loop ggh:\", elapsed_ggh, \"s\")\n watch.Start()\n vbf = hists[\"VBF\"].GetValue()\n elapsed_vbf = watch.RealTime()\n print(\"\\tEvent loop vbf:\", elapsed_vbf, \"s\")\n watch.Start()\n data = hists[\"data\"].GetValue()\n elapsed_data = watch.RealTime()\n print(\"\\tEvent loop data:\", elapsed_data, \"s\")\n\n # Create the plot\n\n # Set styles\n ROOT.gROOT.SetStyle(\"ATLAS\")\n\n # Create canvas with pads for main plot and data/MC ratio\n c = ROOT.TCanvas(\"c\", \"\", 700, 750)\n\n upper_pad = ROOT.TPad(\"upper_pad\", \"\", 0, 0.35, 1, 1)\n lower_pad = ROOT.TPad(\"lower_pad\", \"\", 0, 0, 1, 0.35)\n for p in [upper_pad, lower_pad]:\n p.SetLeftMargin(0.14)\n p.SetRightMargin(0.05)\n p.SetTickx(False)\n p.SetTicky(False)\n upper_pad.SetBottomMargin(0)\n lower_pad.SetTopMargin(0)\n lower_pad.SetBottomMargin(0.3)\n\n upper_pad.Draw()\n lower_pad.Draw()\n\n # Fit signal + background model to data\n upper_pad.cd()\n fit = ROOT.TF1(\"fit\", \"([0]+[1]*x+[2]*x^2+[3]*x^3)+[4]*exp(-0.5*((x-[5])/[6])^2)\", 105, 160)\n fit.FixParameter(5, 125.0)\n fit.FixParameter(4, 119.1)\n fit.FixParameter(6, 2.39)\n fit.SetLineColor(2)\n fit.SetLineStyle(1)\n fit.SetLineWidth(2)\n data.Fit(\"fit\", \"\", \"E SAME\", 105, 160)\n fit.Draw(\"SAME\")\n\n # Draw background\n bkg = ROOT.TF1(\"bkg\", \"([0]+[1]*x+[2]*x^2+[3]*x^3)\", 105, 160)\n for i in range(4):\n bkg.SetParameter(i, fit.GetParameter(i))\n bkg.SetLineColor(4)\n bkg.SetLineStyle(2)\n bkg.SetLineWidth(2)\n bkg.Draw(\"SAME\")\n\n # Draw data\n data.SetMarkerStyle(20)\n data.SetMarkerSize(1.2)\n data.SetLineWidth(2)\n data.SetLineColor(ROOT.kBlack)\n data.Draw(\"E SAME\")\n data.SetMinimum(1e-3)\n data.SetMaximum(8e3)\n data.GetYaxis().SetLabelSize(0.045)\n data.GetYaxis().SetTitleSize(0.05)\n data.SetStats(0)\n data.SetTitle(\"\")\n\n # Scale simulated events with luminosity * cross-section / sum of weights\n # and merge to single Higgs signal\n lumi = 10064.0\n ggh.Scale(lumi * 0.102 / 55922617.6297)\n vbf.Scale(lumi * 0.008518764 / 3441426.13711)\n higgs = ggh.Clone()\n higgs.Add(vbf)\n higgs.Draw(\"HIST SAME\")\n\n # Draw ratio\n lower_pad.cd()\n\n ratiobkg = ROOT.TF1(\"zero\", \"0\", 105, 160)\n ratiobkg.SetLineColor(4)\n ratiobkg.SetLineStyle(2)\n ratiobkg.SetLineWidth(2)\n ratiobkg.SetMinimum(-125)\n ratiobkg.SetMaximum(250)\n ratiobkg.GetXaxis().SetLabelSize(0.08)\n ratiobkg.GetXaxis().SetTitleSize(0.12)\n ratiobkg.GetXaxis().SetTitleOffset(1.0)\n ratiobkg.GetYaxis().SetLabelSize(0.08)\n ratiobkg.GetYaxis().SetTitleSize(0.09)\n ratiobkg.GetYaxis().SetTitle(\"Data - Bkg.\")\n ratiobkg.GetYaxis().CenterTitle()\n ratiobkg.GetYaxis().SetTitleOffset(0.7)\n ratiobkg.GetYaxis().SetNdivisions(503, False)\n ratiobkg.GetYaxis().ChangeLabel(-1, -1, 0)\n ratiobkg.GetXaxis().SetTitle(\"m_{#gamma#gamma} [GeV]\")\n ratiobkg.Draw()\n\n ratiosig = ROOT.TH1F(\"ratiosig\", \"ratiosig\", 5500, 105, 160)\n ratiosig.Eval(fit)\n ratiosig.SetLineColor(2)\n ratiosig.SetLineStyle(1)\n ratiosig.SetLineWidth(2)\n ratiosig.Add(bkg, -1)\n ratiosig.Draw(\"SAME\")\n\n ratiodata = data.Clone()\n ratiodata.Add(bkg, -1)\n ratiodata.Draw(\"E SAME\")\n for i in range(1, data.GetNbinsX()):\n ratiodata.SetBinError(i, data.GetBinError(i))\n\n # Add legend\n upper_pad.cd()\n legend = ROOT.TLegend(0.55, 0.55, 0.89, 0.85)\n legend.SetTextFont(42)\n legend.SetFillStyle(0)\n legend.SetBorderSize(0)\n legend.SetTextSize(0.05)\n legend.SetTextAlign(32)\n legend.AddEntry(data, \"Data\" ,\"lep\")\n legend.AddEntry(bkg, \"Background\", \"l\")\n legend.AddEntry(fit, \"Signal + Bkg.\", \"l\")\n legend.AddEntry(higgs, \"Signal\", \"l\")\n legend.Draw(\"SAME\")\n\n # Add ATLAS label\n text = ROOT.TLatex()\n text.SetNDC()\n text.SetTextFont(72)\n text.SetTextSize(0.05)\n text.DrawLatex(0.18, 0.84, \"ATLAS\")\n text.SetTextFont(42)\n text.DrawLatex(0.18 + 0.13, 0.84, \"Open Data\")\n text.SetTextSize(0.04)\n text.DrawLatex(0.18, 0.78, \"#sqrt{s} = 13 TeV, 10 fb^{-1}\");\n\n # Save the plot\n c.SaveAs(\"HiggsToTwoPhotons.pdf\");\n","sub_path":"benchmarks/df104_HiggsToTwoPhotons_10xdata.py","file_name":"df104_HiggsToTwoPhotons_10xdata.py","file_ext":"py","file_size_in_byte":7887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"209477204","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\n#importing datasets and executing basic operations on them\n\ndf1 = pd.read_csv(r\"C:\\Users\\user\\Downloads\\Datasets\\IMDB_title_basics\\data.tsv\", sep='\\t', \n dtype={'genres':str, 'startYear':str})\n\ndf2 = df1[['tconst', 'primaryTitle', 'genres', 'startYear','titleType']]\n\ndf3 = pd.read_csv(r\"C:\\Users\\user\\Downloads\\Datasets\\IMDB_title_ratings\\data.tsv\", delim_whitespace=True, \n dtype={'averageRating':float, 'numVotes':int})\n\ndf_SEnumbers = pd.read_csv(r\"C:\\Users\\user\\Downloads\\Datasets\\IMDB_TVSeries\\data.tsv\", delim_whitespace=True,\n dtype={'seasonNumber':str, 'episodeNumber':str})\ndfs = pd.merge(df2, df3)\ndf_without_na = dfs.dropna()\ndfs2 = pd.merge(dfs, df_SEnumbers)\n\n#creating dataframes for movies and tv episodes, filtering data\n\nmovies = df_without_na.drop(df_without_na[df_without_na.titleType != 'movie'].index)\nSciFiMovies = movies[movies.genres.str.contains('Sci-Fi') & (movies.numVotes >= 1000) & (movies.averageRating >= 7)]\npacked_SFM = SciFiMovies.drop(['tconst', 'genres', 'startYear', 'titleType'], axis=1)\nsortedSFM = packed_SFM.sort_values(by='averageRating', ascending=False)\nfinalSFM = sortedSFM.set_index('primaryTitle')\nSFM_rating_count = finalSFM['averageRating'].value_counts().sort_index()\n\ntv_df = pd.merge(df_without_na, df_SEnumbers)\ntv_df = tv_df.drop(tv_df[tv_df.titleType == 'tvMovie'].index)\ntv_df_without_na = tv_df.drop(tv_df[(tv_df.seasonNumber == r'\\N') | (tv_df.episodeNumber == r'\\N')].index)\nSciFiTV = tv_df_without_na[tv_df_without_na.genres.str.contains('Sci-Fi') & (tv_df_without_na.numVotes >= 1000) & \\\n (tv_df_without_na.averageRating >= 7)]\nSciFiTV = SciFiTV.drop(['tconst', 'startYear', 'titleType', 'parentTconst', 'genres'], axis=1)\nsortedSFTV = SciFiTV.sort_values(by='averageRating', ascending=False)\nfinalSFTV = sortedSFTV.set_index('primaryTitle')\nSFTV_rating_count = finalSFTV['averageRating'].value_counts().sort_index()\n\n#gathering info to show it on plot\n\nSFM_text = \"\"\nfor i in range(10):\n SFM_text += \"%i. %s avg.rate: %.1f \\n\" % (i+1, finalSFM.index[i], finalSFM['averageRating'][i])\nSFM_final_text = (\"Top 10 rated Sci-Fi movies ever:\\n\") + (SFM_text)\n\nSFTV_text = \"\"\nfor i in range(10):\n SFTV_text += \"%i. %s (S%s E%s) avg.rate: %.1f \\n\" % (i+1, finalSFTV.index[i], finalSFTV['seasonNumber'][i], \n finalSFTV['episodeNumber'][i], finalSFTV['averageRating'][i]) \nSFTV_final_text = (\"\\nTop 10 rated Sci-Fi episodes ever:\\n\") + (SFTV_text)\n\nfinal_text = SFM_final_text + SFTV_final_text\n\n#creating the plot\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nx = [x * 0.1 for x in range(70,100)]\ny_m = SFM_rating_count\ny_tv = SFTV_rating_count\nax.bar(y_m.index, y_m, width=-0.025, align='edge', label='Movies')\nax.bar(y_tv.index, y_tv, width=0.025, align='edge', label='TV Episodes')\nax.legend(loc='upper left', fontsize=15)\nax.set_title(\"Sci-Fi Movies / TV Episodes from IMDB database with over 1 000 ratings\", fontsize=15)\nax.set_xlabel('User rating', fontsize=15)\nax.set_ylabel('Number of movies / TV Episodes which received the rating', fontsize =15)\nax.set_yticks(range(0,90,5))\nax.set_xticks([x*0.1 for x in range(70,100)])\nax.set_xlim(left=6.9, right=10.0)\nax.text(9.23, 38, final_text, color='black', bbox=dict(edgecolor='grey', facecolor='white', \n boxstyle='round'), fontsize=11)\nax.yaxis.grid(True, linestyle='--')\nax.set_axisbelow(True)\n\nplt.show()\n\n#not used methods, helpful in different scenarios\n\n\"\"\"\nplt.gcf().subplots_adjust(bottom=1, top=1, left=1, right=1)\nymin, ymax = ax.get_ylim()\nxmin, xmax = ax.get_xlim()\nprint(xmin, xmax, ymin, ymax)\nfig.set_tight_layout(False)\n\"\"\"","sub_path":"comparison.py","file_name":"comparison.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"544762","text":"import numpy as np\nimport pywavefront\nfrom PIL import Image\nfrom pyrr import matrix44 as m44, Vector3 as v3\nfrom OpenGL.GL import *\n\nfrom shader import Shader\n\n\nclass LoadedObject:\n def __init__(self, path: str, x: float = 0.0, y: float = 0.0, z: float = 0.0, scale: float = 1.0):\n \"\"\"Object loaded from .obj and .mtl files, ready to be drawn.\"\"\"\n self._path = path\n self._wavefront = None\n self.vaos = None\n self._vbos = None\n self.materials = []\n self.textures = None\n self.use_texture = False\n self.lengths = []\n # Set position and model\n self.pos = m44.create_from_translation(v3([x, y, z]))\n self.model = self.pos\n self._scale = scale\n self._scale_matrix: m44 = m44.create_from_scale(v3([self._scale] * 3))\n # Load wavefront\n self._load_obj()\n\n def set_pos(self, pos: v3):\n self.pos = m44.create_from_translation(pos)\n self.model = self.pos\n\n def _load_obj(self) -> None:\n \"\"\"Loads wavefront obj and materials. Stores vertex data into VAOs and VBOs.\"\"\"\n self._wavefront = pywavefront.Wavefront(self._path, collect_faces=True, create_materials=True)\n\n # Generate buffers\n materials_count = len(self._wavefront.materials)\n self.vaos = glGenVertexArrays(materials_count)\n self._vbos = glGenBuffers(materials_count)\n self.textures = glGenTextures(materials_count)\n\n if materials_count == 1:\n # glGen* will return an int instead of an np.array if argument is 1.\n self.vaos = np.array([self.vaos], dtype=np.uint32)\n self._vbos = np.array([self._vbos], dtype=np.uint32)\n self.textures = np.array([self.textures], dtype=np.uint32)\n\n # For each material fill buffers and load a texture\n ind = 0\n for material in self._wavefront.materials.values():\n vertex_size = material.vertex_size\n scene_vertices = np.array(material.vertices, dtype=np.float32)\n # Store length and materials for drawing\n self.lengths.append(len(scene_vertices))\n self.materials.append(material)\n # Load texture by path (may break in some weird cases, I guess)\n if material.texture is not None:\n self._load_texture(material.texture.path, self.textures[ind])\n self.use_texture = True\n\n # Bind VAO\n glBindVertexArray(self.vaos[ind])\n # Fill VBO\n glBindBuffer(GL_ARRAY_BUFFER, self._vbos[ind])\n glBufferData(GL_ARRAY_BUFFER, scene_vertices.nbytes, scene_vertices, GL_STATIC_DRAW)\n\n # Set attribute buffers\n attr_format = {\n \"T2F\": (1, 2), # Tex coords (2 floats): ind=1\n \"C3F\": (2, 3), # Color (3 floats): ind=2\n \"N3F\": (3, 3), # Normal (3 floats): ind=3\n \"V3F\": (0, 3), # Position (3 floats): ind=0\n }\n\n cur_off = 0 # current start offset\n for attr in material.vertex_format.split(\"_\"):\n if attr not in attr_format:\n raise Exception(\"Unknown format\")\n\n # Apply\n attr_ind, attr_size = attr_format[attr]\n glEnableVertexAttribArray(attr_ind)\n glVertexAttribPointer(attr_ind, attr_size, GL_FLOAT, GL_FALSE, scene_vertices.itemsize * vertex_size,\n ctypes.c_void_p(cur_off))\n cur_off += attr_size * 4\n\n # Unbind (Technically not necessary but used as a precaution)\n glBindVertexArray(0)\n ind += 1\n\n @staticmethod\n def _load_texture(path: str, texture: int) -> None:\n \"\"\"\n Loads texture into buffer by given path and tex buffer ID.\n\n :param path: Texture path.\n :param texture: Texture buffer ID.\n \"\"\"\n # For use with GLFW\n glBindTexture(GL_TEXTURE_2D, texture)\n # Set the texture wrapping parameters\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)\n # Set texture filtering parameters\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n # Load image\n image = Image.open(path)\n image = image.transpose(Image.FLIP_TOP_BOTTOM)\n img_data = image.convert(\"RGBA\").tobytes()\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data)\n\n def draw(self, shader: Shader, model=None) -> None:\n \"\"\"Draws loaded object onto GL buffer with selected shader.\"\"\"\n # shader.use_program() # Not really sure if that's how you should do it\n for vao, tex, length, mat in zip(self.vaos, self.textures, self.lengths, self.materials):\n glBindVertexArray(vao)\n glBindTexture(GL_TEXTURE_2D, tex)\n if model is not None:\n shader.set_model(model)\n else:\n shader.set_model(m44.multiply(self._scale_matrix, self.model))\n shader.set_v3(\"material.ambient\", mat.ambient)\n shader.set_v3(\"material.diffuse\", mat.diffuse)\n shader.set_v3(\"material.specular\", mat.specular)\n shader.set_float(\"material.shininess\", mat.shininess)\n glDrawArrays(GL_TRIANGLES, 0, length)\n","sub_path":"loaded_object.py","file_name":"loaded_object.py","file_ext":"py","file_size_in_byte":5492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"20101990","text":"\"\"\"\ntxt2psqldb.py\n处理 eh0(tcp)_8:58的数据,\n将数据打包成一个个请求,并且分类\n并存入数据库\n\"\"\"\n\nimport psycopg2\n\n\nclass FormatError(Exception):\n pass\n\n\nclass TXT2PSQLDB:\n \"\"\"\n root_path: 类型:str。设置文件根目录,以 / 或 \\ 结尾,例如:\"/root/\"\n file_name: 类型:str。设置文件名, 例如:\"demon.txt\"\n \"\"\"\n\n def __init__(self, header_amount=0, root_path=\"\", file_name=\"\"):\n self.header_amount = header_amount\n self.root_path = root_path\n self.file_name = file_name\n\n @property\n def file_name(self):\n return self.__file_name\n\n @file_name.setter\n def file_name(self, value):\n self.__file_name = value\n\n @property\n def root_path(self):\n return self.__root_path\n\n @root_path.setter\n def root_path(self, value):\n if value[-1] not in (\"/\", \"\\\\\"):\n raise FormatError(\"请按格式传参,root_path 例: '/root/';file_name 例: 'demon.txt'\")\n else:\n self.__root_path = value\n\n def __get_tar(self):\n \"\"\"\n 将行数据分割好放到self.__tar中\n :return:\n \"\"\"\n raise NotImplementedError\n\n def __classify(self):\n \"\"\"\n 把列分类好的数据放入self.__notes这个二维列表里面\n :return:\n \"\"\"\n raise NotImplementedError\n\n\nclass MYTXT2PSQLDB(TXT2PSQLDB):\n def __init__(self, header_amount=0, root_path=\"\", file_name=\"\"):\n super().__init__(header_amount, root_path, file_name)\n self.__tar = []\n self.__notes = []\n self.__list_info = []\n\n def __get_tar(self):\n fr = open(self.root_path + self.file_name, \"r\")\n temp = \"\"\n for line in fr:\n if line[0:3] == \"No.\":\n self.__tar.append(temp)\n temp = \"\"\n temp += line\n fr.close()\n\n def __classify(self):\n for i in range(1, len(self.__tar)):\n temp = []\n str_info = self.__tar[i].split(\"\\n\")[1].strip()\n list_info_temp = str_info.split(\" \")\n self.__list_info = []\n for j in range(len(list_info_temp)):\n if list_info_temp[j] != \"\":\n self.__list_info.append(list_info_temp[j])\n for k in range(self.header_amount - 2):\n temp.append(self.__list_info[k])\n temp.append(\" \".join(self.__list_info[6:]))\n temp.append(\"\\n\".join(self.__tar[i].split(\"\\n\")[3:]))\n self.__notes.append(temp)\n\n def run(self):\n # 打开数据库\n db = psycopg2.connect(\"dbname=tar_data user=postgres password=toor host=localhost\")\n cur = db.cursor()\n # 以 No. 为标志进行分割,划分各个数据包\n self.__get_tar()\n self.__classify()\n # 放入数据库\n match = \"(\"+(\"%s,\" * self.header_amount)[0:-1] +\")\"\n psql = \"insert into tcp values \" + match\n for i in range(len(self.__notes)):\n try:\n cur.execute(psql, self.__notes[i])\n db.commit()\n except Exception as e:\n print(e)\n db.rollback()\n cur.close()\n db.close()\n","sub_path":"txt2psqldb.py","file_name":"txt2psqldb.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"23647490","text":"import mxnet as mx\r\nimport logging\r\nimport time\r\n\r\nlogging.getLogger().setLevel(logging.DEBUG)\r\nbatch_s = 8\r\nprint(\"Mariya config\")\r\ntrain_data = mx.io.ImageRecordIter(\r\n path_imgrec=\"data.rec\",\r\n data_shape=(3, 128, 128),\r\n batch_size=batch_s)\r\ntest_data = mx.io.ImageRecordIter(\r\n path_imgrec=\"test_data.rec\",\r\n data_shape=(3, 128, 128),\r\n batch_size=batch_s)\r\nprint(\"data - ok\")\r\n\r\n#First 'layer', if it can be put that way.\r\ndata = mx.sym.var('data')\r\ninput = mx.sym.flatten(data=data)\r\nfirst = mx.sym.FullyConnected(data=input, num_hidden=2000)\r\nfirstact = mx.sym.Activation(data=first, act_type='relu')\r\nsecond = mx.sym.FullyConnected(data=firstact, num_hidden=1000)\r\nsecondact = mx.sym.Activation(data=second, act_type='relu')\r\nthird = mx.sym.FullyConnected(data=secondact, num_hidden=500)\r\nthirdact = mx.sym.Activation(data=third, act_type='relu')\r\nfourth = mx.sym.FullyConnected(data=thirdact, num_hidden=250)\r\nfourthact = mx.sym.Activation(data=fourth, act_type='sigmoid')\r\nfc = mx.sym.FullyConnected(data=fourthact, num_hidden=2)\r\nsoftmax = mx.sym.SoftmaxOutput(data=fc, name='softmax')\r\n#softmax = mx.sym.LogisticRegressionOutput(data=fc, name='softmax')\r\n\r\nprint(\"layers - ok\")\r\nfcnn_net = mx.mod.Module(symbol=softmax, context=mx.gpu())\r\nstart_time = time.clock()\r\nfcnn_net.fit(train_data,\r\n eval_data=test_data,\r\n optimizer='sgd',\r\n optimizer_params={'learning_rate': 0.001},\r\n eval_metric='acc',\r\n batch_end_callback=mx.callback.Speedometer(batch_s, 100),\r\n num_epoch=10)\r\nfit_time = time.clock() - start_time\r\nprint(\"Fit time: %f\", fit_time)\r\nacc = mx.metric.Accuracy()\r\nfcnn_net.score(test_data, acc)\r\nprint(acc)\r\n","sub_path":"lab2/src/fcnn_rrrs1.py","file_name":"fcnn_rrrs1.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"496823084","text":"def delete_wire(coordinate_begin, itemnet, distances, gate_connections, allwires, blocked):\n wires = []\n x_coordinate_start = int(coordinate_begin[0])\n y_coordinate_start = int(coordinate_begin[1])\n z_coordinate_start = int(coordinate_begin[2])\n coordinate = coordinate_begin\n \n # Switch order of gates\n end_gate = itemnet[0]\n start_gate = itemnet[1]\n distances.append(((start_gate, end_gate), 2))\n\n coordinates = gate_connections[itemnet]\n print(\"BEFOREDEL: \", len(allwires), len(blocked))\n # Delete wire from gate connections dictionary\n del gate_connections[itemnet]\n \n # Delete blocking wire\n for i in coordinates:\n print(\"incoo: \", i, type(i))\n if str(i) in blocked:\n print(\"DELETEBLOCK\", i)\n blocked.remove(str(i))\n deletelist = []\n # Delete blocking wire\n for i, item2 in enumerate(allwires):\n if item2.net == itemnet:\n # print(\"DELETETOM\")\n # print(allwires[i])\n deletelist.append(allwires[i])\n # print(\"DELETINGTHIS: \", str(deletelist))\n for delete_wire in deletelist: \n allwires.remove(delete_wire)\n print(\"AFTERDEL: \", len(allwires), len(blocked))\n\n return wires, x_coordinate_start, y_coordinate_start, z_coordinate_start, coordinate, gate_connections, allwires, blocked","sub_path":"code/functions/astardelete.py","file_name":"astardelete.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"303778442","text":"#!/usr/bin/env python3\n\n\"\"\"\n/************************************************************/\n/* Author(s): 3JRS - Janeel, Jennie, Jess, Richie, Steph\n/* Major: Information Technology\n/* Compiler: Python 3.6 \n/* Creation Date: 4/29/18\n/* Due Date: 12/12/18\n/* Course: CSC354-020\n/* Professor Name: Prof. Demarco\n/* Assignment: Software Engineering Project (Prototype)\n/* Filename: socket_communication.py\n/* Purpose: To write a server that will communicate with a client (which will also be a server) via client/server communication\n/************************************************************/\n\"\"\"\nimport socket\nimport sys, os \n\ndef Main():\n ipaddress = \"127.0.0.1\"\n IPaddr = socket.gethostbyname(ipaddress) #translate hostname to ip address\n message = \"TEST\"\n bufferSize = 1024\n port = 4444\n serverInfo = ((IPaddr, port)) \n \n try: #Attempt to connect to server\n clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n clientSocket.connect(serverInfo)\n print ('You have successfully connected')\n except socket.error as err:\n print('Socket connection error:', err)\n sys.exit()\n \n try:\n status = clientSocket.recv(bufferSize) #attempt to receive wait message \n status = status.decode()\n except socket.error as msg:\n print ('Unable to receive message from server: ' + str(msg[0]))\n \n connection = True \n while connection:\n try:\n final = clientSocket.recv(4) #Receieve GO from server\n final = final.decode() \n except Exception as s:\n print ('Unable to send client input and READY message: ', s)\n sys.exit(0)\n if (final == \"TEST\"):\n cInput(clientSocket)\n connection = False\n clientSocket.close() \n\nif __name__ == '__main__': #ensures in current module Main \n Main()\nelse:\n sys.exit(0)","sub_path":"socket_communication.py","file_name":"socket_communication.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"114481584","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/9/21 11:34\n# @Author : Burrows\n# @FileName: runTest.py\n\n'''封装公共测试流'''\n\nimport unittest\nimport time\nimport re\nimport json\n\nfrom jsonpath import jsonpath\n\nfrom base.runMethod import RunMethod\nfrom base.readLogger import ReadLogger\nfrom util.relyData import RelyData\nfrom base.aydException import *\n\nclass RunTest(unittest.TestCase, unittest.SkipTest, DataCheck):\n def __init__(self, methodName = 'runTest'):\n super(RunTest, self).__init__(methodName)\n\n # 获取logger和run_log\n read_logger = ReadLogger()\n self.logger = read_logger.get_logger()\n self.run_log_src = read_logger.get_run_log()\n\n # 使用自封装requests\n self.run_method = RunMethod()\n\n # 使用自封装关联数据\n self.rely_data = RelyData()\n\n self.case_id = '' # 用例id\n self.desc = '' # 用例描述\n self.resp = None # 响应数据\n self.req_msg = {'request': {}, '\\nresponse': {}} # 用例基本信息\n\n def get_resp(self):\n \"\"\"\n 获取响应信息\n :return: response data\n \"\"\"\n return self.resp\n\n def skipTest(self, reason):\n \"\"\"\n 过滤用例\n :param reason: 过滤用例原因\n :return: unittest.SkipTest\n \"\"\"\n raise unittest.SkipTest\n\n def getCasePro(self):\n \"\"\"\n 获取用例基本信息\n :return: case_id, desc\n \"\"\"\n return self.case_id, self.desc\n\n def getCaseMsg(self):\n \"\"\"\n 获取待执行用例详细信息\n :return: req_msg = {'request': {}, '\\nresponse': {}}\n \"\"\"\n return self.req_msg\n\n def start(self, url, uri, method, api_name, header, cookie, **kw):\n \"\"\"\n 用例运行主入口\n :param url: 请求地址\n :param uri: 请求路径\n :param method: 请求方法\n :param api_name: 接口名称\n :param header: header设置\n :param cookie: cookie设置\n :param kw: 其他参数\n :return: None\n \"\"\"\n\n # 获取case数据\n options = kw.get('options', {})\n skip = options.get('skip', '0') # skip默认值为0,为1表示跳过该case\n data_check = options.get('datacheck', None) # 数据校验\n toJsonData = options.get('jsonData', '0') # jsonData默认值为0,表示请求数据不做序列化\n self.case_id = kw.get('case_id') # case id\n self.desc = kw.get('desc') # case描述\n api_name = api_name # api名\n url = url + uri # 请求url\n method = method # 请求方法\n header = header # header设置\n cookie = cookie # cookie设置\n data = kw.get('request_data', '') # 请求数据,缺省为空\n validators = kw.get('validators') # 断言设置\n relyDataExport = kw.get('relyDataExport') # 关联输出,即该接口响应返回被其他接口关联字段\n relyDataImport = kw.get('relyDataImport') # 关联引入,即该接口运行所需的关联字段设置\n start_time = time.strftime(\"%Y/%m/%d %H:%M:%S\") # 开始时间\n start_timestamp = time.time() * 1000 # 时间戳,ms\n\n # 处理关联数据\n if relyDataImport is not None:\n for x in relyDataImport:\n datatype = x.get('datatype') # 获取目标关联数据替换源,可能是 request_data/header/cookie\n relyDataSrc = x.get('relyDataSrc') # 获取依赖字段,可能在request_data中为层级结构\n relyDataDes = x.get('relyDataDes') # 获取关联字段\n rely_value = self.rely_data.get_rely_from_file(relyDataDes) # 获取关联数据\n # 替换依赖字段值为关联数据\n if datatype in \"header\":\n header[relyDataSrc] = rely_value\n elif datatype in \"cookie\":\n cookie[relyDataSrc] = rely_value\n else:\n paths = jsonpath(data, '$..%s' % relyDataSrc, result_type='IPATH') # 获取目标字段的位置的层级结构,返回list\n # 替换request_data中所有目标key的值为关联数据\n for path in paths:\n lens = len(path)\n for index in range(lens):\n if re.match(r'[0-9]', path[index]):\n path[index] = int(path[index])\n if lens == 1:\n data[path[0]] = rely_value\n elif lens == 2:\n data[path[0]][path[1]] = rely_value\n elif lens == 3:\n data[path[0]][path[1]][path[2]] = rely_value\n elif lens == 4:\n data[path[0]][path[1]][path[2]][path[3]] = rely_value\n elif lens == 5:\n data[path[0]][path[1]][path[2]][path[3]][path[4]] = rely_value\n elif lens == 6:\n data[path[0]][path[1]][path[2]][path[3]][path[4]][path[5]] = rely_value\n else:\n self.logger.debug('层级结构过长')\n\n self.req_msg.get('request').setdefault('\\nreq.url', url)\n self.req_msg.get('request').setdefault('\\nreq.method', method)\n self.req_msg.get('request').setdefault('\\nreq.header', header)\n self.req_msg.get('request').setdefault('\\nreq.cookie', cookie)\n self.req_msg.get('request').setdefault('\\nreq.data', data)\n self.req_msg.get('request').setdefault('\\nreq.validators', validators)\n self.req_msg.get('request').setdefault('\\nreq.relyDataExport', relyDataExport)\n self.req_msg.get('request').setdefault('\\nreq.relyDataImport', str(relyDataImport))\n self.req_msg.get('request').setdefault('\\nreq.data_check', str(data_check) + '\\n')\n\n if int(skip) == 1:\n self.logger.debug('跳过用例 :%s(%s)' % (self.case_id, self.desc))\n self.skipTest('skip case')\n\n try:\n self.logger.debug('用例编号 :%s ' % self.case_id)\n self.logger.debug('接口名称 : %s' % api_name)\n self.logger.debug('用例描述 : %s' % self.desc)\n self.logger.debug('请求时间 : %s' % start_time)\n self.logger.debug(' 请求信息 '.center(50, '-'))\n self.logger.debug('url : %s' % url)\n self.logger.debug('method : %s' % method)\n self.logger.debug('header : %s' % header)\n self.logger.debug('cookie : %s' % cookie)\n self.logger.debug('请求数据 : %s' % data)\n self.logger.debug('断言设置 : %s' % validators)\n self.logger.debug('关联输出 : %s' % relyDataExport)\n self.logger.debug('关联引入 : %s' % relyDataImport)\n self.logger.debug('校验数据 : %s' % data_check)\n\n # 发送请求\n # 接口有异常的情况下,可能返回的不是json串,会报错\n if toJsonData == 1:\n resp = self.run_method.run_main(method, url, json.dumps(data), cookies=cookie, headers=header)\n else:\n resp = self.run_method.run_main(method, url, data, cookies=cookie, headers=header)\n resp_headers = dict(resp.headers) # 响应头\n resp_status_code = resp.status_code # 响应码\n resp_cookie = dict(resp.cookies) # 响应cookie\n resp_text = resp.text # 响应文本\n\n end_time = time.strftime(\"%Y/%m/%d %H:%M:%S\")\n end_timestamp = time.time() * 1000 # ms\n time_spend = '%.2f' % (end_timestamp - start_timestamp) # ms精度\n\n self.logger.debug(' 响应信息 '.center(50, '-'))\n self.logger.debug('响应时间 : %s' % end_time)\n self.logger.debug('响应耗时 : %s ms' % time_spend)\n self.logger.debug('响应码 : %s' % resp_status_code)\n self.logger.debug('响应头 : %s' % resp_headers)\n\n self.req_msg.get('\\nresponse').setdefault('\\nresp.status_code', resp_status_code)\n self.req_msg.get('\\nresponse').setdefault('\\nresp.headers', resp_headers)\n\n # 查看是否包含 断言查看一次错误就停止,后面加入错误提示\n self.assertEqual(resp_status_code, 200, msg='预计结果不符:http_code预期结果 200,实际结果【%s】' % (resp_status_code))\n\n # 响应结果处理,可能是文本、网页、dict\n if resp_text.startswith('{'):\n resp = resp.json()\n self.resp = resp\n self.req_msg.get('\\nresponse').setdefault('\\nresp.json', str(resp) + '\\n')\n\n # 保存被关联数据\n if relyDataExport is not None:\n for x in relyDataExport:\n datatype = x.get('datatype')\n relyKey = x.get('relyKey')\n keepKey = x.get('keepKey')\n if datatype in \"header\":\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp_headers)\n elif datatype in \"cookie\":\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp_cookie)\n else:\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp)\n\n # 响应数据断言 json\n for valid in validators:\n check = valid.get('check') # 待检查字段\n expect = valid.get('expect') # 预期值\n resp_data = resp.get(check)\n if isinstance(expect, int):\n self.assertEqual(expect, resp_data, msg='预计结果不符:【%s】字段预期结果【%s】,实际结果【%s】' % (check, expect, resp_data))\n if isinstance(expect, str):\n self.assertIn(expect, resp_data, msg='预计结果不符:【%s】字段预期结果【%s】,实际结果【%s】' % (check, expect, resp_data))\n\n else:\n resp = resp_text\n resp = resp.replace(r\"<\", r\"<--\") # 注释html标签,防止误识别\n self.resp = resp\n self.req_msg.get('\\nresponse').setdefault('\\nresp.text', str(resp) + '\\n')\n\n\n # 保存被关联数据\n if relyDataExport is not None:\n for x in relyDataExport:\n datatype = x.get('datatype')\n relyKey = x.get('relyKey')\n keepKey = x.get('keepKey')\n if datatype in \"header\":\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp_headers)\n elif datatype in \"cookie\":\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp_cookie)\n else:\n pass\n\n # 响应数据断言 text\n for valid in validators:\n expect = valid.get('expect') # 预期值\n if isinstance(expect, str):\n self.assertIn(expect, resp_text, msg='预计结果不符:预期值【%s】在响应文本中不存在!' % expect)\n\n self.logger.debug('响应内容 : %s' % resp)\n\n # 数据校验\n if data_check == 1:\n raise DataCheck\n\n except DataCheck:\n raise\n except Exception as e:\n self.logger.debug('响应内容 : %s' % resp)\n self.logger.error('错误信息 : %s' % e)\n raise\n # finally:\n # self.logger.debug('结束测试 %s ' % self.case_id)\n","sub_path":"src/common/runTest.py","file_name":"runTest.py","file_ext":"py","file_size_in_byte":12066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"413153452","text":"# Get per capita personal income from CA1 table for SC counties for all years\nimport requests\nimport json\n\nkey = \"F414B54D-68CF-452A-BFD9-7B7BDA23AE7C\"\ndataset_name = \"RegionalIncome\"\nparameter_name = \"LineCode\"\ntable_name = \"CA1\"\nline_code = \"3\"\nyear = \"ALL\"\ngeo_fips = \"45000\"\nresult_format = \"json\"\nurl = \"https://apps.bea.gov/api/data?&UserID=\" + key + \\\n\"&method=GetData&datasetname=\" + dataset_name + \\\n\"&TableName=\" + table_name + \"&LineCode=\" + line_code + \\\n\"&Year=\" + year + \"&GeoFips=\" + geo_fips + \\\n\"&ResultFormat=\" + result_format\n\nresponse = requests.get(url) # Get response from site\ndata = response.json() # put response in object\n\nwith open(\"ca1_per_capita_personal_income_sc.json\", \"w\") as jsondata: # Write json response to file\n jsondata.write(json.dumps(data, sort_keys=True, indent=2))\n\n#for item in data[\"BEAAPI\"][\"Results\"][\"Data\"]: # Printing the info\n# number_meaning = item[\"CL_UNIT\"]\n# population = item[\"DataValue\"]\n# table_code = item[\"Code\"]\n# location_code = item[\"GeoFips\"]\n# location_name = item[\"GeoName\"]\n# year = item[\"TimePeriod\"]\n# dollar_exponent = item[\"UNIT_MULT\"]\n# print(year + \": \" + location_name + \"| \" + population)","sub_path":"regional_income/table_ca1/state/sc/ca1_per_capita_personal_income_sc.py","file_name":"ca1_per_capita_personal_income_sc.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"}
+{"seq_id":"544576665","text":"#!-*- coding: utf-8 -*-\nfrom django.db import connection\nfrom django.template import Template, Context\n\nclass Middleware(object):\n def process_response(self, request, response):\n content_types = ('text/plain', 'text/html')\n if request.META['CONTENT_TYPE'] not in content_types:\n return response\n time = sum([float(q['time']) for q in connection.queries])\n template = Template(\"\"\"